xoq 0.3.6

X-Embodiment over QUIC - P2P and relay communication for robotics
Documentation
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
//! CAN bridge server - bridges local CAN interface to remote clients over iroh P2P.
//!
//! Architecture: 2 persistent OS threads (reader + writer) communicate with the
//! BridgeServer via Vec<u8> channels. Wire encoding/decoding happens in the threads.

use anyhow::Result;
use socketcan::Socket;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::bridge_server::{BridgeServer, MoqConfig};
use crate::can::{CanFdFrame, CanFrame};
use crate::can_types::{wire, AnyCanFrame};

/// Read the CAN bus error state by parsing sysfs or `ip -details link show`.
/// Returns e.g. "ERROR-ACTIVE", "ERROR-PASSIVE", "BUS-OFF", or None if unknown.
fn can_bus_state(interface: &str) -> Option<String> {
    if let Ok(s) = std::fs::read_to_string(format!("/sys/class/net/{}/can_state", interface)) {
        return Some(s.trim().to_uppercase());
    }
    let output = std::process::Command::new("ip")
        .args(["-details", "link", "show", interface])
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("can ") {
            if let Some(pos) = rest.find("state ") {
                let after = &rest[pos + 6..];
                let state = after.split_whitespace().next()?;
                return Some(state.to_string());
            }
        }
    }
    None
}

/// A server that bridges a local CAN interface to remote clients over iroh P2P.
/// Optionally broadcasts CAN state via MoQ for browser monitoring.
pub struct CanServer {
    interface: String,
    bridge: BridgeServer,
}

/// Reader thread for CAN FD sockets. Encodes frames to wire format Vec<u8>.
fn can_reader_thread_fd(
    socket: Arc<socketcan::CanFdSocket>,
    tx: tokio::sync::mpsc::Sender<Vec<u8>>,
    moq_tx: Option<tokio::sync::mpsc::Sender<Vec<u8>>>,
    write_count: Arc<AtomicU64>,
) {
    let mut last_read = Instant::now();
    let mut would_blocks: u32 = 0;
    let mut timed_outs: u32 = 0;
    let mut writes_at_gap_start: u64 = 0;
    // MoQ batch buffer: accumulate frames, flush on CAN bus gap (timeout/wouldblock)
    let mut moq_batch = Vec::with_capacity(256);
    let mut moq_batch_frames = 0u32;
    let mut moq_flush_count = 0u64;
    let mut moq_total_frames = 0u64;
    let mut moq_last_log = Instant::now();
    loop {
        match socket.read_frame() {
            Ok(frame) => {
                let gap = last_read.elapsed();
                let writes_now = write_count.load(Ordering::Relaxed);
                let writes_during = writes_now - writes_at_gap_start;
                if gap > Duration::from_millis(50) && writes_during >= 3 {
                    tracing::debug!(
                        "CAN response delay: {:.1}ms ({} timed_out, {} would_block, {} writes during gap)",
                        gap.as_secs_f64() * 1000.0,
                        timed_outs,
                        would_blocks,
                        writes_during,
                    );
                }
                last_read = Instant::now();
                would_blocks = 0;
                timed_outs = 0;
                writes_at_gap_start = writes_now;
                let any_frame = match frame {
                    socketcan::CanAnyFrame::Normal(f) => match CanFrame::try_from(f) {
                        Ok(cf) => AnyCanFrame::Can(cf),
                        Err(e) => {
                            tracing::warn!("CAN frame conversion error: {}", e);
                            continue;
                        }
                    },
                    socketcan::CanAnyFrame::Fd(f) => match CanFdFrame::try_from(f) {
                        Ok(cf) => AnyCanFrame::CanFd(cf),
                        Err(e) => {
                            tracing::warn!("CAN FD frame conversion error: {}", e);
                            continue;
                        }
                    },
                    socketcan::CanAnyFrame::Remote(_) | socketcan::CanAnyFrame::Error(_) => {
                        continue;
                    }
                };
                let bytes = wire::encode(&any_frame);
                // Accumulate for MoQ batch (flushed on bus gap)
                if moq_tx.is_some() {
                    moq_batch.extend_from_slice(&bytes);
                    moq_batch_frames += 1;
                }
                if tx.blocking_send(bytes).is_err() {
                    break;
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                would_blocks += 1;
                // Bus gap — flush MoQ batch if any frames accumulated
                if !moq_batch.is_empty() {
                    if let Some(ref moq) = moq_tx {
                        moq_flush_count += 1;
                        moq_total_frames += moq_batch_frames as u64;
                        if moq.try_send(moq_batch.clone()).is_err() {
                            tracing::debug!("MoQ channel full, dropping batch");
                        }
                        if moq_last_log.elapsed() >= Duration::from_secs(10) {
                            tracing::info!(
                                "CAN reader MoQ: {} flushes, {} frames, {:.1} frames/flush, {} bytes last",
                                moq_flush_count, moq_total_frames,
                                moq_total_frames as f64 / moq_flush_count.max(1) as f64,
                                moq_batch.len(),
                            );
                            moq_last_log = Instant::now();
                        }
                        moq_batch.clear();
                        moq_batch_frames = 0;
                    }
                }
                continue;
            }
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
                timed_outs += 1;
                // Bus gap — flush MoQ batch if any frames accumulated
                if !moq_batch.is_empty() {
                    if let Some(ref moq) = moq_tx {
                        moq_flush_count += 1;
                        moq_total_frames += moq_batch_frames as u64;
                        if moq.try_send(moq_batch.clone()).is_err() {
                            tracing::debug!("MoQ channel full, dropping batch");
                        }
                        if moq_last_log.elapsed() >= Duration::from_secs(10) {
                            tracing::info!(
                                "CAN reader MoQ: {} flushes, {} frames, {:.1} frames/flush, {} bytes last",
                                moq_flush_count, moq_total_frames,
                                moq_total_frames as f64 / moq_flush_count.max(1) as f64,
                                moq_batch.len(),
                            );
                            moq_last_log = Instant::now();
                        }
                        moq_batch.clear();
                        moq_batch_frames = 0;
                    }
                }
                continue;
            }
            Err(e) => {
                tracing::warn!("CAN read error (ignoring): {}", e);
                std::thread::sleep(Duration::from_millis(10));
            }
        }
    }
}

/// Reader thread for standard CAN sockets. Encodes frames to wire format Vec<u8>.
fn can_reader_thread_std(
    socket: Arc<socketcan::CanSocket>,
    tx: tokio::sync::mpsc::Sender<Vec<u8>>,
    moq_tx: Option<tokio::sync::mpsc::Sender<Vec<u8>>>,
    write_count: Arc<AtomicU64>,
) {
    let mut last_read = Instant::now();
    let mut would_blocks: u32 = 0;
    let mut timed_outs: u32 = 0;
    let mut writes_at_gap_start: u64 = 0;
    // MoQ batch buffer: accumulate frames, flush on CAN bus gap (timeout/wouldblock)
    let mut moq_batch = Vec::with_capacity(256);
    let mut moq_batch_frames = 0u32;
    let mut moq_flush_count = 0u64;
    let mut moq_total_frames = 0u64;
    let mut moq_last_log = Instant::now();
    loop {
        match socket.read_frame() {
            Ok(frame) => {
                let gap = last_read.elapsed();
                let writes_now = write_count.load(Ordering::Relaxed);
                let writes_during = writes_now - writes_at_gap_start;
                if gap > Duration::from_millis(50) && writes_during >= 3 {
                    tracing::debug!(
                        "CAN response delay: {:.1}ms ({} timed_out, {} would_block, {} writes during gap)",
                        gap.as_secs_f64() * 1000.0,
                        timed_outs,
                        would_blocks,
                        writes_during,
                    );
                }
                last_read = Instant::now();
                would_blocks = 0;
                timed_outs = 0;
                writes_at_gap_start = writes_now;
                let any_frame = match CanFrame::try_from(frame) {
                    Ok(cf) => AnyCanFrame::Can(cf),
                    Err(e) => {
                        tracing::warn!("CAN frame conversion error: {}", e);
                        continue;
                    }
                };
                let bytes = wire::encode(&any_frame);
                // Accumulate for MoQ batch (flushed on bus gap)
                if moq_tx.is_some() {
                    moq_batch.extend_from_slice(&bytes);
                    moq_batch_frames += 1;
                }
                if tx.blocking_send(bytes).is_err() {
                    break;
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                would_blocks += 1;
                // Bus gap — flush MoQ batch if any frames accumulated
                if !moq_batch.is_empty() {
                    if let Some(ref moq) = moq_tx {
                        moq_flush_count += 1;
                        moq_total_frames += moq_batch_frames as u64;
                        if moq.try_send(moq_batch.clone()).is_err() {
                            tracing::debug!("MoQ channel full, dropping batch");
                        }
                        if moq_last_log.elapsed() >= Duration::from_secs(10) {
                            tracing::info!(
                                "CAN reader MoQ: {} flushes, {} frames, {:.1} frames/flush, {} bytes last",
                                moq_flush_count, moq_total_frames,
                                moq_total_frames as f64 / moq_flush_count.max(1) as f64,
                                moq_batch.len(),
                            );
                            moq_last_log = Instant::now();
                        }
                        moq_batch.clear();
                        moq_batch_frames = 0;
                    }
                }
                continue;
            }
            Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {
                timed_outs += 1;
                // Bus gap — flush MoQ batch if any frames accumulated
                if !moq_batch.is_empty() {
                    if let Some(ref moq) = moq_tx {
                        moq_flush_count += 1;
                        moq_total_frames += moq_batch_frames as u64;
                        if moq.try_send(moq_batch.clone()).is_err() {
                            tracing::debug!("MoQ channel full, dropping batch");
                        }
                        if moq_last_log.elapsed() >= Duration::from_secs(10) {
                            tracing::info!(
                                "CAN reader MoQ: {} flushes, {} frames, {:.1} frames/flush, {} bytes last",
                                moq_flush_count, moq_total_frames,
                                moq_total_frames as f64 / moq_flush_count.max(1) as f64,
                                moq_batch.len(),
                            );
                            moq_last_log = Instant::now();
                        }
                        moq_batch.clear();
                        moq_batch_frames = 0;
                    }
                }
                continue;
            }
            Err(e) => {
                tracing::warn!("CAN read error (ignoring): {}", e);
                std::thread::sleep(Duration::from_millis(10));
            }
        }
    }
}

/// Writer thread for CAN FD sockets. Decodes wire format Vec<u8> to frames.
fn can_writer_thread_fd(
    socket: Arc<socketcan::CanFdSocket>,
    mut rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    write_count: Arc<AtomicU64>,
) {
    let write_count_ref = &write_count;
    let write_fn = |frame: &AnyCanFrame| {
        for attempt in 0..4u32 {
            let result = match frame {
                AnyCanFrame::Can(f) => match socketcan::CanFrame::try_from(f) {
                    Ok(sf) => socket.write_frame(&sf).map(|_| ()),
                    Err(e) => {
                        tracing::warn!("CAN frame conversion error on write: {}", e);
                        return;
                    }
                },
                AnyCanFrame::CanFd(f) => match socketcan::CanFdFrame::try_from(f) {
                    Ok(sf) => socket.write_frame(&sf).map(|_| ()),
                    Err(e) => {
                        tracing::warn!("CAN FD frame conversion error on write: {}", e);
                        return;
                    }
                },
            };
            if result.is_ok() {
                write_count_ref.fetch_add(1, Ordering::Relaxed);
                return;
            }
            let err = result.unwrap_err();
            if err.raw_os_error() == Some(105) && attempt < 3 {
                std::thread::sleep(Duration::from_micros(100));
                continue;
            }
            tracing::warn!("CAN write error (dropping frame): {}", err);
            return;
        }
    };

    let mut pending = Vec::new();
    let mut last_recv = Instant::now();
    while let Some(data) = rx.blocking_recv() {
        let recv_gap = last_recv.elapsed();
        last_recv = Instant::now();
        if recv_gap > Duration::from_millis(50) {
            tracing::debug!(
                "CAN writer: {:.1}ms gap between commands from network",
                recv_gap.as_secs_f64() * 1000.0,
            );
        }
        pending.extend_from_slice(&data);

        while pending.len() >= wire::FRAME_SIZE {
            match wire::decode(&pending) {
                Ok((frame, consumed)) => {
                    let write_start = Instant::now();
                    write_fn(&frame);
                    let write_dur = write_start.elapsed();
                    if write_dur > Duration::from_millis(5) {
                        tracing::debug!(
                            "CAN writer: write_frame took {:.1}ms",
                            write_dur.as_secs_f64() * 1000.0,
                        );
                    }
                    pending.drain(..consumed);
                }
                Err(e) => {
                    tracing::error!("CAN wire decode error: {}", e);
                    pending.clear();
                    break;
                }
            }
        }
    }
}

/// Writer thread for standard CAN sockets. Decodes wire format Vec<u8> to frames.
fn can_writer_thread_std(
    socket: Arc<socketcan::CanSocket>,
    mut rx: tokio::sync::mpsc::Receiver<Vec<u8>>,
    write_count: Arc<AtomicU64>,
) {
    let write_count_ref = &write_count;
    let write_fn = |frame: &AnyCanFrame| {
        for attempt in 0..4u32 {
            let result = match frame {
                AnyCanFrame::Can(f) => match socketcan::CanFrame::try_from(f) {
                    Ok(sf) => socket.write_frame(&sf).map(|_| ()),
                    Err(e) => {
                        tracing::warn!("CAN frame conversion error on write: {}", e);
                        return;
                    }
                },
                AnyCanFrame::CanFd(_) => {
                    tracing::warn!("CAN FD frame on standard CAN socket, dropping");
                    return;
                }
            };
            if result.is_ok() {
                write_count_ref.fetch_add(1, Ordering::Relaxed);
                return;
            }
            let err = result.unwrap_err();
            if err.raw_os_error() == Some(105) && attempt < 3 {
                std::thread::sleep(Duration::from_micros(100));
                continue;
            }
            tracing::warn!("CAN write error (dropping frame): {}", err);
            return;
        }
    };

    let mut pending = Vec::new();
    let mut last_recv = Instant::now();
    while let Some(data) = rx.blocking_recv() {
        let recv_gap = last_recv.elapsed();
        last_recv = Instant::now();
        if recv_gap > Duration::from_millis(50) {
            tracing::debug!(
                "CAN writer: {:.1}ms gap between commands from network",
                recv_gap.as_secs_f64() * 1000.0,
            );
        }
        pending.extend_from_slice(&data);

        while pending.len() >= wire::FRAME_SIZE {
            match wire::decode(&pending) {
                Ok((frame, consumed)) => {
                    let write_start = Instant::now();
                    write_fn(&frame);
                    let write_dur = write_start.elapsed();
                    if write_dur > Duration::from_millis(5) {
                        tracing::debug!(
                            "CAN writer: write_frame took {:.1}ms",
                            write_dur.as_secs_f64() * 1000.0,
                        );
                    }
                    pending.drain(..consumed);
                }
                Err(e) => {
                    tracing::error!("CAN wire decode error: {}", e);
                    pending.clear();
                    break;
                }
            }
        }
    }
}

impl CanServer {
    /// Create a new CAN bridge server.
    ///
    /// If `moq_relay` is provided, CAN read frames are also fan-out to a MoQ
    /// publisher for browser monitoring.
    pub async fn new(
        interface: &str,
        enable_fd: bool,
        identity_path: Option<&str>,
        iroh_relay_url: Option<&str>,
        moq_relay: Option<&str>,
        moq_path: Option<&str>,
        moq_insecure: bool,
    ) -> Result<Self> {
        // Check CAN bus state on startup — bail early if not healthy
        match can_bus_state(interface) {
            Some(ref state) if state == "ERROR-ACTIVE" => {
                tracing::info!("[{}] CAN bus state: {}", interface, state);
            }
            Some(ref state) => {
                anyhow::bail!(
                    "[{}] CAN bus is {} — interface may be down or motors unpowered. \
                     Fix: sudo ip link set {} down && sudo ip link set {} up type can bitrate 1000000 dbitrate 5000000 fd on restart-ms 100",
                    interface, state, interface, interface,
                );
            }
            None => tracing::warn!(
                "[{}] Could not read CAN bus state (will continue anyway)",
                interface
            ),
        }

        // Channels between CAN threads and BridgeServer (Vec<u8> wire-encoded)
        let (read_tx, read_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(16);
        let (write_tx, write_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(16);
        let write_count = Arc::new(AtomicU64::new(0));

        let (moq_tx, moq_rx) = if moq_relay.is_some() {
            let (tx, rx) = tokio::sync::mpsc::channel(128);
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };

        if enable_fd {
            let socket = socketcan::CanFdSocket::open(interface).map_err(|e| {
                anyhow::anyhow!("Failed to open CAN FD socket on {}: {}", interface, e)
            })?;
            socket
                .set_read_timeout(Duration::from_millis(10))
                .map_err(|e| anyhow::anyhow!("Failed to set read timeout: {}", e))?;
            tracing::info!("CAN FD socket opened on {}", interface);
            let socket = Arc::new(socket);

            let socket_reader = Arc::clone(&socket);
            let wc_reader = Arc::clone(&write_count);
            let moq_reader_tx = moq_tx.clone();
            std::thread::Builder::new()
                .name(format!("can-read-{}", interface))
                .spawn(move || {
                    can_reader_thread_fd(socket_reader, read_tx, moq_reader_tx, wc_reader)
                })?;

            let socket_writer = Arc::clone(&socket);
            let wc_writer = Arc::clone(&write_count);
            std::thread::Builder::new()
                .name(format!("can-write-{}", interface))
                .spawn(move || can_writer_thread_fd(socket_writer, write_rx, wc_writer))?;
        } else {
            let socket = socketcan::CanSocket::open(interface).map_err(|e| {
                anyhow::anyhow!("Failed to open CAN socket on {}: {}", interface, e)
            })?;
            socket
                .set_read_timeout(Duration::from_millis(10))
                .map_err(|e| anyhow::anyhow!("Failed to set read timeout: {}", e))?;
            tracing::info!("CAN socket opened on {}", interface);
            let socket = Arc::new(socket);

            let socket_reader = Arc::clone(&socket);
            let wc_reader = Arc::clone(&write_count);
            let moq_reader_tx = moq_tx.clone();
            std::thread::Builder::new()
                .name(format!("can-read-{}", interface))
                .spawn(move || {
                    can_reader_thread_std(socket_reader, read_tx, moq_reader_tx, wc_reader)
                })?;

            let socket_writer = Arc::clone(&socket);
            let wc_writer = Arc::clone(&write_count);
            std::thread::Builder::new()
                .name(format!("can-write-{}", interface))
                .spawn(move || can_writer_thread_std(socket_writer, write_rx, wc_writer))?;
        }

        let moq_path_str = moq_path
            .map(|p| p.to_string())
            .unwrap_or_else(|| format!("anon/xoq-can-{}", interface));

        let moq_config = moq_relay.map(|relay| MoqConfig {
            relay: relay.to_string(),
            path: moq_path_str.clone(),
            insecure: moq_insecure,
            state_subpath: "state".to_string(),
            command_subpath: "commands".to_string(),
            track_name: "can".to_string(),
        });

        let bridge = BridgeServer::new(
            identity_path,
            iroh_relay_url,
            write_tx,
            read_rx,
            moq_rx,
            moq_config,
        )
        .await?;

        Ok(Self {
            interface: interface.to_string(),
            bridge,
        })
    }

    /// Get the server's endpoint ID (share this with clients).
    pub fn id(&self) -> &str {
        self.bridge.id()
    }

    /// Run the bridge server (blocks forever, handling connections).
    pub async fn run(&self) -> Result<()> {
        tracing::info!(
            "[{}] CAN bridge server running. ID: {}",
            self.interface,
            self.bridge.id()
        );
        self.bridge.run().await
    }

    /// Run the bridge server for a single connection, then return.
    pub async fn run_once(&self) -> Result<()> {
        tracing::info!(
            "CAN bridge server waiting for connection. ID: {}",
            self.bridge.id()
        );
        self.bridge.run_once().await
    }
}