Krolyxon
Commit b37b005

Branches

Refs →

budctlcratesbudctl-coresrcdevicesrealme_t310codec.rs

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