Started work on fullfillment of requests

This commit is contained in:
2022-12-14 05:30:46 +01:00
parent e4369ebf41
commit 36cd0e9b61
14 changed files with 1100 additions and 67 deletions

View File

@@ -0,0 +1,11 @@
use serde::Serialize;
use serde_with::skip_serializing_none;
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Attributes {
pub command_only_on_off: Option<bool>,
pub query_only_on_off: Option<bool>,
pub scene_reversible: Option<bool>,
}

96
google-home/src/device.rs Normal file
View File

@@ -0,0 +1,96 @@
use serde::Serialize;
use serde_with::skip_serializing_none;
use crate::{response, types::Type, traits::{AsOnOff, Trait, AsScene}};
pub trait GoogleHomeDevice: AsOnOff + AsScene {
fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name;
fn get_id(&self) -> &str;
// Default values that can optionally be overriden
fn will_report_state(&self) -> bool {
false
}
fn get_room_hint(&self) -> Option<String> {
None
}
fn get_device_info(&self) -> Option<Info> {
None
}
}
// This trait exists just to hide the sync, query and execute function from the user
pub trait GoogleHomeDeviceFullfillment: 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());
device.name = name;
device.will_report_state = self.will_report_state();
// notification_supported_by_agent
device.room_hint = self.get_room_hint();
device.device_info = self.get_device_info();
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();
}
}
// Scene
{
if let Some(d) = AsScene::cast(self) {
traits.push(Trait::Scene);
device.attributes.scene_reversible = d.is_scene_reversible();
}
}
device.traits = traits;
return device;
}
}
impl<T: GoogleHomeDevice> GoogleHomeDeviceFullfillment for T {}
#[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());
}
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Info {
pub manufacturer: Option<String>,
pub model: Option<String>,
pub hw_version: Option<String>,
pub sw_version: Option<String>,
// attributes
// customData
// otherDeviceIds
}

View File

@@ -0,0 +1,169 @@
use crate::{request::{Request, Intent, self}, device::GoogleHomeDeviceFullfillment, response::{sync, ResponsePayload, query, execute, Response}};
pub struct GoogleHome {
user_id: String,
// Add credentials so we can notify google home of actions
}
impl GoogleHome {
pub fn new(user_id: &str) -> Self {
Self { user_id: user_id.into() }
}
pub fn handle_request(&self, request: Request, devices: Vec<&mut dyn GoogleHomeDeviceFullfillment>) -> 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
.inputs
.into_iter()
.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)),
}).next();
match payload {
Some(payload) => Ok(Response::new(request.request_id, payload)),
_ => Err(anyhow::anyhow!("Something went wrong, expected at least ResponsePayload")),
}
}
fn sync(&self, devices: &Vec<&mut dyn GoogleHomeDeviceFullfillment>) -> sync::Payload {
let mut payload = sync::Payload::new(&self.user_id);
payload.devices = devices.iter().map(|device| device.sync()).collect::<Vec<_>>();
return payload;
}
fn query(&self, payload: request::query::Payload, devices: &Vec<&mut dyn GoogleHomeDeviceFullfillment>) -> query::Payload {
return query::Payload::new();
}
fn execute(&self, payload: request::execute::Payload, devices: &Vec<&mut dyn GoogleHomeDeviceFullfillment>) -> execute::Payload {
return execute::Payload::new();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{request::Request, device::{GoogleHomeDevice, self}, types, traits};
struct TestOutlet {
on: bool,
}
impl TestOutlet {
fn new() -> Self {
Self { 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");
return name;
}
fn get_id(&self) -> &str {
return "bedroom/nightstand";
}
fn get_room_hint(&self) -> Option<String> {
Some("Bedroom".into())
}
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, anyhow::Error> {
Ok(self.on)
}
fn set_on(&mut self, on: bool) -> Result<(), anyhow::Error> {
self.on = on;
Ok(())
}
}
impl traits::AsScene for TestOutlet {}
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 {
return "living/party_mode";
}
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> {
println!("Activating the party scene");
Ok(())
}
}
impl traits::AsOnOff for TestScene {}
#[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 device = TestOutlet::new();
let mut scene = TestScene::new();
let devices: Vec<&mut dyn GoogleHomeDeviceFullfillment> = vec![&mut device, &mut scene];
let resp = gh.handle_request(req, devices).unwrap();
let json = serde_json::to_string(&resp).unwrap();
println!("{}", json)
}
}

View File

@@ -1,4 +1,9 @@
pub mod fullfillment;
pub mod device;
pub mod request;
pub mod response;
pub mod types;
pub mod traits;
pub mod attributes;

View File

@@ -7,7 +7,7 @@ use uuid::Uuid;
#[derive(Debug, Deserialize)]
#[serde(tag = "intent", content = "payload")]
enum Intent {
pub enum Intent {
#[serde(rename = "action.devices.SYNC")]
Sync,
#[serde(rename = "action.devices.QUERY")]
@@ -18,7 +18,7 @@ enum Intent {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Request {
pub struct Request {
pub request_id: Uuid,
pub inputs: Vec<Intent>,
}

View File

@@ -27,6 +27,10 @@ pub enum CommandType {
OnOff {
on: bool
},
#[serde(rename = "action.devices.commands.ActivateScene")]
ActivateScene {
deactivate: bool
}
}
#[cfg(test)]
@@ -95,7 +99,7 @@ mod tests {
assert_eq!(payload.commands[0].execution.len(), 1);
match payload.commands[0].execution[0] {
CommandType::OnOff{on} => assert_eq!(on, true),
// _ => panic!("Expected OnOff")
_ => panic!("Expected OnOff")
}
},
_ => panic!("Expected Execute intent")

View File

@@ -3,6 +3,7 @@ pub mod query;
pub mod execute;
use serde::Serialize;
use serde_with::skip_serializing_none;
use uuid::Uuid;
#[derive(Debug, Serialize)]
@@ -13,7 +14,7 @@ pub struct Response {
}
impl Response {
fn new(request_id: Uuid, payload: ResponsePayload) -> Self {
pub fn new(request_id: Uuid, payload: ResponsePayload) -> Self {
Self { request_id, payload }
}
}
@@ -26,10 +27,10 @@ pub enum ResponsePayload {
Execute(execute::Payload),
}
#[skip_serializing_none]
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct State {
#[serde(skip_serializing_if = "Option::is_none")]
on: Option<bool>,
}

View File

@@ -1,13 +1,13 @@
use serde::Serialize;
use serde_with::skip_serializing_none;
use crate::response::State;
#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
commands: Vec<Command>,
}
@@ -22,10 +22,10 @@ impl Payload {
}
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Command {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
ids: Vec<String>,

View File

@@ -1,15 +1,15 @@
use std::collections::HashMap;
use serde::Serialize;
use serde_with::skip_serializing_none;
use crate::response::State;
#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Payload {
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
devices: HashMap<String, Device>,
}
@@ -33,12 +33,12 @@ pub enum Status {
Error,
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
online: bool,
status: Status,
#[serde(skip_serializing_if = "Option::is_none")]
pub error_code: Option<String>,
#[serde(flatten)]

View File

@@ -1,15 +1,17 @@
use serde::Serialize;
use serde_with::skip_serializing_none;
use crate::attributes::Attributes;
use crate::device;
use crate::types::Type;
use crate::traits::Trait;
#[skip_serializing_none]
#[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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub debug_string: Option<String>,
pub devices: Vec<Device>,
}
@@ -24,6 +26,7 @@ impl Payload {
}
}
#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
@@ -31,16 +34,12 @@ pub struct Device {
#[serde(rename = "type")]
device_type: Type,
pub traits: Vec<Trait>,
pub name: DeviceName,
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 = "String::is_empty")]
pub room_hint: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub device_info: Option<DeviceInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
pub attributes: Option<Attributes>,
pub room_hint: Option<String>,
pub device_info: Option<device::Info>,
pub attributes: Attributes,
}
impl Device {
@@ -49,51 +48,16 @@ impl Device {
id: id.into(),
device_type,
traits: Vec::new(),
name: DeviceName {
default_names: Vec::new(),
name: name.into(),
nicknames: Vec::new() },
name: device::Name::new(name),
will_report_state: false,
notification_supported_by_agent: None,
room_hint: "".into(),
room_hint: None,
device_info: None,
attributes: None,
attributes: Attributes::default(),
}
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceName {
#[serde(skip_serializing_if = "Vec::is_empty")]
pub default_names: Vec<String>,
name: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub nicknames: Vec<String>,
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceInfo {
#[serde(skip_serializing_if = "String::is_empty")]
pub manufacturer: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub model: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub hw_version: String,
#[serde(skip_serializing_if = "String::is_empty")]
pub sw_version: String,
// attributes
// customData
// otherDeviceIds
}
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Attributes {
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
@@ -107,15 +71,15 @@ mod tests {
let mut device = Device::new("123", "Night light", Type::Kettle);
device.traits.push(Trait::OnOff);
device.name.default_names.push("My Outlet 1234".to_string());
device.name.nicknames.push("wall plug".to_string());
device.name.add_default_name("My Outlet 1234");
device.name.add_nickname("wall plug");
device.room_hint = "kitchen".into();
device.device_info = Some(DeviceInfo {
manufacturer: "lights-out-inc".to_string(),
model: "hs1234".to_string(),
hw_version: "3.2".to_string(),
sw_version: "11.4".to_string(),
device.room_hint = Some("kitchen".into());
device.device_info = Some(device::Info {
manufacturer: Some("lights-out-inc".to_string()),
model: Some("hs1234".to_string()),
hw_version: Some("3.2".to_string()),
sw_version: Some("11.4".to_string()),
});
sync_resp.add_device(device);

View File

@@ -1,5 +1,7 @@
use serde::Serialize;
use crate::device::GoogleHomeDevice;
#[derive(Debug, Serialize)]
pub enum Trait {
#[serde(rename = "action.devices.traits.OnOff")]
@@ -7,3 +9,58 @@ pub enum Trait {
#[serde(rename = "action.devices.traits.Scene")]
Scene,
}
pub trait OnOff {
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
fn is_on(&self) -> Result<bool, anyhow::Error>;
fn set_on(&mut self, on: bool) -> Result<(), anyhow::Error>;
}
pub trait AsOnOff {
fn cast(&self) -> Option<&dyn OnOff> {
None
}
fn cast_mut(&mut self) -> Option<&mut dyn OnOff> {
None
}
}
impl<T: GoogleHomeDevice + OnOff> AsOnOff for T {
fn cast(&self) -> Option<&dyn OnOff> {
Some(self)
}
fn cast_mut(&mut self) -> Option<&mut dyn OnOff> {
Some(self)
}
}
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<T: GoogleHomeDevice + Scene> AsScene for T {
fn cast(&self) -> Option<&dyn Scene> {
Some(self)
}
fn cast_mut(&mut self) -> Option<&mut dyn Scene> {
Some(self)
}
}