Cleanup
This commit is contained in:
parent
9aa16e3ef8
commit
758500a071
15
Cargo.lock
generated
15
Cargo.lock
generated
|
@ -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"
|
||||
|
|
13
Cargo.toml
13
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"] }
|
||||
|
|
|
@ -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<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 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::<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()
|
||||
}
|
||||
|
|
|
@ -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<bool>,
|
||||
query_only_on_off: Option<bool>,
|
||||
async fn on(&self) -> Result<bool, ErrorCode>,
|
||||
"action.devices.commands.OnOff" => async fn set_on(&self, on: bool) -> Result<(), ErrorCode>,
|
||||
},
|
||||
"action.devices.traits.Scene" => trait Scene {
|
||||
scene_reversible: Option<bool>,
|
||||
|
||||
"action.devices.commands.ActivateScene" => async fn set_active(&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>,
|
||||
fn current_fan_speed_percent(&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" => fn set_fan_speed(&self, fan_speed: String),
|
||||
},
|
||||
"action.devices.traits.HumiditySetting" => trait HumiditySetting {
|
||||
query_only_humidity_setting: Option<bool>,
|
||||
|
||||
fn humidity_ambient_percent(&self) -> Result<Option<isize>, ErrorCode>,
|
||||
}
|
||||
}
|
||||
|
||||
struct Device {}
|
||||
impl GoogleHomeDevice for Device {}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl OnOff for Device {
|
||||
fn command_only_on_off(&self) -> Option<bool> {
|
||||
Some(true)
|
||||
}
|
||||
|
||||
async fn on(&self) -> Result<bool, ErrorCode> {
|
||||
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<bool> {
|
||||
Some(true)
|
||||
}
|
||||
|
||||
fn humidity_ambient_percent(&self) -> Result<Option<isize>, ErrorCode> {
|
||||
Ok(Some(44))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let device: Box<dyn GoogleHomeDevice> = 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(())
|
||||
}
|
|
@ -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"
|
|
@ -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();
|
||||
|
|
@ -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<T: Cast<dyn GoogleHomeDevice> + ?Sized + 'static>(
|
||||
pub async fn handle_request<T: Cast<dyn Device> + ?Sized + 'static>(
|
||||
&self,
|
||||
request: Request,
|
||||
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
|
||||
|
@ -59,14 +59,14 @@ impl GoogleHome {
|
|||
.map(|payload| Response::new(&request.request_id, payload))
|
||||
}
|
||||
|
||||
async fn sync<T: Cast<dyn GoogleHomeDevice> + ?Sized + 'static>(
|
||||
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(GoogleHomeDevice::sync(device).await)
|
||||
Some(Device::sync(device).await)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
@ -76,7 +76,7 @@ impl GoogleHome {
|
|||
resp_payload
|
||||
}
|
||||
|
||||
async fn query<T: Cast<dyn GoogleHomeDevice> + ?Sized + 'static>(
|
||||
async fn query<T: Cast<dyn Device> + ?Sized + 'static>(
|
||||
&self,
|
||||
payload: request::query::Payload,
|
||||
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
|
||||
|
@ -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<T: Cast<dyn GoogleHomeDevice> + ?Sized + 'static>(
|
||||
async fn execute<T: Cast<dyn Device> + ?Sized + 'static>(
|
||||
&self,
|
||||
payload: request::execute::Payload,
|
||||
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
|
||||
|
@ -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
|
|
@ -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;
|
|
@ -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"),
|
||||
}
|
||||
}
|
|
@ -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<bool>,
|
||||
query_only_on_off: Option<bool>,
|
12
google_home/google_home_macro/Cargo.toml
Normal file
12
google_home/google_home_macro/Cargo.toml
Normal 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"] }
|
569
google_home/google_home_macro/src/lib.rs
Normal file
569
google_home/google_home_macro/src/lib.rs
Normal 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()
|
||||
}
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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<dyn GoogleHomeDevice>
|
||||
+ Cast<dyn google_home::Device>
|
||||
+ Cast<dyn OnMqtt>
|
||||
+ Cast<dyn OnMqtt>
|
||||
+ Cast<dyn OnPresence>
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user