tuiserial_core/
log.rs

1//! Log entry and message log functionality
2//!
3//! This module defines log entries for serial communication events and
4//! the message log that stores communication history.
5
6use chrono::{DateTime, Local};
7use std::collections::VecDeque;
8
9/// Direction of serial communication
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum LogDirection {
12    Rx,
13    Tx,
14}
15
16/// A single log entry representing a serial communication event
17#[derive(Debug, Clone)]
18pub struct LogEntry {
19    pub timestamp: DateTime<Local>,
20    pub direction: LogDirection,
21    pub data: Vec<u8>,
22}
23
24impl LogEntry {
25    /// Create a new log entry with the current timestamp
26    pub fn new(direction: LogDirection, data: Vec<u8>) -> Self {
27        Self {
28            timestamp: Local::now(),
29            direction,
30            data,
31        }
32    }
33}
34
35/// Maximum number of log lines to keep in memory
36pub const MAX_LOG_LINES: usize = 10000;
37
38/// Message log containing all serial communication events
39#[derive(Debug, Default, Clone)]
40pub struct MessageLog {
41    pub entries: VecDeque<LogEntry>,
42    pub rx_count: u64,
43    pub tx_count: u64,
44}
45
46impl MessageLog {
47    /// Create a new empty message log
48    pub fn new() -> Self {
49        Self {
50            entries: VecDeque::with_capacity(MAX_LOG_LINES),
51            rx_count: 0,
52            tx_count: 0,
53        }
54    }
55
56    /// Add a received data entry to the log
57    pub fn push_rx(&mut self, data: Vec<u8>) {
58        self.push_entry(LogEntry::new(LogDirection::Rx, data));
59        self.rx_count += 1;
60    }
61
62    /// Add a transmitted data entry to the log
63    pub fn push_tx(&mut self, data: Vec<u8>) {
64        self.push_entry(LogEntry::new(LogDirection::Tx, data));
65        self.tx_count += 1;
66    }
67
68    /// Internal method to add an entry, maintaining size limit
69    fn push_entry(&mut self, entry: LogEntry) {
70        if self.entries.len() >= MAX_LOG_LINES {
71            self.entries.pop_front();
72        }
73        self.entries.push_back(entry);
74    }
75
76    /// Clear all log entries and reset counters
77    pub fn clear(&mut self) {
78        self.entries.clear();
79        self.rx_count = 0;
80        self.tx_count = 0;
81    }
82}