Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions blinksy-desktop/examples/1d-rainbow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,37 @@ use blinksy::{
ControlBuilder,
};
use blinksy_desktop::{
driver::{Desktop, DesktopError},
driver::{Desktop, DesktopError, DesktopLedClicks},
time::elapsed_in_ms,
};
use std::{thread::sleep, time::Duration};

layout1d!(StripLayout, 30);

fn main() {
Desktop::new_1d::<StripLayout>().start(|driver| {
let mut control = ControlBuilder::new_1d()
.with_layout::<StripLayout, { StripLayout::PIXEL_COUNT }>()
.with_pattern::<Rainbow>(RainbowParams {
..Default::default()
})
.with_driver(driver)
.with_frame_buffer_size::<{ StripLayout::PIXEL_COUNT }>()
.build();
let mut led_clicks = DesktopLedClicks::new();
Desktop::new_1d::<StripLayout>()
.with_led_clicks(&led_clicks)
.start(move |driver| {
let mut control = ControlBuilder::new_1d()
.with_layout::<StripLayout, { StripLayout::PIXEL_COUNT }>()
.with_pattern::<Rainbow>(RainbowParams {
..Default::default()
})
.with_driver(driver)
.with_frame_buffer_size::<{ StripLayout::PIXEL_COUNT }>()
.build();

loop {
if let Err(DesktopError::WindowClosed) = control.tick(elapsed_in_ms()) {
break;
}
loop {
while let Some(led_index) = led_clicks.try_take() {
println!("LED {led_index} clicked");
}

if let Err(DesktopError::WindowClosed) = control.tick(elapsed_in_ms()) {
break;
}

sleep(Duration::from_millis(16));
}
});
sleep(Duration::from_millis(16));
}
});
}
94 changes: 94 additions & 0 deletions blinksy-desktop/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ impl Desktop<Dim1d, ()> {
let stage = DesktopStageOptions {
positions,
receiver,
led_click_sender: None,
config,
is_window_closed: is_window_closed_2,
};
Expand Down Expand Up @@ -260,6 +261,7 @@ impl Desktop<Dim2d, ()> {
let stage = DesktopStageOptions {
positions,
receiver,
led_click_sender: None,
config,
is_window_closed: is_window_closed_2,
};
Expand Down Expand Up @@ -329,6 +331,7 @@ impl Desktop<Dim3d, ()> {
let stage = DesktopStageOptions {
positions,
receiver,
led_click_sender: None,
config,
is_window_closed: is_window_closed_2,
};
Expand Down Expand Up @@ -378,6 +381,15 @@ where
f(driver).await
}

/// Registers a queue for LED click events.
///
/// The handle is only borrowed during registration and can then be moved into
/// the control loop. Calling this again replaces the previously registered queue.
pub fn with_led_clicks(mut self, led_clicks: &DesktopLedClicks) -> Self {
self.stage.led_click_sender = Some(led_clicks.sender.clone());
self
}

/// Registers a keycode to be treated as a button input.
/// Take care not to conflict with the keys used for camera control (R,O) to avoid surprising behavior.
pub fn with_button<D, I>(mut self, keycode: KeyCode, button: &DesktopButton<D, I>) -> Self
Expand Down Expand Up @@ -421,6 +433,36 @@ impl<Dim, Layout> DesktopDriver<Dim, Layout> {
}
}

/// A non-blocking receiver for LED click events from the desktop simulator.
///
/// Create this handle before starting the simulator and register it with
/// [`Desktop::with_led_clicks`], then move it into your control loop.
pub struct DesktopLedClicks {
sender: Sender<usize>,
receiver: Receiver<usize>,
}

impl DesktopLedClicks {
/// Creates an empty LED click queue.
pub fn new() -> Self {
let (sender, receiver) = channel();
Self { sender, receiver }
}

/// Returns the next LED index clicked in the simulator, if one is pending.
///
/// This method never blocks. Only successful primary-button LED picks emit events.
pub fn try_take(&mut self) -> Option<usize> {
self.receiver.try_recv().ok()
}
}

impl Default for DesktopLedClicks {
fn default() -> Self {
Self::new()
}
}

/// Errors that can occur when using the Desktop driver.
#[derive(Debug)]
pub enum DesktopError {
Expand Down Expand Up @@ -1056,6 +1098,7 @@ impl Renderer {
struct DesktopStageOptions {
pub positions: Vec<Vec3>,
pub receiver: Receiver<LedMessage>,
pub led_click_sender: Option<Sender<usize>>,
pub config: DesktopConfig,
pub is_window_closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
}
Expand All @@ -1069,6 +1112,7 @@ struct DesktopStage {
brightness: f32,
correction: ColorCorrection,
receiver: Receiver<LedMessage>,
led_click_sender: Option<Sender<usize>>,
camera: Camera,
config: DesktopConfig,
is_window_closed: std::sync::Arc<std::sync::atomic::AtomicBool>,
Expand Down Expand Up @@ -1103,6 +1147,7 @@ impl DesktopStage {
let DesktopStageOptions {
positions,
receiver,
led_click_sender,
config,
is_window_closed,
} = options;
Expand Down Expand Up @@ -1136,6 +1181,7 @@ impl DesktopStage {
brightness: 1.0,
correction: ColorCorrection::default(),
receiver,
led_click_sender,
camera,
config,
is_window_closed,
Expand Down Expand Up @@ -1294,6 +1340,11 @@ impl EventHandler for DesktopStage {
if !self.mouse_down {
// Only do picking when button is first pressed
self.led_picker.try_select_at(x, y, &self.camera);
if let Some(led_index) = self.led_picker.selected_led {
if let Some(sender) = &self.led_click_sender {
let _ = sender.send(led_index);
}
}
}

self.mouse_down = true;
Expand Down Expand Up @@ -1338,6 +1389,49 @@ impl EventHandler for DesktopStage {
}
}

#[cfg(test)]
mod tests {
use super::*;

blinksy::layout1d!(TestStrip, 8);

#[test]
fn registered_click_queue_can_move_to_control_thread() {
let mut clicks = DesktopLedClicks::new();
let desktop = Desktop::new_1d::<TestStrip>().with_led_clicks(&clicks);
let sender = desktop.stage.led_click_sender.as_ref().unwrap();
assert_eq!(clicks.try_take(), None);
sender.send(2).unwrap();
sender.send(7).unwrap();

std::thread::spawn(move || {
assert_eq!(clicks.try_take(), Some(2));
assert_eq!(clicks.try_take(), Some(7));
assert_eq!(clicks.try_take(), None);
})
.join()
.unwrap();
}

#[test]
fn click_registration_is_optional_and_replaceable() {
let desktop = Desktop::new_1d::<TestStrip>();
assert!(desktop.stage.led_click_sender.is_none());
let mut first = DesktopLedClicks::default();
let mut second = DesktopLedClicks::new();
let desktop = desktop.with_led_clicks(&first).with_led_clicks(&second);
desktop
.stage
.led_click_sender
.as_ref()
.unwrap()
.send(3)
.unwrap();
assert_eq!(first.try_take(), None);
assert_eq!(second.try_take(), Some(3));
}
}

/// Shader definitions for rendering LEDs
mod shader {
use miniquad::*;
Expand Down
11 changes: 9 additions & 2 deletions blinksy-desktop/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
//! layout::{Layout2d, Shape2d, Vec2},
//! patterns::rainbow::{Rainbow, RainbowParams}
//! };
//! use blinksy_desktop::{driver::Desktop, time::elapsed_in_ms};
//! use blinksy_desktop::{driver::{Desktop, DesktopLedClicks}, time::elapsed_in_ms};
//!
//! // Define your layout
//! layout2d!(
Expand All @@ -29,7 +29,10 @@
//! );
//!
//! // Create the Desktop simulator
//! Desktop::new_2d::<PanelLayout>().start(|driver| {
//! let mut led_clicks = DesktopLedClicks::new();
//! Desktop::new_2d::<PanelLayout>()
//! .with_led_clicks(&led_clicks)
//! .start(move |driver| {
//! // Create a control using the desktop driver instead of physical hardware
//! let mut control = ControlBuilder::new_2d()
//! .with_layout::<PanelLayout, { PanelLayout::PIXEL_COUNT }>()
Expand All @@ -40,6 +43,10 @@
//!
//! // Run your normal animation loop
//! loop {
//! while let Some(led_index) = led_clicks.try_take() {
//! println!("LED {led_index} clicked");
//! }
//!
//! control.tick(elapsed_in_ms()).unwrap();
//!
//! // Sleep on every frame (16 ms per frame ~= 60 frames per second)
Expand Down
Loading