use std::{
collections::{BTreeMap, BTreeSet},
num::NonZeroU8,
time::Duration,
};
use thiserror::Error;
use crate::{
Address, Master,
operation::{DeviceIdentity, Operation, ReadDeviceIdentity, Request},
profile::{AddressTiming, AddressTimings, LineProfile},
service::{ExchangeError, LinkClient, QueueId, RetryPolicy},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredDevice {
pub module: u16,
pub address: Address,
pub identity: DeviceIdentity,
}
#[derive(Debug, Default)]
pub struct DiscoveryReport {
pub attempts: usize,
pub hinted_attempts: usize,
pub hint_fallbacks: usize,
pub passes_completed: u8,
pub devices: Vec<DiscoveredDevice>,
pub errors: Vec<(Address, ExchangeError)>,
}
pub const MAXIMUM_DISCOVERY_HINTS: usize = 128;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiscoveryHints {
preambles: BTreeMap<Address, u8>,
}
impl DiscoveryHints {
pub const fn new() -> Self {
Self {
preambles: BTreeMap::new(),
}
}
pub fn insert(&mut self, address: Address, preambles: u8) -> Result<(), DiscoveryHintError> {
if address.polling_node().is_none() {
return Err(DiscoveryHintError::UniqueAddress);
}
if !(2..=40).contains(&preambles) {
return Err(DiscoveryHintError::Preambles(preambles));
}
if !self.preambles.contains_key(&address) && self.preambles.len() >= MAXIMUM_DISCOVERY_HINTS
{
return Err(DiscoveryHintError::Limit(MAXIMUM_DISCOVERY_HINTS));
}
self.preambles.insert(address, preambles);
Ok(())
}
pub fn get(&self, address: Address) -> Option<u8> {
self.preambles.get(&address).copied()
}
pub fn len(&self) -> usize {
self.preambles.len()
}
pub fn is_empty(&self) -> bool {
self.preambles.is_empty()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum DiscoveryHintError {
#[error("discovery hint requires a short polling address")]
UniqueAddress,
#[error("discovery preamble hint {0} is outside 2..=40")]
Preambles(u8),
#[error("discovery hint limit {0} reached")]
Limit(usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveryOptions {
pub passes: NonZeroU8,
pub queue: QueueId,
pub retry: RetryPolicy,
pub pass_delay: Duration,
pub preamble_hints: DiscoveryHints,
}
impl Default for DiscoveryOptions {
fn default() -> Self {
Self {
passes: NonZeroU8::MIN,
queue: QueueId::DEFAULT,
retry: RetryPolicy::default(),
pass_delay: Duration::ZERO,
preamble_hints: DiscoveryHints::new(),
}
}
}
impl DiscoveryOptions {
pub const fn with_passes(mut self, passes: NonZeroU8) -> Self {
self.passes = passes;
self
}
pub const fn with_queue(mut self, queue: QueueId) -> Self {
self.queue = queue;
self
}
pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
}
pub const fn with_pass_delay(mut self, pass_delay: Duration) -> Self {
self.pass_delay = pass_delay;
self
}
pub fn with_preamble_hints(mut self, preamble_hints: DiscoveryHints) -> Self {
self.preamble_hints = preamble_hints;
self
}
}
#[derive(Debug, Error)]
pub enum DiscoveryError {
#[error(transparent)]
Profile(#[from] crate::profile::ProfileError),
#[error(transparent)]
Retry(#[from] crate::service::RetryPolicyError),
#[error("discovery pass delay {0:?} exceeds the supported limit")]
PassDelay(Duration),
}
pub async fn discover_line(
link: &LinkClient,
profile: &LineProfile,
master: Master,
) -> Result<DiscoveryReport, crate::profile::ProfileError> {
profile.validate()?;
Ok(discover_validated(link, profile, master, DiscoveryOptions::default(), None).await)
}
pub async fn discover_line_with_options(
link: &LinkClient,
profile: &LineProfile,
master: Master,
options: DiscoveryOptions,
) -> Result<DiscoveryReport, DiscoveryError> {
profile.validate()?;
options.retry.validate()?;
if options.pass_delay > crate::profile::MAXIMUM_PROFILE_DURATION {
return Err(DiscoveryError::PassDelay(options.pass_delay));
}
Ok(discover_validated(link, profile, master, options, None).await)
}
pub async fn discover_line_with_address_timings(
link: &LinkClient,
profile: &LineProfile,
master: Master,
options: DiscoveryOptions,
address_timings: &AddressTimings,
) -> Result<DiscoveryReport, DiscoveryError> {
profile.validate()?;
options.retry.validate()?;
if options.pass_delay > crate::profile::MAXIMUM_PROFILE_DURATION {
return Err(DiscoveryError::PassDelay(options.pass_delay));
}
for (_, timing) in address_timings.iter() {
if let Some(response_timeout) = timing.response_timeout {
discovery_retry(options.retry, response_timeout, true).validate_runtime()?;
}
}
Ok(discover_validated(link, profile, master, options, Some(address_timings)).await)
}
async fn discover_validated(
link: &LinkClient,
profile: &LineProfile,
master: Master,
options: DiscoveryOptions,
address_timings: Option<&AddressTimings>,
) -> DiscoveryReport {
if !profile.timing.connect_settle.is_zero() {
tokio::time::sleep(profile.timing.connect_settle).await;
}
let mut report = DiscoveryReport::default();
let mut wake_prefix = Some(profile.wake_prefix.clone());
for pass in 0..options.passes.get() {
let mut visited = BTreeSet::new();
let mut previous_probe = false;
for module in &profile.modules {
for local in module.polling.iter() {
let Some(node) = LineProfile::shifted_address(*module, local) else {
continue;
};
let Ok(address) = Address::polling(node, master) else {
continue;
};
if !visited.insert(address)
|| report
.devices
.iter()
.any(|device| device.address == address)
{
continue;
}
if previous_probe && !profile.timing.scan_interval.is_zero() {
tokio::time::sleep(profile.timing.scan_interval).await;
}
previous_probe = true;
let address_timing = wait_for_address_timing(address_timings, node).await;
let conservative = profile.discovery_preambles;
let hinted = (pass == 0)
.then(|| options.preamble_hints.get(address))
.flatten()
.filter(|preambles| *preambles < conservative);
let first = hinted.unwrap_or(conservative);
for (probe, preambles) in [first, conservative].into_iter().enumerate() {
if probe == 1 && hinted.is_none() {
break;
}
if probe == 0 && hinted.is_some() {
report.hinted_attempts += 1;
}
report.attempts += 1;
let response_timeout = discovery_response_timeout(
profile,
address_timing,
hinted.is_some() && probe == 0,
report.devices.is_empty(),
);
let retry = discovery_retry(
options.retry,
response_timeout,
probe != 0 || hinted.is_none(),
);
let request = Request::new(address, 0u8, Vec::new()).with_preambles(preambles);
let prefix = wake_prefix.take().unwrap_or_default();
match link
.request_with_prefix(request, prefix, options.queue, retry)
.await
{
Ok(reply) => {
match ReadDeviceIdentity.decode_reply(&reply) {
Ok(identity) => report.devices.push(DiscoveredDevice {
module: module.module,
address,
identity,
}),
Err(error) => report
.errors
.push((address, ExchangeError::Operation(error))),
}
break;
}
Err(ExchangeError::ResponseTimeout | ExchangeError::Deadline)
if hinted.is_some() && probe == 0 =>
{
report.hint_fallbacks += 1;
}
Err(ExchangeError::ResponseTimeout | ExchangeError::Deadline) => break,
Err(error) => {
report.errors.push((address, error));
break;
}
}
}
}
}
report.passes_completed = pass.saturating_add(1);
if report.devices.len() >= visited.len() {
break;
}
if pass.saturating_add(1) < options.passes.get() && !options.pass_delay.is_zero() {
tokio::time::sleep(options.pass_delay).await;
}
}
report
}
async fn wait_for_address_timing(
address_timings: Option<&AddressTimings>,
polling_address: u8,
) -> AddressTiming {
let timing = address_timings
.and_then(|timings| timings.get(polling_address))
.unwrap_or_default();
if !timing.delay_before_probe.is_zero() {
tokio::time::sleep(timing.delay_before_probe).await;
}
timing
}
fn discovery_response_timeout(
profile: &LineProfile,
address_timing: AddressTiming,
hinted_probe: bool,
no_devices_found: bool,
) -> Duration {
address_timing.response_timeout.unwrap_or({
if hinted_probe || !no_devices_found {
profile.timing.steady_response
} else {
profile.timing.first_response
}
})
}
fn discovery_retry(
base: RetryPolicy,
response_timeout: Duration,
allow_transport_retries: bool,
) -> RetryPolicy {
let transport_retries = if allow_transport_retries {
base.transport_retries
} else {
0
};
let maximum_attempts = 1_u32
.saturating_add(u32::from(transport_retries))
.saturating_add(u32::from(base.busy_retries))
.saturating_add(u32::from(base.delayed_response_polls));
let transient_waits =
u32::from(base.busy_retries).saturating_add(u32::from(base.delayed_response_polls));
RetryPolicy {
transport_retries,
response_timeout,
total_timeout: response_timeout
.saturating_mul(maximum_attempts)
.saturating_add(base.retry_delay.saturating_mul(transient_waits)),
..base
}
}