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 b7881f6..51347e0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,76 +3,77 @@ // 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 std::sync::Arc; +use std::sync::Mutex; + use midir::MidiInput; -use midir::MidiInputPort; + use midir::MidiOutput; -use midir::MidiOutputPort; +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)] 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 {} -} - -pub fn connect_with_callback(port: usize, name: &str) -// 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 _connection = input_interface - .connect( - input_port, - name, - 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"); - }, - (), - ) - .unwrap(); + 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_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(); + }), + ), + ], + ); } diff --git a/src/midi.rs b/src/midi.rs index 464178f..cedec07 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -2,6 +2,15 @@ // 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; + +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 @@ -17,3 +26,95 @@ pub fn print_midi_interfaces() { println!(" {}: {}", i, midi_in.port_name(port).unwrap()); } } + +pub fn connect_loop_with_callback( + port: usize, + name: &str, + out_port: &mut Arc>, + calls: Vec<(u8, Box)>, +) { + // 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 fn_clone = Arc::clone(&calls); + let _connection = input_interface + .connect( + input_port, + name, + 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(); + } + } + } + (_, _) => (), + } + }, + (), + ) + .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..=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) { + 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/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..cf94de2 --- /dev/null +++ b/src/webtest.rs @@ -0,0 +1,55 @@ +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 +}