From 4078b602ecbc8130b9ea4453da46c611e81c101a Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Apr 2023 00:16:49 +0200 Subject: [PATCH 1/3] Fast draft, 50% ? --- src/main.rs | 81 ++++++++++++++++++++++++++++++++++++++++------------- src/midi.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+), 20 deletions(-) diff --git a/src/main.rs b/src/main.rs index b7881f6..73f8d48 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,10 +4,15 @@ // It should also use the commands module to send commands asynchronously. // use crate::midi::print_midi_interfaces; use clap::Parser; + use midir::MidiInput; -use midir::MidiInputPort; + +use std::sync::Arc; +use std::sync::Mutex; + use midir::MidiOutput; -use midir::MidiOutputPort; +use midir::MidiOutputConnection; + // use midir::MidiOutput; pub mod midi; @@ -17,38 +22,38 @@ pub mod midi; struct Args { /// The midi interface to select midi_interface: Option, - - /// The port to use (default 0) - #[arg(short, long)] - port: Option, } fn main() { // Parse Arguments - let mut args = Args::parse(); + let args = Args::parse(); match args { Args { midi_interface: None, - port: _, } => { midi::print_midi_interfaces(); return; } Args { midi_interface: Some(_), - port: None, - } => args.port = Some(0), - Args { - midi_interface: Some(_), - port: Some(_), } => {} } // println!("{:?}", args); - connect_with_callback(1, "Rusty MIDI Commander Input"); - loop {} + let mut output_interface = + create_output_interface(args.midi_interface.unwrap(), "Rusty MIDI Commander Output"); + cleanup(&mut output_interface.lock().unwrap()); + connect_with_callback( + args.midi_interface.unwrap(), + "Rusty MIDI Commander Input", + &mut output_interface, + ); } -pub fn connect_with_callback(port: usize, name: &str) +pub fn connect_with_callback( + port: usize, + name: &str, + out_port: &mut Arc>, +) // where // F: FnMut(u64, &[u8], &mut T) + Send + 'static, { @@ -60,6 +65,7 @@ pub fn connect_with_callback(port: usize, name: &str) // Connect to port let input_port = &input_ports[port]; + let conn_clone = Arc::clone(&out_port); let _connection = input_interface .connect( input_port, @@ -67,12 +73,47 @@ pub fn connect_with_callback(port: usize, name: &str) move |_timestamp, message, _| { // Handle MIDI messages here println!("Received MIDI message: {:?}", message); - - // let conn = &midi_co - // .output_interface - // .connect(&midi_co.output_port.clone(), "Rusty MIDI Commander Input"); + conn_clone.lock().unwrap().send(message).unwrap(); }, (), ) .unwrap(); + loop {} +} + +pub fn create_output_interface(port: usize, name: &str) -> Arc> { + let output_interface = MidiOutput::new(name).unwrap(); + let output_port = &output_interface.ports()[port]; + Arc::new(Mutex::new( + output_interface + .connect(output_port, "Rusty MIDI Commander Output") + .unwrap(), + )) +} + +pub fn cleanup( + out_port: &mut MidiOutputConnection, /*, range: &dyn std::iter::Iterator*/ +) { + // let _messages = vec![[0xB0, 0x7B, 0x00], [0xB0, 0x79, 0x00]]; + + // for message in messages.iter() { + // co.send(message).unwrap(); + // } + for n in 0..=63 { + send_note_on(out_port, n, 0); + } + for n in 82..=89 { + send_note_on(out_port, n, 0); + } +} + +pub fn send_note_on(out_port: &mut MidiOutputConnection, pitch: u8, velocity: u8) { + let msg = &[0x90, pitch, velocity]; + out_port.send(msg).unwrap(); +} + +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); + } } diff --git a/src/midi.rs b/src/midi.rs index 464178f..437d19c 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -2,6 +2,11 @@ // It should handle the low-level details of communicating with the MIDI devices. use crate::MidiInput; +use crate::MidiOutput; +use crate::MidiOutputConnection; + +use std::sync::Arc; +use std::sync::Mutex; pub fn print_midi_interfaces() { // Create MIDI input and output instances @@ -17,3 +22,72 @@ pub fn print_midi_interfaces() { println!(" {}: {}", i, midi_in.port_name(port).unwrap()); } } + +pub fn connect_with_callback( + port: usize, + name: &str, + out_port: &mut Arc>, +) +// where +// F: FnMut(u64, &[u8], &mut T) + Send + 'static, +{ + // Create MIDI input instance + let input_interface = MidiInput::new(name).unwrap(); + + // Get available MIDI input ports + let input_ports = input_interface.ports(); + + // Connect to port + let input_port = &input_ports[port]; + let conn_clone = Arc::clone(&out_port); + let _connection = input_interface + .connect( + input_port, + name, + move |_timestamp, message, _| { + // Handle MIDI messages here + println!("Received MIDI message: {:?}", message); + conn_clone.lock().unwrap().send(message).unwrap(); + }, + (), + ) + .unwrap(); + loop {} +} + +pub fn create_output_interface(port: usize, name: &str) -> Arc> { + let output_interface = MidiOutput::new(name).unwrap(); + let output_port = &output_interface.ports()[port]; + Arc::new(Mutex::new( + output_interface + .connect(output_port, "Rusty MIDI Commander Output") + .unwrap(), + )) +} + +pub fn cleanup( + out_port: &mut MidiOutputConnection, /*, range: &dyn std::iter::Iterator*/ +) { + // let _messages = vec![[0xB0, 0x7B, 0x00], [0xB0, 0x79, 0x00]]; + + // for message in messages.iter() { + // co.send(message).unwrap(); + // } + for n in 0..=63 { + send_note_on(out_port, n, 0); + } + for n in 82..=89 { + send_note_on(out_port, n, 0); + } +} + +pub fn send_note_on(out_port: &mut MidiOutputConnection, pitch: u8, velocity: u8) { + let msg = &[0x90, pitch, velocity]; + out_port.send(msg).unwrap(); +} + +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); + } +} -- 2.45.1 From f0b63d057298152f06aae0ef3ffdf9746106272d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Apr 2023 02:36:49 +0200 Subject: [PATCH 2/3] Blinking lights --- Cargo.toml | 14 +++++- src/main.rs | 110 +++++++++++++++-------------------------------- src/midi.rs | 27 ++++++++---- src/projector.rs | 71 ++++++++++++++++++++++++++++++ src/webtest.rs | 44 +++++++++++++++++++ 5 files changed, 182 insertions(+), 84 deletions(-) create mode 100644 src/projector.rs create mode 100644 src/webtest.rs diff --git a/Cargo.toml b/Cargo.toml index 9fb7c78..42e6fa8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,9 +2,21 @@ name = "rusty_midicommander" version = "0.1.0" edition = "2021" - +default-run = "rusty_midicommander" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] midir = "0.9.1" clap = { version = "4.2.1", features = ["derive","color"] } +actix-web = "4.3.1" +reqwest = { version = "0.11.16", features = ["blocking"] } +base64 = "0.21.0" +lazy_static = "1.4.0" + +[[bin]] +name = "rusty_midicommander" +path = "src/main.rs" + +[[bin]] +name = "webtest" +path = "src/webtest.rs" \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 73f8d48..51347e0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,19 +3,22 @@ // 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; +use crate::midi::cleanup; +use crate::midi::connect_loop_with_callback; +use crate::midi::create_output_interface; +use crate::midi::prepare; use clap::Parser; - -use midir::MidiInput; - use std::sync::Arc; use std::sync::Mutex; +use midir::MidiInput; + use midir::MidiOutput; use midir::MidiOutputConnection; // use midir::MidiOutput; pub mod midi; - +mod projector; /// Simple program to greet a person #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] @@ -38,82 +41,39 @@ fn main() { midi_interface: Some(_), } => {} } - // println!("{:?}", args); + println!("{:?}", args); + let proj = Arc::new(Mutex::new(projector::Projector::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_with_callback( + connect_loop_with_callback( args.midi_interface.unwrap(), "Rusty MIDI Commander Input", &mut output_interface, + vec![ + ( + 3, + Box::new(move || { + proj1.lock().unwrap().shutter_on().unwrap(); + }), + ), + ( + 4, + Box::new(move || { + proj2.lock().unwrap().shutter_on().unwrap(); + }), + ), + ], ); } - -pub fn connect_with_callback( - port: usize, - name: &str, - out_port: &mut Arc>, -) -// where -// F: FnMut(u64, &[u8], &mut T) + Send + 'static, -{ - // Create MIDI input instance - let input_interface = MidiInput::new(name).unwrap(); - - // Get available MIDI input ports - let input_ports = input_interface.ports(); - - // Connect to port - let input_port = &input_ports[port]; - let conn_clone = Arc::clone(&out_port); - let _connection = input_interface - .connect( - input_port, - name, - move |_timestamp, message, _| { - // Handle MIDI messages here - println!("Received MIDI message: {:?}", message); - conn_clone.lock().unwrap().send(message).unwrap(); - }, - (), - ) - .unwrap(); - loop {} -} - -pub fn create_output_interface(port: usize, name: &str) -> Arc> { - let output_interface = MidiOutput::new(name).unwrap(); - let output_port = &output_interface.ports()[port]; - Arc::new(Mutex::new( - output_interface - .connect(output_port, "Rusty MIDI Commander Output") - .unwrap(), - )) -} - -pub fn cleanup( - out_port: &mut MidiOutputConnection, /*, range: &dyn std::iter::Iterator*/ -) { - // let _messages = vec![[0xB0, 0x7B, 0x00], [0xB0, 0x79, 0x00]]; - - // for message in messages.iter() { - // co.send(message).unwrap(); - // } - for n in 0..=63 { - send_note_on(out_port, n, 0); - } - for n in 82..=89 { - send_note_on(out_port, n, 0); - } -} - -pub fn send_note_on(out_port: &mut MidiOutputConnection, pitch: u8, velocity: u8) { - let msg = &[0x90, pitch, velocity]; - out_port.send(msg).unwrap(); -} - -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); - } -} diff --git a/src/midi.rs b/src/midi.rs index 437d19c..79e9958 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -4,10 +4,14 @@ use crate::MidiInput; use crate::MidiOutput; use crate::MidiOutputConnection; - +use lazy_static::lazy_static; use std::sync::Arc; use std::sync::Mutex; +lazy_static! { + static ref INIT_NOTES: Vec<(u8, u8)> = vec![(3, 1), (4, 3)]; +} + pub fn print_midi_interfaces() { // Create MIDI input and output instances let midi_in = MidiInput::new("Rusty MIDI Commander Input").unwrap(); @@ -23,14 +27,12 @@ pub fn print_midi_interfaces() { } } -pub fn connect_with_callback( +pub fn connect_loop_with_callback( port: usize, name: &str, out_port: &mut Arc>, -) -// where -// F: FnMut(u64, &[u8], &mut T) + Send + 'static, -{ + calls: Vec<(u8, Box ()>)>, +) { // Create MIDI input instance let input_interface = MidiInput::new(name).unwrap(); @@ -46,8 +48,16 @@ pub fn connect_with_callback( name, move |_timestamp, message, _| { // Handle MIDI messages here + let (a, note, value) = (message[0], message[1], message[2]); println!("Received MIDI message: {:?}", message); - conn_clone.lock().unwrap().send(message).unwrap(); + // for (id, _) in calls.iter() { + // println!("{:?}", id); + // } + conn_clone + .lock() + .unwrap() + .send(&[a, note, (value + 1) % 7]) + .unwrap(); }, (), ) @@ -73,12 +83,13 @@ pub fn cleanup( // for message in messages.iter() { // co.send(message).unwrap(); // } - for n in 0..=63 { + for n in 0..=71 { send_note_on(out_port, n, 0); } for n in 82..=89 { send_note_on(out_port, n, 0); } + prepare(out_port, INIT_NOTES.to_vec()) } pub fn send_note_on(out_port: &mut MidiOutputConnection, pitch: u8, velocity: u8) { diff --git a/src/projector.rs b/src/projector.rs new file mode 100644 index 0000000..d3aedf4 --- /dev/null +++ b/src/projector.rs @@ -0,0 +1,71 @@ +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.7; + +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> { + 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> { + 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> { + self.open_url("shutter_on") + } + + pub fn shutter_off(&self) -> Result> { + self.open_url("shutter_off") + } + + pub 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)?; + let response = builder.send()?; + let body = response.text()?; + Ok(body) + } +} diff --git a/src/webtest.rs b/src/webtest.rs new file mode 100644 index 0000000..913e6bf --- /dev/null +++ b/src/webtest.rs @@ -0,0 +1,44 @@ +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"); + println!("{}", response); + HttpResponse::Ok().body(response) +} + +async fn get_osd(_req: HttpRequest) -> impl Responder { + let response = format!("OSD status for projector: ON"); + println!("{}", response); + HttpResponse::Ok().body(response) +} + +async fn debug_handler(req: HttpRequest/*,config: web::Data*/) -> HttpResponse { + if let Some(header_value) = req.headers().get("Authorization") { + if let Ok(header_value) = header_value.to_str() { + if let Some(credentials) = header_value.strip_prefix("Basic ") { + // Authentication succeeded + println!("Debug message! {:?}", general_purpose::STANDARD_NO_PAD.decode(credentials).unwrap_or("".into())); + return HttpResponse::Ok().body(general_purpose::STANDARD_NO_PAD.decode(credentials).unwrap_or("".into())); + } + } + } + + // Authentication failed + HttpResponse::Unauthorized().append_header(("WWW-Authenticate","Basic realm=\"Restricted area\"")).finish() +} + +// in your `App` configuration + +#[actix_web::main] +async fn main() -> std::io::Result<()> { + HttpServer::new(|| { + App::new().route("/debug", web::get().to(debug_handler)) + .route("/cgi-bin/proj_ctl.cgi", web::get().to(proj_ctl)) + .route("/cgi-bin/get_osd.cgi", web::get().to(get_osd)) + + }) + .bind("127.0.0.1:8080")? + .run() + .await +} \ No newline at end of file -- 2.45.1 From 4290e0da9ca78c4c09c5294b5a54fec40672b777 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 4 Apr 2023 11:50:13 +0200 Subject: [PATCH 3/3] Working Placeholder, now let's refactor EVERYTHING --- src/midi.rs | 36 ++++++++++++++++++++++++++---------- src/webtest.rs | 31 +++++++++++++++++++++---------- 2 files changed, 47 insertions(+), 20 deletions(-) diff --git a/src/midi.rs b/src/midi.rs index 79e9958..cedec07 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -31,7 +31,7 @@ pub fn connect_loop_with_callback( port: usize, name: &str, out_port: &mut Arc>, - calls: Vec<(u8, Box ()>)>, + calls: Vec<(u8, Box)>, ) { // Create MIDI input instance let input_interface = MidiInput::new(name).unwrap(); @@ -42,22 +42,38 @@ pub fn connect_loop_with_callback( // Connect to port let input_port = &input_ports[port]; let conn_clone = Arc::clone(&out_port); + // let fn_clone = Arc::clone(&calls); let _connection = input_interface .connect( input_port, name, move |_timestamp, message, _| { // Handle MIDI messages here - let (a, note, value) = (message[0], message[1], message[2]); + let (command, note, _value) = (message[0], message[1], message[2]); println!("Received MIDI message: {:?}", message); - // for (id, _) in calls.iter() { - // println!("{:?}", id); - // } - conn_clone - .lock() - .unwrap() - .send(&[a, note, (value + 1) % 7]) - .unwrap(); + 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(); + } + } + } + (_, _) => (), + } }, (), ) diff --git a/src/webtest.rs b/src/webtest.rs index 913e6bf..cf94de2 100644 --- a/src/webtest.rs +++ b/src/webtest.rs @@ -13,19 +13,30 @@ async fn get_osd(_req: HttpRequest) -> impl Responder { HttpResponse::Ok().body(response) } -async fn debug_handler(req: HttpRequest/*,config: web::Data*/) -> HttpResponse { +async fn debug_handler(req: HttpRequest /*,config: web::Data*/) -> HttpResponse { if let Some(header_value) = req.headers().get("Authorization") { if let Ok(header_value) = header_value.to_str() { if let Some(credentials) = header_value.strip_prefix("Basic ") { - // Authentication succeeded - println!("Debug message! {:?}", general_purpose::STANDARD_NO_PAD.decode(credentials).unwrap_or("".into())); - return HttpResponse::Ok().body(general_purpose::STANDARD_NO_PAD.decode(credentials).unwrap_or("".into())); - } + // Authentication succeeded + println!( + "Debug message! {:?}", + general_purpose::STANDARD_NO_PAD + .decode(credentials) + .unwrap_or("".into()) + ); + return HttpResponse::Ok().body( + general_purpose::STANDARD_NO_PAD + .decode(credentials) + .unwrap_or("".into()), + ); } } - + } + // Authentication failed - HttpResponse::Unauthorized().append_header(("WWW-Authenticate","Basic realm=\"Restricted area\"")).finish() + HttpResponse::Unauthorized() + .append_header(("WWW-Authenticate", "Basic realm=\"Restricted area\"")) + .finish() } // in your `App` configuration @@ -33,12 +44,12 @@ async fn debug_handler(req: HttpRequest/*,config: web::Data*/) -> HttpRe #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(|| { - App::new().route("/debug", web::get().to(debug_handler)) + App::new() + .route("/debug", web::get().to(debug_handler)) .route("/cgi-bin/proj_ctl.cgi", web::get().to(proj_ctl)) .route("/cgi-bin/get_osd.cgi", web::get().to(get_osd)) - }) .bind("127.0.0.1:8080")? .run() .await -} \ No newline at end of file +} -- 2.45.1