Implement supported commands

This commit is contained in:
Aode (lion) 2021-10-02 14:46:34 -05:00
commit e9910a4b6e
3 changed files with 97 additions and 0 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
/target
Cargo.lock

15
Cargo.toml Normal file
View file

@ -0,0 +1,15 @@
[package]
name = "streamdeck-commands"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
thiserror = "1.0.29"
tokio = { version = "1.12.0", default-features = false, features = ["io-util"] }
tokio-serial = "5.4.1"
tracing-error = "0.1.2"
[dev-dependencies]
tokio = { version = "1.12.0", features = ["rt", "macros"] }

80
src/lib.rs Normal file
View file

@ -0,0 +1,80 @@
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio_serial::SerialStream;
use tracing_error::SpanTrace;
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
context: SpanTrace,
}
#[derive(Debug, thiserror::Error)]
pub enum ErrorKind {
#[error(transparent)]
Serial(#[from] tokio_serial::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
}
pub async fn identity(port: &mut SerialStream) -> Result<Vec<u8>, Error> {
get_prop(port, b"ident").await
}
pub async fn author(port: &mut SerialStream) -> Result<Vec<u8>, Error> {
get_prop(port, b"author").await
}
pub async fn repo(port: &mut SerialStream) -> Result<Vec<u8>, Error> {
get_prop(port, b"repo").await
}
pub async fn reset(port: &mut SerialStream) -> Result<(), Error> {
send_command(port, b"reset").await
}
async fn send_command<Port>(port: &mut Port, command: &[u8]) -> Result<(), Error>
where
Port: AsyncWrite + Unpin,
{
port.write_all(command).await?;
port.flush().await?;
Ok(())
}
async fn get_prop<Port>(port: &mut Port, prop: &[u8]) -> Result<Vec<u8>, Error>
where
Port: AsyncRead + AsyncWrite + Unpin,
{
send_command::<Port>(port, prop).await?;
let mut len_buf = [0u8; 1];
port.read_exact(&mut len_buf).await?;
let input_len = len_buf[0];
let mut input = vec![0u8; input_len as usize];
port.read_exact(&mut input).await?;
Ok(input)
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.kind)?;
std::fmt::Display::fmt(&self.context, f)
}
}
impl<T> From<T> for Error
where
ErrorKind: From<T>,
{
fn from(error: T) -> Self {
Error {
kind: error.into(),
context: SpanTrace::capture(),
}
}
}