From 70b4dea5350e308481e78b951a01086b3ea2989b Mon Sep 17 00:00:00 2001 From: sknowledge1 <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:17:36 +0000 Subject: [PATCH] feat: add PowerStation fan controls PowerStation can now set fan profiles (ShadowBlip/PowerStation#54), but OpenGamepadUI has no way to choose one. Add a Fan card to the quick bar. The card lists Automatic, the profiles PowerStation has installed for this device, and Manual with a speed slider. The choice is saved in the settings. PowerStation does not save it, so it is loaded again whenever PowerStation starts or the choice changes. The new Fan class only wraps PowerStation's fan D-Bus API, like the existing Cpu and Gpu classes. Automatic and Manual are sent as small JSON profiles, and installed profiles are opened and passed as a file. The card is hidden when PowerStation has no fans to control. Assisted-by: LLM --- core/systems/performance/power_station.gd | 45 ++++- core/ui/card_ui/quick_bar/fan_card.tscn | 15 ++ core/ui/card_ui/quick_bar/quick_bar_menu.tscn | 6 +- core/ui/common/quick_bar/fan_menu.gd | 74 ++++++++ core/ui/common/quick_bar/fan_menu.gd.uid | 1 + core/ui/common/quick_bar/fan_menu.tscn | 32 ++++ docs/class-reference/.nav.yml | 1 + docs/class-reference/Fan.md | 95 +++++++++++ docs/class-reference/PowerStation.md | 12 +- docs/class-reference/PowerStationInstance.md | 10 ++ extensions/core/src/dbus/powerstation.rs | 2 + extensions/core/src/dbus/powerstation/fan.rs | 32 ++++ .../core/src/dbus/powerstation/fan_device.rs | 23 +++ .../core/src/performance/powerstation.rs | 19 +++ .../core/src/performance/powerstation/fan.rs | 161 ++++++++++++++++++ 15 files changed, 525 insertions(+), 3 deletions(-) create mode 100644 core/ui/card_ui/quick_bar/fan_card.tscn create mode 100644 core/ui/common/quick_bar/fan_menu.gd create mode 100644 core/ui/common/quick_bar/fan_menu.gd.uid create mode 100644 core/ui/common/quick_bar/fan_menu.tscn create mode 100644 docs/class-reference/Fan.md create mode 100644 extensions/core/src/dbus/powerstation/fan.rs create mode 100644 extensions/core/src/dbus/powerstation/fan_device.rs create mode 100644 extensions/core/src/performance/powerstation/fan.rs diff --git a/core/systems/performance/power_station.gd b/core/systems/performance/power_station.gd index e714a78b9..858d5fa0a 100644 --- a/core/systems/performance/power_station.gd +++ b/core/systems/performance/power_station.gd @@ -5,19 +5,62 @@ class_name PowerStation ## Proxy interface to PowerStation over DBus ## ## Provides wrapper classes and methods for interacting with PowerStation over -## DBus to control CPU and GPU performance. +## DBus to control CPU and GPU performance and fans. @export var instance: PowerStationInstance = load("res://core/systems/performance/power_station.tres") as PowerStationInstance +var settings_manager := load("res://core/global/settings_manager.tres") as SettingsManager + # Keep a reference to instances so they are not cleaned up automatically var _cpu: Cpu +var _fan: Fan var _gpu: Gpu var logger := Log.get_logger("PowerStation") func _ready() -> void: _cpu = instance.get_cpu() + _fan = instance.get_fan() _gpu = instance.get_gpu() + instance.started.connect(_load_fan_setting) + settings_manager.setting_changed.connect(_on_setting_changed) + + +func _on_setting_changed(section: String, _key: String, _value: Variant) -> void: + if section != "fan": + return + _load_fan_setting() + + +## Loads the fan profile chosen in the "fan" settings section. PowerStation +## does not save fan profiles, so this runs every time PowerStation starts. +func _load_fan_setting() -> void: + if not _fan: + return + var profile := settings_manager.get_value("fan", "profile", "") as String + if profile.is_empty(): + return + + var result: Error + match profile: + "automatic": + result = _fan.load_profile_json(JSON.stringify({"name": "Automatic", "fans": []})) + "manual": + result = _load_manual_fan_profile() + _: + result = _fan.load_profile(profile) + if result != OK: + logger.warn("Failed to load fan profile '" + profile + "': " + error_string(result)) + + +## Runs every fan at the percentage saved in the "fan" settings section +func _load_manual_fan_profile() -> Error: + var percent := settings_manager.get_value("fan", "manual_percent", 50) as int + var sensors := _fan.get_sensors() + var fans: Array[Dictionary] = [] + for id: String in _fan.get_fan_ids(): + fans.append({"fan": id, "mode": "manual", "percent": percent, "sensors": sensors}) + return _fan.load_profile_json(JSON.stringify({"name": "Manual", "fans": fans})) func _process(_delta: float) -> void: diff --git a/core/ui/card_ui/quick_bar/fan_card.tscn b/core/ui/card_ui/quick_bar/fan_card.tscn new file mode 100644 index 000000000..8a62eeb95 --- /dev/null +++ b/core/ui/card_ui/quick_bar/fan_card.tscn @@ -0,0 +1,15 @@ +[gd_scene load_steps=3 format=3] + +[ext_resource type="PackedScene" path="res://core/ui/card_ui/quick_bar/qb_card.tscn" id="1_card"] +[ext_resource type="PackedScene" path="res://core/ui/common/quick_bar/fan_menu.tscn" id="2_menu"] + +[node name="FanCard" instance=ExtResource("1_card")] +visible = false +title = "Fan" + +[node name="SectionLabel" parent="MarginContainer/CardVBoxContainer" index="0"] +text = "Fan" + +[node name="Fan" parent="MarginContainer/CardVBoxContainer/ContentContainer" index="0" instance=ExtResource("2_menu")] +layout_mode = 2 +size_flags_vertical = 0 diff --git a/core/ui/card_ui/quick_bar/quick_bar_menu.tscn b/core/ui/card_ui/quick_bar/quick_bar_menu.tscn index 5d00aec59..2b1217499 100644 --- a/core/ui/card_ui/quick_bar/quick_bar_menu.tscn +++ b/core/ui/card_ui/quick_bar/quick_bar_menu.tscn @@ -1,4 +1,4 @@ -[gd_scene load_steps=30 format=3 uid="uid://hroo3ll4inrb"] +[gd_scene load_steps=31 format=3 uid="uid://hroo3ll4inrb"] [ext_resource type="Script" uid="uid://3sik128fffg7" path="res://core/ui/card_ui/quick_bar/quick_bar_menu.gd" id="1_56jo7"] [ext_resource type="PackedScene" uid="uid://shvyhrv5sx3v" path="res://core/systems/state/state_watcher.tscn" id="2_6rvrx"] @@ -29,6 +29,7 @@ [ext_resource type="PackedScene" uid="uid://bjy50kdrebgre" path="res://core/ui/card_ui/quick_bar/notifications_card.tscn" id="19_pppbi"] [ext_resource type="PackedScene" uid="uid://dxaeufuk7ump2" path="res://core/ui/card_ui/quick_bar/quick_settings_card.tscn" id="20_17ks0"] [ext_resource type="PackedScene" uid="uid://dycb7m0oj13ly" path="res://core/ui/card_ui/quick_bar/performance_card.tscn" id="21_uw510"] +[ext_resource type="PackedScene" path="res://core/ui/card_ui/quick_bar/fan_card.tscn" id="22_fan"] [node name="QuickBarMenu" type="Control" groups=["quick-bar"]] z_index = 20 @@ -235,3 +236,6 @@ layout_mode = 2 [node name="PerformanceCard" parent="MarginContainer/PanelContainer/MarginContainer/VBoxContainer/ScrollContainer/Viewport" instance=ExtResource("21_uw510")] layout_mode = 2 + +[node name="FanCard" parent="MarginContainer/PanelContainer/MarginContainer/VBoxContainer/ScrollContainer/Viewport" instance=ExtResource("22_fan")] +layout_mode = 2 diff --git a/core/ui/common/quick_bar/fan_menu.gd b/core/ui/common/quick_bar/fan_menu.gd new file mode 100644 index 000000000..1d2ca4a14 --- /dev/null +++ b/core/ui/common/quick_bar/fan_menu.gd @@ -0,0 +1,74 @@ +extends VBoxContainer + +## Quick bar menu to choose a PowerStation fan profile +## +## Saves the choice in the "fan" settings section. [PowerStation] loads it. + +var power_station := load("res://core/systems/performance/power_station.tres") as PowerStationInstance +var settings_manager := load("res://core/global/settings_manager.tres") as SettingsManager + +# Setting value for each dropdown item: "automatic", profile paths, then "manual" +var _profiles := PackedStringArray() + +@onready var focus_group := $%FocusGroup as FocusGroup +@onready var profile_dropdown := $%ProfileDropdown as Dropdown +@onready var manual_slider := $%ManualSlider as ValueSlider +@onready var apply_timer := $%ApplyTimer as Timer + + +func _ready() -> void: + manual_slider.value = settings_manager.get_value("fan", "manual_percent", 50) as int + _update() + power_station.started.connect(_update) + power_station.stopped.connect(_update) + profile_dropdown.item_selected.connect(_on_profile_selected) + manual_slider.value_changed.connect(_on_manual_changed) + apply_timer.timeout.connect(_on_apply_timer_timeout) + + +## Lists the fan profiles for this device. Hides the card if PowerStation +## cannot control any fans. +func _update() -> void: + var fan := power_station.get_fan() + var has_fans := fan != null and not fan.get_fan_ids().is_empty() + var card := owner as Control + if card: + card.visible = has_fans + if not has_fans: + return + + _profiles = PackedStringArray(["automatic"]) + _profiles.append_array(fan.get_profiles()) + _profiles.append("manual") + profile_dropdown.clear() + for profile: String in _profiles: + profile_dropdown.add_item(_get_label(profile)) + + var current := settings_manager.get_value("fan", "profile", "automatic") as String + profile_dropdown.select(maxi(_profiles.find(current), 0)) + manual_slider.visible = current == "manual" + focus_group.recalculate_focus.call_deferred() + + +func _get_label(profile: String) -> String: + if profile == "automatic": + return "Automatic" + if profile == "manual": + return "Manual" + return profile.get_file().get_basename().capitalize() + + +func _on_profile_selected(index: int) -> void: + if index < 0 or index >= _profiles.size(): + return + var profile := _profiles[index] + manual_slider.visible = profile == "manual" + settings_manager.set_value("fan", "profile", profile) + + +func _on_manual_changed(_value: float) -> void: + apply_timer.start() + + +func _on_apply_timer_timeout() -> void: + settings_manager.set_value("fan", "manual_percent", int(manual_slider.value)) diff --git a/core/ui/common/quick_bar/fan_menu.gd.uid b/core/ui/common/quick_bar/fan_menu.gd.uid new file mode 100644 index 000000000..044b75eb5 --- /dev/null +++ b/core/ui/common/quick_bar/fan_menu.gd.uid @@ -0,0 +1 @@ +uid://cpwcj2kv0yv37 diff --git a/core/ui/common/quick_bar/fan_menu.tscn b/core/ui/common/quick_bar/fan_menu.tscn new file mode 100644 index 000000000..aea309e87 --- /dev/null +++ b/core/ui/common/quick_bar/fan_menu.tscn @@ -0,0 +1,32 @@ +[gd_scene load_steps=6 format=3] + +[ext_resource type="Script" path="res://core/ui/common/quick_bar/fan_menu.gd" id="1_fan"] +[ext_resource type="PackedScene" path="res://core/systems/input/focus_group.tscn" id="2_focus"] +[ext_resource type="Resource" path="res://core/ui/card_ui/quick_bar/quick_bar_menu_focus.tres" id="3_stack"] +[ext_resource type="PackedScene" path="res://core/ui/components/dropdown.tscn" id="4_dropdown"] +[ext_resource type="PackedScene" path="res://core/ui/components/slider.tscn" id="5_slider"] + +[node name="Fan" type="VBoxContainer"] +anchors_preset = 10 +anchor_right = 1.0 +grow_horizontal = 2 +script = ExtResource("1_fan") + +[node name="FocusGroup" parent="." instance=ExtResource("2_focus")] +unique_name_in_owner = true +focus_stack = ExtResource("3_stack") + +[node name="ApplyTimer" type="Timer" parent="."] +unique_name_in_owner = true +one_shot = true + +[node name="ProfileDropdown" parent="." instance=ExtResource("4_dropdown")] +unique_name_in_owner = true +layout_mode = 2 +title = "Fan Profile" + +[node name="ManualSlider" parent="." instance=ExtResource("5_slider")] +unique_name_in_owner = true +visible = false +layout_mode = 2 +text = "Fan Speed (%)" diff --git a/docs/class-reference/.nav.yml b/docs/class-reference/.nav.yml index 2b73e970e..cd932efc2 100644 --- a/docs/class-reference/.nav.yml +++ b/docs/class-reference/.nav.yml @@ -50,6 +50,7 @@ nav: - ./EventDevice.md - ./ExpandableCard.md - ./FadeEffect.md + - ./Fan.md - ./Feature.md - ./FeatureFlags.md - ./FifoReader.md diff --git a/docs/class-reference/Fan.md b/docs/class-reference/Fan.md new file mode 100644 index 000000000..74a2fe3a7 --- /dev/null +++ b/docs/class-reference/Fan.md @@ -0,0 +1,95 @@ +# Fan + +**Inherits:** [Resource](https://docs.godotengine.org/en/stable/classes/class_resource.html) + + +## Methods + +| Returns | Signature | +| ------- | --------- | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [get_dbus_path](./#get_dbus_path)() | +| [PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) | [get_fan_ids](./#get_fan_ids)() | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [get_profile_name](./#get_profile_name)() | +| [String](https://docs.godotengine.org/en/stable/classes/class_string.html) | [get_profile_path](./#get_profile_path)() | +| [PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) | [get_profiles](./#get_profiles)() | +| [PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) | [get_sensors](./#get_sensors)() | +| [int](https://docs.godotengine.org/en/stable/classes/class_int.html) | [load_profile](./#load_profile)(path: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | +| [int](https://docs.godotengine.org/en/stable/classes/class_int.html) | [load_profile_json](./#load_profile_json)(json: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) | + + +------------------ + +## Method Descriptions + +### `get_dbus_path()` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) **get_dbus_path**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `get_fan_ids()` + + +[PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) **get_fan_ids**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `get_profile_name()` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) **get_profile_name**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `get_profile_path()` + + +[String](https://docs.godotengine.org/en/stable/classes/class_string.html) **get_profile_path**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `get_profiles()` + + +[PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) **get_profiles**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `get_sensors()` + + +[PackedStringArray](https://docs.godotengine.org/en/stable/classes/class_packedstringarray.html) **get_sensors**() + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `load_profile()` + + +[int](https://docs.godotengine.org/en/stable/classes/class_int.html) **load_profile**(path: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +!!! note + There is currently no description for this method. Please help us by contributing one! + +### `load_profile_json()` + + +[int](https://docs.godotengine.org/en/stable/classes/class_int.html) **load_profile_json**(json: [String](https://docs.godotengine.org/en/stable/classes/class_string.html)) + + +!!! note + There is currently no description for this method. Please help us by contributing one! + diff --git a/docs/class-reference/PowerStation.md b/docs/class-reference/PowerStation.md index 968252775..688c805b1 100644 --- a/docs/class-reference/PowerStation.md +++ b/docs/class-reference/PowerStation.md @@ -5,12 +5,13 @@ Proxy interface to PowerStation over DBus ## Description -Provides wrapper classes and methods for interacting with PowerStation over DBus to control CPU and GPU performance. +Provides wrapper classes and methods for interacting with PowerStation over DBus to control CPU and GPU performance and fans. ## Properties | Type | Name | Default | | ---- | ---- | ------- | | [PowerStationInstance](../PowerStationInstance) | [instance](./#instance) | | +| [SettingsManager](../SettingsManager) | [settings_manager](./#settings_manager) | | | [CustomLogger](../CustomLogger) | [logger](./#logger) | | @@ -25,6 +26,15 @@ Provides wrapper classes and methods for interacting with PowerStation over DBus [PowerStationInstance](../PowerStationInstance) instance +!!! note + There is currently no description for this property. Please help us by contributing one! + +### `settings_manager` + + +[SettingsManager](../SettingsManager) settings_manager + + !!! note There is currently no description for this property. Please help us by contributing one! diff --git a/docs/class-reference/PowerStationInstance.md b/docs/class-reference/PowerStationInstance.md index b7d95429b..248b8c522 100644 --- a/docs/class-reference/PowerStationInstance.md +++ b/docs/class-reference/PowerStationInstance.md @@ -8,6 +8,7 @@ | Type | Name | Default | | ---- | ---- | ------- | | [Cpu](../Cpu) | [cpu](./#cpu) | | +| [Fan](../Fan) | [fan](./#fan) | | | [Gpu](../Gpu) | [gpu](./#gpu) | | ## Methods @@ -28,6 +29,15 @@ [Cpu](../Cpu) cpu +!!! note + There is currently no description for this property. Please help us by contributing one! + +### `fan` + + +[Fan](../Fan) fan + + !!! note There is currently no description for this property. Please help us by contributing one! diff --git a/extensions/core/src/dbus/powerstation.rs b/extensions/core/src/dbus/powerstation.rs index 3ae387c03..370a6f541 100644 --- a/extensions/core/src/dbus/powerstation.rs +++ b/extensions/core/src/dbus/powerstation.rs @@ -2,5 +2,7 @@ pub mod card; pub mod connector; pub mod core; pub mod cpu; +pub mod fan; +pub mod fan_device; pub mod gpu; pub mod tdp; diff --git a/extensions/core/src/dbus/powerstation/fan.rs b/extensions/core/src/dbus/powerstation/fan.rs new file mode 100644 index 000000000..a87794c95 --- /dev/null +++ b/extensions/core/src/dbus/powerstation/fan.rs @@ -0,0 +1,32 @@ +use zbus::proxy; +#[proxy( + interface = "org.shadowblip.Fan", + default_service = "org.shadowblip.PowerStation", + default_path = "/org/shadowblip/Performance/Fan" +)] +pub trait Fan { + /// EnumerateFans method + fn enumerate_fans(&self) -> zbus::Result>; + + /// LoadProfile method + fn load_profile(&self, file: zbus::zvariant::Fd<'_>) -> zbus::Result<()>; + + /// LoadProfileJson method + fn load_profile_json(&self, json: &str) -> zbus::Result<()>; + + /// ProfileName property + #[zbus(property)] + fn profile_name(&self) -> zbus::Result; + + /// ProfilePath property + #[zbus(property)] + fn profile_path(&self) -> zbus::Result; + + /// Profiles property + #[zbus(property)] + fn profiles(&self) -> zbus::Result>; + + /// Sensors property + #[zbus(property)] + fn sensors(&self) -> zbus::Result>; +} diff --git a/extensions/core/src/dbus/powerstation/fan_device.rs b/extensions/core/src/dbus/powerstation/fan_device.rs new file mode 100644 index 000000000..36c528d8e --- /dev/null +++ b/extensions/core/src/dbus/powerstation/fan_device.rs @@ -0,0 +1,23 @@ +use zbus::proxy; +#[proxy( + interface = "org.shadowblip.Fan.Device", + default_service = "org.shadowblip.PowerStation", + default_path = "/org/shadowblip/Performance/Fan/Fan0" +)] +pub trait FanDevice { + /// AvailableModes property + #[zbus(property)] + fn available_modes(&self) -> zbus::Result>; + + /// Id property + #[zbus(property)] + fn id(&self) -> zbus::Result; + + /// Mode property + #[zbus(property)] + fn mode(&self) -> zbus::Result; + + /// Percent property + #[zbus(property)] + fn percent(&self) -> zbus::Result; +} diff --git a/extensions/core/src/performance/powerstation.rs b/extensions/core/src/performance/powerstation.rs index 5400ea9d6..ec60a6910 100644 --- a/extensions/core/src/performance/powerstation.rs +++ b/extensions/core/src/performance/powerstation.rs @@ -1,5 +1,6 @@ pub mod cpu; pub mod cpu_core; +pub mod fan; pub mod gpu; pub mod gpu_card; pub mod gpu_connector; @@ -10,6 +11,7 @@ use std::{ }; use cpu::Cpu; +use fan::Fan; use godot::{classes::Engine, prelude::*}; use gpu::Gpu; use zbus::names::BusName; @@ -18,6 +20,7 @@ use crate::{dbus::RunError, get_dbus_system, get_dbus_system_blocking, RUNTIME}; pub const POWERSTATION_BUS: &str = "org.shadowblip.PowerStation"; const POWERSTATION_CPU_PATH: &str = "/org/shadowblip/Performance/CPU"; +const POWERSTATION_FAN_PATH: &str = "/org/shadowblip/Performance/Fan"; const POWERSTATION_GPU_PATH: &str = "/org/shadowblip/Performance/GPU"; /// Signals that can be emitted @@ -35,12 +38,16 @@ pub struct PowerStationInstance { rx: Receiver, conn: Option, cpu_instance: Option>, + fan_instance: Option>, gpu_instance: Option>, #[allow(dead_code)] #[var(get = get_cpu)] cpu: Option>, #[allow(dead_code)] + #[var(get = get_fan)] + fan: Option>, + #[allow(dead_code)] #[var(get = get_gpu)] gpu: Option>, } @@ -75,6 +82,12 @@ impl PowerStationInstance { self.cpu_instance.clone() } + /// Returns an instance of the fan control + #[func] + fn get_fan(&self) -> Option> { + self.fan_instance.clone() + } + /// Returns an instance of the GPU #[func] fn get_gpu(&self) -> Option> { @@ -144,8 +157,10 @@ impl IResource for PowerStationInstance { rx, conn, cpu_instance: Default::default(), + fan_instance: Default::default(), gpu_instance: Default::default(), cpu: Default::default(), + fan: Default::default(), gpu: Default::default(), }; } @@ -159,6 +174,8 @@ impl IResource for PowerStationInstance { // Create CPU instance let cpu = Some(Cpu::new(POWERSTATION_CPU_PATH)); + // Create fan instance + let fan = Some(Fan::new(POWERSTATION_FAN_PATH)); // Create GPU instance let gpu = Some(Gpu::new(POWERSTATION_GPU_PATH)); @@ -168,8 +185,10 @@ impl IResource for PowerStationInstance { rx, conn, cpu_instance: cpu, + fan_instance: fan, gpu_instance: gpu, cpu: None, + fan: None, gpu: None, } } diff --git a/extensions/core/src/performance/powerstation/fan.rs b/extensions/core/src/performance/powerstation/fan.rs new file mode 100644 index 000000000..b746d4a96 --- /dev/null +++ b/extensions/core/src/performance/powerstation/fan.rs @@ -0,0 +1,161 @@ +use std::fs::File; + +use godot::{classes::ResourceLoader, global::Error, prelude::*}; +use zbus::zvariant::Fd; + +use crate::{ + dbus::powerstation::{fan::FanProxyBlocking, fan_device::FanDeviceProxyBlocking}, + get_dbus_system_blocking, +}; + +use super::POWERSTATION_BUS; + +/// Fan control provided by PowerStation +#[derive(GodotClass)] +#[class(no_init, base=Resource)] +pub struct Fan { + base: Base, + path: String, + proxy: Option>, +} + +#[godot_api] +impl Fan { + /// Create a new [Fan] instance with the given DBus path + fn from_path(path: GString) -> Gd { + Gd::from_init_fn(|base| { + let conn = get_dbus_system_blocking().ok(); + let proxy = conn.as_ref().and_then(|conn| { + FanProxyBlocking::builder(conn) + .path(path.to_string()) + .ok() + .and_then(|builder| builder.build().ok()) + }); + + Self { + base, + path: path.to_string(), + proxy, + } + }) + } + + /// Get or create a [Fan] with the given DBus path. If an instance already + /// exists with the given path, then it will be loaded from the resource + /// cache. + pub fn new(path: &str) -> Gd { + let res_path = format!("dbus://{POWERSTATION_BUS}{path}"); + + let mut resource_loader = ResourceLoader::singleton(); + if resource_loader.exists(res_path.as_str()) { + if let Some(res) = resource_loader.load(res_path.as_str()) { + return res.cast(); + } + } + let mut device = Fan::from_path(path.into()); + device.take_over_path(res_path.as_str()); + device + } + + /// Return the DBus path to the fan instance + #[func] + pub fn get_dbus_path(&self) -> GString { + self.path.as_str().into() + } + + /// Returns the IDs of all fans PowerStation can control + #[func] + pub fn get_fan_ids(&self) -> PackedStringArray { + let mut ids = PackedStringArray::new(); + let Some(proxy) = self.proxy.as_ref() else { + return ids; + }; + let conn = proxy.inner().connection(); + for path in proxy.enumerate_fans().unwrap_or_default() { + let Some(fan) = FanDeviceProxyBlocking::builder(conn) + .path(path) + .ok() + .and_then(|builder| builder.build().ok()) + else { + continue; + }; + let Ok(id) = fan.id() else { + continue; + }; + ids.push(id.as_str()); + } + ids + } + + /// Returns the IDs of all temperature sensors + #[func] + pub fn get_sensors(&self) -> PackedStringArray { + let Some(proxy) = self.proxy.as_ref() else { + return PackedStringArray::new(); + }; + let sensors = proxy.sensors().unwrap_or_default(); + sensors.iter().map(|sensor| sensor.to_godot()).collect() + } + + /// Returns the paths of the installed fan profiles for this device + #[func] + pub fn get_profiles(&self) -> PackedStringArray { + let Some(proxy) = self.proxy.as_ref() else { + return PackedStringArray::new(); + }; + let profiles = proxy.profiles().unwrap_or_default(); + profiles.iter().map(|profile| profile.to_godot()).collect() + } + + /// Returns the name of the loaded fan profile + #[func] + pub fn get_profile_name(&self) -> GString { + let Some(proxy) = self.proxy.as_ref() else { + return GString::new(); + }; + proxy.profile_name().unwrap_or_default().as_str().into() + } + + /// Returns the path of the loaded fan profile. Empty for profiles loaded + /// from JSON. + #[func] + pub fn get_profile_path(&self) -> GString { + let Some(proxy) = self.proxy.as_ref() else { + return GString::new(); + }; + proxy.profile_path().unwrap_or_default().as_str().into() + } + + /// Load the TOML fan profile at the given path + #[func] + pub fn load_profile(&self, path: GString) -> Error { + let Some(proxy) = self.proxy.as_ref() else { + return Error::ERR_UNAVAILABLE; + }; + let file = match File::open(path.to_string()) { + Ok(file) => file, + Err(e) => { + log::error!("Failed to open fan profile '{path}': {e}"); + return Error::ERR_FILE_CANT_OPEN; + } + }; + if let Err(e) = proxy.load_profile(Fd::from(&file)) { + log::error!("Failed to load fan profile '{path}': {e}"); + return Error::FAILED; + } + Error::OK + } + + /// Load a fan profile from a JSON string + #[func] + pub fn load_profile_json(&self, json: GString) -> Error { + let Some(proxy) = self.proxy.as_ref() else { + return Error::ERR_UNAVAILABLE; + }; + if let Err(e) = proxy.load_profile_json(json.to_string().as_str()) { + log::error!("Failed to load fan profile: {e}"); + return Error::FAILED; + } + Error::OK + } +}