Store devices wrapped in Arc RwLock
This commit is contained in:
@@ -7,6 +7,9 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
impl_cast = { path = "../impl_cast" }
|
||||
serde = { version ="1.0.149", features = ["derive"] }
|
||||
serde = { version = "1.0.149", features = ["derive"] }
|
||||
serde_json = "1.0.89"
|
||||
thiserror = "1.0.37"
|
||||
tokio = "1"
|
||||
async-trait = "0.1.61"
|
||||
futures = "0.3.25"
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use async_trait::async_trait;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::{
|
||||
@@ -8,8 +9,43 @@ use crate::{
|
||||
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)]
|
||||
pub trait GoogleHomeDevice: Sync + Send + 'static {
|
||||
pub trait GoogleHomeDevice: AsGoogleHomeDevice + Sync + Send + 'static {
|
||||
fn get_device_type(&self) -> Type;
|
||||
fn get_device_name(&self) -> Name;
|
||||
fn get_id(&self) -> &str;
|
||||
@@ -26,7 +62,7 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
|
||||
None
|
||||
}
|
||||
|
||||
fn sync(&self) -> response::sync::Device {
|
||||
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());
|
||||
@@ -40,9 +76,11 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
|
||||
device.device_info = self.get_device_info();
|
||||
|
||||
let mut traits = Vec::new();
|
||||
|
||||
// OnOff
|
||||
if let Some(on_off) = As::<dyn OnOff>::cast(self) {
|
||||
traits.push(Trait::OnOff);
|
||||
let on_off = on_off;
|
||||
device.attributes.command_only_on_off = on_off.is_command_only();
|
||||
device.attributes.query_only_on_off = on_off.is_query_only();
|
||||
}
|
||||
@@ -58,7 +96,7 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
|
||||
device
|
||||
}
|
||||
|
||||
fn query(&self) -> response::query::Device {
|
||||
async fn query(&self) -> response::query::Device {
|
||||
let mut device = response::query::Device::new();
|
||||
if !self.is_online() {
|
||||
device.set_offline();
|
||||
@@ -72,19 +110,21 @@ pub trait GoogleHomeDevice: Sync + Send + 'static {
|
||||
device
|
||||
}
|
||||
|
||||
fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
|
||||
async fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
|
||||
match command {
|
||||
CommandType::OnOff { on } => {
|
||||
let on_off = As::<dyn OnOff>::cast_mut(self)
|
||||
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
|
||||
|
||||
on_off.set_on(*on)?;
|
||||
if let Some(on_off) = As::<dyn OnOff>::cast_mut(self) {
|
||||
on_off.set_on(*on)?;
|
||||
} else {
|
||||
return Err(DeviceError::ActionNotAvailable.into());
|
||||
}
|
||||
}
|
||||
CommandType::ActivateScene { deactivate } => {
|
||||
let scene = As::<dyn Scene>::cast_mut(self)
|
||||
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
|
||||
|
||||
scene.set_active(!deactivate)?;
|
||||
if let Some(scene) = As::<dyn Scene>::cast(self) {
|
||||
scene.set_active(!deactivate)?;
|
||||
} else {
|
||||
return Err(DeviceError::ActionNotAvailable.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
|
||||
use futures::future::{join_all, OptionFuture};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use crate::{
|
||||
device::GoogleHomeDevice,
|
||||
device::AsGoogleHomeDevice,
|
||||
errors::{DeviceError, ErrorCode},
|
||||
request::{self, Intent, Request},
|
||||
response::{self, execute, query, sync, Response, ResponsePayload, State},
|
||||
@@ -28,387 +30,415 @@ impl GoogleHome {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_request(
|
||||
pub async fn handle_request<T: AsGoogleHomeDevice + ?Sized + 'static>(
|
||||
&self,
|
||||
request: Request,
|
||||
devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>,
|
||||
devices: &HashMap<String, Arc<RwLock<Box<T>>>>,
|
||||
) -> Result<Response, FullfillmentError> {
|
||||
// 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))
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
.next();
|
||||
.into();
|
||||
|
||||
payload
|
||||
.await
|
||||
.ok_or(FullfillmentError::ExpectedOnePayload)
|
||||
.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);
|
||||
resp_payload.devices = devices
|
||||
.iter()
|
||||
.map(|(_, device)| device.sync())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
resp_payload
|
||||
}
|
||||
|
||||
fn query(
|
||||
&self,
|
||||
payload: request::query::Payload,
|
||||
devices: &HashMap<&str, &mut dyn GoogleHomeDevice>,
|
||||
) -> query::Payload {
|
||||
let mut resp_payload = query::Payload::new();
|
||||
resp_payload.devices = payload
|
||||
.devices
|
||||
.into_iter()
|
||||
.map(|device| device.id)
|
||||
.map(|id| {
|
||||
let device = devices.get(id.as_str()).map_or_else(
|
||||
|| {
|
||||
let mut device = query::Device::new();
|
||||
device.set_offline();
|
||||
device.set_error(DeviceError::DeviceNotFound.into());
|
||||
|
||||
device
|
||||
},
|
||||
|device| device.query(),
|
||||
);
|
||||
|
||||
(id, device)
|
||||
})
|
||||
.collect();
|
||||
|
||||
resp_payload
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&self,
|
||||
payload: request::execute::Payload,
|
||||
devices: &mut HashMap<&str, &mut dyn GoogleHomeDevice>,
|
||||
) -> 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| {
|
||||
devices.get_mut(id.as_str()).map_or(
|
||||
(id.clone(), Err(DeviceError::DeviceNotFound.into())),
|
||||
|device| {
|
||||
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 {
|
||||
(id, Err(err))
|
||||
} else {
|
||||
(id, Ok(true))
|
||||
}
|
||||
},
|
||||
)
|
||||
})
|
||||
.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);
|
||||
let f = devices.iter().map(|(_, device)| async move {
|
||||
if let Some(device) = device.read().await.as_ref().cast() {
|
||||
Some(device.sync().await)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
|
||||
resp_payload.devices = join_all(f).await.into_iter().flatten().collect();
|
||||
resp_payload
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
device::{self, GoogleHomeDevice},
|
||||
errors::ErrorCode,
|
||||
request::Request,
|
||||
traits, types,
|
||||
};
|
||||
async fn query<T: AsGoogleHomeDevice + ?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().await
|
||||
} else {
|
||||
let mut device = query::Device::new();
|
||||
device.set_offline();
|
||||
device.set_error(DeviceError::DeviceNotFound.into());
|
||||
|
||||
#[derive(Debug)]
|
||||
struct TestOutlet {
|
||||
name: String,
|
||||
on: bool,
|
||||
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
|
||||
}
|
||||
|
||||
impl TestOutlet {
|
||||
fn new(name: &str) -> Self {
|
||||
Self {
|
||||
name: name.into(),
|
||||
on: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
async fn execute<T: AsGoogleHomeDevice + ?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()));
|
||||
|
||||
impl GoogleHomeDevice for TestOutlet {
|
||||
fn get_device_type(&self) -> types::Type {
|
||||
types::Type::Outlet
|
||||
}
|
||||
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: 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();
|
||||
|
||||
fn get_device_name(&self) -> device::Name {
|
||||
let mut name = device::Name::new("Nightstand");
|
||||
name.add_default_name("Outlet");
|
||||
name.add_nickname("Nightlight");
|
||||
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));
|
||||
}
|
||||
|
||||
name
|
||||
}
|
||||
// NOTE: We can not use .map here because async =(
|
||||
let mut results = Vec::new();
|
||||
for cmd in &execution {
|
||||
results.push(device.execute(cmd).await);
|
||||
}
|
||||
|
||||
fn get_id(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
// Convert vec of results to a result with a vec and the first
|
||||
// encountered error
|
||||
let results = results
|
||||
.into_iter()
|
||||
.collect::<Result<Vec<_>, ErrorCode>>();
|
||||
|
||||
fn is_online(&self) -> bool {
|
||||
true
|
||||
}
|
||||
// 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()))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
fn get_room_hint(&self) -> Option<&str> {
|
||||
Some("Bedroom")
|
||||
}
|
||||
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),
|
||||
};
|
||||
});
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
impl traits::OnOff for TestOutlet {
|
||||
fn is_on(&self) -> Result<bool, ErrorCode> {
|
||||
Ok(self.on)
|
||||
}
|
||||
join_all(f).await;
|
||||
|
||||
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().to_owned();
|
||||
devices.insert(&id, &mut nightstand);
|
||||
let id = lamp.get_id().to_owned();
|
||||
devices.insert(&id, &mut lamp);
|
||||
let id = scene.get_id().to_owned();
|
||||
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().to_owned();
|
||||
devices.insert(&id, &mut nightstand);
|
||||
let id = lamp.get_id().to_owned();
|
||||
devices.insert(&id, &mut lamp);
|
||||
let id = scene.get_id().to_owned();
|
||||
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().to_owned();
|
||||
devices.insert(&id, &mut nightstand);
|
||||
let id = lamp.get_id().to_owned();
|
||||
devices.insert(&id, &mut lamp);
|
||||
let id = scene.get_id().to_owned();
|
||||
devices.insert(&id, &mut scene);
|
||||
|
||||
let resp = gh.handle_request(req, &mut devices).unwrap();
|
||||
|
||||
let json = serde_json::to_string(&resp).unwrap();
|
||||
println!("{}", json)
|
||||
// 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)]
|
||||
// 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().to_owned();
|
||||
// devices.insert(&id, &mut nightstand);
|
||||
// let id = lamp.get_id().to_owned();
|
||||
// devices.insert(&id, &mut lamp);
|
||||
// let id = scene.get_id().to_owned();
|
||||
// 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().to_owned();
|
||||
// devices.insert(&id, &mut nightstand);
|
||||
// let id = lamp.get_id().to_owned();
|
||||
// devices.insert(&id, &mut lamp);
|
||||
// let id = scene.get_id().to_owned();
|
||||
// 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().to_owned();
|
||||
// devices.insert(&id, &mut nightstand);
|
||||
// let id = lamp.get_id().to_owned();
|
||||
// devices.insert(&id, &mut lamp);
|
||||
// let id = scene.get_id().to_owned();
|
||||
// devices.insert(&id, &mut scene);
|
||||
//
|
||||
// let resp = gh.handle_request(req, &mut devices).unwrap();
|
||||
//
|
||||
// let json = serde_json::to_string(&resp).unwrap();
|
||||
// println!("{}", json)
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#![allow(incomplete_features)]
|
||||
#![feature(specialization)]
|
||||
#![feature(let_chains)]
|
||||
pub mod device;
|
||||
mod fullfillment;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ pub struct Device {
|
||||
// customData
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, Clone, Copy)]
|
||||
#[serde(tag = "command", content = "params")]
|
||||
pub enum CommandType {
|
||||
#[serde(rename = "action.devices.commands.OnOff")]
|
||||
|
||||
@@ -28,7 +28,7 @@ pub enum ResponsePayload {
|
||||
Execute(execute::Payload),
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize)]
|
||||
#[derive(Debug, Default, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct State {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
|
||||
@@ -2,7 +2,7 @@ use serde::Serialize;
|
||||
|
||||
use crate::{errors::ErrorCode, response::State};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Payload {
|
||||
#[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")]
|
||||
pub struct Command {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -65,7 +65,7 @@ impl Command {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct States {
|
||||
pub online: bool,
|
||||
@@ -74,7 +74,7 @@ pub struct States {
|
||||
pub state: State,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[derive(Debug, Serialize, Clone)]
|
||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||
pub enum Status {
|
||||
Success,
|
||||
|
||||
Reference in New Issue
Block a user