Compare commits

..

12 Commits

21 changed files with 754 additions and 303 deletions

6
.gitignore vendored
View File

@ -19,3 +19,9 @@ Cargo.lock
# Added by cargo
/target
# Tarpaulin
tarpaulin-report.html
test/
.ignore
*.json

View File

@ -12,12 +12,29 @@ actix-web = "4.3.1"
reqwest = { version = "0.11.16", features = ["blocking"] }
base64 = "0.21.0"
lazy_static = "1.4.0"
toml = "0.7.3"
ratatui = "0.29.0"
serde = { version = "1.0.215", features = ["derive", "alloc"] }
thiserror = "2.0.4"
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"
path = "src/main.rs"
[lib]
name = "rmc_lib"
path = "src/lib.rs"
[[bin]]
name = "webtest"
path = "src/webtest.rs"
[[bin]]
name = "viewboard"
path = "src/viewboard.rs"

View File

@ -1,8 +1,14 @@
# 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. Built on top of popular Rust MIDI libraries, it provides a simple and modular framework for defining MIDI commands and executing them asynchronously. Whether you need to control web APIs, hardware devices, or other MIDI-enabled software, Rusty MIDI Commander makes it easy to build powerful and responsive MIDI control systems.
Rusty MIDI Commander is a lightweight and flexible Rust program for sending asynchronous commands in response to MIDI input.
Built on top of popular Rust MIDI libraries, it provides a simple and modular framework
for defining MIDI commands and executing them asynchronously.
Whether you need to control web APIs, hardware devices, or other MIDI-enabled software,
Rusty MIDI Commander makes it easy to build powerful and responsive MIDI control systems.
# Macro Reading
https://veykril.github.io/tlborm/syntax-extensions/expansion.html
https://doc.rust-lang.org/book/ch19-06-macros.html
# Installation
Depends on:
- `librust-alsa-sys-dev`

1
badges/coverage.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="116" height="18" role="img" aria-label="test-coverage: 5%"><title>test-coverage: 5%</title><linearGradient id="bms-723b1f05ec0b5c8a" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-723b1f05ec0b5c8a"><rect width="116" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-723b1f05ec0b5c8a)"><rect width="87" height="18" fill="#555"/><rect x="87" width="29" height="18" fill="#e05d44"/><rect width="116" height="18" fill="url(#bms-723b1f05ec0b5c8a)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1005" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="190">5%</text><text x="1005" y="130" transform="scale(.1)" fill="#fff" textLength="190">5%</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/test.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="82" height="18" role="img" aria-label="test: passing"><title>test: passing</title><linearGradient id="bms-5402c39dce014bd3" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-5402c39dce014bd3"><rect width="82" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-5402c39dce014bd3)"><rect width="31" height="18" fill="#555"/><rect x="31" width="51" height="18" fill="#97ca00"/><rect width="82" height="18" fill="url(#bms-5402c39dce014bd3)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="165" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="210">test</text><text x="165" y="130" transform="scale(.1)" fill="#fff" textLength="210">test</text><text aria-hidden="true" x="555" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">passing</text><text x="555" y="130" transform="scale(.1)" fill="#fff" textLength="410">passing</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

1
badges/version.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="18" role="img" aria-label="version: 0.1.0"><title>version: 0.1.0</title><linearGradient id="bms-0431e50b7af7883f" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-0431e50b7af7883f"><rect width="90" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-0431e50b7af7883f)"><rect width="51" height="18" fill="#555"/><rect x="51" width="39" height="18" fill="#fe7d37"/><rect width="90" height="18" fill="url(#bms-0431e50b7af7883f)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="695" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="290">0.1.0</text><text x="695" y="130" transform="scale(.1)" fill="#fff" textLength="290">0.1.0</text></g></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1,8 +0,0 @@
[general]
midi_name = "Rusty MIDI Commander"
[projector]
address = "127.0.0.1:8080"
login = "admin1"
password = "panasonic"

150
src/cli.rs Normal file
View File

@ -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<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
// 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>,
}
// 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<RMCArgs, RustyMidiError> {
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<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) => {
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<CLIArgs, RustyMidiError> {
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(())
}
}

View File

@ -1,32 +0,0 @@
// The commands module should define the commands that the program can send.
// This module should provide functions to send each command asynchronously.
// The functions should return immediately, without waiting for the command to complete.
struct MidiData {
// Define your MIDI data struct here
}
trait Command {
fn execute(&self, midi_data: &MidiData);
}
struct CommandA;
impl Command for CommandA {
fn execute(&self, midi_data: &MidiData) {
println!("Executing CommandA with MIDI data {:?}", midi_data);
}
}
struct CommandB {
message: String,
}
impl Command for CommandB {
fn execute(&self, midi_data: &MidiData) {
println!(
"Executing CommandB with message '{}' and MIDI data {:?}",
self.message, midi_data
);
}
}

82
src/dispatch.rs Normal file
View File

@ -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(())
}

24
src/error.rs Normal file
View File

@ -0,0 +1,24 @@
//! Generic Rusty MIDI Commander error
//!
use thiserror::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),
}

27
src/lib.rs Normal file
View File

@ -0,0 +1,27 @@
//! The Rusty Midi Commander lib holds the the following parts of the project
//! - The Async Web Requesting: Connect and Disconnect of VP and send requests
//! - The TUI (optionnal): To have a "nice" review of what is happening
//! - The Dispatch: In the middle to handle all orders and communications
//! - The CLI parser: Handle both cli and config
//!
#![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");
}

View File

@ -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.
//! 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.
use crate::midi::cleanup;
use crate::midi::connect_loop_with_callback;
use crate::midi::create_output_interface;
#![warn(clippy::missing_docs_in_private_items)]
use rmc_lib::{cli_launch, create_config, init_logger};
use std::process::exit;
use clap::Parser;
use std::sync::Arc;
use std::sync::Mutex;
use midir::MidiInput;
use midir::MidiOutput;
use midir::MidiOutputConnection;
pub mod midi;
mod projector;
mod utils;
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
/// The midi interface to select
midi_input: Option<usize>,
midi_output: Option<usize>,
config: Option<String>,
}
use rmc_lib::cli;
fn main() {
init_logger();
// Parse Arguments
let args = Args::parse();
match args {
Args {
midi_input: None,
midi_output: None,
config: _,
} => {
midi::print_midi_interfaces(&"No interface selected, please select one:".into());
return;
}
Args {
midi_input: Some(_),
midi_output: Some(_),
config: _,
} => {}
Args {
midi_input: _,
midi_output: None,
config: _,
} => {
midi::print_midi_interfaces(&"No interface selected, please select one:".into());
return;
}
_ => {}
}
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);
});
// let config_text = &args.config;
println!("[INFO] Connecting with args: {:?}", args);
let proj = Arc::new(Mutex::new(projector::Projector::new(
"127.0.0.1:8080",
"admin1",
"panasonic",
)));
let mut output_interface =
create_output_interface(args.midi_output, "Rusty MIDI Commander Output");
cleanup(&mut output_interface.lock().unwrap());
connect_loop_with_callback(
args.midi_input.unwrap(),
"Rusty MIDI Commander Input",
&mut output_interface,
list_actions!(proj, 3, shutter_on, 4, shutter_off),
);
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
)
});
}

View File

@ -1,57 +1,40 @@
// 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 lazy_static::lazy_static;
use std::sync::Arc;
use std::sync::Mutex;
use std::{
sync::{Arc, Mutex},
thread::sleep,
time::Duration,
};
use lazy_static::lazy_static;
use midir::{MidiInput, MidiOutput, MidiOutputConnection};
// TODO: All this should be generic with an impl for every midi pad, possibly from a config file
// As: GenericFromFile, GenericAkai, etc...
// TODO: NO
lazy_static! {
static ref INIT_NOTES: Vec<(u8, u8)> = vec![(3, 1), (4, 3)];
}
pub fn print_midi_interfaces(error_message: &String) {
// TODO: Meh ?
pub fn print_midi_interfaces() {
// Create MIDI input and output instances
let midi_in = MidiInput::new("Rusty MIDI Commander Input").unwrap();
let midi_out = MidiOutput::new("Rusty MIDI Commander Output").unwrap();
// Get available MIDI input and output ports
let input_ports = midi_in.ports();
let output_ports = midi_out.ports();
// let output_ports = midi_out.ports();
// Print available input ports
match (input_ports.len(), output_ports.len()) {
(0, 0) => {
println!(
"[ERROR] No MIDI interface was found, please ensure a MIDI interface is plugged in"
);
return;
}
(_, 0) => println!("No MIDI output interface was found, no feedback will be sent"),
(0, _) => {
println!(
"[ERROR] No MIDI input interface was found, please ensure a MIDI interface is plugged in"
);
return;
}
(_, _) => println!("{}", error_message),
}
println!("[Input]");
println!("No interface selected, please select one:");
for (i, port) in input_ports.iter().enumerate() {
println!(" {}: {}", i, midi_in.port_name(port).unwrap());
}
if output_ports.len() == 0 {
return;
}
println!("[Output]");
for (i, port) in output_ports.iter().enumerate() {
println!(" {}: {}", i, midi_out.port_name(port).unwrap());
println!(" {}: {}", i, midi_in.port_name(port).unwrap());
}
}
// Acceptable, should be more generic maybe ?
pub fn connect_loop_with_callback(
port: usize,
name: &str,
@ -65,13 +48,10 @@ pub fn connect_loop_with_callback(
let input_ports = input_interface.ports();
// Connect to port
if port >= input_ports.len() {
print_midi_interfaces(&"[ERROR] Midi input port is out of range".to_string());
std::process::exit(1);
}
let input_port = &input_ports[port];
let conn_clone = Arc::clone(&out_port);
// let fn_clone = Arc::clone(&calls);
let conn_clone = Arc::clone(out_port);
// TODO: Unacceptable
let _connection = input_interface
.connect(
input_port,
@ -79,67 +59,55 @@ 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);
match (command, note) {
(144, 3..=4) => {
for (id, f) in calls.iter() {
if note == *id {
println!("match");
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();
}
//println!("Received MIDI message: {:?}", message);
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();
}
}
(_, _) => (),
}
},
(),
)
.unwrap();
loop {}
loop {
sleep(Duration::from_millis(300));
}
}
// Currently doesn't accept virtual output or no output
pub fn create_output_interface(
port: Option<usize>,
name: &str,
) -> Arc<Mutex<MidiOutputConnection>> {
let output_interface = match port {
None => MidiOutput::new(name).unwrap(),
Some(_) => MidiOutput::new(name).unwrap(),
};
if port.unwrap() >= output_interface.ports().len() {
print_midi_interfaces(
&"[ERROR] The midi output interface selected is out of bounds".into(),
);
std::process::exit(1);
}
let output_port = &output_interface.ports()[port.unwrap()];
// 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]; // TODO: This error is ideous
Arc::new(Mutex::new(
output_interface.connect(output_port, name).unwrap(),
output_interface
.connect(output_port, "Rusty MIDI Commander Output")
.unwrap(),
))
}
// TODO: A more generic cleanup
pub fn cleanup(
out_port: &mut MidiOutputConnection, /*, range: &dyn std::iter::Iterator<Item = usize>*/
) {
// let _messages = vec![[0xB0, 0x7B, 0x00], [0xB0, 0x79, 0x00]];
// for message in messages.iter() {
// co.send(message).unwrap();
// }
// out_port
// .send(&[0xF0, 0x47, 0x7F, 0x29, 0x60, 0x00, 0x40, 0x08, 0x00, 0xF7])
// .unwrap();
for n in 0..=71 {
send_note_on(out_port, n, 0);
}
@ -149,11 +117,13 @@ pub fn cleanup(
prepare(out_port, INIT_NOTES.to_vec())
}
// TODO: more generic interface
pub fn send_note_on(out_port: &mut MidiOutputConnection, pitch: u8, velocity: u8) {
let msg = &[0x90, pitch, velocity];
out_port.send(msg).unwrap();
}
// TODO: doc
pub fn prepare(out_port: &mut MidiOutputConnection, notes_values: Vec<(u8, u8)>) {
for (note, val) in notes_values.iter() {
send_note_on(out_port, *note, *val);

View File

@ -1,73 +0,0 @@
#![allow(dead_code)]
use base64::{engine::general_purpose, Engine as _};
use reqwest::blocking::{Client, RequestBuilder};
use std::error::Error;
use std::time::Duration;
static WAIT_TIME: f64 = 0.5;
pub struct Projector {
ip: String,
username: String,
password: String,
}
impl Projector {
pub fn new(ip: &str, username: &str, password: &str) -> Projector {
Projector {
ip: ip.to_string(),
username: username.to_string(),
password: password.to_string(),
}
}
fn make_auth_header(&self) -> String {
let auth = format!("{}:{}", self.username, self.password);
let encoded_auth = general_purpose::STANDARD_NO_PAD.encode(auth);
format!("Basic {}", encoded_auth)
}
fn make_url(&self, cmd: &str) -> String {
format!(
"http://{}/cgi-bin/proj_ctl.cgi?key={}&lang=e&osd=off",
self.ip, cmd
)
}
fn make_request(&self, url: &str, headers: &str) -> Result<RequestBuilder, Box<dyn Error>> {
let client = Client::new();
let builder = client
.get(url)
.header("Authorization", headers)
.timeout(Duration::from_secs_f64(WAIT_TIME));
Ok(builder)
}
pub fn open_url(&self, cmd: &str) -> Result<String, Box<dyn Error>> {
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)
}
pub fn shutter_on(&self) -> Result<String, Box<dyn Error>> {
self.open_url("shutter_on")
}
pub fn shutter_off(&self) -> Result<String, Box<dyn Error>> {
self.open_url("shutter_off")
}
pub fn get_osd(&self) -> Result<String, Box<dyn Error>> {
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)?;
let response = builder.send()?;
let body = response.text()?;
Ok(body)
}
}

26
src/projector/mod.rs Normal file
View File

@ -0,0 +1,26 @@
//! Contains all projector related commands
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")
}
}
}

101
src/projector/panasonic.rs Normal file
View File

@ -0,0 +1,101 @@
//! A panasonic webpage interface implementation
//!
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::proj_traits::{GenericProjector, RequestReturn};
/// A projector and all info to connect to it
#[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 timeout
timeout: f64,
}
#[typetag::serde]
impl GenericProjector for PanasonicProjector {
fn connect(&self) -> Result<RequestReturn, RustyMidiError> {
Ok(String::new().into())
}
/// A request to turn the projector on
fn shutter_on(&self) -> Result<RequestReturn, RustyMidiError> {
self.open_url("shutter_on")
}
/// A request to turn the projector off
fn shutter_off(&self) -> Result<RequestReturn, RustyMidiError> {
self.open_url("shutter_off")
}
}
impl PanasonicProjector {
/// Create a new projector with the basic information
// 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(),
timeout: 0.7,
}
}
/// Make the authentication header
fn make_auth_header(&self) -> String {
let auth = format!("{}:{}", self.username, self.password);
let encoded_auth = general_purpose::STANDARD_NO_PAD.encode(auth);
format!("Basic {}", encoded_auth)
}
/// Make a control command
fn make_url(&self, cmd: &str) -> String {
format!(
"http://{}/cgi-bin/proj_ctl.cgi?key={}&lang=e&osd=off",
self.ip, cmd
)
}
/// Make a request from a url
fn make_request(&self, url: &str, headers: &str) -> Result<RequestBuilder, RustyMidiError> {
let client = Client::new();
let builder = client
.get(url)
.header("Authorization", headers)
.timeout(Duration::from_secs_f64(self.timeout));
Ok(builder)
}
/// Make the actual request
fn open_url(&self, cmd: &str) -> Result<RequestReturn, RustyMidiError> {
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.into())
}
/// The request to the the osd
fn get_osd(&self) -> Result<String, RustyMidiError> {
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)?;
let response = builder.send()?;
let body = response.text()?;
Ok(body)
}
}

View File

@ -0,0 +1,142 @@
//! Generic trait for a projector
//!
//!
use crate::RustyMidiError;
use serde::Serialize;
use std::fmt::Debug;
use std::io::{Read, Write};
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct RequestReturn {
pub message: String,
}
impl From<String> 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<Box<dyn GenericProjector>, 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<RequestReturn, RustyMidiError>;
/// Turns the shutter on
///
/// Returns an error on disconnection or if the command failed
fn shutter_on(&self) -> Result<RequestReturn, RustyMidiError>;
/// Turns the shutter off
///
/// Returns an error on disconnection or if the command failed
fn shutter_off(&self) -> Result<RequestReturn, RustyMidiError>;
}
/// A lot of advanced methods
pub trait AdvancedCommands {
/// The return object type
type RObject;
/// Shutdown the VP
fn shutdown(&self) -> Result<Self::RObject, RustyMidiError>;
/// Turn on the VP
fn turn_on(&self) -> Result<Self::RObject, RustyMidiError>;
/// Get the OSD
fn get_osd(&self) -> Result<Self::RObject, RustyMidiError>;
}
#[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<super::RequestReturn, crate::RustyMidiError> {
Ok(super::RequestReturn {
message: "connected".into(),
})
}
fn shutter_on(&self) -> Result<super::RequestReturn, crate::RustyMidiError> {
Ok(super::RequestReturn {
message: "opened".into(),
})
}
fn shutter_off(&self) -> Result<super::RequestReturn, crate::RustyMidiError> {
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);
}
}

View File

@ -1,30 +0,0 @@
// The utils module should provide utility functions that are used throughout the program.
// These functions could include functions to convert MIDI messages to and from human-readable formats, or to handle errors.
#[macro_export]
macro_rules! list_actions {
($proj:ident, $($id:literal, $action:ident),+ ) => {
{
let mut temp_vec:Vec<(u8, Box<(dyn Fn() + Send + 'static)>)> = Vec::new();
$(
let proj = Arc::clone(&$proj);
temp_vec.push((
$id,
Box::new(move || {
match proj.lock().unwrap().$action() {
Ok(_) => {}
Err(e) => {
println!(
"[ERROR] An error occurend while sending a ({}) message",
stringify!($action)
);
println!(" {}", e)
}
};
}),
));
)+
temp_vec
}
};
}

78
src/viewboard.rs Normal file
View File

@ -0,0 +1,78 @@
#![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<Mutex<MidiOutputConnection>>,
/// The list of available notes
pub list_notes: Vec<u8>,
/// The list of current notes values (if no other source has sent changes)
pub current_values: Vec<u8>,
/// The list of notes about to be sent
pub future_values: Vec<u8>,
/// The state of the board, wether it is visible or not
pub live: bool,
}
impl RecvCommander<'_> {
fn new(output_interface: &mut Arc<Mutex<MidiOutputConnection>>) -> RecvCommander {
// Assert all vectors are of the same size
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 {
sleep(Duration::from_millis(500));
}
}

View File

@ -2,13 +2,13 @@ use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use base64::{engine::general_purpose, Engine as _};
async fn proj_ctl(_req: HttpRequest) -> impl Responder {
let response = format!("Projector received command");
let response = "Projector received command".to_string();
println!("{}", response);
HttpResponse::Ok().body(response)
}
async fn get_osd(_req: HttpRequest) -> impl Responder {
let response = format!("OSD status for projector: ON");
let response = "OSD status for projector: ON".to_string();
println!("{}", response);
HttpResponse::Ok().body(response)
}