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
use crate::config::MergedConfig;
use crate::rtt_reader::RttDefmtReader;
use crate::serial::{
get_timestamp, parse_data_bits, parse_flow_control, parse_parity, parse_stop_bits,
};
use inline_colorization::*;
use std::fs::OpenOptions;
use std::io::{self, BufWriter, Read, Write};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use crossterm::{
event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
terminal,
};
use pretty_hex::*;
enum MonitorCommand {
Repaint(u8),
SwitchMode,
Quit,
}
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
match chars.peek() {
Some('[') => {
chars.next();
for ch in chars.by_ref() {
if ch.is_ascii_alphabetic() {
break;
}
}
}
_ => {
chars.next();
}
}
} else {
out.push(c);
}
}
out
}
macro_rules! poll_ctrl_rx_while_waiting {
($ctrl_rx:expr, $running:expr) => {
let range = core::range::Range { start: 0, end: 20 };
for _ in range {
if let Ok(cmd) = $ctrl_rx.try_recv() {
match cmd {
MonitorCommand::SwitchMode => {
terminal::disable_raw_mode().ok();
return Ok(crate::AppExitState::SwitchToPlotter {
port: None,
rtt_reader: None,
});
}
MonitorCommand::Quit => {
println!("\r\n{color_yellow} Shutting down ComChan…{color_reset}");
$running.store(false, std::sync::atomic::Ordering::SeqCst);
return Ok(crate::AppExitState::Quit);
}
_ => {}
}
}
thread::sleep(Duration::from_millis(50));
}
};
}
pub fn run_normal_mode(
config: MergedConfig,
port_name: String,
passed_port: Option<Box<dyn serialport::SerialPort>>,
passed_rtt: Option<crate::rtt_reader::RttDefmtReader>,
) -> Result<crate::AppExitState, Box<dyn std::error::Error>> {
let serial_config = if config.simulate || config.replay_file.is_some() || config.rtt {
None
} else {
Some((
parse_data_bits(config.data_bits).map_err(|e| format!("Configuration error: {}", e))?,
parse_stop_bits(config.stop_bits).map_err(|e| format!("Configuration error: {}", e))?,
parse_parity(&config.parity).map_err(|e| format!("Configuration error: {}", e))?,
parse_flow_control(&config.flow_control)
.map_err(|e| format!("Configuration error: {}", e))?,
))
};
// 1. Setup logging ONCE
let mut log_writer = if let Some(log_path) = &config.log_file {
let file = OpenOptions::new()
.create(true)
.append(true)
.open(log_path)
.map_err(|e| format!("Failed to open log file {}: {}", log_path, e))?;
Some(BufWriter::new(file))
} else {
None
};
let mut csv_streamer = if let Some(csv_path) = &config.csv_file {
crate::export::CsvStreamer::new(csv_path)
.map_err(|e| format!("Failed to open CSV file {}: {}", csv_path, e))
.ok()
} else {
None
};
let mut session_replayer = if let Some(ref path) = config.replay_file {
Some(
crate::replay::SessionReplayer::new(path)
.map_err(|e| format!("Failed to open replay file '{}': {}", path, e))?,
)
} else {
None
};
println!("{color_green} Listening… (Ctrl+C to exit, Ctrl+L to clear screen){color_reset}\n");
// 2. Setup channels and input thread ONCE
let (input_tx, input_rx) = mpsc::channel::<String>();
let (ctrl_tx, ctrl_rx) = mpsc::channel::<MonitorCommand>();
thread::spawn(move || {
terminal::enable_raw_mode().ok();
let mut line_buf = String::new();
loop {
if event::poll(Duration::from_millis(10)).unwrap_or(false) {
match event::read() {
Ok(Event::Key(KeyEvent {
code, modifiers, ..
})) => match (code, modifiers) {
(KeyCode::Char('l'), KeyModifiers::CONTROL) => {
print!("\x1bc\x1b[5 q");
io::stdout().flush().ok();
ctrl_tx.send(MonitorCommand::Repaint(b'\r')).ok();
}
(KeyCode::Char('p'), KeyModifiers::CONTROL) => {
ctrl_tx.send(MonitorCommand::SwitchMode).ok();
break;
}
(KeyCode::Char('c'), KeyModifiers::CONTROL) => {
ctrl_tx.send(MonitorCommand::Quit).ok();
break;
}
(KeyCode::Enter, _) => {
let _ = input_tx.send(line_buf.clone());
line_buf.clear();
}
(KeyCode::Backspace, _) => {
line_buf.pop();
print!("\x08 \x08");
io::stdout().flush().ok();
}
(KeyCode::Char(c), _) => {
line_buf.push(c);
print!("{}", c);
io::stdout().flush().ok();
}
_ => {}
},
Err(_) => break,
_ => {}
}
}
}
terminal::disable_raw_mode().ok();
});
let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
let mut buffer = [0u8; 1024];
let mut last_sent: Option<String> = None;
let mut line_acc = String::new();
let mut rx_buf = String::new();
let mut lines_discarded = 0;
const DISCARD_COUNT: usize = 5;
let mut active_port = passed_port;
let mut active_rtt = passed_rtt;
// Connection & Reconnection
while running.load(std::sync::atomic::Ordering::SeqCst) {
// Initialize RTT reader
let mut rtt_reader = if let Some(r) = active_rtt.take() {
Some(r)
} else if config.rtt {
let elf = config.elf.as_deref().unwrap_or("");
match RttDefmtReader::new(elf, config.chip.clone()) {
Ok(reader) => Some(reader),
Err(e) => {
let err_msg = e.to_string();
if err_msg.contains("No such file")
|| err_msg.contains("No defmt table")
|| err_msg.contains("ChipNotFound")
|| err_msg.contains("requires an ELF file")
{
return Err(e);
}
// Otherwise, treat as a transient hardware/connection error and wait
print!("\r{color_yellow}⏳ Waiting for RTT target...{color_reset}\x1b[K");
io::stdout().flush().ok();
poll_ctrl_rx_while_waiting!(ctrl_rx, running);
continue;
}
}
} else {
None
};
// Serial Port
let mut port = if let Some(p) = active_port.take() {
Some(p)
} else if config.simulate || config.replay_file.is_some() || config.rtt {
None
} else {
// Match handles the error instead of returning it
let (data_bits, stop_bits, parity, flow_control) = serial_config.unwrap();
match serialport::new(&port_name, config.baud)
.timeout(Duration::from_millis(config.timeout_ms))
.data_bits(data_bits)
.stop_bits(stop_bits)
.parity(parity)
.flow_control(flow_control)
.open()
{
Ok(mut p) => {
let _ = p.write_data_terminal_ready(false);
thread::sleep(Duration::from_millis(config.reset_delay_ms));
let _ = p.write_all(b"\r");
let _ = p.flush();
if config.zephyr {
thread::sleep(Duration::from_millis(100));
let _ = p.write_all(b"shell echo off\r");
let _ = p.flush();
thread::sleep(Duration::from_millis(100));
}
println!(
"\r\n{color_green}🔌 Connected to {} at {} baud{color_reset}",
port_name, config.baud
);
if config.verbose {
println!(
"\r{color_blue}⚙️ Config: {} data bits, {} stop bits, {} parity, {} flow control{color_reset}",
config.data_bits, config.stop_bits, config.parity, config.flow_control
);
if let Some(log_path) = &config.log_file {
println!("\r{color_blue} Logging to: {}{color_reset}", log_path);
}
}
Some(p)
}
Err(_) => {
// Retry connection every 1 second
print!(
"\r{color_yellow}⏳ Waiting for device on {}...{color_reset}\x1b[K",
port_name
);
io::stdout().flush().ok();
poll_ctrl_rx_while_waiting!(ctrl_rx, running);
continue;
}
}
};
let mut is_connected = true;
let mut hex_buf: Vec<u8> = Vec::new();
// Read / Write Data
while running.load(std::sync::atomic::Ordering::SeqCst) && is_connected {
// ── Read from serial ─────────────────────────────────────────────────
if config.simulate {
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs_f64();
let sim_text = format!(
"Temperature: {:2}, Humidity: {:.2}, Pressure: {:.2}\r\n",
(t * 1.0).sin() * 50.0,
(t * 0.8).cos() * 50.0,
(t * 0.5).sin() * 50.0
);
if config.hex_mode || config.hex_pretty {
let hex_out = format!("{:?}", sim_text.as_bytes().hex_dump());
let raw_mode_safe_hex = hex_out.replace('\n', "\r\n");
print!("\r\n{}\r\n", raw_mode_safe_hex);
io::stdout().flush().ok();
} else {
io::stdout().write_all(sim_text.as_bytes()).ok();
io::stdout().flush().ok();
}
if let Some(ref mut streamer) = csv_streamer {
let clean = strip_ansi(sim_text.trim());
let readings = crate::parser::parse_sensor_data(&clean);
let _ = streamer.write_row(&readings);
}
thread::sleep(Duration::from_millis(500));
} else if let Some(ref mut replayer) = session_replayer {
match replayer.next_payload() {
crate::replay::ReplayEvent::Payload(payload) => {
let text = format!("{}\r\n", payload);
io::stdout().write_all(text.as_bytes()).ok();
io::stdout().flush().ok();
}
crate::replay::ReplayEvent::Waiting => {}
crate::replay::ReplayEvent::Eof => {
println!("\n{color_yellow}Replay Finished.{color_reset}");
running.store(false, std::sync::atomic::Ordering::SeqCst);
break;
}
}
} else if let Some(reader) = rtt_reader.as_mut() {
match reader.poll_logs() {
Ok(logs) => {
if logs.is_empty() {
thread::sleep(Duration::from_millis(10));
} else {
for line in logs {
let trimmed = line.trim_end();
if trimmed.is_empty() {
continue;
}
if config.verbose {
print!("\r[{}] {}\r\n", get_timestamp(), trimmed);
} else {
print!("\r{}\r\n", trimmed);
}
io::stdout().flush().ok();
if let Some(ref mut writer) = log_writer {
writeln!(writer, "RX [{}]: {}", get_timestamp(), trimmed).ok();
let _ = writer.flush();
}
if let Some(ref mut streamer) = csv_streamer {
let readings = crate::parser::parse_sensor_data(trimmed);
let _ = streamer.write_row(&readings);
}
}
}
}
Err(e) => {
eprintln!(
"\r\n{color_yellow}⚠️ RTT connection lost ({color_red}{}{color_yellow}). Attempting to reconnect...{color_reset}",
e
);
if let Some(ref mut writer) = log_writer {
writeln!(
writer,
"ERROR [{}]: RTT connection lost: {}",
get_timestamp(),
e
)
.ok();
let _ = writer.flush();
}
is_connected = false;
}
}
} else if let Some(p) = port.as_mut() {
match p.read(&mut buffer) {
Ok(n) if n > 0 => {
let raw = &buffer[..n];
if config.hex_mode || config.hex_pretty {
let (should_print, data_to_print) = if config.hex_pretty {
hex_buf.extend_from_slice(raw);
if hex_buf.contains(&b'\n') || hex_buf.len() >= 64 {
let data = hex_buf.clone();
hex_buf.clear();
(true, data)
} else {
(false, Vec::new())
}
} else {
(true, raw.to_vec())
};
if should_print {
let hex_out = format!("{:?}", data_to_print.hex_dump());
let raw_mode_safe_hex = hex_out.replace('\n', "\r\n");
print!("\r\n{}\r\n", raw_mode_safe_hex);
io::stdout().flush().ok();
if let Some(ref mut writer) = log_writer {
writeln!(writer, "RX HEX [{}]:\n{}", get_timestamp(), hex_out)
.ok();
let _ = writer.flush();
}
}
continue;
}
let text = String::from_utf8_lossy(raw);
// ── Echo suppression ─────────────────────────────────────────
line_acc.push_str(&text);
let mut suppress = false;
if let Some(ref sent) = last_sent {
let clean_acc = strip_ansi(&line_acc).trim().to_string();
if clean_acc == *sent {
suppress = true;
last_sent = None;
line_acc.clear();
}
}
if suppress {
continue;
}
// ── Verbose timestamp prefix ─────────────────────────────────
if config.verbose {
let mut remaining = text.as_ref();
while let Some(pos) = remaining.find('\n') {
let chunk = &remaining[..=pos];
let clean = strip_ansi(chunk);
if !clean.trim().is_empty() {
print!("[{}] {}", get_timestamp(), chunk);
} else {
print!("{}", chunk);
}
remaining = &remaining[pos + 1..];
}
if !remaining.is_empty() {
print!("{}", remaining);
}
} else {
io::stdout().write_all(raw).ok();
}
io::stdout().flush().ok();
// ── Logging & CSV streaming ───────────────────────────────────────────────────
/*if let Some(ref mut writer) = log_writer {
let mut remaining = text.as_ref();
while let Some(pos) = remaining.find('\n') {
let chunk = &remaining[..=pos];
let clean = strip_ansi(chunk);
writeln!(writer, "RX [{}]: {}", get_timestamp(), clean.trim_end())
.ok();
// Stream to CSV
if let Some(ref mut streamer) = csv_streamer {
let readings = crate::parser::parse_sensor_data(clean.trim());
let _ = streamer.write_row(&readings);
}
remaining = &remaining[pos + 1..];
}
let _ = writer.flush();
} else {
if csv_streamer.is_some() {
let mut remaining = text.as_ref();
while let Some(pos) = remaining.find('\n') {
let chunk = &remaining[..=pos];
let clean = strip_ansi(chunk);
if let Some(ref mut streamer) = csv_streamer {
let readings = crate::parser::parse_sensor_data(clean.trim());
let _ = streamer.write_row(&readings);
}
remaining = &remaining[pos + 1..];
}
}
}*/
rx_buf.push_str(&text);
while let Some(pos) = rx_buf.find('\n') {
let full_line = rx_buf.drain(..=pos).collect::<String>();
let clean = strip_ansi(&full_line);
let trimmed = clean.trim_end();
if trimmed.is_empty() {
continue;
}
if lines_discarded < DISCARD_COUNT {
lines_discarded += 1;
continue;
}
if let Some(ref mut writer) = log_writer {
writeln!(writer, "RX [{}]: {}", get_timestamp(), trimmed).ok();
let _ = writer.flush();
}
if let Some(ref mut streamer) = csv_streamer {
let readings = crate::parser::parse_sensor_data(trimmed);
let _ = streamer.write_row(&readings);
}
}
if line_acc.contains('\n') {
line_acc.clear();
}
}
Ok(_) => {}
Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {}
Err(e) => {
// Read Error -> Trigger Reconnection
eprintln!(
"\r\n{color_yellow}⚠️ Device connection lost ({color_red}{}{color_yellow}). Attempting to reconnect...{color_reset}",
e
);
if let Some(ref mut writer) = log_writer {
writeln!(
writer,
"ERROR [{}]: Connection lost: {}",
get_timestamp(),
e
)
.ok();
let _ = writer.flush();
}
is_connected = false;
}
}
}
// Write user input
if let Ok(input) = input_rx.try_recv() {
let clean = input.trim_end();
if !clean.is_empty() {
let message = format!("{}\r", clean);
if let Some(p) = port.as_mut() {
if let Err(e) = p.write_all(message.as_bytes()) {
// Write Error -> Trigger Reconnection
eprintln!("\r\n{color_red}❌ Write error: {e}{color_reset}");
if let Some(ref mut writer) = log_writer {
writeln!(writer, "ERROR [{}]: Write error: {}", get_timestamp(), e)
.ok();
let _ = writer.flush();
}
is_connected = false;
continue;
}
p.flush().ok();
} else if config.rtt {
eprintln!(
"\r\n{color_yellow}Sending Input over RTT is not supported{color_reset}"
);
continue;
}
last_sent = Some(clean.to_string());
line_acc.clear();
if config.verbose {
print!("\r\n[{}] Sent: {}\r\n", get_timestamp(), clean);
io::stdout().flush().ok();
}
if let Some(ref mut writer) = log_writer {
writeln!(writer, "TX [{}]: {}", get_timestamp(), clean).ok();
let _ = writer.flush();
}
thread::sleep(Duration::from_millis(100));
}
}
// ── Control bytes (e.g. Ctrl+L repaint) ─────────────────────────────
if let Ok(cmd) = ctrl_rx.try_recv() {
match cmd {
MonitorCommand::Repaint(byte) => {
if let Some(p) = port.as_mut() {
let _ = p.write_all(&[byte]);
let _ = p.flush();
}
}
MonitorCommand::SwitchMode => {
terminal::disable_raw_mode().ok();
return Ok(crate::AppExitState::SwitchToPlotter { port, rtt_reader });
}
MonitorCommand::Quit => {
println!("\r\n{color_yellow} Shutting down ComChan…{color_reset}");
running.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
}
thread::sleep(Duration::from_millis(10));
}
}
println!("\r\n{color_green} ComChan disconnected cleanly{color_reset}");
terminal::disable_raw_mode().ok();
Ok(crate::AppExitState::Quit)
}