haply 0.8.2

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
mod base_types;
pub use base_types::*;

use serde::{Deserialize, Serialize, Deserializer};
use serde::de::{self, Visitor};
use ts_rs::TS;


// device info - aligned with TypeScript schema
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct DeviceInfo {
    pub id: String,
    pub major_version: u32, // Required in TypeScript
    pub minor_version: u32, // Required in TypeScript
    pub device_type: DeviceType, // Required in TypeScript
    pub uuid: String, // Required in TypeScript
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct DevicesInfo {
    pub devices: Vec<DeviceInfo>,
}
// impl from for Devices info from vecs
impl From<Vec<DeviceInfo>> for DevicesInfo {
    fn from(devices: Vec<DeviceInfo>) -> Self {
        DevicesInfo { devices }
    }
}
/// Coordinate system permutation configuration
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct CoordinateSystem {
    pub permutation: String,
}

/// Transform structure containing position, rotation, and scale
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Transform {
    pub position: Linear3D,
    pub rotation: Orientation4D,
    pub scale: Linear3D,
}

/// Deserializes an `Option<Transform>`, treating empty objects `{}` as `None`.
/// Supports the new service format where transforms are omitted (sent as `{}`)
/// when they are zero/identity, while still parsing full transform objects from
/// older service versions.
fn deserialize_optional_transform<'de, D>(deserializer: D) -> Result<Option<Transform>, D::Error>
where
    D: Deserializer<'de>,
{
    let v: serde_json::Value = Deserialize::deserialize(deserializer)?;
    match &v {
        serde_json::Value::Null => Ok(None),
        serde_json::Value::Object(map) if map.is_empty() => Ok(None),
        _ => serde_json::from_value::<Transform>(v)
            .map(Some)
            .map_err(de::Error::custom),
    }
}

/// Represents the full device configuration.
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct DeviceConfig {
    #[serde(default)]
    pub id: String,
    #[serde(rename = "type")]
    pub type_: DeviceType,
    pub device_info: DeviceInfo,
    pub port: String,
    pub extended_device_id: String,
    pub extended_firmware_version: String,
    pub gravity_compensation: GravityCompensation,
    pub handedness: Handedness,
    pub torque_scaling: TorqueScaling,
    // 
    pub cursor_offset: Option<Linear3D>,
    pub coordinate_origin: Option<CoordinateOrigin>,
    #[serde(alias = "basis")]
    pub coordinate_system: Option<CoordinateSystem>,
    pub streaming_mode: Option<StreamingMode>,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VGConfig {
    #[serde(default)]
    pub id: String,
    pub port: String,
    #[serde(rename = "type")]
    pub type_: DeviceType,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct WVGConfig {
    #[serde(default)]
    pub id: String,
    pub port: String,
    #[serde(rename = "type")]
    pub type_: DeviceType,
    pub major_version: u32,
    pub minor_version: u32,
    pub hardware_version: u32,
    //
    pub streaming_mode: Option<StreamingMode>, // "Radio" or "USB"
    #[serde(alias = "basis")]
    pub coordinate_system: Option<CoordinateSystem>,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct GravityCompensation {
    pub enabled: bool,
    pub scaling_factor: f32,
}

#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct TorqueScaling {
    pub enabled: bool,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub enum Config {
    DeviceConfig(DeviceConfig),
    VGConfig(VGConfig),
    WVGConfig(WVGConfig),
}

impl Config {
    pub fn id(&self) -> &str {
        match self {
            Config::DeviceConfig(cfg) => &cfg.id,
            Config::VGConfig(cfg) => &cfg.id,
            Config::WVGConfig(cfg) => &cfg.id,
        }
    }
}

// device state to be received from service
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Buttons {
    #[serde(default)]
    pub a: bool,
    #[serde(default)]
    pub b: bool,
    #[serde(default)]
    pub c: bool,
    #[serde(default)]
    pub down: bool,
    #[serde(default)]
    pub up: bool,
    #[serde(default)]
    pub right: bool,
    #[serde(default)]
    pub left: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Inverse3State {
    pub cursor_position: Option<Linear3D>,
    pub angular_position: Option<Angular3D>, // ✅ Fix: Matches `a0, a1, a2`
    pub angular_velocity: Option<Angular3D>, // ✅ Fix: Matches `a0, a1, a2`
    pub body_orientation: Option<Orientation4D>,
    pub cursor_velocity: Option<Linear3D>,
    pub mode: DeviceMode, // "idle" | "position" | "force"
    pub control_domain: Option<ControlDomain>, // "undefined" | "cartesian" | "angular"
    pub control_mode: Option<ControlMode>, // "idle" | "position" | "force"
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform: Option<Transform>,
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform_velocity: Option<Transform>,
}
/// Represents device status.
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Inverse3Status {
    pub calibrated: bool,
    pub in_use: bool,
    pub power_supply: bool,
    pub ready: bool,
    pub started: bool,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Inverse3Message {
    pub device_id: String,
    pub state: Inverse3State,
    pub status: Inverse3Status, // 🔹 Ensure this field exists
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct Inverse3Device {
    pub device_id: String,
    pub config: Option<DeviceConfig>,
    pub state: Inverse3State,
    pub status: Inverse3Status,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VerseGripState {
    pub button: Option<bool>,
    pub hall: Option<i32>,
    pub orientation: Option<Orientation4D>,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VerseGripStatus {
    pub error: Option<i32>,
    pub ready: Option<bool>,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VerseGripMessage {
    pub device_id: String,
    pub state: VerseGripState,
    pub status: VerseGripStatus,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VerseGripDevice {
    pub device_id: String,
    pub config: Option<VGConfig>,
    pub state: VerseGripState,
    pub status: VerseGripStatus,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct WirelessVerseGripState {
    pub battery_level: Option<f64>,
    pub battery_voltage: Option<f64>,
    pub buttons: Option<Buttons>,
    pub hall: Option<i32>,
    pub orientation: Option<Orientation4D>,
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform: Option<Transform>,
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform_velocity: Option<Transform>,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct WirelessVerseGripStatus {
    #[serde(default)]
    pub ready: bool,
    #[serde(default)]
    pub connected: bool,
    #[serde(default)]
    pub awake: bool,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct WirelessVerseGripMessage {
    pub device_id: String,
    pub state: WirelessVerseGripState,
    pub status: WirelessVerseGripStatus,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct WirelessVerseGripDevice {
    pub device_id: String,
    pub config: Option<WVGConfig>,
    pub state: WirelessVerseGripState,
    pub status: WirelessVerseGripStatus,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct CustomVerseGripState {
    pub battery_level: Option<f64>,
    pub battery_voltage: Option<f64>,
    pub buttons: Option<Buttons>,
    pub hall: Option<i32>,
    pub orientation: Option<Orientation4D>,
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform: Option<Transform>,
    #[serde(default, deserialize_with = "deserialize_optional_transform")]
    pub transform_velocity: Option<Transform>,
    pub extension_data: Option<Vec<i32>>, // Changed to Vec<i32> to match the actual response format
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct CustomVerseGripMessage {
    pub device_id: String,
    pub state: CustomVerseGripState,
    pub status: WirelessVerseGripStatus,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct CustomVerseGripDevice {
    pub device_id: String,
    pub config: Option<WVGConfig>,
    pub state: CustomVerseGripState,
    pub status: WirelessVerseGripStatus,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub struct ServiceData {
    pub inverse3: Vec<Inverse3Device>,
    pub verse_grip: Vec<VerseGripDevice>,
    pub wireless_verse_grip: Vec<WirelessVerseGripDevice>,
    pub custom_verse_grip: Vec<CustomVerseGripDevice>, // Added to match TypeScript schema
    pub session_id: u64, // Changed from Option<u64> to match TypeScript number type
}

#[derive(Clone, Debug, PartialEq)]
pub struct TimestampedServiceData {
    pub data: ServiceData,
    pub timestamp: std::time::Instant,
}

impl Default for ServiceData {
    fn default() -> Self {
        ServiceData {
            inverse3: Vec::new(),
            verse_grip: Vec::new(),
            wireless_verse_grip: Vec::new(),
            custom_verse_grip: Vec::new(),
            session_id: 0,
        }
    }
}

// represents just the service data without the config info, the data get gets returned after a force update
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub struct ServiceState {
    pub inverse3: Vec<Inverse3Message>,
    pub verse_grip: Vec<VerseGripMessage>,
    pub wireless_verse_grip: Vec<WirelessVerseGripMessage>,
    pub custom_verse_grip: Vec<CustomVerseGripMessage>, // Added to match TypeScript schema
    #[serde(default)]
    pub session_id: u64, // Changed from Option<u64> to match TypeScript number type
}

impl Default for ServiceState {
    fn default() -> Self {
        ServiceState {
            inverse3: Vec::new(),
            verse_grip: Vec::new(),
            wireless_verse_grip: Vec::new(),
            custom_verse_grip: Vec::new(),
            session_id: 0,
        }
    }
}

// device cmds to be sent to service
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ForceInput {
    pub device_id: String,
    pub forces: Force,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct PositionInput {
    pub device_id: String,
    pub positions: Linear3D,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ExtensionDataInput {
    pub device_id: String,
    pub extension_data: Vec<i32>,
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct SetCursorPosition {
    pub values: Linear3D,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct SetCursorForce {
    pub values: Force,
    pub execute: bool,
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ProbeOrientation {
    pub probe_orientation: (),
}
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct SetExtensionData {
    pub extension_data: Vec<i32>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum VgCommand {
    ProbeOrientation(ProbeOrientation),
    SetExtensionData(SetExtensionData),
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ProbeCursorPosition {
    pub probe_cursor_position: (),
}
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ProbeAngularPosition {
    pub probe_angular_position: (),
}
/// Represents the `commands` field in the request.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum I3Command {
    SetCursorForce(SetCursorForce),
    SetCursorPosition(SetCursorPosition),
    ProbeCursorPosition(ProbeCursorPosition),
    ProbeAngularPosition(ProbeAngularPosition),
}

#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub struct DeviceCommandMsg<C> {
    pub device_id: String,
    // Updating according to API spec
    #[serde(rename = "commands")]
    pub command: C,
}

pub type VerseGripMsg = DeviceCommandMsg<VgCommand>;
pub type Inverse3Msg = DeviceCommandMsg<I3Command>;

/// Represents the full command payload.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub struct ServiceMsg {
    pub session: SessionMsg,
    pub inverse3: Vec<Inverse3Msg>,
    pub verse_grip: Vec<VerseGripMsg>,
    pub wireless_verse_grip: Vec<VerseGripMsg>,
    pub custom_verse_grip: Vec<VerseGripMsg>, // Added to match TypeScript schema
}
impl Default for ServiceMsg {
    fn default() -> Self {
        ServiceMsg {
            // Always request a full state render at the top of every message
            session: SessionMsg { force_render_full_state: ForceRenderFullStateMsg {} },
            inverse3: Vec::new(),
            verse_grip: Vec::new(),
            wireless_verse_grip: Vec::new(),
            custom_verse_grip: Vec::new(),
        }
    }
}

// Represents a session-level command requesting full-state rendering
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct ForceRenderFullStateMsg {}

// Wrapper for session-level commands. Always present.
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct SessionMsg {
    pub force_render_full_state: ForceRenderFullStateMsg,
}

/// Represents a single command to be sent to the service.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, TS)]
pub enum Command {
    VgCommand(VerseGripMsg),
    WvgCommand(VerseGripMsg),
    I3Command(Inverse3Msg),
    ForceRenderFullState,
}

// Device type constants to match TypeScript schema
pub const DEVICE_TYPE_INVERSE3: &str = "inverse3";
pub const DEVICE_TYPE_INVERSE3X: &str = "inverse3x";
pub const DEVICE_TYPE_MINVERSE: &str = "minverse";
pub const DEVICE_TYPE_WIRELESS_VERSE_GRIP: &str = "wireless_verse_grip";
pub const DEVICE_TYPE_CUSTOM_VERSE_GRIP: &str = "custom_verse_grip";

// Device type enum for better type safety
#[derive(Copy, Clone, Debug, PartialEq, Default, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
    #[default]
    Inverse3,
    Inverse3x,
    Minverse,
    VerseGrip,
    WirelessVerseGrip,
    CustomVerseGrip,
    Ruko,
}

// Custom deserializer for DeviceType that handles both strings and integers
impl<'de> Deserialize<'de> for DeviceType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
        struct DeviceTypeVisitor;

        impl<'de> Visitor<'de> for DeviceTypeVisitor {
            type Value = DeviceType;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a string or an integer representing device type")
            }

            fn visit_str<E>(self, value: &str) -> Result<DeviceType, E> where E: de::Error {
                match value {
                    "inverse3" => Ok(DeviceType::Inverse3),
                    "inverse3x" => Ok(DeviceType::Inverse3x),
                    "minverse" => Ok(DeviceType::Minverse),
                    "verse_grip" => Ok(DeviceType::VerseGrip),
                    "wireless_verse_grip" => Ok(DeviceType::WirelessVerseGrip),
                    "custom_verse_grip" => Ok(DeviceType::CustomVerseGrip),
                    "ruko" => Ok(DeviceType::Ruko),
                    _ => Err(E::custom(format!("unknown device type: {}", value))),
                }
            }

            fn visit_u64<E>(self, value: u64) -> Result<DeviceType, E> where E: de::Error {
                match value {
                    4 => Ok(DeviceType::Inverse3),
                    6 => Ok(DeviceType::Minverse),
                    _ => Err(E::custom(format!("unknown device type code: {}", value))),
                }
            }

            // Handle i64 values too
            fn visit_i64<E>(self, value: i64) -> Result<DeviceType, E> where E: de::Error {
                if value < 0 {
                    return Err(E::custom(format!("negative device type code: {}", value)));
                }
                self.visit_u64(value as u64)
            }
        }

        deserializer.deserialize_any(DeviceTypeVisitor)
    }
}

// Mode enum to match TypeScript
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum DeviceMode {
    #[default]
    Idle,
    Position,
    Angular,
}

// Control domain enum to match TypeScript
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum ControlDomain {
    #[default]
    Undefined,
    Cartesian,
    Angular,
}

// Control mode enum to match TypeScript
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum ControlMode {
    #[default]
    Idle,
    Position,
    Force,
}

// Handedness enum
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum Handedness {
    Left,
    #[default]
    Right,
}

// Streaming mode enum
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub enum StreamingMode {
    #[default]
    USB,
    Radio,
}

// Coordinate origin enum
#[derive(Copy, Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
#[serde(rename_all = "snake_case")]
pub enum CoordinateOrigin {
    #[default]
    DeviceBase,
    WorkspaceCenter,
}

/// Version information returned by the service.
#[derive(Clone, Debug, PartialEq, Default, Deserialize, Serialize, TS)]
pub struct VersionResponse {
    pub build_time: String,
    pub git_branch: String,
    pub git_describe: String,
    pub git_hash: String,
    pub git_tag: String,
    pub project_name: String,
    pub project_version: String,
}