Thanks to visit codestin.com
Credit goes to docs.rs

socketcan/
lib.rs

1// socketcan/src/lib.rs
2//
3// The main lib file for the Rust SocketCAN library.
4//
5// This file is part of the Rust 'socketcan-rs' library.
6//
7// Licensed under the MIT license:
8//   <LICENSE or http://opensource.org/licenses/MIT>
9// This file may not be copied, modified, or distributed except according
10// to those terms.
11
12//! SocketCAN support.
13//!
14//! The Linux kernel supports using CAN-devices through a network-like API
15//! (see <https://www.kernel.org/doc/Documentation/networking/can.txt>). This
16//! crate allows easy access to this functionality without having to wrestle
17//! libc calls.
18//!
19//! # An introduction to CAN
20//!
21//! The CAN bus was originally designed to allow microcontrollers inside a
22//! vehicle to communicate over a single shared bus. Messages called
23//! *frames* are multicast to all devices on the bus.
24//!
25//! Every frame consists of an ID and a payload of up to 8 bytes. If two
26//! devices attempt to send a frame at the same time, the device with the
27//! higher ID will notice the conflict, stop sending and reattempt to sent its
28//! frame in the next time slot. This means that the lower the ID, the higher
29//! the priority. Since most devices have a limited buffer for outgoing frames,
30//! a single device with a high priority (== low ID) can block communication
31//! on that bus by sending messages too fast.
32//!
33//! The CAN Flexible Data-Rate (CAN FD) standard extended the data payload up to
34//! 64 bytes and added the ability to increase the the bitrate for the data bit
35//! in the frame.
36//!
37//! The Linux socketcan subsystem makes the CAN bus available as a regular
38//! networking device. Opening a network interface allows an application to
39//! receive all CAN messages from the bus and/or to filter for specific messages
40//! based on the CAN ID field. A device can be opened multiple times, every
41//! client will receive all CAN frames simultaneously.
42//!
43//! Similarly, CAN frames can be sent to the bus by multiple client
44//! simultaneously as well.
45//!
46//! # Hardware and more information
47//!
48//! More information on CAN can be found on
49//! [Wikipedia](https://en.wikipedia.org/wiki/CAN_bus).
50//! When not running on an embedded platform with already integrated CAN components,
51//! [Thomas Fischl's USBtin](http://www.fischl.de/usbtin/) (see
52//! [section 2.4](http://www.fischl.de/usbtin/#socketcan)) is one of many ways
53//! to get started.
54//!
55//! # RawFd and OwnedFd
56//!
57//! Raw access to the underlying file descriptor and construction through one
58//! is available through the `AsRawFd`, `IntoRawFd` and `FromRawFd`, and
59//! similar implementations.
60//!
61//! # Crate Features
62//!
63//! ### Default
64//!
65//! * **netlink** -
66//!   Whether to include programmable CAN interface configuration capabilities
67//!   based on netlink kernel communications. This brings in the
68//!   [neli](https://docs.rs/neli/latest/neli/) library and its dependencies.
69//!
70//! * **dump** -
71//!   Whether to include candump parsing capabilities.
72//!
73//! ### Non-default
74//!
75//! * **enumerate** -
76//!   Include the `enumerate` module which can be used to get a list of the CANbus
77//!   network interfaces attached to the host. This brings in the dependency for
78//!   [libudev](https://crates.io/crates/libudev)
79//!
80//! * **utils** -
81//!   Whether to build command-line utilities. This brings in additional
82//!   dependencies like [anyhow](https://docs.rs/anyhow/latest/anyhow/) and
83//!   [clap](https://docs.rs/clap/latest/clap/)
84//!
85//! * **tokio** -
86//!   Include support for async/await using [tokio](https://crates.io/crates/tokio).
87//!
88//! * **async-io** -
89//!   Include support for async/await using [async-io](https://crates.io/crates/async-io)
90//!   This will work with any runtime that uses _async_io_, including
91//!   [async-std](https://crates.io/crates/async-std) and [smol](https://crates.io/crates/smol).
92//!
93//! * **async-std** -
94//!   Include support for async/await using [async-io](https://crates.io/crates/async-io)
95//!   with a submodule aliased for [async-std](https://crates.io/crates/async-std) and examples
96//!   for that runtime.
97//!
98//! * **smol** -
99//!   Include support for async/await using [async-io](https://crates.io/crates/async-io)
100//!   with a submodule aliased for [smol](https://crates.io/crates/smol) and examples
101//!   for that runtime.
102//!
103//! ### Test Features
104//!
105//! Additional test can be built and run, but have requirements:
106//!
107//! * **vcan_tests** -
108//!   Requires a virtual CAN interface to be installed on the host. This can be done
109//!   by running the `vcan.sh` script included with the crate.
110//!
111//! * **netlink_tests** -
112//!   Requires superuser privileges to run/pass.
113//!
114
115// clippy: do not warn about things like "SocketCAN" inside the docs
116#![allow(clippy::doc_markdown)]
117// Some lints
118#![deny(
119    missing_docs,
120    missing_copy_implementations,
121    missing_debug_implementations,
122    unstable_features,
123    unused_import_braces,
124    unused_qualifications,
125    unsafe_op_in_unsafe_fn
126)]
127
128use std::mem::size_of;
129
130// Re-export the embedded_can crate so that applications can rely on
131// finding the same version we use.
132pub use embedded_can::{
133    self, blocking::Can as BlockingCan, nb::Can as NonBlockingCan, ExtendedId,
134    Frame as EmbeddedFrame, Id, StandardId,
135};
136
137pub mod errors;
138pub use errors::{
139    CanError, CanErrorDecodingFailure, ConstructionError, Error, IoError, IoErrorKind, IoResult,
140    Result,
141};
142
143pub mod addr;
144pub use addr::CanAddr;
145
146pub mod id;
147pub use id::CanId;
148
149pub mod frame;
150pub use frame::{
151    CanAnyFrame, CanDataFrame, CanErrorFrame, CanFdFrame, CanFrame, CanRawFrame, CanRemoteFrame,
152    Frame,
153};
154
155#[cfg(feature = "dump")]
156pub mod dump;
157
158pub mod socket;
159pub use socket::{CanFdSocket, CanFilter, CanSocket, ShouldRetry, Socket, SocketOptions};
160
161#[cfg(feature = "netlink")]
162pub mod nl;
163
164#[cfg(feature = "netlink")]
165pub use nl::{CanCtrlMode, CanInterface, InterfaceCanParams};
166
167/// Optional tokio support
168#[cfg(feature = "tokio")]
169pub mod tokio;
170
171/// Optional support for async-io-based async runtimes, like async-std and smol.
172#[cfg(any(feature = "async-io", feature = "async-std", feature = "smol"))]
173pub mod async_io;
174
175/// Using the specific definition for 'smol', just re-export the async_io module.
176#[cfg(feature = "smol")]
177pub mod smol {
178    pub use crate::async_io::*;
179}
180
181/// Using the specific definition for 'async_std', just re-export the async_io module.
182#[cfg(feature = "async-std")]
183pub mod async_std {
184    pub use crate::async_io::*;
185}
186
187#[cfg(feature = "enumerate")]
188pub mod enumerate;
189#[cfg(feature = "enumerate")]
190pub use enumerate::available_interfaces;
191
192// ===== helper functions =====
193
194/// Gets a byte slice for any sized variable.
195///
196/// Note that this should normally be unsafe, but since we're only
197/// using it internally for types sent to the kernel, it's OK.
198pub(crate) fn as_bytes<T: Sized>(val: &T) -> &[u8] {
199    let sz = size_of::<T>();
200    unsafe { std::slice::from_raw_parts::<'_, u8>(val as *const _ as *const u8, sz) }
201}
202
203/// Gets a mutable byte slice for any sized variable.
204pub(crate) fn as_bytes_mut<T: Sized>(val: &mut T) -> &mut [u8] {
205    let sz = size_of::<T>();
206    unsafe { std::slice::from_raw_parts_mut(val as *mut _ as *mut u8, sz) }
207}