69 lines
1.7 KiB
Rust
69 lines
1.7 KiB
Rust
use super::DeckMessage;
|
|
use tokio::io::AsyncReadExt;
|
|
use tokio_actors::{BoxFuture, Context, SendHandle};
|
|
use tokio_serial::SerialStream;
|
|
use tracing::{Instrument, Span};
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub(super) enum PortMessage {
|
|
Start,
|
|
}
|
|
|
|
pub(super) struct Port {
|
|
parent: SendHandle<DeckMessage>,
|
|
serial: SerialStream,
|
|
}
|
|
|
|
impl std::fmt::Debug for Port {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("Port").finish()
|
|
}
|
|
}
|
|
|
|
impl Port {
|
|
pub(super) fn new(parent: SendHandle<DeckMessage>, serial: SerialStream) -> Self {
|
|
Port { parent, serial }
|
|
}
|
|
|
|
#[tracing::instrument(skip(ctx))]
|
|
pub(super) fn on_start<'a>(&'a mut self, ctx: &'a mut Context<PortMessage>) -> BoxFuture<'a> {
|
|
Box::pin(
|
|
async move {
|
|
ctx.stop_on_error();
|
|
ctx.handle().send(PortMessage::Start).await?;
|
|
|
|
Ok(())
|
|
}
|
|
.instrument(Span::current()),
|
|
)
|
|
}
|
|
|
|
#[tracing::instrument(skip(ctx))]
|
|
pub(super) fn turn<'a>(
|
|
&'a mut self,
|
|
msg: PortMessage,
|
|
ctx: &'a mut Context<PortMessage>,
|
|
) -> BoxFuture<'a> {
|
|
Box::pin(
|
|
async move {
|
|
match msg {
|
|
PortMessage::Start => self.start(ctx).await,
|
|
}
|
|
}
|
|
.instrument(Span::current()),
|
|
)
|
|
}
|
|
|
|
#[tracing::instrument(skip(ctx))]
|
|
async fn start(&mut self, ctx: &'_ mut Context<PortMessage>) -> tokio_actors::Result<()> {
|
|
ctx.handle().send(PortMessage::Start).await?;
|
|
|
|
loop {
|
|
let mut key = [0u8; 1];
|
|
self.serial.read_exact(&mut key).await?;
|
|
|
|
self.parent.send(DeckMessage::Press(key[0])).await?;
|
|
}
|
|
}
|
|
}
|