Simplify and remove further code

This commit is contained in:
Luke
2020-06-30 16:01:00 +12:00
parent 20b82b1f24
commit 9fad94a834
8 changed files with 66 additions and 189 deletions

View File

@@ -30,7 +30,8 @@ pub enum AuraModes {
Flash(SingleColour), Flash(SingleColour),
MultiStatic(MultiColour), MultiStatic(MultiColour),
LedBrightness(u8), LedBrightness(u8),
Aura, // TODO: use a serializable structure for this (KeyColourArray)
RGB(Vec<Vec<u8>>),
} }
impl From<SetAuraBuiltin> for AuraModes { impl From<SetAuraBuiltin> for AuraModes {

View File

@@ -26,7 +26,6 @@ impl AuraDbusWriter {
let stopper2 = stop.clone(); let stopper2 = stop.clone();
let match_rule = dbus::message::MatchRule::new_signal(DBUS_IFACE, "KeyBacklightChanged"); let match_rule = dbus::message::MatchRule::new_signal(DBUS_IFACE, "KeyBacklightChanged");
let stop_token = connection.add_match(match_rule, move |_: (), _, msg| { let stop_token = connection.add_match(match_rule, move |_: (), _, msg| {
dbg!(&msg);
if let Ok(stop) = msg.read1::<bool>() { if let Ok(stop) = msg.read1::<bool>() {
if stop { if stop {
stopper2.store(true, Ordering::Relaxed); stopper2.store(true, Ordering::Relaxed);
@@ -47,7 +46,7 @@ impl AuraDbusWriter {
/// the keyboard LED EC in the correct mode /// the keyboard LED EC in the correct mode
#[inline] #[inline]
pub fn init_effect(&self) -> Result<(), Box<dyn std::error::Error>> { pub fn init_effect(&self) -> Result<(), Box<dyn std::error::Error>> {
let mode = AuraModes::Aura; let mode = AuraModes::RGB(vec![vec![]]);
let mut msg = let mut msg =
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")? Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")?
.append1(serde_json::to_string(&mode)?); .append1(serde_json::to_string(&mode)?);
@@ -66,11 +65,14 @@ impl AuraDbusWriter {
key_colour_array: &KeyColourArray, key_colour_array: &KeyColourArray,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
let group = key_colour_array.get(); let group = key_colour_array.get();
let mut msg = Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "LedWriteEffect")? let mut vecs = Vec::with_capacity(group.len());
.append3(&group[0].to_vec(), &group[1].to_vec(), &group[2].to_vec()) for v in group {
.append3(&group[3].to_vec(), &group[4].to_vec(), &group[5].to_vec()) vecs.push(v.to_vec());
.append3(&group[6].to_vec(), &group[7].to_vec(), &group[8].to_vec()) }
.append2(&group[9].to_vec(), &group[10].to_vec()); let mode = AuraModes::RGB(vecs);
let mut msg =
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")?
.append1(serde_json::to_string(&mode)?);
msg.set_no_reply(true); msg.set_no_reply(true);
self.connection.send(msg).unwrap(); self.connection.send(msg).unwrap();
thread::sleep(Duration::from_micros(self.block_time)); thread::sleep(Duration::from_micros(self.block_time));
@@ -83,22 +85,6 @@ impl AuraDbusWriter {
Ok(()) Ok(())
} }
#[inline]
pub fn write_multizone(
&mut self,
group: &[[u8; LED_MSG_LEN]; 4],
) -> Result<(), Box<dyn std::error::Error>> {
let mut msg =
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "LedWriteMultizone")?
.append1(&group[0].to_vec())
.append1(&group[1].to_vec())
.append1(&group[2].to_vec())
.append1(&group[3].to_vec());
msg.set_no_reply(true);
self.connection.send(msg).unwrap();
Ok(())
}
#[inline] #[inline]
pub fn write_keyboard_leds(&self, mode: &AuraModes) -> Result<(), Box<dyn std::error::Error>> { pub fn write_keyboard_leds(&self, mode: &AuraModes) -> Result<(), Box<dyn std::error::Error>> {
let mut msg = let mut msg =

View File

@@ -36,7 +36,6 @@ impl Config {
for n in supported_led_modes { for n in supported_led_modes {
c.builtin_modes.push(AuraModes::from(*n)) c.builtin_modes.push(AuraModes::from(*n))
} }
dbg!(&c.builtin_modes);
// Should be okay to unwrap this as is since it is a Default // Should be okay to unwrap this as is since it is a Default
let json = serde_json::to_string_pretty(&c).unwrap(); let json = serde_json::to_string_pretty(&c).unwrap();

View File

@@ -2,7 +2,7 @@ use crate::{
animatrix_control::{AniMeWriter, AnimatrixCommand}, animatrix_control::{AniMeWriter, AnimatrixCommand},
config::Config, config::Config,
laptops::match_laptop, laptops::match_laptop,
led_control::{AuraCommand, LedWriter}, led_control::LedWriter,
rog_dbus::dbus_create_tree, rog_dbus::dbus_create_tree,
rogcore::*, rogcore::*,
}; };
@@ -188,38 +188,32 @@ pub async fn start_daemon() -> Result<(), Box<dyn Error>> {
while let Some(command) = aura_command_recv.recv().await { while let Some(command) = aura_command_recv.recv().await {
let mut config = config.lock().await; let mut config = config.lock().await;
match &command { match &command {
AuraCommand::WriteEffect(_) | AuraCommand::WriteMultizone(_) => led_writer AuraModes::RGB(_) => {
.do_command(command, &mut config) led_writer
.await .do_command(command, &mut config)
.unwrap_or_else(|err| warn!("{:?}", err)), .await
AuraCommand::WriteMode(mode) => match mode { .unwrap_or_else(|err| warn!("{:?}", err));
AuraModes::Aura => { }
led_writer _ => {
.do_command(command, &mut config) led_writer
.await .do_command(command, &mut config)
.unwrap_or_else(|err| warn!("{:?}", err)); .await
} .unwrap_or_else(|err| warn!("{:?}", err));
_ => { connection
led_writer .send(
.do_command(command, &mut config) effect_cancel_signal
.await .msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.unwrap_or_else(|err| warn!("{:?}", err)); .append1(true),
connection )
.send( .unwrap_or_else(|_| 0);
effect_cancel_signal connection
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into()) .send(
.append1(true), effect_cancel_signal
) .msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.unwrap_or_else(|_| 0); .append1(false),
connection )
.send( .unwrap_or_else(|_| 0);
effect_cancel_signal }
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.append1(false),
)
.unwrap_or_else(|_| 0);
}
},
} }
} }
} }

View File

@@ -1,4 +1,4 @@
use crate::{config::Config, led_control::AuraCommand, rogcore::RogCore}; use crate::{config::Config, rogcore::RogCore};
use rog_client::{ use rog_client::{
aura_modes::{ aura_modes::{
AuraModes, BREATHING, COMET, FLASH, HIGHLIGHT, LASER, PULSE, RAIN, RAINBOW, RIPPLE, SINGLE, AuraModes, BREATHING, COMET, FLASH, HIGHLIGHT, LASER, PULSE, RAIN, RAINBOW, RIPPLE, SINGLE,
@@ -116,7 +116,7 @@ impl LaptopBase {
rogcore: &mut RogCore, rogcore: &mut RogCore,
config: &Mutex<Config>, config: &Mutex<Config>,
key_buf: [u8; 32], key_buf: [u8; 32],
mut aura_command: mpsc::Sender<AuraCommand>, mut aura_command: mpsc::Sender<AuraModes>,
) -> Result<(), AuraError> { ) -> Result<(), AuraError> {
let mut config = config.lock().await; let mut config = config.lock().await;
match FnKeys::from(key_buf[1]) { match FnKeys::from(key_buf[1]) {
@@ -127,7 +127,7 @@ impl LaptopBase {
info!("Increased LED brightness to {:#?}", bright); info!("Increased LED brightness to {:#?}", bright);
} }
aura_command aura_command
.send(AuraCommand::WriteMode(AuraModes::LedBrightness(bright))) .send(AuraModes::LedBrightness(bright))
.await .await
.unwrap_or_else(|err| warn!("LedBrightUp: {}", err)); .unwrap_or_else(|err| warn!("LedBrightUp: {}", err));
} }
@@ -137,7 +137,7 @@ impl LaptopBase {
bright -= 1; bright -= 1;
} }
aura_command aura_command
.send(AuraCommand::WriteMode(AuraModes::LedBrightness(bright))) .send(AuraModes::LedBrightness(bright))
.await .await
.unwrap_or_else(|err| warn!("LedBrightDown: {}", err)); .unwrap_or_else(|err| warn!("LedBrightDown: {}", err));
} }
@@ -150,7 +150,7 @@ impl LaptopBase {
}; };
if let Some(data) = config.get_led_mode_data(self.supported_modes[idx_next]) { if let Some(data) = config.get_led_mode_data(self.supported_modes[idx_next]) {
aura_command aura_command
.send(AuraCommand::WriteMode(data.to_owned())) .send(data.to_owned())
.await .await
.unwrap_or_else(|_| {}); .unwrap_or_else(|_| {});
} }
@@ -167,7 +167,7 @@ impl LaptopBase {
}; };
if let Some(data) = config.get_led_mode_data(self.supported_modes[idx_next]) { if let Some(data) = config.get_led_mode_data(self.supported_modes[idx_next]) {
aura_command aura_command
.send(AuraCommand::WriteMode(data.to_owned())) .send(data.to_owned())
.await .await
.unwrap_or_else(|_| {}); .unwrap_or_else(|_| {});
} }

View File

@@ -19,13 +19,6 @@ use std::marker::PhantomData;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::time::Duration; use std::time::Duration;
#[derive(Clone)]
pub enum AuraCommand {
WriteMode(AuraModes),
WriteEffect(Vec<Vec<u8>>),
WriteMultizone(Vec<Vec<u8>>),
}
/// UNSAFE: Must live as long as RogCore /// UNSAFE: Must live as long as RogCore
/// ///
/// Because we're holding a pointer to something that *may* go out of scope while the /// Because we're holding a pointer to something that *may* go out of scope while the
@@ -81,16 +74,11 @@ where
pub async fn do_command( pub async fn do_command(
&mut self, &mut self,
command: AuraCommand, mode: AuraModes,
config: &mut Config, config: &mut Config,
) -> Result<(), AuraError> { ) -> Result<(), AuraError> {
self.initialise().await?; self.initialise().await?;
match command { self.set_and_save(mode, config).await
AuraCommand::WriteMode(mode) => self.set_and_save(mode, config).await?,
AuraCommand::WriteMultizone(effect) => self.write_multizone(effect).await?,
AuraCommand::WriteEffect(effect) => self.write_effect(effect).await?,
}
Ok(())
} }
/// Should only be used if the bytes you are writing are verified correct /// Should only be used if the bytes you are writing are verified correct
@@ -128,25 +116,23 @@ where
Ok(()) Ok(())
} }
#[inline]
async fn write_multizone(&mut self, effect: Vec<Vec<u8>>) -> Result<(), AuraError> {
for row in effect.iter() {
self.write_bytes(row).await?;
}
self.write_bytes(&LED_SET).await?;
self.write_bytes(&LED_APPLY).await?;
Ok(())
}
/// Used to set a builtin mode and save the settings for it /// Used to set a builtin mode and save the settings for it
/// ///
/// This needs to be universal so that settings applied by dbus stick /// This needs to be universal so that settings applied by dbus stick
#[inline] #[inline]
async fn set_and_save(&self, mode: AuraModes, config: &mut Config) -> Result<(), AuraError> { async fn set_and_save(
&mut self,
mode: AuraModes,
config: &mut Config,
) -> Result<(), AuraError> {
match mode { match mode {
AuraModes::Aura => { AuraModes::RGB(v) => {
let bytes = KeyColourArray::get_init_msg(); if v[0].is_empty() {
self.write_bytes(&bytes).await?; let bytes = KeyColourArray::get_init_msg();
self.write_bytes(&bytes).await?;
} else {
self.write_effect(v).await?;
}
return Ok(()); return Ok(());
} }
AuraModes::LedBrightness(n) => { AuraModes::LedBrightness(n) => {

View File

@@ -3,10 +3,8 @@ use daemon::rogcore::FanLevel;
use gumdrop::Options; use gumdrop::Options;
use log::LevelFilter; use log::LevelFilter;
use rog_client::{ use rog_client::{
aura_modes::AuraModes,
cli_options::{LedBrightness, SetAuraBuiltin}, cli_options::{LedBrightness, SetAuraBuiltin},
core_dbus::AuraDbusWriter, core_dbus::AuraDbusWriter,
LED_MSG_LEN,
}; };
use std::io::Write; use std::io::Write;
@@ -61,19 +59,11 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Version: {}", VERSION); println!("Version: {}", VERSION);
} }
let mut writer = AuraDbusWriter::new()?; let writer = AuraDbusWriter::new()?;
if let Some(Command::LedMode(mode)) = parsed.command { if let Some(Command::LedMode(mode)) = parsed.command {
if let Some(command) = mode.command { if let Some(command) = mode.command {
// Check for special modes here, eg, per-key or multi-zone writer.write_builtin_mode(&command.into())?
match command {
SetAuraBuiltin::MultiStatic(_) => {
let command: AuraModes = command.into();
let byte_arr = <[[u8; LED_MSG_LEN]; 4]>::from(command);
writer.write_multizone(&byte_arr)?;
}
_ => writer.write_builtin_mode(&command.into())?,
}
} }
} }
if let Some(brightness) = parsed.bright { if let Some(brightness) = parsed.bright {

View File

@@ -1,16 +1,15 @@
use crate::config::Config; use crate::config::Config;
use crate::daemon::DbusU8Type; use crate::daemon::DbusU8Type;
use crate::led_control::AuraCommand;
use dbus::tree::{Factory, MTSync, Method, MethodErr, Signal, Tree}; use dbus::tree::{Factory, MTSync, Method, MethodErr, Signal, Tree};
use log::warn; use log::warn;
use rog_client::{DBUS_IFACE, DBUS_PATH}; use rog_client::{aura_modes::AuraModes, DBUS_IFACE, DBUS_PATH};
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::{ use tokio::sync::{
mpsc::{channel, Receiver, Sender}, mpsc::{channel, Receiver, Sender},
Mutex, Mutex,
}; };
pub(super) fn dbus_set_ledmsg(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSync, ()> { pub(super) fn dbus_set_ledmsg(sender: Mutex<Sender<AuraModes>>) -> Method<MTSync, ()> {
let factory = Factory::new_sync::<()>(); let factory = Factory::new_sync::<()>();
factory factory
// method for ledmessage // method for ledmessage
@@ -19,8 +18,7 @@ pub(super) fn dbus_set_ledmsg(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSy
let json: &str = m.msg.read1()?; let json: &str = m.msg.read1()?;
if let Ok(mut lock) = sender.try_lock() { if let Ok(mut lock) = sender.try_lock() {
if let Ok(data) = serde_json::from_str(json) { if let Ok(data) = serde_json::from_str(json) {
let command = AuraCommand::WriteMode(data); lock.try_send(data).unwrap_or_else(|err| {
lock.try_send(command).unwrap_or_else(|err| {
warn!("SetKeyBacklight over mpsc failed: {}", err) warn!("SetKeyBacklight over mpsc failed: {}", err)
}); });
} else { } else {
@@ -36,81 +34,6 @@ pub(super) fn dbus_set_ledmsg(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSy
.annotate("org.freedesktop.DBus.Method.NoReply", "true") .annotate("org.freedesktop.DBus.Method.NoReply", "true")
} }
pub(super) fn dbus_set_ledmultizone(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSync, ()> {
let factory = Factory::new_sync::<()>();
factory
// method for ledmessage
.method("LedWriteMultizone", (), {
move |m| {
if let Ok(mut lock) = sender.try_lock() {
let mut iter = m.msg.iter_init();
let byte_array: Vec<Vec<u8>> =
vec![iter.read()?, iter.read()?, iter.read()?, iter.read()?];
let command = AuraCommand::WriteMultizone(byte_array);
lock.try_send(command)
.unwrap_or_else(|err| warn!("LedWriteMultizone over mpsc failed: {}", err));
let mret = m
.msg
.method_return()
.append1(&"Got effect part".to_string());
Ok(vec![mret])
} else {
Err(MethodErr::failed("Could not lock daemon for access"))
}
}
})
.outarg::<&str, _>("reply")
.inarg::<Vec<u8>, _>("bytearray1")
.inarg::<Vec<u8>, _>("bytearray2")
.inarg::<Vec<u8>, _>("bytearray3")
.inarg::<Vec<u8>, _>("bytearray4")
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
}
pub(super) fn dbus_set_ledeffect(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSync, ()> {
let factory = Factory::new_sync::<()>();
factory
// method for ledmessage
.method("LedWriteEffect", (), {
move |m| {
if let Ok(mut lock) = sender.try_lock() {
let mut iter = m.msg.iter_init();
let byte_array: Vec<Vec<u8>> = vec![
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
iter.read()?,
];
let command = AuraCommand::WriteEffect(byte_array);
lock.try_send(command)
.unwrap_or_else(|err| warn!("LedWriteEffect over mpsc failed: {}", err));
Ok(vec![])
} else {
Err(MethodErr::failed("Could not lock daemon for access"))
}
}
})
.inarg::<Vec<u8>, _>("bytearray1")
.inarg::<Vec<u8>, _>("bytearray2")
.inarg::<Vec<u8>, _>("bytearray3")
.inarg::<Vec<u8>, _>("bytearray4")
.inarg::<Vec<u8>, _>("bytearray5")
.inarg::<Vec<u8>, _>("bytearray6")
.inarg::<Vec<u8>, _>("bytearray7")
.inarg::<Vec<u8>, _>("bytearray8")
.inarg::<Vec<u8>, _>("bytearray9")
.inarg::<Vec<u8>, _>("bytearray10")
.inarg::<Vec<u8>, _>("bytearray11")
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
}
pub(super) fn dbus_set_animatrix( pub(super) fn dbus_set_animatrix(
sender: Mutex<Sender<Vec<Vec<u8>>>>, // need mutex only to get interior mutability in MTSync sender: Mutex<Sender<Vec<Vec<u8>>>>, // need mutex only to get interior mutability in MTSync
) -> Method<MTSync, ()> { ) -> Method<MTSync, ()> {
@@ -212,8 +135,8 @@ pub(super) fn dbus_create_tree(
config: Arc<Mutex<Config>>, config: Arc<Mutex<Config>>,
) -> ( ) -> (
Tree<MTSync, ()>, Tree<MTSync, ()>,
Sender<AuraCommand>, Sender<AuraModes>,
Receiver<AuraCommand>, Receiver<AuraModes>,
Receiver<Vec<Vec<u8>>>, Receiver<Vec<Vec<u8>>>,
DbusU8Type, DbusU8Type,
DbusU8Type, DbusU8Type,
@@ -221,7 +144,7 @@ pub(super) fn dbus_create_tree(
Arc<Signal<()>>, Arc<Signal<()>>,
Arc<Signal<()>>, Arc<Signal<()>>,
) { ) {
let (aura_command_send, aura_command_recv) = channel::<AuraCommand>(1); let (aura_command_send, aura_command_recv) = channel::<AuraModes>(1);
let (animatrix_send, animatrix_recv) = channel::<Vec<Vec<u8>>>(1); let (animatrix_send, animatrix_recv) = channel::<Vec<Vec<u8>>>(1);
let fan_mode: DbusU8Type = Arc::new(Mutex::new(None)); let fan_mode: DbusU8Type = Arc::new(Mutex::new(None));
let charge_limit: DbusU8Type = Arc::new(Mutex::new(None)); let charge_limit: DbusU8Type = Arc::new(Mutex::new(None));
@@ -247,8 +170,6 @@ pub(super) fn dbus_create_tree(
factory factory
.interface(DBUS_IFACE, ()) .interface(DBUS_IFACE, ())
.add_m(dbus_set_ledmsg(Mutex::new(aura_command_send.clone()))) .add_m(dbus_set_ledmsg(Mutex::new(aura_command_send.clone())))
.add_m(dbus_set_ledmultizone(Mutex::new(aura_command_send.clone())))
.add_m(dbus_set_ledeffect(Mutex::new(aura_command_send.clone())))
.add_m(dbus_set_animatrix(Mutex::new(animatrix_send))) .add_m(dbus_set_animatrix(Mutex::new(animatrix_send)))
.add_m(dbus_set_fan_mode(fan_mode.clone())) .add_m(dbus_set_fan_mode(fan_mode.clone()))
.add_m(dbus_set_charge_limit(charge_limit.clone())) .add_m(dbus_set_charge_limit(charge_limit.clone()))