Config files use generic traits

This commit is contained in:
Luke D. Jones
2023-01-06 12:03:12 +13:00
parent 54273cfb60
commit e4f79a3e6f
18 changed files with 314 additions and 333 deletions

View File

@@ -1,90 +1,42 @@
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::path::PathBuf;
use log::{error, warn};
use rog_profiles::{FanCurveProfiles, Profile};
use serde_derive::{Deserialize, Serialize};
use crate::{config_file, config_file_open};
use crate::config_traits::{StdConfig, StdConfigLoad1};
static CONFIG_FILE: &str = "profile.conf";
const CONFIG_FILE: &str = "profile.conf";
const CONFIG_FAN_FILE: &str = "fan_curves.conf";
#[derive(Deserialize, Serialize, Debug)]
pub struct ProfileConfig {
#[serde(skip)]
config_path: PathBuf,
/// For restore on boot
pub active_profile: Profile,
/// States to restore
pub fan_curves: Option<FanCurveProfiles>,
}
impl ProfileConfig {
fn new(config_path: PathBuf) -> Self {
impl StdConfig for ProfileConfig {
fn new() -> Self {
Self {
config_path,
active_profile: Profile::Balanced,
fan_curves: None,
}
}
pub fn load() -> Self {
let config_path = config_file(CONFIG_FILE);
let mut file = config_file_open(CONFIG_FILE);
let mut buf = String::new();
let mut config;
if let Ok(read_len) = file.read_to_string(&mut buf) {
if read_len == 0 {
config = Self::new(config_path);
} else if let Ok(data) = toml::from_str(&buf) {
config = data;
config.config_path = config_path;
} else {
warn!(
"Could not deserialise {config_path:?}.\nWill rename to {config_path:?}-old \
and recreate config",
);
let mut cfg_old = config_path.clone();
cfg_old.push("-old");
std::fs::rename(config_path.clone(), cfg_old).unwrap_or_else(|err| {
panic!(
"Could not rename. Please remove {config_path:?} then restart service: \
Error {err}",
)
});
config = Self::new(config_path);
}
} else {
config = Self::new(config_path);
}
config
}
pub fn read(&mut self) {
let mut file = OpenOptions::new()
.read(true)
.open(&self.config_path)
.unwrap_or_else(|err| panic!("Error reading {:?}: {}", self.config_path, err));
let mut buf = String::new();
if let Ok(l) = file.read_to_string(&mut buf) {
if l == 0 {
warn!("File is empty {:?}", self.config_path);
} else {
let mut data: ProfileConfig = toml::from_str(&buf)
.unwrap_or_else(|_| panic!("Could not deserialise {:?}", self.config_path));
// copy over serde skipped values
data.config_path = self.config_path.clone();
*self = data;
}
}
}
pub fn write(&self) {
let mut file = File::create(&self.config_path).expect("Couldn't overwrite config");
let data = toml::to_string(self).expect("Parse config to toml failed");
file.write_all(data.as_bytes())
.unwrap_or_else(|err| error!("Could not write config: {}", err));
fn file_name() -> &'static str {
CONFIG_FILE
}
}
impl StdConfigLoad1<ProfileConfig> for ProfileConfig {}
impl StdConfig for FanCurveProfiles {
fn new() -> Self {
Self::default()
}
fn file_name() -> &'static str {
CONFIG_FAN_FILE
}
}
impl StdConfigLoad1<ProfileConfig> for FanCurveProfiles {}

View File

@@ -5,11 +5,12 @@ use rog_profiles::error::ProfileError;
use rog_profiles::{FanCurveProfiles, Profile};
use super::config::ProfileConfig;
use crate::config_traits::StdConfig;
use crate::error::RogError;
use crate::GetSupported;
pub struct CtrlPlatformProfile {
pub config: ProfileConfig,
pub profile_config: ProfileConfig,
pub platform: AsusPlatform,
}
@@ -50,17 +51,17 @@ impl CtrlPlatformProfile {
if platform.has_platform_profile() || platform.has_throttle_thermal_policy() {
info!("Device has profile control available");
let mut controller = CtrlPlatformProfile { config, platform };
let mut controller = CtrlPlatformProfile { profile_config: config, platform };
if FanCurveProfiles::get_device().is_ok() {
info!("Device has fan curves available");
if controller.config.fan_curves.is_none() {
controller.config.fan_curves = Some(Default::default());
if controller.profile_config.fan_curves.is_none() {
controller.profile_config.fan_curves = Some(Default::default());
for _ in [Profile::Balanced, Profile::Performance, Profile::Quiet] {
controller.set_next_profile()?;
controller.set_active_curve_to_defaults()?;
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
if let Some(curves) = controller.config.fan_curves.as_ref() {
if let Some(curves) = controller.profile_config.fan_curves.as_ref() {
info!(
"{active:?}: {}",
String::from(curves.get_fan_curves_for(active))
@@ -77,25 +78,25 @@ impl CtrlPlatformProfile {
}
pub fn save_config(&self) {
self.config.write();
self.profile_config.write();
}
/// Toggle to next profile in list. This will first read the config, switch,
/// then write out
pub(super) fn set_next_profile(&mut self) -> Result<(), RogError> {
// Read first just incase the user has modified the config before calling this
match self.config.active_profile {
match self.profile_config.active_profile {
Profile::Balanced => {
Profile::set_profile(Profile::Performance)?;
self.config.active_profile = Profile::Performance;
self.profile_config.active_profile = Profile::Performance;
}
Profile::Performance => {
Profile::set_profile(Profile::Quiet)?;
self.config.active_profile = Profile::Quiet;
self.profile_config.active_profile = Profile::Quiet;
}
Profile::Quiet => {
Profile::set_profile(Profile::Balanced)?;
self.config.active_profile = Profile::Balanced;
self.profile_config.active_profile = Profile::Balanced;
}
}
self.write_profile_curve_to_platform()?;
@@ -104,18 +105,18 @@ impl CtrlPlatformProfile {
/// Set the curve for the active profile active
pub(super) fn write_profile_curve_to_platform(&mut self) -> Result<(), RogError> {
if let Some(curves) = &mut self.config.fan_curves {
if let Some(curves) = &mut self.profile_config.fan_curves {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.write_profile_curve_to_platform(self.config.active_profile, &mut device)?;
curves.write_profile_curve_to_platform(self.profile_config.active_profile, &mut device)?;
}
}
Ok(())
}
pub(super) fn set_active_curve_to_defaults(&mut self) -> Result<(), RogError> {
if let Some(curves) = self.config.fan_curves.as_mut() {
if let Some(curves) = self.profile_config.fan_curves.as_mut() {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.set_active_curve_to_defaults(self.config.active_profile, &mut device)?;
curves.set_active_curve_to_defaults(self.profile_config.active_profile, &mut device)?;
}
}
Ok(())

View File

@@ -10,6 +10,7 @@ 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;
@@ -40,7 +41,7 @@ impl ProfileZbus {
.unwrap_or_else(|err| warn!("{}", err));
ctrl.save_config();
Self::notify_profile(&ctxt, ctrl.config.active_profile)
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
.await
.ok();
}
@@ -48,8 +49,8 @@ impl ProfileZbus {
/// Fetch the active profile name
async fn active_profile(&mut self) -> zbus::fdo::Result<Profile> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
Ok(ctrl.config.active_profile)
ctrl.profile_config.read();
Ok(ctrl.profile_config.active_profile)
}
/// Set this platform_profile name as active
@@ -60,18 +61,18 @@ impl ProfileZbus {
) {
let mut ctrl = self.0.lock().await;
// Read first just incase the user has modified the config before calling this
ctrl.config.read();
ctrl.profile_config.read();
Profile::set_profile(profile)
.map_err(|e| warn!("set_profile, {}", e))
.ok();
ctrl.config.active_profile = profile;
ctrl.profile_config.active_profile = profile;
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("write_profile_curve_to_platform, {}", e))
.ok();
ctrl.save_config();
Self::notify_profile(&ctxt, ctrl.config.active_profile)
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
.await
.ok();
}
@@ -79,8 +80,8 @@ impl ProfileZbus {
/// Get a list of profiles that have fan-curves enabled.
async fn enabled_fan_profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
if let Some(curves) = &ctrl.config.fan_curves {
ctrl.profile_config.read();
if let Some(curves) = &ctrl.profile_config.fan_curves {
return Ok(curves.get_enabled_curve_profiles());
}
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
@@ -94,8 +95,8 @@ impl ProfileZbus {
enabled: bool,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
if let Some(curves) = &mut ctrl.config.fan_curves {
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.profile_config.fan_curves {
curves.set_profile_curve_enabled(profile, enabled);
ctrl.write_profile_curve_to_platform()
@@ -112,8 +113,8 @@ impl ProfileZbus {
/// Get the fan-curve data for the currently active Profile
async fn fan_curve_data(&mut self, profile: Profile) -> zbus::fdo::Result<FanCurveSet> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
if let Some(curves) = &ctrl.config.fan_curves {
ctrl.profile_config.read();
if let Some(curves) = &ctrl.profile_config.fan_curves {
let curve = curves.get_fan_curves_for(profile);
return Ok(curve.clone());
}
@@ -124,8 +125,8 @@ impl ProfileZbus {
/// Will also activate the fan curve if the user is in the same mode.
async fn set_fan_curve(&self, profile: Profile, curve: CurveData) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
if let Some(curves) = &mut ctrl.config.fan_curves {
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.profile_config.fan_curves {
curves
.save_fan_curve(curve, profile)
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
@@ -147,7 +148,7 @@ impl ProfileZbus {
/// read only for the currently active profile.
async fn set_active_curve_to_defaults(&self) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
ctrl.profile_config.read();
ctrl.set_active_curve_to_defaults()
.map_err(|e| warn!("Profile::set_active_curve_to_defaults, {}", e))
.ok();
@@ -162,7 +163,7 @@ impl ProfileZbus {
/// read only for the currently active profile.
async fn reset_profile_curves(&self, profile: Profile) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.config.read();
ctrl.profile_config.read();
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
Profile::set_profile(profile)
@@ -215,14 +216,14 @@ impl CtrlTask for ProfileZbus {
let mut lock = ctrl.lock().await;
let new_thermal = lock.platform.get_throttle_thermal_policy().unwrap();
let new_profile = Profile::from_throttle_thermal_policy(new_thermal);
if new_profile != lock.config.active_profile {
if new_profile != lock.profile_config.active_profile {
info!("throttle_thermal_policy changed to {new_profile}");
lock.config.active_profile = new_profile;
lock.profile_config.active_profile = new_profile;
lock.write_profile_curve_to_platform().unwrap();
lock.save_config();
Profile::set_profile(lock.config.active_profile).unwrap();
Profile::set_profile(lock.profile_config.active_profile).unwrap();
}
Self::notify_profile(&signal_ctxt, lock.config.active_profile)
Self::notify_profile(&signal_ctxt, lock.profile_config.active_profile)
.await
.ok();
})
@@ -238,14 +239,14 @@ impl crate::Reloadable for ProfileZbus {
/// Fetch the active profile and use that to set all related components up
async fn reload(&mut self) -> Result<(), RogError> {
let mut ctrl = self.0.lock().await;
let active = ctrl.config.active_profile;
if let Some(curves) = &mut ctrl.config.fan_curves {
let active = ctrl.profile_config.active_profile;
if let Some(curves) = &mut ctrl.profile_config.fan_curves {
if let Ok(mut device) = FanCurveProfiles::get_device() {
// 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)?;
ctrl.config.write();
ctrl.profile_config.write();
}
}
Ok(())