Compare commits

...

4 Commits

Author SHA1 Message Date
1c7aa7b764
Improved google_home tests
Some checks failed
Build and deploy / Build application (push) Successful in 3m44s
Check / Run checks (push) Successful in 3m25s
Build and deploy / Build container (push) Failing after 30s
Build and deploy / Deploy container (push) Has been skipped
2024-07-08 23:07:45 +02:00
6b2b450092
Cleanup
Some checks failed
Build and deploy / Build application (push) Successful in 4m38s
Check / Run checks (push) Successful in 3m32s
Build and deploy / Build container (push) Failing after 30s
Build and deploy / Deploy container (push) Has been skipped
2024-07-08 22:38:55 +02:00
120c1edea8
Started actually using the google home trait macro
Some checks failed
Build and deploy / Build application (push) Successful in 4m6s
Check / Run checks (push) Successful in 3m39s
Build and deploy / Build container (push) Failing after 37s
Build and deploy / Deploy container (push) Has been skipped
2024-07-06 00:34:15 +02:00
99808ee4b2
Initial google home trait macro 2024-07-04 01:39:50 +02:00
33 changed files with 1169 additions and 576 deletions

112
Cargo.lock generated
View File

@ -73,9 +73,9 @@ checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711"
[[package]]
name = "async-trait"
version = "0.1.72"
version = "0.1.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc6dde6e4ed435a4c1ee4e73592f5ba9da2151af10076cc04858746af9352d09"
checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca"
dependencies = [
"proc-macro2",
"quote",
@ -103,9 +103,9 @@ dependencies = [
"enum_dispatch",
"eui48",
"futures",
"google-home",
"google_home",
"hostname",
"indexmap 2.0.0",
"indexmap 2.2.6",
"mlua",
"once_cell",
"paste",
@ -136,9 +136,13 @@ version = "0.1.0"
name = "automation_macro"
version = "0.1.0"
dependencies = [
"async-trait",
"automation_cast",
"itertools 0.12.1",
"proc-macro2",
"quote",
"serde",
"serde_json",
"syn 2.0.60",
]
@ -370,12 +374,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.16"
version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
dependencies = [
"cfg-if",
]
checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
[[package]]
name = "darling"
@ -636,19 +637,30 @@ 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",
"futures",
"google_home_macro",
"json_value_merge",
"serde",
"serde_json",
"thiserror",
"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"
@ -676,9 +688,9 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.0"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
"allocator-api2",
@ -871,12 +883,12 @@ dependencies = [
[[package]]
name = "indexmap"
version = "2.0.0"
version = "2.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d"
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
dependencies = [
"equivalent",
"hashbrown 0.14.0",
"hashbrown 0.14.5",
"serde",
]
@ -919,6 +931,15 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "json_value_merge"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b0a3aadd8aaadfe2be6fd22bbdb5dbc63494ce22b7c124211f684fd757b3215"
dependencies = [
"serde_json",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
@ -1166,6 +1187,29 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"
[[package]]
name = "parking_lot"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets 0.52.5",
]
[[package]]
name = "paste"
version = "1.0.14"
@ -1332,6 +1376,15 @@ dependencies = [
"getrandom",
]
[[package]]
name = "redox_syscall"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c82cf8cff14456045f55ec4241383baeff27af886adb72ffb2162f99911de0fd"
dependencies = [
"bitflags 2.5.0",
]
[[package]]
name = "regex"
version = "1.9.3"
@ -1599,9 +1652,9 @@ dependencies = [
[[package]]
name = "serde"
version = "1.0.198"
version = "1.0.202"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc"
checksum = "226b61a0d411b2ba5ff6d7f73a476ac4f8bb900373459cd00fab8512828ba395"
dependencies = [
"serde_derive",
]
@ -1618,9 +1671,9 @@ dependencies = [
[[package]]
name = "serde_derive"
version = "1.0.198"
version = "1.0.202"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9"
checksum = "6048858004bcff69094cd972ed40a32500f153bd3be9f716b2eed2e8217c4838"
dependencies = [
"proc-macro2",
"quote",
@ -1629,9 +1682,9 @@ dependencies = [
[[package]]
name = "serde_json"
version = "1.0.104"
version = "1.0.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c"
checksum = "d947f6b3163d8857ea16c4fa0dd4840d52f3041039a85decd46867eb1abef2e4"
dependencies = [
"itoa",
"ryu",
@ -1681,7 +1734,7 @@ dependencies = [
"chrono",
"hex",
"indexmap 1.9.3",
"indexmap 2.0.0",
"indexmap 2.2.6",
"serde",
"serde_json",
"serde_with_macros",
@ -1706,7 +1759,7 @@ version = "0.9.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3cc7a1570e38322cfe4154732e5110f887ea57e22b76f4bfd32b5bdd3368666c"
dependencies = [
"indexmap 2.0.0",
"indexmap 2.2.6",
"itoa",
"ryu",
"serde",
@ -1722,6 +1775,15 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
dependencies = [
"libc",
]
[[package]]
name = "slab"
version = "0.4.8"
@ -1890,7 +1952,9 @@ dependencies = [
"libc",
"mio",
"num_cpus",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2 0.5.3",
"tokio-macros",
"tracing",
@ -1976,7 +2040,7 @@ dependencies = [
"futures-io",
"futures-sink",
"futures-util",
"hashbrown 0.14.0",
"hashbrown 0.14.5",
"pin-project-lite",
"slab",
"tokio",

View File

@ -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"] }

View File

@ -7,7 +7,14 @@ edition = "2021"
proc-macro = true
[dependencies]
automation_cast = { path = "../automation_cast" }
async-trait = "0.1.80"
itertools = "0.12.1"
proc-macro2 = "1.0.81"
quote = "1.0.36"
serde = { version = "1.0.202", features = ["derive"] }
syn = { version = "2.0.60", features = ["extra-traits", "full"] }
serde_json = "1.0.118"
[dev-dependencies]
serde = { version = "1.0.202", features = ["derive"] }

View File

@ -1,3 +1,5 @@
#![feature(let_chains)]
#![feature(iter_intersperse)]
mod lua_device;
mod lua_device_config;

View File

@ -1,22 +0,0 @@
use serde::Serialize;
use crate::traits::AvailableSpeeds;
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Attributes {
#[serde(skip_serializing_if = "Option::is_none")]
pub command_only_on_off: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub query_only_on_off: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub scene_reversible: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reversible: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command_only_fan_speed: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub available_fan_speeds: Option<AvailableSpeeds>,
#[serde(skip_serializing_if = "Option::is_none")]
pub query_only_humidity_setting: Option<bool>,
}

View File

@ -1,174 +0,0 @@
use async_trait::async_trait;
use automation_cast::Cast;
use serde::Serialize;
use crate::errors::{DeviceError, ErrorCode};
use crate::request::execute::CommandType;
use crate::response;
use crate::traits::{FanSpeed, HumiditySetting, OnOff, Scene, Trait};
use crate::types::Type;
#[async_trait]
pub trait GoogleHomeDevice:
Sync + Send + Cast<dyn OnOff> + Cast<dyn Scene> + Cast<dyn FanSpeed> + Cast<dyn HumiditySetting>
{
fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name;
fn get_id(&self) -> String;
fn is_online(&self) -> bool;
// Default values that can optionally be overridden
fn will_report_state(&self) -> bool {
false
}
fn get_room_hint(&self) -> Option<&str> {
None
}
fn get_device_info(&self) -> Option<Info> {
None
}
async fn sync(&self) -> response::sync::Device {
let name = self.get_device_name();
let mut device =
response::sync::Device::new(&self.get_id(), &name.name, self.get_device_type());
device.name = name;
device.will_report_state = self.will_report_state();
// notification_supported_by_agent
if let Some(room) = self.get_room_hint() {
device.room_hint = Some(room.into());
}
device.device_info = self.get_device_info();
let mut traits = Vec::new();
// OnOff
if let Some(on_off) = self.cast() as Option<&dyn OnOff> {
traits.push(Trait::OnOff);
device.attributes.command_only_on_off = on_off.is_command_only();
device.attributes.query_only_on_off = on_off.is_query_only();
}
// Scene
if let Some(scene) = self.cast() as Option<&dyn Scene> {
traits.push(Trait::Scene);
device.attributes.scene_reversible = scene.is_scene_reversible();
}
// FanSpeed
if let Some(fan_speed) = self.cast() as Option<&dyn FanSpeed> {
traits.push(Trait::FanSpeed);
device.attributes.command_only_fan_speed = fan_speed.command_only_fan_speed();
device.attributes.available_fan_speeds = Some(fan_speed.available_speeds());
}
if let Some(humidity_setting) = self.cast() as Option<&dyn HumiditySetting> {
traits.push(Trait::HumiditySetting);
device.attributes.query_only_humidity_setting =
humidity_setting.query_only_humidity_setting();
}
device.traits = traits;
device
}
async fn query(&self) -> response::query::Device {
let mut device = response::query::Device::new();
if !self.is_online() {
device.set_offline();
}
// OnOff
if let Some(on_off) = self.cast() as Option<&dyn OnOff> {
device.state.on = on_off
.is_on()
.await
.map_err(|err| device.set_error(err))
.ok();
}
// FanSpeed
if let Some(fan_speed) = self.cast() as Option<&dyn FanSpeed> {
device.state.current_fan_speed_setting = Some(fan_speed.current_speed().await);
}
if let Some(humidity_setting) = self.cast() as Option<&dyn HumiditySetting> {
device.state.humidity_ambient_percent =
Some(humidity_setting.humidity_ambient_percent().await);
}
device
}
async fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
match command {
CommandType::OnOff { on } => {
if let Some(t) = self.cast_mut() as Option<&mut dyn OnOff> {
t.set_on(*on).await?;
} else {
return Err(DeviceError::ActionNotAvailable.into());
}
}
CommandType::ActivateScene { deactivate } => {
if let Some(t) = self.cast_mut() as Option<&mut dyn Scene> {
t.set_active(!deactivate).await?;
} else {
return Err(DeviceError::ActionNotAvailable.into());
}
}
CommandType::SetFanSpeed { fan_speed } => {
if let Some(t) = self.cast_mut() as Option<&mut dyn FanSpeed> {
t.set_speed(fan_speed).await?;
}
}
}
Ok(())
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Name {
#[serde(skip_serializing_if = "Vec::is_empty")]
default_names: Vec<String>,
name: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
nicknames: Vec<String>,
}
impl Name {
pub fn new(name: &str) -> Self {
Self {
default_names: Vec::new(),
name: name.into(),
nicknames: Vec::new(),
}
}
pub fn add_default_name(&mut self, name: &str) {
self.default_names.push(name.into());
}
pub fn add_nickname(&mut self, name: &str) {
self.nicknames.push(name.into());
}
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
#[serde(skip_serializing_if = "Option::is_none")]
pub manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hw_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sw_version: Option<String>,
// attributes
// customData
// otherDeviceIds
}

View File

@ -1,152 +0,0 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
pub commands: Vec<Command>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Command {
pub devices: Vec<Device>,
pub execution: Vec<CommandType>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
// customData
}
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "command", content = "params")]
pub enum CommandType {
#[serde(rename = "action.devices.commands.OnOff")]
OnOff { on: bool },
#[serde(rename = "action.devices.commands.ActivateScene")]
ActivateScene { deactivate: bool },
#[serde(
rename = "action.devices.commands.SetFanSpeed",
rename_all = "camelCase"
)]
SetFanSpeed { fan_speed: String },
}
#[cfg(test)]
mod tests {
use super::*;
use crate::request::{Intent, Request};
#[test]
fn deserialize_set_fan_speed() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [],
"execution": [
{
"command": "action.devices.commands.SetFanSpeed",
"params": {
"fanSpeed": "Test"
}
}
]
}
]
}
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 0);
assert_eq!(payload.commands[0].execution.len(), 1);
match &payload.commands[0].execution[0] {
CommandType::SetFanSpeed { fan_speed } => assert_eq!(fan_speed, "Test"),
_ => panic!("Expected SetFanSpeed"),
}
}
_ => panic!("Expected Execute intent"),
};
}
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [
{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "sheepdip"
}
},
{
"id": "456",
"customData": {
"fooValue": 36,
"barValue": false,
"bazValue": "moarsheep"
}
}
],
"execution": [
{
"command": "action.devices.commands.OnOff",
"params": {
"on": true
}
}
]
}
]
}
}
]
}"#;
let req: Request = serde_json::from_str(json).unwrap();
println!("{:?}", req);
assert_eq!(
req.request_id,
"ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_string()
);
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 2);
assert_eq!(payload.commands[0].devices[0].id, "123");
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),
_ => panic!("Expected OnOff"),
}
}
_ => panic!("Expected Execute intent"),
};
}
}

View File

@ -1,83 +0,0 @@
use async_trait::async_trait;
use serde::Serialize;
use crate::errors::ErrorCode;
#[derive(Debug, Serialize)]
pub enum Trait {
#[serde(rename = "action.devices.traits.OnOff")]
OnOff,
#[serde(rename = "action.devices.traits.Scene")]
Scene,
#[serde(rename = "action.devices.traits.FanSpeed")]
FanSpeed,
#[serde(rename = "action.devices.traits.HumiditySetting")]
HumiditySetting,
}
#[async_trait]
pub trait OnOff: Sync + Send {
fn is_command_only(&self) -> Option<bool> {
None
}
fn is_query_only(&self) -> Option<bool> {
None
}
// TODO: Implement correct error so we can handle them properly
async fn is_on(&self) -> Result<bool, ErrorCode>;
async fn set_on(&mut self, on: bool) -> Result<(), ErrorCode>;
}
#[async_trait]
pub trait Scene: Sync + Send {
fn is_scene_reversible(&self) -> Option<bool> {
None
}
async fn set_active(&self, activate: bool) -> Result<(), ErrorCode>;
}
#[derive(Debug, Serialize)]
pub struct SpeedValues {
pub speed_synonym: Vec<String>,
pub lang: String,
}
#[derive(Debug, Serialize)]
pub struct Speed {
pub speed_name: String,
pub speed_values: Vec<SpeedValues>,
}
#[derive(Debug, Serialize)]
pub struct AvailableSpeeds {
pub speeds: Vec<Speed>,
pub ordered: bool,
}
#[async_trait]
pub trait FanSpeed: Sync + Send {
fn reversible(&self) -> Option<bool> {
None
}
fn command_only_fan_speed(&self) -> Option<bool> {
None
}
fn available_speeds(&self) -> AvailableSpeeds;
async fn current_speed(&self) -> String;
async fn set_speed(&self, speed: &str) -> Result<(), ErrorCode>;
}
#[async_trait]
pub trait HumiditySetting: Sync + Send {
// TODO: This implementation is not complete, I have only implemented what I need right now
fn query_only_humidity_setting(&self) -> Option<bool> {
None
}
async fn humidity_ambient_percent(&self) -> isize;
}

View File

@ -1,16 +1,18 @@
[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_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"
tokio = { version = "1", features = ["sync"] }
tokio = { version = "1", features = ["sync", "full"] }
async-trait = "0.1.61"
futures = "0.3.25"
anyhow = "1.0.75"
json_value_merge = "2.0.0"

View File

@ -0,0 +1,110 @@
use async_trait::async_trait;
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::response;
use crate::traits::{Command, DeviceFulfillment};
use crate::types::Type;
#[async_trait]
pub trait Device: DeviceFulfillment {
fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name;
fn get_id(&self) -> String;
fn is_online(&self) -> bool;
// Default values that can optionally be overridden
fn will_report_state(&self) -> bool {
false
}
fn get_room_hint(&self) -> Option<&str> {
None
}
fn get_device_info(&self) -> Option<Info> {
None
}
async fn sync(&self) -> response::sync::Device {
let name = self.get_device_name();
let mut device =
response::sync::Device::new(&self.get_id(), &name.name, self.get_device_type());
device.name = name;
device.will_report_state = self.will_report_state();
// notification_supported_by_agent
if let Some(room) = self.get_room_hint() {
device.room_hint = Some(room.into());
}
device.device_info = self.get_device_info();
let (traits, attributes) = DeviceFulfillment::sync(self).await.unwrap();
device.traits = traits;
device.attributes = attributes;
device
}
async fn query(&self) -> response::query::Device {
let mut device = response::query::Device::new();
if !self.is_online() {
device.set_offline();
}
device.state = DeviceFulfillment::query(self).await.unwrap();
device
}
async fn execute(&mut self, command: Command) -> Result<(), ErrorCode> {
DeviceFulfillment::execute(self, command.clone())
.await
.unwrap();
Ok(())
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Name {
#[serde(skip_serializing_if = "Vec::is_empty")]
default_names: Vec<String>,
name: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
nicknames: Vec<String>,
}
impl Name {
pub fn new(name: &str) -> Self {
Self {
default_names: Vec::new(),
name: name.into(),
nicknames: Vec::new(),
}
}
pub fn add_default_name(&mut self, name: &str) {
self.default_names.push(name.into());
}
pub fn add_nickname(&mut self, name: &str) {
self.nicknames.push(name.into());
}
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
#[serde(skip_serializing_if = "Option::is_none")]
pub manufacturer: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hw_version: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sw_version: Option<String>,
// attributes
// customData
// otherDeviceIds
}

View File

@ -8,8 +8,8 @@ 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, State};
use crate::GoogleHomeDevice;
use crate::response::{self, execute, query, sync, Response, ResponsePayload};
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(device.sync().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()
{
device.query().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>>>>,
@ -121,12 +121,12 @@ impl GoogleHome {
let mut success = response::execute::Command::new(execute::Status::Success);
success.states = Some(execute::States {
online: true,
state: State::default(),
state: Default::default(),
});
let mut offline = response::execute::Command::new(execute::Status::Offline);
offline.states = Some(execute::States {
online: false,
state: State::default(),
state: Default::default(),
});
let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new();
@ -147,7 +147,7 @@ impl GoogleHome {
// NOTE: We can not use .map here because async =(
let mut results = Vec::new();
for cmd in &execution {
results.push(device.execute(cmd).await);
results.push(Device::execute(device, cmd.clone()).await);
}
// Convert vec of results to a result with a vec and the first

View File

@ -7,12 +7,11 @@ mod fulfillment;
mod request;
mod response;
mod attributes;
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;

View File

@ -0,0 +1,142 @@
use serde::Deserialize;
use crate::traits;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
pub commands: Vec<Command>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Command {
pub devices: Vec<Device>,
pub execution: Vec<traits::Command>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
// customData
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::request::{Intent, Request};
#[test]
fn deserialize_set_fan_speed() {
let req = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [],
"execution": [
{
"command": "action.devices.commands.SetFanSpeed",
"params": {
"fanSpeed": "Test"
}
}
]
}
]
}
}
]
});
let req: Request = serde_json::from_value(req).unwrap();
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 0);
assert_eq!(payload.commands[0].execution.len(), 1);
match &payload.commands[0].execution[0] {
traits::Command::SetFanSpeed { fan_speed } => assert_eq!(fan_speed, "Test"),
_ => panic!("Expected SetFanSpeed"),
}
}
_ => panic!("Expected Execute intent"),
};
}
#[test]
fn deserialize() {
let req = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.EXECUTE",
"payload": {
"commands": [
{
"devices": [
{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "sheepdip"
}
},
{
"id": "456",
"customData": {
"fooValue": 36,
"barValue": false,
"bazValue": "moarsheep"
}
}
],
"execution": [
{
"command": "action.devices.commands.OnOff",
"params": {
"on": true
}
}
]
}
]
}
}
]
});
let req: Request = serde_json::from_value(req).unwrap();
println!("{:?}", req);
assert_eq!(
req.request_id,
"ff36a3cc-ec34-11e6-b1a0-64510650abcf".to_string()
);
assert_eq!(req.inputs.len(), 1);
match &req.inputs[0] {
Intent::Execute(payload) => {
assert_eq!(payload.commands.len(), 1);
assert_eq!(payload.commands[0].devices.len(), 2);
assert_eq!(payload.commands[0].devices[0].id, "123");
assert_eq!(payload.commands[0].devices[1].id, "456");
assert_eq!(payload.commands[0].execution.len(), 1);
match payload.commands[0].execution[0] {
traits::Command::OnOff { on } => assert!(on),
_ => panic!("Expected OnOff"),
}
}
_ => panic!("Expected Execute intent"),
};
}
}

View File

@ -15,11 +15,13 @@ pub struct Device {
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
let req = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
@ -46,9 +48,9 @@ mod tests {
}
}
]
}"#;
});
let req: Request = serde_json::from_str(json).unwrap();
let req: Request = serde_json::from_value(req).unwrap();
println!("{:?}", req);

View File

@ -1,19 +1,21 @@
#[cfg(test)]
mod tests {
use serde_json::json;
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
let req = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.SYNC"
}
]
}"#;
});
let req: Request = serde_json::from_str(json).unwrap();
let req: Request = serde_json::from_value(req).unwrap();
println!("{:?}", req);

View File

@ -27,16 +27,3 @@ pub enum ResponsePayload {
Query(query::Payload),
Execute(execute::Payload),
}
#[derive(Debug, Default, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct State {
#[serde(skip_serializing_if = "Option::is_none")]
pub on: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub current_fan_speed_setting: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub humidity_ambient_percent: Option<isize>,
}

View File

@ -1,7 +1,6 @@
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::response::State;
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
@ -72,7 +71,7 @@ pub struct States {
pub online: bool,
#[serde(flatten)]
pub state: State,
pub state: serde_json::Value,
}
#[derive(Debug, Serialize, Clone)]
@ -87,19 +86,19 @@ pub enum Status {
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::errors::DeviceError;
use crate::response::{Response, ResponsePayload, State};
use crate::response::{Response, ResponsePayload};
#[test]
fn serialize() {
let mut execute_resp = Payload::new();
let state = State {
on: Some(true),
current_fan_speed_setting: None,
humidity_ambient_percent: None,
};
let state = json!({
"on": true,
});
let mut command = Command::new(Status::Success);
command.states = Some(States {
online: true,
@ -118,10 +117,28 @@ mod tests {
ResponsePayload::Execute(execute_resp),
);
let json = serde_json::to_string(&resp).unwrap();
let resp = serde_json::to_value(resp).unwrap();
println!("{}", json);
let resp_expected = json!({
"payload": {
"commands": [
{
"states": {
"on": true,
"online": true
},
"ids": ["123"],
"status": "SUCCESS"
}, {
"errorCode": "deviceNotFound",
"ids": ["456"],
"status":"ERROR"
}
]
},
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf"
});
// TODO: Add a known correct output to test against
assert_eq!(resp, resp_expected);
}
}

View File

@ -3,7 +3,6 @@ use std::collections::HashMap;
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::response::State;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@ -53,7 +52,7 @@ pub struct Device {
error_code: Option<ErrorCode>,
#[serde(flatten)]
pub state: State,
pub state: serde_json::Value,
}
impl Device {
@ -62,7 +61,7 @@ impl Device {
online: true,
status: Status::Success,
error_code: None,
state: State::default(),
state: Default::default(),
}
}
@ -88,6 +87,8 @@ impl Default for Device {
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::response::{Response, ResponsePayload};
@ -96,11 +97,15 @@ mod tests {
let mut query_resp = Payload::new();
let mut device = Device::new();
device.state.on = Some(true);
device.state = json!({
"on": true,
});
query_resp.add_device("123", device);
let mut device = Device::new();
device.state.on = Some(false);
device.state = json!({
"on": true,
});
query_resp.add_device("456", device);
let resp = Response::new(
@ -108,10 +113,26 @@ mod tests {
ResponsePayload::Query(query_resp),
);
let json = serde_json::to_string(&resp).unwrap();
let resp = serde_json::to_value(resp).unwrap();
println!("{}", json);
let resp_expected = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"payload": {
"devices": {
"123": {
"online": true,
"status": "SUCCESS",
"on": true
},
"456": {
"online": true,
"status": "SUCCESS",
"on":true
}
}
}
});
// TODO: Add a known correct output to test against
assert_eq!(resp, resp_expected);
}
}

View File

@ -1,6 +1,5 @@
use serde::Serialize;
use crate::attributes::Attributes;
use crate::device;
use crate::errors::ErrorCode;
use crate::traits::Trait;
@ -47,7 +46,8 @@ pub struct Device {
pub room_hint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_info: Option<device::Info>,
pub attributes: Attributes,
#[serde(skip_serializing_if = "serde_json::Value::is_null")]
pub attributes: serde_json::Value,
}
impl Device {
@ -61,13 +61,15 @@ impl Device {
notification_supported_by_agent: None,
room_hint: None,
device_info: None,
attributes: Attributes::default(),
attributes: Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::response::{Response, ResponsePayload};
use crate::traits::Trait;
@ -97,10 +99,35 @@ mod tests {
ResponsePayload::Sync(sync_resp),
);
let json = serde_json::to_string(&resp).unwrap();
let resp = serde_json::to_value(resp).unwrap();
println!("{}", json);
let resp_expected = json!({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"payload": {
"agentUserId": "1836.15267389",
"devices": [
{
"id": "123",
"type": "action.devices.types.KETTLE",
"traits": ["action.devices.traits.OnOff"],
"name": {
"defaultNames": ["My Outlet 1234"],
"name": "Night light",
"nicknames": ["wall plug"]
},
"willReportState": false,
"roomHint": "kitchen",
"deviceInfo": {
"manufacturer": "lights-out-inc",
"model": "hs1234",
"hwVersion": "3.2",
"swVersion": "11.4"
}
}
]
}
});
// assert_eq!(json, r#"{"requestId":"ff36a3cc-ec34-11e6-b1a0-64510650abcf","payload":{"agentUserId":"1836.15267389","devices":[{"id":"123","type":"action.devices.types.KETTLE","traits":["action.devices.traits.OnOff"],"name":{"defaultNames":["My Outlet 1234"],"name":"Night light","nicknames":["wall plug"]},"willReportState":false,"roomHint":"kitchen","deviceInfo":{"manufacturer":"lights-out-inc","model":"hs1234","hwVersion":"3.2","swVersion":"11.4"}}]}}"#)
assert_eq!(resp, resp_expected);
}
}

View File

@ -0,0 +1,55 @@
use automation_cast::Cast;
use google_home_macro::traits;
use serde::Serialize;
use crate::errors::ErrorCode;
use crate::Device;
traits! {
Device,
"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(&mut self, on: bool) -> Result<(), ErrorCode>,
},
"action.devices.traits.Scene" => trait Scene {
scene_reversible: Option<bool>,
"action.devices.commands.ActivateScene" => async fn set_active(&mut 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>,
// TODO: Figure out some syntax for optional command?
// Probably better to just force the user to always implement commands?
"action.devices.commands.SetFanSpeed" => async fn set_fan_speed(&mut self, fan_speed: String) -> Result<(), ErrorCode>,
},
"action.devices.traits.HumiditySetting" => trait HumiditySetting {
query_only_humidity_setting: Option<bool>,
fn humidity_ambient_percent(&self) -> Result<isize, ErrorCode>,
}
}
#[derive(Debug, Serialize)]
pub struct SpeedValues {
pub speed_synonym: Vec<String>,
pub lang: String,
}
#[derive(Debug, Serialize)]
pub struct Speed {
pub speed_name: String,
pub speed_values: Vec<SpeedValues>,
}
#[derive(Debug, Serialize)]
pub struct AvailableSpeeds {
pub speeds: Vec<Speed>,
pub ordered: bool,
}

View 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"] }

View 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()
}

View File

@ -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
}
@ -134,7 +133,7 @@ impl GoogleHomeDevice for AirFilter {
#[async_trait]
impl OnOff for AirFilter {
async fn is_on(&self) -> Result<bool, ErrorCode> {
async fn on(&self) -> Result<bool, ErrorCode> {
Ok(self.last_known_state.state != AirFilterFanState::Off)
}
@ -153,7 +152,7 @@ impl OnOff for AirFilter {
#[async_trait]
impl FanSpeed for AirFilter {
fn available_speeds(&self) -> AvailableSpeeds {
fn available_fan_speeds(&self) -> AvailableSpeeds {
AvailableSpeeds {
speeds: vec![
Speed {
@ -189,7 +188,7 @@ impl FanSpeed for AirFilter {
}
}
async fn current_speed(&self) -> String {
fn current_fan_speed_setting(&self) -> Result<String, ErrorCode> {
let speed = match self.last_known_state.state {
AirFilterFanState::Off => "off",
AirFilterFanState::Low => "low",
@ -197,17 +196,18 @@ impl FanSpeed for AirFilter {
AirFilterFanState::High => "high",
};
speed.into()
Ok(speed.into())
}
async fn set_speed(&self, speed: &str) -> Result<(), ErrorCode> {
let state = if speed == "off" {
async fn set_fan_speed(&mut self, fan_speed: String) -> Result<(), ErrorCode> {
let fan_speed = fan_speed.as_str();
let state = if fan_speed == "off" {
AirFilterFanState::Off
} else if speed == "low" {
} else if fan_speed == "low" {
AirFilterFanState::Low
} else if speed == "medium" {
} else if fan_speed == "medium" {
AirFilterFanState::Medium
} else if speed == "high" {
} else if fan_speed == "high" {
AirFilterFanState::High
} else {
return Err(google_home::errors::DeviceError::TransientError.into());
@ -225,7 +225,7 @@ impl HumiditySetting for AirFilter {
Some(true)
}
async fn humidity_ambient_percent(&self) -> isize {
self.last_known_state.humidity.round() as isize
fn humidity_ambient_percent(&self) -> Result<isize, ErrorCode> {
Ok(self.last_known_state.humidity.round() as isize)
}
}

View File

@ -92,7 +92,7 @@ impl OnMqtt for AudioSetup {
) {
match action {
RemoteAction::On => {
if mixer.is_on().await.unwrap() {
if mixer.on().await.unwrap() {
speakers.set_on(false).await.unwrap();
mixer.set_on(false).await.unwrap();
} else {
@ -101,9 +101,9 @@ impl OnMqtt for AudioSetup {
}
},
RemoteAction::BrightnessMoveUp => {
if !mixer.is_on().await.unwrap() {
if !mixer.on().await.unwrap() {
mixer.set_on(true).await.unwrap();
} else if speakers.is_on().await.unwrap() {
} else if speakers.on().await.unwrap() {
speakers.set_on(false).await.unwrap();
} else {
speakers.set_on(true).await.unwrap();

View File

@ -155,7 +155,7 @@ impl OnMqtt for ContactSensor {
for (light, previous) in &mut trigger.devices {
let mut light = light.write().await;
if let Some(light) = light.as_mut().cast_mut() as Option<&mut dyn OnOff> {
*previous = light.is_on().await.unwrap();
*previous = light.on().await.unwrap();
light.set_on(true).await.ok();
}
}

View File

@ -152,7 +152,7 @@ impl OnOff for HueGroup {
Ok(())
}
async fn is_on(&self) -> Result<bool, ErrorCode> {
async fn on(&self) -> Result<bool, ErrorCode> {
let res = reqwest::Client::new()
.get(self.url_get_state())
.send()

View File

@ -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,
@ -205,7 +205,7 @@ impl GoogleHomeDevice for IkeaOutlet {
#[async_trait]
impl traits::OnOff for IkeaOutlet {
async fn is_on(&self) -> Result<bool, ErrorCode> {
async fn on(&self) -> Result<bool, ErrorCode> {
Ok(self.last_known_state)
}

View File

@ -207,7 +207,7 @@ impl Response {
#[async_trait]
impl traits::OnOff for KasaOutlet {
async fn is_on(&self) -> Result<bool, errors::ErrorCode> {
async fn on(&self) -> Result<bool, errors::ErrorCode> {
let mut stream = TcpStream::connect(self.config.addr)
.await
.or::<DeviceError>(Err(DeviceError::DeviceOffline))?;

View File

@ -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>

View File

@ -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
}
@ -103,7 +103,7 @@ impl GoogleHomeDevice for WakeOnLAN {
#[async_trait]
impl traits::Scene for WakeOnLAN {
async fn set_active(&self, activate: bool) -> Result<(), ErrorCode> {
async fn set_active(&mut self, activate: bool) -> Result<(), ErrorCode> {
if activate {
debug!(
id = Device::get_id(self),