Skip to content

Commit

Permalink
Refactor variable names for clarity and improve code readability
Browse files Browse the repository at this point in the history
  • Loading branch information
samclane committed Jan 13, 2025
1 parent 1331e02 commit cbecef0
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 140 deletions.
44 changes: 28 additions & 16 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
display_color_circle,
listener::input_listener::InputListener,
scenes::Scene,
screencap::{FollowType, ScreenSubregion},
screencap::{RegionCaptureTarget, ScreenSubregion},
settings::Settings,
shortcut::ShortcutManager,
toggle_button,
Expand All @@ -39,7 +39,7 @@ pub const SUBREGION_ICON: &[u8; 218] = include_bytes!("../res/icons/square.png")
pub struct RunningWaveform {
pub active: bool,
pub last_update: Instant,
pub follow_type: FollowType,
pub follow_type: RegionCaptureTarget,
pub stop_tx: Option<mpsc::Sender<()>>,
}
pub struct ColorChannelEntry {
Expand All @@ -53,7 +53,7 @@ pub type ColorChannel = HashMap<u64, ColorChannelEntry>;
#[serde(default)]
pub struct MantleApp {
#[serde(skip)]
pub mgr: LifxManager,
pub lighting_manager: LifxManager,
#[serde(skip)]
pub screen_manager: ScreencapManager,
#[serde(skip)]
Expand Down Expand Up @@ -85,7 +85,7 @@ impl Default for MantleApp {
let lifx_manager = LifxManager::new().expect("Failed to create manager");
let shortcut_handle = Some(shortcut_manager.start(lifx_manager.clone()));
Self {
mgr: lifx_manager,
lighting_manager: lifx_manager,
screen_manager: ScreencapManager::new().expect("Failed to create screen manager"),
input_listener,
shortcut_manager,
Expand Down Expand Up @@ -145,13 +145,13 @@ impl MantleApp {
}
DeviceInfo::Group(group) => {
if let Ok(s) = group.label.cstr().to_str() {
if *group == self.mgr.all {
if *group == self.lighting_manager.all_bulbs_group {
ui.label(RichText::new(s).size(16.0).strong().underline());
} else {
ui.label(RichText::new(s).size(16.0).strong());
}
}
Some(self.mgr.get_avg_group_color(group, bulbs))
Some(self.lighting_manager.get_avg_group_color(group, bulbs))
}
};

Expand All @@ -168,7 +168,13 @@ impl MantleApp {
ui.vertical(|ui| {
ui.horizontal(|ui| {
ui.label("Power");
toggle_button(ui, &self.mgr, device, Vec2::new(1.0, 1.0), bulbs);
toggle_button(
ui,
&self.lighting_manager,
device,
Vec2::new(1.0, 1.0),
bulbs,
);
});
if let Some(before_color) = color {
let mut after_color =
Expand All @@ -180,7 +186,7 @@ impl MantleApp {
if before_color != after_color.next {
match device {
DeviceInfo::Bulb(bulb) => {
if let Err(e) = self.mgr.set_color(
if let Err(e) = self.lighting_manager.set_color(
&&**bulb,
after_color.next,
after_color.duration,
Expand All @@ -189,7 +195,7 @@ impl MantleApp {
}
}
DeviceInfo::Group(group) => {
if let Err(e) = self.mgr.set_group_color(
if let Err(e) = self.lighting_manager.set_group_color(
group,
after_color.next,
bulbs,
Expand Down Expand Up @@ -241,7 +247,7 @@ impl MantleApp {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
if ui.input_mut(|i| i.consume_shortcut(&refresh_shortcut)) {
if let Err(e) = self.mgr.refresh() {
if let Err(e) = self.lighting_manager.refresh() {
log::error!("Error refreshing manager: {}", e);
}
}
Expand All @@ -255,7 +261,7 @@ impl MantleApp {
)
.clicked()
{
if let Err(e) = self.mgr.refresh() {
if let Err(e) = self.lighting_manager.refresh() {
log::error!("Error refreshing manager: {}", e);
}
ui.close_menu();
Expand Down Expand Up @@ -296,12 +302,16 @@ impl MantleApp {
});
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
let bulbs = self.mgr.bulbs.clone();
let bulbs = self.lighting_manager.bulbs.clone();
let bulbs = bulbs.lock();
let mut seen_groups = HashSet::<String>::new();
ui.vertical(|ui| {
if let Ok(bulbs) = bulbs {
self.display_device(ui, &DeviceInfo::Group(self.mgr.all.clone()), &bulbs);
self.display_device(
ui,
&DeviceInfo::Group(self.lighting_manager.all_bulbs_group.clone()),
&bulbs,
);
let sorted_bulbs = self.sort_bulbs(bulbs.values().collect());
for bulb in sorted_bulbs {
if let Some(group) = bulb.group.data.as_ref() {
Expand Down Expand Up @@ -354,12 +364,14 @@ impl eframe::App for MantleApp {
fn update(&mut self, _ctx: &egui::Context, _frame: &mut eframe::Frame) {
#[cfg(debug_assertions)]
puffin::GlobalProfiler::lock().new_frame();
if Instant::now() - self.mgr.last_discovery
if Instant::now() - self.lighting_manager.last_discovery
> Duration::from_millis(self.settings.refresh_rate_ms)
{
self.mgr.discover().expect("Failed to discover bulbs");
self.lighting_manager
.discover()
.expect("Failed to discover bulbs");
}
if let Err(e) = self.mgr.refresh() {
if let Err(e) = self.lighting_manager.refresh() {
log::error!("Error refreshing manager: {}", e);
}
self.update_ui(_ctx);
Expand Down
62 changes: 37 additions & 25 deletions src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,18 @@ impl From<HSBK> for RGB8 {
};

let rgb_k = kelvin_to_rgb(kelvin);
let a = saturation as f64 / u16::MAX as f64;
let b = (1.0 - a) / 255.0;

let red = (rgb_hsb.red as f64 * (a + rgb_k.red as f64 * b)).round() as u8;
let green = (rgb_hsb.green as f64 * (a + rgb_k.green as f64 * b)).round() as u8;
let blue = (rgb_hsb.blue as f64 * (a + rgb_k.blue as f64 * b)).round() as u8;
let normalized_saturation = saturation as f64 / u16::MAX as f64;
let normalized_brightness = (1.0 - normalized_saturation) / 255.0;

let red = (rgb_hsb.red as f64
* (normalized_saturation + rgb_k.red as f64 * normalized_brightness))
.round() as u8;
let green = (rgb_hsb.green as f64
* (normalized_saturation + rgb_k.green as f64 * normalized_brightness))
.round() as u8;
let blue = (rgb_hsb.blue as f64
* (normalized_saturation + rgb_k.blue as f64 * normalized_brightness))
.round() as u8;

RGB8 {
red,
Expand All @@ -94,28 +100,28 @@ impl From<HSBK> for RGB8 {

impl From<RGB8> for HSBK {
fn from(color: RGB8) -> HSBK {
let cmax = *[color.red, color.green, color.blue]
let max_color_component = *[color.red, color.green, color.blue]
.iter()
.max()
.expect("Invalid color tuple") as f32;
let cmin = *[color.red, color.green, color.blue]
let min_color_component = *[color.red, color.green, color.blue]
.iter()
.min()
.expect("Invalid color tuple") as f32;
let cdel = cmax - cmin;
let color_range = max_color_component - min_color_component;

let brightness = ((cmax / 255.0) * u16::MAX as f32) as u16;
let brightness = ((max_color_component / 255.0) * u16::MAX as f32) as u16;

let (saturation, hue) = if cdel != 0.0 {
let saturation = ((cdel / cmax) * u16::MAX as f32) as u16;
let (saturation, hue) = if color_range != 0.0 {
let saturation = ((color_range / max_color_component) * u16::MAX as f32) as u16;

let redc = (cmax - color.red as f32) / cdel;
let greenc = (cmax - color.green as f32) / cdel;
let bluec = (cmax - color.blue as f32) / cdel;
let redc = (max_color_component - color.red as f32) / color_range;
let greenc = (max_color_component - color.green as f32) / color_range;
let bluec = (max_color_component - color.blue as f32) / color_range;

let mut hue = if color.red as f32 == cmax {
let mut hue = if color.red as f32 == max_color_component {
bluec - greenc
} else if color.green as f32 == cmax {
} else if color.green as f32 == max_color_component {
2.0 + redc - bluec
} else {
4.0 + greenc - redc
Expand Down Expand Up @@ -147,25 +153,31 @@ impl From<RGB8> for Color32 {
}

pub fn kelvin_to_rgb(temperature: u16) -> RGB8 {
let p_temp = temperature / 100;
let percentage_temperature = temperature / 100;
let red;
let green;

if p_temp <= 66 {
if percentage_temperature <= 66 {
red = 255.;
green = (99.4708025861 * (p_temp as f64 + 0.0000000001).ln() - 161.1195681661)
green = (99.4708025861 * (percentage_temperature as f64 + 0.0000000001).ln()
- 161.1195681661)
.clamp(0.0, 255.0);
} else {
red = 329.698727466 * ((p_temp - 60) as f64).powf(-0.1332047592).clamp(0.0, 255.0);
green = (288.1221695283 * ((p_temp - 60) as f64).powf(-0.0755148492)).clamp(0.0, 255.0);
red = 329.698727466
* ((percentage_temperature - 60) as f64)
.powf(-0.1332047592)
.clamp(0.0, 255.0);
green = (288.1221695283 * ((percentage_temperature - 60) as f64).powf(-0.0755148492))
.clamp(0.0, 255.0);
}

let blue = if p_temp >= 66 {
let blue = if percentage_temperature >= 66 {
255.0
} else if p_temp <= 19 {
} else if percentage_temperature <= 19 {
0.0
} else {
(138.5177312231 * ((p_temp - 10) as f64).ln() - 305.0447927307).clamp(0.0, 255.0)
(138.5177312231 * ((percentage_temperature - 10) as f64).ln() - 305.0447927307)
.clamp(0.0, 255.0)
};

RGB8 {
Expand Down
7 changes: 5 additions & 2 deletions src/device_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ pub struct BulbInfo {
deserialize_with = "deserialize_instant"
)]
pub last_seen: Instant,
/// If the source is non-zero, then the LIFX device with send a unicast message to the IP
/// address/port of the client that sent the originating message. If zero, then the LIFX
/// device may send a broadcast message that can be received by all clients on the same sub-net.
pub source: u32,
pub target: u64,
pub addr: SocketAddr,
Expand Down Expand Up @@ -327,8 +330,8 @@ impl std::fmt::Debug for BulbInfo {
if let Some((major, minor)) = self.wifi_firmware.as_ref() {
write!(f, " WifiFW:{}.{}", major, minor)?;
}
if let Some(level) = self.power_level.as_ref() {
if *level > 0 {
if let Some(power_level) = self.power_level.as_ref() {
if *power_level > 0 {
write!(f, " Powered On(")?;
match self.color {
DeviceColor::Unknown => write!(f, "??")?,
Expand Down
27 changes: 15 additions & 12 deletions src/device_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,22 @@ use std::time::{Duration, Instant};

pub struct LifxManager {
pub bulbs: Arc<Mutex<HashMap<u64, BulbInfo>>>,
pub all: GroupInfo,
pub all_bulbs_group: GroupInfo,
pub last_discovery: Instant,
pub sock: UdpSocket,
pub socket: UdpSocket,
/// If the source is non-zero, then the LIFX device with send a unicast message to the IP
/// address/port of the client that sent the originating message. If zero, then the LIFX
/// device may send a broadcast message that can be received by all clients on the same sub-net.
pub source: u32,
}

impl Clone for LifxManager {
fn clone(&self) -> Self {
LifxManager {
bulbs: self.bulbs.clone(),
all: self.all.clone(),
all_bulbs_group: self.all_bulbs_group.clone(),
last_discovery: self.last_discovery,
sock: self.sock.try_clone().expect("Failed to clone socket"),
socket: self.socket.try_clone().expect("Failed to clone socket"),
source: self.source,
}
}
Expand All @@ -43,15 +46,15 @@ impl LifxManager {

spawn(move || Self::worker(recv_sock, source, receiver_bulbs));

let mut mgr = LifxManager {
let mut lifx_manager = LifxManager {
bulbs,
last_discovery: Instant::now(),
sock,
socket: sock,
source,
all: GroupInfo::build_all_group(),
all_bulbs_group: GroupInfo::build_all_group(),
};
mgr.discover()?;
Ok(mgr)
lifx_manager.discover()?;
Ok(lifx_manager)
}

fn handle_message(raw: RawMessage, bulb: &mut BulbInfo) -> Result<(), lifx_core::Error> {
Expand Down Expand Up @@ -234,7 +237,7 @@ impl LifxManager {
}
let addr = SocketAddr::new(IpAddr::V4(bcast), 56700);
log::debug!("Discovering bulbs on LAN {:?}", addr);
self.sock.send_to(&bytes, addr)?;
self.socket.send_to(&bytes, addr)?;
count += 1;
}
}
Expand All @@ -249,7 +252,7 @@ impl LifxManager {
if let Ok(mut bulbs) = self.bulbs.lock() {
let bulbs = bulbs.values_mut();
for bulb in bulbs {
bulb.query_for_missing_info(&self.sock)?;
bulb.query_for_missing_info(&self.socket)?;
count += 1;
}
}
Expand All @@ -267,7 +270,7 @@ impl LifxManager {
};
let raw = RawMessage::build(&opts, message).expect("Failed to build message");
let bytes = raw.pack().expect("Failed to pack message");
self.sock.send_to(&bytes, target)
self.socket.send_to(&bytes, target)
}

pub fn set_power(&self, bulb: &&BulbInfo, level: u16) -> Result<usize, std::io::Error> {
Expand Down
Loading

0 comments on commit cbecef0

Please sign in to comment.