Total refactor of structure. Builds faster

This commit is contained in:
Luke
2020-04-21 22:51:53 +12:00
parent e21a6e3fb3
commit a38541ba4b
18 changed files with 479 additions and 1171 deletions

View File

@@ -1,118 +0,0 @@
use crate::{DBUS_IFACE, DBUS_PATH};
use dbus::{
blocking::Connection,
tree::{Factory, MethodErr},
};
use log::{error, info, warn};
use rog_lib::{
core::RogCore,
laptops::{match_laptop, LaptopRunner},
};
use std::error::Error;
use std::time::Duration;
use std::{cell::RefCell, rc::Rc};
pub(crate) struct Daemon {
rogcore: RogCore,
laptop: Box<dyn LaptopRunner>,
}
impl Daemon {
pub(crate) fn new() -> Self {
let laptop = match_laptop();
Daemon {
rogcore: RogCore::new(&*laptop).map_or_else(
|err| {
error!("{}", err);
panic!("{}", err);
},
|daemon| {
info!("RogCore loaded");
daemon
},
),
laptop,
}
}
pub(crate) fn start() -> Result<(), Box<dyn Error>> {
let mut connection = Connection::new_system().map_or_else(
|err| {
error!("{:?}", err);
panic!("{:?}", err);
},
|dbus| {
info!("DBus connected");
dbus
},
);
connection.request_name(DBUS_IFACE, false, true, false)?;
let factory = Factory::new_fnmut::<()>();
let daemon = Self::new();
let daemon = Rc::new(RefCell::new(daemon));
// We create a tree with one object path inside and make that path introspectable.
let tree = factory.tree(()).add(
factory.object_path(DBUS_PATH, ()).introspectable().add(
// We add an interface to the object path...
factory
.interface(DBUS_IFACE, ())
// ...and a method inside the interface
.add_m(
factory
.method("ledmessage", (), {
let daemon = daemon.clone();
move |m| {
// Reads the args passed to the method
let bytes: Vec<u8> = m.msg.read1()?;
let supported =
Vec::from(daemon.borrow().laptop.supported_modes());
match daemon
.borrow_mut()
.rogcore
.aura_set_and_save(&supported, &bytes[..])
{
Ok(_) => {
let s = format!("Wrote {:x?}", bytes);
let mret = m.msg.method_return().append1(&s);
Ok(vec![mret])
}
Err(err) => {
warn!("{:?}", err);
Err(MethodErr::failed(&err))
}
}
}
})
// Input?
.outarg::<&str, _>("reply")
.inarg::<Vec<u8>, _>("bytearray"),
),
),
);
// We add the tree to the connection so that incoming method calls will be handled.
tree.start_receive(&connection);
loop {
connection
.process(Duration::from_millis(10))
.unwrap_or_else(|err| {
error!("{:?}", err);
false
});
// TODO: this needs to move to a thread, but there is unsafety
let borrowed_daemon = daemon.borrow_mut();
let mut rogcore = unsafe { &mut (*daemon.as_ptr()).rogcore };
borrowed_daemon
.laptop
.run(&mut rogcore)
.unwrap_or_else(|err| {
error!("{:?}", err);
});
}
}
}

View File

@@ -1,85 +0,0 @@
mod daemon;
use crate::daemon::*;
use dbus::Error as DbusError;
use dbus::{ffidisp::Connection, Message};
use env_logger::{Builder, Target};
use gumdrop::Options;
use log::LevelFilter;
use rog_lib::{
cli_options::SetAuraBuiltin,
core::{LedBrightness, RogCore, LED_MSG_LEN},
};
pub static DBUS_NAME: &'static str = "org.rogcore.Daemon";
pub static DBUS_PATH: &'static str = "/org/rogcore/Daemon";
pub static DBUS_IFACE: &'static str = "org.rogcore.Daemon";
#[derive(Debug, Options)]
struct CLIStart {
#[options(help = "print help message")]
help: bool,
#[options(help = "start daemon")]
daemon: bool,
#[options(meta = "VAL", help = "<off, low, med, high>")]
bright: Option<LedBrightness>,
#[options(command)]
command: Option<Command>,
}
#[derive(Debug, Options)]
enum Command {
#[options(help = "Set the keyboard lighting from built-in modes")]
LedMode(LedModeCommand),
}
#[derive(Debug, Options)]
struct LedModeCommand {
#[options(help = "print help message")]
help: bool,
#[options(command, required)]
command: Option<SetAuraBuiltin>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut builder = Builder::from_env("ROGCORE_LOG");
builder.target(Target::Stdout);
builder.format_timestamp(None);
builder.filter(None, LevelFilter::Info).init();
let parsed = CLIStart::parse_args_default_or_exit();
if parsed.daemon {
Daemon::start()?;
}
match parsed.command {
Some(Command::LedMode(mode)) => {
if let Some(command) = mode.command {
let mode = <[u8; LED_MSG_LEN]>::from(command);
dbus_led_builtin_write(&mode)?;
}
}
None => {}
}
match parsed.bright {
Some(brightness) => {
let bytes = RogCore::aura_brightness_bytes(brightness.level())?;
dbus_led_builtin_write(&bytes)?;
}
_ => {}
}
Ok(())
}
pub fn dbus_led_builtin_write(bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
let bus = Connection::new_system()?;
//let proxy = bus.with_proxy(DBUS_IFACE, "/", Duration::from_millis(5000));
let msg = Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "ledmessage")?
.append1(bytes.to_vec());
let r = bus.send_with_reply_and_block(msg, 5000)?;
if let Some(reply) = r.get1::<&str>() {
println!("Success: {:x?}", reply);
return Ok(());
}
Err(Box::new(DbusError::new_custom("name", "message")))
}