Skip to main content

device_daemon_core/
serial.rs

1use anyhow::{bail, Result};
2use std::time::Duration;
3
4const MODBUS_RTU_BITS_PER_CHARACTER_X2: u128 = 22;
5const MODBUS_RTU_SILENT_CHARACTERS_X2: u128 = 7;
6const HIGH_BAUD_MINIMUM_MICROS: u128 = 1_750;
7const HIGH_BAUD_THRESHOLD: u32 = 19_200;
8
9/// Calculate the minimum Modbus RTU inter-frame silence for a baud rate.
10///
11/// The calculation uses the standard 11-bit character time and 3.5 character
12/// silence. At baud rates above 19,200, the Modbus RTU fixed minimum of 1.75 ms
13/// is used. The result is rounded up to the next microsecond so it never falls
14/// below the calculated minimum.
15///
16/// This function applies only to Modbus RTU. Other serial protocols must use
17/// their own timing requirements.
18pub fn minimum_modbus_rtu_delay(baud_rate: u32) -> Result<Duration> {
19    if baud_rate == 0 {
20        bail!("Modbus RTU baud rate must be greater than zero");
21    }
22
23    let numerator = MODBUS_RTU_BITS_PER_CHARACTER_X2 * MODBUS_RTU_SILENT_CHARACTERS_X2 * 1_000_000;
24    let denominator = 4 * u128::from(baud_rate);
25    let calculated_micros = numerator.div_ceil(denominator);
26    let minimum_micros = if baud_rate > HIGH_BAUD_THRESHOLD {
27        HIGH_BAUD_MINIMUM_MICROS
28    } else {
29        calculated_micros
30    };
31
32    Ok(Duration::from_micros(minimum_micros as u64))
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn computes_standard_rtu_silence_with_rounding_up() {
41        assert_eq!(
42            minimum_modbus_rtu_delay(9_600).unwrap(),
43            Duration::from_micros(4_011)
44        );
45        assert_eq!(
46            minimum_modbus_rtu_delay(19_200).unwrap(),
47            Duration::from_micros(2_006)
48        );
49    }
50
51    #[test]
52    fn applies_fixed_minimum_above_19200_baud() {
53        assert_eq!(
54            minimum_modbus_rtu_delay(19_201).unwrap(),
55            Duration::from_micros(1_750)
56        );
57        assert_eq!(
58            minimum_modbus_rtu_delay(38_400).unwrap(),
59            Duration::from_micros(1_750)
60        );
61    }
62
63    #[test]
64    fn rejects_zero_baud_rate() {
65        assert!(minimum_modbus_rtu_delay(0).is_err());
66    }
67}