medius 3.4.1

Host control library for the medius transparent mouse passthrough box
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
use std::time::Duration;

use crate::error::{Error, Result};
use crate::link::Link;
use crate::protocol::opcode::{
    OPT_BEARING, OPT_EMIT, OPT_IMPERFECT, OPT_MOVE_RIDE, OPT_RENDER, OPT_SPREAD, Q_CAPS, Q_CATCH,
    Q_CLIP, Q_DEVICE_INFO, Q_FIRMWARE, Q_HEALTH, Q_LOCKS, Q_PATCH_ENTRY, Q_PATCHES, Q_RATE,
    Q_REWRITE, Q_REWRITE_ENTRY, Q_STATS, Q_TRANSFORMS, Q_VERSION,
};
use crate::protocol::{Resp, parse_resp};
use crate::types::{
    Action, Axis, Bearing, BearingMode, Blanket, Caps, CatchFilter, CatchState, ClipBuilder,
    ClipPacketTrigger, ClipSettings, ClipStatus, ClipTrigger, CountersSnapshot, DeviceInfo,
    Direction, Edge, EmitPace, EmitPaceStatus, FirmwareInfo, Health, ImperfectStatus, LedMode,
    LedTarget, LockTarget, Locks, Motion, MoveTiming, Patch, PatchSet, PendingMotion, Rate,
    RebootTarget, RenderMode, RenderStatus, RewriteRule, RewriteTable, Setup, SpreadStatus, Stats,
    TransferOutcome, TransferStatus, Transform, Transforms, UpdateProgress, UpdateTarget, Usage,
    Version,
};

use super::Device;
use super::catch::EventStream;
use super::clip::ClipHandle;
use super::discover::BoxInfo;
use super::input::InputStream;
use super::logs::LogStream;
use super::raw::DEFAULT_TRANSFER_TIMEOUT;

/// An async view over a [`Device`]: the same `Link` core, with `async` queries.
#[derive(Clone, Debug)]
pub struct AsyncDevice {
    link: Link,
}

impl From<Device> for AsyncDevice {
    fn from(device: Device) -> Self {
        AsyncDevice { link: device.link }
    }
}

impl Device {
    /// Convert this device into an [`AsyncDevice`] over the same core.
    pub fn into_async(self) -> AsyncDevice {
        AsyncDevice::from(self)
    }
}

impl AsyncDevice {
    fn dev(&self) -> Device {
        Device {
            link: self.link.clone(),
        }
    }

    /// Consume back into the sync [`Device`].
    pub fn into_inner(self) -> Device {
        Device { link: self.link }
    }

    /// `MOVE`: relative cursor movement. Instant; see [`Device::move_rel`].
    pub fn move_rel(&self, dx: i16, dy: i16) -> Result<()> {
        self.dev().move_rel(dx, dy)
    }

    /// `WHEEL`: vertical scroll. Instant; see [`Device::wheel`].
    pub fn wheel(&self, delta: i16) -> Result<()> {
        self.dev().wheel(delta)
    }

    /// `MOVE` (cursor) bypassing movement riding. Instant; see [`Device::move_rel_now`].
    pub fn move_rel_now(&self, dx: i16, dy: i16) -> Result<()> {
        self.dev().move_rel_now(dx, dy)
    }

    /// `MOVE` (wheel) bypassing movement riding. Instant; see [`Device::wheel_now`].
    pub fn wheel_now(&self, delta: i16) -> Result<()> {
        self.dev().wheel_now(delta)
    }

    /// `MOVE` (AC Pan): horizontal scroll. Instant; see [`Device::pan`].
    pub fn pan(&self, delta: i16) -> Result<()> {
        self.dev().pan(delta)
    }

    /// `MOVE` (AC Pan) bypassing movement riding. Instant; see [`Device::pan_now`].
    pub fn pan_now(&self, delta: i16) -> Result<()> {
        self.dev().pan_now(delta)
    }

    /// Emit the motion held for a ride now. Instant; see [`Device::flush_motion`].
    pub fn flush_motion(&self) -> Result<()> {
        self.dev().flush_motion()
    }

    /// Drop the motion held for a ride. Instant; see [`Device::discard_motion`].
    pub fn discard_motion(&self) -> Result<()> {
        self.dev().discard_motion()
    }

    /// `MOVE`: field-generic relative axis (cursor, wheel, or AC Pan). Instant; see [`Device::move_axis`].
    pub fn move_axis(
        &self,
        motion: Motion,
        timing: MoveTiming,
        pending: PendingMotion,
    ) -> Result<()> {
        self.dev().move_axis(motion, timing, pending)
    }

    /// `INJECT`: momentary override for any usage (button, key, or media). Instant; see [`Device::inject`].
    pub fn inject(&self, usage: impl Into<Usage>, action: Action) -> Result<()> {
        self.dev().inject(usage, action)
    }

    /// Press (force down) any usage. Instant; see [`Device::press`].
    pub fn press(&self, usage: impl Into<Usage>) -> Result<()> {
        self.dev().press(usage)
    }

    /// Soft-release any usage. Instant; see [`Device::release`].
    pub fn release(&self, usage: impl Into<Usage>) -> Result<()> {
        self.dev().release(usage)
    }

    /// Force-release any usage. Instant; see [`Device::force_release`].
    pub fn force_release(&self, usage: impl Into<Usage>) -> Result<()> {
        self.dev().force_release(usage)
    }

    /// `RESET`: return to passthrough. Instant; see [`Device::reset`].
    pub fn reset(&self) -> Result<()> {
        self.dev().reset()
    }

    /// Reboot a chip (run or ROM download per the target). Instant; see [`Device::reboot`].
    pub fn reboot(&self, target: RebootTarget) -> Result<()> {
        self.dev().reboot(target)
    }

    /// Re-assert every currently held override. Instant; see [`Device::reapply`].
    pub fn reapply(&self) -> Result<()> {
        self.dev().reapply()
    }

    /// Best-effort reconnect over the shared core; blocks the calling thread. See [`Device::reconnect`].
    pub fn reconnect(&self) -> Result<()> {
        self.dev().reconnect()
    }

    /// A snapshot of the always-on counters. See [`Device::counters`].
    pub fn counters(&self) -> CountersSnapshot {
        self.dev().counters()
    }

    /// A [`LogStream`] over the device `LOG` stream; it offers `recv_async`. See [`Device::logs`].
    pub fn logs(&self) -> LogStream {
        self.dev().logs()
    }

    /// `LED`: override a status LED. Instant; see [`Device::led`].
    pub fn led(&self, target: LedTarget, mode: LedMode, level: u8) -> Result<()> {
        self.dev().led(target, mode, level)
    }

    /// `LOCK`: weigh physical input on a target. Instant; see [`Device::scale`].
    pub fn scale(
        &self,
        target: impl Into<LockTarget>,
        direction: Direction,
        scale: i16,
    ) -> Result<()> {
        self.dev().scale(target, direction, scale)
    }

    /// `LOCK`: weigh a relative axis by sign. Instant; see [`Device::scale_axis`].
    pub fn scale_axis(&self, axis: Axis, direction: Direction, scale: i16) -> Result<()> {
        self.dev().scale_axis(axis, direction, scale)
    }

    /// `LOCK`: weigh a whole [`Blanket`] group. Instant; see [`Device::scale_all`].
    pub fn scale_all(&self, what: Blanket, direction: Direction, scale: i16) -> Result<()> {
        self.dev().scale_all(what, direction, scale)
    }

    /// `LOCK`: block a usage (button/key/media) or axis. Instant; see [`Device::lock`].
    pub fn lock(&self, target: impl Into<LockTarget>, direction: Direction) -> Result<()> {
        self.dev().lock(target, direction)
    }

    /// `LOCK`: release a locked usage or axis. Instant; see [`Device::unlock`].
    pub fn unlock(&self, target: impl Into<LockTarget>, direction: Direction) -> Result<()> {
        self.dev().unlock(target, direction)
    }

    /// `LOCK`: block a relative axis by sign. Instant; see [`Device::lock_axis`].
    pub fn lock_axis(&self, axis: Axis, direction: Direction) -> Result<()> {
        self.dev().lock_axis(axis, direction)
    }

    /// `LOCK`: release an axis lock. Instant; see [`Device::unlock_axis`].
    pub fn unlock_axis(&self, axis: Axis, direction: Direction) -> Result<()> {
        self.dev().unlock_axis(axis, direction)
    }

    /// `LOCK`: blanket-block a whole group. Instant; see [`Device::lock_all`].
    pub fn lock_all(&self, what: Blanket, direction: Direction) -> Result<()> {
        self.dev().lock_all(what, direction)
    }

    /// `LOCK`: release a blanket lock. Instant; see [`Device::unlock_all`].
    pub fn unlock_all(&self, what: Blanket, direction: Direction) -> Result<()> {
        self.dev().unlock_all(what, direction)
    }

    /// Subscribe to the catch stream. Instant; see [`Device::catch_events`].
    pub fn catch_events(
        &self,
        filters: impl IntoIterator<Item = CatchFilter>,
    ) -> Result<EventStream> {
        self.dev().catch_events(filters)
    }

    /// Subscribe to decoded input edges. Instant; see [`Device::input_events`].
    pub fn input_events(
        &self,
        filters: impl IntoIterator<Item = CatchFilter>,
    ) -> Result<InputStream> {
        self.dev().input_events(filters)
    }

    /// `OPTION(IMPERFECT)`: opt into cloning an over-capacity device. Instant; see [`Device::allow_imperfect_clones`].
    pub fn allow_imperfect_clones(&self, allow: bool) -> Result<()> {
        self.dev().allow_imperfect_clones(allow)
    }

    /// `OPTION(MOVE_RIDE)`: movement riding. Instant; see [`Device::set_movement_riding`].
    pub fn set_movement_riding(&self, window: Option<Duration>) -> Result<()> {
        self.dev().set_movement_riding(window)
    }

    /// `OPTION(EMIT)`: emit-rate pacing and the forced wire rate. Instant; see [`Device::set_emit_pace`].
    pub fn set_emit_pace(&self, pace: EmitPace, force_hz: Option<u16>) -> Result<()> {
        self.dev().set_emit_pace(pace, force_hz)
    }

    /// `OPTION(NAME)`: set the box's persistent name. Instant; see [`Device::set_name`].
    pub fn set_name(&self, name: &str) -> Result<()> {
        self.dev().set_name(name)
    }

    /// `OPTION(NAME)` clear: revert to the synthesised default. Instant; see [`Device::clear_name`].
    pub fn clear_name(&self) -> Result<()> {
        self.dev().clear_name()
    }

    /// `OPTION(BEARING)`: what `With`/`Against` are measured against. Instant; see [`Device::set_bearing`].
    pub fn set_bearing(&self, window: Option<Duration>, mode: BearingMode) -> Result<()> {
        self.dev().set_bearing(window, mode)
    }

    /// `OPTION(RENDER)`: what motion is rendered with, and whether native motion goes through it.
    /// Instant; see [`Device::set_render`].
    pub fn set_render(&self, mode: RenderMode, full: bool) -> Result<()> {
        self.dev().set_render(mode, full)
    }

    /// `OPTION(SPREAD)`: percent of the host's command interval an injected delta is released
    /// across. Instant; see [`Device::set_spread`].
    pub fn set_spread(&self, percent: u16) -> Result<()> {
        self.dev().set_spread(percent)
    }

    /// Query the box version, awaiting the correlated `RESP` with the default timeout.
    pub async fn query_version(&self) -> Result<Version> {
        let payload = self
            .link
            .query_async(Q_VERSION, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Version(v)) => Ok(v),
            _ => Err(Error::NoReply),
        }
    }

    /// Both chips' firmware versions and slot state (§4.16), awaiting the correlated `RESP`.
    pub async fn firmware_info(&self) -> Result<FirmwareInfo> {
        let payload = self
            .link
            .query_async(Q_FIRMWARE, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Firmware(f)) => Ok(f),
            _ => Err(Error::NoReply),
        }
    }

    /// Write one image into the target chip's spare slot; it stays inert until
    /// [`activate_firmware`](Self::activate_firmware).
    pub async fn stage_firmware(
        &self,
        target: UpdateTarget,
        image: Vec<u8>,
        mut progress: impl FnMut(UpdateProgress) + Send + 'static,
    ) -> Result<u32> {
        self.offload(move |d| d.stage_firmware(target, &image, &mut progress))
            .await
    }

    /// Drop whatever is staged or in flight for one target.
    pub async fn abort_update(&self, target: UpdateTarget) -> Result<()> {
        self.offload(move |d| d.abort_update(target)).await
    }

    /// Commit every staged image and reboot into it.
    pub async fn activate_firmware(&self) -> Result<()> {
        self.offload(|d| d.activate_firmware()).await
    }

    /// Stage one image and activate it.
    ///
    /// NOT cancellable. Dropping the returned future stops the waiting, not the transfer: the work
    /// runs to completion on a thread of its own and the box still reboots into the new image.
    pub async fn update_firmware(
        &self,
        target: UpdateTarget,
        image: Vec<u8>,
        mut progress: impl FnMut(UpdateProgress) + Send + 'static,
    ) -> Result<()> {
        self.offload(move |d| {
            d.stage_firmware(target, &image, &mut progress)?;
            d.activate_firmware()
        })
        .await
    }

    /// Block until neither chip is still on probation.
    pub async fn wait_firmware_confirmed(&self) -> Result<FirmwareInfo> {
        self.offload(|d| d.wait_firmware_confirmed()).await
    }

    // Run one blocking update call on a thread of its own and await the result.
    //
    // NOT cancellable. Dropping the returned future stops the waiting, not the transfer: the thread
    // runs to completion and `update_firmware` will still reboot the box. Wrap it in a timeout only
    // if that is acceptable.
    //
    // The transfer is a credit-windowed conversation with its own timeouts, and this crate carries
    // no runtime and no timer, so an `async` reimplementation would have nothing to bound its waits
    // with. Driving the sync path instead keeps one implementation of the wire, which is the whole
    // point: a duplicated loop is where sync and async quietly stop agreeing.
    async fn offload<T, F>(&self, f: F) -> Result<T>
    where
        T: Send + 'static,
        F: FnOnce(&Device) -> Result<T> + Send + 'static,
    {
        let device = Device {
            link: self.link.clone(),
        };
        let (tx, rx) = flume::bounded(1);
        std::thread::Builder::new()
            .name("medius-update".into())
            .spawn(move || {
                let _ = tx.send(f(&device));
            })
            .map_err(Error::Io)?;
        rx.recv_async().await.map_err(|_| Error::Disconnected)?
    }

    /// Query the box health flags, awaiting the correlated `RESP` with the default timeout.
    pub async fn query_health(&self) -> Result<Health> {
        let payload = self
            .link
            .query_async(Q_HEALTH, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Health(h)) => Ok(h),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the cloned device's USB identity, kind, and product (§4.3), awaiting the correlated `RESP`.
    pub async fn device_info(&self) -> Result<DeviceInfo> {
        let payload = self
            .link
            .query_async(Q_DEVICE_INFO, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::DeviceInfo(m)) => Ok(m),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the whole cloned device's capabilities in one request (§4.4), awaiting the correlated `RESP`.
    pub async fn caps(&self) -> Result<Caps> {
        let payload = self
            .link
            .query_async(Q_CAPS, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Caps(c)) => {
                // Cache the declared button count, exactly as the sync path does, so a later button
                // blanket expands onto every declared button.
                self.link
                    .desired()
                    .lock()
                    .note_declared_buttons(c.mouse.n_buttons);
                Ok(c)
            }
            _ => Err(Error::NoReply),
        }
    }

    /// Query the live native report rate (§4.5), awaiting the correlated `RESP`.
    pub async fn query_rate(&self) -> Result<Rate> {
        let payload = self
            .link
            .query_async(Q_RATE, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Rate(r)) => Ok(r),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the box's delivery/telemetry counters (§4.6), awaiting the correlated `RESP`.
    pub async fn query_stats(&self) -> Result<Stats> {
        let payload = self
            .link
            .query_async(Q_STATS, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Stats(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the active lock bitmask (§4.8), awaiting the correlated `RESP`.
    pub async fn query_locks(&self) -> Result<Locks> {
        let payload = self
            .link
            .query_async(Q_LOCKS, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Locks(l)) => Ok(l),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the catch subscription mask + box-side dropped count (§4.9), awaiting the correlated `RESP`.
    pub async fn query_catch(&self) -> Result<CatchState> {
        let payload = self
            .link
            .query_async(Q_CATCH, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Catch(c)) => Ok(c),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the imperfect-clone status (§4.14), awaiting the correlated `RESP`.
    pub async fn query_imperfect(&self) -> Result<ImperfectStatus> {
        let payload = self
            .link
            .query_option_async(OPT_IMPERFECT, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Imperfect(i)) => Ok(i),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the movement-riding window (§4.14), awaiting the correlated `RESP`; `None` = off.
    pub async fn query_movement_riding(&self) -> Result<Option<Duration>> {
        let payload = self
            .link
            .query_option_async(OPT_MOVE_RIDE, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::MovementRiding(w)) => Ok(w),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the emit-rate pacing mode + the rate in effect (§4.14), awaiting the correlated `RESP`.
    pub async fn query_emit_pace(&self) -> Result<EmitPaceStatus> {
        let payload = self
            .link
            .query_option_async(OPT_EMIT, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::EmitPace(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    /// Query the bearing (§4.14), awaiting the correlated `RESP`.
    pub async fn query_bearing(&self) -> Result<Bearing> {
        let payload = self
            .link
            .query_option_async(OPT_BEARING, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Bearing(b)) => Ok(b),
            _ => Err(Error::NoReply),
        }
    }

    /// Query what motion is rendered with and whether a profile has armed (§4.14), awaiting the
    /// correlated `RESP`.
    pub async fn query_render(&self) -> Result<RenderStatus> {
        let payload = self
            .link
            .query_option_async(OPT_RENDER, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Render(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    /// Query how far an injected delta is spread and the interval in effect (§4.14), awaiting the
    /// correlated `RESP`.
    pub async fn query_spread(&self) -> Result<SpreadStatus> {
        let payload = self
            .link
            .query_option_async(OPT_SPREAD, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Spread(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    // The advanced control layer (§3.14). The gated setters read the opt-in on the async query path rather
    // than blocking the executor on the sync one, then hand off to the send-only core they share with
    // the sync `Device`.
    async fn require_imperfect(&self) -> Result<()> {
        if self.query_imperfect().await?.allowed {
            Ok(())
        } else {
            Err(Error::ImperfectRequired)
        }
    }

    /// `RAW`: put raw bytes on a cloned endpoint number in a direction. See [`Device::raw`].
    // Nothing to await since the send stopped reading the opt-in, but it stays a future: every caller
    // awaits it.
    pub async fn raw(&self, ep: u8, direction: Direction, bytes: &[u8]) -> Result<()> {
        self.dev().raw(ep, direction, bytes)
    }

    /// `TRANSFER`: run one control transfer against the device. See [`Device::transfer`].
    pub async fn transfer(&self, ep: u8, setup: Setup, out: &[u8]) -> Result<TransferOutcome> {
        self.transfer_timeout(ep, setup, out, DEFAULT_TRANSFER_TIMEOUT)
            .await
    }

    /// [`transfer`](Self::transfer) with an explicit reply timeout. See [`Device::transfer_timeout`].
    pub async fn transfer_timeout(
        &self,
        ep: u8,
        setup: Setup,
        out: &[u8],
        timeout: Duration,
    ) -> Result<TransferOutcome> {
        let (status, data) = self.link.transfer_async(ep, setup, out, timeout).await?;
        Ok(TransferOutcome {
            status: TransferStatus::from_u8(status),
            data,
        })
    }

    /// `REWRITE`: install one rewrite rule. See [`Device::set_rewrite`].
    pub async fn set_rewrite(&self, rule: &RewriteRule) -> Result<()> {
        crate::device::rewrite::validate_rule(rule)?;
        self.require_imperfect().await?;
        self.dev().set_rewrite_checked(rule)
    }

    /// `REWRITE` remove: drop one rewrite rule by key. See [`Device::remove_rewrite`].
    pub fn remove_rewrite(&self, rule: &RewriteRule) -> Result<()> {
        self.dev().remove_rewrite(rule)
    }

    /// `REWRITE` clear: drop the whole rewrite table. See [`Device::clear_rewrite`].
    pub fn clear_rewrite(&self) -> Result<()> {
        self.dev().clear_rewrite()
    }

    /// `QUERY(REWRITE)`: the rewrite-table summary. See [`Device::query_rewrite`].
    pub async fn query_rewrite(&self) -> Result<RewriteTable> {
        let payload = self
            .link
            .query_async(Q_REWRITE, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Rewrite(t)) => Ok(t),
            _ => Err(Error::NoReply),
        }
    }

    /// `QUERY(REWRITE_ENTRY)`: one rule in full. See [`Device::query_rewrite_entry`].
    pub async fn query_rewrite_entry(&self, index: u8) -> Result<RewriteRule> {
        let payload = self
            .link
            .query_indexed_async(Q_REWRITE_ENTRY, index, self.link.query_timeout_default())
            .await?;
        crate::types::rewrite::rewrite_entry_from_payload(&payload).ok_or(Error::NoReply)
    }

    /// `PATCH`: store one descriptor patch. See [`Device::set_patch`].
    pub fn set_patch(&self, patch: &Patch) -> Result<()> {
        self.dev().set_patch(patch)
    }

    /// `PATCH` APPLY: re-present the clone with the stored set. See [`Device::apply_patch`].
    pub async fn apply_patch(&self) -> Result<()> {
        self.require_imperfect().await?;
        self.dev().apply_patch_send()
    }

    /// `PATCH` CLEAR: drop every patch and re-present. See [`Device::clear_patch`].
    pub fn clear_patch(&self) -> Result<()> {
        self.dev().clear_patch()
    }

    /// `QUERY(PATCHES)`: the descriptor-patch set summary. See [`Device::query_patches`].
    pub async fn query_patches(&self) -> Result<PatchSet> {
        let payload = self
            .link
            .query_async(Q_PATCHES, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Patches(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    /// `QUERY(PATCH_ENTRY)`: one patch in full. See [`Device::query_patch_entry`].
    pub async fn query_patch_entry(&self, index: u8) -> Result<Patch> {
        let payload = self
            .link
            .query_indexed_async(Q_PATCH_ENTRY, index, self.link.query_timeout_default())
            .await?;
        crate::types::patch::patch_entry_from_payload(&payload).ok_or(Error::NoReply)
    }

    /// `TRANSFORM`: install one field transform (ungated). Instant; see [`Device::transform`].
    pub fn transform(&self, t: &Transform) -> Result<()> {
        self.dev().transform(t)
    }

    /// `TRANSFORM` remove: drop one transform by key. Instant; see [`Device::untransform`].
    pub fn untransform(&self, t: &Transform) -> Result<()> {
        self.dev().untransform(t)
    }

    /// `TRANSFORM` clear: drop the whole transform table. Instant; see [`Device::clear_transforms`].
    pub fn clear_transforms(&self) -> Result<()> {
        self.dev().clear_transforms()
    }

    /// `TRANSFORM`: exchange two axes. Instant; see [`Device::transform_swap`].
    pub fn transform_swap(&self, a: Axis, b: Axis) -> Result<()> {
        self.dev().transform_swap(a, b)
    }

    /// `TRANSFORM`: remap a source field into a destination. Instant; see [`Device::transform_remap`].
    pub fn transform_remap(
        &self,
        source: impl Into<LockTarget>,
        dest: impl Into<LockTarget>,
    ) -> Result<()> {
        self.dev().transform_remap(source, dest)
    }

    /// `QUERY(TRANSFORMS)`: the transform-table summary. See [`Device::query_transforms`].
    pub async fn query_transforms(&self) -> Result<Transforms> {
        let payload = self
            .link
            .query_async(Q_TRANSFORMS, self.link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Transforms(t)) => Ok(t),
            _ => Err(Error::NoReply),
        }
    }

    /// Buffered-clip playback over the async view (§3.11); see [`Device::clip`].
    pub fn clip(&self) -> AsyncClipHandle {
        AsyncClipHandle {
            inner: self.dev().clip(),
        }
    }

    /// Open a device at `path` and wrap it as an [`AsyncDevice`].
    pub fn open(path: impl AsRef<std::path::Path>) -> Result<AsyncDevice> {
        Ok(Device::open(path)?.into_async())
    }

    /// Discover the first medius box, open it, and wrap as an [`AsyncDevice`]; blocks. See [`Device::find`].
    pub fn find() -> Result<AsyncDevice> {
        Ok(Device::find()?.into_async())
    }

    /// Enumerate every connected box; blocks (scan + a version read per box). See [`Device::list`].
    pub fn list() -> Vec<BoxInfo> {
        Device::list()
    }

    /// Open the box whose identity matches `id` (device MAC or CH343 serial). See [`Device::open_by_id`].
    pub fn open_by_id(id: &str) -> Result<AsyncDevice> {
        Ok(Device::open_by_id(id)?.into_async())
    }

    /// Open the first box whose clone is a mouse. See [`Device::find_mouse_box`].
    pub fn find_mouse_box() -> Result<AsyncDevice> {
        Ok(Device::find_mouse_box()?.into_async())
    }

    /// Open the first box whose clone is a keyboard. See [`Device::find_keyboard_box`].
    pub fn find_keyboard_box() -> Result<AsyncDevice> {
        Ok(Device::find_keyboard_box()?.into_async())
    }
}

/// An async view over a [`ClipHandle`](crate::ClipHandle) (§3.11); see [`AsyncDevice::clip`].
#[derive(Clone, Debug)]
pub struct AsyncClipHandle {
    inner: ClipHandle,
}

impl AsyncClipHandle {
    /// Append entries to the ring. Instant; see [`ClipHandle::append`](crate::ClipHandle::append).
    pub fn append(&self, clip: &ClipBuilder) -> Result<()> {
        self.inner.append(clip)
    }

    /// Set the autolock scope. Instant; see [`ClipHandle::set_autolock`](crate::ClipHandle::set_autolock).
    pub fn set_autolock(&self, scope: &[Blanket]) -> Result<()> {
        self.inner.set_autolock(scope)
    }

    /// Set loop mode. Instant; see [`ClipHandle::set_loop`](crate::ClipHandle::set_loop).
    pub fn set_loop(&self, on: bool) -> Result<()> {
        self.inner.set_loop(on)
    }

    /// Set retained mode. Instant; see [`ClipHandle::set_retain`](crate::ClipHandle::set_retain).
    pub fn set_retain(&self, on: bool) -> Result<()> {
        self.inner.set_retain(on)
    }

    /// Set whether clip motion rides. Instant; see [`ClipHandle::set_ride`](crate::ClipHandle::set_ride).
    pub fn set_ride(&self, on: bool) -> Result<()> {
        self.inner.set_ride(on)
    }

    /// Add or overwrite an input trigger. Instant; see [`ClipHandle::bind`](crate::ClipHandle::bind).
    pub fn bind(&self, trigger: ClipTrigger) -> Result<()> {
        self.inner.bind(trigger)
    }

    /// Remove an input trigger. Instant; see [`ClipHandle::unbind`](crate::ClipHandle::unbind).
    pub fn unbind(&self, usage: impl Into<Usage>, edge: Edge) -> Result<()> {
        self.inner.unbind(usage, edge)
    }

    /// Add or overwrite a packet trigger. Instant; see [`ClipHandle::bind_packet`](crate::ClipHandle::bind_packet).
    pub fn bind_packet(&self, trigger: &ClipPacketTrigger) -> Result<()> {
        self.inner.bind_packet(trigger)
    }

    /// Remove a packet trigger. Instant; see [`ClipHandle::unbind_packet`](crate::ClipHandle::unbind_packet).
    pub fn unbind_packet(&self, trigger: &ClipPacketTrigger) -> Result<()> {
        self.inner.unbind_packet(trigger)
    }

    /// Remove every trigger of both kinds. Instant; see [`ClipHandle::clear_triggers`](crate::ClipHandle::clear_triggers).
    pub fn clear_triggers(&self) -> Result<()> {
        self.inner.clear_triggers()
    }

    /// Rewind and play. Instant; see [`ClipHandle::start`](crate::ClipHandle::start).
    pub fn start(&self) -> Result<()> {
        self.inner.start()
    }

    /// Stop playback. Instant; see [`ClipHandle::stop`](crate::ClipHandle::stop).
    pub fn stop(&self) -> Result<()> {
        self.inner.stop()
    }

    /// Halt mid-clip. Instant; see [`ClipHandle::pause`](crate::ClipHandle::pause).
    pub fn pause(&self) -> Result<()> {
        self.inner.pause()
    }

    /// Continue from the paused cursor. Instant; see [`ClipHandle::resume`](crate::ClipHandle::resume).
    pub fn resume(&self) -> Result<()> {
        self.inner.resume()
    }

    /// Force a rewind and play. Instant; see [`ClipHandle::restart`](crate::ClipHandle::restart).
    pub fn restart(&self) -> Result<()> {
        self.inner.restart()
    }

    /// Toggle play/stop. Instant; see [`ClipHandle::toggle`](crate::ClipHandle::toggle).
    pub fn toggle(&self) -> Result<()> {
        self.inner.toggle()
    }

    /// Discard the loaded clip. Instant; see [`ClipHandle::clear`](crate::ClipHandle::clear).
    pub fn clear(&self) -> Result<()> {
        self.inner.clear()
    }

    /// Finalize a retained clip. Instant; see [`ClipHandle::finalize`](crate::ClipHandle::finalize).
    pub fn finalize(&self) -> Result<()> {
        self.inner.finalize()
    }

    /// `QUERY(CLIP)`: the ring depth, progress, and playback counters, awaiting the correlated `RESP`. See [`ClipHandle::query_status`](crate::ClipHandle::query_status).
    pub async fn query_status(&self) -> Result<ClipStatus> {
        let link = self.inner.link();
        let payload = link
            .query_async(Q_CLIP, link.query_timeout_default())
            .await?;
        match parse_resp(&payload) {
            Some(Resp::Clip(s)) => Ok(s),
            _ => Err(Error::NoReply),
        }
    }

    /// `QUERY(CLIP)`: the clip configuration, awaiting the correlated `RESP`. See [`ClipHandle::query_config`](crate::ClipHandle::query_config).
    pub async fn query_config(&self) -> Result<ClipSettings> {
        let link = self.inner.link();
        let payload = link
            .query_async(Q_CLIP, link.query_timeout_default())
            .await?;
        ClipSettings::from_payload(&payload).ok_or(Error::NoReply)
    }
}