Compare commits

..

1 Commits

Author SHA1 Message Date
e0d2e846ff refactor!: Rewrote device implementation macro once again
All checks were successful
Build and deploy / build (push) Successful in 12m34s
Build and deploy / Deploy container (push) Successful in 30s
This time with a bit more though put into the design of the code, as a
result the macro should be a lot more robust.

This did result in the macro getting renamed from LuaDevice to Device as
this should be _the_ Device macro.
The attribute also got renamed from traits to device_traits and the
syntax got overhauled to allow for a bit more expression.
2025-09-09 02:48:44 +02:00
15 changed files with 97 additions and 165 deletions

1
Cargo.lock generated
View File

@@ -167,7 +167,6 @@ name = "automation_macro"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"itertools", "itertools",
"mlua",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn 2.0.106",

View File

@@ -20,7 +20,7 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff))] #[device_traits(OnOff)]
pub struct AirFilter { pub struct AirFilter {
config: Config, config: Config,
} }

View File

@@ -49,7 +49,7 @@ struct State {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OpenClose))] #[device_traits(OpenClose)]
pub struct ContactSensor { pub struct ContactSensor {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,

View File

@@ -3,6 +3,7 @@ use std::net::SocketAddr;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::lua::traits::AddAdditionalMethods;
use automation_macro::{Device, LuaDeviceConfig}; use automation_macro::{Device, LuaDeviceConfig};
use mlua::LuaSerdeExt; use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -31,7 +32,7 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(add_methods(Self::add_methods))] #[device_traits(AddAdditionalMethods)]
pub struct HueBridge { pub struct HueBridge {
config: Config, config: Config,
} }
@@ -83,8 +84,19 @@ impl HueBridge {
} }
} }
} }
}
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { impl Device for HueBridge {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}
impl AddAdditionalMethods for HueBridge {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static,
{
methods.add_async_method( methods.add_async_method(
"set_flag", "set_flag",
async |lua, this, (flag, value): (mlua::Value, bool)| { async |lua, this, (flag, value): (mlua::Value, bool)| {
@@ -97,9 +109,3 @@ impl HueBridge {
); );
} }
} }
impl Device for HueBridge {
fn get_id(&self) -> String {
self.config.identifier.clone()
}
}

View File

@@ -20,7 +20,7 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff))] #[device_traits(OnOff)]
pub struct HueGroup { pub struct HueGroup {
config: Config, config: Config,
} }

View File

@@ -22,7 +22,7 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff))] #[device_traits(OnOff)]
pub struct KasaOutlet { pub struct KasaOutlet {
config: Config, config: Config,
} }

View File

@@ -3,6 +3,7 @@ use std::convert::Infallible;
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::lua::traits::AddAdditionalMethods;
use automation_macro::{Device, LuaDeviceConfig}; use automation_macro::{Device, LuaDeviceConfig};
use mlua::LuaSerdeExt; use mlua::LuaSerdeExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -118,26 +119,11 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(add_methods(Self::add_methods))] #[device_traits(AddAdditionalMethods)]
pub struct Ntfy { pub struct Ntfy {
config: Config, config: Config,
} }
impl Ntfy {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method(
"send_notification",
async |lua, this, notification: mlua::Value| {
let notification: Notification = lua.from_value(notification)?;
this.send(notification).await;
Ok(())
},
);
}
}
#[async_trait] #[async_trait]
impl LuaDeviceCreate for Ntfy { impl LuaDeviceCreate for Ntfy {
type Config = Config; type Config = Config;
@@ -176,3 +162,21 @@ impl Ntfy {
} }
} }
} }
impl AddAdditionalMethods for Ntfy {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static,
{
methods.add_async_method(
"send_notification",
async |lua, this, notification: mlua::Value| {
let notification: Notification = lua.from_value(notification)?;
this.send(notification).await;
Ok(())
},
);
}
}

View File

@@ -6,6 +6,7 @@ use automation_lib::action_callback::ActionCallback;
use automation_lib::config::MqttDeviceConfig; use automation_lib::config::MqttDeviceConfig;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::lua::traits::AddAdditionalMethods;
use automation_lib::messages::PresenceMessage; use automation_lib::messages::PresenceMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{Device, LuaDeviceConfig}; use automation_macro::{Device, LuaDeviceConfig};
@@ -34,7 +35,7 @@ pub struct State {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(add_methods(Self::add_methods))] #[device_traits(AddAdditionalMethods)]
pub struct Presence { pub struct Presence {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
@@ -48,12 +49,6 @@ impl Presence {
async fn state_mut(&self) -> RwLockWriteGuard<'_, State> { async fn state_mut(&self) -> RwLockWriteGuard<'_, State> {
self.state.write().await self.state.write().await
} }
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_method("overall_presence", async |_lua, this, ()| {
Ok(this.state().await.current_overall_presence)
});
}
} }
#[async_trait] #[async_trait]
@@ -130,3 +125,14 @@ impl OnMqtt for Presence {
} }
} }
} }
impl AddAdditionalMethods for Presence {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static,
{
methods.add_async_method("overall_presence", async |_lua, this, ()| {
Ok(this.state().await.current_overall_presence)
});
}
}

View File

@@ -89,9 +89,9 @@ impl From<StateColorTemperature> for StateBrightness {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff for <StateOnOff>, <StateBrightness>, <StateColorTemperature>))] #[device_traits(OnOff for <StateOnOff>, <StateBrightness>, <StateColorTemperature>)]
#[device(traits(Brightness for <StateBrightness>, <StateColorTemperature>))] #[device_traits(Brightness for <StateBrightness>, <StateColorTemperature>)]
#[device(traits(ColorSetting for <StateColorTemperature>))] #[device_traits(ColorSetting for <StateColorTemperature>)]
pub struct Light<T: LightState> { pub struct Light<T: LightState> {
config: Config<T>, config: Config<T>,

View File

@@ -81,7 +81,7 @@ impl From<StatePower> for StateOnOff {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device(traits(OnOff for <StateOnOff>, <StatePower>))] #[device_traits(OnOff for <StateOnOff>, <StatePower>)]
pub struct Outlet<T: OutletState> { pub struct Outlet<T: OutletState> {
config: Config<T>, config: Config<T>,

View File

@@ -78,3 +78,9 @@ pub trait OpenClose {
} }
} }
impl<T> OpenClose for T where T: google_home::traits::OpenClose {} impl<T> OpenClose for T where T: google_home::traits::OpenClose {}
pub trait AddAdditionalMethods {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M)
where
Self: Sized + 'static;
}

View File

@@ -11,6 +11,3 @@ itertools = { workspace = true }
proc-macro2 = { workspace = true } proc-macro2 = { workspace = true }
quote = { workspace = true } quote = { workspace = true }
syn = { workspace = true } syn = { workspace = true }
[dev-dependencies]
mlua = { workspace = true }

View File

@@ -4,41 +4,14 @@ use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, quote}; use quote::{ToTokens, quote};
use syn::parse::{Parse, ParseStream}; use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated; use syn::punctuated::Punctuated;
use syn::{Attribute, DeriveInput, Token, parenthesized}; use syn::{Attribute, DeriveInput, Token};
enum Attr { struct DeviceTraitAttribute {
Trait(TraitAttr),
AddMethods(AddMethodsAttr),
}
impl Parse for Attr {
fn parse(input: ParseStream) -> syn::Result<Self> {
let ident: syn::Ident = input.parse()?;
let attr;
_ = parenthesized!(attr in input);
let attr = match ident.to_string().as_str() {
"traits" => Attr::Trait(attr.parse()?),
"add_methods" => Attr::AddMethods(attr.parse()?),
_ => {
return Err(syn::Error::new(
ident.span(),
"Expected 'traits' or 'add_methods'",
));
}
};
Ok(attr)
}
}
struct TraitAttr {
traits: Traits, traits: Traits,
generics: Generics, generics: Generics,
} }
impl Parse for TraitAttr { impl Parse for DeviceTraitAttribute {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self { Ok(Self {
traits: input.parse()?, traits: input.parse()?,
@@ -89,11 +62,7 @@ impl Generics {
impl Parse for Generics { impl Parse for Generics {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
if !input.peek(Token![for]) { if !input.peek(Token![for]) {
if input.is_empty() {
return Ok(Default::default()); return Ok(Default::default());
} else {
return Err(input.error("Expected ')' or 'for'"));
}
} }
_ = input.parse::<syn::Token![for]>()?; _ = input.parse::<syn::Token![for]>()?;
@@ -105,38 +74,23 @@ impl Parse for Generics {
} }
} }
#[derive(Clone)]
struct AddMethodsAttr(syn::Path);
impl Parse for AddMethodsAttr {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self(input.parse()?))
}
}
impl ToTokens for AddMethodsAttr {
fn to_tokens(&self, tokens: &mut TokenStream2) {
let Self(path) = self;
tokens.extend(quote! {
#path
});
}
}
struct Implementation { struct Implementation {
generics: Option<syn::AngleBracketedGenericArguments>, generics: Option<syn::AngleBracketedGenericArguments>,
traits: Traits, traits: Traits,
add_methods: Vec<AddMethodsAttr>, }
impl From<(Option<syn::AngleBracketedGenericArguments>, Traits)> for Implementation {
fn from(value: (Option<syn::AngleBracketedGenericArguments>, Traits)) -> Self {
Self {
generics: value.0,
traits: value.1,
}
}
} }
impl quote::ToTokens for Implementation { impl quote::ToTokens for Implementation {
fn to_tokens(&self, tokens: &mut TokenStream2) { fn to_tokens(&self, tokens: &mut TokenStream2) {
let Self { let Self { generics, traits } = &self;
generics,
traits,
add_methods,
} = &self;
tokens.extend(quote! { tokens.extend(quote! {
#generics { #generics {
@@ -157,10 +111,6 @@ impl quote::ToTokens for Implementation {
methods.add_async_method("get_id", async |_lua, this, _: ()| { Ok(this.get_id()) }); methods.add_async_method("get_id", async |_lua, this, _: ()| { Ok(this.get_id()) });
#traits #traits
#(
#add_methods(methods);
)*
} }
} }
}); });
@@ -169,14 +119,11 @@ impl quote::ToTokens for Implementation {
struct Implementations(Vec<Implementation>); struct Implementations(Vec<Implementation>);
impl From<Vec<Attr>> for Implementations { impl From<Vec<DeviceTraitAttribute>> for Implementations {
fn from(attributes: Vec<Attr>) -> Self { fn from(attributes: Vec<DeviceTraitAttribute>) -> Self {
let mut add_methods = Vec::new();
let mut all = Traits::default(); let mut all = Traits::default();
let mut implementations: HashMap<_, Traits> = HashMap::new(); let mut implementations: HashMap<_, Traits> = HashMap::new();
for attribute in attributes { for attribute in attributes {
match attribute {
Attr::Trait(attribute) => {
if attribute.generics.has_generics() { if attribute.generics.has_generics() {
for generic in &attribute.generics.0 { for generic in &attribute.generics.0 {
implementations implementations
@@ -188,9 +135,6 @@ impl From<Vec<Attr>> for Implementations {
all.extend(&attribute.traits); all.extend(&attribute.traits);
} }
} }
Attr::AddMethods(attribute) => add_methods.push(attribute),
}
}
if implementations.is_empty() { if implementations.is_empty() {
implementations.entry(None).or_default().extend(&all); implementations.entry(None).or_default().extend(&all);
@@ -200,16 +144,7 @@ impl From<Vec<Attr>> for Implementations {
} }
} }
Self( Self(implementations.into_iter().map(Into::into).collect())
implementations
.into_iter()
.map(|(generics, traits)| Implementation {
generics,
traits,
add_methods: add_methods.clone(),
})
.collect(),
)
} }
} }
@@ -219,7 +154,7 @@ pub fn device(input: &DeriveInput) -> TokenStream2 {
let Implementations(imp) = match input let Implementations(imp) = match input
.attrs .attrs
.iter() .iter()
.filter(|attr| attr.path().is_ident("device")) .filter(|attr| attr.path().is_ident("device_traits"))
.map(Attribute::parse_args) .map(Attribute::parse_args)
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
{ {

View File

@@ -32,41 +32,25 @@ pub fn lua_serialize(input: proc_macro::TokenStream) -> proc_macro::TokenStream
/// Derive macro generating an impl for the trait `::mlua::UserData` /// Derive macro generating an impl for the trait `::mlua::UserData`
/// ///
/// # Device traits /// The `device_traits` attribute can be used to tell the macro what traits are implemented so that
/// The `device(traits)` attribute can be used to tell the macro what traits are implemented so that
/// the appropriate methods can automatically be registered. /// the appropriate methods can automatically be registered.
/// If the struct does not have any type parameters the syntax is very simple: /// If the struct does not have any type parameters the syntax is very simple:
/// ```rust /// ```
/// #[device(traits(TraitA, TraitB))] /// #[device_traits(TraitA, TraitB)]
/// ``` /// ```
/// ///
/// If the type does have type parameters you will have to manually specify all variations that /// If the type does have type parameters you will have to manually specify all variations that
/// have the trait available: /// have the trait available:
/// ```rust /// ```
/// #[device(traits(TraitA, TraitB for <StateA>, <StateB>))] /// #[device_traits(TraitA, TraitB for <StateA>, <StateB>)]
/// ``` /// ```
/// If multiple of these attributes are specified they will all combined appropriately. /// If multiple of these attributes are specified they will all combined appropriately.
/// ///
/// ///
/// ## NOTE /// # NOTE
/// If your type _has_ type parameters any instance of the traits attribute that does not specify /// If your type has type parameters any instance of the attribute will have the traits applied to
/// any type parameters will have the traits applied to _all_ other type parameter variations /// _all_ other type parameter variations listed in the other attributes.
/// listed in the other trait attributes. This behavior only applies if there is at least one #[proc_macro_derive(Device, attributes(device_traits))]
/// instance with type parameters specified.
///
/// # Additional methods
/// Additional methods can be added by using the `device(add_methods)` attribute. This attribute
/// takes the path to a function with the following signature that can register the additional methods:
///
/// ```rust
/// # struct D;
/// fn top_secret<M: mlua::UserDataMethods<D>>(methods: &mut M) {}
/// ```
/// It can then be registered with:
/// ```rust
/// #[device(add_methods(top_secret))]
/// ```
#[proc_macro_derive(Device, attributes(device))]
pub fn device(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn device(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = parse_macro_input!(input as DeriveInput); let ast = parse_macro_input!(input as DeriveInput);
device::device(&ast).into() device::device(&ast).into()

View File

@@ -7,7 +7,7 @@ mod web;
use std::net::SocketAddr; use std::net::SocketAddr;
use std::path::Path; use std::path::Path;
use std::process; use std::process;
use std::time::{Duration, SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use ::config::{Environment, File}; use ::config::{Environment, File};
use automation_lib::config::{FulfillmentConfig, MqttConfig}; use automation_lib::config::{FulfillmentConfig, MqttConfig};
@@ -172,11 +172,6 @@ async fn app() -> anyhow::Result<()> {
.as_millis()) .as_millis())
})?; })?;
utils.set("get_epoch", get_epoch)?; utils.set("get_epoch", get_epoch)?;
let sleep = lua.create_async_function(async |_lua, duration: u64| {
tokio::time::sleep(Duration::from_millis(duration)).await;
Ok(())
})?;
utils.set("sleep", sleep)?;
lua.register_module("utils", utils)?; lua.register_module("utils", utils)?;
automation_devices::register_with_lua(&lua)?; automation_devices::register_with_lua(&lua)?;