From 355402ea0807ac608212bb0803072f145a50e6d7 Mon Sep 17 00:00:00 2001 From: beffroi Date: Tue, 4 Apr 2023 16:56:27 +0200 Subject: [PATCH 1/8] Workaround for the Error values --- src/main.rs | 18 +++++++++++++----- src/midi.rs | 3 +-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/main.rs b/src/main.rs index 51347e0..33d5915 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,7 +43,7 @@ fn main() { } println!("{:?}", args); let proj = Arc::new(Mutex::new(projector::Projector::new( - "127.0.0.1:8080", + "192.168.0.8", //"127.0.0.1:8080", "admin1", "panasonic", ))); @@ -64,14 +64,22 @@ fn main() { vec![ ( 3, - Box::new(move || { - proj1.lock().unwrap().shutter_on().unwrap(); + 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 || { - proj2.lock().unwrap().shutter_on().unwrap(); + 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((|| {})()); }), ), ], diff --git a/src/midi.rs b/src/midi.rs index cedec07..f53d474 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -50,12 +50,11 @@ pub fn connect_loop_with_callback( move |_timestamp, message, _| { // Handle MIDI messages here let (command, note, _value) = (message[0], message[1], message[2]); - println!("Received MIDI message: {:?}", message); + //println!("Received MIDI message: {:?}", message); match (command, note) { (144, 3..=4) => { for (id, f) in calls.iter() { if note == *id { - println!("match"); f(); } let mut list = vec![]; From bb6760030863ea7d9fa3a15049e7fad7c38d2b37 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 7 Apr 2023 16:25:14 +0200 Subject: [PATCH 2/8] Added a viewboard, problem right now is lack of project --- Cargo.toml | 6 +++- src/midi.rs | 9 +++--- src/viewboard.rs | 77 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 5 deletions(-) create mode 100644 src/viewboard.rs diff --git a/Cargo.toml b/Cargo.toml index 42e6fa8..ee32985 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,4 +19,8 @@ path = "src/main.rs" [[bin]] name = "webtest" -path = "src/webtest.rs" \ No newline at end of file +path = "src/webtest.rs" + +[[bin]] +name = "viewboard" +path = "src/viewboard.rs" \ No newline at end of file diff --git a/src/midi.rs b/src/midi.rs index f53d474..cfc2a30 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -1,9 +1,10 @@ // The midi module should provide a high-level interface for receiving and sending MIDI messages. // It should handle the low-level details of communicating with the MIDI devices. -use crate::MidiInput; -use crate::MidiOutput; -use crate::MidiOutputConnection; +use midir::MidiInput; +use midir::MidiOutput; +use midir::MidiOutputConnection; + use lazy_static::lazy_static; use std::sync::Arc; use std::sync::Mutex; @@ -99,7 +100,7 @@ pub fn cleanup( // co.send(message).unwrap(); // } for n in 0..=71 { - send_note_on(out_port, n, 0); + send_note_on(out_port, n, 2); } for n in 82..=89 { send_note_on(out_port, n, 0); diff --git a/src/viewboard.rs b/src/viewboard.rs new file mode 100644 index 0000000..baf6a27 --- /dev/null +++ b/src/viewboard.rs @@ -0,0 +1,77 @@ +#![allow(dead_code)] + +use crate::midi::create_output_interface; +use crate::midi::print_midi_interfaces; +use crate::midi::send_note_on; +use midir::MidiOutputConnection; +use std::sync::Arc; +use std::sync::Mutex; +use std::thread::sleep; +use std::time::Duration; + +/// A viewboard to represent the commanderpad +mod midi; +struct Placeholder {} + +struct RecvCommander<'a> { + /// The midi channel to communicate with the board + pub midi_address: &'a mut Arc>, + /// The list of available notes + pub list_notes: Vec, + /// The list of current notes values (if no other source has sent changes) + pub current_values: Vec, + /// The list of notes about to be sent + pub future_values: Vec, + /// The state of the board, wether it is visible or not + pub live: bool, +} + +impl RecvCommander<'_> { + fn new(output_interface: &mut Arc>) -> RecvCommander { + // Assert all vectors are of the same size + assert_eq!(70, 70); + RecvCommander { + midi_address: output_interface, + list_notes: (0..89).collect(), + current_values: vec![0; 89], + future_values: vec![0; 89], + live: false, + } + } + fn reset(&self) { + // let mut _addr = self.midi_address.lock().unwrap(); + for (i, note) in self.list_notes.iter().enumerate() { + send_note_on(&mut self.midi_address.lock().unwrap(), *note, 0); + if i % 20 == 0 { + sleep(Duration::from_millis(100)); + } + } + } + fn update(&self) { + for (i, note) in self.list_notes.iter().enumerate() { + let cr_note = self.current_values[i]; + let fu_note = self.future_values[i]; + if i % 20 == 0 { + sleep(Duration::from_millis(100)); + } + if fu_note == cr_note { + continue; + } + + send_note_on(&mut self.midi_address.lock().unwrap(), *note, fu_note); + } + } +} + +fn main() { + print_midi_interfaces(); + let output_interface = create_output_interface(3, "Rusty MIDI Commander Output"); + let mut binding = Arc::clone(&output_interface); + let board = RecvCommander::new(&mut binding); + // cleanup(&mut output_interface.lock().unwrap()); + board.reset(); + send_note_on(&mut output_interface.lock().unwrap(), 2, 1); + // sleep(Duration::from_millis(1000)); + board.update(); + loop {} +} From c82294f1f97d15d18aedbe40f13950d34ac0ec2e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 4 Dec 2023 22:47:57 +0100 Subject: [PATCH 3/8] Fix weird color --- src/midi.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/midi.rs b/src/midi.rs index cfc2a30..7bf6b64 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -100,7 +100,7 @@ pub fn cleanup( // co.send(message).unwrap(); // } for n in 0..=71 { - send_note_on(out_port, n, 2); + send_note_on(out_port, n, 0); } for n in 82..=89 { send_note_on(out_port, n, 0); From 670b1540c125d47c23b8544da8e06284a8d684c9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 7 Dec 2024 11:40:54 -0600 Subject: [PATCH 4/8] Adds a viewboard (?) --- src/midi.rs | 34 ++++++++++++++++------------------ src/viewboard.rs | 5 +++-- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/midi.rs b/src/midi.rs index dd2528d..d45c5f8 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -60,24 +60,22 @@ pub fn connect_loop_with_callback( // Handle MIDI messages here let (command, note, _value) = (message[0], message[1], message[2]); //println!("Received MIDI message: {:?}", message); - match (command, note) { - (144, 3..=4) => { - for (id, f) in calls.iter() { - if note == *id { - f(); - } - let mut list = vec![]; - if note == 3 { - list.push([command, 3, 2]); - list.push([command, 4, 3]); - } else { - list.push([command, 3, 1]); - list.push([command, 4, 4]); - } - for n in list.iter() { - conn_clone.lock().unwrap().send(n).unwrap(); - conn_clone.lock().unwrap().send(n).unwrap(); - } + if let (144, 3..=4) = (command, note) { + for (id, f) in calls.iter() { + if note == *id { + f(); + } + let mut list = vec![]; + if note == 3 { + list.push([command, 3, 2]); + list.push([command, 4, 3]); + } else { + list.push([command, 3, 1]); + list.push([command, 4, 4]); + } + for n in list.iter() { + conn_clone.lock().unwrap().send(n).unwrap(); + conn_clone.lock().unwrap().send(n).unwrap(); } } } diff --git a/src/viewboard.rs b/src/viewboard.rs index baf6a27..4836bb6 100644 --- a/src/viewboard.rs +++ b/src/viewboard.rs @@ -29,7 +29,6 @@ struct RecvCommander<'a> { impl RecvCommander<'_> { fn new(output_interface: &mut Arc>) -> RecvCommander { // Assert all vectors are of the same size - assert_eq!(70, 70); RecvCommander { midi_address: output_interface, list_notes: (0..89).collect(), @@ -73,5 +72,7 @@ fn main() { send_note_on(&mut output_interface.lock().unwrap(), 2, 1); // sleep(Duration::from_millis(1000)); board.update(); - loop {} + loop { + sleep(Duration::from_millis(500)); + } } From d094b291576b71fc39bfc142e12537edc91a7005 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 8 Dec 2024 14:50:36 +0100 Subject: [PATCH 5/8] Adds some cli & Error handling --- .gitignore | 3 ++ Cargo.toml | 3 +- README.md | 3 +- badges/coverage.svg | 1 + badges/test.svg | 1 + badges/version.svg | 1 + src/cli.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++ src/error.rs | 22 ++++++++++-- src/lib.rs | 1 + src/main.rs | 38 ++++++++++----------- 10 files changed, 133 insertions(+), 23 deletions(-) create mode 100644 badges/coverage.svg create mode 100644 badges/test.svg create mode 100644 badges/version.svg create mode 100644 src/cli.rs diff --git a/.gitignore b/.gitignore index 193d30e..bd11ae0 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ Cargo.lock # Added by cargo /target + +# Tarpaulin +tarpaulin-report.html diff --git a/Cargo.toml b/Cargo.toml index 552a5ba..152570e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,11 @@ reqwest = { version = "0.11.16", features = ["blocking"] } base64 = "0.21.0" lazy_static = "1.4.0" ratatui = "0.29.0" -serde = "1.0.215" +serde = { version = "1.0.215", features = ["derive", "alloc"] } thiserror = "2.0.4" tracing = "0.1.41" tokio = "1.42.0" +ron = "0.8.1" [[bin]] name = "rusty_midicommander" diff --git a/README.md b/README.md index 59b03a9..4831eca 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # RustyMIDICommander +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) Rusty MIDI Commander is a lightweight and flexible Rust program for sending asynchronous commands in response to MIDI input. @@ -10,4 +11,4 @@ Rusty MIDI Commander makes it easy to build powerful and responsive MIDI control # Installation Depends on: - - `librust-alsa-dev` + - `librust-alsa-sys-dev` diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..e6a15fe --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 0%test-coverage0% diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..a7859aa --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: passingtestpassing diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c28c459 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1.0version0.1.0 diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..255b2cb --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,83 @@ +//! CLI & config processing. +//! +//! Processes all arguments given by the CLI invocation via clap +//! The usage of config will provide if used a way to have default values for all arguments + +use std::{ + fs::{read_to_string, File}, + io::Write, +}; + +use clap::Parser; +use serde::{Deserialize, Serialize}; +use tracing::{debug, info, warn}; + +use crate::RustyMidiError; + +#[derive(Parser, Debug, Serialize, Deserialize, Default)] +#[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 midi_interface: Option, + + /// Natural timeout delay + pub delay: Option, + + /// Config, holding another subset of values + pub config: Option, + + /// Create a config file from all the given arguments + pub save: Option, +} + +/// 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 { + 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( + ron::ser::to_string_pretty(&cli, ron::ser::PrettyConfig::default())?.as_bytes(), + )?; + } + Ok(cli) +} + +/// Parse all cli arguments and loads a config from file if needed +fn parse_cli_and_load() -> Result { + 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) + } + } + } else { + Ok(args_og) + } +} + +/// Load a given config from disk and return it as a Config +fn load_from_disk(path: &str) -> Result { + Ok(ron::from_str(&read_to_string(path)?)?) +} + +/// Update a parameter +macro_rules! update { + ($args_og:ident, $new_args:ident, $param:ident) => { + $args_og.$param.or($new_args.$param) + }; +} + +/// 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), + } +} diff --git a/src/error.rs b/src/error.rs index 0e79da7..63ec23c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,12 +1,30 @@ -//! Generic rusty midi commander error +//! Generic Rusty MIDI Commander error //! use thiserror::Error; -/// A generic error +/// A generic error for the Rusty Midi Commander. /// +/// # Example Usage +/// ``` +/// use rmc_lib::RustyMidiError; +/// +/// match Some(reqwest::Error::new(reqwest::StatusCode::NotFound)) { +/// None => println!("No error"), +/// Some(err) => return Err(RustyMidiError::NetworkRequest(err)), +/// } +/// ``` #[derive(Error, Debug)] pub enum RustyMidiError { #[error("network request failed {0}")] NetworkRequest(#[from] reqwest::Error), + + #[error("an error occured while accessing a file {0}")] + IO(#[from] std::io::Error), + + #[error("an error occured while trying to deserialize the config file {0}")] + RonSerialization(#[from] ron::de::SpannedError), + + #[error("an error occured while trying to serialize the config file {0}")] + RonDeSerialization(#[from] ron::Error), } diff --git a/src/lib.rs b/src/lib.rs index b1e8c4e..3acb5f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,6 +7,7 @@ #![warn(clippy::missing_docs_in_private_items)] // use midir::MidiOutput; +pub mod cli; pub mod error; pub mod midi; pub mod projector; diff --git a/src/main.rs b/src/main.rs index 2ae34e8..3d788e8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,37 +1,37 @@ -//! In this organization, src/main.rs is the entry point for the program. -//! This file should set up the MIDI input and output devices, and then -//! start a loop to receive and process MIDI messages. -//! It should also use the commands module to send commands asynchronously. -//! use crate::midi::print_midi_interfaces; +//! This file initializes MIDI input and output devices, then continually listens to and processes MIDI messages. +//! It employs the `commands` module to send commands asynchronously. For all input MIDI devices present on the system, +//! it registers a command with the input interface which will be executed when a MIDI message with the specified velocity +//! is received from that device. #![warn(clippy::missing_docs_in_private_items)] -use std::sync::{Arc, Mutex}; +use std::{ + process::exit, + sync::{Arc, Mutex}, +}; use clap::Parser; use rmc_lib::{ + cli, midi::{self, cleanup, connect_loop_with_callback, create_output_interface}, projector, }; -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -/// Description of the cli -struct Args { - /// The midi interface to select - midi_interface: Option, -} - fn main() { // Parse Arguments - let args = Args::parse(); - if let Args { - midi_interface: None, - } = args - { + 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"]); + 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::Projector::new( "127.0.0.1:8080", From 255dd143fa1da8f52cc10b456f308c53e1d5e946 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 8 Dec 2024 18:13:45 +0100 Subject: [PATCH 6/8] More work on the cli --- .gitignore | 2 + Cargo.toml | 3 +- badges/coverage.svg | 2 +- src/cli.rs | 6 +- src/error.rs | 22 ++---- src/main.rs | 3 +- src/projector/mod.rs | 4 +- src/projector/panasonic.rs | 53 ++++++++----- src/projector/proj_traits.rs | 140 ++++++++++++++++++++++++++++++++++- 9 files changed, 187 insertions(+), 48 deletions(-) diff --git a/.gitignore b/.gitignore index bd11ae0..86c1320 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,5 @@ Cargo.lock # Tarpaulin tarpaulin-report.html +test/ +.ignore diff --git a/Cargo.toml b/Cargo.toml index 152570e..ca5d6ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,8 @@ serde = { version = "1.0.215", features = ["derive", "alloc"] } thiserror = "2.0.4" tracing = "0.1.41" tokio = "1.42.0" -ron = "0.8.1" +typetag = "0.2.18" +serde_json = { version = "1.0.133", features = ["alloc", "preserve_order"] } [[bin]] name = "rusty_midicommander" diff --git a/badges/coverage.svg b/badges/coverage.svg index e6a15fe..7242f88 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 0%test-coverage0% +test-coverage: 5%test-coverage5% diff --git a/src/cli.rs b/src/cli.rs index 255b2cb..bbed7a0 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -37,9 +37,7 @@ pub fn get_arguments_from_cli() -> Result { 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( - ron::ser::to_string_pretty(&cli, ron::ser::PrettyConfig::default())?.as_bytes(), - )?; + File::create(save_path)?.write_all(serde_json::to_string(&cli)?.as_bytes())?; } Ok(cli) } @@ -62,7 +60,7 @@ fn parse_cli_and_load() -> Result { /// Load a given config from disk and return it as a Config fn load_from_disk(path: &str) -> Result { - Ok(ron::from_str(&read_to_string(path)?)?) + Ok(serde_json::from_str(&read_to_string(path)?)?) } /// Update a parameter diff --git a/src/error.rs b/src/error.rs index 63ec23c..718fcd7 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,16 +4,6 @@ use thiserror::Error; /// A generic error for the Rusty Midi Commander. -/// -/// # Example Usage -/// ``` -/// use rmc_lib::RustyMidiError; -/// -/// match Some(reqwest::Error::new(reqwest::StatusCode::NotFound)) { -/// None => println!("No error"), -/// Some(err) => return Err(RustyMidiError::NetworkRequest(err)), -/// } -/// ``` #[derive(Error, Debug)] pub enum RustyMidiError { #[error("network request failed {0}")] @@ -22,9 +12,13 @@ pub enum RustyMidiError { #[error("an error occured while accessing a file {0}")] IO(#[from] std::io::Error), - #[error("an error occured while trying to deserialize the config file {0}")] - RonSerialization(#[from] ron::de::SpannedError), + // #[error("an error occured while trying to deserialize the config file {0}")] + // RonSerialization(#[from] ron::de::SpannedError), - #[error("an error occured while trying to serialize the config file {0}")] - RonDeSerialization(#[from] ron::Error), + // #[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}")] + JSONSerialisation(#[from] serde_json::Error), + // #[error("an error occured while trying to serialize the config file {0}")] + // RonDeSerialization(#[from] ron::Error), } diff --git a/src/main.rs b/src/main.rs index 3d788e8..edd51b6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ #![warn(clippy::missing_docs_in_private_items)] +use rmc_lib::projector::GenericProjector; use std::{ process::exit, sync::{Arc, Mutex}, @@ -33,7 +34,7 @@ fn main() { } println!("{:?}", args); - let proj = Arc::new(Mutex::new(projector::panasonic::Projector::new( + let proj = Arc::new(Mutex::new(projector::panasonic::PanasonicProjector::new( "127.0.0.1:8080", "admin1", "panasonic", diff --git a/src/projector/mod.rs b/src/projector/mod.rs index 132a896..27104bf 100644 --- a/src/projector/mod.rs +++ b/src/projector/mod.rs @@ -3,6 +3,4 @@ pub mod panasonic; pub mod proj_traits; -/// The standard wait time -// TODO: NO -static WAIT_TIME: f64 = 0.7; +pub use proj_traits::{AdvancedCommands, GenericProjector}; diff --git a/src/projector/panasonic.rs b/src/projector/panasonic.rs index ed5781e..39c63ff 100644 --- a/src/projector/panasonic.rs +++ b/src/projector/panasonic.rs @@ -5,13 +5,15 @@ use std::time::Duration; use base64::{engine::general_purpose, Engine}; use reqwest::blocking::{Client, RequestBuilder}; +use serde::{Deserialize, Serialize}; use crate::error::RustyMidiError; -use super::WAIT_TIME; +use super::proj_traits::{GenericProjector, RequestReturn}; /// A projector and all info to connect to it -pub struct Projector { +#[derive(Clone, Default, Debug, Deserialize, Serialize)] +pub struct PanasonicProjector { /// The projector ip ip: String, /// The username to connect to it @@ -20,17 +22,38 @@ pub struct Projector { password: String, /// An optionnal port for connection port: Option, + /// An optionnal timeout + timeout: f64, } -// TODO: Trait -impl Projector { +#[typetag::serde] +impl GenericProjector for PanasonicProjector { + fn connect(&self) -> Result { + Ok(String::new().into()) + } + + /// A request to turn the projector on + fn shutter_on(&self) -> Result { + self.open_url("shutter_on") + } + + /// A request to turn the projector off + fn shutter_off(&self) -> Result { + self.open_url("shutter_off") + } +} + +impl PanasonicProjector { /// Create a new projector with the basic information - pub fn new(ip: &str, username: &str, password: &str) -> Projector { - Projector { + // TODO: Load it from file instead + #[deprecated] + pub fn new(ip: &str, username: &str, password: &str) -> PanasonicProjector { + PanasonicProjector { ip: ip.to_string(), username: username.to_string(), password: password.to_string(), port: None, + timeout: 0.7, } } @@ -55,32 +78,22 @@ impl Projector { let builder = client .get(url) .header("Authorization", headers) - .timeout(Duration::from_secs_f64(WAIT_TIME)); + .timeout(Duration::from_secs_f64(self.timeout)); Ok(builder) } /// Make the actual request - pub fn open_url(&self, cmd: &str) -> Result { + fn open_url(&self, cmd: &str) -> Result { let headers = self.make_auth_header(); let url = self.make_url(cmd); let builder = self.make_request(&url, &headers)?; let response = builder.send()?; let body = response.text()?; - Ok(body) - } - - /// A request to turn the projector on - pub fn shutter_on(&self) -> Result { - self.open_url("shutter_on") - } - - /// A request to turn the projector off - pub fn shutter_off(&self) -> Result { - self.open_url("shutter_off") + Ok(body.into()) } /// The request to the the osd - pub fn get_osd(&self) -> Result { + fn get_osd(&self) -> Result { let headers = self.make_auth_header(); let url = format!("http://{}/cgi-bin/get_osd.cgi?lang=e", self.ip); let builder = self.make_request(&url, &headers)?; diff --git a/src/projector/proj_traits.rs b/src/projector/proj_traits.rs index 30f9413..0d224d5 100644 --- a/src/projector/proj_traits.rs +++ b/src/projector/proj_traits.rs @@ -2,8 +2,140 @@ //! //! -/// A generic Projector, contains all methods for a controllable vp -trait GenericProjector {} +use crate::RustyMidiError; +use serde::Serialize; +use std::fmt::Debug; +use std::io::{Read, Write}; -/// A generic Projector OSD, to retreive information from the vp -trait GenericProjectorOSD {} +#[derive(Debug, Clone)] +#[cfg_attr(test, derive(Eq, PartialEq))] +pub struct RequestReturn { + pub message: String, +} + +impl From for RequestReturn { + fn from(value: String) -> Self { + Self { message: value } + } +} + +impl From<&str> for RequestReturn { + fn from(value: &str) -> Self { + Self { + message: value.to_string(), + } + } +} + +/// A generic Projector, contains all methods for a controllable vp +#[typetag::serde(tag = "projector_type")] +pub trait GenericProjector +where + Self: Debug, +{ + /// Loads this projector from a file + /// + /// Return a projector on success + fn load(path: &str) -> Result, RustyMidiError> + where + Self: Sized, + { + let buf = &mut String::new(); + std::fs::File::open(path)?.read_to_string(buf)?; + Ok(serde_json::from_str(buf)?) + } + + /// 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> + where + Self: Sized + Serialize, + { + std::fs::File::create(path)? + .write_all(serde_json::to_string(self as &dyn GenericProjector)?.as_bytes())?; + Ok(()) + } + + /// This method assert the projector is connectable to + /// + /// Any form of verification is acceptable, but a Ok() result is the mark of a successful connection + fn connect(&self) -> Result; + + /// Turns the shutter on + /// + /// Returns an error on disconnection or if the command failed + fn shutter_on(&self) -> Result; + + /// Turns the shutter off + /// + /// Returns an error on disconnection or if the command failed + fn shutter_off(&self) -> Result; +} + +/// A lot of advanced methods +pub trait AdvancedCommands { + /// The return object type + type RObject; + + /// Shutdown the VP + fn shutdown(&self) -> Result; + + /// Turn on the VP + fn turn_on(&self) -> Result; + + /// Get the OSD + fn get_osd(&self) -> Result; +} + +#[cfg(test)] +mod test { + use super::GenericProjector; + use serde::{Deserialize, Serialize}; + + #[derive(Serialize, Deserialize, Debug)] + struct Bob {} + + #[typetag::serde] + impl GenericProjector for Bob { + fn connect(&self) -> Result { + Ok(super::RequestReturn { + message: "connected".into(), + }) + } + + fn shutter_on(&self) -> Result { + Ok(super::RequestReturn { + message: "opened".into(), + }) + } + + fn shutter_off(&self) -> Result { + Ok(super::RequestReturn { + message: "closed".into(), + }) + } + } + #[test] + fn test_base_impl() { + let b = Bob {}; + assert_eq!(b.connect().unwrap(), "connected".into()); + assert_eq!(b.shutter_on().unwrap(), "opened".into()); + assert_eq!(b.shutter_off().unwrap(), "closed".into()); + } + + #[test] + fn test_save_and_load() { + 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(); + + 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(); + + assert_eq!(b_s, bb_s); + } +} From 9a3fdfc14961dfee4ef5600cef2bd0e825348039 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 8 Dec 2024 22:02:30 +0100 Subject: [PATCH 7/8] Adds dispatch, works on config --- src/cli.rs | 135 ++++++++++++++++++++++++++++------- src/dispatch.rs | 75 +++++++++++++++++++ src/lib.rs | 2 + src/main.rs | 73 ++++--------------- src/projector/proj_traits.rs | 2 +- 5 files changed, 200 insertions(+), 87 deletions(-) create mode 100644 src/dispatch.rs diff --git a/src/cli.rs b/src/cli.rs index bbed7a0..b2a3d36 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -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, /// Natural timeout delay @@ -29,37 +50,68 @@ pub struct Args { /// Create a config file from all the given arguments pub save: Option, + // + // /// Connect to a VP + // pub vp: Option>, } +/// 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, +} + +/// Enumerate all the VP types +#[derive(Parser, Serialize, Deserialize, Clone, Debug)] +pub enum VPType { + Panasonic, +} + +// impl From 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 { +pub fn get_arguments_from_cli() -> Result { 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 { - 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 { + 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 { +fn load_from_disk(path: &str) -> Result { 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(()) } } diff --git a/src/dispatch.rs b/src/dispatch.rs new file mode 100644 index 0000000..d4bf6de --- /dev/null +++ b/src/dispatch.rs @@ -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((|| {})()); + }), + ), + ], + ); +} diff --git a/src/lib.rs b/src/lib.rs index 3acb5f7..2dd98c7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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; diff --git a/src/main.rs b/src/main.rs index edd51b6..e9effe3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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), + } } diff --git a/src/projector/proj_traits.rs b/src/projector/proj_traits.rs index 0d224d5..d302104 100644 --- a/src/projector/proj_traits.rs +++ b/src/projector/proj_traits.rs @@ -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()); } From 1d8ddbe279e283c520f5ae53581b5dedc6bc2f11 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 9 Dec 2024 00:09:32 +0100 Subject: [PATCH 8/8] More refactoring and generalizing --- .gitignore | 1 + Cargo.toml | 5 ++- src/cli.rs | 68 ++++++++++++++---------------------- src/dispatch.rs | 15 +++++--- src/error.rs | 2 +- src/lib.rs | 10 ++++++ src/main.rs | 12 +++++-- src/midi.rs | 2 +- src/projector/mod.rs | 20 +++++++++++ src/projector/panasonic.rs | 3 -- src/projector/proj_traits.rs | 11 +++--- 11 files changed, 91 insertions(+), 58 deletions(-) diff --git a/.gitignore b/.gitignore index 86c1320..679f4b7 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,4 @@ Cargo.lock tarpaulin-report.html test/ .ignore +*.json diff --git a/Cargo.toml b/Cargo.toml index ca5d6ba..fc2092c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/src/cli.rs b/src/cli.rs index b2a3d36..1c4c6c9 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -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, - /// Natural timeout delay - pub delay: Option, - /// Config, holding another subset of values + #[arg(short, long)] pub config: Option, /// Create a config file from all the given arguments + #[arg(short, long)] pub save: Option, // // /// Connect to a VP @@ -63,12 +61,6 @@ pub struct CreateArgs { pub create: Option, } -/// Enumerate all the VP types -#[derive(Parser, Serialize, Deserialize, Clone, Debug)] -pub enum VPType { - Panasonic, -} - // impl From 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 { - 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 { 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 { /// 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(()) } diff --git a/src/dispatch.rs b/src/dispatch.rs index d4bf6de..5ac1194 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -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(()) } diff --git a/src/error.rs b/src/error.rs index 718fcd7..1773f98 100644 --- a/src/error.rs +++ b/src/error.rs @@ -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), diff --git a/src/lib.rs b/src/lib.rs index 2dd98c7..ee9bc3b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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"); +} diff --git a/src/main.rs b/src/main.rs index e9effe3..940e173 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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 + ) + }); } diff --git a/src/midi.rs b/src/midi.rs index d45c5f8..3cd2ec8 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -91,7 +91,7 @@ pub fn connect_loop_with_callback( // TODO: Doc pub fn create_output_interface(port: usize, name: &str) -> Arc> { 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") diff --git a/src/projector/mod.rs b/src/projector/mod.rs index 27104bf..103a4db 100644 --- a/src/projector/mod.rs +++ b/src/projector/mod.rs @@ -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") + } + } +} diff --git a/src/projector/panasonic.rs b/src/projector/panasonic.rs index 39c63ff..ec0c83d 100644 --- a/src/projector/panasonic.rs +++ b/src/projector/panasonic.rs @@ -20,8 +20,6 @@ pub struct PanasonicProjector { username: String, /// The password for the connection password: String, - /// An optionnal port for connection - port: Option, /// 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, } } diff --git a/src/projector/proj_traits.rs b/src/projector/proj_traits.rs index d302104..c701549 100644 --- a/src/projector/proj_traits.rs +++ b/src/projector/proj_traits.rs @@ -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); }