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

use std::{
    ffi::c_void,
    sync::{Arc, Mutex, PoisonError},
    time::Instant,
    path::Path
};

#[cfg(windows)]
use winreg::enums::*;

#[cfg(windows)]
use winreg::{RegKey, RegValue};


use j2534_rust::{
    ConnectFlags, FilterType, IoctlID, Loggable, PassthruError, Protocol, TxFlag, PASSTHRU_MSG,
};

use crate::channel::{
    CanChannel, CanFrame, ChannelError, ChannelResult, IsoTPChannel, IsoTPSettings, Packet,
    PacketChannel, PayloadChannel,
};

use self::lib_funcs::PassthruDrv;

use super::{HardwareCapabilities, HardwareError, HardwareInfo, HardwareResult};

mod lib_funcs;

/// Device scanner for Passthru supported devices
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PassthruScanner {
    devices: Vec<PassthruInfo>,
}

impl std::default::Default for PassthruScanner {
    fn default() -> Self {
        Self::new()
    }
}

impl PassthruScanner {
    #[cfg(unix)]
    /// Creates a passthru scanner. Scanning is done
    /// by scanning the ~/.passthru folder on the users PC for supported passthru
    /// JSON entries. This is UNOFFICIAL and should be considered experimental
    /// as Passthru API does not out of the box support UNIX Operating systems.
    pub fn new() -> Self {
        match std::fs::read_dir(shellexpand::tilde("~/.passthru").to_string()) {
            Ok(list) => {
                Self {
                    devices: list
                        .into_iter()
                        // Remove files that cannot be read
                        .filter_map(|p| p.ok())
                        // Filter any files that are not json files
                        .filter(|p| p.file_name().to_str().unwrap().ends_with(".json"))
                        // Attempt to read a PassthruDevice from each json file found
                        .map(|p| PassthruInfo::new(&p.path()))
                        // Keep Oks that were found, any entries that ended with errors are discarded
                        .filter_map(|s| s.ok())
                        // Convert result into vector
                        .collect(),
                }
            }
            Err(_) => Self {
                devices: Vec::new(),
            },
        }
    }

    #[cfg(windows)]
    /// Creates a passthru scanner. This scanner scans for devices by checking
    /// the windows registry entry `HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\PassthruSupport.04.04`
    pub fn new() -> Self {
        match RegKey::predef(HKEY_LOCAL_MACHINE)
            .open_subkey("SOFTWARE\\WOW6432Node\\PassThruSupport.04.04")
        {
            Ok(r) => {
                Self {
                    devices: r
                    .enum_keys()
                    .into_iter()
                    .filter_map(|e| e.ok())
                    .map(|key| r.open_subkey(key))
                    .map(|x| PassthruInfo::new(&x.unwrap()))
                    .filter_map(|d| d.ok())
                    .collect()
                }
            },
            Err(_) => Self {
                devices: Vec::new(),
            },
        }
    }
}

impl super::HardwareScanner<PassthruDevice> for PassthruScanner {
    fn list_devices(&self) -> Vec<super::HardwareInfo> {
        self.devices.iter().map(|x| x.into()).collect()
    }

    fn open_device_by_index(
        &self,
        idx: usize,
    ) -> super::HardwareResult<Arc<Mutex<PassthruDevice>>> {
        match self.devices.get(idx) {
            Some(info) => Ok(Arc::new(Mutex::new(PassthruDevice::open_device(info)?))),
            None => Err(HardwareError::DeviceNotFound),
        }
    }

    fn open_device_by_name(&self, name: &str) -> super::HardwareResult<Arc<Mutex<PassthruDevice>>> {
        match self.devices.iter().find(|s| s.name == name) {
            Some(info) => Ok(Arc::new(Mutex::new(PassthruDevice::open_device(info)?))),
            None => Err(HardwareError::DeviceNotFound),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct PassthruInfo {
    name: String,
    vendor: String,
    function_lib: String,
    can: bool,
    iso15765: bool,
    iso14230: bool,
    iso9141: bool,
    j1850pwm: bool,
    j1850vpw: bool,
    sci_a_engine: bool,
    sci_b_engine: bool,
    sci_a_trans: bool,
    sci_b_trans: bool,
}

impl PassthruInfo {
    #[cfg(unix)]
    pub fn new(path: &Path) -> HardwareResult<Self> {

        return if let Ok(s) = std::fs::read_to_string(&path) {
            if let Ok(json) = serde_json::from_str::<serde_json::Value>(s.as_str()) {
                let lib = json["FUNCTION_LIB"].as_str().unwrap_or("UNKNOWN PASSTHRU DEVICE FUNCTION LIB");
                let name = json["NAME"].as_str().unwrap_or("UNKNOWN PASSTHRU DEVICE");
                let vend = json["VENDOR"].as_str().unwrap_or("UNKNOWN PASSTHRU DEVICE VENDOR");
                Ok(PassthruInfo {
                    function_lib: String::from(lib),
                    name: String::from(name),
                    vendor: String::from(vend),
                    can: Self::read_bool(&json, "CAN"),
                    iso15765: Self::read_bool(&json, "ISO15765"),
                    iso14230: Self::read_bool(&json, "ISO14230"),
                    iso9141: Self::read_bool(&json, "ISO9141"),
                    j1850pwm: Self::read_bool(&json, "J1850PWM"),
                    j1850vpw: Self::read_bool(&json, "J1850VPW"),
                    sci_a_engine: Self::read_bool(&json, "SCI_A_ENGINE"),
                    sci_a_trans: Self::read_bool(&json, "SCN_A_TRANS"),
                    sci_b_engine: Self::read_bool(&json, "SCI_B_ENGINE"),
                    sci_b_trans: Self::read_bool(&json, "SCI_B_TRANS"),
                })
            } else {
                return Err(HardwareError::DeviceNotFound);
            }
        } else {
            Err(HardwareError::DeviceNotFound)
        };
    }

    #[cfg(unix)]
    #[inline]
    fn read_bool(j: &serde_json::Value, s: &str) -> bool {
        j[s].as_bool().unwrap_or(false)
    }


    #[cfg(windows)]
    pub fn new(r: &RegKey) -> HardwareResult<Self> {
        let lib: String = match r.get_value("FunctionLibrary") {
            Ok(s) => s,
            Err(_) => "UNKNOWN PASSTHRU DEVICE FUNCTION LIB".into(),
        };

        let name: String = match r.get_value("Name") {
            Ok(s) => s,
            Err(_) => "UNKNOWN PASSTHRU DEVICE".into(),
        };

        let vend: String = match r.get_value("Vendor") {
            Ok(s) => s,
            Err(_) => "UNKNOWN PASSTHRU DEVICE VENDOR".into(),
        };

        Ok(PassthruInfo {
            function_lib: String::from(lib),
            name: String::from(name),
            vendor: String::from(vend),
            can: Self::read_bool(&r, "CAN"),
            iso15765: Self::read_bool(&r, "ISO15765"),
            iso14230: Self::read_bool(&r, "ISO14230"),
            iso9141: Self::read_bool(&r, "ISO9141"),
            j1850pwm: Self::read_bool(&r, "J1850PWM"),
            j1850vpw: Self::read_bool(&r, "J1850VPW"),
            sci_a_engine: Self::read_bool(&r, "SCI_A_ENGINE"),
            sci_a_trans: Self::read_bool(&r, "SCN_A_TRANS"),
            sci_b_engine: Self::read_bool(&r, "SCI_B_ENGINE"),
            sci_b_trans: Self::read_bool(&r, "SCI_B_TRANS"),
        })
    }

    #[cfg(windows)]
    #[inline]
    fn read_bool(k: &RegKey, name: &str) -> bool {
        let val: u32 = match k.get_value(name.to_string()) {
            Ok(b) => b,
            Err(_) => return false,
        };
        return val != 0;
    }
}

impl From<&PassthruInfo> for HardwareInfo {
    fn from(x: &PassthruInfo) -> Self {
        HardwareInfo {
            name: x.name.clone(),
            vendor: x.vendor.clone(),
            capabilities: HardwareCapabilities {
                iso_tp: x.iso15765,
                can: x.can,
                kline: x.iso9141,
                kline_kwp: x.iso14230,
                sae_j1850: x.j1850pwm && x.j1850vpw,
                sci: x.sci_a_engine && x.sci_a_trans && x.sci_b_engine && x.sci_b_trans,
                ip: false, // Passthru never supports this protocol
            },
        }
    }
}

/// Passthru device
#[derive(Debug)]
pub struct PassthruDevice {
    info: HardwareInfo,
    drv: PassthruDrv,
    device_idx: Option<u32>,
    can_channel: bool,
}

impl PassthruDevice {
    /// Opens the passthru device
    fn open_device(info: &PassthruInfo) -> HardwareResult<Self> {
        let lib = info.function_lib.clone();
        let mut drv = lib_funcs::PassthruDrv::load_lib(lib)?;
        let idx = drv.open()?;
        Ok(Self {
            info: info.into(),
            drv,
            device_idx: Some(idx),
            can_channel: false,
        })
    }

    pub(crate) fn safe_passthru_op<
        X,
        T: FnOnce(u32, PassthruDrv) -> lib_funcs::PassthruResult<X>,
    >(
        &self,
        f: T,
    ) -> HardwareResult<X> {
        match self.device_idx {
            Some(idx) => match f(idx, self.drv.clone()) {
                Ok(res) => Ok(res),
                Err(e) => {
                    if e == PassthruError::ERR_FAILED {
                        // Err failed, query the adapter for error!
                        if let Ok(reason) = self.drv.get_last_error() {
                            Err(HardwareError::APIError {
                                code: e as u32,
                                desc: reason,
                            })
                        } else {
                            // No reason, just ERR_FAILED
                            Err(e.into())
                        }
                    } else {
                        Err(e.into())
                    }
                }
            },
            None => Err(HardwareError::DeviceNotOpen),
        }
    }
}

impl Drop for PassthruDevice {
    #[allow(unused_must_use)] // If this function fails, then device is already closed, so don't care!
    fn drop(&mut self) {
        if let Some(idx) = self.device_idx {
            self.drv.close(idx);
            self.device_idx = None;
        }
    }
}

impl super::Hardware for PassthruDevice {
    fn create_iso_tp_channel(this: Arc<Mutex<Self>>) -> HardwareResult<Box<dyn IsoTPChannel>> {
        {
            let this = this.lock()?;
            if !this.info.capabilities.iso_tp {
                return Err(HardwareError::ChannelNotSupported);
            }
            if this.can_channel {
                return Err(HardwareError::ConflictingChannel);
            }
        }
        let iso_tp_channel = PassthruIsoTpChannel {
            device: this,
            channel_id: None,
            cfg: IsoTPSettings::default(),
            ids: (0, 0),
            cfg_complete: false,
        };
        Ok(Box::new(iso_tp_channel))
    }

    fn create_can_channel(this: Arc<Mutex<Self>>) -> HardwareResult<Box<dyn CanChannel>> {
        {
            let this = this.lock()?;
            if !this.info.capabilities.can {
                return Err(HardwareError::ChannelNotSupported);
            }
            if this.can_channel {
                return Err(HardwareError::ConflictingChannel);
            }
        }
        let can_channel = PassthruCanChannel {
            device: this,
            channel_id: None,
            baud: 0,
            use_ext: false,
        };
        Ok(Box::new(can_channel))
    }

    fn read_battery_voltage(&mut self) -> Option<f32> {
        let mut output: u32 = 0;
        match self.safe_passthru_op(|idx, drv: PassthruDrv| {
            drv.ioctl(
                idx,
                IoctlID::READ_VBATT,
                std::ptr::null_mut(),
                (&mut output) as *mut _ as *mut c_void,
            )
        }) {
            Ok(_) => Some(output as f32 / 1000.0),
            Err(_) => None,
        }
    }

    fn get_capabilities(&self) -> &super::HardwareCapabilities {
        &self.info.capabilities
    }
}

/// Passthru device CAN Channel
#[derive(Debug)]
pub struct PassthruCanChannel {
    pub(crate) device: Arc<Mutex<PassthruDevice>>,
    pub(crate) channel_id: Option<u32>,
    pub(crate) baud: u32,
    pub(crate) use_ext: bool,
}

impl PassthruCanChannel {
    fn get_channel_id(&self) -> ChannelResult<u32> {
        match self.channel_id {
            None => Err(ChannelError::NotOpen),
            Some(x) => Ok(x),
        }
    }
}

impl CanChannel for PassthruCanChannel {
    fn set_can_cfg(&mut self, baud: u32, use_extended: bool) -> crate::channel::ChannelResult<()> {
        self.baud = baud;
        self.use_ext = use_extended;
        Ok(())
    }
}

impl PacketChannel<CanFrame> for PassthruCanChannel {
    fn open(&mut self) -> crate::channel::ChannelResult<()> {
        let mut device = self.device.lock()?;
        // Already open, ignore request
        if self.channel_id.is_some() {
            return Ok(());
        }

        let mut flags = 0u32;
        if self.use_ext {
            flags |= ConnectFlags::CAN_29BIT_ID as u32;
        }
        // Initialize the interface
        let channel_id = device
            .safe_passthru_op(|device_id, device| {
                device.connect(device_id, Protocol::CAN, flags, self.baud)
            })
            .map_err(ChannelError::HardwareError)?;
        device.can_channel = true; // Acknowledge CAN is open now
        self.channel_id = Some(channel_id);

        // Now create open filter
        let mut mask = PASSTHRU_MSG {
            protocol_id: Protocol::CAN as u32,
            data_size: 4,
            ..Default::default()
        };

        let mut pattern = PASSTHRU_MSG {
            protocol_id: Protocol::CAN as u32,
            data_size: 4,
            ..Default::default()
        };

        // For open filter,
        // mask and pattern both need to be 0x0000
        //
        // CANID & 0x0000 == 0x0000
        mask.data[0..4].copy_from_slice(&[0x00, 0x00, 0x00, 0x00]);
        pattern.data[0..4].copy_from_slice(&[0x00, 0x00, 0x00, 0x00]);

        match device.safe_passthru_op(|_, device| {
            device.start_msg_filter(channel_id, FilterType::PASS_FILTER, &mask, &pattern, None)
        }) {
            Ok(_) => Ok(()), // Channel setup complete
            Err(e) => {
                // Oops! Teardown
                std::mem::drop(device);
                if let Err(e) = self.close() {
                    eprintln!("TODO PT close failed! {}", e)
                }
                Err(e.into())
            }
        }
    }
    fn close(&mut self) -> crate::channel::ChannelResult<()> {
        let mut device = self.device.lock()?;
        // Channel already closed, ignore request
        if self.channel_id.is_none() {
            return Ok(());
        }
        let id = self.get_channel_id().unwrap(); // Unwrap as we checked previously if none
        device
            .safe_passthru_op(|_, device| device.disconnect(id))
            .map_err(ChannelError::HardwareError)?;
        device.can_channel = false;
        self.channel_id = None;
        Ok(())
    }

    fn write_packets(
        &mut self,
        packets: Vec<CanFrame>,
        timeout_ms: u32,
    ) -> crate::channel::ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        let mut msgs: Vec<PASSTHRU_MSG> = packets.iter().map(|f| f.into()).collect();
        self.device
            .lock()?
            .safe_passthru_op(|_, device| device.write_messages(channel_id, &mut msgs, timeout_ms))
            .map_err(|e| e.into())
            .map(|_| ())
    }

    fn read_packets(
        &mut self,
        max: usize,
        timeout_ms: u32,
    ) -> crate::channel::ChannelResult<Vec<CanFrame>> {
        let channel_id = self.get_channel_id()?;
        match self
            .device
            .lock()?
            .safe_passthru_op(|_, device| device.read_messages(channel_id, max as u32, timeout_ms))
        {
            Ok(res) => Ok(res.iter().map(CanFrame::from).collect()),
            Err(e) => Err(e.into()),
        }
    }

    fn clear_rx_buffer(&mut self) -> crate::channel::ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        self.device
            .lock()?
            .safe_passthru_op(|_, device| {
                device.ioctl(
                    channel_id,
                    IoctlID::CLEAR_RX_BUFFER,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            })
            .map_err(|e| e.into())
    }

    fn clear_tx_buffer(&mut self) -> crate::channel::ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        self.device
            .lock()?
            .safe_passthru_op(|_, device| {
                device.ioctl(
                    channel_id,
                    IoctlID::CLEAR_TX_BUFFER,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            })
            .map_err(|e| e.into())
    }
}

impl Drop for PassthruCanChannel {
    #[allow(unused_must_use)]
    fn drop(&mut self) {
        // Close the channel before dropping!
        self.close();
    }
}

/// Passthru ISO TP Channel
#[derive(Debug)]
pub struct PassthruIsoTpChannel {
    device: Arc<Mutex<PassthruDevice>>,
    channel_id: Option<u32>,
    cfg: IsoTPSettings,
    ids: (u32, u32),
    cfg_complete: bool,
}

impl PassthruIsoTpChannel {
    fn get_channel_id(&self) -> ChannelResult<u32> {
        match self.channel_id {
            None => Err(ChannelError::NotOpen),
            Some(x) => Ok(x),
        }
    }
}

impl PayloadChannel for PassthruIsoTpChannel {
    fn open(&mut self) -> ChannelResult<()> {
        if self.channel_id.is_some() {
            return Ok(());
        }
        let mut flags = 0u32;
        if self.cfg.can_use_ext_addr {
            flags |= ConnectFlags::CAN_29BIT_ID as u32;
        }
        if self.cfg.extended_addressing {
            flags |= ConnectFlags::ISO15765_ADDR_TYPE as u32;
        }

        let mut device = self.device.lock()?;

        // Initialize the interface
        let channel_id = device
            .safe_passthru_op(|device_id, device| {
                device.connect(device_id, Protocol::ISO15765, flags, self.cfg.can_speed)
            })
            .map_err(ChannelError::HardwareError)?;
        device.can_channel = true; // Acknowledge CAN is open now
        self.channel_id = Some(channel_id);

        // Now create open filter
        let mut mask = PASSTHRU_MSG {
            protocol_id: Protocol::ISO15765 as u32,
            data_size: 4,
            ..Default::default()
        };

        let mut pattern = PASSTHRU_MSG {
            protocol_id: Protocol::ISO15765 as u32,
            data_size: 4,
            ..Default::default()
        };

        let mut flow_control = PASSTHRU_MSG {
            protocol_id: Protocol::ISO15765 as u32,
            data_size: 4,
            ..Default::default()
        };

        // 3 filters are to be configured like so:
        // Mask: 0xFFFF
        // Pattern: Recv ID
        // FC: Send ID
        mask.data[0..4].copy_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF]);
        pattern.data[0..4].copy_from_slice(&self.ids.1.to_be_bytes());
        flow_control.data[0..4].copy_from_slice(&self.ids.0.to_be_bytes());

        match device.safe_passthru_op(|_, device| {
            device.start_msg_filter(
                channel_id,
                FilterType::FLOW_CONTROL_FILTER,
                &mask,
                &pattern,
                Some(flow_control),
            )
        }) {
            Ok(_) => Ok(()), // Channel setup complete
            Err(e) => {
                // Oops! Teardown
                std::mem::drop(device);
                if let Err(e) = self.close() {
                    eprintln!("TODO PT close failed! {}", e)
                }
                Err(e.into())
            }
        }
    }

    fn close(&mut self) -> ChannelResult<()> {
        // Channel already closed, ignore request
        if self.channel_id.is_none() {
            return Ok(());
        }
        {
            let mut device = self.device.lock()?;
            let id = self.get_channel_id().unwrap(); // Unwrap as we checked previously if none
            device
                .safe_passthru_op(|_, device| device.disconnect(id))
                .map_err(ChannelError::HardwareError)?;
            device.can_channel = false;
            self.channel_id = None;
        }
        Ok(())
    }

    fn set_ids(&mut self, send: u32, recv: u32) -> ChannelResult<()> {
        self.ids = (send, recv);
        Ok(())
    }

    fn read_bytes(&mut self, timeout_ms: u32) -> ChannelResult<Vec<u8>> {
        let channel_id = self.get_channel_id()?;
        let start = Instant::now();
        let timeout = std::cmp::max(1, timeout_ms); // Need 1ms minimum
        while start.elapsed().as_millis() <= timeout as u128 {
            let read = self
                .device
                .lock()?
                .safe_passthru_op(|_, device| device.read_messages(channel_id, 1, 0))
                .map_err(ChannelError::HardwareError)?;
            if let Some(msg) = read.get(0) {
                // Ignore messages with length of 4 as these
                // are Tx confirm or Rx confirm messages with Passthru API's ISO-TP
                if msg.data_size != 4 {
                    // Read complete!
                    // First 4 bytes are CAN ID, so ignore those
                    return Ok(msg.data[4..msg.data_size as usize].to_vec());
                }
            }
        }
        if timeout_ms == 0 {
            Err(ChannelError::BufferEmpty)
        } else {
            Err(ChannelError::ReadTimeout)
        }
    }

    fn write_bytes(&mut self, addr: u32, buffer: &[u8], timeout_ms: u32) -> ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        let mut write_msg = PASSTHRU_MSG {
            protocol_id: Protocol::ISO15765 as u32,
            data_size: 4 + buffer.len() as u32, // First 4 bytes are CAN ID
            ..Default::default()
        };

        let mut tx_flags = 0u32;
        if self.cfg.can_use_ext_addr {
            tx_flags |= TxFlag::CAN_29BIT_ID.bits();
        }
        if self.cfg.pad_frame {
            tx_flags |= TxFlag::ISO15765_FRAME_PAD.bits();
        }
        if self.cfg.extended_addressing {
            tx_flags |= TxFlag::ISO15765_EXT_ADDR.bits();
        }

        write_msg.tx_flags = tx_flags;
        write_msg.data[0] = (addr >> 24) as u8;
        write_msg.data[1] = (addr >> 16) as u8;
        write_msg.data[2] = (addr >> 8) as u8;
        write_msg.data[3] = addr as u8;
        write_msg.data[4..4 + buffer.len()].copy_from_slice(buffer);

        // Now transmit our message!

        self.device
            .lock()?
            .safe_passthru_op(|_, device| {
                device.write_messages(channel_id, &mut [write_msg], timeout_ms)
            })
            .map_err(ChannelError::HardwareError)
            .map(|_| ())
    }

    fn clear_rx_buffer(&mut self) -> ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        self.device
            .lock()?
            .safe_passthru_op(|_, device| {
                device.ioctl(
                    channel_id,
                    IoctlID::CLEAR_RX_BUFFER,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            })
            .map_err(|e| e.into())
    }

    fn clear_tx_buffer(&mut self) -> ChannelResult<()> {
        let channel_id = self.get_channel_id()?;
        self.device
            .lock()?
            .safe_passthru_op(|_, device| {
                device.ioctl(
                    channel_id,
                    IoctlID::CLEAR_TX_BUFFER,
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                )
            })
            .map_err(|e| e.into())
    }
}

impl<'a> IsoTPChannel for PassthruIsoTpChannel {
    fn set_iso_tp_cfg(&mut self, cfg: crate::channel::IsoTPSettings) -> ChannelResult<()> {
        self.cfg_complete = true;
        self.cfg = cfg;
        Ok(())
    }
}

impl<'a> Drop for PassthruIsoTpChannel {
    #[allow(unused_must_use)]
    fn drop(&mut self) {
        // Close the channel before dropping!
        self.close();
    }
}

impl From<&CanFrame> for PASSTHRU_MSG {
    fn from(frame: &CanFrame) -> Self {
        let mut f = PASSTHRU_MSG::default();
        if frame.is_extended() {
            f.tx_flags |= TxFlag::CAN_29BIT_ID.bits();
        }
        f.protocol_id = Protocol::CAN as u32;
        f.data_size = (frame.get_data().len() + 4) as u32;
        f.data[0] = (frame.get_address() >> 24) as u8;
        f.data[1] = (frame.get_address() >> 16) as u8;
        f.data[2] = (frame.get_address() >> 8) as u8;
        f.data[3] = frame.get_address() as u8;
        f.data[4..4 + frame.get_data().len()].copy_from_slice(frame.get_data());
        f
    }
}

impl From<&PASSTHRU_MSG> for CanFrame {
    fn from(msg: &PASSTHRU_MSG) -> CanFrame {
        let id = (msg.data[0] as u32) << 24
            | (msg.data[1] as u32) << 16
            | (msg.data[2] as u32) << 8
            | (msg.data[3] as u32);
        let data = &msg.data[4..msg.data_size as usize];
        let is_ext = msg.tx_flags & TxFlag::CAN_29BIT_ID.bits() != 0;
        CanFrame::new(id, data, is_ext)
    }
}

impl From<j2534_rust::PassthruError> for HardwareError {
    fn from(err: j2534_rust::PassthruError) -> Self {
        HardwareError::APIError {
            code: err as u32,
            desc: err.to_string().into(),
        }
    }
}

impl<T> From<PoisonError<T>> for ChannelError {
    fn from(_x: PoisonError<T>) -> Self {
        ChannelError::HardwareError(HardwareError::APIError {
            code: 99,
            desc: "PoisonError".into(),
        })
    }
}

impl<T> From<PoisonError<T>> for HardwareError {
    fn from(_x: PoisonError<T>) -> Self {
        HardwareError::APIError {
            code: 99,
            desc: "PoisonError".into(),
        }
    }
}