diff --git a/driver/kasa/src/connection.rs b/driver/kasa/src/connection.rs index 159d3fd..7c1afee 100644 --- a/driver/kasa/src/connection.rs +++ b/driver/kasa/src/connection.rs @@ -186,8 +186,7 @@ async fn send_request< let incoming_length = reader.read_u32().await.context(ReadSnafu)?; tracing::info!(?incoming_length); - let mut incoming_message = Vec::new(); - incoming_message.resize(incoming_length as usize, 0); + let mut incoming_message = vec![0; incoming_length as usize]; reader .read_exact(&mut incoming_message) .await diff --git a/driver/kasa/src/messages.rs b/driver/kasa/src/messages.rs index 53a25d1..8b7f2aa 100644 --- a/driver/kasa/src/messages.rs +++ b/driver/kasa/src/messages.rs @@ -178,7 +178,7 @@ impl<'de> Deserialize<'de> for MaybeKelvin { match u16::deserialize(deserializer)? { 0 => Ok(MaybeKelvin(None)), value => { - let kelvin = Kelvin::try_from(value).map_err(|e| { + let kelvin = Kelvin::try_from(value).map_err(|_e| { serde::de::Error::custom(format!( "{value} is not in the range {}..{}", Kelvin::MIN, diff --git a/home-assistant/src/event/context/context.rs b/home-assistant/src/event/context/context.rs deleted file mode 100644 index 593052c..0000000 --- a/home-assistant/src/event/context/context.rs +++ /dev/null @@ -1,42 +0,0 @@ -use super::id::Id; -use once_cell::sync::OnceCell; -use pyo3::{ - types::{PyAnyMethods, PyModule, PyType}, - Bound, FromPyObject, IntoPyObject, Py, PyAny, PyErr, Python, -}; - -/// The context that triggered something. -#[derive(Debug, FromPyObject)] -pub struct Context { - pub id: Id, - pub user_id: Option, - pub parent_id: Option, - /// In order to prevent cycles, the user must decide to pass [`Py`] for the `Event` type here - /// or for the `Context` type in [`Event`] - pub origin_event: Event, -} - -impl<'py, Event: IntoPyObject<'py>> IntoPyObject<'py> for Context { - type Target = PyAny; - - type Output = Bound<'py, Self::Target>; - - type Error = PyErr; - - fn into_pyobject(self, py: Python<'py>) -> Result { - static HOMEASSISTANT_CORE: OnceCell> = OnceCell::new(); - - let homeassistant_core = HOMEASSISTANT_CORE - .get_or_try_init(|| Result::<_, PyErr>::Ok(py.import("homeassistant.core")?.unbind()))? - .bind(py); - - let context_class = homeassistant_core.getattr("Context")?; - let context_class = context_class.cast_into::()?; - - let context_instance = context_class.call1((self.user_id, self.parent_id, self.id))?; - - context_instance.setattr("origin_event", self.origin_event)?; - - Ok(context_instance) - } -} diff --git a/home-assistant/src/event/context/id.rs b/home-assistant/src/event/context/context_id.rs similarity index 60% rename from home-assistant/src/event/context/id.rs rename to home-assistant/src/event/context/context_id.rs index f7d0168..b9ce1bd 100644 --- a/home-assistant/src/event/context/id.rs +++ b/home-assistant/src/event/context/context_id.rs @@ -4,38 +4,38 @@ use python_utils::{FromPyFromStr, ToStrToPy}; use ulid::Ulid; #[derive(Debug, Clone, FromPyFromStr, ToStrToPy)] -pub enum Id { +pub enum ContextId { Ulid(Ulid), Other(Arc), } -impl From for Id { +impl From for ContextId { fn from(s: String) -> Self { if let Ok(ulid) = s.parse() { - Id::Ulid(ulid) + ContextId::Ulid(ulid) } else { - Id::Other(s.into()) + ContextId::Other(s.into()) } } } -impl FromStr for Id { +impl FromStr for ContextId { type Err = Infallible; fn from_str(s: &str) -> Result { if let Ok(ulid) = s.parse() { - Ok(Id::Ulid(ulid)) + Ok(ContextId::Ulid(ulid)) } else { - Ok(Id::Other(s.into())) + Ok(ContextId::Other(s.into())) } } } -impl Display for Id { +impl Display for ContextId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Id::Ulid(ulid) => write!(f, "{ulid}"), - Id::Other(other) => write!(f, "{other}"), + ContextId::Ulid(ulid) => write!(f, "{ulid}"), + ContextId::Other(other) => write!(f, "{other}"), } } } diff --git a/home-assistant/src/event/context/mod.rs b/home-assistant/src/event/context/mod.rs index 23cc631..c234765 100644 --- a/home-assistant/src/event/context/mod.rs +++ b/home-assistant/src/event/context/mod.rs @@ -1,2 +1,44 @@ -pub mod context; -pub mod id; +use once_cell::sync::OnceCell; +use pyo3::{ + types::{PyAnyMethods, PyModule, PyType}, + Bound, FromPyObject, IntoPyObject, Py, PyAny, PyErr, Python, +}; + +mod context_id; +pub use context_id::ContextId; + +/// The context that triggered something. +#[derive(Debug, FromPyObject)] +pub struct Context { + pub id: ContextId, + pub user_id: Option, + pub parent_id: Option, + /// In order to prevent cycles, the user must decide to pass [`Py`] for the `Event` type here + /// or for the `Context` type in [`Event`] + pub origin_event: Event, +} + +impl<'py, Event: IntoPyObject<'py>> IntoPyObject<'py> for Context { + type Target = PyAny; + + type Output = Bound<'py, Self::Target>; + + type Error = PyErr; + + fn into_pyobject(self, py: Python<'py>) -> Result { + static HOMEASSISTANT_CORE: OnceCell> = OnceCell::new(); + + let homeassistant_core = HOMEASSISTANT_CORE + .get_or_try_init(|| Result::<_, PyErr>::Ok(py.import("homeassistant.core")?.unbind()))? + .bind(py); + + let context_class = homeassistant_core.getattr("Context")?; + let context_class = context_class.cast_into::()?; + + let context_instance = context_class.call1((self.user_id, self.parent_id, self.id))?; + + context_instance.setattr("origin_event", self.origin_event)?; + + Ok(context_instance) + } +} diff --git a/home-assistant/src/event/event.rs b/home-assistant/src/event/event.rs deleted file mode 100644 index a3ed3ae..0000000 --- a/home-assistant/src/event/event.rs +++ /dev/null @@ -1,27 +0,0 @@ -use chrono::{DateTime, Utc}; -use pyo3::FromPyObject; - -use super::event_origin::EventOrigin; - -/// Representation of an event within the bus. -#[derive(Debug, FromPyObject)] -pub struct Event { - pub event_type: Type, - pub data: Data, - pub origin: EventOrigin, - /// In order to prevent cycles, the user must decide to pass [`Py`] for the `Context` type here - /// or for the `Event` type in [`Context`] - pub context: Context, - time_fired_timestamp: f64, -} - -impl Event { - pub fn time_fired(&self) -> Option> { - const NANOS_PER_SEC: i32 = 1_000_000_000; - - let secs = self.time_fired_timestamp as i64; - let nsecs = (self.time_fired_timestamp.fract() * (NANOS_PER_SEC as f64)) as u32; - - DateTime::from_timestamp(secs, nsecs) - } -} diff --git a/home-assistant/src/event/mod.rs b/home-assistant/src/event/mod.rs index da586ea..b390405 100644 --- a/home-assistant/src/event/mod.rs +++ b/home-assistant/src/event/mod.rs @@ -1,4 +1,31 @@ pub mod context; -pub mod event; pub mod event_origin; pub mod specific; + +use chrono::{DateTime, Utc}; +use pyo3::FromPyObject; + +pub use event_origin::{EventOrigin, ExtractEventOriginError}; + +/// Representation of an event within the bus. +#[derive(Debug, FromPyObject)] +pub struct Event { + pub event_type: Type, + pub data: Data, + pub origin: EventOrigin, + /// In order to prevent cycles, the user must decide to pass [`Py`] for the `Context` type here + /// or for the `Event` type in [`Context`] + pub context: Context, + time_fired_timestamp: f64, +} + +impl Event { + pub fn time_fired(&self) -> Option> { + const NANOS_PER_SEC: i32 = 1_000_000_000; + + let secs = self.time_fired_timestamp as i64; + let nsecs = (self.time_fired_timestamp.fract() * (NANOS_PER_SEC as f64)) as u32; + + DateTime::from_timestamp(secs, nsecs) + } +} diff --git a/home-assistant/src/event/specific/state_changed.rs b/home-assistant/src/event/specific/state_changed.rs index 392d020..5096e93 100644 --- a/home-assistant/src/event/specific/state_changed.rs +++ b/home-assistant/src/event/specific/state_changed.rs @@ -32,7 +32,7 @@ pub type Event< NewAttributes, NewStateContextEvent, Context, -> = super::super::event::Event< +> = super::super::Event< Type, Data< OldState, diff --git a/home-assistant/src/input_number/mod.rs b/home-assistant/src/input_number/mod.rs index 5090d76..a85fea9 100644 --- a/home-assistant/src/input_number/mod.rs +++ b/home-assistant/src/input_number/mod.rs @@ -57,7 +57,7 @@ pub fn signal<'py>( .map(|state_object_arc_result_option| { state_object_arc_result_option.map(|state_object_arc_result| { Arc::new( - (&*state_object_arc_result) + (*state_object_arc_result) .as_ref() .map(|state_object| state_object.state.clone()) .map_err(|e| e.clone()), diff --git a/home-assistant/src/light/protocol.rs b/home-assistant/src/light/protocol.rs index 2c8a150..4eb06f5 100644 --- a/home-assistant/src/light/protocol.rs +++ b/home-assistant/src/light/protocol.rs @@ -3,7 +3,7 @@ use super::{GetStateObjectError, HomeAssistantLight}; use crate::home_assistant::GetServicesError; use crate::service_registry::CallServiceError; use crate::{ - event::context::context::Context, + event::context::Context, state::{ErrorState, HomeAssistantState, UnexpectedState}, }; use protocol::light::{GetState, SetState}; diff --git a/home-assistant/src/service_registry.rs b/home-assistant/src/service_registry.rs index 5b4ba20..aa37207 100644 --- a/home-assistant/src/service_registry.rs +++ b/home-assistant/src/service_registry.rs @@ -1,4 +1,4 @@ -use super::{event::context::context::Context, service::IntoServiceCall}; +use super::{event::context::Context, service::IntoServiceCall}; use pyo3::{ conversion::FromPyObjectOwned, exceptions::{PyException, PyTypeError}, diff --git a/home-assistant/src/state_machine.rs b/home-assistant/src/state_machine.rs index 87c6fb7..7f23a4c 100644 --- a/home-assistant/src/state_machine.rs +++ b/home-assistant/src/state_machine.rs @@ -53,6 +53,7 @@ impl StateMachine { .call_method1(py, "get", args) .map_err(Arc::new) .context(GetStateObjectSnafu)?; - Ok(state.extract(py).context(ExtractStateObjectSnafu)?) + + state.extract(py).context(ExtractStateObjectSnafu) } } diff --git a/home-assistant/src/state_object.rs b/home-assistant/src/state_object.rs index ddb36a3..ad45e80 100644 --- a/home-assistant/src/state_object.rs +++ b/home-assistant/src/state_object.rs @@ -1,5 +1,5 @@ use super::{ - event::{context::context::Context, specific::state_changed}, + event::{context::Context, specific::state_changed}, home_assistant::HomeAssistant, }; use crate::{entity_id::EntityId, home_assistant::GetStatesError, state_machine::GetStateError}; diff --git a/python-utils/src/lib.rs b/python-utils/src/lib.rs index a291666..e1c0475 100644 --- a/python-utils/src/lib.rs +++ b/python-utils/src/lib.rs @@ -85,5 +85,5 @@ pub fn validate_type_by_name( }); } - return Ok(()); + Ok(()) } diff --git a/string-literal/src/lib.rs b/string-literal/src/lib.rs index fa9b2b3..b7d29ad 100644 --- a/string-literal/src/lib.rs +++ b/string-literal/src/lib.rs @@ -15,7 +15,7 @@ where { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { actual, expected } = self; - let expected_str = <&'static str>::from(&expected); + let expected_str = <&'static str>::from(expected); write!(f, "expected {expected_str:?} but got {actual:?}") }