This commit is contained in:
2024-07-08 22:38:55 +02:00
parent 9aa16e3ef8
commit 758500a071
25 changed files with 632 additions and 690 deletions

View File

@@ -0,0 +1,18 @@
[package]
name = "google_home"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
automation_cast = { path = "../../automation_cast/" }
google_home_macro = { path = "../google_home_macro/" }
serde = { version = "1.0.149", features = ["derive"] }
serde_json = "1.0.89"
thiserror = "1.0.37"
tokio = { version = "1", features = ["sync", "full"] }
async-trait = "0.1.61"
futures = "0.3.25"
anyhow = "1.0.75"
json_value_merge = "2.0.0"

View File

@@ -0,0 +1,110 @@
use async_trait::async_trait;
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::response;
use crate::traits::{Command, DeviceFulfillment};
use crate::types::Type;
#[async_trait]
pub trait Device: DeviceFulfillment {
fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name;
fn get_id(&self) -> String;
fn is_online(&self) -> bool;
// Default values that can optionally be overridden
fn will_report_state(&self) -> bool {
false
}
fn get_room_hint(&self) -> Option<&str> {
None
}
fn get_device_info(&self) -> Option<Info> {
None
}
async fn sync(&self) -> response::sync::Device {
let name = self.get_device_name();
let mut device =
response::sync::Device::new(&self.get_id(), &name.name, self.get_device_type());
device.name = name;
device.will_report_state = self.will_report_state();
// notification_supported_by_agent
if let Some(room) = self.get_room_hint() {
device.room_hint = Some(room.into());
}
device.device_info = self.get_device_info();
let (traits, attributes) = DeviceFulfillment::sync(self).await.unwrap();
device.traits = traits;
device.attributes = attributes;
device
}
async fn query(&self) -> response::query::Device {
let mut device = response::query::Device::new();
if !self.is_online() {
device.set_offline();
}
device.state = DeviceFulfillment::query(self).await.unwrap();
device
}
async fn execute(&mut self, command: Command) -> Result<(), ErrorCode> {
DeviceFulfillment::execute(self, command.clone())
.await
.unwrap();
Ok(())
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Name {
#[serde(skip_serializing_if = "Vec::is_empty")]
default_names: Vec<String>,
name: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
nicknames: Vec<String>,
}
impl Name {
pub fn new(name: &str) -> Self {
Self {
default_names: Vec::new(),
name: name.into(),
nicknames: Vec::new(),
}
}
pub fn add_default_name(&mut self, name: &str) {
self.default_names.push(name.into());
}
pub fn add_nickname(&mut self, name: &str) {
self.nicknames.push(name.into());
}
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
#[serde(skip_serializing_if = "Option::is_none")]
pub manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hw_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sw_version: Option<String>,
// attributes
// customData
// otherDeviceIds
}

View File

@@ -0,0 +1,40 @@
use serde::Serialize;
use thiserror::Error;
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Error)]
#[serde(rename_all = "camelCase")]
pub enum DeviceError {
#[error("deviceNotFound")]
DeviceNotFound,
#[error("deviceOffline")]
DeviceOffline,
#[error("actionNotAvailable")]
ActionNotAvailable,
#[error("transientError")]
TransientError,
}
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Error)]
#[serde(rename_all = "camelCase")]
pub enum DeviceException {}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Serialize, Error)]
#[serde(untagged)]
pub enum ErrorCode {
#[error("{0}")]
DeviceError(DeviceError),
#[error("{0}")]
DeviceException(DeviceException),
}
impl From<DeviceError> for ErrorCode {
fn from(value: DeviceError) -> Self {
Self::DeviceError(value)
}
}
impl From<DeviceException> for ErrorCode {
fn from(value: DeviceException) -> Self {
Self::DeviceException(value)
}
}

View File

@@ -0,0 +1,446 @@
use std::collections::HashMap;
use std::sync::Arc;
use automation_cast::Cast;
use futures::future::{join_all, OptionFuture};
use thiserror::Error;
use tokio::sync::{Mutex, RwLock};
use crate::errors::{DeviceError, ErrorCode};
use crate::request::{self, Intent, Request};
use crate::response::{self, execute, query, sync, Response, ResponsePayload};
use crate::Device;
#[derive(Debug)]
pub struct GoogleHome {
user_id: String,
// Add credentials so we can notify google home of actions
}
#[derive(Debug, Error)]
pub enum FulfillmentError {
#[error("Expected at least one ResponsePayload")]
ExpectedOnePayload,
}
impl GoogleHome {
pub fn new(user_id: &str) -> Self {
Self {
user_id: user_id.into(),
}
}
pub async fn handle_request<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
request: Request,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> Result<Response, FulfillmentError> {
// TODO: What do we do if we actually get more then one thing in the input array, right now
// we only respond to the first thing
let intent = request.inputs.into_iter().next();
let payload: OptionFuture<_> = intent
.map(|intent| async move {
match intent {
Intent::Sync => ResponsePayload::Sync(self.sync(devices).await),
Intent::Query(payload) => {
ResponsePayload::Query(self.query(payload, devices).await)
}
Intent::Execute(payload) => {
ResponsePayload::Execute(self.execute(payload, devices).await)
}
}
})
.into();
payload
.await
.ok_or(FulfillmentError::ExpectedOnePayload)
.map(|payload| Response::new(&request.request_id, payload))
}
async fn sync<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> sync::Payload {
let mut resp_payload = sync::Payload::new(&self.user_id);
let f = devices.iter().map(|(_, device)| async move {
if let Some(device) = device.read().await.as_ref().cast() {
Some(Device::sync(device).await)
} else {
None
}
});
resp_payload.devices = join_all(f).await.into_iter().flatten().collect();
resp_payload
}
async fn query<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
payload: request::query::Payload,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> query::Payload {
let mut resp_payload = query::Payload::new();
let f = payload
.devices
.into_iter()
.map(|device| device.id)
.map(|id| async move {
// NOTE: Requires let_chains feature
let device = if let Some(device) = devices.get(id.as_str())
&& let Some(device) = device.read().await.as_ref().cast()
{
Device::query(device).await
} else {
let mut device = query::Device::new();
device.set_offline();
device.set_error(DeviceError::DeviceNotFound.into());
device
};
(id, device)
});
// Await all the futures and then convert the resulting vector into a hashmap
resp_payload.devices = join_all(f).await.into_iter().collect();
resp_payload
}
async fn execute<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
payload: request::execute::Payload,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> execute::Payload {
let resp_payload = Arc::new(Mutex::new(response::execute::Payload::new()));
let f = payload.commands.into_iter().map(|command| {
let resp_payload = resp_payload.clone();
async move {
let mut success = response::execute::Command::new(execute::Status::Success);
success.states = Some(execute::States {
online: true,
state: Default::default(),
});
let mut offline = response::execute::Command::new(execute::Status::Offline);
offline.states = Some(execute::States {
online: false,
state: Default::default(),
});
let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new();
let f = command
.devices
.into_iter()
.map(|device| device.id)
.map(|id| {
let execution = command.execution.clone();
async move {
if let Some(device) = devices.get(id.as_str())
&& let Some(device) = device.write().await.as_mut().cast_mut()
{
if !device.is_online() {
return (id, Ok(false));
}
// NOTE: We can not use .map here because async =(
let mut results = Vec::new();
for cmd in &execution {
results.push(Device::execute(device, cmd.clone()).await);
}
// Convert vec of results to a result with a vec and the first
// encountered error
let results =
results.into_iter().collect::<Result<Vec<_>, ErrorCode>>();
// TODO: We only get one error not all errors
if let Err(err) = results {
(id, Err(err))
} else {
(id, Ok(true))
}
} else {
(id.clone(), Err(DeviceError::DeviceNotFound.into()))
}
}
});
let a = join_all(f).await;
a.into_iter().for_each(|(id, state)| {
match state {
Ok(true) => success.add_id(&id),
Ok(false) => offline.add_id(&id),
Err(err) => errors
.entry(err)
.or_insert_with(|| match &err {
ErrorCode::DeviceError(_) => {
response::execute::Command::new(execute::Status::Error)
}
ErrorCode::DeviceException(_) => {
response::execute::Command::new(execute::Status::Exceptions)
}
})
.add_id(&id),
};
});
let mut resp_payload = resp_payload.lock().await;
resp_payload.add_command(success);
resp_payload.add_command(offline);
for (error, mut cmd) in errors {
cmd.error_code = Some(error);
resp_payload.add_command(cmd);
}
}
});
join_all(f).await;
std::sync::Arc::<tokio::sync::Mutex<response::execute::Payload>>::try_unwrap(resp_payload)
.expect("All futures are done, so there should only be one strong reference")
.into_inner()
}
}
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::{
// device::{self, GoogleHomeDevice},
// errors::ErrorCode,
// request::Request,
// traits, types,
// };
//
// #[derive(Debug)]
// struct TestOutlet {
// name: String,
// on: bool,
// }
//
// impl TestOutlet {
// fn new(name: &str) -> Self {
// Self {
// name: name.into(),
// on: false,
// }
// }
// }
//
// impl GoogleHomeDevice for TestOutlet {
// fn get_device_type(&self) -> types::Type {
// types::Type::Outlet
// }
//
// fn get_device_name(&self) -> device::Name {
// let mut name = device::Name::new("Nightstand");
// name.add_default_name("Outlet");
// name.add_nickname("Nightlight");
//
// name
// }
//
// fn get_id(&self) -> &str {
// &self.name
// }
//
// fn is_online(&self) -> bool {
// true
// }
//
// fn get_room_hint(&self) -> Option<&str> {
// Some("Bedroom")
// }
//
// fn get_device_info(&self) -> Option<device::Info> {
// Some(device::Info {
// manufacturer: Some("Company".into()),
// model: Some("Outlet II".into()),
// hw_version: None,
// sw_version: None,
// })
// }
// }
//
// impl traits::OnOff for TestOutlet {
// fn is_on(&self) -> Result<bool, ErrorCode> {
// Ok(self.on)
// }
//
// fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> {
// self.on = on;
// Ok(())
// }
// }
//
// #[derive(Debug)]
// struct TestScene;
//
// impl TestScene {
// fn new() -> Self {
// Self {}
// }
// }
//
// impl GoogleHomeDevice for TestScene {
// fn get_device_type(&self) -> types::Type {
// types::Type::Scene
// }
//
// fn get_device_name(&self) -> device::Name {
// device::Name::new("Party")
// }
//
// fn get_id(&self) -> &str {
// "living/party_mode"
// }
//
// fn is_online(&self) -> bool {
// true
// }
//
// fn get_room_hint(&self) -> Option<&str> {
// Some("Living room")
// }
// }
//
// impl traits::Scene for TestScene {
// fn set_active(&self, _activate: bool) -> Result<(), ErrorCode> {
// println!("Activating the party scene");
// Ok(())
// }
// }
//
// #[test]
// fn handle_sync() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.SYNC"
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
//
// #[test]
// fn handle_query() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.QUERY",
// "payload": {
// "devices": [
// {
// "id": "bedroom/nightstand"
// },
// {
// "id": "living/party_mode"
// }
// ]
// }
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
//
// #[test]
// fn handle_execute() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.EXECUTE",
// "payload": {
// "commands": [
// {
// "devices": [
// {
// "id": "bedroom/nightstand"
// },
// {
// "id": "living/lamp"
// }
// ],
// "execution": [
// {
// "command": "action.devices.commands.OnOff",
// "params": {
// "on": true
// }
// }
// ]
// }
// ]
// }
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
// }

View File

@@ -0,0 +1,17 @@
#![allow(incomplete_features)]
#![feature(specialization)]
#![feature(let_chains)]
pub mod device;
mod fulfillment;
mod request;
mod response;
pub mod errors;
pub mod traits;
pub mod types;
pub use device::Device;
pub use fulfillment::{FulfillmentError, GoogleHome};
pub use request::Request;
pub use response::Response;

View File

@@ -0,0 +1,23 @@
pub mod execute;
pub mod query;
pub mod sync;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(tag = "intent", content = "payload")]
pub enum Intent {
#[serde(rename = "action.devices.SYNC")]
Sync,
#[serde(rename = "action.devices.QUERY")]
Query(query::Payload),
#[serde(rename = "action.devices.EXECUTE")]
Execute(execute::Payload),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Request {
pub request_id: String,
pub inputs: Vec<Intent>,
}

View File

@@ -0,0 +1,140 @@
use serde::Deserialize;
use crate::traits;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
pub commands: Vec<Command>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Command {
pub devices: Vec<Device>,
pub execution: Vec<traits::Command>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
// customData
}
#[cfg(test)]
mod tests {
use super::*;
use crate::request::{Intent, Request};
#[test]
fn deserialize_set_fan_speed() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [],
"execution": [
{
"command": "action.devices.commands.SetFanSpeed",
"params": {
"fanSpeed": "Test"
}
}
]
}
]
}
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 0);
assert_eq!(payload.commands[0].execution.len(), 1);
match &payload.commands[0].execution[0] {
traits::Command::SetFanSpeed { fan_speed } => assert_eq!(fan_speed, "Test"),
_ => panic!("Expected SetFanSpeed"),
}
}
_ => panic!("Expected Execute intent"),
};
}
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [
{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "sheepdip"
}
},
{
"id": "456",
"customData": {
"fooValue": 36,
"barValue": false,
"bazValue": "moarsheep"
}
}
],
"execution": [
{
"command": "action.devices.commands.OnOff",
"params": {
"on": true
}
}
]
}
]
}
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
println!("{:?}", req);
assert_eq!(
req.request_id,
"ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_string()
);
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 2);
assert_eq!(payload.commands[0].devices[0].id, "123");
assert_eq!(payload.commands[0].devices[1].id, "456");
assert_eq!(payload.commands[0].execution.len(), 1);
match payload.commands[0].execution[0] {
traits::Command::OnOff { on } => assert!(on),
_ => panic!("Expected OnOff"),
}
}
_ => panic!("Expected Execute intent"),
};
}
}

View File

@@ -0,0 +1,69 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
pub devices: Vec<Device>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
// customData
}
#[cfg(test)]
mod tests {
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.QUERY",
"payload": {
"devices": [
{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "foo"
}
},
{
"id": "456",
"customData": {
"fooValue": 12,
"barValue": false,
"bazValue": "bar"
}
}
]
}
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
println!("{:?}", req);
assert_eq!(
req.request_id,
"ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_string()
);
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Query(payload) => {
assert_eq!(payload.devices.len(), 2);
assert_eq!(payload.devices[0].id, "123");
assert_eq!(payload.devices[1].id, "456");
}
_ => panic!("Expected Query intent"),
};
}
}

View File

@@ -0,0 +1,30 @@
#[cfg(test)]
mod tests {
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.SYNC"
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
println!("{:?}", req);
assert_eq!(
req.request_id,
"ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_string()
);
assert_eq!(req.inputs.len(), 1);
match req.inputs[0] {
Intent::Sync => {}
_ => panic!("Expected Sync intent"),
}
}
}

View File

@@ -0,0 +1,29 @@
pub mod execute;
pub mod query;
pub mod sync;
use serde::Serialize;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Response {
request_id: String,
payload: ResponsePayload,
}
impl Response {
pub fn new(request_id: &str, payload: ResponsePayload) -> Self {
Self {
request_id: request_id.into(),
payload,
}
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ResponsePayload {
Sync(sync::Payload),
Query(query::Payload),
Execute(execute::Payload),
}

View File

@@ -0,0 +1,126 @@
use serde::Serialize;
use crate::errors::ErrorCode;
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
commands: Vec<Command>,
}
impl Payload {
pub fn new() -> Self {
Self {
error_code: None,
debug_string: None,
commands: Vec::new(),
}
}
pub fn add_command(&mut self, command: Command) {
if !command.is_empty() {
self.commands.push(command);
}
}
}
impl Default for Payload {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Command {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
ids: Vec<String>,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub states: Option<States>,
}
impl Command {
pub fn new(status: Status) -> Self {
Self {
error_code: None,
ids: Vec::new(),
status,
states: None,
}
}
pub fn add_id(&mut self, id: &str) {
self.ids.push(id.into());
}
pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct States {
pub online: bool,
#[serde(flatten)]
pub state: serde_json::Value,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Status {
Success,
Pending,
Offline,
Exceptions,
Error,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::errors::DeviceError;
use crate::response::{Response, ResponsePayload};
#[test]
fn serialize() {
let mut execute_resp = Payload::new();
let state = json!({
"on": true,
});
let mut command = Command::new(Status::Success);
command.states = Some(States {
online: true,
state,
});
command.ids.push("123".into());
execute_resp.add_command(command);
let mut command = Command::new(Status::Error);
command.error_code = Some(DeviceError::DeviceNotFound.into());
command.ids.push("456".into());
execute_resp.add_command(command);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Execute(execute_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// TODO: Add a known correct output to test against
}
}

View File

@@ -0,0 +1,122 @@
use std::collections::HashMap;
use serde::Serialize;
use crate::errors::ErrorCode;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
pub devices: HashMap<String, Device>,
}
impl Payload {
pub fn new() -> Self {
Self {
error_code: None,
debug_string: None,
devices: HashMap::new(),
}
}
pub fn add_device(&mut self, id: &str, device: Device) {
self.devices.insert(id.into(), device);
}
}
impl Default for Payload {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Status {
Success,
Offline,
Exceptions,
Error,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
online: bool,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
error_code: Option<ErrorCode>,
#[serde(flatten)]
pub state: serde_json::Value,
}
impl Device {
pub fn new() -> Self {
Self {
online: true,
status: Status::Success,
error_code: None,
state: Default::default(),
}
}
pub fn set_offline(&mut self) {
self.online = false;
self.status = Status::Offline;
}
pub fn set_error(&mut self, err: ErrorCode) {
self.status = match err {
ErrorCode::DeviceError(_) => Status::Error,
ErrorCode::DeviceException(_) => Status::Exceptions,
};
self.error_code = Some(err);
}
}
impl Default for Device {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::response::{Response, ResponsePayload};
#[test]
fn serialize() {
let mut query_resp = Payload::new();
let mut device = Device::new();
device.state = json!({
"on": true,
});
query_resp.add_device("123", device);
let mut device = Device::new();
device.state = json!({
"on": true,
});
query_resp.add_device("456", device);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Query(query_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// TODO: Add a known correct output to test against
}
}

View File

@@ -0,0 +1,105 @@
use serde::Serialize;
use crate::device;
use crate::errors::ErrorCode;
use crate::traits::Trait;
use crate::types::Type;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
agent_user_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
pub devices: Vec<Device>,
}
impl Payload {
pub fn new(agent_user_id: &str) -> Self {
Self {
agent_user_id: agent_user_id.into(),
error_code: None,
debug_string: None,
devices: Vec::new(),
}
}
pub fn add_device(&mut self, device: Device) {
self.devices.push(device);
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
id: String,
#[serde(rename = "type")]
device_type: Type,
pub traits: Vec<Trait>,
pub name: device::Name,
pub will_report_state: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub notification_supported_by_agent: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub room_hint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_info: Option<device::Info>,
pub attributes: serde_json::Value,
}
impl Device {
pub fn new(id: &str, name: &str, device_type: Type) -> Self {
Self {
id: id.into(),
device_type,
traits: Vec::new(),
name: device::Name::new(name),
will_report_state: false,
notification_supported_by_agent: None,
room_hint: None,
device_info: None,
attributes: Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::response::{Response, ResponsePayload};
use crate::traits::Trait;
use crate::types::Type;
#[test]
fn serialize() {
let mut sync_resp = Payload::new("1836.15267389");
let mut device = Device::new("123", "Night light", Type::Kettle);
device.traits.push(Trait::OnOff);
device.name.add_default_name("My Outlet 1234");
device.name.add_nickname("wall plug");
device.room_hint = Some("kitchen".into());
device.device_info = Some(device::Info {
manufacturer: Some("lights-out-inc".into()),
model: Some("hs1234".into()),
hw_version: Some("3.2".into()),
sw_version: Some("11.4".into()),
});
sync_resp.add_device(device);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Sync(sync_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// assert_eq!(json, r#"{"requestId":"ff36a3cc-ec34-11e6-b1a0-64510650abcf","payload":{"agentUserId":"1836.15267389","devices":[{"id":"123","type":"action.devices.types.KETTLE","traits":["action.devices.traits.OnOff"],"name":{"defaultNames":["My Outlet 1234"],"name":"Night light","nicknames":["wall plug"]},"willReportState":false,"roomHint":"kitchen","deviceInfo":{"manufacturer":"lights-out-inc","model":"hs1234","hwVersion":"3.2","swVersion":"11.4"}}]}}"#)
}
}

View File

@@ -0,0 +1,55 @@
use automation_cast::Cast;
use google_home_macro::traits;
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::Device;
traits! {
Device,
"action.devices.traits.OnOff" => trait OnOff {
command_only_on_off: Option<bool>,
query_only_on_off: Option<bool>,
async fn on(&self) -> Result<bool, ErrorCode>,
"action.devices.commands.OnOff" => async fn set_on(&mut self, on: bool) -> Result<(), ErrorCode>,
},
"action.devices.traits.Scene" => trait Scene {
scene_reversible: Option<bool>,
"action.devices.commands.ActivateScene" => async fn set_active(&mut self, activate: bool) -> Result<(), ErrorCode>,
},
"action.devices.traits.FanSpeed" => trait FanSpeed {
reversible: Option<bool>,
command_only_fan_speed: Option<bool>,
available_fan_speeds: AvailableSpeeds,
fn current_fan_speed_setting(&self) -> Result<String, ErrorCode>,
// TODO: Figure out some syntax for optional command?
// Probably better to just force the user to always implement commands?
"action.devices.commands.SetFanSpeed" => async fn set_fan_speed(&mut self, fan_speed: String) -> Result<(), ErrorCode>,
},
"action.devices.traits.HumiditySetting" => trait HumiditySetting {
query_only_humidity_setting: Option<bool>,
fn humidity_ambient_percent(&self) -> Result<isize, ErrorCode>,
}
}
#[derive(Debug, Serialize)]
pub struct SpeedValues {
pub speed_synonym: Vec<String>,
pub lang: String,
}
#[derive(Debug, Serialize)]
pub struct Speed {
pub speed_name: String,
pub speed_values: Vec<SpeedValues>,
}
#[derive(Debug, Serialize)]
pub struct AvailableSpeeds {
pub speeds: Vec<Speed>,
pub ordered: bool,
}

View File

@@ -0,0 +1,15 @@
use serde::Serialize;
#[derive(Debug, Serialize)]
pub enum Type {
#[serde(rename = "action.devices.types.KETTLE")]
Kettle,
#[serde(rename = "action.devices.types.OUTLET")]
Outlet,
#[serde(rename = "action.devices.types.LIGHT")]
Light,
#[serde(rename = "action.devices.types.SCENE")]
Scene,
#[serde(rename = "action.devices.types.AIRPURIFIER")]
AirPurifier,
}

View File

@@ -0,0 +1,12 @@
[package]
name = "google_home_macro"
version = "0.1.0"
edition = "2021"
[lib]
proc-macro = true
[dependencies]
proc-macro2 = "1.0.81"
quote = "1.0.36"
syn = { version = "2.0.60", features = ["extra-traits", "full"] }

View File

@@ -0,0 +1,569 @@
#![feature(let_chains)]
#![feature(iter_intersperse)]
use proc_macro::TokenStream;
use quote::quote;
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::token::Brace;
use syn::{
braced, parse_macro_input, GenericArgument, Ident, LitStr, Path, PathArguments, PathSegment,
ReturnType, Signature, Token, Type, TypePath,
};
mod kw {
use syn::custom_keyword;
custom_keyword!(required);
}
#[derive(Debug)]
struct FieldAttribute {
ident: Ident,
_colon_token: Token![:],
ty: Type,
}
impl Parse for FieldAttribute {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Self {
ident: input.parse()?,
_colon_token: input.parse()?,
ty: input.parse()?,
})
}
}
#[derive(Debug)]
struct FieldState {
sign: Signature,
}
impl Parse for FieldState {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Self {
sign: input.parse()?,
})
}
}
#[derive(Debug)]
struct FieldExecute {
name: LitStr,
_fat_arrow_token: Token![=>],
sign: Signature,
}
impl Parse for FieldExecute {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Self {
name: input.parse()?,
_fat_arrow_token: input.parse()?,
sign: input.parse()?,
})
}
}
#[derive(Debug)]
enum Field {
Attribute(FieldAttribute),
State(FieldState),
Execute(FieldExecute),
}
impl Parse for Field {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
if input.peek(Ident) {
Ok(Field::Attribute(input.parse()?))
} else if input.peek(LitStr) {
Ok(Field::Execute(input.parse()?))
} else {
Ok(Field::State(input.parse()?))
}
}
}
#[derive(Debug)]
struct Trait {
name: LitStr,
_fat_arrow_token: Token![=>],
_trait_token: Token![trait],
ident: Ident,
_brace_token: Brace,
fields: Punctuated<Field, Token![,]>,
}
impl Parse for Trait {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let content;
Ok(Self {
name: input.parse()?,
_fat_arrow_token: input.parse()?,
_trait_token: input.parse()?,
ident: input.parse()?,
_brace_token: braced!(content in input),
fields: content.parse_terminated(Field::parse, Token![,])?,
})
}
}
#[derive(Debug)]
struct Input {
ty: TypePath,
_comma: Token![,],
traits: Punctuated<Trait, Token![,]>,
}
// TODO: Error on duplicate name?
impl Parse for Input {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
Ok(Self {
ty: input.parse()?,
_comma: input.parse()?,
traits: input.parse_terminated(Trait::parse, Token![,])?,
})
}
}
fn extract_type_path(ty: &syn::Type) -> Option<&Path> {
match *ty {
Type::Path(ref typepath) if typepath.qself.is_none() => Some(&typepath.path),
_ => None,
}
}
fn extract_segment<'a>(path: &'a Path, options: &[&str]) -> Option<&'a PathSegment> {
let idents_of_path = path
.segments
.iter()
.map(|segment| segment.ident.to_string())
.intersperse('|'.into())
.collect::<String>();
options
.iter()
.find(|s| &idents_of_path == *s)
.and_then(|_| path.segments.last())
}
// Based on: https://stackoverflow.com/a/56264023
fn extract_type_from_option(ty: &syn::Type) -> Option<&syn::Type> {
extract_type_path(ty)
.and_then(|path| {
extract_segment(path, &["Option", "std|option|Option", "core|option|Option"])
})
.and_then(|path_seg| {
let type_params = &path_seg.arguments;
// It should have only on angle-bracketed param ("<String>"):
match *type_params {
PathArguments::AngleBracketed(ref params) => params.args.first(),
_ => None,
}
})
.and_then(|generic_arg| match *generic_arg {
GenericArgument::Type(ref ty) => Some(ty),
_ => None,
})
}
fn extract_type_from_result(ty: &syn::Type) -> Option<&syn::Type> {
extract_type_path(ty)
.and_then(|path| {
extract_segment(path, &["Result", "std|result|Result", "core|result|Result"])
})
.and_then(|path_seg| {
let type_params = &path_seg.arguments;
// It should have only on angle-bracketed param ("<String>"):
match *type_params {
PathArguments::AngleBracketed(ref params) => params.args.first(),
_ => None,
}
})
.and_then(|generic_arg| match *generic_arg {
GenericArgument::Type(ref ty) => Some(ty),
_ => None,
})
}
fn get_attributes_struct_ident(t: &Trait) -> Ident {
syn::Ident::new(&format!("{}Attributes", t.ident), t.ident.span())
}
fn get_attributes_struct(t: &Trait) -> proc_macro2::TokenStream {
let fields = t.fields.iter().filter_map(|f| match f {
Field::Attribute(attr) => {
let ident = &attr.ident;
let ty = &attr.ty;
// TODO: Extract into function
if let Some(ty) = extract_type_from_option(ty) {
Some(quote! {
#[serde(skip_serializing_if = "core::option::Option::is_none")]
#ident: ::core::option::Option<#ty>
})
} else {
Some(quote! {
#ident: #ty
})
}
}
_ => None,
});
let name = get_attributes_struct_ident(t);
quote! {
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct #name {
#(#fields,)*
}
}
}
fn get_state_struct_ident(t: &Trait) -> Ident {
syn::Ident::new(&format!("{}State", t.ident), t.ident.span())
}
fn get_state_struct(t: &Trait) -> proc_macro2::TokenStream {
let fields = t.fields.iter().filter_map(|f| match f {
Field::State(state) => {
let ident = &state.sign.ident;
let ReturnType::Type(_, ty) = &state.sign.output else {
return None;
};
let ty = extract_type_from_result(ty).unwrap_or(ty);
if let Some(ty) = extract_type_from_option(ty) {
Some(quote! {
#[serde(skip_serializing_if = "core::option::Option::is_none")]
#ident: ::core::option::Option<#ty>
})
} else {
Some(quote! {#ident: #ty})
}
}
_ => None,
});
let name = get_state_struct_ident(t);
quote! {
#[derive(Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct #name {
#(#fields,)*
}
}
}
fn get_command_enum(traits: &Punctuated<Trait, Token![,]>) -> proc_macro2::TokenStream {
let items = traits.iter().flat_map(|t| {
t.fields.iter().filter_map(|f| match f {
Field::Execute(execute) => {
let name = execute.name.value();
let ident = Ident::new(
name.split_at(name.rfind('.').map(|v| v + 1).unwrap_or(0)).1,
execute.name.span(),
);
let parameters = execute.sign.inputs.iter().skip(1);
Some(quote! {
#[serde(rename = #name, rename_all = "camelCase")]
#ident {
#(#parameters,)*
}
})
}
_ => None,
})
});
quote! {
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(tag = "command", content = "params", rename_all = "camelCase")]
pub enum Command {
#(#items,)*
}
}
}
fn get_trait_enum(traits: &Punctuated<Trait, Token![,]>) -> proc_macro2::TokenStream {
let items = traits.iter().map(|t| {
let name = &t.name;
let ident = &t.ident;
quote! {
#[serde(rename = #name)]
#ident
}
});
quote! {
#[derive(Debug, serde::Serialize)]
pub enum Trait {
#(#items,)*
}
}
}
fn get_trait(t: &Trait) -> proc_macro2::TokenStream {
let fields = t.fields.iter().map(|f| match f {
Field::Attribute(attr) => {
let name = &attr.ident;
let ty = &attr.ty;
// If the default type is marked as optional, respond None by default
if let Some(ty) = extract_type_from_option(ty) {
quote! {
fn #name(&self) -> Option<#ty> {
None
}
}
} else {
quote! {
fn #name(&self) -> #ty;
}
}
}
Field::State(state) => {
let sign = &state.sign;
let ReturnType::Type(_, ty) = &state.sign.output else {
todo!("Handle weird function return types");
};
let inner = extract_type_from_result(ty);
// If the default type is marked as optional, respond None by default
if extract_type_from_option(inner.unwrap_or(ty)).is_some() {
if inner.is_some() {
quote! {
#sign {
Ok(None)
}
}
} else {
quote! {
#sign {
None
}
}
}
} else {
quote! {
#sign;
}
}
}
Field::Execute(execute) => {
let sign = &execute.sign;
quote! {
#sign;
}
}
});
let ident = &t.ident;
let attr_ident = get_attributes_struct_ident(t);
let attr = t.fields.iter().filter_map(|f| match f {
Field::Attribute(attr) => {
let name = &attr.ident;
Some(quote! {
#name: self.#name()
})
}
_ => None,
});
let state_ident = get_state_struct_ident(t);
let state = t.fields.iter().filter_map(|f| match f {
Field::State(state) => {
let ident = &state.sign.ident;
let f_ident = &state.sign.ident;
let asyncness = if state.sign.asyncness.is_some() {
quote! {.await}
} else {
quote! {}
};
let errors = if let ReturnType::Type(_, ty) = &state.sign.output
&& extract_type_from_result(ty).is_some()
{
quote! {?}
} else {
quote! {}
};
Some(quote! {
#ident: self.#f_ident() #asyncness #errors,
})
}
_ => None,
});
quote! {
#[async_trait::async_trait]
pub trait #ident: Sync + Send {
#(#fields)*
fn get_attributes(&self) -> #attr_ident {
#attr_ident { #(#attr,)* }
}
async fn get_state(&self) -> Result<#state_ident, Box<dyn ::std::error::Error>> {
Ok(#state_ident { #(#state)* })
}
}
}
}
#[proc_macro]
pub fn traits(item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as Input);
let traits = input.traits;
let structs = traits.iter().map(|t| {
let attr = get_attributes_struct(t);
let state = get_state_struct(t);
let tra = get_trait(t);
quote! {
#attr
#state
#tra
}
});
let command_enum = get_command_enum(&traits);
let trait_enum = get_trait_enum(&traits);
let sync = traits.iter().map(|t| {
let ident = &t.ident;
quote! {
if let Some(t) = self.cast() as Option<&dyn #ident> {
traits.push(Trait::#ident);
let value = serde_json::to_value(t.get_attributes())?;
json_value_merge::Merge::merge(&mut attrs, &value);
}
}
});
let query = traits.iter().map(|t| {
let ident = &t.ident;
quote! {
if let Some(t) = self.cast() as Option<&dyn #ident> {
let value = serde_json::to_value(t.get_state().await?)?;
json_value_merge::Merge::merge(&mut state, &value);
}
}
});
let execute = traits.iter().flat_map(|t| {
t.fields.iter().filter_map(|f| match f {
Field::Execute(execute) => {
let ident = &t.ident;
let name = execute.name.value();
let command_name = Ident::new(
name.split_at(name.rfind('.').map(|v| v + 1).unwrap_or(0)).1,
execute.name.span(),
);
let f_name = &&execute.sign.ident;
let parameters = execute
.sign
.inputs
.iter()
.filter_map(|p| {
if let syn::FnArg::Typed(p) = p {
Some(&p.pat)
} else {
None
}
})
.collect::<Vec<_>>();
let asyncness = if execute.sign.asyncness.is_some() {
quote! {.await}
} else {
quote! {}
};
let errors = if let ReturnType::Type(_, ty) = &execute.sign.output
&& extract_type_from_result(ty).is_some()
{
quote! {?}
} else {
quote! {}
};
Some(quote! {
Command::#command_name {#(#parameters,)*} => {
if let Some(t) = self.cast_mut() as Option<&mut dyn #ident> {
t.#f_name(#(#parameters,)*) #asyncness #errors;
serde_json::to_value(t.get_state().await?)?
} else {
todo!("Device does not support action, return proper error");
}
}
})
}
_ => None,
})
});
let ty = input.ty;
let fulfillment = Ident::new(
&format!("{}Fulfillment", ty.path.segments.last().unwrap().ident),
ty.path.segments.last().unwrap().ident.span(),
);
quote! {
// TODO: This is always the same, so should not be part of the macro, but instead something
// else
#[async_trait::async_trait]
pub trait #fulfillment: Sync + Send {
async fn sync(&self) -> Result<(Vec<Trait>, serde_json::Value), Box<dyn ::std::error::Error>>;
async fn query(&self) -> Result<serde_json::Value, Box<dyn ::std::error::Error>>;
async fn execute(&mut self, command: Command) -> Result<serde_json::Value, Box<dyn std::error::Error>>;
}
#(#structs)*
#command_enum
#trait_enum
#[async_trait::async_trait]
impl<D> #fulfillment for D where D: #ty
{
async fn sync(&self) -> Result<(Vec<Trait>, serde_json::Value), Box<dyn ::std::error::Error>> {
let mut traits = Vec::new();
let mut attrs = serde_json::Value::Null;
#(#sync)*
Ok((traits, attrs))
}
async fn query(&self) -> Result<serde_json::Value, Box<dyn ::std::error::Error>> {
let mut state = serde_json::Value::Null;
#(#query)*
Ok(state)
}
async fn execute(&mut self, command: Command) -> Result<serde_json::Value, Box<dyn std::error::Error>> {
let value = match command {
#(#execute)*
};
Ok(value)
}
}
}
.into()
}