Finished basic google home implementation with some slight refactors along the way
This commit is contained in:
35
google-home/Cargo.lock
generated
35
google-home/Cargo.lock
generated
@@ -177,9 +177,11 @@ name = "google-home"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"impl_cast",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"thiserror",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -225,6 +227,13 @@ version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
|
||||
|
||||
[[package]]
|
||||
name = "impl_cast"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"paste",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.2"
|
||||
@@ -300,6 +309,12 @@ version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860"
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf1c2c742266c2f1041c914ba65355a83ae8747b05f208319784083583494b4b"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.47"
|
||||
@@ -415,6 +430,26 @@ dependencies = [
|
||||
"winapi-util",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.17"
|
||||
|
||||
@@ -6,10 +6,12 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0"
|
||||
anyhow = "1.0.66"
|
||||
impl_cast = { path = "../impl_cast" }
|
||||
serde = { version ="1.0.149", features = ["derive"] }
|
||||
serde_json = "1.0.89"
|
||||
serde_with = "2.1.0"
|
||||
thiserror = "1.0.37"
|
||||
|
||||
[dependencies.uuid]
|
||||
version = "1.2.2"
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
use serde::Serialize;
|
||||
use serde_with::skip_serializing_none;
|
||||
|
||||
use crate::{response, types::Type, traits::{AsOnOff, Trait, AsScene}};
|
||||
use crate::{response, types::Type, traits::{AsOnOff, Trait, AsScene}, errors::{DeviceError, ErrorCode}, request::execute::CommandType};
|
||||
|
||||
pub trait GoogleHomeDevice<'a>: AsOnOff + AsScene {
|
||||
pub trait GoogleHomeDevice: AsOnOff + AsScene {
|
||||
fn get_device_type(&self) -> Type;
|
||||
fn get_device_name(&self) -> Name;
|
||||
fn get_id(&self) -> &'a str;
|
||||
fn get_id(&self) -> String;
|
||||
fn is_online(&self) -> bool;
|
||||
|
||||
// Default values that can optionally be overriden
|
||||
fn will_report_state(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn get_room_hint(&self) -> Option<&'a str> {
|
||||
fn get_room_hint(&self) -> Option<String> {
|
||||
None
|
||||
}
|
||||
fn get_device_info(&self) -> Option<Info> {
|
||||
@@ -22,7 +22,7 @@ pub trait GoogleHomeDevice<'a>: AsOnOff + AsScene {
|
||||
}
|
||||
|
||||
// This trait exists just to hide the sync, query and execute function from the user
|
||||
pub trait Fullfillment<'a>: GoogleHomeDevice<'a> {
|
||||
pub trait Fullfillment: GoogleHomeDevice {
|
||||
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());
|
||||
@@ -37,20 +37,16 @@ pub trait Fullfillment<'a>: GoogleHomeDevice<'a> {
|
||||
|
||||
let mut traits = Vec::new();
|
||||
// OnOff
|
||||
{
|
||||
if let Some(d) = AsOnOff::cast(self) {
|
||||
traits.push(Trait::OnOff);
|
||||
device.attributes.command_only_on_off = d.is_command_only();
|
||||
device.attributes.query_only_on_off = d.is_query_only();
|
||||
}
|
||||
if let Some(d) = AsOnOff::cast(self) {
|
||||
traits.push(Trait::OnOff);
|
||||
device.attributes.command_only_on_off = d.is_command_only();
|
||||
device.attributes.query_only_on_off = d.is_query_only();
|
||||
}
|
||||
|
||||
// Scene
|
||||
{
|
||||
if let Some(d) = AsScene::cast(self) {
|
||||
traits.push(Trait::Scene);
|
||||
device.attributes.scene_reversible = d.is_scene_reversible();
|
||||
}
|
||||
if let Some(d) = AsScene::cast(self) {
|
||||
traits.push(Trait::Scene);
|
||||
device.attributes.scene_reversible = d.is_scene_reversible();
|
||||
}
|
||||
|
||||
device.traits = traits;
|
||||
@@ -59,29 +55,45 @@ pub trait Fullfillment<'a>: GoogleHomeDevice<'a> {
|
||||
}
|
||||
|
||||
fn query(&self) -> response::query::Device {
|
||||
let status;
|
||||
let online = self.is_online();
|
||||
if online {
|
||||
status = response::query::Status::Success;
|
||||
} else {
|
||||
status = response::query::Status::Offline;
|
||||
let mut device = response::query::Device::new();
|
||||
if !self.is_online() {
|
||||
device.set_offline();
|
||||
}
|
||||
|
||||
let mut device = response::query::Device::new(online, status);
|
||||
|
||||
// OnOff
|
||||
{
|
||||
if let Some(d) = AsOnOff::cast(self) {
|
||||
// @TODO Handle errors
|
||||
device.state.on = Some(d.is_on().unwrap());
|
||||
if let Some(d) = AsOnOff::cast(self) {
|
||||
match d.is_on() {
|
||||
Ok(state) => device.state.on = Some(state),
|
||||
Err(err) => device.set_error(err),
|
||||
}
|
||||
}
|
||||
|
||||
return device;
|
||||
}
|
||||
|
||||
fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
|
||||
match command {
|
||||
CommandType::OnOff { on } => {
|
||||
if let Some(d) = AsOnOff::cast_mut(self) {
|
||||
d.set_on(*on)?;
|
||||
} else {
|
||||
return Err(DeviceError::ActionNotAvailable.into());
|
||||
}
|
||||
},
|
||||
CommandType::ActivateScene { deactivate } => {
|
||||
if let Some(d) = AsScene::cast_mut(self) {
|
||||
d.set_active(!deactivate)?;
|
||||
} else {
|
||||
return Err(DeviceError::ActionNotAvailable.into());
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: GoogleHomeDevice<'a>> Fullfillment<'a> for T {}
|
||||
impl<T: GoogleHomeDevice> Fullfillment for T {}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1,7 +1,37 @@
|
||||
use thiserror::Error;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Error)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Errors {
|
||||
DeviceNotFound
|
||||
pub enum DeviceError {
|
||||
#[error("deviceNotFound")]
|
||||
DeviceNotFound,
|
||||
#[error("actionNotAvailable")]
|
||||
ActionNotAvailable,
|
||||
}
|
||||
|
||||
#[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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{request::{Request, Intent, self}, device::Fullfillment, response::{sync, ResponsePayload, query, execute, Response}, errors::Errors};
|
||||
use crate::{request::{Request, Intent, self}, device::Fullfillment, response::{sync, ResponsePayload, query, execute, Response, self, State}, errors::{DeviceError, ErrorCode}};
|
||||
|
||||
pub struct GoogleHome {
|
||||
user_id: String,
|
||||
@@ -12,7 +12,7 @@ impl GoogleHome {
|
||||
Self { user_id: user_id.into() }
|
||||
}
|
||||
|
||||
pub fn handle_request(&self, request: Request, devices: &HashMap<String, &mut dyn Fullfillment>) -> Result<Response, anyhow::Error> {
|
||||
pub fn handle_request(&self, request: Request, mut devices: &mut HashMap<String, &mut dyn Fullfillment>) -> Result<Response, anyhow::Error> {
|
||||
// @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 payload = request
|
||||
@@ -21,7 +21,7 @@ impl GoogleHome {
|
||||
.map(|input| match input {
|
||||
Intent::Sync => ResponsePayload::Sync(self.sync(&devices)),
|
||||
Intent::Query(payload) => ResponsePayload::Query(self.query(payload, &devices)),
|
||||
Intent::Execute(payload) => ResponsePayload::Execute(self.execute(payload, &devices)),
|
||||
Intent::Execute(payload) => ResponsePayload::Execute(self.execute(payload, &mut devices)),
|
||||
}).next();
|
||||
|
||||
match payload {
|
||||
@@ -32,49 +32,113 @@ impl GoogleHome {
|
||||
|
||||
fn sync(&self, devices: &HashMap<String, &mut dyn Fullfillment>) -> sync::Payload {
|
||||
let mut resp_payload = sync::Payload::new(&self.user_id);
|
||||
resp_payload.devices = devices.iter().map(|(_, device)| device.sync()).collect::<Vec<_>>();
|
||||
resp_payload.devices = devices
|
||||
.iter()
|
||||
.map(|(_, device)| device.sync())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
return resp_payload;
|
||||
}
|
||||
|
||||
fn query(&self, payload: request::query::Payload, devices: &HashMap<String, &mut dyn Fullfillment>) -> query::Payload {
|
||||
let mut resp_payload = query::Payload::new();
|
||||
for request::query::Device{id} in payload.devices {
|
||||
let mut d: query::Device;
|
||||
if let Some(device) = devices.get(&id) {
|
||||
d = device.query();
|
||||
} else {
|
||||
d = query::Device::new(false, query::Status::Error);
|
||||
d.error_code = Some(Errors::DeviceNotFound);
|
||||
}
|
||||
resp_payload.add_device(&id, d)
|
||||
}
|
||||
resp_payload.devices = payload.devices
|
||||
.into_iter()
|
||||
.map(|device| device.id)
|
||||
.map(|id| {
|
||||
let mut d: query::Device;
|
||||
if let Some(device) = devices.get(id.as_str()) {
|
||||
d = device.query();
|
||||
} else {
|
||||
d = query::Device::new();
|
||||
d.set_offline();
|
||||
d.set_error(DeviceError::DeviceNotFound.into());
|
||||
}
|
||||
|
||||
return (id, d);
|
||||
}).collect();
|
||||
|
||||
return resp_payload;
|
||||
|
||||
}
|
||||
|
||||
fn execute(&self, payload: request::execute::Payload, devices: &HashMap<String, &mut dyn Fullfillment>) -> execute::Payload {
|
||||
return execute::Payload::new();
|
||||
fn execute(&self, payload: request::execute::Payload, devices: &mut HashMap<String, &mut dyn Fullfillment>) -> execute::Payload {
|
||||
let mut resp_payload = response::execute::Payload::new();
|
||||
|
||||
payload.commands
|
||||
.into_iter()
|
||||
.for_each(|command| {
|
||||
let mut success = response::execute::Command::new(execute::Status::Success);
|
||||
success.states = Some(execute::States { online: true, state: State::default() });
|
||||
let mut offline = response::execute::Command::new(execute::Status::Offline);
|
||||
offline.states = Some(execute::States { online: false, state: State::default() });
|
||||
let mut errors: HashMap<ErrorCode, response::execute::Command> = HashMap::new();
|
||||
|
||||
command.devices
|
||||
.into_iter()
|
||||
.map(|device| device.id)
|
||||
.map(|id| {
|
||||
if let Some(device) = devices.get_mut(id.as_str()) {
|
||||
if !device.is_online() {
|
||||
return (id, Ok(false));
|
||||
}
|
||||
let results = command.execution.iter().map(|cmd| {
|
||||
// @TODO We should also return the state after update in the state
|
||||
// struct, however that will make things WAY more complicated
|
||||
device.execute(cmd)
|
||||
}).collect::<Result<Vec<_>, ErrorCode>>();
|
||||
|
||||
// @TODO We only get one error not all errors
|
||||
if let Err(err) = results {
|
||||
return (id, Err(err));
|
||||
} else {
|
||||
return (id, Ok(true));
|
||||
}
|
||||
} else {
|
||||
return (id, Err(DeviceError::DeviceNotFound.into()));
|
||||
}
|
||||
}).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),
|
||||
};
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
return resp_payload;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{request::Request, device::{GoogleHomeDevice, self}, types, traits};
|
||||
use crate::{request::Request, device::{GoogleHomeDevice, self}, types, traits, errors::ErrorCode};
|
||||
|
||||
struct TestOutlet {
|
||||
name: String,
|
||||
on: bool,
|
||||
}
|
||||
|
||||
impl TestOutlet {
|
||||
fn new() -> Self {
|
||||
Self { on: false }
|
||||
fn new(name: &str) -> Self {
|
||||
Self { name: name.into(), on: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> GoogleHomeDevice<'a> for TestOutlet {
|
||||
impl GoogleHomeDevice for TestOutlet {
|
||||
fn get_device_type(&self) -> types::Type {
|
||||
types::Type::Outlet
|
||||
}
|
||||
@@ -87,16 +151,16 @@ mod tests {
|
||||
return name;
|
||||
}
|
||||
|
||||
fn get_id(&self) -> &'a str {
|
||||
return "bedroom/nightstand";
|
||||
fn get_id(&self) -> String {
|
||||
return self.name.clone();
|
||||
}
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_room_hint(&self) -> Option<&'a str> {
|
||||
Some("Bedroom")
|
||||
fn get_room_hint(&self) -> Option<String> {
|
||||
Some("Bedroom".into())
|
||||
}
|
||||
|
||||
fn get_device_info(&self) -> Option<device::Info> {
|
||||
@@ -110,19 +174,16 @@ mod tests {
|
||||
}
|
||||
|
||||
impl traits::OnOff for TestOutlet {
|
||||
fn is_on(&self) -> Result<bool, anyhow::Error> {
|
||||
fn is_on(&self) -> Result<bool, ErrorCode> {
|
||||
Ok(self.on)
|
||||
}
|
||||
|
||||
fn set_on(&mut self, on: bool) -> Result<(), anyhow::Error> {
|
||||
fn set_on(&mut self, on: bool) -> Result<(), ErrorCode> {
|
||||
self.on = on;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl traits::AsScene for TestOutlet {}
|
||||
|
||||
|
||||
struct TestScene {}
|
||||
|
||||
impl TestScene {
|
||||
@@ -131,7 +192,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> GoogleHomeDevice<'a> for TestScene {
|
||||
impl GoogleHomeDevice for TestScene {
|
||||
fn get_device_type(&self) -> types::Type {
|
||||
types::Type::Scene
|
||||
}
|
||||
@@ -140,30 +201,26 @@ mod tests {
|
||||
device::Name::new("Party")
|
||||
}
|
||||
|
||||
fn get_id(&self) -> &'a str {
|
||||
return "living/party_mode";
|
||||
fn get_id(&self) -> String {
|
||||
return "living/party_mode".into();
|
||||
}
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn get_room_hint(&self) -> Option<&'a str> {
|
||||
Some("Living room")
|
||||
fn get_room_hint(&self) -> Option<String> {
|
||||
Some("Living room".into())
|
||||
}
|
||||
}
|
||||
|
||||
impl traits::Scene for TestScene {
|
||||
fn set_active(&self, _activate: bool) -> Result<(), anyhow::Error> {
|
||||
fn set_active(&self, _activate: bool) -> Result<(), ErrorCode> {
|
||||
println!("Activating the party scene");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl traits::AsOnOff for TestScene {}
|
||||
|
||||
|
||||
|
||||
#[test]
|
||||
fn handle_sync() {
|
||||
let json = r#"{
|
||||
@@ -180,13 +237,15 @@ mod tests {
|
||||
user_id: "Dreaded_X".into(),
|
||||
};
|
||||
|
||||
let mut device = TestOutlet::new();
|
||||
let mut nightstand = TestOutlet::new("bedroom/nightstand");
|
||||
let mut lamp = TestOutlet::new("living/lamp");
|
||||
let mut scene = TestScene::new();
|
||||
let mut devices: HashMap<String, &mut dyn Fullfillment> = HashMap::new();
|
||||
devices.insert(device.get_id().into(), &mut device);
|
||||
devices.insert(scene.get_id().into(), &mut scene);
|
||||
devices.insert(nightstand.get_id(), &mut nightstand);
|
||||
devices.insert(lamp.get_id(), &mut lamp);
|
||||
devices.insert(scene.get_id(), &mut scene);
|
||||
|
||||
let resp = gh.handle_request(req, &devices).unwrap();
|
||||
let resp = gh.handle_request(req, &mut devices).unwrap();
|
||||
|
||||
let json = serde_json::to_string(&resp).unwrap();
|
||||
println!("{}", json)
|
||||
@@ -218,13 +277,67 @@ mod tests {
|
||||
user_id: "Dreaded_X".into(),
|
||||
};
|
||||
|
||||
let mut device = TestOutlet::new();
|
||||
let mut nightstand = TestOutlet::new("bedroom/nightstand");
|
||||
let mut lamp = TestOutlet::new("living/lamp");
|
||||
let mut scene = TestScene::new();
|
||||
let mut devices: HashMap<String, &mut dyn Fullfillment> = HashMap::new();
|
||||
devices.insert(device.get_id().into(), &mut device);
|
||||
devices.insert(scene.get_id().into(), &mut scene);
|
||||
devices.insert(nightstand.get_id(), &mut nightstand);
|
||||
devices.insert(lamp.get_id(), &mut lamp);
|
||||
devices.insert(scene.get_id(), &mut scene);
|
||||
|
||||
let resp = gh.handle_request(req, &devices).unwrap();
|
||||
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<String, &mut dyn Fullfillment> = HashMap::new();
|
||||
devices.insert(nightstand.get_id(), &mut nightstand);
|
||||
devices.insert(lamp.get_id(), &mut lamp);
|
||||
devices.insert(scene.get_id(), &mut scene);
|
||||
|
||||
let resp = gh.handle_request(req, &mut devices).unwrap();
|
||||
|
||||
let json = serde_json::to_string(&resp).unwrap();
|
||||
println!("{}", json)
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
pub mod fullfillment;
|
||||
#![feature(specialization)]
|
||||
mod fullfillment;
|
||||
pub mod device;
|
||||
|
||||
pub mod request;
|
||||
pub mod response;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub mod types;
|
||||
pub mod traits;
|
||||
pub mod attributes;
|
||||
pub mod errors;
|
||||
mod attributes;
|
||||
|
||||
pub use fullfillment::GoogleHome;
|
||||
pub use device::Fullfillment;
|
||||
pub use device::GoogleHomeDevice;
|
||||
|
||||
@@ -3,20 +3,20 @@ use serde::Deserialize;
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Payload {
|
||||
commands: Vec<Command>,
|
||||
pub commands: Vec<Command>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Command {
|
||||
devices: Vec<Device>,
|
||||
execution: Vec<CommandType>
|
||||
pub devices: Vec<Device>,
|
||||
pub execution: Vec<CommandType>
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Device {
|
||||
id: String,
|
||||
pub id: String,
|
||||
// customData
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use serde::Serialize;
|
||||
use serde_with::skip_serializing_none;
|
||||
|
||||
use crate::{response::State, errors::Errors};
|
||||
use crate::{response::State, errors::ErrorCode};
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Payload {
|
||||
pub error_code: Option<Errors>,
|
||||
pub error_code: Option<ErrorCode>,
|
||||
pub debug_string: Option<String>,
|
||||
commands: Vec<Command>,
|
||||
}
|
||||
@@ -18,7 +18,9 @@ impl Payload {
|
||||
}
|
||||
|
||||
pub fn add_command(&mut self, command: Command) {
|
||||
self.commands.push(command);
|
||||
if !command.is_empty() {
|
||||
self.commands.push(command);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +28,7 @@ impl Payload {
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Command {
|
||||
pub error_code: Option<Errors>,
|
||||
pub error_code: Option<ErrorCode>,
|
||||
|
||||
ids: Vec<String>,
|
||||
status: Status,
|
||||
@@ -41,6 +43,10 @@ impl Command {
|
||||
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)]
|
||||
@@ -67,7 +73,7 @@ mod tests {
|
||||
use std::str::FromStr;
|
||||
use uuid::Uuid;
|
||||
use super::*;
|
||||
use crate::response::{Response, ResponsePayload, State};
|
||||
use crate::{response::{Response, ResponsePayload, State}, errors::DeviceError};
|
||||
|
||||
#[test]
|
||||
fn serialize() {
|
||||
@@ -84,7 +90,7 @@ mod tests {
|
||||
execute_resp.add_command(command);
|
||||
|
||||
let mut command = Command::new(Status::Error);
|
||||
command.error_code = Some(Errors::DeviceNotFound);
|
||||
command.error_code = Some(DeviceError::DeviceNotFound.into());
|
||||
command.ids.push("456".into());
|
||||
execute_resp.add_command(command);
|
||||
|
||||
|
||||
@@ -3,15 +3,15 @@ use std::collections::HashMap;
|
||||
use serde::Serialize;
|
||||
use serde_with::skip_serializing_none;
|
||||
|
||||
use crate::{response::State, errors::Errors};
|
||||
use crate::{response::State, errors::ErrorCode};
|
||||
|
||||
#[skip_serializing_none]
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Payload {
|
||||
pub error_code: Option<Errors>,
|
||||
pub error_code: Option<ErrorCode>,
|
||||
pub debug_string: Option<String>,
|
||||
devices: HashMap<String, Device>,
|
||||
pub devices: HashMap<String, Device>,
|
||||
}
|
||||
|
||||
impl Payload {
|
||||
@@ -39,15 +39,28 @@ pub enum Status {
|
||||
pub struct Device {
|
||||
online: bool,
|
||||
status: Status,
|
||||
pub error_code: Option<Errors>,
|
||||
error_code: Option<ErrorCode>,
|
||||
|
||||
#[serde(flatten)]
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub fn new(online: bool, status: Status) -> Self {
|
||||
Self { online, status, error_code: None, state: State::default() }
|
||||
pub fn new() -> Self {
|
||||
Self { online: true, status: Status::Success, error_code: None, state: State::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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,19 +69,17 @@ mod tests {
|
||||
use std::str::FromStr;
|
||||
use uuid::Uuid;
|
||||
use super::*;
|
||||
use crate::response::{Response, ResponsePayload, State};
|
||||
use crate::response::{Response, ResponsePayload};
|
||||
|
||||
#[test]
|
||||
fn serialize() {
|
||||
let mut query_resp = Payload::new();
|
||||
|
||||
let state = State::default();
|
||||
let mut device = Device::new(true, Status::Success);
|
||||
let mut device = Device::new();
|
||||
device.state.on = Some(true);
|
||||
query_resp.add_device("123", device);
|
||||
|
||||
let state = State::default();
|
||||
let mut device = Device::new(true, Status::Success);
|
||||
let mut device = Device::new();
|
||||
device.state.on = Some(false);
|
||||
query_resp.add_device("456", device);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ use serde_with::skip_serializing_none;
|
||||
|
||||
use crate::attributes::Attributes;
|
||||
use crate::device;
|
||||
use crate::errors::Errors;
|
||||
use crate::errors::ErrorCode;
|
||||
use crate::types::Type;
|
||||
use crate::traits::Trait;
|
||||
|
||||
@@ -12,7 +12,7 @@ use crate::traits::Trait;
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Payload {
|
||||
agent_user_id: String,
|
||||
pub error_code: Option<Errors>,
|
||||
pub error_code: Option<ErrorCode>,
|
||||
pub debug_string: Option<String>,
|
||||
pub devices: Vec<Device>,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::device::GoogleHomeDevice;
|
||||
use crate::{device::GoogleHomeDevice, errors::ErrorCode};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub enum Trait {
|
||||
@@ -20,47 +20,16 @@ pub trait OnOff {
|
||||
}
|
||||
|
||||
// @TODO Implement correct error so we can handle them properly
|
||||
fn is_on(&self) -> Result<bool, anyhow::Error>;
|
||||
fn set_on(&mut self, on: bool) -> Result<(), anyhow::Error>;
|
||||
fn is_on(&self) -> Result<bool, ErrorCode>;
|
||||
fn set_on(&mut self, on: bool) -> Result<(), ErrorCode>;
|
||||
}
|
||||
pub trait AsOnOff {
|
||||
fn cast(&self) -> Option<&dyn OnOff> {
|
||||
None
|
||||
}
|
||||
fn cast_mut(&mut self) -> Option<&mut dyn OnOff> {
|
||||
None
|
||||
}
|
||||
}
|
||||
impl<'a, T: GoogleHomeDevice<'a> + OnOff> AsOnOff for T {
|
||||
fn cast(&self) -> Option<&dyn OnOff> {
|
||||
Some(self)
|
||||
}
|
||||
fn cast_mut(&mut self) -> Option<&mut dyn OnOff> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl_cast::impl_cast!(GoogleHomeDevice, OnOff);
|
||||
|
||||
pub trait Scene {
|
||||
fn is_scene_reversible(&self) -> Option<bool> {
|
||||
None
|
||||
}
|
||||
|
||||
fn set_active(&self, activate: bool) -> Result<(), anyhow::Error>;
|
||||
}
|
||||
pub trait AsScene {
|
||||
fn cast(&self) -> Option<&dyn Scene> {
|
||||
None
|
||||
}
|
||||
fn cast_mut(&mut self) -> Option<&mut dyn Scene> {
|
||||
None
|
||||
}
|
||||
}
|
||||
impl<'a, T: GoogleHomeDevice<'a> + Scene> AsScene for T {
|
||||
fn cast(&self) -> Option<&dyn Scene> {
|
||||
Some(self)
|
||||
}
|
||||
fn cast_mut(&mut self) -> Option<&mut dyn Scene> {
|
||||
Some(self)
|
||||
}
|
||||
fn set_active(&self, activate: bool) -> Result<(), ErrorCode>;
|
||||
}
|
||||
impl_cast::impl_cast!(GoogleHomeDevice, Scene);
|
||||
|
||||
Reference in New Issue
Block a user