Krolyxon
Commit 801bf1e

Branches

Refs →

budctlcratesbudctl-coresrcdevicesrealme_t310codec.rs

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