ebus-homie 0.1.1

Homie 5 protocol core for eBus: identifiers, topics, datatypes, descriptions and the controller and device state machines, with no I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Public value types of the controller: ids, configuration, events, views.

use alloc::{string::String, sync::Arc, vec::Vec};
use core::fmt;

use ebus_mqtt::{Link, QoS, filter};
use rpds::RedBlackTreeMapSync;

pub use crate::{Id, PropertyAddr};
pub use ebus_mqtt::Handled;

use crate::EBUS_DOMAIN;
use crate::datatype::Problem;
use crate::description::{DescriptionError, DeviceDescription, Ignored};
use crate::id::is_valid_id;
use crate::state::DeviceState;

/// The topic domain (first topic level) the controller watches.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Domain {
    /// One domain, `ebus` by default (framework.md:85).
    Named(String),
    /// Every domain (`+/5/+/$state`, convention.md:161-162); wildcard discovery
    /// only.
    Any,
}

/// Which devices the controller tracks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Discovery {
    /// Every device that publishes a `$state` in the domain.
    Wildcard,
    /// One device, plus the `$state` of the root its description names.
    Device(Id),
    /// A root device and every device its `children` declare, transitively.
    Tree {
        /// The root device.
        root: Id,
    },
}

/// Limits on how many devices replay their retained property messages at once
/// (python-sdk#97). Start from [`Pacing::default`] and set the fields.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Pacing {
    /// Devices whose property burst may be in flight at once.
    pub batch_devices: usize,
    /// Retained messages the devices in flight may owe in total, two per
    /// retained property (a value and a `$target`).
    pub batch_values: usize,
}

impl Default for Pacing {
    /// python-sdk's constants: 8 devices, 500 messages.
    fn default() -> Self {
        Pacing {
            batch_devices: 8,
            batch_values: 500,
        }
    }
}

/// Controller configuration. Start from [`Config::wildcard`],
/// [`Config::tree`] or [`Config::device`] and adjust the fields.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
    /// Topic domain; [`Domain::Named`] `"ebus"` by default.
    pub domain: Domain,
    /// Discovery mode.
    pub discovery: Discovery,
    /// QoS of every subscription; `ExactlyOnce` by default (convention.md:45).
    pub subscribe_qos: QoS,
    /// Subscription pacing; `None` subscribes every device's property filters
    /// with its `$description`.
    pub pacing: Option<Pacing>,
    /// Milliseconds a device may wait for its retained messages before it is
    /// resubscribed; `None` disables stuck healing. 10 000 by default.
    pub stuck_timeout_ms: Option<u64>,
    /// Resubscribe attempts before a stuck device is given up; 3 by default.
    pub max_resubscribe_attempts: u8,
    /// Milliseconds after a link-up within which a known device must be heard
    /// again, or [`Event::DeviceAbsent`] fires; 30 000 by default.
    pub absent_after_ms: u64,
    /// Milliseconds after a description is applied, or after a link-up, before
    /// [`Event::DeviceSynced`] reports missing values; 10 000 by default.
    pub sync_timeout_ms: u64,
    /// Trust a CONNACK with `session_present: true` and keep every
    /// subscription; `false` (the default) re-paces as after a clean session.
    pub trust_session: bool,
    /// The host never sends, after a `Link::Up { session_present: false }`,
    /// a SUBSCRIBE the controller queued before handling it. Replay matching
    /// then restarts at each clean link-up, so a replay lost with a
    /// connection delays no later re-sync; `false` (the default) keeps the
    /// unmatched SUBSCRIBEs across it.
    pub link_up_discards_queued: bool,
    /// Values buffered per device before its `$description` arrives; 1024 by
    /// default.
    pub max_early_values: usize,
    /// Alerts held per device; a new alert id past it is dropped. 256 by
    /// default.
    pub max_alerts: usize,
    /// Most devices tracked at once; `None` (the default) is unbounded.
    pub max_devices: Option<usize>,
    /// Filters the host subscribes on the same client. The controller never
    /// unsubscribes them.
    pub host_filters: Vec<String>,
}

impl Config {
    /// Wildcard discovery in the `ebus` domain, with every default.
    pub fn wildcard() -> Self {
        Config {
            domain: Domain::Named(String::from(EBUS_DOMAIN)),
            discovery: Discovery::Wildcard,
            subscribe_qos: QoS::ExactlyOnce,
            pacing: Some(Pacing::default()),
            stuck_timeout_ms: Some(10_000),
            max_resubscribe_attempts: 3,
            absent_after_ms: 30_000,
            sync_timeout_ms: 10_000,
            trust_session: false,
            link_up_discards_queued: false,
            max_early_values: 1024,
            max_alerts: 256,
            max_devices: None,
            host_filters: Vec::new(),
        }
    }

    /// Tree discovery from `root`, otherwise as [`Config::wildcard`].
    pub fn tree(root: &str) -> Result<Self, ConfigError> {
        let root = Id::new(root).ok_or(ConfigError::InvalidDeviceId)?;
        Ok(Config {
            discovery: Discovery::Tree { root },
            ..Config::wildcard()
        })
    }

    /// Single-device discovery of `id`, otherwise as [`Config::wildcard`].
    pub fn device(id: &str) -> Result<Self, ConfigError> {
        let id = Id::new(id).ok_or(ConfigError::InvalidDeviceId)?;
        Ok(Config {
            discovery: Discovery::Device(id),
            ..Config::wildcard()
        })
    }

    pub(super) fn validate(&self) -> Result<(), ConfigError> {
        match (&self.domain, &self.discovery) {
            (Domain::Named(d), _) if !is_valid_id(d) => return Err(ConfigError::InvalidDomain),
            (Domain::Any, Discovery::Device(_) | Discovery::Tree { .. }) => {
                return Err(ConfigError::InvalidDomain);
            }
            _ => {}
        }
        if self
            .pacing
            .is_some_and(|p| p.batch_devices == 0 || p.batch_values == 0)
        {
            return Err(ConfigError::ZeroBatch);
        }
        if !self.host_filters.iter().all(|f| filter::is_valid_filter(f)) {
            return Err(ConfigError::InvalidHostFilter);
        }
        Ok(())
    }
}

impl Default for Config {
    /// [`Config::wildcard`].
    fn default() -> Self {
        Config::wildcard()
    }
}

/// Why a [`Config`] was refused.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ConfigError {
    /// [`Domain::Named`] holds an invalid id, or [`Domain::Any`] is combined
    /// with device or tree discovery.
    InvalidDomain,
    /// The device or root id is not a valid id.
    InvalidDeviceId,
    /// A [`Pacing`] limit is zero.
    ZeroBatch,
    /// A host filter is not a valid MQTT topic filter.
    InvalidHostFilter,
}

impl ConfigError {
    /// camelCase reason code.
    pub const fn as_str(self) -> &'static str {
        match self {
            ConfigError::InvalidDomain => "invalidDomain",
            ConfigError::InvalidDeviceId => "invalidDeviceId",
            ConfigError::ZeroBatch => "zeroBatch",
            ConfigError::InvalidHostFilter => "invalidHostFilter",
        }
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl core::error::Error for ConfigError {}

/// Where a property message came from, read from [`ebus_mqtt::Message::retain`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Origin {
    /// The broker's retained copy (retain bit set).
    Retained,
    /// A live publish (retain bit clear).
    Live,
    /// The client does not report the retain bit.
    Unknown,
}

impl Origin {
    pub(super) fn of(retain: Option<bool>) -> Self {
        match retain {
            Some(true) => Origin::Retained,
            Some(false) => Origin::Live,
            None => Origin::Unknown,
        }
    }
}

/// A received value or `$target`, delivered unmodified (convention.md:78).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Value {
    /// The payload text, with a single `0x00` byte decoded to `""`.
    pub raw: Arc<str>,
    /// [`check_value`](crate::datatype::check_value) against the property's
    /// declaration.
    pub check: Result<(), Problem>,
}

/// What a stuck device still lacks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Missing {
    /// Its `$state`.
    State,
    /// Its `$description`.
    Description,
    /// Retained property values.
    Properties,
}

/// Something the controller observed. Events are hints; the views returned by
/// [`Controller::device`](super::Controller::device) are the truth.
///
/// Each struct variant is `#[non_exhaustive]`, so a pattern names the fields
/// it needs and ends with `..`.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Event {
    /// The broker link changed, emitted after the commands it caused are queued.
    Link(Link),
    /// A device's first valid `$state`.
    #[non_exhaustive]
    DeviceDiscovered {
        /// Device id.
        device: Id,
        /// Its state.
        state: DeviceState,
    },
    /// A device's `$state` changed; also emitted, with `old: None`, after
    /// [`Event::DeviceDiscovered`].
    #[non_exhaustive]
    StateChanged {
        /// Device id.
        device: Id,
        /// The previous state.
        old: Option<DeviceState>,
        /// The new state.
        new: DeviceState,
        /// The device's effective state after the change.
        effective: DeviceState,
    },
    /// A device's effective state changed while its own `$state` did not:
    /// its root changed state or went away.
    #[non_exhaustive]
    EffectiveStateChanged {
        /// Device id.
        device: Id,
        /// The previous effective state.
        old: DeviceState,
        /// The new effective state.
        new: DeviceState,
    },
    /// A device announced a description: on its ready edge, or at once when
    /// it changed it while `ready`. A change while `sleeping` is announced on
    /// the next ready edge.
    #[non_exhaustive]
    DescriptionChanged {
        /// Device id.
        device: Id,
        /// The parsed description.
        description: Arc<DeviceDescription>,
        /// Nodes and properties left out as illegal.
        ignored: Vec<Ignored>,
        /// The description changed while the device was `ready` or
        /// `sleeping`, which convention.md:207 forbids.
        while_ready: bool,
    },
    /// A `$description` with an illegal device-level field. The device keeps
    /// its `$state` and has no model.
    #[non_exhaustive]
    DescriptionRejected {
        /// Device id.
        device: Id,
        /// Why it was rejected.
        error: DescriptionError,
    },
    /// A retained property's value changed.
    #[non_exhaustive]
    PropertyChanged {
        /// The property.
        addr: PropertyAddr,
        /// The value.
        value: Value,
        /// Where it came from.
        origin: Origin,
    },
    /// A message for a property declared `retained: false`; never cached
    /// (convention.md:370-371). An event with [`Origin::Retained`] is a stale
    /// copy the broker replayed on a subscribe, which convention.md:50 forbids
    /// devices to publish.
    #[non_exhaustive]
    PropertyEvent {
        /// The property.
        addr: PropertyAddr,
        /// The value.
        value: Value,
        /// Where it came from.
        origin: Origin,
    },
    /// A property's value was cleared: by a zero-length payload, or because
    /// a re-sync found it no longer retained.
    #[non_exhaustive]
    PropertyCleared {
        /// The property.
        addr: PropertyAddr,
    },
    /// A property's `$target` changed; `None` when it was cleared.
    #[non_exhaustive]
    TargetChanged {
        /// The property.
        addr: PropertyAddr,
        /// The target.
        target: Option<Value>,
    },
    /// A device's `$alert` changed.
    #[non_exhaustive]
    Alert {
        /// Device id.
        device: Id,
        /// Alert id.
        alert: Id,
        /// Alert text; `None` when the alert was cleared.
        message: Option<String>,
    },
    /// A device's description is held, its property burst is over, and every
    /// retained property it declares has a value (`missing: 0`), or
    /// [`Config::sync_timeout_ms`] passed with `missing` still absent.
    /// Re-armed by a description change and by a link-up.
    #[non_exhaustive]
    DeviceSynced {
        /// Device id.
        device: Id,
        /// Declared retained properties without a value.
        missing: u32,
    },
    /// A device's retained messages did not arrive in time.
    #[non_exhaustive]
    DeviceStuck {
        /// Device id.
        device: Id,
        /// What it lacks.
        missing: Missing,
        /// The resubscribe attempt now made, or with `gave_up` the attempts made.
        attempt: u8,
        /// No more attempts follow; the subscriptions stay in place.
        gave_up: bool,
    },
    /// A known device was not heard within [`Config::absent_after_ms`] of a
    /// link-up. It stays known and heals on its next message. This is also
    /// the only signal for a device whose `$state` was deleted while the
    /// controller did not hear it, since nothing retained is replayed for it.
    #[non_exhaustive]
    DeviceAbsent {
        /// Device id.
        device: Id,
    },
    /// A device left the registry: a zero-length `$state`, or, in tree mode,
    /// its parent no longer declares it.
    #[non_exhaustive]
    DeviceRemoved {
        /// Device id.
        device: Id,
    },
    /// Every device declared under a root has published its description.
    /// Fires on each incomplete-to-complete edge.
    #[non_exhaustive]
    TreeComplete {
        /// The root.
        root: Id,
    },
}

/// Options for [`Controller::set`](super::Controller::set). Start from
/// [`SetOptions::default`] and set the fields or chain the setters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct SetOptions {
    /// Send even when the device's effective state is not `ready`.
    pub allow_not_ready: bool,
    /// Skip the payload check.
    pub unchecked: bool,
}

impl SetOptions {
    /// With `allow_not_ready` set.
    #[must_use]
    pub const fn allow_not_ready(mut self, allow: bool) -> Self {
        self.allow_not_ready = allow;
        self
    }

    /// With `unchecked` set.
    #[must_use]
    pub const fn unchecked(mut self, unchecked: bool) -> Self {
        self.unchecked = unchecked;
        self
    }
}

/// Why a `/set` or `$broadcast` was not sent.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SetError {
    /// The broker link is down; QoS 0 is never held (convention.md:695).
    NotConnected,
    /// No device with that id is known.
    UnknownDevice,
    /// The device has no model, or declares no such property.
    UnknownProperty,
    /// The property is not settable.
    NotSettable,
    /// The device's effective state is not `ready` (convention.md:279).
    DeviceNotReady(DeviceState),
    /// The payload fails the check the device runs.
    Invalid(Problem),
    /// A `$broadcast` subtopic level is not a valid id, or the domain is
    /// [`Domain::Any`].
    InvalidTopic,
}

impl SetError {
    /// camelCase reason code.
    pub const fn as_str(self) -> &'static str {
        match self {
            SetError::NotConnected => "notConnected",
            SetError::UnknownDevice => "unknownDevice",
            SetError::UnknownProperty => "unknownProperty",
            SetError::NotSettable => "notSettable",
            SetError::DeviceNotReady(_) => "deviceNotReady",
            SetError::Invalid(_) => "invalid",
            SetError::InvalidTopic => "invalidTopic",
        }
    }
}

impl fmt::Display for SetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SetError::DeviceNotReady(s) => write!(f, "deviceNotReady({s})"),
            SetError::Invalid(p) => write!(f, "invalid({p})"),
            other => f.write_str(other.as_str()),
        }
    }
}

impl core::error::Error for SetError {}

/// What the controller knows about one property.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PropertyView {
    /// The last value, checked; always `None` for a `retained: false` property.
    pub value: Option<Value>,
    /// The last value text that passed the check.
    pub last_valid: Option<Arc<str>>,
    /// The last `$target`.
    pub target: Option<Value>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Slot {
    pub(super) view: PropertyView,
    pub(super) node: Id,
    pub(super) prop: Id,
    /// Position in `DeviceDescription::nodes` and the node's `properties`.
    pub(super) node_idx: usize,
    pub(super) prop_idx: usize,
    pub(super) retained: bool,
}

/// A device's slots by node, then property. Persistent: a clone shares every
/// entry, and a change copies only the path to it.
pub(super) type Props = RedBlackTreeMapSync<Id, RedBlackTreeMapSync<Id, Slot>>;

/// What the controller knows about one device.
#[derive(Clone, Debug)]
pub struct DeviceView {
    /// Device id.
    pub id: Id,
    /// Topic domain it publishes in.
    pub domain: Arc<str>,
    /// Last valid `$state`; always `Some` for a device the queries return.
    pub state: Option<DeviceState>,
    /// Effective state (convention.md:262-267): `lost` when its root is lost,
    /// else its own state.
    pub effective: Option<DeviceState>,
    /// The applied description, `None` before the first valid one.
    pub description: Option<Arc<DeviceDescription>>,
    /// Heard since the last link-up.
    pub confirmed: bool,
    /// [`Event::DeviceSynced`] fired since the last description change or
    /// link-up.
    pub synced: bool,
    pub(super) props: Props,
    pub(super) alerts: RedBlackTreeMapSync<Id, String>,
}

impl DeviceView {
    pub(super) fn new(id: Id, domain: Arc<str>) -> Self {
        DeviceView {
            id,
            domain,
            state: None,
            effective: None,
            description: None,
            confirmed: true,
            synced: false,
            props: Props::new_sync(),
            alerts: RedBlackTreeMapSync::new_sync(),
        }
    }

    /// True when `other` holds the very maps of properties and alerts this
    /// view holds, as a clone does until either is changed. Constant time;
    /// `false` does not prove the contents differ.
    pub fn shares_values(&self, other: &DeviceView) -> bool {
        self.props.ptr_eq(&other.props) && self.alerts.ptr_eq(&other.alerts)
    }

    /// The property `node/property`, when the description declares it.
    pub fn property(&self, node: &str, property: &str) -> Option<&PropertyView> {
        self.props.get(node)?.get(property).map(|s| &s.view)
    }

    /// Every declared property as `(node, property, view)`, in id order.
    pub fn properties(&self) -> impl Iterator<Item = (&Id, &Id, &PropertyView)> + '_ {
        self.props
            .values()
            .flat_map(|m| m.values())
            .map(|s| (&s.node, &s.prop, &s.view))
    }

    /// The text of alert `id`, when it is set.
    pub fn alert(&self, id: &str) -> Option<&str> {
        self.alerts.get(id).map(String::as_str)
    }

    /// Every set alert as `(id, text)`, in id order.
    pub fn alerts(&self) -> impl Iterator<Item = (&Id, &str)> + '_ {
        self.alerts.iter().map(|(k, v)| (k, v.as_str()))
    }
}