Skip to main content

device_daemon_core/
mqtt.rs

1use crate::{
2    daemon::{CommandEffect, HardwareStatus, Output, MAX_POLL_INTERVAL},
3    output::{flatten_values, OutputFormat},
4};
5use anyhow::{bail, Context, Result};
6use async_trait::async_trait;
7use log::{info, warn};
8use rand::Rng;
9use rumqttc::{
10    AsyncClient, Event, EventLoop, Incoming, LastWill, MqttOptions, PublishOptions, QoS, Transport,
11};
12use serde::{Deserialize, Serialize};
13use std::{
14    collections::BTreeMap,
15    fmt,
16    str::FromStr,
17    sync::{
18        atomic::{AtomicU8, Ordering},
19        Arc,
20    },
21    time::{Duration, SystemTime, UNIX_EPOCH},
22};
23use tokio::{sync::mpsc, task::JoinHandle, time::sleep};
24
25const INITIAL_RECONNECT_CEILING: Duration = Duration::from_secs(1);
26const MAX_RECONNECT_CEILING: Duration = Duration::from_secs(30);
27const MQTT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);
28
29/// Common broker settings shared by the device projects.
30#[derive(Clone, Deserialize)]
31#[serde(default)]
32pub struct MqttConfig {
33    pub host: String,
34    pub port: u16,
35    pub tls: bool,
36    pub username: Option<String>,
37    pub password: Option<String>,
38    pub topic: String,
39    pub client_id: String,
40    pub qos: u8,
41    #[serde(deserialize_with = "crate::duration::deserialize_duration")]
42    pub keep_alive: Duration,
43    pub allow_control: bool,
44    pub allow_daemon_control: bool,
45}
46
47impl Default for MqttConfig {
48    fn default() -> Self {
49        Self {
50            host: "localhost".to_owned(),
51            port: 1883,
52            tls: false,
53            username: None,
54            password: None,
55            topic: "device".to_owned(),
56            client_id: "device-daemon".to_owned(),
57            qos: 0,
58            keep_alive: Duration::from_secs(30),
59            allow_control: false,
60            allow_daemon_control: false,
61        }
62    }
63}
64
65/// Value and optional correlation ID parsed from an MQTT set command.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct MqttSetCommandPayload {
68    pub value: String,
69    pub request_id: Option<String>,
70}
71
72#[derive(Debug, Serialize)]
73pub struct MqttCommandResult {
74    pub request_id: Option<String>,
75    pub command: String,
76    pub status: String,
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub poll_interval_secs: Option<u64>,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub error: Option<String>,
81}
82
83#[derive(Debug)]
84pub struct DaemonCommandOutcome {
85    pub result: MqttCommandResult,
86    pub effect: CommandEffect,
87    pub poll_interval_secs: Option<u64>,
88}
89
90#[derive(Deserialize)]
91struct ReadNowCommand {
92    #[serde(default)]
93    request_id: Option<String>,
94}
95
96/// Parse a plain scalar payload or a JSON object containing `value_field` and
97/// an optional `request_id`.
98pub fn parse_mqtt_set_payload(payload: &[u8], value_field: &str) -> Result<MqttSetCommandPayload> {
99    let payload = std::str::from_utf8(payload)
100        .context("MQTT set command payload must be valid UTF-8")?
101        .trim();
102
103    if !payload.starts_with('{') {
104        return Ok(MqttSetCommandPayload {
105            value: payload.to_owned(),
106            request_id: None,
107        });
108    }
109
110    let mut object: serde_json::Map<String, serde_json::Value> =
111        serde_json::from_str(payload).context("MQTT set command payload must be a JSON object")?;
112    let request_id = match object.remove("request_id") {
113        None | Some(serde_json::Value::Null) => None,
114        Some(serde_json::Value::String(request_id)) => Some(request_id),
115        Some(_) => bail!("MQTT set command `request_id` must be a string"),
116    };
117    let value = object
118        .remove(value_field)
119        .with_context(|| format!("MQTT set command JSON must contain `{value_field}`"))?;
120    let value = match value {
121        serde_json::Value::String(value) => value,
122        value => value.to_string(),
123    };
124
125    Ok(MqttSetCommandPayload { value, request_id })
126}
127
128/// Validate and apply a shared daemon control command.
129///
130/// The returned result and polling-interval update still need to be published
131/// by the application. `result_prefix` preserves an application's naming
132/// convention for rejected/unsupported commands.
133pub fn process_daemon_command(
134    command: &str,
135    payload: &[u8],
136    enabled: bool,
137    result_prefix: &str,
138    poll_interval: &mut Duration,
139) -> DaemonCommandOutcome {
140    let rejected =
141        |command: String, request_id: Option<String>, error: String| DaemonCommandOutcome {
142            result: MqttCommandResult {
143                request_id,
144                command,
145                status: "rejected".to_owned(),
146                poll_interval_secs: None,
147                error: Some(error),
148            },
149            effect: CommandEffect::Continue,
150            poll_interval_secs: None,
151        };
152
153    if !enabled {
154        return rejected(
155            format!("{result_prefix}{command}"),
156            None,
157            "daemon control is disabled".to_owned(),
158        );
159    }
160
161    match command {
162        "poll_interval_secs/set" => {
163            let request = match parse_mqtt_set_payload(payload, "seconds") {
164                Ok(request) => request,
165                Err(error) => {
166                    return rejected(
167                        command.to_owned(),
168                        None,
169                        format!(
170                            "payload must be an integer seconds value or JSON with a `seconds` field: {error:#}"
171                        ),
172                    );
173                }
174            };
175            let seconds = match request.value.parse::<u64>() {
176                Ok(seconds) => seconds,
177                Err(_) => {
178                    return rejected(
179                        command.to_owned(),
180                        request.request_id,
181                        "seconds must be an integer".to_owned(),
182                    );
183                }
184            };
185            if seconds == 0 || seconds > MAX_POLL_INTERVAL.as_secs() {
186                return rejected(
187                    command.to_owned(),
188                    request.request_id,
189                    format!(
190                        "seconds must be between 1 and {}",
191                        MAX_POLL_INTERVAL.as_secs()
192                    ),
193                );
194            }
195
196            *poll_interval = Duration::from_secs(seconds);
197            DaemonCommandOutcome {
198                result: MqttCommandResult {
199                    request_id: request.request_id,
200                    command: command.to_owned(),
201                    status: "applied".to_owned(),
202                    poll_interval_secs: Some(seconds),
203                    error: None,
204                },
205                effect: CommandEffect::Continue,
206                poll_interval_secs: Some(seconds),
207            }
208        }
209        "read_now" => {
210            let request = if payload.is_empty() {
211                Ok(ReadNowCommand { request_id: None })
212            } else {
213                serde_json::from_slice::<ReadNowCommand>(payload)
214            };
215            match request {
216                Ok(request) => DaemonCommandOutcome {
217                    result: MqttCommandResult {
218                        request_id: request.request_id,
219                        command: command.to_owned(),
220                        status: "accepted".to_owned(),
221                        poll_interval_secs: None,
222                        error: None,
223                    },
224                    effect: CommandEffect::PollNow,
225                    poll_interval_secs: None,
226                },
227                Err(_) => rejected(
228                    command.to_owned(),
229                    None,
230                    "payload must be an empty message or JSON object".to_owned(),
231                ),
232            }
233        }
234        _ => rejected(
235            format!("{result_prefix}{command}"),
236            None,
237            "unsupported daemon command".to_owned(),
238        ),
239    }
240}
241
242impl fmt::Debug for MqttConfig {
243    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244        f.debug_struct("MqttConfig")
245            .field("host", &self.host)
246            .field("port", &self.port)
247            .field("tls", &self.tls)
248            .field("username", &self.username)
249            .field("password", &self.password.as_ref().map(|_| "********"))
250            .field("topic", &self.topic)
251            .field("client_id", &self.client_id)
252            .field("qos", &self.qos)
253            .field("keep_alive", &self.keep_alive)
254            .field("allow_control", &self.allow_control)
255            .field("allow_daemon_control", &self.allow_daemon_control)
256            .finish()
257    }
258}
259
260impl MqttConfig {
261    /// Load YAML configuration and apply the shared `MQTT_*` environment overrides.
262    pub async fn load(path: impl AsRef<std::path::Path>) -> Result<Self> {
263        let path = path.as_ref();
264        let source = tokio::fs::read_to_string(path)
265            .await
266            .with_context(|| format!("Cannot open MQTT config file {}", path.display()))?;
267        let mut config: Self = yaml_serde::from_str(&source)
268            .with_context(|| format!("Cannot parse MQTT config file {}", path.display()))?;
269        config.apply_env_overrides()?;
270        config.validate()?;
271        Ok(config)
272    }
273
274    /// Validate settings supplied directly by the caller.
275    pub fn validate(&self) -> Result<()> {
276        if self.host.trim().is_empty() {
277            bail!("MQTT host must not be empty");
278        }
279        if self.port == 0 {
280            bail!("MQTT port must be greater than zero");
281        }
282        if self.topic.trim().is_empty() || self.topic.contains('+') || self.topic.contains('#') {
283            bail!("MQTT topic must be non-empty and cannot contain wildcards");
284        }
285        if self.client_id.trim().is_empty() {
286            bail!("MQTT client_id must not be empty");
287        }
288        if self.keep_alive.is_zero() {
289            bail!("MQTT keep_alive must be greater than zero");
290        }
291        if self.keep_alive.subsec_nanos() != 0 || self.keep_alive.as_secs() > u16::MAX as u64 {
292            bail!("MQTT keep_alive must be a whole number of seconds no greater than 65535");
293        }
294        if self.username.is_none() && self.password.is_some() {
295            bail!("MQTT password requires a username");
296        }
297        if self.qos > 2 {
298            bail!("MQTT QoS must be 0, 1, or 2");
299        }
300        Ok(())
301    }
302
303    /// Apply the standard `MQTT_*` environment overrides.
304    pub fn apply_env_overrides(&mut self) -> Result<()> {
305        if let Some(value) = env_value("MQTT_HOST")? {
306            self.host = value;
307        }
308        if let Some(value) = env_value("MQTT_PORT")? {
309            self.port = value;
310        }
311        if let Some(value) = env_value("MQTT_TLS")? {
312            self.tls = value;
313        }
314        if let Some(value) = env_value("MQTT_USERNAME")? {
315            self.username = Some(value);
316        }
317        if let Some(value) = env_value("MQTT_PASSWORD")? {
318            self.password = Some(value);
319        }
320        if let Some(value) = env_value("MQTT_TOPIC")? {
321            self.topic = value;
322        }
323        if let Some(value) = env_value("MQTT_CLIENT_ID")? {
324            self.client_id = value;
325        }
326        if let Some(value) = env_value("MQTT_QOS")? {
327            self.qos = value;
328        }
329        if let Some(value) = env_value::<String>("MQTT_KEEP_ALIVE")? {
330            self.keep_alive = crate::duration::parse_duration(&value)
331                .map_err(|error| anyhow::anyhow!("Invalid value for MQTT_KEEP_ALIVE: {error}"))?;
332        } else if let Some(value) = env_value::<u16>("MQTT_KEEP_ALIVE_SECS")? {
333            self.keep_alive = Duration::from_secs(value as u64);
334        }
335        if let Some(value) = env_value("MQTT_ALLOW_CONTROL")? {
336            self.allow_control = value;
337        }
338        if let Some(value) = env_value("MQTT_ALLOW_DAEMON_CONTROL")? {
339            self.allow_daemon_control = value;
340        }
341        Ok(())
342    }
343
344    fn qos(&self) -> QoS {
345        match self.qos {
346            0 => QoS::AtMostOnce,
347            1 => QoS::AtLeastOnce,
348            _ => QoS::ExactlyOnce,
349        }
350    }
351}
352
353fn env_value<T>(name: &str) -> Result<Option<T>>
354where
355    T: FromStr,
356    T::Err: fmt::Display,
357{
358    match std::env::var(name) {
359        Ok(value) => value
360            .parse()
361            .map(Some)
362            .map_err(|error| anyhow::anyhow!("Invalid value for {name}: {error}")),
363        Err(std::env::VarError::NotPresent) => Ok(None),
364        Err(error) => Err(error).with_context(|| format!("Cannot read {name}")),
365    }
366}
367
368/// A control packet delivered to the device-specific command adapter.
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct MqttControlMessage {
371    pub topic: String,
372    pub payload: Vec<u8>,
373}
374
375/// Shared MQTT connection and publication primitives.
376#[derive(Clone)]
377pub struct MqttClient {
378    client: AsyncClient,
379    topic: String,
380    qos: QoS,
381    device_status: Arc<AtomicU8>,
382    shutting_down: Arc<std::sync::atomic::AtomicBool>,
383}
384
385impl MqttClient {
386    pub fn connect(config: &MqttConfig) -> Result<(Self, EventLoop)> {
387        config.validate()?;
388        let mut options = MqttOptions::new(&config.client_id, (config.host.as_str(), config.port));
389        let keep_alive_secs = u16::try_from(config.keep_alive.as_secs())
390            .context("MQTT keep_alive exceeds the supported whole-second range")?;
391        options.set_keep_alive(keep_alive_secs);
392        options.set_last_will(LastWill::new(
393            format!("{}/daemon_state", config.topic),
394            "offline",
395            QoS::AtLeastOnce,
396            true,
397        ));
398        if config.username.is_some() || config.password.is_some() {
399            options.set_credentials(
400                config.username.clone().unwrap_or_default(),
401                config.password.clone().unwrap_or_default(),
402            );
403        }
404        if config.tls {
405            options.set_transport(Transport::tls_with_default_config());
406        }
407
408        let (client, event_loop) = AsyncClient::builder(options)
409            .capacity(100)
410            .try_build()
411            .context("Failed to create MQTT client")?;
412        Ok((
413            Self {
414                client,
415                topic: config.topic.clone(),
416                qos: config.qos(),
417                device_status: Arc::new(AtomicU8::new(status_code(HardwareStatus::Unknown))),
418                shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
419            },
420            event_loop,
421        ))
422    }
423
424    pub fn topic(&self) -> &str {
425        &self.topic
426    }
427
428    pub fn command_name<'a>(&self, topic: &'a str, group: &str) -> Option<&'a str> {
429        let prefix = format!("{}/command/{group}/", self.topic);
430        topic.strip_prefix(&prefix)
431    }
432
433    pub async fn publish_daemon_availability(&self, online: bool) -> Result<()> {
434        self.client
435            .publish(
436                format!("{}/daemon_state", self.topic),
437                if online { "online" } else { "offline" },
438                PublishOptions::new(QoS::AtLeastOnce).retained(),
439            )
440            .await
441            .context("Failed to publish daemon availability")
442    }
443
444    pub async fn publish_hardware_availability(&self, status: HardwareStatus) -> Result<()> {
445        self.client
446            .publish(
447                format!("{}/device_state", self.topic),
448                status.as_str(),
449                PublishOptions::new(QoS::AtLeastOnce).retained(),
450            )
451            .await
452            .context("Failed to publish device availability")?;
453        self.device_status
454            .store(status_code(status), Ordering::Relaxed);
455        Ok(())
456    }
457
458    async fn republish_device_availability(&self) -> Result<()> {
459        self.client
460            .publish(
461                format!("{}/device_state", self.topic),
462                status_from_code(self.device_status.load(Ordering::Relaxed)).as_str(),
463                PublishOptions::new(QoS::AtLeastOnce).retained(),
464            )
465            .await
466            .context("Failed to republish device availability")
467    }
468
469    fn is_shutting_down(&self) -> bool {
470        self.shutting_down.load(Ordering::Relaxed)
471    }
472
473    pub async fn publish_state<T: Serialize>(&self, device: &str, values: &T) -> Result<()> {
474        let payload = state_envelope(device, values)?;
475        self.client
476            .publish(
477                format!("{}/telemetry", self.topic),
478                payload,
479                PublishOptions::new(self.qos).retained(),
480            )
481            .await
482            .context("Failed to publish device state")
483    }
484
485    pub async fn publish_individual<T: Serialize>(&self, values: &T, retained: bool) -> Result<()> {
486        for (path, value) in flatten_values(values)? {
487            if path.contains('+') || path.contains('#') {
488                bail!("Individual MQTT value path cannot contain wildcards: {path}");
489            }
490            let options = PublishOptions::new(self.qos);
491            let options = if retained {
492                options.retained()
493            } else {
494                options
495            };
496            self.client
497                .publish(format!("{}/telemetry/{path}", self.topic), value, options)
498                .await
499                .with_context(|| format!("Failed to publish MQTT value {path}"))?;
500        }
501        Ok(())
502    }
503
504    pub async fn publish_metrics<T: Serialize>(
505        &self,
506        metrics: &BTreeMap<String, T>,
507        retained: bool,
508    ) -> Result<()> {
509        for (metric, value) in metrics {
510            if metric.is_empty()
511                || metric.contains('/')
512                || metric.contains('+')
513                || metric.contains('#')
514            {
515                bail!("Invalid MQTT metric name: {metric}");
516            }
517            let payload = serde_json::to_string(value)
518                .with_context(|| format!("Cannot serialize MQTT metric {metric}"))?;
519            let options = PublishOptions::new(self.qos);
520            let options = if retained {
521                options.retained()
522            } else {
523                options
524            };
525            self.client
526                .publish(
527                    format!("{}/telemetry/{metric}", self.topic),
528                    payload,
529                    options,
530                )
531                .await
532                .with_context(|| format!("Failed to publish MQTT metric {metric}"))?;
533        }
534        Ok(())
535    }
536
537    pub async fn publish_daemon_poll_interval(&self, interval_secs: u64) -> Result<()> {
538        self.client
539            .publish(
540                format!("{}/daemon_config/poll_interval_secs", self.topic),
541                interval_secs.to_string(),
542                PublishOptions::new(QoS::AtLeastOnce).retained(),
543            )
544            .await
545            .context("Failed to publish daemon poll interval")
546    }
547
548    pub async fn publish_command_result<T: Serialize>(&self, result: &T) -> Result<()> {
549        let payload =
550            serde_json::to_string(result).context("Cannot serialize MQTT command result")?;
551        self.client
552            .publish(
553                format!("{}/command/result", self.topic),
554                payload,
555                PublishOptions::new(self.qos),
556            )
557            .await
558            .context("Failed to publish MQTT command result")
559    }
560
561    pub async fn subscribe(&self, filter: &str) -> Result<()> {
562        self.client
563            .subscribe(filter, QoS::AtLeastOnce)
564            .await
565            .with_context(|| format!("Failed to subscribe to MQTT control filter {filter}"))
566    }
567
568    pub async fn disconnect(&self) -> Result<()> {
569        self.client
570            .disconnect()
571            .await
572            .context("Failed to disconnect from MQTT broker")
573    }
574}
575
576#[derive(Serialize)]
577struct StateEnvelope<'a, T> {
578    device: &'a str,
579    timestamp_unix_ms: u64,
580    values: &'a T,
581}
582
583/// Serialize values using the common retained `<topic>/telemetry` envelope shape.
584pub fn state_envelope<T: Serialize>(device: &str, values: &T) -> Result<String> {
585    let timestamp = SystemTime::now()
586        .duration_since(UNIX_EPOCH)
587        .context("System clock is before the Unix epoch")?
588        .as_millis()
589        .try_into()
590        .context("Unix timestamp does not fit in u64 milliseconds")?;
591    serde_json::to_string(&StateEnvelope {
592        device,
593        timestamp_unix_ms: timestamp,
594        values,
595    })
596    .context("Cannot serialize device state envelope")
597}
598
599/// MQTT sink using the common state envelope and flattened individual topics.
600pub struct MqttOutput {
601    client: MqttClient,
602    device: String,
603    format: OutputFormat,
604    retain_individual: bool,
605    event_task: Option<JoinHandle<()>>,
606    control_receiver: Option<mpsc::Receiver<MqttControlMessage>>,
607}
608
609impl MqttOutput {
610    /// Create a sink and start its broker event loop.
611    ///
612    /// The optional control filter is subscribed only when device or daemon
613    /// control is enabled in the MQTT configuration. Retained control packets
614    /// are dropped.
615    pub fn new(
616        config: &MqttConfig,
617        device: impl Into<String>,
618        format: OutputFormat,
619        control_filter: Option<String>,
620        retain_individual: bool,
621    ) -> Result<Self> {
622        let (client, event_loop) = MqttClient::connect(config)?;
623        let (control_sender, control_receiver) = mpsc::channel(32);
624        let filter = if config.allow_control || config.allow_daemon_control {
625            control_filter.or_else(|| {
626                if config.allow_daemon_control {
627                    Some(format!("{}/command/daemon/#", config.topic))
628                } else {
629                    Some(format!("{}/set/#", config.topic))
630                }
631            })
632        } else {
633            None
634        };
635        let event_task = Some(spawn_event_loop(
636            client.clone(),
637            event_loop,
638            filter,
639            control_sender,
640        ));
641        Ok(Self {
642            client,
643            device: device.into(),
644            format,
645            retain_individual,
646            event_task,
647            control_receiver: Some(control_receiver),
648        })
649    }
650
651    /// Take the control receiver for passing to the daemon runner.
652    pub fn take_control_receiver(&mut self) -> Option<mpsc::Receiver<MqttControlMessage>> {
653        self.control_receiver.take()
654    }
655
656    pub fn client(&self) -> MqttClient {
657        self.client.clone()
658    }
659
660    pub async fn publish_metrics<T: Serialize>(&self, metrics: &BTreeMap<String, T>) -> Result<()> {
661        self.client
662            .publish_metrics(metrics, self.retain_individual)
663            .await
664    }
665}
666
667#[async_trait]
668impl<S> Output<S> for MqttOutput
669where
670    S: Serialize + Send + Sync,
671{
672    async fn publish(&mut self, snapshot: &S) -> Result<()> {
673        match self.format {
674            OutputFormat::Json => self.client.publish_state(&self.device, snapshot).await,
675            OutputFormat::Individual => {
676                self.client
677                    .publish_individual(snapshot, self.retain_individual)
678                    .await
679            }
680        }
681    }
682
683    async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
684        self.client.publish_hardware_availability(status).await
685    }
686
687    async fn shutdown(&mut self) -> Result<()> {
688        self.client.shutting_down.store(true, Ordering::Relaxed);
689        let shutdown_result = tokio::time::timeout(MQTT_SHUTDOWN_TIMEOUT, async {
690            let mut shutdown_error = self.client.publish_daemon_availability(false).await.err();
691            sleep(Duration::from_millis(250)).await;
692            if let Err(error) = self.client.disconnect().await {
693                if shutdown_error.is_none() {
694                    shutdown_error = Some(error);
695                }
696            }
697            shutdown_error.map_or(Ok(()), Err)
698        })
699        .await
700        .context("MQTT shutdown timed out")
701        .and_then(|result| result);
702        if let Some(task) = self.event_task.take() {
703            task.abort();
704            let _ = task.await;
705        }
706        shutdown_result
707    }
708}
709
710fn spawn_event_loop(
711    client: MqttClient,
712    mut event_loop: EventLoop,
713    control_filter: Option<String>,
714    control_sender: mpsc::Sender<MqttControlMessage>,
715) -> JoinHandle<()> {
716    tokio::spawn(async move {
717        let mut retry_ceiling = INITIAL_RECONNECT_CEILING;
718        loop {
719            match event_loop.poll().await {
720                Ok(Event::Incoming(Incoming::ConnAck(_))) => {
721                    info!("Connected to MQTT broker");
722                    retry_ceiling = INITIAL_RECONNECT_CEILING;
723                    if !client.is_shutting_down() {
724                        if let Err(error) = client.publish_daemon_availability(true).await {
725                            warn!("{error:#}");
726                        }
727                        if let Err(error) = client.republish_device_availability().await {
728                            warn!("{error:#}");
729                        }
730                        if let Some(filter) = &control_filter {
731                            if let Err(error) = client.subscribe(filter).await {
732                                warn!("{error:#}");
733                            }
734                        }
735                    }
736                }
737                Ok(Event::Incoming(Incoming::Publish(publish))) => {
738                    if control_filter.is_none() {
739                        continue;
740                    }
741                    if publish.retain {
742                        let topic = String::from_utf8_lossy(&publish.topic).into_owned();
743                        warn!("Ignoring retained MQTT control message on {topic}");
744                        continue;
745                    }
746                    let message = MqttControlMessage {
747                        topic: String::from_utf8_lossy(&publish.topic).into_owned(),
748                        payload: publish.payload.to_vec(),
749                    };
750                    if control_sender.send(message).await.is_err() {
751                        warn!("MQTT control receiver closed; stopping event loop");
752                        break;
753                    }
754                }
755                Ok(_) => {}
756                Err(error) => {
757                    let delay = equal_jitter(retry_ceiling);
758                    warn!("MQTT connection unavailable: {error}; retrying in {delay:?}");
759                    sleep(delay).await;
760                    retry_ceiling = retry_ceiling
761                        .checked_mul(2)
762                        .unwrap_or(MAX_RECONNECT_CEILING)
763                        .min(MAX_RECONNECT_CEILING);
764                }
765            }
766        }
767    })
768}
769
770fn equal_jitter(ceiling: Duration) -> Duration {
771    let upper_millis = ceiling.as_millis().clamp(1, u64::MAX.into()) as u64;
772    let lower_millis = upper_millis.div_ceil(2);
773    Duration::from_millis(rand::rng().random_range(lower_millis..=upper_millis))
774}
775
776const fn status_code(status: HardwareStatus) -> u8 {
777    match status {
778        HardwareStatus::Unknown => 0,
779        HardwareStatus::Online => 1,
780        HardwareStatus::Offline => 2,
781    }
782}
783
784const fn status_from_code(code: u8) -> HardwareStatus {
785    match code {
786        1 => HardwareStatus::Online,
787        2 => HardwareStatus::Offline,
788        _ => HardwareStatus::Unknown,
789    }
790}
791
792#[cfg(test)]
793mod tests {
794    use super::*;
795
796    #[test]
797    fn parses_mqtt_set_payload_values_and_request_ids() {
798        let payload = parse_mqtt_set_payload(b" 16.0 \n", "value").unwrap();
799        assert_eq!(payload.value, "16.0");
800        assert_eq!(payload.request_id, None);
801
802        let payload =
803            parse_mqtt_set_payload(br#"{"value":16.0,"request_id":"current-1"}"#, "value").unwrap();
804        assert_eq!(payload.value, "16.0");
805        assert_eq!(payload.request_id.as_deref(), Some("current-1"));
806
807        let payload =
808            parse_mqtt_set_payload(br#"{"seconds":30,"request_id":"interval-1"}"#, "seconds")
809                .unwrap();
810        assert_eq!(payload.value, "30");
811        assert_eq!(payload.request_id.as_deref(), Some("interval-1"));
812    }
813
814    #[test]
815    fn rejects_invalid_mqtt_set_json_payloads() {
816        assert!(parse_mqtt_set_payload(br#"{"value":1"#, "value").is_err());
817        assert!(parse_mqtt_set_payload(br#"{"request_id":"id"}"#, "value").is_err());
818        assert!(parse_mqtt_set_payload(br#"{"value":1,"request_id":true}"#, "value").is_err());
819    }
820
821    #[test]
822    fn processes_shared_daemon_commands() {
823        let mut poll_interval = Duration::from_secs(5);
824        let outcome = process_daemon_command(
825            "poll_interval_secs/set",
826            br#"{"seconds":30,"request_id":"interval-1"}"#,
827            true,
828            "daemon/",
829            &mut poll_interval,
830        );
831        assert_eq!(poll_interval, Duration::from_secs(30));
832        assert_eq!(outcome.poll_interval_secs, Some(30));
833        assert_eq!(outcome.effect, CommandEffect::Continue);
834        assert_eq!(outcome.result.request_id.as_deref(), Some("interval-1"));
835        assert_eq!(outcome.result.command, "poll_interval_secs/set");
836        assert_eq!(outcome.result.status, "applied");
837
838        let outcome = process_daemon_command(
839            "read_now",
840            br#"{"request_id":"read-1"}"#,
841            true,
842            "daemon/",
843            &mut poll_interval,
844        );
845        assert_eq!(outcome.effect, CommandEffect::PollNow);
846        assert_eq!(outcome.result.request_id.as_deref(), Some("read-1"));
847    }
848
849    #[test]
850    fn rejects_invalid_or_disabled_daemon_commands_without_changing_interval() {
851        let mut poll_interval = Duration::from_secs(5);
852        let outcome = process_daemon_command(
853            "poll_interval_secs/set",
854            b"0",
855            true,
856            "daemon/",
857            &mut poll_interval,
858        );
859        assert_eq!(poll_interval, Duration::from_secs(5));
860        assert_eq!(outcome.result.status, "rejected");
861        assert_eq!(outcome.result.request_id, None);
862
863        let outcome =
864            process_daemon_command("unsupported", b"", false, "daemon/", &mut poll_interval);
865        assert_eq!(outcome.result.command, "daemon/unsupported");
866        assert_eq!(
867            outcome.result.error.as_deref(),
868            Some("daemon control is disabled")
869        );
870    }
871
872    #[test]
873    fn configuration_defaults_are_safe_and_valid() {
874        let config = MqttConfig::default();
875        assert!(!config.allow_control);
876        assert!(!config.allow_daemon_control);
877        assert_eq!(config.topic, "device");
878        assert_eq!(config.keep_alive, Duration::from_secs(30));
879        assert!(config.validate().is_ok());
880    }
881
882    #[test]
883    fn keep_alive_accepts_duration_and_legacy_seconds_configuration() {
884        let config: MqttConfig = yaml_serde::from_str("keep_alive: 45s").unwrap();
885        assert_eq!(config.keep_alive, Duration::from_secs(45));
886        assert!(config.validate().is_ok());
887
888        let config: MqttConfig = yaml_serde::from_str("keep_alive_secs: 30").unwrap();
889        assert_eq!(config.keep_alive, Duration::from_secs(30));
890        assert!(config.validate().is_ok());
891    }
892
893    #[test]
894    fn keep_alive_must_be_whole_seconds_within_protocol_range() {
895        let config: MqttConfig = yaml_serde::from_str("keep_alive: 1500ms").unwrap();
896        assert!(config.validate().is_err());
897        let config: MqttConfig = yaml_serde::from_str("keep_alive: 0s").unwrap();
898        assert!(config.validate().is_err());
899        let config: MqttConfig = yaml_serde::from_str("keep_alive: 65536s").unwrap();
900        assert!(config.validate().is_err());
901    }
902
903    #[test]
904    fn rejects_invalid_topics_and_qos() {
905        let config = MqttConfig {
906            topic: "bad/#".to_owned(),
907            ..MqttConfig::default()
908        };
909        assert!(config.validate().is_err());
910        let config = MqttConfig {
911            qos: 3,
912            ..MqttConfig::default()
913        };
914        assert!(config.validate().is_err());
915    }
916
917    #[test]
918    fn state_payload_has_the_shared_envelope() {
919        let payload = state_envelope("demo", &serde_json::json!({"value": 42})).unwrap();
920        let value: serde_json::Value = serde_json::from_str(&payload).unwrap();
921        assert!(value.get("schema_version").is_none());
922        assert_eq!(value["device"], "demo");
923        assert!(value["timestamp_unix_ms"].is_u64());
924        assert_eq!(value["values"]["value"], 42);
925    }
926
927    #[test]
928    fn reconnect_jitter_stays_in_the_upper_half_of_its_ceiling() {
929        for ceiling in [
930            Duration::from_secs(1),
931            Duration::from_secs(8),
932            MAX_RECONNECT_CEILING,
933        ] {
934            let delay = equal_jitter(ceiling);
935            assert!(delay >= ceiling / 2);
936            assert!(delay <= ceiling);
937        }
938    }
939}