Skip to content

Commit

Permalink
Merge branch 'master' into refactor/fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
danieleades authored Feb 21, 2024
2 parents 1c15f97 + 27192d2 commit e40353b
Show file tree
Hide file tree
Showing 16 changed files with 144 additions and 111 deletions.
4 changes: 4 additions & 0 deletions data/com.system76.PowerDaemon.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@
<method name="GetSwitchable">
<arg name="switchable" type="b" direction="out"/>
</method>

<method name="GetDesktop">
<arg name="desktop" type="b" direction="out"/>
</method>

<signal name="HotPlugDetect">
<arg name="port" type="t"/>
Expand Down
8 changes: 4 additions & 4 deletions examples/gpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct GpioCommunity<'a> {
}

impl<'a> GpioCommunity<'a> {
pub fn skylake() -> &'static [GpioCommunity<'static>] {
pub const fn skylake() -> &'static [GpioCommunity<'static>] {
&[
GpioCommunity {
id: 0xAF,
Expand All @@ -42,7 +42,7 @@ impl<'a> GpioCommunity<'a> {
}

#[allow(dead_code)]
pub fn cannonlake() -> &'static [GpioCommunity<'static>] {
pub const fn cannonlake() -> &'static [GpioCommunity<'static>] {
&[
GpioCommunity {
id: 0x6E,
Expand Down Expand Up @@ -77,9 +77,9 @@ fn inner() -> Result<(), SidebandError> {

let sideband = unsafe { Sideband::new(PCR_BASE_ADDRESS)? };

for community in communities.iter() {
for community in communities {
let mut pad = 0;
for group in community.groups.iter() {
for group in community.groups {
for i in 0..group.count {
let data = unsafe { sideband.gpio(community.id, pad) };
let low = data as u32;
Expand Down
97 changes: 63 additions & 34 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ pub struct PowerClient {
}

impl PowerClient {
pub fn new() -> Result<PowerClient, String> {
pub fn new() -> Result<Self, String> {
let bus = Connection::new_system().map_err(err_str)?;
Ok(PowerClient { bus })
Ok(Self { bus })
}

fn call_method<A: Append>(
Expand Down Expand Up @@ -89,6 +89,11 @@ impl Power for PowerClient {
r.get1().ok_or_else(|| "return value not found".to_string())
}

fn get_desktop(&mut self) -> Result<bool, String> {
let r = self.call_method::<bool>("GetDesktop", None)?;
r.get1().ok_or_else(|| "return value not found".to_string())
}

fn set_graphics(&mut self, vendor: &str) -> Result<(), String> {
println!("setting graphics to {}", vendor);
let r = self.call_method::<&str>("SetGraphics", Some(vendor)).map(|_| ());
Expand Down Expand Up @@ -173,44 +178,68 @@ pub fn client(args: &Args) -> Result<(), String> {
let mut client = PowerClient::new()?;

match args {
Args::Profile { profile: name } => match name.as_deref() {
Some("balanced") => client.balanced(),
Some("battery") => client.battery(),
Some("performance") => client.performance(),
_ => profile(&mut client).map_err(err_str),
},
Args::Graphics { cmd } => match cmd.as_ref() {
Some(GraphicsArgs::Compute) => client.set_graphics("compute"),
Some(GraphicsArgs::Hybrid) => client.set_graphics("hybrid"),
Some(GraphicsArgs::Integrated) => client.set_graphics("integrated"),
Some(GraphicsArgs::Nvidia) => client.set_graphics("nvidia"),
Some(GraphicsArgs::Switchable) => {
if client.get_switchable()? {
println!("switchable");
} else {
println!("not switchable");
}
Ok(())
Args::Profile { profile: name } => {
if client.get_desktop()? {
return Err(String::from(
r#"
Power profiles are not supported on desktop computers.
"#,
));
}

match name.as_deref() {
Some("balanced") => client.balanced(),
Some("battery") => client.battery(),
Some("performance") => client.performance(),
_ => profile(&mut client).map_err(err_str),
}
Some(GraphicsArgs::Power { state }) => match state.as_deref() {
Some("auto") => client.auto_graphics_power(),
Some("off") => client.set_graphics_power(false),
Some("on") => client.set_graphics_power(true),
_ => {
if client.get_graphics_power()? {
println!("on (discrete)");
} else {
println!("off (discrete)");
}
Args::Graphics { cmd } => {
if !client.get_switchable()? {
return Err(String::from(
r#"
Graphics switching is not supported on this device, because
this device is either a desktop or doesn't have both an iGPU and dGPU.
"#,
));
}

match cmd.as_ref() {
Some(GraphicsArgs::Compute) => client.set_graphics("compute"),
Some(GraphicsArgs::Hybrid) => client.set_graphics("hybrid"),
Some(GraphicsArgs::Integrated) => client.set_graphics("integrated"),
Some(GraphicsArgs::Nvidia) => client.set_graphics("nvidia"),
Some(GraphicsArgs::Switchable) => client
.get_switchable()
.map(|b| println!("{}", if b { "switchable" } else { "not switchable" })),
Some(GraphicsArgs::Power { state }) => match state.as_deref() {
Some("auto") => client.auto_graphics_power(),
Some("off") => client.set_graphics_power(false),
Some("on") => client.set_graphics_power(true),
_ => {
if client.get_graphics_power()? {
println!("on (discrete)");
} else {
println!("off (discrete)");
}
Ok(())
}
},
None => {
println!("{}", client.get_graphics()?);
Ok(())
}
},
None => {
println!("{}", client.get_graphics()?);
Ok(())
}
},
}
Args::ChargeThresholds { profile, list_profiles, thresholds } => {
if client.get_desktop()? {
return Err(String::from(
r#"
Charge thresholds are not supported on desktop computers.
"#,
));
}

let profiles = client.get_charge_profiles()?;

if !thresholds.is_empty() {
Expand Down
15 changes: 9 additions & 6 deletions src/daemon/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ struct PowerDaemon {
}

impl PowerDaemon {
fn new(dbus_connection: Arc<SyncConnection>) -> Result<PowerDaemon, String> {
fn new(dbus_connection: Arc<SyncConnection>) -> Result<Self, String> {
let graphics = Graphics::new().map_err(err_str)?;
Ok(PowerDaemon {
Ok(Self {
initial_set: false,
graphics,
power_profile: String::new(),
Expand All @@ -110,7 +110,7 @@ impl PowerDaemon {
let message =
Message::new_signal(DBUS_PATH, DBUS_NAME, "PowerProfileSwitch").unwrap().append1(name);

if let Err(()) = self.dbus_connection.send(message) {
if self.dbus_connection.send(message).is_err() {
log::error!("failed to send power profile switch message");
}

Expand Down Expand Up @@ -168,6 +168,8 @@ impl Power for PowerDaemon {

fn get_switchable(&mut self) -> Result<bool, String> { Ok(self.graphics.can_switch()) }

fn get_desktop(&mut self) -> Result<bool, String> { Ok(self.graphics.is_desktop()) }

fn set_graphics(&mut self, vendor: &str) -> Result<(), String> {
let vendor = match vendor {
"nvidia" => GraphicsMode::Discrete,
Expand Down Expand Up @@ -227,7 +229,7 @@ pub async fn daemon() -> Result<(), String> {
let nvidia_exists = !daemon.graphics.nvidia.is_empty();

log::info!("Disabling NMI Watchdog (for kernel debugging only)");
NmiWatchdog::default().set(b"0");
NmiWatchdog.set(b"0");

// Get the NVIDIA device ID before potentially removing it.
let nvidia_device_id = if nvidia_exists {
Expand Down Expand Up @@ -284,6 +286,7 @@ pub async fn daemon() -> Result<(), String> {
sync_set_method(b, "SetGraphics", "vendor", |d, s: String| d.set_graphics(&s));
sync_get_method(b, "GetProfile", "profile", PowerDaemon::get_profile);
sync_get_method(b, "GetSwitchable", "switchable", PowerDaemon::get_switchable);
sync_get_method(b, "GetDesktop", "desktop", PowerDaemon::get_desktop);
sync_get_method(b, "GetGraphicsPower", "power", PowerDaemon::get_graphics_power);
sync_set_method(b, "SetGraphicsPower", "power", PowerDaemon::set_graphics_power);
sync_get_method(b, "GetChargeThresholds", "thresholds", PowerDaemon::get_charge_thresholds);
Expand Down Expand Up @@ -410,7 +413,7 @@ fn sync_action_method<F>(b: &mut IfaceBuilder<PowerDaemon>, name: &'static str,
where
F: Fn(&mut PowerDaemon) -> Result<(), String> + Send + 'static,
{
sync_method(b, name, (), (), move |d, _: ()| f(d));
sync_method(b, name, (), (), move |d, ()| f(d));
}

/// `DBus` wrapper for method taking no arguments and returning one value
Expand All @@ -423,7 +426,7 @@ fn sync_get_method<T, F>(
T: arg::Arg + arg::Append + Debug,
F: Fn(&mut PowerDaemon) -> Result<T, String> + Send + 'static,
{
sync_method(b, name, (), (output_arg,), move |d, _: ()| f(d).map(|x| (x,)));
sync_method(b, name, (), (output_arg,), move |d, ()| f(d).map(|x| (x,)));
}

/// `DBus` wrapper for method taking one argument and returning no values
Expand Down
10 changes: 5 additions & 5 deletions src/daemon/profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub fn balanced(errors: &mut Vec<ProfileError>, set_brightness: bool) {

// Enables the laptop mode feature in the kernel, which allows mechanical drives to spin down
// when inactive.
LaptopMode::default().set(b"2");
LaptopMode.set(b"2");

// Sets radeon power profiles for AMD graphics.
RadeonDevice::get_devices().for_each(|dev| dev.set_profiles("auto", "performance", "auto"));
Expand Down Expand Up @@ -99,7 +99,7 @@ pub fn performance(errors: &mut Vec<ProfileError>, _set_brightness: bool) {
}

Dirty::default().set_max_lost_work(15);
LaptopMode::default().set(b"0");
LaptopMode.set(b"0");
RadeonDevice::get_devices().for_each(|dev| dev.set_profiles("high", "performance", "auto"));
catch!(errors, scsi_host_link_time_pm_policy(&["med_power_with_dipm", "max_performance"]));
crate::cpufreq::set(Profile::Performance, 100);
Expand Down Expand Up @@ -131,7 +131,7 @@ pub fn battery(errors: &mut Vec<ProfileError>, set_brightness: bool) {
}

Dirty::default().set_max_lost_work(15);
LaptopMode::default().set(b"2");
LaptopMode.set(b"2");
RadeonDevice::get_devices().for_each(|dev| dev.set_profiles("low", "battery", "low"));
catch!(errors, scsi_host_link_time_pm_policy(&["min_power", "min_power"]));
crate::cpufreq::set(Profile::Battery, 50);
Expand Down Expand Up @@ -303,7 +303,7 @@ impl ModelProfiles {
let model_line =
fs::read_to_string("/sys/class/dmi/id/product_version").unwrap_or_default();
match model_line.trim() {
"galp5" => Some(ModelProfiles {
"galp5" => Some(Self {
balanced: ModelProfile {
pl1: Some(28),
pl2: None, // galp5 doesn't like setting pl2
Expand All @@ -320,7 +320,7 @@ impl ModelProfiles {
tcc_offset: Some(32), // 68 C
},
}),
"lemp9" => Some(ModelProfiles {
"lemp9" => Some(Self {
balanced: ModelProfile {
pl1: Some(20),
pl2: Some(40), // Upped from 30
Expand Down
10 changes: 5 additions & 5 deletions src/fan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub struct FanDaemon {
impl FanDaemon {
pub fn new(nvidia_exists: bool) -> Self {
let model = fs::read_to_string("/sys/class/dmi/id/product_version").unwrap_or_default();
let mut daemon = FanDaemon {
let mut daemon = Self {
curve: match model.trim() {
"thelio-major-r1" => FanCurve::threadripper2(),
"thelio-major-r2" | "thelio-major-r2.1" | "thelio-major-b1" | "thelio-major-b2"
Expand Down Expand Up @@ -158,7 +158,7 @@ impl FanDaemon {

/// Calculate the correct duty cycle and apply it to all fans
pub fn step(&mut self) {
if let Ok(()) = self.discover() {
if self.discover().is_ok() {
self.set_duty(self.get_temp().and_then(|temp| self.get_duty(temp)));
}
}
Expand All @@ -177,11 +177,11 @@ pub struct FanPoint {
}

impl FanPoint {
pub fn new(temp: i16, duty: u16) -> Self { Self { temp, duty } }
pub const fn new(temp: i16, duty: u16) -> Self { Self { temp, duty } }

/// Find the duty between two points and a given temperature, if the temperature
/// lies within this range.
fn get_duty_between_points(self, next: FanPoint, temp: i16) -> Option<u16> {
fn get_duty_between_points(self, next: Self, temp: i16) -> Option<u16> {
// If the temp matches the next point, return the next point duty
if temp == next.temp {
return Some(next.duty);
Expand All @@ -201,7 +201,7 @@ impl FanPoint {
}

/// Interpolates the current duty with that of the given next point and temperature.
fn interpolate_duties(self, next: FanPoint, temp: i16) -> u16 {
fn interpolate_duties(self, next: Self, temp: i16) -> u16 {
let dtemp = next.temp - self.temp;
let dduty = next.duty - self.duty;

Expand Down
Loading

0 comments on commit e40353b

Please sign in to comment.