This commit is contained in:
2024-07-08 22:38:55 +02:00
parent 9aa16e3ef8
commit 758500a071
25 changed files with 632 additions and 690 deletions

View File

@@ -0,0 +1,18 @@
[package]
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/" }
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", "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

@@ -0,0 +1,40 @@
use serde::Serialize;
use thiserror::Error;
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Error)]
#[serde(rename_all = "camelCase")]
pub enum DeviceError {
#[error("deviceNotFound")]
DeviceNotFound,
#[error("deviceOffline")]
DeviceOffline,
#[error("actionNotAvailable")]
ActionNotAvailable,
#[error("transientError")]
TransientError,
}
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Error)]
#[serde(rename_all = "camelCase")]
pub enum DeviceException {}
#[derive(Debug, Hash, PartialEq, Eq, Clone, Copy, Serialize, Error)]
#[serde(untagged)]
pub enum ErrorCode {
#[error("{0}")]
DeviceError(DeviceError),
#[error("{0}")]
DeviceException(DeviceException),
}
impl From<DeviceError> for ErrorCode {
fn from(value: DeviceError) -> Self {
Self::DeviceError(value)
}
}
impl From<DeviceException> for ErrorCode {
fn from(value: DeviceException) -> Self {
Self::DeviceException(value)
}
}

View File

@@ -0,0 +1,446 @@
use std::collections::HashMap;
use std::sync::Arc;
use automation_cast::Cast;
use futures::future::{join_all, OptionFuture};
use thiserror::Error;
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};
use crate::Device;
#[derive(Debug)]
pub struct GoogleHome {
user_id: String,
// Add credentials so we can notify google home of actions
}
#[derive(Debug, Error)]
pub enum FulfillmentError {
#[error("Expected at least one ResponsePayload")]
ExpectedOnePayload,
}
impl GoogleHome {
pub fn new(user_id: &str) -> Self {
Self {
user_id: user_id.into(),
}
}
pub async fn handle_request<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
request: Request,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> Result<Response, FulfillmentError> {
// 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
let intent = request.inputs.into_iter().next();
let payload: OptionFuture<_> = intent
.map(|intent| async move {
match intent {
Intent::Sync => ResponsePayload::Sync(self.sync(devices).await),
Intent::Query(payload) => {
ResponsePayload::Query(self.query(payload, devices).await)
}
Intent::Execute(payload) => {
ResponsePayload::Execute(self.execute(payload, devices).await)
}
}
})
.into();
payload
.await
.ok_or(FulfillmentError::ExpectedOnePayload)
.map(|payload| Response::new(&request.request_id, payload))
}
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(device).await)
} else {
None
}
});
resp_payload.devices = join_all(f).await.into_iter().flatten().collect();
resp_payload
}
async fn query<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
payload: request::query::Payload,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> query::Payload {
let mut resp_payload = query::Payload::new();
let f = payload
.devices
.into_iter()
.map(|device| device.id)
.map(|id| async move {
// 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(device).await
} else {
let mut device = query::Device::new();
device.set_offline();
device.set_error(DeviceError::DeviceNotFound.into());
device
};
(id, device)
});
// 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
}
async fn execute<T: Cast<dyn Device> + ?Sized + 'static>(
&self,
payload: request::execute::Payload,
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
) -> execute::Payload {
let resp_payload = Arc::new(Mutex::new(response::execute::Payload::new()));
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);
success.states = Some(execute::States {
online: true,
state: Default::default(),
});
let mut offline = response::execute::Command::new(execute::Status::Offline);
offline.states = Some(execute::States {
online: false,
state: Default::default(),
});
let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new();
let f = command
.devices
.into_iter()
.map(|device| device.id)
.map(|id| {
let execution = command.execution.clone();
async move {
if let Some(device) = devices.get(id.as_str())
&& let Some(device) = device.write().await.as_mut().cast_mut()
{
if !device.is_online() {
return (id, Ok(false));
}
// NOTE: We can not use .map here because async =(
let mut results = Vec::new();
for cmd in &execution {
results.push(Device::execute(device, cmd.clone()).await);
}
// Convert vec of results to a result with a vec and the first
// encountered error
let results =
results.into_iter().collect::<Result<Vec<_>, ErrorCode>>();
// TODO: We only get one error not all errors
if let Err(err) = results {
(id, Err(err))
} else {
(id, Ok(true))
}
} else {
(id.clone(), Err(DeviceError::DeviceNotFound.into()))
}
}
});
let a = join_all(f).await;
a.into_iter().for_each(|(id, state)| {
match state {
Ok(true) => success.add_id(&id),
Ok(false) => offline.add_id(&id),
Err(err) => errors
.entry(err)
.or_insert_with(|| match &err {
ErrorCode::DeviceError(_) => {
response::execute::Command::new(execute::Status::Error)
}
ErrorCode::DeviceException(_) => {
response::execute::Command::new(execute::Status::Exceptions)
}
})
.add_id(&id),
};
});
let mut resp_payload = resp_payload.lock().await;
resp_payload.add_command(success);
resp_payload.add_command(offline);
for (error, mut cmd) in errors {
cmd.error_code = Some(error);
resp_payload.add_command(cmd);
}
}
});
join_all(f).await;
std::sync::Arc::<tokio::sync::Mutex<response::execute::Payload>>::try_unwrap(resp_payload)
.expect("All futures are done, so there should only be one strong reference")
.into_inner()
}
}
// #[cfg(test)]
// mod tests {
// use super::*;
// use crate::{
// device::{self, GoogleHomeDevice},
// errors::ErrorCode,
// request::Request,
// traits, types,
// };
//
// #[derive(Debug)]
// struct TestOutlet {
// name: String,
// on: bool,
// }
//
// impl TestOutlet {
// fn new(name: &str) -> Self {
// Self {
// name: name.into(),
// on: false,
// }
// }
// }
//
// impl GoogleHomeDevice for TestOutlet {
// fn get_device_type(&self) -> types::Type {
// types::Type::Outlet
// }
//
// fn get_device_name(&self) -> device::Name {
// let mut name = device::Name::new("Nightstand");
// name.add_default_name("Outlet");
// name.add_nickname("Nightlight");
//
// name
// }
//
// fn get_id(&self) -> &str {
// &self.name
// }
//
// fn is_online(&self) -> bool {
// true
// }
//
// fn get_room_hint(&self) -> Option<&str> {
// Some("Bedroom")
// }
//
// fn get_device_info(&self) -> Option<device::Info> {
// Some(device::Info {
// manufacturer: Some("Company".into()),
// model: Some("Outlet II".into()),
// hw_version: None,
// sw_version: None,
// })
// }
// }
//
// impl traits::OnOff for TestOutlet {
// fn is_on(&self) -> Result<bool, ErrorCode> {
// Ok(self.on)
// }
//
// fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> {
// self.on = on;
// Ok(())
// }
// }
//
// #[derive(Debug)]
// struct TestScene;
//
// impl TestScene {
// fn new() -> Self {
// Self {}
// }
// }
//
// impl GoogleHomeDevice for TestScene {
// fn get_device_type(&self) -> types::Type {
// types::Type::Scene
// }
//
// fn get_device_name(&self) -> device::Name {
// device::Name::new("Party")
// }
//
// fn get_id(&self) -> &str {
// "living/party_mode"
// }
//
// fn is_online(&self) -> bool {
// true
// }
//
// fn get_room_hint(&self) -> Option<&str> {
// Some("Living room")
// }
// }
//
// impl traits::Scene for TestScene {
// fn set_active(&self, _activate: bool) -> Result<(), ErrorCode> {
// println!("Activating the party scene");
// Ok(())
// }
// }
//
// #[test]
// fn handle_sync() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.SYNC"
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
//
// #[test]
// fn handle_query() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.QUERY",
// "payload": {
// "devices": [
// {
// "id": "bedroom/nightstand"
// },
// {
// "id": "living/party_mode"
// }
// ]
// }
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
//
// #[test]
// fn handle_execute() {
// let json = r#"{
// "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
// "inputs": [
// {
// "intent": "action.devices.EXECUTE",
// "payload": {
// "commands": [
// {
// "devices": [
// {
// "id": "bedroom/nightstand"
// },
// {
// "id": "living/lamp"
// }
// ],
// "execution": [
// {
// "command": "action.devices.commands.OnOff",
// "params": {
// "on": true
// }
// }
// ]
// }
// ]
// }
// }
// ]
// }"#;
// let req: Request = serde_json::from_str(json).unwrap();
//
// let gh = GoogleHome {
// user_id: "Dreaded_X".into(),
// };
//
// let mut nightstand = TestOutlet::new("bedroom/nightstand");
// let mut lamp = TestOutlet::new("living/lamp");
// let mut scene = TestScene::new();
// let mut devices: HashMap<&str, &mut dyn GoogleHomeDevice> = HashMap::new();
// let id = nightstand.get_id().into();
// devices.insert(&id, &mut nightstand);
// let id = lamp.get_id().into();
// devices.insert(&id, &mut lamp);
// let id = scene.get_id().into();
// devices.insert(&id, &mut scene);
//
// let resp = gh.handle_request(req, &mut devices).unwrap();
//
// let json = serde_json::to_string(&resp).unwrap();
// println!("{}", json)
// }
// }

View File

@@ -0,0 +1,17 @@
#![allow(incomplete_features)]
#![feature(specialization)]
#![feature(let_chains)]
pub mod device;
mod fulfillment;
mod request;
mod response;
pub mod errors;
pub mod traits;
pub mod types;
pub use device::Device;
pub use fulfillment::{FulfillmentError, GoogleHome};
pub use request::Request;
pub use response::Response;

View File

@@ -0,0 +1,23 @@
pub mod execute;
pub mod query;
pub mod sync;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(tag = "intent", content = "payload")]
pub enum Intent {
#[serde(rename = "action.devices.SYNC")]
Sync,
#[serde(rename = "action.devices.QUERY")]
Query(query::Payload),
#[serde(rename = "action.devices.EXECUTE")]
Execute(execute::Payload),
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Request {
pub request_id: String,
pub inputs: Vec<Intent>,
}

View File

@@ -0,0 +1,140 @@
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 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] {
traits::Command::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] {
traits::Command::OnOff { on } => assert!(on),
_ => panic!("Expected OnOff"),
}
}
_ => panic!("Expected Execute intent"),
};
}
}

View File

@@ -0,0 +1,69 @@
use serde::Deserialize;
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
pub devices: Vec<Device>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub id: String,
// customData
}
#[cfg(test)]
mod tests {
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.QUERY",
"payload": {
"devices": [
{
"id": "123",
"customData": {
"fooValue": 74,
"barValue": true,
"bazValue": "foo"
}
},
{
"id": "456",
"customData": {
"fooValue": 12,
"barValue": false,
"bazValue": "bar"
}
}
]
}
}
]
}"#;
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::Query(payload) => {
assert_eq!(payload.devices.len(), 2);
assert_eq!(payload.devices[0].id, "123");
assert_eq!(payload.devices[1].id, "456");
}
_ => panic!("Expected Query intent"),
};
}
}

View File

@@ -0,0 +1,30 @@
#[cfg(test)]
mod tests {
use crate::request::{Intent, Request};
#[test]
fn deserialize() {
let json = r#"{
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [
{
"intent": "action.devices.SYNC"
}
]
}"#;
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::Sync => {}
_ => panic!("Expected Sync intent"),
}
}
}

View File

@@ -0,0 +1,29 @@
pub mod execute;
pub mod query;
pub mod sync;
use serde::Serialize;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Response {
request_id: String,
payload: ResponsePayload,
}
impl Response {
pub fn new(request_id: &str, payload: ResponsePayload) -> Self {
Self {
request_id: request_id.into(),
payload,
}
}
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum ResponsePayload {
Sync(sync::Payload),
Query(query::Payload),
Execute(execute::Payload),
}

View File

@@ -0,0 +1,126 @@
use serde::Serialize;
use crate::errors::ErrorCode;
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
commands: Vec<Command>,
}
impl Payload {
pub fn new() -> Self {
Self {
error_code: None,
debug_string: None,
commands: Vec::new(),
}
}
pub fn add_command(&mut self, command: Command) {
if !command.is_empty() {
self.commands.push(command);
}
}
}
impl Default for Payload {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Command {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
ids: Vec<String>,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub states: Option<States>,
}
impl Command {
pub fn new(status: Status) -> Self {
Self {
error_code: None,
ids: Vec::new(),
status,
states: None,
}
}
pub fn add_id(&mut self, id: &str) {
self.ids.push(id.into());
}
pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct States {
pub online: bool,
#[serde(flatten)]
pub state: serde_json::Value,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Status {
Success,
Pending,
Offline,
Exceptions,
Error,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::errors::DeviceError;
use crate::response::{Response, ResponsePayload};
#[test]
fn serialize() {
let mut execute_resp = Payload::new();
let state = json!({
"on": true,
});
let mut command = Command::new(Status::Success);
command.states = Some(States {
online: true,
state,
});
command.ids.push("123".into());
execute_resp.add_command(command);
let mut command = Command::new(Status::Error);
command.error_code = Some(DeviceError::DeviceNotFound.into());
command.ids.push("456".into());
execute_resp.add_command(command);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Execute(execute_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// TODO: Add a known correct output to test against
}
}

View File

@@ -0,0 +1,122 @@
use std::collections::HashMap;
use serde::Serialize;
use crate::errors::ErrorCode;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
pub devices: HashMap<String, Device>,
}
impl Payload {
pub fn new() -> Self {
Self {
error_code: None,
debug_string: None,
devices: HashMap::new(),
}
}
pub fn add_device(&mut self, id: &str, device: Device) {
self.devices.insert(id.into(), device);
}
}
impl Default for Payload {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Status {
Success,
Offline,
Exceptions,
Error,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
online: bool,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
error_code: Option<ErrorCode>,
#[serde(flatten)]
pub state: serde_json::Value,
}
impl Device {
pub fn new() -> Self {
Self {
online: true,
status: Status::Success,
error_code: None,
state: Default::default(),
}
}
pub fn set_offline(&mut self) {
self.online = false;
self.status = Status::Offline;
}
pub fn set_error(&mut self, err: ErrorCode) {
self.status = match err {
ErrorCode::DeviceError(_) => Status::Error,
ErrorCode::DeviceException(_) => Status::Exceptions,
};
self.error_code = Some(err);
}
}
impl Default for Device {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::response::{Response, ResponsePayload};
#[test]
fn serialize() {
let mut query_resp = Payload::new();
let mut device = Device::new();
device.state = json!({
"on": true,
});
query_resp.add_device("123", device);
let mut device = Device::new();
device.state = json!({
"on": true,
});
query_resp.add_device("456", device);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Query(query_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// TODO: Add a known correct output to test against
}
}

View File

@@ -0,0 +1,105 @@
use serde::Serialize;
use crate::device;
use crate::errors::ErrorCode;
use crate::traits::Trait;
use crate::types::Type;
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
agent_user_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<ErrorCode>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
pub devices: Vec<Device>,
}
impl Payload {
pub fn new(agent_user_id: &str) -> Self {
Self {
agent_user_id: agent_user_id.into(),
error_code: None,
debug_string: None,
devices: Vec::new(),
}
}
pub fn add_device(&mut self, device: Device) {
self.devices.push(device);
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
id: String,
#[serde(rename = "type")]
device_type: Type,
pub traits: Vec<Trait>,
pub name: device::Name,
pub will_report_state: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub notification_supported_by_agent: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub room_hint: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_info: Option<device::Info>,
pub attributes: serde_json::Value,
}
impl Device {
pub fn new(id: &str, name: &str, device_type: Type) -> Self {
Self {
id: id.into(),
device_type,
traits: Vec::new(),
name: device::Name::new(name),
will_report_state: false,
notification_supported_by_agent: None,
room_hint: None,
device_info: None,
attributes: Default::default(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::response::{Response, ResponsePayload};
use crate::traits::Trait;
use crate::types::Type;
#[test]
fn serialize() {
let mut sync_resp = Payload::new("1836.15267389");
let mut device = Device::new("123", "Night light", Type::Kettle);
device.traits.push(Trait::OnOff);
device.name.add_default_name("My Outlet 1234");
device.name.add_nickname("wall plug");
device.room_hint = Some("kitchen".into());
device.device_info = Some(device::Info {
manufacturer: Some("lights-out-inc".into()),
model: Some("hs1234".into()),
hw_version: Some("3.2".into()),
sw_version: Some("11.4".into()),
});
sync_resp.add_device(device);
let resp = Response::new(
"ff36a3cc-ec34-11e6-b1a0-64510650abcf",
ResponsePayload::Sync(sync_resp),
);
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json);
// 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"}}]}}"#)
}
}

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,15 @@
use serde::Serialize;
#[derive(Debug, Serialize)]
pub enum Type {
#[serde(rename = "action.devices.types.KETTLE")]
Kettle,
#[serde(rename = "action.devices.types.OUTLET")]
Outlet,
#[serde(rename = "action.devices.types.LIGHT")]
Light,
#[serde(rename = "action.devices.types.SCENE")]
Scene,
#[serde(rename = "action.devices.types.AIRPURIFIER")]
AirPurifier,
}