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
//! Serial (UART) channel for ZeptoClaw.
//!
//! Enables two-way agent communication over a serial port. Inbound messages
//! arrive as newline-delimited JSON (`{"type":"message","text":"...","sender":"..."}`).
//! Responses are written back as `{"type":"response","text":"..."}`.
//!
//! This is the "Telegram but for embedded devices" channel — an ESP32, Arduino,
//! or STM32 can talk to the agent over USB-serial.
//!
//! # Feature Gate
//!
//! This entire module requires the `hardware` feature:
//! ```bash
//! cargo build --features hardware
//! ```
//!
//! # Protocol
//!
//! Inbound (device → agent):
//! ```json
//! {"type":"message","text":"Hello","sender":"esp32-0"}
//! ```
//!
//! Outbound (agent → device):
//! ```json
//! {"type":"response","text":"Hi!"}
//! ```
#[cfg(feature = "hardware")]
mod inner {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::Mutex;
use tokio_serial::SerialPortBuilderExt;
use tracing::{debug, error, info, warn};
use crate::bus::{InboundMessage, MessageBus, OutboundMessage};
use crate::channels::types::{BaseChannelConfig, Channel};
use crate::config::SerialChannelConfig;
use crate::error::{Result, ZeptoError};
use crate::peripherals::validate_serial_path;
/// Inbound message format from the serial device.
#[derive(Debug, Deserialize)]
struct SerialInbound {
#[serde(rename = "type")]
msg_type: String,
text: String,
#[serde(default)]
sender: String,
}
/// Outbound message format sent to the serial device.
#[derive(Debug, Serialize)]
struct SerialOutbound {
#[serde(rename = "type")]
msg_type: String,
text: String,
}
/// Serial (UART) channel — lets embedded devices chat with the agent.
pub struct SerialChannel {
config: SerialChannelConfig,
base_config: BaseChannelConfig,
bus: Arc<MessageBus>,
/// Atomic running flag shared with the spawned read-loop task.
running: Arc<AtomicBool>,
port: Option<Arc<Mutex<tokio_serial::SerialStream>>>,
/// Shutdown signal sender — dropping or sending signals the read loop to exit.
shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
}
impl SerialChannel {
/// Create a new `SerialChannel` from the given config and bus.
pub fn new(config: SerialChannelConfig, bus: Arc<MessageBus>) -> Self {
let base_config = BaseChannelConfig {
name: "serial".to_string(),
allowlist: config.allow_from.clone(),
deny_by_default: config.deny_by_default,
};
Self {
config,
base_config,
bus,
running: Arc::new(AtomicBool::new(false)),
port: None,
shutdown_tx: None,
}
}
}
#[async_trait]
impl Channel for SerialChannel {
fn name(&self) -> &str {
"serial"
}
async fn start(&mut self) -> Result<()> {
validate_serial_path(&self.config.port).map_err(ZeptoError::Config)?;
let stream = tokio_serial::new(&self.config.port, self.config.baud_rate)
.open_native_async()
.map_err(|e| {
ZeptoError::Config(format!(
"Failed to open serial port {}: {}",
self.config.port, e
))
})?;
let port = Arc::new(Mutex::new(stream));
self.port = Some(port.clone());
self.running.store(true, Ordering::SeqCst);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();
self.shutdown_tx = Some(shutdown_tx);
// Spawn the read loop in a background task.
let bus = self.bus.clone();
let running = self.running.clone();
let channel_name = "serial".to_string();
let allow_from = self.config.allow_from.clone();
let deny_by_default = self.config.deny_by_default;
tokio::spawn(async move {
let mut shutdown_rx = shutdown_rx;
// Acquire the lock once for the read loop. The BufReader persists
// across iterations so its internal buffer is never discarded (C2 fix).
// Outbound `send()` will block on the Mutex while the read loop holds
// it; this is acceptable for half-duplex serial where inbound messages
// and outbound responses do not overlap.
let mut guard = port.lock().await;
let mut reader = BufReader::new(&mut *guard);
loop {
let mut buf = String::new();
let read_result = tokio::select! {
result = reader.read_line(&mut buf) => result,
_ = &mut shutdown_rx => {
info!("Serial channel shutdown signal received");
break;
}
};
match read_result {
Ok(0) => {
// EOF — port closed.
info!("Serial channel: port closed (EOF)");
break;
}
Ok(_) => {}
Err(e) => {
error!("Serial read error: {}", e);
break;
}
}
let trimmed = buf.trim();
if trimmed.is_empty() {
continue;
}
let inbound: SerialInbound = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(e) => {
warn!(
"Serial: failed to parse inbound JSON: {} — {:?}",
e, trimmed
);
continue;
}
};
if inbound.msg_type != "message" {
debug!("Serial: ignoring non-message type '{}'", inbound.msg_type);
continue;
}
let sender = if inbound.sender.is_empty() {
"serial-device".to_string()
} else {
inbound.sender.clone()
};
// Access control check.
let allowed = if allow_from.is_empty() {
!deny_by_default
} else {
allow_from.contains(&sender)
};
if !allowed {
warn!("Serial: message from '{}' denied by allowlist", sender);
continue;
}
let msg =
InboundMessage::new(&channel_name, &sender, &channel_name, &inbound.text);
// Drop the Mutex guard temporarily so send() can acquire it
// for outbound writes while we publish.
// NOTE: For half-duplex serial this is not strictly needed, but
// we release it here so bus.publish_inbound() doesn't deadlock
// if the handler tries to send() a response synchronously.
// In practice the bus is async and the send() path is separate,
// so holding the lock is fine. Keeping the simpler single-lock
// approach avoids split() complexity on SerialStream.
if let Err(e) = bus.publish_inbound(msg).await {
error!("Serial: failed to publish inbound message: {}", e);
}
}
running.store(false, Ordering::SeqCst);
info!("Serial channel stopped");
});
Ok(())
}
async fn stop(&mut self) -> Result<()> {
self.running.store(false, Ordering::SeqCst);
if let Some(tx) = self.shutdown_tx.take() {
if tx.send(()).is_err() {
warn!("Serial shutdown receiver already dropped");
}
}
self.port = None;
Ok(())
}
async fn send(&self, msg: OutboundMessage) -> Result<()> {
let port = match &self.port {
Some(p) => p.clone(),
None => return Err(ZeptoError::Config("Serial channel not started".to_string())),
};
let outbound = SerialOutbound {
msg_type: "response".to_string(),
text: msg.content,
};
let mut line = serde_json::to_string(&outbound)
.map_err(|e| ZeptoError::Tool(format!("Serial serialize error: {e}")))?;
line.push('\n');
let mut guard = port.lock().await;
guard
.write_all(line.as_bytes())
.await
.map_err(|e| ZeptoError::Tool(format!("Serial write error: {e}")))?;
guard
.flush()
.await
.map_err(|e| ZeptoError::Tool(format!("Serial flush error: {e}")))?;
Ok(())
}
fn is_running(&self) -> bool {
self.running.load(Ordering::SeqCst)
}
fn is_allowed(&self, user_id: &str) -> bool {
self.base_config.is_allowed(user_id)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bus::MessageBus;
use crate::config::SerialChannelConfig;
fn make_channel(config: SerialChannelConfig) -> SerialChannel {
let bus = Arc::new(MessageBus::new());
SerialChannel::new(config, bus)
}
#[test]
fn test_serial_channel_name() {
let ch = make_channel(SerialChannelConfig {
port: "/dev/ttyUSB0".to_string(),
..Default::default()
});
assert_eq!(ch.name(), "serial");
}
#[test]
fn test_serial_channel_not_running_initially() {
let ch = make_channel(SerialChannelConfig {
port: "/dev/ttyUSB0".to_string(),
..Default::default()
});
assert!(!ch.is_running());
}
#[test]
fn test_serial_channel_allowlist() {
let ch = make_channel(SerialChannelConfig {
port: "/dev/ttyUSB0".to_string(),
allow_from: vec!["esp32-0".to_string()],
..Default::default()
});
assert!(ch.is_allowed("esp32-0"));
assert!(!ch.is_allowed("esp32-1"));
}
#[test]
fn test_serial_channel_deny_by_default() {
let ch = make_channel(SerialChannelConfig {
port: "/dev/ttyUSB0".to_string(),
allow_from: vec![],
deny_by_default: true,
..Default::default()
});
assert!(!ch.is_allowed("anyone"));
}
#[test]
fn test_serial_outbound_serialization() {
let outbound = SerialOutbound {
msg_type: "response".to_string(),
text: "Hi!".to_string(),
};
let json = serde_json::to_string(&outbound).unwrap();
assert!(json.contains("\"type\":\"response\""));
assert!(json.contains("\"text\":\"Hi!\""));
}
#[test]
fn test_serial_inbound_deserialization() {
let raw = r#"{"type":"message","text":"Hello","sender":"esp32-0"}"#;
let inbound: SerialInbound = serde_json::from_str(raw).unwrap();
assert_eq!(inbound.msg_type, "message");
assert_eq!(inbound.text, "Hello");
assert_eq!(inbound.sender, "esp32-0");
}
#[test]
fn test_serial_channel_running_flag_is_atomic() {
let ch = make_channel(SerialChannelConfig {
port: "/dev/ttyUSB0".to_string(),
..Default::default()
});
assert!(!ch.is_running());
ch.running.store(true, Ordering::SeqCst);
assert!(ch.is_running());
ch.running.store(false, Ordering::SeqCst);
assert!(!ch.is_running());
}
}
}
#[cfg(feature = "hardware")]
pub use inner::SerialChannel;