Compare commits

..

3 Commits

Author SHA1 Message Date
5abdc88a35 feat!: Removed AddAdditionalMethods
All checks were successful
Build and deploy / build (push) Successful in 11m1s
Build and deploy / Deploy container (push) Successful in 40s
It has been replaced with the add_methods device attribute.
2025-09-09 04:24:20 +02:00
19cdb37dfb feat: Added attribute to easily register additional lua methods
Previously this could only be done by implementing a trait, like
`AddAdditionalMethods`, that that has an add_methods function where you
can put your custom methods. With this new attribute you can pass in a
register function directly!
2025-09-09 04:23:58 +02:00
3a33e3fa55 refactor!: Rewrote device implementation macro once again
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 04:05:56 +02:00
15 changed files with 165 additions and 97 deletions

1
Cargo.lock generated
View File

@@ -167,6 +167,7 @@ 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,7 +3,6 @@ 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};
@@ -32,7 +31,7 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device_traits(AddAdditionalMethods)] #[device(add_methods(Self::add_methods))]
pub struct HueBridge { pub struct HueBridge {
config: Config, config: Config,
} }
@@ -84,19 +83,8 @@ impl HueBridge {
} }
} }
} }
}
impl Device for HueBridge { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
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)| {
@@ -109,3 +97,9 @@ impl AddAdditionalMethods for 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,7 +3,6 @@ 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};
@@ -119,11 +118,26 @@ pub struct Config {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device_traits(AddAdditionalMethods)] #[device(add_methods(Self::add_methods))]
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;
@@ -162,21 +176,3 @@ 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,7 +6,6 @@ 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};
@@ -35,7 +34,7 @@ pub struct State {
} }
#[derive(Debug, Clone, Device)] #[derive(Debug, Clone, Device)]
#[device_traits(AddAdditionalMethods)] #[device(add_methods(Self::add_methods))]
pub struct Presence { pub struct Presence {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
@@ -49,6 +48,12 @@ 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]
@@ -125,14 +130,3 @@ 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,9 +78,3 @@ 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,3 +11,6 @@ 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,14 +4,41 @@ 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}; use syn::{Attribute, DeriveInput, Token, parenthesized};
struct DeviceTraitAttribute { enum Attr {
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 DeviceTraitAttribute { impl Parse for TraitAttr {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self { Ok(Self {
traits: input.parse()?, traits: input.parse()?,
@@ -62,7 +89,11 @@ 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]) {
return Ok(Default::default()); if input.is_empty() {
return Ok(Default::default());
} else {
return Err(input.error("Expected ')' or 'for'"));
}
} }
_ = input.parse::<syn::Token![for]>()?; _ = input.parse::<syn::Token![for]>()?;
@@ -74,23 +105,38 @@ 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 { generics, traits } = &self; let Self {
generics,
traits,
add_methods,
} = &self;
tokens.extend(quote! { tokens.extend(quote! {
#generics { #generics {
@@ -111,6 +157,10 @@ 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);
)*
} }
} }
}); });
@@ -119,20 +169,26 @@ impl quote::ToTokens for Implementation {
struct Implementations(Vec<Implementation>); struct Implementations(Vec<Implementation>);
impl From<Vec<DeviceTraitAttribute>> for Implementations { impl From<Vec<Attr>> for Implementations {
fn from(attributes: Vec<DeviceTraitAttribute>) -> Self { fn from(attributes: Vec<Attr>) -> 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 {
if attribute.generics.has_generics() { match attribute {
for generic in &attribute.generics.0 { Attr::Trait(attribute) => {
implementations if attribute.generics.has_generics() {
.entry(Some(generic.clone())) for generic in &attribute.generics.0 {
.or_default() implementations
.extend(&attribute.traits); .entry(Some(generic.clone()))
.or_default()
.extend(&attribute.traits);
}
} else {
all.extend(&attribute.traits);
}
} }
} else { Attr::AddMethods(attribute) => add_methods.push(attribute),
all.extend(&attribute.traits);
} }
} }
@@ -144,7 +200,16 @@ impl From<Vec<DeviceTraitAttribute>> for Implementations {
} }
} }
Self(implementations.into_iter().map(Into::into).collect()) Self(
implementations
.into_iter()
.map(|(generics, traits)| Implementation {
generics,
traits,
add_methods: add_methods.clone(),
})
.collect(),
)
} }
} }
@@ -154,7 +219,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_traits")) .filter(|attr| attr.path().is_ident("device"))
.map(Attribute::parse_args) .map(Attribute::parse_args)
.try_collect::<Vec<_>>() .try_collect::<Vec<_>>()
{ {

View File

@@ -32,25 +32,41 @@ 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`
/// ///
/// The `device_traits` attribute can be used to tell the macro what traits are implemented so that /// # Device traits
/// 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 attribute will have the traits applied to /// If your type _has_ type parameters any instance of the traits attribute that does not specify
/// _all_ other type parameter variations listed in the other attributes. /// any type parameters will have the traits applied to _all_ other type parameter variations
#[proc_macro_derive(Device, attributes(device_traits))] /// listed in the other trait attributes. This behavior only applies if there is at least one
/// 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::{SystemTime, UNIX_EPOCH}; use std::time::{Duration, SystemTime, UNIX_EPOCH};
use ::config::{Environment, File}; use ::config::{Environment, File};
use automation_lib::config::{FulfillmentConfig, MqttConfig}; use automation_lib::config::{FulfillmentConfig, MqttConfig};
@@ -172,6 +172,11 @@ 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)?;