- allow communication to elm327 device via a serialport

- allow creation of elm327 device without requiring unwrap()
- added some extra documentation
- add fuel_level obd-ii command
- expose reset() functionality of device
This commit is contained in:
Nicholas Orlowsky 2025-03-18 21:59:16 -04:00
parent db4b4d990d
commit 3010f9326f
10 changed files with 189 additions and 63 deletions

View file

@ -1,34 +1,24 @@
use log::{debug, info, trace};
use std::{
collections::VecDeque,
io::{Read, Write},
thread, time,
};
use std::{collections::VecDeque, thread, time};
use super::{Error, Obd2BaseDevice, Obd2Reader, Result};
use super::{serial_comm::SerialComm, Error, Obd2BaseDevice, Obd2Reader, Result};
/// An ELM327 OBD-II adapter
///
/// It communicates with the computer over UART using an FTDI FT232R USB-to-UART converter.
/// It communicates with the computer or UART using an FTDI FT232R USB-to-UART converter.
/// Commands to the device itself are indicated by sending "AT" followed by the command, while
/// plain strings of hex data indicate OBD-II requests to be sent to the vehicle. The responses of
/// the vehicle are echoed back as hex characters. Capitalization and spaces are always ignored.
///
/// [Datasheet for v1.4b](https://github.com/rsammelson/obd2/blob/master/docs/ELM327DSH.pdf), and
/// the [source](https://www.elmelectronics.com/products/dsheets/).
pub struct Elm327 {
device: ftdi::Device,
pub struct Elm327<T: SerialComm> {
device: T,
buffer: VecDeque<u8>,
baud_rate: u32,
}
impl Default for Elm327 {
fn default() -> Self {
Elm327::new().unwrap()
}
}
impl Obd2BaseDevice for Elm327 {
impl<T: SerialComm> Obd2BaseDevice for Elm327<T> {
fn reset(&mut self) -> Result<()> {
self.flush_buffers()?;
self.reset_ic()?;
@ -48,7 +38,7 @@ impl Obd2BaseDevice for Elm327 {
}
}
impl Obd2Reader for Elm327 {
impl<T: SerialComm> Obd2Reader for Elm327<T> {
fn get_line(&mut self) -> Result<Option<Vec<u8>>> {
self.get_until(b'\n', false)
}
@ -64,22 +54,14 @@ impl Obd2Reader for Elm327 {
}
}
impl Elm327 {
fn new() -> Result<Self> {
let mut ftdi_device = ftdi::find_by_vid_pid(0x0403, 0x6001)
.interface(ftdi::Interface::A)
.open()?;
ftdi_device.set_baud_rate(38400)?;
ftdi_device.configure(ftdi::Bits::Eight, ftdi::StopBits::One, ftdi::Parity::None)?;
// device.set_latency_timer(2).unwrap();
ftdi_device.usb_reset()?;
impl<T: SerialComm> Elm327<T> {
/// Creates a new Elm327 adapter with the given
/// unserlying Serial Communication device
pub fn new(serial_device: T) -> Result<Self> {
let mut device = Elm327 {
device: ftdi_device,
device: serial_device,
buffer: VecDeque::new(),
baud_rate: 38400,
baud_rate: 38_400,
};
device.connect(false)?;
@ -98,7 +80,7 @@ impl Elm327 {
}
fn flush_buffers(&mut self) -> Result<()> {
self.device.usb_purge_buffers()?;
self.device.purge_buffers()?;
Ok(())
}
@ -123,25 +105,22 @@ impl Elm327 {
fn reset_ic(&mut self) -> Result<()> {
info!("Performing IC reset");
self.send_serial_str("ATZ")?;
let response = self.get_response()?;
debug!(
"reset_ic: got response {:?}",
self.get_response()?
.as_ref()
.map(|l| std::str::from_utf8(l.as_slice()))
response.as_ref().map(|l| std::str::from_utf8(l.as_slice()))
);
Ok(())
}
fn reset_protocol(&mut self) -> Result<()> {
info!("Performing protocol reset");
debug!(
"reset_protocol: got response {:?}",
self.serial_cmd("ATSP0")?
);
debug!(
"reset_protocol: got OBD response {:?}",
self.cmd(&[0x01, 0x00])?
);
let elm_response = self.serial_cmd("ATSP0")?;
debug!("reset_protocol: got response {:?}", elm_response);
let obd_response = self.cmd(&[0x01, 0x00])?;
debug!("reset_protocol: got OBD response {:?}", obd_response);
self.flush_buffers()?;
Ok(())
}
@ -258,13 +237,18 @@ impl Elm327 {
fn read_into_queue(&mut self) -> Result<()> {
let mut buf = [0u8; 16];
loop {
let len = self.device.read(&mut buf)?;
if len > 0 {
self.buffer.extend(&buf[0..len]);
trace!(
"read_into_queue: values {:?}",
std::str::from_utf8(&buf[0..len])
);
let len_res = self.device.read(&mut buf);
if let Ok(len) = len_res {
if len > 0 {
self.buffer.extend(&buf[0..len]);
trace!(
"read_into_queue: values {:?}",
std::str::from_utf8(&buf[0..len])
);
} else {
trace!("read_into_queue: no values left to read");
break;
}
} else {
trace!("read_into_queue: no values left to read");
break;

View file

@ -3,6 +3,9 @@
mod elm327;
pub use elm327::Elm327;
mod serial_comm;
pub use serial_comm::{FTDIDevice, SerialPort};
type Result<T> = std::result::Result<T, Error>;
/// A lower-level API for using an OBD-II device
@ -54,6 +57,10 @@ pub enum Error {
#[error("FTDI error: `{0:?}`")]
Ftdi(ftdi::Error),
/// An error with the underlying [serialport device](serialport::SerialPort)
#[error("Serialport error: `{0:?}`")]
Serialport(serialport::Error),
/// An I/O error in a low-level [std::io] stream operation
#[error("IO error: `{0:?}`")]
IO(std::io::Error),
@ -69,6 +76,12 @@ impl From<ftdi::Error> for Error {
}
}
impl From<serialport::Error> for Error {
fn from(e: serialport::Error) -> Self {
Error::Serialport(e)
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::IO(e)

94
src/device/serial_comm.rs Normal file
View file

@ -0,0 +1,94 @@
use super::Result;
use std::io::{Read, Write};
use std::time::Duration;
const DEFAULT_BAUD_RATE: u32 = 38_400;
/// An API to communicate with a serial device
pub trait SerialComm {
fn write_all(&mut self, data: &[u8]) -> Result<()>;
fn read(&mut self, data: &mut [u8]) -> Result<usize>;
fn set_baud_rate(&mut self, baud_rate: u32) -> Result<()>;
fn purge_buffers(&mut self) -> Result<()>;
}
/// Communicate with a serial device using the
/// serialport library
///
/// /dev/tty* or similar on unix-like systems
/// COM devices on Windows systems
pub struct SerialPort {
device: Box<dyn serialport::SerialPort>,
}
impl SerialPort {
/// Creates a new instance of a SerialPort
pub fn new(path: &str) -> Result<Self> {
let device = serialport::new(path, DEFAULT_BAUD_RATE)
.timeout(Duration::from_millis(10))
.parity(serialport::Parity::None)
.data_bits(serialport::DataBits::Eight)
.stop_bits(serialport::StopBits::One)
.path(path)
.open()?;
Ok(Self { device })
}
}
impl SerialComm for SerialPort {
fn write_all(&mut self, data: &[u8]) -> Result<()> {
Ok(self.device.write_all(data)?)
}
fn read(&mut self, data: &mut [u8]) -> Result<usize> {
Ok(self.device.read(data)?)
}
fn set_baud_rate(&mut self, baud_rate: u32) -> Result<()> {
Ok(self.device.set_baud_rate(baud_rate)?)
}
fn purge_buffers(&mut self) -> Result<()> {
Ok(self.device.clear(serialport::ClearBuffer::All)?)
}
}
/// Communicate with a USB to Serial FTDI device
/// with the FTDI library
pub struct FTDIDevice {
device: ftdi::Device,
}
impl FTDIDevice {
/// Creates a new instance of an FTDIDevice
pub fn new() -> Result<Self> {
let mut device = ftdi::find_by_vid_pid(0x0404, 0x6001)
.interface(ftdi::Interface::A)
.open()?;
device.set_baud_rate(DEFAULT_BAUD_RATE)?;
device.configure(ftdi::Bits::Eight, ftdi::StopBits::One, ftdi::Parity::None)?;
device.usb_reset()?;
Ok(Self { device })
}
}
impl SerialComm for FTDIDevice {
fn write_all(&mut self, data: &[u8]) -> Result<()> {
Ok(self.device.write_all(data)?)
}
fn read(&mut self, data: &mut [u8]) -> Result<usize> {
Ok(self.device.read(data)?)
}
fn set_baud_rate(&mut self, baud_rate: u32) -> Result<()> {
Ok(self.device.set_baud_rate(baud_rate)?)
}
fn purge_buffers(&mut self) -> Result<()> {
Ok(self.device.usb_purge_buffers()?)
}
}