ascom_alpaca/api/device_state/
mod.rs

1use std::time::SystemTime;
2
3#[cfg(feature = "server")]
4pub(crate) mod ser;
5
6#[cfg(feature = "client")]
7pub(crate) mod de;
8
9/// A wrapper for the device-specific state with the common optional timestamp field.
10#[derive(Default, Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
11#[cfg_attr(feature = "server", derive(serde::Serialize))]
12#[cfg_attr(feature = "client", derive(serde::Deserialize))]
13pub struct TimestampedDeviceState<T> {
14    /// The timestamp of the last update to the state, if available.
15    #[serde(
16        rename = "TimeStamp",
17        skip_serializing_if = "Option::is_none",
18        with = "timestamp"
19    )]
20    pub timestamp: Option<SystemTime>,
21    /// The device-specific state.
22    #[deref]
23    #[deref_mut]
24    #[serde(flatten)]
25    pub state: T,
26}
27
28impl<T> TimestampedDeviceState<T> {
29    /// Create a new `TimestampedDeviceState` with the given state and the current timestamp.
30    pub fn new(state: T) -> Self {
31        Self {
32            timestamp: Some(SystemTime::now()),
33            state,
34        }
35    }
36}
37
38mod timestamp {
39    use crate::api::time_repr::{Iso8601, TimeRepr};
40    use std::time::SystemTime;
41
42    #[cfg(feature = "server")]
43    use serde::{Serialize, Serializer};
44
45    #[cfg(feature = "client")]
46    use serde::{Deserialize, Deserializer};
47
48    #[cfg(feature = "server")]
49    #[allow(clippy::ref_option)]
50    pub(super) fn serialize<S: Serializer>(
51        timestamp: &Option<SystemTime>,
52        serializer: S,
53    ) -> Result<S::Ok, S::Error> {
54        TimeRepr::<Iso8601>::from(timestamp.unwrap_or_else(|| unreachable!())).serialize(serializer)
55    }
56
57    #[cfg(feature = "client")]
58    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
59        deserializer: D,
60    ) -> Result<Option<SystemTime>, D::Error> {
61        let timestamp = Option::<TimeRepr<Iso8601>>::deserialize(deserializer)?;
62        Ok(timestamp.map(SystemTime::from))
63    }
64}