This commit is contained in:
Lapin Raving 2023-08-23 13:13:53 +02:00
parent 4a87821c22
commit baf149ef8a
23 changed files with 1030 additions and 856 deletions

View File

@ -1,7 +1,6 @@
/// ///
/// $ cargo run --example populate_redis /// $ cargo run --example populate_redis
/// ///
use redis::{ use redis::{
//RedisResult, //RedisResult,
Client, Client,
@ -13,10 +12,13 @@ fn do_something() -> redis::RedisResult<()> {
let client = Client::open("redis://127.0.0.1/")?; let client = Client::open("redis://127.0.0.1/")?;
let mut con: Connection = client.get_connection()?; let mut con: Connection = client.get_connection()?;
let _ = con.set("/clientkey", "/pl/0/")?; 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(
let _ = con.set("/kpps/0", "5000")?; "/EDH/0",
let _ = con.set("/intensity/0", "255")?; "[[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(()) Ok(())
} }
fn main() { fn main() {

View File

@ -1,7 +1,6 @@
/// ///
/// $ cargo run --example simple_client /// $ cargo run --example simple_client
/// ///
use redis::{ use redis::{
//RedisResult, //RedisResult,
Client, Client,
@ -15,28 +14,24 @@ fn do_something() -> redis::RedisResult<()> {
let client = Client::open("redis://127.0.0.1/")?; let client = Client::open("redis://127.0.0.1/")?;
let mut con: Connection = client.get_connection()?; let mut con: Connection = client.get_connection()?;
let start = Instant::now(); let start = Instant::now();
loop { loop {
let elapsed = start.elapsed(); let elapsed = start.elapsed();
let time = 60.0 * elapsed.as_millis() as f32 / 1000.0; let time = 60.0 * elapsed.as_millis() as f32 / 1000.0;
let mut v : Vec<(f32,f32,u32)> = vec![]; 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; for i in 0..128 {
let y = a.sin() * r; let a = (time + i as f32) / 128.0 * std::f32::consts::PI * 2.0;
let col = if i % 8 < 4 { let r = 1200.0 + (a * 5.0).cos() * (500.0 * (time / 5.0).cos());
0x000000ff
} else { let x = a.cos() * r;
0x00ff0000 let y = a.sin() * r;
}; let col = if i % 8 < 4 { 0x000000ff } else { 0x00ff0000 };
v.push((x,y,col)); v.push((x, y, col));
} }
// println!("{:?}", v); // println!("{:?}", v);
let _ = con.set("/pl/0/0", format!("{:?}", v))?; let _ = con.set("/pl/0/0", format!("{:?}", v))?;
} }
// Ok(()) // Ok(())
} }

View File

@ -1,7 +1,7 @@
use config::Config; use crate::errors::{LJError, LJResult};
use serde::{Serialize,Deserialize};
use crate::errors::{LJError,LJResult};
use crate::transformer; use crate::transformer;
use config::Config;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Conf { pub struct Conf {
@ -10,89 +10,100 @@ pub struct Conf {
pub redis_url: String, pub redis_url: String,
pub dac: DacFamily, pub dac: DacFamily,
#[serde(default)] #[serde(default)]
pub transformers: Vec<TransformConf> pub transformers: Vec<TransformConf>,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub enum DacFamily { pub enum DacFamily {
#[serde(rename = "helios")] #[serde(rename = "helios")]
Helios(HeliosConf), Helios(HeliosConf),
#[serde(rename = "etherdream")] #[serde(rename = "etherdream")]
Etherdream(EtherDreamConf), Etherdream(EtherDreamConf),
#[serde(rename = "dummy")] #[serde(rename = "dummy")]
Dummy, Dummy,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HeliosConf { pub struct HeliosConf {
pub id: u8 pub id: u8,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EtherDreamConf { pub struct EtherDreamConf {
pub ip: String pub ip: String,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub enum TransformConf { pub enum TransformConf {
#[serde(rename = "translate")] #[serde(rename = "translate")]
Translate(transformer::Translate), Translate(transformer::Translate),
#[serde(rename = "replicate")] #[serde(rename = "replicate")]
Replicate(transformer::Replicate), Replicate(transformer::Replicate),
#[serde(rename = "rotate")] #[serde(rename = "rotate")]
Rotate(transformer::Rotate), Rotate(transformer::Rotate),
#[serde(rename = "flip_horizontal")] #[serde(rename = "flip_horizontal")]
FlipH(transformer::FlipHorizontal), FlipH(transformer::FlipHorizontal),
#[serde(rename = "flip_vertical")] #[serde(rename = "flip_vertical")]
FlipV(transformer::FlipVertical), FlipV(transformer::FlipVertical),
#[serde(rename = "grid")] #[serde(rename = "grid")]
Grid(transformer::Grid), Grid(transformer::Grid),
#[serde(rename = "homography")] #[serde(rename = "homography")]
Homography(transformer::Homography) Homography(transformer::Homography),
#[serde(rename = "angle_correction")]
AngleOptimisation(transformer::AngleOptimisation),
} }
impl Conf { impl Conf {
pub fn new(path: &str) -> LJResult<Conf> { pub fn new(path: &str) -> LJResult<Conf> {
let settings = Config::builder() let settings = Config::builder()
.add_source(config::File::with_name(path)) .add_source(config::File::with_name(path))
.build()?; .build()?;
let conf : Conf = settings.try_deserialize().map_err(LJError::Config)?; dbg!("path:", path);
Ok(conf) //println!("plop");
dbg!(settings.clone());
let conf: Conf = settings.try_deserialize().map_err(LJError::Config)?;
//println!("plum");
Ok(conf)
} }
//println!("plop");
pub fn get_transformers(&self) -> Vec<Box<dyn transformer::Transformers>> { pub fn get_transformers(&self) -> Vec<Box<dyn transformer::Transformers>> {
let mut v = vec![]; let mut v = vec![];
for t in &self.transformers { for t in &self.transformers {
let t : Box<dyn transformer::Transformers> = match t { let t: Box<dyn transformer::Transformers> = match t {
TransformConf::Translate(t) => Box::new(*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::Rotate(r) => Box::new(*r),
TransformConf::FlipH(r) => Box::new(*r), TransformConf::FlipH(r) => Box::new(*r),
TransformConf::FlipV(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), TransformConf::Homography(r) => Box::new(*r),
}; TransformConf::AngleOptimisation(r) => Box::new(*r),
v.push(t); };
} v.push(t);
v }
v
} }
#[allow(dead_code)] #[allow(dead_code)]
pub fn dump() { pub fn dump() {
let conf = Conf { let conf = Conf {
laser_id: 0, laser_id: 0,
debug: true, debug: true,
redis_url: "redis://127.0.0.1:6379/".to_string(), redis_url: "redis://127.0.0.1:6379/".to_string(),
dac: DacFamily::Helios(HeliosConf { id: 0 }), dac: DacFamily::Helios(HeliosConf { id: 0 }),
transformers: vec![ transformers: vec![
TransformConf::Translate(transformer::Translate { x: 2000.0, TransformConf::Translate(transformer::Translate {
y: 2000.0 } ), x: 2000.0,
TransformConf::Replicate(transformer::Replicate::Until(48)) y: 2000.0,
] }),
}; TransformConf::Replicate(transformer::Replicate::Until(48)),
let s = toml::to_string(&conf).unwrap(); ],
println!("{}", s); };
let s = toml::to_string(&conf).unwrap();
println!("{}", s);
} }
} }

View File

@ -1,15 +1,15 @@
mod helios;
mod dummy; mod dummy;
mod etherdream; mod etherdream;
mod helios;
use std::fmt;
use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/}; use crate::conf::{Conf, DacFamily /*EtherDreamConf, HeliosConf*/};
use crate::device::helios::HeliosDevice;
use crate::device::dummy::DummyDevice; use crate::device::dummy::DummyDevice;
use crate::device::etherdream::EtherdreamDevice;
use crate::device::helios::HeliosDevice;
use crate::errors::LJResult; use crate::errors::LJResult;
use crate::point::Point; use crate::point::Point;
use serde::Serialize; use serde::Serialize;
use crate::device::etherdream::EtherdreamDevice; use std::fmt;
/* /*
self.protocol_version, self.protocol_version,
@ -26,25 +26,25 @@ self.point_count
#[repr(u8)] #[repr(u8)]
#[derive(Debug, PartialEq, Serialize, Copy, Clone)] #[derive(Debug, PartialEq, Serialize, Copy, Clone)]
pub enum PlaybackState { pub enum PlaybackState {
IDLE = 0, IDLE = 0,
PREPARE = 1, PREPARE = 1,
PLAYING = 2, PLAYING = 2,
UNKNOWN = 99, UNKNOWN = 99,
} }
impl fmt::Display for PlaybackState { impl fmt::Display for PlaybackState {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self) write!(f, "{:?}", self)
} }
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Status { pub struct Status {
pub last_traced_at: String, pub last_traced_at: String,
pub properties: Vec<String>, pub properties: Vec<String>,
pub playback_state: PlaybackState, pub playback_state: PlaybackState,
pub capacity: u16, pub capacity: u16,
pub lack: String, pub lack: String,
} }
// /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) // /lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing)
@ -52,21 +52,17 @@ pub struct Status {
// /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. // /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection.
pub trait Device { pub trait Device {
fn status(&mut self) -> Status; fn status(&mut self) -> Status;
fn draw( fn draw(&mut self, frame: Vec<Point>, speed: u32) -> LJResult<()>;
&mut self, fn stop(&mut self) -> LJResult<()>;
frame: Vec<Point>, fn grid(&mut self) -> Vec<Point>;
speed: u32,
) -> LJResult<()>;
fn stop(&mut self) -> LJResult<()>;
fn grid(&mut self) -> Vec<Point>;
} }
pub fn device_factory(config: &Conf) -> LJResult<Box<dyn Device>> { pub fn device_factory(config: &Conf) -> LJResult<Box<dyn Device>> {
let device: Box<dyn Device> = match &config.dac { let device: Box<dyn Device> = match &config.dac {
DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?), DacFamily::Helios(conf) => Box::new(HeliosDevice::new(conf)?),
DacFamily::Etherdream( conf) => Box::new( EtherdreamDevice::new(conf)?), DacFamily::Etherdream(conf) => Box::new(EtherdreamDevice::new(conf)?),
DacFamily::Dummy => Box::new(DummyDevice::new()?) DacFamily::Dummy => Box::new(DummyDevice::new()?),
}; };
Ok(device) Ok(device)
} }

View File

@ -1,43 +1,44 @@
use crate::device::{Device, Status, PlaybackState}; use crate::device::{Device, PlaybackState, Status};
use crate::errors::LJResult; use crate::errors::LJResult;
use crate::point::{Color, Point}; use crate::point::{Color, Point};
use log::debug; use log::debug;
pub struct DummyDevice { pub struct DummyDevice {
state: PlaybackState state: PlaybackState,
} }
impl DummyDevice { impl DummyDevice {
pub fn new() -> LJResult<Self> { pub fn new() -> LJResult<Self> {
Ok(Self { state: PlaybackState::IDLE }) Ok(Self {
} state: PlaybackState::IDLE,
})
}
} }
impl Device for DummyDevice { impl Device for DummyDevice {
fn status(&mut self) -> Status { fn status(&mut self) -> Status {
Status { Status {
last_traced_at: "never".to_string(), last_traced_at: "never".to_string(),
properties: vec!["foo".to_string()], properties: vec!["foo".to_string()],
playback_state: self.state, playback_state: self.state,
capacity: 0, capacity: 0,
lack: "lack".to_string() lack: "lack".to_string(),
} }
} }
fn draw(&mut self, fn draw(&mut self, line: Vec<Point>, speed: u32) -> LJResult<()> {
line: Vec<Point>, debug!("Draw Line at speed {speed} : {:?}", line);
speed: u32, Ok(())
) -> LJResult<()> { }
debug!("Draw Line at speed {speed} : {:?}", line);
Ok(())
}
fn stop(&mut self) -> LJResult<()> { fn stop(&mut self) -> LJResult<()> {
Ok(()) Ok(())
} }
fn grid(&mut self) -> Vec<Point> { fn grid(&mut self) -> Vec<Point> {
vec!( vec![Point {
Point{ x: 0 as f32, y: 0 as f32, color:Color{ r: 0, g: 0, b: 0 }} x: 0 as f32,
) y: 0 as f32,
} color: Color { r: 0, g: 0, b: 0 },
}]
}
} }

View File

@ -1,10 +1,10 @@
use std::time;
use std::net::SocketAddr;
use ether_dream::dac::stream::connect; use ether_dream::dac::stream::connect;
use ether_dream::dac::Stream; use ether_dream::dac::Stream;
use std::net::SocketAddr;
use std::time;
use crate::conf::EtherDreamConf; use crate::conf::EtherDreamConf;
use crate::device::{Device, Status, PlaybackState}; use crate::device::{Device, PlaybackState, Status};
use crate::errors::{LJError, LJResult}; use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point}; use crate::point::{Color, Point};
use ether_dream::protocol::{DacBroadcast, DacStatus}; use ether_dream::protocol::{DacBroadcast, DacStatus};
@ -12,142 +12,144 @@ use log::{info, warn};
#[warn(dead_code)] #[warn(dead_code)]
pub struct EtherdreamDevice { pub struct EtherdreamDevice {
pub conf: EtherDreamConf, pub conf: EtherDreamConf,
dac: DacBroadcast, dac: DacBroadcast,
// source_address: SocketAddr, // source_address: SocketAddr,
stream: Stream, stream: Stream,
// sent_points: u16, // sent_points: u16,
lack: String, lack: String,
last_traced_at: String, last_traced_at: String,
} }
impl EtherdreamDevice { impl EtherdreamDevice {
pub fn new(conf: &EtherDreamConf) -> LJResult<Self> { pub fn new(conf: &EtherDreamConf) -> LJResult<Self> {
let (dac, _source_address, stream) = EtherdreamDevice::get_dac(conf)?; let (dac, _source_address, stream) = EtherdreamDevice::get_dac(conf)?;
// let (dac, source_address) = EtherdreamDevice::get_dac(conf)?; // let (dac, source_address) = EtherdreamDevice::get_dac(conf)?;
Ok(Self { Ok(Self {
conf: (*conf).clone(), conf: (*conf).clone(),
dac, dac,
// source_address, // source_address,
stream, stream,
// sent_points: 0, // sent_points: 0,
lack: "".to_string(), 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)> { pub fn get_dac(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> {
let ip = &conf.ip; let ip = &conf.ip;
let dac_broadcast = ether_dream::recv_dac_broadcasts()?; let dac_broadcast = ether_dream::recv_dac_broadcasts()?;
dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?; dac_broadcast.set_timeout(Some(time::Duration::new(10, 0)))?;
info!("Attempting to get DAC broadcast..."); info!("Attempting to get DAC broadcast...");
let broadcast = dac_broadcast let broadcast = dac_broadcast
.filter_map(|result| { .filter_map(|result| match result {
match result { Err(err) => {
Err(err) => { warn!("Failed to find a valid DAC via broadcast. Error: {:?}", err);
warn!( "Failed to find a valid DAC via broadcast. Error: {:?}", err); info!("Retrying...");
info!( "Retrying..."); None
None }
}, Ok((dac, source_addr)) => {
Ok((dac, source_addr)) => { if source_addr.is_ipv6() {
if source_addr.is_ipv6() { return None; } return None;
if &source_addr.ip().to_string() != ip { return None; } }
info!("Valid broadcast"); if &source_addr.ip().to_string() != ip {
Some(Ok((dac, source_addr))) return None;
} }
} info!("Valid broadcast");
}) Some(Ok((dac, source_addr)))
.next() }
.expect("Failed to receive broadcast."); })
match broadcast { .next()
Err(err) => { .expect("Failed to receive broadcast.");
Err(Box::new(LJError::EtherdreamConnectError(err))) match broadcast {
} Err(err) => Err(Box::new(LJError::EtherdreamConnectError(err))),
Ok((dac, source_addr)) => { Ok((dac, source_addr)) => {
let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?; let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?;
Ok((dac, source_addr, stream)) Ok((dac, source_addr, stream))
} }
} }
} }
pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult<Stream> { pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult<Stream> {
// Establish the TCP connection. // Establish the TCP connection.
let mut stream = connect(dac, source_address.ip())?; let mut stream = connect(dac, source_address.ip())?;
// Prepare stream // Prepare stream
stream stream
.queue_commands() .queue_commands()
.prepare_stream() .prepare_stream()
.submit() .submit()
.err() .err()
.map(|err| { .map(|err| {
eprintln!( eprintln!(
"err occurred when submitting PREPARE_STREAM \ "err occurred when submitting PREPARE_STREAM \
command and listening for response: {}", command and listening for response: {}",
err err
); );
}); });
Ok(stream) 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(())
}
pub fn check_tcp_stream(&mut self) -> LJResult<()> { // Determine the number of points needed to fill the DAC.
// todo Reinit stream if needed fn points_to_generate(&self) -> usize {
// self.stream = EtherdreamDevice::get_tcp_stream(&self.dac, &self.source_address)? self.dac.buffer_capacity as usize - 1 - self.dac.dac_status.buffer_fullness as usize
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 { impl Device for EtherdreamDevice {
fn status(&mut self) -> Status { fn status(&mut self) -> Status {
let _ = self.check_tcp_stream(); let _ = self.check_tcp_stream();
// "a": ACK "F": Full "I": invalid. 64 or 35 for no connection. // "a": ACK "F": Full "I": invalid. 64 or 35 for no connection.
let playback_state = match self.dac.dac_status.playback_state { let playback_state = match self.dac.dac_status.playback_state {
DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE, DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE,
DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE, DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE,
DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING, DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING,
_ => PlaybackState::UNKNOWN _ => PlaybackState::UNKNOWN,
}; };
Status { Status {
last_traced_at: self.last_traced_at.clone(), last_traced_at: self.last_traced_at.clone(),
properties: vec!["foo".to_string()], properties: vec!["foo".to_string()],
playback_state, playback_state,
capacity: self.dac.dac_status.buffer_fullness, capacity: self.dac.dac_status.buffer_fullness,
lack: String::from(&self.lack), lack: String::from(&self.lack),
} }
} }
fn draw(&mut self, fn draw(&mut self, line: Vec<Point>, _speed: u32) -> LJResult<()> {
line: Vec<Point>, let n_points = self.points_to_generate();
_speed: u32, self.stream
) -> LJResult<()> { .queue_commands()
let n_points = self.points_to_generate(); .data(line.into_iter().map(|point| point.into()).take(n_points))
self.stream .submit()?;
.queue_commands() Ok(())
.data(line.into_iter().map(|point| point.into()).take(n_points)) }
.submit()?;
Ok(())
}
fn stop(&mut self) -> LJResult<()> { fn stop(&mut self) -> LJResult<()> {
self.stream self.stream
.queue_commands() .queue_commands()
.stop() .stop()
.submit() .submit()
.expect("err occurred when submitting STOP command and listening for response"); .expect("err occurred when submitting STOP command and listening for response");
Ok(()) Ok(())
} }
fn grid(&mut self) -> Vec<Point> { fn grid(&mut self) -> Vec<Point> {
vec!( vec![Point {
Point { x: 0.0, y: 0.0, color: Color { r: 255, g: 255, b: 255 } } x: 0.0,
) y: 0.0,
} color: Color {
r: 255,
g: 255,
b: 255,
},
}]
}
} }

View File

@ -1,103 +1,152 @@
use crate::conf::HeliosConf;
use crate::device::{Device, PlaybackState, Status};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use chrono::Utc;
use helios_dac::{
// Coordinate,
// Color,
DeviceStatus,
Frame,
// Point as HeliosPoint,
};
/// ///
/// Configure udev: /// Configure udev:
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md /// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
/// ///
use helios_dac::{NativeHeliosDac, NativeHeliosDacController}; use helios_dac::{NativeHeliosDac, NativeHeliosDacController};
use helios_dac::{
// Coordinate,
// Color,
DeviceStatus,
Frame,
// Point as HeliosPoint,
};
use crate::conf::HeliosConf;
use crate::device::{Device, Status, PlaybackState};
use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use chrono::Utc;
pub struct HeliosDevice { pub struct HeliosDevice {
pub conf: HeliosConf, pub conf: HeliosConf,
dac: NativeHeliosDac, dac: NativeHeliosDac,
sent_points: u16, sent_points: u16,
state: PlaybackState, state: PlaybackState,
lack: String, lack: String,
last_traced_at: String, last_traced_at: String,
} }
impl HeliosDevice { impl HeliosDevice {
pub fn new(conf: &HeliosConf) -> LJResult<Self> { pub fn new(conf: &HeliosConf) -> LJResult<Self> {
let id = conf.id; let id = conf.id;
let controller = NativeHeliosDacController::new()?; let controller = NativeHeliosDacController::new()?;
let devices = controller.list_devices()?; let devices = controller.list_devices()?;
let Some(device) = devices.into_iter().nth(id as usize) else { let Some(device) = devices.into_iter().nth(id as usize) else {
return Err(Box::new(LJError::HeliosDeviceMissing)); return Err(Box::new(LJError::HeliosDeviceMissing));
}; };
let dac = device.open()?; let dac = device.open()?;
Ok(Self { Ok(Self {
conf: (*conf).clone(), conf: (*conf).clone(),
dac, dac,
sent_points: 0, sent_points: 0,
state: PlaybackState::PREPARE, state: PlaybackState::PREPARE,
lack: "".to_string(), 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 { impl Device for HeliosDevice {
fn status(&mut self) -> Status { fn status(&mut self) -> Status {
let lack = self.lack.clone(); let lack = self.lack.clone();
Status { Status {
last_traced_at: self.last_traced_at.clone(), last_traced_at: self.last_traced_at.clone(),
properties: vec!["foo".to_string()], properties: vec!["foo".to_string()],
playback_state: self.state, playback_state: self.state,
capacity: self.sent_points, capacity: self.sent_points,
lack, lack,
} }
} }
fn draw(&mut self, fn draw(&mut self, line: Vec<Point>, speed: u32) -> LJResult<()> {
line: Vec<Point>, self.state = PlaybackState::IDLE;
speed: u32, while let Ok(DeviceStatus::NotReady) = self.dac.status() {}
) -> LJResult<()> { self.state = PlaybackState::PLAYING;
self.state = PlaybackState::IDLE;
while let Ok(DeviceStatus::NotReady) = self.dac.status() {}
self.state = PlaybackState::PLAYING;
let points: Vec<helios_dac::Point> = line.into_iter().map(|p| p.into()).collect(); let points: Vec<helios_dac::Point> = line.into_iter().map(|p| p.into()).collect();
let frame = Frame::new(speed, points.clone()); let frame = Frame::new(speed, points.clone());
self.dac.write_frame(frame.clone())?; self.dac.write_frame(frame.clone())?;
self.sent_points = points.len() as u16; self.sent_points = points.len() as u16;
self.last_traced_at = Utc::now().to_rfc3339(); self.last_traced_at = Utc::now().to_rfc3339();
Ok(()) Ok(())
} }
fn stop(&mut self) -> LJResult<()> { fn stop(&mut self) -> LJResult<()> {
self.dac.stop()?; self.dac.stop()?;
Ok(()) Ok(())
} }
fn grid(&mut self) -> Vec<Point> { fn grid(&mut self) -> Vec<Point> {
let dim_min = 0 as f32; let dim_min = 0 as f32;
let dim_mid = 2047 as f32; let dim_mid = 2047 as f32;
let dim_max = 4095 as f32; let dim_max = 4095 as f32;
let col_min = Color { r: 0, g: 0, b: 0 }; let col_min = Color { r: 0, g: 0, b: 0 };
let col_max = Color { r: 255, g: 255, b: 255 }; let col_max = Color {
r: 255,
g: 255,
b: 255,
};
vec![ vec![
Point { x: dim_min, y: dim_max, color: col_min }, Point {
Point { x: dim_min, y: dim_max, color: col_max }, x: dim_min,
Point { x: dim_max, y: dim_max, color: col_max }, y: dim_max,
Point { x: dim_max, y: dim_min, color: col_max }, color: col_min,
Point { x: dim_min, y: dim_min, color: col_max }, },
Point { x: dim_min, y: dim_min, color: col_min }, Point {
Point { x: dim_min, y: dim_mid, color: col_min }, x: dim_min,
Point { x: dim_min, y: dim_mid, color: col_max }, y: dim_max,
Point { x: dim_mid, y: dim_mid, color: col_max }, color: col_max,
Point { x: dim_mid, y: dim_min, color: col_max }, },
Point { x: dim_min, y: dim_min, color: col_max }, Point {
Point { x: dim_min, y: dim_min, color: col_min }, 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,
},
]
}
} }

View File

@ -1,50 +1,50 @@
use config::ConfigError;
use redis::RedisError;
use std::error::Error; use std::error::Error;
use std::{fmt, io}; use std::{fmt, io};
use redis::RedisError;
use config::ConfigError;
pub type LJResult<T> = Result<T, Box<dyn std::error::Error>>; pub type LJResult<T> = Result<T, Box<dyn std::error::Error>>;
#[derive(Debug)] #[derive(Debug)]
pub enum LJError { pub enum LJError {
Config(ConfigError), Config(ConfigError),
RedisConnect(RedisError), RedisConnect(RedisError),
HeliosDeviceMissing, HeliosDeviceMissing,
BadEDH, BadEDH,
EtherdreamConnectError(io::Error), EtherdreamConnectError(io::Error),
} }
impl fmt::Display for LJError { impl fmt::Display for LJError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use LJError::*; use LJError::*;
match self { match self {
Config(err) => { Config(err) => {
write!(f, "unable to load config file: {err}") write!(f, "unable to load config file: {err}")
} }
RedisConnect(err) => { RedisConnect(err) => {
write!(f, "unable to connect to redis server: {err}") write!(f, "unable to connect to redis server: {err}")
} }
HeliosDeviceMissing => { HeliosDeviceMissing => {
write!(f, "helios device not found") write!(f, "helios device not found")
} }
BadEDH => { BadEDH => {
write!(f, "EDH matrix is not a 3x3 matrix") write!(f, "EDH matrix is not a 3x3 matrix")
} }
EtherdreamConnectError(err) => { EtherdreamConnectError(err) => {
write!(f, "Failed to retrieve Etherdream device: {err}") write!(f, "Failed to retrieve Etherdream device: {err}")
} }
} }
} }
} }
impl Error for LJError { impl Error for LJError {
fn source(&self) -> Option<&(dyn Error + 'static)> { fn source(&self) -> Option<&(dyn Error + 'static)> {
use LJError::*; use LJError::*;
match self { match self {
RedisConnect(err) => Some(err), RedisConnect(err) => Some(err),
_ => None _ => None,
} }
} }
} }

View File

@ -1,7 +1,7 @@
pub mod redis_ctrl;
pub mod conf; pub mod conf;
pub mod errors;
pub mod device; pub mod device;
pub mod errors;
pub mod point; pub mod point;
pub mod redis_ctrl;
pub mod transformer; pub mod transformer;
pub mod worldstate; pub mod worldstate;

View File

@ -1,193 +1,178 @@
mod conf;
mod device;
mod errors;
mod point;
/// ///
/// Configure udev: /// Configure udev:
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md /// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
/// ///
mod redis_ctrl; mod redis_ctrl;
mod conf;
mod errors;
mod point;
mod transformer; mod transformer;
mod device;
mod worldstate; mod worldstate;
use conf::Conf;
use device::device_factory; use device::device_factory;
use env_logger::Builder;
use errors::LJResult;
use log::{/* warn, */ error, info, LevelFilter};
use point::{Color, Point};
use redis_ctrl::{Order, RedisCtrl};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use redis_ctrl::{RedisCtrl, Order};
use conf::Conf;
use errors::LJResult;
use point::{Point, Color};
use transformer::Transformers; use transformer::Transformers;
use log::{LevelFilter, info, /* warn, */ error};
use env_logger::Builder;
use worldstate::WorldState; use worldstate::WorldState;
const DEFAULT_CONF_FILE: &str = "settings.toml"; const DEFAULT_CONF_FILE: &str = "settings.toml";
pub fn main() { pub fn main() {
match run_all() { match run_all() {
Ok(()) => {} Ok(()) => {}
Err(err) => { Err(err) => {
error!("Error: {}", err); error!("Error: {}", err);
} }
} }
} }
fn run_all() -> LJResult<()> { fn run_all() -> LJResult<()> {
// Setup configuration file and set up logs // Setup configuration file and set up logs
let filename = std::env::args().nth(1).unwrap_or_else(|| { let filename = std::env::args()
DEFAULT_CONF_FILE.to_string() .nth(1)
}); .unwrap_or_else(|| DEFAULT_CONF_FILE.to_string());
let config = Conf::new(&filename); let config = Conf::new(&filename);
init_logging(&config); init_logging(&config);
let config = config?; let config = config?;
info!("*** Starting up ***"); info!("*** Starting up ***");
info!("{:?}", config); info!("{:?}", config);
// Setup Redis Service // Setup Redis Service
let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?; let mut rs = RedisCtrl::new(&config.redis_url, &config.laser_id)?;
let mut world_state = rs.init_world_state().unwrap(); let mut world_state = rs.init_world_state().unwrap();
info!("WorldState: {:?}", world_state); info!("WorldState: {:?}", world_state);
dbg!("worldstate.kpps: {}", world_state.kpps);
// Setup handler for interrupt Signals // Setup handler for interrupt Signals
let running = Arc::new(AtomicBool::new(true)); let running = Arc::new(AtomicBool::new(true));
let r = running.clone(); let r = running.clone();
ctrlc::set_handler(move || { ctrlc::set_handler(move || {
r.store(false, Ordering::SeqCst); r.store(false, Ordering::SeqCst);
})?; })?;
// Setup Laser Device based on conf // Setup Laser Device based on conf
let mut tracer = device_factory(&config)?; let mut tracer = device_factory(&config)?;
world_state.grid = tracer.grid(); world_state.grid = tracer.grid();
// can't work, but we can add + Debug to Device to make it work... // can't work, but we can add + Debug to Device to make it work...
//dbg!(tracer); //dbg!(tracer);
// Setup geometry transformers on points lists // Setup geometry transformers on points lists
let transformers = config.get_transformers(); let transformers = config.get_transformers();
// Dispatch based on redis requests // Dispatch based on redis requests
while running.load(Ordering::SeqCst) { while running.load(Ordering::SeqCst) {
rs.set_status(tracer.status())?; rs.set_status(tracer.status())?;
let order = rs.get_order(config.laser_id)?; let order = rs.get_order(config.laser_id)?;
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, &mut rs, &world_state)?;
// For now, draw all the time
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")?;
//dbg!(world_state.kpps);
}
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
info!("Order: {:?}", order);
}
}
}
match order { info!("Exiting, stoping device.");
Order::Draw | Order::Black | Order::Grid => { tracer.stop()?;
// 0 : Draw Normal point list Ok(())
// 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,
&mut rs,
&world_state,
)?;
// For now, draw all the time
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 => {
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
info!("Order: {:?}", order);
}
}
}
info!("Exiting, stoping device.");
tracer.stop()?;
Ok(())
} }
fn init_logging(config: &LJResult<Conf>) { fn init_logging(config: &LJResult<Conf>) {
if let Ok(ref config) = config { if let Ok(ref config) = config {
if config.debug { if config.debug {
let mut builder = Builder::from_default_env(); let mut builder = Builder::from_default_env();
builder builder.filter(None, LevelFilter::Info).init();
.filter(None, LevelFilter::Info) info!("Debug mode enabled from configuration file");
.init(); return;
info!("Debug mode enabled from configuration file"); }
return; }
} info!("Logging level inherited from env");
} env_logger::init();
info!("Logging level inherited from env");
env_logger::init();
} }
fn get_next_frame( fn get_next_frame(
config: &Conf, config: &Conf,
transformers: &[Box<dyn Transformers>], transformers: &[Box<dyn Transformers>],
rs: &mut RedisCtrl, rs: &mut RedisCtrl,
world_state: &WorldState, world_state: &WorldState,
) -> LJResult<Vec<Point>> { ) -> LJResult<Vec<Point>> {
let format_key = format!("{}{}", let format_key = format!("{}{}", world_state.client_key, config.laser_id);
world_state.client_key,
config.laser_id);
// Handle the grid case // Handle the grid case
let mut line: Vec<Point> = if world_state.draw_grid { let mut line: Vec<Point> = if world_state.draw_grid {
world_state.grid.clone() world_state.grid.clone()
} else { } else {
let redis_line = rs.get_line(&format_key)?; let redis_line = rs.get_line(&format_key)?;
redis_line.into_iter() redis_line.into_iter().map(|tpl| tpl.into()).collect()
.map(|tpl| tpl.into()) };
.collect()
};
for transformer in transformers { for transformer in transformers {
line = transformer.apply(&line, world_state); line = transformer.apply(&line, world_state);
} }
info!("Draw Black -> {}", world_state.draw_black); info!("Draw Black -> {}", world_state.draw_black);
info!("Draw Grid -> {}", world_state.draw_grid); info!("Draw Grid -> {}", world_state.draw_grid);
// LIMITER and BLACK // LIMITER and BLACK
line = line.into_iter() line = line
.map(|p| { .into_iter()
let color = if world_state.draw_black { .map(|p| {
Color { r: 0, g: 0, b: 0 } let color = if world_state.draw_black {
} else { Color { r: 0, g: 0, b: 0 }
Color { } else {
r: p.color.r.min(world_state.intensity), Color {
g: p.color.g.min(world_state.intensity), r: p.color.r.min(world_state.intensity),
b: p.color.b.min(world_state.intensity), g: p.color.g.min(world_state.intensity),
} b: p.color.b.min(world_state.intensity),
}; }
Point { };
color, Point { color, ..p }
..p })
} .collect();
})
.collect();
//info!("Line: {:?}", line); //info!("Line: {:?}", line);
Ok(line) Ok(line)
} }

View File

@ -2,63 +2,91 @@ use ether_dream::protocol::DacPoint;
#[derive(Debug, Clone, Copy, Default, PartialEq)] #[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Point { pub struct Point {
pub x: f32, pub x: f32,
pub y: f32, pub y: f32,
pub color: Color, pub color: Color,
} }
#[derive(Debug, Clone, Copy, Default, PartialEq)] #[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Color { pub struct Color {
pub r: u8, pub r: u8,
pub g: u8, pub g: u8,
pub b: u8, pub b: u8,
} }
impl Point {
pub fn diff(p1: &Self, p2: &Self) -> Self {
Point {
x: p1.x - p2.x,
y: p1.y - p2.y,
color: Color { r: 0, g: 0, b: 0 },
}
}
pub fn normalize(&mut self) -> Self {
let length = (self.x * self.x + self.y * self.y).sqrt();
self.x = self.x / length;
self.y = self.y / length;
*self
}
pub fn cross(&self, pt: &Self) -> f32 {
self.x * pt.x + self.y * pt.y
}
}
// normalaize
// diff
impl From<Color> for u32 { impl From<Color> for u32 {
fn from(value: Color) -> Self { fn from(value: Color) -> Self {
let r = value.r as u32; let r = value.r as u32;
let g = value.g as u32; let g = value.g as u32;
let b = (value.b) as u32; let b = (value.b) as u32;
(r << 16) + (g << 8) + b (r << 16) + (g << 8) + b
} }
} }
impl From<(f32, f32, u32)> for Point { impl From<(f32, f32, u32)> for Point {
fn from((x, y, color): (f32, f32, u32)) -> Point { fn from((x, y, color): (f32, f32, u32)) -> Point {
let r = (color >> 16) as u8; let r = (color >> 16) as u8;
let g = ((color >> 8) & 255) as u8; let g = ((color >> 8) & 255) as u8;
let b = (color & 255) as u8; let b = (color & 255) as u8;
Point { x, y, color: Color { r, g, b } } Point {
} x,
y,
color: Color { r, g, b },
}
}
} }
impl From<Point> for helios_dac::Point { impl From<Point> for helios_dac::Point {
fn from(pt: Point) -> helios_dac::Point { fn from(pt: Point) -> helios_dac::Point {
let x = pt.x.clamp(0.0, 4095.0) as u16; let x = pt.x.clamp(0.0, 4095.0) as u16;
let y = pt.y.clamp(0.0, 4095.0) as u16; let y = pt.y.clamp(0.0, 4095.0) as u16;
helios_dac::Point { helios_dac::Point {
coordinate: (x, y).into(), coordinate: (x, y).into(),
color: helios_dac::Color::new(pt.color.r, pt.color.g, pt.color.b), color: helios_dac::Color::new(pt.color.r, pt.color.g, pt.color.b),
intensity: 0xFF, intensity: 0xFF,
} }
} }
} }
impl From<Point> for DacPoint { impl From<Point> for DacPoint {
fn from(pt: Point) -> DacPoint { fn from(pt: Point) -> DacPoint {
let control = 0; let control = 0;
let (u1, u2) = (0, 0); let (u1, u2) = (0, 0);
let i = 255; let i = 255;
DacPoint { DacPoint {
control, control,
x: pt.x as i16, x: pt.x as i16,
y: pt.y as i16, y: pt.y as i16,
i, i,
r: pt.color.r.into(), r: pt.color.r.into(),
g: pt.color.g.into(), g: pt.color.g.into(),
b: pt.color.b.into(), b: pt.color.b.into(),
u1, u1,
u2, u2,
} }
} }
} }

View File

@ -1,132 +1,134 @@
use redis::{Client, Commands, Connection};
use ron::de::from_str;
use crate::device::Status; use crate::device::Status;
use crate::errors::{LJError, LJResult}; use crate::errors::{LJError, LJResult};
use crate::worldstate::{WorldState,EDH}; use crate::worldstate::{WorldState, EDH};
use redis::{Client, Commands, Connection};
use ron::de::from_str;
// use log::info; // use log::info;
#[repr(u8)] #[repr(u8)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum Order { pub enum Order {
Draw = 0, Draw = 0,
Edh, Edh,
//homography //homography
Black, Black,
Grid, Grid,
Resampler, Resampler,
ClientKey, ClientKey,
Intensity, Intensity,
Kpps, Kpps,
ColorBalance, ColorBalance,
} }
impl TryFrom<u8> for Order { impl TryFrom<u8> for Order {
type Error = String; type Error = String;
fn try_from(value: u8) -> Result<Self, Self::Error> { fn try_from(value: u8) -> Result<Self, Self::Error> {
use Order::*; use Order::*;
if value > 8 { if value > 8 {
return Err("order out of range".to_string()); return Err("order out of range".to_string());
} }
Ok(match value { Ok(match value {
0 => Draw, 0 => Draw,
1 => Edh, 1 => Edh,
2 => Black, 2 => Black,
3 => Grid, 3 => Grid,
4 => Resampler, 4 => Resampler,
5 => ClientKey, 5 => ClientKey,
6 => Intensity, 6 => Intensity,
7 => Kpps, 7 => Kpps,
8 => ColorBalance, 8 => ColorBalance,
_ => unreachable!() _ => unreachable!(),
}) })
} }
} }
pub type Line = Vec<(f32, f32, u32)>; pub type Line = Vec<(f32, f32, u32)>;
pub struct RedisCtrl { pub struct RedisCtrl {
pub client: Client, pub client: Client,
pub connection: Connection, pub connection: Connection,
laser_id: u8, laser_id: u8,
} }
impl RedisCtrl { impl RedisCtrl {
pub fn new(url: &str, laser_id: &u8) -> LJResult<Self> { pub fn new(url: &str, laser_id: &u8) -> LJResult<Self> {
let client = Client::open(url) let client = Client::open(url).map_err(LJError::RedisConnect)?;
.map_err(LJError::RedisConnect)?; let connection = client.get_connection().map_err(LJError::RedisConnect)?;
let connection = client.get_connection() Ok(RedisCtrl {
.map_err(LJError::RedisConnect)?; client,
Ok(RedisCtrl { client, connection, laser_id: *laser_id }) connection,
} laser_id: *laser_id,
})
}
pub fn get_line(&mut self, key: &str) -> LJResult<Line> { pub fn get_line(&mut self, key: &str) -> LJResult<Line> {
let val: String = self.connection.get(key)?; let val: String = self.connection.get(key)?;
let line: Line = from_str(&val)?; let line: Line = from_str(&val)?;
Ok(line) Ok(line)
} }
pub fn set(&mut self, key: String, value: String) -> LJResult<()> { pub fn set(&mut self, key: String, value: String) -> LJResult<()> {
self.connection.set(key, value)?; self.connection.set(key, value)?;
Ok(()) Ok(())
} }
pub fn get_order(&mut self, id: u8) -> LJResult<Order> { pub fn get_order(&mut self, id: u8) -> LJResult<Order> {
let path = format!("/order/{id}"); let path = format!("/order/{id}");
let val: u8 = self.connection.get(path.clone())?; let val: u8 = self.connection.get(path.clone())?;
if val == 1 || val >= 4 { if val == 1 || val >= 4 {
self.connection.set(path, 0)?; self.connection.set(path, 0)?;
} }
Ok(val.try_into()?) Ok(val.try_into()?)
} }
/** /**
/lstt/lasernumber etherdream last_status.playback_state (0: idle 1: prepare 2: playing) /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) /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. /lack/lasernumber "a": ACK "F": Full "I": invalid. 64 or 35 for no connection.
**/ **/
pub fn set_status(&mut self, status: Status) -> LJResult<()> { pub fn set_status(&mut self, status: Status) -> LJResult<()> {
let lstt_key = format!("/lstt/{}", self.laser_id); let lstt_key = format!("/lstt/{}", self.laser_id);
let cap_key = format!("/cap/{}", self.laser_id); let cap_key = format!("/cap/{}", self.laser_id);
let lack_key = format!("/lack/{}", self.laser_id); let lack_key = format!("/lack/{}", self.laser_id);
self.set(lstt_key, status.playback_state.to_string())?; self.set(lstt_key, status.playback_state.to_string())?;
self.set(cap_key, status.capacity.to_string())?; self.set(cap_key, status.capacity.to_string())?;
self.set(lack_key, status.lack.to_string())?; self.set(lack_key, status.lack.to_string())?;
Ok(()) Ok(())
} }
pub fn init_world_state( &mut self) -> LJResult<WorldState>{ pub fn init_world_state(&mut self) -> LJResult<WorldState> {
Ok(WorldState { Ok(WorldState {
client_key: self.get_client_key().unwrap(), client_key: self.get_client_key().unwrap(),
edh: self.get_edh().unwrap(), edh: self.get_edh().unwrap(),
kpps: self.get_int("kpps").unwrap().try_into().unwrap(), kpps: self.get_int("kpps").unwrap().try_into().unwrap(),
intensity: self.get_int("intensity").unwrap().try_into().unwrap(), intensity: self.get_int("intensity").unwrap().try_into().unwrap(),
..WorldState::default() ..WorldState::default()
}) })
} }
pub fn get_edh( &mut self ) -> LJResult<EDH> { pub fn get_edh(&mut self) -> LJResult<EDH> {
// Get new EDH // Get new EDH
let edh_key = format!("/EDH/{}", self.laser_id); let edh_key = format!("/EDH/{}", self.laser_id);
let edh : String = self.connection.get(edh_key)?; let edh: String = self.connection.get(edh_key)?;
let edh : Vec<Vec<f32>> = from_str(&edh)?; let edh: Vec<Vec<f32>> = from_str(&edh)?;
let edh = EDH::new(edh)?; let edh = EDH::new(edh)?;
Ok(edh) Ok(edh)
} }
pub fn get_client_key( &mut self ) -> LJResult<String> { pub fn get_client_key(&mut self) -> LJResult<String> {
let key : String = self.connection.get("/clientkey")?; let key: String = self.connection.get("/clientkey")?;
Ok(key) Ok(key)
} }
pub fn get_int(&mut self, key: &str ) -> LJResult<u32> { pub fn get_int(&mut self, key: &str) -> LJResult<u32> {
// Get new Int // Get new Int
let fmt = format!("/{key}/{}", self.laser_id); let fmt = format!("/{key}/{}", self.laser_id);
let val : u32 = self.connection.get(fmt)?; let val: u32 = self.connection.get(fmt)?;
Ok(val) Ok(val)
} }
} }

View File

@ -1,28 +1,26 @@
//pub mod common; //pub mod common;
mod translate; mod angle_optimisation;
mod replicate;
mod rotate;
mod flip_horizontal; mod flip_horizontal;
mod flip_vertical; mod flip_vertical;
mod grid; mod grid;
mod homography; mod homography;
mod replicate;
mod rotate;
mod translate;
use crate::point::Point; use crate::point::Point;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
// re-export transformers to be abe to use it directly from transformer:: // re-export transformers to be abe to use it directly from transformer::
pub use translate::Translate; pub use self::homography::Homography;
pub use replicate::Replicate; pub use angle_optimisation::AngleOptimisation;
pub use rotate::Rotate;
pub use flip_horizontal::FlipHorizontal; pub use flip_horizontal::FlipHorizontal;
pub use flip_vertical::FlipVertical; pub use flip_vertical::FlipVertical;
pub use grid::Grid; pub use grid::Grid;
pub use self::homography::Homography; pub use replicate::Replicate;
pub use rotate::Rotate;
pub use translate::Translate;
pub trait Transformers { pub trait Transformers {
fn apply( fn apply(&self, point_list: &[Point], world_state: &WorldState) -> Vec<Point>;
&self,
point_list: &[Point],
world_state: &WorldState
) -> Vec<Point>;
} }

View File

@ -0,0 +1,86 @@
use crate::point::{Color, Point};
use crate::transformer::Transformers;
use crate::worldstate::WorldState;
use serde::{Deserialize, Serialize};
use std::f32::consts::PI;
/// Angle Optimisation
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct AngleOptimisation {
coef: f32,
}
fn color_not_zero(p1: &Point, p2: &Point, p3: &Point) -> bool {
let c0 = Color { r: 0, g: 0, b: 0 };
if p1.color == c0 || p2.color == c0 || p3.color == c0 {
false
} else {
true
}
}
fn pos_different(p1: &Point, p2: &Point) -> bool {
if p1.x == p2.x && p1.y == p2.y {
false
} else {
true
}
}
impl Transformers for AngleOptimisation {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
let c0 = Color { r: 0, g: 0, b: 0 };
let mut v = vec![];
//println!();
//println!("====================");
//println!("= next Frame =");
//println!("====================");
v.push(point_list[0]);
for i in 1..(point_list.len() - 1) {
let prev = point_list[i - 1];
let node = point_list[i];
let next = point_list[i + 1];
if color_not_zero(&prev, &node, &next)
&& pos_different(&prev, &node)
&& pos_different(&node, &next)
{
//println!("=========");
let mut d1 = Point::diff(&node, &prev);
let mut d2 = Point::diff(&next, &next);
//dbg!(d1);
//dbg!(d2);
d1.normalize();
d2.normalize();
let cross = d1.cross(&d2);
let angle = d1.cross(&d2).acos();
let deg = angle * 180. / PI;
//dbg!(prev);
//dbg!(node);
//dbg!(next);
//dbg!(d1);
//dbg!(d2);
//dbg!(cross);
//dbg!(angle);
//dbg!(deg);
//println!("deg: {deg}");
let nb_add = (self.coef * (1. - angle / PI)) as usize;
for _ in 0..nb_add {}
}
v.push(node); // push node
}
v.push(point_list[point_list.len() - 1]); // push last
v
}
}

View File

@ -1,24 +1,27 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
/// Flip Horizontal /// Flip Horizontal
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct FlipHorizontal { pub struct FlipHorizontal {
x: f32, x: f32,
} }
impl Transformers for FlipHorizontal { impl Transformers for FlipHorizontal {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter() point_list
.map(| pt | { .iter()
let dx = pt.x - self.x; .map(|pt| {
Point { x: dx - 2. * dx, let dx = pt.x - self.x;
..*pt Point {
} x: dx - 2. * dx,
}).collect() ..*pt
}
})
.collect()
} }
} }

View File

@ -1,24 +1,27 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
/// Flip Vertical /// Flip Vertical
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct FlipVertical { pub struct FlipVertical {
y: f32, y: f32,
} }
impl Transformers for FlipVertical { impl Transformers for FlipVertical {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter() point_list
.map(| pt | { .iter()
let dy = pt.y - self.y; .map(|pt| {
Point { y: dy - 2. * dy, let dy = pt.y - self.y;
..*pt Point {
} y: dy - 2. * dy,
}).collect() ..*pt
}
})
.collect()
} }
} }

View File

@ -1,58 +1,48 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
/// Translate /// Translate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Grid { pub struct Grid {
width: f32, width: f32,
height: f32 height: f32,
} }
fn square_box(size: f32, color: u32) -> Vec<(f32, f32, u32)> { fn square_box(size: f32, color: u32) -> Vec<(f32, f32, u32)> {
vec![ vec![
(-size, -size, 0), (-size, -size, 0),
(-size, -size, color), (-size, -size, color),
(0.0, -size, color),
(0.0, -size, color), (0.0, -size, color),
(0.0, -size, color), (size, -size, color),
(size, -size, color),
(size, -size, color), (size, 0.0, color),
(size, -size, color), (size, 0.0, color),
(size, size, color),
(size, 0.0, color), (size, size, color),
(size, 0.0, color), (0.0, size, color),
(0.0, size, color),
(size, size, color), (-size, size, color),
(size, size, color), (-size, size, color),
(-size, 0.0, color),
(0.0, size, color), (-size, 0.0, color),
(0.0, size, color), (-size, -size, color),
(-size, -size, color),
(-size, size, color), (-size, -size, 0),
(-size, size, color),
(-size, 0.0, color),
(-size, 0.0, color),
(-size, -size, color),
(-size, -size, color),
(-size, -size, 0)
] ]
} }
impl Transformers for Grid { impl Transformers for Grid {
fn apply(&self, _point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, _point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
let mut sq1 = square_box(1000.0, 255 << 8); let mut sq1 = square_box(1000.0, 255 << 8);
let mut line = square_box(2000.0, 255); let mut line = square_box(2000.0, 255);
line.append(&mut sq1); line.append(&mut sq1);
let line: Vec<Point> = line.into_iter() let line: Vec<Point> = line.into_iter().map(|tpl| tpl.into()).collect();
.map(|tpl| tpl.into()).collect(); line
line
} }
} }

View File

@ -1,20 +1,18 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::worldstate::{WorldState,EDH}; use crate::transformer::Transformers;
use serde::{Serialize,Deserialize}; use crate::worldstate::{WorldState, EDH};
use serde::{Deserialize, Serialize};
/// Homography /// Homography
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Homography {} pub struct Homography {}
impl Transformers for Homography { impl Transformers for Homography {
fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], ws: &WorldState) -> Vec<Point> {
let edh : &EDH = &ws.edh; let edh: &EDH = &ws.edh;
point_list.iter() point_list.iter().map(|point| edh.apply(point)).collect()
.map(| point | edh.apply(point))
.collect()
} }
} }
@ -24,41 +22,67 @@ mod tests {
#[test] #[test]
fn identity_matrix_let_point_unchanged() { fn identity_matrix_let_point_unchanged() {
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; let p0 = Point {
x: -1500.0,
y: 1500.0,
..Point::default()
};
let edh = EDH::new(vec![ let edh = EDH::new(vec![
vec![ 1.0, 0.0, 0.0 ], vec![1.0, 0.0, 0.0],
vec![ 0.0, 1.0, 0.0 ], vec![0.0, 1.0, 0.0],
vec![ 0.0, 0.0, 1.0 ] vec![0.0, 0.0, 1.0],
]).unwrap(); ])
.unwrap();
let ws = WorldState { edh : edh, ..WorldState::default() }; let ws = WorldState {
edh: edh,
let homography = Homography{}; ..WorldState::default()
let result = homography.apply(&[p0], &ws); };
assert_eq!(result, vec![Point { x: -1500.0, let homography = Homography {};
y: 1500.0, let result = homography.apply(&[p0], &ws);
..Point::default() }]);
assert_eq!(
result,
vec![Point {
x: -1500.0,
y: 1500.0,
..Point::default()
}]
);
} }
#[test] #[test]
fn rotation_matrix_rotate_the_point() { fn rotation_matrix_rotate_the_point() {
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() }; let p0 = Point {
x: -1500.0,
y: 1500.0,
..Point::default()
};
let edh = EDH::new(vec![ let edh = EDH::new(vec![
vec![ 1.24107321e-03, 1.00500127e-03, 7.15439347e-01], vec![1.24107321e-03, 1.00500127e-03, 7.15439347e-01],
vec![-9.93223912e-04, 1.22652939e-03,-6.98671238e-01], vec![-9.93223912e-04, 1.22652939e-03, -6.98671238e-01],
vec![ 1.06017142e-17,-4.69459541e-17, 3.32700590e-05] vec![1.06017142e-17, -4.69459541e-17, 3.32700590e-05],
]).unwrap(); ])
.unwrap();
let ws = WorldState { edh : edh, ..WorldState::default() }; let ws = WorldState {
edh: edh,
let homography = Homography{}; ..WorldState::default()
let result = homography.apply(&[p0], &ws); };
assert_eq!(result, vec![Point { x: 10860.557, let homography = Homography {};
y: 79078.87, let result = homography.apply(&[p0], &ws);
..Point::default() }]);
assert_eq!(
result,
vec![Point {
x: 10860.557,
y: 79078.87,
..Point::default()
}]
);
} }
} }

View File

@ -1,34 +1,33 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
/// Replicate /// Replicate
#[allow(dead_code)] #[allow(dead_code)]
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub enum Replicate { pub enum Replicate {
Until(usize), Until(usize),
Times(usize) Times(usize),
} }
impl Transformers for Replicate { impl Transformers for Replicate {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
let mut point_list2 = vec![]; let mut point_list2 = vec![];
match self { match self {
Replicate::Until(n) => { Replicate::Until(n) => {
while point_list2.len() < *n { while point_list2.len() < *n {
point_list2.append(&mut point_list.to_vec()); point_list2.append(&mut point_list.to_vec());
} }
}, }
Replicate::Times(n) => { Replicate::Times(n) => {
for _ in 0..*n { for _ in 0..*n {
point_list2.append(&mut point_list.to_vec()); point_list2.append(&mut point_list.to_vec());
} }
} }
} }
point_list2 point_list2
} }
} }

View File

@ -1,35 +1,32 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
//use std::f32::consts::PI; //use std::f32::consts::PI;
/// Rotate /// Rotate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Rotate { pub struct Rotate {
cx: f32, cx: f32,
cy: f32, cy: f32,
angle: f32, angle: f32,
} }
impl Transformers for Rotate { impl Transformers for Rotate {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter() point_list
.map(| pt | { .iter()
let dx = pt.x - self.cx; .map(|pt| {
let dy = pt.y - self.cy; let dx = pt.x - self.cx;
let cos = self.angle.cos(); let dy = pt.y - self.cy;
let sin = self.angle.sin(); let cos = self.angle.cos();
let x = (dx * cos - dy * sin) + self.cx; let sin = self.angle.sin();
let y = (dx * sin + dy * cos) + self.cy; let x = (dx * cos - dy * sin) + self.cx;
Point { x, let y = (dx * sin + dy * cos) + self.cy;
y, Point { x, y, ..*pt }
..*pt })
} .collect()
}).collect()
} }
} }

View File

@ -1,24 +1,25 @@
use crate::transformer::Transformers;
use crate::point::Point; use crate::point::Point;
use crate::transformer::Transformers;
use crate::worldstate::WorldState; use crate::worldstate::WorldState;
use serde::{Serialize,Deserialize}; use serde::{Deserialize, Serialize};
/// Translate /// Translate
#[derive(Serialize,Deserialize,Debug,Clone,Copy)] #[derive(Serialize, Deserialize, Debug, Clone, Copy)]
pub struct Translate { pub struct Translate {
pub x: f32, pub x: f32,
pub y: f32 pub y: f32,
} }
impl Transformers for Translate { impl Transformers for Translate {
fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> { fn apply(&self, point_list: &[Point], _ws: &WorldState) -> Vec<Point> {
point_list.iter() point_list
.map(| pt | { .iter()
Point { x: pt.x + self.x, .map(|pt| Point {
y: pt.y + self.y, x: pt.x + self.x,
..*pt y: pt.y + self.y,
} ..*pt
}).collect() })
.collect()
} }
} }

View File

@ -1,52 +1,54 @@
use crate::point::{Point, Color};
use nalgebra::base::{Matrix3, Matrix1x3};
use crate::errors::{LJError, LJResult}; use crate::errors::{LJError, LJResult};
use crate::point::{Color, Point};
use log::debug; use log::debug;
use nalgebra::base::{Matrix1x3, Matrix3};
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct EDH { pub struct EDH {
pub matrix: Matrix3<f32>, pub matrix: Matrix3<f32>,
} }
impl EDH { impl EDH {
pub fn new(vec: Vec<Vec<f32>>) -> LJResult<EDH> { pub fn new(vec: Vec<Vec<f32>>) -> LJResult<EDH> {
if vec.len() != 3 || if vec.len() != 3 || vec[0].len() != 3 || vec[1].len() != 3 || vec[2].len() != 3 {
vec[0].len() != 3 || return Err(Box::new(LJError::BadEDH));
vec[1].len() != 3 || }
vec[2].len() != 3 {
return Err(Box::new(LJError::BadEDH));
}
// this is the matrix already transposed. // this is the matrix already transposed.
let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0], let matrix = Matrix3::new(
vec[0][1], vec[1][1], vec[2][1], 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[0][2], vec[1][2], vec[2][2]); vec[2][2],
);
Ok(EDH { matrix }) Ok(EDH { matrix })
} }
pub fn apply(&self, point: &Point) -> Point { pub fn apply(&self, point: &Point) -> Point {
let p = Matrix1x3::new(point.x, point.y, 1.0); let p = Matrix1x3::new(point.x, point.y, 1.0);
let p = p * self.matrix; let p = p * self.matrix;
let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point }; let new_p = Point {
x: p[0] / p[2],
y: p[1] / p[2],
..*point
};
debug!("{:?} => {:?}", point, new_p); debug!("{:?} => {:?}", point, new_p);
new_p new_p
} }
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct WorldState { pub struct WorldState {
pub edh: EDH, pub edh: EDH,
pub resampler: Vec<f32>, pub resampler: Vec<f32>,
pub client_key: String, pub client_key: String,
pub intensity: u8, pub intensity: u8,
pub kpps: u32, pub kpps: u32,
pub color: Color, pub color: Color,
pub draw_black: bool, pub draw_black: bool,
pub draw_grid: bool, pub draw_grid: bool,
pub grid: Vec<Point>, pub grid: Vec<Point>,
} }
impl WorldState {} impl WorldState {}

View File

@ -1,4 +1,4 @@
use lj_rust::conf::{Conf, DacFamily, HeliosConf, EtherDreamConf}; use lj_rust::conf::{Conf, DacFamily, EtherDreamConf, HeliosConf};
#[test] #[test]
fn it_loads_a_valid_conf() { fn it_loads_a_valid_conf() {