device-daemon-core 0.0.1

Reusable async daemon and MQTT infrastructure for device clients
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
use crate::{
    daemon::{CommandEffect, HardwareStatus, Output, MAX_POLL_INTERVAL},
    output::{flatten_values, OutputFormat},
};
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use log::{info, warn};
use rand::Rng;
use rumqttc::{
    AsyncClient, Event, EventLoop, Incoming, LastWill, MqttOptions, PublishOptions, QoS, Transport,
};
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    fmt,
    str::FromStr,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc,
    },
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{sync::mpsc, task::JoinHandle, time::sleep};

const INITIAL_RECONNECT_CEILING: Duration = Duration::from_secs(1);
const MAX_RECONNECT_CEILING: Duration = Duration::from_secs(30);
const MQTT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);

/// Common broker settings shared by the device projects.
#[derive(Clone, Deserialize)]
#[serde(default)]
pub struct MqttConfig {
    pub host: String,
    pub port: u16,
    pub tls: bool,
    pub username: Option<String>,
    pub password: Option<String>,
    pub topic: String,
    pub client_id: String,
    pub qos: u8,
    #[serde(deserialize_with = "crate::duration::deserialize_duration")]
    pub keep_alive: Duration,
    pub allow_control: bool,
    pub allow_daemon_control: bool,
}

impl Default for MqttConfig {
    fn default() -> Self {
        Self {
            host: "localhost".to_owned(),
            port: 1883,
            tls: false,
            username: None,
            password: None,
            topic: "device".to_owned(),
            client_id: "device-daemon".to_owned(),
            qos: 0,
            keep_alive: Duration::from_secs(30),
            allow_control: false,
            allow_daemon_control: false,
        }
    }
}

/// Value and optional correlation ID parsed from an MQTT set command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MqttSetCommandPayload {
    pub value: String,
    pub request_id: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct MqttCommandResult {
    pub request_id: Option<String>,
    pub command: String,
    pub status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poll_interval_secs: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

#[derive(Debug)]
pub struct DaemonCommandOutcome {
    pub result: MqttCommandResult,
    pub effect: CommandEffect,
    pub poll_interval_secs: Option<u64>,
}

#[derive(Deserialize)]
struct ReadNowCommand {
    #[serde(default)]
    request_id: Option<String>,
}

/// Parse a plain scalar payload or a JSON object containing `value_field` and
/// an optional `request_id`.
pub fn parse_mqtt_set_payload(payload: &[u8], value_field: &str) -> Result<MqttSetCommandPayload> {
    let payload = std::str::from_utf8(payload)
        .context("MQTT set command payload must be valid UTF-8")?
        .trim();

    if !payload.starts_with('{') {
        return Ok(MqttSetCommandPayload {
            value: payload.to_owned(),
            request_id: None,
        });
    }

    let mut object: serde_json::Map<String, serde_json::Value> =
        serde_json::from_str(payload).context("MQTT set command payload must be a JSON object")?;
    let request_id = match object.remove("request_id") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::String(request_id)) => Some(request_id),
        Some(_) => bail!("MQTT set command `request_id` must be a string"),
    };
    let value = object
        .remove(value_field)
        .with_context(|| format!("MQTT set command JSON must contain `{value_field}`"))?;
    let value = match value {
        serde_json::Value::String(value) => value,
        value => value.to_string(),
    };

    Ok(MqttSetCommandPayload { value, request_id })
}

/// Validate and apply a shared daemon control command.
///
/// The returned result and polling-interval update still need to be published
/// by the application. `result_prefix` preserves an application's naming
/// convention for rejected/unsupported commands.
pub fn process_daemon_command(
    command: &str,
    payload: &[u8],
    enabled: bool,
    result_prefix: &str,
    poll_interval: &mut Duration,
) -> DaemonCommandOutcome {
    let rejected =
        |command: String, request_id: Option<String>, error: String| DaemonCommandOutcome {
            result: MqttCommandResult {
                request_id,
                command,
                status: "rejected".to_owned(),
                poll_interval_secs: None,
                error: Some(error),
            },
            effect: CommandEffect::Continue,
            poll_interval_secs: None,
        };

    if !enabled {
        return rejected(
            format!("{result_prefix}{command}"),
            None,
            "daemon control is disabled".to_owned(),
        );
    }

    match command {
        "poll_interval_secs/set" => {
            let request = match parse_mqtt_set_payload(payload, "seconds") {
                Ok(request) => request,
                Err(error) => {
                    return rejected(
                        command.to_owned(),
                        None,
                        format!(
                            "payload must be an integer seconds value or JSON with a `seconds` field: {error:#}"
                        ),
                    );
                }
            };
            let seconds = match request.value.parse::<u64>() {
                Ok(seconds) => seconds,
                Err(_) => {
                    return rejected(
                        command.to_owned(),
                        request.request_id,
                        "seconds must be an integer".to_owned(),
                    );
                }
            };
            if seconds == 0 || seconds > MAX_POLL_INTERVAL.as_secs() {
                return rejected(
                    command.to_owned(),
                    request.request_id,
                    format!(
                        "seconds must be between 1 and {}",
                        MAX_POLL_INTERVAL.as_secs()
                    ),
                );
            }

            *poll_interval = Duration::from_secs(seconds);
            DaemonCommandOutcome {
                result: MqttCommandResult {
                    request_id: request.request_id,
                    command: command.to_owned(),
                    status: "applied".to_owned(),
                    poll_interval_secs: Some(seconds),
                    error: None,
                },
                effect: CommandEffect::Continue,
                poll_interval_secs: Some(seconds),
            }
        }
        "read_now" => {
            let request = if payload.is_empty() {
                Ok(ReadNowCommand { request_id: None })
            } else {
                serde_json::from_slice::<ReadNowCommand>(payload)
            };
            match request {
                Ok(request) => DaemonCommandOutcome {
                    result: MqttCommandResult {
                        request_id: request.request_id,
                        command: command.to_owned(),
                        status: "accepted".to_owned(),
                        poll_interval_secs: None,
                        error: None,
                    },
                    effect: CommandEffect::PollNow,
                    poll_interval_secs: None,
                },
                Err(_) => rejected(
                    command.to_owned(),
                    None,
                    "payload must be an empty message or JSON object".to_owned(),
                ),
            }
        }
        _ => rejected(
            format!("{result_prefix}{command}"),
            None,
            "unsupported daemon command".to_owned(),
        ),
    }
}

impl fmt::Debug for MqttConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MqttConfig")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("tls", &self.tls)
            .field("username", &self.username)
            .field("password", &self.password.as_ref().map(|_| "********"))
            .field("topic", &self.topic)
            .field("client_id", &self.client_id)
            .field("qos", &self.qos)
            .field("keep_alive", &self.keep_alive)
            .field("allow_control", &self.allow_control)
            .field("allow_daemon_control", &self.allow_daemon_control)
            .finish()
    }
}

impl MqttConfig {
    /// Load YAML configuration and apply the shared `MQTT_*` environment overrides.
    pub async fn load(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let path = path.as_ref();
        let source = tokio::fs::read_to_string(path)
            .await
            .with_context(|| format!("Cannot open MQTT config file {}", path.display()))?;
        let mut config: Self = yaml_serde::from_str(&source)
            .with_context(|| format!("Cannot parse MQTT config file {}", path.display()))?;
        config.apply_env_overrides()?;
        config.validate()?;
        Ok(config)
    }

    /// Validate settings supplied directly by the caller.
    pub fn validate(&self) -> Result<()> {
        if self.host.trim().is_empty() {
            bail!("MQTT host must not be empty");
        }
        if self.port == 0 {
            bail!("MQTT port must be greater than zero");
        }
        if self.topic.trim().is_empty() || self.topic.contains('+') || self.topic.contains('#') {
            bail!("MQTT topic must be non-empty and cannot contain wildcards");
        }
        if self.client_id.trim().is_empty() {
            bail!("MQTT client_id must not be empty");
        }
        if self.keep_alive.is_zero() {
            bail!("MQTT keep_alive must be greater than zero");
        }
        if self.keep_alive.subsec_nanos() != 0 || self.keep_alive.as_secs() > u16::MAX as u64 {
            bail!("MQTT keep_alive must be a whole number of seconds no greater than 65535");
        }
        if self.username.is_none() && self.password.is_some() {
            bail!("MQTT password requires a username");
        }
        if self.qos > 2 {
            bail!("MQTT QoS must be 0, 1, or 2");
        }
        Ok(())
    }

    /// Apply the standard `MQTT_*` environment overrides.
    pub fn apply_env_overrides(&mut self) -> Result<()> {
        if let Some(value) = env_value("MQTT_HOST")? {
            self.host = value;
        }
        if let Some(value) = env_value("MQTT_PORT")? {
            self.port = value;
        }
        if let Some(value) = env_value("MQTT_TLS")? {
            self.tls = value;
        }
        if let Some(value) = env_value("MQTT_USERNAME")? {
            self.username = Some(value);
        }
        if let Some(value) = env_value("MQTT_PASSWORD")? {
            self.password = Some(value);
        }
        if let Some(value) = env_value("MQTT_TOPIC")? {
            self.topic = value;
        }
        if let Some(value) = env_value("MQTT_CLIENT_ID")? {
            self.client_id = value;
        }
        if let Some(value) = env_value("MQTT_QOS")? {
            self.qos = value;
        }
        if let Some(value) = env_value::<String>("MQTT_KEEP_ALIVE")? {
            self.keep_alive = crate::duration::parse_duration(&value)
                .map_err(|error| anyhow::anyhow!("Invalid value for MQTT_KEEP_ALIVE: {error}"))?;
        } else if let Some(value) = env_value::<u16>("MQTT_KEEP_ALIVE_SECS")? {
            self.keep_alive = Duration::from_secs(value as u64);
        }
        if let Some(value) = env_value("MQTT_ALLOW_CONTROL")? {
            self.allow_control = value;
        }
        if let Some(value) = env_value("MQTT_ALLOW_DAEMON_CONTROL")? {
            self.allow_daemon_control = value;
        }
        Ok(())
    }

    fn qos(&self) -> QoS {
        match self.qos {
            0 => QoS::AtMostOnce,
            1 => QoS::AtLeastOnce,
            _ => QoS::ExactlyOnce,
        }
    }
}

fn env_value<T>(name: &str) -> Result<Option<T>>
where
    T: FromStr,
    T::Err: fmt::Display,
{
    match std::env::var(name) {
        Ok(value) => value
            .parse()
            .map(Some)
            .map_err(|error| anyhow::anyhow!("Invalid value for {name}: {error}")),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(error) => Err(error).with_context(|| format!("Cannot read {name}")),
    }
}

/// A control packet delivered to the device-specific command adapter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MqttControlMessage {
    pub topic: String,
    pub payload: Vec<u8>,
}

/// Shared MQTT connection and publication primitives.
#[derive(Clone)]
pub struct MqttClient {
    client: AsyncClient,
    topic: String,
    qos: QoS,
    device_status: Arc<AtomicU8>,
    shutting_down: Arc<std::sync::atomic::AtomicBool>,
}

impl MqttClient {
    pub fn connect(config: &MqttConfig) -> Result<(Self, EventLoop)> {
        config.validate()?;
        let mut options = MqttOptions::new(&config.client_id, (config.host.as_str(), config.port));
        let keep_alive_secs = u16::try_from(config.keep_alive.as_secs())
            .context("MQTT keep_alive exceeds the supported whole-second range")?;
        options.set_keep_alive(keep_alive_secs);
        options.set_last_will(LastWill::new(
            format!("{}/daemon_state", config.topic),
            "offline",
            QoS::AtLeastOnce,
            true,
        ));
        if config.username.is_some() || config.password.is_some() {
            options.set_credentials(
                config.username.clone().unwrap_or_default(),
                config.password.clone().unwrap_or_default(),
            );
        }
        if config.tls {
            options.set_transport(Transport::tls_with_default_config());
        }

        let (client, event_loop) = AsyncClient::builder(options)
            .capacity(100)
            .try_build()
            .context("Failed to create MQTT client")?;
        Ok((
            Self {
                client,
                topic: config.topic.clone(),
                qos: config.qos(),
                device_status: Arc::new(AtomicU8::new(status_code(HardwareStatus::Unknown))),
                shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            },
            event_loop,
        ))
    }

    pub fn topic(&self) -> &str {
        &self.topic
    }

    pub fn command_name<'a>(&self, topic: &'a str, group: &str) -> Option<&'a str> {
        let prefix = format!("{}/command/{group}/", self.topic);
        topic.strip_prefix(&prefix)
    }

    pub async fn publish_daemon_availability(&self, online: bool) -> Result<()> {
        self.client
            .publish(
                format!("{}/daemon_state", self.topic),
                if online { "online" } else { "offline" },
                PublishOptions::new(QoS::AtLeastOnce).retained(),
            )
            .await
            .context("Failed to publish daemon availability")
    }

    pub async fn publish_hardware_availability(&self, status: HardwareStatus) -> Result<()> {
        self.client
            .publish(
                format!("{}/device_state", self.topic),
                status.as_str(),
                PublishOptions::new(QoS::AtLeastOnce).retained(),
            )
            .await
            .context("Failed to publish device availability")?;
        self.device_status
            .store(status_code(status), Ordering::Relaxed);
        Ok(())
    }

    async fn republish_device_availability(&self) -> Result<()> {
        self.client
            .publish(
                format!("{}/device_state", self.topic),
                status_from_code(self.device_status.load(Ordering::Relaxed)).as_str(),
                PublishOptions::new(QoS::AtLeastOnce).retained(),
            )
            .await
            .context("Failed to republish device availability")
    }

    fn is_shutting_down(&self) -> bool {
        self.shutting_down.load(Ordering::Relaxed)
    }

    pub async fn publish_state<T: Serialize>(&self, device: &str, values: &T) -> Result<()> {
        let payload = state_envelope(device, values)?;
        self.client
            .publish(
                format!("{}/telemetry", self.topic),
                payload,
                PublishOptions::new(self.qos).retained(),
            )
            .await
            .context("Failed to publish device state")
    }

    pub async fn publish_individual<T: Serialize>(&self, values: &T, retained: bool) -> Result<()> {
        for (path, value) in flatten_values(values)? {
            if path.contains('+') || path.contains('#') {
                bail!("Individual MQTT value path cannot contain wildcards: {path}");
            }
            let options = PublishOptions::new(self.qos);
            let options = if retained {
                options.retained()
            } else {
                options
            };
            self.client
                .publish(format!("{}/telemetry/{path}", self.topic), value, options)
                .await
                .with_context(|| format!("Failed to publish MQTT value {path}"))?;
        }
        Ok(())
    }

    pub async fn publish_metrics<T: Serialize>(
        &self,
        metrics: &BTreeMap<String, T>,
        retained: bool,
    ) -> Result<()> {
        for (metric, value) in metrics {
            if metric.is_empty()
                || metric.contains('/')
                || metric.contains('+')
                || metric.contains('#')
            {
                bail!("Invalid MQTT metric name: {metric}");
            }
            let payload = serde_json::to_string(value)
                .with_context(|| format!("Cannot serialize MQTT metric {metric}"))?;
            let options = PublishOptions::new(self.qos);
            let options = if retained {
                options.retained()
            } else {
                options
            };
            self.client
                .publish(
                    format!("{}/telemetry/{metric}", self.topic),
                    payload,
                    options,
                )
                .await
                .with_context(|| format!("Failed to publish MQTT metric {metric}"))?;
        }
        Ok(())
    }

    pub async fn publish_daemon_poll_interval(&self, interval_secs: u64) -> Result<()> {
        self.client
            .publish(
                format!("{}/daemon_config/poll_interval_secs", self.topic),
                interval_secs.to_string(),
                PublishOptions::new(QoS::AtLeastOnce).retained(),
            )
            .await
            .context("Failed to publish daemon poll interval")
    }

    pub async fn publish_command_result<T: Serialize>(&self, result: &T) -> Result<()> {
        let payload =
            serde_json::to_string(result).context("Cannot serialize MQTT command result")?;
        self.client
            .publish(
                format!("{}/command/result", self.topic),
                payload,
                PublishOptions::new(self.qos),
            )
            .await
            .context("Failed to publish MQTT command result")
    }

    pub async fn subscribe(&self, filter: &str) -> Result<()> {
        self.client
            .subscribe(filter, QoS::AtLeastOnce)
            .await
            .with_context(|| format!("Failed to subscribe to MQTT control filter {filter}"))
    }

    pub async fn disconnect(&self) -> Result<()> {
        self.client
            .disconnect()
            .await
            .context("Failed to disconnect from MQTT broker")
    }
}

#[derive(Serialize)]
struct StateEnvelope<'a, T> {
    device: &'a str,
    timestamp_unix_ms: u64,
    values: &'a T,
}

/// Serialize values using the common retained `<topic>/telemetry` envelope shape.
pub fn state_envelope<T: Serialize>(device: &str, values: &T) -> Result<String> {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .context("System clock is before the Unix epoch")?
        .as_millis()
        .try_into()
        .context("Unix timestamp does not fit in u64 milliseconds")?;
    serde_json::to_string(&StateEnvelope {
        device,
        timestamp_unix_ms: timestamp,
        values,
    })
    .context("Cannot serialize device state envelope")
}

/// MQTT sink using the common state envelope and flattened individual topics.
pub struct MqttOutput {
    client: MqttClient,
    device: String,
    format: OutputFormat,
    retain_individual: bool,
    event_task: Option<JoinHandle<()>>,
    control_receiver: Option<mpsc::Receiver<MqttControlMessage>>,
}

impl MqttOutput {
    /// Create a sink and start its broker event loop.
    ///
    /// The optional control filter is subscribed only when device or daemon
    /// control is enabled in the MQTT configuration. Retained control packets
    /// are dropped.
    pub fn new(
        config: &MqttConfig,
        device: impl Into<String>,
        format: OutputFormat,
        control_filter: Option<String>,
        retain_individual: bool,
    ) -> Result<Self> {
        let (client, event_loop) = MqttClient::connect(config)?;
        let (control_sender, control_receiver) = mpsc::channel(32);
        let filter = if config.allow_control || config.allow_daemon_control {
            control_filter.or_else(|| {
                if config.allow_daemon_control {
                    Some(format!("{}/command/daemon/#", config.topic))
                } else {
                    Some(format!("{}/set/#", config.topic))
                }
            })
        } else {
            None
        };
        let event_task = Some(spawn_event_loop(
            client.clone(),
            event_loop,
            filter,
            control_sender,
        ));
        Ok(Self {
            client,
            device: device.into(),
            format,
            retain_individual,
            event_task,
            control_receiver: Some(control_receiver),
        })
    }

    /// Take the control receiver for passing to the daemon runner.
    pub fn take_control_receiver(&mut self) -> Option<mpsc::Receiver<MqttControlMessage>> {
        self.control_receiver.take()
    }

    pub fn client(&self) -> MqttClient {
        self.client.clone()
    }

    pub async fn publish_metrics<T: Serialize>(&self, metrics: &BTreeMap<String, T>) -> Result<()> {
        self.client
            .publish_metrics(metrics, self.retain_individual)
            .await
    }
}

#[async_trait]
impl<S> Output<S> for MqttOutput
where
    S: Serialize + Send + Sync,
{
    async fn publish(&mut self, snapshot: &S) -> Result<()> {
        match self.format {
            OutputFormat::Json => self.client.publish_state(&self.device, snapshot).await,
            OutputFormat::Individual => {
                self.client
                    .publish_individual(snapshot, self.retain_individual)
                    .await
            }
        }
    }

    async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
        self.client.publish_hardware_availability(status).await
    }

    async fn shutdown(&mut self) -> Result<()> {
        self.client.shutting_down.store(true, Ordering::Relaxed);
        let shutdown_result = tokio::time::timeout(MQTT_SHUTDOWN_TIMEOUT, async {
            let mut shutdown_error = self.client.publish_daemon_availability(false).await.err();
            sleep(Duration::from_millis(250)).await;
            if let Err(error) = self.client.disconnect().await {
                if shutdown_error.is_none() {
                    shutdown_error = Some(error);
                }
            }
            shutdown_error.map_or(Ok(()), Err)
        })
        .await
        .context("MQTT shutdown timed out")
        .and_then(|result| result);
        if let Some(task) = self.event_task.take() {
            task.abort();
            let _ = task.await;
        }
        shutdown_result
    }
}

fn spawn_event_loop(
    client: MqttClient,
    mut event_loop: EventLoop,
    control_filter: Option<String>,
    control_sender: mpsc::Sender<MqttControlMessage>,
) -> JoinHandle<()> {
    tokio::spawn(async move {
        let mut retry_ceiling = INITIAL_RECONNECT_CEILING;
        loop {
            match event_loop.poll().await {
                Ok(Event::Incoming(Incoming::ConnAck(_))) => {
                    info!("Connected to MQTT broker");
                    retry_ceiling = INITIAL_RECONNECT_CEILING;
                    if !client.is_shutting_down() {
                        if let Err(error) = client.publish_daemon_availability(true).await {
                            warn!("{error:#}");
                        }
                        if let Err(error) = client.republish_device_availability().await {
                            warn!("{error:#}");
                        }
                        if let Some(filter) = &control_filter {
                            if let Err(error) = client.subscribe(filter).await {
                                warn!("{error:#}");
                            }
                        }
                    }
                }
                Ok(Event::Incoming(Incoming::Publish(publish))) => {
                    if control_filter.is_none() {
                        continue;
                    }
                    if publish.retain {
                        let topic = String::from_utf8_lossy(&publish.topic).into_owned();
                        warn!("Ignoring retained MQTT control message on {topic}");
                        continue;
                    }
                    let message = MqttControlMessage {
                        topic: String::from_utf8_lossy(&publish.topic).into_owned(),
                        payload: publish.payload.to_vec(),
                    };
                    if control_sender.send(message).await.is_err() {
                        warn!("MQTT control receiver closed; stopping event loop");
                        break;
                    }
                }
                Ok(_) => {}
                Err(error) => {
                    let delay = equal_jitter(retry_ceiling);
                    warn!("MQTT connection unavailable: {error}; retrying in {delay:?}");
                    sleep(delay).await;
                    retry_ceiling = retry_ceiling
                        .checked_mul(2)
                        .unwrap_or(MAX_RECONNECT_CEILING)
                        .min(MAX_RECONNECT_CEILING);
                }
            }
        }
    })
}

fn equal_jitter(ceiling: Duration) -> Duration {
    let upper_millis = ceiling.as_millis().clamp(1, u64::MAX.into()) as u64;
    let lower_millis = upper_millis.div_ceil(2);
    Duration::from_millis(rand::rng().random_range(lower_millis..=upper_millis))
}

const fn status_code(status: HardwareStatus) -> u8 {
    match status {
        HardwareStatus::Unknown => 0,
        HardwareStatus::Online => 1,
        HardwareStatus::Offline => 2,
    }
}

const fn status_from_code(code: u8) -> HardwareStatus {
    match code {
        1 => HardwareStatus::Online,
        2 => HardwareStatus::Offline,
        _ => HardwareStatus::Unknown,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_mqtt_set_payload_values_and_request_ids() {
        let payload = parse_mqtt_set_payload(b" 16.0 \n", "value").unwrap();
        assert_eq!(payload.value, "16.0");
        assert_eq!(payload.request_id, None);

        let payload =
            parse_mqtt_set_payload(br#"{"value":16.0,"request_id":"current-1"}"#, "value").unwrap();
        assert_eq!(payload.value, "16.0");
        assert_eq!(payload.request_id.as_deref(), Some("current-1"));

        let payload =
            parse_mqtt_set_payload(br#"{"seconds":30,"request_id":"interval-1"}"#, "seconds")
                .unwrap();
        assert_eq!(payload.value, "30");
        assert_eq!(payload.request_id.as_deref(), Some("interval-1"));
    }

    #[test]
    fn rejects_invalid_mqtt_set_json_payloads() {
        assert!(parse_mqtt_set_payload(br#"{"value":1"#, "value").is_err());
        assert!(parse_mqtt_set_payload(br#"{"request_id":"id"}"#, "value").is_err());
        assert!(parse_mqtt_set_payload(br#"{"value":1,"request_id":true}"#, "value").is_err());
    }

    #[test]
    fn processes_shared_daemon_commands() {
        let mut poll_interval = Duration::from_secs(5);
        let outcome = process_daemon_command(
            "poll_interval_secs/set",
            br#"{"seconds":30,"request_id":"interval-1"}"#,
            true,
            "daemon/",
            &mut poll_interval,
        );
        assert_eq!(poll_interval, Duration::from_secs(30));
        assert_eq!(outcome.poll_interval_secs, Some(30));
        assert_eq!(outcome.effect, CommandEffect::Continue);
        assert_eq!(outcome.result.request_id.as_deref(), Some("interval-1"));
        assert_eq!(outcome.result.command, "poll_interval_secs/set");
        assert_eq!(outcome.result.status, "applied");

        let outcome = process_daemon_command(
            "read_now",
            br#"{"request_id":"read-1"}"#,
            true,
            "daemon/",
            &mut poll_interval,
        );
        assert_eq!(outcome.effect, CommandEffect::PollNow);
        assert_eq!(outcome.result.request_id.as_deref(), Some("read-1"));
    }

    #[test]
    fn rejects_invalid_or_disabled_daemon_commands_without_changing_interval() {
        let mut poll_interval = Duration::from_secs(5);
        let outcome = process_daemon_command(
            "poll_interval_secs/set",
            b"0",
            true,
            "daemon/",
            &mut poll_interval,
        );
        assert_eq!(poll_interval, Duration::from_secs(5));
        assert_eq!(outcome.result.status, "rejected");
        assert_eq!(outcome.result.request_id, None);

        let outcome =
            process_daemon_command("unsupported", b"", false, "daemon/", &mut poll_interval);
        assert_eq!(outcome.result.command, "daemon/unsupported");
        assert_eq!(
            outcome.result.error.as_deref(),
            Some("daemon control is disabled")
        );
    }

    #[test]
    fn configuration_defaults_are_safe_and_valid() {
        let config = MqttConfig::default();
        assert!(!config.allow_control);
        assert!(!config.allow_daemon_control);
        assert_eq!(config.topic, "device");
        assert_eq!(config.keep_alive, Duration::from_secs(30));
        assert!(config.validate().is_ok());
    }

    #[test]
    fn keep_alive_accepts_duration_and_legacy_seconds_configuration() {
        let config: MqttConfig = yaml_serde::from_str("keep_alive: 45s").unwrap();
        assert_eq!(config.keep_alive, Duration::from_secs(45));
        assert!(config.validate().is_ok());

        let config: MqttConfig = yaml_serde::from_str("keep_alive_secs: 30").unwrap();
        assert_eq!(config.keep_alive, Duration::from_secs(30));
        assert!(config.validate().is_ok());
    }

    #[test]
    fn keep_alive_must_be_whole_seconds_within_protocol_range() {
        let config: MqttConfig = yaml_serde::from_str("keep_alive: 1500ms").unwrap();
        assert!(config.validate().is_err());
        let config: MqttConfig = yaml_serde::from_str("keep_alive: 0s").unwrap();
        assert!(config.validate().is_err());
        let config: MqttConfig = yaml_serde::from_str("keep_alive: 65536s").unwrap();
        assert!(config.validate().is_err());
    }

    #[test]
    fn rejects_invalid_topics_and_qos() {
        let config = MqttConfig {
            topic: "bad/#".to_owned(),
            ..MqttConfig::default()
        };
        assert!(config.validate().is_err());
        let config = MqttConfig {
            qos: 3,
            ..MqttConfig::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn state_payload_has_the_shared_envelope() {
        let payload = state_envelope("demo", &serde_json::json!({"value": 42})).unwrap();
        let value: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert!(value.get("schema_version").is_none());
        assert_eq!(value["device"], "demo");
        assert!(value["timestamp_unix_ms"].is_u64());
        assert_eq!(value["values"]["value"], 42);
    }

    #[test]
    fn reconnect_jitter_stays_in_the_upper_half_of_its_ceiling() {
        for ceiling in [
            Duration::from_secs(1),
            Duration::from_secs(8),
            MAX_RECONNECT_CEILING,
        ] {
            let delay = equal_jitter(ceiling);
            assert!(delay >= ceiling / 2);
            assert!(delay <= ceiling);
        }
    }
}