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 automation_lib::config::InfoConfig;
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::errors::ErrorCode;
use google_home::traits::{
@@ -19,7 +19,8 @@ pub struct Config {
pub url: String,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct AirFilter {
config: Config,
}
@@ -62,7 +63,6 @@ impl AirFilter {
Ok(reqwest::get(url).await?.json().await?)
}
}
impl_device!(AirFilter);
#[async_trait]
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::mqtt::WrappedAsyncClient;
use automation_lib::presence::DEFAULT_PRESENCE;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device;
use google_home::errors::{DeviceError, ErrorCode};
use google_home::traits::OpenClose;
@@ -61,12 +61,12 @@ struct State {
handle: Option<JoinHandle<()>>,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
#[traits(OpenClose)]
pub struct ContactSensor {
config: Config,
state: Arc<RwLock<State>>,
}
impl_device!(ContactSensor);
impl ContactSensor {
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::messages::{DarknessMessage, PresenceMessage};
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use tracing::{trace, warn};
#[derive(Debug, LuaDeviceConfig, Clone)]
@@ -18,11 +18,10 @@ pub struct Config {
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
pub struct DebugBridge {
config: Config,
}
impl_device!(DebugBridge);
#[async_trait]
impl LuaDeviceCreate for DebugBridge {

View File

@@ -4,7 +4,7 @@ use std::net::SocketAddr;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::{OnDarkness, OnPresence};
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use serde::{Deserialize, Serialize};
use tracing::{error, trace, warn};
@@ -29,11 +29,10 @@ pub struct Config {
pub flags: FlagIDs,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
pub struct HueBridge {
config: Config,
}
impl_device!(HueBridge);
#[derive(Debug, Serialize)]
struct FlagMessage {

View File

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

View File

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

View File

@@ -5,7 +5,7 @@ use std::str::Utf8Error;
use async_trait::async_trait;
use automation_lib::device::{Device, LuaDeviceCreate};
use automation_lib::event::OnPresence;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use bytes::{Buf, BufMut};
use google_home::errors::{self, DeviceError};
use google_home::traits::OnOff;
@@ -22,11 +22,11 @@ pub struct Config {
pub addr: SocketAddr,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
#[traits(OnOff)]
pub struct KasaOutlet {
config: Config,
}
impl_device!(KasaOutlet);
#[async_trait]
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::messages::BrightnessMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
is_dark: bool,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
pub struct LightSensor {
config: Config,
state: Arc<RwLock<State>>,
}
impl_device!(LightSensor);
impl LightSensor {
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::messages::ActivateMessage;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use eui48::MacAddress;
use google_home::device;
use google_home::errors::ErrorCode;
@@ -28,11 +28,10 @@ pub struct Config {
pub client: WrappedAsyncClient,
}
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
pub struct WakeOnLAN {
config: Config,
}
impl_device!(WakeOnLAN);
#[async_trait]
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::mqtt::WrappedAsyncClient;
use automation_lib::ntfy::{Notification, Priority};
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use rumqttc::Publish;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tracing::{debug, error, trace, warn};
@@ -31,12 +31,11 @@ pub struct State {
}
// TODO: Add google home integration
#[derive(Debug, Clone)]
#[derive(Debug, Clone, LuaDevice)]
pub struct Washer {
config: Config,
state: Arc<RwLock<State>>,
}
impl_device!(Washer);
impl Washer {
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::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device;
use google_home::errors::ErrorCode;
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> {
config: Config<T>,
@@ -96,11 +99,8 @@ pub struct Light<T: LightState> {
}
pub type LightOnOff = Light<StateOnOff>;
impl_device!(LightOnOff -> OnOff);
pub type LightBrightness = Light<StateBrightness>;
impl_device!(LightBrightness -> OnOff, Brightness);
pub type LightColorTemperature = Light<StateColorTemperature>;
impl_device!(LightColorTemperature -> OnOff, Brightness, ColorSetting);
impl<T: LightState> Light<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::helpers::serialization::state_deserializer;
use automation_lib::mqtt::WrappedAsyncClient;
use automation_macro::{LuaDeviceConfig, impl_device};
use automation_macro::{LuaDevice, LuaDeviceConfig};
use google_home::device;
use google_home::errors::ErrorCode;
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> {
config: Config<T>,
@@ -92,9 +94,7 @@ pub struct Outlet<T: OutletState> {
}
pub type OutletOnOff = Outlet<StateOnOff>;
impl_device!(OutletOnOff -> OnOff);
pub type OutletPower = Outlet<StatePower>;
impl_device!(OutletPower -> OnOff);
impl<T: OutletState> Outlet<T> {
async fn state(&self) -> RwLockReadGuard<'_, T> {

View File

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

View File

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

View File

@@ -1,53 +1,52 @@
use proc_macro::TokenStream;
use quote::quote;
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::parse::Parse;
use syn::punctuated::Punctuated;
use syn::{Path, Token, parse_macro_input};
use syn::{AngleBracketedGenericArguments, Attribute, DeriveInput, Ident, Path, Token};
struct ImplDevice {
ty: Path,
impls: Option<Punctuated<Path, Token![,]>>,
#[derive(Debug, Default)]
struct Impl {
generics: Option<AngleBracketedGenericArguments>,
traits: Vec<Path>,
}
impl Parse for ImplDevice {
impl Parse for Impl {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let ty = input.parse()?;
let impls = if input.peek(Token![->]) {
input.parse::<Token![->]>()?;
Some(input.parse_terminated(Path::parse, Token![,])?)
let generics = if input.peek(Token![<]) {
let generics = input.parse()?;
input.parse::<Token![:]>()?;
Some(generics)
} else {
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 {
let ImplDevice { ty, impls } = parse_macro_input!(input as ImplDevice);
impl Impl {
fn generate(&self, name: &Ident) -> TokenStream {
let generics = &self.generics;
let impls: Vec<_> = impls
.iter()
.flatten()
.map(|i| {
let ident = i
.segments
.last()
.expect("There should be at least one segment")
.ident
.clone();
quote! {
::automation_lib::lua::traits::#ident::add_methods(methods);
// If an identifier is specified, assume it is placed in ::automation_lib::lua::traits,
// otherwise use the provided path
let traits = self.traits.iter().map(|t| {
if let Some(ident) = t.get_ident() {
quote! {::automation_lib::lua::traits::#ident }
} else {
t.to_token_stream()
}
})
.collect();
});
quote! {
impl mlua::UserData for #ty {
impl mlua::UserData for #name #generics {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_async_function("new", |_lua, config| async {
let device: #ty = LuaDeviceCreate::create(config)
let device: Self = LuaDeviceCreate::create(config)
.await
.map_err(mlua::ExternalError::into_lua_err)?;
@@ -62,9 +61,28 @@ pub fn impl_device_macro(input: proc_macro::TokenStream) -> TokenStream {
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()
}
#[proc_macro]
#[proc_macro_derive(LuaDevice, attributes(traits))]
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()
}