Giter VIP home page Giter VIP logo

socketcan-rs's Introduction

Rust SocketCAN

This library implements Controller Area Network (CAN) communications on Linux using the SocketCAN subsystem. This provides a network socket interface to the CAN bus.

Linux SocketCAN

Please see the documentation for details about the Rust API provided by this library.

Latest News

Version 3.x adds integrated async/await, improved Netlink coverage, and more!

Version 3.0 adds integrated support for async/await, with the most popular runtimes, tokio, async-std, and smol. We have merged the tokio-socketcan crate into this one and implemented async-io.

Unfortunaly this required a minor breaking change to the existing API, so we bumped the version to 3.0.

The async support is optional, and can be enabled with a feature for the target runtime: tokio, async-std, or smol.

Additional implementation of the netlink control of the CAN interface was added in v3.1 allowing an application to do things like set the bitrate on the interface, set control modes, restart the inteface, etc.

v3.2 increased the interface configuration coverage with Netlink, allowing an application to set most interface CAN parameters and query them all back.

What's New in Version 3.3

  • #53 Added CanFD support for tokio
  • Serialized tokio unit tests and put them behind the "vcan_tests" feature

What's New in Version 3.2

  • #32 Further expanded netlink functionality:
    • Added setters for most additional interface CAN parameters
    • Ability to query back interface CAN parameters
    • Expanded InterfaceDetails to include CAN-specific parameters
    • Better integration of low-level types with neli
    • Significant cleanup of the nl module
    • Split the nl module into separate sources for higher and lower-level code

Next Steps

A number of items still did not make it into a release. These will be added in v3.x, coming soon.

  • Issue #22 Timestamps, including optional hardware timestamps
  • Better documentation. This README will be expanded with basic usage information, along with better doc comments, and perhaps creation of the wiki

Minimum Supported Rust Version (MSRV)

The current version of the crate targets Rust Edition 2021 with an MSRV of Rust v1.70.0.

Note that, the core library can likely compile with an earlier version if dependencies are carefully selected, but tests are being done with the latest stable compiler and the stated MSRV.

Async Support

Tokio

The tokio-socketcan crate was merged into this one to provide async support for CANbus using tokio.

This is enabled with the optional feature, tokio.

Example bridge with tokio

This is a simple example of sending data frames from one CAN interface to another. It is included in the example applications as tokio_bridge.rs.

use futures_util::StreamExt;
use socketcan::{tokio::CanSocket, CanFrame, Result};
use tokio;

#[tokio::main]
async fn main() -> Result<()> {
    let mut sock_rx = CanSocket::open("vcan0")?;
    let sock_tx = CanSocket::open("can0")?;

    while let Some(Ok(frame)) = sock_rx.next().await {
        if matches!(frame, CanFrame::Data(_)) {
            sock_tx.write_frame(frame)?.await?;
        }
    }

    Ok(())
}

async-io (async-std & smol)

New support was added for the async-io runtime, supporting the async-std and smol runtimes.

This is enabled with the optional feature, async-io. It can also be enabled with either feature, async-std or smol. Either of those specific runtime flags will simply build the async-io support but then also alias the async-io submodule with the specific feature/runtime name. This is simply for convenience.

Additionally, when building examples, the specific examples for the runtime will be built if specifying the async-std or smol feature(s).

Example bridge with async-std

This is a simple example of sending data frames from one CAN interface to another. It is included in the example applications as async_std_bridge.rs.

use socketcan::{async_std::CanSocket, CanFrame, Result};

#[async_std::main]
async fn main() -> Result<()> {
    let sock_rx = CanSocket::open("vcan0")?;
    let sock_tx = CanSocket::open("can0")?;

    loop {
        let frame = sock_rx.read_frame().await?;
        if matches!(frame, CanFrame::Data(_)) {
            sock_tx.write_frame(&frame).await?;
        }
    }
}

Testing

Integrating the full suite of tests into a CI system is non-trivial as it relies on a vcan0 virtual CAN device existing. Adding it to most Linux systems is pretty easy with root access, but attaching a vcan device to a container for CI seems difficult to implement.

Therefore, tests requiring vcan0 were placed behind an optional feature, vcan_tests.

The steps to install and add a virtual interface to Linux are in the scripts/vcan.sh script. Run it with root proveleges, then run the tests:

$ sudo ./scripts/vcan.sh
$ cargo test --features=vcan_tests

socketcan-rs's People

Contributors

akhiltthomas avatar almini avatar andresv avatar dlips avatar dnsco avatar fpagliughi avatar gama-ci avatar gmarull avatar hmvp avatar jmagnuson avatar jreppnow avatar marcelbuesing avatar matiasvara avatar mbr avatar mchodzikiewicz avatar nnarain avatar poeschel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socketcan-rs's Issues

Instead of own implementation, just re-export frame types provided by libc?

(Making an extra ticket explicitly not to disrupt the PR #16 even further..)

As @fpagliughi has stated in the comments for PR #16, the libc crate already has correct definitions for both the frame structs (2.0 and FD) -> this crate could consequentually just pub use them (possibly assigning a backwards compatible name) and implement its added logic as traits on top.

Once the current sleugh of PRs is done with an if the maintainers agree, I would see if that can be done easily.

Reimplement sockets using socket2::Socket

From the beginning, this crate has used low-level file handles and libc calls to implement CAN sockets. This was necessary since the std library didn't support RAW sockets. But the socket2 library does support RAW (and DGRAM) sockets, and is flexible enough to work with different protocols and address types, even if not directly supported.

Moving to an implementation based on socket2::Socket would substantially reduce our code size, number of unsafe blocks, and manual error checking. Our sockets would simply wrap those from socket2:

pub struct CanSocket(socket2::Socket);

An initial test is in the socket2 branch:
https://github.com/socketcan-rs/socketcan-rs/tree/socket2

Interestingly, since those sockets support AsRawFd, they can be dropped into the existing libc code and tested incrementally, changing just a few functions at a time to use the new socket calls instead of the libc calls.

Any thoughts?

embedded Hal for CanFdSocket

I'm looking at the code but fail to understand why the embedded Hal interfaces are implemented for CanSocket but not CanFdSocket?

Can anyone shed some light onto the matter?

CAN XL support

I think it would be interesting to add support for this, although I guess there is little adoption so far.

More info e.g. here.

Using socketcan with asynchronous loop

Hi Marc,

For a quick project I have been playing with socketcan, but all my other IO (mainly TCP) were using Metal IO; as a first run I'm using 2 different threads, but in a short future it would be nice to read/write to the CAN socket directly from the async loop!

2 things are missing at the moment, which I added in a fork in this fork:

  • access to the internal file descriptor
  • API to set as non-blocking. (Directly related to #6)

Then I wrote this small miocan adapter to make the glue between socketcan 1.6 and mio 0.6.9, plus an example of usage which works nicely on read.

I don't know yet what would be the best course (integration in socketcan? in mio? 3rd repo as now?), but at least it's pretty cool to bootstrap that work!

Please comment when you have time.
Cheers!

Add support for custom socket protocol (CAN_RAW)

Unfortunately, some platforms use custom values for the protocol in the socket syscall instead of CAN_RAW.
Would you agree to add support for this, given I prepare and maintain a patch?
I see three ways of providing support for it:

  • Simply providing functions in CanSocket allowing to specify the protocol number. This is 100% backwards compatible.
  • Adding support for it in the Socket trait. This would be incompatible for all existing implementations of Socket outside of this crate. This would introduce a new function open_addr_with_proto(addr: CanAddr, protocol: c_int) which needs to be implemented while the existing function could be auto provided using CAN_RAW as protocol.
  • An environment variable could be used to allow to override the socket protocol. This could be disabled per default and be linked to a crate feature.

You are also providing a way to pass in an existing socket, so this isn't strictly necessary (however it would be convenient). This special case could also be implemented in the final application alone.

Would you consider merging such a change? Which one of the variants would you prefer (if any of them sounds acceptable at all)?
I would be happy to provide an implementation if there is a chance of acceptance ;) Of course, I would be open for other suggestions as well.

CAN-FD Support

Hello everyone!

Thank you very much for this useful crate!

Are there any plans to support CAN-FD in addition to standard CAN 2.0 within the scope of this crate?

If yes, I would certainly be willing to get started on the topic and contribute, as I need it for another project I am working on atm.

One problem I am seeing is the API - ideally, one would avoid duplicating all the structs for CAN-FD, as to have a unified interface. But especially CANFrame would blow up quite drastically in size, as CAN-FD payloads are up to 64 bytes. This would make copying the struct a lot more expensive as well. One option would be to keep the payload in a Vec or some other heap-allocated container in the CAN-FD case, but that adds an arguable unnecessary allocation. Happy to hear your thoughts on the matter!

Best regards,
Janosch.

J1939 support

Hi,
I've seen the J1939 conversation come up here several times... Any chance such an improvement would be considered? Has anyone tried to implement it?
Thanks,

PS: glad to see this project is back in active development... looking very good I must say

ISO-TP support

Will ISO-TP support be added? If not, would a PR to add support be accepted?

Version 3.3.0 Not Compiling With Neli

Hi SocketCan Team, Im working on an embedded project and am trying to build socket can for the newer versions, however any version above 2.0.0 fails to compile when I cargo build due to what seems to be a conflict with the neli library.

My Cargo.toml looks like this

name = "calypso"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
socketcan = "3.3.0"
paho-mqtt = "0.12.3"
nalgebra = "0.32.3"

When I move socketcan down to version 1.7.0 it compiles and works fine, but I want to upgrade to 3.3.0. All 2.x versions fail.

Heres some sample Terminal output from my cargo build command.
Screenshot 2023-12-01 at 12 37 25 AM

Any advice would be much appreciated

socketcan2-rs

Since there isn't that much progress in this library for some time, I published my implementation of a libc-socketcan wrapper. You can find it here: https://crates.io/crates/socketcan2

socketcan2 supports timestamps which also work in combination with multithreading (in contrast to the method used in this project) and it is possible to wait on multiple CAN devices in the same thread using one timeout what indispensable for certain kinds of applications.

Use 'nix' crate instead of 'libc' when possible.

The libc crate is a low-level, unsafe wrapper around much of the standard C library and platform system calls. The nix crate sits at a slightly higher level, wrapping the libc calls into safe alternatives. I just submit a couple small PR's to the nix repo to add some missing functionality for SocketCAN in Linux:

If those land, we can start rewriting some of the socket functionality to use it. It moves the CanAddr upstream, and makes, for example, the CanSocket::if_open() much simpler without any unsafe calls directly:

pub fn open_interface(ifindex: c_uint) -> nix::Result<CanSocket> {
    let addr = CanAddr::new(ifindex);

    let fd = socket(
        AddressFamily::Can,
        SockType::Raw,
        SockFlag::empty(),
        SockProtocol::CanRaw
    )?;

    if let Err(err) = bind(fd, &addr) {
        close(fd);
        return Err(err);
    }

    Ok(CanSocket { fd })
}

example code compile failed

source: https://github.com/socketcan-rs/socketcan-rs/blob/master/examples/tokio_bridge.rs
rustc: 1.74.0-nightly (2f5df8a94 2023-08-31)
output:

 fawdlstty@fa-pc  ~/_tmp/test_rs2   master  cargo run
   Compiling test_rs2 v0.1.0 (/home/fawdlstty/_tmp/test_rs2)
error[E0432]: unresolved import `futures_util`
 --> src/main.rs:1:5
  |
1 | use futures_util::StreamExt;
  |     ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`

error[E0599]: no method named `next` found for struct `AsyncCanSocket` in the current scope
   --> src/main.rs:9:41
    |
9   |     while let Some(Ok(frame)) = sock_rx.next().await {
    |                                         ^^^^ method not found in `AsyncCanSocket<CanSocket>`
    |
   ::: /home/fawdlstty/.cargo/registry/src/rsproxy.cn-8f6827c7555bfaf8/futures-util-0.3.29/src/stream/stream/mod.rs:273:8
    |
273 |     fn next(&mut self) -> Next<'_, Self>
    |        ---- the method is available for `AsyncCanSocket<CanSocket>` here
    |
    = help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
    |
1   + use futures_util::stream::stream::StreamExt;
    |

Some errors have detailed explanations: E0432, E0599.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `test_rs2` (bin "test_rs2") due to 2 previous errors
 ✘ fawdlstty@fa-pc  ~/_tmp/test_rs2   master 

Standard/extended identifier implementation incorrect?

I believe the current implementation of the CANFrame constructor is incorrect, because it does not allow the construction of frames with an extended identifier less than 0x800.

Code is currently as follows:

    pub fn new(id: u32, data: &[u8], rtr: bool, err: bool) -> Result<CanFrame, ConstructionError> {

        ...

        if id > EFF_MASK {
            return Err(ConstructionError::IDTooLarge);
        }

        // set EFF_FLAG on large message
        if id > SFF_MASK {
            _id |= EFF_FLAG;
        }

Say I wanted to construct a frame with extended identifier 0x100. If I pass id=EFF_FLAG | 0x100 the constructor would return an IDTooLarge error. If I pass id=0x100, the constructor returns a frame with a standard identifier.

The CAN standard allows for extended identifiers less than 0x800, and in fact these are commonly used, here are a few examples:
https://stackoverflow.com/questions/63213413/standard-and-extended-messages-with-same-identifier
https://forum.hms-networks.com/t/about-extended-frame-format/2237
https://kb.vector.com/entry/1093/

Recommendation: add an argument to CANFrame::new to set the identifier type explicitly (this is a breaking change to the API- but current behavior is incorrect in some cases)

CanFDFrames with ExtendedID are not correctly parsed by socketcan::dump::Reader

I found that candump log messages for CanFD frames with extended ID seemed to have their ID components truncated.

In the following test, the packet has an extended ID of 0x12345678, however when passed through a dump::Reader it returns a frame with ID 0x678, and the .is_extended() method returns False

#[test]
fn test_extended_id_fd_can_dump_record() {
    let candump_string =
        String::from("(1234.567890) testcan0 12345678##500112233445566778899AABBCCDDEEFF");

    let mut reader = socketcan::dump::Reader::from_reader(candump_string.as_bytes());
    let rec = reader.next_record().unwrap().unwrap();
    let frame = rec.frame.clone();

    let inner_frame = match frame {
        CanAnyFrame::Fd(f) => f,
        _ => panic!(),
    };

    assert_eq!(true, inner_frame.is_extended()); // fails
    assert_eq!(0x12345678, inner_frame.raw_id()); // fails with id=0x678
}```

Netlink (neli) code for the CAN interfaces

It would be great to have full coverage of the Netlink API to interact with the CAN interfaces. Or even something better than what is already there. I don't have any experience with the Netlink CAN interfaces, so if anyone has some existing code to get it started, that would be helpful.

@marcelbuesing ? @jreppnow ?

Unmaintained?

This crate appears to be unmaintained. Any plans to continue supporting? If so, I'll consider making some pull-requests. If not, I might fork or consider other options.

Tokio-Async CanFd not capable of sending RemoteFrame?

I noticed that the Sync and async-io implementations of write_frame followed the CanAnyFrame usage pattern for the CanFdSocket, however the implementation in tokio.rs was only capable of sending CanFdFrames. Is there a reason for this API difference for Tokio vs async-io and sync?

Sync write_frame:
https://github.com/socketcan-rs/socketcan-rs/blob/master/src/socket.rs#L648

async-io write_frame:
https://github.com/socketcan-rs/socketcan-rs/blob/master/src/async_io.rs#L90

tokio write_frame:
https://github.com/socketcan-rs/socketcan-rs/blob/master/src/tokio.rs#L163

This is impacting a project where we are trying to send RemoteFrames over a CanFdSocket asynchronously using tokio. Do you have any information about this usecase?

Socket read and write hangs after a while

I'm trying to get this library working to connect to a CAN based motor controller. I have a fully functional implementation based on python-can and now I'm trying to port to rust. I have no issues communicating with the motor controller with the python implementation so I know my hardware is correct.

What I've noticed is if I run my code for ~10 seconds, eventually it will lock up either at an attempt to read or write data. Up until that point, I will receive heartbeat packages from the controller as expected.

Also, I can't seem to get data back from my requests. I've double checked the packets I'm sending are the same as the ones from the python implementation.

What can I do to debug this further?

non blocking write_frame

I see that write_frame and write_frame_insists serve different purpose. write_frame_insists is supposed to be blocking while write_frame isn't. So, I tried to use write_frame with expectation that it won't block and return immediately, practically just adding can frame to the tx_queue. However, I observed that between each frame, there is a delay about 1 ms. When I read socketcan app in C/C++, I found this little piece of code:

fcntl(soc, F_SETFL, O_NONBLOCK);

I forked this repo without informing you first to particularly add that line of code, because I need it right away in my project. So, what do you think to handle this issue? How do we expose this configuration? adding set_nonblocking method to CANSocket struct? Add new parameter open method?

FYI, I am using v1.6.

Async/Await

Hello,

@fpagliughi you mentioned in #28 (comment) that you were interested in having this library support async/await.

I have a fork of tokio-socketcan using the v2 interface (need to update to the latest from crates.io): https://github.com/nnarain/tokio-socketcan

Personally happy with either approach, figured we could use this issue to discuss.

Firstly, I'm not sure if it's possible to have executor agnostic async/await implementations. Maybe someone can provide insight on how that might be accomplished.

fyi @marcelbuesing @oefd

setting can interface to can fd mode does not work

I tried setting a can interface to can fd mode using socketcan-rs and set_ctrlmodes. I have something like this:

let nl_if = CanInterface::open("can0")?;
nl_if.set_ctrlmodes(CanCtrlModes::from_mode(CanCtrlMode::Fd, true))?;

It fails with Error response received from netlink: Operation not supported (os error 95).
Hmm, lets try official rcan program?

sudo ./target/debug/rcan can0 iface fd on
Error response received from netlink: Operation not supported (os error 95)

Ok, at least the provided example/reference program has the same problem. What else can I do?

sudo ip link set can0 type can fd on
RTNETLINK answers: Operation not supported

Is ip-utils also wrong or is it just me?
After fiddling around with different parameter combinations I got this to work:

sudo ip link set can0 type can bitrate 500000 dbitrate 500000 fd on

It answers with silence, but it worked:

ip -details link show can0
79: can0: <NOARP,ECHO> mtu 72 qdisc noop state DOWN mode DEFAULT group default qlen 10
    link/can  promiscuity 0 minmtu 0 maxmtu 0 
    can <FD> state STOPPED (berr-counter tx 0 rx 0) restart-ms 0 
          bitrate 500000 sample-point 0.875 
          tq 12 prop-seg 69 phase-seg1 70 phase-seg2 20 sjw 1
          pcan_usb_fd: tseg1 1..256 tseg2 1..128 sjw 1..128 brp 1..1024 brp-inc 1
          dbitrate 500000 dsample-point 0.875 
          dtq 62 dprop-seg 13 dphase-seg1 14 dphase-seg2 4 dsjw 1
          pcan_usb_fd: dtseg1 1..32 dtseg2 1..16 dsjw 1..16 dbrp 1..1024 dbrp-inc 1
          clock 80000000 numtxqueues 1 numrxqueues 1 gso_max_size 65536 gso_max_segs 65535 parentbus usb parentdev 1-12.2:1.0

Notice the <FD>! It is a can fd capable interface that supports fd mode on linux.
During fiddling around, i noticed, that setting to fd mode alone does not work(as seen above). When setting to fd mode, it also wants a dbitrate and bitrate at the same time. With knowing that, lets move back to rcan:

sudo ./target/debug/rcan can0 iface bitrate 500000 fd on
error: unexpected argument 'fd' found

Usage: rcan iface bitrate <bitrate>

No. It does not work. rcan only supports one parameter at a time. And so does the netlink api of socketcan-rs. Looking at CanInterface I do not see a way to set multiple parameters at the same time.
So my questions are:

  1. Am I missing something or am I doing something wrong?
  2. Is there a way using public socketcan-rs api for doing what I need?
  3. If not, how can we best resolve this?
    I do see InterfaceCanParams as part of InterfaceDetails as a candidate that would allow setting all fields as needed, but it is not ideal. It has much more fields, even fields, that can only be query'd and there is also no set_details or the like on CanInterface. That needs to be implemented then.

What do you think?

Thanks,
Lars

Ideas for v2.0

Hey All. Thanks for all the feedback recently. It feels good to finally get some inertia on this crate after so long!

I'd like to get v2.0 released by the end of the year, if that's possible. Here's what I'm thinking for it:

  • Get all the outstanding issues and PR's done:

  • Make better use of the upstream crates.

    • Some of the low-level types, constants, and other definitions have since been added to the upstream crates, like nix. So give a quick review and remove whatever possible from this one.
  • [Maybe] Consolidate the error types or make a wrapping Error type with a Result

    • Lately I've been finding it tough to use a lot of libraries in an application when each has a dozen error types.
    • It's nice when a library has a single, top-level error to say, for example, "Was this a CAN error?"
  • Overall cleanup:

    • Better documentation on all the types, functions, modules, etc
    • More restrictive linte like #![deny(missing_docs)], etc
    • Unit Tests!
  • Timestamps

    • The whole reason I wanted to update this crate in the first place was because I needed hardware timestamps! Now I can't even remember if I did anything about that.

After that is finished and released, I would like to start putting together v2.1 to add full NetLink support for the CAN interfaces.

2.0 ?

Your README was updated 4 months ago with a nice promise

 this library is currently being updated for a v2.0 release

Questions:

  • are you planning to push those new update as a Rust crate 2.0? if then do you already have a target date ?
  • I also found https://github.com/xR3b0rn/socketcan2-rs which is a much smaller interface and that does not force a dependence to embedded-hal

Would be cool to have unique SocketCan interface for Linux that pull a minimal set of dependencies.
thank you

Fetch stats or stats64 with socketcan

I am a beginner in Rust and working with the socketcan-rs crate. I am trying to fetch the statistics available inside the /sys/class/net//statistics/ directory. However, I haven't been able to find a way to do this.

I also attempted to combine the netlink_packet_route crate with socketcan, but I encountered an "Address is already in use" error.

Could you please let me know if there is support for fetching these statistics using socketcan? Alternatively, is there a way to successfully combine both crates?

Thank you for your assistance.

Cross-platform support

Inherently, there is no need to use the kernel driver for this, since at least some of the features of this crate could be used also on MacOS or Windows. Using conditional compilation and features it might be possible to make it truly cross-platform

No way to mutate CanFrame

I'm currently writing a rust lib for uavcan. I'm planning to use socketcan as the main testing platform (for convenience reasons).

The way the CanFrame is currently structured there's no way to mutate the dlc/data after a frame has been created. That means I will have to work with an intermediate structure until the moment I'm ready to transfer, then convert it into a socketcan::CanFrame.

Would you mind exposing some methods which makes it possible to implement something similar to the following trait?

pub trait TransferFrame {
/// Maximum data length the transfer protocol supports.
const MAX_DATA_LENGTH: usize;

/// Create a new TransferFrame with id: id, and length 0.
/// Data length can be changed with `set_data_length(&self)`.
/// Data can be changed with `data_as_mut(&mut self)`.
fn new(id: TransferFrameID) -> Self;

/// Returns the 28 bit ID of this TransferFrame.
///
/// When deciding which frame that will be transmitted,
/// the ID is used to prioritze (lower ID means higher priority)
fn id(&self) -> TransferFrameID;

/// Returns a slice with the data in this TransferFrame
///
/// Length can be found by checking the length
/// of this slice `self.data().len()`
fn data(&self) -> &[u8];

/// Returns a mutable slice with the data in this TransferFrame
/// use this method to set/change the data inside this TransferFrame
fn data_as_mut(&mut self) -> &mut[u8];

/// Set the data length of this TransferFrame
///
/// ## Panics
/// `set_data_lengt(&mut self, length: usize)` should panic if `length > T::MAX_DATA_LENGTH`
fn set_data_length(&mut self, length: usize);

Creating Error Frames For Test Purposes

Hello,

In socketcan 1.7.0, CanFrame::new(...) had parameters as options to indicate that the canframe built was intended as an Error frame. See: https://docs.rs/socketcan/1.7.0/socketcan/struct.CANFrame.html#method.new

In 2.0.0, it appears that we cannot construct CanErrorFrames and that this is intentionally not supported. See: https://docs.rs/socketcan/2.0.0/src/socketcan/frame.rs.html#752-754

For my application, I want to mock something that returns CanFrame data.
I want to be able to create CanErrorFrames to test our error cases.

How would I go about creating a CanErrorFrame for the purposes of mocking in tests? This is currently a requirement for me to move my app from 1.7.0 to 2.0.0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.