feat: the etherdream device should work

This commit is contained in:
alban 2023-07-19 01:28:45 +02:00
parent 4a87821c22
commit ae75092d34
5 changed files with 316 additions and 57 deletions

150
examples/etherdream.rs Normal file
View File

@ -0,0 +1,150 @@
extern crate ether_dream;
use ether_dream::dac;
fn main() {
println!("Listening for an Ether Dream DAC...");
let (dac_broadcast, source_addr) = ether_dream::recv_dac_broadcasts()
.expect("failed to bind to UDP socket")
.filter_map(Result::ok)
.next()
.unwrap();
let mac_address = dac::MacAddress(dac_broadcast.mac_address);
println!(
"Discovered DAC \"{}\" at \"{}\"! Connecting...",
mac_address, source_addr
);
// Establish the TCP connection.
let mut stream = dac::stream::connect(&dac_broadcast, source_addr.ip().clone()).unwrap();
// If we want to create an animation (in our case a moving sine wave) we need a frame rate.
let frames_per_second = 60.0;
// Lets use the DAC at an eighth the maximum scan rate.
let points_per_second = stream.dac().max_point_rate / 32;
// Determine the number of points per frame given our target frame and point rates.
let points_per_frame = (points_per_second as f32 / frames_per_second) as u16;
println!(
"Preparing for playback:\n\tframe_hz: {}\n\tpoint_hz: {}\n\tpoints_per_frame: {}\n",
frames_per_second, points_per_second, points_per_frame
);
// Prepare the DAC's playback engine and await the repsonse.
stream
.queue_commands()
.prepare_stream()
.submit()
.err()
.map(|err| {
eprintln!(
"err occurred when submitting PREPARE_STREAM \
command and listening for response: {}",
err
);
});
println!("Beginning playback!");
// The sine wave used to generate points.
let mut sine_wave = SineWave {
point: 0,
points_per_frame,
frames_per_second,
};
// Queue the initial frame and tell the DAC to begin producing output.
let n_points = points_to_generate(stream.dac());
stream
.queue_commands()
.data(sine_wave.by_ref().take(n_points))
.begin(0, points_per_second)
.submit()
.err()
.map(|err| {
eprintln!(
"err occurred when submitting initial DATA and BEGIN \
commands and listening for response: {}",
err
);
});
// Loop and continue to send points forever.
loop {
// Determine how many points the DAC can currently receive.
let n_points = points_to_generate(stream.dac());
if let Err(err) = stream
.queue_commands()
.data(sine_wave.by_ref().take(n_points))
.submit()
{
eprintln!(
"err occurred when submitting DATA command and listening \
for response: {}",
err
);
break;
}
}
// Tell the DAC to stop producing output and return to idle. Wait for the response.
//
// Note that the DAC is commanded to stop on `Drop` if this is not called and any errors
// produced are ignored.
stream
.queue_commands()
.stop()
.submit()
.expect("err occurred when submitting STOP command and listening for response");
}
// Determine the number of points needed to fill the DAC.
fn points_to_generate(dac: &ether_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::i16::MAX;
let x = (x_min as f32 + fract * (x_max as f32 - x_min as f32)) as i16;
let y = (amp * x_max as f32) as i16;
let control = 0;
let (u1, u2) = (0, 0);
let p = ether_dream::protocol::DacPoint {
control,
x,
y,
i,
r,
g,
b,
u1,
u2,
};
self.point += 1;
Some(p)
}
}

View File

@ -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 {

View File

@ -1,14 +1,14 @@
use std::time; use std::time;
use std::net::SocketAddr; 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::{Playback, Stream};
use crate::conf::EtherDreamConf; use crate::conf::EtherDreamConf;
use crate::device::{Device, Status, PlaybackState}; 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, DacPoint};
use log::{info, warn}; use log::{debug, info, warn};
#[warn(dead_code)] #[warn(dead_code)]
pub struct EtherdreamDevice { pub struct EtherdreamDevice {
@ -21,10 +21,11 @@ pub struct EtherdreamDevice {
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)?;
Ok(Self { Ok(Self {
conf: (*conf).clone(), conf: (*conf).clone(),
dac, dac,
@ -41,17 +42,18 @@ impl EtherdreamDevice {
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
.take(3)
.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)) => {
info!("Valid broadcast, source_addr: {}", source_addr);
if source_addr.is_ipv6() { return None; } if source_addr.is_ipv6() { return None; }
if &source_addr.ip().to_string() != ip { return None; } if &source_addr.ip().to_string() != ip { return None; }
info!("Valid broadcast");
Some(Ok((dac, source_addr))) Some(Ok((dac, source_addr)))
} }
} }
@ -64,6 +66,7 @@ impl EtherdreamDevice {
} }
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)?;
info!("Finished configuring DAC and TCP stream.");
Ok((dac, source_addr, stream)) Ok((dac, source_addr, stream))
} }
} }
@ -72,22 +75,61 @@ impl EtherdreamDevice {
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())?;
EtherdreamDevice::prepare_tcp_stream(&mut stream).unwrap();
Ok(stream)
}
fn prepare_tcp_stream(stream: &mut Stream) -> LJResult<()> {
// Prepare stream // Prepare stream
stream match stream
.queue_commands() .queue_commands()
.prepare_stream() .prepare_stream()
.submit() .submit() {
.err() Err(err) => {
.map(|err| { warn!(
eprintln!( "err occurred when submitting PREPARE_STREAM command and listening for response: {}",
"err occurred when submitting PREPARE_STREAM \
command and listening for response: {}",
err err
); );
}); }
Ok(_) => {
info!("Prepared Stream.")
}
}
Ok(stream) let control = 0;
let (u1, u2) = (0, 0);
let i = 255;
let point = DacPoint {
control,
x: 0,
y: 0,
i,
r: 0,
g: 0,
b: 0,
u1,
u2,
};
let begin_list = vec![point];
let points_per_second = stream.dac().max_point_rate / 32;
match stream
.queue_commands()
.data(begin_list.into_iter().take(1 as usize))
.begin(0, points_per_second)
.submit() {
Err(err) => {
warn!(
"err occurred when submitting first data: {}",
err
);
}
Ok(_) => {
info!("Sent first data to Etherdream.")
}
}
Ok(())
} }
@ -98,8 +140,10 @@ impl EtherdreamDevice {
} }
// Determine the number of points needed to fill the DAC. // Determine the number of points needed to fill the DAC.
fn points_to_generate(&self) -> usize { fn points_capacity(&self) -> u16 {
self.dac.buffer_capacity as usize - 1 - self.dac.dac_status.buffer_fullness as usize // Fixme thread 'main' panicked at 'attempt to subtract with overflow', src/device/etherdream.rs:144:24
let n_points = self.dac.buffer_capacity as u16 - self.stream.dac().dac.status.buffer_fullness as u16 - 1;
n_points
} }
} }
@ -108,46 +152,93 @@ impl Device for EtherdreamDevice {
let _ = self.check_tcp_stream(); 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.stream.dac().dac.status.playback {
DacStatus::PLAYBACK_IDLE => PlaybackState::IDLE, Playback::Idle => PlaybackState::IDLE,
DacStatus::PLAYBACK_PREPARED => PlaybackState::PREPARE, Playback::Prepared => PlaybackState::PREPARE,
DacStatus::PLAYBACK_PLAYING => PlaybackState::PLAYING, Playback::Playing => PlaybackState::PLAYING,
_ => PlaybackState::UNKNOWN
}; };
Status { let 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.points_capacity(),
lack: String::from(&self.lack), lack: String::from(&self.lack),
} };
// info!("Dac Status: {:?} ", status );
// info!("Etherdream Dac {:?} ", self.dac );
// info!("Stream dac{:?}", self.stream.dac());
status
} }
fn draw(&mut self, fn draw(&mut self,
line: Vec<Point>, line: Vec<Point>,
_speed: u32, _speed: u32,
) -> LJResult<()> { ) -> LJResult<()> {
let n_points = self.points_to_generate(); let n_points = self.points_capacity();
self.stream // let n_points = &line.len();
debug!("Etherdream::device draw Generating {:?} points", n_points);
return match self.stream
.queue_commands() .queue_commands()
.data(line.into_iter().map(|point| point.into()).take(n_points)) .data(
.submit()?; line.into_iter()
.map(|point| point.into())
// .take(line.len() as usize)
.take(n_points as usize )
)
.submit() {
Err(err) => {
// We should account for
// 'Broken pipe (os error 32)'
// Connection reset by peer (os error 104)
warn!("Draw error: '{}'",err);
Ok(()) Ok(())
} }
Ok(_) => {
debug!("Draw is 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!( let dim_mid = 16000 as f32;
Point { x: 0.0, y: 0.0, color: Color { r: 255, g: 255, b: 255 } } let dim_max = 32000 as f32;
) let col_min = Color { r: 0, g: 0, b: 0 };
let col_max = Color { r: 255, g: 255, b: 255 };
vec![
Point { x: -dim_max, y: dim_max, color: col_min },
Point { x: -dim_max, y: dim_max, color: col_max },
Point { x: dim_max, y: dim_max, color: col_max },
Point { x: dim_max, y: -dim_max, color: col_max },
Point { x: -dim_max, y: -dim_max, color: col_max },
Point { x: -dim_max, y: -dim_mid, color: col_min },
Point { x: -dim_mid, y: dim_mid, color: col_min },
Point { x: -dim_mid, y: dim_mid, color: col_max },
Point { x: dim_mid, y: dim_mid, color: col_max },
Point { x: dim_mid, y: -dim_mid, color: col_max },
Point { x: -dim_mid, y: -dim_mid, color: col_max },
Point { x: -dim_mid, y: -dim_mid, color: col_min },
]
} }
} }

View File

@ -35,6 +35,13 @@ 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().nth(1).unwrap_or_else(|| { let filename = std::env::args().nth(1).unwrap_or_else(|| {
DEFAULT_CONF_FILE.to_string() DEFAULT_CONF_FILE.to_string()
@ -53,12 +60,6 @@ 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);
// 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)?;
@ -108,7 +109,7 @@ fn run_all() -> LJResult<()> {
} }
Order::ClientKey => { Order::ClientKey => {
world_state.client_key = rs.get_client_key()?; world_state.client_key = rs.get_client_key()?;
}, }
// Order::ColorBalance => {}, // Order::ColorBalance => {},
_ => { _ => {
// 4 : Resampler Change (longs and shorts lsteps) // 4 : Resampler Change (longs and shorts lsteps)
@ -127,15 +128,19 @@ 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 builder
.filter(None, LevelFilter::Info) .filter(None, level)
.init(); .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();
} }
@ -165,8 +170,8 @@ fn get_next_frame(
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.into_iter()

View File

@ -1,5 +1,15 @@
use ether_dream::protocol::DacPoint; use ether_dream::protocol::DacPoint;
fn clamp(val: f32, min: f32, max: f32) -> f32 {
if val < min {
return min;
}
if val > max {
return max;
}
val
}
#[derive(Debug, Clone, Copy, Default, PartialEq)] #[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Point { pub struct Point {
pub x: f32, pub x: f32,
@ -45,14 +55,18 @@ impl From<Point> for helios_dac::Point {
} }
impl From<Point> for DacPoint { impl From<Point> for DacPoint {
fn from(pt: Point) -> DacPoint { fn from(pt: Point) -> DacPoint {
print!(".");
let control = 0; let control = 0;
let (u1, u2) = (0, 0); let (u1, u2) = (0, 0);
let i = 255; let i = 255;
let x = clamp(pt.x, -32000 as f32, 32000 as f32);
let y = clamp(pt.y, -32000 as f32, 32000 as f32);
DacPoint { 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.into(),
g: pt.color.g.into(), g: pt.color.g.into(),