Fixed error handling

This commit is contained in:
Sebastian 2024-06-22 23:19:04 +02:00
parent 9bb7cc7a2c
commit ecb5399a42
3 changed files with 139 additions and 10 deletions

View file

@ -1,5 +1,9 @@
mod rotctl;
use anyhow::Result;
use fern::colors::{Color, ColoredLevelConfig};
use log::{debug, error, info, warn};
use std::io;
use tokio::{
self,
io::{AsyncBufReadExt, AsyncWriteExt, BufStream},
@ -10,8 +14,6 @@ use tokio::{
use rotctl::Command;
use std::io;
async fn process_socket(
socket: TcpStream,
cmd_tx: mpsc::Sender<Command>,
@ -27,7 +29,7 @@ async fn process_socket(
return;
}
println!("> {}", line);
debug!("Received: {}", line.strip_suffix("\n").unwrap());
match rotctl::parse_command(&line) {
Ok(cmd) => match cmd {
@ -52,7 +54,8 @@ async fn process_socket(
}
},
Err(msg) => {
stream.write_all(msg.as_bytes()).await.unwrap();
error!("Unable to parse input:\n{}", msg);
stream.write_all("RPRT 6\n".as_bytes()).await.unwrap();
stream.flush().await.unwrap();
}
}
@ -76,7 +79,7 @@ async fn control_rotor(mut rx_cmd: mpsc::Receiver<Command>, pos_tx: watch::Sende
Some(command) = rx_cmd.recv() => {
match command {
Command::SetPos(az, el) => {
println!("Received set pos {} {}", az, el);
info!("Received set pos {} {}", az, el);
target_az = az;
target_el = el;
}
@ -103,8 +106,39 @@ async fn control_rotor(mut rx_cmd: mpsc::Receiver<Command>, pos_tx: watch::Sende
}
}
fn setup_logger() -> Result<()> {
let colors = ColoredLevelConfig::new()
.info(Color::Green)
.error(Color::Red)
.warn(Color::Yellow)
.debug(Color::Blue);
fern::Dispatch::new()
// Perform allocation-free log formatting
.format(move |out, message, record| {
out.finish(format_args!(
"[{} {} {}] {}",
humantime::format_rfc3339_millis(std::time::SystemTime::now()),
colors.color(record.level()),
record.target(),
message
))
})
// Add blanket level filter -
.level(log::LevelFilter::Debug)
// - and per-module overrides
.chain(std::io::stdout())
.chain(fern::log_file("output.log")?)
// Apply globally
.apply()?;
Ok(())
}
#[tokio::main]
async fn main() -> io::Result<()> {
async fn main() -> Result<()> {
setup_logger()?;
let (cmd_tx, cmd_rx) = mpsc::channel::<Command>(16);
let (pos_tx, pos_rx) = watch::channel::<(f32, f32)>((0.0, 0.0));