Add some anyhow error handling

This commit is contained in:
zaubentrucker 2025-02-21 23:53:20 +01:00
parent 8fbdddda38
commit 25e1fc4333
5 changed files with 49 additions and 32 deletions

View file

@ -6,6 +6,7 @@ edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = { version = "1.0.96" }
euclid = "0.22.7"
futures = "0.3.24"
gilrs = "0.10.1"

View file

@ -49,10 +49,10 @@ impl Gamepad {
///
/// The tasks are terminated on drop.
pub fn new() -> Result<Self, gilrs::Error> {
let gilrs = Gilrs::new().unwrap();
let gilrs = Gilrs::new()?;
for (_id, gamepad) in gilrs.gamepads() {
println!(
"Found gamepad {}: {:?}",
eprintln!(
"INFO: Found gamepad {}: {:?}",
gamepad.name(),
gamepad.power_info()
);

View file

@ -1,7 +1,7 @@
use crate::gamepad::Gamepad;
use crate::printer::Printer;
use euclid::{vec3, Vector3D};
use futures::never::Never;
use anyhow::{Context, Result, anyhow};
use euclid::{Vector3D, vec3};
use std::time::Duration;
/// Time that a single movement command should take
@ -30,31 +30,39 @@ pub struct PrinterUnits;
pub type PrinterVec = Vector3D<f64, PrinterUnits>;
/// Jog the gantry by pumping loads of gcode into the printer board
pub fn jog(gamepad: &mut Gamepad, mut printer: Printer) -> Never {
printer.use_absolute_movements().unwrap();
println!("Using absolute movements");
pub fn jog(gamepad: &mut Gamepad, mut printer: Printer) -> Result<()> {
printer
.use_absolute_movements()
.with_context(|| anyhow!("Setting printer to absolute movement mode"))?;
eprintln!("INFO: Using absolute movements");
loop {
let events = gamepad.get_pending();
let (setpoint_x, setpoint_y, setpoint_z) = gamepad.speed_set_point(&events);
let (set_point_x, set_point_y, set_point_z) = gamepad.speed_set_point(&events);
let distance: PrinterVec = vec3(
FULL_SCALE_SPEED_XY * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (setpoint_x as f64),
FULL_SCALE_SPEED_XY * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (setpoint_y as f64),
FULL_SCALE_SPEED_Z * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (setpoint_z as f64),
FULL_SCALE_SPEED_XY * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (set_point_x as f64),
FULL_SCALE_SPEED_XY * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (set_point_y as f64),
FULL_SCALE_SPEED_Z * (TIME_PER_MOVEMENT.as_secs_f64() / 60.0) * (set_point_z as f64),
);
if distance.length() == 0.0 {
std::thread::sleep(TIME_PER_MOVEMENT);
continue;
}
let velocity = distance.length() / (TIME_PER_MOVEMENT.as_secs_f64() / 60.0);
let old_postion = printer.state.lock().unwrap().position;
let old_postion = printer
.state
.lock()
.expect("Printer state mutex is dead!")
.position;
printer
.move_absolute(
old_postion.x + distance.x,
old_postion.y + distance.y,
old_postion.z + distance.z,
velocity.into(),
).expect("Failed to send movement command!");
)
.with_context(|| anyhow!("Sending movement command!"))?;
println!(
"New position {pos:?}",

View file

@ -1,19 +1,17 @@
#![warn(rust_2018_idioms)]
use anyhow::{Context, Result, anyhow};
use futures::never::Never;
use red::gamepad::Gamepad;
use red::jogger;
use red::printer::Printer;
use std::path::{Path};
use std::path::Path;
fn main() -> Never {
fn main() -> Result<()> {
jog()
}
fn jog() -> Never {
let mut gamepad = Gamepad::new().expect("Failed to open gamepad");
println!("Entering App");
fn find_printer_port() -> Result<String> {
let dev_dir = std::fs::read_dir(Path::new("/dev")).expect("Failed to open device directory");
let mut usb_tty_ports: Vec<String> = dev_dir
.filter_map(|entry| {
@ -25,18 +23,22 @@ fn jog() -> Never {
.collect();
if usb_tty_ports.len() > 1 {
eprintln!("Found more than one ttyUSB port! Picking the first one...")
eprintln!("WARNING: Found more than one ttyUSB port! Picking the first one...")
}
let port_path = usb_tty_ports.pop().expect("No USB serial port found!");
eprintln!("Found serial port: {:?}", &port_path);
usb_tty_ports
.pop()
.ok_or(anyhow!("No USB serial port found!"))
}
let printer = Printer::connect_to_path(
&port_path
)
.unwrap();
fn jog() -> Result<()> {
let mut gamepad = Gamepad::new().expect("Failed to open gamepad");
jogger::jog(&mut gamepad, printer)
let printer_tty_path = find_printer_port()?;
let printer = Printer::connect_to_path(&printer_tty_path)
.with_context(|| anyhow!("Initializing printer connection"))?;
jogger::jog(&mut gamepad, printer).with_context(|| anyhow!("Running jog mode"))
}
fn print_gamepad_events() -> Never {
@ -46,4 +48,4 @@ fn print_gamepad_events() -> Never {
println!("speed setpoint: {:?}", gamepad.speed_set_point(&events));
std::thread::sleep(std::time::Duration::from_millis(500));
}
}
}

View file

@ -1,7 +1,7 @@
pub mod gcode;
use lazy_static::lazy_static;
use core::panic;
use std::panic;
pub use gcode::{GcodeCommand};
use regex::Regex;
use serialport::SerialPort;
@ -18,7 +18,6 @@ use std::sync::Arc;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use std::{io, str};
use crate::printer::gcode::{G91Command, M114Command};
use self::gcode::{G0Command, G28Command, G90Command, GcodeReplyError};
@ -44,7 +43,7 @@ pub enum Port {
#[derive(Debug)]
pub enum PrinterError {
IO(std::io::Error),
IO(io::Error),
PrinterTaskDown,
OutputChannelDropped,
GcodeReply(GcodeReplyError),
@ -55,6 +54,13 @@ pub enum PrinterError {
InitializationError(String),
}
impl std::fmt::Display for PrinterError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_fmt(format_args!("{:?}", self))
}
}
impl std::error::Error for PrinterError {}
#[derive(Debug, Clone, Copy)]
pub struct PrinterPosition {
pub x: f64,