diff --git a/.gitignore b/.gitignore index 193d30e..679f4b7 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,9 @@ Cargo.lock # Added by cargo /target + +# Tarpaulin +tarpaulin-report.html +test/ +.ignore +*.json diff --git a/Cargo.toml b/Cargo.toml index 552a5ba..fc2092c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,10 +13,15 @@ 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" +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/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..7242f88 --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 5%test-coverage5% 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..1c4c6c9 --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,150 @@ +//! 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, Subcommand}; +use serde::{Deserialize, Serialize}; + +use crate::{projector::VPType, RustyMidiError}; + +#[derive(Parser, Debug)] +#[command(author, version, about, long_about = None)] +/// A struct representing command line arguments for a CLI. +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, 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, + + /// 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 + // 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, +} + +// 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 { + 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 { + log::info!("Saving config as {}: ", save_path); + File::create(save_path)? + .write_all(serde_json::to_string_pretty(&cliargs)?.as_bytes())?; + } + } + Ok(cli) +} + +/// Parse all cli arguments and loads a config from file if needed +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) => { + log::debug!( + "Updated arguments with new values \n [OLD] {:?} \n [NEW] {:?}", + cliargs, + args_new + ); + update_non_default(cliargs, args_new); + } + Err(e) => { + log::warn!("The file {} couldn't be loaded:\n {}", path, e); + } + } + } + }; + Ok(args) +} + +/// Load a given config from disk and return it as a Config +fn load_from_disk(path: &str) -> Result { + Ok(serde_json::from_str(&read_to_string(path)?)?) +} + +/// Update a parameter +macro_rules! update { + ($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, args_new: CLIArgs) { + update!(args_og, args_new, save); + update!(args_og, args_new, config); + update!(args_og, args_new, midi_interface); +} + +impl RMCArgs { + /// Save the config + pub fn save(&self) -> Result<(), RustyMidiError> { + if let RMCArgs { + command: + SubCommands::Launch( + cliargs @ CLIArgs { + midi_interface: _, + config: _, + save: Some(save_path), + }, + ), + } = &self + { + 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 new file mode 100644 index 0000000..5ac1194 --- /dev/null +++ b/src/dispatch.rs @@ -0,0 +1,82 @@ +//! 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, new_default_projector_of_type, GenericProjector}, + RustyMidiError, +}; + +/// Execute all config creation action +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) -> Result<(), RustyMidiError> { + println!("{:?}", 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((|| {})()); + }), + ), + ], + ); + Ok(()) +} diff --git a/src/error.rs b/src/error.rs index 0e79da7..1773f98 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,12 +1,24 @@ -//! Generic rusty midi commander error +//! Generic Rusty MIDI Commander error //! use thiserror::Error; -/// A generic error -/// +/// A generic error for the Rusty Midi Commander. #[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), + #[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 b1e8c4e..ee9bc3b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,8 +7,21 @@ #![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; + +/// 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 2ae34e8..940e173 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,78 +1,40 @@ -//! 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 rmc_lib::{cli_launch, create_config, init_logger}; +use std::process::exit; use clap::Parser; -use rmc_lib::{ - 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, -} +use rmc_lib::cli; fn main() { + init_logger(); + // Parse Arguments - let args = Args::parse(); - if let Args { - midi_interface: None, - } = args - { - midi::print_midi_interfaces(); - return; - } - println!("{:?}", args); - let proj = Arc::new(Mutex::new(projector::panasonic::Projector::new( - "127.0.0.1:8080", - "admin1", - "panasonic", - ))); - let proj1 = Arc::clone(&proj); - let proj2 = Arc::clone(&proj); + let args = cli::get_arguments_from_cli().unwrap_or_else(|e| { + println!("Coudln't read the command line {}", e); + // TODO: Test this + cli::RMCArgs::parse_from(vec!["-h"]); + exit(1); + }); - // 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) { + 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 132a896..103a4db 100644 --- a/src/projector/mod.rs +++ b/src/projector/mod.rs @@ -3,6 +3,24 @@ pub mod panasonic; pub mod proj_traits; -/// The standard wait time -// TODO: NO -static WAIT_TIME: f64 = 0.7; +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 ed5781e..ec0c83d 100644 --- a/src/projector/panasonic.rs +++ b/src/projector/panasonic.rs @@ -5,32 +5,52 @@ 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 username: String, /// The password for the connection 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 +75,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..c701549 100644 --- a/src/projector/proj_traits.rs +++ b/src/projector/proj_traits.rs @@ -2,8 +2,141 @@ //! //! -/// 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_default_config_file(&self, path: &str) -> Result<(), RustyMidiError> + where + Self: Sized + Serialize, + { + std::fs::File::create(path)? + .write_all(serde_json::to_string_pretty(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".to_string().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_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_pretty(&b as &dyn GenericProjector).unwrap(); + let bb_s = serde_json::to_string_pretty(&bb).unwrap(); + + assert_eq!(b_s, bb_s); + } +}