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
//! Protocol-neutral orchestration for serial device discovery.
//!
//! The caller supplies only configurations supported by its device and owns
//! the protocol-specific connect/probe implementation. This module never
//! assumes a broadcast address or that a failed probe means "not found".

use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use std::{collections::HashSet, time::Duration};
use tokio::{
    io::{AsyncBufReadExt, AsyncWriteExt},
    sync::watch,
    task::JoinHandle,
    time,
};

/// Read a yes/no response using a shared asynchronous console prompt.
///
/// If `invalid_response` is supplied, it is printed and the prompt is repeated
/// when the input is not a recognized yes/no response.
pub async fn confirm_yes_no(prompt: &str, invalid_response: Option<&str>) -> Result<bool> {
    let mut stdin = tokio::io::BufReader::new(tokio::io::stdin());
    let mut stdout = tokio::io::stdout();

    loop {
        stdout
            .write_all(prompt.as_bytes())
            .await
            .context("Failed to write confirmation prompt")?;
        stdout
            .flush()
            .await
            .context("Failed to flush confirmation prompt")?;

        let mut response = String::new();
        if stdin
            .read_line(&mut response)
            .await
            .context("Failed to read user confirmation")?
            == 0
        {
            return Ok(false);
        }

        match response.trim().to_ascii_lowercase().as_str() {
            "y" | "yes" => return Ok(true),
            "" | "n" | "no" => return Ok(false),
            _ => match invalid_response {
                Some(message) => {
                    stdout
                        .write_all(message.as_bytes())
                        .await
                        .context("Failed to write invalid-response message")?;
                }
                None => return Ok(false),
            },
        }
    }
}

/// Create a shutdown receiver that is set when Ctrl-C is received.
pub fn ctrl_c_shutdown() -> (watch::Receiver<bool>, JoinHandle<()>) {
    let (shutdown_sender, shutdown_receiver) = watch::channel(false);
    let signal_task = tokio::spawn(async move {
        if let Err(error) = tokio::signal::ctrl_c().await {
            log::warn!("Failed to listen for Ctrl-C during address scan: {error}");
        }
        let _ = shutdown_sender.send(true);
    });
    (shutdown_receiver, signal_task)
}

/// Stop the Ctrl-C listener after the scan has finished.
pub async fn stop_signal_task(signal_task: JoinHandle<()>) {
    signal_task.abort();
    let _ = signal_task.await;
}

/// Serial parameters for one explicitly supported device configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SerialSettings {
    pub baud_rate: u32,
    pub data_bits: u8,
    pub parity: Parity,
    pub stop_bits: u8,
    pub flow_control: FlowControl,
}

/// Serial parity mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Parity {
    None,
    Even,
    Odd,
}

/// Serial flow-control mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FlowControl {
    None,
    Software,
    Hardware,
}

/// Address candidates, in the order to probe for each serial configuration.
///
/// The broadcast address is optional and is never inferred from the protocol.
/// Applications should only include it when the device protocol defines a
/// useful, safe response to probing that address.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddressPlan {
    pub default: Option<u8>,
    pub broadcast: Option<u8>,
    pub addresses: Vec<u8>,
}

impl AddressPlan {
    fn ordered_unique(&self) -> Vec<u8> {
        let mut seen = HashSet::new();
        self.default
            .into_iter()
            .chain(self.broadcast)
            .chain(self.addresses.iter().copied())
            .filter(|address| seen.insert(*address))
            .collect()
    }

    fn validate(&self) -> Result<()> {
        if self.default.is_none() && self.broadcast.is_none() && self.addresses.is_empty() {
            bail!("Serial scan address plan must contain at least one address");
        }
        Ok(())
    }
}

/// Device-specific scan limits and the exact supported candidate set.
#[derive(Debug, Clone)]
pub struct ScanProfile {
    pub default_serial: SerialSettings,
    /// Valid settings only; unsupported baud/parity combinations are excluded.
    pub supported_serial: Vec<SerialSettings>,
    pub addresses: AddressPlan,
    pub operation_timeout: Duration,
    pub delay_between_probes: Duration,
    pub stop_after_first_match: bool,
}

impl ScanProfile {
    pub fn validate(&self) -> Result<()> {
        if self.operation_timeout.is_zero() {
            bail!("Serial scan operation timeout must be greater than zero");
        }
        if self.default_serial.baud_rate == 0 {
            bail!("Default serial scan baud rate must be greater than zero");
        }
        if self
            .supported_serial
            .iter()
            .any(|settings| settings.baud_rate == 0)
        {
            bail!("Supported serial scan baud rates must be greater than zero");
        }
        self.addresses.validate()
    }

    fn ordered_serial_settings(&self) -> Vec<SerialSettings> {
        let mut seen = HashSet::new();
        std::iter::once(self.default_serial)
            .chain(self.supported_serial.iter().copied())
            .filter(|settings| seen.insert(*settings))
            .collect()
    }
}

/// Result of applying serial parameters to the underlying adapter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigureResult {
    Ready,
    Unsupported,
}

/// One confirmed device found during a scan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScanMatch<T> {
    pub serial: SerialSettings,
    pub address: u8,
    pub details: T,
}

/// Summary returned after scanning all candidates or finding the configured
/// first match. A cancelled scan returns the matches collected so far.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScanReport<T> {
    pub matches: Vec<ScanMatch<T>>,
    pub configurations_tested: usize,
    pub probes_attempted: usize,
    pub cancelled: bool,
}

/// Device-specific serial connection and protocol probe.
#[async_trait]
pub trait SerialProbe: Send {
    type Match: Send;

    /// Configure/open the serial transport for one supported setting.
    ///
    /// Return `Unsupported` when this adapter/OS cannot apply the setting.
    /// Unexpected I/O errors should be returned as errors and abort scanning.
    async fn configure(&mut self, settings: SerialSettings) -> Result<ConfigureResult>;

    /// Check whether a device responds at an address.
    ///
    /// Return `Ok(None)` for an expected no-response or protocol mismatch.
    /// Return an error for failures that should abort the scan. Device
    /// adapters decide which protocol errors are ordinary misses.
    async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>>;
}

/// Scan serial settings and addresses sequentially in profile order.
///
/// The default serial settings are always tried first. For each configuration,
/// address order is default, optional broadcast, then the explicit address
/// list, with duplicates removed. Every configure/probe call is bounded by the
/// profile timeout. A `true` shutdown watch value stops scanning promptly.
pub async fn scan<P: SerialProbe>(
    profile: &ScanProfile,
    probe: &mut P,
    mut shutdown: watch::Receiver<bool>,
) -> Result<ScanReport<P::Match>> {
    profile.validate()?;
    let mut report = ScanReport {
        matches: Vec::new(),
        configurations_tested: 0,
        probes_attempted: 0,
        cancelled: false,
    };
    let addresses = profile.addresses.ordered_unique();

    for settings in profile.ordered_serial_settings() {
        if *shutdown.borrow() {
            report.cancelled = true;
            break;
        }

        let configure_result = tokio::select! {
            result = time::timeout(profile.operation_timeout, probe.configure(settings)) => {
                result.context("Timed out configuring serial scan settings")??
            }
            changed = shutdown.changed() => {
                if changed.is_err() || *shutdown.borrow() {
                    report.cancelled = true;
                    break;
                }
                continue;
            }
        };
        if configure_result == ConfigureResult::Unsupported {
            continue;
        }
        report.configurations_tested += 1;

        for &address in &addresses {
            if *shutdown.borrow() {
                report.cancelled = true;
                break;
            }
            if report.probes_attempted > 0 && !profile.delay_between_probes.is_zero() {
                tokio::select! {
                    _ = time::sleep(profile.delay_between_probes) => {}
                    changed = shutdown.changed() => {
                        if changed.is_err() || *shutdown.borrow() {
                            report.cancelled = true;
                            break;
                        }
                    }
                }
            }
            if report.cancelled {
                break;
            }

            report.probes_attempted += 1;
            let result = tokio::select! {
                result = time::timeout(profile.operation_timeout, probe.probe(address)) => {
                    result.context("Timed out probing serial scan address")??
                }
                changed = shutdown.changed() => {
                    if changed.is_err() || *shutdown.borrow() {
                        report.cancelled = true;
                        break;
                    }
                    continue;
                }
            };
            if let Some(details) = result {
                report.matches.push(ScanMatch {
                    serial: settings,
                    address,
                    details,
                });
                if profile.stop_after_first_match {
                    return Ok(report);
                }
            }
        }
        if report.cancelled {
            break;
        }
    }
    Ok(report)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        collections::VecDeque,
        sync::{Arc, Mutex},
    };

    fn settings(baud_rate: u32, parity: Parity) -> SerialSettings {
        SerialSettings {
            baud_rate,
            data_bits: 8,
            parity,
            stop_bits: 1,
            flow_control: FlowControl::None,
        }
    }

    fn profile() -> ScanProfile {
        ScanProfile {
            default_serial: settings(9_600, Parity::None),
            supported_serial: vec![
                settings(9_600, Parity::None),
                settings(19_200, Parity::Even),
            ],
            addresses: AddressPlan {
                default: Some(1),
                broadcast: Some(0),
                addresses: vec![1, 2, 3],
            },
            operation_timeout: Duration::from_secs(1),
            delay_between_probes: Duration::ZERO,
            stop_after_first_match: false,
        }
    }

    #[derive(Default)]
    struct FakeProbe {
        configured: Vec<SerialSettings>,
        addresses: Vec<u8>,
        hits: VecDeque<(u32, u8, &'static str)>,
    }

    #[async_trait]
    impl SerialProbe for FakeProbe {
        type Match = &'static str;

        async fn configure(&mut self, settings: SerialSettings) -> Result<ConfigureResult> {
            self.configured.push(settings);
            Ok(ConfigureResult::Ready)
        }

        async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>> {
            self.addresses.push(address);
            let Some((baud_rate, hit_address, details)) = self.hits.front().copied() else {
                return Ok(None);
            };
            if baud_rate == 9_600 && hit_address == address {
                self.hits.pop_front();
                Ok(Some(details))
            } else {
                Ok(None)
            }
        }
    }

    #[tokio::test]
    async fn scans_default_settings_then_deduplicated_addresses() {
        let mut probe = FakeProbe::default();
        let (_shutdown_sender, shutdown) = watch::channel(false);
        let mut profile = profile();
        profile.supported_serial.truncate(1);

        let report = scan(&profile, &mut probe, shutdown).await.unwrap();

        assert_eq!(probe.configured, vec![settings(9_600, Parity::None)]);
        assert_eq!(probe.addresses, vec![1, 0, 2, 3]);
        assert_eq!(report.probes_attempted, 4);
    }

    #[tokio::test]
    async fn supports_optional_broadcast_and_explicit_valid_settings() {
        let mut probe = FakeProbe {
            hits: VecDeque::from([(9_600, 0, "found")]),
            ..FakeProbe::default()
        };
        let (_shutdown_sender, shutdown) = watch::channel(false);
        let mut profile = profile();
        profile.stop_after_first_match = true;

        let report = scan(&profile, &mut probe, shutdown).await.unwrap();

        assert_eq!(report.matches.len(), 1);
        assert_eq!(report.matches[0].address, 0);
        assert_eq!(report.matches[0].details, "found");
        assert_eq!(probe.addresses, vec![1, 0]);
    }

    #[tokio::test]
    async fn skips_unsupported_configurations() {
        struct UnsupportedProbe(Arc<Mutex<Vec<SerialSettings>>>);

        #[async_trait]
        impl SerialProbe for UnsupportedProbe {
            type Match = ();

            async fn configure(&mut self, settings: SerialSettings) -> Result<ConfigureResult> {
                self.0.lock().unwrap().push(settings);
                Ok(ConfigureResult::Unsupported)
            }

            async fn probe(&mut self, _address: u8) -> Result<Option<Self::Match>> {
                panic!("unsupported configuration must not be probed");
            }
        }

        let attempted = Arc::new(Mutex::new(Vec::new()));
        let mut probe = UnsupportedProbe(attempted.clone());
        let (_shutdown_sender, shutdown) = watch::channel(false);
        let report = scan(&profile(), &mut probe, shutdown).await.unwrap();

        assert_eq!(report.configurations_tested, 0);
        assert_eq!(attempted.lock().unwrap().len(), 2);
    }

    #[test]
    fn validates_profiles_and_rejects_empty_address_sets() {
        let mut profile = profile();
        profile.operation_timeout = Duration::ZERO;
        assert!(profile.validate().is_err());
        profile.operation_timeout = Duration::from_secs(1);
        profile.addresses = AddressPlan {
            default: None,
            broadcast: None,
            addresses: Vec::new(),
        };
        assert!(profile.validate().is_err());
    }
}