Break config-traits out in to crate

This commit is contained in:
Luke D. Jones
2023-01-07 20:46:00 +13:00
parent ea5e5db490
commit 90b711c7b9
26 changed files with 161 additions and 110 deletions

View File

@@ -1,7 +1,6 @@
use config_traits::{StdConfig, StdConfigLoad3};
use serde_derive::{Deserialize, Serialize};
use crate::config_traits::{StdConfig, StdConfigLoad3};
const CONFIG_FILE: &str = "asusd.conf";
#[derive(Deserialize, Serialize, Default)]
@@ -25,6 +24,10 @@ impl StdConfig for Config {
}
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name() -> &'static str {
CONFIG_FILE
}

View File

@@ -1,191 +0,0 @@
use std::fs::{create_dir, File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;
use log::{error, warn};
use ron::ser::PrettyConfig;
use serde::de::DeserializeOwned;
use serde::Serialize;
const CONFIG_PATH_BASE: &str = "/etc/asusd/";
/// Config file helper traits. Only `new()` and `file_name()` are required to be
/// implemented, the rest are intended to be free methods.
pub trait StdConfig
where
Self: Serialize + DeserializeOwned,
{
fn new() -> Self;
fn file_name() -> &'static str;
fn file_path() -> PathBuf {
let mut config = PathBuf::from(CONFIG_PATH_BASE);
if !config.exists() {
create_dir(config.as_path())
.unwrap_or_else(|e| panic!("Could not create {CONFIG_PATH_BASE} {e}"));
}
config.push(Self::file_name());
config
}
fn file_open() -> File {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(Self::file_path())
.unwrap_or_else(|e| panic!("Could not open {:?} {e}", Self::file_path()))
}
fn read(&mut self) {
let mut file = match OpenOptions::new().read(true).open(Self::file_path()) {
Ok(data) => data,
Err(err) => {
error!("Error reading {:?}: {}", Self::file_path(), err);
return;
}
};
let mut buf = String::new();
if let Ok(l) = file.read_to_string(&mut buf) {
if l == 0 {
warn!("File is empty {:?}", Self::file_path());
} else if let Ok(data) = ron::from_str(&buf) {
*self = data;
} else if let Ok(data) = serde_json::from_str(&buf) {
*self = data;
} else {
warn!("Could not deserialise {:?}", Self::file_path());
}
}
}
fn write(&self) {
let mut file = match File::create(Self::file_path()) {
Ok(data) => data,
Err(e) => {
error!(
"Couldn't overwrite config {:?}, error: {e}",
Self::file_path()
);
return;
}
};
let ron = match ron::ser::to_string_pretty(&self, PrettyConfig::new().depth_limit(4)) {
Ok(data) => data,
Err(e) => {
error!("Parse {:?} to RON failed, error: {e}", Self::file_path());
return;
}
};
file.write_all(ron.as_bytes())
.unwrap_or_else(|err| error!("Could not write config: {}", err));
}
/// Renames the existing file to `<file>-old`
fn rename_file_old() {
warn!(
"Renaming {} to {}-old and recreating config",
Self::file_name(),
Self::file_name()
);
let cfg_old = Self::file_path().to_string_lossy().to_string() + "-old";
std::fs::rename(Self::file_path(), cfg_old).unwrap_or_else(|err| {
error!(
"Could not rename. Please remove {} then restart service: Error {}",
Self::file_name(),
err
)
});
}
}
pub trait StdConfigLoad1<T>
where
T: StdConfig + DeserializeOwned + Serialize,
{
fn load() -> T {
let mut file = T::file_open();
let mut buf = String::new();
let config: T;
if let Ok(read_len) = file.read_to_string(&mut buf) {
if read_len == 0 {
config = T::new();
} else if let Ok(data) = ron::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str(&buf) {
config = data;
} else {
T::rename_file_old();
config = T::new();
}
} else {
config = T::new();
}
config.write();
config
}
}
pub trait StdConfigLoad2<T1, T2>
where
T1: StdConfig + DeserializeOwned + Serialize,
T2: DeserializeOwned + Into<T1>,
{
fn load() -> T1 {
let mut file = T1::file_open();
let mut buf = String::new();
let config: T1;
if let Ok(read_len) = file.read_to_string(&mut buf) {
if read_len == 0 {
config = T1::new();
} else if let Ok(data) = ron::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str::<T2>(&buf) {
config = data.into();
} else {
T1::rename_file_old();
config = T1::new();
}
} else {
config = T1::new();
}
config.write();
config
}
}
pub trait StdConfigLoad3<T1, T2, T3>
where
T1: StdConfig + DeserializeOwned + Serialize,
T2: DeserializeOwned + Into<T1>,
T3: DeserializeOwned + Into<T1>,
{
fn load() -> T1 {
let mut file = T1::file_open();
let mut buf = String::new();
let config: T1;
if let Ok(read_len) = file.read_to_string(&mut buf) {
if read_len == 0 {
config = T1::new();
} else if let Ok(data) = ron::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str(&buf) {
config = data;
} else if let Ok(data) = serde_json::from_str::<T2>(&buf) {
config = data.into();
} else if let Ok(data) = serde_json::from_str::<T3>(&buf) {
config = data.into();
} else {
T1::rename_file_old();
config = T1::new();
}
} else {
config = T1::new();
}
config.write();
config
}
}

View File

@@ -1,11 +1,10 @@
use std::time::Duration;
use config_traits::{StdConfig, StdConfigLoad3};
use rog_anime::error::AnimeError;
use rog_anime::{ActionData, ActionLoader, AnimTime, AnimeType, Fade, Vec2};
use serde_derive::{Deserialize, Serialize};
use crate::config_traits::{StdConfig, StdConfigLoad3};
const CONFIG_FILE: &str = "anime.conf";
#[derive(Deserialize, Serialize)]
@@ -141,6 +140,10 @@ impl StdConfig for AnimeConfig {
Self::create_default()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name() -> &'static str {
CONFIG_FILE
}

View File

@@ -2,6 +2,7 @@ use std::sync::atomic::Ordering;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{info, warn};
use rog_anime::usb::{pkt_for_apply, pkt_for_set_boot, pkt_for_set_on};
use rog_anime::{AnimeDataBuffer, AnimePowerStates};
@@ -9,7 +10,6 @@ use zbus::export::futures_util::lock::{Mutex, MutexGuard};
use zbus::{dbus_interface, Connection, SignalContext};
use super::CtrlAnime;
use crate::config_traits::StdConfig;
use crate::error::RogError;
pub(super) const ZBUS_PATH: &str = "/org/asuslinux/Anime";

View File

@@ -1,5 +1,6 @@
use std::collections::{BTreeMap, HashSet};
use config_traits::{StdConfig, StdConfigLoad1};
use rog_aura::aura_detection::{LaptopLedData, ASUS_KEYBOARD_DEVICES};
use rog_aura::usb::{AuraDev1866, AuraDev19b6, AuraDevTuf, AuraDevice, AuraPowerDev};
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Direction, LedBrightness, Speed, GRADIENT};
@@ -7,8 +8,6 @@ use rog_platform::hid_raw::HidRaw;
use rog_platform::keyboard_led::KeyboardLed;
use serde_derive::{Deserialize, Serialize};
use crate::config_traits::{StdConfig, StdConfigLoad1};
const CONFIG_FILE: &str = "aura.conf";
/// Enable/disable LED control in various states such as
@@ -191,6 +190,10 @@ impl StdConfig for AuraConfig {
Self::create_default(&LaptopLedData::get_data())
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name() -> &'static str {
CONFIG_FILE
}

View File

@@ -1,5 +1,6 @@
use std::collections::BTreeMap;
use config_traits::StdConfig;
use log::{info, warn};
use rog_aura::advanced::{LedUsbPackets, UsbPackets};
use rog_aura::aura_detection::{LaptopLedData, ASUS_KEYBOARD_DEVICES};
@@ -10,7 +11,6 @@ use rog_platform::keyboard_led::KeyboardLed;
use rog_platform::supported::LedSupportedFunctions;
use super::config::{AuraConfig, AuraPowerConfig};
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::GetSupported;

View File

@@ -2,6 +2,7 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_aura::advanced::UsbPackets;
use rog_aura::usb::AuraPowerDev;
@@ -11,7 +12,6 @@ use zbus::export::futures_util::StreamExt;
use zbus::{dbus_interface, Connection, SignalContext};
use super::controller::CtrlKbdLed;
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::CtrlTask;

View File

@@ -5,6 +5,7 @@ use std::process::Command;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{info, warn};
use rog_platform::platform::{AsusPlatform, GpuMode};
use rog_platform::supported::RogBiosSupportedFunctions;
@@ -12,7 +13,6 @@ use zbus::export::futures_util::lock::Mutex;
use zbus::{dbus_interface, Connection, SignalContext};
use crate::config::Config;
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::{task_watch_item, CtrlTask, GetSupported};

View File

@@ -3,6 +3,7 @@ use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_platform::power::AsusPower;
use rog_platform::supported::ChargeSupportedFunctions;
@@ -12,7 +13,6 @@ use zbus::export::futures_util::lock::Mutex;
use zbus::{dbus_interface, Connection, SignalContext};
use crate::config::Config;
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::{task_watch_item, CtrlTask, GetSupported};

View File

@@ -1,7 +1,11 @@
use std::path::PathBuf;
use config_traits::{StdConfig, StdConfigLoad1};
use rog_profiles::fan_curve_set::FanCurveSet;
use rog_profiles::{FanCurveProfiles, Profile};
use serde_derive::{Deserialize, Serialize};
use crate::config_traits::{StdConfig, StdConfigLoad1};
use crate::CONFIG_PATH_BASE;
const CONFIG_FILE: &str = "profile.conf";
const CONFIG_FAN_FILE: &str = "fan_curves.conf";
@@ -19,6 +23,10 @@ impl StdConfig for ProfileConfig {
}
}
fn config_dir() -> std::path::PathBuf {
PathBuf::from(CONFIG_PATH_BASE)
}
fn file_name() -> &'static str {
CONFIG_FILE
}
@@ -26,9 +34,46 @@ impl StdConfig for ProfileConfig {
impl StdConfigLoad1<ProfileConfig> for ProfileConfig {}
impl StdConfig for FanCurveProfiles {
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct FanCurveConfig {
balanced: FanCurveSet,
performance: FanCurveSet,
quiet: FanCurveSet,
#[serde(skip)]
device: FanCurveProfiles,
}
impl FanCurveConfig {
pub fn update_device_config(&mut self) {
self.balanced = self.device.balanced.clone();
self.performance = self.device.performance.clone();
self.quiet = self.device.quiet.clone();
}
pub fn update_config(&mut self) {
self.balanced = self.device.balanced.clone();
self.performance = self.device.performance.clone();
self.quiet = self.device.quiet.clone();
}
pub fn device(&self) -> &FanCurveProfiles {
&self.device
}
pub fn device_mut(&mut self) -> &mut FanCurveProfiles {
&mut self.device
}
}
impl StdConfig for FanCurveConfig {
fn new() -> Self {
Self::default()
let mut tmp = Self::default();
tmp.update_device_config();
tmp
}
fn config_dir() -> std::path::PathBuf {
PathBuf::from(CONFIG_PATH_BASE)
}
fn file_name() -> &'static str {
@@ -36,4 +81,4 @@ impl StdConfig for FanCurveProfiles {
}
}
impl StdConfigLoad1<ProfileConfig> for FanCurveProfiles {}
impl StdConfigLoad1<ProfileConfig> for FanCurveConfig {}

View File

@@ -1,17 +1,17 @@
use config_traits::StdConfig;
use log::{info, warn};
use rog_platform::platform::AsusPlatform;
use rog_platform::supported::PlatformProfileFunctions;
use rog_profiles::error::ProfileError;
use rog_profiles::{FanCurveProfiles, Profile};
use super::config::ProfileConfig;
use crate::config_traits::StdConfig;
use super::config::{FanCurveConfig, ProfileConfig};
use crate::error::RogError;
use crate::GetSupported;
pub struct CtrlPlatformProfile {
pub profile_config: ProfileConfig,
pub fan_config: Option<FanCurveProfiles>,
pub fan_config: Option<FanCurveConfig>,
pub platform: AsusPlatform,
}
@@ -69,7 +69,7 @@ impl CtrlPlatformProfile {
if let Some(curves) = controller.fan_config.as_ref() {
info!(
"{active:?}: {}",
String::from(curves.get_fan_curves_for(active))
String::from(curves.device().get_fan_curves_for(active))
);
curves.write();
}
@@ -83,9 +83,10 @@ impl CtrlPlatformProfile {
Err(ProfileError::NotSupported.into())
}
pub fn save_config(&self) {
pub fn save_config(&mut self) {
self.profile_config.write();
if let Some(fans) = self.fan_config.as_ref() {
if let Some(fans) = self.fan_config.as_mut() {
fans.update_config();
fans.write();
}
}
@@ -116,7 +117,7 @@ impl CtrlPlatformProfile {
pub(super) fn write_profile_curve_to_platform(&mut self) -> Result<(), RogError> {
if let Some(curves) = &mut self.fan_config {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.write_profile_curve_to_platform(
curves.device_mut().write_profile_curve_to_platform(
self.profile_config.active_profile,
&mut device,
)?;
@@ -128,10 +129,11 @@ impl CtrlPlatformProfile {
pub(super) fn set_active_curve_to_defaults(&mut self) -> Result<(), RogError> {
if let Some(curves) = self.fan_config.as_mut() {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.set_active_curve_to_defaults(
curves.device_mut().set_active_curve_to_defaults(
self.profile_config.active_profile,
&mut device,
)?;
curves.update_config();
}
}
Ok(())

View File

@@ -2,6 +2,7 @@ use std::str::FromStr;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_profiles::fan_curve_set::{CurveData, FanCurveSet};
use rog_profiles::{FanCurveProfiles, Profile};
@@ -11,7 +12,6 @@ use zbus::fdo::Error;
use zbus::{dbus_interface, Connection, SignalContext};
use super::controller::CtrlPlatformProfile;
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::CtrlTask;
@@ -82,8 +82,8 @@ impl ProfileZbus {
async fn enabled_fan_profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &ctrl.fan_config {
return Ok(curves.get_enabled_curve_profiles());
if let Some(curves) = &mut ctrl.fan_config {
return Ok(curves.device().get_enabled_curve_profiles());
}
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
}
@@ -98,7 +98,10 @@ impl ProfileZbus {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_config {
curves.set_profile_curve_enabled(profile, enabled);
curves
.device_mut()
.set_profile_curve_enabled(profile, enabled);
curves.update_config();
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("write_profile_curve_to_platform, {}", e))
@@ -115,8 +118,8 @@ impl ProfileZbus {
async fn fan_curve_data(&mut self, profile: Profile) -> zbus::fdo::Result<FanCurveSet> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &ctrl.fan_config {
let curve = curves.get_fan_curves_for(profile);
if let Some(curves) = &mut ctrl.fan_config {
let curve = curves.device().get_fan_curves_for(profile);
return Ok(curve.clone());
}
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
@@ -129,8 +132,10 @@ impl ProfileZbus {
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_config {
curves
.device_mut()
.save_fan_curve(curve, profile)
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
curves.update_config();
} else {
return Err(Error::Failed(UNSUPPORTED_MSG.to_owned()));
}
@@ -295,7 +300,10 @@ impl crate::Reloadable for ProfileZbus {
// There is a possibility that the curve was default zeroed, so this call
// initialises the data from system read and we need to save it
// after
curves.write_profile_curve_to_platform(active, &mut device)?;
curves
.device_mut()
.write_profile_curve_to_platform(active, &mut device)?;
curves.update_config();
ctrl.profile_config.write();
}
}

View File

@@ -6,8 +6,8 @@ use std::time::Duration;
use ::zbus::export::futures_util::lock::Mutex;
use ::zbus::Connection;
use config_traits::{StdConfigLoad1, StdConfigLoad3};
use daemon::config::Config;
use daemon::config_traits::{StdConfigLoad1, StdConfigLoad3};
use daemon::ctrl_anime::config::AnimeConfig;
use daemon::ctrl_anime::trait_impls::CtrlAnimeZbus;
use daemon::ctrl_anime::CtrlAnime;

View File

@@ -1,8 +1,6 @@
#![deny(unused_must_use)]
/// Configuration loading, saving
pub mod config;
/// Base traits for configuration file loading
pub mod config_traits;
/// Control of anime matrix display
pub mod ctrl_anime;
/// Keyboard LED brightness control, RGB, and LED display modes
@@ -30,6 +28,8 @@ use zbus::{Connection, SignalContext};
use crate::error::RogError;
const CONFIG_PATH_BASE: &str = "/etc/asusd/";
/// This macro adds a function which spawns an `inotify` task on the passed in
/// `Executor`.
///