rns-net 0.5.5

Network interfaces and node driver for the Reticulum Network Stack
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
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
//! KISS interface with flow control and TNC configuration.
//!
//! Matches Python `KISSInterface.py` — opens a serial port,
//! sends TNC configuration commands, handles KISS framing with
//! optional flow control.

use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};

use rns_core::transport::types::InterfaceId;

use crate::event::{Event, EventSender};
use crate::interface::Writer;
use crate::kiss;
use crate::serial::{Parity, SerialConfig, SerialPort};

/// Configuration for a KISS interface.
#[derive(Debug, Clone)]
pub struct KissIfaceConfig {
    pub name: String,
    pub port: String,
    pub speed: u32,
    pub data_bits: u8,
    pub parity: Parity,
    pub stop_bits: u8,
    pub preamble: u16,                // ms, default 350
    pub txtail: u16,                  // ms, default 20
    pub persistence: u8,              // 0-255, default 64
    pub slottime: u16,                // ms, default 20
    pub flow_control: bool,           // default false
    pub beacon_interval: Option<u32>, // seconds
    pub beacon_data: Option<Vec<u8>>, // padded to 15 bytes
    pub interface_id: InterfaceId,
}

impl Default for KissIfaceConfig {
    fn default() -> Self {
        KissIfaceConfig {
            name: String::new(),
            port: String::new(),
            speed: 9600,
            data_bits: 8,
            parity: Parity::None,
            stop_bits: 1,
            preamble: 350,
            txtail: 20,
            persistence: 64,
            slottime: 20,
            flow_control: false,
            beacon_interval: None,
            beacon_data: None,
            interface_id: InterfaceId(0),
        }
    }
}

/// Shared flow-control state between writer and reader threads.
struct FlowState {
    ready: bool,
    queue: VecDeque<Vec<u8>>,
    lock_time: Instant,
}

/// Writer that sends KISS-framed data over a serial port.
/// Handles flow control: when enabled, queues packets until CMD_READY.
struct KissWriter {
    file: std::fs::File,
    flow_control: bool,
    flow_state: Arc<Mutex<FlowState>>,
}

impl Writer for KissWriter {
    fn send_frame(&mut self, data: &[u8]) -> io::Result<()> {
        if self.flow_control {
            let mut state = self.flow_state.lock().unwrap();
            if state.ready {
                state.ready = false;
                state.lock_time = Instant::now();
                drop(state);
                self.file.write_all(&kiss::frame(data))
            } else {
                state.queue.push_back(data.to_vec());
                Ok(())
            }
        } else {
            self.file.write_all(&kiss::frame(data))
        }
    }
}

/// Start the KISS interface. Opens the port, configures TNC, spawns reader thread.
pub fn start(config: KissIfaceConfig, tx: EventSender) -> io::Result<Box<dyn Writer>> {
    let serial_config = SerialConfig {
        path: config.port.clone(),
        baud: config.speed,
        data_bits: config.data_bits,
        parity: config.parity,
        stop_bits: config.stop_bits,
    };

    let port = SerialPort::open(&serial_config)?;
    let reader_file = port.reader()?;
    let mut writer_file = port.writer()?;
    let flow_writer_file = port.writer()?;

    let id = config.interface_id;

    // Initial 2-second delay for TNC initialization (matches Python)
    thread::sleep(Duration::from_secs(2));

    // Signal interface up
    let _ = tx.send(Event::InterfaceUp(id, None, None));

    // Send TNC configuration commands
    configure_tnc(&mut writer_file, &config)?;

    let flow_state = Arc::new(Mutex::new(FlowState {
        ready: true,
        queue: VecDeque::new(),
        lock_time: Instant::now(),
    }));

    let reader_flow_state = flow_state.clone();

    // Spawn reader thread
    let reader_config = config.clone();
    thread::Builder::new()
        .name(format!("kiss-reader-{}", id.0))
        .spawn(move || {
            reader_loop(
                reader_file,
                flow_writer_file,
                id,
                reader_config,
                tx,
                reader_flow_state,
            );
        })?;

    Ok(Box::new(KissWriter {
        file: writer_file,
        flow_control: config.flow_control,
        flow_state,
    }))
}

/// Send TNC configuration commands via KISS.
/// Matches Python `KISSInterface.configure_device()`.
fn configure_tnc(writer: &mut std::fs::File, config: &KissIfaceConfig) -> io::Result<()> {
    log::info!("[{}] configuring KISS interface parameters", config.name);

    // Preamble: value is ms/10, clamped to 0-255
    let preamble_val = (config.preamble / 10).min(255) as u8;
    writer.write_all(&kiss::command_frame(kiss::CMD_TXDELAY, &[preamble_val]))?;

    // TX tail: value is ms/10, clamped to 0-255
    let txtail_val = (config.txtail / 10).min(255) as u8;
    writer.write_all(&kiss::command_frame(kiss::CMD_TXTAIL, &[txtail_val]))?;

    // Persistence: raw value, clamped to 0-255
    writer.write_all(&kiss::command_frame(kiss::CMD_P, &[config.persistence]))?;

    // Slot time: value is ms/10, clamped to 0-255
    let slottime_val = (config.slottime / 10).min(255) as u8;
    writer.write_all(&kiss::command_frame(kiss::CMD_SLOTTIME, &[slottime_val]))?;

    // Flow control: send CMD_READY with 0x01 (matches Python setFlowControl)
    writer.write_all(&kiss::command_frame(kiss::CMD_READY, &[0x01]))?;

    log::info!("[{}] KISS interface configured", config.name);
    Ok(())
}

/// Reader loop: reads from serial, KISS-decodes, dispatches events.
/// Also handles flow control unlocking and beacon transmission.
fn reader_loop(
    mut reader: std::fs::File,
    mut flow_writer: std::fs::File,
    id: InterfaceId,
    config: KissIfaceConfig,
    tx: EventSender,
    flow_state: Arc<Mutex<FlowState>>,
) {
    let mut decoder = kiss::Decoder::new();
    let mut buf = [0u8; 4096];
    let mut first_tx: Option<Instant> = None;

    loop {
        match reader.read(&mut buf) {
            Ok(0) => {
                log::warn!("[{}] KISS port closed", config.name);
                let _ = tx.send(Event::InterfaceDown(id));
                match reconnect(&config, &tx, &flow_state) {
                    Some((new_reader, new_flow_writer)) => {
                        reader = new_reader;
                        flow_writer = new_flow_writer;
                        decoder = kiss::Decoder::new();
                        continue;
                    }
                    None => return,
                }
            }
            Ok(n) => {
                for event in decoder.feed(&buf[..n]) {
                    match event {
                        kiss::KissEvent::DataFrame(data) => {
                            if tx
                                .send(Event::Frame {
                                    interface_id: id,
                                    data,
                                })
                                .is_err()
                            {
                                return;
                            }
                        }
                        kiss::KissEvent::Ready => {
                            process_queue(&flow_state, &mut flow_writer, &mut first_tx, &config);
                        }
                    }
                }
            }
            Err(e) => {
                log::warn!("[{}] KISS read error: {}", config.name, e);
                let _ = tx.send(Event::InterfaceDown(id));
                match reconnect(&config, &tx, &flow_state) {
                    Some((new_reader, new_flow_writer)) => {
                        reader = new_reader;
                        flow_writer = new_flow_writer;
                        decoder = kiss::Decoder::new();
                        continue;
                    }
                    None => return,
                }
            }
        }

        // Flow control timeout check
        if config.flow_control {
            let state = flow_state.lock().unwrap();
            if !state.ready && state.lock_time.elapsed() > Duration::from_secs(5) {
                drop(state);
                log::warn!("[{}] unlocking flow control due to timeout", config.name);
                process_queue(&flow_state, &mut flow_writer, &mut first_tx, &config);
            }
        }

        // Beacon check
        if let (Some(interval), Some(ref beacon_data)) =
            (config.beacon_interval, &config.beacon_data)
        {
            if let Some(first) = first_tx {
                if first.elapsed() > Duration::from_secs(interval as u64) {
                    log::debug!("[{}] transmitting beacon data", config.name);
                    // Pad to minimum 15 bytes
                    let mut frame = beacon_data.clone();
                    while frame.len() < 15 {
                        frame.push(0x00);
                    }
                    let _ = flow_writer.write_all(&kiss::frame(&frame));
                    first_tx = None;
                }
            }
        }
    }
}

/// Process the flow control queue: send next queued packet, mark ready.
fn process_queue(
    flow_state: &Arc<Mutex<FlowState>>,
    writer: &mut std::fs::File,
    first_tx: &mut Option<Instant>,
    _config: &KissIfaceConfig,
) {
    let mut state = flow_state.lock().unwrap();
    if let Some(data) = state.queue.pop_front() {
        state.ready = false;
        state.lock_time = Instant::now();
        drop(state);
        let _ = writer.write_all(&kiss::frame(&data));
        if first_tx.is_none() {
            *first_tx = Some(Instant::now());
        }
    } else {
        state.ready = true;
    }
}

/// Attempt to reconnect the serial port.
fn reconnect(
    config: &KissIfaceConfig,
    tx: &EventSender,
    flow_state: &Arc<Mutex<FlowState>>,
) -> Option<(std::fs::File, std::fs::File)> {
    loop {
        thread::sleep(Duration::from_secs(5));
        log::info!(
            "[{}] attempting to reconnect KISS port {}...",
            config.name,
            config.port
        );

        let serial_config = SerialConfig {
            path: config.port.clone(),
            baud: config.speed,
            data_bits: config.data_bits,
            parity: config.parity,
            stop_bits: config.stop_bits,
        };

        match SerialPort::open(&serial_config) {
            Ok(port) => {
                match (port.reader(), port.writer(), port.writer()) {
                    (Ok(reader), Ok(mut cfg_writer), Ok(flow_writer)) => {
                        // 2-second init delay
                        thread::sleep(Duration::from_secs(2));
                        if let Err(e) = configure_tnc(&mut cfg_writer, config) {
                            log::warn!("[{}] TNC config failed: {}", config.name, e);
                            continue;
                        }
                        // Reset flow state
                        let mut state = flow_state.lock().unwrap();
                        state.ready = true;
                        state.queue.clear();
                        drop(state);

                        let new_writer: Box<dyn Writer> = Box::new(KissWriter {
                            file: cfg_writer,
                            flow_control: config.flow_control,
                            flow_state: flow_state.clone(),
                        });
                        let _ = tx.send(Event::InterfaceUp(
                            config.interface_id,
                            Some(new_writer),
                            None,
                        ));
                        log::info!("[{}] KISS port reconnected", config.name);
                        return Some((reader, flow_writer));
                    }
                    _ => {
                        log::warn!("[{}] failed to get handles from serial port", config.name);
                    }
                }
            }
            Err(e) => {
                log::warn!("[{}] KISS reconnect failed: {}", config.name, e);
            }
        }
    }
}

// --- Factory implementation ---

use super::{InterfaceConfigData, InterfaceFactory, StartContext, StartResult};
use rns_core::transport::types::InterfaceInfo;
use std::collections::HashMap;

/// Factory for `KISSInterface`.
pub struct KissFactory;

impl InterfaceFactory for KissFactory {
    fn type_name(&self) -> &str {
        "KISSInterface"
    }

    fn default_ifac_size(&self) -> usize {
        8
    }

    fn parse_config(
        &self,
        name: &str,
        id: InterfaceId,
        params: &HashMap<String, String>,
    ) -> Result<Box<dyn InterfaceConfigData>, String> {
        let port = params
            .get("port")
            .cloned()
            .ok_or_else(|| "KISSInterface requires 'port'".to_string())?;

        let speed = params
            .get("speed")
            .and_then(|v| v.parse().ok())
            .unwrap_or(9600u32);

        let data_bits = params
            .get("databits")
            .and_then(|v| v.parse().ok())
            .unwrap_or(8u8);

        let parity = params
            .get("parity")
            .map(|v| match v.to_lowercase().as_str() {
                "e" | "even" => crate::serial::Parity::Even,
                "o" | "odd" => crate::serial::Parity::Odd,
                _ => crate::serial::Parity::None,
            })
            .unwrap_or(crate::serial::Parity::None);

        let stop_bits = params
            .get("stopbits")
            .and_then(|v| v.parse().ok())
            .unwrap_or(1u8);

        let preamble = params
            .get("preamble")
            .and_then(|v| v.parse().ok())
            .unwrap_or(350u16);

        let txtail = params
            .get("txtail")
            .and_then(|v| v.parse().ok())
            .unwrap_or(20u16);

        let persistence = params
            .get("persistence")
            .and_then(|v| v.parse().ok())
            .unwrap_or(64u8);

        let slottime = params
            .get("slottime")
            .and_then(|v| v.parse().ok())
            .unwrap_or(20u16);

        let flow_control = params
            .get("flow_control")
            .and_then(|v| crate::config::parse_bool_pub(v))
            .unwrap_or(false);

        let beacon_interval = params
            .get("id_interval")
            .or_else(|| params.get("beacon_interval"))
            .and_then(|v| v.parse().ok());

        let beacon_data = params
            .get("id_callsign")
            .or_else(|| params.get("beacon_data"))
            .map(|v| v.as_bytes().to_vec());

        Ok(Box::new(KissIfaceConfig {
            name: name.to_string(),
            port,
            speed,
            data_bits,
            parity,
            stop_bits,
            preamble,
            txtail,
            persistence,
            slottime,
            flow_control,
            beacon_interval,
            beacon_data,
            interface_id: id,
        }))
    }

    fn start(
        &self,
        config: Box<dyn InterfaceConfigData>,
        ctx: StartContext,
    ) -> std::io::Result<StartResult> {
        let kiss_config = *config
            .into_any()
            .downcast::<KissIfaceConfig>()
            .map_err(|_| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, "wrong config type")
            })?;

        let id = kiss_config.interface_id;
        let name = kiss_config.name.clone();

        let info = InterfaceInfo {
            id,
            name,
            mode: ctx.mode,
            out_capable: true,
            in_capable: true,
            bitrate: Some(1200),
            announce_rate_target: None,
            announce_rate_grace: 0,
            announce_rate_penalty: 0.0,
            announce_cap: rns_core::constants::ANNOUNCE_CAP,
            is_local_client: false,
            wants_tunnel: false,
            tunnel_id: None,
            mtu: rns_core::constants::MTU as u32,
            ingress_control: rns_core::transport::types::IngressControlConfig::disabled(),
            ia_freq: 0.0,
            started: crate::time::now(),
        };

        let writer = start(kiss_config, ctx.tx)?;

        Ok(StartResult::Simple {
            id,
            info,
            writer,
            interface_type_name: "KISSInterface".to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::serial::open_pty_pair;
    use std::os::unix::io::{AsRawFd, FromRawFd};
    use std::sync::mpsc;

    /// Helper: poll an fd for reading with timeout (ms).
    fn poll_read(fd: i32, timeout_ms: i32) -> bool {
        let mut pfd = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        let ret = unsafe { libc::poll(&mut pfd, 1, timeout_ms) };
        ret > 0
    }

    #[test]
    fn kiss_data_roundtrip() {
        let (master_fd, slave_fd) = open_pty_pair().unwrap();
        let mut master_file = unsafe { std::fs::File::from_raw_fd(master_fd) };
        let mut slave_file = unsafe { std::fs::File::from_raw_fd(slave_fd) };

        // Write a KISS data frame to the master side
        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let framed = kiss::frame(&payload);
        master_file.write_all(&framed).unwrap();
        master_file.flush().unwrap();

        // Read from slave using KISS decoder
        assert!(poll_read(slave_file.as_raw_fd(), 2000));

        let mut decoder = kiss::Decoder::new();
        let mut buf = [0u8; 4096];
        let n = slave_file.read(&mut buf).unwrap();
        let events = decoder.feed(&buf[..n]);
        assert_eq!(events.len(), 1);
        assert_eq!(events[0], kiss::KissEvent::DataFrame(payload));
    }

    #[test]
    fn kiss_writer_frames() {
        let (master_fd, slave_fd) = open_pty_pair().unwrap();

        let writer_file = unsafe { std::fs::File::from_raw_fd(slave_fd) };
        let flow_state = Arc::new(Mutex::new(FlowState {
            ready: true,
            queue: VecDeque::new(),
            lock_time: Instant::now(),
        }));

        let mut writer = KissWriter {
            file: writer_file,
            flow_control: false,
            flow_state,
        };

        let payload = vec![0xC0, 0xDB, 0x01]; // includes bytes that need KISS escaping
        writer.send_frame(&payload).unwrap();

        // Read from master
        let mut master_file = unsafe { std::fs::File::from_raw_fd(master_fd) };
        assert!(poll_read(master_file.as_raw_fd(), 2000));

        let expected = kiss::frame(&payload);
        let mut buf = [0u8; 256];
        let n = master_file.read(&mut buf).unwrap();
        assert_eq!(&buf[..n], &expected[..]);
    }

    #[test]
    fn kiss_config_commands() {
        use std::time::Instant;

        let (master_fd, slave_fd) = open_pty_pair().unwrap();

        let mut writer_file = unsafe { std::fs::File::from_raw_fd(slave_fd) };
        let config = KissIfaceConfig {
            preamble: 350,
            txtail: 20,
            persistence: 64,
            slottime: 20,
            ..Default::default()
        };

        configure_tnc(&mut writer_file, &config).unwrap();

        // Read all commands from master
        let mut master_file = unsafe { std::fs::File::from_raw_fd(master_fd) };
        let deadline = Instant::now() + Duration::from_secs(2);
        let mut data = Vec::new();
        let mut buf = [0u8; 1024];
        while Instant::now() < deadline {
            let remaining_ms = deadline
                .saturating_duration_since(Instant::now())
                .as_millis()
                .min(i32::MAX as u128) as i32;
            if remaining_ms <= 0 || !poll_read(master_file.as_raw_fd(), remaining_ms) {
                break;
            }

            let n = master_file.read(&mut buf).unwrap();
            if n == 0 {
                break;
            }
            data.extend_from_slice(&buf[..n]);

            let have_all = data.windows(4).any(|w| {
                w[0] == kiss::FEND && w[1] == kiss::CMD_TXDELAY && w[2] == 35 && w[3] == kiss::FEND
            }) && data.windows(4).any(|w| {
                w[0] == kiss::FEND && w[1] == kiss::CMD_TXTAIL && w[2] == 2 && w[3] == kiss::FEND
            }) && data.windows(4).any(|w| {
                w[0] == kiss::FEND && w[1] == kiss::CMD_P && w[2] == 64 && w[3] == kiss::FEND
            }) && data.windows(4).any(|w| {
                w[0] == kiss::FEND && w[1] == kiss::CMD_SLOTTIME && w[2] == 2 && w[3] == kiss::FEND
            });
            if have_all {
                break;
            }
        }

        // Should contain TXDELAY command: FEND, CMD_TXDELAY, value, FEND
        // preamble: 350/10 = 35
        assert!(
            data.windows(4).any(|w| w[0] == kiss::FEND
                && w[1] == kiss::CMD_TXDELAY
                && w[2] == 35
                && w[3] == kiss::FEND),
            "should contain TXDELAY command"
        );

        // TXTAIL: 20/10 = 2
        assert!(
            data.windows(4).any(|w| w[0] == kiss::FEND
                && w[1] == kiss::CMD_TXTAIL
                && w[2] == 2
                && w[3] == kiss::FEND),
            "should contain TXTAIL command"
        );

        // Persistence: 64
        assert!(
            data.windows(4).any(|w| w[0] == kiss::FEND
                && w[1] == kiss::CMD_P
                && w[2] == 64
                && w[3] == kiss::FEND),
            "should contain P command"
        );

        // Slottime: 20/10 = 2
        assert!(
            data.windows(4).any(|w| w[0] == kiss::FEND
                && w[1] == kiss::CMD_SLOTTIME
                && w[2] == 2
                && w[3] == kiss::FEND),
            "should contain SLOTTIME command"
        );
    }

    #[test]
    fn kiss_flow_control_lock() {
        let flow_state = Arc::new(Mutex::new(FlowState {
            ready: true,
            queue: VecDeque::new(),
            lock_time: Instant::now(),
        }));

        let (master_fd, slave_fd) = open_pty_pair().unwrap();
        let writer_file = unsafe { std::fs::File::from_raw_fd(slave_fd) };

        let mut writer = KissWriter {
            file: writer_file,
            flow_control: true,
            flow_state: flow_state.clone(),
        };

        // First send should go through (ready=true) and lock
        writer.send_frame(b"hello").unwrap();
        assert!(!flow_state.lock().unwrap().ready);

        // Second send should be queued (ready=false)
        writer.send_frame(b"world").unwrap();
        assert_eq!(flow_state.lock().unwrap().queue.len(), 1);

        // Simulate CMD_READY: process_queue
        let mut flow_writer = unsafe { std::fs::File::from_raw_fd(libc::dup(master_fd)) };
        let mut first_tx = None;
        let config = KissIfaceConfig::default();
        process_queue(&flow_state, &mut flow_writer, &mut first_tx, &config);

        // Queue should be empty now (dequeued "world"), but ready=false because it sent
        assert_eq!(flow_state.lock().unwrap().queue.len(), 0);
        assert!(!flow_state.lock().unwrap().ready);

        // Process again with empty queue: should set ready=true
        process_queue(&flow_state, &mut flow_writer, &mut first_tx, &config);
        assert!(flow_state.lock().unwrap().ready);

        // Clean up
        unsafe { libc::close(master_fd) };
    }

    #[test]
    fn kiss_flow_control_timeout() {
        let flow_state = Arc::new(Mutex::new(FlowState {
            ready: false,
            queue: VecDeque::new(),
            lock_time: Instant::now() - Duration::from_secs(6), // already timed out
        }));

        // Check that the timeout condition triggers
        let state = flow_state.lock().unwrap();
        assert!(!state.ready);
        assert!(state.lock_time.elapsed() > Duration::from_secs(5));
    }

    #[test]
    fn kiss_fragmented() {
        let (master_fd, slave_fd) = open_pty_pair().unwrap();
        let mut master_file = unsafe { std::fs::File::from_raw_fd(master_fd) };
        let slave_file = unsafe { std::fs::File::from_raw_fd(slave_fd) };

        let payload = vec![0x01, 0x02, 0x03, 0x04, 0x05];
        let framed = kiss::frame(&payload);
        let mid = framed.len() / 2;

        // Spawn reader thread first (it will block waiting for data)
        let (tx, rx) = mpsc::channel::<kiss::KissEvent>();
        let reader_thread = thread::spawn(move || {
            let mut reader = slave_file;
            let mut decoder = kiss::Decoder::new();
            let mut buf = [0u8; 4096];

            loop {
                match reader.read(&mut buf) {
                    Ok(n) if n > 0 => {
                        for event in decoder.feed(&buf[..n]) {
                            let _ = tx.send(event.clone());
                            if matches!(event, kiss::KissEvent::DataFrame(_)) {
                                return;
                            }
                        }
                    }
                    _ => return,
                }
            }
        });

        // Write first half
        master_file.write_all(&framed[..mid]).unwrap();
        master_file.flush().unwrap();

        thread::sleep(Duration::from_millis(50));

        // Write second half
        master_file.write_all(&framed[mid..]).unwrap();
        master_file.flush().unwrap();

        let event = rx.recv_timeout(Duration::from_secs(2)).unwrap();
        assert_eq!(event, kiss::KissEvent::DataFrame(payload));

        let _ = reader_thread.join();
    }
}