Compare commits
14 Commits
Author | SHA1 | Date | |
---|---|---|---|
a45abd69ec | |||
|
2c0d5cd13f | ||
|
22d7d3c718 | ||
|
514f4cc7c9 | ||
|
6f04925ea5 | ||
|
3ce346306f | ||
|
ff96bdf6fa | ||
|
e148a1ec5e | ||
|
f45b9e5748 | ||
|
810a3677de | ||
|
71fabde385 | ||
|
4719dcc430 | ||
|
8e10e0d82e | ||
|
ae75092d34 |
@ -35,7 +35,3 @@ Until = 48
|
|||||||
[[transformers]]
|
[[transformers]]
|
||||||
[transformers.intensity]
|
[transformers.intensity]
|
||||||
|
|
||||||
|
|
||||||
[[transformers]]
|
|
||||||
[transformers.angle_correction]
|
|
||||||
coef = 2000.0
|
|
||||||
|
151
examples/etherdream.rs
Normal file
151
examples/etherdream.rs
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
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
|
||||||
|
);
|
||||||
|
});
|
||||||
|
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 \
|
||||||
|
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<Self::Item> {
|
||||||
|
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::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;
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,13 @@
|
|||||||
///
|
use std::io::_print;
|
||||||
/// $ cargo run --example populate_redis
|
/**
|
||||||
///
|
|
||||||
|
# Populate Redis Example
|
||||||
|
|
||||||
|
**This script simulates the redis content provided by the LJ Python / web tool**
|
||||||
|
|
||||||
|
$ cargo run --example populate_redis
|
||||||
|
**/
|
||||||
|
|
||||||
use redis::{
|
use redis::{
|
||||||
//RedisResult,
|
//RedisResult,
|
||||||
Client,
|
Client,
|
||||||
@ -11,16 +18,17 @@ use redis::{
|
|||||||
fn do_something() -> redis::RedisResult<()> {
|
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(
|
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]]")?;
|
||||||
"/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("/kpps/0", "5000")?;
|
||||||
let _ = con.set("/intensity/0", "255")?;
|
let _ = con.set("/intensity/0", "255")?;
|
||||||
|
let _ = con.set("/pl/0/0", "[(1000, 2000, 0), (1000, 1000, 65535), (2000, 1000, 65535), (2000, 2000, 65535), (1000, 2000, 65535)]")?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
_ = do_something();
|
match do_something() {
|
||||||
|
Err(err) => println!("Something wrong occured: {:?}", err),
|
||||||
|
Ok(..) => println!("Successfully inserted content in Redis")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
///
|
///
|
||||||
/// $ cargo run --example simple_client
|
/// $ cargo run --example simple_client
|
||||||
///
|
///
|
||||||
|
|
||||||
use redis::{
|
use redis::{
|
||||||
//RedisResult,
|
//RedisResult,
|
||||||
Client,
|
Client,
|
||||||
@ -19,16 +20,20 @@ fn do_something() -> redis::RedisResult<()> {
|
|||||||
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 {
|
for i in 0..128 {
|
||||||
let a = (time + i as f32) / 128.0 * std::f32::consts::PI * 2.0;
|
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 r = 1200.0 + (a*5.0).cos() * (500.0 * (time/5.0).cos());
|
||||||
|
|
||||||
let x = a.cos() * r;
|
let x = a.cos() * r;
|
||||||
let y = a.sin() * r;
|
let y = a.sin() * r;
|
||||||
let col = if i % 8 < 4 { 0x000000ff } else { 0x00ff0000 };
|
let col = if i % 8 < 4 {
|
||||||
v.push((x, y, col));
|
0x000000ff
|
||||||
|
} else {
|
||||||
|
0x00ff0000
|
||||||
|
};
|
||||||
|
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))?;
|
||||||
|
46
examples/test.rs
Normal file
46
examples/test.rs
Normal file
@ -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();
|
||||||
|
}
|
27
src/conf.rs
27
src/conf.rs
@ -1,7 +1,7 @@
|
|||||||
|
use config::Config;
|
||||||
|
use serde::{Serialize, Deserialize};
|
||||||
use crate::errors::{LJError, LJResult};
|
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 {
|
||||||
@ -49,39 +49,36 @@ pub enum TransformConf {
|
|||||||
Grid(transformer::Grid),
|
Grid(transformer::Grid),
|
||||||
#[serde(rename = "homography")]
|
#[serde(rename = "homography")]
|
||||||
Homography(transformer::Homography),
|
Homography(transformer::Homography),
|
||||||
#[serde(rename = "angle_correction")]
|
#[serde(rename = "helios_to_etherdream")]
|
||||||
AngleOptimisation(transformer::AngleOptimisation),
|
HeliosToEtherdream(transformer::HeliosToEtherdream),
|
||||||
|
#[serde(rename = "intensity")]
|
||||||
|
Intensity(transformer::Intensity),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
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()?;
|
||||||
|
|
||||||
dbg!("path:", path);
|
|
||||||
//println!("plop");
|
|
||||||
dbg!(settings.clone());
|
|
||||||
let conf: Conf = settings.try_deserialize().map_err(LJError::Config)?;
|
let conf: Conf = settings.try_deserialize().map_err(LJError::Config)?;
|
||||||
|
|
||||||
//println!("plum");
|
|
||||||
Ok(conf)
|
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::Replicate(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::HeliosToEtherdream(r) => Box::new(*r),
|
||||||
TransformConf::Homography(r) => Box::new(*r),
|
TransformConf::Homography(r) => Box::new(*r),
|
||||||
TransformConf::AngleOptimisation(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.push(t);
|
||||||
}
|
}
|
||||||
|
@ -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::dummy::DummyDevice;
|
|
||||||
use crate::device::etherdream::EtherdreamDevice;
|
|
||||||
use crate::device::helios::HeliosDevice;
|
use crate::device::helios::HeliosDevice;
|
||||||
|
use crate::device::dummy::DummyDevice;
|
||||||
use crate::errors::LJResult;
|
use crate::errors::LJResult;
|
||||||
use crate::point::Point;
|
use crate::point::Point;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::fmt;
|
use crate::device::etherdream::EtherdreamDevice;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
self.protocol_version,
|
self.protocol_version,
|
||||||
@ -28,8 +28,7 @@ self.point_count
|
|||||||
pub enum PlaybackState {
|
pub enum PlaybackState {
|
||||||
IDLE = 0,
|
IDLE = 0,
|
||||||
PREPARE = 1,
|
PREPARE = 1,
|
||||||
PLAYING = 2,
|
PLAYING = 2
|
||||||
UNKNOWN = 99,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Display for PlaybackState {
|
impl fmt::Display for PlaybackState {
|
||||||
@ -43,7 +42,7 @@ 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: usize,
|
||||||
pub lack: String,
|
pub lack: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -53,7 +52,11 @@ pub struct Status {
|
|||||||
|
|
||||||
pub trait Device {
|
pub trait Device {
|
||||||
fn status(&mut self) -> Status;
|
fn status(&mut self) -> Status;
|
||||||
fn draw(&mut self, frame: Vec<Point>, speed: u32) -> LJResult<()>;
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
frame: Vec<Point>,
|
||||||
|
speed: u32,
|
||||||
|
) -> LJResult<()>;
|
||||||
fn stop(&mut self) -> LJResult<()>;
|
fn stop(&mut self) -> LJResult<()>;
|
||||||
fn grid(&mut self) -> Vec<Point>;
|
fn grid(&mut self) -> Vec<Point>;
|
||||||
}
|
}
|
||||||
@ -61,8 +64,8 @@ pub trait Device {
|
|||||||
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)
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,15 @@
|
|||||||
use crate::device::{Device, PlaybackState, Status};
|
use crate::device::{Device, Status, PlaybackState};
|
||||||
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 {
|
Ok(Self { state: PlaybackState::IDLE })
|
||||||
state: PlaybackState::IDLE,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,11 +20,14 @@ impl Device for DummyDevice {
|
|||||||
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, line: Vec<Point>, speed: u32) -> LJResult<()> {
|
fn draw(&mut self,
|
||||||
|
line: Vec<Point>,
|
||||||
|
speed: u32,
|
||||||
|
) -> LJResult<()> {
|
||||||
debug!("Draw Line at speed {speed} : {:?}", line);
|
debug!("Draw Line at speed {speed} : {:?}", line);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@ -35,10 +36,8 @@ impl Device for DummyDevice {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn grid(&mut self) -> Vec<Point> {
|
fn grid(&mut self) -> Vec<Point> {
|
||||||
vec![Point {
|
vec!(
|
||||||
x: 0 as f32,
|
Point{ x: 0 as f32, y: 0 as f32, color:Color{ r: 0, g: 0, b: 0 }}
|
||||||
y: 0 as f32,
|
)
|
||||||
color: Color { r: 0, g: 0, b: 0 },
|
|
||||||
}]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,155 +1,308 @@
|
|||||||
use ether_dream::dac::stream::connect;
|
#[warn(unused_imports)]
|
||||||
use ether_dream::dac::Stream;
|
use log::{ debug, info, warn};
|
||||||
|
|
||||||
use std::net::SocketAddr;
|
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;
|
use std::time;
|
||||||
|
use std::time::{Duration, SystemTime};
|
||||||
|
|
||||||
use crate::conf::EtherDreamConf;
|
use crate::conf::EtherDreamConf;
|
||||||
use crate::device::{Device, PlaybackState, Status};
|
use crate::device::{Device, Status, PlaybackState};
|
||||||
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, DacResponse};
|
||||||
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,
|
|
||||||
stream: Stream,
|
stream: Stream,
|
||||||
// sent_points: u16,
|
|
||||||
lack: String,
|
// "a": ACK "F": Full "I": invalid. 64 or 35 for no connection.
|
||||||
last_traced_at: String,
|
// /// 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 {
|
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::connect(conf)?;
|
||||||
// let (dac, source_address) = EtherdreamDevice::get_dac(conf)?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
conf: (*conf).clone(),
|
conf: (*conf).clone(),
|
||||||
dac,
|
dac,
|
||||||
// source_address,
|
|
||||||
stream,
|
stream,
|
||||||
// sent_points: 0,
|
dac_response: DacResponse::ACK,
|
||||||
lack: "".to_string(),
|
|
||||||
last_traced_at: "1985-04-12T23:20:50.52Z".to_string(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
pub fn get_dac(conf: &EtherDreamConf) -> LJResult<(DacBroadcast, SocketAddr, Stream)> {
|
fn connect(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| match result {
|
.take(3)
|
||||||
|
.filter_map(|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)) => {
|
||||||
|
info!("Valid broadcast, source_addr: {}", source_addr);
|
||||||
if source_addr.is_ipv6() {
|
if source_addr.is_ipv6() {
|
||||||
|
warn!("Broadcast ignored: ipv6 address.");
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
if &source_addr.ip().to_string() != ip {
|
let src_ip = source_addr.ip().to_string();
|
||||||
|
if &src_ip != ip {
|
||||||
|
warn!("Broadcast ignored: expected {ip}, got: {src_ip} ");
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
info!("Valid broadcast");
|
|
||||||
Some(Ok((dac, source_addr)))
|
Some(Ok((dac, source_addr)))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.next()
|
.next()
|
||||||
.expect("Failed to receive broadcast.");
|
.expect("Failed to receive broadcast.");
|
||||||
match broadcast {
|
match broadcast {
|
||||||
Err(err) => Err(Box::new(LJError::EtherdreamConnectError(err))),
|
Err(err) => {
|
||||||
|
Err(Box::new(LJError::EtherdreamConnectError(err)))
|
||||||
|
}
|
||||||
Ok((dac, source_addr)) => {
|
Ok((dac, source_addr)) => {
|
||||||
|
info!("Trying to open TCP stream...");
|
||||||
let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?;
|
let stream = EtherdreamDevice::get_tcp_stream(&dac, &source_addr)?;
|
||||||
|
info!("Finished configuring DAC and TCP stream.");
|
||||||
Ok((dac, source_addr, stream))
|
Ok((dac, source_addr, stream))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult<Stream> {
|
fn get_tcp_stream(dac: &DacBroadcast, source_address: &SocketAddr) -> LJResult<Stream> {
|
||||||
// Establish the TCP connection.
|
|
||||||
let mut stream = connect(dac, source_address.ip())?;
|
let mut stream = connect(dac, source_address.ip())?;
|
||||||
|
match stream
|
||||||
// Prepare stream
|
|
||||||
stream
|
|
||||||
.queue_commands()
|
.queue_commands()
|
||||||
.prepare_stream()
|
.prepare_stream()
|
||||||
.submit()
|
.submit() {
|
||||||
.err()
|
Err(err) => warn!("err occurred when submitting PREPARE_STREAM command and listening for response: {}",err),
|
||||||
.map(|err| {
|
Ok(_) => info!("Prepared Stream.")
|
||||||
eprintln!(
|
}
|
||||||
"err occurred when submitting PREPARE_STREAM \
|
// If we want to create an animation (in our case a moving sine wave) we need a frame rate.
|
||||||
command and listening for response: {}",
|
let frames_per_second = 60.0;
|
||||||
err
|
// 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(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)
|
Ok(stream)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn check_tcp_stream(&mut self) -> LJResult<()> {
|
fn points_capacity(&self) -> usize {
|
||||||
// todo Reinit stream if needed
|
/***
|
||||||
// self.stream = EtherdreamDevice::get_tcp_stream(&self.dac, &self.source_address)?
|
Determine the number of points needed to fill the DAC.
|
||||||
Ok(())
|
***/
|
||||||
|
// Fixme thread 'main' panicked at 'attempt to subtract with overflow', src/device/etherdream.rs:144:24
|
||||||
|
let n_points = self.dac.buffer_capacity as usize - self.stream.dac().dac.status.buffer_fullness as usize - 1;
|
||||||
|
n_points
|
||||||
}
|
}
|
||||||
|
|
||||||
// Determine the number of points needed to fill the DAC.
|
fn ping(&mut self) -> LJResult<()> {
|
||||||
fn points_to_generate(&self) -> usize {
|
|
||||||
self.dac.buffer_capacity as usize - 1 - self.dac.dac_status.buffer_fullness as usize
|
Ok(self.stream.queue_commands().ping().submit()?)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Device for EtherdreamDevice {
|
impl Device for EtherdreamDevice {
|
||||||
fn status(&mut self) -> Status {
|
fn status(&mut self) -> Status {
|
||||||
let _ = self.check_tcp_stream();
|
let playback_state = match self.stream.dac().dac.status.playback {
|
||||||
|
Playback::Idle => PlaybackState::IDLE,
|
||||||
// "a": ACK "F": Full "I": invalid. 64 or 35 for no connection.
|
Playback::Prepared => PlaybackState::PREPARE,
|
||||||
let playback_state = match self.dac.dac_status.playback_state {
|
Playback::Playing => PlaybackState::PLAYING,
|
||||||
DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE,
|
|
||||||
DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE,
|
|
||||||
DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING,
|
|
||||||
_ => PlaybackState::UNKNOWN,
|
|
||||||
};
|
};
|
||||||
|
let now = SystemTime::now();
|
||||||
|
let now: DateTime<Utc> = now.into();
|
||||||
|
let now = now.to_rfc3339();
|
||||||
|
|
||||||
Status {
|
Status {
|
||||||
last_traced_at: self.last_traced_at.clone(),
|
last_traced_at: now,
|
||||||
properties: vec!["foo".to_string()],
|
properties: vec!["foo".to_string()],
|
||||||
playback_state,
|
playback_state,
|
||||||
capacity: self.dac.dac_status.buffer_fullness,
|
capacity: self.points_capacity(),
|
||||||
lack: String::from(&self.lack),
|
lack: self.dac_response.to_string(),
|
||||||
}
|
}
|
||||||
|
// debug!("Dac Status: {:?} ", status );
|
||||||
|
// debug!("Etherdream Dac {:?} ", self.dac );
|
||||||
|
// debug!("Stream dac{:?}", self.stream.dac());
|
||||||
|
// status
|
||||||
}
|
}
|
||||||
|
|
||||||
fn draw(&mut self, line: Vec<Point>, _speed: u32) -> LJResult<()> {
|
fn draw(&mut self,
|
||||||
let n_points = self.points_to_generate();
|
line: Vec<Point>,
|
||||||
self.stream
|
_speed: u32,
|
||||||
|
) -> LJResult<()> {
|
||||||
|
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 {
|
||||||
|
debug!("Sleep, capacity : {:?}", capacity);
|
||||||
|
// Sleep for 1/100th of a sec
|
||||||
|
sleep(Duration::new( 0, 10000000));
|
||||||
|
self.ping()?;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
debug!("drawing");
|
||||||
|
match self.stream
|
||||||
.queue_commands()
|
.queue_commands()
|
||||||
.data(line.into_iter().map(|point| point.into()).take(n_points))
|
.data(
|
||||||
.submit()?;
|
chunk.iter()
|
||||||
|
.map(|point| (*point).into())
|
||||||
|
.take(chunk_size)
|
||||||
|
)
|
||||||
|
.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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stop(&mut self) -> LJResult<()> {
|
fn stop(&mut self) -> LJResult<()> {
|
||||||
self.stream
|
info!("Stopping Etherdream device...");
|
||||||
|
match self.stream
|
||||||
.queue_commands()
|
.queue_commands()
|
||||||
.stop()
|
.stop()
|
||||||
.submit()
|
.submit()
|
||||||
.expect("err occurred when submitting STOP command and listening for response");
|
{
|
||||||
|
Err(err) => {
|
||||||
|
warn!("Failed to stop EtherDream device with error {:?}", err);
|
||||||
|
Err(Box::new(err))
|
||||||
|
}
|
||||||
|
Ok(_) => {
|
||||||
|
info!("Sucessfully closed EtherDream device.");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn grid(&mut self) -> Vec<Point> {
|
fn grid(&mut self) -> Vec<Point> {
|
||||||
vec![Point {
|
let dim_mid = 16000.0;
|
||||||
x: 0.0,
|
let dim_max = 32000.0;
|
||||||
y: 0.0,
|
let col_min = Color { r: 0, g: 0, b: 0 };
|
||||||
color: Color {
|
let col_max = Color { r: 255, g: 255, b: 255 };
|
||||||
r: 255,
|
|
||||||
g: 255,
|
vec![
|
||||||
b: 255,
|
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 },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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<Self::Item> {
|
||||||
|
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),
|
||||||
|
_ => (u16::MAX, u16::MAX, u16::MAX),
|
||||||
|
};
|
||||||
|
let x_min = i16::MIN;
|
||||||
|
let x_max = i16::MAX;
|
||||||
|
let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16;
|
||||||
|
let y = (amp * x_max as f32) as i16;
|
||||||
|
let control = 0;
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
use crate::conf::HeliosConf;
|
use std::time::SystemTime;
|
||||||
use crate::device::{Device, PlaybackState, Status};
|
///
|
||||||
use crate::errors::{LJError, LJResult};
|
/// Configure udev:
|
||||||
use crate::point::{Color, Point};
|
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
|
||||||
use chrono::Utc;
|
///
|
||||||
|
use helios_dac::{NativeHeliosDac, NativeHeliosDacController};
|
||||||
use helios_dac::{
|
use helios_dac::{
|
||||||
// Coordinate,
|
// Coordinate,
|
||||||
// Color,
|
// Color,
|
||||||
@ -10,11 +11,11 @@ use helios_dac::{
|
|||||||
Frame,
|
Frame,
|
||||||
// Point as HeliosPoint,
|
// Point as HeliosPoint,
|
||||||
};
|
};
|
||||||
///
|
use crate::conf::HeliosConf;
|
||||||
/// Configure udev:
|
use crate::device::{Device, Status, PlaybackState};
|
||||||
/// https://github.com/Grix/helios_dac/blob/master/docs/udev_rules_for_linux.md
|
use crate::errors::{LJError, LJResult};
|
||||||
///
|
use crate::point::{Color, Point};
|
||||||
use helios_dac::{NativeHeliosDac, NativeHeliosDacController};
|
use chrono::{DateTime, Utc};
|
||||||
|
|
||||||
pub struct HeliosDevice {
|
pub struct HeliosDevice {
|
||||||
pub conf: HeliosConf,
|
pub conf: HeliosConf,
|
||||||
@ -34,13 +35,17 @@ impl HeliosDevice {
|
|||||||
return Err(Box::new(LJError::HeliosDeviceMissing));
|
return Err(Box::new(LJError::HeliosDeviceMissing));
|
||||||
};
|
};
|
||||||
let dac = device.open()?;
|
let dac = device.open()?;
|
||||||
|
let now = SystemTime::now();
|
||||||
|
let now: DateTime<Utc> = now.into();
|
||||||
|
let last_traced_at = now.to_rfc3339();
|
||||||
|
|
||||||
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,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -52,12 +57,15 @@ impl Device for HeliosDevice {
|
|||||||
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 as usize,
|
||||||
lack,
|
lack,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn draw(&mut self, line: Vec<Point>, speed: u32) -> LJResult<()> {
|
fn draw(&mut self,
|
||||||
|
line: Vec<Point>,
|
||||||
|
speed: u32,
|
||||||
|
) -> LJResult<()> {
|
||||||
self.state = PlaybackState::IDLE;
|
self.state = PlaybackState::IDLE;
|
||||||
while let Ok(DeviceStatus::NotReady) = self.dac.status() {}
|
while let Ok(DeviceStatus::NotReady) = self.dac.status() {}
|
||||||
self.state = PlaybackState::PLAYING;
|
self.state = PlaybackState::PLAYING;
|
||||||
@ -77,76 +85,24 @@ impl Device for HeliosDevice {
|
|||||||
|
|
||||||
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.0;
|
||||||
let dim_max = 4095 as f32;
|
let dim_max = 4095.0;
|
||||||
let col_min = Color { r: 0, g: 0, b: 0 };
|
let col_min = Color { r: 0, g: 0, b: 0 };
|
||||||
let col_max = Color {
|
let col_max = Color { r: 255, g: 255, b: 255 };
|
||||||
r: 255,
|
|
||||||
g: 255,
|
|
||||||
b: 255,
|
|
||||||
};
|
|
||||||
|
|
||||||
vec![
|
vec![
|
||||||
Point {
|
Point { x: dim_min, y: dim_max, color: col_min },
|
||||||
x: dim_min,
|
Point { x: dim_min, y: dim_max, color: col_max },
|
||||||
y: dim_max,
|
Point { x: dim_max, y: dim_max, color: col_max },
|
||||||
color: col_min,
|
Point { x: dim_max, 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_min,
|
Point { x: dim_min, y: dim_mid, color: col_min },
|
||||||
y: dim_max,
|
Point { x: dim_min, y: dim_mid, color: col_max },
|
||||||
color: col_max,
|
Point { x: dim_mid, y: dim_mid, color: col_max },
|
||||||
},
|
Point { x: dim_mid, y: dim_min, color: col_max },
|
||||||
Point {
|
Point { x: dim_min, y: dim_min, color: col_max },
|
||||||
x: dim_max,
|
Point { x: dim_min, y: dim_min, color: col_min },
|
||||||
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,
|
|
||||||
},
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
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>>;
|
||||||
|
|
||||||
@ -44,7 +44,7 @@ impl Error for LJError {
|
|||||||
|
|
||||||
match self {
|
match self {
|
||||||
RedisConnect(err) => Some(err),
|
RedisConnect(err) => Some(err),
|
||||||
_ => None,
|
_ => None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
39
src/framerate.rs
Normal file
39
src/framerate.rs
Normal file
@ -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<Self> {
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,8 @@
|
|||||||
pub mod conf;
|
|
||||||
pub mod device;
|
|
||||||
pub mod errors;
|
|
||||||
pub mod point;
|
|
||||||
pub mod redis_ctrl;
|
pub mod redis_ctrl;
|
||||||
|
pub mod conf;
|
||||||
|
pub mod errors;
|
||||||
|
pub mod device;
|
||||||
|
pub mod point;
|
||||||
pub mod transformer;
|
pub mod transformer;
|
||||||
pub mod worldstate;
|
pub mod worldstate;
|
||||||
|
pub mod framerate;
|
||||||
|
107
src/main.rs
107
src/main.rs
@ -1,26 +1,28 @@
|
|||||||
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;
|
||||||
|
mod framerate;
|
||||||
|
|
||||||
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;
|
||||||
|
use framerate::Framerate;
|
||||||
|
|
||||||
const DEFAULT_CONF_FILE: &str = "settings.toml";
|
const DEFAULT_CONF_FILE: &str = "settings.toml";
|
||||||
|
|
||||||
@ -33,11 +35,19 @@ pub fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fn run_all() -> LJResult<()> {
|
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
|
// Setup configuration file and set up logs
|
||||||
let filename = std::env::args()
|
let filename = std::env::args().nth(1).unwrap_or_else(|| {
|
||||||
.nth(1)
|
DEFAULT_CONF_FILE.to_string()
|
||||||
.unwrap_or_else(|| DEFAULT_CONF_FILE.to_string());
|
});
|
||||||
|
|
||||||
let config = Conf::new(&filename);
|
let config = Conf::new(&filename);
|
||||||
init_logging(&config);
|
init_logging(&config);
|
||||||
@ -51,31 +61,23 @@ fn run_all() -> LJResult<()> {
|
|||||||
|
|
||||||
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
|
|
||||||
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
|
// 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...
|
|
||||||
//dbg!(tracer);
|
|
||||||
|
|
||||||
// Setup geometry transformers on points lists
|
// Setup geometry transformers on points lists
|
||||||
let transformers = config.get_transformers();
|
let transformers = config.get_transformers();
|
||||||
|
|
||||||
|
// Setup framerate limiter
|
||||||
|
let mut framerate_handler = Framerate::new()?;
|
||||||
|
|
||||||
// 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())?;
|
||||||
|
framerate_handler.handle_time()?;
|
||||||
let order = rs.get_order(config.laser_id)?;
|
let order = rs.get_order(config.laser_id)?;
|
||||||
|
|
||||||
match order {
|
match order {
|
||||||
Order::Draw | Order::Black | Order::Grid => {
|
Order::Draw | Order::Black | Order::Grid => {
|
||||||
// 0 : Draw Normal point list
|
// 0 : Draw Normal point list
|
||||||
@ -83,13 +85,19 @@ fn run_all() -> LJResult<()> {
|
|||||||
// 3 : Draw GRID point list
|
// 3 : Draw GRID point list
|
||||||
world_state.draw_black = order == Order::Black;
|
world_state.draw_black = order == Order::Black;
|
||||||
world_state.draw_grid = order == Order::Grid;
|
world_state.draw_grid = order == Order::Grid;
|
||||||
let frame = get_next_frame(&config, &transformers, &mut rs, &world_state)?;
|
let frame = get_next_frame(
|
||||||
|
&config,
|
||||||
|
&transformers,
|
||||||
|
&mut rs,
|
||||||
|
&world_state,
|
||||||
|
)?;
|
||||||
// For now, draw all the time
|
// For now, draw all the time
|
||||||
tracer.draw(frame, world_state.kpps)?;
|
tracer.draw(frame, world_state.kpps)?;
|
||||||
}
|
}
|
||||||
Order::Intensity => {
|
Order::Intensity => {
|
||||||
// 6 : Max Intensity Change = reread redis key /intensity
|
// 6 : Max Intensity Change = reread redis key /intensity
|
||||||
world_state.intensity = rs.get_int("intensity")?.try_into()?;
|
world_state.intensity = rs.get_int("intensity")?
|
||||||
|
.try_into()?;
|
||||||
}
|
}
|
||||||
Order::Edh => {
|
Order::Edh => {
|
||||||
// 1 : Get the new EDH = reread redis key /EDH/lasernumber
|
// 1 : Get the new EDH = reread redis key /EDH/lasernumber
|
||||||
@ -98,16 +106,18 @@ fn run_all() -> LJResult<()> {
|
|||||||
Order::Kpps => {
|
Order::Kpps => {
|
||||||
// 7 : kpps change = reread redis key /kpps
|
// 7 : kpps change = reread redis key /kpps
|
||||||
world_state.kpps = rs.get_int("kpps")?;
|
world_state.kpps = rs.get_int("kpps")?;
|
||||||
//dbg!(world_state.kpps);
|
|
||||||
}
|
}
|
||||||
Order::ClientKey => {
|
Order::ClientKey => {
|
||||||
world_state.client_key = rs.get_client_key()?;
|
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
|
// 9 : poweroff LJ
|
||||||
info!("Order: {:?}", order);
|
info!("Order: {:?}", order);
|
||||||
}
|
}
|
||||||
@ -121,13 +131,18 @@ fn run_all() -> LJResult<()> {
|
|||||||
|
|
||||||
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 {
|
let level = if config.debug {
|
||||||
|
LevelFilter::Debug
|
||||||
|
} else {
|
||||||
|
LevelFilter::Info
|
||||||
|
};
|
||||||
let mut builder = Builder::from_default_env();
|
let mut builder = Builder::from_default_env();
|
||||||
builder.filter(None, LevelFilter::Info).init();
|
builder
|
||||||
|
.filter(None, level)
|
||||||
|
.init();
|
||||||
info!("Debug mode enabled from configuration file");
|
info!("Debug mode enabled from configuration file");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
info!("Logging level inherited from env");
|
info!("Logging level inherited from env");
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
}
|
}
|
||||||
@ -138,7 +153,9 @@ fn get_next_frame(
|
|||||||
rs: &mut RedisCtrl,
|
rs: &mut RedisCtrl,
|
||||||
world_state: &WorldState,
|
world_state: &WorldState,
|
||||||
) -> LJResult<Vec<Point>> {
|
) -> LJResult<Vec<Point>> {
|
||||||
let format_key = format!("{}{}", world_state.client_key, config.laser_id);
|
let format_key = format!("{}{}",
|
||||||
|
world_state.client_key,
|
||||||
|
config.laser_id);
|
||||||
|
|
||||||
// Handle the grid case
|
// Handle the grid case
|
||||||
|
|
||||||
@ -146,20 +163,20 @@ fn get_next_frame(
|
|||||||
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().map(|tpl| tpl.into()).collect()
|
redis_line.into_iter()
|
||||||
|
.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
|
line = line.into_iter()
|
||||||
.into_iter()
|
|
||||||
.map(|p| {
|
.map(|p| {
|
||||||
let color = if world_state.draw_black {
|
let color = if world_state.draw_black {
|
||||||
Color { r: 0, g: 0, b: 0 }
|
Color { r: 0, g: 0, b: 0 }
|
||||||
@ -170,10 +187,14 @@ fn get_next_frame(
|
|||||||
b: p.color.b.min(world_state.intensity),
|
b: p.color.b.min(world_state.intensity),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Point { color, ..p }
|
Point {
|
||||||
|
color,
|
||||||
|
..p
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
//info!("Line: {:?}", line);
|
//info!("Line: {:?}", line);
|
||||||
Ok(line)
|
Ok(line)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
55
src/point.rs
55
src/point.rs
@ -1,4 +1,6 @@
|
|||||||
use ether_dream::protocol::DacPoint;
|
use ether_dream::protocol::DacPoint;
|
||||||
|
use std::ops::Mul;
|
||||||
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||||
pub struct Point {
|
pub struct Point {
|
||||||
@ -13,31 +15,18 @@ pub struct Color {
|
|||||||
pub g: u8,
|
pub g: u8,
|
||||||
pub b: u8,
|
pub b: u8,
|
||||||
}
|
}
|
||||||
|
impl Mul<u8> for Color {
|
||||||
|
type Output = Self;
|
||||||
|
|
||||||
impl Point {
|
fn mul(self, rhs: u8) -> Self {
|
||||||
pub fn diff(p1: &Self, p2: &Self) -> Self {
|
Self{
|
||||||
Point {
|
r: (255 * self.r as u16 / rhs as u16) as u8,
|
||||||
x: p1.x - p2.x,
|
g: (255 * self.g as u16 / rhs as u16) as u8,
|
||||||
y: p1.y - p2.y,
|
b: (255 * self.b as u16 / rhs as u16) as u8,
|
||||||
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;
|
||||||
@ -52,11 +41,7 @@ impl From<(f32, f32, u32)> for 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 {
|
Point { x, y, color: Color { r, g, b } }
|
||||||
x,
|
|
||||||
y,
|
|
||||||
color: Color { r, g, b },
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -76,17 +61,21 @@ 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 = 0;
|
||||||
DacPoint {
|
let x = pt.x.clamp(-32000.0, 32000.0);
|
||||||
|
let y = pt.y.clamp(-32000.0, 32000.0);
|
||||||
|
let pt = DacPoint {
|
||||||
control,
|
control,
|
||||||
x: pt.x as i16,
|
x: x as i16,
|
||||||
y: pt.y as i16,
|
y: y as i16,
|
||||||
i,
|
i,
|
||||||
r: pt.color.r.into(),
|
r: (pt.color.r as u16) * 255,
|
||||||
g: pt.color.g.into(),
|
g: (pt.color.g as u16) * 255,
|
||||||
b: pt.color.b.into(),
|
b: (pt.color.b as u16) * 255,
|
||||||
u1,
|
u1,
|
||||||
u2,
|
u2,
|
||||||
}
|
};
|
||||||
|
// debug!("point {:?}", pt);
|
||||||
|
pt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
|
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)]
|
||||||
@ -10,7 +10,6 @@ use ron::de::from_str;
|
|||||||
pub enum Order {
|
pub enum Order {
|
||||||
Draw = 0,
|
Draw = 0,
|
||||||
Edh,
|
Edh,
|
||||||
//homography
|
|
||||||
Black,
|
Black,
|
||||||
Grid,
|
Grid,
|
||||||
Resampler,
|
Resampler,
|
||||||
@ -18,6 +17,7 @@ pub enum Order {
|
|||||||
Intensity,
|
Intensity,
|
||||||
Kpps,
|
Kpps,
|
||||||
ColorBalance,
|
ColorBalance,
|
||||||
|
PowerOff
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TryFrom<u8> for Order {
|
impl TryFrom<u8> for Order {
|
||||||
@ -40,12 +40,14 @@ impl TryFrom<u8> for Order {
|
|||||||
6 => Intensity,
|
6 => Intensity,
|
||||||
7 => Kpps,
|
7 => Kpps,
|
||||||
8 => ColorBalance,
|
8 => ColorBalance,
|
||||||
_ => unreachable!(),
|
9 => PowerOff,
|
||||||
|
_ => unreachable!()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Line = Vec<(f32, f32, u32)>;
|
pub type Line = Vec<(f32, f32, u32)>;
|
||||||
|
pub type Resampler = Vec<Vec<(f32,f32)>>;
|
||||||
|
|
||||||
pub struct RedisCtrl {
|
pub struct RedisCtrl {
|
||||||
pub client: Client,
|
pub client: Client,
|
||||||
@ -55,13 +57,11 @@ pub struct RedisCtrl {
|
|||||||
|
|
||||||
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).map_err(LJError::RedisConnect)?;
|
let client = Client::open(url)
|
||||||
let connection = client.get_connection().map_err(LJError::RedisConnect)?;
|
.map_err(LJError::RedisConnect)?;
|
||||||
Ok(RedisCtrl {
|
let connection = client.get_connection()
|
||||||
client,
|
.map_err(LJError::RedisConnect)?;
|
||||||
connection,
|
Ok(RedisCtrl { client, connection, laser_id: *laser_id })
|
||||||
laser_id: *laser_id,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_line(&mut self, key: &str) -> LJResult<Line> {
|
pub fn get_line(&mut self, key: &str) -> LJResult<Line> {
|
||||||
@ -86,11 +86,6 @@ impl RedisCtrl {
|
|||||||
Ok(val.try_into()?)
|
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<()> {
|
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);
|
||||||
@ -103,10 +98,10 @@ impl RedisCtrl {
|
|||||||
|
|
||||||
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()?,
|
||||||
edh: self.get_edh().unwrap(),
|
edh: self.get_edh()?,
|
||||||
kpps: self.get_int("kpps").unwrap().try_into().unwrap(),
|
kpps: self.get_int("kpps")?.try_into()?,
|
||||||
intensity: self.get_int("intensity").unwrap().try_into().unwrap(),
|
intensity: self.get_int("intensity")?.try_into()?,
|
||||||
..WorldState::default()
|
..WorldState::default()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -125,6 +120,20 @@ impl RedisCtrl {
|
|||||||
Ok(key)
|
Ok(key)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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<Resampler> {
|
||||||
|
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<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);
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
//pub mod common;
|
|
||||||
mod angle_optimisation;
|
|
||||||
mod flip_horizontal;
|
mod flip_horizontal;
|
||||||
mod flip_vertical;
|
mod flip_vertical;
|
||||||
mod grid;
|
mod grid;
|
||||||
|
mod helios_to_etherdream;
|
||||||
mod homography;
|
mod homography;
|
||||||
|
mod intensity;
|
||||||
mod replicate;
|
mod replicate;
|
||||||
mod rotate;
|
mod rotate;
|
||||||
mod translate;
|
mod translate;
|
||||||
@ -12,15 +12,20 @@ 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 self::homography::Homography;
|
pub use translate::Translate;
|
||||||
pub use angle_optimisation::AngleOptimisation;
|
pub use replicate::Replicate;
|
||||||
|
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 replicate::Replicate;
|
pub use self::homography::Homography;
|
||||||
pub use rotate::Rotate;
|
pub use helios_to_etherdream::HeliosToEtherdream;
|
||||||
pub use translate::Translate;
|
pub use intensity::Intensity;
|
||||||
|
|
||||||
pub trait Transformers {
|
pub trait Transformers {
|
||||||
fn apply(&self, point_list: &[Point], world_state: &WorldState) -> Vec<Point>;
|
fn apply(
|
||||||
|
&self,
|
||||||
|
point_list: &[Point],
|
||||||
|
world_state: &WorldState
|
||||||
|
) -> Vec<Point>;
|
||||||
}
|
}
|
||||||
|
@ -1,129 +0,0 @@
|
|||||||
use crate::point::{Color, Point};
|
|
||||||
use crate::transformer::Transformers;
|
|
||||||
use crate::worldstate::WorldState;
|
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::f64::consts::PI;
|
|
||||||
//use std::cmp::min;
|
|
||||||
|
|
||||||
/// Angle Optimisation
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
|
|
||||||
pub struct AngleOptimisation {
|
|
||||||
coef: f64,
|
|
||||||
//pps: u16,
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Le temps a attendre a un angle est toujours le meme, peu importe les kpps.
|
|
||||||
* Donc le nombre de point a rajouter est proportionelle a la vitesse du laser.
|
|
||||||
*
|
|
||||||
* kpps /
|
|
||||||
* */
|
|
||||||
|
|
||||||
fn color_same(p1: &Point, p2: &Point) -> bool {
|
|
||||||
if p1.color.r == p2.color.r && p1.color.g == p2.color.g && p1.color.b == p2.color.b {
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// quand on rajoute un point, on le rejoute ou et avec quelle couleur
|
|
||||||
// -> j'ai l'impression qu'on le rajoute surtout a l'arriver
|
|
||||||
|
|
||||||
fn get_prev(pl: &[Point], id: usize) -> (Option<&Point>, usize) {
|
|
||||||
for i in (0..id).rev() {
|
|
||||||
if pos_different(&pl[id], &pl[i]) {
|
|
||||||
return (Some(&pl[i]), id - i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(None, id - 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_next(pl: &[Point], id: usize) -> (Option<&Point>, usize) {
|
|
||||||
for i in id..(pl.len() - 1) {
|
|
||||||
if pos_different(&pl[id], &pl[i]) {
|
|
||||||
return (Some(&pl[i]), i - id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(None, pl.len() - id - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn max(v1: f64, v2: f64) -> f64 {
|
|
||||||
if v1 > v2 {
|
|
||||||
v1
|
|
||||||
} else {
|
|
||||||
v2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Transformers for AngleOptimisation {
|
|
||||||
fn apply(&self, pl: &[Point], _ws: &WorldState) -> Vec<Point> {
|
|
||||||
let c0 = Color { r: 0, g: 0, b: 0 };
|
|
||||||
let mut v = vec![];
|
|
||||||
|
|
||||||
let to_add_max = _ws.kpps as f64 / self.coef; // for 180 deg
|
|
||||||
let to_add_min = max(to_add_max / 1.5, 2.); // for 180 deg
|
|
||||||
|
|
||||||
let mut first_blanc = pl[0].clone();
|
|
||||||
first_blanc.color = Color{r:0, g:0, b:0};
|
|
||||||
for _ in 0..(to_add_max as u32) {
|
|
||||||
v.push(first_blanc); // push first
|
|
||||||
}
|
|
||||||
v.push(pl[0]);
|
|
||||||
for i in 1..(pl.len() - 1) {
|
|
||||||
let node = &pl[i];
|
|
||||||
if let ((Some(prev), dist_prev), (Some(next), dist_next)) =
|
|
||||||
(get_prev(pl, i), get_next(pl, i))
|
|
||||||
{
|
|
||||||
let d1 = Point::diff(node, prev).normalize();
|
|
||||||
let d2 = Point::diff(next, node).normalize();
|
|
||||||
let angle = (d1.cross(&d2) as f64).acos();
|
|
||||||
let to_add = ((to_add_max - to_add_min) * (angle / PI) + to_add_min) as usize;
|
|
||||||
println!("\nangle: {}", (angle / PI * 180.));
|
|
||||||
dbg!(to_add);
|
|
||||||
dbg!(to_add_max);
|
|
||||||
for _ in 0..to_add {
|
|
||||||
v.push(*node);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
v.push(*node);
|
|
||||||
};
|
|
||||||
//v.push(*node); // push node
|
|
||||||
}
|
|
||||||
for _ in 0..(to_add_max as u32) {
|
|
||||||
v.push(pl[pl.len() - 2]); // push last
|
|
||||||
}
|
|
||||||
for _ in 0..(to_add_max as u32) {
|
|
||||||
v.push(pl[pl.len() - 1]); // push last
|
|
||||||
}
|
|
||||||
println!("\tbefore: {}\tafter: {}", pl.len(), v.len());
|
|
||||||
|
|
||||||
v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* |\
|
|
||||||
* | \
|
|
||||||
* | \
|
|
||||||
* | |
|
|
||||||
* */
|
|
@ -1,27 +1,24 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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
|
point_list.iter()
|
||||||
.iter()
|
.map(| pt | {
|
||||||
.map(|pt| {
|
|
||||||
let dx = pt.x - self.x;
|
let dx = pt.x - self.x;
|
||||||
Point {
|
Point { x: dx - 2. * dx,
|
||||||
x: dx - 2. * dx,
|
|
||||||
..*pt
|
..*pt
|
||||||
}
|
}
|
||||||
})
|
}).collect()
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,27 +1,24 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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
|
point_list.iter()
|
||||||
.iter()
|
.map(| pt | {
|
||||||
.map(|pt| {
|
|
||||||
let dy = pt.y - self.y;
|
let dy = pt.y - self.y;
|
||||||
Point {
|
Point { y: dy - 2. * dy,
|
||||||
y: dy - 2. * dy,
|
|
||||||
..*pt
|
..*pt
|
||||||
}
|
}
|
||||||
})
|
}).collect()
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,38 +1,47 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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, -size, color),
|
||||||
|
|
||||||
(size, 0.0, color),
|
(size, 0.0, color),
|
||||||
(size, 0.0, color),
|
(size, 0.0, color),
|
||||||
|
|
||||||
(size, size, color),
|
(size, size, color),
|
||||||
(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, size, color),
|
||||||
|
|
||||||
(-size, 0.0, color),
|
(-size, 0.0, color),
|
||||||
(-size, 0.0, color),
|
(-size, 0.0, color),
|
||||||
|
|
||||||
(-size, -size, color),
|
(-size, -size, color),
|
||||||
(-size, -size, color),
|
(-size, -size, color),
|
||||||
(-size, -size, 0),
|
|
||||||
|
(-size, -size, 0)
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,7 +51,8 @@ impl Transformers for Grid {
|
|||||||
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().map(|tpl| tpl.into()).collect();
|
let line: Vec<Point> = line.into_iter()
|
||||||
|
.map(|tpl| tpl.into()).collect();
|
||||||
line
|
line
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
27
src/transformer/helios_to_etherdream.rs
Normal file
27
src/transformer/helios_to_etherdream.rs
Normal file
@ -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<Point> {
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,18 +1,20 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
use crate::worldstate::{WorldState, EDH};
|
use crate::point::Point;
|
||||||
use serde::{Deserialize, Serialize};
|
use crate::worldstate::{WorldState,EDH};
|
||||||
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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().map(|point| edh.apply(point)).collect()
|
point_list.iter()
|
||||||
|
.map(| point | edh.apply(point))
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,67 +24,41 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn identity_matrix_let_point_unchanged() {
|
fn identity_matrix_let_point_unchanged() {
|
||||||
let p0 = Point {
|
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() };
|
||||||
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 {
|
let ws = WorldState { edh : edh, ..WorldState::default() };
|
||||||
edh: edh,
|
|
||||||
..WorldState::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let homography = Homography {};
|
let homography = Homography{};
|
||||||
let result = homography.apply(&[p0], &ws);
|
let result = homography.apply(&[p0], &ws);
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(result, vec![Point { x: -1500.0,
|
||||||
result,
|
|
||||||
vec![Point {
|
|
||||||
x: -1500.0,
|
|
||||||
y: 1500.0,
|
y: 1500.0,
|
||||||
..Point::default()
|
..Point::default() }]);
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rotation_matrix_rotate_the_point() {
|
fn rotation_matrix_rotate_the_point() {
|
||||||
let p0 = Point {
|
let p0 = Point { x: -1500.0, y: 1500.0, ..Point::default() };
|
||||||
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 {
|
let ws = WorldState { edh : edh, ..WorldState::default() };
|
||||||
edh: edh,
|
|
||||||
..WorldState::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let homography = Homography {};
|
let homography = Homography{};
|
||||||
let result = homography.apply(&[p0], &ws);
|
let result = homography.apply(&[p0], &ws);
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(result, vec![Point { x: 10860.557,
|
||||||
result,
|
|
||||||
vec![Point {
|
|
||||||
x: 10860.557,
|
|
||||||
y: 79078.87,
|
y: 79078.87,
|
||||||
..Point::default()
|
..Point::default() }]);
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
28
src/transformer/intensity.rs
Normal file
28
src/transformer/intensity.rs
Normal file
@ -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<Point> {
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,43 +1,27 @@
|
|||||||
use crate::point::{Color, Point};
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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 {
|
||||||
if point_list.len() == 0 {
|
|
||||||
// to prevent infinit loop in case of empty frame
|
|
||||||
point_list2.append(
|
|
||||||
&mut vec![
|
|
||||||
Point {
|
|
||||||
x: 0.,
|
|
||||||
y: 0.,
|
|
||||||
color: Color { r: 0, g: 0, b: 0 }
|
|
||||||
};
|
|
||||||
*n
|
|
||||||
]
|
|
||||||
.to_vec(),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
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());
|
||||||
@ -47,3 +31,4 @@ impl Transformers for Replicate {
|
|||||||
point_list2
|
point_list2
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,32 +1,35 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
//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
|
point_list.iter()
|
||||||
.iter()
|
.map(| pt | {
|
||||||
.map(|pt| {
|
|
||||||
let dx = pt.x - self.cx;
|
let dx = pt.x - self.cx;
|
||||||
let dy = pt.y - self.cy;
|
let dy = pt.y - self.cy;
|
||||||
let cos = self.angle.cos();
|
let cos = self.angle.cos();
|
||||||
let sin = self.angle.sin();
|
let sin = self.angle.sin();
|
||||||
let x = (dx * cos - dy * sin) + self.cx;
|
let x = (dx * cos - dy * sin) + self.cx;
|
||||||
let y = (dx * sin + dy * cos) + self.cy;
|
let y = (dx * sin + dy * cos) + self.cy;
|
||||||
Point { x, y, ..*pt }
|
Point { x,
|
||||||
})
|
y,
|
||||||
.collect()
|
..*pt
|
||||||
|
}
|
||||||
|
}).collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,25 +1,24 @@
|
|||||||
use crate::point::Point;
|
|
||||||
use crate::transformer::Transformers;
|
use crate::transformer::Transformers;
|
||||||
|
use crate::point::Point;
|
||||||
use crate::worldstate::WorldState;
|
use crate::worldstate::WorldState;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Serialize,Deserialize};
|
||||||
|
|
||||||
/// 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
|
point_list.iter()
|
||||||
.iter()
|
.map(| pt | {
|
||||||
.map(|pt| Point {
|
Point { x: pt.x + self.x,
|
||||||
x: pt.x + self.x,
|
|
||||||
y: pt.y + self.y,
|
y: pt.y + self.y,
|
||||||
..*pt
|
..*pt
|
||||||
})
|
}
|
||||||
.collect()
|
}).collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
|
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};
|
use crate::redis_ctrl::Resampler;
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct EDH {
|
pub struct EDH {
|
||||||
@ -10,15 +11,17 @@ pub struct EDH {
|
|||||||
|
|
||||||
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 || vec[0].len() != 3 || vec[1].len() != 3 || vec[2].len() != 3 {
|
if vec.len() != 3 ||
|
||||||
|
vec[0].len() != 3 ||
|
||||||
|
vec[1].len() != 3 ||
|
||||||
|
vec[2].len() != 3 {
|
||||||
return Err(Box::new(LJError::BadEDH));
|
return Err(Box::new(LJError::BadEDH));
|
||||||
}
|
}
|
||||||
|
|
||||||
// this is the matrix already transposed.
|
// this is the matrix already transposed.
|
||||||
let matrix = Matrix3::new(
|
let matrix = Matrix3::new(vec[0][0], vec[1][0], vec[2][0],
|
||||||
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][1], vec[1][1], vec[2][1],
|
||||||
vec[2][2],
|
vec[0][2], vec[1][2], vec[2][2]);
|
||||||
);
|
|
||||||
|
|
||||||
Ok(EDH { matrix })
|
Ok(EDH { matrix })
|
||||||
}
|
}
|
||||||
@ -26,11 +29,7 @@ impl EDH {
|
|||||||
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 {
|
let new_p = Point { x: p[0] / p[2], y: p[1] / p[2], ..*point };
|
||||||
x: p[0] / p[2],
|
|
||||||
y: p[1] / p[2],
|
|
||||||
..*point
|
|
||||||
};
|
|
||||||
|
|
||||||
debug!("{:?} => {:?}", point, new_p);
|
debug!("{:?} => {:?}", point, new_p);
|
||||||
|
|
||||||
@ -41,7 +40,7 @@ impl EDH {
|
|||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct WorldState {
|
pub struct WorldState {
|
||||||
pub edh: EDH,
|
pub edh: EDH,
|
||||||
pub resampler: Vec<f32>,
|
pub resampler: Resampler,
|
||||||
pub client_key: String,
|
pub client_key: String,
|
||||||
pub intensity: u8,
|
pub intensity: u8,
|
||||||
pub kpps: u32,
|
pub kpps: u32,
|
||||||
@ -49,6 +48,7 @@ pub struct WorldState {
|
|||||||
pub draw_black: bool,
|
pub draw_black: bool,
|
||||||
pub draw_grid: bool,
|
pub draw_grid: bool,
|
||||||
pub grid: Vec<Point>,
|
pub grid: Vec<Point>,
|
||||||
|
pub color_balance: Color,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WorldState {}
|
impl WorldState {}
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use lj_rust::conf::{Conf, DacFamily, EtherDreamConf, HeliosConf};
|
use lj_rust::conf::{Conf, DacFamily, HeliosConf, EtherDreamConf};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_loads_a_valid_conf() {
|
fn it_loads_a_valid_conf() {
|
||||||
|
Loading…
Reference in New Issue
Block a user