can_socket/lib.rs
1//! CAN socket
2//!
3//! This library exposes a [`CanSocket`] and related types,
4//! allowing you to communicate over a Controller Area Network (CAN) bus.
5//!
6//! The is a standard blocking or non-blocking [`CanSocket`],
7//! and an asynchronous [`tokio::CanSocket`].
8//!
9//! This library uses the `SocketCAN` interface and only works on Linux.
10//!
11//! Supported features:
12//! * Bind sockets to specific interfaces by name or index.
13//! * Bind sockets to *all* CAN interfaces at the same time.
14//! * Send and receive data frames and RTR frames.
15//! * Send and receive standard frames and extended frames.
16//! * Setting per-socket filters.
17//! * Control over the `loopback` and `recv_own_msgs` options.
18//! * Constructing compile-time checked CAN IDs.
19
20#![cfg_attr(feature = "doc-cfg", feature(doc_cfg))]
21
22#![warn(missing_docs)]
23#![warn(missing_debug_implementations)]
24
25pub mod error;
26
27#[cfg(feature = "tokio")]
28#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "tokio")))]
29pub mod tokio;
30
31mod id;
32pub use id::{ExtendedId, CanId, StandardId, MAX_EXTENDED_ID, MAX_STANDARD_ID};
33
34mod filter;
35pub use filter::CanFilter;
36
37mod frame;
38pub use frame::{CanFrame, CanData};
39
40mod interface;
41pub use interface::CanInterface;
42
43mod socket;
44pub use socket::CanSocket;
45
46mod sys;
47
48/// Trait for types that can be used as a timeout or deadline.
49pub trait Deadline {
50 /// Get the instant at which the timeout/deadline expires.
51 fn deadline(&self) -> std::time::Instant;
52}
53
54impl Deadline for std::time::Duration {
55 /// Get the instant at which the timeout/deadline expires.
56 ///
57 /// If the `"tokio"` feature is enabled, this uses [`tokio::time::Instant`][::tokio::time::Instant] to compute the deadline.
58 /// This means that [`tokio::time::pause()`][::tokio::time::pause] and [`tokio::time::advance()`][::tokio::time::advance] will work as expected.
59 fn deadline(&self) -> std::time::Instant {
60 // Use tokio's `Instant::now()` when the `tokio` feature is enabled.
61 // This ensures that tokio::time::pause() and tokio::time::advance() will work.
62 #[cfg(feature = "tokio")]
63 {
64 (::tokio::time::Instant::now() + *self).into_std()
65 }
66
67 #[cfg(not(feature = "tokio"))]
68 {
69 std::time::Instant::now() + *self
70 }
71 }
72}
73
74impl Deadline for std::time::Instant {
75 fn deadline(&self) -> std::time::Instant {
76 *self
77 }
78}
79
80#[cfg(feature = "tokio")]
81impl Deadline for ::tokio::time::Instant {
82 fn deadline(&self) -> std::time::Instant {
83 self.into_std()
84 }
85}