1use crate::error::ParseError;
9use crate::{be_u16, be_u32};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Command {
14 GetFirmwareVersion,
16 GetBattery,
18 GetSerialNumber,
20 TimeSync(u32),
22 GetDeviceName,
24 GetDeviceTime,
26 GetDeviceId,
28 HeartRatePeriodic(bool),
30 OnConnected,
32 StreamControl {
34 mask: u8,
36 enable: bool,
38 },
39 SetPromptVolume(u8),
41 GetImuCalibration,
43 StartSession,
46 EndSession,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct Encoded {
53 buf: [u8; 8],
54 len: u8,
55}
56
57impl Encoded {
58 fn new(bytes: &[u8]) -> Self {
59 let mut buf = [0u8; 8];
60 let len = bytes.len().min(8);
61 if let (Some(dst), Some(src)) = (buf.get_mut(..len), bytes.get(..len)) {
62 dst.copy_from_slice(src);
63 }
64 Self { buf, len: len as u8 }
65 }
66
67 pub fn as_bytes(&self) -> &[u8] {
69 self.buf.get(..self.len as usize).unwrap_or(&[])
70 }
71}
72
73impl Command {
74 pub const fn opcode(&self) -> u8 {
76 match self {
77 Self::GetFirmwareVersion => 0x01,
78 Self::GetBattery => 0x02,
79 Self::StreamControl { .. } => 0x03,
80 Self::GetSerialNumber => 0x06,
81 Self::TimeSync(_) => 0x07,
82 Self::GetDeviceName => 0x09,
83 Self::GetDeviceTime => 0x0b,
84 Self::GetDeviceId => 0x0c,
85 Self::OnConnected | Self::StartSession | Self::EndSession => 0x0e,
86 Self::HeartRatePeriodic(_) => 0x10,
87 Self::SetPromptVolume(_) => 0x36,
88 Self::GetImuCalibration => 0xf8,
89 }
90 }
91
92 pub fn encode(&self) -> Encoded {
94 let op = self.opcode();
95 match *self {
96 Self::TimeSync(t) => {
97 let b = t.to_be_bytes();
98 Encoded::new(&[op, b[0], b[1], b[2], b[3]])
99 }
100 Self::HeartRatePeriodic(on) => Encoded::new(&[op, u8::from(on)]),
101 Self::OnConnected => Encoded::new(&[op, 0x00]),
102 Self::StartSession => Encoded::new(&[op, 0x02]),
103 Self::EndSession => Encoded::new(&[op, 0x03]),
104 Self::StreamControl { mask, enable } => Encoded::new(&[op, mask, u8::from(enable)]),
105 Self::SetPromptVolume(v) => Encoded::new(&[op, v]),
106 _ => Encoded::new(&[op]),
107 }
108 }
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Response {
114 pub opcode: u8,
116 pub status: u8,
118 payload: [u8; Self::MAX_PAYLOAD],
119 len: u8,
120}
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum ResponseBody<'a> {
125 Ack,
127 FirmwareVersion(&'a str),
129 Battery(u8),
131 SerialNumber(&'a str),
133 DeviceName(&'a str),
135 DeviceTime(u32),
137 DeviceId(&'a str),
139 ImuCalibration {
142 std: [u8; 3],
144 diff: [u16; 3],
146 },
147 Other(&'a [u8]),
149}
150
151impl Response {
152 pub const MAX_PAYLOAD: usize = 64;
154
155 pub fn decode(p: &[u8]) -> Result<Self, ParseError> {
157 let (&opcode, rest) = p.split_first().ok_or(ParseError::EmptyResponse)?;
158 let (status, body) = match rest.split_first() {
159 Some((&s, b)) => (s, b),
160 None => return Err(ParseError::EmptyResponse),
161 };
162 if body.len() > Self::MAX_PAYLOAD {
163 return Err(ParseError::ResponseLength {
164 opcode,
165 actual: body.len(),
166 });
167 }
168 let mut payload = [0u8; Self::MAX_PAYLOAD];
169 payload
170 .get_mut(..body.len())
171 .ok_or(ParseError::EmptyResponse)?
172 .copy_from_slice(body);
173 Ok(Self {
174 opcode,
175 status,
176 payload,
177 len: body.len() as u8,
178 })
179 }
180
181 pub fn payload(&self) -> &[u8] {
183 self.payload.get(..self.len as usize).unwrap_or(&[])
184 }
185
186 pub fn ok(&self) -> bool {
188 self.status == 0
189 }
190
191 pub fn body(&self) -> Result<ResponseBody<'_>, ParseError> {
193 let p = self.payload();
194 fn as_text<'a>(p: &'a [u8], make: fn(&'a str) -> ResponseBody<'a>) -> ResponseBody<'a> {
195 core::str::from_utf8(p).map_or(ResponseBody::Other(p), make)
196 }
197 let text = |make| as_text(p, make);
198 let len_err = ParseError::ResponseLength {
199 opcode: self.opcode,
200 actual: p.len(),
201 };
202 Ok(match self.opcode {
203 0x01 => text(ResponseBody::FirmwareVersion),
204 0x02 => ResponseBody::Battery(*p.first().ok_or(len_err)?),
205 0x06 => text(ResponseBody::SerialNumber),
206 0x09 => text(ResponseBody::DeviceName),
207 0x0b => ResponseBody::DeviceTime(be_u32(p, 0).ok_or(len_err)?),
208 0x0c => text(ResponseBody::DeviceId),
209 0xf8 => {
210 if p.len() != 9 {
211 return Err(len_err);
212 }
213 ResponseBody::ImuCalibration {
214 std: [
215 *p.first().ok_or(len_err)?,
216 *p.get(1).ok_or(len_err)?,
217 *p.get(2).ok_or(len_err)?,
218 ],
219 diff: [
220 be_u16(p, 3).ok_or(len_err)?,
221 be_u16(p, 5).ok_or(len_err)?,
222 be_u16(p, 7).ok_or(len_err)?,
223 ],
224 }
225 }
226 _ if p.is_empty() => ResponseBody::Ack,
227 _ => ResponseBody::Other(p),
228 })
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 #[test]
237 fn encodings_match_observed_wire_bytes() {
238 let cases: [(Command, &[u8]); 10] = [
239 (Command::GetFirmwareVersion, &[0x01]),
240 (Command::TimeSync(0x6b00_92f6), &[0x07, 0x6b, 0x00, 0x92, 0xf6]),
241 (Command::SetPromptVolume(0), &[0x36, 0x00]),
242 (Command::HeartRatePeriodic(true), &[0x10, 0x01]),
243 (Command::OnConnected, &[0x0e, 0x00]),
244 (
245 Command::StreamControl {
246 mask: 0xff,
247 enable: true,
248 },
249 &[0x03, 0xff, 0x01],
250 ),
251 (
252 Command::StreamControl {
253 mask: 0xff,
254 enable: false,
255 },
256 &[0x03, 0xff, 0x00],
257 ),
258 (Command::GetImuCalibration, &[0xf8]),
259 (Command::StartSession, &[0x0e, 0x02]),
260 (Command::EndSession, &[0x0e, 0x03]),
261 ];
262 for (cmd, bytes) in cases {
263 assert_eq!(cmd.encode().as_bytes(), bytes, "{cmd:?}");
264 }
265 }
266
267 #[test]
268 fn responses_decode_like_the_hardware_sent_them() {
269 let fw = Response::decode(b"\x01\x00X8.2.2_1.1.19").unwrap();
270 assert_eq!(fw.body().unwrap(), ResponseBody::FirmwareVersion("X8.2.2_1.1.19"));
271 assert_eq!(
272 Response::decode(&[0x02, 0x00, 0x5a]).unwrap().body().unwrap(),
273 ResponseBody::Battery(90)
274 );
275 assert_eq!(
276 Response::decode(&[0x0b, 0x00, 0x6b, 0x00, 0x99, 0x70])
277 .unwrap()
278 .body()
279 .unwrap(),
280 ResponseBody::DeviceTime(0x6b00_9970)
281 );
282 let cal = Response::decode(&[0xf8, 0x00, 0x29, 0x2b, 0x28, 0x0d, 0x9a, 0x0e, 0xf4, 0x0b, 0x25]).unwrap();
283 assert_eq!(
284 cal.body().unwrap(),
285 ResponseBody::ImuCalibration {
286 std: [41, 43, 40],
287 diff: [3482, 3828, 2853]
288 }
289 );
290 let ack = Response::decode(&[0x07, 0x00]).unwrap();
291 assert!(ack.ok());
292 assert_eq!(ack.body().unwrap(), ResponseBody::Ack);
293 assert_eq!(Response::decode(&[0x01]), Err(ParseError::EmptyResponse));
294 assert!(Response::decode(&[0xf8, 0x00, 1, 2]).unwrap().body().is_err());
295 }
296}