Skip to main content

open_stomp/
state.rs

1//! Device state tracker: applies MIDI traffic (either direction) to a model of the pedal and
2//! describes each message in plain English.
3
4use crate::catalog::{Module, NOTES, drum_pattern_name};
5use crate::midi::{Cmd, Dir, HOST_CH, Msg, hex};
6use crate::records::{CHAIN_LEN, PRESET_COUNT, Preset, Settings, parse_ir_slot, u14, valid_chain};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum Origin {
10    /// Pedal → host.
11    Pedal,
12    /// Host → pedal (this app, or the official app in a replayed capture).
13    Host,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum Category {
18    Preset,
19    Effect(Module),
20    Volume,
21    Navigation,
22    Looper,
23    Drum,
24    Tuner,
25    Settings,
26    Device,
27    /// Request/reply plumbing (handshake reads, acks, upload chunks).
28    Protocol,
29    Unknown,
30}
31
32impl Category {
33    pub fn label(self) -> &'static str {
34        match self {
35            Category::Preset => "PRESET",
36            Category::Effect(m) => m.name(),
37            Category::Volume => "VOLUME",
38            Category::Navigation => "PAGE",
39            Category::Looper => "LOOPER",
40            Category::Drum => "DRUM",
41            Category::Tuner => "TUNER",
42            Category::Settings => "SETTINGS",
43            Category::Device => "DEVICE",
44            Category::Protocol => "SYSEX",
45            Category::Unknown => "???",
46        }
47    }
48}
49
50/// A human-readable description of one MIDI message.
51#[derive(Clone, Debug)]
52pub struct Event {
53    pub origin: Origin,
54    pub category: Category,
55    /// What changed, e.g. `"Mar J800 · GAIN"`.
56    pub subject: String,
57    /// The new value, e.g. `"64"`.
58    pub value: String,
59    /// Consecutive events with the same key may be merged into one log row (knob sweeps).
60    pub coalesce: Option<u64>,
61    /// The message didn't change the tracked state (e.g. the CC burst after a preset change
62    /// repeating values already known from the preset record, or values for unused param slots).
63    pub redundant: bool,
64    pub raw: Vec<u8>,
65}
66
67#[derive(Clone, Debug, Default)]
68pub struct Looper {
69    /// 0 empty, 1 recording, 2 playing, 3 overdubbing, 4 stopped.
70    pub state: u8,
71    /// 0x1 = overdub layer on top (undo available), 0x2 = base layer only.
72    pub layers: u8,
73    pub rec_level: Option<u8>,
74    pub play_level: Option<u8>,
75    pub sync: Option<bool>,
76    /// 0 NR, 1 AR.
77    pub mode: Option<u8>,
78}
79
80impl Looper {
81    pub fn set(&mut self, v: u8) {
82        self.state = v & 0x0F;
83        self.layers = v >> 4;
84    }
85
86    pub fn state_name(&self) -> &'static str {
87        looper_state_name(self.state)
88    }
89}
90
91pub fn looper_state_name(s: u8) -> &'static str {
92    match s {
93        0 => "Empty",
94        1 => "Recording",
95        2 => "Playing",
96        3 => "Overdubbing",
97        4 => "Stopped",
98        _ => "Unknown",
99    }
100}
101
102#[derive(Clone, Debug, Default)]
103pub struct Drum {
104    pub playing: bool,
105    pub pattern: Option<u8>,
106    pub level: Option<u8>,
107    pub bpm: Option<u16>,
108}
109
110#[derive(Clone, Debug, Default)]
111pub struct Tuner {
112    pub active: bool,
113    pub detected: bool,
114    pub note: Option<u8>,
115    /// Raw, 50 = in tune.
116    pub cents: Option<u8>,
117}
118
119impl Tuner {
120    pub fn cents_offset(&self) -> Option<i16> {
121        self.cents.map(|c| c as i16 - 50)
122    }
123}
124
125#[derive(Clone, Debug)]
126pub struct DeviceState {
127    pub firmware: Option<String>,
128    pub model_id: Option<String>,
129    pub product: Option<String>,
130    pub presets: Vec<Option<Preset>>,
131    /// Active preset index (0-based).
132    pub current: Option<u8>,
133    /// The live edit buffer: stored preset + every change since.
134    pub live: Preset,
135    pub live_known: bool,
136    pub page: Option<Module>,
137    pub looper: Looper,
138    pub drum: Drum,
139    pub tuner: Tuner,
140    pub settings: Option<Settings>,
141    pub user_amps: [Option<String>; 10],
142    pub user_irs: [Option<String>; 10],
143}
144
145impl Default for DeviceState {
146    fn default() -> Self {
147        DeviceState {
148            firmware: None,
149            model_id: None,
150            product: None,
151            presets: vec![None; PRESET_COUNT],
152            current: None,
153            live: Preset::default(),
154            live_known: false,
155            page: None,
156            looper: Looper::default(),
157            drum: Drum::default(),
158            tuner: Tuner::default(),
159            settings: None,
160            user_amps: Default::default(),
161            user_irs: Default::default(),
162        }
163    }
164}
165
166fn key(parts: &[u64]) -> Option<u64> {
167    Some(parts.iter().fold(0xcbf29ce484222325u64, |h, p| (h ^ p).wrapping_mul(0x100000001b3)))
168}
169
170/// `"4352 / 8192 bytes"` for an upload chunk.
171fn upload_progress(payload: &[u8]) -> String {
172    match crate::upload::Chunk::parse(payload) {
173        Some(c) => format!("{} / {} bytes", c.offset as usize + c.data.len(), c.total),
174        None => format!("{} bytes", payload.len()),
175    }
176}
177
178pub fn preset_label(i: u8) -> String {
179    format!("P{:02}", i as u16 + 1)
180}
181
182/// `"GATE > OD/FX > AMP > …"` for a chain order.
183pub fn chain_label(chain: &[u8]) -> String {
184    let names: Vec<&str> = chain.iter().map(|i| Module::from_index(*i).map_or("?", |m| m.name())).collect();
185    names.join(" > ")
186}
187
188impl DeviceState {
189    pub fn stored(&self, i: u8) -> Option<&Preset> {
190        self.presets.get(i as usize)?.as_ref()
191    }
192
193    pub fn preset_name(&self, i: u8) -> Option<&str> {
194        self.stored(i).map(|p| p.name.as_str())
195    }
196
197    /// The live edit buffer differs from the stored preset.
198    pub fn modified(&self) -> bool {
199        match (self.current, self.live_known) {
200            (Some(i), true) => self.stored(i).is_some_and(|p| !p.same_sound(&self.live)),
201            _ => false,
202        }
203    }
204
205    /// Model name for display, using user slot names where known.
206    pub fn model_name(&self, m: Module, model: u8) -> String {
207        let user = match m {
208            Module::Amp if model >= 30 => self.user_amps.get(model as usize - 30),
209            Module::Cab if model >= 30 => self.user_irs.get(model as usize - 30),
210            _ => None,
211        };
212        match user.and_then(|n| n.as_deref()) {
213            Some(n) if !n.is_empty() && !n.starts_with("--") && n != m.model_name(model) => {
214                format!("{} · {n}", m.model_name(model))
215            }
216            _ => m.model_name(model),
217        }
218    }
219
220    /// Apply one complete MIDI message and describe it.
221    pub fn apply(&mut self, bytes: &[u8], origin: Origin) -> Event {
222        let mut ev = Event {
223            origin,
224            category: Category::Unknown,
225            subject: String::new(),
226            value: String::new(),
227            coalesce: None,
228            redundant: false,
229            raw: bytes.to_vec(),
230        };
231        match Msg::parse(bytes) {
232            Msg::Cc { ch, cc, val } => self.apply_cc(&mut ev, ch, cc, val),
233            Msg::Pc { prog, .. } => {
234                self.select_preset(prog);
235                ev.category = Category::Preset;
236                ev.subject = "Preset selected".into();
237                ev.value = match self.preset_name(prog) {
238                    Some(n) => format!("{} · {n}", preset_label(prog)),
239                    None => preset_label(prog),
240                };
241            }
242            Msg::Short { kind, payload } => self.apply_short(&mut ev, kind, &payload),
243            Msg::Notify { what, payload } => self.apply_notify(&mut ev, what, &payload),
244            Msg::Nep { cmd, dir, payload } => self.apply_nep(&mut ev, cmd, dir, &payload),
245            Msg::Other(b) => {
246                ev.subject = "Unrecognised message".into();
247                ev.value = hex(&b);
248            }
249        }
250        ev
251    }
252
253    pub fn select_preset(&mut self, prog: u8) {
254        self.current = Some(prog);
255        if let Some(p) = self.stored(prog) {
256            self.live = p.clone();
257            self.live_known = true;
258        }
259    }
260
261    fn apply_cc(&mut self, ev: &mut Event, ch: u8, cc: u8, val: u8) {
262        let o = ev.origin as u64;
263        match cc {
264            0x00..=0x07 => {
265                let m = Module::from_index(cc).unwrap();
266                let st = &mut self.live.modules[m.index()];
267                let (was_on, was_model) = (st.on, st.model);
268                ev.redundant = st.head() == val && self.live_known;
269                st.set_head(val);
270                let (on, model) = (st.on, st.model);
271                ev.category = Category::Effect(m);
272                let name = self.model_name(m, model);
273                if model != was_model {
274                    ev.subject = "Model".into();
275                    ev.value = format!("#{:02} {name}", model + 1);
276                    ev.coalesce = key(&[o, 1, cc as u64]);
277                } else {
278                    ev.subject = name;
279                    ev.value = if on { "ON" } else { "OFF" }.into();
280                }
281                if on != was_on && model != was_model {
282                    ev.value.push_str(if on { " · ON" } else { " · OFF" });
283                }
284            }
285            0x08..=0x39 if Module::from_param_cc(cc).is_some() => {
286                let (m, slot) = Module::from_param_cc(cc).unwrap();
287                let st = &mut self.live.modules[m.index()];
288                let model = st.model;
289                ev.redundant = (st.params[slot] == val && self.live_known) || m.param(model, slot).is_none();
290                st.params[slot] = val;
291                ev.category = Category::Effect(m);
292                let (pname, pval) = match m.param(model, slot) {
293                    Some(p) => (p.name.to_owned(), p.format(val)),
294                    None => (format!("P{}", slot + 1), val.to_string()),
295                };
296                ev.subject = format!("{} · {pname}", m.model_name(model));
297                ev.value = pval;
298                ev.coalesce = key(&[o, 2, cc as u64, model as u64]);
299            }
300            0x3A => {
301                ev.redundant = self.live.volume == val && self.live_known;
302                self.live.volume = val;
303                ev.category = Category::Volume;
304                ev.subject = "Preset volume".into();
305                ev.value = val.to_string();
306                ev.coalesce = key(&[o, 3]);
307            }
308            0x3B => {
309                self.page = Module::from_index(val);
310                ev.category = Category::Navigation;
311                ev.subject = "Pedal page".into();
312                ev.value = self.page.map(|m| m.name().to_owned()).unwrap_or_else(|| val.to_string());
313            }
314            0x3F => {
315                self.drum.playing = val != 0;
316                ev.category = Category::Drum;
317                ev.subject = "Drum".into();
318                ev.value = if val != 0 { "PLAYING" } else { "STOPPED" }.into();
319            }
320            0x40 => {
321                self.drum.pattern = Some(val);
322                ev.category = Category::Drum;
323                ev.subject = "Pattern".into();
324                ev.value = drum_pattern_name(val);
325                ev.coalesce = key(&[o, 4]);
326            }
327            0x41 => {
328                self.drum.level = Some(val);
329                ev.category = Category::Drum;
330                ev.subject = "Drum level".into();
331                ev.value = val.to_string();
332                ev.coalesce = key(&[o, 5]);
333            }
334            0x42 | 0x43 => {
335                let (slot, name) = if cc == 0x42 {
336                    (&mut self.looper.rec_level, "Record level")
337                } else {
338                    (&mut self.looper.play_level, "Playback level")
339                };
340                *slot = Some(val);
341                ev.category = Category::Looper;
342                ev.subject = name.into();
343                ev.value = val.to_string();
344                ev.coalesce = key(&[o, 6, cc as u64]);
345            }
346            0x44 if ch == HOST_CH => {
347                ev.category = Category::Looper;
348                ev.subject = "Looper button".into();
349                ev.value = match val {
350                    1 => "REC / PLAY / DUB",
351                    2 => "STOP",
352                    4 => "CLEAR",
353                    8 => "UNDO / REDO",
354                    _ => "?",
355                }
356                .into();
357            }
358            0x44 => {
359                self.looper.set(val);
360                ev.category = Category::Looper;
361                ev.subject = "Looper".into();
362                ev.value = self.looper.state_name().to_uppercase();
363                match self.looper.layers {
364                    1 => ev.value.push_str(" · overdub layer (undo available)"),
365                    2 => ev.value.push_str(" · base layer"),
366                    _ => {}
367                }
368            }
369            0x45 | 0x46 | 0x48 => {
370                match cc {
371                    0x45 => self.tuner.detected = val != 0,
372                    // The pedal counts pitch classes from A (A=0); NOTES starts at C.
373                    0x46 => self.tuner.note = Some((val + 9) % 12),
374                    _ => self.tuner.cents = Some(val),
375                }
376                ev.category = Category::Tuner;
377                ev.subject = "Pitch".into();
378                ev.value = match (self.tuner.detected, self.tuner.note, self.tuner.cents_offset()) {
379                    (false, _, _) => "—".into(),
380                    (true, Some(n), Some(c)) => format!("{} {c:+} ¢", NOTES[n as usize]),
381                    (true, Some(n), None) => NOTES[n as usize].into(),
382                    _ => "detecting…".into(),
383                };
384                ev.coalesce = key(&[o, 7]);
385            }
386            0x49 => {
387                self.looper.sync = Some(val != 0);
388                ev.category = Category::Looper;
389                ev.subject = "Loop sync".into();
390                ev.value = if val != 0 { "ON" } else { "OFF" }.into();
391            }
392            0x4A => {
393                self.looper.mode = Some(val);
394                ev.category = Category::Looper;
395                ev.subject = "Loop mode".into();
396                ev.value = if val == 0 { "NR" } else { "AR" }.into();
397            }
398            _ => {
399                ev.subject = format!("CC 0x{cc:02X} (ch {})", ch + 1);
400                ev.value = val.to_string();
401                ev.coalesce = key(&[o, 8, cc as u64]);
402            }
403        }
404    }
405
406    fn apply_short(&mut self, ev: &mut Event, kind: u8, payload: &[u8]) {
407        ev.category = Category::Device;
408        let strings: Vec<String> = payload
409            .split(|b| *b == 0)
410            .filter(|s| !s.is_empty() && s.iter().all(|c| (0x20..0x7F).contains(c)))
411            .map(|s| String::from_utf8_lossy(s).into_owned())
412            .collect();
413        match kind {
414            0x00 => {
415                ev.category = Category::Protocol;
416                ev.subject = "Version request".into();
417            }
418            0x10 if strings.is_empty() => {
419                ev.subject = "Identity ping".into();
420            }
421            0x10 => {
422                self.firmware = strings.first().cloned();
423                self.model_id = strings.get(1).cloned();
424                ev.subject = "Firmware".into();
425                ev.value = strings.join(" · ");
426            }
427            0x60 if payload.is_empty() => {
428                ev.category = Category::Protocol;
429                ev.subject = "Product name request".into();
430            }
431            0x60 => {
432                self.product = strings.first().cloned();
433                ev.subject = "Product".into();
434                ev.value = strings.first().cloned().unwrap_or_default();
435            }
436            _ => {
437                ev.category = Category::Unknown;
438                ev.subject = format!("Short SysEx 0x{kind:02X}");
439                ev.value = hex(payload);
440            }
441        }
442    }
443
444    fn apply_notify(&mut self, ev: &mut Event, what: u8, payload: &[u8]) {
445        match what {
446            0x19 => {
447                if payload.len() >= 6 {
448                    self.drum.pattern = Some(payload[1]);
449                    self.drum.bpm = Some(u14(payload[4], payload[5]));
450                }
451                ev.category = Category::Drum;
452                ev.subject = "Tempo".into();
453                ev.value = self.drum.bpm.map(|b| format!("{b} BPM")).unwrap_or_default();
454                ev.coalesce = key(&[ev.origin as u64, 9]);
455            }
456            0x0B => {
457                let i = payload.first().copied().unwrap_or(0);
458                ev.category = Category::Preset;
459                ev.subject = "Saved on pedal".into();
460                ev.value = preset_label(i);
461            }
462            0x6F => {
463                ev.category = Category::Tuner;
464                ev.subject = "Tuner".into();
465                ev.value = "toggled on pedal".into();
466            }
467            0x0D => {
468                ev.category = Category::Preset;
469                ev.subject = "Chain".into();
470                ev.value = "reordered on pedal".into();
471            }
472            _ => {
473                ev.category = Category::Unknown;
474                ev.subject = format!("Notify 0x{what:02X} ({})", Cmd::label(what));
475                ev.value = hex(payload);
476            }
477        }
478    }
479
480    fn apply_nep(&mut self, ev: &mut Event, cmd: u8, dir: u8, payload: &[u8]) {
481        ev.category = Category::Protocol;
482        ev.subject = format!("{} {}", Cmd::label(cmd), Dir::label(dir));
483        let data = dir == Dir::Reply as u8 || dir == Dir::Write as u8;
484        let host_write = dir == Dir::Write as u8;
485        match Cmd::from_u8(cmd) {
486            Some(Cmd::Preset) if data => {
487                if let Some(p) = Preset::from_packed(payload) {
488                    let i = p.index;
489                    ev.value = format!("{} · {}", preset_label(i), p.name);
490                    if host_write {
491                        ev.category = Category::Preset;
492                        ev.subject = "Preset written".into();
493                    }
494                    let is_current = self.current == Some(i);
495                    if let Some(slot) = self.presets.get_mut(i as usize) {
496                        *slot = Some(p.clone());
497                    }
498                    if is_current && (!self.live_known || host_write) {
499                        self.live = p;
500                        self.live_known = true;
501                    }
502                }
503            }
504            Some(Cmd::EditBuffer) if data => {
505                if let Some(mut p) = Preset::from_packed(payload) {
506                    // The record's index field is always 0 here, and no read is known to return the
507                    // active slot, so identify it by matching against the stored presets.
508                    if self.current.is_none() {
509                        self.current = self
510                            .presets
511                            .iter()
512                            .position(|s| s.as_ref().is_some_and(|s| s.name == p.name && s.same_sound(&p)))
513                            .map(|i| i as u8);
514                    }
515                    p.index = self.current.unwrap_or(0);
516                    ev.value = p.name.clone();
517                    self.live = p;
518                    self.live_known = true;
519                }
520            }
521            Some(Cmd::Chain) if data => {
522                if let Some(order) = payload.get(..CHAIN_LEN).filter(|o| valid_chain(o)) {
523                    let changed = self.live.chain[..] != *order;
524                    self.live.chain.copy_from_slice(order);
525                    ev.value = chain_label(order);
526                    // a reply only matters when it brings a change (a move made on the pedal)
527                    if host_write || changed {
528                        ev.category = Category::Preset;
529                        ev.subject = "Chain order".into();
530                    }
531                }
532            }
533            Some(Cmd::PresetName) if host_write => {
534                let name = crate::records::ascii(payload.get(1..).unwrap_or_default());
535                ev.category = Category::Preset;
536                ev.subject = "Rename".into();
537                ev.value = format!("“{name}”");
538                self.live.name = name;
539            }
540            Some(Cmd::System) if data => {
541                if let Some(s) = Settings::from_packed(payload) {
542                    ev.value = format!(
543                        "trim {:+} dB · EQ {}/{}/{} · wireless {} · loopback {}",
544                        s.input_trim_db(),
545                        s.eq_bass,
546                        s.eq_mid,
547                        s.eq_treble,
548                        if s.wireless { "on" } else { "off" },
549                        if s.loopback { "on" } else { "off" },
550                    );
551                    if host_write {
552                        ev.category = Category::Settings;
553                        ev.subject = "System settings".into();
554                        ev.coalesce = key(&[ev.origin as u64, 10]);
555                    }
556                    self.settings = Some(s);
557                }
558            }
559            Some(Cmd::IrSlot) if data => {
560                if let Some((slot, name)) = parse_ir_slot(payload) {
561                    ev.value = format!("USER IR {:02} · {name}", slot + 1);
562                    if host_write {
563                        ev.category = Category::Effect(Module::Cab);
564                        ev.subject = "User IR slot".into();
565                    }
566                    if let Some(s) = self.user_irs.get_mut(slot as usize) {
567                        *s = Some(name);
568                    }
569                }
570            }
571            Some(Cmd::UserAmp) if dir == Dir::Reply as u8 || host_write => {
572                use crate::upload::{Chunk, UserAmpInfo, amp_sub};
573                let chunk = Chunk::parse(payload);
574                if let Some(info) = UserAmpInfo::parse(payload) {
575                    ev.value = format!("USER AMP {:02} · {}", info.slot + 1, info.name);
576                    if host_write {
577                        ev.category = Category::Effect(Module::Amp);
578                        ev.subject = "User AMP slot".into();
579                    }
580                    if let Some(s) = self.user_amps.get_mut(info.slot as usize) {
581                        *s = Some(info.name);
582                    }
583                } else if let Some(c) = chunk.as_ref().filter(|c| c.sub == amp_sub::DELETE) {
584                    ev.category = Category::Effect(Module::Amp);
585                    ev.subject = "User AMP deleted".into();
586                    ev.value = format!("USER AMP {:02}", c.slot + 1);
587                } else if host_write {
588                    ev.subject = format!("{} upload", Cmd::label(cmd));
589                    ev.value = upload_progress(payload);
590                    ev.coalesce = key(&[ev.origin as u64, 11, cmd as u64]);
591                } else if chunk.is_some_and(|c| c.sub == amp_sub::READ_DATA) {
592                    ev.subject = format!("{} read", Cmd::label(cmd));
593                    ev.value = upload_progress(payload);
594                    ev.coalesce = key(&[ev.origin as u64, 12, cmd as u64]);
595                }
596            }
597            Some(Cmd::UserAmp) if dir == Dir::Read as u8 => {
598                if crate::upload::Chunk::parse(payload).is_some_and(|c| c.sub == crate::upload::amp_sub::READ_DATA) {
599                    ev.subject = format!("{} read", Cmd::label(cmd));
600                    ev.value = upload_progress(payload);
601                    ev.coalesce = key(&[ev.origin as u64, 12, cmd as u64]);
602                }
603            }
604            Some(Cmd::IrData) if host_write => {
605                ev.subject = format!("{} upload", Cmd::label(cmd));
606                ev.value = upload_progress(payload);
607                ev.coalesce = key(&[ev.origin as u64, 11, cmd as u64]);
608            }
609            // reading a slot back (requests and replies)
610            Some(Cmd::IrData) => {
611                ev.subject = format!("{} read", Cmd::label(cmd));
612                ev.value = upload_progress(payload);
613                ev.coalesce = key(&[ev.origin as u64, 12, cmd as u64]);
614            }
615            Some(Cmd::Loop) if data => {
616                if payload.len() >= 4 {
617                    self.looper.rec_level = Some(payload[1]);
618                    self.looper.play_level = Some(payload[2]);
619                    self.looper.set(payload[3]);
620                    ev.value = format!(
621                        "{} · rec {} · play {}",
622                        self.looper.state_name(),
623                        payload[1],
624                        payload[2]
625                    );
626                }
627            }
628            Some(Cmd::Drum) if data => {
629                if payload.len() >= 6 {
630                    self.drum.pattern = Some(payload[1]);
631                    self.drum.level = Some(payload[2]);
632                    self.drum.bpm = Some(u14(payload[4], payload[5]));
633                    ev.value = format!(
634                        "{} · level {} · {} BPM",
635                        drum_pattern_name(payload[1]),
636                        payload[2],
637                        u14(payload[4], payload[5])
638                    );
639                }
640            }
641            Some(Cmd::Tuner) if data => {
642                if let Some(&s) = payload.first() {
643                    self.tuner.active = s != 0;
644                    ev.value = if s != 0 { "active" } else { "off" }.into();
645                }
646            }
647            _ => {
648                if !payload.is_empty() {
649                    let shown = &payload[..payload.len().min(16)];
650                    ev.value = hex(shown) + if payload.len() > 16 { " …" } else { "" };
651                }
652            }
653        }
654    }
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660    use crate::midi::host;
661
662    #[test]
663    fn chain_writes_and_replies_update_live() {
664        let mut st = DeviceState::default();
665        let ev = st.apply(&host::chain(&[0, 6, 1, 2, 7, 4, 3, 5]).unwrap(), Origin::Host);
666        assert_eq!(st.live.chain, [0, 6, 1, 2, 7, 4, 3, 5]);
667        assert_eq!((ev.category, ev.value.as_str()), (Category::Preset, "OD/FX > GATE > AMP > CAB > EQ > DELAY > MOD > REVERB"));
668        // the pedal's echo of the same order changes nothing
669        let echo = [0xF0, 0, 0x21, 0x7A, 0x70, 0x0D, 2, 0, 6, 1, 2, 7, 4, 3, 5, 0xF7];
670        assert_eq!(st.apply(&echo, Origin::Pedal).category, Category::Protocol);
671        // read after REVERB was moved ahead of EQ on the pedal (2026-12-03)
672        let moved = [0xF0, 0, 0x21, 0x7A, 0x70, 0x0D, 2, 6, 0, 1, 2, 5, 7, 3, 4, 0xF7];
673        assert_eq!(st.apply(&moved, Origin::Pedal).category, Category::Preset);
674        assert_eq!(st.live.chain, [6, 0, 1, 2, 5, 7, 3, 4]);
675    }
676
677    #[test]
678    fn tuner_pitch_class_counts_from_a() {
679        let mut st = DeviceState::default();
680        st.apply(&[0xB0, 0x45, 1], Origin::Pedal);
681        st.apply(&[0xB0, 0x48, 50], Origin::Pedal);
682        // Raw values the pedal sent for a bass's open strings.
683        for (raw, note) in [(7, "E"), (0, "A"), (5, "D"), (10, "G")] {
684            let ev = st.apply(&[0xB0, 0x46, raw], Origin::Pedal);
685            assert_eq!(st.tuner.note.map(|n| NOTES[n as usize]), Some(note));
686            assert_eq!(ev.value, format!("{note} +0 ¢"));
687        }
688    }
689}