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
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
//! serialport-compatible interface to remote serial ports over P2P.
//!
//! This module provides a `serialport` crate compatible API for connecting
//! to remote serial ports over iroh P2P or MoQ relay.
//!
//! # Example
//!
//! ```no_run
//! use xoq::serialport;
//! use std::io::{Read, Write};
//!
//! let mut port = serialport::new("server-endpoint-id").open()?;
//! port.write_all(b"AT\r\n")?;
//! let mut buf = [0u8; 100];
//! let n = port.read(&mut buf)?;
//! # Ok::<(), anyhow::Error>(())
//! ```

use anyhow::Result;
use bytes::Bytes;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;

use crate::iroh::{IrohClientBuilder, IrohConnection};

/// A client that connects to a remote serial port over iroh P2P
pub struct Client {
    send: Arc<Mutex<iroh::endpoint::SendStream>>,
    recv: Arc<Mutex<iroh::endpoint::RecvStream>>,
    conn: Arc<IrohConnection>,
    use_datagrams: bool,
}

impl Client {
    /// Connect to a remote serial bridge server
    pub async fn connect(server_id: &str) -> Result<Self> {
        Self::connect_with_options(server_id, false).await
    }

    /// Connect with datagram mode option.
    ///
    /// When `use_datagrams` is true, write/read use QUIC unreliable datagrams
    /// instead of streams. This bypasses ACK-based flow control and retransmission,
    /// ideal for latency-sensitive data like servo positions.
    pub async fn connect_with_options(server_id: &str, use_datagrams: bool) -> Result<Self> {
        tracing::debug!(
            "Connecting to server: {} (datagrams={})",
            server_id,
            use_datagrams
        );
        let conn = IrohClientBuilder::new()
            .connect_str(server_id)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to connect to server: {}", e))?;
        tracing::debug!("Connected to server, opening stream...");
        let stream = conn
            .open_stream()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to open stream: {}", e))?;
        tracing::debug!("Stream opened successfully");
        // Split stream so reads and writes don't block each other
        let (send, recv) = stream.split();

        Ok(Self {
            send: Arc::new(Mutex::new(send)),
            recv: Arc::new(Mutex::new(recv)),
            conn: Arc::new(conn),
            use_datagrams,
        })
    }

    /// Write data to the remote serial port
    pub async fn write(&self, data: &[u8]) -> Result<()> {
        if self.use_datagrams {
            self.conn.send_datagram(Bytes::copy_from_slice(data))?;
            return Ok(());
        }
        let mut send = self.send.lock().await;
        send.write_all(data).await?;
        drop(send);
        // quinn's flush() is a no-op — yield to let connection task send
        tokio::task::yield_now().await;
        Ok(())
    }

    /// Write a string to the remote serial port
    pub async fn write_str(&self, data: &str) -> Result<()> {
        self.write(data.as_bytes()).await
    }

    /// Read data from the remote serial port.
    ///
    /// Always reads from the stream, even in datagram mode. Datagrams are
    /// unreliable and not suitable for request-response protocols (like Dynamixel)
    /// that need every byte. The server sends responses via both stream and datagram.
    pub async fn read(&self, buf: &mut [u8]) -> Result<Option<usize>> {
        let mut recv = self.recv.lock().await;
        Ok(recv.read(buf).await?)
    }

    /// Read a string from the remote serial port
    pub async fn read_string(&self) -> Result<Option<String>> {
        let mut buf = vec![0u8; 4096];
        if let Some(n) = self.read(&mut buf).await? {
            return Ok(Some(String::from_utf8_lossy(&buf[..n]).to_string()));
        }
        Ok(None)
    }

    /// Run an interactive bridge to local stdin/stdout
    pub async fn run_interactive(&self) -> Result<()> {
        use std::io::{Read, Write};

        let recv = self.recv.clone();
        let send = self.send.clone();

        // Spawn task: network -> stdout
        tokio::spawn(async move {
            let mut buf = vec![0u8; 1024];
            loop {
                let n = {
                    let mut r = recv.lock().await;
                    match r.read(&mut buf).await {
                        Ok(Some(n)) if n > 0 => {
                            tracing::debug!("Received {} bytes from network", n);
                            n
                        }
                        Ok(Some(_)) => {
                            tracing::debug!("Received 0 bytes (EOF)");
                            break;
                        }
                        Ok(None) => {
                            tracing::debug!("Stream closed");
                            break;
                        }
                        Err(e) => {
                            tracing::debug!("Network read error: {}", e);
                            break;
                        }
                    }
                };
                let _ = std::io::stdout().write_all(&buf[..n]);
                let _ = std::io::stdout().flush();
            }
        });

        // Main: stdin -> network
        loop {
            let result = tokio::task::spawn_blocking(|| {
                let mut buf = [0u8; 256];
                match std::io::stdin().read(&mut buf) {
                    Ok(n) if n > 0 => Some(buf[..n].to_vec()),
                    _ => None,
                }
            })
            .await?;

            match result {
                Some(data) => {
                    tracing::debug!(
                        "Sending {} bytes to network: {:?}",
                        data.len(),
                        String::from_utf8_lossy(&data)
                    );
                    let mut s = send.lock().await;
                    if let Err(e) = s.write_all(&data).await {
                        tracing::debug!("Network write error: {}", e);
                        break;
                    }
                    drop(s);
                    // quinn's flush() is a no-op — yield to let connection task send
                    tokio::task::yield_now().await;
                    tracing::debug!("Sent successfully");
                }
                None => break,
            }
        }

        Ok(())
    }
}

/// Transport type for the serial port connection.
#[derive(Clone)]
pub enum Transport {
    /// Iroh P2P connection (default)
    Iroh {
        /// Custom ALPN protocol
        alpn: Option<Vec<u8>>,
    },
    /// MoQ relay connection
    Moq {
        /// Relay URL
        relay: String,
        /// Authentication token
        token: Option<String>,
        /// Disable TLS verification (for self-signed certs)
        insecure: bool,
    },
}

impl Default for Transport {
    fn default() -> Self {
        Transport::Iroh { alpn: None }
    }
}

/// Builder for creating a remote serial port connection.
///
/// Mimics the `serialport::new()` API for drop-in compatibility.
///
/// # Example
///
/// ```no_run
/// use xoq::serialport;
/// use std::time::Duration;
///
/// // Simple iroh P2P connection (default)
/// let port = serialport::new("server-endpoint-id").open()?;
///
/// // With timeout
/// let port = serialport::new("server-endpoint-id")
///     .timeout(Duration::from_millis(500))
///     .open()?;
///
/// // With MoQ relay
/// let port = serialport::new("my-channel")
///     .with_moq("https://relay.example.com")
///     .token("jwt-token")
///     .open()?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub struct SerialPortBuilder {
    port_name: String,
    timeout: Duration,
    transport: Transport,
    use_datagrams: bool,
}

impl SerialPortBuilder {
    /// Create a new serial port builder.
    pub fn new(port: &str) -> Self {
        Self {
            port_name: port.to_string(),
            timeout: Duration::from_secs(1),
            transport: Transport::default(),
            use_datagrams: false,
        }
    }

    /// Set the read/write timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Use iroh P2P transport (default).
    pub fn with_iroh(mut self) -> Self {
        self.transport = Transport::Iroh { alpn: None };
        self
    }

    /// Set custom ALPN for iroh connection.
    pub fn alpn(mut self, alpn: &[u8]) -> Self {
        if let Transport::Iroh { alpn: ref mut a } = self.transport {
            *a = Some(alpn.to_vec());
        }
        self
    }

    /// Use MoQ relay transport.
    pub fn with_moq(mut self, relay: &str) -> Self {
        self.transport = Transport::Moq {
            relay: relay.to_string(),
            token: None,
            insecure: false,
        };
        self
    }

    /// Disable TLS verification for MoQ (for self-signed certs).
    pub fn insecure(mut self) -> Self {
        if let Transport::Moq {
            insecure: ref mut i,
            ..
        } = self.transport
        {
            *i = true;
        }
        self
    }

    /// Set authentication token (for MoQ).
    pub fn token(mut self, token: &str) -> Self {
        if let Transport::Moq {
            token: ref mut t, ..
        } = self.transport
        {
            *t = Some(token.to_string());
        }
        self
    }

    /// Use QUIC unreliable datagrams instead of streams for data transfer.
    ///
    /// Datagrams bypass ACK-based flow control, retransmission, and ordering.
    /// Ideal for latency-sensitive data (e.g., servo positions) where the latest
    /// value supersedes older ones. Only works with iroh transport.
    pub fn use_datagrams(mut self, enabled: bool) -> Self {
        self.use_datagrams = enabled;
        self
    }

    /// Open the connection to the remote serial port.
    pub fn open(self) -> Result<RemoteSerialPort> {
        let runtime = tokio::runtime::Runtime::new()?;
        let use_datagrams = self.use_datagrams;

        let client = match self.transport {
            Transport::Iroh { alpn } => runtime.block_on(async {
                let mut builder = IrohClientBuilder::new();
                if let Some(alpn) = alpn {
                    builder = builder.alpn(&alpn);
                }
                let conn = builder.connect_str(&self.port_name).await?;
                let stream = conn.open_stream().await?;
                let conn = Arc::new(conn);
                Ok::<_, anyhow::Error>(ClientInner::Iroh {
                    stream: Arc::new(Mutex::new(stream)),
                    conn,
                    use_datagrams,
                })
            })?,
            Transport::Moq {
                relay,
                token: _,
                insecure,
            } => runtime.block_on(async {
                let stream = if insecure {
                    crate::moq::MoqStream::connect_to_insecure(&relay, &self.port_name).await?
                } else {
                    crate::moq::MoqStream::connect_to(&relay, &self.port_name).await?
                };
                Ok::<_, anyhow::Error>(ClientInner::Moq {
                    stream: Arc::new(Mutex::new(stream)),
                })
            })?,
        };

        Ok(RemoteSerialPort {
            client,
            runtime,
            port_name: self.port_name,
            timeout: self.timeout,
            buffer: Vec::new(),
        })
    }
}

/// Internal client representation supporting multiple transports.
enum ClientInner {
    Iroh {
        stream: Arc<Mutex<crate::iroh::IrohStream>>,
        conn: Arc<IrohConnection>,
        use_datagrams: bool,
    },
    Moq {
        stream: Arc<Mutex<crate::moq::MoqStream>>,
    },
}

/// Create a new remote serial port builder.
///
/// This function mimics `serialport::new()` for drop-in compatibility.
///
/// # Example
///
/// ```no_run
/// use xoq::serialport;
///
/// // Drop-in replacement for serialport crate
/// let port = serialport::new("server-endpoint-id").open()?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn new(port: &str) -> SerialPortBuilder {
    SerialPortBuilder::new(port)
}

/// A `serialport`-compatible interface to a remote serial port.
///
/// This struct provides a blocking API that mimics the `serialport` crate,
/// implementing `std::io::Read` and `std::io::Write` traits for seamless
/// integration with existing code. Supports both iroh P2P and MoQ relay transports.
///
/// # Example
///
/// ```no_run
/// use xoq::serialport;
/// use std::io::{BufRead, BufReader, Write};
///
/// // Iroh P2P (default)
/// let mut port = serialport::new("server-endpoint-id").open()?;
///
/// // Or with MoQ relay
/// let mut port = serialport::new("my-channel")
///     .with_moq("https://relay.example.com")
///     .open()?;
///
/// port.write_all(b"AT\r\n")?;
/// let mut reader = BufReader::new(port);
/// let mut line = String::new();
/// reader.read_line(&mut line)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub struct RemoteSerialPort {
    client: ClientInner,
    runtime: tokio::runtime::Runtime,
    port_name: String,
    timeout: Duration,
    buffer: Vec<u8>,
}

impl RemoteSerialPort {
    /// Open a connection to a remote serial port via iroh P2P.
    ///
    /// Prefer using `xoq::serialport::new(port).open()` for more options.
    pub fn open(port: &str) -> Result<Self> {
        new(port).open()
    }

    /// Get the port name (server endpoint ID or MoQ path).
    pub fn name(&self) -> Option<String> {
        Some(self.port_name.clone())
    }

    /// Get the current timeout.
    pub fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Set the read/write timeout.
    pub fn set_timeout(&mut self, timeout: Duration) -> Result<()> {
        self.timeout = timeout;
        Ok(())
    }

    /// Get the number of bytes available to read.
    pub fn bytes_to_read(&self) -> Result<u32> {
        Ok(self.buffer.len() as u32)
    }

    /// Get the number of bytes waiting to be written (always 0 for network).
    pub fn bytes_to_write(&self) -> Result<u32> {
        Ok(0)
    }

    /// Clear the input buffer.
    pub fn clear_input(&mut self) -> Result<()> {
        self.buffer.clear();
        Ok(())
    }

    /// Clear the output buffer (no-op for network).
    pub fn clear_output(&mut self) -> Result<()> {
        Ok(())
    }

    /// Clear all buffers.
    pub fn clear_all(&mut self) -> Result<()> {
        self.buffer.clear();
        Ok(())
    }

    /// Write bytes to the remote serial port.
    pub fn write_bytes(&mut self, data: &[u8]) -> Result<usize> {
        self.runtime.block_on(async {
            match &self.client {
                ClientInner::Iroh {
                    stream,
                    conn,
                    use_datagrams,
                } => {
                    if *use_datagrams {
                        conn.send_datagram(Bytes::copy_from_slice(data))?;
                    } else {
                        let mut s = stream.lock().await;
                        s.write(data).await?;
                    }
                }
                ClientInner::Moq { stream } => {
                    let mut s = stream.lock().await;
                    s.write(data.to_vec());
                }
            }
            Ok::<_, anyhow::Error>(())
        })?;
        Ok(data.len())
    }

    /// Read bytes from the remote serial port.
    pub fn read_bytes(&mut self, buf: &mut [u8]) -> Result<usize> {
        // First drain from buffer
        if !self.buffer.is_empty() {
            let take = std::cmp::min(buf.len(), self.buffer.len());
            buf[..take].copy_from_slice(&self.buffer[..take]);
            self.buffer.drain(..take);
            return Ok(take);
        }

        // Read from network with timeout
        let timeout = self.timeout;
        let result = self.runtime.block_on(async {
            tokio::time::timeout(timeout, async {
                match &self.client {
                    ClientInner::Iroh { stream, .. } => {
                        let mut s = stream.lock().await;
                        s.read(buf).await
                    }
                    ClientInner::Moq { stream } => {
                        let mut s = stream.lock().await;
                        if let Some(data) = s.read().await? {
                            let n = std::cmp::min(data.len(), buf.len());
                            buf[..n].copy_from_slice(&data[..n]);
                            Ok(Some(n))
                        } else {
                            Ok(None)
                        }
                    }
                }
            })
            .await
        });

        match result {
            Ok(Ok(Some(n))) => Ok(n),
            Ok(Ok(None)) => Ok(0),
            Ok(Err(e)) => Err(e),
            Err(_) => Ok(0), // Timeout
        }
    }

    /// Read until a specific byte is found.
    pub fn read_until(&mut self, byte: u8) -> Result<Vec<u8>> {
        let mut result = Vec::new();

        // Check buffer first
        if let Some(pos) = self.buffer.iter().position(|&b| b == byte) {
            result.extend(self.buffer.drain(..=pos));
            return Ok(result);
        }
        result.append(&mut self.buffer);

        // Keep reading until we find the byte
        let mut temp = [0u8; 256];
        loop {
            let n = self.read_bytes(&mut temp)?;
            if n == 0 {
                break;
            }
            if let Some(pos) = temp[..n].iter().position(|&b| b == byte) {
                result.extend_from_slice(&temp[..=pos]);
                self.buffer.extend_from_slice(&temp[pos + 1..n]);
                break;
            }
            result.extend_from_slice(&temp[..n]);
        }

        Ok(result)
    }

    /// Read a line (until newline).
    pub fn read_line(&mut self) -> Result<String> {
        let bytes = self.read_until(b'\n')?;
        Ok(String::from_utf8_lossy(&bytes).into_owned())
    }
}

impl std::io::Read for RemoteSerialPort {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.read_bytes(buf).map_err(std::io::Error::other)
    }
}

impl std::io::Write for RemoteSerialPort {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.write_bytes(buf).map_err(std::io::Error::other)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

// Only implement serialport::SerialPort trait when the serialport crate is available
#[cfg(feature = "serial")]
impl serialport::SerialPort for RemoteSerialPort {
    fn name(&self) -> Option<String> {
        Some(self.port_name.clone())
    }

    fn baud_rate(&self) -> serialport::Result<u32> {
        // Remote port - baud rate is configured on the server side
        Ok(1_000_000)
    }

    fn data_bits(&self) -> serialport::Result<serialport::DataBits> {
        Ok(serialport::DataBits::Eight)
    }

    fn flow_control(&self) -> serialport::Result<serialport::FlowControl> {
        Ok(serialport::FlowControl::None)
    }

    fn parity(&self) -> serialport::Result<serialport::Parity> {
        Ok(serialport::Parity::None)
    }

    fn stop_bits(&self) -> serialport::Result<serialport::StopBits> {
        Ok(serialport::StopBits::One)
    }

    fn timeout(&self) -> Duration {
        self.timeout
    }

    fn set_baud_rate(&mut self, _: u32) -> serialport::Result<()> {
        // Baud rate is configured on the server side
        Ok(())
    }

    fn set_data_bits(&mut self, _: serialport::DataBits) -> serialport::Result<()> {
        Ok(())
    }

    fn set_flow_control(&mut self, _: serialport::FlowControl) -> serialport::Result<()> {
        Ok(())
    }

    fn set_parity(&mut self, _: serialport::Parity) -> serialport::Result<()> {
        Ok(())
    }

    fn set_stop_bits(&mut self, _: serialport::StopBits) -> serialport::Result<()> {
        Ok(())
    }

    fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
        self.timeout = timeout;
        Ok(())
    }

    fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
        Ok(())
    }

    fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
        Ok(())
    }

    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
        Ok(false)
    }

    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
        Ok(true)
    }

    fn bytes_to_read(&self) -> serialport::Result<u32> {
        Ok(self.buffer.len() as u32)
    }

    fn bytes_to_write(&self) -> serialport::Result<u32> {
        Ok(0)
    }

    fn clear(&self, _: serialport::ClearBuffer) -> serialport::Result<()> {
        Ok(())
    }

    fn try_clone(&self) -> serialport::Result<Box<dyn serialport::SerialPort>> {
        Err(serialport::Error::new(
            serialport::ErrorKind::Io(std::io::ErrorKind::Unsupported),
            "Clone not supported for remote serial ports",
        ))
    }

    fn set_break(&self) -> serialport::Result<()> {
        Ok(())
    }

    fn clear_break(&self) -> serialport::Result<()> {
        Ok(())
    }
}