Store devices wrapped in Arc RwLock

This commit is contained in:
Dreaded_X 2023-08-11 02:24:58 +02:00
parent 7733e8cc8f
commit 330523166f
Signed by: Dreaded_X
GPG Key ID: FA5F485356B0D2D4
13 changed files with 538 additions and 457 deletions

13
Cargo.lock generated
View File

@ -75,6 +75,7 @@ dependencies = [
"reqwest", "reqwest",
"rumqttc", "rumqttc",
"serde", "serde",
"serde-tuple-vec-map",
"serde_json", "serde_json",
"serde_repr", "serde_repr",
"thiserror", "thiserror",
@ -461,10 +462,13 @@ checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e"
name = "google-home" name = "google-home"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait",
"futures",
"impl_cast", "impl_cast",
"serde", "serde",
"serde_json", "serde_json",
"thiserror", "thiserror",
"tokio",
] ]
[[package]] [[package]]
@ -1212,6 +1216,15 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "serde-tuple-vec-map"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a04d0ebe0de77d7d445bb729a895dcb0a288854b267ca85f030ce51cdc578c82"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.183" version = "1.0.183"

View File

@ -37,6 +37,7 @@ anyhow = "1.0.68"
wakey = "0.3.0" wakey = "0.3.0"
console-subscriber = "0.1.8" console-subscriber = "0.1.8"
tracing-subscriber = "0.3.16" tracing-subscriber = "0.3.16"
serde-tuple-vec-map = "1.0.1"
[profile.release] [profile.release]
lto = true lto = true

View File

@ -10,3 +10,6 @@ impl_cast = { path = "../impl_cast" }
serde = { version = "1.0.149", features = ["derive"] } serde = { version = "1.0.149", features = ["derive"] }
serde_json = "1.0.89" serde_json = "1.0.89"
thiserror = "1.0.37" thiserror = "1.0.37"
tokio = "1"
async-trait = "0.1.61"
futures = "0.3.25"

View File

@ -1,3 +1,4 @@
use async_trait::async_trait;
use serde::Serialize; use serde::Serialize;
use crate::{ use crate::{
@ -8,8 +9,43 @@ use crate::{
types::Type, types::Type,
}; };
// TODO: Find a more elegant way to do this
pub trait AsGoogleHomeDevice {
fn cast(&self) -> Option<&dyn GoogleHomeDevice>;
fn cast_mut(&mut self) -> Option<&mut dyn GoogleHomeDevice>;
}
// Default impl
impl<T> AsGoogleHomeDevice for T
where
T: 'static,
{
default fn cast(&self) -> Option<&(dyn GoogleHomeDevice + 'static)> {
None
}
default fn cast_mut(&mut self) -> Option<&mut (dyn GoogleHomeDevice + 'static)> {
None
}
}
// Specialization
impl<T> AsGoogleHomeDevice for T
where
T: GoogleHomeDevice + 'static,
{
fn cast(&self) -> Option<&(dyn GoogleHomeDevice + 'static)> {
Some(self)
}
fn cast_mut(&mut self) -> Option<&mut (dyn GoogleHomeDevice + 'static)> {
Some(self)
}
}
#[async_trait]
#[impl_cast::device(As: OnOff + Scene)] #[impl_cast::device(As: OnOff + Scene)]
pub trait GoogleHomeDevice: Sync + Send + 'static { pub trait GoogleHomeDevice: AsGoogleHomeDevice + Sync + Send + 'static {
fn get_device_type(&self) -> Type; fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name; fn get_device_name(&self) -> Name;
fn get_id(&self) -> &str; fn get_id(&self) -> &str;
@ -26,7 +62,7 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
None None
} }
fn sync(&self) -> response::sync::Device { async fn sync(&self) -> response::sync::Device {
let name = self.get_device_name(); let name = self.get_device_name();
let mut device = let mut device =
response::sync::Device::new(self.get_id(), &name.name, self.get_device_type()); response::sync::Device::new(self.get_id(), &name.name, self.get_device_type());
@ -40,9 +76,11 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
device.device_info = self.get_device_info(); device.device_info = self.get_device_info();
let mut traits = Vec::new(); let mut traits = Vec::new();
// OnOff // OnOff
if let Some(on_off) = As::<dyn OnOff>::cast(self) { if let Some(on_off) = As::<dyn OnOff>::cast(self) {
traits.push(Trait::OnOff); traits.push(Trait::OnOff);
let on_off = on_off;
device.attributes.command_only_on_off = on_off.is_command_only(); device.attributes.command_only_on_off = on_off.is_command_only();
device.attributes.query_only_on_off = on_off.is_query_only(); device.attributes.query_only_on_off = on_off.is_query_only();
} }
@ -58,7 +96,7 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
device device
} }
fn query(&self) -> response::query::Device { async fn query(&self) -> response::query::Device {
let mut device = response::query::Device::new(); let mut device = response::query::Device::new();
if !self.is_online() { if !self.is_online() {
device.set_offline(); device.set_offline();
@ -72,19 +110,21 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
device device
} }
fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> { async fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
match command { match command {
CommandType::OnOff { on } => { CommandType::OnOff { on } => {
let on_off = As::<dyn OnOff>::cast_mut(self) if let Some(on_off) = As::<dyn OnOff>::cast_mut(self) {
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
on_off.set_on(*on)?; on_off.set_on(*on)?;
} else {
return Err(DeviceError::ActionNotAvailable.into());
}
} }
CommandType::ActivateScene { deactivate } => { CommandType::ActivateScene { deactivate } => {
let scene = As::<dyn Scene>::cast_mut(self) if let Some(scene) = As::<dyn Scene>::cast(self) {
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
scene.set_active(!deactivate)?; scene.set_active(!deactivate)?;
} else {
return Err(DeviceError::ActionNotAvailable.into());
}
} }
} }

View File

@ -1,9 +1,11 @@
use std::collections::HashMap; use std::{collections::HashMap, sync::Arc};
use futures::future::{join_all, OptionFuture};
use thiserror::Error; use thiserror::Error;
use tokio::sync::{Mutex, RwLock};
use crate::{ use crate::{
device::GoogleHomeDevice, device::AsGoogleHomeDevice,
errors::{DeviceError, ErrorCode}, errors::{DeviceError, ErrorCode},
request::{self, Intent, Request}, request::{self, Intent, Request},
response::{self, execute, query, sync, Response, ResponsePayload, State}, response::{self, execute, query, sync, Response, ResponsePayload, State},
@ -28,77 +30,92 @@ impl GoogleHome {
} }
} }
pub fn handle_request( pub async fn handle_request<T: AsGoogleHomeDevice + ?Sized + 'static>(
&self, &self,
request: Request, request: Request,
devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>, devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> Result<Response, FullfillmentError> { ) -> Result<Response, FullfillmentError> {
// TODO: What do we do if we actually get more then one thing in the input array, right now // TODO: What do we do if we actually get more then one thing in the input array, right now
// we only respond to the first thing // we only respond to the first thing
let payload = request let intent = request.inputs.into_iter().next();
.inputs
.into_iter() let payload: OptionFuture<_> = intent
.map(|input| match input { .map(|intent| async move {
Intent::Sync => ResponsePayload::Sync(self.sync(devices)), match intent {
Intent::Query(payload) => ResponsePayload::Query(self.query(payload, devices)), Intent::Sync => ResponsePayload::Sync(self.sync(devices).await),
Intent::Query(payload) => {
ResponsePayload::Query(self.query(payload, devices).await)
}
Intent::Execute(payload) => { Intent::Execute(payload) => {
ResponsePayload::Execute(self.execute(payload, devices)) ResponsePayload::Execute(self.execute(payload, devices).await)
}
} }
}) })
.next(); .into();
payload payload
.await
.ok_or(FullfillmentError::ExpectedOnePayload) .ok_or(FullfillmentError::ExpectedOnePayload)
.map(|payload| Response::new(&request.request_id, payload)) .map(|payload| Response::new(&request.request_id, payload))
} }
fn sync(&self, devices: &HashMap<&str, &mut dyn GoogleHomeDevice>) -> sync::Payload { async fn sync<T: AsGoogleHomeDevice + ?Sized + 'static>(
&self,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> sync::Payload {
let mut resp_payload = sync::Payload::new(&self.user_id); let mut resp_payload = sync::Payload::new(&self.user_id);
resp_payload.devices = devices let f = devices.iter().map(|(_, device)| async move {
.iter() if let Some(device) = device.read().await.as_ref().cast() {
.map(|(_, device)| device.sync()) Some(device.sync().await)
.collect::<Vec<_>>(); } else {
None
}
});
resp_payload.devices = join_all(f).await.into_iter().flatten().collect();
resp_payload resp_payload
} }
fn query( async fn query<T: AsGoogleHomeDevice + ?Sized + 'static>(
&self, &self,
payload: request::query::Payload, payload: request::query::Payload,
devices: &HashMap<&str, &mut dyn GoogleHomeDevice>, devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> query::Payload { ) -> query::Payload {
let mut resp_payload = query::Payload::new(); let mut resp_payload = query::Payload::new();
resp_payload.devices = payload let f = payload
.devices .devices
.into_iter() .into_iter()
.map(|device| device.id) .map(|device| device.id)
.map(|id| { .map(|id| async move {
let device = devices.get(id.as_str()).map_or_else( // NOTE: Requires let_chains feature
|| { let device = if let Some(device) = devices.get(id.as_str()) && let Some(device) = device.read().await.as_ref().cast() {
device.query().await
} else {
let mut device = query::Device::new(); let mut device = query::Device::new();
device.set_offline(); device.set_offline();
device.set_error(DeviceError::DeviceNotFound.into()); device.set_error(DeviceError::DeviceNotFound.into());
device device
}, };
|device| device.query(),
);
(id, device) (id, device)
}) });
.collect();
// Await all the futures and then convert the resulting vector into a hashmap
resp_payload.devices = join_all(f).await.into_iter().collect();
resp_payload resp_payload
} }
fn execute( async fn execute<T: AsGoogleHomeDevice + ?Sized + 'static>(
&self, &self,
payload: request::execute::Payload, payload: request::execute::Payload,
devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>, devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> execute::Payload { ) -> execute::Payload {
let mut resp_payload = response::execute::Payload::new(); let resp_payload = Arc::new(Mutex::new(response::execute::Payload::new()));
payload.commands.into_iter().for_each(|command| { let f = payload.commands.into_iter().map(|command| {
let resp_payload = resp_payload.clone();
async move {
let mut success = response::execute::Command::new(execute::Status::Success); let mut success = response::execute::Command::new(execute::Status::Success);
success.states = Some(execute::States { success.states = Some(execute::States {
online: true, online: true,
@ -111,26 +128,28 @@ impl GoogleHome {
}); });
let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new(); let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new();
command let f = command
.devices .devices
.into_iter() .into_iter()
.map(|device| device.id) .map(|device| device.id)
.map(|id| { .map(|id| {
devices.get_mut(id.as_str()).map_or( let execution = command.execution.clone();
(id.clone(), Err(DeviceError::DeviceNotFound.into())), async move {
|device| { if let Some(device) = devices.get(id.as_str()) && let Some(device) = device.write().await.as_mut().cast_mut() {
if !device.is_online() { if !device.is_online() {
return (id, Ok(false)); return (id, Ok(false));
} }
let results = command // NOTE: We can not use .map here because async =(
.execution let mut results = Vec::new();
.iter() for cmd in &execution {
.map(|cmd| { results.push(device.execute(cmd).await);
// TODO: We should also return the state after update in the state }
// struct, however that will make things WAY more complicated
device.execute(cmd) // Convert vec of results to a result with a vec and the first
}) // encountered error
let results = results
.into_iter()
.collect::<Result<Vec<_>, ErrorCode>>(); .collect::<Result<Vec<_>, ErrorCode>>();
// TODO: We only get one error not all errors // TODO: We only get one error not all errors
@ -139,10 +158,14 @@ impl GoogleHome {
} else { } else {
(id, Ok(true)) (id, Ok(true))
} }
}, } else {
) (id.clone(), Err(DeviceError::DeviceNotFound.into()))
}) }
.for_each(|(id, state)| { }
});
let a = join_all(f).await;
a.into_iter().for_each(|(id, state)| {
match state { match state {
Ok(true) => success.add_id(&id), Ok(true) => success.add_id(&id),
Ok(false) => offline.add_id(&id), Ok(false) => offline.add_id(&id),
@ -160,255 +183,262 @@ impl GoogleHome {
}; };
}); });
let mut resp_payload = resp_payload.lock().await;
resp_payload.add_command(success); resp_payload.add_command(success);
resp_payload.add_command(offline); resp_payload.add_command(offline);
for (error, mut cmd) in errors { for (error, mut cmd) in errors {
cmd.error_code = Some(error); cmd.error_code = Some(error);
resp_payload.add_command(cmd); resp_payload.add_command(cmd);
} }
}
}); });
resp_payload join_all(f).await;
// We await all the futures that use resp_payload so try_unwrap should never fail
std::sync::Arc::<tokio::sync::Mutex<response::execute::Payload>>::try_unwrap(resp_payload)
.unwrap()
.into_inner()
} }
} }
#[cfg(test)] // #[cfg(test)]
mod tests { // mod tests {
use super::*; // use super::*;
use crate::{ // use crate::{
device::{self, GoogleHomeDevice}, // device::{self, GoogleHomeDevice},
errors::ErrorCode, // errors::ErrorCode,
request::Request, // request::Request,
traits, types, // traits, types,
}; // };
//
#[derive(Debug)] // #[derive(Debug)]
struct TestOutlet { // struct TestOutlet {
name: String, // name: String,
on: bool, // on: bool,
} // }
//
impl TestOutlet { // impl TestOutlet {
fn new(name: &str) -> Self { // fn new(name: &str) -> Self {
Self { // Self {
name: name.into(), // name: name.into(),
on: false, // on: false,
} // }
} // }
} // }
//
impl GoogleHomeDevice for TestOutlet { // impl GoogleHomeDevice for TestOutlet {
fn get_device_type(&self) -> types::Type { // fn get_device_type(&self) -> types::Type {
types::Type::Outlet // types::Type::Outlet
} // }
//
fn get_device_name(&self) -> device::Name { // fn get_device_name(&self) -> device::Name {
let mut name = device::Name::new("Nightstand"); // let mut name = device::Name::new("Nightstand");
name.add_default_name("Outlet"); // name.add_default_name("Outlet");
name.add_nickname("Nightlight"); // name.add_nickname("Nightlight");
//
name // name
} // }
//
fn get_id(&self) -> &str { // fn get_id(&self) -> &str {
&self.name // &self.name
} // }
//
fn is_online(&self) -> bool { // fn is_online(&self) -> bool {
true // true
} // }
//
fn get_room_hint(&self) -> Option<&str> { // fn get_room_hint(&self) -> Option<&str> {
Some("Bedroom") // Some("Bedroom")
} // }
//
fn get_device_info(&self) -> Option<device::Info> { // fn get_device_info(&self) -> Option<device::Info> {
Some(device::Info { // Some(device::Info {
manufacturer: Some("Company".into()), // manufacturer: Some("Company".into()),
model: Some("Outlet II".into()), // model: Some("Outlet II".into()),
hw_version: None, // hw_version: None,
sw_version: None, // sw_version: None,
}) // })
} // }
} // }
//
impl traits::OnOff for TestOutlet { // impl traits::OnOff for TestOutlet {
fn is_on(&self) -> Result<bool, ErrorCode> { // fn is_on(&self) -> Result<bool, ErrorCode> {
Ok(self.on) // Ok(self.on)
} // }
//
fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> { // fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> {
self.on = on; // self.on = on;
Ok(()) // Ok(())
} // }
} // }
//
#[derive(Debug)] // #[derive(Debug)]
struct TestScene; // struct TestScene;
//
impl TestScene { // impl TestScene {
fn new() -> Self { // fn new() -> Self {
Self {} // Self {}
} // }
} // }
//
impl GoogleHomeDevice for TestScene { // impl GoogleHomeDevice for TestScene {
fn get_device_type(&self) -> types::Type { // fn get_device_type(&self) -> types::Type {
types::Type::Scene // types::Type::Scene
} // }
//
fn get_device_name(&self) -> device::Name { // fn get_device_name(&self) -> device::Name {
device::Name::new("Party") // device::Name::new("Party")
} // }
//
fn get_id(&self) -> &str { // fn get_id(&self) -> &str {
"living/party_mode" // "living/party_mode"
} // }
//
fn is_online(&self) -> bool { // fn is_online(&self) -> bool {
true // true
} // }
//
fn get_room_hint(&self) -> Option<&str> { // fn get_room_hint(&self) -> Option<&str> {
Some("Living room") // Some("Living room")
} // }
} // }
//
impl traits::Scene for TestScene { // impl traits::Scene for TestScene {
fn set_active(&self, _activate: bool) -> Result<(), ErrorCode> { // fn set_active(&self, _activate: bool) -> Result<(), ErrorCode> {
println!("Activating the party scene"); // println!("Activating the party scene");
Ok(()) // Ok(())
} // }
} // }
//
#[test] // #[test]
fn handle_sync() { // fn handle_sync() {
let json = r#"{ // let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", // "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [ // "inputs": [
{ // {
"intent": "action.devices.SYNC" // "intent": "action.devices.SYNC"
} // }
] // ]
}"#; // }"#;
let req: Request = serde_json::from_str(json).unwrap(); // let req: Request = serde_json::from_str(json).unwrap();
//
let gh = GoogleHome { // let gh = GoogleHome {
user_id: "Dreaded_X".into(), // user_id: "Dreaded_X".into(),
}; // };
//
let mut nightstand = TestOutlet::new("bedroom/nightstand"); // let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); // let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); // let mut scene = TestScene::new();
let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new(); // let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
let id = nightstand.get_id().to_owned(); // let id = nightstand.get_id().to_owned();
devices.insert(&id, &mut nightstand); // devices.insert(&id, &mut nightstand);
let id = lamp.get_id().to_owned(); // let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp); // devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned(); // let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene); // devices.insert(&id, &mut scene);
//
let resp = gh.handle_request(req, &mut devices).unwrap(); // let resp = gh.handle_request(req, &mut devices).unwrap();
//
let json = serde_json::to_string(&resp).unwrap(); // let json = serde_json::to_string(&resp).unwrap();
println!("{}", json) // println!("{}", json)
} // }
//
#[test] // #[test]
fn handle_query() { // fn handle_query() {
let json = r#"{ // let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", // "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [ // "inputs": [
{ // {
"intent": "action.devices.QUERY", // "intent": "action.devices.QUERY",
"payload": { // "payload": {
"devices": [ // "devices": [
{ // {
"id": "bedroom/nightstand" // "id": "bedroom/nightstand"
}, // },
{ // {
"id": "living/party_mode" // "id": "living/party_mode"
} // }
] // ]
} // }
} // }
] // ]
}"#; // }"#;
let req: Request = serde_json::from_str(json).unwrap(); // let req: Request = serde_json::from_str(json).unwrap();
//
let gh = GoogleHome { // let gh = GoogleHome {
user_id: "Dreaded_X".into(), // user_id: "Dreaded_X".into(),
}; // };
//
let mut nightstand = TestOutlet::new("bedroom/nightstand"); // let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); // let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); // let mut scene = TestScene::new();
let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new(); // let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
let id = nightstand.get_id().to_owned(); // let id = nightstand.get_id().to_owned();
devices.insert(&id, &mut nightstand); // devices.insert(&id, &mut nightstand);
let id = lamp.get_id().to_owned(); // let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp); // devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned(); // let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene); // devices.insert(&id, &mut scene);
//
let resp = gh.handle_request(req, &mut devices).unwrap(); // let resp = gh.handle_request(req, &mut devices).unwrap();
//
let json = serde_json::to_string(&resp).unwrap(); // let json = serde_json::to_string(&resp).unwrap();
println!("{}", json) // println!("{}", json)
} // }
//
#[test] // #[test]
fn handle_execute() { // fn handle_execute() {
let json = r#"{ // let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf", // "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [ // "inputs": [
{ // {
"intent": "action.devices.EXECUTE", // "intent": "action.devices.EXECUTE",
"payload": { // "payload": {
"commands": [ // "commands": [
{ // {
"devices": [ // "devices": [
{ // {
"id": "bedroom/nightstand" // "id": "bedroom/nightstand"
}, // },
{ // {
"id": "living/lamp" // "id": "living/lamp"
} // }
], // ],
"execution": [ // "execution": [
{ // {
"command": "action.devices.commands.OnOff", // "command": "action.devices.commands.OnOff",
"params": { // "params": {
"on": true // "on": true
} // }
} // }
] // ]
} // }
] // ]
} // }
} // }
] // ]
}"#; // }"#;
let req: Request = serde_json::from_str(json).unwrap(); // let req: Request = serde_json::from_str(json).unwrap();
//
let gh = GoogleHome { // let gh = GoogleHome {
user_id: "Dreaded_X".into(), // user_id: "Dreaded_X".into(),
}; // };
//
let mut nightstand = TestOutlet::new("bedroom/nightstand"); // let mut nightstand = TestOutlet::new("bedroom/nightstand");
let mut lamp = TestOutlet::new("living/lamp"); // let mut lamp = TestOutlet::new("living/lamp");
let mut scene = TestScene::new(); // let mut scene = TestScene::new();
let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new(); // let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
let id = nightstand.get_id().to_owned(); // let id = nightstand.get_id().to_owned();
devices.insert(&id, &mut nightstand); // devices.insert(&id, &mut nightstand);
let id = lamp.get_id().to_owned(); // let id = lamp.get_id().to_owned();
devices.insert(&id, &mut lamp); // devices.insert(&id, &mut lamp);
let id = scene.get_id().to_owned(); // let id = scene.get_id().to_owned();
devices.insert(&id, &mut scene); // devices.insert(&id, &mut scene);
//
let resp = gh.handle_request(req, &mut devices).unwrap(); // let resp = gh.handle_request(req, &mut devices).unwrap();
//
let json = serde_json::to_string(&resp).unwrap(); // let json = serde_json::to_string(&resp).unwrap();
println!("{}", json) // println!("{}", json)
} // }
} // }

View File

@ -1,5 +1,6 @@
#![allow(incomplete_features)] #![allow(incomplete_features)]
#![feature(specialization)] #![feature(specialization)]
#![feature(let_chains)]
pub mod device; pub mod device;
mod fullfillment; mod fullfillment;

View File

@ -20,7 +20,7 @@ pub struct Device {
// customData // customData
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize, Clone, Copy)]
#[serde(tag = "command", content = "params")] #[serde(tag = "command", content = "params")]
pub enum CommandType { pub enum CommandType {
#[serde(rename = "action.devices.commands.OnOff")] #[serde(rename = "action.devices.commands.OnOff")]

View File

@ -28,7 +28,7 @@ pub enum ResponsePayload {
Execute(execute::Payload), Execute(execute::Payload),
} }
#[derive(Debug, Default, Serialize)] #[derive(Debug, Default, Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct State { pub struct State {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]

View File

@ -2,7 +2,7 @@ use serde::Serialize;
use crate::{errors::ErrorCode, response::State}; use crate::{errors::ErrorCode, response::State};
#[derive(Debug, Serialize)] #[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Payload { pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -34,7 +34,7 @@ impl Default for Payload {
} }
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Command { pub struct Command {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
@ -65,7 +65,7 @@ impl Command {
} }
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct States { pub struct States {
pub online: bool, pub online: bool,
@ -74,7 +74,7 @@ pub struct States {
pub state: State, pub state: State,
} }
#[derive(Debug, Serialize)] #[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Status { pub enum Status {
Success, Success,

View File

@ -1,5 +1,4 @@
use std::{ use std::{
collections::HashMap,
fs, fs,
net::{Ipv4Addr, SocketAddr}, net::{Ipv4Addr, SocketAddr},
time::Duration, time::Duration,
@ -32,8 +31,8 @@ pub struct Config {
pub light_sensor: LightSensorConfig, pub light_sensor: LightSensorConfig,
pub hue_bridge: Option<HueBridgeConfig>, pub hue_bridge: Option<HueBridgeConfig>,
pub debug_bridge: Option<DebugBridgeConfig>, pub debug_bridge: Option<DebugBridgeConfig>,
#[serde(default)] #[serde(default, with = "tuple_vec_map")]
pub devices: HashMap<String, DeviceConfig>, pub devices: Vec<(String, DeviceConfig)>,
} }
#[derive(Debug, Clone, Deserialize)] #[derive(Debug, Clone, Deserialize)]

View File

@ -21,12 +21,14 @@ pub use self::presence::{Presence, PresenceConfig, DEFAULT_PRESENCE};
pub use self::wake_on_lan::WakeOnLAN; pub use self::wake_on_lan::WakeOnLAN;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::Arc;
use futures::future::join_all; use futures::future::join_all;
use google_home::{traits::OnOff, FullfillmentError, GoogleHome, GoogleHomeDevice}; use google_home::device::AsGoogleHomeDevice;
use google_home::{traits::OnOff, FullfillmentError};
use rumqttc::{matches, AsyncClient, QoS}; use rumqttc::{matches, AsyncClient, QoS};
use thiserror::Error; use thiserror::Error;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot, RwLock};
use tracing::{debug, error, instrument, trace}; use tracing::{debug, error, instrument, trace};
use crate::{ use crate::{
@ -37,25 +39,25 @@ use crate::{
event::{Event, EventChannel}, event::{Event, EventChannel},
}; };
#[impl_cast::device(As: OnMqtt + OnPresence + OnDarkness + OnNotification + GoogleHomeDevice + OnOff)] #[impl_cast::device(As: OnMqtt + OnPresence + OnDarkness + OnNotification + OnOff)]
pub trait Device: std::fmt::Debug + Sync + Send { pub trait Device: AsGoogleHomeDevice + std::fmt::Debug + Sync + Send {
fn get_id(&self) -> &str; fn get_id(&self) -> &str;
} }
pub type DeviceMap = HashMap<String, Arc<RwLock<Box<dyn Device>>>>;
// TODO: Add an inner type that we can wrap with Arc<RwLock<>> to make this type a little bit nicer // TODO: Add an inner type that we can wrap with Arc<RwLock<>> to make this type a little bit nicer
// to work with // to work with
#[derive(Debug)] #[derive(Debug)]
struct Devices { struct Devices {
devices: HashMap<String, Box<dyn Device>>, devices: DeviceMap,
client: AsyncClient, client: AsyncClient,
} }
#[derive(Debug)] #[derive(Debug)]
pub enum Command { pub enum Command {
Fullfillment { Fullfillment {
google_home: GoogleHome, tx: oneshot::Sender<DeviceMap>,
payload: google_home::Request,
tx: oneshot::Sender<Result<google_home::Response, FullfillmentError>>,
}, },
AddDevice { AddDevice {
device: Box<dyn Device>, device: Box<dyn Device>,
@ -80,20 +82,10 @@ pub enum DevicesError {
impl DevicesHandle { impl DevicesHandle {
// TODO: Improve error type // TODO: Improve error type
pub async fn fullfillment( pub async fn fullfillment(&self) -> Result<DeviceMap, DevicesError> {
&self,
google_home: GoogleHome,
payload: google_home::Request,
) -> Result<google_home::Response, DevicesError> {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
self.tx self.tx.send(Command::Fullfillment { tx }).await?;
.send(Command::Fullfillment { Ok(rx.await?)
google_home,
payload,
tx,
})
.await?;
Ok(rx.await??)
} }
pub async fn add_device(&self, device: Box<dyn Device>) -> Result<(), DevicesError> { pub async fn add_device(&self, device: Box<dyn Device>) -> Result<(), DevicesError> {
@ -140,14 +132,8 @@ pub fn start(client: AsyncClient) -> (DevicesHandle, EventChannel) {
impl Devices { impl Devices {
async fn handle_cmd(&mut self, cmd: Command) { async fn handle_cmd(&mut self, cmd: Command) {
match cmd { match cmd {
Command::Fullfillment { Command::Fullfillment { tx } => {
google_home, tx.send(self.devices.clone()).ok();
payload,
tx,
} => {
let result =
google_home.handle_request(payload, &mut self.get::<dyn GoogleHomeDevice>());
tx.send(result).ok();
} }
Command::AddDevice { device, tx } => { Command::AddDevice { device, tx } => {
self.add_device(device).await; self.add_device(device).await;
@ -158,7 +144,12 @@ impl Devices {
} }
async fn add_device(&mut self, device: Box<dyn Device>) { async fn add_device(&mut self, device: Box<dyn Device>) {
let id = device.get_id(); let id = device.get_id().to_owned();
let device = Arc::new(RwLock::new(device));
{
let device = device.read().await;
debug!(id, "Adding device"); debug!(id, "Adding device");
// If the device listens to mqtt, subscribe to the topics // If the device listens to mqtt, subscribe to the topics
@ -172,25 +163,30 @@ impl Devices {
} }
} }
} }
}
self.devices.insert(device.get_id().to_owned(), device); self.devices.insert(id, device);
} }
#[instrument(skip(self))] #[instrument(skip(self))]
async fn handle_event(&mut self, event: Event) { async fn handle_event(&mut self, event: Event) {
match event { match event {
Event::MqttMessage(message) => { Event::MqttMessage(message) => {
let iter = self.get::<dyn OnMqtt>().into_iter().map(|(id, listener)| { let iter = self.devices.iter().map(|(id, device)| {
let message = message.clone(); let message = message.clone();
async move { async move {
let subscribed = listener let mut device = device.write().await;
let device = device.as_mut();
if let Some(device) = As::<dyn OnMqtt>::cast_mut(device) {
let subscribed = device
.topics() .topics()
.iter() .iter()
.any(|topic| matches(&message.topic, topic)); .any(|topic| matches(&message.topic, topic));
if subscribed { if subscribed {
trace!(id, "Handling"); trace!(id, "Handling");
listener.on_mqtt(message).await; device.on_mqtt(message).await;
}
} }
} }
}); });
@ -198,52 +194,44 @@ impl Devices {
join_all(iter).await; join_all(iter).await;
} }
Event::Darkness(dark) => { Event::Darkness(dark) => {
let iter = let iter = self.devices.iter().map(|(id, device)| async move {
self.get::<dyn OnDarkness>() let mut device = device.write().await;
.into_iter() let device = device.as_mut();
.map(|(id, device)| async move { if let Some(device) = As::<dyn OnDarkness>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_darkness(dark).await; device.on_darkness(dark).await;
}
}); });
join_all(iter).await; join_all(iter).await;
} }
Event::Presence(presence) => { Event::Presence(presence) => {
let iter = let iter = self.devices.iter().map(|(id, device)| async move {
self.get::<dyn OnPresence>() let mut device = device.write().await;
.into_iter() let device = device.as_mut();
.map(|(id, device)| async move { if let Some(device) = As::<dyn OnPresence>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_presence(presence).await; device.on_presence(presence).await;
}
}); });
join_all(iter).await; join_all(iter).await;
} }
Event::Ntfy(notification) => { Event::Ntfy(notification) => {
let iter = self let iter = self.devices.iter().map(|(id, device)| {
.get::<dyn OnNotification>()
.into_iter()
.map(|(id, device)| {
let notification = notification.clone(); let notification = notification.clone();
async move { async move {
let mut device = device.write().await;
let device = device.as_mut();
if let Some(device) = As::<dyn OnNotification>::cast_mut(device) {
trace!(id, "Handling"); trace!(id, "Handling");
device.on_notification(notification).await; device.on_notification(notification).await;
} }
}
}); });
join_all(iter).await; join_all(iter).await;
} }
} }
} }
fn get<T>(&mut self) -> HashMap<&str, &mut T>
where
T: ?Sized + 'static,
(dyn Device): As<T>,
{
self.devices
.iter_mut()
.filter_map(|(id, device)| As::<T>::cast_mut(device.as_mut()).map(|t| (id.as_str(), t)))
.collect()
}
} }

View File

@ -128,12 +128,18 @@ async fn app() -> anyhow::Result<()> {
post(async move |user: User, Json(payload): Json<Request>| { post(async move |user: User, Json(payload): Json<Request>| {
debug!(username = user.preferred_username, "{payload:#?}"); debug!(username = user.preferred_username, "{payload:#?}");
let gc = GoogleHome::new(&user.preferred_username); let gc = GoogleHome::new(&user.preferred_username);
let result = match device_handler.fullfillment(gc, payload).await { let result = match device_handler.fullfillment().await {
Ok(devices) => match gc.handle_request(payload, &devices).await {
Ok(result) => result, Ok(result) => result,
Err(err) => { Err(err) => {
return ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into()) return ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into())
.into_response() .into_response()
} }
},
Err(err) => {
return ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, err.into())
.into_response()
}
}; };
debug!(username = user.preferred_username, "{result:#?}"); debug!(username = user.preferred_username, "{result:#?}");