Improved impl_cast and made all traits Sync + Send + 'static
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-04-10 23:51:22 +02:00
parent 65f76904dd
commit b54c9512b9
9 changed files with 77 additions and 66 deletions

View File

@@ -4,11 +4,11 @@ use crate::{
errors::{DeviceError, ErrorCode},
request::execute::CommandType,
response,
traits::{AsOnOff, AsScene, Trait},
traits::{As, OnOff, Scene, Trait},
types::Type,
};
pub trait GoogleHomeDevice: AsOnOff + AsScene {
pub trait GoogleHomeDevice: As<dyn OnOff> + As<dyn Scene> + 'static {
fn get_device_type(&self) -> Type;
fn get_device_name(&self) -> Name;
fn get_id(&self) -> &str;
@@ -40,14 +40,14 @@ pub trait GoogleHomeDevice: AsOnOff + AsScene {
let mut traits = Vec::new();
// OnOff
if let Some(on_off) = AsOnOff::cast(self) {
if let Some(on_off) = As::<dyn OnOff>::cast(self) {
traits.push(Trait::OnOff);
device.attributes.command_only_on_off = on_off.is_command_only();
device.attributes.query_only_on_off = on_off.is_query_only();
}
// Scene
if let Some(scene) = AsScene::cast(self) {
if let Some(scene) = As::<dyn Scene>::cast(self) {
traits.push(Trait::Scene);
device.attributes.scene_reversible = scene.is_scene_reversible();
}
@@ -64,7 +64,7 @@ pub trait GoogleHomeDevice: AsOnOff + AsScene {
}
// OnOff
if let Some(on_off) = AsOnOff::cast(self) {
if let Some(on_off) = As::<dyn OnOff>::cast(self) {
device.state.on = on_off.is_on().map_err(|err| device.set_error(err)).ok();
}
@@ -74,13 +74,13 @@ pub trait GoogleHomeDevice: AsOnOff + AsScene {
fn execute(&mut self, command: &CommandType) -> Result<(), ErrorCode> {
match command {
CommandType::OnOff { on } => {
let on_off = AsOnOff::cast_mut(self)
let on_off = As::<dyn OnOff>::cast_mut(self)
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
on_off.set_on(*on)?;
}
CommandType::ActivateScene { deactivate } => {
let scene = AsScene::cast_mut(self)
let scene = As::<dyn Scene>::cast_mut(self)
.ok_or::<ErrorCode>(DeviceError::ActionNotAvailable.into())?;
scene.set_active(!deactivate)?;

View File

@@ -10,7 +10,11 @@ pub enum Trait {
Scene,
}
pub trait OnOff: std::fmt::Debug {
impl_cast::impl_setup!();
impl_cast::impl_cast!(GoogleHomeDevice, OnOff);
impl_cast::impl_cast!(GoogleHomeDevice, Scene);
pub trait OnOff: std::fmt::Debug + Sync + Send + 'static {
fn is_command_only(&self) -> Option<bool> {
None
}
@@ -23,13 +27,11 @@ pub trait OnOff: std::fmt::Debug {
fn is_on(&self) -> Result<bool, ErrorCode>;
fn set_on(&mut self, on: bool) -> Result<(), ErrorCode>;
}
impl_cast::impl_cast!(GoogleHomeDevice, OnOff);
pub trait Scene: std::fmt::Debug {
pub trait Scene: std::fmt::Debug + Sync + Send + 'static {
fn is_scene_reversible(&self) -> Option<bool> {
None
}
fn set_active(&self, activate: bool) -> Result<(), ErrorCode>;
}
impl_cast::impl_cast!(GoogleHomeDevice, Scene);