Skip to main content

vlcb_defs/
dcc.rs

1use byteorder::{ByteOrder, NetworkEndian};
2use num_enum::{FromPrimitive, IntoPrimitive, TryFromPrimitive};
3
4pub struct LocoAddress([u8;2], bool);
5
6impl LocoAddress {
7    /// Constructs short DCC locomotive address
8    pub fn new(addr: u8) -> Self {
9        Self(
10            [0x0, addr],
11            false,
12        )
13    }
14
15    /// Constructs long DCC locomotive address
16    pub fn new_long(addr: u16) -> Self {
17        let mut s = Self([0u8; 2], true);
18        NetworkEndian::write_u16(&mut s.0, addr);
19        s
20    }
21
22    /// Get the address type
23    ///
24    /// Returns true when the address is 14 bits long
25    pub fn is_long(&self) -> bool {
26        self.1
27    }
28
29    /// Returns the address data as two octets in big endian
30    pub fn as_bytes(&self) -> [u8; 2] {
31        self.0
32    }
33
34    /// Returns the address data as two octets in big endian with
35    /// sanitization that is useful for constructing CBUS packets
36    ///
37    /// 7 bit addresses have most significant octet set to 0.
38    /// 14 bit addresses have bits 6,7 of most significant octet set to 1.
39    pub fn as_bytes_sanitized(&self) -> [u8; 2] {
40        let mut bytes = self.as_bytes();
41
42        if self.is_long() {
43            bytes[0] |= 0xC0;
44        } else {
45            bytes[0] = 0x0;
46        }
47
48        bytes
49    }
50}
51
52
53/// Loco state
54#[derive(FromPrimitive, IntoPrimitive, Debug, Clone, PartialEq, Eq, Copy)]
55#[repr(u8)]
56pub enum LocoState {
57    Active = 0,
58    Consisted = 1,
59    ConsistMaster = 2,
60    #[default]
61    Inactive = 3,
62}
63
64#[derive(TryFromPrimitive, IntoPrimitive, Debug, Clone, PartialEq, Eq, Copy)]
65#[repr(u8)]
66pub enum LocoFunctionRange {
67    F0ToF4 = 1,
68    F5ToF8 = 2,
69    F9ToF12 = 3,
70    F13ToF20 = 4,
71    F21ToF28= 5,
72}
73
74#[derive(FromPrimitive, IntoPrimitive, Debug, Clone, PartialEq, Eq, Copy)]
75#[repr(u8)]
76pub enum SessionQueryMode {
77    #[default]
78    Default = 0x00,
79    Steal = 0x01,
80    Share = 0x02,
81}