1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
#[cfg(feature = "std")]
use std::fmt::Display;

use deku::prelude::*;

use crate::{app::interface::InterfaceType, network::Addressee, physical::Channel, types::VarInt};

/// The Response Modes define the condition for termination on success of a Request
#[derive(DekuRead, DekuWrite, Default, Debug, Clone, PartialEq)]
#[deku(bits = 3, type = "u8")]
pub enum ResponseMode {
    /// A Request is acknowledged if the DLL CSMA-CA routine succeeds. No
    /// responses are expected.
    ///
    /// Eg. The request is successful if your packet was successfully sent on the radio.
    #[default]
    #[deku(id = "0")]
    No,

    /// If the addressee is broadcast, a Request is acknowledged if as many as
    /// possible D7ATP responses to this Request are received (may be zero).
    ///
    /// If the addressee is unicast, a Request is acknowledged if the addressee provides a
    /// D7ATP response. All responses received during the D7ATP Receive Period
    /// are vectored to upper layer.
    ///
    /// Eg. Succeeds if everyone addressed responds to the radio packet.
    #[deku(id = "1")]
    All,

    /// A Request is acknowledged if at least one D7ATP response to this Request is
    /// received.
    ///
    /// Eg. Succeeds if you receive one response to the radio packet.
    #[deku(id = "2")]
    Any,

    /// A Request is acknowledged if the DLL CSMA-CA routine succeeds REPEAT
    /// times. No responses are expected. The parameters REPEAT is defined in the
    /// SEL configuration file.
    #[deku(id = "4")]
    NoRepeat,

    /// A Request is acknowledged if the DLL CSMA-CA routine succeeds. It is un-
    /// acknowledged when a response does not acknowledge the Request. The
    /// procedure behaves as RESP_ALL, but Responders provide responses only
    /// when their D7ATP ACK Templates is not void or if the upper layer provides a
    /// response.
    ///
    /// Eg. Succeeds only if the responder gives back an ALP packet in response (which is more
    /// restrictive than succeeding upon successful radio ACK).
    #[deku(id = "5")]
    OnError,

    /// A Request is acknowledged if at least one D7ATP response to this Request is
    /// received. The procedure behaves as RESP_ANY, but the Addressee is
    /// managed dynamically. It is set to broadcast after failure to receive an
    /// acknowledgement. On acknowledgement success, it is set to the
    /// Addressee of one of the responders that acknowledged the Request (preferred
    /// addressee). The preferred addressee selection is implementation dependent.
    #[deku(id = "6")]
    Preferred,
}

/// The Retry Modes define the pattern for re-flushing a FIFO that terminates on error.
///
/// In other words, what is the retry policy when sending your payload.
#[derive(DekuRead, DekuWrite, Default, Debug, Clone, PartialEq)]
#[deku(bits = 3, type = "u8")]
pub enum RetryMode {
    #[default]
    #[deku(id = "0")]
    No,
    #[deku(id = "1")]
    OneshotRetry,
    #[deku(id = "2")]
    FifoFast,
    #[deku(id = "3")]
    FifoSlow,
    #[deku(id = "4")]
    SingleFast,
    #[deku(id = "5")]
    SingleSlow,
    #[deku(id = "6")]
    OneshotSticky,
    #[deku(id = "7")]
    Rfu,
}

/// QoS of the request
#[derive(DekuRead, DekuWrite, Default, Debug, Clone, PartialEq)]
pub struct QoS {
    #[deku(bits = 1)]
    pub stop_on_error: bool,
    #[deku(bits = 1)]
    pub record: bool,
    pub retry_mode: RetryMode,
    pub response_mode: ResponseMode,
}

#[derive(DekuRead, DekuWrite, Debug, Clone, PartialEq)]
#[deku(ctx = "interface_id: InterfaceType, length: u32", id = "interface_id")]
pub enum InterfaceStatus {
    #[deku(id = "InterfaceType::Host")]
    Host,

    #[deku(id = "InterfaceType::Serial")]
    Serial,

    // #[deku(id = "InterfaceType::LoRaWanABP")]
    // LoRaWanABP(LoRaWANABPInterfaceStatus),

    // #[deku(id = "InterfaceType::LoRaWanOTAA")]
    // LoRaWanOTAA(LoRaWANOTAAInterfaceStatus),
    #[deku(id = "InterfaceType::Dash7")]
    Dash7(Dash7InterfaceStatus),

    #[deku(id_pat = "_")]
    Other(#[deku(count = "length")] Vec<u8>),
}

#[cfg(feature = "std")]
impl Display for InterfaceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Dash7(status) => status.fmt(f),
            Self::Other(status) => f.write_str(&format!("OtherInterfaceStatus{{ {:?} }}", status)),
            _ => f.write_str(&format!(
                "{}InterfaceStatus{{}}",
                self.deku_id()
                    .map(|i| format!("{:?}", i))
                    .unwrap_or("Unknown".to_string())
            )),
        }
    }
}

#[derive(DekuRead, DekuWrite, Debug, Clone, PartialEq)]
pub struct Dash7InterfaceStatus {
    /// PHY layer channel
    pub channel: Channel,
    /// PHY layer RX level in -dBm
    pub rx_level: u8,
    /// PHY layer link budget in dB
    pub link_budget: u8,

    pub target_rx_level: u8,
    #[deku(bits = 1)]
    pub nls: bool,
    #[deku(bits = 1)]
    pub missed: bool,
    #[deku(bits = 1)]
    pub retry: bool,
    #[deku(bits = 1)]
    pub unicast: bool,

    /// Value of the D7ATP Dialog ID
    #[deku(pad_bits_before = "4")]
    pub fifo_token: u8,

    /// Value of the D7ATP Transaction ID
    pub sequence_number: u8,

    /// Response delay (request to response time) in TiT
    pub response_timeout: VarInt,

    /// Address of source
    pub addressee: Addressee,
}

#[cfg(feature = "std")]
impl Display for Dash7InterfaceStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Dash7InterfaceStatus { ")?;
        f.write_str(&format!("channel: {:?}, ", self.channel))?;
        f.write_str(&format!("rx_level: {:?}, ", self.rx_level))?;
        f.write_str(&format!("link_budget: {:?}, ", self.link_budget))?;
        f.write_str(&format!("target_rx_level: {:?}, ", self.target_rx_level))?;
        f.write_str(&format!("nls: {:?}, ", self.nls))?;
        f.write_str(&format!("missed: {:?}, ", self.missed))?;
        f.write_str(&format!("retry: {:?}, ", self.retry))?;
        f.write_str(&format!("unicast: {:?}, ", self.unicast))?;
        f.write_str(&format!("fifo_token: {:?}, ", self.fifo_token))?;
        f.write_str(&format!("sequence_number: {:?}, ", self.sequence_number))?;
        f.write_str(&format!(
            "response_timeout: {:?}, ",
            Into::<u32>::into(self.response_timeout)
        ))?;
        f.write_str(&format!("addressee: {:?}, ", self.addressee))?;
        f.write_str(" }")?;
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test_tools::test_item;
    use hex_literal::hex;

    #[test]
    fn test_qos() {
        test_item(QoS::default(), &[0]);

        test_item(
            QoS {
                retry_mode: RetryMode::No,
                response_mode: ResponseMode::Any,
                record: true,
                stop_on_error: true,
            },
            &[0b11000010],
        );

        test_item(
            QoS {
                retry_mode: RetryMode::No,
                response_mode: ResponseMode::NoRepeat,
                record: false,
                stop_on_error: false,
            },
            &hex!("04"),
        )
    }
}