From ae75092d340047d4e9caacd219f90f293100ca47 Mon Sep 17 00:00:00 2001 From: alban Date: Wed, 19 Jul 2023 01:28:45 +0200 Subject: [PATCH 01/13] 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 02/13] 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 03/13] 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 04/13] 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 05/13] 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 06/13] 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 07/13] 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 08/13] 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 09/13] 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 10/13] 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 11/13] 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 12/13] 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 13/13] 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 + } +} +