From a791514cbe2aacea80da1c305f7747edd5a713f3 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 8 Jun 2023 20:34:09 +0200 Subject: [PATCH 01/48] better error message for config issues --- src/conf.rs | 4 ++-- src/errors.rs | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/conf.rs b/src/conf.rs index 02a4c15..fe5e762 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -1,6 +1,6 @@ use config::Config; use serde::{Serialize,Deserialize}; -use crate::errors::LJResult; +use crate::errors::{LJError,LJResult}; use crate::transformer; #[derive(Serialize, Deserialize, Debug, Clone)] @@ -46,7 +46,7 @@ impl Conf { .add_source(config::File::with_name(path)) .build()?; - let conf : Conf = settings.try_deserialize()?; + let conf : Conf = settings.try_deserialize().map_err(LJError::Config)?; Ok(conf) } diff --git a/src/errors.rs b/src/errors.rs index 45363e5..ff40f33 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,11 +1,13 @@ use std::error::Error; use std::fmt; use redis::RedisError; +use config::ConfigError; pub type LJResult = Result>; #[derive(Debug)] pub enum LJError { + Config(ConfigError), RedisConnect(RedisError), HeliosDeviceMissing } @@ -15,6 +17,10 @@ impl fmt::Display for LJError { use LJError::*; match self { + Config(err) => { + write!(f, "unable to load config file: {err}") + }, + RedisConnect(err) => { write!(f, "unable to connect to redis server: {err}") }, From 0f72b64a15ee2668f2684f6197d01c60f565d8a5 Mon Sep 17 00:00:00 2001 From: Lapin Raving Date: Thu, 8 Jun 2023 22:13:42 +0200 Subject: [PATCH 02/48] fix: add a value do the redis db to draw According to the new redis db value. --- examples/simple_client.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/examples/simple_client.rs b/examples/simple_client.rs index a62c4cc..3055c24 100644 --- a/examples/simple_client.rs +++ b/examples/simple_client.rs @@ -9,6 +9,10 @@ fn do_something() -> redis::RedisResult<()> { let client = Client::open("redis://127.0.0.1/")?; let mut con: Connection = client.get_connection()?; + let _ = con.set("/order/0", 0)?; + + + /* do something here */ //let val : String = con.get("/pl/0/0")?; let _ = con.set("/pl/0/0", "[(150.0, 230.0, 65280), \ @@ -16,7 +20,7 @@ fn do_something() -> redis::RedisResult<()> { (230.0, 170.0, 65280), \ (210.0, 230.0, 65280), \ (150.0, 230.0, 65280)]")?; - + Ok(()) } From 08e78b9a8815abbf033b0f31e3f9d36207b753f6 Mon Sep 17 00:00:00 2001 From: Lapin Raving Date: Thu, 8 Jun 2023 22:34:03 +0200 Subject: [PATCH 03/48] feat: adding somme new transformation * Rotate to rotate the image, !! Some point could be outside of the 0-4096 range on x and y !! you should parameter a center and an angle. All the point will move around the center. The angle is un degre. * Flip vertical: flip all the point verticaly. You should parameter an height where all point will flip * Flip horizontaly. You should parameter an X corrodinate where all point will flip around. --- src/transformer.rs | 6 +++++ src/transformer/flip_horizontal.rs | 28 +++++++++++++++++++++ src/transformer/flip_vertical.rs | 28 +++++++++++++++++++++ src/transformer/rotate.rs | 39 ++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+) create mode 100644 src/transformer/flip_horizontal.rs create mode 100644 src/transformer/flip_vertical.rs create mode 100644 src/transformer/rotate.rs diff --git a/src/transformer.rs b/src/transformer.rs index 564b981..c31b947 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -1,12 +1,18 @@ //pub mod common; mod translate; mod replicate; +mod rotate; +mod flip_horizontal; +mod flip_vertical; use crate::point::Point; // re-export transformers to be abe to use it directly from transformer:: pub use translate::Translate; pub use replicate::Replicate; +pub use rotate::Rotate; +pub use flip_horizontal::FlipHorizontal; +pub use flip_vertical::FlipVertical; pub trait Transformers { fn apply(&self, point_list: &[Point]) -> Vec; diff --git a/src/transformer/flip_horizontal.rs b/src/transformer/flip_horizontal.rs new file mode 100644 index 0000000..2157ddd --- /dev/null +++ b/src/transformer/flip_horizontal.rs @@ -0,0 +1,28 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use serde::{Serialize,Deserialize}; + +/// Flip Horizontal + +#[derive(Serialize,Deserialize,Debug,Clone,Copy)] +pub struct FlipHorizontal { + x: f32, +} + +impl FlipHorizontal { + pub fn new(x: f32) -> Self { + Self {x} + } +} + +impl Transformers for FlipHorizontal { + fn apply(&self, point_list: &[Point]) -> Vec { + point_list.iter() + .map(| pt | { + let dx = pt.x - self.x; + Point { x: dx - 2. * dx, + ..*pt + } + }).collect() + } +} diff --git a/src/transformer/flip_vertical.rs b/src/transformer/flip_vertical.rs new file mode 100644 index 0000000..b4f6d59 --- /dev/null +++ b/src/transformer/flip_vertical.rs @@ -0,0 +1,28 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use serde::{Serialize,Deserialize}; + +/// Flip Vertical + +#[derive(Serialize,Deserialize,Debug,Clone,Copy)] +pub struct FlipVertical { + y: f32, +} + +impl FlipVertical { + pub fn new(y: f32) -> Self { + Self {y} + } +} + +impl Transformers for FlipVertical { + fn apply(&self, point_list: &[Point]) -> Vec { + point_list.iter() + .map(| pt | { + let dy = pt.y - self.y; + Point { y: dy - 2. * dy, + ..*pt + } + }).collect() + } +} diff --git a/src/transformer/rotate.rs b/src/transformer/rotate.rs new file mode 100644 index 0000000..ca574ba --- /dev/null +++ b/src/transformer/rotate.rs @@ -0,0 +1,39 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use serde::{Serialize,Deserialize}; +use std::f32::consts::PI; + +/// Rotate + +#[derive(Serialize,Deserialize,Debug,Clone,Copy)] +pub struct Rotate { + cx: f32, + cy: f32, + angle: f32, + +} + +impl Rotate { + pub fn new(cx: f32, cy: f32, angle: f32) -> Self { + Self { cx, cy, angle: angle / 180. * PI} + } +} + +impl Transformers for Rotate { + fn apply(&self, point_list: &[Point]) -> Vec { + point_list.iter() + .map(| pt | { + let dx = (pt.x - self.cx); + let dy = (pt.y - self.cy); + let cos = self.angle.cos(); + let sin = self.angle.sin(); + let x = (dx * cos - dy * sin) + self.cx; + let y = (dx * sin + dy * cos) + self.cy; + Point { x, + y, + ..*pt + } + }).collect() + } +} + From 81de6728fc12d2ec50f511c8b534f615173722fc Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 10 Jun 2023 17:08:08 +0200 Subject: [PATCH 04/48] fix warnings --- src/main.rs | 2 +- src/transformer/rotate.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 669642c..e37a2b8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,7 +73,7 @@ fn run_all() -> LJResult<()> { let frame = get_next_frame(&config, &transformers, &mut rs, order == Order::Black)?; // For now, draw all the time - tracer.draw(frame, 10_000)?; + tracer.draw(frame, 40_000)?; } info!("Exiting, stoping device."); diff --git a/src/transformer/rotate.rs b/src/transformer/rotate.rs index ca574ba..177a0d3 100644 --- a/src/transformer/rotate.rs +++ b/src/transformer/rotate.rs @@ -23,8 +23,8 @@ impl Transformers for Rotate { fn apply(&self, point_list: &[Point]) -> Vec { point_list.iter() .map(| pt | { - let dx = (pt.x - self.cx); - let dy = (pt.y - self.cy); + let dx = pt.x - self.cx; + let dy = pt.y - self.cy; let cos = self.angle.cos(); let sin = self.angle.sin(); let x = (dx * cos - dy * sin) + self.cx; From 9a5db444a01ad2a002b4d244a00957cb2d3850fc Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 10 Jun 2023 18:47:04 +0200 Subject: [PATCH 05/48] cleanup and new grid --- src/conf.rs | 19 ++++++++-- src/main.rs | 9 +++-- src/transformer.rs | 2 ++ src/transformer/flip_horizontal.rs | 6 ---- src/transformer/flip_vertical.rs | 6 ---- src/transformer/grid.rs | 56 ++++++++++++++++++++++++++++++ src/transformer/rotate.rs | 6 ---- src/transformer/translate.rs | 12 ++----- 8 files changed, 83 insertions(+), 33 deletions(-) create mode 100644 src/transformer/grid.rs diff --git a/src/conf.rs b/src/conf.rs index fe5e762..01827c3 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -36,7 +36,16 @@ pub enum TransformConf { #[serde(rename = "translate")] Translate(transformer::Translate), #[serde(rename = "replicate")] - Replicate(transformer::Replicate) + Replicate(transformer::Replicate), + #[serde(rename = "rotate")] + Rotate(transformer::Rotate), + #[serde(rename = "flip_horizontal")] + FlipH(transformer::FlipHorizontal), + #[serde(rename = "flip_vertical")] + FlipV(transformer::FlipVertical), + #[serde(rename = "grid")] + Grid(transformer::Grid) + } @@ -55,7 +64,11 @@ impl Conf { for t in &self.transformers { let t : Box = match t { TransformConf::Translate(t) => Box::new(*t), - TransformConf::Replicate(r) => Box::new(*r) + TransformConf::Replicate(r) => Box::new(*r), + TransformConf::Rotate(r) => Box::new(*r), + TransformConf::FlipH(r) => Box::new(*r), + TransformConf::FlipV(r) => Box::new(*r), + TransformConf::Grid(r) => Box::new(*r) }; v.push(t); } @@ -69,7 +82,7 @@ impl Conf { redis_url: "redis://127.0.0.1:6379/".to_string(), dac: DacFamily::Helios(HeliosConf { id: 0 }), transformers: vec![ - TransformConf::Translate(transformer::Translate::new(2000.0,2000.0)), + TransformConf::Translate(transformer::Translate { x: 2000.0, y: 2000.0 } ), TransformConf::Replicate(transformer::Replicate::Until(48)) ] }; diff --git a/src/main.rs b/src/main.rs index e37a2b8..95c0dfa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,7 +73,7 @@ fn run_all() -> LJResult<()> { let frame = get_next_frame(&config, &transformers, &mut rs, order == Order::Black)?; // For now, draw all the time - tracer.draw(frame, 40_000)?; + tracer.draw(frame, 2_000)?; } info!("Exiting, stoping device."); @@ -102,8 +102,11 @@ fn get_next_frame( rs: &mut RedisCtrl, _black: bool, ) -> LJResult> { - let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; - let mut line: Vec = line.into_iter().map(|tpl| tpl.into()).collect(); + //let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; + let line = vec![(300.0,200.0,0),(500.0,200.0,65280),(500.0,400.0,65280),(300.0,400.0,65280),(300.0,200.0,65280),(300.0,200.0,0),(200.0,100.0,0),(600.0,100.0,65280),(600.0,500.0,65280),(200.0,500.0,65280),(200.0,100.0,65280)]; + + let mut line: Vec = line.into_iter().map(|tpl| tpl.into()).collect(); + for transformer in transformers { line = transformer.apply(&line); } diff --git a/src/transformer.rs b/src/transformer.rs index c31b947..19d4445 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -4,6 +4,7 @@ mod replicate; mod rotate; mod flip_horizontal; mod flip_vertical; +mod grid; use crate::point::Point; @@ -13,6 +14,7 @@ pub use replicate::Replicate; pub use rotate::Rotate; pub use flip_horizontal::FlipHorizontal; pub use flip_vertical::FlipVertical; +pub use grid::Grid; pub trait Transformers { fn apply(&self, point_list: &[Point]) -> Vec; diff --git a/src/transformer/flip_horizontal.rs b/src/transformer/flip_horizontal.rs index 2157ddd..d156739 100644 --- a/src/transformer/flip_horizontal.rs +++ b/src/transformer/flip_horizontal.rs @@ -9,12 +9,6 @@ pub struct FlipHorizontal { x: f32, } -impl FlipHorizontal { - pub fn new(x: f32) -> Self { - Self {x} - } -} - impl Transformers for FlipHorizontal { fn apply(&self, point_list: &[Point]) -> Vec { point_list.iter() diff --git a/src/transformer/flip_vertical.rs b/src/transformer/flip_vertical.rs index b4f6d59..fc741c7 100644 --- a/src/transformer/flip_vertical.rs +++ b/src/transformer/flip_vertical.rs @@ -9,12 +9,6 @@ pub struct FlipVertical { y: f32, } -impl FlipVertical { - pub fn new(y: f32) -> Self { - Self {y} - } -} - impl Transformers for FlipVertical { fn apply(&self, point_list: &[Point]) -> Vec { point_list.iter() diff --git a/src/transformer/grid.rs b/src/transformer/grid.rs new file mode 100644 index 0000000..25258ff --- /dev/null +++ b/src/transformer/grid.rs @@ -0,0 +1,56 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use serde::{Serialize,Deserialize}; + +/// Translate + +#[derive(Serialize,Deserialize,Debug,Clone,Copy)] +pub struct Grid { + width: f32, + height: f32 +} + +fn square_box(size: f32, color: u32) -> Vec<(f32, f32, u32)> { + vec![ + (-size, -size, 0), + (-size, -size, color), + + (0.0, -size, color), + (0.0, -size, color), + + (size, -size, color), + (size, -size, color), + + (size, 0.0, color), + (size, 0.0, color), + + (size, size, color), + (size, size, color), + + (0.0, size, color), + (0.0, size, color), + + (-size, size, color), + (-size, size, color), + + (-size, 0.0, color), + (-size, 0.0, color), + + (-size, -size, color), + (-size, -size, color), + + (-size, -size, 0) + ] +} + +impl Transformers for Grid { + fn apply(&self, _point_list: &[Point]) -> Vec { + let mut sq1 = square_box(1000.0, 255 << 8); + let mut line = square_box(2000.0, 255); + line.append(&mut sq1); + + let line: Vec = line.into_iter() + .map(|tpl| tpl.into()).collect(); + line + } +} diff --git a/src/transformer/rotate.rs b/src/transformer/rotate.rs index 177a0d3..2cb9cac 100644 --- a/src/transformer/rotate.rs +++ b/src/transformer/rotate.rs @@ -13,12 +13,6 @@ pub struct Rotate { } -impl Rotate { - pub fn new(cx: f32, cy: f32, angle: f32) -> Self { - Self { cx, cy, angle: angle / 180. * PI} - } -} - impl Transformers for Rotate { fn apply(&self, point_list: &[Point]) -> Vec { point_list.iter() diff --git a/src/transformer/translate.rs b/src/transformer/translate.rs index a36f272..c3f4fec 100644 --- a/src/transformer/translate.rs +++ b/src/transformer/translate.rs @@ -6,18 +6,12 @@ use serde::{Serialize,Deserialize}; #[derive(Serialize,Deserialize,Debug,Clone,Copy)] pub struct Translate { - x: f32, - y: f32 -} - -impl Translate { - pub fn new(x: f32, y: f32) -> Self { - Self { x, y } - } + pub x: f32, + pub y: f32 } impl Transformers for Translate { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point]) -> Vec { point_list.iter() .map(| pt | { Point { x: pt.x + self.x, From 883c72ff24090401eb9f01e8e1ce3ad8d2b79c4b Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 10 Jun 2023 18:53:10 +0200 Subject: [PATCH 06/48] cleanups --- src/main.rs | 8 ++++---- src/transformer/rotate.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index 95c0dfa..020dce3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -102,10 +102,10 @@ fn get_next_frame( rs: &mut RedisCtrl, _black: bool, ) -> LJResult> { - //let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; - let line = vec![(300.0,200.0,0),(500.0,200.0,65280),(500.0,400.0,65280),(300.0,400.0,65280),(300.0,200.0,65280),(300.0,200.0,0),(200.0,100.0,0),(600.0,100.0,65280),(600.0,500.0,65280),(200.0,500.0,65280),(200.0,100.0,65280)]; - - let mut line: Vec = line.into_iter().map(|tpl| tpl.into()).collect(); + let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; + let mut line: Vec = line.into_iter() + .map(|tpl| tpl.into()) + .collect(); for transformer in transformers { line = transformer.apply(&line); diff --git a/src/transformer/rotate.rs b/src/transformer/rotate.rs index 2cb9cac..60fc109 100644 --- a/src/transformer/rotate.rs +++ b/src/transformer/rotate.rs @@ -1,7 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; use serde::{Serialize,Deserialize}; -use std::f32::consts::PI; +//use std::f32::consts::PI; /// Rotate From 526a78428baeb617d823ef528705254e153f854b Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 12 Jun 2023 19:23:59 +0200 Subject: [PATCH 07/48] feat; add device status --- Cargo.toml | 1 + src/device.rs | 50 +++++++++++------ src/device/helios.rs | 20 ++++--- src/main.rs | 3 +- src/redis_ctrl.rs | 125 +++++++++++++++++++++++++------------------ 5 files changed, 126 insertions(+), 73 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 18f311d..9789221 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +chrono = "0.4.26" config = "0.13.3" ctrlc = "3.4.0" env_logger = "0.10.0" diff --git a/src/device.rs b/src/device.rs index d85d95a..0947bf2 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,10 +1,12 @@ -use crate::point::Point; mod helios; -use crate::conf::{Conf, DacFamily, /*EtherDreamConf, HeliosConf*/}; +use std::fmt; +use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/}; use crate::device::helios::HeliosDevice; use crate::errors::LJResult; +use crate::point::Point; +use serde::Serialize; /* self.protocol_version, @@ -18,22 +20,40 @@ self.fullness, self.point_rate, self.point_count */ - - -pub struct Status { - pub active: bool, - pub last_traced_at: String, - pub properties: Vec +#[repr(u8)] +#[derive(Debug, PartialEq, Serialize, Copy, Clone)] +pub enum PlaybackState { + IDLE = 0, + PREPARE, + PLAYING, +} +impl fmt::Display for PlaybackState { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self) + } } +#[derive(Debug)] +pub struct Status { + pub last_traced_at: String, + pub properties: Vec, + pub playback_state: PlaybackState, + pub capacity: u16, + pub lack: String +} + +// /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) +// /cap/lasernumber number of empty points sent to fill etherdream buffer (up to 1799) +// /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. + pub trait Device { - fn status( &self ) -> Status; - fn draw( - &mut self, - frame: Vec, - speed: u32, - ) -> LJResult<()> ; - fn stop(&mut self) -> LJResult<()>; + fn status(&self) -> Status; + fn draw( + &mut self, + frame: Vec, + speed: u32, + ) -> LJResult<()>; + fn stop(&mut self) -> LJResult<()>; } pub fn device_factory(config: &Conf) -> LJResult> { diff --git a/src/device/helios.rs b/src/device/helios.rs index f607bb8..2e1041c 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -11,13 +11,16 @@ use helios_dac::{ // Point as HeliosPoint, }; use crate::conf::HeliosConf; -use crate::device::{Device, Status}; +use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::Point; pub struct HeliosDevice { pub conf: HeliosConf, dac: NativeHeliosDac, + sent_points: u16, + state: PlaybackState, + lack: String } impl HeliosDevice { @@ -29,16 +32,20 @@ impl HeliosDevice { return Err(Box::new(LJError::HeliosDeviceMissing)); }; let dac = device.open()?; - Ok(Self { conf: (*conf).clone(), dac }) + Ok(Self { conf: (*conf).clone(), dac, sent_points: 0, state: PlaybackState::IDLE, lack: "".to_string() }) } } impl Device for HeliosDevice { fn status(&self) -> Status { + + let lack = self.lack.clone(); Status { - active: true, last_traced_at: "now".to_string(), properties: vec!["foo".to_string()], + playback_state: self.state, + capacity: self.sent_points, + lack, } } @@ -46,12 +53,13 @@ impl Device for HeliosDevice { line: Vec, speed: u32, ) -> LJResult<()> { - while let Ok(DeviceStatus::NotReady) = self.dac.status() { - } + while let Ok(DeviceStatus::NotReady) = self.dac.status() {} let points: Vec = line.into_iter().map(|p| p.into()).collect(); - let frame = Frame::new(speed, points); + let frame = Frame::new(speed, points.clone()); self.dac.write_frame(frame.clone())?; + self.sent_points = points.len() as u16; + self.state = PlaybackState::PLAYING; Ok(()) } diff --git a/src/main.rs b/src/main.rs index 020dce3..2cf7953 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,7 +45,7 @@ fn run_all() -> LJResult<()> { info!("{:?}", config); // Setup Redis Service - let mut rs = RedisCtrl::new(&config.redis_url)?; + let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; // Setup handler for interrupt Signals let running = Arc::new(AtomicBool::new(true)); @@ -65,6 +65,7 @@ fn run_all() -> LJResult<()> { // Dispatch based on redis requests while running.load(Ordering::SeqCst) { + rs.set_status( tracer.status())?; let order = rs.get_order(config.laser_id)?; if order != Order::Draw { info!("Order: {:?}", order); diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 7ae8d9f..448ed43 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -1,76 +1,99 @@ use redis::{Client, Commands, Connection}; use ron::de::from_str; -use crate::errors::{LJError,LJResult}; +use crate::device::Status; +use crate::errors::{LJError, LJResult}; #[repr(u8)] #[derive(Debug, PartialEq)] pub enum Order { - Draw = 0, - Edh, //homography - Black, - Grid, - Resampler, - ClientKey, - Intensity, - Kpps, - ColorBalance, + Draw = 0, + Edh, + //homography + Black, + Grid, + Resampler, + ClientKey, + Intensity, + Kpps, + ColorBalance, } impl TryFrom for Order { - type Error = String; + type Error = String; - fn try_from(value: u8) -> Result { - use Order::*; + fn try_from(value: u8) -> Result { + use Order::*; - if value > 8 { - return Err("order out of range".to_string()); + if value > 8 { + return Err("order out of range".to_string()); + } + + Ok(match value { + 0 => Draw, + 1 => Edh, + 2 => Black, + 3 => Grid, + 4 => Resampler, + 5 => ClientKey, + 6 => Intensity, + 7 => Kpps, + 8 => ColorBalance, + _ => unreachable!() + }) } - - Ok(match value { - 0 => Draw, - 1 => Edh, - 2 => Black, - 3 => Grid, - 4 => Resampler, - 5 => ClientKey, - 6 => Intensity, - 7 => Kpps, - 8 => ColorBalance, - _ => unreachable!() - }) - } } pub type Line = Vec<(f32, f32, u32)>; pub struct RedisCtrl { - pub client: Client, - pub connection: Connection, + pub client: Client, + pub connection: Connection, + laser_id: u8, } impl RedisCtrl { - pub fn new(url: &str) -> LJResult { - let client = Client::open(url) - .map_err(LJError::RedisConnect)?; - let connection = client.get_connection() - .map_err(LJError::RedisConnect)?; - Ok(RedisCtrl { client, connection }) - } + pub fn new(url: &str, laser_id: &u8) -> LJResult { + let client = Client::open(url) + .map_err(LJError::RedisConnect)?; + let connection = client.get_connection() + .map_err(LJError::RedisConnect)?; + Ok(RedisCtrl { client, connection, laser_id: *laser_id }) + } - pub fn get(&mut self, key: &str) -> LJResult { - let val: String = self.connection.get(key)?; - let line: Line = from_str(&val)?; - Ok(line) - } + pub fn get(&mut self, key: &str) -> LJResult { + let val: String = self.connection.get(key)?; + let line: Line = from_str(&val)?; + Ok(line) + } - pub fn get_order(&mut self, id: u8) -> LJResult { - let path = format!("/order/{id}"); - let val: u8 = self.connection.get(path.clone())?; + pub fn set(&mut self, key: String, value: String) -> LJResult<()> { + self.connection.set(key, value)?; + Ok(()) + } - if val == 1 || val >= 4 { - self.connection.set(path, 0)?; - } + pub fn get_order(&mut self, id: u8) -> LJResult { + let path = format!("/order/{id}"); + let val: u8 = self.connection.get(path.clone())?; - Ok(val.try_into()?) - } + if val == 1 || val >= 4 { + self.connection.set(path, 0)?; + } + + Ok(val.try_into()?) + } + + /** + /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) + /cap/lasernumber number of empty points sent to fill etherdream buffer (up to 1799) + /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. + **/ + pub fn set_status(&mut self, status: Status) -> LJResult<()> { + let lstt_key = format!("/lstt/{}", self.laser_id); + let cap_key = format!("/cap/{}", self.laser_id); + let lack_key = format!("/lack/{}", self.laser_id); + self.set(lstt_key, status.playback_state.to_string())?; + self.set(cap_key, status.capacity.to_string())?; + self.set(lack_key, status.lack.to_string())?; + Ok(()) + } } From 0f3ee7c54a01c4c982e9ba335e38229d8763d9f1 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 12 Jun 2023 19:27:44 +0200 Subject: [PATCH 08/48] fix: helios.status state --- src/device/helios.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/device/helios.rs b/src/device/helios.rs index 2e1041c..deab194 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -32,7 +32,7 @@ impl HeliosDevice { return Err(Box::new(LJError::HeliosDeviceMissing)); }; let dac = device.open()?; - Ok(Self { conf: (*conf).clone(), dac, sent_points: 0, state: PlaybackState::IDLE, lack: "".to_string() }) + Ok(Self { conf: (*conf).clone(), dac, sent_points: 0, state: PlaybackState::PREPARE, lack: "".to_string() }) } } @@ -53,13 +53,14 @@ impl Device for HeliosDevice { line: Vec, speed: u32, ) -> LJResult<()> { + self.state = PlaybackState::IDLE; while let Ok(DeviceStatus::NotReady) = self.dac.status() {} + self.state = PlaybackState::PLAYING; let points: Vec = line.into_iter().map(|p| p.into()).collect(); let frame = Frame::new(speed, points.clone()); self.dac.write_frame(frame.clone())?; self.sent_points = points.len() as u16; - self.state = PlaybackState::PLAYING; Ok(()) } From 9b9e04ad6304f0e8b918cb4ecd9d9a9f94cdb034 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 12 Jun 2023 21:56:21 +0200 Subject: [PATCH 09/48] fix: helios status trace time --- src/device/helios.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/device/helios.rs b/src/device/helios.rs index deab194..eb59d16 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -14,13 +14,15 @@ use crate::conf::HeliosConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::Point; +use chrono::Utc; pub struct HeliosDevice { pub conf: HeliosConf, dac: NativeHeliosDac, sent_points: u16, state: PlaybackState, - lack: String + lack: String, + last_traced_at : String } impl HeliosDevice { @@ -32,7 +34,14 @@ impl HeliosDevice { return Err(Box::new(LJError::HeliosDeviceMissing)); }; let dac = device.open()?; - Ok(Self { conf: (*conf).clone(), dac, sent_points: 0, state: PlaybackState::PREPARE, lack: "".to_string() }) + Ok(Self { + conf: (*conf).clone(), + dac, + sent_points: 0, + state: PlaybackState::PREPARE, + lack: "".to_string(), + last_traced_at: "1985-04-12T23:20:50.52Z".to_string() + }) } } @@ -41,7 +50,7 @@ impl Device for HeliosDevice { let lack = self.lack.clone(); Status { - last_traced_at: "now".to_string(), + last_traced_at: self.last_traced_at.clone(), properties: vec!["foo".to_string()], playback_state: self.state, capacity: self.sent_points, @@ -61,6 +70,7 @@ impl Device for HeliosDevice { let frame = Frame::new(speed, points.clone()); self.dac.write_frame(frame.clone())?; self.sent_points = points.len() as u16; + self.last_traced_at = Utc::now().to_rfc3339(); Ok(()) } From ce86a1cecb0b21f4e934dfb66a979c6cd0c10d91 Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 29 Jun 2023 22:36:00 +0200 Subject: [PATCH 10/48] wip: add worldstate --- src/main.rs | 65 ++++++++++++++++++++++++++++++++++++----------- src/redis_ctrl.rs | 13 ++++++++++ src/worldstate.rs | 23 +++++++++++++++++ 3 files changed, 86 insertions(+), 15 deletions(-) create mode 100644 src/worldstate.rs diff --git a/src/main.rs b/src/main.rs index 2cf7953..874ae54 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ mod errors; mod point; mod transformer; mod device; +mod worldstate; use device::device_factory; use std::sync::atomic::{AtomicBool, Ordering}; @@ -15,10 +16,11 @@ use std::sync::Arc; use redis_ctrl::{RedisCtrl, Order}; use conf::Conf; use errors::LJResult; -use point::Point; +use point::{Point, Color}; use transformer::Transformers; use log::{LevelFilter, info, /* warn, */ error}; use env_logger::Builder; +use worldstate::WorldState; const DEFAULT_CONF_FILE: &str = "settings.toml"; @@ -31,6 +33,7 @@ pub fn main() { } } + fn run_all() -> LJResult<()> { // Setup configuration file and set up logs let filename = std::env::args().nth(1).unwrap_or_else(|| { @@ -47,6 +50,8 @@ fn run_all() -> LJResult<()> { // Setup Redis Service let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; + let mut world_state = rs.init_world_state(); + // Setup handler for interrupt Signals let running = Arc::new(AtomicBool::new(true)); let r = running.clone(); @@ -61,20 +66,49 @@ fn run_all() -> LJResult<()> { //dbg!(tracer); // Setup geometry transformers on points lists - let transformers = config.get_transformers(); + let transformers = config.get_transformers(); // Dispatch based on redis requests while running.load(Ordering::SeqCst) { - rs.set_status( tracer.status())?; - let order = rs.get_order(config.laser_id)?; - if order != Order::Draw { - info!("Order: {:?}", order); - } + rs.set_status(tracer.status())?; - let frame = get_next_frame(&config, &transformers, - &mut rs, order == Order::Black)?; - // For now, draw all the time - tracer.draw(frame, 2_000)?; + let order = rs.get_order(config.laser_id)?; + // 0 : Draw Normal point list + // 2 : Draw BLACK point list + // 3 : Draw GRID point list + + // /worldstate.rs + // /edh.rs + + // 1 : Get the new EDH = reread redis key /EDH/lasernumber + // 4 : Resampler Change (longs and shorts lsteps) + // 5 : Client Key Change = reread redis key /clientkey + // 6 : Max Intensity Change = reread redis key /intensity + // 7 : kpps change = reread redis key /kpps + // 8 : color balance change = reread redis keys /red /green /blue + + match order { + Order::Draw => { + let frame = get_next_frame( + &config, + &transformers, + &mut rs, + // order == Order::Black, + &world_state + )?; + // For now, draw all the time + tracer.draw(frame, 2_000)?; + } + Order::Edh => { + let world_state.edh = rs.get_edh(), + } + + // Order::ClientKey => rs.client_key(), + // Order::ColorBalance => {}, + _ => { + info!("Order: {:?}", order); + } + } } info!("Exiting, stoping device."); @@ -101,17 +135,18 @@ fn get_next_frame( config: &Conf, transformers: &[Box], rs: &mut RedisCtrl, - _black: bool, + world_state : &WorldState ) -> LJResult> { let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; let mut line: Vec = line.into_iter() - .map(|tpl| tpl.into()) - .collect(); + .map(|tpl| tpl.into()) + .collect(); for transformer in transformers { - line = transformer.apply(&line); + line = transformer.apply(&line, world_state); } //info!("Line: {:?}", line); Ok(line) } + diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 448ed43..cbffc7c 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -2,6 +2,7 @@ use redis::{Client, Commands, Connection}; use ron::de::from_str; use crate::device::Status; use crate::errors::{LJError, LJResult}; +use crate::worldstate::{WorldState}; #[repr(u8)] #[derive(Debug, PartialEq)] @@ -96,4 +97,16 @@ impl RedisCtrl { self.set(lack_key, status.lack.to_string())?; Ok(()) } + + pub fn init_world_state( &mut self) -> LJResult{ + WorldState + } + + pub fn get_edh( &mut self ) -> LJResult<()> { + + // Get new EDH + let edh = self.get("/EDH/1"); + EDH( edh ) + + } } diff --git a/src/worldstate.rs b/src/worldstate.rs new file mode 100644 index 0000000..097b19b --- /dev/null +++ b/src/worldstate.rs @@ -0,0 +1,23 @@ + + +pub struct EDH { + pub matrix: Matrix3 +} + +#[derive(Debug, Default )] +impl EDH { + +} + +pub struct WorldState { + pub edh: EDH, + pub resampler: Vec, + pub client_key: u8, + pub intensity: u8, + pub kpps: u32, + pub color: Color +} + +impl WorldState{ + +} From f307fea63c6cc5274a23dfeab33fe64c64cf05e4 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 29 Jun 2023 23:24:56 +0200 Subject: [PATCH 11/48] fix code + dummy dac --- copyme.settings.toml | 3 +++ src/conf.rs | 2 ++ src/device.rs | 9 +++++--- src/device/dummy.rs | 36 ++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 6 ++--- src/point.rs | 4 ++-- src/redis_ctrl.rs | 15 ++++++------- src/transformer.rs | 7 +++++- src/transformer/flip_horizontal.rs | 4 +++- src/transformer/flip_vertical.rs | 4 +++- src/transformer/grid.rs | 4 +++- src/transformer/replicate.rs | 4 +++- src/transformer/rotate.rs | 4 +++- src/transformer/translate.rs | 3 ++- src/worldstate.rs | 8 ++++--- 16 files changed, 88 insertions(+), 26 deletions(-) create mode 100644 src/device/dummy.rs diff --git a/copyme.settings.toml b/copyme.settings.toml index f440bc0..5f9eaff 100644 --- a/copyme.settings.toml +++ b/copyme.settings.toml @@ -15,6 +15,9 @@ redis_url = "redis://127.0.0.1:6379/" [dac.helios] id = 0 +# For dummy dac: +# [dac.dummy] + # For Etherdream. IP of the DAC # [dac.etherdream] # url = "192.168.1.68" diff --git a/src/conf.rs b/src/conf.rs index 01827c3..1cc1b3e 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -19,6 +19,8 @@ pub enum DacFamily { Helios(HeliosConf), #[serde(rename = "etherdream")] Etherdream(EtherDreamConf), + #[serde(rename = "dummy")] + Dummy, } #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/src/device.rs b/src/device.rs index 0947bf2..c97276c 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,9 +1,11 @@ mod helios; +mod dummy; use std::fmt; use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/}; use crate::device::helios::HeliosDevice; +use crate::device::dummy::DummyDevice; use crate::errors::LJResult; use crate::point::Point; use serde::Serialize; @@ -57,9 +59,10 @@ pub trait Device { } pub fn device_factory(config: &Conf) -> LJResult> { - let device = match &config.dac { - DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?), - DacFamily::Etherdream(_conf) => todo!(), + let device : Box = match &config.dac { + DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?), + DacFamily::Etherdream(_conf) => todo!(), + DacFamily::Dummy => Box::new(DummyDevice::new()?) }; Ok(device) } diff --git a/src/device/dummy.rs b/src/device/dummy.rs new file mode 100644 index 0000000..8a9ed9b --- /dev/null +++ b/src/device/dummy.rs @@ -0,0 +1,36 @@ +use crate::device::{Device, Status, PlaybackState}; +use crate::errors::{LJError, LJResult}; +use crate::point::Point; + +pub struct DummyDevice { + state: PlaybackState +} + +impl DummyDevice { + pub fn new() -> LJResult { + Ok(Self { state: PlaybackState::IDLE }) + } +} + +impl Device for DummyDevice { + fn status(&self) -> Status { + Status { + last_traced_at: "never".to_string(), + properties: vec!["foo".to_string()], + playback_state: self.state, + capacity: 0, + lack: "lack".to_string() + } + } + + fn draw(&mut self, + line: Vec, + speed: u32, + ) -> LJResult<()> { + Ok(()) + } + + fn stop(&mut self) -> LJResult<()> { + Ok(()) + } +} diff --git a/src/lib.rs b/src/lib.rs index b183c49..9048f40 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,3 +4,4 @@ pub mod errors; pub mod device; pub mod point; pub mod transformer; +pub mod worldstate; diff --git a/src/main.rs b/src/main.rs index 874ae54..6a1103b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use redis_ctrl::{RedisCtrl, Order}; use conf::Conf; use errors::LJResult; -use point::{Point, Color}; +use point::Point; use transformer::Transformers; use log::{LevelFilter, info, /* warn, */ error}; use env_logger::Builder; @@ -50,7 +50,7 @@ fn run_all() -> LJResult<()> { // Setup Redis Service let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; - let mut world_state = rs.init_world_state(); + let mut world_state = rs.init_world_state()?; // Setup handler for interrupt Signals let running = Arc::new(AtomicBool::new(true)); @@ -100,7 +100,7 @@ fn run_all() -> LJResult<()> { tracer.draw(frame, 2_000)?; } Order::Edh => { - let world_state.edh = rs.get_edh(), + world_state.edh = rs.get_edh()?; } // Order::ClientKey => rs.client_key(), diff --git a/src/point.rs b/src/point.rs index 1d43bfe..44fa9b4 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,11 +1,11 @@ -#[derive(Debug,Clone,Copy)] +#[derive(Debug,Clone,Copy,Default)] pub struct Point { pub x: f32, pub y: f32, pub color: Color } -#[derive(Debug,Clone,Copy)] +#[derive(Debug,Clone,Copy,Default)] pub struct Color { r: u8, g: u8, diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index cbffc7c..b78af9e 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -2,7 +2,7 @@ use redis::{Client, Commands, Connection}; use ron::de::from_str; use crate::device::Status; use crate::errors::{LJError, LJResult}; -use crate::worldstate::{WorldState}; +use crate::worldstate::{WorldState,EDH}; #[repr(u8)] #[derive(Debug, PartialEq)] @@ -99,14 +99,13 @@ impl RedisCtrl { } pub fn init_world_state( &mut self) -> LJResult{ - WorldState + Ok(WorldState::default()) } - pub fn get_edh( &mut self ) -> LJResult<()> { - - // Get new EDH - let edh = self.get("/EDH/1"); - EDH( edh ) - + pub fn get_edh( &mut self ) -> LJResult { + // Get new EDH + let edh : String = self.connection.get("/EDH/0")?; + let edh : Vec> = from_str(&edh)?; + Ok(EDH { matrix: edh }) } } diff --git a/src/transformer.rs b/src/transformer.rs index 19d4445..6132658 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -7,6 +7,7 @@ mod flip_vertical; mod grid; use crate::point::Point; +use crate::worldstate::WorldState; // re-export transformers to be abe to use it directly from transformer:: pub use translate::Translate; @@ -17,5 +18,9 @@ pub use flip_vertical::FlipVertical; pub use grid::Grid; pub trait Transformers { - fn apply(&self, point_list: &[Point]) -> Vec; + fn apply( + &self, + point_list: &[Point], + world_state: &WorldState + ) -> Vec; } diff --git a/src/transformer/flip_horizontal.rs b/src/transformer/flip_horizontal.rs index d156739..ed9cec3 100644 --- a/src/transformer/flip_horizontal.rs +++ b/src/transformer/flip_horizontal.rs @@ -1,5 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; + use serde::{Serialize,Deserialize}; /// Flip Horizontal @@ -10,7 +12,7 @@ pub struct FlipHorizontal { } impl Transformers for FlipHorizontal { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { point_list.iter() .map(| pt | { let dx = pt.x - self.x; diff --git a/src/transformer/flip_vertical.rs b/src/transformer/flip_vertical.rs index fc741c7..19529e8 100644 --- a/src/transformer/flip_vertical.rs +++ b/src/transformer/flip_vertical.rs @@ -1,5 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; + use serde::{Serialize,Deserialize}; /// Flip Vertical @@ -10,7 +12,7 @@ pub struct FlipVertical { } impl Transformers for FlipVertical { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { point_list.iter() .map(| pt | { let dy = pt.y - self.y; diff --git a/src/transformer/grid.rs b/src/transformer/grid.rs index 25258ff..7a9d37b 100644 --- a/src/transformer/grid.rs +++ b/src/transformer/grid.rs @@ -1,5 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; + use serde::{Serialize,Deserialize}; /// Translate @@ -44,7 +46,7 @@ fn square_box(size: f32, color: u32) -> Vec<(f32, f32, u32)> { } impl Transformers for Grid { - fn apply(&self, _point_list: &[Point]) -> Vec { + fn apply(&self, _point_list: &[Point], _ws: &WorldState) -> Vec { let mut sq1 = square_box(1000.0, 255 << 8); let mut line = square_box(2000.0, 255); line.append(&mut sq1); diff --git a/src/transformer/replicate.rs b/src/transformer/replicate.rs index 99258ae..a5e5ab2 100644 --- a/src/transformer/replicate.rs +++ b/src/transformer/replicate.rs @@ -1,5 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; + use serde::{Serialize,Deserialize}; /// Replicate @@ -12,7 +14,7 @@ pub enum Replicate { } impl Transformers for Replicate { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { let mut point_list2 = vec![]; match self { Replicate::Until(n) => { diff --git a/src/transformer/rotate.rs b/src/transformer/rotate.rs index 60fc109..0dac920 100644 --- a/src/transformer/rotate.rs +++ b/src/transformer/rotate.rs @@ -1,5 +1,7 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; + use serde::{Serialize,Deserialize}; //use std::f32::consts::PI; @@ -14,7 +16,7 @@ pub struct Rotate { } impl Transformers for Rotate { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { point_list.iter() .map(| pt | { let dx = pt.x - self.cx; diff --git a/src/transformer/translate.rs b/src/transformer/translate.rs index c3f4fec..a0262a1 100644 --- a/src/transformer/translate.rs +++ b/src/transformer/translate.rs @@ -1,5 +1,6 @@ use crate::transformer::Transformers; use crate::point::Point; +use crate::worldstate::WorldState; use serde::{Serialize,Deserialize}; /// Translate @@ -11,7 +12,7 @@ pub struct Translate { } impl Transformers for Translate { - fn apply(&self, point_list: &[Point]) -> Vec { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { point_list.iter() .map(| pt | { Point { x: pt.x + self.x, diff --git a/src/worldstate.rs b/src/worldstate.rs index 097b19b..41eeef7 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -1,14 +1,16 @@ +use crate::point::Color; - +#[derive(Debug, Default)] pub struct EDH { - pub matrix: Matrix3 + pub matrix: Vec> //Matrix3 } -#[derive(Debug, Default )] + impl EDH { } +#[derive(Debug, Default)] pub struct WorldState { pub edh: EDH, pub resampler: Vec, From 63c700f12de4251da84e3f7beaf60e716ed6b3f5 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 29 Jun 2023 23:27:54 +0200 Subject: [PATCH 12/48] get edh --- src/redis_ctrl.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index b78af9e..e7e80fa 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -3,6 +3,7 @@ use ron::de::from_str; use crate::device::Status; use crate::errors::{LJError, LJResult}; use crate::worldstate::{WorldState,EDH}; +use log::info; #[repr(u8)] #[derive(Debug, PartialEq)] @@ -99,7 +100,13 @@ impl RedisCtrl { } pub fn init_world_state( &mut self) -> LJResult{ - Ok(WorldState::default()) + let edh = self.get_edh()?; + info!("EDH: {:?}", edh); + + Ok(WorldState { + edh, + ..WorldState::default() + }) } pub fn get_edh( &mut self ) -> LJResult { From 5470a9b78acad755e63301d3a1840f3b7a627ecd Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 14:34:30 +0200 Subject: [PATCH 13/48] add homography crate, use Matrix3 to store EDH --- Cargo.toml | 3 +++ src/device/dummy.rs | 6 ++++-- src/redis_ctrl.rs | 3 ++- src/worldstate.rs | 14 ++++++++++---- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9789221..65d03bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,11 @@ config = "0.13.3" ctrlc = "3.4.0" env_logger = "0.10.0" helios-dac = { version = "0.1", default-features = false, features = ["native"] } + log = "0.4.18" redis = "0.23.0" ron = "0.8.0" serde = { version = "1.0.163", features = ["derive"] } toml = "0.7.4" +homography = { git = "https://github.com/azazdeaz/homography" } +nalgebra = "0.32.2" diff --git a/src/device/dummy.rs b/src/device/dummy.rs index 8a9ed9b..e4c9e42 100644 --- a/src/device/dummy.rs +++ b/src/device/dummy.rs @@ -1,6 +1,7 @@ use crate::device::{Device, Status, PlaybackState}; -use crate::errors::{LJError, LJResult}; +use crate::errors::LJResult; use crate::point::Point; +use log::debug; pub struct DummyDevice { state: PlaybackState @@ -27,7 +28,8 @@ impl Device for DummyDevice { line: Vec, speed: u32, ) -> LJResult<()> { - Ok(()) + debug!("Draw Line at speed {speed} : {:?}", line); + Ok(()) } fn stop(&mut self) -> LJResult<()> { diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index e7e80fa..ee2efe7 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -113,6 +113,7 @@ impl RedisCtrl { // Get new EDH let edh : String = self.connection.get("/EDH/0")?; let edh : Vec> = from_str(&edh)?; - Ok(EDH { matrix: edh }) + let edh = EDH::new(edh)?; + Ok(edh) } } diff --git a/src/worldstate.rs b/src/worldstate.rs index 41eeef7..38b1bd0 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -1,13 +1,19 @@ use crate::point::Color; - +use nalgebra::base::Matrix3; +use crate::errors::LJResult; #[derive(Debug, Default)] pub struct EDH { - pub matrix: Vec> //Matrix3 + pub matrix: Matrix3 } impl EDH { - + pub fn new(vec: Vec>) -> LJResult { + let matrix = Matrix3::new(vec[0][0], vec[0][1], vec[0][2], + vec[1][0], vec[1][1], vec[1][2], + vec[2][0], vec[2][1], vec[2][2]); + Ok(EDH { matrix }) + } } #[derive(Debug, Default)] @@ -20,6 +26,6 @@ pub struct WorldState { pub color: Color } -impl WorldState{ +impl WorldState { } From 42773aa2a2f2bb2bd53c486a4382ce3c47268b2d Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 14:44:51 +0200 Subject: [PATCH 14/48] add error handling --- src/errors.rs | 6 +++++- src/worldstate.rs | 10 ++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/errors.rs b/src/errors.rs index ff40f33..1173dbe 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -9,7 +9,8 @@ pub type LJResult = Result>; pub enum LJError { Config(ConfigError), RedisConnect(RedisError), - HeliosDeviceMissing + HeliosDeviceMissing, + BadEDH } impl fmt::Display for LJError { @@ -26,6 +27,9 @@ impl fmt::Display for LJError { }, HeliosDeviceMissing => { write!(f, "helios device not found") + }, + BadEDH => { + write!(f, "EDH matrix is not a 3x3 matrix") } } } diff --git a/src/worldstate.rs b/src/worldstate.rs index 38b1bd0..d51536b 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -1,14 +1,20 @@ use crate::point::Color; use nalgebra::base::Matrix3; -use crate::errors::LJResult; +use crate::errors::{LJError,LJResult}; + #[derive(Debug, Default)] pub struct EDH { pub matrix: Matrix3 } - impl EDH { pub fn new(vec: Vec>) -> LJResult { + if vec.len() != 3 || + vec[0].len() != 3 || + vec[1].len() != 3 || + vec[2].len() != 3 { + return Err(Box::new(LJError::BadEDH)); + } let matrix = Matrix3::new(vec[0][0], vec[0][1], vec[0][2], vec[1][0], vec[1][1], vec[1][2], vec[2][0], vec[2][1], vec[2][2]); From ddf44460aefdb77dfc0d6953f6905fa5218046ab Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 14:54:37 +0200 Subject: [PATCH 15/48] fetch the right edh for this laser --- src/redis_ctrl.rs | 3 ++- src/worldstate.rs | 3 +++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index ee2efe7..5f6eea0 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -111,7 +111,8 @@ impl RedisCtrl { pub fn get_edh( &mut self ) -> LJResult { // Get new EDH - let edh : String = self.connection.get("/EDH/0")?; + let edh_key = format!("/EDH/{}", self.laser_id); + let edh : String = self.connection.get(edh_key)?; let edh : Vec> = from_str(&edh)?; let edh = EDH::new(edh)?; Ok(edh) diff --git a/src/worldstate.rs b/src/worldstate.rs index d51536b..aaf26e7 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -15,6 +15,9 @@ impl EDH { vec[2].len() != 3 { return Err(Box::new(LJError::BadEDH)); } + // + // [FIX] Not sure of the order, if is it's vec[x][y] or vec[y][x] ... + // let matrix = Matrix3::new(vec[0][0], vec[0][1], vec[0][2], vec[1][0], vec[1][1], vec[1][2], vec[2][0], vec[2][1], vec[2][2]); From ee9e3f1da0b3919ffa723f968a9eb40c918ff693 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 16:01:11 +0200 Subject: [PATCH 16/48] add homography transformer --- src/conf.rs | 8 +++++--- src/transformer.rs | 2 ++ src/transformer/homography.rs | 36 +++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 src/transformer/homography.rs diff --git a/src/conf.rs b/src/conf.rs index 1cc1b3e..815211c 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -46,8 +46,9 @@ pub enum TransformConf { #[serde(rename = "flip_vertical")] FlipV(transformer::FlipVertical), #[serde(rename = "grid")] - Grid(transformer::Grid) - + Grid(transformer::Grid), + #[serde(rename = "homography")] + Homography(transformer::Homography) } @@ -70,7 +71,8 @@ impl Conf { TransformConf::Rotate(r) => Box::new(*r), TransformConf::FlipH(r) => Box::new(*r), TransformConf::FlipV(r) => Box::new(*r), - TransformConf::Grid(r) => Box::new(*r) + TransformConf::Grid(r) => Box::new(*r), + TransformConf::Homography(r) => Box::new(*r), }; v.push(t); } diff --git a/src/transformer.rs b/src/transformer.rs index 6132658..aa25291 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -5,6 +5,7 @@ mod rotate; mod flip_horizontal; mod flip_vertical; mod grid; +mod homography; use crate::point::Point; use crate::worldstate::WorldState; @@ -16,6 +17,7 @@ pub use rotate::Rotate; pub use flip_horizontal::FlipHorizontal; pub use flip_vertical::FlipVertical; pub use grid::Grid; +pub use self::homography::Homography; pub trait Transformers { fn apply( diff --git a/src/transformer/homography.rs b/src/transformer/homography.rs new file mode 100644 index 0000000..bda21c3 --- /dev/null +++ b/src/transformer/homography.rs @@ -0,0 +1,36 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use crate::worldstate::WorldState; +use serde::{Serialize,Deserialize}; +use log::info; +use nalgebra::Matrix3; + +/// Homography + +#[derive(Serialize,Deserialize,Debug,Clone,Copy)] +pub struct Homography {} + +impl Transformers for Homography { + fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec { + let m = ws.edh.matrix; + + point_list.iter() + .map(| point | { + + // THIS IS CERTAINLY ALL WRONG! NEEDS DEBUGING!!! + + let p = Matrix3::new(point.x, point.y, 1.0, + 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0); + let dot = p.tr_dot(&m); + let new_p = Point { x: point.x / dot, y: point.y / dot, + ..*point + }; + + info!("{:?} => {:?}", point, new_p); + + new_p + }) + .collect() + } +} From 3d53982e7292533faf700a389da50eb6a381440d Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 17:14:01 +0200 Subject: [PATCH 17/48] fix homography calculation + test --- src/point.rs | 4 +-- src/transformer/homography.rs | 65 ++++++++++++++++++++++++++++------- src/worldstate.rs | 8 +++++ 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/src/point.rs b/src/point.rs index 44fa9b4..5eb6d42 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,11 +1,11 @@ -#[derive(Debug,Clone,Copy,Default)] +#[derive(Debug,Clone,Copy,Default,PartialEq)] pub struct Point { pub x: f32, pub y: f32, pub color: Color } -#[derive(Debug,Clone,Copy,Default)] +#[derive(Debug,Clone,Copy,Default,PartialEq)] pub struct Color { r: u8, g: u8, diff --git a/src/transformer/homography.rs b/src/transformer/homography.rs index bda21c3..0713583 100644 --- a/src/transformer/homography.rs +++ b/src/transformer/homography.rs @@ -1,9 +1,10 @@ use crate::transformer::Transformers; use crate::point::Point; -use crate::worldstate::WorldState; +use crate::worldstate::{WorldState,EDH}; use serde::{Serialize,Deserialize}; use log::info; use nalgebra::Matrix3; +use nalgebra::Matrix1x3; /// Homography @@ -12,25 +13,63 @@ pub struct Homography {} impl Transformers for Homography { fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec { - let m = ws.edh.matrix; + let edh : &EDH = &ws.edh; point_list.iter() .map(| point | { - - // THIS IS CERTAINLY ALL WRONG! NEEDS DEBUGING!!! + let p = Matrix1x3::new(point.x, point.y, 1.0); + let p = p * edh.matrix; + let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; - let p = Matrix3::new(point.x, point.y, 1.0, - 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0); - let dot = p.tr_dot(&m); - let new_p = Point { x: point.x / dot, y: point.y / dot, - ..*point - }; - - info!("{:?} => {:?}", point, new_p); + dbg!("{:?} => {:?}", point, new_p); new_p }) .collect() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_homography_identity() { + let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; + + let edh = EDH::new(vec![ + vec![ 1.0, 0.0, 0.0 ], + vec![ 0.0, 1.0, 0.0 ], + vec![ 0.0, 0.0, 1.0 ] + ]).unwrap(); + + let ws = WorldState { edh : edh, ..WorldState::default() }; + + let homography = Homography{}; + let result = homography.apply(&[p0], &ws); + + assert_eq!(result, vec![Point { x: -1500.0, + y: 1500.0, + ..Point::default() }]); + } + + #[test] + fn test_homography_rotation() { + let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; + + let edh = EDH::new(vec![ + vec![ 1.24107321e-03, 1.00500127e-03, 7.15439347e-01], + vec![-9.93223912e-04, 1.22652939e-03,-6.98671238e-01], + vec![ 1.06017142e-17,-4.69459541e-17, 3.32700590e-05] + ]).unwrap(); + + let ws = WorldState { edh : edh, ..WorldState::default() }; + + let homography = Homography{}; + let result = homography.apply(&[p0], &ws); + + assert_eq!(result, vec![Point { x: 10860.557, + y: 79078.87, + ..Point::default() }]); + } +} diff --git a/src/worldstate.rs b/src/worldstate.rs index aaf26e7..8377212 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -18,9 +18,17 @@ impl EDH { // // [FIX] Not sure of the order, if is it's vec[x][y] or vec[y][x] ... // + /* let matrix = Matrix3::new(vec[0][0], vec[0][1], vec[0][2], vec[1][0], vec[1][1], vec[1][2], vec[2][0], vec[2][1], vec[2][2]); + */ + + // this is the matrix already transposed. + let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0], + vec[0][1], vec[1][1], vec[2][1], + vec[0][2], vec[1][2], vec[2][2]); + Ok(EDH { matrix }) } } From 6c0678ca1dbd0ba7a8d18ef04f2d283c7247e44a Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 17:17:33 +0200 Subject: [PATCH 18/48] cleanup --- src/transformer/homography.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/transformer/homography.rs b/src/transformer/homography.rs index 0713583..f054319 100644 --- a/src/transformer/homography.rs +++ b/src/transformer/homography.rs @@ -2,8 +2,7 @@ use crate::transformer::Transformers; use crate::point::Point; use crate::worldstate::{WorldState,EDH}; use serde::{Serialize,Deserialize}; -use log::info; -use nalgebra::Matrix3; +use log::debug; use nalgebra::Matrix1x3; /// Homography @@ -21,7 +20,7 @@ impl Transformers for Homography { let p = p * edh.matrix; let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; - dbg!("{:?} => {:?}", point, new_p); + debug!("{:?} => {:?}", point, new_p); new_p }) From 1d61235e51fa02ccb05d159bd086f85e0dd51dcb Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 17:19:48 +0200 Subject: [PATCH 19/48] cleanup --- src/transformer/homography.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/transformer/homography.rs b/src/transformer/homography.rs index f054319..3fe1f95 100644 --- a/src/transformer/homography.rs +++ b/src/transformer/homography.rs @@ -33,7 +33,7 @@ mod tests { use super::*; #[test] - fn test_homography_identity() { + fn identity_matrix_let_point_unchanged() { let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; let edh = EDH::new(vec![ @@ -53,7 +53,7 @@ mod tests { } #[test] - fn test_homography_rotation() { + fn rotation_matrix_rotate_the_point() { let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; let edh = EDH::new(vec![ From 2b0a2ce06d91124a868e70f705991e6f15743047 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Sat, 1 Jul 2023 17:42:31 +0200 Subject: [PATCH 20/48] refacto --- Cargo.toml | 1 - src/transformer/homography.rs | 12 +----------- src/worldstate.rs | 15 +++++++++++++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 65d03bf..61520a8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,5 +17,4 @@ redis = "0.23.0" ron = "0.8.0" serde = { version = "1.0.163", features = ["derive"] } toml = "0.7.4" -homography = { git = "https://github.com/azazdeaz/homography" } nalgebra = "0.32.2" diff --git a/src/transformer/homography.rs b/src/transformer/homography.rs index 3fe1f95..8f1091f 100644 --- a/src/transformer/homography.rs +++ b/src/transformer/homography.rs @@ -2,8 +2,6 @@ use crate::transformer::Transformers; use crate::point::Point; use crate::worldstate::{WorldState,EDH}; use serde::{Serialize,Deserialize}; -use log::debug; -use nalgebra::Matrix1x3; /// Homography @@ -15,15 +13,7 @@ impl Transformers for Homography { let edh : &EDH = &ws.edh; point_list.iter() - .map(| point | { - let p = Matrix1x3::new(point.x, point.y, 1.0); - let p = p * edh.matrix; - let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; - - debug!("{:?} => {:?}", point, new_p); - - new_p - }) + .map(| point | edh.apply(point)) .collect() } } diff --git a/src/worldstate.rs b/src/worldstate.rs index 8377212..426dc1c 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -1,6 +1,7 @@ -use crate::point::Color; -use nalgebra::base::Matrix3; +use crate::point::{Point,Color}; +use nalgebra::base::{Matrix3,Matrix1x3}; use crate::errors::{LJError,LJResult}; +use log::debug; #[derive(Debug, Default)] pub struct EDH { @@ -31,6 +32,16 @@ impl EDH { Ok(EDH { matrix }) } + + pub fn apply(&self, point: &Point) -> Point { + let p = Matrix1x3::new(point.x, point.y, 1.0); + let p = p * self.matrix; + let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; + + debug!("{:?} => {:?}", point, new_p); + + new_p + } } #[derive(Debug, Default)] From e5e8ad878b7abf4f6038cea2ff152547202d626f Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 6 Jul 2023 20:26:06 +0200 Subject: [PATCH 21/48] micro-cleanup --- src/worldstate.rs | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/worldstate.rs b/src/worldstate.rs index 426dc1c..bf5ecc9 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -16,15 +16,7 @@ impl EDH { vec[2].len() != 3 { return Err(Box::new(LJError::BadEDH)); } - // - // [FIX] Not sure of the order, if is it's vec[x][y] or vec[y][x] ... - // - /* - let matrix = Matrix3::new(vec[0][0], vec[0][1], vec[0][2], - vec[1][0], vec[1][1], vec[1][2], - vec[2][0], vec[2][1], vec[2][2]); - */ - + // this is the matrix already transposed. let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0], vec[0][1], vec[1][1], vec[2][1], From 538f13f539053673c3aebb3f403eb1a3c154a20b Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 6 Jul 2023 21:52:20 +0200 Subject: [PATCH 22/48] more worldstate keys --- src/conf.rs | 18 ++++++++++-------- src/main.rs | 37 ++++++++++++++++++++++--------------- src/redis_ctrl.rs | 19 +++++++++++++------ src/worldstate.rs | 2 +- 4 files changed, 46 insertions(+), 30 deletions(-) diff --git a/src/conf.rs b/src/conf.rs index 815211c..7d91cad 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -81,14 +81,16 @@ impl Conf { #[allow(dead_code)] pub fn dump() { - let conf = Conf { laser_id: 0, - debug: true, - redis_url: "redis://127.0.0.1:6379/".to_string(), - dac: DacFamily::Helios(HeliosConf { id: 0 }), - transformers: vec![ - TransformConf::Translate(transformer::Translate { x: 2000.0, y: 2000.0 } ), - TransformConf::Replicate(transformer::Replicate::Until(48)) - ] + let conf = Conf { + laser_id: 0, + debug: true, + redis_url: "redis://127.0.0.1:6379/".to_string(), + dac: DacFamily::Helios(HeliosConf { id: 0 }), + transformers: vec![ + TransformConf::Translate(transformer::Translate { x: 2000.0, + y: 2000.0 } ), + TransformConf::Replicate(transformer::Replicate::Until(48)) + ] }; let s = toml::to_string(&conf).unwrap(); println!("{}", s); diff --git a/src/main.rs b/src/main.rs index 6a1103b..344a71d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,7 +51,8 @@ fn run_all() -> LJResult<()> { let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; let mut world_state = rs.init_world_state()?; - + info!("WorldState: {:?}", world_state); + // Setup handler for interrupt Signals let running = Arc::new(AtomicBool::new(true)); let r = running.clone(); @@ -93,15 +94,18 @@ fn run_all() -> LJResult<()> { &config, &transformers, &mut rs, - // order == Order::Black, &world_state )?; // For now, draw all the time tracer.draw(frame, 2_000)?; - } + }, + Order::Intensity => { + world_state.intensity = rs.get_int("intensity")? + .try_into()?; + }, Order::Edh => { world_state.edh = rs.get_edh()?; - } + }, // Order::ClientKey => rs.client_key(), // Order::ColorBalance => {}, @@ -137,16 +141,19 @@ fn get_next_frame( rs: &mut RedisCtrl, world_state : &WorldState ) -> LJResult> { - let line = rs.get(&format!("/pl/{}/0", config.laser_id))?; - let mut line: Vec = line.into_iter() - .map(|tpl| tpl.into()) - .collect(); - - for transformer in transformers { - line = transformer.apply(&line, world_state); - } - - //info!("Line: {:?}", line); - Ok(line) + let format_key = format!("{}{}", + world_state.client_key, + config.laser_id); + let line = rs.get_line(&format_key)?; + let mut line: Vec = line.into_iter() + .map(|tpl| tpl.into()) + .collect(); + + for transformer in transformers { + line = transformer.apply(&line, world_state); + } + + //info!("Line: {:?}", line); + Ok(line) } diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 5f6eea0..4b13d8a 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -3,7 +3,7 @@ use ron::de::from_str; use crate::device::Status; use crate::errors::{LJError, LJResult}; use crate::worldstate::{WorldState,EDH}; -use log::info; +// use log::info; #[repr(u8)] #[derive(Debug, PartialEq)] @@ -62,7 +62,7 @@ impl RedisCtrl { Ok(RedisCtrl { client, connection, laser_id: *laser_id }) } - pub fn get(&mut self, key: &str) -> LJResult { + pub fn get_line(&mut self, key: &str) -> LJResult { let val: String = self.connection.get(key)?; let line: Line = from_str(&val)?; Ok(line) @@ -100,11 +100,11 @@ impl RedisCtrl { } pub fn init_world_state( &mut self) -> LJResult{ - let edh = self.get_edh()?; - info!("EDH: {:?}", edh); - Ok(WorldState { - edh, + client_key: self.connection.get("/clientkey")?, + edh: self.get_edh()?, + kpps: self.get_int("kpps")?.try_into()?, + intensity: self.get_int("intensity")?.try_into()?, ..WorldState::default() }) } @@ -117,4 +117,11 @@ impl RedisCtrl { let edh = EDH::new(edh)?; Ok(edh) } + + pub fn get_int(&mut self, key: &str ) -> LJResult { + // Get new Int + let fmt = format!("/{key}/{}", self.laser_id); + let val : u32 = self.connection.get(fmt)?; + Ok(val) + } } diff --git a/src/worldstate.rs b/src/worldstate.rs index bf5ecc9..c097247 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -40,7 +40,7 @@ impl EDH { pub struct WorldState { pub edh: EDH, pub resampler: Vec, - pub client_key: u8, + pub client_key: String, //u8, pub intensity: u8, pub kpps: u32, pub color: Color From 5ff4ecacdd4b4d5d15cb4e37609cd49eb86daaa3 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 6 Jul 2023 22:17:49 +0200 Subject: [PATCH 23/48] kpps working --- src/main.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 344a71d..1900de8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -97,7 +97,7 @@ fn run_all() -> LJResult<()> { &world_state )?; // For now, draw all the time - tracer.draw(frame, 2_000)?; + tracer.draw(frame, world_state.kpps)?; }, Order::Intensity => { world_state.intensity = rs.get_int("intensity")? @@ -106,6 +106,9 @@ fn run_all() -> LJResult<()> { Order::Edh => { world_state.edh = rs.get_edh()?; }, + Order::Kpps => { + world_state.kpps = rs.get_int("kpps")?; + }, // Order::ClientKey => rs.client_key(), // Order::ColorBalance => {}, From 76cc1c12755e452514098e18c76e0926a8f144bc Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 6 Jul 2023 22:18:44 +0200 Subject: [PATCH 24/48] wip --- Cargo.toml | 1 + copyme.settings.toml | 5 ++ src/device.rs | 3 +- src/device/etherdream.rs | 108 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 src/device/etherdream.rs diff --git a/Cargo.toml b/Cargo.toml index 61520a8..ca0464a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ chrono = "0.4.26" config = "0.13.3" ctrlc = "3.4.0" env_logger = "0.10.0" +ether-dream = "0.2.5" helios-dac = { version = "0.1", default-features = false, features = ["native"] } log = "0.4.18" diff --git a/copyme.settings.toml b/copyme.settings.toml index 5f9eaff..19182bb 100644 --- a/copyme.settings.toml +++ b/copyme.settings.toml @@ -29,3 +29,8 @@ y = 2000 [[transformers]] [transformers.replicate] Until = 48 + +# Never remove this : this is mandatory +[[transformers]] +[transformers.intensity] + diff --git a/src/device.rs b/src/device.rs index c97276c..91027d8 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,6 +1,7 @@ mod helios; mod dummy; +mod etherdream; use std::fmt; use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/}; @@ -35,7 +36,7 @@ impl fmt::Display for PlaybackState { } } -#[derive(Debug)] +#[derive(Debug, Default )] pub struct Status { pub last_traced_at: String, pub properties: Vec, diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs new file mode 100644 index 0000000..fec964e --- /dev/null +++ b/src/device/etherdream.rs @@ -0,0 +1,108 @@ +use ether_dream::{dac}; + + + +use crate::conf::EtherDreamConf; +use crate::device::{Device, Status, PlaybackState}; +use crate::errors::{LJError, LJResult}; +use crate::point::Point; +use chrono::Utc; + +pub struct EtherdreamDevice { + pub conf: EtherDreamConf, + dac: dac, + sent_points: u16, + state: PlaybackState, + lack: String, + last_traced_at : String +} + +impl EtherdreamDevice { + pub fn new(conf: &EtherDreamConf) -> LJResult { + let id = conf.id; + + // // Todo : use the config + // let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts() + // .expect("failed to bind to UDP socket") + // .filter_map(Result::ok) + // .next() + // .unwrap(); + // let mac_address = dac::MacAddress(dac_broadcast.mac_address); + // + // println!( + // "Discovered DAC \"{}\" at \"{}\"! Connecting...", + // mac_address, source_addr + // ); + + + // Establish the TCP connection. + let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap(); + + // If we want to create an animation (in our case a moving sine wave) we need a frame rate. + let frames_per_second = 60.0; + // Lets use the DAC at an eighth the maximum scan rate. + let points_per_second = stream.dac().max_point_rate / 32; + // Determine the number of points per frame given our target frame and point rates. + let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; + + // Prepare the DAC's playback engine and await the repsonse. + stream + .queue_commands() + .prepare_stream() + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting PREPARE_STREAM \ + command and listening for response: {}", + err + ); + }); + + println!("Ready for playback!"); + + Ok(Self { + conf: (*conf).clone(), + dac, + sent_points: 0, + state: PlaybackState::PREPARE, + lack: "".to_string(), + last_traced_at: "1985-04-12T23:20:50.52Z".to_string() + }) + } +} + +impl Device for EtherdreamDevice { + fn status(&self) -> Status { + + let lack = self.lack.clone(); + Status { + last_traced_at: self.last_traced_at.clone(), + properties: vec!["foo".to_string()], + playback_state: self.state, + capacity: self.sent_points, + lack, + } + } + + fn draw(&mut self, + line: Vec, + speed: u32, + ) -> LJResult<()> { + self.state = PlaybackState::IDLE; + while let Ok(DeviceStatus::NotReady) = self.dac.status() {} + self.state = PlaybackState::PLAYING; + + let points: Vec = line.into_iter().map(|p| p.into()).collect(); + let frame = Frame::new(speed, points.clone()); + self.dac.write_frame(frame.clone())?; + self.sent_points = points.len() as u16; + self.last_traced_at = Utc::now().to_rfc3339(); + Ok(()) + } + + fn stop(&mut self) -> LJResult<()> { + self.dac.stop()?; + Ok(()) + } +} From 21bc0496c2c2288f6a308ffa0bb745e96c8bae3b Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 6 Jul 2023 22:22:56 +0200 Subject: [PATCH 25/48] kpps working --- src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.rs b/src/main.rs index 1900de8..1e56068 100644 --- a/src/main.rs +++ b/src/main.rs @@ -103,6 +103,8 @@ fn run_all() -> LJResult<()> { world_state.intensity = rs.get_int("intensity")? .try_into()?; }, + Order::Black => { + }, Order::Edh => { world_state.edh = rs.get_edh()?; }, From 69b619dbf5fc26996cbfb4bb0244a108c3162150 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Thu, 6 Jul 2023 22:58:24 +0200 Subject: [PATCH 26/48] black working --- src/main.rs | 30 +++++++++++++++++++++++++----- src/point.rs | 6 +++--- src/worldstate.rs | 3 ++- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1e56068..9eeca6d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,7 +16,7 @@ use std::sync::Arc; use redis_ctrl::{RedisCtrl, Order}; use conf::Conf; use errors::LJResult; -use point::Point; +use point::{Point,Color}; use transformer::Transformers; use log::{LevelFilter, info, /* warn, */ error}; use env_logger::Builder; @@ -87,9 +87,10 @@ fn run_all() -> LJResult<()> { // 6 : Max Intensity Change = reread redis key /intensity // 7 : kpps change = reread redis key /kpps // 8 : color balance change = reread redis keys /red /green /blue - match order { - Order::Draw => { + Order::Draw | Order::Black => { + world_state.black = order == Order::Black; + let frame = get_next_frame( &config, &transformers, @@ -103,8 +104,6 @@ fn run_all() -> LJResult<()> { world_state.intensity = rs.get_int("intensity")? .try_into()?; }, - Order::Black => { - }, Order::Edh => { world_state.edh = rs.get_edh()?; }, @@ -157,6 +156,27 @@ fn get_next_frame( for transformer in transformers { line = transformer.apply(&line, world_state); } + + info!("-> {}", world_state.black); + + // LIMITER and BLACK + line = line.into_iter() + .map(| p | { + + let color = if world_state.black { + Color { r: 0, g: 0, b: 0 } + } else { + Color { + r: p.color.r.min(world_state.intensity), + g: p.color.g.min(world_state.intensity), + b: p.color.b.min(world_state.intensity) + } + }; + Point { color, + ..p + } + }) + .collect(); //info!("Line: {:?}", line); Ok(line) diff --git a/src/point.rs b/src/point.rs index 5eb6d42..21c65c8 100644 --- a/src/point.rs +++ b/src/point.rs @@ -7,9 +7,9 @@ pub struct Point { #[derive(Debug,Clone,Copy,Default,PartialEq)] pub struct Color { - r: u8, - g: u8, - b: u8 + pub r: u8, + pub g: u8, + pub b: u8 } impl From<(f32,f32,u32)> for Point { diff --git a/src/worldstate.rs b/src/worldstate.rs index c097247..24bb22a 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -43,7 +43,8 @@ pub struct WorldState { pub client_key: String, //u8, pub intensity: u8, pub kpps: u32, - pub color: Color + pub color: Color, + pub black: bool } impl WorldState { From e4580e0e538d58a494fd61093a9f0fa00ba41c89 Mon Sep 17 00:00:00 2001 From: alban Date: Sun, 9 Jul 2023 22:16:01 +0200 Subject: [PATCH 27/48] feat: add grid --- src/device.rs | 2 + src/device/common.rs | 31 ------------ src/device/dummy.rs | 7 ++- src/device/helios.rs | 33 ++++++++++-- src/main.rs | 116 +++++++++++++++++++++++-------------------- src/point.rs | 55 +++++++++++--------- src/worldstate.rs | 65 ++++++++++++------------ 7 files changed, 164 insertions(+), 145 deletions(-) delete mode 100644 src/device/common.rs diff --git a/src/device.rs b/src/device.rs index c97276c..79f0114 100644 --- a/src/device.rs +++ b/src/device.rs @@ -9,6 +9,7 @@ use crate::device::dummy::DummyDevice; use crate::errors::LJResult; use crate::point::Point; use serde::Serialize; +use crate::redis_ctrl::Line; /* self.protocol_version, @@ -56,6 +57,7 @@ pub trait Device { speed: u32, ) -> LJResult<()>; fn stop(&mut self) -> LJResult<()>; + fn grid(&mut self) -> Vec; } pub fn device_factory(config: &Conf) -> LJResult> { diff --git a/src/device/common.rs b/src/device/common.rs deleted file mode 100644 index 020ad4d..0000000 --- a/src/device/common.rs +++ /dev/null @@ -1,31 +0,0 @@ - -/* -self.protocol_version, -self.le_state, -self.playback_state, -self.source, -self.le_flags, -self.playback_flags, -self.source_flags, -self.fullness, -self.point_rate, -self.point_count -*/ - -pub struct Status { - pub active: bool, - pub last_traced_at: String, - pub properties: Vec -} - -pub trait Device { - /** - fn intersect(&self, orig : &Vec3, dir : &Vec3) -> Option; - fn get_surface(&self, v : &Vec3) -> Vec3; - fn get_normal(&self, v : &Vec3) -> Vec3; - fn get_material(&self) -> &dyn Material; - **/ - - fn status( &self ) -> Status; - -} diff --git a/src/device/dummy.rs b/src/device/dummy.rs index e4c9e42..544d6c8 100644 --- a/src/device/dummy.rs +++ b/src/device/dummy.rs @@ -1,6 +1,6 @@ use crate::device::{Device, Status, PlaybackState}; use crate::errors::LJResult; -use crate::point::Point; +use crate::point::{Color, Point}; use log::debug; pub struct DummyDevice { @@ -35,4 +35,9 @@ impl Device for DummyDevice { fn stop(&mut self) -> LJResult<()> { Ok(()) } + fn grid(&mut self) -> Vec { + vec!( + Point{ x: 0 as f32, y: 0 as f32, color:Color{ r: 0, g: 0, b: 0 }} + ) + } } diff --git a/src/device/helios.rs b/src/device/helios.rs index eb59d16..42373f0 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -13,8 +13,9 @@ use helios_dac::{ use crate::conf::HeliosConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; -use crate::point::Point; +use crate::point::{Color, Point}; use chrono::Utc; +use crate::redis_ctrl::Line; pub struct HeliosDevice { pub conf: HeliosConf, @@ -22,7 +23,7 @@ pub struct HeliosDevice { sent_points: u16, state: PlaybackState, lack: String, - last_traced_at : String + last_traced_at: String, } impl HeliosDevice { @@ -40,17 +41,16 @@ impl HeliosDevice { sent_points: 0, state: PlaybackState::PREPARE, lack: "".to_string(), - last_traced_at: "1985-04-12T23:20:50.52Z".to_string() + last_traced_at: "1985-04-12T23:20:50.52Z".to_string(), }) } } impl Device for HeliosDevice { fn status(&self) -> Status { - let lack = self.lack.clone(); Status { - last_traced_at: self.last_traced_at.clone(), + last_traced_at: self.last_traced_at.clone(), properties: vec!["foo".to_string()], playback_state: self.state, capacity: self.sent_points, @@ -78,4 +78,27 @@ impl Device for HeliosDevice { self.dac.stop()?; Ok(()) } + + fn grid(&mut self) -> Vec { + let dim_min = 0 as f32; + let dim_mid = 2047 as f32; + let dim_max = 4095 as f32; + let col_min = Color { r: 0, g: 0, b: 0 }; + let col_max = Color { r: 255, g: 255, b: 255 }; + + vec![ + Point { x: dim_min, y: dim_max, color: col_min }, + Point { x: dim_min, y: dim_max, color: col_max }, + Point { x: dim_max, y: dim_max, color: col_max }, + Point { x: dim_max, y: dim_min, color: col_max }, + Point { x: dim_min, y: dim_min, color: col_max }, + Point { x: dim_min, y: dim_min, color: col_min }, + Point { x: dim_min, y: dim_mid, color: col_min }, + Point { x: dim_min, y: dim_mid, color: col_max }, + Point { x: dim_mid, y: dim_mid, color: col_max }, + Point { x: dim_mid, y: dim_min, color: col_max }, + Point { x: dim_min, y: dim_min, color: col_max }, + Point { x: dim_min, y: dim_min, color: col_min }, + ] + } } diff --git a/src/main.rs b/src/main.rs index 9eeca6d..c7e8ccb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,10 +13,10 @@ mod worldstate; use device::device_factory; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use redis_ctrl::{RedisCtrl, Order}; +use redis_ctrl::{RedisCtrl, Order, Line}; use conf::Conf; use errors::LJResult; -use point::{Point,Color}; +use point::{Point, Color}; use transformer::Transformers; use log::{LevelFilter, info, /* warn, */ error}; use env_logger::Builder; @@ -51,8 +51,8 @@ fn run_all() -> LJResult<()> { let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; let mut world_state = rs.init_world_state()?; - info!("WorldState: {:?}", world_state); - + info!("WorldState: {:?}", world_state); + // Setup handler for interrupt Signals let running = Arc::new(AtomicBool::new(true)); let r = running.clone(); @@ -62,6 +62,7 @@ fn run_all() -> LJResult<()> { // Setup Laser Device based on conf let mut tracer = device_factory(&config)?; + world_state.grid = tracer.grid(); // can't work, but we can add + Debug to Device to make it work... //dbg!(tracer); @@ -78,8 +79,6 @@ fn run_all() -> LJResult<()> { // 2 : Draw BLACK point list // 3 : Draw GRID point list - // /worldstate.rs - // /edh.rs // 1 : Get the new EDH = reread redis key /EDH/lasernumber // 4 : Resampler Change (longs and shorts lsteps) @@ -88,28 +87,29 @@ fn run_all() -> LJResult<()> { // 7 : kpps change = reread redis key /kpps // 8 : color balance change = reread redis keys /red /green /blue match order { - Order::Draw | Order::Black => { - world_state.black = order == Order::Black; - + Order::Draw | Order::Black | Order::Grid => { + world_state.draw_black = order == Order::Black; + world_state.draw_grid = order == Order::Grid; + let frame = get_next_frame( &config, &transformers, - &mut rs, - &world_state + &mut rs, + &world_state, )?; // For now, draw all the time tracer.draw(frame, world_state.kpps)?; - }, - Order::Intensity => { - world_state.intensity = rs.get_int("intensity")? - .try_into()?; - }, + } + Order::Intensity => { + world_state.intensity = rs.get_int("intensity")? + .try_into()?; + } Order::Edh => { world_state.edh = rs.get_edh()?; - }, + } Order::Kpps => { world_state.kpps = rs.get_int("kpps")?; - }, + } // Order::ClientKey => rs.client_key(), // Order::ColorBalance => {}, @@ -143,42 +143,52 @@ fn get_next_frame( config: &Conf, transformers: &[Box], rs: &mut RedisCtrl, - world_state : &WorldState + world_state: &WorldState, ) -> LJResult> { - let format_key = format!("{}{}", - world_state.client_key, - config.laser_id); - let line = rs.get_line(&format_key)?; - let mut line: Vec = line.into_iter() - .map(|tpl| tpl.into()) - .collect(); - - for transformer in transformers { - line = transformer.apply(&line, world_state); - } + let format_key = format!("{}{}", + world_state.client_key, + config.laser_id); - info!("-> {}", world_state.black); - - // LIMITER and BLACK - line = line.into_iter() - .map(| p | { - - let color = if world_state.black { - Color { r: 0, g: 0, b: 0 } - } else { - Color { - r: p.color.r.min(world_state.intensity), - g: p.color.g.min(world_state.intensity), - b: p.color.b.min(world_state.intensity) - } - }; - Point { color, - ..p - } - }) - .collect(); - - //info!("Line: {:?}", line); - Ok(line) + // Handle the grid case + + let mut line : Vec; + if world_state.draw_grid { + line = world_state.grid.clone(); + } else { + let redis_line = rs.get_line(&format_key)?; + line = redis_line.into_iter() + .map(|tpl| tpl.into()) + .collect(); + }; + + + for transformer in transformers { + line = transformer.apply(&line, world_state); + } + + info!("Draw Black -> {}", world_state.draw_black); + info!("Draw Grid -> {}", world_state.draw_grid); + + // LIMITER and BLACK + line = line.into_iter() + .map(|p| { + let color = if world_state.draw_black { + Color { r: 0, g: 0, b: 0 } + } else { + Color { + r: p.color.r.min(world_state.intensity), + g: p.color.g.min(world_state.intensity), + b: p.color.b.min(world_state.intensity), + } + }; + Point { + color, + ..p + } + }) + .collect(); + + //info!("Line: {:?}", line); + Ok(line) } diff --git a/src/point.rs b/src/point.rs index 21c65c8..ed18697 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,34 +1,43 @@ -#[derive(Debug,Clone,Copy,Default,PartialEq)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Point { - pub x: f32, - pub y: f32, - pub color: Color + pub x: f32, + pub y: f32, + pub color: Color, } -#[derive(Debug,Clone,Copy,Default,PartialEq)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Color { - pub r: u8, - pub g: u8, - pub b: u8 + pub r: u8, + pub g: u8, + pub b: u8, } -impl From<(f32,f32,u32)> for Point { - fn from((x, y, color) : (f32, f32, u32)) -> Point { - let r = (color >> 16) as u8 ; - let g = ((color >> 8) & 255) as u8 ; - let b = (color & 255) as u8 ; - Point { x, y, color: Color { r, g, b } } - } +impl From for u32 { + fn from(value: Color) -> Self { + let r = value.r as u32; + let g = value.g as u32; + let b = (value.b) as u32; + (r << 16) + (g << 8) + b + } +} + +impl From<(f32, f32, u32)> for Point { + fn from((x, y, color): (f32, f32, u32)) -> Point { + let r = (color >> 16) as u8; + let g = ((color >> 8) & 255) as u8; + let b = (color & 255) as u8; + Point { x, y, color: Color { r, g, b } } + } } impl From for helios_dac::Point { - fn from(pt: Point) -> helios_dac::Point { - let x = pt.x.clamp(0.0, 4095.0) as u16; - let y = pt.y.clamp(0.0, 4095.0) as u16; - helios_dac::Point { - coordinate: (x, y).into(), - color: helios_dac::Color::new(pt.color.r, pt.color.g, pt.color.b), - intensity: 0xFF + fn from(pt: Point) -> helios_dac::Point { + let x = pt.x.clamp(0.0, 4095.0) as u16; + let y = pt.y.clamp(0.0, 4095.0) as u16; + helios_dac::Point { + coordinate: (x, y).into(), + color: helios_dac::Color::new(pt.color.r, pt.color.g, pt.color.b), + intensity: 0xFF, + } } - } } diff --git a/src/worldstate.rs b/src/worldstate.rs index 24bb22a..7461c14 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -1,52 +1,53 @@ -use crate::point::{Point,Color}; -use nalgebra::base::{Matrix3,Matrix1x3}; -use crate::errors::{LJError,LJResult}; +use crate::point::{Point, Color}; +use nalgebra::base::{Matrix3, Matrix1x3}; +use crate::errors::{LJError, LJResult}; use log::debug; +use crate::redis_ctrl::Line; #[derive(Debug, Default)] pub struct EDH { - pub matrix: Matrix3 + pub matrix: Matrix3, } impl EDH { - pub fn new(vec: Vec>) -> LJResult { - if vec.len() != 3 || - vec[0].len() != 3 || - vec[1].len() != 3 || - vec[2].len() != 3 { - return Err(Box::new(LJError::BadEDH)); - } + pub fn new(vec: Vec>) -> LJResult { + if vec.len() != 3 || + vec[0].len() != 3 || + vec[1].len() != 3 || + vec[2].len() != 3 { + return Err(Box::new(LJError::BadEDH)); + } - // this is the matrix already transposed. - let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0], - vec[0][1], vec[1][1], vec[2][1], - vec[0][2], vec[1][2], vec[2][2]); + // this is the matrix already transposed. + let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0], + vec[0][1], vec[1][1], vec[2][1], + vec[0][2], vec[1][2], vec[2][2]); - Ok(EDH { matrix }) - } + Ok(EDH { matrix }) + } - pub fn apply(&self, point: &Point) -> Point { - let p = Matrix1x3::new(point.x, point.y, 1.0); - let p = p * self.matrix; - let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; - - debug!("{:?} => {:?}", point, new_p); - - new_p - } + pub fn apply(&self, point: &Point) -> Point { + let p = Matrix1x3::new(point.x, point.y, 1.0); + let p = p * self.matrix; + let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; + + debug!("{:?} => {:?}", point, new_p); + + new_p + } } #[derive(Debug, Default)] pub struct WorldState { pub edh: EDH, pub resampler: Vec, - pub client_key: String, //u8, + pub client_key: String, pub intensity: u8, pub kpps: u32, - pub color: Color, - pub black: bool + pub color: Color, + pub draw_black: bool, + pub draw_grid: bool, + pub grid: Vec, } -impl WorldState { - -} +impl WorldState {} From 6fa884699760832fdc9b2e1c596b80545bd567e7 Mon Sep 17 00:00:00 2001 From: alban Date: Sun, 9 Jul 2023 22:44:15 +0200 Subject: [PATCH 28/48] feat: add get_client_key + cleanup --- src/device.rs | 1 - src/device/helios.rs | 1 - src/main.rs | 31 ++++++++++++++++--------------- src/redis_ctrl.rs | 5 +++++ src/worldstate.rs | 3 +-- 5 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/device.rs b/src/device.rs index 79f0114..e3a6270 100644 --- a/src/device.rs +++ b/src/device.rs @@ -9,7 +9,6 @@ use crate::device::dummy::DummyDevice; use crate::errors::LJResult; use crate::point::Point; use serde::Serialize; -use crate::redis_ctrl::Line; /* self.protocol_version, diff --git a/src/device/helios.rs b/src/device/helios.rs index 42373f0..59e5a54 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -15,7 +15,6 @@ use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; use chrono::Utc; -use crate::redis_ctrl::Line; pub struct HeliosDevice { pub conf: HeliosConf, diff --git a/src/main.rs b/src/main.rs index c7e8ccb..16cf14d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -13,7 +13,7 @@ mod worldstate; use device::device_factory; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use redis_ctrl::{RedisCtrl, Order, Line}; +use redis_ctrl::{RedisCtrl, Order}; use conf::Conf; use errors::LJResult; use point::{Point, Color}; @@ -75,22 +75,15 @@ fn run_all() -> LJResult<()> { rs.set_status(tracer.status())?; let order = rs.get_order(config.laser_id)?; - // 0 : Draw Normal point list - // 2 : Draw BLACK point list - // 3 : Draw GRID point list - // 1 : Get the new EDH = reread redis key /EDH/lasernumber - // 4 : Resampler Change (longs and shorts lsteps) - // 5 : Client Key Change = reread redis key /clientkey - // 6 : Max Intensity Change = reread redis key /intensity - // 7 : kpps change = reread redis key /kpps - // 8 : color balance change = reread redis keys /red /green /blue match order { Order::Draw | Order::Black | Order::Grid => { + // 0 : Draw Normal point list + // 2 : Draw BLACK point list + // 3 : Draw GRID point list world_state.draw_black = order == Order::Black; world_state.draw_grid = order == Order::Grid; - let frame = get_next_frame( &config, &transformers, @@ -101,19 +94,27 @@ fn run_all() -> LJResult<()> { tracer.draw(frame, world_state.kpps)?; } Order::Intensity => { + // 6 : Max Intensity Change = reread redis key /intensity world_state.intensity = rs.get_int("intensity")? .try_into()?; } Order::Edh => { + // 1 : Get the new EDH = reread redis key /EDH/lasernumber world_state.edh = rs.get_edh()?; } Order::Kpps => { + // 7 : kpps change = reread redis key /kpps world_state.kpps = rs.get_int("kpps")?; } - - // Order::ClientKey => rs.client_key(), + Order::ClientKey => { + world_state.client_key = rs.get_client_key()?; + }, // Order::ColorBalance => {}, _ => { + // 4 : Resampler Change (longs and shorts lsteps) + // 5 : Client Key Change = reread redis key /clientkey + // 8 : color balance change = reread redis keys /red /green /blue + // 9 : poweroff LJ world_state.intensity = rs.get_int("intensity")? info!("Order: {:?}", order); } } @@ -151,12 +152,12 @@ fn get_next_frame( // Handle the grid case - let mut line : Vec; + let mut line: Vec; if world_state.draw_grid { line = world_state.grid.clone(); } else { let redis_line = rs.get_line(&format_key)?; - line = redis_line.into_iter() + line = redis_line.into_iter() .map(|tpl| tpl.into()) .collect(); }; diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 4b13d8a..363fdc1 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -118,6 +118,11 @@ impl RedisCtrl { Ok(edh) } + pub fn get_client_key( &mut self ) -> LJResult { + let key : u8 = self.connection.get("/clientkey")?; + Ok(key as u8) + } + pub fn get_int(&mut self, key: &str ) -> LJResult { // Get new Int let fmt = format!("/{key}/{}", self.laser_id); diff --git a/src/worldstate.rs b/src/worldstate.rs index 7461c14..1f6bea2 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -2,7 +2,6 @@ use crate::point::{Point, Color}; use nalgebra::base::{Matrix3, Matrix1x3}; use crate::errors::{LJError, LJResult}; use log::debug; -use crate::redis_ctrl::Line; #[derive(Debug, Default)] pub struct EDH { @@ -41,7 +40,7 @@ impl EDH { pub struct WorldState { pub edh: EDH, pub resampler: Vec, - pub client_key: String, + pub client_key: u8, pub intensity: u8, pub kpps: u32, pub color: Color, From ffba2efeedfbb15d84ae79d0eef26237a32ff17d Mon Sep 17 00:00:00 2001 From: alban Date: Sun, 16 Jul 2023 20:26:45 +0200 Subject: [PATCH 29/48] fix: conf for etherdream uses ip --- src/conf.rs | 2 +- tests/settings/valid_etherdream.toml | 2 +- tests/test_conf.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/conf.rs b/src/conf.rs index 7d91cad..2996c7d 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -30,7 +30,7 @@ pub struct HeliosConf { #[derive(Serialize, Deserialize, Debug, Clone)] pub struct EtherDreamConf { - pub url: String + pub ip: String } #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/tests/settings/valid_etherdream.toml b/tests/settings/valid_etherdream.toml index b136ccf..836e934 100644 --- a/tests/settings/valid_etherdream.toml +++ b/tests/settings/valid_etherdream.toml @@ -12,4 +12,4 @@ redis_url = "redis://127.0.0.1:6379/" # For Etherdream. IP of the DAC [dac.etherdream] -url = "192.168.1.68" +ip = "192.168.1.68" diff --git a/tests/test_conf.rs b/tests/test_conf.rs index 1c7b77b..0dcb123 100644 --- a/tests/test_conf.rs +++ b/tests/test_conf.rs @@ -28,7 +28,7 @@ fn it_finds_struct_fields() { fn it_finds_etherdream_fields() { let config = Conf::new("tests/settings/valid_etherdream").unwrap(); assert!(match config.dac { - DacFamily::Etherdream(EtherDreamConf { url }) if url == "192.168.1.68" => true, + DacFamily::Etherdream(EtherDreamConf { ip }) if ip == "192.168.1.68" => true, _ => false, }); } From 86e32e08b11bff69cadd49bf7010eacba9e22f4e Mon Sep 17 00:00:00 2001 From: alban Date: Sun, 16 Jul 2023 20:28:06 +0200 Subject: [PATCH 30/48] feat: adds Etherdream device --- src/device.rs | 32 +++---- src/device/dummy.rs | 2 +- src/device/etherdream.rs | 181 ++++++++++++++++++++++++--------------- src/device/helios.rs | 2 +- src/errors.rs | 63 ++++++++------ src/main.rs | 12 ++- src/point.rs | 21 +++++ 7 files changed, 190 insertions(+), 123 deletions(-) diff --git a/src/device.rs b/src/device.rs index 83ae0fe..fe28f74 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,4 +1,3 @@ - mod helios; mod dummy; mod etherdream; @@ -10,6 +9,7 @@ use crate::device::dummy::DummyDevice; use crate::errors::LJResult; use crate::point::Point; use serde::Serialize; +use crate::device::etherdream::EtherdreamDevice; /* self.protocol_version, @@ -27,22 +27,24 @@ self.point_count #[derive(Debug, PartialEq, Serialize, Copy, Clone)] pub enum PlaybackState { IDLE = 0, - PREPARE, - PLAYING, -} -impl fmt::Display for PlaybackState { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self) - } + PREPARE = 1, + PLAYING = 2, + UNKNOWN = 99, } -#[derive(Debug, Default )] +impl fmt::Display for PlaybackState { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +#[derive(Debug)] pub struct Status { pub last_traced_at: String, pub properties: Vec, pub playback_state: PlaybackState, pub capacity: u16, - pub lack: String + pub lack: String, } // /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) @@ -50,7 +52,7 @@ pub struct Status { // /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. pub trait Device { - fn status(&self) -> Status; + fn status(&mut self) -> Status; fn draw( &mut self, frame: Vec, @@ -61,10 +63,10 @@ pub trait Device { } pub fn device_factory(config: &Conf) -> LJResult> { - let device : Box = match &config.dac { - DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?), - DacFamily::Etherdream(_conf) => todo!(), - DacFamily::Dummy => Box::new(DummyDevice::new()?) + let device: Box = match &config.dac { + DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?), + DacFamily::Etherdream( conf) => Box::new( EtherdreamDevice::new(conf)?), + DacFamily::Dummy => Box::new(DummyDevice::new()?) }; Ok(device) } diff --git a/src/device/dummy.rs b/src/device/dummy.rs index 544d6c8..724d132 100644 --- a/src/device/dummy.rs +++ b/src/device/dummy.rs @@ -14,7 +14,7 @@ impl DummyDevice { } impl Device for DummyDevice { - fn status(&self) -> Status { + fn status(&mut self) -> Status { Status { last_traced_at: "never".to_string(), properties: vec!["foo".to_string()], diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index fec964e..e620f61 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -1,108 +1,147 @@ -use ether_dream::{dac}; - - +use std::time; +use std::net::SocketAddr; +use ether_dream::dac::stream::connect; +use ether_dream::dac::Stream; use crate::conf::EtherDreamConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; -use crate::point::Point; -use chrono::Utc; +use crate::point::{Color, Point}; +use ether_dream::protocol::{DacBroadcast, DacStatus}; +use log::info; +#[warn(dead_code)] pub struct EtherdreamDevice { pub conf: EtherDreamConf, - dac: dac, - sent_points: u16, - state: PlaybackState, + dac: DacBroadcast, + // source_address: SocketAddr, + stream: Stream, + // sent_points: u16, lack: String, - last_traced_at : String + last_traced_at: String, } impl EtherdreamDevice { pub fn new(conf: &EtherDreamConf) -> LJResult { - let id = conf.id; - - // // Todo : use the config - // let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts() - // .expect("failed to bind to UDP socket") - // .filter_map(Result::ok) - // .next() - // .unwrap(); - // let mac_address = dac::MacAddress(dac_broadcast.mac_address); - // - // println!( - // "Discovered DAC \"{}\" at \"{}\"! Connecting...", - // mac_address, source_addr - // ); - - - // Establish the TCP connection. - let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap(); - - // If we want to create an animation (in our case a moving sine wave) we need a frame rate. - let frames_per_second = 60.0; - // Lets use the DAC at an eighth the maximum scan rate. - let points_per_second = stream.dac().max_point_rate / 32; - // Determine the number of points per frame given our target frame and point rates. - let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; - - // Prepare the DAC's playback engine and await the repsonse. - stream - .queue_commands() - .prepare_stream() - .submit() - .err() - .map(|err| { - eprintln!( - "err occurred when submitting PREPARE_STREAM \ - command and listening for response: {}", - err - ); - }); - - println!("Ready for playback!"); - + let (dac, _source_address, stream) = EtherdreamDevice::get_dac(conf)?; + // let (dac, source_address) = EtherdreamDevice::get_dac(conf)?; Ok(Self { conf: (*conf).clone(), dac, - sent_points: 0, - state: PlaybackState::PREPARE, + // source_address, + stream, + // sent_points: 0, lack: "".to_string(), - last_traced_at: "1985-04-12T23:20:50.52Z".to_string() + last_traced_at: "1985-04-12T23:20:50.52Z".to_string(), }) } + pub fn get_dac(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> { + let ip = &conf.ip; + let dac_broadcast = ether_dream::recv_dac_broadcasts()?; + dac_broadcast.set_nonblocking(true)?; + dac_broadcast.set_timeout(Some(time::Duration::new(60, 30)))?; + let broadcast = dac_broadcast + .filter_map(|result| { + info!("Received new broadcast {:?}", result); + if result.is_err() { return None; } + let (dac, source_addr) = result.unwrap(); + if source_addr.is_ipv6() { return None; } + if source_addr.ip().to_string() != ip.clone() { return None; } + info!("Valid broadcast"); + Some(Ok((dac, source_addr))) + }) + .next() + .ok_or(LJError::EtherdreamError("Failed to receive broadcast".to_string()))?; + match broadcast { + Err(err) => { + Err(Box::new(LJError::EtherdreamConnectError(err))) + } + Ok((dac, source_addr)) => { + let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?; + Ok((dac, source_addr, stream)) + } + } + } + + pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult { + // Establish the TCP connection. + let mut stream = connect(dac, source_address.ip())?; + + // Prepare stream + stream + .queue_commands() + .prepare_stream() + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting PREPARE_STREAM \ + command and listening for response: {}", + err + ); + }); + + Ok(stream) + } + + + pub fn check_tcp_stream(&mut self) -> LJResult<()> { + // todo Reinit stream if needed + // self.stream = EtherdreamDevice::get_tcp_stream(&self.dac, &self.source_address)? + Ok(()) + } + + // Determine the number of points needed to fill the DAC. + fn points_to_generate(&self) -> usize { + self.dac.buffer_capacity as usize - 1 - self.dac.dac_status.buffer_fullness as usize + } } impl Device for EtherdreamDevice { - fn status(&self) -> Status { + fn status(&mut self) -> Status { + let _ = self.check_tcp_stream(); + + // "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. + let playback_state = match self.dac.dac_status.playback_state { + DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE, + DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE, + DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING, + _ => PlaybackState::UNKNOWN + }; - let lack = self.lack.clone(); Status { - last_traced_at: self.last_traced_at.clone(), + last_traced_at: self.last_traced_at.clone(), properties: vec!["foo".to_string()], - playback_state: self.state, - capacity: self.sent_points, - lack, + playback_state, + capacity: self.dac.dac_status.buffer_fullness, + lack: String::from(&self.lack), } } fn draw(&mut self, line: Vec, - speed: u32, + _speed: u32, ) -> LJResult<()> { - self.state = PlaybackState::IDLE; - while let Ok(DeviceStatus::NotReady) = self.dac.status() {} - self.state = PlaybackState::PLAYING; - - let points: Vec = line.into_iter().map(|p| p.into()).collect(); - let frame = Frame::new(speed, points.clone()); - self.dac.write_frame(frame.clone())?; - self.sent_points = points.len() as u16; - self.last_traced_at = Utc::now().to_rfc3339(); + let n_points = self.points_to_generate(); + self.stream + .queue_commands() + .data(line.into_iter().map(|point| point.into()).take(n_points)) + .submit()?; Ok(()) } fn stop(&mut self) -> LJResult<()> { - self.dac.stop()?; + self.stream + .queue_commands() + .stop() + .submit() + .expect("err occurred when submitting STOP command and listening for response"); Ok(()) } + + fn grid(&mut self) -> Vec { + vec!( + Point { x: 0.0, y: 0.0, color: Color { r: 255, g: 255, b: 255 } } + ) + } } diff --git a/src/device/helios.rs b/src/device/helios.rs index 59e5a54..19a346c 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -46,7 +46,7 @@ impl HeliosDevice { } impl Device for HeliosDevice { - fn status(&self) -> Status { + fn status(&mut self) -> Status { let lack = self.lack.clone(); Status { last_traced_at: self.last_traced_at.clone(), diff --git a/src/errors.rs b/src/errors.rs index 1173dbe..16237d5 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,5 +1,5 @@ use std::error::Error; -use std::fmt; +use std::{fmt, io}; use redis::RedisError; use config::ConfigError; @@ -7,41 +7,48 @@ pub type LJResult = Result>; #[derive(Debug)] pub enum LJError { - Config(ConfigError), - RedisConnect(RedisError), - HeliosDeviceMissing, - BadEDH + Config(ConfigError), + RedisConnect(RedisError), + HeliosDeviceMissing, + BadEDH, + EtherdreamError(String), + EtherdreamConnectError(io::Error), } impl fmt::Display for LJError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use LJError::*; - - match self { - Config(err) => { - write!(f, "unable to load config file: {err}") - }, + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use LJError::*; - RedisConnect(err) => { - write!(f, "unable to connect to redis server: {err}") - }, - HeliosDeviceMissing => { - write!(f, "helios device not found") - }, - BadEDH => { - write!(f, "EDH matrix is not a 3x3 matrix") - } + match self { + Config(err) => { + write!(f, "unable to load config file: {err}") + } + RedisConnect(err) => { + write!(f, "unable to connect to redis server: {err}") + } + HeliosDeviceMissing => { + write!(f, "helios device not found") + } + BadEDH => { + write!(f, "EDH matrix is not a 3x3 matrix") + } + EtherdreamError(msg) => { + write!(f, "Unexpected Etherdream device error: {msg}") + } + EtherdreamConnectError(err) => { + write!(f, "Failed to retrieve Etherdream device: {err}") + } + } } - } } impl Error for LJError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - use LJError::*; + fn source(&self) -> Option<&(dyn Error + 'static)> { + use LJError::*; - match self { - RedisConnect(err) => Some(err), - _ => None + match self { + RedisConnect(err) => Some(err), + _ => None + } } - } } diff --git a/src/main.rs b/src/main.rs index 16cf14d..8e88018 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,7 +114,7 @@ fn run_all() -> LJResult<()> { // 4 : Resampler Change (longs and shorts lsteps) // 5 : Client Key Change = reread redis key /clientkey // 8 : color balance change = reread redis keys /red /green /blue - // 9 : poweroff LJ world_state.intensity = rs.get_int("intensity")? + // 9 : poweroff LJ info!("Order: {:?}", order); } } @@ -152,17 +152,15 @@ fn get_next_frame( // Handle the grid case - let mut line: Vec; - if world_state.draw_grid { - line = world_state.grid.clone(); + let mut line: Vec = if world_state.draw_grid { + world_state.grid.clone() } else { let redis_line = rs.get_line(&format_key)?; - line = redis_line.into_iter() + redis_line.into_iter() .map(|tpl| tpl.into()) - .collect(); + .collect() }; - for transformer in transformers { line = transformer.apply(&line, world_state); } diff --git a/src/point.rs b/src/point.rs index ed18697..b64a01d 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,3 +1,5 @@ +use ether_dream::protocol::DacPoint; + #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Point { pub x: f32, @@ -41,3 +43,22 @@ impl From for helios_dac::Point { } } } + +impl From for DacPoint { + fn from(pt: Point) -> DacPoint { + let control = 0; + let (u1, u2) = (0, 0); + let i = 255; + DacPoint { + control, + x: pt.x as i16, + y: pt.y as i16, + i, + r: pt.color.r.into(), + g: pt.color.g.into(), + b: pt.color.b.into(), + u1, + u2, + } + } +} From afaa397a524bcb0a6fdea875a96bf473299af8d2 Mon Sep 17 00:00:00 2001 From: alban Date: Sun, 16 Jul 2023 23:12:10 +0200 Subject: [PATCH 31/48] fix: the settings should use ip for etherdream --- copyme.settings.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/copyme.settings.toml b/copyme.settings.toml index 19182bb..fa9d255 100644 --- a/copyme.settings.toml +++ b/copyme.settings.toml @@ -20,7 +20,7 @@ id = 0 # For Etherdream. IP of the DAC # [dac.etherdream] -# url = "192.168.1.68" +# ip = "192.168.1.68" [[transformers]] [transformers.translate] From 60121a01c263a7c8ba84edd75b6d376acade61b1 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 17 Jul 2023 10:24:02 +0200 Subject: [PATCH 32/48] fix: client_key is a string --- src/redis_ctrl.rs | 8 ++++---- src/worldstate.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 363fdc1..9c245f5 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -101,7 +101,7 @@ impl RedisCtrl { pub fn init_world_state( &mut self) -> LJResult{ Ok(WorldState { - client_key: self.connection.get("/clientkey")?, + client_key: self.get_client_key()?, edh: self.get_edh()?, kpps: self.get_int("kpps")?.try_into()?, intensity: self.get_int("intensity")?.try_into()?, @@ -118,9 +118,9 @@ impl RedisCtrl { Ok(edh) } - pub fn get_client_key( &mut self ) -> LJResult { - let key : u8 = self.connection.get("/clientkey")?; - Ok(key as u8) + pub fn get_client_key( &mut self ) -> LJResult { + let key : String = self.connection.get("/clientkey")?; + Ok(key) } pub fn get_int(&mut self, key: &str ) -> LJResult { diff --git a/src/worldstate.rs b/src/worldstate.rs index 1f6bea2..e03edb1 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -40,7 +40,7 @@ impl EDH { pub struct WorldState { pub edh: EDH, pub resampler: Vec, - pub client_key: u8, + pub client_key: String, pub intensity: u8, pub kpps: u32, pub color: Color, From fd9ad6227899f91a39d162d891c5ea92dc38800f Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 17 Jul 2023 22:44:06 +0200 Subject: [PATCH 33/48] feat: add redis populate --- README.md | 0 examples/populate_redis.rs | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 README.md create mode 100644 examples/populate_redis.rs diff --git a/README.md b/README.md new file mode 100644 index 0000000..e69de29 diff --git a/examples/populate_redis.rs b/examples/populate_redis.rs new file mode 100644 index 0000000..cd95e77 --- /dev/null +++ b/examples/populate_redis.rs @@ -0,0 +1,24 @@ +/// +/// $ cargo run --example populate_redis +/// + +use redis::{ + //RedisResult, + Client, + Commands, + Connection, +}; + +fn do_something() -> redis::RedisResult<()> { + let client = Client::open("redis://127.0.0.1/")?; + let mut con: Connection = client.get_connection()?; + + let _ = con.set("/clientkey", "/pl/0/")?; + let _ = con.set("/EDH/0", "[[1.0, 0.0, 0.0],\n [ 0.0, 1.0, 0.0],\n [ 0.0, 0.0, 1.0]]")?; + let _ = con.set("/kpps/0", "5000")?; + let _ = con.set("/intensity/0", "255")?; + Ok(()) +} +fn main() { + _ = do_something(); +} From 4a87821c22264078c892ec12dd4999d15db867a3 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 17 Jul 2023 22:44:27 +0200 Subject: [PATCH 34/48] fix: various fixes for etherdream and debug --- README.md | 16 ++++++++++++++++ copyme.settings.toml | 9 +++++---- src/device/etherdream.rs | 28 +++++++++++++++++----------- src/errors.rs | 4 ---- src/main.rs | 2 +- src/redis_ctrl.rs | 8 ++++---- 6 files changed, 43 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index e69de29..f9ebc29 100644 --- a/README.md +++ b/README.md @@ -0,0 +1,16 @@ +# LJ rust + +## Crashcourse + +```shell + +# Copy and edit the settings file +$ cp copyme.settings.toml settings.toml + +# Populate the redis database +$ cargo run --example populate_redis + +# Run +$ cargo run --release + +``` \ No newline at end of file diff --git a/copyme.settings.toml b/copyme.settings.toml index fa9d255..ea131ff 100644 --- a/copyme.settings.toml +++ b/copyme.settings.toml @@ -1,4 +1,4 @@ -# file: Settings.toml +# file: settings.toml # Rename me ! # The main key of your laser in LJ @@ -12,11 +12,11 @@ redis_url = "redis://127.0.0.1:6379/" # Either Helios or Etherdream # For Helios. USB Device Id of the DAC -[dac.helios] -id = 0 +#[dac.helios] +#id = 0 # For dummy dac: -# [dac.dummy] + [dac.dummy] # For Etherdream. IP of the DAC # [dac.etherdream] @@ -26,6 +26,7 @@ id = 0 [transformers.translate] x = 2000 y = 2000 + [[transformers]] [transformers.replicate] Until = 48 diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index e620f61..d1aaac6 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -8,7 +8,7 @@ use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; use ether_dream::protocol::{DacBroadcast, DacStatus}; -use log::info; +use log::{info, warn}; #[warn(dead_code)] pub struct EtherdreamDevice { @@ -38,20 +38,26 @@ impl EtherdreamDevice { pub fn get_dac(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> { let ip = &conf.ip; let dac_broadcast = ether_dream::recv_dac_broadcasts()?; - dac_broadcast.set_nonblocking(true)?; - dac_broadcast.set_timeout(Some(time::Duration::new(60, 30)))?; + dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?; + info!("Attempting to get DAC broadcast..."); let broadcast = dac_broadcast .filter_map(|result| { - info!("Received new broadcast {:?}", result); - if result.is_err() { return None; } - let (dac, source_addr) = result.unwrap(); - if source_addr.is_ipv6() { return None; } - if source_addr.ip().to_string() != ip.clone() { return None; } - info!("Valid broadcast"); - Some(Ok((dac, source_addr))) + match result { + Err(err) => { + warn!( "Failed to find a valid DAC via broadcast. Error: {:?}", err); + info!( "Retrying..."); + None + }, + Ok((dac, source_addr)) => { + if source_addr.is_ipv6() { return None; } + if &source_addr.ip().to_string() != ip { return None; } + info!("Valid broadcast"); + Some(Ok((dac, source_addr))) + } + } }) .next() - .ok_or(LJError::EtherdreamError("Failed to receive broadcast".to_string()))?; + .expect("Failed to receive broadcast."); match broadcast { Err(err) => { Err(Box::new(LJError::EtherdreamConnectError(err))) diff --git a/src/errors.rs b/src/errors.rs index 16237d5..9640b11 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -11,7 +11,6 @@ pub enum LJError { RedisConnect(RedisError), HeliosDeviceMissing, BadEDH, - EtherdreamError(String), EtherdreamConnectError(io::Error), } @@ -32,9 +31,6 @@ impl fmt::Display for LJError { BadEDH => { write!(f, "EDH matrix is not a 3x3 matrix") } - EtherdreamError(msg) => { - write!(f, "Unexpected Etherdream device error: {msg}") - } EtherdreamConnectError(err) => { write!(f, "Failed to retrieve Etherdream device: {err}") } diff --git a/src/main.rs b/src/main.rs index 8e88018..501d8cd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -50,7 +50,7 @@ fn run_all() -> LJResult<()> { // Setup Redis Service let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; - let mut world_state = rs.init_world_state()?; + let mut world_state = rs.init_world_state().unwrap(); info!("WorldState: {:?}", world_state); // Setup handler for interrupt Signals diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 9c245f5..74ac5a0 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -101,10 +101,10 @@ impl RedisCtrl { pub fn init_world_state( &mut self) -> LJResult{ Ok(WorldState { - client_key: self.get_client_key()?, - edh: self.get_edh()?, - kpps: self.get_int("kpps")?.try_into()?, - intensity: self.get_int("intensity")?.try_into()?, + client_key: self.get_client_key().unwrap(), + edh: self.get_edh().unwrap(), + kpps: self.get_int("kpps").unwrap().try_into().unwrap(), + intensity: self.get_int("intensity").unwrap().try_into().unwrap(), ..WorldState::default() }) } From ae75092d340047d4e9caacd219f90f293100ca47 Mon Sep 17 00:00:00 2001 From: alban Date: Wed, 19 Jul 2023 01:28:45 +0200 Subject: [PATCH 35/48] feat: the etherdream device should work --- examples/etherdream.rs | 150 +++++++++++++++++++++++++++++++++++ src/device.rs | 3 +- src/device/etherdream.rs | 163 ++++++++++++++++++++++++++++++--------- src/main.rs | 39 ++++++---- src/point.rs | 18 ++++- 5 files changed, 316 insertions(+), 57 deletions(-) create mode 100644 examples/etherdream.rs diff --git a/examples/etherdream.rs b/examples/etherdream.rs new file mode 100644 index 0000000..e174a88 --- /dev/null +++ b/examples/etherdream.rs @@ -0,0 +1,150 @@ +extern crate ether_dream; + +use ether_dream::dac; + +fn main() { + println!("Listening for an Ether Dream DAC..."); + + let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts() + .expect("failed to bind to UDP socket") + .filter_map(Result::ok) + .next() + .unwrap(); + let mac_address = dac::MacAddress(dac_broadcast.mac_address); + + println!( + "Discovered DAC \"{}\" at \"{}\"! Connecting...", + mac_address, source_addr + ); + + // Establish the TCP connection. + let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap(); + + // If we want to create an animation (in our case a moving sine wave) we need a frame rate. + let frames_per_second = 60.0; + // Lets use the DAC at an eighth the maximum scan rate. + let points_per_second = stream.dac().max_point_rate / 32; + // Determine the number of points per frame given our target frame and point rates. + let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; + + println!( + "Preparing for playback:\n\tframe_hz: {}\n\tpoint_hz: {}\n\tpoints_per_frame: {}\n", + frames_per_second, points_per_second, points_per_frame + ); + + // Prepare the DAC's playback engine and await the repsonse. + stream + .queue_commands() + .prepare_stream() + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting PREPARE_STREAM \ + command and listening for response: {}", + err + ); + }); + + println!("Beginning playback!"); + + // The sine wave used to generate points. + let mut sine_wave = SineWave { + point: 0, + points_per_frame, + frames_per_second, + }; + + // Queue the initial frame and tell the DAC to begin producing output. + let n_points = points_to_generate(stream.dac()); + stream + .queue_commands() + .data(sine_wave.by_ref().take(n_points)) + .begin(0, points_per_second) + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting initial DATA and BEGIN \ + commands and listening for response: {}", + err + ); + }); + + // Loop and continue to send points forever. + loop { + // Determine how many points the DAC can currently receive. + let n_points = points_to_generate(stream.dac()); + if let Err(err) = stream + .queue_commands() + .data(sine_wave.by_ref().take(n_points)) + .submit() + { + eprintln!( + "err occurred when submitting DATA command and listening \ + for response: {}", + err + ); + break; + } + } + + // Tell the DAC to stop producing output and return to idle. Wait for the response. + // + // Note that the DAC is commanded to stop on `Drop` if this is not called and any errors + // produced are ignored. + stream + .queue_commands() + .stop() + .submit() + .expect("err occurred when submitting STOP command and listening for response"); +} + +// Determine the number of points needed to fill the DAC. +fn points_to_generate(dac: ðer_dream::dac::Dac) -> usize { + dac.buffer_capacity as usize - 1 - dac.status.buffer_fullness as usize +} + +// An iterator that endlessly generates a sine wave of DAC points. +// +// The sine wave oscillates at a rate of once per second. +struct SineWave { + point: u32, + points_per_frame: u16, + frames_per_second: f32, +} + +impl Iterator for SineWave { + type Item = ether_dream::protocol::DacPoint; + fn next(&mut self) -> Option { + let coloured_points_per_frame = self.points_per_frame - 1; + let i = (self.point % self.points_per_frame as u32) as u16; + let hz = 1.0; + let fract = i as f32 / coloured_points_per_frame as f32; + let phase = (self.point as f32 / coloured_points_per_frame as f32) / self.frames_per_second; + let amp = (hz * (fract + phase) * 2.0 * std::f32::consts::PI).sin(); + let (r, g, b) = match i { + i if i == coloured_points_per_frame || i < 13 => (0, 0, 0), + _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), + }; + let x_min = std::i16::MIN; + let x_max = std::i16::MAX; + let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; + let y = (amp * x_max as f32) as i16; + let control = 0; + let (u1, u2) = (0, 0); + let p = ether_dream::protocol::DacPoint { + control, + x, + y, + i, + r, + g, + b, + u1, + u2, + }; + self.point += 1; + Some(p) + } +} \ No newline at end of file diff --git a/src/device.rs b/src/device.rs index fe28f74..6cbf0d5 100644 --- a/src/device.rs +++ b/src/device.rs @@ -28,8 +28,7 @@ self.point_count pub enum PlaybackState { IDLE = 0, PREPARE = 1, - PLAYING = 2, - UNKNOWN = 99, + PLAYING = 2 } impl fmt::Display for PlaybackState { diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index d1aaac6..d5bc4e8 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -1,14 +1,14 @@ use std::time; use std::net::SocketAddr; use ether_dream::dac::stream::connect; -use ether_dream::dac::Stream; +use ether_dream::dac::{Playback, Stream}; use crate::conf::EtherDreamConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; -use ether_dream::protocol::{DacBroadcast, DacStatus}; -use log::{info, warn}; +use ether_dream::protocol::{DacBroadcast, DacPoint}; +use log::{debug, info, warn}; #[warn(dead_code)] pub struct EtherdreamDevice { @@ -21,10 +21,11 @@ pub struct EtherdreamDevice { last_traced_at: String, } + impl EtherdreamDevice { pub fn new(conf: &EtherDreamConf) -> LJResult { let (dac, _source_address, stream) = EtherdreamDevice::get_dac(conf)?; - // let (dac, source_address) = EtherdreamDevice::get_dac(conf)?; + Ok(Self { conf: (*conf).clone(), dac, @@ -41,17 +42,18 @@ impl EtherdreamDevice { dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?; info!("Attempting to get DAC broadcast..."); let broadcast = dac_broadcast + .take(3) .filter_map(|result| { match result { Err(err) => { warn!( "Failed to find a valid DAC via broadcast. Error: {:?}", err); info!( "Retrying..."); None - }, + } Ok((dac, source_addr)) => { + info!("Valid broadcast, source_addr: {}", source_addr); if source_addr.is_ipv6() { return None; } if &source_addr.ip().to_string() != ip { return None; } - info!("Valid broadcast"); Some(Ok((dac, source_addr))) } } @@ -64,6 +66,7 @@ impl EtherdreamDevice { } Ok((dac, source_addr)) => { let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?; + info!("Finished configuring DAC and TCP stream."); Ok((dac, source_addr, stream)) } } @@ -72,22 +75,61 @@ impl EtherdreamDevice { pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult { // Establish the TCP connection. let mut stream = connect(dac, source_address.ip())?; + EtherdreamDevice::prepare_tcp_stream(&mut stream).unwrap(); + Ok(stream) + } + + fn prepare_tcp_stream(stream: &mut Stream) -> LJResult<()> { // Prepare stream - stream + match stream .queue_commands() .prepare_stream() - .submit() - .err() - .map(|err| { - eprintln!( - "err occurred when submitting PREPARE_STREAM \ - command and listening for response: {}", + .submit() { + Err(err) => { + warn!( + "err occurred when submitting PREPARE_STREAM command and listening for response: {}", err ); - }); + } + Ok(_) => { + info!("Prepared Stream.") + } + } - Ok(stream) + let control = 0; + let (u1, u2) = (0, 0); + let i = 255; + let point = DacPoint { + control, + x: 0, + y: 0, + i, + r: 0, + g: 0, + b: 0, + u1, + u2, + }; + let begin_list = vec![point]; + let points_per_second = stream.dac().max_point_rate / 32; + match stream + .queue_commands() + .data(begin_list.into_iter().take(1 as usize)) + .begin(0, points_per_second) + .submit() { + Err(err) => { + warn!( + "err occurred when submitting first data: {}", + err + ); + } + Ok(_) => { + info!("Sent first data to Etherdream.") + } + } + + Ok(()) } @@ -98,8 +140,10 @@ impl EtherdreamDevice { } // Determine the number of points needed to fill the DAC. - fn points_to_generate(&self) -> usize { - self.dac.buffer_capacity as usize - 1 - self.dac.dac_status.buffer_fullness as usize + fn points_capacity(&self) -> u16 { + // Fixme thread 'main' panicked at 'attempt to subtract with overflow', src/device/etherdream.rs:144:24 + let n_points = self.dac.buffer_capacity as u16 - self.stream.dac().dac.status.buffer_fullness as u16 - 1; + n_points } } @@ -108,46 +152,93 @@ impl Device for EtherdreamDevice { let _ = self.check_tcp_stream(); // "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. - let playback_state = match self.dac.dac_status.playback_state { - DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE, - DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE, - DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING, - _ => PlaybackState::UNKNOWN + let playback_state = match self.stream.dac().dac.status.playback { + Playback::Idle => PlaybackState::IDLE, + Playback::Prepared => PlaybackState::PREPARE, + Playback::Playing => PlaybackState::PLAYING, }; - Status { + let status = Status { last_traced_at: self.last_traced_at.clone(), properties: vec!["foo".to_string()], playback_state, - capacity: self.dac.dac_status.buffer_fullness, + capacity: self.points_capacity(), lack: String::from(&self.lack), - } + }; + // info!("Dac Status: {:?} ", status ); + // info!("Etherdream Dac {:?} ", self.dac ); + // info!("Stream dac{:?}", self.stream.dac()); + + status } fn draw(&mut self, line: Vec, _speed: u32, ) -> LJResult<()> { - let n_points = self.points_to_generate(); - self.stream + let n_points = self.points_capacity(); + // let n_points = &line.len(); + debug!("Etherdream::device draw Generating {:?} points", n_points); + return match self.stream .queue_commands() - .data(line.into_iter().map(|point| point.into()).take(n_points)) - .submit()?; - Ok(()) + .data( + line.into_iter() + .map(|point| point.into()) + // .take(line.len() as usize) + .take(n_points as usize ) + ) + .submit() { + Err(err) => { + // We should account for + // 'Broken pipe (os error 32)' + // Connection reset by peer (os error 104) + warn!("Draw error: '{}'",err); + Ok(()) + } + Ok(_) => { + debug!("Draw is ok"); + Ok(()) + } + }; } fn stop(&mut self) -> LJResult<()> { - self.stream + info!("Stopping Etherdream device..."); + match self.stream .queue_commands() .stop() .submit() - .expect("err occurred when submitting STOP command and listening for response"); - Ok(()) + { + Err(err) => { + warn!("Failed to stop EtherDream device with error {:?}", err); + Err(Box::new(err)) + } + Ok(_) => { + info!("Sucessfully closed EtherDream device."); + Ok(()) + } + } } fn grid(&mut self) -> Vec { - vec!( - Point { x: 0.0, y: 0.0, color: Color { r: 255, g: 255, b: 255 } } - ) + let dim_mid = 16000 as f32; + let dim_max = 32000 as f32; + let col_min = Color { r: 0, g: 0, b: 0 }; + let col_max = Color { r: 255, g: 255, b: 255 }; + + vec![ + Point { x: -dim_max, y: dim_max, color: col_min }, + Point { x: -dim_max, y: dim_max, color: col_max }, + Point { x: dim_max, y: dim_max, color: col_max }, + Point { x: dim_max, y: -dim_max, color: col_max }, + Point { x: -dim_max, y: -dim_max, color: col_max }, + Point { x: -dim_max, y: -dim_mid, color: col_min }, + Point { x: -dim_mid, y: dim_mid, color: col_min }, + Point { x: -dim_mid, y: dim_mid, color: col_max }, + Point { x: dim_mid, y: dim_mid, color: col_max }, + Point { x: dim_mid, y: -dim_mid, color: col_max }, + Point { x: -dim_mid, y: -dim_mid, color: col_max }, + Point { x: -dim_mid, y: -dim_mid, color: col_min }, + ] } } diff --git a/src/main.rs b/src/main.rs index 501d8cd..2624273 100644 --- a/src/main.rs +++ b/src/main.rs @@ -35,6 +35,13 @@ pub fn main() { fn run_all() -> LJResult<()> { + // Setup handler for interrupt Signals + let running = Arc::new(AtomicBool::new(true)); + let r = running.clone(); + ctrlc::set_handler(move || { + r.store(false, Ordering::SeqCst); + })?; + // Setup configuration file and set up logs let filename = std::env::args().nth(1).unwrap_or_else(|| { DEFAULT_CONF_FILE.to_string() @@ -53,12 +60,6 @@ fn run_all() -> LJResult<()> { let mut world_state = rs.init_world_state().unwrap(); info!("WorldState: {:?}", world_state); - // Setup handler for interrupt Signals - let running = Arc::new(AtomicBool::new(true)); - let r = running.clone(); - ctrlc::set_handler(move || { - r.store(false, Ordering::SeqCst); - })?; // Setup Laser Device based on conf let mut tracer = device_factory(&config)?; @@ -108,7 +109,7 @@ fn run_all() -> LJResult<()> { } Order::ClientKey => { world_state.client_key = rs.get_client_key()?; - }, + } // Order::ColorBalance => {}, _ => { // 4 : Resampler Change (longs and shorts lsteps) @@ -127,14 +128,18 @@ fn run_all() -> LJResult<()> { fn init_logging(config: &LJResult) { if let Ok(ref config) = config { - if config.debug { - let mut builder = Builder::from_default_env(); - builder - .filter(None, LevelFilter::Info) - .init(); - info!("Debug mode enabled from configuration file"); - return; - } + + let level = if config.debug { + LevelFilter::Debug + } else { + LevelFilter::Info + }; + let mut builder = Builder::from_default_env(); + builder + .filter(None, level) + .init(); + info!("Debug mode enabled from configuration file"); + return; } info!("Logging level inherited from env"); env_logger::init(); @@ -165,8 +170,8 @@ fn get_next_frame( line = transformer.apply(&line, world_state); } - info!("Draw Black -> {}", world_state.draw_black); - info!("Draw Grid -> {}", world_state.draw_grid); + // info!("Draw Black -> {}", world_state.draw_black); + // info!("Draw Grid -> {}", world_state.draw_grid); // LIMITER and BLACK line = line.into_iter() diff --git a/src/point.rs b/src/point.rs index b64a01d..d060fd5 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,5 +1,15 @@ use ether_dream::protocol::DacPoint; +fn clamp(val: f32, min: f32, max: f32) -> f32 { + if val < min { + return min; + } + if val > max { + return max; + } + val +} + #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Point { pub x: f32, @@ -45,14 +55,18 @@ impl From for helios_dac::Point { } impl From for DacPoint { + fn from(pt: Point) -> DacPoint { + print!("."); let control = 0; let (u1, u2) = (0, 0); let i = 255; + let x = clamp(pt.x, -32000 as f32, 32000 as f32); + let y = clamp(pt.y, -32000 as f32, 32000 as f32); DacPoint { control, - x: pt.x as i16, - y: pt.y as i16, + x: x as i16, + y: y as i16, i, r: pt.color.r.into(), g: pt.color.g.into(), From 8e10e0d82ed43fbfe72b40284594adbba572d2a0 Mon Sep 17 00:00:00 2001 From: alban Date: Wed, 19 Jul 2023 21:39:25 +0200 Subject: [PATCH 36/48] fix: /etherdream some cleanup and better error management --- examples/populate_redis.rs | 34 ++++++---- src/device/etherdream.rs | 134 ++++++++++++++++--------------------- src/point.rs | 1 - 3 files changed, 78 insertions(+), 91 deletions(-) diff --git a/examples/populate_redis.rs b/examples/populate_redis.rs index cd95e77..a1d43fe 100644 --- a/examples/populate_redis.rs +++ b/examples/populate_redis.rs @@ -1,24 +1,34 @@ -/// -/// $ cargo run --example populate_redis -/// +use std::io::_print; +/** + +# Populate Redis Example + +**This script simulates the redis content provided by the LJ Python / web tool** + +$ cargo run --example populate_redis + **/ use redis::{ - //RedisResult, - Client, - Commands, - Connection, + //RedisResult, + Client, + Commands, + Connection, }; fn do_something() -> redis::RedisResult<()> { - let client = Client::open("redis://127.0.0.1/")?; - let mut con: Connection = client.get_connection()?; - + let client = Client::open("redis://127.0.0.1/")?; + let mut con: Connection = client.get_connection()?; let _ = con.set("/clientkey", "/pl/0/")?; let _ = con.set("/EDH/0", "[[1.0, 0.0, 0.0],\n [ 0.0, 1.0, 0.0],\n [ 0.0, 0.0, 1.0]]")?; let _ = con.set("/kpps/0", "5000")?; let _ = con.set("/intensity/0", "255")?; - Ok(()) + let _ = con.set("/pl/0/0", "[(-300, 300, 0), (-300, -300, 65280), (300, -300, 65280), (300, 300, 65280), (-300, 300, 65280)]")?; + Ok(()) } + fn main() { - _ = do_something(); + match do_something() { + Err(err) => println!("Something wrong occured: {:?}", err), + Ok(..) => println!("Successfully inserted content in Redis") + } } diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index d5bc4e8..86b6a6b 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -1,42 +1,48 @@ use std::time; use std::net::SocketAddr; -use ether_dream::dac::stream::connect; +use ether_dream::dac::stream::{CommunicationError, connect}; use ether_dream::dac::{Playback, Stream}; +use chrono::{DateTime, Utc}; +use std::time::SystemTime; use crate::conf::EtherDreamConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; -use ether_dream::protocol::{DacBroadcast, DacPoint}; +use ether_dream::protocol::{DacBroadcast, DacPoint, DacResponse}; use log::{debug, info, warn}; #[warn(dead_code)] pub struct EtherdreamDevice { pub conf: EtherDreamConf, dac: DacBroadcast, - // source_address: SocketAddr, stream: Stream, - // sent_points: u16, - lack: String, - last_traced_at: String, -} + // "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. + // /// The previous command was accepted. + // pub const ACK: u8 = 0x61; + // /// The write command could not be performed because there was not enough buffer space when it + // /// was received. + // pub const NAK_FULL: u8 = 0x46; + // /// The command contained an invalid `command` byte or parameters. + // pub const NAK_INVALID: u8 = 0x49; + // /// An emergency-stop condition still exists. + // pub const NAK_STOP_CONDITION: u8 = 0x21; + // } + dac_response: u8, +} impl EtherdreamDevice { pub fn new(conf: &EtherDreamConf) -> LJResult { - let (dac, _source_address, stream) = EtherdreamDevice::get_dac(conf)?; - + let (dac, _source_address, stream) = EtherdreamDevice::connect(conf)?; Ok(Self { conf: (*conf).clone(), dac, - // source_address, stream, - // sent_points: 0, - lack: "".to_string(), - last_traced_at: "1985-04-12T23:20:50.52Z".to_string(), + dac_response: DacResponse::ACK, }) } - pub fn get_dac(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> { + fn connect(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> { let ip = &conf.ip; let dac_broadcast = ether_dream::recv_dac_broadcasts()?; dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?; @@ -72,75 +78,34 @@ impl EtherdreamDevice { } } - pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult { - // Establish the TCP connection. + fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult { let mut stream = connect(dac, source_address.ip())?; - EtherdreamDevice::prepare_tcp_stream(&mut stream).unwrap(); - Ok(stream) - } - - fn prepare_tcp_stream(stream: &mut Stream) -> LJResult<()> { - - // Prepare stream match stream .queue_commands() .prepare_stream() .submit() { - Err(err) => { - warn!( - "err occurred when submitting PREPARE_STREAM command and listening for response: {}", - err - ); - } - Ok(_) => { - info!("Prepared Stream.") - } + Err(err) => warn!("err occurred when submitting PREPARE_STREAM command and listening for response: {}",err), + Ok(_) => info!("Prepared Stream.") } - - let control = 0; - let (u1, u2) = (0, 0); - let i = 255; - let point = DacPoint { - control, - x: 0, - y: 0, - i, - r: 0, - g: 0, - b: 0, - u1, - u2, - }; - let begin_list = vec![point]; + let begin_list = vec![ + DacPoint { control: 0, x: 0, y: 0, i: 255, r: 0, g: 0, b: 0, u1: 0, u2: 0 }, + ]; let points_per_second = stream.dac().max_point_rate / 32; match stream .queue_commands() .data(begin_list.into_iter().take(1 as usize)) .begin(0, points_per_second) .submit() { - Err(err) => { - warn!( - "err occurred when submitting first data: {}", - err - ); - } - Ok(_) => { - info!("Sent first data to Etherdream.") - } + Err(err) => warn!("err occurred when submitting first data: {}",err), + Ok(_) => info!("Sent first data to Etherdream.") } - - Ok(()) + Ok(stream) } - - pub fn check_tcp_stream(&mut self) -> LJResult<()> { - // todo Reinit stream if needed - // self.stream = EtherdreamDevice::get_tcp_stream(&self.dac, &self.source_address)? - Ok(()) - } - - // Determine the number of points needed to fill the DAC. fn points_capacity(&self) -> u16 { + /*** + Determine the number of points needed to fill the DAC. + ***/ // Fixme thread 'main' panicked at 'attempt to subtract with overflow', src/device/etherdream.rs:144:24 let n_points = self.dac.buffer_capacity as u16 - self.stream.dac().dac.status.buffer_fullness as u16 - 1; n_points @@ -149,26 +114,25 @@ impl EtherdreamDevice { impl Device for EtherdreamDevice { fn status(&mut self) -> Status { - let _ = self.check_tcp_stream(); - - // "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. let playback_state = match self.stream.dac().dac.status.playback { Playback::Idle => PlaybackState::IDLE, Playback::Prepared => PlaybackState::PREPARE, Playback::Playing => PlaybackState::PLAYING, }; + let now = SystemTime::now(); + let now: DateTime = now.into(); + let now = now.to_rfc3339(); let status = Status { - last_traced_at: self.last_traced_at.clone(), + last_traced_at: now, properties: vec!["foo".to_string()], playback_state, capacity: self.points_capacity(), - lack: String::from(&self.lack), + lack: self.dac_response.to_string(), }; // info!("Dac Status: {:?} ", status ); // info!("Etherdream Dac {:?} ", self.dac ); // info!("Stream dac{:?}", self.stream.dac()); - status } @@ -179,27 +143,41 @@ impl Device for EtherdreamDevice { let n_points = self.points_capacity(); // let n_points = &line.len(); debug!("Etherdream::device draw Generating {:?} points", n_points); - return match self.stream + match self.stream .queue_commands() .data( line.into_iter() .map(|point| point.into()) // .take(line.len() as usize) - .take(n_points as usize ) + .take(n_points as usize) ) .submit() { Err(err) => { // We should account for // 'Broken pipe (os error 32)' // Connection reset by peer (os error 104) - warn!("Draw error: '{}'",err); - Ok(()) + self.dac_response = match err { + CommunicationError::Io(err) => { + warn!("IO ERROR while drawing: '{}'",err); + DacResponse::ACK + } + CommunicationError::Protocol(err) => { + warn!("Protocol ERROR while drawing: '{}'",err); + DacResponse::ACK + } + CommunicationError::Response(err) => { + warn!("Response ERROR while drawing: '{}'",err); + err.response.response + } + }; + } Ok(_) => { + self.dac_response = DacResponse::ACK; debug!("Draw is ok"); - Ok(()) } }; + Ok(()) } fn stop(&mut self) -> LJResult<()> { diff --git a/src/point.rs b/src/point.rs index d060fd5..1298905 100644 --- a/src/point.rs +++ b/src/point.rs @@ -57,7 +57,6 @@ impl From for helios_dac::Point { impl From for DacPoint { fn from(pt: Point) -> DacPoint { - print!("."); let control = 0; let (u1, u2) = (0, 0); let i = 255; From 4719dcc4305fa85f6b668dd856a6017e8ae9df37 Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 20 Jul 2023 00:54:24 +0200 Subject: [PATCH 37/48] feat: more dispatch actions and cosmetic --- src/main.rs | 18 +++++-------- src/redis_ctrl.rs | 69 ++++++++++++++++++++++++++--------------------- src/worldstate.rs | 4 ++- 3 files changed, 49 insertions(+), 42 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2624273..62067a8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -65,19 +65,13 @@ fn run_all() -> LJResult<()> { let mut tracer = device_factory(&config)?; world_state.grid = tracer.grid(); - // can't work, but we can add + Debug to Device to make it work... - //dbg!(tracer); - // Setup geometry transformers on points lists let transformers = config.get_transformers(); // Dispatch based on redis requests while running.load(Ordering::SeqCst) { rs.set_status(tracer.status())?; - let order = rs.get_order(config.laser_id)?; - - match order { Order::Draw | Order::Black | Order::Grid => { // 0 : Draw Normal point list @@ -110,11 +104,14 @@ fn run_all() -> LJResult<()> { Order::ClientKey => { world_state.client_key = rs.get_client_key()?; } - // Order::ColorBalance => {}, + Order::ColorBalance => { + let (r, g, b) = rs.get_color_balance()?; + world_state.color_balance = Color { r, g, b }; + } + Order::Resampler => { + world_state.resampler = rs.get_resampler()?; + } _ => { - // 4 : Resampler Change (longs and shorts lsteps) - // 5 : Client Key Change = reread redis key /clientkey - // 8 : color balance change = reread redis keys /red /green /blue // 9 : poweroff LJ info!("Order: {:?}", order); } @@ -128,7 +125,6 @@ fn run_all() -> LJResult<()> { fn init_logging(config: &LJResult) { if let Ok(ref config) = config { - let level = if config.debug { LevelFilter::Debug } else { diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 74ac5a0..9b4bb4a 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -2,7 +2,7 @@ use redis::{Client, Commands, Connection}; use ron::de::from_str; use crate::device::Status; use crate::errors::{LJError, LJResult}; -use crate::worldstate::{WorldState,EDH}; +use crate::worldstate::{WorldState, EDH}; // use log::info; #[repr(u8)] @@ -10,7 +10,6 @@ use crate::worldstate::{WorldState,EDH}; pub enum Order { Draw = 0, Edh, - //homography Black, Grid, Resampler, @@ -46,6 +45,7 @@ impl TryFrom for Order { } pub type Line = Vec<(f32, f32, u32)>; +pub type Resampler = Vec<(f32,f32)>; pub struct RedisCtrl { pub client: Client, @@ -84,11 +84,6 @@ impl RedisCtrl { Ok(val.try_into()?) } - /** - /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) - /cap/lasernumber number of empty points sent to fill etherdream buffer (up to 1799) - /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. - **/ pub fn set_status(&mut self, status: Status) -> LJResult<()> { let lstt_key = format!("/lstt/{}", self.laser_id); let cap_key = format!("/cap/{}", self.laser_id); @@ -99,34 +94,48 @@ impl RedisCtrl { Ok(()) } - pub fn init_world_state( &mut self) -> LJResult{ - Ok(WorldState { - client_key: self.get_client_key().unwrap(), - edh: self.get_edh().unwrap(), - kpps: self.get_int("kpps").unwrap().try_into().unwrap(), - intensity: self.get_int("intensity").unwrap().try_into().unwrap(), - ..WorldState::default() - }) + pub fn init_world_state(&mut self) -> LJResult { + Ok(WorldState { + client_key: self.get_client_key().unwrap(), + edh: self.get_edh().unwrap(), + kpps: self.get_int("kpps").unwrap().try_into().unwrap(), + intensity: self.get_int("intensity").unwrap().try_into().unwrap(), + ..WorldState::default() + }) } - pub fn get_edh( &mut self ) -> LJResult { - // Get new EDH - let edh_key = format!("/EDH/{}", self.laser_id); - let edh : String = self.connection.get(edh_key)?; - let edh : Vec> = from_str(&edh)?; - let edh = EDH::new(edh)?; - Ok(edh) + pub fn get_edh(&mut self) -> LJResult { + // Get new EDH + let edh_key = format!("/EDH/{}", self.laser_id); + let edh: String = self.connection.get(edh_key)?; + let edh: Vec> = from_str(&edh)?; + let edh = EDH::new(edh)?; + Ok(edh) } - pub fn get_client_key( &mut self ) -> LJResult { - let key : String = self.connection.get("/clientkey")?; - Ok(key) + pub fn get_client_key(&mut self) -> LJResult { + let key: String = self.connection.get("/clientkey")?; + Ok(key) } - pub fn get_int(&mut self, key: &str ) -> LJResult { - // Get new Int - let fmt = format!("/{key}/{}", self.laser_id); - let val : u32 = self.connection.get(fmt)?; - Ok(val) + pub fn get_color_balance(&mut self) -> LJResult<(u8, u8, u8)> { + Ok(( + self.connection.get("/red")?, + self.connection.get("/green")?, + self.connection.get("/blue")?, + )) + } + + pub fn get_resampler(&mut self ) -> LJResult { + let val: String = self.connection.get(format!("/resampler/{}", self.laser_id))?; + let resampler : Resampler = from_str(&val)?; + Ok(resampler) + } + + pub fn get_int(&mut self, key: &str) -> LJResult { + // Get new Int + let fmt = format!("/{key}/{}", self.laser_id); + let val: u32 = self.connection.get(fmt)?; + Ok(val) } } diff --git a/src/worldstate.rs b/src/worldstate.rs index e03edb1..4c1366c 100644 --- a/src/worldstate.rs +++ b/src/worldstate.rs @@ -2,6 +2,7 @@ use crate::point::{Point, Color}; use nalgebra::base::{Matrix3, Matrix1x3}; use crate::errors::{LJError, LJResult}; use log::debug; +use crate::redis_ctrl::Resampler; #[derive(Debug, Default)] pub struct EDH { @@ -39,7 +40,7 @@ impl EDH { #[derive(Debug, Default)] pub struct WorldState { pub edh: EDH, - pub resampler: Vec, + pub resampler: Resampler, pub client_key: String, pub intensity: u8, pub kpps: u32, @@ -47,6 +48,7 @@ pub struct WorldState { pub draw_black: bool, pub draw_grid: bool, pub grid: Vec, + pub color_balance: Color, } impl WorldState {} From 71fabde38565a6af515231fdc9f036703d918257 Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 20 Jul 2023 21:11:57 +0200 Subject: [PATCH 38/48] fix: Resampler should have correct type --- src/redis_ctrl.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 9b4bb4a..4fdcdde 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -45,7 +45,7 @@ impl TryFrom for Order { } pub type Line = Vec<(f32, f32, u32)>; -pub type Resampler = Vec<(f32,f32)>; +pub type Resampler = Vec>; pub struct RedisCtrl { pub client: Client, From 810a3677de4b640449c5449a48ecc3b725926747 Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 20 Jul 2023 21:12:17 +0200 Subject: [PATCH 39/48] fix: populate redis general geometry --- examples/populate_redis.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/populate_redis.rs b/examples/populate_redis.rs index a1d43fe..307acd6 100644 --- a/examples/populate_redis.rs +++ b/examples/populate_redis.rs @@ -22,7 +22,7 @@ fn do_something() -> redis::RedisResult<()> { let _ = con.set("/EDH/0", "[[1.0, 0.0, 0.0],\n [ 0.0, 1.0, 0.0],\n [ 0.0, 0.0, 1.0]]")?; let _ = con.set("/kpps/0", "5000")?; let _ = con.set("/intensity/0", "255")?; - let _ = con.set("/pl/0/0", "[(-300, 300, 0), (-300, -300, 65280), (300, -300, 65280), (300, 300, 65280), (-300, 300, 65280)]")?; + let _ = con.set("/pl/0/0", "[(1000, 2000, 0), (1000, 1000, 65535), (2000, 1000, 65535), (2000, 2000, 65535), (1000, 2000, 65535)]")?; Ok(()) } From f45b9e5748aaa40da2111c5f621e2e85969c003b Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 20 Jul 2023 21:12:34 +0200 Subject: [PATCH 40/48] fix: dac/etherdream should work --- examples/etherdream.rs | 235 ++++++++++++++++++++------------------- src/device/etherdream.rs | 90 +++++++++++++-- src/point.rs | 7 +- 3 files changed, 204 insertions(+), 128 deletions(-) diff --git a/examples/etherdream.rs b/examples/etherdream.rs index e174a88..75d888c 100644 --- a/examples/etherdream.rs +++ b/examples/etherdream.rs @@ -3,148 +3,149 @@ extern crate ether_dream; use ether_dream::dac; fn main() { - println!("Listening for an Ether Dream DAC..."); + println!("Listening for an Ether Dream DAC..."); - let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts() - .expect("failed to bind to UDP socket") - .filter_map(Result::ok) - .next() - .unwrap(); - let mac_address = dac::MacAddress(dac_broadcast.mac_address); + let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts() + .expect("failed to bind to UDP socket") + .filter_map(Result::ok) + .next() + .unwrap(); + let mac_address = dac::MacAddress(dac_broadcast.mac_address); - println!( - "Discovered DAC \"{}\" at \"{}\"! Connecting...", - mac_address, source_addr - ); + println!( + "Discovered DAC \"{}\" at \"{}\"! Connecting...", + mac_address, source_addr + ); - // Establish the TCP connection. - let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap(); + // Establish the TCP connection. + let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap(); - // If we want to create an animation (in our case a moving sine wave) we need a frame rate. - let frames_per_second = 60.0; - // Lets use the DAC at an eighth the maximum scan rate. - let points_per_second = stream.dac().max_point_rate / 32; - // Determine the number of points per frame given our target frame and point rates. - let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; + // If we want to create an animation (in our case a moving sine wave) we need a frame rate. + let frames_per_second = 60.0; + // Lets use the DAC at an eighth the maximum scan rate. + let points_per_second = stream.dac().max_point_rate / 32; + // Determine the number of points per frame given our target frame and point rates. + let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; - println!( - "Preparing for playback:\n\tframe_hz: {}\n\tpoint_hz: {}\n\tpoints_per_frame: {}\n", - frames_per_second, points_per_second, points_per_frame - ); + println!( + "Preparing for playback:\n\tframe_hz: {}\n\tpoint_hz: {}\n\tpoints_per_frame: {}\n", + frames_per_second, points_per_second, points_per_frame + ); - // Prepare the DAC's playback engine and await the repsonse. - stream - .queue_commands() - .prepare_stream() - .submit() - .err() - .map(|err| { - eprintln!( - "err occurred when submitting PREPARE_STREAM \ + // Prepare the DAC's playback engine and await the repsonse. + stream + .queue_commands() + .prepare_stream() + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting PREPARE_STREAM \ command and listening for response: {}", - err - ); - }); + err + ); + }); - println!("Beginning playback!"); + println!("Beginning playback!"); - // The sine wave used to generate points. - let mut sine_wave = SineWave { - point: 0, - points_per_frame, - frames_per_second, - }; + // The sine wave used to generate points. + let mut sine_wave = SineWave { + point: 0, + points_per_frame, + frames_per_second, + }; - // Queue the initial frame and tell the DAC to begin producing output. - let n_points = points_to_generate(stream.dac()); - stream - .queue_commands() - .data(sine_wave.by_ref().take(n_points)) - .begin(0, points_per_second) - .submit() - .err() - .map(|err| { - eprintln!( - "err occurred when submitting initial DATA and BEGIN \ + // Queue the initial frame and tell the DAC to begin producing output. + let n_points = points_to_generate(stream.dac()); + stream + .queue_commands() + .data(sine_wave.by_ref().take(n_points)) + .begin(0, points_per_second) + .submit() + .err() + .map(|err| { + eprintln!( + "err occurred when submitting initial DATA and BEGIN \ commands and listening for response: {}", - err - ); - }); + err + ); + }); + eprintln!("Stream dac{:?}", stream.dac()); - // Loop and continue to send points forever. - loop { - // Determine how many points the DAC can currently receive. - let n_points = points_to_generate(stream.dac()); - if let Err(err) = stream - .queue_commands() - .data(sine_wave.by_ref().take(n_points)) - .submit() - { - eprintln!( - "err occurred when submitting DATA command and listening \ + // Loop and continue to send points forever. + loop { + // Determine how many points the DAC can currently receive. + let n_points = points_to_generate(stream.dac()); + if let Err(err) = stream + .queue_commands() + .data(sine_wave.by_ref().take(n_points)) + .submit() + { + eprintln!( + "err occurred when submitting DATA command and listening \ for response: {}", - err - ); - break; - } - } + err + ); + break; + } + } - // Tell the DAC to stop producing output and return to idle. Wait for the response. - // - // Note that the DAC is commanded to stop on `Drop` if this is not called and any errors - // produced are ignored. - stream - .queue_commands() - .stop() - .submit() - .expect("err occurred when submitting STOP command and listening for response"); + // Tell the DAC to stop producing output and return to idle. Wait for the response. + // + // Note that the DAC is commanded to stop on `Drop` if this is not called and any errors + // produced are ignored. + stream + .queue_commands() + .stop() + .submit() + .expect("err occurred when submitting STOP command and listening for response"); } // Determine the number of points needed to fill the DAC. fn points_to_generate(dac: ðer_dream::dac::Dac) -> usize { - dac.buffer_capacity as usize - 1 - dac.status.buffer_fullness as usize + dac.buffer_capacity as usize - 1 - dac.status.buffer_fullness as usize } // An iterator that endlessly generates a sine wave of DAC points. // // The sine wave oscillates at a rate of once per second. struct SineWave { - point: u32, - points_per_frame: u16, - frames_per_second: f32, + point: u32, + points_per_frame: u16, + frames_per_second: f32, } impl Iterator for SineWave { - type Item = ether_dream::protocol::DacPoint; - fn next(&mut self) -> Option { - let coloured_points_per_frame = self.points_per_frame - 1; - let i = (self.point % self.points_per_frame as u32) as u16; - let hz = 1.0; - let fract = i as f32 / coloured_points_per_frame as f32; - let phase = (self.point as f32 / coloured_points_per_frame as f32) / self.frames_per_second; - let amp = (hz * (fract + phase) * 2.0 * std::f32::consts::PI).sin(); - let (r, g, b) = match i { - i if i == coloured_points_per_frame || i < 13 => (0, 0, 0), - _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), - }; - let x_min = std::i16::MIN; - let x_max = std::i16::MAX; - let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; - let y = (amp * x_max as f32) as i16; - let control = 0; - let (u1, u2) = (0, 0); - let p = ether_dream::protocol::DacPoint { - control, - x, - y, - i, - r, - g, - b, - u1, - u2, - }; - self.point += 1; - Some(p) - } + type Item = ether_dream::protocol::DacPoint; + fn next(&mut self) -> Option { + let coloured_points_per_frame = self.points_per_frame - 1; + let i = (self.point % self.points_per_frame as u32) as u16; + let hz = 1.0; + let fract = i as f32 / coloured_points_per_frame as f32; + let phase = (self.point as f32 / coloured_points_per_frame as f32) / self.frames_per_second; + let amp = (hz * (fract + phase) * 2.0 * std::f32::consts::PI).sin(); + let (r, g, b) = match i { + i if i == coloured_points_per_frame || i < 13 => (0, 0, 0), + _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), + }; + let x_min = std::i16::MIN; + let x_max = std::i16::MAX; + let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; + let y = (amp * x_max as f32) as i16; + let control = 0; + let (u1, u2) = (0, 0); + let p = ether_dream::protocol::DacPoint { + control, + x, + y, + i, + r, + g, + b, + u1, + u2, + }; + self.point += 1; + Some(p) + } } \ No newline at end of file diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index 86b6a6b..6d1e626 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -71,6 +71,7 @@ impl EtherdreamDevice { Err(Box::new(LJError::EtherdreamConnectError(err))) } Ok((dac, source_addr)) => { + info!("Trying to open TCP stream..."); let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?; info!("Finished configuring DAC and TCP stream."); Ok((dac, source_addr, stream)) @@ -87,18 +88,29 @@ impl EtherdreamDevice { Err(err) => warn!("err occurred when submitting PREPARE_STREAM command and listening for response: {}",err), Ok(_) => info!("Prepared Stream.") } - let begin_list = vec![ - DacPoint { control: 0, x: 0, y: 0, i: 255, r: 0, g: 0, b: 0, u1: 0, u2: 0 }, - ]; + // If we want to create an animation (in our case a moving sine wave) we need a frame rate. + let frames_per_second = 60.0; + // Lets use the DAC at an eighth the maximum scan rate. let points_per_second = stream.dac().max_point_rate / 32; + // Determine the number of points per frame given our target frame and point rates. + let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; + + let mut sine_wave = SineWave { + point: 0, + points_per_frame, + frames_per_second, + }; + match stream .queue_commands() - .data(begin_list.into_iter().take(1 as usize)) + .data(sine_wave.by_ref().take(400)) + // .data(begin_list.into_iter().take(400 as usize)) .begin(0, points_per_second) .submit() { Err(err) => warn!("err occurred when submitting first data: {}",err), Ok(_) => info!("Sent first data to Etherdream.") } + Ok(stream) } @@ -130,9 +142,9 @@ impl Device for EtherdreamDevice { capacity: self.points_capacity(), lack: self.dac_response.to_string(), }; - // info!("Dac Status: {:?} ", status ); - // info!("Etherdream Dac {:?} ", self.dac ); - // info!("Stream dac{:?}", self.stream.dac()); + // debug!("Dac Status: {:?} ", status ); + // debug!("Etherdream Dac {:?} ", self.dac ); + debug!("Stream dac{:?}", self.stream.dac()); status } @@ -143,6 +155,17 @@ impl Device for EtherdreamDevice { let n_points = self.points_capacity(); // let n_points = &line.len(); debug!("Etherdream::device draw Generating {:?} points", n_points); + let frames_per_second = 60.0; + // Lets use the DAC at an eighth the maximum scan rate. + let points_per_second = self.stream.dac().max_point_rate / 32; + // Determine the number of points per frame given our target frame and point rates. + let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; + + let mut sine_wave = SineWave { + point: 0, + points_per_frame, + frames_per_second, + }; match self.stream .queue_commands() .data( @@ -151,6 +174,8 @@ impl Device for EtherdreamDevice { // .take(line.len() as usize) .take(n_points as usize) ) + // .data(sine_wave.by_ref().take(n_points as usize)) + .submit() { Err(err) => { // We should account for @@ -170,7 +195,6 @@ impl Device for EtherdreamDevice { err.response.response } }; - } Ok(_) => { self.dac_response = DacResponse::ACK; @@ -220,3 +244,53 @@ impl Device for EtherdreamDevice { ] } } + +// Determine the number of points needed to fill the DAC. +fn points_to_generate(dac: ðer_dream::dac::Dac) -> usize { + dac.buffer_capacity as usize - 1 - dac.status.buffer_fullness as usize +} + +// An iterator that endlessly generates a sine wave of DAC points. +// +// The sine wave oscillates at a rate of once per second. +struct SineWave { + point: u32, + points_per_frame: u16, + frames_per_second: f32, +} + +impl Iterator for SineWave { + type Item = ether_dream::protocol::DacPoint; + fn next(&mut self) -> Option { + let coloured_points_per_frame = self.points_per_frame - 1; + let i = (self.point % self.points_per_frame as u32) as u16; + let hz = 1.0; + let fract = i as f32 / coloured_points_per_frame as f32; + let phase = (self.point as f32 / coloured_points_per_frame as f32) / self.frames_per_second; + let amp = (hz * (fract + phase) * 2.0 * std::f32::consts::PI).sin(); + let (r, g, b) = match i { + i if i == coloured_points_per_frame || i < 13 => (0, 0, 0), + _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), + }; + let x_min = std::i16::MIN; + let x_max = std::i16::MAX; + let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; + let y = (amp * x_max as f32) as i16; + let control = 0; + let (u1, u2) = (0, 0); + let p = ether_dream::protocol::DacPoint { + control, + x, + y, + i, + r, + g, + b, + u1, + u2, + }; + debug!("{:?}",p); + self.point += 1; + Some(p) + } +} \ No newline at end of file diff --git a/src/point.rs b/src/point.rs index 1298905..9f88f43 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,4 +1,5 @@ use ether_dream::protocol::DacPoint; +use log::debug; fn clamp(val: f32, min: f32, max: f32) -> f32 { if val < min { @@ -67,9 +68,9 @@ impl From for DacPoint { x: x as i16, y: y as i16, i, - r: pt.color.r.into(), - g: pt.color.g.into(), - b: pt.color.b.into(), + r: (pt.color.r as u16) * 255, + g: (pt.color.g as u16) * 255, + b: (pt.color.b as u16) * 255, u1, u2, } From e148a1ec5eefa9e7dab03966e39042967961339f Mon Sep 17 00:00:00 2001 From: alban Date: Thu, 20 Jul 2023 21:34:23 +0200 Subject: [PATCH 41/48] fix: cleanup for errors --- src/device/etherdream.rs | 19 ++----------------- src/device/helios.rs | 9 +++++++-- src/point.rs | 16 ++-------------- src/redis_ctrl.rs | 2 ++ 4 files changed, 13 insertions(+), 33 deletions(-) diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index 6d1e626..e4ea6a6 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -9,7 +9,7 @@ use crate::conf::EtherDreamConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; -use ether_dream::protocol::{DacBroadcast, DacPoint, DacResponse}; +use ether_dream::protocol::{DacBroadcast, DacResponse}; use log::{debug, info, warn}; #[warn(dead_code)] @@ -155,23 +155,13 @@ impl Device for EtherdreamDevice { let n_points = self.points_capacity(); // let n_points = &line.len(); debug!("Etherdream::device draw Generating {:?} points", n_points); - let frames_per_second = 60.0; - // Lets use the DAC at an eighth the maximum scan rate. - let points_per_second = self.stream.dac().max_point_rate / 32; - // Determine the number of points per frame given our target frame and point rates. - let points_per_frame = (points_per_second as f32 / frames_per_second) as u16; - let mut sine_wave = SineWave { - point: 0, - points_per_frame, - frames_per_second, - }; + match self.stream .queue_commands() .data( line.into_iter() .map(|point| point.into()) - // .take(line.len() as usize) .take(n_points as usize) ) // .data(sine_wave.by_ref().take(n_points as usize)) @@ -245,11 +235,6 @@ impl Device for EtherdreamDevice { } } -// Determine the number of points needed to fill the DAC. -fn points_to_generate(dac: ðer_dream::dac::Dac) -> usize { - dac.buffer_capacity as usize - 1 - dac.status.buffer_fullness as usize -} - // An iterator that endlessly generates a sine wave of DAC points. // // The sine wave oscillates at a rate of once per second. diff --git a/src/device/helios.rs b/src/device/helios.rs index 19a346c..0971aeb 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -1,3 +1,4 @@ +use std::time::SystemTime; /// /// Configure udev: /// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md @@ -14,7 +15,7 @@ use crate::conf::HeliosConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; -use chrono::Utc; +use chrono::{DateTime, Utc}; pub struct HeliosDevice { pub conf: HeliosConf, @@ -34,13 +35,17 @@ impl HeliosDevice { return Err(Box::new(LJError::HeliosDeviceMissing)); }; let dac = device.open()?; + let now = SystemTime::now(); + let now: DateTime = now.into(); + let last_traced_at = now.to_rfc3339(); + Ok(Self { conf: (*conf).clone(), dac, sent_points: 0, state: PlaybackState::PREPARE, lack: "".to_string(), - last_traced_at: "1985-04-12T23:20:50.52Z".to_string(), + last_traced_at, }) } } diff --git a/src/point.rs b/src/point.rs index 9f88f43..6ce6268 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,15 +1,4 @@ use ether_dream::protocol::DacPoint; -use log::debug; - -fn clamp(val: f32, min: f32, max: f32) -> f32 { - if val < min { - return min; - } - if val > max { - return max; - } - val -} #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Point { @@ -56,13 +45,12 @@ impl From for helios_dac::Point { } impl From for DacPoint { - fn from(pt: Point) -> DacPoint { let control = 0; let (u1, u2) = (0, 0); let i = 255; - let x = clamp(pt.x, -32000 as f32, 32000 as f32); - let y = clamp(pt.y, -32000 as f32, 32000 as f32); + let x = pt.x.clamp(-32000.0, 32000.0); + let y = pt.y.clamp(-32000.0, 32000.0); DacPoint { control, x: x as i16, diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 4fdcdde..03d7cba 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -17,6 +17,7 @@ pub enum Order { Intensity, Kpps, ColorBalance, + PowerOff } impl TryFrom for Order { @@ -39,6 +40,7 @@ impl TryFrom for Order { 6 => Intensity, 7 => Kpps, 8 => ColorBalance, + 9 => PowerOff, _ => unreachable!() }) } From ff96bdf6fa91a2dd7f3278b829b69898859c3160 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 17:28:18 +0200 Subject: [PATCH 42/48] fix: etherdream example --- examples/etherdream.rs | 2 +- examples/test.rs | 46 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 examples/test.rs diff --git a/examples/etherdream.rs b/examples/etherdream.rs index 75d888c..c521b0b 100644 --- a/examples/etherdream.rs +++ b/examples/etherdream.rs @@ -129,7 +129,7 @@ impl Iterator for SineWave { _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), }; let x_min = std::i16::MIN; - let x_max = std::i16::MAX; + let x_max = std::i8::MAX as i16; let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; let y = (amp * x_max as f32) as i16; let control = 0; diff --git a/examples/test.rs b/examples/test.rs new file mode 100644 index 0000000..b8fb5f3 --- /dev/null +++ b/examples/test.rs @@ -0,0 +1,46 @@ +/// +/// $ cargo run --example simple_client +/// + +use redis::{ + //RedisResult, + Client, + Commands, + Connection, +}; + +use std::time::Instant; + +fn do_something() -> redis::RedisResult<()> { + let client = Client::open("redis://127.0.0.1/")?; + let mut con: Connection = client.get_connection()?; + let start = Instant::now(); + + loop { + let elapsed = start.elapsed(); + let time = 60.0 * elapsed.as_millis() as f32 / 1000.0; + + let mut v: Vec<(f32, f32, u32)> = vec![]; + + for i in 0..128 { + let a = (time + i as f32) / 128.0 * std::f32::consts::PI * 2.0; + let r = 1200.0 + (a * 5.0).cos() * (500.0 * (time / 5.0).cos()); + + let x = a.cos() * r; + let y = a.sin() * r; + let col = if i % 8 < 4 { + 0x000000ff + } else { + 0x00ff0000 + }; + v.push((x, y, col)); + } + // println!("{:?}", v); + let _ = con.set("/pl/0/0", format!("{:?}", v))?; + } + // Ok(()) +} + +fn main() { + _ = do_something(); +} From 3ce346306f15569f8d191140e734f0db73d86cc0 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 17:29:33 +0200 Subject: [PATCH 43/48] feat: add helios to etherdream transformer --- src/conf.rs | 5 ++++- src/transformer.rs | 2 ++ src/transformer/helios_to_etherdream.rs | 27 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/transformer/helios_to_etherdream.rs diff --git a/src/conf.rs b/src/conf.rs index 2996c7d..4ddf686 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -48,7 +48,9 @@ pub enum TransformConf { #[serde(rename = "grid")] Grid(transformer::Grid), #[serde(rename = "homography")] - Homography(transformer::Homography) + Homography(transformer::Homography), + #[serde(rename = "helios_to_etherdream")] + HeliosToEtherdream(transformer::HeliosToEtherdream), } @@ -73,6 +75,7 @@ impl Conf { TransformConf::FlipV(r) => Box::new(*r), TransformConf::Grid(r) => Box::new(*r), TransformConf::Homography(r) => Box::new(*r), + TransformConf::HeliosToEtherdream(r) => Box::new(*r), }; v.push(t); } diff --git a/src/transformer.rs b/src/transformer.rs index aa25291..2b9465f 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -6,6 +6,7 @@ mod flip_horizontal; mod flip_vertical; mod grid; mod homography; +mod helios_to_etherdream; use crate::point::Point; use crate::worldstate::WorldState; @@ -18,6 +19,7 @@ pub use flip_horizontal::FlipHorizontal; pub use flip_vertical::FlipVertical; pub use grid::Grid; pub use self::homography::Homography; +pub use helios_to_etherdream::HeliosToEtherdream; pub trait Transformers { fn apply( diff --git a/src/transformer/helios_to_etherdream.rs b/src/transformer/helios_to_etherdream.rs new file mode 100644 index 0000000..1891d5d --- /dev/null +++ b/src/transformer/helios_to_etherdream.rs @@ -0,0 +1,27 @@ +use crate::transformer::Transformers; +use crate::point::Point; +use crate::worldstate::WorldState; + +use serde::{Serialize, Deserialize}; + +/// Converts helios Geometry to Helios +#[allow(dead_code)] +#[derive(Serialize, Deserialize, Debug, Clone, Copy)] +pub struct HeliosToEtherdream { +} + +impl Transformers for HeliosToEtherdream { + fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec { + // debug!("list helios {:?}", point_list); + let out = point_list.iter().map(|pt| { + Point { + x: 8.0 * (pt.x - 2047.0), + y: 8.0 * (pt.y - 2047.0), + ..*pt + } + }).collect(); + // debug!("list etherdream {:?}", out); + out + } +} + From 6f04925ea5e56f8d6bc8b0ea0c53086b25753129 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 17:34:06 +0200 Subject: [PATCH 44/48] feat: add framerate with fixed value for now (20Hz) --- src/framerate.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 6 ++++++ 3 files changed, 46 insertions(+) create mode 100644 src/framerate.rs diff --git a/src/framerate.rs b/src/framerate.rs new file mode 100644 index 0000000..dbab25b --- /dev/null +++ b/src/framerate.rs @@ -0,0 +1,39 @@ +use log::{debug, warn}; +use std::time::{Duration, Instant}; +use crate::errors::LJResult; +use std::{thread}; + +/// Converts helios Geometry to Helios +#[derive(Debug, Clone, Copy)] +pub struct Framerate { + prev_trace_time: Instant, + fps: u8, +} + +impl Framerate { + pub fn new() -> LJResult { + Ok(Framerate { + prev_trace_time: Instant::now(), + fps: 20, + }) + } + pub fn handle_time(&mut self) -> LJResult<()> { + let frame_time = 1000000000 / self.fps as u128; + let now = Instant::now(); + // How long since last loop ? + let nanotime_spent = self.prev_trace_time.elapsed().as_nanos(); + // Diw it go too fast? If so : sleep a bit + if frame_time > nanotime_spent { + let nanotime_towait = frame_time - nanotime_spent; + let dur = Duration::new(0, (nanotime_towait as f32 * 0.9) as u32); + // debug!("{:?} - {:?} : {:?}", nanotime_towait, self.prev_trace_time, now ); + thread::sleep(dur); + debug!("Framerate OK"); + } else { + warn!("Frame longer than expected {:?} > {:?}", nanotime_spent, frame_time, ); + } + + self.prev_trace_time = now; + Ok(()) + } +} diff --git a/src/lib.rs b/src/lib.rs index 9048f40..ac3d833 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,3 +5,4 @@ pub mod device; pub mod point; pub mod transformer; pub mod worldstate; +pub mod framerate; diff --git a/src/main.rs b/src/main.rs index 62067a8..c1ba308 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,7 @@ mod point; mod transformer; mod device; mod worldstate; +mod framerate; use device::device_factory; use std::sync::atomic::{AtomicBool, Ordering}; @@ -21,6 +22,7 @@ use transformer::Transformers; use log::{LevelFilter, info, /* warn, */ error}; use env_logger::Builder; use worldstate::WorldState; +use framerate::Framerate; const DEFAULT_CONF_FILE: &str = "settings.toml"; @@ -68,9 +70,13 @@ fn run_all() -> LJResult<()> { // Setup geometry transformers on points lists let transformers = config.get_transformers(); + // Setup framerate limiter + let mut framerate_handler = Framerate::new()?; + // Dispatch based on redis requests while running.load(Ordering::SeqCst) { rs.set_status(tracer.status())?; + let _ = framerate_handler.handle_time()?; let order = rs.get_order(config.laser_id)?; match order { Order::Draw | Order::Black | Order::Grid => { From 514f4cc7c9183ba61e3d1602c1c304ded6039220 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 17:35:15 +0200 Subject: [PATCH 45/48] fix: etherdream should work with device trait adjustments --- src/device.rs | 2 +- src/device/etherdream.rs | 116 +++++++++++++++++++++++---------------- src/device/helios.rs | 2 +- 3 files changed, 70 insertions(+), 50 deletions(-) diff --git a/src/device.rs b/src/device.rs index 6cbf0d5..cf83dba 100644 --- a/src/device.rs +++ b/src/device.rs @@ -42,7 +42,7 @@ pub struct Status { pub last_traced_at: String, pub properties: Vec, pub playback_state: PlaybackState, - pub capacity: u16, + pub capacity: usize, pub lack: String, } diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index e4ea6a6..b9e3cab 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -1,16 +1,20 @@ -use std::time; +#[warn(unused_imports)] +use log::{ debug, info, warn}; + use std::net::SocketAddr; +use std::thread::sleep; use ether_dream::dac::stream::{CommunicationError, connect}; use ether_dream::dac::{Playback, Stream}; use chrono::{DateTime, Utc}; -use std::time::SystemTime; +use std::time; +use std::time::{Duration, SystemTime}; use crate::conf::EtherDreamConf; use crate::device::{Device, Status, PlaybackState}; use crate::errors::{LJError, LJResult}; use crate::point::{Color, Point}; use ether_dream::protocol::{DacBroadcast, DacResponse}; -use log::{debug, info, warn}; + #[warn(dead_code)] pub struct EtherdreamDevice { @@ -114,14 +118,20 @@ impl EtherdreamDevice { Ok(stream) } - fn points_capacity(&self) -> u16 { + fn points_capacity(&self) -> usize { /*** Determine the number of points needed to fill the DAC. ***/ // Fixme thread 'main' panicked at 'attempt to subtract with overflow', src/device/etherdream.rs:144:24 - let n_points = self.dac.buffer_capacity as u16 - self.stream.dac().dac.status.buffer_fullness as u16 - 1; + let n_points = self.dac.buffer_capacity as usize - self.stream.dac().dac.status.buffer_fullness as usize - 1; n_points } + + fn ping(&mut self) -> LJResult<()> { + + Ok(self.stream.queue_commands().ping().submit()?) + + } } impl Device for EtherdreamDevice { @@ -135,62 +145,72 @@ impl Device for EtherdreamDevice { let now: DateTime = now.into(); let now = now.to_rfc3339(); - let status = Status { + Status { last_traced_at: now, properties: vec!["foo".to_string()], playback_state, capacity: self.points_capacity(), lack: self.dac_response.to_string(), - }; + } // debug!("Dac Status: {:?} ", status ); // debug!("Etherdream Dac {:?} ", self.dac ); - debug!("Stream dac{:?}", self.stream.dac()); - status + // debug!("Stream dac{:?}", self.stream.dac()); + // status } fn draw(&mut self, line: Vec, _speed: u32, ) -> LJResult<()> { - let n_points = self.points_capacity(); - // let n_points = &line.len(); - debug!("Etherdream::device draw Generating {:?} points", n_points); - - - match self.stream - .queue_commands() - .data( - line.into_iter() - .map(|point| point.into()) - .take(n_points as usize) - ) - // .data(sine_wave.by_ref().take(n_points as usize)) - - .submit() { - Err(err) => { - // We should account for - // 'Broken pipe (os error 32)' - // Connection reset by peer (os error 104) - self.dac_response = match err { - CommunicationError::Io(err) => { - warn!("IO ERROR while drawing: '{}'",err); - DacResponse::ACK - } - CommunicationError::Protocol(err) => { - warn!("Protocol ERROR while drawing: '{}'",err); - DacResponse::ACK - } - CommunicationError::Response(err) => { - warn!("Response ERROR while drawing: '{}'",err); - err.response.response - } - }; + let chunk_size = 64; + let points_iter = line.into_iter(); + for chunk in points_iter.as_slice().chunks(chunk_size){ + debug!("New chunk length: {:?}", chunk.len()); + loop { + let capacity = self.points_capacity(); + if chunk.len() > capacity as usize { + debug!("Sleep, capacity : {:?}", capacity); + // Sleep for 1/100th of a sec + sleep(Duration::new( 0, 10000000)); + self.ping(); + } else { + break; + } } - Ok(_) => { - self.dac_response = DacResponse::ACK; - debug!("Draw is ok"); - } - }; + debug!("drawing"); + match self.stream + .queue_commands() + .data( + chunk.into_iter() + .map(|point| (*point).into()) + .take(chunk_size as usize) + ) + .submit() { + Err(err) => { + // We should account for + // 'Broken pipe (os error 32)' + // Connection reset by peer (os error 104) + self.dac_response = match err { + CommunicationError::Io(err) => { + warn!("IO ERROR while drawing: '{}'",err); + DacResponse::ACK + } + CommunicationError::Protocol(err) => { + warn!("Protocol ERROR while drawing: '{}'",err); + DacResponse::ACK + } + CommunicationError::Response(err) => { + warn!("Response ERROR while drawing: '{}'",err); + err.response.response + } + }; + } + Ok(_) => { + self.dac_response = DacResponse::ACK; + // debug!("Draw is ok"); + } + }; + } Ok(()) } @@ -274,7 +294,7 @@ impl Iterator for SineWave { u1, u2, }; - debug!("{:?}",p); + // debug!("{:?}",p); self.point += 1; Some(p) } diff --git a/src/device/helios.rs b/src/device/helios.rs index 0971aeb..9106243 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -57,7 +57,7 @@ impl Device for HeliosDevice { last_traced_at: self.last_traced_at.clone(), properties: vec!["foo".to_string()], playback_state: self.state, - capacity: self.sent_points, + capacity: self.sent_points as usize, lack, } } From 22d7d3c718c8db551871565f73ee9fdcdfa24aa6 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 17:35:39 +0200 Subject: [PATCH 46/48] fix: i in point for etherdream is meh --- src/point.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/point.rs b/src/point.rs index 6ce6268..273bfbc 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,5 +1,6 @@ use ether_dream::protocol::DacPoint; + #[derive(Debug, Clone, Copy, Default, PartialEq)] pub struct Point { pub x: f32, @@ -48,10 +49,10 @@ impl From for DacPoint { fn from(pt: Point) -> DacPoint { let control = 0; let (u1, u2) = (0, 0); - let i = 255; + let i = 0; let x = pt.x.clamp(-32000.0, 32000.0); let y = pt.y.clamp(-32000.0, 32000.0); - DacPoint { + let pt = DacPoint { control, x: x as i16, y: y as i16, @@ -61,6 +62,8 @@ impl From for DacPoint { b: (pt.color.b as u16) * 255, u1, u2, - } + }; + // debug!("point {:?}", pt); + pt } } From 2c0d5cd13fb15dab20245b2cf3fae3693f6d7ed7 Mon Sep 17 00:00:00 2001 From: alban Date: Mon, 24 Jul 2023 18:53:19 +0200 Subject: [PATCH 47/48] feat: add Intensity Transformer --- src/conf.rs | 149 ++++++++++++++++++----------------- src/point.rs | 12 +++ src/transformer.rs | 11 +-- src/transformer/intensity.rs | 28 +++++++ 4 files changed, 123 insertions(+), 77 deletions(-) create mode 100644 src/transformer/intensity.rs diff --git a/src/conf.rs b/src/conf.rs index 4ddf686..9cff95c 100644 --- a/src/conf.rs +++ b/src/conf.rs @@ -1,101 +1,106 @@ use config::Config; -use serde::{Serialize,Deserialize}; -use crate::errors::{LJError,LJResult}; +use serde::{Serialize, Deserialize}; +use crate::errors::{LJError, LJResult}; use crate::transformer; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Conf { - pub laser_id: u8, - pub debug: bool, - pub redis_url: String, - pub dac: DacFamily, - #[serde(default)] - pub transformers: Vec + pub laser_id: u8, + pub debug: bool, + pub redis_url: String, + pub dac: DacFamily, + #[serde(default)] + pub transformers: Vec, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum DacFamily { - #[serde(rename = "helios")] - Helios(HeliosConf), - #[serde(rename = "etherdream")] - Etherdream(EtherDreamConf), - #[serde(rename = "dummy")] - Dummy, + #[serde(rename = "helios")] + Helios(HeliosConf), + #[serde(rename = "etherdream")] + Etherdream(EtherDreamConf), + #[serde(rename = "dummy")] + Dummy, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HeliosConf { - pub id: u8 + pub id: u8, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct EtherDreamConf { - pub ip: String + pub ip: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum TransformConf { - #[serde(rename = "translate")] - Translate(transformer::Translate), - #[serde(rename = "replicate")] - Replicate(transformer::Replicate), - #[serde(rename = "rotate")] - Rotate(transformer::Rotate), - #[serde(rename = "flip_horizontal")] - FlipH(transformer::FlipHorizontal), - #[serde(rename = "flip_vertical")] - FlipV(transformer::FlipVertical), - #[serde(rename = "grid")] - Grid(transformer::Grid), - #[serde(rename = "homography")] - Homography(transformer::Homography), - #[serde(rename = "helios_to_etherdream")] - HeliosToEtherdream(transformer::HeliosToEtherdream), + #[serde(rename = "translate")] + Translate(transformer::Translate), + #[serde(rename = "replicate")] + Replicate(transformer::Replicate), + #[serde(rename = "rotate")] + Rotate(transformer::Rotate), + #[serde(rename = "flip_horizontal")] + FlipH(transformer::FlipHorizontal), + #[serde(rename = "flip_vertical")] + FlipV(transformer::FlipVertical), + #[serde(rename = "grid")] + Grid(transformer::Grid), + #[serde(rename = "homography")] + Homography(transformer::Homography), + #[serde(rename = "helios_to_etherdream")] + HeliosToEtherdream(transformer::HeliosToEtherdream), + #[serde(rename = "intensity")] + Intensity(transformer::Intensity), } impl Conf { - pub fn new(path: &str) -> LJResult { - let settings = Config::builder() - .add_source(config::File::with_name(path)) - .build()?; - - let conf : Conf = settings.try_deserialize().map_err(LJError::Config)?; - Ok(conf) - } + pub fn new(path: &str) -> LJResult { + let settings = Config::builder() + .add_source(config::File::with_name(path)) + .build()?; - pub fn get_transformers(&self) -> Vec> { - let mut v = vec![]; - for t in &self.transformers { - let t : Box = match t { - TransformConf::Translate(t) => Box::new(*t), - TransformConf::Replicate(r) => Box::new(*r), - TransformConf::Rotate(r) => Box::new(*r), - TransformConf::FlipH(r) => Box::new(*r), - TransformConf::FlipV(r) => Box::new(*r), - TransformConf::Grid(r) => Box::new(*r), - TransformConf::Homography(r) => Box::new(*r), - TransformConf::HeliosToEtherdream(r) => Box::new(*r), - }; - v.push(t); + let conf: Conf = settings.try_deserialize().map_err(LJError::Config)?; + Ok(conf) } - v - } - #[allow(dead_code)] - pub fn dump() { - let conf = Conf { - laser_id: 0, - debug: true, - redis_url: "redis://127.0.0.1:6379/".to_string(), - dac: DacFamily::Helios(HeliosConf { id: 0 }), - transformers: vec![ - TransformConf::Translate(transformer::Translate { x: 2000.0, - y: 2000.0 } ), - TransformConf::Replicate(transformer::Replicate::Until(48)) - ] - }; - let s = toml::to_string(&conf).unwrap(); - println!("{}", s); - } + pub fn get_transformers(&self) -> Vec> { + let mut v = vec![]; + for t in &self.transformers { + let t: Box = match t { + TransformConf::FlipH(r) => Box::new(*r), + TransformConf::FlipV(r) => Box::new(*r), + TransformConf::Grid(r) => Box::new(*r), + TransformConf::HeliosToEtherdream(r) => Box::new(*r), + TransformConf::Homography(r) => Box::new(*r), + TransformConf::Intensity(r) => Box::new(*r), + TransformConf::Replicate(r) => Box::new(*r), + TransformConf::Rotate(r) => Box::new(*r), + TransformConf::Translate(t) => Box::new(*t), + }; + v.push(t); + } + v + } + + #[allow(dead_code)] + pub fn dump() { + let conf = Conf { + laser_id: 0, + debug: true, + redis_url: "redis://127.0.0.1:6379/".to_string(), + dac: DacFamily::Helios(HeliosConf { id: 0 }), + transformers: vec![ + TransformConf::Translate(transformer::Translate { + x: 2000.0, + y: 2000.0, + }), + TransformConf::Replicate(transformer::Replicate::Until(48)), + ], + }; + let s = toml::to_string(&conf).unwrap(); + println!("{}", s); + } } diff --git a/src/point.rs b/src/point.rs index 273bfbc..21b5694 100644 --- a/src/point.rs +++ b/src/point.rs @@ -1,4 +1,5 @@ use ether_dream::protocol::DacPoint; +use std::ops::Mul; #[derive(Debug, Clone, Copy, Default, PartialEq)] @@ -14,6 +15,17 @@ pub struct Color { pub g: u8, pub b: u8, } +impl Mul for Color { + type Output = Self; + + fn mul(self, rhs: u8) -> Self { + Self{ + r: (255 * self.r as u16 / rhs as u16) as u8, + g: (255 * self.g as u16 / rhs as u16) as u8, + b: (255 * self.b as u16 / rhs as u16) as u8, + } + } +} impl From for u32 { fn from(value: Color) -> Self { diff --git a/src/transformer.rs b/src/transformer.rs index 2b9465f..ae66f8b 100644 --- a/src/transformer.rs +++ b/src/transformer.rs @@ -1,12 +1,12 @@ -//pub mod common; -mod translate; -mod replicate; -mod rotate; mod flip_horizontal; mod flip_vertical; mod grid; -mod homography; mod helios_to_etherdream; +mod homography; +mod intensity; +mod replicate; +mod rotate; +mod translate; use crate::point::Point; use crate::worldstate::WorldState; @@ -20,6 +20,7 @@ pub use flip_vertical::FlipVertical; pub use grid::Grid; pub use self::homography::Homography; pub use helios_to_etherdream::HeliosToEtherdream; +pub use intensity::Intensity; pub trait Transformers { fn apply( diff --git a/src/transformer/intensity.rs b/src/transformer/intensity.rs new file mode 100644 index 0000000..0aacc1c --- /dev/null +++ b/src/transformer/intensity.rs @@ -0,0 +1,28 @@ +use log::debug; +use crate::transformer::Transformers; +use crate::point::Point; +use crate::worldstate::WorldState; + +use serde::{Serialize, Deserialize}; + +/// Converts helios Geometry to Helios +#[allow(dead_code)] +#[derive(Serialize, Deserialize, Debug, Clone, Copy)] +pub struct Intensity { +} + +impl Transformers for Intensity { + fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec { + // debug!("list helios {:?}", point_list); + let out = point_list.iter().map(|pt| { + Point { + x: pt.x, + y: pt.y, + color: pt.color * ws.intensity + } + }).collect(); + debug!("list intensity {:?}", out); + out + } +} + From a45abd69ec3a944892c11a0ceddc1a791952e675 Mon Sep 17 00:00:00 2001 From: Marc Planard Date: Wed, 14 Aug 2024 18:41:47 +0200 Subject: [PATCH 48/48] fix: less warnings, better logging for helios broadcast --- src/device/etherdream.rs | 31 +++++++++++++++++++------------ src/device/helios.rs | 4 ++-- src/main.rs | 2 +- src/redis_ctrl.rs | 8 ++++---- 4 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/device/etherdream.rs b/src/device/etherdream.rs index b9e3cab..8463f68 100644 --- a/src/device/etherdream.rs +++ b/src/device/etherdream.rs @@ -62,8 +62,15 @@ impl EtherdreamDevice { } Ok((dac, source_addr)) => { info!("Valid broadcast, source_addr: {}", source_addr); - if source_addr.is_ipv6() { return None; } - if &source_addr.ip().to_string() != ip { return None; } + if source_addr.is_ipv6() { + warn!("Broadcast ignored: ipv6 address."); + return None; + } + let src_ip = source_addr.ip().to_string(); + if &src_ip != ip { + warn!("Broadcast ignored: expected {ip}, got: {src_ip} "); + return None; + } Some(Ok((dac, source_addr))) } } @@ -168,11 +175,11 @@ impl Device for EtherdreamDevice { debug!("New chunk length: {:?}", chunk.len()); loop { let capacity = self.points_capacity(); - if chunk.len() > capacity as usize { + if chunk.len() > capacity { debug!("Sleep, capacity : {:?}", capacity); // Sleep for 1/100th of a sec sleep(Duration::new( 0, 10000000)); - self.ping(); + self.ping()?; } else { break; } @@ -181,9 +188,9 @@ impl Device for EtherdreamDevice { match self.stream .queue_commands() .data( - chunk.into_iter() + chunk.iter() .map(|point| (*point).into()) - .take(chunk_size as usize) + .take(chunk_size) ) .submit() { Err(err) => { @@ -233,8 +240,8 @@ impl Device for EtherdreamDevice { } fn grid(&mut self) -> Vec { - let dim_mid = 16000 as f32; - let dim_max = 32000 as f32; + let dim_mid = 16000.0; + let dim_max = 32000.0; let col_min = Color { r: 0, g: 0, b: 0 }; let col_max = Color { r: 255, g: 255, b: 255 }; @@ -275,10 +282,10 @@ impl Iterator for SineWave { let amp = (hz * (fract + phase) * 2.0 * std::f32::consts::PI).sin(); let (r, g, b) = match i { i if i == coloured_points_per_frame || i < 13 => (0, 0, 0), - _ => (std::u16::MAX, std::u16::MAX, std::u16::MAX), + _ => (u16::MAX, u16::MAX, u16::MAX), }; - let x_min = std::i16::MIN; - let x_max = std::i16::MAX; + let x_min = i16::MIN; + let x_max = i16::MAX; let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16; let y = (amp * x_max as f32) as i16; let control = 0; @@ -298,4 +305,4 @@ impl Iterator for SineWave { self.point += 1; Some(p) } -} \ No newline at end of file +} diff --git a/src/device/helios.rs b/src/device/helios.rs index 9106243..a1f6af4 100644 --- a/src/device/helios.rs +++ b/src/device/helios.rs @@ -85,8 +85,8 @@ impl Device for HeliosDevice { fn grid(&mut self) -> Vec { let dim_min = 0 as f32; - let dim_mid = 2047 as f32; - let dim_max = 4095 as f32; + let dim_mid = 2047.0; + let dim_max = 4095.0; let col_min = Color { r: 0, g: 0, b: 0 }; let col_max = Color { r: 255, g: 255, b: 255 }; diff --git a/src/main.rs b/src/main.rs index c1ba308..39e7e81 100644 --- a/src/main.rs +++ b/src/main.rs @@ -76,7 +76,7 @@ fn run_all() -> LJResult<()> { // Dispatch based on redis requests while running.load(Ordering::SeqCst) { rs.set_status(tracer.status())?; - let _ = framerate_handler.handle_time()?; + framerate_handler.handle_time()?; let order = rs.get_order(config.laser_id)?; match order { Order::Draw | Order::Black | Order::Grid => { diff --git a/src/redis_ctrl.rs b/src/redis_ctrl.rs index 03d7cba..4dc9722 100644 --- a/src/redis_ctrl.rs +++ b/src/redis_ctrl.rs @@ -98,10 +98,10 @@ impl RedisCtrl { pub fn init_world_state(&mut self) -> LJResult { Ok(WorldState { - client_key: self.get_client_key().unwrap(), - edh: self.get_edh().unwrap(), - kpps: self.get_int("kpps").unwrap().try_into().unwrap(), - intensity: self.get_int("intensity").unwrap().try_into().unwrap(), + client_key: self.get_client_key()?, + edh: self.get_edh()?, + kpps: self.get_int("kpps")?.try_into()?, + intensity: self.get_int("intensity")?.try_into()?, ..WorldState::default() }) }