autors-cli 0.1.0

CANoe-inspired terminal workbench for the autors crate family
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
use std::collections::VecDeque;
use std::time::{Duration, Instant};

use async_trait::async_trait;
use autors_ldf::model::{FrameRef, Ldf, SignalValue};
use autors_lin::device::{
    compute_checksum, ChecksumType as LinChecksumType, LinConfiguration, LinDevice, LinFrame,
};
use autors_ltrc::{
    ChecksumType as LtrcChecksumType, Direction as LtrcDirection, LtrcFile, LtrcVersion,
    Record as LtrcRecord, StartTime, TraceFrame,
};
use autors_scheduler::lin::LinFrameState;
use autors_scheduler::LinScheduler;

use crate::hardware::{create_lin, AdapterKind};

const TRACE_LIMIT: usize = 10_000;

/// One operation captured by the virtual LIN channel.
#[derive(Debug, Clone)]
pub struct LinBusTrace {
    pub timestamp: Duration,
    pub is_tx: bool,
    pub id: u8,
    pub frame: String,
    pub operation: &'static str,
    pub data: Vec<u8>,
    pub dlc: u8,
    pub signals: Vec<String>,
}

/// Runtime model for LDF scheduling and virtual LIN traffic.
pub struct LinBusSession {
    device: VirtualLinDevice,
    hardware_device: Option<TracingHardwareLinDevice>,
    adapter: AdapterKind,
    channel: i32,
    hardware_type: i32,
    scheduler: Option<LinScheduler>,
    database: Option<Ldf>,
    origin: Instant,
    elapsed: Duration,
    trace: VecDeque<LinBusTrace>,
    pub connected: bool,
    pub running: bool,
    pub last_error: Option<String>,
    tx_frames: u64,
    rx_frames: u64,
    wire_bits: u64,
}

impl Default for LinBusSession {
    fn default() -> Self {
        Self::new()
    }
}

impl LinBusSession {
    pub fn new() -> Self {
        Self {
            device: VirtualLinDevice::new(),
            hardware_device: None,
            adapter: AdapterKind::Virtual,
            channel: 0,
            hardware_type: 0,
            scheduler: None,
            database: None,
            origin: Instant::now(),
            elapsed: Duration::ZERO,
            trace: VecDeque::new(),
            connected: false,
            running: false,
            last_error: None,
            tx_frames: 0,
            rx_frames: 0,
            wire_bits: 0,
        }
    }

    pub fn attach_database(&mut self, database: &Ldf) -> Result<(), String> {
        let scheduler =
            LinScheduler::from_ldf_at(database, self.origin).map_err(|error| error.to_string())?;
        self.database = Some(database.clone());
        self.scheduler = Some(scheduler);
        self.running = false;
        self.last_error = None;
        Ok(())
    }

    pub fn connect(&mut self) -> Result<(), String> {
        if self.connected {
            return Ok(());
        }
        let baud_rate = self
            .database
            .as_ref()
            .map_or(19_200, |database| database.baud_rate);
        let baud_rate = u16::try_from(baud_rate)
            .map_err(|_| format!("LIN baud rate {baud_rate} exceeds the adapter range"))?;
        let mut configuration = LinConfiguration::new(0x3c, baud_rate);
        configuration.channel = self.channel;
        configuration.hardware_type = self.hardware_type;
        let bus_id = format!("{}/LIN{}", self.adapter.name(), self.channel + 1);
        configuration.bus_id = Some(bus_id.clone());
        let opened = if self.adapter == AdapterKind::Virtual {
            autors_runtime::block_on(self.device.open(&configuration))
                .map_err(|error| error.to_string())?
        } else {
            let mut device =
                TracingHardwareLinDevice::new(create_lin(self.adapter)?, bus_id, self.elapsed);
            let opened = autors_runtime::block_on(device.open(&configuration))
                .map_err(|error| error.to_string())?;
            self.hardware_device = Some(device);
            opened
        };
        if !opened {
            self.hardware_device = None;
            return Err(format!(
                "{} LIN channel refused to open",
                self.adapter.name()
            ));
        }
        self.connected = true;
        self.last_error = None;
        Ok(())
    }

    pub fn disconnect(&mut self) {
        if self.adapter == AdapterKind::Virtual {
            autors_runtime::block_on(self.device.close());
        } else if let Some(device) = &mut self.hardware_device {
            autors_runtime::block_on(device.close());
        }
        self.hardware_device = None;
        self.connected = false;
        self.running = false;
    }

    pub fn set_running(&mut self, running: bool) -> Result<(), String> {
        if running && !self.connected {
            return Err("connect the selected LIN channel first".to_owned());
        }
        if running {
            let scheduler = self
                .scheduler
                .as_mut()
                .ok_or_else(|| "open an LDF before starting LIN scheduling".to_owned())?;
            if scheduler.active_schedule().is_none() {
                let schedule = scheduler
                    .schedules()
                    .next()
                    .map(str::to_owned)
                    .ok_or_else(|| "the LDF has no schedule tables".to_owned())?;
                scheduler
                    .start_schedule(&schedule)
                    .map_err(|error| error.to_string())?;
            }
        }
        self.running = running;
        Ok(())
    }

    pub fn advance(&mut self, elapsed: Duration) {
        if !self.connected {
            return;
        }
        self.elapsed = self.elapsed.saturating_add(elapsed);
        if self.adapter == AdapterKind::Virtual {
            self.device.set_clock(self.elapsed);
        } else if let Some(device) = &mut self.hardware_device {
            device.set_clock(self.elapsed);
        }
        if self.running {
            let now = self.origin.checked_add(self.elapsed).unwrap_or(self.origin);
            if let Some(scheduler) = &mut self.scheduler {
                let result = if self.adapter == AdapterKind::Virtual {
                    autors_runtime::block_on(scheduler.poll_at(&mut self.device, now))
                } else if let Some(device) = &mut self.hardware_device {
                    autors_runtime::block_on(scheduler.poll_at(device, now))
                } else {
                    return;
                };
                if let Err(error) = result {
                    self.last_error = Some(error.to_string());
                    self.running = false;
                }
            }
        }
        self.collect_device_traffic();
    }

    pub fn send_text(&mut self, command: &str) -> Result<usize, String> {
        if !self.connected {
            return Err("connect the selected LIN channel first".to_owned());
        }
        let (id, data) = parse_send_command(command)?;
        let sent = if self.adapter == AdapterKind::Virtual {
            self.device.set_clock(self.elapsed);
            autors_runtime::block_on(self.device.send(id, &data))
        } else {
            let device = self
                .hardware_device
                .as_mut()
                .ok_or_else(|| "selected LIN adapter is not open".to_owned())?;
            device.set_clock(self.elapsed);
            autors_runtime::block_on(device.send(id, &data))
        }
        .map_err(|error| error.to_string())?;
        self.collect_device_traffic();
        Ok(sent)
    }

    pub fn inject_text(&mut self, command: &str) -> Result<usize, String> {
        if !self.connected {
            return Err("connect the selected LIN channel first".to_owned());
        }
        if self.adapter != AdapterKind::Virtual {
            return Err("receive injection is available only on the virtual adapter".to_owned());
        }
        let (id, data) = parse_send_command(command)?;
        self.device.inject(id, data.clone());
        self.collect_device_traffic();
        Ok(data.len())
    }

    pub fn clear_trace(&mut self) {
        self.trace.clear();
        self.tx_frames = 0;
        self.rx_frames = 0;
        self.wire_bits = 0;
    }

    pub fn trace(&self) -> &VecDeque<LinBusTrace> {
        &self.trace
    }

    pub fn save_ltrc(&self, path: &std::path::Path) -> Result<usize, String> {
        let records = self
            .trace
            .iter()
            .enumerate()
            .map(|(index, record)| {
                let header_only = record.operation == "Header";
                let checksum = if header_only {
                    0
                } else {
                    compute_checksum(
                        LinChecksumType::CalcChecksumEnhanced,
                        record.id,
                        &record.data,
                    )
                };
                LtrcRecord::Frame(TraceFrame {
                    index: index as u64 + 1,
                    timestamp: record.timestamp,
                    direction: if header_only {
                        LtrcDirection::Subscriber
                    } else {
                        LtrcDirection::Publisher
                    },
                    id: record.id,
                    dlc: record.dlc,
                    data: if header_only {
                        vec![None; usize::from(record.dlc)]
                    } else {
                        record.data.iter().copied().map(Some).collect()
                    },
                    checksum,
                    checksum_type: LtrcChecksumType::Enhanced,
                    errors: Vec::new(),
                })
            })
            .collect::<Vec<_>>();
        let count = records.len();
        LtrcFile {
            version: LtrcVersion::V1_2,
            start_time: Some(StartTime::OleAutomationDays(0.0)),
            records,
        }
        .save(path)
        .map_err(|error| error.to_string())?;
        Ok(count)
    }

    pub fn frames(&self) -> Vec<LinFrameState> {
        self.scheduler
            .as_ref()
            .map(LinScheduler::frames)
            .unwrap_or_default()
    }

    pub fn schedules(&self) -> Vec<String> {
        self.scheduler
            .as_ref()
            .map(|scheduler| scheduler.schedules().map(str::to_owned).collect())
            .unwrap_or_default()
    }

    pub fn active_schedule(&self) -> Option<&str> {
        self.scheduler
            .as_ref()
            .and_then(LinScheduler::active_schedule)
    }

    pub fn select_schedule(&mut self, index: usize) -> Result<String, String> {
        let names = self.schedules();
        let name = names
            .get(index)
            .ok_or_else(|| "the LDF has no schedule at that index".to_owned())?
            .clone();
        self.scheduler
            .as_mut()
            .ok_or_else(|| "open an LDF first".to_owned())?
            .start_schedule(&name)
            .map_err(|error| error.to_string())?;
        Ok(name)
    }

    pub fn set_frame_enabled(&mut self, name: &str, enabled: bool) -> Result<(), String> {
        self.scheduler
            .as_mut()
            .ok_or_else(|| "open an LDF first".to_owned())?
            .set_frame_enabled(name, enabled)
            .map_err(|error| error.to_string())
    }

    pub fn trigger(&mut self, name: &str) -> Result<(), String> {
        self.scheduler
            .as_mut()
            .ok_or_else(|| "open an LDF first".to_owned())?
            .trigger_frame(name)
            .map_err(|error| error.to_string())
    }

    pub fn set_payload_text(&mut self, name: &str, payload: &str) -> Result<(), String> {
        let payload = parse_payload(payload)?;
        self.scheduler
            .as_mut()
            .ok_or_else(|| "open an LDF first".to_owned())?
            .set_payload(name, payload)
            .map_err(|error| error.to_string())
    }

    pub fn elapsed(&self) -> Duration {
        self.elapsed
    }

    pub fn tx_frames(&self) -> u64 {
        self.tx_frames
    }

    pub fn rx_frames(&self) -> u64 {
        self.rx_frames
    }

    pub fn average_bits_per_second(&self) -> f64 {
        if self.elapsed.is_zero() {
            0.0
        } else {
            self.wire_bits as f64 / self.elapsed.as_secs_f64()
        }
    }

    pub fn average_frames_per_second(&self) -> f64 {
        if self.elapsed.is_zero() {
            0.0
        } else {
            (self.tx_frames + self.rx_frames) as f64 / self.elapsed.as_secs_f64()
        }
    }

    pub fn baud_rate(&self) -> u32 {
        self.database
            .as_ref()
            .map_or(19_200, |database| database.baud_rate)
    }

    pub fn network_name(&self) -> &str {
        self.database
            .as_ref()
            .and_then(|database| database.channel_name.as_deref())
            .unwrap_or(if self.database.is_some() {
                "LDF network loaded"
            } else {
                "No LDF loaded"
            })
    }

    pub fn adapter_name(&self) -> &'static str {
        self.adapter.name()
    }

    pub fn driver_name(&self) -> &'static str {
        self.adapter.driver()
    }

    pub fn channel(&self) -> i32 {
        self.channel
    }

    pub fn hardware_type(&self) -> i32 {
        self.hardware_type
    }

    pub fn cycle_adapter(&mut self) -> Result<&'static str, String> {
        if self.connected {
            return Err("disconnect LIN before changing adapters".to_owned());
        }
        self.adapter = self.adapter.next();
        self.channel = 0;
        self.hardware_type = self.adapter.default_lin_hardware_type();
        self.last_error = None;
        Ok(self.adapter.name())
    }

    pub fn configure_adapter(&mut self, input: &str) -> Result<(), String> {
        if self.connected {
            return Err("disconnect LIN before changing its channel".to_owned());
        }
        let (channel, hardware_type) = parse_adapter_configuration(input)?;
        self.channel = channel;
        if let Some(hardware_type) = hardware_type {
            self.hardware_type = hardware_type;
        }
        Ok(())
    }

    pub fn cycle_channel(&mut self, delta: isize) -> Result<i32, String> {
        if self.connected {
            return Err("disconnect LIN before changing its channel".to_owned());
        }
        self.channel = if delta.is_negative() {
            self.channel.saturating_sub(1)
        } else {
            self.channel.saturating_add(1)
        };
        Ok(self.channel)
    }

    fn collect_device_traffic(&mut self) {
        let sent = if self.adapter == AdapterKind::Virtual {
            self.device.drain_sent().collect::<Vec<_>>()
        } else {
            self.hardware_device
                .as_mut()
                .map(|device| device.drain_sent().collect::<Vec<_>>())
                .unwrap_or_default()
        };
        for record in sent {
            self.push_trace(record.frame, record.header_only);
        }
        loop {
            let received = if self.adapter == AdapterKind::Virtual {
                autors_runtime::block_on(self.device.on_receive())
            } else if let Some(device) = &mut self.hardware_device {
                autors_runtime::block_on(device.on_receive())
            } else {
                break;
            };
            match received {
                Ok(Some(frame)) => self.push_trace(frame, false),
                Ok(None) => break,
                Err(error) => {
                    self.last_error = Some(error.to_string());
                    break;
                }
            }
        }
    }

    fn push_trace(&mut self, frame: LinFrame, header_only: bool) {
        let name = self
            .database
            .as_ref()
            .and_then(|database| database.frame_by_id(frame.id))
            .map(frame_name)
            .unwrap_or_else(|| "-".to_owned());
        let signals = if header_only {
            Vec::new()
        } else {
            self.database
                .as_ref()
                .and_then(|database| {
                    database
                        .unconditional_frame_by_id(frame.id)
                        .and_then(|definition| {
                            database
                                .decode_frame(&definition.name, &frame.data, true)
                                .ok()
                        })
                })
                .map(|values| {
                    values
                        .into_iter()
                        .map(|(name, value)| format!("{name} = {}", format_signal_value(&value)))
                        .collect()
                })
                .unwrap_or_default()
        };
        if frame.is_master_frame {
            self.tx_frames = self.tx_frames.saturating_add(1);
        } else {
            self.rx_frames = self.rx_frames.saturating_add(1);
        }
        let bits = if header_only {
            34
        } else {
            44 + (frame.data.len() as u64 * 10)
        };
        self.wire_bits = self.wire_bits.saturating_add(bits);
        if self.trace.len() == TRACE_LIMIT {
            self.trace.pop_front();
        }
        let dlc = self
            .database
            .as_ref()
            .and_then(|database| database.unconditional_frame_by_id(frame.id))
            .map_or(frame.data.len() as u8, |definition| definition.length)
            .clamp(1, 8);
        self.trace.push_back(LinBusTrace {
            timestamp: frame.elapsed,
            is_tx: frame.is_master_frame,
            id: frame.id,
            frame: name,
            operation: if header_only { "Header" } else { "Frame" },
            data: frame.data,
            dlc,
            signals,
        });
    }
}

struct VirtualLinRecord {
    frame: LinFrame,
    header_only: bool,
}

struct TracingHardwareLinDevice {
    inner: Box<dyn LinDevice + Send>,
    bus_id: String,
    clock: Duration,
    sent: VecDeque<VirtualLinRecord>,
}

impl TracingHardwareLinDevice {
    fn new(inner: Box<dyn LinDevice + Send>, bus_id: String, clock: Duration) -> Self {
        Self {
            inner,
            bus_id,
            clock,
            sent: VecDeque::new(),
        }
    }

    fn set_clock(&mut self, clock: Duration) {
        self.clock = clock;
    }

    fn drain_sent(&mut self) -> impl Iterator<Item = VirtualLinRecord> + '_ {
        self.sent.drain(..)
    }

    fn record_sent(&mut self, id: u8, data: Vec<u8>, header_only: bool) {
        let mut frame = LinFrame::new(&self.bus_id, id, data, true);
        frame.elapsed = self.clock;
        self.sent.push_back(VirtualLinRecord { frame, header_only });
    }
}

#[async_trait]
impl LinDevice for TracingHardwareLinDevice {
    fn unique_bus_id(&self) -> i32 {
        self.inner.unique_bus_id()
    }

    fn is_available(&self) -> bool {
        self.inner.is_available()
    }

    async fn open(&mut self, config: &LinConfiguration) -> autors_lin::Result<bool> {
        self.bus_id = config.bus_id.clone().unwrap_or_else(|| self.bus_id.clone());
        self.inner.open(config).await
    }

    async fn send(&mut self, id: u8, data: &[u8]) -> autors_lin::Result<usize> {
        let sent = self.inner.send(id, data).await?;
        if sent > 0 {
            self.record_sent(id, data[..sent.min(data.len())].to_vec(), false);
        }
        Ok(sent)
    }

    async fn request(&mut self, id: u8) -> autors_lin::Result<bool> {
        let sent = self.inner.request(id).await?;
        if sent {
            self.record_sent(id, Vec::new(), true);
        }
        Ok(sent)
    }

    async fn on_receive(&mut self) -> autors_lin::Result<Option<LinFrame>> {
        self.inner.on_receive().await
    }

    async fn close(&mut self) {
        self.inner.close().await;
        self.sent.clear();
    }
}

struct VirtualLinDevice {
    opened: bool,
    bus_id: String,
    clock: Duration,
    sent: VecDeque<VirtualLinRecord>,
    received: VecDeque<LinFrame>,
}

impl VirtualLinDevice {
    fn new() -> Self {
        Self {
            opened: false,
            bus_id: "Virtual/LIN1".to_owned(),
            clock: Duration::ZERO,
            sent: VecDeque::new(),
            received: VecDeque::new(),
        }
    }

    fn set_clock(&mut self, clock: Duration) {
        self.clock = clock;
    }

    fn inject(&mut self, id: u8, data: Vec<u8>) {
        let mut frame = LinFrame::new(&self.bus_id, id, data, false);
        frame.elapsed = self.clock;
        self.received.push_back(frame);
    }

    fn drain_sent(&mut self) -> impl Iterator<Item = VirtualLinRecord> + '_ {
        self.sent.drain(..)
    }

    fn validate_operation(&self, id: u8, data: &[u8]) -> autors_lin::Result<()> {
        if !self.opened {
            return Err(autors_lin::Error::Driver(
                "virtual LIN channel is closed".to_owned(),
            ));
        }
        if id > 0x3f {
            return Err(autors_lin::Error::Invalid(format!(
                "LIN ID 0x{id:02X} exceeds 0x3F"
            )));
        }
        if data.len() > 8 {
            return Err(autors_lin::Error::Invalid(format!(
                "LIN payload has {} bytes; maximum is 8",
                data.len()
            )));
        }
        Ok(())
    }
}

#[async_trait]
impl LinDevice for VirtualLinDevice {
    fn unique_bus_id(&self) -> i32 {
        1
    }

    fn is_available(&self) -> bool {
        true
    }

    async fn open(&mut self, configuration: &LinConfiguration) -> autors_lin::Result<bool> {
        self.bus_id = configuration
            .bus_id
            .clone()
            .unwrap_or_else(|| "Virtual/LIN1".to_owned());
        self.opened = true;
        Ok(true)
    }

    async fn send(&mut self, id: u8, data: &[u8]) -> autors_lin::Result<usize> {
        self.validate_operation(id, data)?;
        let mut frame = LinFrame::new(&self.bus_id, id, data.to_vec(), true);
        frame.elapsed = self.clock;
        self.sent.push_back(VirtualLinRecord {
            frame,
            header_only: false,
        });
        Ok(data.len())
    }

    async fn request(&mut self, id: u8) -> autors_lin::Result<bool> {
        self.validate_operation(id, &[])?;
        let mut frame = LinFrame::new(&self.bus_id, id, Vec::new(), true);
        frame.elapsed = self.clock;
        self.sent.push_back(VirtualLinRecord {
            frame,
            header_only: true,
        });
        Ok(true)
    }

    async fn on_receive(&mut self) -> autors_lin::Result<Option<LinFrame>> {
        if !self.opened {
            return Ok(None);
        }
        Ok(self.received.pop_front())
    }

    async fn close(&mut self) {
        self.opened = false;
        self.received.clear();
    }
}

fn parse_adapter_configuration(input: &str) -> Result<(i32, Option<i32>), String> {
    let mut values = input.split_whitespace();
    let channel = values
        .next()
        .ok_or_else(|| "enter a zero-based channel and optional hardware type".to_owned())?;
    let channel = parse_i32(channel, "channel")?;
    if channel < 0 {
        return Err("channel must be zero or greater".to_owned());
    }
    let hardware_type = values
        .next()
        .map(|value| parse_i32(value, "hardware type"))
        .transpose()?;
    if values.next().is_some() {
        return Err("enter only a channel and optional hardware type".to_owned());
    }
    Ok((channel, hardware_type))
}

fn parse_i32(value: &str, field: &str) -> Result<i32, String> {
    let parsed = if let Some(hex) = value
        .strip_prefix("0x")
        .or_else(|| value.strip_prefix("0X"))
    {
        i32::from_str_radix(hex, 16)
    } else {
        value.parse()
    };
    parsed.map_err(|_| format!("invalid {field} {value:?}"))
}

fn parse_send_command(command: &str) -> Result<(u8, Vec<u8>), String> {
    let mut fields = command.split_whitespace();
    let id_text = fields
        .next()
        .ok_or_else(|| "enter a LIN ID followed by hexadecimal bytes".to_owned())?;
    let id = u8::from_str_radix(id_text.trim_start_matches("0x"), 16)
        .map_err(|_| format!("invalid hexadecimal LIN ID {id_text:?}"))?;
    if id > 0x3f {
        return Err(format!("LIN ID {id_text:?} exceeds 0x3F"));
    }
    Ok((id, parse_payload_fields(fields)?))
}

fn parse_payload(payload: &str) -> Result<Vec<u8>, String> {
    parse_payload_fields(payload.split_whitespace())
}

fn parse_payload_fields<'a>(fields: impl Iterator<Item = &'a str>) -> Result<Vec<u8>, String> {
    let data = fields
        .map(|field| {
            u8::from_str_radix(field.trim_start_matches("0x"), 16)
                .map_err(|_| format!("invalid hexadecimal data byte {field:?}"))
        })
        .collect::<Result<Vec<_>, _>>()?;
    if data.len() > 8 {
        return Err(format!(
            "LIN payload has {} bytes; maximum is 8",
            data.len()
        ));
    }
    Ok(data)
}

fn frame_name(frame: FrameRef<'_>) -> String {
    match frame {
        FrameRef::Unconditional(frame) => frame.name.clone(),
        FrameRef::Sporadic(frame) => frame.name.clone(),
        FrameRef::EventTriggered(frame) => frame.name.clone(),
        FrameRef::Diagnostic(frame) => frame.name.clone(),
    }
}

fn format_signal_value(value: &SignalValue) -> String {
    match value {
        SignalValue::Integer(value) => value.to_string(),
        SignalValue::Float(value) => format!("{value:.6}"),
        SignalValue::Text(value) => value.clone(),
        SignalValue::Bytes(value) => value
            .iter()
            .map(|byte| format!("{byte:02X}"))
            .collect::<Vec<_>>()
            .join(" "),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const LDF: &str = r#"
LIN_description_file;
LIN_protocol_version = "2.2";
LIN_language_version = "2.2";
LIN_speed = 19.2 kbps;
Channel_name = "BodyLIN";

Nodes {
    Master: Master, 5 ms, 0.1 ms;
    Slaves: Slave;
}
Signals {
    CommandValue: 8, 7, Master, Slave;
    StatusValue: 8, 2, Slave, Master;
}
Frames {
    Command: 3, Master, 1 { CommandValue, 0; }
    Status: 1, Slave, 1 { StatusValue, 0; }
}
Node_attributes {
    Slave {
        LIN_protocol = "2.2";
        configured_NAD = 1;
        product_id = 1, 2, 3;
    }
}
Schedule_tables {
    Main {
        Command delay 10 ms;
        Status delay 10 ms;
    }
}
"#;

    #[test]
    fn manual_send_and_injection_are_traced_and_decoded() {
        let database = Ldf::parse_str(LDF).unwrap();
        let mut session = LinBusSession::new();
        session.attach_database(&database).unwrap();
        session.connect().unwrap();
        assert_eq!(session.send_text("03 2A").unwrap(), 1);
        assert_eq!(session.inject_text("01 05").unwrap(), 1);
        assert_eq!(session.tx_frames(), 1);
        assert_eq!(session.rx_frames(), 1);
        assert_eq!(session.trace()[0].frame, "Command");
        assert_eq!(session.trace()[1].signals, ["StatusValue = 5"]);
    }

    #[test]
    fn ldf_schedule_sends_master_and_requests_unsimulated_slave() {
        let database = Ldf::parse_str(LDF).unwrap();
        let mut session = LinBusSession::new();
        session.attach_database(&database).unwrap();
        session.connect().unwrap();
        session.set_payload_text("Command", "2A").unwrap();
        session.set_running(true).unwrap();
        session.advance(Duration::ZERO);
        assert_eq!(session.trace()[0].frame, "Command");
        assert_eq!(session.trace()[0].data, [0x2a]);
        session.advance(Duration::from_millis(10));
        assert_eq!(session.trace()[1].frame, "Status");
        assert_eq!(session.trace()[1].operation, "Header");
    }

    #[test]
    fn exports_live_trace_as_roundtrippable_ltrc() {
        let database = Ldf::parse_str(LDF).unwrap();
        let mut session = LinBusSession::new();
        session.attach_database(&database).unwrap();
        session.connect().unwrap();
        session.set_running(true).unwrap();
        session.advance(Duration::ZERO);
        session.advance(Duration::from_millis(10));
        let path =
            std::env::temp_dir().join(format!("autors-cli-live-lin-{}.ltrc", std::process::id()));
        assert_eq!(session.save_ltrc(&path).unwrap(), 2);
        let trace = LtrcFile::open(&path).unwrap();
        assert_eq!(trace.records.len(), 2);
        let LtrcRecord::Frame(header) = &trace.records[1] else {
            panic!("expected header request")
        };
        assert!(header.data.iter().all(Option::is_none));
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn parses_lin_commands_and_rejects_invalid_ranges() {
        assert_eq!(
            parse_send_command("22 AA BB").unwrap(),
            (0x22, vec![0xaa, 0xbb])
        );
        assert!(parse_send_command("40 00").is_err());
        assert!(parse_send_command("01 GG").is_err());
        assert!(parse_send_command("01 00 01 02 03 04 05 06 07 08").is_err());
    }

    #[test]
    fn adapter_configuration_accepts_vendor_hardware_type() {
        assert_eq!(parse_adapter_configuration("1 3").unwrap(), (1, Some(3)));
        assert_eq!(parse_adapter_configuration("4 0x2").unwrap(), (4, Some(2)));
        assert!(parse_adapter_configuration("").is_err());
    }
}