haply 1.2.1

Haply Robotics Client Library for the Inverse Service
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
//! Device module provides the core functionality for interacting with Haply haptic devices.
//! It handles device communication, state management, and command processing through both
//! HTTP and WebSocket protocols.

use crate::device_model::{
    AngularPositionInput,
    AngularTorqueInput,
    Command,
    Config,
    ExtensionDataInput,
    ForceInput,
    Inverse3CommandClear,
    Inverse3Configure,
    PositionInput,
    SdfHfxObject,
    ServiceData,
    ServiceMsg,
    SessionConfigure,
    TimestampedServiceData,
    VerseGripCommandClear,
    VerseGripConfigure,
    VerseGripDuplicateMode,
    VersionResponse,
};
use crate::state::{
    clear_inverse3_commands_in_msg,
    clear_oneshot_fields,
    clear_verse_grip_commands_in_msg,
    update_entire_msg,
    update_state_on_message,
    VerseGripLane,
};
use crate::http::InverseHttpClient;
use crate::websocket::InverseWebSocketClient;
use log::{ error, trace };
use std::sync::Arc;
use tokio::sync::Mutex;

#[cfg(test)]
#[path = "unit_tests.rs"]
mod unit_tests;

/// Main struct representing a Haply haptic device.
/// Handles all communication and state management for a connected device.
pub struct HaplyDevice {
    http_client: InverseHttpClient,
    pub ws_client: InverseWebSocketClient,
    /// Cached device state
    pub state: Arc<Mutex<TimestampedServiceData>>,
    /// Cached service cmd msg that will be sent to the device on `send_command` call
    pub device_cmd_msg: Arc<Mutex<ServiceMsg>>,
    verse_grip_mode: VerseGripDuplicateMode,
}

impl HaplyDevice {
    /// Creates a new HaplyDevice with default options (`PreferCustom` dedup mode).
    pub async fn new(
        http_base: &str,
        ws_url: &str
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Self::with_options(http_base, ws_url, VerseGripDuplicateMode::default()).await
    }

    /// Creates a new HaplyDevice with a specific verse grip duplicate mode.
    pub async fn with_options(
        http_base: &str,
        ws_url: &str,
        verse_grip_mode: VerseGripDuplicateMode
    ) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        let http_client = InverseHttpClient::with_options(http_base, verse_grip_mode);
        let mut ws_client = InverseWebSocketClient::new(ws_url);
        ws_client.connect().await?;

        let initial_state = TimestampedServiceData {
            data: ServiceData::default(),
            timestamp: std::time::Instant::now(),
        };
        let device = Self {
            http_client,
            ws_client: ws_client.clone(),
            state: Arc::new(Mutex::new(initial_state)),
            device_cmd_msg: Arc::new(Mutex::new(ServiceMsg::default())),
            verse_grip_mode,
        };

        device.start_listening();
        Ok(device)
    }

    /// Shutdown the device and its connections.
    pub async fn shutdown(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.ws_client.disconnect().await
    }

    /// Starts the WebSocket listening loop for device updates.
    fn start_listening(&self) {
        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::start_listening");

        let state_clone = Arc::clone(&self.state);
        let mut ws_client = self.ws_client.clone();
        let mode = self.verse_grip_mode;
        tokio::spawn(async move {
            let mut first_msg = true;
            ws_client.listen(move |message| {
                let state_clone = Arc::clone(&state_clone);
                async move {
                    update_state_on_message(state_clone, message, &mut first_msg, mode).await;
                }
            }).await;
        });
    }

    /// Retrieves the current state of the device.
    pub async fn read_state(
        &self
    ) -> Result<ServiceData, Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::read_state");

        trace!("Reading device state");
        let data = {
            #[cfg(feature = "tracy")]
            let _lock_span = tracy_client::span!("device::read_state_lock_and_clone");
            self.state.lock().await.data.clone()
        };
        Ok(data)
    }

    /// Forces a full state update from the service then returns the current state.
    pub async fn force_read_full_state(
        &mut self,
        timeout: Option<std::time::Duration>
    ) -> Result<ServiceData, Box<dyn std::error::Error + Send + Sync>> {
        let start = std::time::Instant::now();
        self.send_force_full_render().await?;
        if let Some(dur) = timeout {
            loop {
                let elapsed = start.elapsed();
                if elapsed >= dur {
                    error!("Timeout waiting for full state update");
                    return Err("Timeout waiting for full state update".into());
                }
                let last_update = self.state.lock().await;
                if last_update.timestamp >= start {
                    trace!("State updated after force render");
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            }
        }
        self.read_state().await
    }

    // -------------------------------------------------------
    // Per-tick command convenience methods
    // -------------------------------------------------------

    /// Updates force values for one or more Inverse3 devices.
    pub async fn update_force(
        &mut self,
        forces_input: Vec<ForceInput>,
        execute_check: Option<bool>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = forces_input
            .into_iter()
            .map(|fi| Command::SetCursorForce {
                device_id: fi.device_id,
                vector: fi.forces,
                execute: execute_check.unwrap_or(true),
            })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Updates position values for one or more Inverse3 devices.
    pub async fn update_position(
        &mut self,
        positions_input: Vec<PositionInput>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = positions_input
            .into_iter()
            .map(|pi| Command::SetCursorPosition {
                device_id: pi.device_id,
                position: pi.positions,
                execute: true,
            })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Updates angular torques for one or more Inverse3 devices.
    pub async fn update_angular_torques(
        &mut self,
        inputs: Vec<AngularTorqueInput>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = inputs
            .into_iter()
            .map(|i| Command::SetAngularTorques {
                device_id: i.device_id,
                torques: i.torques,
                execute: true,
            })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Updates angular position for one or more Inverse3 devices.
    pub async fn update_angular_position(
        &mut self,
        inputs: Vec<AngularPositionInput>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = inputs
            .into_iter()
            .map(|i| Command::SetAngularPosition {
                device_id: i.device_id,
                angles: i.angles,
                execute: true,
            })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Updates extension data for wireless verse grip devices.
    pub async fn update_extension_data(
        &mut self,
        extension_data_inputs: Vec<ExtensionDataInput>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = extension_data_inputs
            .into_iter()
            .map(|edi| Command::SetExtensionData {
                device_id: edi.device_id,
                extension_data: edi.extension_data,
            })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Requests position probe from specified Inverse3 devices.
    pub async fn probe_cursor_position(
        &mut self,
        device_ids: Vec<String>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = device_ids
            .into_iter()
            .map(|id| Command::ProbePosition { device_id: id })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Requests position probe (3.5 unified probe — replaces separate angular probe).
    #[deprecated(
        note = "Use probe_cursor_position instead — 3.5 unified probe_position covers both"
    )]
    pub async fn probe_angular_position(
        &mut self,
        device_ids: Vec<String>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.probe_cursor_position(device_ids, send).await
    }

    /// Requests orientation probe from specified VerseGrip/WVG devices.
    pub async fn probe_orientation(
        &mut self,
        device_ids: Vec<String>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let commands: Vec<Command> = device_ids
            .into_iter()
            .map(|id| Command::ProbeOrientation { device_id: id })
            .collect();

        self.update_command_msg(commands).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    // -------------------------------------------------------
    // Configure convenience methods (one-shot)
    // -------------------------------------------------------

    /// Configures an Inverse3 device (preset, basis, mount, damping, force_gate, navigation).
    pub async fn configure_inverse3(
        &mut self,
        device_id: &str,
        config: Inverse3Configure,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::ConfigureInverse3 {
            device_id: device_id.to_string(),
            config,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Configures a VerseGrip/WVG device (preset, basis, mount).
    pub async fn configure_versegrip(
        &mut self,
        device_id: &str,
        config: VerseGripConfigure,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::ConfigureVerseGrip {
            device_id: device_id.to_string(),
            config,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Configures the session (profile, basis, serialization, sdf output).
    pub async fn configure_session(
        &mut self,
        config: SessionConfigure,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::ConfigureSession(config);
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    // -------------------------------------------------------
    // SDF HFX convenience methods
    // -------------------------------------------------------

    /// Atomic replace — clears all SDF effects for this device, then inserts `objects`.
    pub async fn sdf_set(
        &mut self,
        device_id: &str,
        objects: Vec<SdfHfxObject>,
        from_space: Option<String>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::SdfSet {
            device_id: device_id.to_string(),
            objects,
            from_space,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Partial update — only provided fields are applied; `id` required on each object.
    pub async fn sdf_update(
        &mut self,
        device_id: &str,
        objects: Vec<SdfHfxObject>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::SdfUpdate {
            device_id: device_id.to_string(),
            objects,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Remove SDF effects by ID.
    pub async fn sdf_remove(
        &mut self,
        device_id: &str,
        ids: Vec<String>,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::SdfRemove {
            device_id: device_id.to_string(),
            ids,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    /// Enable or disable SDF state output streaming for the session.
    /// The `device_id` argument is retained for backward compatibility and is ignored.
    pub async fn configure_sdf_output(
        &mut self,
        device_id: &str,
        state_output: bool,
        send: Option<bool>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let command = Command::ConfigureSdfOutput {
            device_id: device_id.to_string(),
            state_output,
        };
        self.update_command_msg(vec![command]).await?;
        if send.unwrap_or(false) {
            self.send_command().await?;
        }
        Ok(())
    }

    // -------------------------------------------------------
    // Session-level commands
    // -------------------------------------------------------

    /// Sends a force full render command to the service.
    pub async fn send_force_full_render(
        &mut self
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.update_command_msg(vec![Command::ForceRenderFullState]).await?;
        self.send_command().await?;
        Ok(())
    }

    /// Sends a lightweight ping to keep the WebSocket connection alive.
    pub async fn send_ping(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.ws_client.send_message("{}").await?;
        Ok(())
    }

    // -------------------------------------------------------
    // Command accumulation and transmission
    // -------------------------------------------------------

    /// Accumulates commands into the cached service message.
    pub async fn update_command_msg(
        &mut self,
        commands: Vec<Command>
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::update_command_msg");

        let mut service_msg = {
            #[cfg(feature = "tracy")]
            let _lock_span = tracy_client::span!("device::update_command_msg_lock");
            self.device_cmd_msg.lock().await
        };
        {
            #[cfg(feature = "tracy")]
            let _merge_span = tracy_client::span!("device::update_command_msg_merge");
            update_entire_msg(&commands, &mut service_msg)?;
        }
        Ok(())
    }

    /// Sends the cached command message through the WebSocket connection.
    /// After sending, one-shot fields (configure, force_render_full_state) are cleared.
    /// Per-tick commands are preserved for the next frame.
    pub async fn send_command(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::send_command");

        let mut msg = {
            #[cfg(feature = "tracy")]
            let _lock_span = tracy_client::span!("device::send_command_lock");
            self.device_cmd_msg.lock().await
        };
        let cmd_text = {
            #[cfg(feature = "tracy")]
            let _serialize_span = tracy_client::span!("device::send_command_serialize");
            serde_json::to_string(&*msg)?
        };
        {
            #[cfg(feature = "tracy")]
            let _send_span = tracy_client::span!("device::send_command_ws_send");
            self.ws_client.send_message(&cmd_text).await?;
        }

        // Clear one-shot fields after send
        {
            #[cfg(feature = "tracy")]
            let _clear_span = tracy_client::span!("device::send_command_clear_oneshot");
            clear_oneshot_fields(&mut msg);
        }

        Ok(())
    }

    // -------------------------------------------------------
    // Per-tick command clearing
    // -------------------------------------------------------
    //
    // Per-tick command fields (`set_cursor_force`, `set_cursor_position`,
    // `set_extension_data`, etc.) are deliberately preserved in the cached
    // `ServiceMsg` across `send_command` flushes so callers can rely on
    // zero-order hold behavior in slow control loops. When the controlling
    // layer is intentionally switching modes — for example moving from
    // force-rendered control to absolute cursor position — the previous
    // mode's field would otherwise stay cached and continue to appear in
    // every outgoing WS frame, causing the firmware to honor both modes
    // each frame. The methods below let the caller explicitly remove the
    // stale fields so subsequent frames serialize without them.
    //
    // The clear is synchronous and one-shot: it operates on the cached
    // `ServiceMsg` immediately and persists across frames just like any
    // other state mutation. Calling with a default-constructed selector
    // (no fields selected) is a cheap no-op.

    /// Clears the selected per-tick command fields cached for one Inverse3
    /// device, so subsequent WS frames emit those fields as absent until the
    /// caller sets them again. Fields not selected in `what` are left intact.
    ///
    /// If clearing leaves the device's command bag entirely empty, the bag
    /// itself is dropped so the WS frame omits the `commands` object for
    /// that device altogether.
    pub async fn clear_inverse3_commands(
        &mut self,
        device_id: &str,
        what: Inverse3CommandClear,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if !what.any() {
            return Ok(());
        }

        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::clear_inverse3_commands");

        let mut msg = {
            #[cfg(feature = "tracy")]
            let _lock_span = tracy_client::span!("device::clear_inverse3_commands_lock");
            self.device_cmd_msg.lock().await
        };
        clear_inverse3_commands_in_msg(&mut msg, device_id, what);
        Ok(())
    }

    /// Clears the selected per-tick command fields cached for one wired
    /// VerseGrip device (the `verse_grip` lane in `ServiceMsg`).
    ///
    /// Most callers writing to VerseGrip should use
    /// [`HaplyDevice::clear_wireless_verse_grip_commands`] instead, since the
    /// existing high-level helpers (`update_extension_data`, `probe_orientation`,
    /// `configure_versegrip`) all route to the wireless lane.
    pub async fn clear_verse_grip_commands(
        &mut self,
        device_id: &str,
        what: VerseGripCommandClear,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if !what.any() {
            return Ok(());
        }

        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::clear_verse_grip_commands");

        let mut msg = self.device_cmd_msg.lock().await;
        clear_verse_grip_commands_in_msg(&mut msg, VerseGripLane::Wired, device_id, what);
        Ok(())
    }

    /// Clears the selected per-tick command fields cached for one
    /// wireless or custom VerseGrip device (the `wireless_verse_grip` lane
    /// in `ServiceMsg`). This is the lane that the existing
    /// `update_extension_data`, `probe_orientation`, and `configure_versegrip`
    /// helpers populate.
    pub async fn clear_wireless_verse_grip_commands(
        &mut self,
        device_id: &str,
        what: VerseGripCommandClear,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if !what.any() {
            return Ok(());
        }

        #[cfg(feature = "tracy")]
        let _span = tracy_client::span!("device::clear_wireless_verse_grip_commands");

        let mut msg = self.device_cmd_msg.lock().await;
        clear_verse_grip_commands_in_msg(&mut msg, VerseGripLane::Wireless, device_id, what);
        Ok(())
    }

    // -------------------------------------------------------
    // Device querying
    // -------------------------------------------------------

    /// Lists all available Haply devices via HTTP.
    pub async fn list_devices(
        &self
    ) -> Result<Vec<Config>, Box<dyn std::error::Error + Send + Sync>> {
        let configs = self.http_client.get_devices().await?;
        Ok(configs)
    }

    /// Returns all device configs from the cached service state.
    pub async fn get_devices(
        &self
    ) -> Result<Vec<Config>, Box<dyn std::error::Error + Send + Sync>> {
        let state = self.state.lock().await;
        let mut configs = Vec::new();
        for d in &state.data.inverse3 {
            let config = d.config.clone().ok_or("Missing config for Inverse3 device")?;
            configs.push(Config::DeviceConfig(config));
        }
        for d in &state.data.verse_grip {
            let config = d.config.clone().ok_or("Missing config for Verse Grip device")?;
            configs.push(Config::VGConfig(config));
        }
        for d in &state.data.wireless_verse_grip {
            let config = d.config.clone().ok_or("Missing config for Wireless Verse Grip device")?;
            configs.push(Config::WVGConfig(config));
        }
        for d in &state.data.custom_verse_grip {
            let config = d.config.clone().ok_or("Missing config for Custom Verse Grip device")?;
            configs.push(Config::WVGConfig(config));
        }
        Ok(configs)
    }

    /// Finds a specific device by ID.
    pub async fn get_device_info(
        &self,
        device_id: &str
    ) -> Result<Config, Box<dyn std::error::Error + Send + Sync>> {
        let devices = self.list_devices().await?;
        let device = devices.into_iter().find(|c| {
            match c {
                Config::DeviceConfig(dc) => dc.device_info.id == device_id,
                Config::VGConfig(vgc) => vgc.id == device_id,
                Config::WVGConfig(wvgc) => wvgc.id == device_id,
            }
        });
        match device {
            Some(cfg) => Ok(cfg),
            None => Err(format!("Device {} not found", device_id).into()),
        }
    }

    /// Gets the service version from the HTTP client.
    pub async fn get_service_version(
        &self
    ) -> Result<VersionResponse, Box<dyn std::error::Error + Send + Sync>> {
        let version = self.http_client.get_version().await?;
        Ok(version)
    }
}