1mod backend;
9mod device;
10mod observations;
11
12pub use backend::{Backend, BackendEvent};
13pub use device::{DeviceEvent, InstalledCertificate, LocalDevice, Outcome};
14use serde::{Deserialize, Serialize};
15
16use crate::wire::{Control, Message, Payload, Power, State, WireError};
17
18#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
20pub struct Clock {
21 pub unix_seconds: i64,
23 pub elapsed_seconds: u64,
25}
26
27impl Clock {
28 pub const fn new(unix_seconds: i64, elapsed_seconds: u64) -> Self {
30 Self {
31 unix_seconds,
32 elapsed_seconds,
33 }
34 }
35}
36
37#[derive(Debug, thiserror::Error)]
39pub enum EngineError {
40 #[error("publication does not match the engine route")]
42 Route,
43 #[error("unexpected message type or relation")]
45 Unexpected,
46 #[error("a conflicting request is already in flight")]
48 Busy,
49 #[error("engine capacity exhausted")]
51 Capacity,
52 #[error("request ID reused with different content")]
54 IdConflict,
55 #[error("equipment outcome requires reconciliation")]
57 ReconciliationRequired,
58 #[error("clock regressed or deadline cannot be represented")]
60 Clock,
61 #[error("invalid device checkpoint")]
63 Checkpoint,
64 #[error("a verified trust readback is required")]
66 TrustReadback,
67 #[error("pairing result does not match the active trust replacement")]
69 PairingMismatch,
70 #[error("accumulated settings cannot be expressed in one legal control reply")]
72 DesiredState,
73 #[error(transparent)]
75 Wire(#[from] WireError),
76}
77
78fn checked(message: Message) -> Result<Message, EngineError> {
79 message.encode()?;
80 Ok(message)
81}
82
83fn families(c: &Control) -> [bool; 4] {
84 [
85 c.limits.is_some(),
86 c.failsafes.is_some(),
87 c.trust.is_some(),
88 c.notify.is_some(),
89 ]
90}
91
92fn conflicts(a: &Control, b: &Control) -> bool {
93 families(a)
94 .into_iter()
95 .zip(families(b))
96 .any(|(a, b)| a && b)
97}
98
99fn merge_power<T: Clone>(current: &mut Option<Power<T>>, patch: &Option<Power<T>>) {
100 if let Some(patch) = patch {
101 let slot = current.get_or_insert_with(|| Power {
102 consumption: None,
103 production: None,
104 });
105 if patch.consumption.is_some() {
106 slot.consumption.clone_from(&patch.consumption);
107 }
108 if patch.production.is_some() {
109 slot.production.clone_from(&patch.production);
110 }
111 }
112}
113
114#[derive(Default, Serialize, Deserialize)]
116struct Deadlines([Option<u64>; 2]);
117
118impl Deadlines {
119 fn update(&mut self, c: &Control, received_at: u64) -> Result<(), EngineError> {
120 if let Some(power) = &c.limits {
121 for (slot, limit) in self
122 .0
123 .iter_mut()
124 .zip([&power.consumption, &power.production])
125 {
126 if let Some(limit) = limit {
127 *slot = limit
128 .duration
129 .map(|d| {
130 received_at
131 .checked_add(u64::from(d))
132 .ok_or(EngineError::Clock)
133 })
134 .transpose()?;
135 }
136 }
137 }
138 Ok(())
139 }
140
141 fn apply(&self, power: &mut Option<Power<crate::wire::Limit>>, now: u64) {
142 if let Some(power) = power {
143 for (slot, limit) in self
144 .0
145 .iter()
146 .zip([&mut power.consumption, &mut power.production])
147 {
148 if let (Some(expires), Some(limit)) = (slot, limit) {
149 let left = expires.saturating_sub(now);
150 if left == 0 {
151 limit.active = false;
152 limit.duration = None;
153 } else {
154 limit.duration = Some(u32::try_from(left).unwrap_or(u32::MAX));
155 }
156 }
157 }
158 }
159 }
160}
161
162const FIELDS: [&str; 6] = [
163 "limits",
164 "failsafes",
165 "trust",
166 "notify",
167 "measurements",
168 "supportedEebusUseCases",
169];
170
171fn filter_state(mut state: State, fields: &[String]) -> State {
172 if !fields.is_empty() {
173 for field in FIELDS {
174 if !fields.iter().any(|f| f == field) {
175 clear_field(&mut state, field);
176 }
177 }
178 }
179 state
180}
181
182fn clear_field(state: &mut State, field: &str) {
183 match field {
184 "limits" => state.limits = None,
185 "failsafes" => state.failsafes = None,
186 "trust" => state.trust = None,
187 "notify" => state.notify = None,
188 "measurements" => state.measurements = None,
189 "supportedEebusUseCases" => state.supported_eebus_use_cases = None,
190 _ => {}
191 }
192}
193
194fn ack(source: &str, relation: &str, error_number: u64) -> Result<Message, EngineError> {
195 checked(
196 Message::new(
197 relation,
198 source,
199 Payload::Ack(crate::wire::Ack { error_number }),
200 )
201 .related_to(relation),
202 )
203}