medius 3.0.0

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
use std::time::Duration;

use crate::error::{Error, Result};
use crate::link::Link;
use crate::protocol::opcode::{
    OPT_EMIT, OPT_IMPERFECT, OPT_MOVE_RIDE, Q_CAPS, Q_CATCH, Q_CLIP, Q_DEVICE_INFO, Q_HEALTH,
    Q_LOCKS, Q_RATE, Q_STATS, Q_VERSION,
};
use crate::protocol::{Resp, parse_resp};
use crate::types::{
    Action, Axis, Blanket, Caps, CatchMask, CatchState, ClipBuilder, ClipSettings, ClipStatus,
    ClipTrigger, CountersSnapshot, DeviceInfo, Edge, EmitPace, EmitPaceStatus, Health,
    ImperfectStatus, LedMode, LedTarget, LockDirection, LockTarget, Locks, Motion, Rate,
    RebootTarget, Stats, Usage, Version,
};

use super::Device;
use super::catch::EventStream;
use super::clip::ClipHandle;
use super::discover::BoxInfo;
use super::logs::LogStream;

/// 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`: field-generic relative axis (cursor or wheel). Instant; see [`Device::move_axis`].
    pub fn move_axis(&self, motion: Motion) -> Result<()> {
        self.dev().move_axis(motion)
    }

    /// `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`: block a usage (button/key/media) or axis. Instant; see [`Device::lock`].
    pub fn lock(&self, target: impl Into<LockTarget>, direction: LockDirection) -> 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: LockDirection) -> 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: LockDirection) -> 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: LockDirection) -> 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: LockDirection) -> 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: LockDirection) -> Result<()> {
        self.dev().unlock_all(what, direction)
    }

    /// Subscribe to the physical-input event stream. Instant; see [`Device::catch_events`].
    pub fn catch_events(&self, mask: CatchMask) -> Result<EventStream> {
        self.dev().catch_events(mask)
    }

    /// `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. Instant; see [`Device::set_emit_pace`].
    pub fn set_emit_pace(&self, pace: EmitPace) -> Result<()> {
        self.dev().set_emit_pace(pace)
    }

    /// `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 synthesized default. Instant; see [`Device::clear_name`].
    pub fn clear_name(&self) -> Result<()> {
        self.dev().clear_name()
    }

    /// 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),
        }
    }

    /// 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)) => 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),
        }
    }

    /// 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 + per-box handshake). 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)
    }

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

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

    /// Remove every trigger binding. 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)
    }
}