flipdot_core/sign_bus.rs
1use std::error::Error;
2use std::fmt::{self, Debug, Formatter};
3
4use crate::Message;
5
6/// Abstraction over a bus containing devices that are able to send and receive [`Message`]s.
7///
8/// Typically `SerialSignBus` from [`flipdot`] or `VirtualSignBus` from [`flipdot-testing`] are sufficient,
9/// and you do not need to implement this yourself.
10///
11/// # Examples
12///
13/// Using `SignBus` as a trait object to allow choosing the type of bus at runtime:
14///
15/// ```
16/// use std::cell::RefCell;
17/// use std::rc::Rc;
18/// use flipdot::{Address, PageFlipStyle, Sign, SignBus, SignType};
19/// use flipdot::serial::SerialSignBus;
20/// use flipdot_testing::{VirtualSign, VirtualSignBus};
21///
22/// # fn use_serial() -> bool { false }
23/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
24/// #
25/// let bus: Rc<RefCell<dyn SignBus>> = if use_serial() {
26/// let port = serial::open("/dev/ttyUSB0")?;
27/// Rc::new(RefCell::new(SerialSignBus::try_new(port)?))
28/// } else {
29/// Rc::new(RefCell::new(VirtualSignBus::new(vec![VirtualSign::new(Address(3), PageFlipStyle::Manual)])))
30/// };
31///
32/// let sign = Sign::new(bus.clone(), Address(3), SignType::Max3000Side90x7);
33/// sign.configure()?;
34/// #
35/// # Ok(()) }
36/// ```
37///
38/// Implementing a custom bus:
39///
40/// ```
41/// use flipdot_core::{Message, SignBus, State};
42///
43/// struct ExampleSignBus {}
44///
45/// impl SignBus for ExampleSignBus {
46/// fn process_message<'a>(&mut self, message: Message)
47/// -> Result<Option<Message<'a>>, Box<dyn std::error::Error + Send + Sync>> {
48/// match message {
49/// Message::Hello(address) |
50/// Message::QueryState(address) =>
51/// Ok(Some(Message::ReportState(address, State::Unconfigured))),
52/// _ => Ok(None), // Implement rest of protocol here...
53/// }
54/// }
55/// }
56/// ```
57///
58/// [`flipdot`]: https://docs.rs/flipdot
59/// [`flipdot-testing`]: https://docs.rs/flipdot_testing
60pub trait SignBus {
61 /// Sends a message to the bus and returns an optional response.
62 ///
63 /// The caller is the "controller" (e.g. an ODK), and this method conceptually delivers the message
64 /// to a certain sign on the bus and returns an optional response from it.
65 ///
66 /// # Examples
67 ///
68 /// See the [trait-level documentation].
69 ///
70 /// [trait-level documentation]: #examples
71 fn process_message<'a>(&mut self, message: Message<'_>) -> Result<Option<Message<'a>>, Box<dyn Error + Send + Sync>>;
72}
73
74// Provide a Debug representation so types that contain trait objects can derive Debug.
75impl Debug for dyn SignBus {
76 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77 write!(f, "<SignBus trait>")
78 }
79}