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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#![forbid(unsafe_code)]
#![deny(warnings)]
#![deny(missing_docs)]
#![forbid(missing_debug_implementations)]
#![deny(unused)]
#![no_std]
#[cfg(not(any(
feature = "accelerometer_event",
feature = "button_event",
feature = "color_event",
feature = "gyro_event",
feature = "location_event",
feature = "magnetometer_event",
feature = "quaternion_event"
)))]
compile_error!("at least one event type must be selected in the features!");
#[cfg(feature = "accelerometer_event")]
pub mod accelerometer_event;
#[cfg(feature = "button_event")]
pub mod button_event;
#[cfg(feature = "color_event")]
pub mod color_event;
#[cfg(feature = "gyro_event")]
pub mod gyro_event;
#[cfg(feature = "location_event")]
pub mod location_event;
#[cfg(feature = "magnetometer_event")]
pub mod magnetometer_event;
#[cfg(feature = "quaternion_event")]
pub mod quaternion_event;
#[cfg(feature = "accelerometer_event")]
use accelerometer_event::AccelerometerEvent;
#[cfg(feature = "button_event")]
use button_event::{ButtonEvent, ButtonParseError};
#[cfg(feature = "color_event")]
use color_event::ColorEvent;
use core::cmp::min;
#[cfg(feature = "gyro_event")]
use gyro_event::GyroEvent;
use heapless::Vec;
#[cfg(feature = "location_event")]
use location_event::LocationEvent;
#[cfg(feature = "magnetometer_event")]
use magnetometer_event::MagnetometerEvent;
#[cfg(feature = "quaternion_event")]
use quaternion_event::QuaternionEvent;
#[derive(PartialEq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[allow(missing_docs)] pub enum ControllerEvent {
#[cfg(feature = "button_event")]
ButtonEvent(ButtonEvent),
#[cfg(feature = "color_event")]
ColorEvent(ColorEvent),
#[cfg(feature = "quaternion_event")]
QuaternionEvent(QuaternionEvent),
#[cfg(feature = "accelerometer_event")]
AccelerometerEvent(AccelerometerEvent),
#[cfg(feature = "gyro_event")]
GyroEvent(GyroEvent),
#[cfg(feature = "magnetometer_event")]
MagnetometerEvent(MagnetometerEvent),
#[cfg(feature = "location_event")]
LocationEvent(LocationEvent),
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ProtocolParseError {
UnknownEvent(Option<u8>),
DisabledControllerDataPackageType(ControllerDataPackageType),
#[cfg(feature = "button_event")]
ButtonParseError(ButtonParseError),
InvalidLength(usize, usize),
InvalidCrc(u8, u16),
InvalidFloatSize(usize),
}
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[allow(missing_docs)] pub enum ControllerDataPackageType {
ButtonCommand,
Color,
Quaternion,
Accelerometer,
Gyro,
Magnetometer,
Location,
}
const BYTES_PER_FLOAT: usize = 4;
pub const MAX_CONTROLLER_MESSAGE_LENGTH: usize = 32; impl ControllerDataPackageType {
fn data_len(&self) -> usize {
match self {
ControllerDataPackageType::ButtonCommand => 2,
ControllerDataPackageType::Color => 3,
ControllerDataPackageType::Quaternion => 4 * BYTES_PER_FLOAT,
ControllerDataPackageType::Accelerometer => 3 * BYTES_PER_FLOAT,
ControllerDataPackageType::Gyro => 3 * BYTES_PER_FLOAT,
ControllerDataPackageType::Magnetometer => 3 * BYTES_PER_FLOAT,
ControllerDataPackageType::Location => 3 * BYTES_PER_FLOAT,
}
}
}
impl TryFrom<u8> for ControllerDataPackageType {
type Error = ProtocolParseError;
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
b'B' => Ok(ControllerDataPackageType::ButtonCommand),
b'C' => Ok(ControllerDataPackageType::Color),
b'Q' => Ok(ControllerDataPackageType::Quaternion),
b'A' => Ok(ControllerDataPackageType::Accelerometer),
b'G' => Ok(ControllerDataPackageType::Gyro),
b'M' => Ok(ControllerDataPackageType::Magnetometer),
b'L' => Ok(ControllerDataPackageType::Location),
_ => Err(ProtocolParseError::UnknownEvent(Some(value))),
}
}
}
pub fn parse<const MAX_RESULTS: usize>(
input: &[u8],
) -> Vec<Result<ControllerEvent, ProtocolParseError>, MAX_RESULTS> {
enum ParserState {
SeekStart,
ParseCommand,
}
let mut state = ParserState::SeekStart;
let mut result: Vec<Result<ControllerEvent, ProtocolParseError>, MAX_RESULTS> = Vec::new();
for pos in 0..input.len() {
let byte = input[pos];
match state {
ParserState::SeekStart => {
if byte == b'!' {
state = ParserState::ParseCommand
}
}
ParserState::ParseCommand => {
let data_package = extract_and_parse_command(&input[(pos - 1)..]);
result.push(data_package).ok();
if result.len() == MAX_RESULTS {
return result;
}
state = ParserState::SeekStart;
}
};
}
result
}
fn extract_and_parse_command(input: &[u8]) -> Result<ControllerEvent, ProtocolParseError> {
let command = ControllerDataPackageType::try_from(input[1])?;
let command_end = min(command.data_len() + 2, input.len() - 1);
parse_command(command, &input[..=command_end])
}
fn parse_command(
command: ControllerDataPackageType,
command_input: &[u8],
) -> Result<ControllerEvent, ProtocolParseError> {
#[cfg(feature = "defmt")]
defmt::debug!(
"parsing the command of type {} from message {:a}",
command,
command_input
);
let len = command_input.len();
let expected_len = command.data_len() + 3; if len != expected_len {
return Err(ProtocolParseError::InvalidLength(expected_len, len));
}
let data_start: usize = 2; let data_end = len - 2;
let crc = &command_input[len - 1];
check_crc(&command_input[..=data_end], crc)?;
let data = &command_input[data_start..=data_end];
match command {
ControllerDataPackageType::ButtonCommand => {
#[cfg(feature = "button_event")]
return ButtonEvent::try_from(data).map(ControllerEvent::ButtonEvent);
#[cfg(not(feature = "button_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Color => {
#[cfg(feature = "color_event")]
return ColorEvent::try_from(data).map(ControllerEvent::ColorEvent);
#[cfg(not(feature = "color_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Quaternion => {
#[cfg(feature = "quaternion_event")]
return QuaternionEvent::try_from(data).map(ControllerEvent::QuaternionEvent);
#[cfg(not(feature = "quaternion_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Accelerometer => {
#[cfg(feature = "accelerometer_event")]
return AccelerometerEvent::try_from(data).map(ControllerEvent::AccelerometerEvent);
#[cfg(not(feature = "accelerometer_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Gyro => {
#[cfg(feature = "gyro_event")]
return GyroEvent::try_from(data).map(ControllerEvent::GyroEvent);
#[cfg(not(feature = "gyro_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Magnetometer => {
#[cfg(feature = "magnetometer_event")]
return MagnetometerEvent::try_from(data).map(ControllerEvent::MagnetometerEvent);
#[cfg(not(feature = "magnetometer_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
ControllerDataPackageType::Location => {
#[cfg(feature = "location_event")]
return LocationEvent::try_from(data).map(ControllerEvent::LocationEvent);
#[cfg(not(feature = "location_event"))]
return Err(ProtocolParseError::DisabledControllerDataPackageType(
command,
));
}
};
}
fn check_crc(data: &[u8], crc: &u8) -> Result<(), ProtocolParseError> {
#[cfg(feature = "defmt")]
defmt::trace!("calculating CRC for {:a}, expecting {}", data, crc);
let mut sum: u16 = 0;
for byte in data {
sum += *byte as u16;
}
let calculated_crc = !sum & 0xff;
if *crc as u16 == calculated_crc {
Ok(())
} else {
Err(ProtocolParseError::InvalidCrc(*crc, calculated_crc))
}
}
#[allow(unused)] fn try_f32_from_le_bytes(input: &[u8]) -> Result<f32, ProtocolParseError> {
Ok(f32::from_le_bytes(<[u8; 4]>::try_from(input).map_err(
|_| ProtocolParseError::InvalidFloatSize(input.len()),
)?))
}
#[cfg(test)]
mod tests {
use crate::button_event::{Button, ButtonState};
use crate::{check_crc, parse, try_f32_from_le_bytes, ControllerEvent, ProtocolParseError};
fn assert_is_button_event(
event: &Result<ControllerEvent, ProtocolParseError>,
button: Button,
button_state: ButtonState,
) {
match event {
Ok(ControllerEvent::ButtonEvent(event)) => {
assert_eq!(event.button(), &button);
assert_eq!(event.state(), &button_state)
}
_ => assert!(false),
}
}
#[test]
fn test_parse() {
const MAX_RESULTS: usize = 4;
let input = b"\x00!B11:!B10;\x00\x00!\x00\x00\x00\x00";
let result = parse::<MAX_RESULTS>(input);
assert_eq!(result.len(), 3);
assert_is_button_event(&result[0], Button::Button1, ButtonState::Pressed);
assert_is_button_event(&result[1], Button::Button1, ButtonState::Released);
assert_eq!(result[2], Err(ProtocolParseError::UnknownEvent(Some(0))));
}
#[test]
fn test_check_crc_ok() {
let input = b"!B11:";
let data = &input[0..input.len() - 1];
let crc = input.last().unwrap();
assert!(check_crc(data, &crc).is_ok());
}
#[test]
fn test_check_crc_err() {
let input = b"!B11;"; let correct_crc = b':';
let data = &input[0..input.len() - 1];
let crc = input.last().unwrap();
assert_eq!(
check_crc(data, &crc),
Err(ProtocolParseError::InvalidCrc(*crc, correct_crc as u16))
);
}
#[test]
fn test_try_f32_from_le_bytes_ok() {
let input = b"9\x1e\x0c\xc0";
let expected: f32 = -2.1893446;
assert_eq!(try_f32_from_le_bytes(input), Ok(expected));
}
#[test]
fn test_try_f32_from_le_bytes_err() {
let input = b"\x1e\x0c\xc0";
assert_eq!(
try_f32_from_le_bytes(input),
Err(ProtocolParseError::InvalidFloatSize(3))
);
}
}