Skip to main content

oscyl_midi/
device.rs

1//! Any registered synth, several at once: which drivers exist, which MIDI
2//! ports look like their synths, and a generic connection to each.
3
4use std::collections::VecDeque;
5use std::fmt;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::time::{Duration, Instant};
8
9#[cfg(feature = "midir")]
10use midir::{MidiInput, MidiOutput};
11use oscyl_driver::engine::OpError;
12use oscyl_driver::sysex::DEVICE_INQUIRY;
13use oscyl_driver::{Driver, DriverError, DriverSession, SessionEvent, SessionOp};
14use oscyl_korg_minilogue_xd::session as xd;
15
16use crate::logue::{UnitEvent, UnitOp, UnitSession, unit_session};
17#[cfg(feature = "midir")]
18use crate::{CLIENT, MidirLink, midi_err};
19use crate::{Error, Link, SimLink};
20
21/// Upper bound on waiting for the identity reply (normally a few ms). Only
22/// reached when the port is not a responsive synth of the driver.
23const INQUIRY_BOUND: Duration = Duration::from_secs(2);
24
25/// Every driver this transport can find synths for.
26pub static DRIVERS: &[&dyn Driver] = &[
27    &oscyl_korg_minilogue_xd::DRIVER,
28    &oscyl_sequential_prophet_rev2::DRIVER,
29    &oscyl_korg_prologue::DRIVER,
30];
31
32/// The registered driver with this [`oscyl_driver::Info::id`].
33pub fn driver(id: &str) -> Option<&'static dyn Driver> {
34    DRIVERS.iter().copied().find(|d| d.info().id == id)
35}
36
37/// A port whose name matches a driver's hint; not yet confirmed by the
38/// device inquiry ([`crate::Device::open`] does that).
39#[derive(Clone)]
40pub struct Candidate {
41    pub driver: &'static dyn Driver,
42    /// The full port name. On ALSA it ends in `client:port`, so two synths
43    /// of the same model differ.
44    pub port: String,
45}
46
47impl PartialEq for Candidate {
48    fn eq(&self, other: &Candidate) -> bool {
49        self.driver.info().id == other.driver.info().id && self.port == other.port
50    }
51}
52
53impl Eq for Candidate {}
54
55impl fmt::Debug for Candidate {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{} on {:?}", self.driver.info().id, self.port)
58    }
59}
60
61/// Every (port, driver) pair where the port's name contains one of the
62/// driver's hints, in port order.
63pub fn candidates(ports: &[String]) -> Vec<Candidate> {
64    ports
65        .iter()
66        .flat_map(|port| {
67            DRIVERS
68                .iter()
69                .filter(|d| d.port_hint().iter().any(|h| port.contains(h)))
70                .map(|&driver| Candidate {
71                    driver,
72                    port: port.clone(),
73                })
74        })
75        .collect()
76}
77
78#[cfg(feature = "midir")]
79/// Candidates among the connected ports that are both an input and an
80/// output.
81pub fn scan() -> Result<Vec<Candidate>, Error> {
82    let input = MidiInput::new(CLIENT).map_err(midi_err)?;
83    let output = MidiOutput::new(CLIENT).map_err(midi_err)?;
84    let ins: Vec<String> = input
85        .ports()
86        .iter()
87        .filter_map(|p| input.port_name(p).ok())
88        .map(|n| crate::port_label(&n))
89        .collect();
90    let duplex: Vec<String> = output
91        .ports()
92        .iter()
93        .filter_map(|p| output.port_name(p).ok())
94        .map(|n| crate::port_label(&n))
95        .filter(|n| ins.contains(n))
96        .collect();
97    Ok(candidates(&duplex))
98}
99
100/// An open connection to one synth, through its driver's session.
101///
102/// A worker thread serving several devices loops: [`Device::submit`] new
103/// commands, [`Device::pump`] every device, then [`wait`] on one bell that
104/// every device ([`Device::ring_on_input`]) and the command sender ring,
105/// until the earliest time a pump returned. [`run_all`] is that loop for a
106/// fixed set of ops.
107pub struct Device {
108    driver: &'static dyn Driver,
109    port_name: String,
110    channel: u8,
111    session: Box<dyn DriverSession>,
112    link: Box<dyn Link>,
113    /// Ops submitted that have not yet reported `Done` or `Failed`.
114    outstanding: usize,
115    /// The synth's answer to the device inquiry.
116    identity: Vec<u8>,
117    /// What input rings now, so a blocking run can put it back.
118    bell: Option<Sender<()>>,
119    /// The driver session has run an op, so a logue session's reply-lag
120    /// check is done before unit ops (see [`Device::submit_units`]).
121    checked: bool,
122    /// The check's own op, as how many user ops finish before it.
123    internal_at: Option<usize>,
124    /// Logue unit ops; they run while the driver session is idle.
125    units: Option<Box<dyn UnitSession>>,
126    unit_outstanding: usize,
127    unit_events: VecDeque<UnitEvent>,
128    /// What the synth's panel picks.
129    panel: Panel,
130    /// Session ops submitted while unit ops run: they go next.
131    held: VecDeque<SessionOp>,
132}
133
134impl Device {
135    #[cfg(feature = "midir")]
136    /// Open a candidate's port and confirm the synth by the device inquiry.
137    pub fn open(c: &Candidate) -> Result<Device, Error> {
138        let link = MidirLink::open_exact(&c.port)?;
139        Device::connect(c.driver, Box::new(link), c.port.clone())
140    }
141
142    /// The driver's simulator as a device, for tests and demo mode.
143    pub fn simulated(driver: &'static dyn Driver) -> Result<Device, Error> {
144        let link = SimLink::from_sim(driver.simulator());
145        let name = format!("simulated {}", driver.info().model);
146        Device::connect(driver, Box::new(link), name)
147    }
148
149    /// The driver's demo simulator ([`Driver::demo_simulator`]) as a
150    /// device, for demo mode.
151    pub fn demo(driver: &'static dyn Driver) -> Result<Device, Error> {
152        let link = SimLink::from_sim(driver.demo_simulator());
153        let name = format!("simulated {}", driver.info().model);
154        Device::connect(driver, Box::new(link), name)
155    }
156
157    /// Send the device inquiry on `link` and wait for an answer `driver`
158    /// recognises. Our own inquiry coming back means a looping port.
159    pub fn connect(
160        driver: &'static dyn Driver,
161        link: Box<dyn Link>,
162        port_name: String,
163    ) -> Result<Device, Error> {
164        let mut o = Opening::start(driver, link, port_name)?;
165        loop {
166            let deadline = o.deadline;
167            match o.link_mut().recv_until(deadline)? {
168                Some(msg) => {
169                    if let Some(done) = o.answer(msg) {
170                        return done;
171                    }
172                }
173                None => return Err(Error::Silent(o.port_name)),
174            }
175        }
176    }
177
178    /// The device `driver` recognised in identity reply `msg`.
179    fn identified(
180        driver: &'static dyn Driver,
181        link: Box<dyn Link>,
182        port_name: String,
183        msg: Vec<u8>,
184    ) -> Device {
185        let channel = msg.get(2).copied().filter(|c| *c < 16).unwrap_or(0);
186        Device {
187            driver,
188            port_name,
189            channel,
190            session: driver.session(channel),
191            link,
192            outstanding: 0,
193            identity: msg,
194            bell: None,
195            checked: false,
196            internal_at: None,
197            units: None,
198            unit_outstanding: 0,
199            unit_events: VecDeque::new(),
200            held: VecDeque::new(),
201            panel: Panel::default(),
202        }
203    }
204
205    pub fn driver(&self) -> &'static dyn Driver {
206        self.driver
207    }
208
209    pub fn port_name(&self) -> &str {
210        &self.port_name
211    }
212
213    /// The MIDI channel from the identity reply. 0 also when the synth
214    /// listens on all channels (it answered on `7F`); either way requests
215    /// sent on it reach the synth.
216    pub fn channel(&self) -> u8 {
217        self.channel
218    }
219
220    /// The firmware version the synth named, for people.
221    pub fn firmware(&self) -> Option<String> {
222        self.driver.firmware(&self.identity)
223    }
224
225    /// Send one complete MIDI message outside the session (a live
226    /// parameter change from [`Driver::live_messages`]).
227    pub fn send(&mut self, msg: &[u8]) -> Result<(), Error> {
228        self.link.send(msg)
229    }
230
231    /// The next complete SysEx message from the synth outside the session,
232    /// or `None` once `deadline` passes (protocol probes). Only while idle.
233    pub fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
234        loop {
235            match self.link.recv_until(deadline)? {
236                Some(msg) => {
237                    if let Some(msg) = self.input(msg) {
238                        return Ok(Some(msg));
239                    }
240                }
241                None => return Ok(None),
242            }
243        }
244    }
245
246    #[cfg(feature = "midir")]
247    /// The minilogue xd on `port` (the first one found when `None`), for
248    /// probes and hardware tests.
249    pub fn open_xd(port: Option<&str>) -> Result<Device, Error> {
250        let xd = oscyl_korg_minilogue_xd::DRIVER.info().id;
251        let c = crate::scan()?
252            .into_iter()
253            .find(|c| c.driver.info().id == xd && port.is_none_or(|p| c.port.contains(p)))
254            .ok_or(Error::NotFound)?;
255        Device::open(&c)
256    }
257
258    /// Close the port now, ending its link; the device answers nothing
259    /// until replaced. A minilogue xd asked for a program while it boots
260    /// stops answering SysEx until its port has been closed.
261    pub fn close(&mut self) {
262        self.link = Box::new(Closed);
263    }
264
265    /// The next program slot the synth's panel picked (see
266    /// [`Driver::program_slot`]).
267    pub fn poll_selected(&mut self) -> Option<u16> {
268        self.panel.selected.pop_front()
269    }
270
271    /// The next Control Change the synth's panel sent (a knob turned),
272    /// for a [`oscyl_driver::PanelListener`].
273    pub fn poll_control(&mut self) -> Option<(u8, u8)> {
274        self.panel.controls.pop_front()
275    }
276
277    /// `msg` from the synth: a SysEx message, returned for a session, or
278    /// a channel message for [`Panel::input`].
279    fn input(&mut self, msg: Vec<u8>) -> Option<Vec<u8>> {
280        self.panel.input(self.driver, self.channel, msg)
281    }
282
283    /// Ring `bell` whenever this device's synth sends something.
284    pub fn ring_on_input(&mut self, bell: Sender<()>) {
285        self.link.ring_on_input(bell.clone());
286        self.bell = Some(bell);
287    }
288
289    /// Queue an op; it runs on the following pumps (after the unit ops
290    /// queued before it).
291    pub fn submit(&mut self, op: SessionOp) -> Result<(), Error> {
292        if self.units_busy() {
293            self.held.push_back(op);
294        } else {
295            self.session.submit(op)?;
296        }
297        self.outstanding += 1;
298        Ok(())
299    }
300
301    fn units_busy(&self) -> bool {
302        self.units.as_ref().is_some_and(|u| !u.is_idle())
303    }
304
305    /// Queue a logue unit op (logue synths only). It runs once the ops
306    /// queued before it are done; its events come from
307    /// [`Device::poll_unit_event`]. The first time, the driver session
308    /// reads the edit buffer first, so a logue session's reply-lag check
309    /// has cleared the firmware fault before unit reads.
310    pub fn submit_units(&mut self, op: UnitOp) -> Result<(), Error> {
311        if self.units.is_none() {
312            self.units = Some(unit_session(self.driver, self.channel).ok_or_else(|| {
313                Error::Driver(DriverError(format!(
314                    "the {} has no user units",
315                    self.driver.info().model
316                )))
317            })?);
318        }
319        if !self.checked && self.internal_at.is_none() && !self.units_busy() {
320            self.session.submit(SessionOp::ReadCurrent)?;
321            self.internal_at = Some(self.outstanding - self.held.len());
322        }
323        self.units.as_mut().expect("made above").submit(op);
324        self.unit_outstanding += 1;
325        Ok(())
326    }
327
328    /// The next event of the unit ops.
329    pub fn poll_unit_event(&mut self) -> Option<UnitEvent> {
330        self.unit_events.pop_front()
331    }
332
333    /// Nothing queued or in flight.
334    pub fn is_idle(&self) -> bool {
335        self.session.is_idle() && !self.units_busy() && self.held.is_empty()
336    }
337
338    /// End every queued and in-flight op at once, each reported as
339    /// [`OpError::Cancelled`] (e.g. hotplug says the synth is gone). The
340    /// device starts afresh; the caller may drop it.
341    pub fn cancel(&mut self, on_event: &mut dyn FnMut(&SessionEvent)) {
342        self.session = self.driver.session(self.channel);
343        self.held.clear();
344        self.internal_at = None;
345        for _ in 0..std::mem::take(&mut self.outstanding) {
346            on_event(&SessionEvent::Failed(OpError::Cancelled));
347        }
348        self.units = None;
349        for _ in 0..std::mem::take(&mut self.unit_outstanding) {
350            self.unit_events
351                .push_back(UnitEvent::Failed(OpError::Cancelled));
352        }
353    }
354
355    /// One non-blocking round: send what the session allows, handle input
356    /// that has arrived and expired deadlines, report events. Returns when
357    /// to pump again at the latest (input rings sooner), or `None` when
358    /// idle.
359    pub fn pump(
360        &mut self,
361        on_event: &mut dyn FnMut(&SessionEvent),
362    ) -> Result<Option<Instant>, Error> {
363        let now = Instant::now();
364        // Unit ops run while the driver session has nothing to do.
365        if self.units_busy() && self.session.is_idle() && self.checked {
366            return self.pump_units(now);
367        }
368        while let Some(msg) = self.session.poll_transmit(now) {
369            self.link.send(&msg)?;
370        }
371        while let Some(msg) = self.link.recv_until(now)? {
372            if let Some(msg) = self.input(msg) {
373                self.session.handle_input(&msg);
374            }
375        }
376        self.session.handle_timeout(now);
377        self.events(on_event);
378        if self.session.is_idle() {
379            // Unit ops waiting go on the next round.
380            return Ok(self.units_busy().then_some(now));
381        }
382        match self.session.next_deadline() {
383            // Everything the synth will say to what was sent is in: the
384            // deadline passes now.
385            Some(deadline) if self.link.synchronous() => {
386                self.session.handle_timeout(deadline);
387                self.events(on_event);
388                Ok(Some(now))
389            }
390            Some(deadline) => Ok(Some(deadline)),
391            // A step completed; the next one goes out on the next round.
392            None => Ok(Some(now)),
393        }
394    }
395
396    fn pump_units(&mut self, now: Instant) -> Result<Option<Instant>, Error> {
397        let units = self.units.as_mut().expect("busy");
398        while let Some(msg) = units.poll_transmit(now) {
399            self.link.send(&msg)?;
400        }
401        while let Some(msg) = self.link.recv_until(now)? {
402            if let Some(msg) = self.panel.input(self.driver, self.channel, msg) {
403                units.handle_input(&msg);
404            }
405        }
406        units.handle_timeout(now);
407        if let Some(deadline) = units.next_deadline()
408            && self.link.synchronous()
409        {
410            // Everything the synth will say is in: the deadline passes now.
411            units.handle_timeout(deadline);
412        }
413        let deadline = units.next_deadline();
414        while let Some(e) = units.poll_event() {
415            if matches!(e, UnitEvent::Done | UnitEvent::Failed(_)) {
416                self.unit_outstanding = self.unit_outstanding.saturating_sub(1);
417            }
418            self.unit_events.push_back(e);
419        }
420        if !self.units_busy() {
421            // The session ops held back go now.
422            for op in std::mem::take(&mut self.held) {
423                self.session.submit(op)?;
424            }
425            return Ok(Some(now));
426        }
427        Ok(Some(match deadline {
428            Some(d) if !self.link.synchronous() => d,
429            _ => now,
430        }))
431    }
432
433    /// Run a logue unit op to completion, blocking (the CLI); see
434    /// [`Device::submit_units`]. A failed op is an [`Error::Op`].
435    pub fn run_units(
436        &mut self,
437        op: UnitOp,
438        mut on_event: impl FnMut(&UnitEvent),
439    ) -> Result<(), Error> {
440        self.submit_units(op)?;
441        let (bell, rung) = channel();
442        let before = self.bell.clone();
443        self.ring_on_input(bell);
444        let result = loop {
445            let next = match self.pump(&mut |_| {}) {
446                Ok(n) => n,
447                Err(e) => break Err(e),
448            };
449            let mut end = None;
450            while let Some(e) = self.poll_unit_event() {
451                on_event(&e);
452                match e {
453                    UnitEvent::Done if self.unit_outstanding == 0 => end = Some(Ok(())),
454                    UnitEvent::Failed(err) => end = Some(Err(Error::Op(err))),
455                    _ => {}
456                }
457            }
458            if let Some(r) = end {
459                break r;
460            }
461            wait(&rung, next);
462        };
463        if let Some(b) = before {
464            self.ring_on_input(b);
465        }
466        result
467    }
468
469    /// Probes and xd session tests: run any minilogue xd op (programs
470    /// too, outside the driver session) to completion on this device's
471    /// link, blocking. Apps use [`Device::submit_units`] instead. Only while idle, so no reply of a
472    /// session op can be taken for one of this op. The first time, a
473    /// [`SessionOp::ReadCurrent`] runs first, so the xd session's
474    /// reply-lag check has cleared the firmware fault before these reads.
475    pub fn run_xd(
476        &mut self,
477        op: xd::Op,
478        mut on_event: impl FnMut(&xd::Event),
479    ) -> Result<(), Error> {
480        if self.driver.info().id != oscyl_korg_minilogue_xd::DRIVER.info().id {
481            return Err(Error::Driver(DriverError(format!(
482                "the {} has no user units",
483                self.driver.info().model
484            ))));
485        }
486        if !self.is_idle() {
487            return Err(Error::Driver(DriverError(
488                "the synth is busy with another operation".into(),
489            )));
490        }
491        if !self.checked {
492            self.run(SessionOp::ReadCurrent, |_| {})?;
493            self.checked = true;
494        }
495        let mut session = xd::Session::new(xd::Xd {
496            channel: self.channel,
497        });
498        session.submit(op);
499        loop {
500            while let Some(msg) = session.poll_transmit(Instant::now()) {
501                self.link.send(&msg)?;
502            }
503            if let Some(deadline) = session.next_deadline() {
504                match self.link.recv_until(deadline)? {
505                    Some(msg) => {
506                        if let Some(msg) = self.input(msg) {
507                            session.handle_input(&msg);
508                        }
509                        session.handle_timeout(Instant::now());
510                    }
511                    // Nothing arrives by the deadline.
512                    None => session.handle_timeout(deadline),
513                }
514            }
515            while let Some(ev) = session.poll_event() {
516                on_event(&ev);
517                match ev {
518                    xd::Event::OpDone => return Ok(()),
519                    xd::Event::OpFailed(e) => return Err(e.into()),
520                    _ => {}
521                }
522            }
523        }
524    }
525
526    fn events(&mut self, on_event: &mut dyn FnMut(&SessionEvent)) {
527        while let Some(e) = self.session.poll_event() {
528            let ends = matches!(e, SessionEvent::Done | SessionEvent::Failed(_));
529            // The check's own op reports nothing.
530            if self.internal_at == Some(0) {
531                if ends {
532                    self.internal_at = None;
533                    self.checked = true;
534                }
535                continue;
536            }
537            if ends {
538                // The session has run an op: its lag check is done.
539                self.checked = true;
540                self.outstanding = self.outstanding.saturating_sub(1);
541                if let Some(k) = self.internal_at.as_mut() {
542                    *k -= 1;
543                }
544            }
545            on_event(&e);
546        }
547    }
548
549    /// Run `op` (and anything queued before it) to completion. A failed op
550    /// is an [`Error::Op`].
551    pub fn run(
552        &mut self,
553        op: SessionOp,
554        mut on_event: impl FnMut(&SessionEvent),
555    ) -> Result<(), Error> {
556        self.submit(op)?;
557        let mut failed = None;
558        let mut results = run_all(&mut [self], |_, e| {
559            if let SessionEvent::Failed(err) = e {
560                failed.get_or_insert(err.clone());
561            }
562            on_event(e);
563        });
564        results.pop().expect("one device")?;
565        failed.map_or(Ok(()), |e| Err(Error::Op(e)))
566    }
567}
568
569/// The link of a closed [`Device`].
570struct Closed;
571
572impl Link for Closed {
573    fn send(&mut self, _: &[u8]) -> Result<(), Error> {
574        Err(Error::Disconnected("closed".into()))
575    }
576
577    fn recv_until(&mut self, _: Instant) -> Result<Option<Vec<u8>>, Error> {
578        Err(Error::Disconnected("closed".into()))
579    }
580}
581
582/// The program the synth's panel picks, from what it sends.
583#[derive(Default)]
584struct Panel {
585    /// The Bank Select (MSB, LSB) the synth sent last.
586    bank: (u8, u8),
587    /// Program slots it picked, oldest first.
588    selected: VecDeque<u16>,
589    /// Its other Control Changes (knobs turned), oldest first.
590    controls: VecDeque<(u8, u8)>,
591}
592
593impl Panel {
594    /// A SysEx message is returned, for a session. A Bank Select or
595    /// Program Change on the synth's `channel` is noted, and its other
596    /// Control Changes kept; anything else (notes) is dropped.
597    fn input(&mut self, driver: &dyn Driver, channel: u8, msg: Vec<u8>) -> Option<Vec<u8>> {
598        if msg.first() == Some(&0xF0) {
599            return Some(msg);
600        }
601        if msg.first().is_none_or(|s| s & 0x0F != channel) {
602            return None;
603        }
604        match (msg[0] & 0xF0, msg.get(1), msg.get(2)) {
605            (0xB0, Some(0), Some(&v)) => self.bank.0 = v,
606            (0xB0, Some(32), Some(&v)) => self.bank.1 = v,
607            (0xB0, Some(&cc), Some(&v)) => {
608                // Unread (a tool that never asks), the oldest go.
609                if self.controls.len() >= 1024 {
610                    self.controls.pop_front();
611                }
612                self.controls.push_back((cc, v));
613            }
614            (0xC0, Some(&p), _) => {
615                let (msb, lsb) = self.bank;
616                self.selected.extend(driver.program_slot(msb, lsb, p));
617            }
618            _ => {}
619        }
620        None
621    }
622}
623
624/// A synth being opened: the device inquiry is out, the answer awaited
625/// without blocking ([`Opening::poll`] from a pumping loop).
626pub struct Opening {
627    driver: &'static dyn Driver,
628    /// Taken by the device once recognised.
629    link: Option<Box<dyn Link>>,
630    port_name: String,
631    deadline: Instant,
632}
633
634/// Where an [`Opening`] stands.
635pub enum Opened {
636    Ready(Box<Device>),
637    Waiting(Opening),
638    Failed(Error),
639}
640
641impl Opening {
642    #[cfg(feature = "midir")]
643    /// Open a candidate's port and send the inquiry.
644    pub fn open(c: &Candidate) -> Result<Opening, Error> {
645        let link = MidirLink::open_exact(&c.port)?;
646        Opening::start(c.driver, Box::new(link), c.port.clone())
647    }
648
649    /// Send the inquiry on `link`.
650    pub fn start(
651        driver: &'static dyn Driver,
652        mut link: Box<dyn Link>,
653        port_name: String,
654    ) -> Result<Opening, Error> {
655        link.send(&DEVICE_INQUIRY)?;
656        Ok(Opening {
657            driver,
658            link: Some(link),
659            port_name,
660            deadline: Instant::now() + INQUIRY_BOUND,
661        })
662    }
663
664    pub fn driver(&self) -> &'static dyn Driver {
665        self.driver
666    }
667
668    pub fn port_name(&self) -> &str {
669        &self.port_name
670    }
671
672    /// Ring `bell` when the synth answers.
673    pub fn ring_on_input(&mut self, bell: Sender<()>) {
674        self.link_mut().ring_on_input(bell);
675    }
676
677    /// The device, an error, or `None` for a message that says nothing
678    /// (a note or knob from the panel included).
679    fn answer(&mut self, msg: Vec<u8>) -> Option<Result<Device, Error>> {
680        if msg.first() != Some(&0xF0) {
681            return None;
682        }
683        if msg == DEVICE_INQUIRY {
684            return Some(Err(Error::Loopback(self.port_name.clone())));
685        }
686        self.driver.recognize(&msg).then(|| {
687            let link = self.link.take().expect("answered once");
688            Ok(Device::identified(
689                self.driver,
690                link,
691                std::mem::take(&mut self.port_name),
692                msg,
693            ))
694        })
695    }
696
697    /// Read what has arrived: the device once recognised, a failure, or
698    /// still waiting (come back by [`Opening::deadline`] at the latest).
699    pub fn poll(mut self, now: Instant) -> Opened {
700        loop {
701            match self.link_mut().recv_until(now) {
702                Ok(Some(msg)) => match self.answer(msg) {
703                    Some(Ok(d)) => return Opened::Ready(Box::new(d)),
704                    Some(Err(e)) => return Opened::Failed(e),
705                    None => {}
706                },
707                Ok(None) if now >= self.deadline || self.link_mut().synchronous() => {
708                    return Opened::Failed(Error::Silent(self.port_name));
709                }
710                Ok(None) => return Opened::Waiting(self),
711                Err(e) => return Opened::Failed(e),
712            }
713        }
714    }
715
716    fn link_mut(&mut self) -> &mut Box<dyn Link> {
717        self.link.as_mut().expect("open until answered")
718    }
719
720    /// When the inquiry is given up.
721    pub fn deadline(&self) -> Instant {
722        self.deadline
723    }
724}
725
726/// Block until `bell` rings or `until` passes (`None`: until it rings).
727/// Rings that piled up meanwhile are drained: their input is already
728/// queued for the next pump. Keep a sender of `bell` alive, or a `None`
729/// wait returns at once.
730pub fn wait(bell: &Receiver<()>, until: Option<Instant>) {
731    let _ = match until {
732        Some(t) => bell
733            .recv_timeout(t.saturating_duration_since(Instant::now()))
734            .ok(),
735        None => bell.recv().ok(),
736    };
737    while bell.try_recv().is_ok() {}
738}
739
740/// Run every device's queued ops at once in this thread, interleaved, until
741/// all are idle. `on_event` gets each event with its device's index. The
742/// results hold transport errors per device (such a device stops; cancel
743/// it); op failures are [`SessionEvent::Failed`] events.
744pub fn run_all(
745    devices: &mut [&mut Device],
746    mut on_event: impl FnMut(usize, &SessionEvent),
747) -> Vec<Result<(), Error>> {
748    let (bell, rung) = channel();
749    // A device's own bell (a worker's) rings again once this returns.
750    let before: Vec<Option<Sender<()>>> = devices.iter().map(|d| d.bell.clone()).collect();
751    for d in devices.iter_mut() {
752        d.ring_on_input(bell.clone());
753    }
754    let mut results: Vec<Result<(), Error>> = devices.iter().map(|_| Ok(())).collect();
755    loop {
756        let mut next: Option<Instant> = None;
757        for (i, d) in devices.iter_mut().enumerate() {
758            if results[i].is_err() {
759                continue;
760            }
761            match d.pump(&mut |e| on_event(i, e)) {
762                Ok(Some(t)) => next = Some(next.map_or(t, |n| n.min(t))),
763                Ok(None) => {}
764                Err(e) => results[i] = Err(e),
765            }
766        }
767        if next.is_none() {
768            for (d, b) in devices.iter_mut().zip(before) {
769                if let Some(b) = b {
770                    d.ring_on_input(b);
771                }
772            }
773            return results;
774        }
775        wait(&rung, next);
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use crate::{InputSender, PushLink};
783    use std::sync::{Arc, Mutex};
784
785    /// A minilogue xd behind a platform link: its simulator answers, and
786    /// the test pushes what its panel sends.
787    fn xd() -> (Device, InputSender) {
788        let d = driver("korg-minilogue-xd").unwrap();
789        let back: Arc<Mutex<Option<InputSender>>> = Arc::default();
790        let to = back.clone();
791        let mut sim = d.simulator();
792        let mut framer = oscyl_driver::sysex::Framer::new();
793        let (link, input) = PushLink::new(Box::new(move |bytes| {
794            for m in framer.push(bytes) {
795                for reply in sim.handle(&m) {
796                    if let Some(i) = to.lock().unwrap().as_ref() {
797                        i.push(&reply);
798                    }
799                }
800            }
801            Ok(())
802        }));
803        *back.lock().unwrap() = Some(input.clone());
804        (
805            Device::connect(d, Box::new(link), "usb xd".into()).unwrap(),
806            input,
807        )
808    }
809
810    /// The panel picking a program (bank select, then program change, on
811    /// the synth's channel) is reported as its slot; the bank holds for
812    /// later changes; other channels are not the synth's.
813    #[test]
814    fn the_synth_picking_a_program_is_reported_as_its_slot() {
815        let (mut d, input) = xd();
816        input.push(&[0xB0, 0x00, 0x00, 0xB0, 0x20, 0x02, 0xC0, 0x05]);
817        input.push(&[0xC1, 0x07, 0x90, 0x40, 0x7F]);
818        input.push(&[0xC0, 0x09]);
819        d.pump(&mut |_| {}).unwrap();
820        assert_eq!(d.poll_selected(), Some(205));
821        assert_eq!(d.poll_selected(), Some(209));
822        assert_eq!(d.poll_selected(), None);
823    }
824
825    /// The panel's knobs come through as their Control Changes, in order;
826    /// bank selects, notes and other channels do not.
827    #[test]
828    fn the_panels_knobs_come_through() {
829        let (mut d, input) = xd();
830        input.push(&[0xB0, 0x3F, 0x05, 0xB0, 0x2B, 0x55, 0xB0, 0x00, 0x00]);
831        input.push(&[0x90, 0x40, 0x7F, 0xB1, 0x2B, 0x01]);
832        d.pump(&mut |_| {}).unwrap();
833        assert_eq!(d.poll_control(), Some((0x3F, 0x05)));
834        assert_eq!(d.poll_control(), Some((0x2B, 0x55)));
835        assert_eq!(d.poll_control(), None);
836    }
837
838    /// A program picked on the panel while a read runs neither breaks the
839    /// read nor is lost.
840    #[test]
841    fn a_program_picked_during_a_read_leaves_the_read_whole() {
842        let (mut d, input) = xd();
843        input.push(&[0xB0, 0x20, 0x01, 0xC0, 0x00]);
844        let mut got = None;
845        d.run(SessionOp::ReadCurrent, |e| {
846            if let SessionEvent::Current(p) = e {
847                got = Some(p.len());
848            }
849        })
850        .unwrap();
851        assert!(got.is_some());
852        assert_eq!(d.poll_selected(), Some(100));
853    }
854}