Krolyxon
Commit 9f993c9

Branches

Refs →

budctlcratesbudctl-coresrcdevicesrealme_t310codec.rs

607 lines · 22.2 KB · Rust

1//! realme Buds T310 commands, tables and pure decoders. No I/O here, so every function can be
2//! tested with bytes from the spec. Each constant cites docs/protocol/realme_t310.md.
3
4use crate::error::{Error, Result};
5use crate::reader::Reader;
6use crate::status::{AncLevel, Battery, Charge, Gesture, NoiseControl, NoiseMode, Switch};
7
8/// Spec: realme_t310.md#bitmap
9pub(super) const HANDSHAKE: u16 = 0x0100;
10/// Spec: realme_t310.md#identity
11pub(super) const PRODUCT_ID: u16 = 0x0103;
12/// Spec: realme_t310.md#firmware
13pub(super) const FIRMWARE: u16 = 0x0105;
14/// Spec: realme_t310.md#battery
15pub(super) const BATTERY: u16 = 0x0106;
16/// Spec: realme_t310.md#gestures
17pub(super) const GESTURES: u16 = 0x0108;
18/// Spec: realme_t310.md#anc-read
19pub(super) const NOISE_CONTROL: u16 = 0x010C;
20/// Spec: realme_t310.md#switches
21pub(super) const SWITCHES: u16 = 0x010D;
22/// Spec: realme_t310.md#anc-write
23pub(super) const NOISE_CONTROL_WRITE: u16 = 0x0404;
24/// Spec: realme_t310.md#eq-read
25pub(super) const EQ_PRESET: u16 = 0x010F;
26/// Spec: realme_t310.md#codec
27pub(super) const CODEC: u16 = 0x0114;
28/// Not sent: the T310 does not answer it (HW1). Kept for W6. Spec: realme_t310.md#bass-read
29#[allow(dead_code)]
30pub(super) const BASS_LEVEL: u16 = 0x0124;
31/// Spec: realme_t310.md#events-offered
32pub(super) const EVENTS_OFFERED: u16 = 0x0200;
33/// Spec: realme_t310.md#subscribe
34pub(super) const SUBSCRIBE: u16 = 0x0205;
35/// Spec: realme_t310.md#fit-test
36pub(super) const FIT_TEST: u16 = 0x0405;
37
38/// Spec: realme_t310.md#identity
39pub(super) const T310_PRODUCT_ID: u32 = 0x06_3C_12;
40
41/// Payload asking for the current noise-control mode. Spec: realme_t310.md#anc-read
42pub(super) const NOISE_MODE_QUERY: [u8; 2] = [0x01, 0x01];
43/// Payload asking for the hold's noise-control cycle (one setting for both buds).
44/// Spec: realme_t310.md#hold-cycle
45pub(super) const HOLD_CYCLE_QUERY: [u8; 2] = [0x02, 0x01];
46/// Count, then the T310's switch ids: `05 06 11 1A 1B 1D`. Spec: realme_t310.md#switches
47pub(super) const SWITCH_QUERY: [u8; 7] = [6, 0x05, 0x06, 0x11, 0x1A, 0x1B, 0x1D];
48
49/// Event codes to subscribe to; the optional ones only when their command is allowed.
50/// Spec: realme_t310.md#subscribe
51const EVENTS: [(u8, Option<u16>); 4] = [(0x01, None), (0x02, None), (0x03, None), (0x04, Some(FIT_TEST))];
52
53/// Spec: realme_t310.md#switches
54const SWITCH_NAMES: [(u8, &str, &str); 5] = [
55 (0x06, "game", "Game mode"),
56 (0x11, "dual", "Dual connection"),
57 (0x1A, "wind", "Wind-noise reduction"),
58 (0x1B, "spatial", "3D sound"),
59 (0x1D, "bass-boost", "Bass boost"),
60];
61
62/// Noise-control masks: mode and level. Spec: realme_t310.md#anc-read
63const NOISE_MODES: [(u32, &str, Option<&str>); 5] = [
64 (0x01, "off", None),
65 (0x02, "transparency", None),
66 (0x04, "anc", Some("light")),
67 (0x08, "anc", Some("deep")),
68 (0x10, "anc", Some("medium")),
69];
70
71/// Bits of the hold cycle. Spec: realme_t310.md#hold-cycle
72const CYCLE_MODES: [(u32, &str); 3] = [(0x01, "off"), (0x02, "transparency"), (0x08, "anc")];
73
74/// Built-in EQ presets by id. Spec: realme_t310.md#eq-read
75const EQ_PRESETS: [(u8, &str); 4] = [
76 (0x00, "pure-raw"),
77 (0x01, "deep-bass"),
78 (0x02, "pure-vocals"),
79 (0x03, "pure-bass"),
80];
81
82/// Spec: realme_t310.md#codec
83const CODECS: [(u8, &str); 8] = [
84 (0x01, "SBC"),
85 (0x02, "AAC"),
86 (0x03, "LDAC"),
87 (0x04, "aptX"),
88 (0x05, "aptX HD"),
89 (0x06, "aptX Adaptive"),
90 (0x07, "LHDC"),
91 (0x08, "LHDC V5"),
92];
93
94/// Gesture-table names. Spec: realme_t310.md#gestures
95const SIDES: [(u8, &str); 3] = [(0x01, "left"), (0x02, "right"), (0x04, "both")];
96/// Spec: realme_t310.md#gestures
97const MAIN_GROUP: u8 = 0x01;
98/// Spec: realme_t310.md#gestures
99const ACTS: [(u8, &str); 6] = [
100 (0x01, "single-tap"),
101 (0x02, "double-tap"),
102 (0x03, "triple-tap"),
103 (0x04, "hold"),
104 (0x05, "slide"),
105 (0x06, "long-hold"),
106];
107/// Spec: realme_t310.md#gestures
108const FUNCTIONS: [(u8, &str); 15] = [
109 (0x00, "none"),
110 (0x01, "play-pause"),
111 (0x03, "voice-assistant"),
112 (0x05, "previous"),
113 (0x06, "next"),
114 (0x07, "volume"),
115 (0x08, "noise-cycle"),
116 (0x09, "favourite-music"),
117 (0x0A, "switch-track"),
118 (0x0B, "volume-up"),
119 (0x0C, "volume-down"),
120 (0x0D, "switch-devices"),
121 (0x11, "game-mode"),
122 (0x1C, "decline-call"),
123 (0x1D, "answer-call"),
124];
125
126fn name_of<K: PartialEq + Copy>(table: &[(K, &'static str)], key: K) -> Option<&'static str> {
127 table.iter().find(|(k, _)| *k == key).map(|(_, name)| *name)
128}
129
130/// When a command may be sent. Spec: realme_t310.md#bitmap
131enum Gate {
132 Always,
133 Bit(u8),
134}
135
136/// The gate of every command budctl uses. An unlisted command is never sent.
137/// Spec: realme_t310.md#bitmap
138fn gate(cmd: u16) -> Option<Gate> {
139 Some(match cmd {
140 0x0100..=0x0104 | 0x0106 | 0x010B | 0x010D | 0x0200 => Gate::Always,
141 0x0105 => Gate::Bit(0),
142 0x0108 | 0x0401 => Gate::Bit(3),
143 0x0109 => Gate::Bit(4),
144 0x0400 => Gate::Bit(5),
145 0x0403 => Gate::Bit(7),
146 0x010C | 0x0404 => Gate::Bit(8),
147 0x0405 => Gate::Bit(9),
148 0x010F | 0x0406 => Gate::Bit(10),
149 0x0114 => Gate::Bit(17),
150 0x0205 => Gate::Bit(22),
151 0x0122 | 0x0418 => Gate::Bit(34),
152 0x0124 | 0x041B => Gate::Bit(38),
153 _ => return None,
154 })
155}
156
157/// The commands these buds accept, from the handshake reply. Spec: realme_t310.md#bitmap
158#[derive(Debug)]
159pub(super) struct Commands {
160 bitmap: Vec<u8>,
161}
162
163impl Commands {
164 pub(super) fn parse(reply: &[u8]) -> Result<Self> {
165 let mut r = ok_reply(reply, "the handshake")?;
166 Ok(Self {
167 bitmap: r.rest().to_vec(),
168 })
169 }
170
171 pub(super) fn allows(&self, cmd: u16) -> bool {
172 match gate(cmd) {
173 Some(Gate::Always) => true,
174 Some(Gate::Bit(n)) => self
175 .bitmap
176 .get(usize::from(n / 8))
177 .is_some_and(|byte| byte & (1 << (n % 8)) != 0),
178 None => false,
179 }
180 }
181}
182
183/// A reply whose status byte is `00`, positioned after it. Spec: realme_t310.md#seq
184fn ok_reply<'a>(reply: &'a [u8], what: &'static str) -> Result<Reader<'a>> {
185 let mut r = Reader::new(reply, what);
186 match r.u8()? {
187 0x00 => Ok(r),
188 status => Err(Error::Rejected {
189 what: what.to_owned(),
190 status,
191 }),
192 }
193}
194
195/// Spec: realme_t310.md#identity
196pub(super) fn decode_product_id(reply: &[u8]) -> Result<u32> {
197 let mut r = ok_reply(reply, "the product id query")?;
198 let [low, middle, high] = [r.u8()?, r.u8()?, r.u8()?];
199 Ok(u32::from_le_bytes([low, middle, high, 0]))
200}
201
202/// Spec: realme_t310.md#events-offered
203pub(super) fn decode_events_offered(reply: &[u8]) -> Result<Vec<u8>> {
204 let mut r = ok_reply(reply, "the event list")?;
205 let count = r.u8()?;
206 Ok(r.take(usize::from(count))?.to_vec())
207}
208
209/// The subscribe payload: count, then the wanted codes the buds offer.
210/// Spec: realme_t310.md#subscribe
211pub(super) fn subscribe_payload(offered: &[u8], commands: &Commands) -> Vec<u8> {
212 let codes: Vec<u8> = EVENTS
213 .iter()
214 .filter(|(code, needs)| offered.contains(code) && needs.is_none_or(|cmd| commands.allows(cmd)))
215 .map(|(code, _)| *code)
216 .collect();
217 let mut payload = vec![u8::try_from(codes.len()).unwrap_or_default()];
218 payload.extend(codes);
219 payload
220}
221
222/// Spec: realme_t310.md#battery
223pub(super) fn decode_battery(reply: &[u8]) -> Result<Battery> {
224 let mut r = ok_reply(reply, "the battery reply")?;
225 let mut battery = Battery::default();
226 for _ in 0..r.u8()? {
227 let part = r.u8()?;
228 let raw = r.u8()?;
229 let level = raw & 0x7F;
230 if level == 0 {
231 continue; // not known
232 }
233 let charge = Some(Charge {
234 level,
235 charging: raw & 0x80 != 0,
236 });
237 match part {
238 0x01 => battery.left = charge,
239 0x02 => battery.right = charge,
240 0x03 => battery.case = charge,
241 _ => {}
242 }
243 }
244 Ok(battery)
245}
246
247/// The versions of kind 2: plain numbers are joined with dots; full dotted versions (the T310's)
248/// are shown once each, joined with ` / `. The raw text when there are none.
249/// Spec: realme_t310.md#firmware
250pub(super) fn decode_firmware(reply: &[u8]) -> Result<String> {
251 let mut r = ok_reply(reply, "the firmware reply")?;
252 let _count = r.u8()?;
253 let text = String::from_utf8_lossy(r.rest()).into_owned();
254 let fields: Vec<&str> = text.split(',').map(str::trim).collect();
255 let mut versions: Vec<&str> = fields
256 .chunks(3)
257 .filter_map(|triple| match triple {
258 [_device, "2", version] => Some(*version),
259 _ => None,
260 })
261 .collect();
262 if versions.is_empty() {
263 return Ok(text);
264 }
265 if !versions.iter().any(|v| v.contains('.')) {
266 return Ok(versions.join("."));
267 }
268 let mut seen = Vec::new();
269 versions.retain(|v| {
270 let new = !seen.contains(v);
271 seen.push(*v);
272 new
273 });
274 Ok(versions.join(" / "))
275}
276
277/// Spec: realme_t310.md#codec
278pub(super) fn decode_codec(reply: &[u8]) -> Result<String> {
279 let codec = ok_reply(reply, "the codec reply")?.u8()?;
280 Ok(name_of(&CODECS, codec).map_or_else(|| format!("unknown (0x{codec:02X})"), str::to_owned))
281}
282
283/// Spec: realme_t310.md#anc-read
284pub(super) fn decode_noise_mode(reply: &[u8]) -> Result<NoiseControl> {
285 let mask = noise_mask(reply, NOISE_MODE_QUERY, "the noise-control reply")?;
286 Ok(match NOISE_MODES.iter().find(|(m, _, _)| *m == mask) {
287 Some((_, mode, level)) => NoiseControl {
288 mode: (*mode).to_owned(),
289 level: level.map(str::to_owned),
290 },
291 None => NoiseControl {
292 mode: format!("unknown (0x{mask:02X})"),
293 level: None,
294 },
295 })
296}
297
298/// The mask that selects `mode`, as written and as read back. Spec: realme_t310.md#anc-write
299pub(super) fn noise_write_mask(mode: NoiseMode) -> u32 {
300 match mode {
301 NoiseMode::Off => 0x01,
302 NoiseMode::Transparency => 0x02,
303 NoiseMode::Anc(AncLevel::Light) => 0x04,
304 NoiseMode::Anc(AncLevel::Medium) => 0x10,
305 // Also plain "noise cancelling on".
306 NoiseMode::Anc(AncLevel::Deep) => 0x08,
307 }
308}
309
310/// `01 01 <mask>`: the noise-mode kind, then the mask in the fewest bytes (all fit in one).
311/// Spec: realme_t310.md#anc-write
312pub(super) fn noise_write_payload(mode: NoiseMode) -> Vec<u8> {
313 let mut payload = NOISE_MODE_QUERY.to_vec();
314 let mask = noise_write_mask(mode).to_le_bytes();
315 let used = mask.iter().rposition(|&b| b != 0).map_or(1, |last| last + 1);
316 payload.extend(mask.iter().take(used));
317 payload
318}
319
320/// The mask in a noise-control read reply. Spec: realme_t310.md#anc-read
321pub(super) fn decode_noise_mask(reply: &[u8]) -> Result<u32> {
322 noise_mask(reply, NOISE_MODE_QUERY, "the noise-control reply")
323}
324
325/// A write reply: `00` means accepted. Spec: realme_t310.md#writes
326pub(super) fn check_write_reply(reply: &[u8], what: &'static str) -> Result<()> {
327 ok_reply(reply, what).map(|_| ())
328}
329
330/// Spec: realme_t310.md#hold-cycle
331pub(super) fn decode_hold_cycle(reply: &[u8]) -> Result<Vec<String>> {
332 let mask = noise_mask(reply, HOLD_CYCLE_QUERY, "the hold-cycle reply")?;
333 let mut modes: Vec<String> = CYCLE_MODES
334 .iter()
335 .filter(|(bit, _)| mask & bit != 0)
336 .map(|(_, name)| (*name).to_owned())
337 .collect();
338 let known = CYCLE_MODES.iter().fold(0, |all, (bit, _)| all | bit);
339 if mask & !known != 0 {
340 modes.push(format!("unknown (0x{:02X})", mask & !known));
341 }
342 Ok(modes)
343}
344
345/// `00 <echo of the query> <mask, 1-4 bytes LE>`. Spec: realme_t310.md#anc-read
346fn noise_mask(reply: &[u8], query: [u8; 2], what: &'static str) -> Result<u32> {
347 let mut r = ok_reply(reply, what)?;
348 if [r.u8()?, r.u8()?] != query {
349 return Err(Error::Protocol(format!("{what} answers a different question")));
350 }
351 let bytes = r.rest();
352 if bytes.is_empty() || bytes.len() > 4 {
353 return Err(Error::Protocol(format!("{what} has a {} byte value", bytes.len())));
354 }
355 Ok(bytes.iter().rev().fold(0, |mask, &b| (mask << 8) | u32::from(b)))
356}
357
358/// Spec: realme_t310.md#switches
359pub(super) fn decode_switches(reply: &[u8]) -> Result<Vec<Switch>> {
360 let mut r = ok_reply(reply, "the switch reply")?;
361 let mut switches = Vec::new();
362 for _ in 0..r.u8()? {
363 let id = r.u8()?;
364 let value = r.u8()?;
365 if let Some((_, key, label)) = SWITCH_NAMES.iter().find(|(known, _, _)| *known == id) {
366 switches.push(Switch {
367 key,
368 label,
369 on: value == 0x01,
370 });
371 }
372 }
373 Ok(switches)
374}
375
376/// Spec: realme_t310.md#eq-read
377pub(super) fn decode_eq(reply: &[u8]) -> Result<String> {
378 let id = ok_reply(reply, "the EQ reply")?.u8()?;
379 Ok(name_of(&EQ_PRESETS, id).map_or_else(|| format!("custom-{id}"), str::to_owned))
380}
381
382/// `00 <min> <max> <level>`, all signed. Not used until W6. Spec: realme_t310.md#bass-read
383#[allow(dead_code)]
384pub(super) fn decode_bass_level(reply: &[u8]) -> Result<i8> {
385 let mut r = ok_reply(reply, "the bass-level reply")?;
386 let (min, max, level) = (r.i8()?, r.i8()?, r.i8()?);
387 if !(min..=max).contains(&level) {
388 return Err(Error::Protocol(format!("bass level {level} outside {min}..={max}")));
389 }
390 Ok(level)
391}
392
393/// Spec: realme_t310.md#gestures
394pub(super) fn decode_gestures(reply: &[u8]) -> Result<Vec<Gesture>> {
395 let mut r = ok_reply(reply, "the gesture table")?;
396 let mut gestures = Vec::new();
397 for _ in 0..r.u8()? {
398 let [side, group, act, function] = [r.u8()?, r.u8()?, r.u8()?, r.u8()?];
399 gestures.push(Gesture {
400 side: name_of(&SIDES, side).map_or_else(|| format!("device-0x{side:02X}"), str::to_owned),
401 gesture: name_of(&ACTS, act).map_or_else(|| format!("act-0x{act:02X}"), str::to_owned),
402 action: name_of(&FUNCTIONS, function).map_or_else(|| format!("fn-0x{function:02X}"), str::to_owned),
403 group: (group != MAIN_GROUP).then_some(group),
404 });
405 }
406 Ok(gestures)
407}
408
409/// The handshake reply of the owner's T310 (HW1). Spec: realme_t310.md#bitmap-t310
410#[cfg(test)]
411pub(super) const T310_BITMAP_REPLY: &str = "00 BF 1F 5A 20 45 04 40 00";
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416 use crate::transport::mock::hex;
417
418 #[test]
419 fn t310_bitmap_allows_its_commands_and_nothing_else() {
420 let commands = Commands::parse(&hex(T310_BITMAP_REPLY)).unwrap();
421 // Every gated command in the T310's logged command set (realme_t310.md#bitmap-t310).
422 for cmd in [
423 0x0100, 0x0103, 0x0105, 0x0106, 0x0108, 0x0109, 0x010C, 0x010D, 0x010F, 0x0114, 0x0122, 0x0124, 0x0205,
424 0x0400, 0x0401, 0x0403, 0x0404, 0x0405, 0x0406, 0x0418, 0x041B, 0x0200,
425 ] {
426 assert!(commands.allows(cmd), "0x{cmd:04X} should be allowed");
427 }
428 // Commands the T310 lacks, and commands budctl has no gate for.
429 for cmd in [0x012F, 0x041E, 0x0413, 0x0130, 0x0427, 0x0423, 0x012A, 0x0422, 0x9999] {
430 assert!(!commands.allows(cmd), "0x{cmd:04X} should be refused");
431 }
432 }
433
434 #[test]
435 fn a_short_bitmap_allows_only_the_always_commands() {
436 let commands = Commands::parse(&hex("00")).unwrap();
437 assert!(commands.allows(BATTERY) && commands.allows(SWITCHES) && commands.allows(HANDSHAKE));
438 assert!(!commands.allows(FIRMWARE) && !commands.allows(NOISE_CONTROL));
439 assert!(matches!(
440 Commands::parse(&hex("01 FF")),
441 Err(Error::Rejected { status: 1, .. })
442 ));
443 }
444
445 #[test]
446 fn product_id_is_three_bytes_little_endian() {
447 assert_eq!(decode_product_id(&hex("00 12 3C 06")).unwrap(), T310_PRODUCT_ID);
448 assert_eq!(decode_product_id(&hex("00 14 54 06")).unwrap(), 0x06_54_14);
449 assert!(decode_product_id(&hex("00 12 3C")).is_err());
450 }
451
452 #[test]
453 fn subscribes_to_offered_events_only() {
454 let commands = Commands::parse(&hex(T310_BITMAP_REPLY)).unwrap();
455 let buds4_offer = hex("00 09 01 02 03 04 08 0B F1 F2 F3");
456 let offered = decode_events_offered(&buds4_offer).unwrap();
457 assert_eq!(subscribe_payload(&offered, &commands), hex("04 01 02 03 04"));
458 assert_eq!(subscribe_payload(&[0x02, 0x01], &commands), hex("02 01 02"));
459 let no_fit_test = Commands::parse(&hex("00 BD 0D")).unwrap();
460 assert_eq!(subscribe_payload(&offered, &no_fit_test), hex("03 01 02 03"));
461 }
462
463 #[test]
464 fn battery_levels_charging_and_unknown_parts() {
465 let battery = decode_battery(&hex("00 03 01 64 02 E4 03 00")).unwrap();
466 assert_eq!(
467 battery.left,
468 Some(Charge {
469 level: 100,
470 charging: false
471 })
472 );
473 assert_eq!(
474 battery.right,
475 Some(Charge {
476 level: 100,
477 charging: true
478 })
479 );
480 assert_eq!(battery.case, None);
481 assert_eq!(decode_battery(&hex("00 00")).unwrap(), Battery::default());
482 assert!(decode_battery(&hex("00 03 01 64")).is_err());
483 }
484
485 #[test]
486 fn firmware_shows_kind_two_versions() {
487 let mut reply = hex("00 04");
488 reply.extend(b"1,2,138,2,2,138,3,1,01,3,2,105");
489 assert_eq!(decode_firmware(&reply).unwrap(), "138.138.105");
490 // The owner's T310 (HW1): both buds report the same full version.
491 let mut t310 = hex("00 02");
492 t310.extend(b"1,2,1.1.0.43,2,2,1.1.0.43");
493 assert_eq!(decode_firmware(&t310).unwrap(), "1.1.0.43");
494 let mut differ = hex("00 02");
495 differ.extend(b"1,2,1.1.0.43,2,2,1.1.0.44");
496 assert_eq!(decode_firmware(&differ).unwrap(), "1.1.0.43 / 1.1.0.44");
497 let mut odd = hex("00 01");
498 odd.extend(b"V1.0.2");
499 assert_eq!(decode_firmware(&odd).unwrap(), "V1.0.2");
500 }
501
502 #[test]
503 fn noise_control_modes() {
504 let mode = |reply: &str| decode_noise_mode(&hex(reply)).unwrap();
505 assert_eq!(mode("00 01 01 01").mode, "off");
506 assert_eq!(mode("00 01 01 02 00").mode, "transparency");
507 let deep = mode("00 01 01 08");
508 assert_eq!((deep.mode.as_str(), deep.level.as_deref()), ("anc", Some("deep")));
509 assert_eq!(mode("00 01 01 10").level.as_deref(), Some("medium"));
510 assert_eq!(mode("00 01 01 00 08").mode, "unknown (0x800)");
511 assert!(decode_noise_mode(&hex("00 02 01 08")).is_err());
512 assert!(decode_noise_mode(&hex("00 01 01")).is_err());
513 assert!(matches!(
514 decode_noise_mode(&hex("0E 01 01 08")),
515 Err(Error::Rejected { status: 0x0E, .. })
516 ));
517 }
518
519 #[test]
520 fn noise_control_write_payloads() {
521 assert_eq!(noise_write_payload(NoiseMode::Off), hex("01 01 01"));
522 assert_eq!(noise_write_payload(NoiseMode::Transparency), hex("01 01 02"));
523 assert_eq!(noise_write_payload(NoiseMode::Anc(AncLevel::Light)), hex("01 01 04"));
524 assert_eq!(noise_write_payload(NoiseMode::Anc(AncLevel::Medium)), hex("01 01 10"));
525 assert_eq!(noise_write_payload(NoiseMode::Anc(AncLevel::Deep)), hex("01 01 08"));
526 // What is written is what a read reports: every write mask decodes to its own mode.
527 for level in [AncLevel::Light, AncLevel::Medium, AncLevel::Deep] {
528 let mut reply = hex("00 01 01");
529 reply.extend(noise_write_payload(NoiseMode::Anc(level)).iter().skip(2));
530 let read = decode_noise_mode(&reply).unwrap();
531 assert_eq!((read.mode.as_str(), read.level.as_deref()), ("anc", Some(level.name())));
532 }
533 // The family's documented frame for "off" (realme_t310.md#frame-whole).
534 let frame =
535 crate::devices::realme_t310::frame::encode(NOISE_CONTROL_WRITE, 0x06, &noise_write_payload(NoiseMode::Off))
536 .unwrap();
537 assert_eq!(frame, hex("AA 0A 00 00 04 04 06 03 00 01 01 01"));
538 }
539
540 #[test]
541 fn write_replies() {
542 assert!(check_write_reply(&hex("00"), "the write").is_ok());
543 assert!(matches!(
544 check_write_reply(&hex("0E"), "the write"),
545 Err(Error::Rejected { status: 0x0E, .. })
546 ));
547 assert!(check_write_reply(&[], "the write").is_err());
548 }
549
550 #[test]
551 fn hold_cycle_lists_modes() {
552 assert_eq!(decode_hold_cycle(&hex("00 02 01 0A")).unwrap(), ["transparency", "anc"]);
553 assert_eq!(
554 decode_hold_cycle(&hex("00 02 01 0B 00")).unwrap(),
555 ["off", "transparency", "anc"]
556 );
557 assert_eq!(decode_hold_cycle(&hex("00 02 01 14")).unwrap(), ["unknown (0x14)"]);
558 }
559
560 #[test]
561 fn switches_from_report_22_values() {
562 let switches = decode_switches(&hex("00 06 05 00 06 00 11 01 1A 00 1B 01 1D 01")).unwrap();
563 let on: Vec<(&str, bool)> = switches.iter().map(|s| (s.key, s.on)).collect();
564 assert_eq!(
565 on,
566 [
567 ("game", false),
568 ("dual", true),
569 ("wind", false),
570 ("spatial", true),
571 ("bass-boost", true)
572 ]
573 );
574 assert!(decode_switches(&hex("00 02 06 01")).is_err());
575 }
576
577 #[test]
578 fn eq_codec_and_bass_level() {
579 assert_eq!(decode_eq(&hex("00 00")).unwrap(), "pure-raw");
580 assert_eq!(decode_eq(&hex("00 03")).unwrap(), "pure-bass");
581 assert_eq!(decode_eq(&hex("00 05")).unwrap(), "custom-5");
582 assert_eq!(decode_codec(&hex("00 02")).unwrap(), "AAC");
583 assert_eq!(decode_codec(&hex("00 09")).unwrap(), "unknown (0x09)");
584 assert_eq!(decode_bass_level(&hex("00 FB 05 FE")).unwrap(), -2);
585 assert!(decode_bass_level(&hex("00 FB 05 07")).is_err());
586 }
587
588 #[test]
589 fn gesture_table_names_known_values() {
590 let gestures = decode_gestures(&hex("00 03 01 01 02 01 02 01 04 08 04 06 02 1D")).unwrap();
591 let rows: Vec<(&str, &str, &str, Option<u8>)> = gestures
592 .iter()
593 .map(|g| (g.side.as_str(), g.gesture.as_str(), g.action.as_str(), g.group))
594 .collect();
595 assert_eq!(
596 rows,
597 [
598 ("left", "double-tap", "play-pause", None),
599 ("right", "hold", "noise-cycle", None),
600 ("both", "double-tap", "answer-call", Some(6)),
601 ]
602 );
603 let odd = decode_gestures(&hex("00 01 09 01 07 42")).unwrap();
604 assert_eq!(odd.first().map(|g| g.action.as_str()), Some("fn-0x42"));
605 assert!(decode_gestures(&hex("00 02 01 01 02 01")).is_err());
606 }
607}