Skip to main content

frenz_proto/
command.rs

1//! Commands (written to [`Characteristic::CommandRx`](crate::Characteristic::CommandRx)) and their
2//! responses (notified on [`Characteristic::CommandResponse`](crate::Characteristic::CommandResponse)).
3//!
4//! Only commands whose effect has been observed on hardware are exposed. Opcodes for audio,
5//! alarms, stimulation, file transfer, firmware update, test modes, reset and renaming exist on the
6//! device but are deliberately absent until they have been characterized on a bench.
7
8use crate::error::ParseError;
9use crate::{be_u16, be_u32};
10
11/// A command the client may send.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum Command {
14    /// Request the firmware version string.
15    GetFirmwareVersion,
16    /// Request the battery percentage.
17    GetBattery,
18    /// Request the serial number.
19    GetSerialNumber,
20    /// Set the device clock (Unix seconds). Afterwards packet device times are Unix seconds.
21    TimeSync(u32),
22    /// Request the advertised device name.
23    GetDeviceName,
24    /// Request the device clock.
25    GetDeviceTime,
26    /// Request the device identifier (the Bluetooth address as text).
27    GetDeviceId,
28    /// Enable or disable periodic heart-rate/SpO2 reporting (1 Hz when enabled, every 5 s otherwise).
29    HeartRatePeriodic(bool),
30    /// Session-start notice (`0e 00`), part of the standard start sequence.
31    OnConnected,
32    /// Start or stop streaming. `mask` is sent as-is; `0xff` (all streams) is the only verified value.
33    StreamControl {
34        /// Stream selection mask.
35        mask: u8,
36        /// Start (`true`) or stop.
37        enable: bool,
38    },
39    /// Set the volume of the band's spoken prompts (`0` = silent).
40    SetPromptVolume(u8),
41    /// Request the IMU calibration report.
42    GetImuCalibration,
43    /// Session-running notice (`0e 02`), part of the standard start sequence. Without it the band
44    /// powers itself off 10 minutes after streaming starts.
45    StartSession,
46    /// Session-end notice (`0e 03`), part of the standard stop sequence; effect not characterized.
47    EndSession,
48}
49
50/// An encoded command, at most 8 bytes.
51#[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    /// The bytes to write.
68    pub fn as_bytes(&self) -> &[u8] {
69        self.buf.get(..self.len as usize).unwrap_or(&[])
70    }
71}
72
73impl Command {
74    /// Opcode (first byte).
75    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    /// Wire encoding.
93    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/// A command response: `[opcode, status, payload…]`.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Response {
114    /// Opcode of the command answered.
115    pub opcode: u8,
116    /// Status byte; `0` = success.
117    pub status: u8,
118    payload: [u8; Self::MAX_PAYLOAD],
119    len: u8,
120}
121
122/// Typed view of a response.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum ResponseBody<'a> {
125    /// Acknowledgement with no payload.
126    Ack,
127    /// Firmware version text.
128    FirmwareVersion(&'a str),
129    /// Battery percentage.
130    Battery(u8),
131    /// Serial number text.
132    SerialNumber(&'a str),
133    /// Device name text.
134    DeviceName(&'a str),
135    /// Device clock (Unix seconds after a time sync).
136    DeviceTime(u32),
137    /// Device identifier text (the Bluetooth address).
138    DeviceId(&'a str),
139    /// IMU calibration report: three per-axis `std` bytes and three per-axis `diff` words. Their
140    /// exact semantics (and the signedness of `diff`) are not yet verified.
141    ImuCalibration {
142        /// Per-axis noise estimate.
143        std: [u8; 3],
144        /// Per-axis offset estimate, raw.
145        diff: [u16; 3],
146    },
147    /// A response this crate does not interpret.
148    Other(&'a [u8]),
149}
150
151impl Response {
152    /// Longest payload accepted (17 bytes observed).
153    pub const MAX_PAYLOAD: usize = 64;
154
155    /// Decodes a response.
156    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    /// Raw payload after opcode and status.
182    pub fn payload(&self) -> &[u8] {
183        self.payload.get(..self.len as usize).unwrap_or(&[])
184    }
185
186    /// True when the status byte reports success.
187    pub fn ok(&self) -> bool {
188        self.status == 0
189    }
190
191    /// Typed interpretation of the payload.
192    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}