Skip to main content

osdp/command/
comset.rs

1//! `osdp_COMSET` (`0x6E`) — set PD address and baud rate.
2//!
3//! # Spec: §6.13
4//!
5//! Body is 5 bytes: `addr (1)` + `baud (4 LE)`.
6
7use crate::error::Error;
8use alloc::vec::Vec;
9
10/// `osdp_COMSET` body.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct ComSet {
13    /// New PD address (`0x00..=0x7E`).
14    pub address: u8,
15    /// New bit rate (e.g. 9600, 115200).
16    pub baud: u32,
17}
18
19impl ComSet {
20    /// Encode.
21    pub fn encode(&self) -> Result<Vec<u8>, Error> {
22        if self.address > crate::MAX_PD_ADDR {
23            return Err(Error::BadAddress(self.address));
24        }
25        let mut out = Vec::with_capacity(5);
26        out.push(self.address);
27        out.extend_from_slice(&self.baud.to_le_bytes());
28        Ok(out)
29    }
30
31    /// Decode.
32    pub fn decode(data: &[u8]) -> Result<Self, Error> {
33        if data.len() != 5 {
34            return Err(Error::MalformedPayload {
35                code: 0x6E,
36                reason: "COMSET requires 5 bytes",
37            });
38        }
39        Ok(Self {
40            address: data[0],
41            baud: u32::from_le_bytes([data[1], data[2], data[3], data[4]]),
42        })
43    }
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    /// Annex E vector: COMSET broadcast → `addr=0x00`, `baud=9600 (0x2580)`.
50    #[test]
51    fn annex_e_vector() {
52        let body = ComSet {
53            address: 0x00,
54            baud: 9600,
55        };
56        let bytes = body.encode().unwrap();
57        assert_eq!(bytes, [0x00, 0x80, 0x25, 0x00, 0x00]);
58    }
59}