Converted macro to derive macro

This commit is contained in:
2025-08-30 04:20:27 +02:00
parent d2b01123b8
commit 5d342afb1f
17 changed files with 108 additions and 97 deletions

View File

@@ -1,7 +1,7 @@
use async_trait::async_trait; use async_trait::async_trait;
use automation_lib::config::InfoConfig; use automation_lib::config::InfoConfig;
use automation_lib::device::{Device, LuaDeviceCreate}; use automation_lib::device::{Device, LuaDeviceCreate};
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device::Name; use google_home::device::Name;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::{ use google_home::traits::{
@@ -19,7 +19,8 @@ pub struct Config {
pub url: String, pub url: String,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct AirFilter { pub struct AirFilter {
config: Config, config: Config,
} }
@@ -62,7 +63,6 @@ impl AirFilter {
Ok(reqwest::get(url).await?.json().await?) Ok(reqwest::get(url).await?.json().await?)
} }
} }
impl_device!(AirFilter);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for AirFilter { impl LuaDeviceCreate for AirFilter {

View File

@@ -10,7 +10,7 @@ use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::messages::{ContactMessage, PresenceMessage}; use automation_lib::messages::{ContactMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::presence::DEFAULT_PRESENCE; use automation_lib::presence::DEFAULT_PRESENCE;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::{DeviceError, ErrorCode}; use google_home::errors::{DeviceError, ErrorCode};
use google_home::traits::OpenClose; use google_home::traits::OpenClose;
@@ -61,12 +61,12 @@ struct State {
handle: Option<JoinHandle<()>>, handle: Option<JoinHandle<()>>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OpenClose)]
pub struct ContactSensor { pub struct ContactSensor {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(ContactSensor);
impl ContactSensor { impl ContactSensor {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence}; use automation_lib::event::{OnDarkness, OnPresence};
use automation_lib::messages::{DarknessMessage, PresenceMessage}; use automation_lib::messages::{DarknessMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn}; use tracing::{trace, warn};
#[derive(Debug, LuaDeviceConfig, Clone)] #[derive(Debug, LuaDeviceConfig, Clone)]
@@ -18,11 +18,10 @@ pub struct Config {
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct DebugBridge { pub struct DebugBridge {
config: Config, config: Config,
} }
impl_device!(DebugBridge);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for DebugBridge { impl LuaDeviceCreate for DebugBridge {

View File

@@ -4,7 +4,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::event::{OnDarkness, OnPresence}; use automation_lib::event::{OnDarkness, OnPresence};
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
@@ -29,11 +29,10 @@ pub struct Config {
pub flags: FlagIDs, pub flags: FlagIDs,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct HueBridge { pub struct HueBridge {
config: Config, config: Config,
} }
impl_device!(HueBridge);
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
struct FlagMessage { struct FlagMessage {

View File

@@ -2,7 +2,7 @@ use std::net::SocketAddr;
use anyhow::Result; use anyhow::Result;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
@@ -19,11 +19,11 @@ pub struct Config {
pub scene_id: String, pub scene_id: String,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct HueGroup { pub struct HueGroup {
config: Config, config: Config,
} }
impl_device!(HueGroup);
// Couple of helper function to get the correct urls // Couple of helper function to get the correct urls
#[async_trait] #[async_trait]

View File

@@ -4,7 +4,7 @@ use automation_lib::config::{InfoConfig, 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::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::{Publish, matches}; use rumqttc::{Publish, matches};
use serde::Deserialize; use serde::Deserialize;
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
@@ -51,11 +51,10 @@ struct State {
action: Action, action: Action,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct HueSwitch { pub struct HueSwitch {
config: Config, config: Config,
} }
impl_device!(HueSwitch);
impl Device for HueSwitch { impl Device for HueSwitch {
fn get_id(&self) -> String { fn get_id(&self) -> String {

View File

@@ -4,7 +4,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::messages::{RemoteAction, RemoteMessage}; use automation_lib::messages::{RemoteAction, RemoteMessage};
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use axum::async_trait; use axum::async_trait;
use rumqttc::{Publish, matches}; use rumqttc::{Publish, matches};
use tracing::{debug, error, trace}; use tracing::{debug, error, trace};
@@ -27,11 +27,10 @@ pub struct Config {
pub callback: ActionCallback<IkeaRemote, bool>, pub callback: ActionCallback<IkeaRemote, bool>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct IkeaRemote { pub struct IkeaRemote {
config: Config, config: Config,
} }
impl_device!(IkeaRemote);
impl Device for IkeaRemote { impl Device for IkeaRemote {
fn get_id(&self) -> String { fn get_id(&self) -> String {

View File

@@ -5,7 +5,7 @@ use std::str::Utf8Error;
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::event::OnPresence; use automation_lib::event::OnPresence;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use bytes::{Buf, BufMut}; use bytes::{Buf, BufMut};
use google_home::errors::{self, DeviceError}; use google_home::errors::{self, DeviceError};
use google_home::traits::OnOff; use google_home::traits::OnOff;
@@ -22,11 +22,11 @@ pub struct Config {
pub addr: SocketAddr, pub addr: SocketAddr,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct KasaOutlet { pub struct KasaOutlet {
config: Config, config: Config,
} }
impl_device!(KasaOutlet);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for KasaOutlet { impl LuaDeviceCreate for KasaOutlet {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{self, Event, EventChannel, OnMqtt}; use automation_lib::event::{self, Event, EventChannel, OnMqtt};
use automation_lib::messages::BrightnessMessage; use automation_lib::messages::BrightnessMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
is_dark: bool, is_dark: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct LightSensor { pub struct LightSensor {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(LightSensor);
impl LightSensor { impl LightSensor {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -6,7 +6,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnMqtt; use automation_lib::event::OnMqtt;
use automation_lib::messages::ActivateMessage; use automation_lib::messages::ActivateMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use eui48::MacAddress; use eui48::MacAddress;
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
@@ -28,11 +28,10 @@ pub struct Config {
pub client: WrappedAsyncClient, pub client: WrappedAsyncClient,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct WakeOnLAN { pub struct WakeOnLAN {
config: Config, config: Config,
} }
impl_device!(WakeOnLAN);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for WakeOnLAN { impl LuaDeviceCreate for WakeOnLAN {

View File

@@ -7,7 +7,7 @@ use automation_lib::event::{self, Event, EventChannel, OnMqtt};
use automation_lib::messages::PowerMessage; use automation_lib::messages::PowerMessage;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_lib::ntfy::{Notification, Priority}; use automation_lib::ntfy::{Notification, Priority};
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn}; use tracing::{debug, error, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
} }
// TODO: Add google home integration // TODO: Add google home integration
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct Washer { pub struct Washer {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(Washer);
impl Washer { impl Washer {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -10,7 +10,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnMqtt, OnPresence}; use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::helpers::serialization::state_deserializer; use automation_lib::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff}; use google_home::traits::{Brightness, Color, ColorSetting, ColorTemperatureRange, OnOff};
@@ -88,7 +88,10 @@ impl From<StateColorTemperature> for StateBrightness {
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(<StateOnOff>: OnOff)]
#[traits(<StateBrightness>: OnOff, Brightness)]
#[traits(<StateColorTemperature>: OnOff, Brightness, ColorSetting)]
pub struct Light<T: LightState> { pub struct Light<T: LightState> {
config: Config<T>, config: Config<T>,
@@ -96,11 +99,8 @@ pub struct Light<T: LightState> {
} }
pub type LightOnOff = Light<StateOnOff>; pub type LightOnOff = Light<StateOnOff>;
impl_device!(LightOnOff -> OnOff);
pub type LightBrightness = Light<StateBrightness>; pub type LightBrightness = Light<StateBrightness>;
impl_device!(LightBrightness -> OnOff, Brightness);
pub type LightColorTemperature = Light<StateColorTemperature>; pub type LightColorTemperature = Light<StateColorTemperature>;
impl_device!(LightColorTemperature -> OnOff, Brightness, ColorSetting);
impl<T: LightState> Light<T> { impl<T: LightState> Light<T> {
async fn state(&self) -> RwLockReadGuard<'_, T> { async fn state(&self) -> RwLockReadGuard<'_, T> {

View File

@@ -10,7 +10,7 @@ use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnMqtt, OnPresence}; use automation_lib::event::{OnMqtt, OnPresence};
use automation_lib::helpers::serialization::state_deserializer; use automation_lib::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient; use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device; use google_home::device;
use google_home::errors::ErrorCode; use google_home::errors::ErrorCode;
use google_home::traits::OnOff; use google_home::traits::OnOff;
@@ -84,7 +84,9 @@ impl From<StatePower> for StateOnOff {
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
#[traits(<StateOnOff>: OnOff)]
#[traits(<StatePower>: OnOff)]
pub struct Outlet<T: OutletState> { pub struct Outlet<T: OutletState> {
config: Config<T>, config: Config<T>,
@@ -92,9 +94,7 @@ pub struct Outlet<T: OutletState> {
} }
pub type OutletOnOff = Outlet<StateOnOff>; pub type OutletOnOff = Outlet<StateOnOff>;
impl_device!(OutletOnOff -> OnOff);
pub type OutletPower = Outlet<StatePower>; pub type OutletPower = Outlet<StatePower>;
impl_device!(OutletPower -> OnOff);
impl<T: OutletState> Outlet<T> { impl<T: OutletState> Outlet<T> {
async fn state(&self) -> RwLockReadGuard<'_, T> { async fn state(&self) -> RwLockReadGuard<'_, T> {

View File

@@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::convert::Infallible; use std::convert::Infallible;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::Serialize; use serde::Serialize;
use serde_repr::*; use serde_repr::*;
use tracing::{error, trace, warn}; use tracing::{error, trace, warn};
@@ -119,11 +119,10 @@ pub struct Config {
pub tx: event::Sender, pub tx: event::Sender,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct Ntfy { pub struct Ntfy {
config: Config, config: Config,
} }
impl_device!(Ntfy);
#[async_trait] #[async_trait]
impl LuaDeviceCreate for Ntfy { impl LuaDeviceCreate for Ntfy {

View File

@@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use automation_macro::{LuaDeviceConfig, impl_device}; use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish; use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}; use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn}; use tracing::{debug, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
current_overall_presence: bool, current_overall_presence: bool,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone, LuaDevice)]
pub struct Presence { pub struct Presence {
config: Config, config: Config,
state: Arc<RwLock<State>>, state: Arc<RwLock<State>>,
} }
impl_device!(Presence);
impl Presence { impl Presence {
async fn state(&self) -> RwLockReadGuard<'_, State> { async fn state(&self) -> RwLockReadGuard<'_, State> {

View File

@@ -1,70 +1,88 @@
use proc_macro::TokenStream; use proc_macro2::TokenStream;
use quote::quote; use quote::{ToTokens, quote};
use syn::parse::Parse; use syn::parse::Parse;
use syn::punctuated::Punctuated; use syn::punctuated::Punctuated;
use syn::{Path, Token, parse_macro_input}; use syn::{AngleBracketedGenericArguments, Attribute, DeriveInput, Ident, Path, Token};
struct ImplDevice { #[derive(Debug, Default)]
ty: Path, struct Impl {
impls: Option<Punctuated<Path, Token![,]>>, generics: Option<AngleBracketedGenericArguments>,
traits: Vec<Path>,
} }
impl Parse for ImplDevice { impl Parse for Impl {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ty = input.parse()?; let generics = if input.peek(Token![<]) {
let impls = if input.peek(Token![->]) { let generics = input.parse()?;
input.parse::<Token![->]>()?; input.parse::<Token![:]>()?;
Some(input.parse_terminated(Path::parse, Token![,])?)
Some(generics)
} else { } else {
None None
}; };
Ok(ImplDevice { ty, impls }) let traits: Punctuated<_, _> = input.parse_terminated(Path::parse, Token![,])?;
let traits = traits.into_iter().collect();
Ok(Impl { generics, traits })
} }
} }
pub fn impl_device_macro(input: proc_macro::TokenStream) -> TokenStream { impl Impl {
let ImplDevice { ty, impls } = parse_macro_input!(input as ImplDevice); fn generate(&self, name: &Ident) -> TokenStream {
let generics = &self.generics;
let impls: Vec<_> = impls // If an identifier is specified, assume it is placed in ::automation_lib::lua::traits,
.iter() // otherwise use the provided path
.flatten() let traits = self.traits.iter().map(|t| {
.map(|i| { if let Some(ident) = t.get_ident() {
let ident = i quote! {::automation_lib::lua::traits::#ident }
.segments } else {
.last() t.to_token_stream()
.expect("There should be at least one segment")
.ident
.clone();
quote! {
::automation_lib::lua::traits::#ident::add_methods(methods);
} }
}) });
.collect();
quote! { quote! {
impl mlua::UserData for #ty { impl mlua::UserData for #name #generics {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) { fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_function("new", |_lua, config| async { methods.add_async_function("new", |_lua, config| async {
let device: #ty = LuaDeviceCreate::create(config) let device: Self = LuaDeviceCreate::create(config)
.await .await
.map_err(mlua::ExternalError::into_lua_err)?; .map_err(mlua::ExternalError::into_lua_err)?;
Ok(device) Ok(device)
}); });
methods.add_method("__box", |_lua, this, _: ()| { methods.add_method("__box", |_lua, this, _: ()| {
let b: Box<dyn Device> = Box::new(this.clone()); let b: Box<dyn Device> = Box::new(this.clone());
Ok(b) Ok(b)
}); });
methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) }); methods.add_async_method("get_id", |_lua, this, _: ()| async move { Ok(this.get_id()) });
#( #(
#impls #traits::add_methods(methods);
)* )*
}
} }
} }
}.into() }
}
pub fn impl_device_macro(ast: &DeriveInput) -> TokenStream {
let name = &ast.ident;
let impls: TokenStream = ast
.attrs
.iter()
.filter(|attr| attr.path().is_ident("traits"))
.flat_map(Attribute::parse_args::<Impl>)
.map(|im| im.generate(name))
.collect();
if impls.is_empty() {
Impl::default().generate(name)
} else {
impls
}
} }

View File

@@ -14,7 +14,9 @@ pub fn lua_device_config_derive(input: proc_macro::TokenStream) -> proc_macro::T
impl_lua_device_config_macro(&ast).into() impl_lua_device_config_macro(&ast).into()
} }
#[proc_macro] #[proc_macro_derive(LuaDevice, attributes(traits))]
pub fn impl_device(input: proc_macro::TokenStream) -> proc_macro::TokenStream { pub fn impl_device(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
impl_device_macro(input) let ast = parse_macro_input!(input as DeriveInput);
impl_device_macro(&ast).into()
} }