Adds dispatch, works on config

This commit is contained in:
Dandaedre 2024-12-08 22:02:30 +01:00
parent 255dd143fa
commit 9a3fdfc149
5 changed files with 200 additions and 87 deletions

View File

@ -8,17 +8,38 @@ use std::{
io::Write,
};
use clap::Parser;
use clap::{Parser, Subcommand};
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
use crate::RustyMidiError;
#[derive(Parser, Debug, Serialize, Deserialize, Default)]
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
/// A struct representing command line arguments for a CLI.
pub struct Args {
/// The midi interface to select
pub struct RMCArgs {
/// The subcommand to pick from
#[command(subcommand)]
pub command: SubCommands,
}
#[derive(Debug, Subcommand)]
pub enum SubCommands {
/// Create a VP config file with the given name
Create(CreateArgs),
/// Launch the program as a cli
Launch(CLIArgs),
// /// Launch the program as a TUI
// TUI(TUIArgs),
}
/// 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)]
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
@ -29,37 +50,68 @@ pub struct Args {
/// Create a config file from all the given arguments
pub save: Option<String>,
//
// /// Connect to a VP
// pub vp: Option<Vec<VPType>>,
}
/// All arguments for creating a VP configuration
#[derive(Debug, Parser, Serialize, Deserialize)]
pub struct CreateArgs {
/// Create a projector config file of a specific type
#[command(subcommand)]
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!()
// }
// }
/// 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<Args, RustyMidiError> {
pub fn get_arguments_from_cli() -> Result<RMCArgs, RustyMidiError> {
debug!("Loading CLI arguments");
let cli = parse_cli_and_load()?;
if let Some(save_path) = &cli.save {
info!("Saving config as {}", save_path);
File::create(save_path)?.write_all(serde_json::to_string(&cli)?.as_bytes())?;
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())?;
}
}
Ok(cli)
}
/// Parse all cli arguments and loads a config from file if needed
fn parse_cli_and_load() -> Result<Args, RustyMidiError> {
let args_og = Args::parse();
if let Some(path) = &args_og.config {
match load_from_disk(path) {
Ok(args_new) => Ok(update_non_default(args_og, args_new)),
Err(e) => {
warn!("The file {} coudln't be loaded: {}", path, e);
Ok(args_og)
fn parse_cli_and_load() -> Result<RMCArgs, RustyMidiError> {
let mut args = RMCArgs::parse();
if let SubCommands::Launch(ref mut cliargs) = args.command {
if let Some(path) = &cliargs.config {
match load_from_disk(path) {
Ok(args_new) => {
debug!(
"Updated arguments with new values {:?} => {:?}",
cliargs, args_new
);
update_non_default(cliargs, args_new)
}
Err(e) => {
warn!("The file {} coudln't be loaded: {}", path, e);
}
}
}
} else {
Ok(args_og)
}
};
Ok(args)
}
/// Load a given config from disk and return it as a Config
fn load_from_disk(path: &str) -> Result<Args, RustyMidiError> {
fn load_from_disk(path: &str) -> Result<CLIArgs, RustyMidiError> {
Ok(serde_json::from_str(&read_to_string(path)?)?)
}
@ -71,11 +123,42 @@ macro_rules! update {
}
/// Update all None parameters withthe config loaded ones
fn update_non_default(args_og: Args, args_new: Args) -> Args {
Args {
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),
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());
}
impl RMCArgs {
/// Save the config
pub fn save(&self) -> Result<(), RustyMidiError> {
if let RMCArgs {
command:
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())?;
}
Ok(())
}
}

75
src/dispatch.rs Normal file
View File

@ -0,0 +1,75 @@
//! All functions executed directly from main
//!
//! Contains all functionnalities the CLI expects
use std::{
process::exit,
sync::{Arc, Mutex},
};
use crate::{
cli::{self, CreateArgs},
midi::{self, cleanup, connect_loop_with_callback, create_output_interface},
projector::{self, GenericProjector},
};
/// Execute all config creation action
pub fn create_config(create_args: CreateArgs) {
// match create_args
}
// TODO: Upgrade
/// Launch the program as a cli
pub fn cli_launch(cliargs: cli::CLIArgs) {
// TODO: Cleanup all the following
if cliargs.midi_interface.is_none() {
midi::print_midi_interfaces();
exit(1);
}
println!("{:?}", cliargs);
let proj = Arc::new(Mutex::new(projector::panasonic::PanasonicProjector::new(
"127.0.0.1:8080",
"admin1",
"panasonic",
)));
let proj1 = Arc::clone(&proj);
let proj2 = Arc::clone(&proj);
// proj.lock().unwrap().shutter_on().unwrap();
// proj.lock().unwrap().shutter_off().unwrap();
// proj.lock().unwrap().get_osd().unwrap();
let mut output_interface = create_output_interface(
cliargs.midi_interface.unwrap(),
"Rusty MIDI Commander Output",
);
cleanup(&mut output_interface.lock().unwrap());
connect_loop_with_callback(
cliargs.midi_interface.unwrap(),
"Rusty MIDI Commander Input",
&mut output_interface,
vec![
(
3,
Box::new(move || match proj1.lock().unwrap().shutter_off() {
Ok(_) => println!("Receiving SHUTTER OFF message"),
Err(_e) => {
println!("Error receiving SHUTTER OFF message");
"Error".to_string();
}
}),
),
(
4,
Box::new(move || match proj2.lock().unwrap().shutter_on() {
Ok(_) => println!("Receiving SHUTTER ON message"),
Err(_e) => {
println!("Error receiving SHUTTER ON message");
"Error".to_string();
} // proj2.lock().unwrap().unwrap_or((|| {})());
}),
),
],
);
}

View File

@ -8,8 +8,10 @@
#![warn(clippy::missing_docs_in_private_items)]
// use midir::MidiOutput;
pub mod cli;
mod dispatch;
pub mod error;
pub mod midi;
pub mod projector;
pub use dispatch::{cli_launch, create_config};
pub use error::RustyMidiError;

View File

@ -5,75 +5,28 @@
#![warn(clippy::missing_docs_in_private_items)]
use rmc_lib::projector::GenericProjector;
use std::{
process::exit,
sync::{Arc, Mutex},
};
use rmc_lib::{cli_launch, create_config};
use std::process::exit;
use clap::Parser;
use rmc_lib::{
cli,
midi::{self, cleanup, connect_loop_with_callback, create_output_interface},
projector,
};
use rmc_lib::cli;
fn main() {
// Parse Arguments
let args = cli::get_arguments_from_cli().unwrap_or_else(|e| {
println!("Coudln't read the command line {}", e);
// TODO: Test this
cli::Args::parse_from(vec!["-h"]);
cli::RMCArgs::parse_from(vec!["-h"]);
exit(1);
});
// TODO: Cleanup all the following
if args.midi_interface.is_none() {
midi::print_midi_interfaces();
return;
}
println!("{:?}", args);
let proj = Arc::new(Mutex::new(projector::panasonic::PanasonicProjector::new(
"127.0.0.1:8080",
"admin1",
"panasonic",
)));
let proj1 = Arc::clone(&proj);
let proj2 = Arc::clone(&proj);
// proj.lock().unwrap().shutter_on().unwrap();
// proj.lock().unwrap().shutter_off().unwrap();
// proj.lock().unwrap().get_osd().unwrap();
let mut output_interface =
create_output_interface(args.midi_interface.unwrap(), "Rusty MIDI Commander Output");
cleanup(&mut output_interface.lock().unwrap());
connect_loop_with_callback(
args.midi_interface.unwrap(),
"Rusty MIDI Commander Input",
&mut output_interface,
vec![
(
3,
Box::new(move || match proj1.lock().unwrap().shutter_off() {
Ok(_) => println!("Receiving SHUTTER OFF message"),
Err(_e) => {
println!("Error receiving SHUTTER OFF message");
"Error".to_string();
}
}),
),
(
4,
Box::new(move || match proj2.lock().unwrap().shutter_on() {
Ok(_) => println!("Receiving SHUTTER ON message"),
Err(_e) => {
println!("Error receiving SHUTTER ON message");
"Error".to_string();
} // proj2.lock().unwrap().unwrap_or((|| {})());
}),
),
],
);
main_dispatch(args);
}
/// The main dispatch, evaluating all tasks and outputting errors and logging
fn main_dispatch(args: cli::RMCArgs) {
match args.command {
cli::SubCommands::Create(create_args) => create_config(create_args),
cli::SubCommands::Launch(cliargs) => cli_launch(cliargs),
}
}

View File

@ -119,7 +119,7 @@ mod test {
#[test]
fn test_base_impl() {
let b = Bob {};
assert_eq!(b.connect().unwrap(), "connected".into());
assert_eq!(b.connect().unwrap(), "connected".to_string().into());
assert_eq!(b.shutter_on().unwrap(), "opened".into());
assert_eq!(b.shutter_off().unwrap(), "closed".into());
}