manager: Implement new API

This commit is contained in:
Vicki Pfau 2024-03-28 16:23:31 -07:00
parent 6a5e693e5b
commit 69e6477053
5 changed files with 419 additions and 196 deletions

View file

@ -6,99 +6,180 @@
*/
use anyhow::Result;
use std::fmt;
use tokio::fs::File;
use tracing::{error, warn};
use tracing::error;
use zbus::{interface, zvariant::Fd};
use crate::hardware::{variant, HardwareVariant};
use crate::power::{set_gpu_clocks, set_gpu_performance_level, set_tdp_limit};
use crate::hardware::{check_support, variant, HardwareCurrentlySupported, HardwareVariant};
use crate::power::{
get_gpu_performance_level, set_gpu_clocks, set_gpu_performance_level, set_tdp_limit,
GPUPerformanceLevel,
};
use crate::process::{run_script, script_output, SYSTEMCTL_PATH};
use crate::wifi::{restart_iwd, setup_iwd_config, start_tracing, stop_tracing, WifiDebugMode};
use crate::wifi::{set_wifi_debug_mode, WifiDebugMode, WifiPowerManagement};
pub struct SMManager {
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
enum PrepareFactoryReset {
Unknown = 0,
RebootRequired = 1,
}
#[derive(PartialEq, Debug, Copy, Clone)]
#[repr(u32)]
enum FanControl {
UnsupportedFeature = 0,
BIOS = 1,
OS = 2,
}
impl TryFrom<u32> for FanControl {
type Error = &'static str;
fn try_from(v: u32) -> Result<Self, Self::Error> {
match v {
x if x == FanControl::UnsupportedFeature as u32 => Ok(FanControl::UnsupportedFeature),
x if x == FanControl::BIOS as u32 => Ok(FanControl::BIOS),
x if x == FanControl::OS as u32 => Ok(FanControl::BIOS),
_ => Err("No enum match for value {v}"),
}
}
}
impl fmt::Display for FanControl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FanControl::UnsupportedFeature => write!(f, "Unsupported feature"),
FanControl::BIOS => write!(f, "BIOS"),
FanControl::OS => write!(f, "OS"),
}
}
}
pub struct SteamOSManager {
wifi_debug_mode: WifiDebugMode,
// Whether we should use trace-cmd or not.
// True on galileo devices, false otherwise
should_trace: bool,
}
impl SMManager {
impl SteamOSManager {
pub async fn new() -> Result<Self> {
Ok(SMManager {
Ok(SteamOSManager {
wifi_debug_mode: WifiDebugMode::Off,
should_trace: variant().await? == HardwareVariant::Galileo,
})
}
}
const MIN_BUFFER_SIZE: u32 = 100;
const ALS_INTEGRATION_PATH: &str = "/sys/devices/platform/AMDI0010:00/i2c-0/i2c-PRP0001:01/iio:device0/in_illuminance_integration_time";
#[interface(name = "com.steampowered.SteamOSManager1")]
impl SMManager {
const API_VERSION: u32 = 1;
#[interface(name = "com.steampowered.SteamOSManager1.Manager")]
impl SteamOSManager {
const API_VERSION: u32 = 7;
async fn say_hello(&self, name: &str) -> String {
format!("Hello {}!", name)
}
async fn factory_reset(&self) -> bool {
async fn prepare_factory_reset(&self) -> u32 {
// Run steamos factory reset script and return true on success
run_script(
let res = run_script(
"factory reset",
"/usr/bin/steamos-factory-reset-config",
&[""],
)
.await
.unwrap_or(false)
}
async fn disable_wifi_power_management(&self) -> bool {
// Run polkit helper script and return true on success
run_script(
"disable wifi power management",
"/usr/bin/steamos-polkit-helpers/steamos-disable-wireless-power-management",
&[""],
)
.await
.unwrap_or(false)
}
async fn enable_fan_control(&self, enable: bool) -> bool {
// Run what steamos-polkit-helpers/jupiter-fan-control does
if enable {
run_script(
"enable fan control",
SYSTEMCTL_PATH,
&["start", "jupiter-fan-control-service"],
)
.await
.unwrap_or(false)
} else {
run_script(
"disable fan control",
SYSTEMCTL_PATH,
&["stop", "jupiter-fan-control.service"],
)
.await
.unwrap_or(false)
.unwrap_or(false);
match res {
true => PrepareFactoryReset::RebootRequired as u32,
false => PrepareFactoryReset::Unknown as u32,
}
}
async fn hardware_check_support(&self) -> bool {
// Run jupiter-check-support note this script does exit 1 for "Support: No" case
// so no need to parse output, etc.
run_script(
"check hardware support",
"/usr/bin/jupiter-check-support",
&[""],
)
.await
.unwrap_or(false)
#[zbus(property)]
fn wifi_power_management_state(&self) -> u32 {
WifiPowerManagement::UnsupportedFeature as u32 // TODO
}
async fn read_als_calibration(&self) -> f32 {
#[zbus(property)]
async fn set_wifi_power_management_state(&self, state: u32) -> zbus::Result<()> {
let state = match WifiPowerManagement::try_from(state) {
Ok(state) => state,
Err(err) => return Err(zbus::fdo::Error::InvalidArgs(err.to_string()).into()),
};
let state = match state {
WifiPowerManagement::Disabled => "off",
WifiPowerManagement::Enabled => "on",
WifiPowerManagement::UnsupportedFeature => {
return Err(zbus::fdo::Error::InvalidArgs(String::from(
"Can't set state to unsupported",
))
.into())
}
};
let res = run_script(
"set wifi power management",
"/usr/bin/iwconfig",
&["wlan0", "power", state],
)
.await;
match res {
Ok(true) => Ok(()),
Ok(false) => Err(zbus::Error::Failure(String::from(
"iwconfig returned non-zero",
))),
Err(e) => Err(zbus::Error::Failure(e.to_string())),
}
}
#[zbus(property)]
fn fan_control_state(&self) -> u32 {
FanControl::UnsupportedFeature as u32 // TODO
}
#[zbus(property)]
async fn set_fan_control_state(&self, state: u32) -> zbus::Result<()> {
let state = match FanControl::try_from(state) {
Ok(state) => state,
Err(err) => return Err(zbus::fdo::Error::InvalidArgs(err.to_string()).into()),
};
let state = match state {
FanControl::OS => "stop",
FanControl::BIOS => "start",
FanControl::UnsupportedFeature => {
return Err(zbus::fdo::Error::InvalidArgs(String::from(
"Can't set state to unsupported",
))
.into())
}
};
// Run what steamos-polkit-helpers/jupiter-fan-control does
let res = run_script(
"enable fan control",
SYSTEMCTL_PATH,
&[state, "jupiter-fan-control-service"],
)
.await;
match res {
Ok(true) => Ok(()),
Ok(false) => Err(zbus::Error::Failure(String::from(
"systemctl returned non-zero",
))),
Err(e) => Err(zbus::Error::Failure(format!("{e}"))),
}
}
#[zbus(property)]
async fn hardware_currently_supported(&self) -> u32 {
match check_support().await {
Ok(res) => res as u32,
Err(_) => HardwareCurrentlySupported::UnsupportedFeature as u32,
}
}
#[zbus(property)]
async fn als_calibration_gain(&self) -> f64 {
// Run script to get calibration value
let result = script_output(
"/usr/bin/steamos-polkit-helpers/jupiter-get-als-gain",
@ -114,40 +195,61 @@ impl SMManager {
}
}
async fn update_bios(&self) -> bool {
async fn get_als_integration_time_file_descriptor(&self) -> Result<Fd, zbus::fdo::Error> {
// Get the file descriptor for the als integration time sysfs path
let result = File::create(ALS_INTEGRATION_PATH).await;
match result {
Ok(f) => Ok(Fd::Owned(std::os::fd::OwnedFd::from(f.into_std().await))),
Err(message) => {
error!("Error opening sysfs file for giving file descriptor: {message}");
Err(zbus::fdo::Error::IOError(message.to_string()))
}
}
}
async fn update_bios(&self) -> Result<(), zbus::fdo::Error> {
// Update the bios as needed
// Return true if the script was successful (though that might mean no update was needed), false otherwise
run_script(
let res = run_script(
"update bios",
"/usr/bin/steamos-potlkit-helpers/jupiter-biosupdate",
&["--auto"],
)
.await
.unwrap_or(false)
.await;
match res {
Ok(_) => Ok(()),
Err(e) => Err(zbus::fdo::Error::Failed(e.to_string())),
}
}
async fn update_dock(&self) -> bool {
async fn update_dock(&self) -> Result<(), zbus::fdo::Error> {
// Update the dock firmware as needed
// Retur true if successful, false otherwise
run_script(
let res = run_script(
"update dock firmware",
"/usr/bin/steamos-polkit-helpers/jupiter-dock-updater",
&[""],
)
.await
.unwrap_or(false)
.await;
match res {
Ok(_) => Ok(()),
Err(e) => Err(zbus::fdo::Error::Failed(e.to_string())),
}
}
async fn trim_devices(&self) -> bool {
async fn trim_devices(&self) -> Result<(), zbus::fdo::Error> {
// Run steamos-trim-devices script
// return true on success, false otherwise
run_script(
let res = run_script(
"trim devices",
"/usr/bin/steamos-polkit-helpers/steamos-trim-devices",
&[""],
)
.await
.unwrap_or(false)
.await;
match res {
Ok(_) => Ok(()),
Err(e) => Err(zbus::fdo::Error::Failed(e.to_string())),
}
}
async fn format_sdcard(&self) -> bool {
@ -162,8 +264,23 @@ impl SMManager {
.unwrap_or(false)
}
async fn set_gpu_performance_level(&self, level: i32) -> bool {
set_gpu_performance_level(level).await.is_ok()
#[zbus(property)]
async fn gpu_performance_level(&self) -> u32 {
match get_gpu_performance_level().await {
Ok(level) => level as u32,
Err(_) => GPUPerformanceLevel::UnsupportedFeature as u32,
}
}
#[zbus(property)]
async fn set_gpu_performance_level(&self, level: u32) -> zbus::Result<()> {
let level = match GPUPerformanceLevel::try_from(level) {
Ok(level) => level,
Err(e) => return Err(zbus::Error::Failure(e.to_string())),
};
set_gpu_performance_level(level)
.await
.map_err(|e| zbus::Error::Failure(e.to_string()))
}
async fn set_gpu_clocks(&self, clocks: i32) -> bool {
@ -174,121 +291,43 @@ impl SMManager {
set_tdp_limit(limit).await.is_ok()
}
async fn get_als_integration_time_file_descriptor(&self) -> Result<Fd, zbus::fdo::Error> {
// Get the file descriptor for the als integration time sysfs path
let result = File::create(ALS_INTEGRATION_PATH).await;
match result {
Ok(f) => Ok(Fd::Owned(std::os::fd::OwnedFd::from(f.into_std().await))),
Err(message) => {
error!("Error opening sysfs file for giving file descriptor: {message}");
Err(zbus::fdo::Error::IOError(message.to_string()))
}
}
}
async fn get_wifi_debug_mode(&mut self) -> u32 {
#[zbus(property)]
async fn wifi_debug_mode_state(&self) -> u32 {
// Get the wifi debug mode
self.wifi_debug_mode as u32
}
async fn set_wifi_debug_mode(&mut self, mode: u32, buffer_size: u32) -> bool {
async fn set_wifi_debug_mode(
&mut self,
mode: u32,
buffer_size: u32,
) -> Result<(), zbus::fdo::Error> {
// Set the wifi debug mode to mode, using an int for flexibility going forward but only
// doing things on 0 or 1 for now
// Return false on error
let wanted_mode = WifiDebugMode::try_from(mode);
match wanted_mode {
Ok(WifiDebugMode::Off) => {
// If mode is 0 disable wifi debug mode
// Stop any existing trace and flush to disk.
if self.should_trace {
let result = match stop_tracing().await {
Ok(result) => result,
Err(message) => {
error!("stop_tracing command got an error: {message}");
return false;
}
};
if !result {
error!("stop_tracing command returned non-zero");
return false;
}
}
// Stop_tracing was successful
if let Err(message) = setup_iwd_config(false).await {
error!("setup_iwd_config false got an error: {message}");
return false;
}
// setup_iwd_config false worked
let value = match restart_iwd().await {
Ok(value) => value,
Err(message) => {
error!("restart_iwd got an error: {message}");
return false;
}
};
if value {
// restart iwd worked
self.wifi_debug_mode = WifiDebugMode::Off;
} else {
// restart_iwd failed
error!("restart_iwd failed, check log above");
return false;
}
let wanted_mode = match WifiDebugMode::try_from(mode) {
Ok(WifiDebugMode::UnsupportedFeature) => {
return Err(zbus::fdo::Error::InvalidArgs(String::from("Invalid mode")))
}
Ok(WifiDebugMode::On) => {
// If mode is 1 enable wifi debug mode
if buffer_size < MIN_BUFFER_SIZE {
return false;
}
if let Err(message) = setup_iwd_config(true).await {
error!("setup_iwd_config true got an error: {message}");
return false;
}
// setup_iwd_config worked
let value = match restart_iwd().await {
Ok(value) => value,
Err(message) => {
error!("restart_iwd got an error: {message}");
return false;
}
};
if !value {
error!("restart_iwd failed");
return false;
}
// restart_iwd worked
if self.should_trace {
let value = match start_tracing(buffer_size).await {
Ok(value) => value,
Err(message) => {
error!("start_tracing got an error: {message}");
return false;
}
};
if !value {
// start_tracing failed
error!("start_tracing failed");
return false;
}
}
// start_tracing worked
self.wifi_debug_mode = WifiDebugMode::On;
Ok(mode) => mode,
Err(e) => return Err(zbus::fdo::Error::InvalidArgs(e.to_string())),
};
match set_wifi_debug_mode(wanted_mode, buffer_size, self.should_trace).await {
Ok(()) => {
self.wifi_debug_mode = wanted_mode;
Ok(())
}
Err(_) => {
// Invalid mode requested, more coming later, but add this catch-all for now
warn!("Invalid wifi debug mode {mode} requested");
return false;
Err(e) => {
error!("Setting wifi debug mode failed: {e}");
Err(zbus::fdo::Error::Failed(e.to_string()))
}
}
true
}
/// A version property.
#[zbus(property)]
async fn version(&self) -> u32 {
SMManager::API_VERSION
SteamOSManager::API_VERSION
}
}