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
use super::*;
use std::convert::TryInto;

#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum JoyConDeviceType {
    JoyConL = 0,
    JoyConR = 1,
    ProCon = 2,
}

pub mod calibration {
    use super::*;

    pub mod stick {
        use super::*;

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct AxisCalibration {
            max: i16,
            center: i16,
            min: i16,
        }

        impl AxisCalibration {
            /// Max above center
            pub fn max(&self) -> i16 {
                self.max
            }

            /// Center
            pub fn center(&self) -> i16 {
                self.center
            }

            /// Min above center
            pub fn min(&self) -> i16 {
                self.min
            }
        }

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub enum StickCalibration {
            Available {
                x: AxisCalibration,
                y: AxisCalibration,
            },
            Unavailable,
        }

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct JoyConSticksCalibration {
            left: StickCalibration,
            right: StickCalibration,
        }

        impl JoyConSticksCalibration {
            pub fn left(&self) -> &StickCalibration {
                &self.left
            }

            pub fn right(&self) -> &StickCalibration {
                &self.right
            }
        }

        impl From<[u8; 18]> for JoyConSticksCalibration {
            fn from(stick_cal: [u8; 18]) -> Self {
                fn stick_cal_to_data(stick_cal: &[u8]) -> [u16; 6] {
                    let mut data = [0u16; 6];

                    data[0] = ((stick_cal[1] as u16) << 8) & 0xF00 | stick_cal[0] as u16;
                    data[1] = ((stick_cal[2] as u16) << 4) | ((stick_cal[1] as u16) >> 4);
                    data[2] = ((stick_cal[4] as u16) << 8) & 0xF00 | stick_cal[3] as u16;
                    data[3] = ((stick_cal[5] as u16) << 4) | ((stick_cal[4] as u16) >> 4);
                    data[4] = ((stick_cal[7] as u16) << 8) & 0xF00 | stick_cal[6] as u16;
                    data[5] = ((stick_cal[8] as u16) << 4) | ((stick_cal[7] as u16) >> 4);

                    data
                }

                let left_stick_calibration = {
                    let left_stick_cal = &stick_cal[0..9];
                    if left_stick_cal.iter().all(|u| u == &0xFF)
                    {
                        StickCalibration::Unavailable
                    } else {
                        let left_stick_data = stick_cal_to_data(&stick_cal[0..9]);

                        StickCalibration::Available {
                            x: AxisCalibration {
                                center: left_stick_data[2] as i16,
                                max: left_stick_data[2] as i16 + left_stick_data[0] as i16,
                                min: left_stick_data[2] as i16 - left_stick_data[4] as i16,
                            },
                            y: AxisCalibration {
                                center: left_stick_data[3] as i16,
                                max: left_stick_data[3] as i16 + left_stick_data[1] as i16,
                                min: left_stick_data[3] as i16 - left_stick_data[5] as i16,
                            },
                        }
                    }
                };

                let right_stick_calibration = {
                    let right_stick_cal = &stick_cal[9..18];
                    if right_stick_cal.iter().all(|u| u == &0xFF)
                    {
                        StickCalibration::Unavailable
                    } else {
                        let right_stick_data = stick_cal_to_data(right_stick_cal);

                        StickCalibration::Available {
                            x: AxisCalibration {
                                center: right_stick_data[0] as i16,
                                max: right_stick_data[0] as i16 + right_stick_data[4] as i16,
                                min: right_stick_data[0] as i16 - right_stick_data[2] as i16,
                            },
                            y: AxisCalibration {
                                center: right_stick_data[1] as i16,
                                max: right_stick_data[1] as i16 + right_stick_data[5] as i16,
                                min: right_stick_data[1] as i16 - right_stick_data[3] as i16,
                            },
                        }
                    }
                };

                JoyConSticksCalibration {
                    left: left_stick_calibration,
                    right: right_stick_calibration,
                }
            }
        }

        pub fn get_factory_calibration(device: &HidDevice) -> Option<JoyConSticksCalibration> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x3D, 0x60, 0, 0, 18])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x3D, 0x60, 0, 0, 18] => {}
                    _ => continue,
                }

                let mut report = [0u8; 18];
                report.copy_from_slice(&buf[20..38]);

                return Some(JoyConSticksCalibration::from(report));
            }

            None
        }

        pub fn get_user_calibration(device: &HidDevice) -> Option<JoyConSticksCalibration> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x12, 0x80, 0, 0, 20])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x12, 0x80, 0, 0, 20] => {}
                    _ => continue,
                }

                let mut report = [0u8; 18];
                {
                    let (left, right) = report.split_at_mut(9);
                    left.copy_from_slice(&buf[20..29]);
                    right.copy_from_slice(&buf[31..40]);
                }

                return Some(JoyConSticksCalibration::from(report));
            }

            None
        }

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct StickParameters {
            dead_zone: u16,
            range_ratio: u16,
        }

        impl StickParameters {
            pub fn dead_zone(&self) -> u16 {
                self.dead_zone
            }

            pub fn range_ratio(&self) -> u16 {
                self.range_ratio
            }
        }

        impl From<[u8; 18]> for StickParameters {
            fn from(array: [u8; 18]) -> Self {
                fn decode(stick_cal: &[u8]) -> [u16; 12] {
                    let mut data = [0u16; 12];

                    data[0] = ((stick_cal[1] as u16) << 8) & 0xF00 | stick_cal[0] as u16;
                    data[1] = ((stick_cal[2] as u16) << 4) | ((stick_cal[1] as u16) >> 4);
                    data[2] = ((stick_cal[4] as u16) << 8) & 0xF00 | stick_cal[3] as u16;
                    data[3] = ((stick_cal[5] as u16) << 4) | ((stick_cal[4] as u16) >> 4);
                    data[4] = ((stick_cal[7] as u16) << 8) & 0xF00 | stick_cal[6] as u16;
                    data[5] = ((stick_cal[8] as u16) << 4) | ((stick_cal[7] as u16) >> 4);
                    data[6] = ((stick_cal[10] as u16) << 8) & 0xF00 | stick_cal[9] as u16;
                    data[7] = ((stick_cal[11] as u16) << 4) | ((stick_cal[10] as u16) >> 4);
                    data[8] = ((stick_cal[13] as u16) << 8) & 0xF00 | stick_cal[12] as u16;
                    data[9] = ((stick_cal[14] as u16) << 4) | ((stick_cal[13] as u16) >> 4);
                    data[10] = ((stick_cal[16] as u16) << 8) & 0xF00 | stick_cal[15] as u16;
                    data[11] = ((stick_cal[17] as u16) << 4) | ((stick_cal[16] as u16) >> 4);

                    data
                }

                let decoded = decode(&array);

                StickParameters {
                    dead_zone: decoded[2],
                    range_ratio: decoded[3],
                }
            }
        }

        pub fn get_parameters(device: &HidDevice) -> Option<StickParameters> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x86, 0x60, 0, 0, 18])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x86, 0x60, 0, 0, 18] => {}
                    _ => continue,
                }

                let mut report = [0u8; 18];
                report.copy_from_slice(&buf[20..38]);

                return Some(StickParameters::from(report));
            }

            None
        }
    }

    pub mod imu {
        use super::*;
        use std::fmt::Debug;
        use std::hash::Hash;

        #[derive(Debug)]
        pub struct XYZ<T: Debug> {
            pub x: T,
            pub y: T,
            pub z: T,
        }

        impl<T> Clone for XYZ<T> where T: Debug + Clone {
            fn clone(&self) -> Self {
                Self {
                    x: self.x.clone(),
                    y: self.y.clone(),
                    z: self.z.clone(),
                }
            }
        }

        impl<T> Hash for XYZ<T> where T: Debug + Hash {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                self.x.hash(state);
                self.y.hash(state);
                self.z.hash(state);
            }
        }

        impl<T> PartialEq for XYZ<T> where T: Debug + PartialEq {
            fn eq(&self, other: &Self) -> bool {
                self.x == other.x
                    && self.y == other.y
                    && self.z == other.z
            }
        }

        impl<T> Eq for XYZ<T> where T: Debug + Eq {}

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub enum IMUCalibration {
            Available {
                /// Acc XYZ origin position when completely horizontal and stick is upside
                acc_origin_position: XYZ<i16>,
                /// Acc XYZ sensitivity special coeff, for default sensitivity: ±8G.
                acc_sensitivity_special_coeff: XYZ<i16>,
                /// Gyro XYZ origin position when still
                gyro_origin_position: XYZ<i16>,
                /// Gyro XYZ sensitivity special coeff, for default sensitivity: ±2000dps.
                gyro_sensitivity_special_coeff: XYZ<i16>,
            },
            Unavailable,
        }

        impl From<[u8; 24]> for IMUCalibration {
            fn from(value: [u8; 24]) -> Self {
                use std::slice::Iter;
                use std::iter::Cloned;

                if value.iter().all(|v| v == &0xFF) {
                    return IMUCalibration::Unavailable;
                }

                fn convert(little: u8, big: u8) -> i16 {
                    i16::from_be_bytes([big, little])
                }

                fn iter_to_xyz_i16(iter: &mut Cloned<Iter<u8>>) -> XYZ<i16> {
                    let x = convert(iter.next().unwrap(), iter.next().unwrap());
                    let y = convert(iter.next().unwrap(), iter.next().unwrap());
                    let z = convert(iter.next().unwrap(), iter.next().unwrap());

                    XYZ { x, y, z }
                }

                let mut iter = value.iter().cloned();

                let acc_origin_position = iter_to_xyz_i16(&mut iter);
                let acc_sensitivity_special_coeff = iter_to_xyz_i16(&mut iter);
                let gyro_origin_position = iter_to_xyz_i16(&mut iter);
                let gyro_sensitivity_special_coeff = iter_to_xyz_i16(&mut iter);

                IMUCalibration::Available {
                    acc_origin_position,
                    acc_sensitivity_special_coeff,
                    gyro_origin_position,
                    gyro_sensitivity_special_coeff,
                }
            }
        }

        pub fn get_factory_calibration(device: &HidDevice) -> Option<IMUCalibration> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x20, 0x60, 0, 0, 24])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x20, 0x60, 0, 0, 24] => {}
                    _ => continue,
                }

                let mut report = [0u8; 24];
                report.copy_from_slice(&buf[20..44]);

                return Some(IMUCalibration::from(report));
            }

            None
        }

        pub fn get_user_calibration(device: &HidDevice) -> Option<IMUCalibration> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x28, 0x80, 0, 0, 24])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x28, 0x80, 0, 0, 24] => {}
                    _ => continue,
                }

                let mut report = [0u8; 24];
                report.copy_from_slice(&buf[20..44]);

                return Some(IMUCalibration::from(report));
            }

            None
        }

        #[derive(Debug, Clone, Hash, Eq, PartialEq)]
        pub struct IMUOffsets {
            pub x: i16,
            pub y: i16,
            pub z: i16,
        }

        impl From<[u8; 6]> for IMUOffsets {
            fn from(array: [u8; 6]) -> Self {
                let x = i16::from_le_bytes([array[0], array[1]]);
                let y = i16::from_le_bytes([array[2], array[3]]);
                let z = i16::from_le_bytes([array[4], array[5]]);

                IMUOffsets {
                    x,
                    y,
                    z,
                }
            }
        }

        pub fn get_offsets(device: &HidDevice) -> Option<IMUOffsets> {
            device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x80, 0x60, 0, 0, 6])
                .ok()?;

            for _ in 0..5 {
                let mut buf = [0u8; 64];
                device.read_timeout(&mut buf, 20)
                    .ok()?;

                match buf[14..20] {
                    [0x10, 0x80, 0x60, 0, 0, 6] => {}
                    _ => continue,
                }

                let mut report = [0u8; 6];
                report.copy_from_slice(&buf[20..26]);

                return Some(IMUOffsets::from(report));
            }

            None
        }
    }
}

pub mod color {
    use super::*;

    #[derive(Debug, Clone, Hash, Eq, PartialEq)]
    pub struct Color {
        /// Controller body color. ex. [30, 220, 0] (Splatoon2 green)
        pub body: [u8; 3],
        pub buttons: [u8; 3],
        pub left_grip: Option<[u8; 3]>,
        pub right_grip: Option<[u8; 3]>,
    }

    impl From<[u8; 12]> for Color {
        fn from(array: [u8; 12]) -> Self {
            let body = [array[0], array[1], array[2]];
            let buttons = [array[3], array[4], array[5]];
            let left_grip = if array[6..9].iter().all(|a| a == &0xFF) {
                None
            } else {
                Some([array[6], array[7], array[8]])
            };
            let right_grip = if array[9..12].iter().all(|a| a == &0xFF) {
                None
            } else {
                Some([array[9], array[10], array[11]])
            };

            Color {
                body,
                buttons,
                left_grip,
                right_grip,
            }
        }
    }

    pub fn get_color(device: &HidDevice) -> Option<Color> {
        device.write(&[0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x50, 0x60, 0, 0, 12])
            .ok()?;

        for _ in 0..5 {
            let mut buf = [0u8; 64];
            device.read_timeout(&mut buf, 20)
                .ok()?;

            match buf[14..20] {
                [0x10, 0x50, 0x60, 0, 0, 12] => {}
                _ => continue,
            }

            let mut report = [0u8; 12];
            report.copy_from_slice(&buf[20..32]);

            return Some(Color::from(report));
        }

        None
    }
}


pub struct JoyConDevice {
    hid_device: Option<HidDevice>,
    serial_number: String,
    device_type: JoyConDeviceType,
    stick_parameters: calibration::stick::StickParameters,
    stick_factory_calibration: calibration::stick::JoyConSticksCalibration,
    stick_user_calibration: calibration::stick::JoyConSticksCalibration,
    imu_offsets: calibration::imu::IMUOffsets,
    imu_factory_calibration: calibration::imu::IMUCalibration,
    imu_user_calibration: calibration::imu::IMUCalibration,
    color: color::Color,
}

impl JoyConDevice {
    pub const VENDOR_ID: u16 = 1406;
    pub const PRODUCT_ID_JOYCON_L: u16 = 8198;
    pub const PRODUCT_ID_JOYCON_R: u16 = 8199;
    pub const PRODUCT_ID_PROCON: u16 = 8201;

    pub fn check_type_of_device(device_info: &DeviceInfo) -> JoyConResult<JoyConDeviceType> {
        if device_info.vendor_id() != JoyConDevice::VENDOR_ID {
            return Err(JoyConDeviceError::InvalidVendorID(device_info.vendor_id()).into());
        }

        match device_info.product_id() {
            JoyConDevice::PRODUCT_ID_JOYCON_L => Ok(JoyConDeviceType::JoyConL),
            JoyConDevice::PRODUCT_ID_JOYCON_R => Ok(JoyConDeviceType::JoyConR),
            JoyConDevice::PRODUCT_ID_PROCON => Ok(JoyConDeviceType::ProCon),
            other => Err(JoyConDeviceError::InvalidProductID(other).into()),
        }
    }

    pub fn is_connected(&self) -> bool {
        self.hid_device.is_some()
    }

    pub fn serial_number(&self) -> &str {
        &self.serial_number
    }

    pub fn stick_parameters(&self) -> &calibration::stick::StickParameters {
        &self.stick_parameters
    }

    pub fn stick_factory_calibration(&self) -> &calibration::stick::JoyConSticksCalibration {
        &self.stick_factory_calibration
    }

    pub fn stick_user_calibration(&self) -> &calibration::stick::JoyConSticksCalibration {
        &self.stick_user_calibration
    }

    pub fn imu_offsets(&self) -> &calibration::imu::IMUOffsets {
        &self.imu_offsets
    }

    pub fn imu_factory_calibration(&self) -> &calibration::imu::IMUCalibration {
        &self.imu_factory_calibration
    }

    pub fn imu_user_calibration(&self) -> &calibration::imu::IMUCalibration {
        &self.imu_user_calibration
    }

    pub fn color(&self) -> &color::Color { &self.color }

    /// Set blocking mode.
    ///
    /// # Notice
    /// If you are using non-blocking mode,
    /// it is more likely to fail to validate the sub command reply.
    pub fn set_blocking_mode(&self, blocking: bool) -> JoyConResult<()> {
        if let Some(hid_device) = &self.hid_device {
            Ok(hid_device.set_blocking_mode(blocking)?)
        } else {
            Err(JoyConError::Disconnected)
        }
    }

    pub fn device_type(&self) -> JoyConDeviceType {
        self.device_type.clone()
    }

    pub fn reset_device(&mut self, hid_device: HidDevice) {
        self.hid_device = Some(hid_device);
    }

    pub fn forget_device(&mut self) {
        self.hid_device = None;
    }

    pub fn new(device_info: &DeviceInfo, hidapi: &HidApi) -> JoyConResult<Self> {
        let device_type = Self::check_type_of_device(device_info)?;

        let serial = device_info.serial_number().unwrap_or("");
        let hid_device = hidapi.open_serial(device_info.vendor_id(),
                                            device_info.product_id(),
                                            serial)?;
        let stick_parameters = calibration::stick::get_parameters(&hid_device)
            .ok_or(JoyConDeviceError::FailedStickParameterLoading)?;
        let stick_factory_calibration = calibration::stick::get_factory_calibration(&hid_device)
            .ok_or(JoyConDeviceError::FailedStickCalibrationLoading)?;
        let stick_user_calibration = calibration::stick::get_user_calibration(&hid_device)
            .ok_or(JoyConDeviceError::FailedStickCalibrationLoading)?;
        let imu_offsets = calibration::imu::get_offsets(&hid_device)
            .ok_or(JoyConDeviceError::FailedIMUOffsetsLoading)?;
        let imu_factory_calibration = calibration::imu::get_factory_calibration(&hid_device)
            .ok_or(JoyConDeviceError::FailedIMUCalibrationLoading)?;
        let imu_user_calibration = calibration::imu::get_user_calibration(&hid_device)
            .ok_or(JoyConDeviceError::FailedIMUCalibrationLoading)?;
        let color = color::get_color(&hid_device)
            .ok_or(JoyConDeviceError::FailedColorLoading)?;

        Ok(
            JoyConDevice {
                hid_device: Some(hid_device),
                serial_number: serial.to_string(),
                device_type,
                stick_parameters,
                stick_factory_calibration,
                stick_user_calibration,
                imu_offsets,
                imu_factory_calibration,
                imu_user_calibration,
                color,
            }
        )
    }

    pub fn write(&self, data: &[u8]) -> JoyConResult<usize> {
        if let Some(hid_device) = &self.hid_device {
            Ok(hid_device.write(data)?)
        } else {
            Err(JoyConError::Disconnected)
        }
    }

    pub fn read(&self, buf: &mut [u8]) -> JoyConResult<usize> {
        if let Some(hid_device) = &self.hid_device {
            let res = hid_device.read(buf)?;

            if buf.iter().all(|e| e == &0) {
                Err(JoyConReportError::EmptyReport.into())
            } else {
                Ok(res)
            }
        } else {
            Err(JoyConError::Disconnected)
        }
    }

    /// * timeout - milli seconds
    pub fn read_timeout(&self, buf: &mut [u8], timeout: i32) -> JoyConResult<usize> {
        if let Some(hid_device) = &self.hid_device {
            let res = hid_device.read_timeout(buf, timeout)?;

            if buf.iter().all(|e| e == &0) {
                Err(JoyConReportError::EmptyReport.into())
            } else {
                Ok(res)
            }
        } else {
            Err(JoyConError::Disconnected)
        }
    }
}

impl Debug for JoyConDevice {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "JoyConDevice {{ hid_device: {}, serial_number: {}, device_type: {:?}, stick_parameters: {:?}, , stick_factory_calibration: {:?}, stick_user_calibration: {:?}, imu_offsets: {:?}, imu_factory_calibration: {:?}, imu_user_calibration: {:?}, color: {:?} }}",
                 if self.is_connected() {
                     "Connected"
                 } else { "Disconnected" },
                 &self.serial_number,
                 &self.device_type,
                 &self.stick_parameters,
                 &self.stick_factory_calibration,
                 &self.stick_user_calibration,
                 &self.imu_offsets,
                 &self.imu_factory_calibration,
                 &self.imu_user_calibration,
                 &self.color,
        )
    }
}

impl<'a> TryInto<&'a HidDevice> for &'a JoyConDevice {
    type Error = JoyConError;

    fn try_into(self) -> Result<&'a HidDevice, Self::Error> {
        self.hid_device.as_ref()
            .ok_or(JoyConError::Disconnected)
    }
}