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,
};
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),
},
}
}
}
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)
}
pub async fn stop_signal_task(signal_task: JoinHandle<()>) {
signal_task.abort();
let _ = signal_task.await;
}
#[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,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Parity {
None,
Even,
Odd,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FlowControl {
None,
Software,
Hardware,
}
#[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(())
}
}
#[derive(Debug, Clone)]
pub struct ScanProfile {
pub default_serial: SerialSettings,
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()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigureResult {
Ready,
Unsupported,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScanMatch<T> {
pub serial: SerialSettings,
pub address: u8,
pub details: T,
}
#[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,
}
#[async_trait]
pub trait SerialProbe: Send {
type Match: Send;
async fn configure(&mut self, settings: SerialSettings) -> Result<ConfigureResult>;
async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>>;
}
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());
}
}