Skip to content

Commit

Permalink
Minor linting
Browse files Browse the repository at this point in the history
Fixed a number of compiler warnings, minor spelling, and ran `cargo fmt`
  • Loading branch information
nyurik committed Jul 1, 2024
1 parent 8255a7c commit f6899be
Show file tree
Hide file tree
Showing 13 changed files with 152 additions and 92 deletions.
13 changes: 8 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,18 @@ targets = ["x86_64-unknown-linux-gnu", "i686-pc-windows-msvc", "x86_64-apple-dar

[features]
default = ["passthru", "socketcan"]
socketcan = ["dep:socketcan-isotp", "dep:socketcan"]
passthru = ["dep:libloading", "dep:shellexpand", "dep:winreg", "dep:serde_json", "dep:j2534_rust"]
socketcan = ["dep:socketcan-isotp", "dep:socketcan"]

[dependencies]
#automotive_diag = { version = "0.1", path = "../automotive_diag" }
automotive_diag = "0.1"
j2534_rust = { version = "1.5.0", optional = true }
serde_json = { version = "1.0.79", optional = true }
libloading = { version = "0.7.3", optional = true }
log="0.4.16"
log = "0.4.16"
serde_json = { version = "1.0.79", optional = true }
strum = "0.24"
strum_macros = "0.24"
thiserror="1.0.44"
thiserror = "1.0.44"

[dev-dependencies]
env_logger = "0.10.0"
Expand All @@ -49,3 +48,7 @@ shellexpand = { version = "2.1.0", optional = true }
[target.'cfg(target_os = "linux")'.dependencies]
socketcan-isotp = { optional = true, version = "1.0.1" }
socketcan = { version = "2.0.0", optional = true }

#[patch.crates-io]
## Enable local automotive_diag crate for development
#automotive_diag = { path = "../automotive_diag" }
25 changes: 17 additions & 8 deletions examples/kwp.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use automotive_diag::kwp2000::{KwpSessionType, KwpSessionTypeByte};
use std::{time::Duration, sync::{Arc, RwLock}};
use std::{
sync::{Arc, RwLock},
time::Duration,
};

use ecu_diagnostics::{
channel::{self, IsoTPSettings},
channel::IsoTPSettings,
dynamic_diag::{
DiagProtocol, DiagServerAdvancedOptions, DiagServerBasicOptions, DiagSessionMode,
DynamicDiagSession, TimeoutConfig, DiagServerEmptyLogger,
DiagProtocol, DiagServerAdvancedOptions, DiagServerBasicOptions, DiagServerEmptyLogger,
DiagSessionMode, DynamicDiagSession, TimeoutConfig,
},
hardware::{self, HardwareScanner, Hardware},
hardware::{Hardware, HardwareScanner},
kwp2000::Kwp2000Protocol,
};

Expand Down Expand Up @@ -79,7 +82,7 @@ fn main() {
tp_ext_id: None,
command_cooldown_ms: 100,
}),
DiagServerEmptyLogger{}
DiagServerEmptyLogger {},
)
.unwrap();

Expand All @@ -104,10 +107,16 @@ fn main() {
let res = diag_server.kwp_set_session(KwpSessionTypeByte::from(0x93)); // Same ID as what we registered at the start
println!("Into special diag mode result: {:?}", res);
print_diag_mode(&diag_server);
println!("Reset result: {:?}", diag_server.kwp_reset_ecu(automotive_diag::kwp2000::ResetType::PowerOnReset));
println!(
"Reset result: {:?}",
diag_server.kwp_reset_ecu(automotive_diag::kwp2000::ResetType::PowerOnReset)
);
print_diag_mode(&diag_server); // ECU should be in standard mode now as the ECU was rebooted
std::thread::sleep(Duration::from_millis(500));
println!("Read op: {:?}", diag_server.kwp_enable_normal_message_transmission());
println!(
"Read op: {:?}",
diag_server.kwp_enable_normal_message_transmission()
);
print_diag_mode(&diag_server); // ECU will automatically be put into 0x93 mode
// (Last requested mode as enable_normal_message_transmission cannot be ran in standard mode)
loop {
Expand Down
22 changes: 15 additions & 7 deletions src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ use std::{
sync::{mpsc, Arc, Mutex, PoisonError},
};

#[cfg(all(feature="socketcan", target_os="linux"))]
use socketcan::{EmbeddedFrame, Id, ExtendedId, StandardId, CanDataFrame};
#[cfg(all(feature = "socketcan", target_os = "linux"))]
use socketcan::{CanDataFrame, EmbeddedFrame, ExtendedId, Id, StandardId};

use crate::hardware::HardwareError;

Expand All @@ -22,7 +22,11 @@ pub type ChannelResult<T> = Result<T, ChannelError>;
pub enum ChannelError {
/// Underlying IO Error with channel
#[error("Device IO error")]
IOError(#[from] #[source] Arc<std::io::Error>),
IOError(
#[from]
#[source]
Arc<std::io::Error>,
),
/// Timeout when writing data to the channel
#[error("Write timeout")]
WriteTimeout,
Expand All @@ -43,7 +47,11 @@ pub enum ChannelError {
InterfaceNotOpen,
/// Underlying API error with hardware
#[error("Device hardware API error")]
HardwareError(#[from] #[source] HardwareError),
HardwareError(
#[from]
#[source]
HardwareError,
),
/// Channel not configured prior to opening
#[error("Channel configuration error")]
ConfigurationError,
Expand Down Expand Up @@ -448,7 +456,7 @@ impl Packet for CanFrame {
}
}

#[cfg(all(feature="socketcan", target_os="linux"))]
#[cfg(all(feature = "socketcan", target_os = "linux"))]
impl From<CanDataFrame> for CanFrame {
fn from(value: CanDataFrame) -> Self {
let (id, ext) = match value.id() {
Expand All @@ -459,12 +467,12 @@ impl From<CanDataFrame> for CanFrame {
}
}

#[cfg(all(feature="socketcan", target_os="linux"))]
#[cfg(all(feature = "socketcan", target_os = "linux"))]
impl Into<CanDataFrame> for CanFrame {
fn into(self) -> CanDataFrame {
let id = match self.ext {
true => Id::Extended(ExtendedId::new(self.get_address()).unwrap()),
false => Id::Standard(StandardId::new(self.get_address() as u16).unwrap())
false => Id::Standard(StandardId::new(self.get_address() as u16).unwrap()),
};
CanDataFrame::new(id, self.get_data()).unwrap()
}
Expand Down
69 changes: 42 additions & 27 deletions src/dynamic_diag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use std::{
collections::HashMap,
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{Receiver, Sender}, Mutex,
mpsc::{Receiver, Sender},
Mutex,
},
time::Duration,
};
Expand Down Expand Up @@ -134,15 +135,14 @@ pub enum ServerEvent {
/// Diag server logger
pub trait DiagServerLogger: Clone + Send + Sync {
/// When a diagnostic server event happens
fn on_event(&self, _evt: ServerEvent){}
fn on_event(&self, _evt: ServerEvent) {}
}

#[derive(Debug, Copy, Clone)]
/// Diag server basic logger (Use this if no logger is to be used in your application)
pub struct DiagServerEmptyLogger{}
pub struct DiagServerEmptyLogger {}

impl DiagServerLogger for DiagServerEmptyLogger {
}
impl DiagServerLogger for DiagServerEmptyLogger {}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// Diagnostic session mode
Expand Down Expand Up @@ -255,8 +255,8 @@ pub struct DynamicDiagSession {
running: Arc<AtomicBool>,
}

unsafe impl Sync for DynamicDiagSession{}
unsafe impl Send for DynamicDiagSession{}
unsafe impl Sync for DynamicDiagSession {}
unsafe impl Send for DynamicDiagSession {}

impl std::fmt::Debug for DynamicDiagSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand All @@ -277,12 +277,12 @@ impl DynamicDiagSession {
channel_cfg: IsoTPSettings,
basic_opts: DiagServerBasicOptions,
advanced_opts: Option<DiagServerAdvancedOptions>,
mut logger: L
mut logger: L,
) -> DiagServerResult<Self>
where
P: DiagProtocol<NRC> + 'static,
NRC: EcuNRC,
L: DiagServerLogger + 'static
L: DiagServerLogger + 'static,
{
// Create iso tp channel using provided HW interface. If this fails, we cannot setup KWP or UDS session!
channel.set_iso_tp_cfg(channel_cfg)?;
Expand Down Expand Up @@ -322,8 +322,8 @@ impl DynamicDiagSession {
let mut tx_addr = basic_opts.send_id;
match protocol.process_req_payload(&req.payload) {
DiagAction::SetSessionMode(mode) => {
let mut needs_response = true;
let mut ext_id = None;
let needs_response = true;
let ext_id = None;
let res = send_recv_ecu_req::<P, NRC, L>(
tx_addr,
rx_addr,
Expand All @@ -335,7 +335,7 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
);
if res.is_ok() {
// Send OK! We can set diag mode in the server side
Expand All @@ -359,7 +359,7 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
);
if res.is_ok() {
log::debug!("ECU Reset detected. Setting default session mode");
Expand All @@ -386,15 +386,15 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
);
if let DiagServerRx::EcuError { b, desc: _ } = &resp {
if NRC::from(*b).is_wrong_diag_mode() {
log::debug!("Trying to switch ECU modes");
// Wrong diag mode. We need to see if we need to change modes
// Switch modes!
tx_resp.send(DiagServerRx::EcuBusy); // Until we have a hook for this specific scenerio
// Now create new diag server request message
// Now create new diag server request message
let mut needs_response = true;
let mut ext_id = None;
if let Some(adv) = advanced_opts {
Expand All @@ -421,11 +421,13 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
)
.is_ok()
{
log::debug!("ECU mode switch OK. Resending the request");
log::debug!(
"ECU mode switch OK. Resending the request"
);
*noti_session_mode_t.write().unwrap() =
current_session_mode.clone();
last_tp_time = Instant::now();
Expand All @@ -441,7 +443,7 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
);
} else {
// Diag session mode req failed. Set session data
Expand All @@ -456,7 +458,7 @@ impl DynamicDiagSession {
tx_resp.send(resp);
}
}
}
}
}
if !do_cmd {
if current_session_mode != requested_session_mode {
Expand Down Expand Up @@ -488,7 +490,7 @@ impl DynamicDiagSession {
0,
&mut channel,
&is_connected_inner,
&mut logger
&mut logger,
)
.is_err()
{
Expand Down Expand Up @@ -533,7 +535,12 @@ impl DynamicDiagSession {
self.internal_send_byte_array(p, &lock, false)
}

fn internal_send_byte_array(&self, p: &[u8], sender: &Sender<DiagTxPayload>, resp_require: bool) -> DiagServerResult<()> {
fn internal_send_byte_array(
&self,
p: &[u8],
sender: &Sender<DiagTxPayload>,
resp_require: bool,
) -> DiagServerResult<()> {
self.clear_rx_queue();
sender
.send(DiagTxPayload {
Expand Down Expand Up @@ -632,12 +639,12 @@ fn send_recv_ecu_req<P, NRC, L>(
cooldown: u32,
channel: &mut Box<dyn IsoTPChannel>,
connect_state: &AtomicBool,
logger: &mut L
logger: &mut L,
) -> DiagServerRx
where
P: DiagProtocol<NRC>,
NRC: EcuNRC,
L: DiagServerLogger
L: DiagServerLogger,
{
// Send the request, and transmit the send state!
let mut res: ChannelResult<()> = Ok(());
Expand All @@ -659,7 +666,11 @@ where
match res {
Ok(_) => {
if !payload.is_empty() {
logger.on_event(ServerEvent::BytesSendState(tx_addr, payload.to_vec(), Ok(())));
logger.on_event(ServerEvent::BytesSendState(
tx_addr,
payload.to_vec(),
Ok(()),
));
}
if needs_response {
log::debug!("Sending OK, awaiting response from ECU");
Expand Down Expand Up @@ -706,7 +717,7 @@ where
cooldown,
channel,
connect_state,
logger
logger,
)
} else if nrc_data.is_repeat_request() {
// ECU wants us to ask again, so we wait a little bit, then call ourselves again
Expand All @@ -723,7 +734,7 @@ where
cooldown,
channel,
connect_state,
logger
logger,
)
} else {
// Unhandled NRC
Expand All @@ -748,7 +759,11 @@ where
}
}
Err(e) => {
logger.on_event(ServerEvent::BytesSendState(rx_addr, payload.to_vec(), Err(e.clone())));
logger.on_event(ServerEvent::BytesSendState(
rx_addr,
payload.to_vec(),
Err(e.clone()),
));
log::error!("Channel send error: {e}");
// Final error here at send state :(
connect_state.store(false, Ordering::Relaxed);
Expand Down
8 changes: 6 additions & 2 deletions src/hardware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub mod passthru; // Not finished at all yet, hide from the crate
#[cfg(feature = "passthru")]
use std::sync::Arc;

#[cfg(all(feature="socketcan", target_os="linux"))]
#[cfg(all(feature = "socketcan", target_os = "linux"))]
pub mod socketcan;

use crate::channel::{CanChannel, IsoTPChannel};
Expand Down Expand Up @@ -116,7 +116,11 @@ pub enum HardwareError {
/// Lib loading error
#[cfg(feature = "passthru")]
#[error("Device API library load error")]
LibLoadError(#[from] #[source] Arc<libloading::Error>),
LibLoadError(
#[from]
#[source]
Arc<libloading::Error>,
),
}

#[cfg(feature = "passthru")]
Expand Down
Loading

0 comments on commit f6899be

Please sign in to comment.