diff --git a/Cargo.lock b/Cargo.lock index 805393a..2a2c450 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -103,7 +103,7 @@ dependencies = [ "enum_dispatch", "eui48", "futures", - "google-home", + "google_home", "hostname", "indexmap 2.2.6", "mlua", @@ -637,14 +637,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" [[package]] -name = "google-home" +name = "google_home" version = "0.1.0" dependencies = [ "anyhow", "async-trait", "automation_cast", - "automation_macro", "futures", + "google_home_macro", "json_value_merge", "serde", "serde_json", @@ -652,6 +652,15 @@ dependencies = [ "tokio", ] +[[package]] +name = "google_home_macro" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.60", +] + [[package]] name = "h2" version = "0.3.20" diff --git a/Cargo.toml b/Cargo.toml index 8486258..fa901b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [workspace] -members = ["google-home", "automation_macro", "automation_cast"] +members = ["automation_macro", "automation_cast", "google_home/google_home", "google_home/google_home_macro"] [dependencies] @@ -13,7 +13,7 @@ automation_cast = { path = "./automation_cast/" } rumqttc = "0.18" serde = { version = "1.0.149", features = ["derive"] } serde_json = "1.0.89" -google-home = { path = "./google-home" } +google_home = { path = "./google_home/google_home/" } paste = "1.0.10" tokio = { version = "1", features = ["rt-multi-thread"] } dotenvy = "0.15.0" @@ -43,7 +43,14 @@ enum_dispatch = "0.3.12" indexmap = { version = "2.0.0", features = ["serde"] } serde_yaml = "0.9.27" tokio-cron-scheduler = "0.9.4" -mlua = { version = "0.9.7", features = ["lua54", "vendored", "macros", "serialize", "async", "send"] } +mlua = { version = "0.9.7", features = [ + "lua54", + "vendored", + "macros", + "serialize", + "async", + "send", +] } once_cell = "1.19.0" hostname = "0.4.0" tokio-util = { version = "0.7.11", features = ["full"] } diff --git a/automation_macro/src/lib.rs b/automation_macro/src/lib.rs index da397ef..7cb1b9c 100644 --- a/automation_macro/src/lib.rs +++ b/automation_macro/src/lib.rs @@ -5,15 +5,7 @@ mod lua_device_config; use lua_device::impl_lua_device_macro; use lua_device_config::impl_lua_device_config_macro; -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, DeriveInput, GenericArgument, Ident, LitStr, Path, PathArguments, - PathSegment, ReturnType, Signature, Token, Type, TypePath, -}; +use syn::{parse_macro_input, DeriveInput}; #[proc_macro_derive(LuaDevice, attributes(config))] pub fn lua_device_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { @@ -28,561 +20,3 @@ pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::T impl_lua_device_config_macro(&ast).into() } - -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 { - 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 { - 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 { - 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 { - 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, -} - -impl Parse for Trait { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - 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, -} - -// TODO: Error on duplicate name? -impl Parse for Input { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - 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::(); - - 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 (""): - 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 (""): - 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) -> 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) -> 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> { - Ok(#state_ident { #(#state)* }) - } - } - } -} - -#[proc_macro] -pub fn google_home_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::>(); - - 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, serde_json::Value), Box>; - async fn query(&self) -> Result>; - async fn execute(&mut self, command: Command) -> Result>; - } - - #(#structs)* - - #command_enum - #trait_enum - - #[async_trait::async_trait] - impl #fulfillment for D where D: #ty - { - async fn sync(&self) -> Result<(Vec, serde_json::Value), Box> { - let mut traits = Vec::new(); - let mut attrs = serde_json::Value::Null; - - #(#sync)* - - Ok((traits, attrs)) - } - - async fn query(&self) -> Result> { - let mut state = serde_json::Value::Null; - - #(#query)* - - Ok(state) - } - - async fn execute(&mut self, command: Command) -> Result> { - let value = match command { - #(#execute)* - }; - - Ok(value) - } - } - } - .into() -} diff --git a/google-home/src/bin/expand.rs b/google-home/src/bin/expand.rs deleted file mode 100644 index 6739b40..0000000 --- a/google-home/src/bin/expand.rs +++ /dev/null @@ -1,86 +0,0 @@ -use std::error::Error; - -use automation_cast::Cast; -use automation_macro::google_home_traits; -use google_home::errors::ErrorCode; -use google_home::traits::AvailableSpeeds; - -trait GoogleHomeDevice: GoogleHomeDeviceFulfillment {} -google_home_traits! { - GoogleHomeDevice, - "action.devices.traits.OnOff" => trait OnOff { - command_only_on_off: Option, - query_only_on_off: Option, - async fn on(&self) -> Result, - "action.devices.commands.OnOff" => async fn set_on(&self, on: bool) -> Result<(), ErrorCode>, - }, - "action.devices.traits.Scene" => trait Scene { - scene_reversible: Option, - - "action.devices.commands.ActivateScene" => async fn set_active(&self, activate: bool) -> Result<(), ErrorCode>, - }, - "action.devices.traits.FanSpeed" => trait FanSpeed { - reversible: Option, - command_only_fan_speed: Option, - available_fan_speeds: AvailableSpeeds, - - fn current_fan_speed_setting(&self) -> Result, - fn current_fan_speed_percent(&self) -> Result, - - // TODO: Figure out some syntax for optional command? - // Probably better to just force the user to always implement commands? - "action.devices.commands.SetFanSpeed" => fn set_fan_speed(&self, fan_speed: String), - }, - "action.devices.traits.HumiditySetting" => trait HumiditySetting { - query_only_humidity_setting: Option, - - fn humidity_ambient_percent(&self) -> Result, ErrorCode>, - } -} - -struct Device {} -impl GoogleHomeDevice for Device {} - -#[async_trait::async_trait] -impl OnOff for Device { - fn command_only_on_off(&self) -> Option { - Some(true) - } - - async fn on(&self) -> Result { - Ok(true) - } - - async fn set_on(&self, _on: bool) -> Result<(), ErrorCode> { - Ok(()) - } -} - -#[async_trait::async_trait] -impl HumiditySetting for Device { - fn query_only_humidity_setting(&self) -> Option { - Some(true) - } - - fn humidity_ambient_percent(&self) -> Result, ErrorCode> { - Ok(Some(44)) - } -} - -#[tokio::main] -async fn main() -> Result<(), Box> { - let device: Box = Box::new(Device {}); - - let (traits, sync) = device.sync().await?; - let query = device.query().await?; - - println!("{traits:?}"); - println!("{sync}"); - println!("{query}"); - - let state = device.execute(Command::OnOff { on: true }).await?; - - println!("{state}"); - - Ok(()) -} diff --git a/google-home/Cargo.toml b/google_home/google_home/Cargo.toml similarity index 75% rename from google-home/Cargo.toml rename to google_home/google_home/Cargo.toml index cb1c861..346de26 100644 --- a/google-home/Cargo.toml +++ b/google_home/google_home/Cargo.toml @@ -1,13 +1,13 @@ [package] -name = "google-home" +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/" } -automation_macro = { path = "../automation_macro/" } +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" diff --git a/google-home/src/device.rs b/google_home/google_home/src/device.rs similarity index 88% rename from google-home/src/device.rs rename to google_home/google_home/src/device.rs index f11157e..03d0ae8 100644 --- a/google-home/src/device.rs +++ b/google_home/google_home/src/device.rs @@ -3,11 +3,11 @@ use serde::Serialize; use crate::errors::ErrorCode; use crate::response; -use crate::traits::{Command, GoogleHomeDeviceFulfillment}; +use crate::traits::{Command, DeviceFulfillment}; use crate::types::Type; #[async_trait] -pub trait GoogleHomeDevice: GoogleHomeDeviceFulfillment { +pub trait Device: DeviceFulfillment { fn get_device_type(&self) -> Type; fn get_device_name(&self) -> Name; fn get_id(&self) -> String; @@ -37,7 +37,7 @@ pub trait GoogleHomeDevice: GoogleHomeDeviceFulfillment { } device.device_info = self.get_device_info(); - let (traits, attributes) = GoogleHomeDeviceFulfillment::sync(self).await.unwrap(); + let (traits, attributes) = DeviceFulfillment::sync(self).await.unwrap(); device.traits = traits; device.attributes = attributes; @@ -51,13 +51,13 @@ pub trait GoogleHomeDevice: GoogleHomeDeviceFulfillment { device.set_offline(); } - device.state = GoogleHomeDeviceFulfillment::query(self).await.unwrap(); + device.state = DeviceFulfillment::query(self).await.unwrap(); device } async fn execute(&mut self, command: Command) -> Result<(), ErrorCode> { - GoogleHomeDeviceFulfillment::execute(self, command.clone()) + DeviceFulfillment::execute(self, command.clone()) .await .unwrap(); diff --git a/google-home/src/errors.rs b/google_home/google_home/src/errors.rs similarity index 100% rename from google-home/src/errors.rs rename to google_home/google_home/src/errors.rs diff --git a/google-home/src/fulfillment.rs b/google_home/google_home/src/fulfillment.rs similarity index 96% rename from google-home/src/fulfillment.rs rename to google_home/google_home/src/fulfillment.rs index 82eb426..f7f421a 100644 --- a/google-home/src/fulfillment.rs +++ b/google_home/google_home/src/fulfillment.rs @@ -9,7 +9,7 @@ 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::GoogleHomeDevice; +use crate::Device; #[derive(Debug)] pub struct GoogleHome { @@ -30,7 +30,7 @@ impl GoogleHome { } } - pub async fn handle_request + ?Sized + 'static>( + pub async fn handle_request + ?Sized + 'static>( &self, request: Request, devices: &HashMap>>>, @@ -59,14 +59,14 @@ impl GoogleHome { .map(|payload| Response::new(&request.request_id, payload)) } - async fn sync + ?Sized + 'static>( + async fn sync + ?Sized + 'static>( &self, devices: &HashMap>>>, ) -> 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(GoogleHomeDevice::sync(device).await) + Some(Device::sync(device).await) } else { None } @@ -76,7 +76,7 @@ impl GoogleHome { resp_payload } - async fn query + ?Sized + 'static>( + async fn query + ?Sized + 'static>( &self, payload: request::query::Payload, devices: &HashMap>>>, @@ -91,7 +91,7 @@ impl GoogleHome { let device = if let Some(device) = devices.get(id.as_str()) && let Some(device) = device.read().await.as_ref().cast() { - GoogleHomeDevice::query(device).await + Device::query(device).await } else { let mut device = query::Device::new(); device.set_offline(); @@ -108,7 +108,7 @@ impl GoogleHome { resp_payload } - async fn execute + ?Sized + 'static>( + async fn execute + ?Sized + 'static>( &self, payload: request::execute::Payload, devices: &HashMap>>>, @@ -147,8 +147,7 @@ impl GoogleHome { // NOTE: We can not use .map here because async =( let mut results = Vec::new(); for cmd in &execution { - results - .push(GoogleHomeDevice::execute(device, cmd.clone()).await); + results.push(Device::execute(device, cmd.clone()).await); } // Convert vec of results to a result with a vec and the first diff --git a/google-home/src/lib.rs b/google_home/google_home/src/lib.rs similarity index 89% rename from google-home/src/lib.rs rename to google_home/google_home/src/lib.rs index fab23bf..fea5720 100644 --- a/google-home/src/lib.rs +++ b/google_home/google_home/src/lib.rs @@ -11,7 +11,7 @@ pub mod errors; pub mod traits; pub mod types; -pub use device::GoogleHomeDevice; +pub use device::Device; pub use fulfillment::{FulfillmentError, GoogleHome}; pub use request::Request; pub use response::Response; diff --git a/google-home/src/request.rs b/google_home/google_home/src/request.rs similarity index 100% rename from google-home/src/request.rs rename to google_home/google_home/src/request.rs diff --git a/google-home/src/request/execute.rs b/google_home/google_home/src/request/execute.rs similarity index 98% rename from google-home/src/request/execute.rs rename to google_home/google_home/src/request/execute.rs index c7ae6ae..625a9cb 100644 --- a/google-home/src/request/execute.rs +++ b/google_home/google_home/src/request/execute.rs @@ -130,7 +130,7 @@ mod tests { assert_eq!(payload.commands[0].devices[1].id, "456"); assert_eq!(payload.commands[0].execution.len(), 1); match payload.commands[0].execution[0] { - CommandType::OnOff { on } => assert!(on), + traits::Command::OnOff { on } => assert!(on), _ => panic!("Expected OnOff"), } } diff --git a/google-home/src/request/query.rs b/google_home/google_home/src/request/query.rs similarity index 100% rename from google-home/src/request/query.rs rename to google_home/google_home/src/request/query.rs diff --git a/google-home/src/request/sync.rs b/google_home/google_home/src/request/sync.rs similarity index 100% rename from google-home/src/request/sync.rs rename to google_home/google_home/src/request/sync.rs diff --git a/google-home/src/response.rs b/google_home/google_home/src/response.rs similarity index 100% rename from google-home/src/response.rs rename to google_home/google_home/src/response.rs diff --git a/google-home/src/response/execute.rs b/google_home/google_home/src/response/execute.rs similarity index 100% rename from google-home/src/response/execute.rs rename to google_home/google_home/src/response/execute.rs diff --git a/google-home/src/response/query.rs b/google_home/google_home/src/response/query.rs similarity index 100% rename from google-home/src/response/query.rs rename to google_home/google_home/src/response/query.rs diff --git a/google-home/src/response/sync.rs b/google_home/google_home/src/response/sync.rs similarity index 100% rename from google-home/src/response/sync.rs rename to google_home/google_home/src/response/sync.rs diff --git a/google-home/src/traits.rs b/google_home/google_home/src/traits.rs similarity index 93% rename from google-home/src/traits.rs rename to google_home/google_home/src/traits.rs index 40d0e29..3f17740 100644 --- a/google-home/src/traits.rs +++ b/google_home/google_home/src/traits.rs @@ -1,12 +1,12 @@ use automation_cast::Cast; -use automation_macro::google_home_traits; +use google_home_macro::traits; use serde::Serialize; use crate::errors::ErrorCode; -use crate::GoogleHomeDevice; +use crate::Device; -google_home_traits! { - GoogleHomeDevice, +traits! { + Device, "action.devices.traits.OnOff" => trait OnOff { command_only_on_off: Option, query_only_on_off: Option, diff --git a/google-home/src/types.rs b/google_home/google_home/src/types.rs similarity index 100% rename from google-home/src/types.rs rename to google_home/google_home/src/types.rs diff --git a/google_home/google_home_macro/Cargo.toml b/google_home/google_home_macro/Cargo.toml new file mode 100644 index 0000000..977676d --- /dev/null +++ b/google_home/google_home_macro/Cargo.toml @@ -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"] } diff --git a/google_home/google_home_macro/src/lib.rs b/google_home/google_home_macro/src/lib.rs new file mode 100644 index 0000000..14e8e41 --- /dev/null +++ b/google_home/google_home_macro/src/lib.rs @@ -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 { + 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 { + 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 { + 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 { + 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, +} + +impl Parse for Trait { + fn parse(input: syn::parse::ParseStream) -> syn::Result { + 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, +} + +// TODO: Error on duplicate name? +impl Parse for Input { + fn parse(input: syn::parse::ParseStream) -> syn::Result { + 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::(); + + 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 (""): + 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 (""): + 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) -> 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) -> 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> { + 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::>(); + + 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, serde_json::Value), Box>; + async fn query(&self) -> Result>; + async fn execute(&mut self, command: Command) -> Result>; + } + + #(#structs)* + + #command_enum + #trait_enum + + #[async_trait::async_trait] + impl #fulfillment for D where D: #ty + { + async fn sync(&self) -> Result<(Vec, serde_json::Value), Box> { + let mut traits = Vec::new(); + let mut attrs = serde_json::Value::Null; + + #(#sync)* + + Ok((traits, attrs)) + } + + async fn query(&self) -> Result> { + let mut state = serde_json::Value::Null; + + #(#query)* + + Ok(state) + } + + async fn execute(&mut self, command: Command) -> Result> { + let value = match command { + #(#execute)* + }; + + Ok(value) + } + } + } + .into() +} diff --git a/src/devices/air_filter.rs b/src/devices/air_filter.rs index 3aa1cf3..60919fb 100644 --- a/src/devices/air_filter.rs +++ b/src/devices/air_filter.rs @@ -4,7 +4,6 @@ use google_home::device::Name; use google_home::errors::ErrorCode; use google_home::traits::{AvailableSpeeds, FanSpeed, HumiditySetting, OnOff, Speed, SpeedValues}; use google_home::types::Type; -use google_home::GoogleHomeDevice; use rumqttc::Publish; use tracing::{debug, error, trace, warn}; @@ -106,7 +105,7 @@ impl OnMqtt for AirFilter { } } -impl GoogleHomeDevice for AirFilter { +impl google_home::Device for AirFilter { fn get_device_type(&self) -> Type { Type::AirPurifier } diff --git a/src/devices/ikea_outlet.rs b/src/devices/ikea_outlet.rs index 14b8d76..15e8945 100644 --- a/src/devices/ikea_outlet.rs +++ b/src/devices/ikea_outlet.rs @@ -3,10 +3,10 @@ use std::time::Duration; use anyhow::Result; use async_trait::async_trait; use automation_macro::{LuaDevice, LuaDeviceConfig}; +use google_home::device; use google_home::errors::ErrorCode; use google_home::traits::{self, OnOff}; use google_home::types::Type; -use google_home::{device, GoogleHomeDevice}; use rumqttc::{matches, Publish, SubscribeFilter}; use serde::Deserialize; use tokio::task::JoinHandle; @@ -171,7 +171,7 @@ impl OnPresence for IkeaOutlet { } } -impl GoogleHomeDevice for IkeaOutlet { +impl google_home::Device for IkeaOutlet { fn get_device_type(&self) -> Type { match self.config.outlet_type { OutletType::Outlet => Type::Outlet, diff --git a/src/devices/mod.rs b/src/devices/mod.rs index b69a1b1..927af26 100644 --- a/src/devices/mod.rs +++ b/src/devices/mod.rs @@ -17,7 +17,6 @@ use std::fmt::Debug; use async_trait::async_trait; use automation_cast::Cast; use google_home::traits::OnOff; -use google_home::GoogleHomeDevice; pub use self::air_filter::*; pub use self::audio_setup::*; @@ -67,7 +66,7 @@ pub trait Device: Debug + Sync + Send - + Cast + + Cast + Cast + Cast + Cast diff --git a/src/devices/wake_on_lan.rs b/src/devices/wake_on_lan.rs index 0454f70..8b54b27 100644 --- a/src/devices/wake_on_lan.rs +++ b/src/devices/wake_on_lan.rs @@ -3,10 +3,10 @@ use std::net::Ipv4Addr; use async_trait::async_trait; use automation_macro::{LuaDevice, LuaDeviceConfig}; use eui48::MacAddress; +use google_home::device; use google_home::errors::ErrorCode; use google_home::traits::{self, Scene}; use google_home::types::Type; -use google_home::{device, GoogleHomeDevice}; use rumqttc::Publish; use tracing::{debug, error, trace}; @@ -76,7 +76,7 @@ impl OnMqtt for WakeOnLAN { } } -impl GoogleHomeDevice for WakeOnLAN { +impl google_home::Device for WakeOnLAN { fn get_device_type(&self) -> Type { Type::Scene }