increase command flexibility

This commit is contained in:
2025-11-30 08:02:39 -08:00
parent eefc3293b4
commit d53d78434c
17 changed files with 422 additions and 220 deletions

View File

@@ -4,11 +4,11 @@ version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.100"
fern = { version = "0.7.1", features = ["colored"] }
log = { version = "0.4.28", features = ["max_level_trace", "release_max_level_debug"] }
chrono = { version = "0.4.42", features = ["serde"] }
ctrlc = "3.5.0"
serde = { version = "1.0.228", features = ["derive"], default-features = false }
ciborium = { version = "0.2.2" }
thiserror = "2.0.17"
anyhow = { workspace = true }
fern = { workspace = true }
log = { workspace = true }
chrono = { workspace = true }
ctrlc = { workspace = true }
serde = { workspace = true }
postcard = { workspace = true }
thiserror = { workspace = true }

View File

@@ -1,6 +1,78 @@
use chrono::serde::ts_nanoseconds;
use chrono::{DateTime, TimeDelta, Utc};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
use std::time::Instant;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Command {
Shutdown,
pub struct SetPin {
pub pin: u8,
pub value: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValidPriorityCommand<T>
where
T: Clone + Debug,
{
pub inner: T,
#[serde(with = "ts_nanoseconds")]
pub valid_until: DateTime<Utc>,
pub priority: u8,
}
impl<T> ValidPriorityCommand<T>
where
T: Clone + Debug,
{
/// Get the valid until time as an Instant
///
/// # Panics
/// While this theoretically could panic, there are checks to prevent this.
pub fn get_valid_until_instant(&self) -> Instant {
let delta = self.valid_until.signed_duration_since(Utc::now());
let now = Instant::now();
if delta >= TimeDelta::zero() {
// Unwrap is safe because we checked that it is not negative
now + delta.to_std().unwrap()
} else {
// Unwrap is safe because we converted the negative to a positive
now.checked_sub((-delta).to_std().unwrap()).unwrap_or(now)
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CommandHeader<'a> {
pub name: &'a str,
pub data: &'a [u8],
}
pub trait Command: Serialize + DeserializeOwned {}
impl Command for () {}
impl Command for SetPin {}
impl<T: Clone + Debug + Command + Serialize + DeserializeOwned> Command
for ValidPriorityCommand<T>
{
}
impl<T: Clone + Debug + Command + Serialize + DeserializeOwned> Deref for ValidPriorityCommand<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Clone + Debug + Command + Serialize + DeserializeOwned> DerefMut
for ValidPriorityCommand<T>
{
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}

View File

@@ -1,7 +1,4 @@
#![warn(
clippy::all,
clippy::pedantic,
)]
#![warn(clippy::all, clippy::pedantic)]
use log::info;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

View File

@@ -6,7 +6,7 @@ use std::str::FromStr;
use std::{env, thread};
/// Set up the logger with a given package name
///
///
/// # Errors
/// If an error occurred while trying to set up the logger
pub fn setup_logger(package_name: &'static str) -> Result<()> {

View File

@@ -1,85 +1,92 @@
use crate::udp::UdpSendCborError::LengthMismatch;
use crate::command::{Command, CommandHeader};
use crate::udp::UdpSendPostcardError::LengthMismatch;
use log::error;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{Cursor, ErrorKind};
use serde::{Deserialize, Serialize};
use std::io::ErrorKind;
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum UdpRecvCborError {
pub enum UdpRecvPostcardError {
#[error("IO Error")]
Io(#[from] std::io::Error),
#[error("Deserialization Error")]
Deserialization(#[from] ciborium::de::Error<std::io::Error>),
Deserialization(#[from] postcard::Error),
#[error("No Data")]
NoData,
}
#[derive(Error, Debug)]
pub enum UdpSendCborError {
pub enum UdpSendPostcardError {
#[error("IO Error")]
Io(#[from] std::io::Error),
#[error("Serialization Error")]
Serialization(#[from] ciborium::ser::Error<std::io::Error>),
Serialization(#[from] postcard::Error),
#[error("Length Mismatch")]
LengthMismatch { expected: usize, actual: usize },
}
pub trait UdpSocketExt {
/// Receive a CBOR encoded message from this UDP Socket
///
/// # Errors
/// An error that could have occurred while trying to receive this message.
/// If no data was received a `UdpRecvCborError::NoData` error would be returned.
fn recv_cbor<T: DeserializeOwned, const N: usize>(
fn recv_postcard<'de, T: Deserialize<'de>>(
&self,
buffer: &mut Cursor<[u8; N]>,
) -> Result<(T, SocketAddr), UdpRecvCborError>;
buffer: &'de mut [u8],
) -> Result<(T, SocketAddr), UdpRecvPostcardError>;
/// Send a CBOR encoded message to an address using this socket
///
/// # Errors
/// An error that could have occurred while trying to send this message
fn send_cbor<T: Serialize + ?Sized, A: ToSocketAddrs, const N: usize>(
fn send_postcard<T: Serialize + ?Sized, A: ToSocketAddrs>(
&self,
data: &T,
buffer: &mut Cursor<[u8; N]>,
buffer: &mut [u8],
addr: A,
) -> Result<(), UdpSendCborError>;
) -> Result<(), UdpSendPostcardError>;
/// Send a command message to an address using this socket
///
/// # Errors
/// An error that could have occurred while trying to send this message
fn send_command<T: Command, A: ToSocketAddrs>(
&self,
name: &str,
data: &T,
addr: A,
) -> Result<(), UdpSendPostcardError>;
}
impl UdpSocketExt for UdpSocket {
fn recv_cbor<T: DeserializeOwned, const N: usize>(
fn recv_postcard<'de, T: Deserialize<'de>>(
&self,
buffer: &mut Cursor<[u8; N]>,
) -> Result<(T, SocketAddr), UdpRecvCborError> {
buffer.set_position(0);
match self.recv_from(buffer.get_mut()) {
Ok((size, addr)) => match ciborium::from_reader::<T, _>(&buffer.get_ref()[..size]) {
buffer: &'de mut [u8],
) -> Result<(T, SocketAddr), UdpRecvPostcardError> {
match self.recv_from(buffer) {
Ok((size, addr)) => match postcard::from_bytes::<T>(&buffer[..size]) {
Ok(res) => Ok((res, addr)),
Err(err) => Err(err.into()),
},
Err(err) => match err.kind() {
ErrorKind::WouldBlock | ErrorKind::TimedOut => Err(UdpRecvCborError::NoData),
ErrorKind::WouldBlock | ErrorKind::TimedOut => Err(UdpRecvPostcardError::NoData),
_ => Err(err.into()),
},
}
}
fn send_cbor<T: Serialize + ?Sized, A: ToSocketAddrs, const N: usize>(
fn send_postcard<T: Serialize + ?Sized, A: ToSocketAddrs>(
&self,
data: &T,
mut buffer: &mut Cursor<[u8; N]>,
buffer: &mut [u8],
addr: A,
) -> Result<(), UdpSendCborError> {
buffer.set_position(0);
match ciborium::into_writer(data, &mut buffer) {
Ok(()) => {
let size_encoded = usize::try_from(buffer.position())
.expect("Values greater than u32 are not expected anyway");
match self.send_to(&buffer.get_ref()[..size_encoded], addr) {
) -> Result<(), UdpSendPostcardError> {
match postcard::to_slice(data, buffer) {
Ok(result) => {
let size_encoded = result.len();
match self.send_to(result, addr) {
Ok(size_sent) => {
if size_encoded != size_sent {
return Err(LengthMismatch {
@@ -91,8 +98,35 @@ impl UdpSocketExt for UdpSocket {
}
Err(e) => Err(e.into()),
}
},
}
Err(e) => Err(e.into()),
}
}
fn send_command<T: Command, A: ToSocketAddrs>(
&self,
name: &str,
data: &T,
addr: A,
) -> Result<(), UdpSendPostcardError> {
let mut inner_buffer = [0u8; 512];
let inner_buffer = postcard::to_slice(data, &mut inner_buffer)?;
let mut buffer = [0u8; 512];
let buffer = postcard::to_slice(
&CommandHeader {
name,
data: inner_buffer,
},
&mut buffer,
)?;
let size_encoded = buffer.len();
let size_sent = self.send_to(buffer, addr)?;
if size_encoded != size_sent {
return Err(LengthMismatch {
expected: size_encoded,
actual: size_sent,
});
}
Ok(())
}
}