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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use std::fmt;

use crate::{Error, EventCode, EventType, Message, MessageCode, MessageData, MessageType, Result};

mod escrow_event;
mod inhibit_event;
mod rejected_event;

pub use escrow_event::*;
pub use inhibit_event::*;
pub use rejected_event::*;

/// Represents an event [Message] sent by the device.
#[repr(C)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Event {
    event_type: EventType,
    event_code: EventCode,
    additional: Vec<u8>,
}

impl Event {
    /// Creates a new [Event].
    pub const fn new() -> Self {
        Self {
            event_type: EventType::new(),
            event_code: EventCode::new(),
            additional: Vec::new(),
        }
    }

    /// Gets the [MessageType] of the [Event].
    pub const fn message_type(&self) -> MessageType {
        MessageType::Event(self.event_type)
    }

    /// Gets the [EventType] of the [Event].
    pub const fn event_type(&self) -> EventType {
        self.event_type
    }

    /// Sets the [EventType] of the [Event].
    pub fn set_event_type(&mut self, event_type: EventType) {
        self.event_type = event_type;
    }

    /// Builder function that sets the [EventType] of the [Event].
    pub fn with_event_type(mut self, event_type: EventType) -> Self {
        self.set_event_type(event_type);
        self
    }

    /// Gets the [MessageCode] of the [Event].
    pub const fn message_code(&self) -> MessageCode {
        MessageCode::Event(self.event_code)
    }

    /// Gets the [EventCode] of the [Event].
    pub const fn event_code(&self) -> EventCode {
        self.event_code
    }

    /// Sets the [EventCode] of the [Event].
    pub fn set_event_code(&mut self, code: EventCode) {
        self.event_code = code;
    }

    /// Builder function that sets the [EventCode] of the [Event].
    pub fn with_event_code(mut self, code: EventCode) -> Self {
        self.set_event_code(code);
        self
    }

    /// Gets a reference to the additional data of the [Event].
    pub fn additional(&self) -> &[u8] {
        &self.additional
    }

    /// Sets the additional data of the [Event].
    pub fn set_additional(&mut self, additional: &[u8]) {
        self.additional = additional.into();
    }

    /// Builder function that sets the additional data of the [Event].
    pub fn with_additional(mut self, additional: &[u8]) -> Self {
        self.set_additional(additional);
        self
    }

    /// Gets the length of the [Message].
    pub fn len(&self) -> usize {
        Self::meta_len() + self.additional.len()
    }

    pub(crate) const fn meta_len() -> usize {
        EventType::len() + EventCode::len()
    }

    /// Gets whether the [Event] is empty.
    pub const fn is_empty(&self) -> bool {
        self.event_type.is_empty() || self.event_code.is_empty()
    }

    /// Writes the [Message] to the provided byte buffer.
    pub fn to_bytes(&self, buf: &mut [u8]) -> Result<()> {
        let len = self.len();
        let buf_len = buf.len();

        if buf_len < len {
            Err(Error::InvalidMessageLen((buf_len, len)))
        } else {
            let msg_iter = [self.event_type.to_u8()]
                .into_iter()
                .chain(self.event_code.to_bytes())
                .chain(self.additional.iter().cloned());

            buf.iter_mut()
                .take(len)
                .zip(msg_iter)
                .for_each(|(dst, src)| *dst = src);

            Ok(())
        }
    }
}

impl TryFrom<&[u8]> for Event {
    type Error = Error;

    fn try_from(val: &[u8]) -> Result<Self> {
        let meta_len = Self::meta_len();
        let len = val.len();

        match len {
            l if l < meta_len => Err(Error::InvalidEventLen((len, meta_len))),
            l if l == meta_len => Ok(Self {
                event_type: val[0].try_into()?,
                event_code: val[EventType::len()..].try_into()?,
                additional: Vec::new(),
            }),
            _ => Ok(Self {
                event_type: val[0].try_into()?,
                event_code: val[EventType::len()..].try_into()?,
                additional: val[Self::meta_len()..].into(),
            }),
        }
    }
}

impl TryFrom<&Message> for Event {
    type Error = Error;

    fn try_from(val: &Message) -> Result<Self> {
        Ok(Self {
            event_type: val.data().message_type().event_type()?,
            event_code: val.data().message_code().event_code()?,
            additional: val.data().additional().into(),
        })
    }
}

impl TryFrom<Message> for Event {
    type Error = Error;

    fn try_from(val: Message) -> Result<Self> {
        (&val).try_into()
    }
}

impl From<&Event> for Message {
    fn from(val: &Event) -> Self {
        Self::new().with_data(
            MessageData::new()
                .with_message_type(val.message_type())
                .with_message_code(val.message_code())
                .with_additional(val.additional()),
        )
    }
}

impl From<Event> for Message {
    fn from(val: Event) -> Self {
        (&val).into()
    }
}

impl Default for Event {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{")?;
        write!(f, r#""event_type":{}, "#, self.event_type)?;
        write!(f, r#""event_code":{}, "#, self.event_code)?;
        write!(f, r#""additional_data": ["#)?;

        for (i, d) in self.additional.iter().enumerate() {
            if i != 0 {
                write!(f, ",")?;
            }
            write!(f, "{d}")?;
        }

        write!(f, "]}}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_event() {
        let type_bytes = EventType::Sequence0.to_u8();
        let code_bytes = EventCode::PowerUp.to_bytes();

        let raw = [type_bytes, code_bytes[0], code_bytes[1]];

        let msg = Message::new().with_data(
            MessageData::new()
                .with_message_type(MessageType::Event(EventType::Sequence0))
                .with_message_code(MessageCode::Event(EventCode::PowerUp)),
        );

        let exp = Event::new()
            .with_event_type(EventType::Sequence0)
            .with_event_code(EventCode::PowerUp);

        assert_eq!(Event::try_from(raw.as_ref()), Ok(exp.clone()));
        assert_eq!(Event::try_from(&msg), Ok(exp.clone()));
        assert_eq!(Event::try_from(msg), Ok(exp.clone()));

        let mut out = [0u8; Event::meta_len()];
        assert_eq!(exp.to_bytes(out.as_mut()), Ok(()));
        assert_eq!(out, raw);
    }

    #[test]
    fn test_event_with_data() {
        let type_bytes = EventType::Sequence0.to_u8();
        let code_bytes = EventCode::Escrow.to_bytes();

        let raw = [
            type_bytes,
            code_bytes[0],
            code_bytes[1],
            b'U',
            b'S',
            b'D',
            0x64,
            0x00,
        ];

        let msg = Message::new().with_data(
            MessageData::new()
                .with_message_type(MessageType::Event(EventType::Sequence0))
                .with_message_code(MessageCode::Event(EventCode::Escrow))
                .with_additional(raw[Event::meta_len()..].as_ref()),
        );

        let exp = Event::new()
            .with_event_type(EventType::Sequence0)
            .with_event_code(EventCode::Escrow)
            .with_additional(raw[Event::meta_len()..].as_ref());

        assert_eq!(Event::try_from(raw.as_ref()), Ok(exp.clone()));
        assert_eq!(Event::try_from(&msg), Ok(exp.clone()));
        assert_eq!(Event::try_from(msg), Ok(exp.clone()));

        let mut out = [0u8; 8];
        assert_eq!(exp.to_bytes(out.as_mut()), Ok(()));
        assert_eq!(out, raw);
    }
}