Skip to content

Commit

Permalink
add helper function to open socketcan by name
Browse files Browse the repository at this point in the history
  • Loading branch information
pd0wm committed Mar 13, 2024
1 parent 1652f3e commit 1bb3a68
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
7 changes: 2 additions & 5 deletions src/adapter.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
//! Convenience functions to get a CAN adapter.

#[cfg(target_os = "linux")]
use socketcan::Socket;

/// Convenience function to get the first available adapter on the system. Supports both comma.ai panda, and SocketCAN.
pub fn get_adapter() -> Result<crate::async_can::AsyncCanAdapter, crate::error::Error> {
if let Ok(panda) = crate::panda::Panda::new_async() {
Expand All @@ -12,8 +9,8 @@ pub fn get_adapter() -> Result<crate::async_can::AsyncCanAdapter, crate::error::
#[cfg(target_os = "linux")]
{
// TODO: iterate over all available SocketCAN adapters to also find things like vcan0
if let Ok(socket) = socketcan::CanFdSocket::open("can0") {
return Ok(crate::socketcan::SocketCan::new_async(socket).unwrap());
if let Ok(socket) = crate::socketcan::SocketCan::new_async_from_name("can0") {
return Ok(socket);
}
}

Expand Down
8 changes: 8 additions & 0 deletions src/socketcan/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ impl SocketCan {
Self { socket }
}

pub fn new_async_from_name(name: &str) -> Result<AsyncCanAdapter, Error> {
if let Ok(socket) = socketcan::CanFdSocket::open(name) {
SocketCan::new_async(socket)
} else {
Err(crate::error::Error::NotFound)
}
}

pub fn new_async(socket: socketcan::CanFdSocket) -> Result<AsyncCanAdapter, Error> {
let socket = SocketCan::new(socket);

Expand Down
4 changes: 1 addition & 3 deletions tests/adapter_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@ fn socketcan_bulk_send_sync() {
#[tokio::test]
#[serial_test::serial]
async fn socketcan_bulk_send_async() {
use socketcan::Socket;
let socket = socketcan::CanFdSocket::open("can0").unwrap();
let adapter = automotive::socketcan::SocketCan::new_async(socket).unwrap();
let adapter = automotive::socketcan::SocketCan::new_async_from_name("can0").unwrap();
bulk_send(&adapter).await;
}

0 comments on commit 1bb3a68

Please sign in to comment.