socketcan 3.6.0

Linux SocketCAN library. Send and receive CAN frames via CANbus on Linux.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! # tokio-socketcan
//!
//! Connective plumbing between the socketcan crate
//! and the tokio asynchronous I/O system
//!
//! # Usage
//!
//! The [socketcan](https://docs.rs/socketcan/1.7.0/socketcan/)
//! crate's documentation is valuable as the api used by
//! tokio-socketcan is largely identical to the socketcan one.
//!
//! An example echo server:
//!
//! ```no_run
//! use futures_util::stream::StreamExt;
//! use socketcan::{Error, tokio::CanSocket};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Error> {
//!     let mut socket_rx = CanSocket::open("vcan0")?;
//!     let socket_tx = CanSocket::open("vcan0")?;
//!
//!     while let Some(Ok(frame)) = socket_rx.next().await {
//!         socket_tx.write_frame(frame).await;
//!     }
//!     Ok(())
//! }
//! ```
use crate::{
    frame::AsPtr, timestamp::CanTimestamps, CanAddr, CanAnyFrame, CanFrame, Error, IoResult,
    Result, Socket, SocketOptions,
};
use futures::{prelude::*, ready, task::Context};
use std::{
    io::{Read, Write},
    os::unix::{
        io::{AsRawFd, OwnedFd},
        prelude::RawFd,
    },
    pin::Pin,
    task::Poll,
    time::{Duration, SystemTime},
};
use tokio::io::unix::AsyncFd;
use tokio::io::Interest;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

/// An asynchronous I/O wrapped CanSocket
#[derive(Debug)]
pub struct AsyncCanSocket<T: Socket>(AsyncFd<T>);

impl<T: Socket + From<OwnedFd>> AsyncCanSocket<T> {
    /// Open a named CAN device such as "can0, "vcan0", etc
    pub fn open(ifname: &str) -> IoResult<Self> {
        let sock = T::open(ifname)?;
        sock.set_nonblocking(true)?;
        Ok(Self(AsyncFd::new(sock)?))
    }

    /// Open CAN device by kernel interface number
    pub fn open_if(ifindex: u32) -> IoResult<Self> {
        let sock = T::open_iface(ifindex)?;
        sock.set_nonblocking(true)?;
        Ok(Self(AsyncFd::new(sock)?))
    }

    /// Open a CAN socket by address
    pub fn open_addr(addr: &CanAddr) -> IoResult<Self> {
        let sock = T::open_addr(addr)?;
        sock.set_nonblocking(true)?;
        Ok(Self(AsyncFd::new(sock)?))
    }
}

impl<T: Socket> SocketOptions for AsyncCanSocket<T> {}

impl<T: Socket> AsRawFd for AsyncCanSocket<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.0.as_raw_fd()
    }
}

/// Asynchronous Can Socket
pub type CanSocket = AsyncCanSocket<crate::CanSocket>;

impl CanSocket {
    /// Write a CAN frame to the socket asynchronously
    pub async fn write_frame(&self, frame: CanFrame) -> IoResult<()> {
        self.0
            .async_io(Interest::WRITABLE, |inner| inner.write_frame(&frame))
            .await
    }

    /// Attempt to write a CAN frame to the socket without blocking.
    ///
    /// Returns `WouldBlock` if the send buffer is full.
    ///
    /// Bypasses the tokio readiness reactor: this call goes straight to
    /// the underlying non-blocking fd, so no `AsyncFd` readiness event is
    /// consumed. Mixing with [`write_frame`](Self::write_frame) on the same
    /// socket is safe — the async path will simply re-check OS-level
    /// readiness on its next poll and may briefly round-trip through
    /// `WouldBlock` before re-arming.
    pub fn try_write_frame(&self, frame: CanFrame) -> IoResult<()> {
        self.0.get_ref().write_frame(&frame)
    }

    /// Read a CAN frame from the socket asynchronously
    pub async fn read_frame(&self) -> IoResult<CanFrame> {
        self.0
            .async_io(Interest::READABLE, |inner| inner.read_frame())
            .await
    }

    /// Attempt to read a CAN frame from the socket without blocking.
    ///
    /// Returns `WouldBlock` if no frame is immediately available.
    ///
    /// Bypasses the tokio readiness reactor: this call goes straight to
    /// the underlying non-blocking fd, so no `AsyncFd` readiness event is
    /// consumed. Mixing with [`read_frame`](Self::read_frame) on the same
    /// socket is safe — the async path will simply re-check OS-level
    /// readiness on its next poll and may briefly round-trip through
    /// `WouldBlock` before re-arming.
    pub fn try_read_frame(&self) -> IoResult<CanFrame> {
        self.0.get_ref().read_frame()
    }

    /// Returns `true` if the bound interface supports hardware receive timestamps.
    pub fn has_hw_timestamps(&self) -> bool {
        self.0.get_ref().has_hw_timestamps()
    }

    /// Read a CAN frame and its socket-layer arrival timestamp asynchronously.
    ///
    /// Requires [`SocketOptions::set_recv_timestamp`] to be called first.
    pub async fn read_frame_with_timestamp(&self) -> IoResult<(CanFrame, SystemTime)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_timestamp()
            })
            .await
    }

    /// Read a CAN frame and all available timestamps asynchronously.
    ///
    /// Timestamp fields are `None` for modes not enabled on the socket.
    pub async fn read_frame_with_timestamps(&self) -> IoResult<(CanFrame, CanTimestamps)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_timestamps()
            })
            .await
    }

    /// Read a CAN frame and its raw hardware clock timestamp asynchronously.
    ///
    /// Requires [`SocketOptions::set_timestamping`] with
    /// `SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_OPT_CMSG` to be called first.
    pub async fn read_frame_with_hw_timestamp(&self) -> IoResult<(CanFrame, Duration)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_hw_timestamp()
            })
            .await
    }
}

impl Stream for CanSocket {
    type Item = Result<CanFrame>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        loop {
            let mut ready_guard = ready!(self.0.poll_read_ready(cx))?;
            match ready_guard.try_io(|inner| inner.get_ref().read_frame()) {
                Ok(result) => return Poll::Ready(Some(result.map_err(|e| e.into()))),
                Err(_would_block) => continue,
            }
        }
    }
}

impl Sink<CanFrame> for CanSocket {
    type Error = Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        let _ = ready!(self.0.poll_write_ready(cx))?;
        Poll::Ready(Ok(()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        // Nothing to flush; the underlying fd closes on drop.
        Poll::Ready(Ok(()))
    }

    fn start_send(self: Pin<&mut Self>, item: CanFrame) -> Result<()> {
        // `poll_ready` already cleared write-readiness, so a single
        // non-blocking write is sufficient — no need to busy-retry.
        self.0.get_ref().write_frame(&item)?;
        Ok(())
    }
}

impl AsyncRead for CanSocket {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<IoResult<()>> {
        loop {
            let mut guard = ready!(self.0.poll_read_ready_mut(cx))?;

            let unfilled = buf.initialize_unfilled();
            match guard.try_io(|inner| inner.get_mut().read(unfilled)) {
                Ok(Ok(len)) => {
                    buf.advance(len);
                    return Poll::Ready(Ok(()));
                }
                Ok(Err(err)) => return Poll::Ready(Err(err)),
                Err(_would_block) => continue,
            }
        }
    }
}

impl AsyncWrite for CanSocket {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<IoResult<usize>> {
        loop {
            let mut guard = ready!(self.0.poll_write_ready_mut(cx))?;

            match guard.try_io(|inner| inner.get_mut().write(buf)) {
                Ok(result) => return Poll::Ready(result),
                Err(_would_block) => continue,
            }
        }
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        Poll::Ready(Ok(()))
    }
}

/// An Asynchronous CAN FD Socket
pub type CanFdSocket = AsyncCanSocket<crate::CanFdSocket>;

impl CanFdSocket {
    /// Write a CAN FD frame to the socket asynchronously
    pub async fn write_frame<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<CanAnyFrame> + AsPtr,
    {
        self.0
            .async_io(Interest::WRITABLE, |inner| inner.write_frame(frame))
            .await
    }

    /// Attempt to write a CAN frame to the socket without blocking.
    ///
    /// Returns `WouldBlock` if the send buffer is full.
    ///
    /// Bypasses the tokio readiness reactor: this call goes straight to
    /// the underlying non-blocking fd, so no `AsyncFd` readiness event is
    /// consumed. Mixing with [`write_frame`](Self::write_frame) on the same
    /// socket is safe — the async path will simply re-check OS-level
    /// readiness on its next poll and may briefly round-trip through
    /// `WouldBlock` before re-arming.
    pub fn try_write_frame<F>(&self, frame: &F) -> IoResult<()>
    where
        F: Into<CanAnyFrame> + AsPtr,
    {
        self.0.get_ref().write_frame(frame)
    }

    /// Reads a CAN FD frame from the socket asynchronously
    pub async fn read_frame(&self) -> IoResult<CanAnyFrame> {
        self.0
            .async_io(Interest::READABLE, |inner| inner.read_frame())
            .await
    }

    /// Attempt to read a CAN frame from the socket without blocking.
    ///
    /// Returns `WouldBlock` if no frame is immediately available.
    ///
    /// Bypasses the tokio readiness reactor: this call goes straight to
    /// the underlying non-blocking fd, so no `AsyncFd` readiness event is
    /// consumed. Mixing with [`read_frame`](Self::read_frame) on the same
    /// socket is safe — the async path will simply re-check OS-level
    /// readiness on its next poll and may briefly round-trip through
    /// `WouldBlock` before re-arming.
    pub fn try_read_frame(&self) -> IoResult<CanAnyFrame> {
        self.0.get_ref().read_frame()
    }

    /// Returns `true` if the bound interface supports hardware receive timestamps.
    pub fn has_hw_timestamps(&self) -> bool {
        self.0.get_ref().has_hw_timestamps()
    }

    /// Read a CAN frame and its socket-layer arrival timestamp asynchronously.
    ///
    /// Requires [`SocketOptions::set_recv_timestamp`] to be called first.
    pub async fn read_frame_with_timestamp(&self) -> IoResult<(CanAnyFrame, SystemTime)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_timestamp()
            })
            .await
    }

    /// Read a CAN frame and all available timestamps asynchronously.
    ///
    /// Timestamp fields are `None` for modes not enabled on the socket.
    pub async fn read_frame_with_timestamps(&self) -> IoResult<(CanAnyFrame, CanTimestamps)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_timestamps()
            })
            .await
    }

    /// Read a CAN frame and its raw hardware clock timestamp asynchronously.
    ///
    /// Requires [`SocketOptions::set_timestamping`] with
    /// `SOF_TIMESTAMPING_RX_HARDWARE | SOF_TIMESTAMPING_OPT_CMSG` to be called first.
    pub async fn read_frame_with_hw_timestamp(&self) -> IoResult<(CanAnyFrame, Duration)> {
        self.0
            .async_io(Interest::READABLE, |inner| {
                inner.read_frame_with_hw_timestamp()
            })
            .await
    }
}

impl Stream for CanFdSocket {
    type Item = Result<CanAnyFrame>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        loop {
            let mut ready_guard = ready!(self.0.poll_read_ready(cx))?;
            match ready_guard.try_io(|inner| inner.get_ref().read_frame()) {
                Ok(result) => return Poll::Ready(Some(result.map_err(|e| e.into()))),
                Err(_would_block) => continue,
            }
        }
    }
}

impl Sink<CanAnyFrame> for CanFdSocket {
    type Error = Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        let _ = ready!(self.0.poll_write_ready(cx))?;
        Poll::Ready(Ok(()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        // Nothing to flush; the underlying fd closes on drop.
        Poll::Ready(Ok(()))
    }

    fn start_send(self: Pin<&mut Self>, item: CanAnyFrame) -> Result<()> {
        // `poll_ready` already cleared write-readiness, so a single
        // non-blocking write is sufficient — no need to busy-retry.
        self.0.get_ref().write_frame(&item)?;
        Ok(())
    }
}

impl AsyncRead for CanFdSocket {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<IoResult<()>> {
        loop {
            let mut guard = ready!(self.0.poll_read_ready_mut(cx))?;

            let unfilled = buf.initialize_unfilled();
            match guard.try_io(|inner| inner.get_mut().read(unfilled)) {
                Ok(Ok(len)) => {
                    buf.advance(len);
                    return Poll::Ready(Ok(()));
                }
                Ok(Err(err)) => return Poll::Ready(Err(err)),
                Err(_would_block) => continue,
            }
        }
    }
}

impl AsyncWrite for CanFdSocket {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<IoResult<usize>> {
        loop {
            let mut guard = ready!(self.0.poll_write_ready_mut(cx))?;

            match guard.try_io(|inner| inner.get_mut().write(buf)) {
                Ok(result) => return Poll::Ready(result),
                Err(_would_block) => continue,
            }
        }
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<IoResult<()>> {
        Poll::Ready(Ok(()))
    }
}

/////////////////////////////////////////////////////////////////////////////

#[cfg(feature = "vcan_tests")]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        frame::{can_frame_default, AsPtr},
        CanFdFrame, CanFrame, Frame, IoErrorKind, StandardId,
    };
    use embedded_can::Frame as EmbeddedFrame;
    use futures::{select, try_join};
    use futures_timer::Delay;
    use serial_test::serial;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    const TIMEOUT: Duration = Duration::from_millis(100);

    /// Receive a frame from the CanSocket
    async fn recv_frame(socket: CanSocket) -> Result<CanSocket> {
        select!(
            frame = socket.read_frame().fuse() => if let Ok(_frame) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Receive a frame from the CanSocket using the `Stream` trait
    async fn recv_frame_with_stream(mut socket: CanSocket) -> Result<CanSocket> {
        select!(
            frame = socket.next().fuse() => if let Some(_frame) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Receive a frame from the CanSocket using the `tokio::io::AsyncRead` trait
    async fn recv_frame_with_async_read(mut socket: CanSocket) -> Result<CanSocket> {
        let mut frame = can_frame_default();
        select!(
            // SAFETY: `frame` is fully zero-initialised by `can_frame_default`.
            frame = socket.read_exact(unsafe { crate::as_bytes_mut(&mut frame) }).fuse() => if let Ok(_bytes_read) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Write a test frame to the CanSocket
    async fn write_frame(socket: &CanSocket) -> Result<()> {
        let test_frame = CanFrame::new(StandardId::new(0x1).unwrap(), &[0]).unwrap();
        socket.write_frame(test_frame).await?;
        Ok(())
    }

    fn try_write_frame(socket: &CanSocket) -> Result<()> {
        let test_frame = CanFrame::new(StandardId::new(0x1).unwrap(), &[0]).unwrap();
        socket.try_write_frame(test_frame)?;
        Ok(())
    }

    /// Write a test frame to the CanSocket using the `tokio::io::AsyncWrite` trait
    async fn write_frame_with_async_write(socket: &mut CanSocket) -> Result<()> {
        let test_frame = CanFrame::new(StandardId::new(0x1).unwrap(), &[0]).unwrap();
        socket.write(test_frame.as_bytes()).await?;
        Ok(())
    }

    /// Receive a frame from the CanFdSocket
    async fn recv_frame_fd(socket: CanFdSocket) -> Result<CanFdSocket> {
        select!(
            frame = socket.read_frame().fuse() => if let Ok(_frame) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Receive a frame from the CanFdSocket using the `Stream` trait
    async fn recv_frame_fd_with_stream(mut socket: CanFdSocket) -> Result<CanFdSocket> {
        select!(
            frame = socket.next().fuse() => if let Some(_frame) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Receive a frame from the CanFdSocket using the `tokio::io::AsyncWrite` trait
    async fn recv_frame_fd_with_async_read(mut socket: CanFdSocket) -> Result<CanFdSocket> {
        let mut frame = can_frame_default();
        select!(
            // SAFETY: `frame` is fully zero-initialised by `can_frame_default`.
            frame = socket.read_exact(unsafe { crate::as_bytes_mut(&mut frame) }).fuse() => if let Ok(_bytes_read) = frame { Ok(socket) } else { panic!("unexpected") },
            _timeout = Delay::new(TIMEOUT).fuse() => Err(IoErrorKind::TimedOut.into()),
        )
    }

    /// Write a test CANFD frame to the CanSocket
    async fn write_frame_fd_canfd(socket: &CanFdSocket) -> Result<()> {
        let test_frame =
            CanFdFrame::new(StandardId::new(0x1).unwrap(), &[0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap();
        socket.write_frame(&test_frame).await?;
        Ok(())
    }

    fn try_write_frame_fd_canfd(socket: &CanFdSocket) -> Result<()> {
        let test_frame =
            CanFdFrame::new(StandardId::new(0x1).unwrap(), &[0, 0, 0, 0, 0, 0, 0, 0, 0]).unwrap();
        socket.try_write_frame(&test_frame)?;
        Ok(())
    }

    /// Write a test CAN frame to the CanSocket
    async fn write_frame_fd_can(socket: &CanFdSocket) -> Result<()> {
        let test_frame = CanFrame::new(StandardId::new(0x1).unwrap(), &[0]).unwrap();
        socket.write_frame(&test_frame).await?;
        Ok(())
    }

    /// Write a test frame to the CanSocket using the `tokio::io::AsyncWrite` trait
    async fn write_frame_fd_with_async_write(socket: &mut CanFdSocket) -> Result<()> {
        let test_frame = CanFdFrame::new(StandardId::new(0x1).unwrap(), &[0]).unwrap();
        socket.write(test_frame.as_bytes()).await?;
        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive() -> Result<()> {
        let socket1 = CanSocket::open("vcan0").unwrap();
        let socket2 = CanSocket::open("vcan0").unwrap();

        let send_frames = future::try_join(write_frame(&socket1), write_frame(&socket1));

        let recv_frames = async {
            let socket2 = recv_frame(socket2).await?;
            let _socket2 = recv_frame(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive_with_stream() -> Result<()> {
        let socket1 = CanSocket::open("vcan0").unwrap();
        let socket2 = CanSocket::open("vcan0").unwrap();

        let send_frames = future::try_join(write_frame(&socket1), write_frame(&socket1));

        let recv_frames = async {
            let socket2 = recv_frame_with_stream(socket2).await?;
            let _socket2 = recv_frame_with_stream(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_asyncread_and_asyncwrite() -> Result<()> {
        let mut socket1 = CanSocket::open("vcan0").unwrap();
        let socket2 = CanSocket::open("vcan0").unwrap();

        let send_frames = write_frame_with_async_write(&mut socket1);

        let recv_frames = async {
            let _socket2 = recv_frame_with_async_read(socket2).await?;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_tryread_and_trywrite() -> Result<()> {
        let socket1 = CanSocket::open("vcan0").unwrap();
        let socket2 = CanSocket::open("vcan0").unwrap();

        let result = socket2.try_read_frame();
        assert!(result.is_err(), "Expected no frames available");
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::WouldBlock);

        try_write_frame(&socket1)?;
        tokio::time::sleep(Duration::from_millis(100)).await;

        socket2.try_read_frame()?;

        let result = socket2.try_read_frame();
        assert!(result.is_err(), "Expected no frames available");
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::WouldBlock);

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive_can_fd_canfd() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let send_frames = future::try_join(
            write_frame_fd_canfd(&socket1),
            write_frame_fd_canfd(&socket1),
        );

        let recv_frames = async {
            let socket2 = recv_frame_fd(socket2).await?;
            let _socket2 = recv_frame_fd(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive_can_fd_can() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let send_frames =
            future::try_join(write_frame_fd_can(&socket1), write_frame_fd_can(&socket1));

        let recv_frames = async {
            let socket2 = recv_frame_fd(socket2).await?;
            let _socket2 = recv_frame_fd(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive_can_fd_canfd_with_stream() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let send_frames = future::try_join(
            write_frame_fd_canfd(&socket1),
            write_frame_fd_canfd(&socket1),
        );

        let recv_frames = async {
            let socket2 = recv_frame_fd_with_stream(socket2).await?;
            let _socket2 = recv_frame_fd_with_stream(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_receive_can_fd_can_with_stream() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let send_frames =
            future::try_join(write_frame_fd_can(&socket1), write_frame_fd_can(&socket1));

        let recv_frames = async {
            let socket2 = recv_frame_fd_with_stream(socket2).await?;
            let _socket2 = recv_frame_fd_with_stream(socket2).await;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_asyncread_and_asyncwrite_fd() -> Result<()> {
        let mut socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let send_frames = write_frame_fd_with_async_write(&mut socket1);

        let recv_frames = async {
            let _socket2 = recv_frame_fd_with_async_read(socket2).await?;
            Ok(())
        };

        try_join!(recv_frames, send_frames)?;

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_sink_stream() -> Result<()> {
        let socket1 = CanSocket::open("vcan0").unwrap();
        let socket2 = CanSocket::open("vcan0").unwrap();

        let frame_id_1 = CanFrame::from_raw_id(0x01, &[0u8]).unwrap();
        let frame_id_2 = CanFrame::from_raw_id(0x02, &[0u8]).unwrap();
        let frame_id_3 = CanFrame::from_raw_id(0x03, &[0u8]).unwrap();

        let (mut sink, _stream) = socket1.split();
        let (_sink, stream) = socket2.split();

        let count_ids_less_than_3 = stream
            .map(|x| x.unwrap())
            .take_while(|frame| future::ready(frame.raw_id() < 3))
            .fold(0u8, |acc, _frame| async move { acc + 1 });

        let send_frames = async {
            let _frame_1 = sink.send(frame_id_1).await?;
            let _frame_2 = sink.send(frame_id_2).await?;
            let _frame_3 = sink.send(frame_id_3).await?;
            println!("Sent 3 frames");
            Ok::<(), Error>(())
        };

        let (x, frame_send_r) = future::join(count_ids_less_than_3, send_frames).await;
        frame_send_r?;

        assert_eq!(x, 2);

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_sink_stream_fd_canfd() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let frame_id_1 = CanFdFrame::from_raw_id(0x01, &[0u8]).unwrap();
        let frame_id_2 = CanFdFrame::from_raw_id(0x02, &[0u8]).unwrap();
        let frame_id_3 = CanFdFrame::from_raw_id(0x03, &[0u8]).unwrap();

        let (mut sink, _stream) = socket1.split();
        let (_sink, stream) = socket2.split();

        let count_ids_less_than_3 = stream
            .map(|x| x.unwrap())
            .take_while(|frame| {
                if let CanAnyFrame::Fd(frame) = frame {
                    future::ready(frame.raw_id() < 3)
                } else {
                    future::ready(false)
                }
            })
            .fold(0u8, |acc, _frame| async move { acc + 1 });

        let send_frames = async {
            let _frame_1 = sink.send(frame_id_1.into()).await?;
            let _frame_2 = sink.send(frame_id_2.into()).await?;
            let _frame_3 = sink.send(frame_id_3.into()).await?;
            println!("Sent 3 frames");
            Ok::<(), Error>(())
        };

        let (x, frame_send_r) = future::join(count_ids_less_than_3, send_frames).await;
        frame_send_r?;

        assert_eq!(x, 2);

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_sink_stream_fd_can() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let frame_id_1 = CanFrame::from_raw_id(0x01, &[0u8]).unwrap();
        let frame_id_2 = CanFrame::from_raw_id(0x02, &[0u8]).unwrap();
        let frame_id_3 = CanFrame::from_raw_id(0x03, &[0u8]).unwrap();

        let (mut sink, _stream) = socket1.split();
        let (_sink, stream) = socket2.split();

        let count_ids_less_than_3 = stream
            .map(|x| x.unwrap())
            .take_while(|frame| {
                if let CanAnyFrame::Normal(frame) = frame {
                    future::ready(frame.raw_id() < 3)
                } else {
                    future::ready(false)
                }
            })
            .fold(0u8, |acc, _frame| async move { acc + 1 });

        let send_frames = async {
            let _frame_1 = sink.send(frame_id_1.into()).await?;
            let _frame_2 = sink.send(frame_id_2.into()).await?;
            let _frame_3 = sink.send(frame_id_3.into()).await?;
            println!("Sent 3 frames");
            Ok::<(), Error>(())
        };

        let (x, frame_send_r) = future::join(count_ids_less_than_3, send_frames).await;
        frame_send_r?;

        assert_eq!(x, 2);

        Ok(())
    }

    #[serial]
    #[tokio::test]
    async fn test_tryread_and_trywrite_fd() -> Result<()> {
        let socket1 = CanFdSocket::open("vcan0").unwrap();
        let socket2 = CanFdSocket::open("vcan0").unwrap();

        let result = socket2.try_read_frame();
        assert!(result.is_err(), "Expected no frames available");
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::WouldBlock);

        try_write_frame_fd_canfd(&socket1)?;
        tokio::time::sleep(Duration::from_millis(100)).await;

        socket2.try_read_frame()?;

        let result = socket2.try_read_frame();
        assert!(result.is_err(), "Expected no frames available");
        assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::WouldBlock);

        Ok(())
    }
}