use crate::clock::{Clock, SystemClock};
use crate::{Modem, WAIT};
use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
use std::collections::VecDeque;
use std::io::{self, Read, Write};
use std::sync::{mpsc, Arc, Condvar, Mutex, MutexGuard, Weak};
use std::time::{Duration, Instant};
type Responder = Box<dyn FnMut(&FakeDevice, &[u8], usize) -> Vec<u8> + Send>;
type Subscriber = Box<dyn FnMut(&[u8]) -> bool + Send>;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Faults {
pub silent: bool,
pub burst: Option<(Vec<u8>, usize)>,
pub chunk: Option<usize>,
pub delay: Duration,
}
impl Faults {
pub fn silent(mut self, on: bool) -> Self {
self.silent = on;
self
}
pub fn burst(mut self, bytes: &[u8], times: usize) -> Self {
self.burst = Some((bytes.to_vec(), times));
self
}
pub fn chunk(mut self, max: usize) -> Self {
self.chunk = Some(max.max(1));
self
}
pub fn delay(mut self, delay: Duration) -> Self {
self.delay = delay;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Lines {
pub cts: bool,
pub dsr: bool,
pub ring: bool,
pub carrier: bool,
}
impl Default for Lines {
fn default() -> Self {
Self {
cts: true,
dsr: true,
ring: false,
carrier: false,
}
}
}
impl Lines {
pub fn cts(mut self, on: bool) -> Self {
self.cts = on;
self
}
pub fn dsr(mut self, on: bool) -> Self {
self.dsr = on;
self
}
pub fn ring(mut self, on: bool) -> Self {
self.ring = on;
self
}
pub fn carrier(mut self, on: bool) -> Self {
self.carrier = on;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Call {
BaudRate(u32),
DataBits(DataBits),
FlowControl(FlowControl),
Parity(Parity),
StopBits(StopBits),
Rts(bool),
Dtr(bool),
Break(bool),
ClearInput,
ClearOutput,
}
#[derive(Clone)]
struct Settings {
baud_rate: u32,
data_bits: DataBits,
flow_control: FlowControl,
parity: Parity,
stop_bits: StopBits,
}
struct State {
rx: VecDeque<u8>,
written: Vec<u8>,
write_timeouts: Vec<Duration>,
calls: Vec<Call>,
settings: Settings,
lines: Lines,
read_error: Option<io::ErrorKind>,
read_errors_left: (usize, io::ErrorKind),
write_error: Option<io::ErrorKind>,
eof_left: usize,
eof_reads: usize,
stall_writes: bool,
hold_writes: bool,
hold_reads: bool,
held: usize,
reading: Vec<usize>,
driver_pending: Option<u32>,
out_pending: u32,
ports: usize,
handles: usize,
responder: Option<Responder>,
unanswered: VecDeque<Vec<u8>>,
answering: bool,
faults: Faults,
clock: Option<Arc<dyn Clock>>,
system_clock: Option<Arc<dyn Clock>>,
subscribers: Vec<Subscriber>,
late: VecDeque<Late>,
late_seq: u64,
}
struct Late {
id: u64,
bytes: Vec<u8>,
due: bool,
}
impl State {
fn flush_late(&mut self) {
while self.late.front().is_some_and(|l| l.due) {
let late = self.late.pop_front().expect("front");
self.rx.extend(late.bytes);
}
}
fn delay_clock(&mut self) -> Arc<dyn Clock> {
if let Some(clock) = &self.clock {
return clock.clone();
}
self.system_clock
.get_or_insert_with(|| Arc::new(SystemClock::new()))
.clone()
}
}
#[derive(Clone)]
struct Shared(Arc<(Mutex<State>, Condvar)>);
impl Shared {
fn lock(&self) -> MutexGuard<'_, State> {
self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
}
fn change<T>(&self, f: impl FnOnce(&mut State) -> T) -> T {
let out = f(&mut self.lock());
self.0 .1.notify_all();
out
}
fn notify(&self) {
self.0 .1.notify_all();
}
fn send_after(&self, after: Duration, bytes: Vec<u8>) {
if after.is_zero() {
self.change(|s| s.rx.extend(bytes));
return;
}
let clock = self.lock().delay_clock();
let shared: Weak<(Mutex<State>, Condvar)> = Arc::downgrade(&self.0);
clock.at(
clock.now() + after,
Box::new(move || {
if let Some(shared) = shared.upgrade() {
Shared(shared).change(|s| s.rx.extend(bytes));
}
}),
);
}
fn deliver(&self, mut reply: Vec<u8>) {
let mut state = self.lock();
if state.faults.silent || reply.is_empty() {
return;
}
if let Some((bytes, times)) = &state.faults.burst {
for _ in 0..*times {
reply.extend(bytes);
}
}
let delay = state.faults.delay;
if delay.is_zero() && state.late.is_empty() {
state.rx.extend(reply);
drop(state);
self.notify();
return;
}
state.late_seq += 1;
let id = state.late_seq;
state.late.push_back(Late {
id,
bytes: reply,
due: delay.is_zero(),
});
if delay.is_zero() {
return;
}
let clock = state.delay_clock();
drop(state);
let shared: Weak<(Mutex<State>, Condvar)> = Arc::downgrade(&self.0);
clock.at(
clock.now() + delay,
Box::new(move || {
if let Some(shared) = shared.upgrade() {
Shared(shared).change(|s| {
if let Some(late) = s.late.iter_mut().find(|l| l.id == id) {
late.due = true;
}
s.flush_late();
});
}
}),
);
}
fn pass<'a>(
&'a self,
mut state: MutexGuard<'a, State>,
gate: impl Fn(&State) -> bool,
) -> MutexGuard<'a, State> {
if gate(&state) {
state.held += 1;
self.notify();
while gate(&state) {
state = self.0 .1.wait(state).unwrap_or_else(|e| e.into_inner());
}
state.held -= 1;
self.notify();
}
state
}
fn wait(&self, what: &str, done: impl Fn(&State) -> bool) {
let deadline = Instant::now() + WAIT;
let mut state = self.lock();
while !done(&state) {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
drop(state);
panic!("never: {what}");
}
let woken = self.0 .1.wait_timeout(state, left);
state = woken.unwrap_or_else(|e| e.into_inner()).0;
}
}
fn answer(&self) {
struct Out<'a> {
shared: &'a Shared,
responder: Option<Responder>,
done: bool,
}
impl Drop for Out<'_> {
fn drop(&mut self) {
if self.done {
return;
}
self.shared.change(|s| {
if s.responder.is_none() {
s.responder = self.responder.take();
}
s.answering = false;
});
}
}
{
let mut state = self.lock();
if state.answering || state.responder.is_none() {
return;
}
state.answering = true;
}
let device = FakeDevice::handle(self.clone());
let mut out = Out {
shared: self,
responder: None,
done: false,
};
while !out.done {
let mut state = self.lock();
let mut replaced = None;
if let Some(new) = state.responder.take() {
replaced = out.responder.replace(new);
}
let next = state.unanswered.pop_front();
let unread = state.rx.len();
if next.is_none() {
state.responder = out.responder.take();
state.answering = false;
out.done = true;
}
drop(state);
drop(replaced);
if let (Some(bytes), Some(responder)) = (next, &mut out.responder) {
let reply = responder(&device, &bytes, unread);
self.deliver(reply);
}
}
}
}
pub struct FakeDevice(Shared);
impl Clone for FakeDevice {
fn clone(&self) -> Self {
Self::handle(self.0.clone())
}
}
impl Drop for FakeDevice {
fn drop(&mut self) {
self.0.change(|s| {
s.handles -= 1;
if s.handles == 0 {
s.hold_reads = false;
s.hold_writes = false;
}
});
}
}
impl Default for FakeDevice {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for FakeDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FakeDevice").finish_non_exhaustive()
}
}
impl FakeDevice {
pub fn new() -> Self {
let state = State {
rx: VecDeque::new(),
written: Vec::new(),
write_timeouts: Vec::new(),
calls: Vec::new(),
settings: Settings {
baud_rate: 115_200,
data_bits: DataBits::Eight,
flow_control: FlowControl::None,
parity: Parity::None,
stop_bits: StopBits::One,
},
lines: Lines::default(),
read_error: None,
read_errors_left: (0, io::ErrorKind::Other),
write_error: None,
eof_left: 0,
eof_reads: 0,
stall_writes: false,
hold_writes: false,
hold_reads: false,
held: 0,
reading: Vec::new(),
driver_pending: None,
out_pending: 0,
ports: 0,
handles: 0,
responder: None,
unanswered: VecDeque::new(),
answering: false,
faults: Faults::default(),
clock: None,
system_clock: None,
subscribers: Vec::new(),
late: VecDeque::new(),
late_seq: 0,
};
Self::handle(Shared(Arc::new((Mutex::new(state), Condvar::new()))))
}
fn handle(shared: Shared) -> Self {
shared.change(|s| s.handles += 1);
Self(shared)
}
pub fn with_modem(modem: Modem) -> Self {
let device = Self::new();
device.modem(modem);
device
}
pub fn port(&self) -> FakePort {
self.open(true)
}
pub fn unclonable_port(&self) -> FakePort {
self.open(false)
}
fn open(&self, clonable: bool) -> FakePort {
self.0.change(|s| s.ports += 1);
FakePort {
shared: self.0.clone(),
timeout: Duration::from_secs(1),
clonable,
}
}
pub fn send(&self, bytes: &[u8]) {
self.0.change(|s| s.rx.extend(bytes));
}
pub fn unread(&self) -> usize {
self.0.lock().rx.len()
}
pub fn wait_read(&self) {
self.0.wait("the host read every byte", |s| s.rx.is_empty());
}
pub fn wait_handled(&self) {
self.0.wait("the host handled every byte", |s| {
s.rx.is_empty() && !s.reading.is_empty()
});
}
pub fn wait_asked(&self, size: usize) {
self.0
.wait(&format!("the host asks for {size} bytes"), |s| {
s.reading.contains(&size)
});
}
pub fn written(&self) -> Vec<u8> {
self.0.lock().written.clone()
}
pub fn wait_written(&self, what: &str, done: impl Fn(&[u8]) -> bool) -> Vec<u8> {
self.0.wait(what, |s| done(&s.written));
self.written()
}
pub fn write_timeouts(&self) -> Vec<Duration> {
self.0.lock().write_timeouts.clone()
}
pub fn calls(&self) -> Vec<Call> {
self.0.lock().calls.clone()
}
pub fn respond(&self, mut reply: impl FnMut(&FakeDevice, &[u8]) -> Vec<u8> + Send + 'static) {
self.set_responder(Box::new(move |device, bytes, _| reply(device, bytes)));
}
pub fn modem(&self, mut modem: Modem) {
self.set_responder(Box::new(move |_, bytes, unread| {
modem.feed_with_unread(bytes, unread)
}));
}
fn set_responder(&self, responder: Responder) {
let _old = self.0.change(|s| s.responder.replace(responder));
}
pub fn clock(&self, clock: Arc<dyn Clock>) {
self.0.change(|s| {
s.clock = Some(clock);
s.late.iter_mut().for_each(|l| l.due = true);
s.flush_late();
});
}
pub fn faults(&self, faults: Faults) {
self.0.change(|s| s.faults = faults);
}
pub fn send_after(&self, after: Duration, bytes: &[u8]) {
self.0.send_after(after, bytes.to_vec());
}
pub fn subscribe_writes(&self) -> mpsc::Receiver<Vec<u8>> {
let (tx, rx) = mpsc::channel();
self.0.change(|s| {
s.subscribers
.push(Box::new(move |bytes| tx.send(bytes.to_vec()).is_ok()))
});
rx
}
#[cfg(feature = "tokio")]
pub fn subscribe_writes_async(&self) -> tokio::sync::mpsc::UnboundedReceiver<Vec<u8>> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
self.0.change(|s| {
s.subscribers
.push(Box::new(move |bytes| tx.send(bytes.to_vec()).is_ok()))
});
rx
}
pub fn fail_reads(&self, kind: io::ErrorKind) {
self.0.change(|s| s.read_error = Some(kind));
}
pub fn fail_reads_times(&self, n: usize, kind: io::ErrorKind) {
self.0.change(|s| s.read_errors_left = (n, kind));
}
pub fn fail_writes(&self, kind: io::ErrorKind) {
self.0.change(|s| s.write_error = Some(kind));
}
pub fn stall_writes(&self, on: bool) {
self.0.change(|s| s.stall_writes = on);
}
pub fn eof(&self) {
self.0.change(|s| s.eof_left = usize::MAX);
}
pub fn recover(&self) {
self.0.change(|s| {
s.read_error = None;
s.read_errors_left.0 = 0;
s.write_error = None;
s.stall_writes = false;
s.eof_left = 0;
});
}
pub fn eof_times(&self, n: usize) {
self.0.change(|s| s.eof_left = n);
}
pub fn eof_reads(&self) -> usize {
self.0.lock().eof_reads
}
pub fn hold_writes(&self, on: bool) {
self.0.change(|s| s.hold_writes = on);
}
pub fn hold_reads(&self, on: bool) {
self.0.change(|s| s.hold_reads = on);
}
pub fn held(&self) -> usize {
self.0.lock().held
}
pub fn wait_held(&self, n: usize) {
self.0
.wait("the host is blocked in the device", |s| s.held == n);
}
pub fn set_lines(&self, lines: Lines) {
self.0.change(|s| s.lines = lines);
}
pub fn set_driver_pending(&self, n: Option<u32>) {
self.0.change(|s| s.driver_pending = n);
}
pub fn set_out_pending(&self, n: u32) {
self.0.change(|s| s.out_pending = n);
}
pub fn open_ports(&self) -> usize {
self.0.lock().ports
}
pub fn wait_closed(&self) {
self.0.wait("the host closed the port", |s| s.ports == 0);
}
}
enum Deadline {
Real(Instant),
Clock {
clock: Arc<dyn Clock>,
at: Duration,
bound: Instant,
armed: bool,
},
}
impl Deadline {
fn arm(&mut self) -> Option<(Arc<dyn Clock>, Duration)> {
match self {
Self::Clock {
clock, at, armed, ..
} if !*armed => {
*armed = true;
Some((clock.clone(), *at))
}
_ => None,
}
}
fn left(&self) -> io::Result<Duration> {
match self {
Self::Real(end) => Ok(end.saturating_duration_since(Instant::now())),
Self::Clock {
clock, at, bound, ..
} => {
if clock.now() >= *at {
return Ok(Duration::ZERO);
}
match bound.saturating_duration_since(Instant::now()) {
left if left.is_zero() => Err(io::Error::other(
"fake device: the clock never reached the port timeout",
)),
left => Ok(left),
}
}
}
}
}
pub struct FakePort {
shared: Shared,
timeout: Duration,
clonable: bool,
}
impl std::fmt::Debug for FakePort {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FakePort")
.field("timeout", &self.timeout)
.finish_non_exhaustive()
}
}
impl FakePort {
fn set(&self, call: Call, f: impl FnOnce(&mut Settings)) -> serialport::Result<()> {
self.shared.change(|s| {
f(&mut s.settings);
s.calls.push(call);
});
Ok(())
}
fn settings(&self) -> Settings {
self.shared.lock().settings.clone()
}
fn read_locked<'a>(
&'a self,
mut state: MutexGuard<'a, State>,
buf: &mut [u8],
) -> (MutexGuard<'a, State>, io::Result<usize>) {
let mut deadline = self.deadline(&state);
let fails = |kind| Err(io::Error::new(kind, "fake device: read error"));
loop {
if state.hold_reads {
state = self.shared.pass(state, |s| s.hold_reads);
deadline = self.deadline(&state);
}
if let Some(kind) = state.read_error {
return (state, fails(kind));
}
if let (left @ 1.., kind) = state.read_errors_left {
state.read_errors_left.0 = left - 1;
return (state, fails(kind));
}
if state.eof_left > 0 {
if state.eof_left != usize::MAX {
state.eof_left -= 1;
}
state.eof_reads += 1;
return (state, Ok(0));
}
if !state.rx.is_empty() {
let max = state.faults.chunk.unwrap_or(usize::MAX).max(1);
let n = buf.len().min(state.rx.len()).min(max);
for (slot, byte) in buf.iter_mut().zip(state.rx.drain(..n)) {
*slot = byte;
}
return (state, Ok(n));
}
let left = match deadline.left() {
Ok(left) => left,
Err(e) => return (state, Err(e)),
};
if left.is_zero() {
let e = io::Error::new(io::ErrorKind::TimedOut, "fake device: no data");
return (state, Err(e));
}
if let Some((clock, at)) = deadline.arm() {
drop(state);
let shared = Arc::downgrade(&self.shared.0);
clock.at(
at,
Box::new(move || {
if let Some(shared) = shared.upgrade() {
drop(shared.0.lock());
shared.1.notify_all();
}
}),
);
state = self.shared.lock();
continue;
}
let woken = self.shared.0 .1.wait_timeout(state, left);
state = woken.unwrap_or_else(|e| e.into_inner()).0;
}
}
fn deadline(&self, state: &State) -> Deadline {
let Some(clock) = state.clock.clone() else {
return Deadline::Real(Instant::now() + self.timeout);
};
let at = clock.now() + self.timeout;
Deadline::Clock {
clock,
at,
bound: Instant::now() + WAIT,
armed: false,
}
}
}
impl Drop for FakePort {
fn drop(&mut self) {
self.shared.change(|s| s.ports -= 1);
}
}
impl Read for FakePort {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let mut state = self.shared.lock();
state.reading.push(buf.len());
self.shared.notify();
let (mut state, result) = self.read_locked(state, buf);
let asked = state.reading.iter().position(|n| *n == buf.len());
asked.map(|i| state.reading.swap_remove(i));
drop(state);
self.shared.notify();
result
}
}
impl Write for FakePort {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut state = self.shared.pass(self.shared.lock(), |s| s.hold_writes);
if let Some(kind) = state.write_error {
return Err(io::Error::new(kind, "fake device: write error"));
}
state.write_timeouts.push(self.timeout);
if state.stall_writes {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"fake device: write stalled",
));
}
state.written.extend(buf);
state.subscribers.retain_mut(|send| send(buf));
if state.responder.is_some() || state.answering {
state.unanswered.push_back(buf.to_vec());
}
drop(state);
self.shared.notify();
self.shared.answer();
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl SerialPort for FakePort {
fn name(&self) -> Option<String> {
Some("fake".into())
}
fn baud_rate(&self) -> serialport::Result<u32> {
Ok(self.settings().baud_rate)
}
fn data_bits(&self) -> serialport::Result<DataBits> {
Ok(self.settings().data_bits)
}
fn flow_control(&self) -> serialport::Result<FlowControl> {
Ok(self.settings().flow_control)
}
fn parity(&self) -> serialport::Result<Parity> {
Ok(self.settings().parity)
}
fn stop_bits(&self) -> serialport::Result<StopBits> {
Ok(self.settings().stop_bits)
}
fn timeout(&self) -> Duration {
self.timeout
}
fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
self.set(Call::BaudRate(v), |s| s.baud_rate = v)
}
fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
self.set(Call::DataBits(v), |s| s.data_bits = v)
}
fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
self.set(Call::FlowControl(v), |s| s.flow_control = v)
}
fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
self.set(Call::Parity(v), |s| s.parity = v)
}
fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
self.set(Call::StopBits(v), |s| s.stop_bits = v)
}
fn set_timeout(&mut self, timeout: Duration) -> serialport::Result<()> {
self.timeout = timeout;
Ok(())
}
fn write_request_to_send(&mut self, v: bool) -> serialport::Result<()> {
self.set(Call::Rts(v), |_| {})
}
fn write_data_terminal_ready(&mut self, v: bool) -> serialport::Result<()> {
self.set(Call::Dtr(v), |_| {})
}
fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
Ok(self.shared.lock().lines.cts)
}
fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
Ok(self.shared.lock().lines.dsr)
}
fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
Ok(self.shared.lock().lines.ring)
}
fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
Ok(self.shared.lock().lines.carrier)
}
fn bytes_to_read(&self) -> serialport::Result<u32> {
let state = self.shared.lock();
Ok(state.driver_pending.unwrap_or(state.rx.len() as u32))
}
fn bytes_to_write(&self) -> serialport::Result<u32> {
Ok(self.shared.lock().out_pending)
}
fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
self.shared.change(|s| {
if matches!(which, ClearBuffer::Input | ClearBuffer::All) {
s.rx.clear();
s.calls.push(Call::ClearInput);
}
if matches!(which, ClearBuffer::Output | ClearBuffer::All) {
s.calls.push(Call::ClearOutput);
}
});
Ok(())
}
fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
if !self.clonable {
return Err(serialport::Error::new(
serialport::ErrorKind::Unknown,
"fake device: this port has no clones",
));
}
self.shared.change(|s| s.ports += 1);
Ok(Box::new(FakePort {
shared: self.shared.clone(),
timeout: self.timeout,
clonable: true,
}))
}
fn set_break(&self) -> serialport::Result<()> {
self.set(Call::Break(true), |_| {})
}
fn clear_break(&self) -> serialport::Result<()> {
self.set(Call::Break(false), |_| {})
}
}