Skip to main content

j2534_mrw/
lib.rs

1//! SAE J2534 PassThru defines a standard library interface for communicating with vehicle control modules.
2//! All automakers in the US are required to provide J2534-compatible service software.
3//! J2534 provides access to the communication layers required for accessing vehicle diagnostics services as
4//! well as downloading and reflashing control modules.
5//!
6//! ### Example
7//! ```rust
8//! use j2534::{Interface, PassThruMsg, Protocol, ConnectFlags, RxStatus, TxFlags};
9//!
10//! fn main() -> j2534::Result<()> {
11//!     // Open the library and connect to a device
12//!     let interface = Interface::new("C:\\device.dll")?;
13//!     let device = interface.open_any()?;
14//!
15//!     // Create a CAN channel
16//!     let channel = device
17//!         .connect(Protocol::CAN, ConnectFlags::NONE, 500000)
18//!         .unwrap();
19//!
20//!     // Create a new message with an arbitration id of `8` and payload of `[0, 1, 2, 3]`.
21//!     let message = PassThruMsg::new_can(8, &[0, 1, 2, 3]);
22//!     channel.write(&mut [message], 1000)?;
23//!     Ok(())
24//! }
25//! ```
26
27#[macro_use]
28extern crate bitflags;
29
30use std::ffi::OsStr;
31use std::ffi::{self, CStr, CString};
32use std::fmt;
33use std::fmt::Debug;
34use std::io;
35use std::marker::PhantomData;
36use std::path::Path;
37use std::str::Utf8Error;
38
39use bitflags::_core::fmt::Formatter;
40use libloading::{Library, Symbol};
41
42use num_derive::{FromPrimitive, ToPrimitive};
43use num_traits::FromPrimitive;
44#[cfg(windows)]
45use winreg::{enums::*, RegKey};
46
47#[derive(thiserror::Error, Debug)]
48pub enum Error {
49    #[error("success")]
50    NoError,
51    #[error("option not supported')")]
52    NotSupported,
53    #[error("invalid channel id")]
54    InvalidChannelId,
55    #[error("invalid protocol id")]
56    InvalidProtocolId,
57    #[error("NULL was incorrectly passed as a parameter")]
58    NullParameter,
59    #[error("invalid ioctl parameter")]
60    InvalidIoctlValue,
61    #[error("invalid flags")]
62    InvalidFlags,
63    #[error("unspecified error")]
64    Failed,
65    #[error("a PassThru device is not connected")]
66    DeviceNotConnected,
67    #[error("timed out")]
68    Timeout,
69    #[error("invalid message")]
70    InvalidMessage,
71    #[error("invalid time interval")]
72    InvalidTimeInterval,
73    #[error("exceeded message limit")]
74    ExceededLimit,
75    #[error("invalid message id")]
76    InvalidMessageId,
77    #[error("device in use")]
78    DeviceInUse,
79    #[error("invalid ioctl id")]
80    InvalidIoctlId,
81    /// Could not read any messages from the vehicle network
82    #[error("could not read messages")]
83    BufferEmpty,
84    #[error("transmit queue full")]
85    BufferFull,
86    /// Receive buffer overflowed and messages were lost
87    #[error("receive buffer overflowed")]
88    BufferOverflow,
89    #[error("unknown pin number or resource in use")]
90    PinInvalid,
91    #[error("channel already in use")]
92    ChannelInUse,
93    #[error("message protocol does not match channel protocol")]
94    MessageProtocolId,
95    #[error("invalid filter id")]
96    InvalidFilterId,
97    #[error("no flow control filter matches outgoing message")]
98    NoFlowControl,
99    #[error("filter already exists")]
100    NotUnique,
101    #[error("unsupported baudrate")]
102    InvalidBaudrate,
103    #[error("invalid device id")]
104    InvalidDeviceId,
105    #[error("unknown j2534 error code {0}")]
106    Unknown(i32),
107}
108
109impl FromPrimitive for Error {
110    fn from_i64(n: i64) -> Option<Self> {
111        todo!()
112    }
113
114    fn from_u64(n: u64) -> Option<Self> {
115        todo!()
116    }
117}
118
119impl Error {
120    pub fn from_code(code: i32) -> Error {
121        match code {
122            0x00 => Error::NoError,
123            0x01 => Error::NotSupported,
124            0x02 => Error::InvalidChannelId,
125            0x03 => Error::InvalidProtocolId,
126            0x04 => Error::NullParameter,
127            0x05 => Error::InvalidIoctlValue,
128            0x06 => Error::InvalidFlags,
129            0x07 => Error::Failed,
130            0x08 => Error::DeviceNotConnected,
131            0x09 => Error::Timeout,
132            0x0A => Error::InvalidMessage,
133            0x0B => Error::InvalidTimeInterval,
134            0x0C => Error::ExceededLimit,
135            0x0D => Error::InvalidMessageId,
136            0x0E => Error::DeviceInUse,
137            0x0F => Error::InvalidIoctlId,
138            0x10 => Error::BufferEmpty,
139            0x11 => Error::BufferFull,
140            0x12 => Error::BufferOverflow,
141            0x13 => Error::PinInvalid,
142            0x14 => Error::ChannelInUse,
143            0x15 => Error::MessageProtocolId,
144            0x16 => Error::InvalidFilterId,
145            0x17 => Error::NoFlowControl,
146            0x18 => Error::NotUnique,
147            0x19 => Error::InvalidBaudrate,
148            0x1A => Error::InvalidDeviceId,
149            other => Error::Unknown(other),
150        }
151    }
152
153    pub fn as_code(&self) -> i32 {
154        match *self {
155            Error::NoError => 0x00,
156            Error::NotSupported => 0x01,
157            Error::InvalidChannelId => 0x02,
158            Error::InvalidProtocolId => 0x03,
159            Error::NullParameter => 0x04,
160            Error::InvalidIoctlValue => 0x05,
161            Error::InvalidFlags => 0x06,
162            Error::Failed => 0x07,
163            Error::DeviceNotConnected => 0x08,
164            Error::Timeout => 0x09,
165            Error::InvalidMessage => 0x0A,
166            Error::InvalidTimeInterval => 0x0B,
167            Error::ExceededLimit => 0x0C,
168            Error::InvalidMessageId => 0x0D,
169            Error::DeviceInUse => 0x0E,
170            Error::InvalidIoctlId => 0x0F,
171            Error::BufferEmpty => 0x10,
172            Error::BufferFull => 0x11,
173            Error::BufferOverflow => 0x12,
174            Error::PinInvalid => 0x13,
175            Error::ChannelInUse => 0x14,
176            Error::MessageProtocolId => 0x15,
177            Error::InvalidFilterId => 0x16,
178            Error::NoFlowControl => 0x17,
179            Error::NotUnique => 0x18,
180            Error::InvalidBaudrate => 0x19,
181            Error::InvalidDeviceId => 0x1A,
182            Error::Unknown(n) => n,
183        }
184    }
185}
186
187pub type PassThruOpenFn =
188    unsafe extern "stdcall" fn(name: *const libc::c_void, device_id: *mut u32) -> i32;
189pub type PassThruCloseFn = unsafe extern "stdcall" fn(device_id: u32) -> i32;
190pub type PassThruConnectFn = unsafe extern "stdcall" fn(
191    device_id: u32,
192    protocol_id: u32,
193    flags: u32,
194    baudrate: u32,
195    channel_id: *mut u32,
196) -> i32;
197pub type PassThruDisconnectFn = unsafe extern "stdcall" fn(channel_id: u32) -> i32;
198pub type PassThruReadMsgsFn = unsafe extern "stdcall" fn(
199    channel_id: u32,
200    msgs: *mut PassThruMsg,
201    num_msgs: *mut u32,
202    timeout: u32,
203) -> i32;
204pub type PassThruWriteMsgsFn = unsafe extern "stdcall" fn(
205    channel_id: u32,
206    msgs: *mut PassThruMsg,
207    num_msgs: *mut u32,
208    timeout: u32,
209) -> i32;
210pub type PassThruStartPeriodicMsgFn = unsafe extern "stdcall" fn(
211    channel_id: u32,
212    msg: *const PassThruMsg,
213    msg_id: *mut u32,
214    time_interval: u32,
215) -> i32;
216pub type PassThruStopPeriodicMsgFn = unsafe extern "stdcall" fn(channel_id: u32, msg_id: u32) -> i32;
217pub type PassThruStartMsgFilterFn = unsafe extern "stdcall" fn(
218    channel_id: u32,
219    filter_type: u32,
220    msg_mask: *const PassThruMsg,
221    pattern_msg: *const PassThruMsg,
222    flow_control_msg: *const PassThruMsg,
223    filter_id: *mut u32,
224) -> i32;
225pub type PassThruStopMsgFilterFn = unsafe extern "stdcall" fn(channel_id: u32, filter_id: u32) -> i32;
226pub type PassThruSetProgrammingVoltageFn =
227    unsafe extern "stdcall" fn(device_id: u32, pin_number: u32, voltage: u32) -> i32;
228pub type PassThruReadVersionFn = unsafe extern "stdcall" fn(
229    device_id: u32,
230    firmware_version: *mut libc::c_char,
231    dll_version: *mut libc::c_char,
232    api_version: *mut libc::c_char,
233) -> i32;
234pub type PassThruGetLastErrorFn =
235    unsafe extern "stdcall" fn(error_description: *mut libc::c_char) -> i32;
236pub type PassThruIoctlFn = unsafe extern "stdcall" fn(
237    handle_id: u32,
238    ioctl_id: u32,
239    input: *mut libc::c_void,
240    output: *mut libc::c_void,
241) -> i32;
242
243// Much of the descriptions and APIs used here were taken from http://www.drewtech.com/support/passthru.html
244
245#[derive(Copy, Clone)]
246#[repr(C, packed(1))]
247/// A message sent a received from the device
248pub struct PassThruMsg {
249    pub protocol_id: u32,
250    pub rx_status: u32,
251    pub tx_flags: u32,
252    pub timestamp: u32,
253    pub data_size: u32,
254    pub extra_data_index: u32,
255    pub data: [u8; 4128],
256}
257
258#[repr(C, packed(1))]
259struct SConfig {
260    parameter: u32,
261    value: u32,
262}
263
264#[repr(C, packed(1))]
265struct SConfigList {
266    size: u32,
267    config_ptr: *const SConfig,
268}
269
270#[repr(C, packed(1))]
271struct SByteArray {
272    size: u32,
273    byte_ptr: *const u8,
274}
275
276impl PassThruMsg {
277    pub fn new_raw(
278        protocol: Protocol,
279        rx_status: RxStatus,
280        tx_flags: TxFlags,
281        timestamp: u32,
282        data_size: u32,
283        extra_data_index: u32,
284        data: [u8; 4128],
285    ) -> PassThruMsg {
286        PassThruMsg {
287            protocol_id: protocol as u32,
288            rx_status: rx_status.bits,
289            tx_flags: tx_flags.bits,
290            timestamp,
291            data_size,
292            extra_data_index,
293            data,
294        }
295    }
296
297    pub fn new(protocol: Protocol) -> PassThruMsg {
298        PassThruMsg {
299            protocol_id: protocol as u32,
300            rx_status: 0,
301            tx_flags: 0,
302            timestamp: 0,
303            data_size: 0,
304            extra_data_index: 0,
305            data: [0; 4128],
306        }
307    }
308
309    /// Creates a new CAN message.
310    /// The data size must be less than or equal to 8 bytes.
311    pub fn new_can(id: u32, data: &[u8]) -> PassThruMsg {
312        let mut msg_data = [0_u8; 4128];
313        // Copy arbitration ID
314        msg_data[0] = ((id >> 24) & 0xFF) as u8;
315        msg_data[1] = ((id >> 16) & 0xFF) as u8;
316        msg_data[2] = ((id >> 8) & 0xFF) as u8;
317        msg_data[3] = (id & 0xFF) as u8;
318
319        // Copy the message
320        &mut msg_data[4..data.len() + 4].copy_from_slice(data);
321
322        PassThruMsg {
323            data: msg_data,
324            data_size: (data.len() + 4) as u32,
325            ..Self::new(Protocol::CAN)
326        }
327    }
328
329    /// Creates a new ISO 15765-2 (ISO-TP) message.
330    /// ISO-TP is a transport-layer protocol that uses multiple CAN messages to transmit
331    /// up to 4095 bytes per packet.
332    /// The data size must be less than or equal to 4095.
333    pub fn new_isotp(id: u32, data: &[u8]) -> PassThruMsg {
334        let mut msg_data = [0_u8; 4128];
335        // Copy arbitration ID
336        msg_data[0] = ((id >> 24) & 0xFF) as u8;
337        msg_data[1] = ((id >> 16) & 0xFF) as u8;
338        msg_data[2] = ((id >> 8) & 0xFF) as u8;
339        msg_data[3] = (id & 0xFF) as u8;
340
341        // Copy the message
342        &mut msg_data[4..data.len() + 4].copy_from_slice(data);
343
344        PassThruMsg {
345            data: msg_data,
346            data_size: (data.len() + 4) as u32,
347            ..Self::new(Protocol::ISO15765)
348        }
349    }
350
351    /// Returns the CAN ID and payload. Also use this method for reading ISO-TP messages.
352    /// Returns `None` if the protocol is not CAN or ISO15765 or if the message is too short.
353    pub fn can_message(&self) -> Option<(u32, &[u8])> {
354        if (self.protocol_id == (Protocol::CAN as u32)
355            || self.protocol_id == (Protocol::ISO15765 as u32))
356            && self.data_size >= 4
357        {
358            let id = ((self.data[0] as u32) << 24)
359                | ((self.data[1] as u32) << 16)
360                | ((self.data[2] as u32) << 8)
361                | (self.data[3] as u32);
362            Some((id, &self.data[4..self.data_size as usize]))
363        } else {
364            None
365        }
366    }
367
368    /// Alias to [`PassThruMsg::can_message`]
369    #[inline]
370    pub fn isotp_message(&self) -> Option<(u32, &[u8])> {
371        self.can_message()
372    }
373
374    /// Sets the rx status of the message
375    pub fn rx_status(mut self, rx_status: RxStatus) -> Self {
376        self.rx_status = rx_status.bits;
377        self
378    }
379
380    /// Sets the transmit flags of the message
381    pub fn tx_flags(mut self, tx_flags: TxFlags) -> Self {
382        self.tx_flags = tx_flags.bits;
383        self
384    }
385
386    /// Returns true if this is an echo of a message transmitted by
387    /// the PassThru device.
388    pub fn transmitted(&self) -> bool {
389        self.rx_status & (RxStatus::TX_MSG_TYPE).bits() != 0
390    }
391
392    /// Returns true if this message indicates the first frame of a ISO15765 packet
393    /// has been received.
394    pub fn first_frame(&self) -> bool {
395        self.rx_status & (RxStatus::ISO15765_FIRST_FRAME).bits() != 0
396    }
397}
398
399impl Default for PassThruMsg {
400    fn default() -> PassThruMsg {
401        PassThruMsg {
402            protocol_id: 0,
403            rx_status: 0,
404            tx_flags: 0,
405            timestamp: 0,
406            data_size: 0,
407            extra_data_index: 0,
408            data: [0; 4128],
409        }
410    }
411}
412
413impl Debug for PassThruMsg {
414    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
415        let protocol_id = self.protocol_id;
416        let rx_status = self.rx_status;
417        let tx_flags = self.tx_flags;
418        let timestamp = self.timestamp;
419        let extra_data_index = self.extra_data_index;
420        unsafe {
421            f.debug_struct("PassThruMsg")
422                .field("protocol_id", &protocol_id)
423                .field("rx_status", &rx_status)
424                .field("tx_flags", &tx_flags)
425                .field("timestamp", &timestamp)
426                .field("extra_data_index", &extra_data_index)
427                .field("data", &&self.data[..self.data_size as usize])
428                .finish()
429        }
430    }
431}
432
433/// Vehicle communication channel ID
434#[derive(Copy, Clone, Debug)]
435struct ChannelId(u32);
436
437/// Device ID
438#[derive(Copy, Clone, Debug)]
439struct DeviceId(u32);
440
441/// Periodic message ID
442#[derive(Copy, Clone, Debug)]
443pub struct MessageId(u32);
444
445/// Message filter ID
446#[derive(Copy, Clone, Debug)]
447pub struct FilterId(u32);
448
449/// A J2534 library
450pub struct Interface {
451    library: Library,
452
453    c_pass_thru_open: PassThruOpenFn,
454    c_pass_thru_close: PassThruCloseFn,
455    c_pass_thru_connect: PassThruConnectFn,
456    c_pass_thru_disconnect: PassThruDisconnectFn,
457    c_pass_thru_read_version: PassThruReadVersionFn,
458    c_pass_thru_get_last_error: PassThruGetLastErrorFn,
459    c_pass_thru_read_msgs: PassThruReadMsgsFn,
460    c_pass_thru_start_msg_filter: PassThruStartMsgFilterFn,
461    c_pass_thru_stop_msg_filter: PassThruStopMsgFilterFn,
462    c_pass_thru_write_msgs: PassThruWriteMsgsFn,
463    c_pass_thru_start_periodic_msg: PassThruStartPeriodicMsgFn,
464    c_pass_thru_stop_periodic_msg: PassThruStopPeriodicMsgFn,
465    c_pass_thru_set_programming_voltage: PassThruSetProgrammingVoltageFn,
466    c_pass_thru_ioctl: PassThruIoctlFn,
467
468    _marker: PhantomData<*mut ()>,
469}
470
471/// A device created with [`Interface::open`]
472pub struct Device<'a> {
473    interface: &'a Interface,
474    id: DeviceId,
475}
476
477/// A communication channel
478pub struct Channel<'a> {
479    device: &'a Device<'a>,
480    id: ChannelId,
481    protocol: Protocol,
482}
483
484impl Interface {
485    /// Returns a J2534 library given the path
486    ///
487    /// # Arguments
488    ///
489    /// * `path` - The absolute path to the J2534 shared library
490    ///
491    /// # Example
492    /// ```no_run
493    /// use j2534::Interface;
494    /// let interface = Interface::new("C:\\j2534_driver.dll").unwrap();
495    /// ```
496    pub fn new<S: AsRef<OsStr>>(path: S) -> Result<Interface, libloading::Error> {
497        let library = Library::new(path)?;
498
499        let interface = unsafe {
500            let c_pass_thru_open: Symbol<PassThruOpenFn> = library.get(b"PassThruOpen\0")?;
501            let c_pass_thru_close: Symbol<PassThruCloseFn> = library.get(b"PassThruClose\0")?;
502            let c_pass_thru_connect: Symbol<PassThruConnectFn> =
503                library.get(b"PassThruConnect\0")?;
504            let c_pass_thru_disconnect: Symbol<PassThruDisconnectFn> =
505                library.get(b"PassThruDisconnect\0")?;
506            let c_pass_thru_read_version: Symbol<PassThruReadVersionFn> =
507                library.get(b"PassThruReadVersion\0")?;
508            let c_pass_thru_get_last_error: Symbol<PassThruGetLastErrorFn> =
509                library.get(b"PassThruGetLastError\0")?;
510            let c_pass_thru_read_msgs: Symbol<PassThruReadMsgsFn> =
511                library.get(b"PassThruReadMsgs\0")?;
512            let c_pass_thru_start_msg_filter: Symbol<PassThruStartMsgFilterFn> =
513                library.get(b"PassThruStartMsgFilter\0")?;
514            let c_pass_thru_stop_msg_filter: Symbol<PassThruStopMsgFilterFn> =
515                library.get(b"PassThruStopMsgFilter\0")?;
516            let c_pass_thru_write_msgs: Symbol<PassThruWriteMsgsFn> =
517                library.get(b"PassThruWriteMsgs\0")?;
518            let c_pass_thru_start_periodic_msg: Symbol<PassThruStartPeriodicMsgFn> =
519                library.get(b"PassThruStartPeriodicMsg\0")?;
520            let c_pass_thru_stop_periodic_msg: Symbol<PassThruStopPeriodicMsgFn> =
521                library.get(b"PassThruStopPeriodicMsg\0")?;
522            let c_pass_thru_set_programming_voltage: Symbol<PassThruSetProgrammingVoltageFn> =
523                library.get(b"PassThruSetProgrammingVoltage\0")?;
524            let c_pass_thru_ioctl: Symbol<PassThruIoctlFn> = library.get(b"PassThruIoctl\0")?;
525            Interface {
526                c_pass_thru_open: *c_pass_thru_open.into_raw(),
527                c_pass_thru_close: *c_pass_thru_close.into_raw(),
528                c_pass_thru_connect: *c_pass_thru_connect.into_raw(),
529                c_pass_thru_disconnect: *c_pass_thru_disconnect.into_raw(),
530                c_pass_thru_read_version: *c_pass_thru_read_version.into_raw(),
531                c_pass_thru_get_last_error: *c_pass_thru_get_last_error.into_raw(),
532                c_pass_thru_read_msgs: *c_pass_thru_read_msgs.into_raw(),
533                c_pass_thru_start_msg_filter: *c_pass_thru_start_msg_filter.into_raw(),
534                c_pass_thru_stop_msg_filter: *c_pass_thru_stop_msg_filter.into_raw(),
535                c_pass_thru_write_msgs: *c_pass_thru_write_msgs.into_raw(),
536                c_pass_thru_start_periodic_msg: *c_pass_thru_start_periodic_msg.into_raw(),
537                c_pass_thru_stop_periodic_msg: *c_pass_thru_stop_periodic_msg.into_raw(),
538                c_pass_thru_set_programming_voltage: *c_pass_thru_set_programming_voltage
539                    .into_raw(),
540                c_pass_thru_ioctl: *c_pass_thru_ioctl.into_raw(),
541                library,
542
543                _marker: PhantomData,
544            }
545        };
546
547        // OpenPort 2.0 debug mode: unsafe { (&interface.c_pass_thru_ioctl)(0, 0x70001, 0x1 as *mut libc::c_void, std::ptr::null_mut() as *mut libc::c_void); }
548
549        Ok(interface)
550    }
551
552    /// Returns a text description of the most recent error
553    pub fn get_last_error(&self) -> Result<CString, Error> {
554        let mut error: [u8; 80] = [0; 80];
555        let res =
556            unsafe { (&self.c_pass_thru_get_last_error)(error.as_mut_ptr() as *mut libc::c_char) };
557        if res != 0 {
558            return Err(Error::from_code(res));
559        }
560
561        let c_str = unsafe { CStr::from_ptr(error.as_mut_ptr() as *mut libc::c_char) };
562        Ok(c_str.to_owned())
563    }
564
565    /// Creates a `Device` from the PassThru interface connected to the given port
566    ///
567    /// # Arguments
568    ///
569    /// * `port` - The port to search for a J2534 device
570    ///
571    /// # Example
572    /// ```no_run
573    /// use j2534::Interface;
574    /// let interface = Interface::new("C:\\j2534_driver.dll").unwrap();
575    /// let device = interface.open("COM2").unwrap();
576    /// ```
577    pub fn open<S: Into<Vec<u8>>>(&self, port: S) -> Result<Device, Error> {
578        let s = ffi::CString::new(port).unwrap();
579        let raw = s.as_ptr() as *const libc::c_void;
580        let mut id = 0;
581
582        let res = unsafe { (&self.c_pass_thru_open)(raw, &mut id as *mut u32) };
583        if res != 0 {
584            return Err(Error::from_code(res));
585        }
586
587        Ok(Device {
588            interface: self,
589            id: DeviceId(id),
590        })
591    }
592
593    /// Creates a `Device` from any connected PassThru devices
594    ///
595    /// # Example
596    /// ```
597    /// use j2534::Interface;
598    /// let interface = Interface::new("C:\\j2534_driver.dll").unwrap();
599    /// let device = interface.open_any().unwrap();
600    /// ```
601    pub fn open_any(&self) -> Result<Device, Error> {
602        let raw = std::ptr::null() as *const libc::c_void;
603        let mut id = 0;
604        let res = unsafe { (&self.c_pass_thru_open)(raw, &mut id as *mut u32) };
605        if res != 0 {
606            return Err(Error::from_code(res));
607        }
608
609        Ok(Device {
610            interface: self,
611            id: DeviceId(id),
612        })
613    }
614
615    /// General purpose I/O control for modifying device or channel characteristics.
616    pub unsafe fn ioctl(
617        &self,
618        handle: u32,
619        id: IoctlId,
620        input: *mut libc::c_void,
621        output: *mut libc::c_void,
622    ) -> Result<i32, Error> {
623        let res = (&self.c_pass_thru_ioctl)(handle, id as u32, input, output);
624        if res != 0 {
625            return Err(Error::from_code(res));
626        }
627        Ok(res)
628    }
629}
630
631#[derive(Copy, Clone, FromPrimitive, ToPrimitive)]
632pub enum Protocol {
633    J1850VPW = 1,
634    J1850PWM = 2,
635    ISO9141 = 3,
636    ISO14230 = 4,
637    CAN = 5,
638    ISO15765 = 6,
639    SCI_A_ENGINE = 7,
640    SCI_A_TRANS = 8,
641    SCI_B_ENGINE = 9,
642    SCI_B_TRANS = 10,
643}
644
645bitflags! {
646    /// Flags used when creating a communication channel
647    pub struct ConnectFlags: u32 {
648        const NONE = 0;
649        const CAN_29_BIT_ID = 0x100;
650        const ISO9141_NO_CHECKSUM = 0x200;
651        const CAN_ID_BOTH = 0x800;
652        const ISO9141_K_LINE_ONLY = 0x1000;
653    }
654}
655
656bitflags! {
657    /// Transmit status flags
658    pub struct TxFlags: u32 {
659        const NONE = 0;
660        // 0 = no padding
661        // 1 = pad all flow controlled messages to a full CAN frame using zeroes
662        const ISO15765_FRAME_PAD = 0x00000040;
663
664        const ISO15765_ADDR_TYPE = 0x00000080;
665        const CAN_29BIT_ID =  0x00000100;
666
667        // 0 = Interface message timing as specified in ISO 14230
668        // 1 = After a response is received for a physical request, the wait time shall be reduced to P3_MIN
669        // Does not affect timing on responses to functional requests
670        const WAIT_P3_MIN_ONLY = 0x00000200;
671
672        const SW_CAN_HV_TX = 0x00000400;
673
674        // 0 = Transmit using SCI Full duplex mode
675        // 1 = Transmit using SCI Half duplex mode
676        const SCI_MODE = 0x00400000;
677
678        // 0 = no voltage after message transmit
679        // 1 = apply 20V after message transmit
680        const SCI_TX_VOLTAGE = 0x00800000;
681
682        const DT_PERIODIC_UPDATE = 0x10000000;
683    }
684}
685
686bitflags! {
687    /// Receive status flags
688    pub struct RxStatus: u32 {
689        const NONE = 0;
690        // 0 = received
691        // 1 = transmitted
692        const TX_MSG_TYPE  = 0x00000001;
693
694        // 0 = Not a start of message indication
695        // 1 = First byte or frame received
696        const START_OF_MESSAGE = 0x00000002;
697        const ISO15765_FIRST_FRAME = 0x00000002  ;
698
699        const ISO15765_EXT_ADDR = 0x00000080;
700
701        // 0 = No break received
702        // 1 = Break received
703        const RX_BREAK = 0x00000004;
704
705        // 0 = No TxDone
706        // 1 = TxDone
707        const TX_INDICATION   = 0x00000008;
708        const TX_DONE = 0x00000008;
709
710        // 0 = No Error
711        // 1 = Padding Error
712        const ISO15765_PADDING_ERROR = 0x00000010;
713
714        // 0 = no extended address,
715        // 1 = extended address is first byte after the CAN ID
716        const ISO15765_ADDR_TYPE = 0x00000080;
717
718        const CAN_29BIT_ID = 0x00000100;
719
720        const SW_CAN_NS_RX = 0x00040000;
721        const SW_CAN_HS_RX = 0x00020000;
722        const SW_CAN_HV_RX = 0x00010000;
723    }
724}
725
726#[derive(Copy, Clone)]
727pub enum IoctlId {
728    GET_CONFIG = 0x01,
729    SET_CONFIG = 0x02,
730    READ_VBATT = 0x03,
731    FIVE_BAUD_INIT = 0x04,
732    FAST_INIT = 0x05,
733    // unused 0x06
734    CLEAR_TX_BUFFER = 0x07,
735    CLEAR_RX_BUFFER = 0x08,
736    CLEAR_PERIODIC_MSGS = 0x09,
737    CLEAR_MSG_FILTERS = 0x0A,
738    CLEAR_FUNCT_MSG_LOOKUP_TABLE = 0x0B,
739    ADD_TO_FUNCT_MSG_LOOKUP_TABLE = 0x0C,
740    DELETE_FROM_FUNCT_MSG_LOOKUP_TABLE = 0x0D,
741    READ_PROG_VOLTAGE = 0x0E,
742
743    SW_CAN_HS = 0x8000,
744    SW_CAN_NS = 0x8001,
745    SET_POLL_RESPONSE = 0x8002,
746    BECOME_MASTER = 0x8003,
747}
748
749#[derive(Copy, Clone)]
750/// Channel configuration parameters. Use with [`Channel::get_config`] and [`Channel::set_config`]
751pub enum ConfigId {
752    DATA_RATE = 0x01,
753    LOOPBACK = 0x03,
754    NODE_ADDRESS = 0x04,
755    NETWORK_LINE = 0x05,
756    P1_MIN = 0x06,
757    P1_MAX = 0x07,
758    P2_MIN = 0x08,
759    P2_MAX = 0x09,
760    P3_MIN = 0x0A,
761    P3_MAX = 0x0B,
762    P4_MIN = 0x0C,
763    P4_MAX = 0x0D,
764
765    W1 = 0x0E,
766    W2 = 0x0F,
767    W3 = 0x10,
768    W4 = 0x11,
769    W5 = 0x12,
770    TIDLE = 0x13,
771    TINIL = 0x14,
772    TWUP = 0x15,
773    PARITY = 0x16,
774    BIT_SAMPLE_POINT = 0x17,
775    SYNC_JUMP_WIDTH = 0x18,
776    W0 = 0x19,
777    T1_MAX = 0x1A,
778    T2_MAX = 0x1B,
779
780    T4_MAX = 0x1C,
781    T5_MAX = 0x1D,
782    ISO15765_BS = 0x1E,
783    ISO15765_STMIN = 0x1F,
784    DATA_BITS = 0x20,
785    FIVE_BAUD_MOD = 0x21,
786    BS_TX = 0x22,
787    STMIN_TX = 0x23,
788    T3_MAX = 0x24,
789    ISO15765_WFT_MAX = 0x25,
790
791    CAN_MIXED_FORMAT = 0x8000,
792
793    J1962_PINS = 0x8001,
794
795    SW_CAN_HS_DATA_RATE = 0x8010,
796    SW_CAN_SPEEDCHANGE_ENABLE = 0x8011,
797    SW_CAN_RES_SWITCH = 0x8012,
798    ACTIVE_CHANNELS = 0x8020,
799    SAMPLE_RATE = 0x8021,
800    SAMPLES_PER_READING = 0x8022,
801    READINGS_PER_MSG = 0x8023,
802    AVERAGING_METHOD = 0x8024,
803    SAMPLE_RESOLUTION = 0x8025,
804    INPUT_RANGE_LOW = 0x8026,
805    INPUT_RANGE_HIGH = 0x8027,
806}
807
808#[derive(Copy, Clone, Debug, FromPrimitive, ToPrimitive)]
809pub enum FilterType {
810    /// Allows matching messages into the receive queue. This filter type is only valid on non-ISO 15765 channels
811    Pass = 1,
812    /// Keeps matching messages out of the receive queue. This filter type is only valid on non-ISO 15765 channels
813    Block = 2,
814    /// Allows matching messages into the receive queue and defines an outgoing flow control message to support
815    /// the ISO 15765-2 flow control mechanism. This filter type is only valid on ISO 15765 channels.
816    FlowControl = 3,
817}
818
819#[derive(Debug)]
820/// Information about a device's version.
821pub struct VersionInfo {
822    pub firmware_version: CString,
823    pub dll_version: CString,
824    pub api_version: CString,
825}
826
827pub const SHORT_TO_GROUND: u32 = 0xFFFFFFFE;
828pub const VOLTAGE_OFF: u32 = 0xFFFFFFFF;
829
830impl<'a> Device<'a> {
831    /// Reads the version info of the device
832    pub fn read_version(&self) -> Result<VersionInfo, Error> {
833        let mut firmware_version: [u8; 80] = [0; 80];
834        let mut dll_version: [u8; 80] = [0; 80];
835        let mut api_version: [u8; 80] = [0; 80];
836        let res = unsafe {
837            (&self.interface.c_pass_thru_read_version)(
838                self.id.0,
839                firmware_version.as_mut_ptr() as *mut libc::c_char,
840                dll_version.as_mut_ptr() as *mut libc::c_char,
841                api_version.as_mut_ptr() as *mut libc::c_char,
842            )
843        };
844        if res != 0 {
845            return Err(Error::from_code(res));
846        }
847        unsafe {
848            Ok(VersionInfo {
849                firmware_version:
850                    CStr::from_ptr(firmware_version.as_mut_ptr() as *mut libc::c_char).to_owned(),
851                api_version: CStr::from_ptr(api_version.as_mut_ptr() as *mut libc::c_char)
852                    .to_owned(),
853                dll_version: CStr::from_ptr(dll_version.as_mut_ptr() as *mut libc::c_char)
854                    .to_owned(),
855            })
856        }
857    }
858
859    /// Outputs a programmable voltage on the specified J1962 connector pin.
860    /// Only one pin can have a specified voltage applied at a time. The only exception: it is permissible to program pin 15 for SHORT_TO_GROUND, and another pin to a voltage level.
861    /// When switching pins, the user application must disable the first voltage (VOLTAGE_OFF option) before enabling the second.
862    ///
863    /// # Arguments
864    ///
865    /// * `pin_number` - The J1962 connector pin to which the PassThru device will apply the specified voltage
866    /// * `voltage` - The voltage value (in millivolts) that will be applied to the specified pin
867    pub fn set_programming_voltage(&self, pin_number: u32, voltage: u32) -> Result<(), Error> {
868        let res = unsafe {
869            (&self.interface.c_pass_thru_set_programming_voltage)(self.id.0, pin_number, voltage)
870        };
871        if res != 0 {
872            return Err(Error::from_code(res));
873        }
874        Ok(())
875    }
876
877    /// Creates a channel
878    ///
879    /// # Arguments
880    ///
881    /// * protocol - Protocol to use with the channel
882    /// * flags - Protocol-specific flags. This is usually set to zero
883    /// * baudrate - Initial baud rate for the channel
884    pub fn connect(
885        &self,
886        protocol: Protocol,
887        flags: ConnectFlags,
888        baudrate: u32,
889    ) -> Result<Channel, Error> {
890        let mut id: u32 = 0;
891        let res = unsafe {
892            (&self.interface.c_pass_thru_connect)(
893                self.id.0,
894                protocol as u32,
895                flags.bits,
896                baudrate,
897                &mut id as *mut u32,
898            )
899        };
900        if res != 0 {
901            return Err(Error::from_code(res));
902        }
903        Ok(Channel {
904            device: self,
905            id: ChannelId(id),
906            protocol: protocol as Protocol,
907        })
908    }
909
910    /// Returns the battery voltage in millivolts read from Pin 16 on the J1962 connector.
911    pub fn read_battery_voltage(&self) -> Result<u32, Error> {
912        let mut voltage: u32 = 0;
913        unsafe {
914            self.interface.ioctl(
915                self.id.0,
916                IoctlId::READ_VBATT,
917                std::ptr::null_mut::<libc::c_void>(),
918                (&mut voltage) as *mut _ as *mut libc::c_void,
919            )
920        }?;
921        Ok(voltage)
922    }
923
924    /// Returns the current output voltage for ECU reprogramming in millivolts.
925    pub fn read_programming_voltage(&self) -> Result<u32, Error> {
926        let mut voltage: u32 = 0;
927        unsafe {
928            self.interface.ioctl(
929                self.id.0,
930                IoctlId::READ_PROG_VOLTAGE,
931                std::ptr::null_mut::<libc::c_void>(),
932                (&mut voltage) as *mut _ as *mut libc::c_void,
933            )
934        }?;
935        Ok(voltage)
936    }
937}
938
939impl<'a> Drop for Device<'a> {
940    fn drop(&mut self) {
941        unsafe { (&self.interface.c_pass_thru_close)(self.id.0) };
942    }
943}
944
945impl<'a> Channel<'a> {
946    /// Fills `msgs` with messages until timing out or until `msgs` is filled. Returns the slice of messages read.
947    ///
948    /// # Arguments
949    ///
950    /// * `msgs` - The array of messages to fill.
951    /// * `timeout` - The amount of time in milliseconds to wait. If set to zero, reads buffered messages and returns immediately
952    ///
953    /// Returns the amount of messages read.
954    pub fn read(&self, buf: &mut [PassThruMsg], timeout: u32) -> Result<usize, Error> {
955        for msg in buf.iter_mut() {
956            msg.protocol_id = self.protocol as u32;
957        }
958        let mut num_msgs: u32 = buf.len() as u32;
959        let res = unsafe {
960            (&self.device.interface.c_pass_thru_read_msgs)(
961                self.id.0,
962                buf.as_mut_ptr(),
963                &mut num_msgs as *mut u32,
964                timeout,
965            )
966        };
967        if res != 0 {
968            return Err(Error::from_code(res));
969        }
970        Ok(num_msgs as usize)
971    }
972
973    /// Reads a single message
974    pub fn read_once(&self, timeout: u32) -> Result<PassThruMsg, Error> {
975        let mut msg = PassThruMsg::new(self.protocol);
976
977        let mut num_msgs = 1 as u32;
978        let res = unsafe {
979            (&self.device.interface.c_pass_thru_read_msgs)(
980                self.id.0,
981                &mut msg as *mut PassThruMsg,
982                &mut num_msgs as *mut u32,
983                timeout,
984            )
985        };
986        if num_msgs == 0 {
987            // This should never happen, but just in case...
988            Err(Error::BufferEmpty)
989        } else if res != 0 {
990            Err(Error::from_code(res))
991        } else {
992            Ok(msg)
993        }
994    }
995
996    /// Writes `msgs` to the device until all messages have been written or until the timeout has been reached. Returns the amount of message written.
997    ///
998    /// # Arguments
999    ///
1000    /// * msgs - The array of messages to send.
1001    /// * timeout - The amount of time in milliseconds to wait. If set to zero, queues as many messages as possible and returns immediately.
1002    pub fn write(&self, msgs: &mut [PassThruMsg], timeout: u32) -> Result<usize, Error> {
1003        let mut num_msgs: u32 = msgs.len() as u32;
1004        let res = unsafe {
1005            (&self.device.interface.c_pass_thru_write_msgs)(
1006                self.id.0,
1007                msgs.as_mut_ptr(),
1008                &mut num_msgs as *mut u32,
1009                timeout,
1010            )
1011        };
1012        if res != 0 {
1013            return Err(Error::from_code(res));
1014        }
1015        Ok(num_msgs as usize)
1016    }
1017
1018    /// Sets up a network protocol filter to filter messages received by the PassThru device. There is a limit of ten filters per network layer protocol.
1019    /// The device blocks all receive frames by default when no filters are defined.
1020    ///
1021    /// Returns filter ID
1022    /// http://www.drewtech.com/support/passthru/startmsgfilter.html
1023    pub fn start_message_filter(
1024        &self,
1025        filter_type: FilterType,
1026        mask_msg: Option<&PassThruMsg>,
1027        pattern_msg: Option<&PassThruMsg>,
1028        flow_control_msg: Option<&PassThruMsg>,
1029    ) -> Result<FilterId, Error> {
1030        let mut msg_id: u32 = 0;
1031
1032        let mask_ptr = match mask_msg {
1033            Some(msg) => msg as *const PassThruMsg,
1034            None => std::ptr::null() as *const PassThruMsg,
1035        };
1036
1037        let pattern_ptr = match pattern_msg {
1038            Some(msg) => msg as *const PassThruMsg,
1039            None => std::ptr::null() as *const PassThruMsg,
1040        };
1041
1042        let flow_control_ptr = match flow_control_msg {
1043            Some(msg) => msg as *const PassThruMsg,
1044            None => std::ptr::null() as *const PassThruMsg,
1045        };
1046
1047        let res = unsafe {
1048            (&self.device.interface.c_pass_thru_start_msg_filter)(
1049                self.id.0,
1050                filter_type as u32,
1051                mask_ptr,
1052                pattern_ptr,
1053                flow_control_ptr,
1054                &mut msg_id as *mut u32,
1055            )
1056        };
1057        if res != 0 {
1058            return Err(Error::from_code(res));
1059        }
1060        Ok(FilterId(msg_id))
1061    }
1062
1063    /// Removes a message filter started with `Channel::start_msg_filter`
1064    ///
1065    /// # Arguments
1066    ///
1067    /// * `msg_id` - The id of the message returned from `Channel::start_msg_filter`
1068    pub fn stop_message_filter(&self, filter_id: FilterId) -> Result<(), Error> {
1069        let res =
1070            unsafe { (&self.device.interface.c_pass_thru_stop_msg_filter)(self.id.0, filter_id.0) };
1071        if res != 0 {
1072            return Err(Error::from_code(res));
1073        }
1074        Ok(())
1075    }
1076
1077    /// Repetitively transmit network protocol messages at the specified time interval over an existing logical communication channel. There is a limit of ten periodic messages per network layer protocol.
1078    /// Returns a handle for the periodic message used in `Channel::stop_periodic_msg`
1079    ///
1080    /// # Arguments
1081    ///
1082    /// * `msg` - The message to send
1083    /// * `time_interval` - The time in milliseconds to wait between sending messages. The acceptable range is between 5 and 65,535 milliseconds.
1084    pub fn start_periodic_message(
1085        &self,
1086        msg: &PassThruMsg,
1087        time_interval: u32,
1088    ) -> Result<MessageId, Error> {
1089        let mut msg_id = 0;
1090        let res = unsafe {
1091            (&self.device.interface.c_pass_thru_start_periodic_msg)(
1092                self.id.0,
1093                msg as *const PassThruMsg,
1094                &mut msg_id as *mut u32,
1095                time_interval,
1096            )
1097        };
1098        if res != 0 {
1099            return Err(Error::from_code(res));
1100        }
1101        Ok(MessageId(msg_id))
1102    }
1103
1104    /// Stops a periodic mesage started with `Channel::start_periodic_msg`
1105    ///
1106    /// # Arguments
1107    ///
1108    /// * msg_id = the id of the periodic message returned from `Channel::start_periodiC_msg`
1109    pub fn stop_periodic_message(&self, msg_id: MessageId) -> Result<(), Error> {
1110        let res =
1111            unsafe { (&self.device.interface.c_pass_thru_stop_periodic_msg)(self.id.0, msg_id.0) };
1112        if res != 0 {
1113            return Err(Error::from_code(res));
1114        }
1115        Ok(())
1116    }
1117
1118    /// Clear transmit message queue
1119    pub fn clear_transmit_buffer(&self) -> Result<(), Error> {
1120        unsafe {
1121            self.device.interface.ioctl(
1122                self.id.0,
1123                IoctlId::CLEAR_TX_BUFFER,
1124                std::ptr::null_mut::<libc::c_void>(),
1125                std::ptr::null_mut::<libc::c_void>(),
1126            )
1127        }?;
1128        Ok(())
1129    }
1130
1131    /// Halt continuous messages
1132    pub fn clear_periodic_messages(&self) -> Result<(), Error> {
1133        unsafe {
1134            self.device.interface.ioctl(
1135                self.id.0,
1136                IoctlId::CLEAR_PERIODIC_MSGS,
1137                std::ptr::null_mut::<libc::c_void>(),
1138                std::ptr::null_mut::<libc::c_void>(),
1139            )
1140        }?;
1141        Ok(())
1142    }
1143
1144    /// Clear receive message queue
1145    pub fn clear_receive_buffer(&self) -> Result<(), Error> {
1146        unsafe {
1147            self.device.interface.ioctl(
1148                self.id.0,
1149                IoctlId::CLEAR_RX_BUFFER,
1150                std::ptr::null_mut::<libc::c_void>(),
1151                std::ptr::null_mut::<libc::c_void>(),
1152            )
1153        }?;
1154        Ok(())
1155    }
1156
1157    /// Removes all message filters
1158    pub fn clear_message_filters(&self) -> Result<(), Error> {
1159        unsafe {
1160            self.device.interface.ioctl(
1161                self.id.0,
1162                IoctlId::CLEAR_MSG_FILTERS,
1163                std::ptr::null_mut::<libc::c_void>(),
1164                std::ptr::null_mut::<libc::c_void>(),
1165            )
1166        }?;
1167        Ok(())
1168    }
1169
1170    /// Gets a single configuration parameter.
1171    pub fn get_config(&self, id: ConfigId) -> Result<u32, Error> {
1172        let mut item = SConfig {
1173            parameter: id as u32,
1174            value: 0,
1175        };
1176        let mut input = SConfigList {
1177            size: 1,
1178            config_ptr: &mut item as *mut SConfig,
1179        };
1180        unsafe {
1181            self.device.interface.ioctl(
1182                self.id.0,
1183                IoctlId::GET_CONFIG,
1184                &mut input as *mut _ as *mut libc::c_void,
1185                std::ptr::null_mut::<libc::c_void>(),
1186            )
1187        }?;
1188        Ok(item.value)
1189    }
1190
1191    /// Sets a single configuration parameter.
1192    pub fn set_config(&self, id: ConfigId, value: u32) -> Result<(), Error> {
1193        let mut item = SConfig {
1194            parameter: id as u32,
1195            value,
1196        };
1197        let mut input = SConfigList {
1198            size: 1,
1199            config_ptr: &mut item as *mut SConfig,
1200        };
1201        unsafe {
1202            self.device.interface.ioctl(
1203                self.id.0,
1204                IoctlId::SET_CONFIG,
1205                &mut input as *mut _ as *mut libc::c_void,
1206                std::ptr::null_mut::<libc::c_void>(),
1207            )
1208        }?;
1209        Ok(())
1210    }
1211}
1212
1213impl<'a> Drop for Channel<'a> {
1214    fn drop(&mut self) {
1215        unsafe { (&self.device.interface.c_pass_thru_disconnect)(self.id.0) };
1216    }
1217}
1218
1219/// Information about an installed PassThru driver
1220#[derive(Debug)]
1221pub struct Driver {
1222    pub name: String,
1223    pub vendor: String,
1224    pub path: String,
1225}
1226
1227#[cfg(windows)]
1228/// Returns a list of all installed PassThru drivers
1229pub fn drivers() -> io::Result<Vec<Driver>> {
1230    let passthru = match RegKey::predef(HKEY_LOCAL_MACHINE)
1231        .open_subkey(Path::new("SOFTWARE").join("PassThruSupport.04.04"))
1232    {
1233        Err(err) if err.kind() == io::ErrorKind::NotFound => {
1234            return Ok(Vec::new());
1235        }
1236        other => other,
1237    }?;
1238    let mut listings = Vec::new();
1239
1240    for name in passthru.enum_keys() {
1241        let name = name?;
1242        let key = passthru.open_subkey(name)?;
1243
1244        let device_name: String = key.get_value("Name")?;
1245        let vendor: String = key.get_value("Vendor")?;
1246        let path: String = key.get_value("FunctionLibrary")?;
1247
1248        listings.push(Driver {
1249            name: device_name,
1250            vendor,
1251            path,
1252        });
1253    }
1254
1255    Ok(listings)
1256}
1257
1258#[cfg(not(windows))]
1259/// Returns a list of all installed PassThru drivers
1260pub fn drivers() -> io::Result<Vec<Driver>> {
1261    Ok(Vec::new())
1262}