chore: address some clippy concerns

This commit is contained in:
J / Jacob Babich
2026-07-15 00:32:04 -04:00
parent 224ee7732f
commit 8ab8dd3441
15 changed files with 93 additions and 93 deletions

View File

@@ -186,8 +186,7 @@ async fn send_request<
let incoming_length = reader.read_u32().await.context(ReadSnafu)?; let incoming_length = reader.read_u32().await.context(ReadSnafu)?;
tracing::info!(?incoming_length); tracing::info!(?incoming_length);
let mut incoming_message = Vec::new(); let mut incoming_message = vec![0; incoming_length as usize];
incoming_message.resize(incoming_length as usize, 0);
reader reader
.read_exact(&mut incoming_message) .read_exact(&mut incoming_message)
.await .await

View File

@@ -178,7 +178,7 @@ impl<'de> Deserialize<'de> for MaybeKelvin {
match u16::deserialize(deserializer)? { match u16::deserialize(deserializer)? {
0 => Ok(MaybeKelvin(None)), 0 => Ok(MaybeKelvin(None)),
value => { value => {
let kelvin = Kelvin::try_from(value).map_err(|e| { let kelvin = Kelvin::try_from(value).map_err(|_e| {
serde::de::Error::custom(format!( serde::de::Error::custom(format!(
"{value} is not in the range {}..{}", "{value} is not in the range {}..{}",
Kelvin::MIN, Kelvin::MIN,

View File

@@ -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<Event> {
pub id: Id,
pub user_id: Option<String>,
pub parent_id: Option<String>,
/// In order to prevent cycles, the user must decide to pass [`Py<PyAny>`] 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<Event> {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
static HOMEASSISTANT_CORE: OnceCell<Py<PyModule>> = 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::<PyType>()?;
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)
}
}

View File

@@ -4,38 +4,38 @@ use python_utils::{FromPyFromStr, ToStrToPy};
use ulid::Ulid; use ulid::Ulid;
#[derive(Debug, Clone, FromPyFromStr, ToStrToPy)] #[derive(Debug, Clone, FromPyFromStr, ToStrToPy)]
pub enum Id { pub enum ContextId {
Ulid(Ulid), Ulid(Ulid),
Other(Arc<str>), Other(Arc<str>),
} }
impl From<String> for Id { impl From<String> for ContextId {
fn from(s: String) -> Self { fn from(s: String) -> Self {
if let Ok(ulid) = s.parse() { if let Ok(ulid) = s.parse() {
Id::Ulid(ulid) ContextId::Ulid(ulid)
} else { } else {
Id::Other(s.into()) ContextId::Other(s.into())
} }
} }
} }
impl FromStr for Id { impl FromStr for ContextId {
type Err = Infallible; type Err = Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(ulid) = s.parse() { if let Ok(ulid) = s.parse() {
Ok(Id::Ulid(ulid)) Ok(ContextId::Ulid(ulid))
} else { } 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 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
Id::Ulid(ulid) => write!(f, "{ulid}"), ContextId::Ulid(ulid) => write!(f, "{ulid}"),
Id::Other(other) => write!(f, "{other}"), ContextId::Other(other) => write!(f, "{other}"),
} }
} }
} }

View File

@@ -1,2 +1,44 @@
pub mod context; use once_cell::sync::OnceCell;
pub mod id; 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<Event> {
pub id: ContextId,
pub user_id: Option<String>,
pub parent_id: Option<String>,
/// In order to prevent cycles, the user must decide to pass [`Py<PyAny>`] 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<Event> {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
static HOMEASSISTANT_CORE: OnceCell<Py<PyModule>> = 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::<PyType>()?;
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)
}
}

View File

@@ -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<Type, Data, Context> {
pub event_type: Type,
pub data: Data,
pub origin: EventOrigin,
/// In order to prevent cycles, the user must decide to pass [`Py<PyAny>`] for the `Context` type here
/// or for the `Event` type in [`Context`]
pub context: Context,
time_fired_timestamp: f64,
}
impl<Type, Data, Context> Event<Type, Data, Context> {
pub fn time_fired(&self) -> Option<DateTime<Utc>> {
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)
}
}

View File

@@ -1,4 +1,31 @@
pub mod context; pub mod context;
pub mod event;
pub mod event_origin; pub mod event_origin;
pub mod specific; 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<Type, Data, Context> {
pub event_type: Type,
pub data: Data,
pub origin: EventOrigin,
/// In order to prevent cycles, the user must decide to pass [`Py<PyAny>`] for the `Context` type here
/// or for the `Event` type in [`Context`]
pub context: Context,
time_fired_timestamp: f64,
}
impl<Type, Data, Context> Event<Type, Data, Context> {
pub fn time_fired(&self) -> Option<DateTime<Utc>> {
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)
}
}

View File

@@ -32,7 +32,7 @@ pub type Event<
NewAttributes, NewAttributes,
NewStateContextEvent, NewStateContextEvent,
Context, Context,
> = super::super::event::Event< > = super::super::Event<
Type, Type,
Data< Data<
OldState, OldState,

View File

@@ -57,7 +57,7 @@ pub fn signal<'py>(
.map(|state_object_arc_result_option| { .map(|state_object_arc_result_option| {
state_object_arc_result_option.map(|state_object_arc_result| { state_object_arc_result_option.map(|state_object_arc_result| {
Arc::new( Arc::new(
(&*state_object_arc_result) (*state_object_arc_result)
.as_ref() .as_ref()
.map(|state_object| state_object.state.clone()) .map(|state_object| state_object.state.clone())
.map_err(|e| e.clone()), .map_err(|e| e.clone()),

View File

@@ -3,7 +3,7 @@ use super::{GetStateObjectError, HomeAssistantLight};
use crate::home_assistant::GetServicesError; use crate::home_assistant::GetServicesError;
use crate::service_registry::CallServiceError; use crate::service_registry::CallServiceError;
use crate::{ use crate::{
event::context::context::Context, event::context::Context,
state::{ErrorState, HomeAssistantState, UnexpectedState}, state::{ErrorState, HomeAssistantState, UnexpectedState},
}; };
use protocol::light::{GetState, SetState}; use protocol::light::{GetState, SetState};

View File

@@ -1,4 +1,4 @@
use super::{event::context::context::Context, service::IntoServiceCall}; use super::{event::context::Context, service::IntoServiceCall};
use pyo3::{ use pyo3::{
conversion::FromPyObjectOwned, conversion::FromPyObjectOwned,
exceptions::{PyException, PyTypeError}, exceptions::{PyException, PyTypeError},

View File

@@ -53,6 +53,7 @@ impl StateMachine {
.call_method1(py, "get", args) .call_method1(py, "get", args)
.map_err(Arc::new) .map_err(Arc::new)
.context(GetStateObjectSnafu)?; .context(GetStateObjectSnafu)?;
Ok(state.extract(py).context(ExtractStateObjectSnafu)?)
state.extract(py).context(ExtractStateObjectSnafu)
} }
} }

View File

@@ -1,5 +1,5 @@
use super::{ use super::{
event::{context::context::Context, specific::state_changed}, event::{context::Context, specific::state_changed},
home_assistant::HomeAssistant, home_assistant::HomeAssistant,
}; };
use crate::{entity_id::EntityId, home_assistant::GetStatesError, state_machine::GetStateError}; use crate::{entity_id::EntityId, home_assistant::GetStatesError, state_machine::GetStateError};

View File

@@ -85,5 +85,5 @@ pub fn validate_type_by_name(
}); });
} }
return Ok(()); Ok(())
} }

View File

@@ -15,7 +15,7 @@ where
{ {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let Self { actual, expected } = self; 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:?}") write!(f, "expected {expected_str:?} but got {actual:?}")
} }