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),
MultiStatic(MultiColour),
LedBrightness(u8),
Aura,
// TODO: use a serializable structure for this (KeyColourArray)
RGB(Vec<Vec<u8>>),
}
impl From<SetAuraBuiltin> for AuraModes {

View File

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

View File

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

View File

@@ -2,7 +2,7 @@ use crate::{
animatrix_control::{AniMeWriter, AnimatrixCommand},
config::Config,
laptops::match_laptop,
led_control::{AuraCommand, LedWriter},
led_control::LedWriter,
rog_dbus::dbus_create_tree,
rogcore::*,
};
@@ -188,38 +188,32 @@ pub async fn start_daemon() -> Result<(), Box<dyn Error>> {
while let Some(command) = aura_command_recv.recv().await {
let mut config = config.lock().await;
match &command {
AuraCommand::WriteEffect(_) | AuraCommand::WriteMultizone(_) => led_writer
.do_command(command, &mut config)
.await
.unwrap_or_else(|err| warn!("{:?}", err)),
AuraCommand::WriteMode(mode) => match mode {
AuraModes::Aura => {
led_writer
.do_command(command, &mut config)
.await
.unwrap_or_else(|err| warn!("{:?}", err));
}
_ => {
led_writer
.do_command(command, &mut config)
.await
.unwrap_or_else(|err| warn!("{:?}", err));
connection
.send(
effect_cancel_signal
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.append1(true),
)
.unwrap_or_else(|_| 0);
connection
.send(
effect_cancel_signal
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.append1(false),
)
.unwrap_or_else(|_| 0);
}
},
AuraModes::RGB(_) => {
led_writer
.do_command(command, &mut config)
.await
.unwrap_or_else(|err| warn!("{:?}", err));
}
_ => {
led_writer
.do_command(command, &mut config)
.await
.unwrap_or_else(|err| warn!("{:?}", err));
connection
.send(
effect_cancel_signal
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
.append1(true),
)
.unwrap_or_else(|_| 0);
connection
.send(
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::{
aura_modes::{
AuraModes, BREATHING, COMET, FLASH, HIGHLIGHT, LASER, PULSE, RAIN, RAINBOW, RIPPLE, SINGLE,
@@ -116,7 +116,7 @@ impl LaptopBase {
rogcore: &mut RogCore,
config: &Mutex<Config>,
key_buf: [u8; 32],
mut aura_command: mpsc::Sender<AuraCommand>,
mut aura_command: mpsc::Sender<AuraModes>,
) -> Result<(), AuraError> {
let mut config = config.lock().await;
match FnKeys::from(key_buf[1]) {
@@ -127,7 +127,7 @@ impl LaptopBase {
info!("Increased LED brightness to {:#?}", bright);
}
aura_command
.send(AuraCommand::WriteMode(AuraModes::LedBrightness(bright)))
.send(AuraModes::LedBrightness(bright))
.await
.unwrap_or_else(|err| warn!("LedBrightUp: {}", err));
}
@@ -137,7 +137,7 @@ impl LaptopBase {
bright -= 1;
}
aura_command
.send(AuraCommand::WriteMode(AuraModes::LedBrightness(bright)))
.send(AuraModes::LedBrightness(bright))
.await
.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]) {
aura_command
.send(AuraCommand::WriteMode(data.to_owned()))
.send(data.to_owned())
.await
.unwrap_or_else(|_| {});
}
@@ -167,7 +167,7 @@ impl LaptopBase {
};
if let Some(data) = config.get_led_mode_data(self.supported_modes[idx_next]) {
aura_command
.send(AuraCommand::WriteMode(data.to_owned()))
.send(data.to_owned())
.await
.unwrap_or_else(|_| {});
}

View File

@@ -19,13 +19,6 @@ use std::marker::PhantomData;
use std::ptr::NonNull;
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
///
/// 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(
&mut self,
command: AuraCommand,
mode: AuraModes,
config: &mut Config,
) -> Result<(), AuraError> {
self.initialise().await?;
match command {
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(())
self.set_and_save(mode, config).await
}
/// Should only be used if the bytes you are writing are verified correct
@@ -128,25 +116,23 @@ where
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
///
/// This needs to be universal so that settings applied by dbus stick
#[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 {
AuraModes::Aura => {
let bytes = KeyColourArray::get_init_msg();
self.write_bytes(&bytes).await?;
AuraModes::RGB(v) => {
if v[0].is_empty() {
let bytes = KeyColourArray::get_init_msg();
self.write_bytes(&bytes).await?;
} else {
self.write_effect(v).await?;
}
return Ok(());
}
AuraModes::LedBrightness(n) => {

View File

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

View File

@@ -1,16 +1,15 @@
use crate::config::Config;
use crate::daemon::DbusU8Type;
use crate::led_control::AuraCommand;
use dbus::tree::{Factory, MTSync, Method, MethodErr, Signal, Tree};
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 tokio::sync::{
mpsc::{channel, Receiver, Sender},
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::<()>();
factory
// 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()?;
if let Ok(mut lock) = sender.try_lock() {
if let Ok(data) = serde_json::from_str(json) {
let command = AuraCommand::WriteMode(data);
lock.try_send(command).unwrap_or_else(|err| {
lock.try_send(data).unwrap_or_else(|err| {
warn!("SetKeyBacklight over mpsc failed: {}", err)
});
} else {
@@ -36,81 +34,6 @@ pub(super) fn dbus_set_ledmsg(sender: Mutex<Sender<AuraCommand>>) -> Method<MTSy
.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(
sender: Mutex<Sender<Vec<Vec<u8>>>>, // need mutex only to get interior mutability in MTSync
) -> Method<MTSync, ()> {
@@ -212,8 +135,8 @@ pub(super) fn dbus_create_tree(
config: Arc<Mutex<Config>>,
) -> (
Tree<MTSync, ()>,
Sender<AuraCommand>,
Receiver<AuraCommand>,
Sender<AuraModes>,
Receiver<AuraModes>,
Receiver<Vec<Vec<u8>>>,
DbusU8Type,
DbusU8Type,
@@ -221,7 +144,7 @@ pub(super) fn dbus_create_tree(
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 fan_mode: 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
.interface(DBUS_IFACE, ())
.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_fan_mode(fan_mode.clone()))
.add_m(dbus_set_charge_limit(charge_limit.clone()))