More refactoring and generalizing

This commit is contained in:
Dandaedre 2024-12-09 00:09:32 +01:00
parent 9a3fdfc149
commit 1d8ddbe279
11 changed files with 91 additions and 58 deletions

1
.gitignore vendored
View File

@ -24,3 +24,4 @@ Cargo.lock
tarpaulin-report.html
test/
.ignore
*.json

View File

@ -15,10 +15,13 @@ lazy_static = "1.4.0"
ratatui = "0.29.0"
serde = { version = "1.0.215", features = ["derive", "alloc"] }
thiserror = "2.0.4"
tracing = "0.1.41"
tokio = "1.42.0"
typetag = "0.2.18"
serde_json = { version = "1.0.133", features = ["alloc", "preserve_order"] }
enum-map = { version = "2.7.3", features = ["serde"] }
colog = "1.3.0"
env_logger = "0.11.5"
log = { version = "0.4.22", features = ["serde", "std", "release_max_level_debug", "max_level_debug"] }
[[bin]]
name = "rusty_midicommander"

View File

@ -10,9 +10,8 @@ use std::{
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
use crate::RustyMidiError;
use crate::{projector::VPType, RustyMidiError};
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
@ -36,19 +35,18 @@ pub enum SubCommands {
/// The bulk of the cli arguments, able to be launch and reloaded from a config file.
///
/// Note that the global config file and a vp config file are different and created differently
#[derive(Debug, Parser, Serialize, Deserialize)]
#[derive(Debug, Parser, Serialize, Deserialize, Clone)]
pub struct CLIArgs {
/// The midi interface to select, if none is selected,
/// the program will not be using midi altogether
pub midi_interface: Option<usize>,
/// Natural timeout delay
pub delay: Option<usize>,
/// Config, holding another subset of values
#[arg(short, long)]
pub config: Option<String>,
/// Create a config file from all the given arguments
#[arg(short, long)]
pub save: Option<String>,
//
// /// Connect to a VP
@ -63,12 +61,6 @@ pub struct CreateArgs {
pub create: Option<VPType>,
}
/// Enumerate all the VP types
#[derive(Parser, Serialize, Deserialize, Clone, Debug)]
pub enum VPType {
Panasonic,
}
// impl From<OsStr> for VPType {
// fn from(value: OsStr) -> Self {
// todo!()
@ -77,12 +69,13 @@ pub enum VPType {
/// Get a parsed Args from the Cli, this function will also perform the basic (save/load) and printing needed
pub fn get_arguments_from_cli() -> Result<RMCArgs, RustyMidiError> {
debug!("Loading CLI arguments");
log::debug!("Loading CLI arguments");
let cli = parse_cli_and_load()?;
if let SubCommands::Launch(cliargs) = &cli.command {
if let Some(save_path) = &cliargs.save {
info!("Saving config as {}", save_path);
File::create(save_path)?.write_all(serde_json::to_string(&cliargs)?.as_bytes())?;
log::info!("Saving config as {}: ", save_path);
File::create(save_path)?
.write_all(serde_json::to_string_pretty(&cliargs)?.as_bytes())?;
}
}
Ok(cli)
@ -95,14 +88,15 @@ fn parse_cli_and_load() -> Result<RMCArgs, RustyMidiError> {
if let Some(path) = &cliargs.config {
match load_from_disk(path) {
Ok(args_new) => {
debug!(
"Updated arguments with new values {:?} => {:?}",
cliargs, args_new
log::debug!(
"Updated arguments with new values \n [OLD] {:?} \n [NEW] {:?}",
cliargs,
args_new
);
update_non_default(cliargs, args_new)
update_non_default(cliargs, args_new);
}
Err(e) => {
warn!("The file {} coudln't be loaded: {}", path, e);
log::warn!("The file {} couldn't be loaded:\n {}", path, e);
}
}
}
@ -117,28 +111,20 @@ fn load_from_disk(path: &str) -> Result<CLIArgs, RustyMidiError> {
/// Update a parameter
macro_rules! update {
($args_og:ident, $new_args:ident, $param:ident) => {
$args_og.$param.or($new_args.$param)
($args_og:ident, $args_new:ident, $param:ident) => {
let og = $args_og.$param.take();
$args_og.$param = og.or_else(|| {
// log::info!("Changing save with {:?}", args_new.config.as_mut());
$args_new.$param
});
};
}
/// Update all None parameters withthe config loaded ones
fn update_non_default(args_og: &mut CLIArgs, mut args_new: CLIArgs) {
// CLIArgs {
// midi_interface: update!(args_og, args_new, midi_interface),
// delay: update!(args_og, args_new, delay),
// config: update!(args_og, args_new, config),
// save: update!(args_og, args_new, save),
// // vp: update!(args_og, args_new, vp),
// // create: update!(args_og, args_new, create),
// }
args_og.config.as_mut().or(args_new.config.as_mut());
args_og.delay.as_mut().or(args_new.delay.as_mut());
args_og.save.as_mut().or(args_new.save.as_mut());
args_og
.midi_interface
.as_mut()
.or(args_new.midi_interface.as_mut());
fn update_non_default(args_og: &mut CLIArgs, args_new: CLIArgs) {
update!(args_og, args_new, save);
update!(args_og, args_new, config);
update!(args_og, args_new, midi_interface);
}
impl RMCArgs {
@ -149,15 +135,15 @@ impl RMCArgs {
SubCommands::Launch(
cliargs @ CLIArgs {
midi_interface: _,
delay: _,
config: _,
save: Some(save_path),
},
),
} = &self
{
info!("Saving config as {}", save_path);
File::create(save_path)?.write_all(serde_json::to_string(&cliargs)?.as_bytes())?;
log::info!("Saving config as {}: ", save_path);
File::create(save_path)?
.write_all(serde_json::to_string_pretty(&cliargs)?.as_bytes())?;
}
Ok(())
}

View File

@ -10,17 +10,23 @@ use std::{
use crate::{
cli::{self, CreateArgs},
midi::{self, cleanup, connect_loop_with_callback, create_output_interface},
projector::{self, GenericProjector},
projector::{self, new_default_projector_of_type, GenericProjector},
RustyMidiError,
};
/// Execute all config creation action
pub fn create_config(create_args: CreateArgs) {
// match create_args
pub fn create_config(create_args: CreateArgs) -> Result<(), RustyMidiError> {
create_args.create.into_iter().for_each(|vp| {
let _ = new_default_projector_of_type(&vp)
.inspect_err(|e| println!("Couldn't save the projector {:?} {}", vp, e));
});
Ok(())
}
// TODO: Upgrade
/// Launch the program as a cli
pub fn cli_launch(cliargs: cli::CLIArgs) {
pub fn cli_launch(cliargs: cli::CLIArgs) -> Result<(), RustyMidiError> {
println!("{:?}", cliargs);
// TODO: Cleanup all the following
if cliargs.midi_interface.is_none() {
midi::print_midi_interfaces();
@ -72,4 +78,5 @@ pub fn cli_launch(cliargs: cli::CLIArgs) {
),
],
);
Ok(())
}

View File

@ -17,7 +17,7 @@ pub enum RustyMidiError {
// #[error("an error occured while trying to serialize the config file {0}")]
// RonDeSerialization(#[from] ron::Error),
#[error("an error occured while trying to deserialize the projector config {0}")]
#[error("an error occured while trying to deserialize the projector config: \n Error: {0}")]
JSONSerialisation(#[from] serde_json::Error),
// #[error("an error occured while trying to serialize the config file {0}")]
// RonDeSerialization(#[from] ron::Error),

View File

@ -15,3 +15,13 @@ pub mod projector;
pub use dispatch::{cli_launch, create_config};
pub use error::RustyMidiError;
/// Basic logging setup
pub fn init_logger() {
// use colog::format::CologStyle;
let mut builder = env_logger::Builder::new();
builder.filter_level(log::LevelFilter::max());
builder.format(colog::formatter(colog::format::DefaultCologStyle));
builder.init();
log::info!("Logging ready");
}

View File

@ -5,13 +5,15 @@
#![warn(clippy::missing_docs_in_private_items)]
use rmc_lib::{cli_launch, create_config};
use rmc_lib::{cli_launch, create_config, init_logger};
use std::process::exit;
use clap::Parser;
use rmc_lib::cli;
fn main() {
init_logger();
// Parse Arguments
let args = cli::get_arguments_from_cli().unwrap_or_else(|e| {
println!("Coudln't read the command line {}", e);
@ -25,8 +27,14 @@ fn main() {
/// The main dispatch, evaluating all tasks and outputting errors and logging
fn main_dispatch(args: cli::RMCArgs) {
match args.command {
let _ = match args.command {
cli::SubCommands::Create(create_args) => create_config(create_args),
cli::SubCommands::Launch(cliargs) => cli_launch(cliargs),
}
.inspect_err(|e| {
println!(
"[ERROR] An error occured while trying to execute the command. {}",
e
)
});
}

View File

@ -91,7 +91,7 @@ pub fn connect_loop_with_callback(
// TODO: Doc
pub fn create_output_interface(port: usize, name: &str) -> Arc<Mutex<MidiOutputConnection>> {
let output_interface = MidiOutput::new(name).unwrap();
let output_port = &output_interface.ports()[port];
let output_port = &output_interface.ports()[port]; // TODO: This error is ideous
Arc::new(Mutex::new(
output_interface
.connect(output_port, "Rusty MIDI Commander Output")

View File

@ -3,4 +3,24 @@
pub mod panasonic;
pub mod proj_traits;
use clap::Parser;
use panasonic::PanasonicProjector;
pub use proj_traits::{AdvancedCommands, GenericProjector};
use serde::{Deserialize, Serialize};
/// Enumerate all the VP types
#[derive(Parser, Serialize, Deserialize, Clone, Debug)]
pub enum VPType {
Panasonic,
}
/// Create a new empty projector of the given type
///
/// While inelegant, this is the most straightforward way of having a generic projector
pub fn new_default_projector_of_type(vptype: &VPType) -> Result<(), crate::RustyMidiError> {
match vptype {
VPType::Panasonic => {
PanasonicProjector::default().create_default_config_file("new_panasonic.json")
}
}
}

View File

@ -20,8 +20,6 @@ pub struct PanasonicProjector {
username: String,
/// The password for the connection
password: String,
/// An optionnal port for connection
port: Option<usize>,
/// An optionnal timeout
timeout: f64,
}
@ -52,7 +50,6 @@ impl PanasonicProjector {
ip: ip.to_string(),
username: username.to_string(),
password: password.to_string(),
port: None,
timeout: 0.7,
}
}

View File

@ -48,12 +48,12 @@ where
/// Create an empty file to fill with info
///
/// TODO: Add a way to bypass this whole: create a file, fill it manually and then launch it
fn create_config_file(&self, path: &str) -> Result<(), RustyMidiError>
fn create_default_config_file(&self, path: &str) -> Result<(), RustyMidiError>
where
Self: Sized + Serialize,
{
std::fs::File::create(path)?
.write_all(serde_json::to_string(self as &dyn GenericProjector)?.as_bytes())?;
.write_all(serde_json::to_string_pretty(self as &dyn GenericProjector)?.as_bytes())?;
Ok(())
}
@ -129,12 +129,13 @@ mod test {
let _ = std::fs::remove_dir_all("test");
let _ = std::fs::create_dir("test");
let b = Bob {};
b.create_config_file("test/test_bob_config.ron").unwrap();
b.create_default_config_file("test/test_bob_config.ron")
.unwrap();
let bb = Bob::load("test/test_bob_config.ron").unwrap();
let b_s = serde_json::to_string(&b as &dyn GenericProjector).unwrap();
let bb_s = serde_json::to_string(&bb).unwrap();
let b_s = serde_json::to_string_pretty(&b as &dyn GenericProjector).unwrap();
let bb_s = serde_json::to_string_pretty(&bb).unwrap();
assert_eq!(b_s, bb_s);
}