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 @@
-
+
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);
+ }
+}