Skip to main content

cls_eedi/
eebus.rs

1//! Integrate CLS.EEDI controls and metering with an authenticated EEBUS peer.
2//!
3//! Use [`meter_snapshot`] to project complete MGCP or MPC reads. Use
4//! [`crate::metering::controllable_total_power`] to combine signed watt readings
5//! from the provisioned fleet. [`LimitAdapter`] handles LPC and LPP writes.
6//!
7//! Establish the binding and drain earlier session events. Read the complete limit
8//! descriptions and current limit list. The host correlates each incoming reply
9//! by peer endpoints and read counter, leaving both reply events on the guard
10//! engine for [`LimitAdapter::new`]. Forward the prepared datagram promptly. The SPINE time
11//! period starts at equipment receipt. Retain unrelated incoming traffic for the
12//! application and deliver only this session's responses here. After receiving
13//! completion, reclaim the engine with `into_engine` and process buffered traffic
14//! (including discovery and binding changes) before constructing the next adapter.
15//!
16//! ```
17//! use cls_eedi::eebus::{AdapterError, LimitAdapter};
18//! use cls_eedi::engine::Clock;
19//! use eebus::model::Datagram;
20//!
21//! fn exchange(adapter: &mut LimitAdapter<'_>, id: &str, now: Clock,
22//!             transport: impl FnOnce(Datagram) -> Datagram) -> Result<(), AdapterError> {
23//!     adapter.dispatch(id, now)?;
24//!     let packet = adapter.poll_transmit().expect("dispatched write");
25//!     let response = transport(packet);
26//!     let completion = adapter.handle_datagram(&response, now)?;
27//!     // Persist completed state before publishing completion.acknowledgement.
28//!     assert!(completion.is_some());
29//!     Ok(())
30//! }
31//! ```
32
33use std::time::Duration;
34
35use ::eebus::codec::ElementTag;
36use ::eebus::model::*;
37use ::eebus::spine::{Engine, SpineEvent, DEFAULT_MAX_RESPONSE_DELAY};
38use ::eebus::usecases::limitation::{resolve_writable_limit, Direction, LimitResolutionError};
39
40use crate::engine::{Clock, EngineError, LocalDevice, Outcome};
41use crate::wire::{Control, Limit, Message};
42
43/// Reason a write or a session handoff could not proceed.
44#[derive(Debug, thiserror::Error)]
45pub enum AdapterError {
46    #[error("fully qualified, distinct peer endpoints and a local client feature are required")]
47    Endpoint,
48    #[error("drain outstanding operations, datagrams and unrelated events before handing over the SPINE engine")]
49    SessionBusy,
50    #[error("the local client does not hold the required remote binding")]
51    Binding,
52    #[error("two fresh full limit-list replies from the selected feature are required")]
53    Snapshot,
54    #[error(transparent)]
55    Limit(#[from] LimitResolutionError),
56    #[error("one directional limit is required")]
57    UnsupportedControl,
58    #[error("a SPINE write is outstanding; reconcile the local operation if the session closes")]
59    Outstanding,
60    #[error("this exchange completed; return the engine and process session updates")]
61    Completed,
62    #[error("the queued limit expired before dispatch; complete it as rejected")]
63    Expired,
64    #[error(transparent)]
65    Local(#[from] EngineError),
66}
67
68/// A verified result and the corresponding local protocol transition.
69pub struct Completion {
70    pub request_id: String,
71    /// Absent for related controls.
72    pub acknowledgement: Option<Message>,
73    /// Original SPINE result for diagnostics.
74    pub error: ErrorNumber,
75}
76
77struct Pending {
78    id: String,
79    counter: MsgCounter,
80    sent: bool,
81    result: Option<ErrorNumber>,
82}
83
84/// Exclusively owns the guard engine while a limit may be retried by that engine.
85/// Drop on timeout or disconnect. This discards queued frames and retransmission
86/// timers. The local journal retains the consumed dispatch for reconciliation.
87pub struct LimitAdapter<'a> {
88    local: &'a mut LocalDevice,
89    engine: Engine,
90    client: FeatureAddress,
91    server: FeatureAddress,
92    descriptions: LoadControlLimitDescriptionListData,
93    current: LoadControlLimitListData,
94    pending: Option<Pending>,
95    completed: bool,
96}
97
98impl<'a> LimitAdapter<'a> {
99    /// Bind a SPINE engine holding exactly two complete LoadControl read replies
100    /// (descriptions and current limits) to one authenticated session and route. On
101    /// construction failure the supplied SPINE engine is discarded.
102    pub fn new(
103        local: &'a mut LocalDevice,
104        mut engine: Engine,
105        client: FeatureAddress,
106        server: FeatureAddress,
107    ) -> Result<Self, AdapterError> {
108        if client.device.as_ref() != Some(engine.device().address())
109            || server.device.is_none()
110            || server.device == client.device
111            || client.entity.as_ref().is_none_or(Vec::is_empty)
112            || server.entity.as_ref().is_none_or(Vec::is_empty)
113            || server.feature.is_none()
114            || !engine
115                .device()
116                .resolve(&client)
117                .is_some_and(|f| f.role() == Role::Client)
118        {
119            return Err(AdapterError::Endpoint);
120        }
121        if engine.poll_timeout().is_some() || engine.poll_transmit().is_some() {
122            return Err(AdapterError::SessionBusy);
123        }
124        let mut descriptions = None;
125        let mut current = None;
126        while let Some(event) = engine.poll_event() {
127            let SpineEvent::ReplyReceived {
128                feature,
129                data,
130                is_partial,
131                ..
132            } = event
133            else {
134                return Err(AdapterError::SessionBusy);
135            };
136            if feature != server || is_partial {
137                return Err(AdapterError::Snapshot);
138            }
139            match data {
140                CmdData::LoadControlLimitDescriptionListData(list) if descriptions.is_none() => {
141                    descriptions = Some(list)
142                }
143                CmdData::LoadControlLimitListData(list) if current.is_none() => {
144                    current = Some(list)
145                }
146                _ => return Err(AdapterError::Snapshot),
147            }
148        }
149        Ok(Self {
150            local,
151            engine,
152            client,
153            server,
154            descriptions: descriptions.ok_or(AdapterError::Snapshot)?,
155            current: current.ok_or(AdapterError::Snapshot)?,
156            pending: None,
157            completed: false,
158        })
159    }
160
161    /// Queue one authorized write with its current remaining duration. Discovery
162    /// and binding errors leave the one-shot dispatch authorization available.
163    pub fn dispatch(&mut self, request_id: &str, now: Clock) -> Result<MsgCounter, AdapterError> {
164        if self.completed {
165            return Err(AdapterError::Completed);
166        }
167        if self.pending.is_some() {
168            return Err(AdapterError::Outstanding);
169        }
170        if !self
171            .engine
172            .relations()
173            .holds_binding(&self.client, &self.server)
174        {
175            return Err(AdapterError::Binding);
176        }
177        let (_, control) = self
178            .local
179            .pending()
180            .find(|(id, _)| *id == request_id)
181            .ok_or(EngineError::Unexpected)?;
182        let (direction, _) = directional(control)?;
183        let limit_id = resolve_writable_limit(&self.descriptions, &self.current, direction)?;
184        let elapsed = Duration::from_secs(now.elapsed_seconds);
185        let delay = self
186            .server
187            .device
188            .as_ref()
189            .and_then(|d| self.engine.peer(d))
190            .and_then(|p| p.feature_at(&self.server))
191            .and_then(|f| f.max_response_delay)
192            .unwrap_or(DEFAULT_MAX_RESPONSE_DELAY);
193        elapsed.checked_add(delay).ok_or(EngineError::Clock)?;
194        let control = self
195            .local
196            .control_for_dispatch(request_id, now)?
197            .ok_or(AdapterError::Expired)?;
198        let (_, limit) = directional(&control)?;
199        let (data, filters) = write(limit_id, direction, limit);
200        let counter =
201            self.engine
202                .write_filtered(&self.server, &self.client, data, filters, elapsed);
203        self.pending = Some(Pending {
204            id: request_id.into(),
205            counter,
206            sent: false,
207            result: None,
208        });
209        Ok(counter)
210    }
211
212    /// Take the write for immediate delivery on this authenticated session.
213    pub fn poll_transmit(&mut self) -> Option<Datagram> {
214        let frame = self.engine.poll_transmit()?;
215        self.pending.as_mut()?.sent = true;
216        Some(frame)
217    }
218
219    /// First SPINE response deadline in the elapsed clock domain. On timeout,
220    /// discard this adapter, then reconcile the outstanding CLS.EEDI operation.
221    pub fn deadline(&self) -> Option<Duration> {
222        self.engine.poll_timeout()
223    }
224
225    /// Accept a single result delivered by the authenticated, directly connected
226    /// peer. Unrelated frames return `None`. A device component omitted in simple
227    /// addressing resolves to its authenticated endpoint (SPINE §5.2.2.1).
228    pub fn handle_datagram(
229        &mut self,
230        packet: &Datagram,
231        now: Clock,
232    ) -> Result<Option<Completion>, AdapterError> {
233        let Some(pending) = &mut self.pending else {
234            return Ok(None);
235        };
236        if !pending.sent || pending.result.is_some() {
237            return Ok(None);
238        }
239        let Some(header) = &packet.header else {
240            return Ok(None);
241        };
242        let Some(error) = result_code(packet) else {
243            return Ok(None);
244        };
245        if header.cmd_classifier != Some(CmdClassifier::Result)
246            || header.msg_counter.is_none()
247            || header
248                .address_originator
249                .as_ref()
250                .is_some_and(|origin| !matches_endpoint(Some(origin), &self.server))
251            || header.msg_counter_reference != Some(pending.counter)
252            || !matches_endpoint(header.address_source.as_ref(), &self.server)
253            || !matches_endpoint(header.address_destination.as_ref(), &self.client)
254        {
255            return Ok(None);
256        }
257        let mut normalized;
258        let frame = if header.address_source.as_ref() == Some(&self.server)
259            && header.address_destination.as_ref() == Some(&self.client)
260        {
261            packet
262        } else {
263            normalized = packet.clone();
264            let header = normalized.header.as_mut().expect("validated header");
265            header.address_source = Some(self.server.clone());
266            header.address_destination = Some(self.client.clone());
267            &normalized
268        };
269        self.engine
270            .handle_datagram(frame, Duration::from_secs(now.elapsed_seconds));
271        if !matches!(self.engine.poll_event(), Some(SpineEvent::ResultReceived {request, error: observed}) if request == pending.counter && observed == error)
272        {
273            return Ok(None);
274        }
275        pending.result = Some(error);
276        self.finish(now)
277    }
278
279    /// Retry the local journal transition if, for example, recording a definitive
280    /// equipment result failed due to an invalid local clock.
281    pub fn finish(&mut self, now: Clock) -> Result<Option<Completion>, AdapterError> {
282        let Some((pending, error)) = self
283            .pending
284            .as_ref()
285            .and_then(|p| p.result.map(|error| (p, error)))
286        else {
287            return Ok(None);
288        };
289        let outcome = match error {
290            ErrorNumber::None => Outcome::Accepted,
291            ErrorNumber::DestinationUnknown
292            | ErrorNumber::DestinationUnreachable
293            | ErrorNumber::CommandNotSupported => Outcome::Unsupported,
294            _ => Outcome::Rejected,
295        };
296        let acknowledgement = self.local.complete(&pending.id, outcome, now)?;
297        let request_id = self.pending.take().expect("verified pending result").id;
298        self.completed = true;
299        Ok(Some(Completion {
300            request_id,
301            acknowledgement,
302            error,
303        }))
304    }
305
306    /// Recover a clean engine. An unresolved write destroys the engine, including
307    /// its SPINE retry buffer, and remains pending on the local device.
308    pub fn into_engine(self) -> Result<Engine, AdapterError> {
309        if self.pending.is_some() {
310            return Err(AdapterError::Outstanding);
311        }
312        Ok(self.engine)
313    }
314}
315
316fn directional(control: &Control) -> Result<(Direction, &Limit), AdapterError> {
317    if control.trust.is_some() || control.failsafes.is_some() || control.notify.is_some() {
318        return Err(AdapterError::UnsupportedControl);
319    }
320    let power = control
321        .limits
322        .as_ref()
323        .ok_or(AdapterError::UnsupportedControl)?;
324    match (&power.consumption, &power.production) {
325        (Some(limit), None) => Ok((Direction::Consumption, limit)),
326        (None, Some(limit)) => Ok((Direction::Production, limit)),
327        _ => Err(AdapterError::UnsupportedControl),
328    }
329}
330
331fn write(id: LoadControlLimitId, direction: Direction, limit: &Limit) -> (CmdData, Vec<Filter>) {
332    let duration = limit.duration;
333    let mut filters = Vec::new();
334    if duration.is_none() {
335        // LPC §3.4.1.4: partial writes preserve omitted fields. Withdraw this
336        // limit's previous end time atomically before applying an open-ended value.
337        filters.push(
338            Filter::delete()
339                .select(FilterSelectors::LoadControlLimitListDataSelectors(
340                    LoadControlLimitListDataSelectors { limit_id: Some(id) },
341                ))
342                .covering(FilterElements::LoadControlLimitDataElements(
343                    LoadControlLimitDataElements {
344                        time_period: Some(TimePeriodElements {
345                            end_time: Some(ElementTag),
346                            ..Default::default()
347                        }),
348                        ..Default::default()
349                    },
350                )),
351        );
352    }
353    filters.push(Filter::partial());
354    // LPP §2.8.1 uses non-positive production watts. The wire validator
355    // requires a nonnegative CLS.EEDI magnitude, so negation is representable.
356    let watts = if direction == Direction::Production {
357        -limit.value
358    } else {
359        limit.value
360    };
361    let data = LoadControlLimitData {
362        limit_id: Some(id),
363        is_limit_active: Some(limit.active),
364        value: Some(ScaledNumber::whole(watts)),
365        time_period: duration.map(|s| TimePeriod {
366            end_time: Some(format_iso8601_duration(Duration::from_secs(s.into())).into()),
367            ..Default::default()
368        }),
369        ..Default::default()
370    };
371    (
372        CmdData::LoadControlLimitListData(LoadControlLimitListData {
373            load_control_limit_data: Some(vec![data]),
374        }),
375        filters,
376    )
377}
378
379fn matches_endpoint(actual: Option<&FeatureAddress>, expected: &FeatureAddress) -> bool {
380    actual.is_some_and(|a| {
381        a.entity == expected.entity
382            && a.feature == expected.feature
383            && (a.device.is_none() || a.device == expected.device)
384    })
385}
386
387fn result_code(packet: &Datagram) -> Option<ErrorNumber> {
388    let [cmd] = packet.payload.as_ref()?.cmd.as_deref()? else {
389        return None;
390    };
391    if cmd
392        .function
393        .as_ref()
394        .is_some_and(|f| f != &Function::ResultData)
395        || cmd.filter.is_some()
396    {
397        return None;
398    }
399    let CmdData::ResultData(result) = cmd.data.as_ref()? else {
400        return None;
401    };
402    result.error_number
403}
404
405mod metering;
406pub use metering::{meter_snapshot, MeterError, MeterProfile, MAX_METER_LIST_ROWS};
407
408#[cfg(feature = "eebus-pairing")]
409mod pairing;
410#[cfg(feature = "eebus-pairing")]
411pub use pairing::confirm_pairing;