-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
6093 lines (5258 loc) · 292 KB
/
main.py
File metadata and controls
6093 lines (5258 loc) · 292 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import decky
import asyncio
import glob
import json
import os
import re
import sys
import traceback
import psutil
import subprocess
import shutil
import time
from typing import Dict, Any, Optional, List, Tuple
# Add py_modules directory to Python path for dynamic imports
py_modules_path = os.path.join(os.path.dirname(__file__), 'py_modules')
if py_modules_path not in sys.path:
sys.path.insert(0, py_modules_path)
# Debug configuration
DEBUG_ENABLED = os.environ.get('POWERDECK_DEBUG', 'false').lower() == 'true'
DISK_LOGGING_ENABLED = os.environ.get('POWERDECK_DISK_LOGGING', 'false').lower() == 'true'
# Version management
def get_plugin_version() -> str:
"""Get plugin version from VERSION file or plugin.json fallback"""
try:
# First try to read from VERSION file (single source of truth)
version_file_path = os.path.join(os.path.dirname(__file__), "VERSION")
if os.path.exists(version_file_path):
with open(version_file_path, 'r') as f:
version = f.read().strip()
if version:
return version
# Fallback to plugin.json
plugin_json_path = os.path.join(os.path.dirname(__file__), "plugin.json")
if os.path.exists(plugin_json_path):
with open(plugin_json_path, 'r') as f:
plugin_data = json.load(f)
return plugin_data.get("version", "unknown")
return "unknown" # Fallback when VERSION file and plugin.json both fail
except Exception as e:
decky.logger.error(f"Failed to get plugin version: {e}")
return "unknown" # Ultimate fallback version
# Standardized logging functions
def debug_log(message: str, *args, **kwargs):
"""Log debug messages only when debug mode is enabled"""
if DEBUG_ENABLED and DISK_LOGGING_ENABLED:
decky.logger.info(f"[DEBUG] {message}", *args, **kwargs)
def debug_error(message: str, *args, **kwargs):
"""Log error messages only when debug mode is enabled"""
if DEBUG_ENABLED and DISK_LOGGING_ENABLED:
decky.logger.error(f"[DEBUG] {message}", *args, **kwargs)
def info_log(message: str, *args, **kwargs):
"""Log important info messages (always visible)"""
if DISK_LOGGING_ENABLED:
decky.logger.info(f"[PowerDeck] {message}", *args, **kwargs)
def error_log(message: str, *args, **kwargs):
"""Log error messages (always visible)"""
if DISK_LOGGING_ENABLED:
decky.logger.error(f"[PowerDeck] {message}", *args, **kwargs)
# Import device-specific controllers
try:
from devices.rog_ally import get_rog_ally_controller
ROG_ALLY_AVAILABLE = True
except ImportError:
ROG_ALLY_AVAILABLE = False
debug_log("ROG Ally support not available")
try:
from devices.lenovo import get_legion_controller
LEGION_AVAILABLE = True
except ImportError:
LEGION_AVAILABLE = False
debug_log("Legion support not available")
try:
from devices.steam_deck import get_steam_deck_controller
STEAM_DECK_AVAILABLE = True
except ImportError:
STEAM_DECK_AVAILABLE = False
debug_log("Steam Deck support not available")
# Try to import device management modules with graceful fallbacks
try:
from device_manager import DeviceManager
from power_core import PowerManager
from profile_manager import ProfileManager
from cpu_manager import CPUManager
from plugin_settings import PowerDeckSettings
from steamfork_fan_control import steamfork_fan_controller
from sleep_wake_manager import get_sleep_wake_manager
from inputplumber_manager import get_inputplumber_manager, ControllerMode
device_support_available = True
except ImportError as e:
error_log(f"Device support modules not available: {e}")
device_support_available = False
# Import processor detection modules
try:
from processor_detection import (
get_current_processor_info,
get_processor_tdp_limits,
get_processor_default_tdp,
is_handheld_device,
refresh_processor_detection
)
# Import unified processor database instead of old separate databases
from unified_processor_db import get_processor_info, get_processor_tdp_info, get_database_stats
processor_support_available = True
info_log("Processor database and detection loaded successfully")
except ImportError as e:
error_log(f"Processor detection modules not available: {e}")
processor_support_available = False
# Import sysfs-based power management
try:
from sysfs_power_manager import (
sysfs_power_manager,
get_sysfs_power_capabilities,
get_sysfs_tdp_limits,
set_sysfs_tdp
)
sysfs_support_available = True
info_log("Sysfs power management loaded successfully")
except ImportError as e:
error_log(f"Sysfs power management not available: {e}")
sysfs_support_available = False
class Plugin:
def __init__(self):
self.device_manager = None
self.power_manager = None
self.profile_manager = None
self.cpu_manager = None
self.settings = None
self.device_controller = None # Device-specific controller
self.device_type = "generic" # Device type identifier
self.processor_info = None # Processor specifications and capabilities
self.power_mode = "hybrid" # Power management mode: sysfs, database, or hybrid
self.original_hardware_defaults = None # Store unmodified hardware state for default profile creation
# Initialize with minimal defaults - real values will be set from processor database during initialization
self.current_profile = {
"tdp": None, # Will be set from processor database default_tdp during initialization
"cpuBoost": True, # Enabled by default to match typical system behavior
"smt": True,
"cpuCores": None, # Will be detected from hardware during initialization
"governor": "powersave", # Always use powersave for efficiency
"epp": "balance_power" # Conservative EPP setting for efficiency
}
# TDP limits will be set from processor database or sysfs during initialization
self.tdp_limits = {"min": 4, "max": None} # Min is hard-coded 4W, max from database
self.enable_per_game_profiles = True # Per-game profiles setting - enabled by default
self.rog_ally_native_tdp_enabled = False # ROG Ally native TDP support - disabled by default
self._rog_ally_native_tdp_explicitly_set = False # Track if user explicitly set this
self.device_info = {
"device_name": "Unknown Device",
"cpu_vendor": "unknown",
"supports_tdp": True,
"supports_cpu_boost": True,
"supports_smt": True,
"supports_gpu_control": True,
"has_fan_control": False, # Will be set during initialization
# TDP values will be set from processor database during initialization
"min_tdp": 4, # Hard-coded minimum for underclocking
"max_tdp": None, # Will be set from processor database
"min_gpu_freq": 400,
"max_gpu_freq": 1600
}
self.ryzenadj_path = None
self.warning_cache = set() # Track warnings to prevent duplicates
# Enhanced sleep/wake management
self.sleep_wake_manager = None
# Background update checking state
self.last_update_check = None
self.update_check_interval = 4 * 3600 # 4 hours in seconds
self.update_available = False
self.latest_available_version = None
self.background_update_task = None
self.staged_update_info = None
self.staged_update_path = None
self.update_staging_dir = "/tmp/powerdeck_staged_update"
# Backend game detection / profile auto-apply
self.game_monitor_task = None
self._last_detected_game_id: Optional[str] = None
self._last_ac_power_state: Optional[bool] = None
def log_warning_once(self, message: str):
"""Log a warning message only once to prevent spam"""
if message not in self.warning_cache:
self.warning_cache.add(message)
decky.logger.warning(message)
async def _main(self):
decky.logger.info("PowerDeck initializing...")
# Log device support status
decky.logger.info(f"Device support available: {device_support_available}")
# Initialize hardware detection
await self.detect_hardware()
# Set system-derived defaults from processor database and hardware detection
await self._set_system_derived_defaults()
# CRITICAL: Store original unmodified hardware state before any profiles are applied
# This ensures default profile creation uses true hardware defaults, not modified state
self.original_hardware_defaults = await self._detect_actual_system_defaults()
decky.logger.info(f"Preserved original hardware defaults: {self.original_hardware_defaults}")
if device_support_available:
try:
# Initialize managers
self.settings = PowerDeckSettings()
self.device_manager = DeviceManager()
# power_manager will be created by device_manager based on detected hardware
self.profile_manager = ProfileManager()
self.cpu_manager = CPUManager()
# Initialize CPU topology mapping for efficient core management
info_log("Initializing CPU topology mapping...")
self.cpu_manager.initialize_cpu_topology()
# Detect fan control availability
try:
self.device_info["has_fan_control"] = steamfork_fan_controller.is_available()
info_log(f"Fan control detection: available={self.device_info['has_fan_control']}")
except Exception as e:
error_log(f"Failed to detect fan control availability: {e}")
self.device_info["has_fan_control"] = False
# Load unified profiles instead of old settings format
await self.load_unified_profiles()
# Initialize enhanced sleep/wake management
if device_support_available:
try:
self.sleep_wake_manager = get_sleep_wake_manager(self)
await self.sleep_wake_manager.start_monitoring()
decky.logger.info("Enhanced sleep/wake management initialized")
except Exception as e:
decky.logger.error(f"Failed to initialize enhanced sleep/wake management: {e}")
# Fallback to original monitoring
asyncio.create_task(self.monitor_system_wake())
decky.logger.info("Falling back to basic sleep/wake monitoring")
else:
# Fallback to original monitoring if device support unavailable
asyncio.create_task(self.monitor_system_wake())
decky.logger.info("Using basic sleep/wake monitoring (no device support)")
# Start background update checking task (non-blocking)
self.background_update_task = asyncio.create_task(self.background_update_checker())
# Start backend game detection loop (applies profiles without needing menu open)
self.game_monitor_task = asyncio.create_task(self.game_monitor())
decky.logger.info("Backend game detection loop started")
decky.logger.info(f"PowerDeck initialized for device: {self.device_info['device_name']}")
except Exception as e:
decky.logger.error(f"Failed to initialize device managers: {e}")
else:
decky.logger.warning("Running in fallback mode without device support")
async def _unload(self):
decky.logger.info("PowerDeck unloading...")
# Stop enhanced sleep/wake monitoring
if self.sleep_wake_manager:
try:
await self.sleep_wake_manager.stop_monitoring()
decky.logger.info("Enhanced sleep/wake monitoring stopped")
except Exception as e:
decky.logger.error(f"Error stopping sleep/wake monitoring: {e}")
# Cancel background update checker task
if self.background_update_task:
try:
self.background_update_task.cancel()
decky.logger.info("Background update checker cancelled")
except Exception as e:
decky.logger.error(f"Error cancelling background update checker: {e}")
if self.game_monitor_task:
try:
self.game_monitor_task.cancel()
decky.logger.info("Game monitor task cancelled")
except Exception as e:
decky.logger.error(f"Error cancelling game monitor task: {e}")
async def _uninstall(self):
decky.logger.info("PowerDeck uninstalling...")
async def _detect_actual_system_defaults(self) -> Dict[str, Any]:
"""Detect actual system defaults from current hardware state - eliminates hard-coding"""
system_defaults = {}
try:
# Detect current CPU boost state
try:
with open("/sys/devices/system/cpu/cpufreq/boost", 'r') as f:
boost_value = f.read().strip()
system_defaults["cpuBoost"] = boost_value == "1"
decky.logger.info(f"Detected system default CPU boost: {system_defaults['cpuBoost']}")
except (OSError, ValueError):
system_defaults["cpuBoost"] = True
# Detect current SMT state
try:
with open("/sys/devices/system/cpu/smt/control", 'r') as f:
smt_value = f.read().strip()
system_defaults["smt"] = smt_value == "on"
decky.logger.info(f"Detected system default SMT: {system_defaults['smt']}")
except (OSError, ValueError):
system_defaults["smt"] = True
# Detect current CPU governor
try:
with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", 'r') as f:
governor = f.read().strip()
system_defaults["governor"] = governor
decky.logger.info(f"Detected system default governor: {governor}")
except (OSError, ValueError):
system_defaults["governor"] = "powersave"
# Detect current EPP setting
try:
with open("/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference", 'r') as f:
epp = f.read().strip()
system_defaults["epp"] = epp
decky.logger.info(f"Detected system default EPP: {epp}")
except (OSError, ValueError):
system_defaults["epp"] = "balance_performance"
# Detect current online CPU cores
try:
with open("/sys/devices/system/cpu/online", 'r') as f:
online_range = f.read().strip()
if '-' in online_range:
max_online = int(online_range.split('-')[-1])
online_cores = max_online + 1
else:
online_cores = 1
system_defaults["cpuCores"] = online_cores
decky.logger.info(f"Detected system default online cores: {online_cores}")
except (OSError, ValueError):
system_defaults["cpuCores"] = 8
decky.logger.info(f"Detected system defaults: {system_defaults}")
return system_defaults
except Exception as e:
decky.logger.error(f"Failed to detect system defaults: {e}")
# Return conservative defaults as fallback
return {
"cpuBoost": True,
"smt": True,
"governor": "powersave",
"epp": "balance_performance",
"cpuCores": 8
}
async def _set_system_derived_defaults(self):
"""Set all default values from processor database and system detection - eliminates hard-coding"""
try:
decky.logger.info("Setting system-derived defaults from processor database and sysfs")
# First, detect actual system defaults from hardware
system_defaults = await self._detect_actual_system_defaults()
# Get processor-based defaults
if processor_support_available:
try:
# Get TDP limits from processor database
tdp_min, tdp_max = get_processor_tdp_limits() # Returns (4, database_max)
# CORRECTED: Use processor tdp_min as PowerDeck default (NOT default_tdp)
processor_info = get_current_processor_info()
if processor_info.get("detected"):
# Use the processor's minimum TDP as PowerDeck default (15W for 7840U)
tdp_default = processor_info.get("tdp_min", 15)
else:
# Fallback conservative default
tdp_default = 15
# Update TDP limits and defaults
self.tdp_limits = {"min": tdp_min, "max": tdp_max}
self.device_info["min_tdp"] = tdp_min
self.device_info["max_tdp"] = tdp_max
# Set PowerDeck default TDP from processor minimum TDP
if self.current_profile["tdp"] is None:
self.current_profile["tdp"] = tdp_default
decky.logger.info(f"Set PowerDeck default TDP to processor minimum: {tdp_default}W")
decky.logger.info(f"Applied processor database TDP limits: {tdp_min}W - {tdp_max}W (PowerDeck default: {tdp_default}W)")
except Exception as e:
decky.logger.warning(f"Failed to get processor database TDP values: {e}")
# Try to get fallback values from processor detection if available
try:
if processor_support_available:
fallback_min, fallback_max = get_processor_tdp_limits()
self.tdp_limits = {"min": fallback_min, "max": fallback_max}
self.device_info["min_tdp"] = fallback_min
self.device_info["max_tdp"] = fallback_max
decky.logger.info(f"Used processor detection fallback TDP limits: {fallback_min}W - {fallback_max}W")
else:
# Last resort conservative defaults only if processor database completely unavailable
self.tdp_limits = {"min": 4, "max": 25}
self.device_info["min_tdp"] = 4
self.device_info["max_tdp"] = 25
decky.logger.warning("Using last resort TDP limits: 4W - 25W")
except Exception:
self.tdp_limits = {"min": 4, "max": 25}
self.device_info["min_tdp"] = 4
self.device_info["max_tdp"] = 25
decky.logger.warning("Using absolute fallback TDP limits: 4W - 25W")
if self.current_profile["tdp"] is None:
self.current_profile["tdp"] = 15
else:
# Fallback when processor database unavailable - try detection first
decky.logger.warning("Processor database unavailable, attempting detection fallback")
try:
if processor_support_available:
fallback_min, fallback_max = get_processor_tdp_limits()
self.tdp_limits = {"min": fallback_min, "max": fallback_max}
self.device_info["min_tdp"] = fallback_min
self.device_info["max_tdp"] = fallback_max
if self.current_profile["tdp"] is None:
fallback_default = get_processor_default_tdp()
self.current_profile["tdp"] = fallback_default
decky.logger.info(f"Used detection fallback: {fallback_min}W - {fallback_max}W")
else:
# Last resort only if no processor support at all
self.tdp_limits = {"min": 4, "max": 25}
self.device_info["min_tdp"] = 4
self.device_info["max_tdp"] = 25
if self.current_profile["tdp"] is None:
self.current_profile["tdp"] = 15
decky.logger.warning("Used absolute fallback TDP limits: 4W - 25W")
except Exception:
self.tdp_limits = {"min": 4, "max": 25}
self.device_info["min_tdp"] = 4
self.device_info["max_tdp"] = 25
if self.current_profile["tdp"] is None:
self.current_profile["tdp"] = 15
decky.logger.warning("Used emergency fallback TDP limits: 4W - 25W")
# Apply detected system defaults to current profile
for key, value in system_defaults.items():
if self.current_profile.get(key) is None:
self.current_profile[key] = value
decky.logger.info(f"Set {key} to system default: {value}")
# Ensure hardware-detected CPU core count is used
detected_cores = system_defaults.get("cpuCores", 8)
self.device_info["max_cpu_cores"] = detected_cores
decky.logger.info(f"Set CPU cores to system-detected value: {detected_cores}")
decky.logger.info(f"System-derived defaults applied - TDP: {self.current_profile['tdp']}W, Cores: {self.current_profile['cpuCores']}, Boost: {self.current_profile['cpuBoost']}, SMT: {self.current_profile['smt']}")
except Exception as e:
decky.logger.error(f"Failed to set system-derived defaults: {e}")
# Ensure we have some working defaults even if everything fails
if self.current_profile["tdp"] is None:
decky.logger.warning("TDP still None after all attempts, using emergency fallback")
self.current_profile["tdp"] = 15
if self.current_profile["cpuCores"] is None:
decky.logger.warning("CPU cores still None after all attempts, using emergency fallback")
self.current_profile["cpuCores"] = 8
async def detect_hardware(self):
"""Detect actual hardware using DMI and system information"""
try:
# Get device information from DMI
device_name = await self.read_file_safe("/sys/class/dmi/id/product_name")
sys_vendor = await self.read_file_safe("/sys/class/dmi/id/sys_vendor")
board_name = await self.read_file_safe("/sys/class/dmi/id/board_name")
if device_name:
self.device_info["device_name"] = f"{sys_vendor} {device_name}".strip()
# Detect CPU vendor
cpu_vendor = await self.get_cpu_vendor()
if cpu_vendor:
self.device_info["cpu_vendor"] = cpu_vendor
# Detect processor specifications using processor database
if processor_support_available:
try:
self.processor_info = get_current_processor_info()
decky.logger.info(f"Processor detected: {self.processor_info.get('processor_name', 'Unknown')}")
# Update device info with processor capabilities
if self.processor_info.get('detected', False):
# Don't use processor DB for core count - always detect from hardware
self.device_info["max_cpu_cores"] = await self.detect_max_cpu_cores()
self.device_info["cpu_model"] = self.processor_info.get('processor_name', 'Unknown')
self.device_info["cpu_family"] = self.processor_info.get('family', 'Unknown')
self.device_info["cpu_series"] = self.processor_info.get('series', 'Unknown')
self.device_info["form_factor"] = self.processor_info.get('form_factor', 'Unknown')
self.device_info["node_process"] = self.processor_info.get('node_process', 'Unknown')
self.device_info["gpu_model"] = self.processor_info.get('gpu_model', 'Unknown')
self.device_info["gpu_cu_count"] = self.processor_info.get('gpu_cu_count', 8)
# Update TDP limits based on processor specs
proc_tdp_min, proc_tdp_max = get_processor_tdp_limits()
self.tdp_limits = {"min": proc_tdp_min, "max": proc_tdp_max}
self.device_info["min_tdp"] = proc_tdp_min
self.device_info["max_tdp"] = proc_tdp_max
# CORRECTED: Set PowerDeck default TDP from processor tdp_min (NOT default_tdp)
# PowerDeck default = processor minimum TDP for conservative startup
processor_min_tdp = self.processor_info.get('tdp_min')
if processor_min_tdp:
self.current_profile["tdp"] = processor_min_tdp
decky.logger.info(f"Set PowerDeck default TDP to processor minimum: {processor_min_tdp}W")
else:
decky.logger.warning("No processor tdp_min found, keeping current default")
# Check if it's a handheld device
if is_handheld_device():
self.device_info["is_handheld"] = True
decky.logger.info("Detected handheld gaming device")
else:
self.device_info["is_handheld"] = False
decky.logger.info(f"Processor TDP limits: {proc_tdp_min}W - {proc_tdp_max}W")
decky.logger.info(f"GPU: {self.processor_info.get('gpu_model')} ({self.processor_info.get('gpu_cu_count')} CUs)")
except Exception as e:
decky.logger.warning(f"Processor detection failed: {e}")
self.processor_info = None
# Detect CPU core count (hardware maximum, not just currently online)
if not self.device_info.get("max_cpu_cores"):
try:
self.device_info["max_cpu_cores"] = await self.detect_max_cpu_cores()
except Exception as e:
decky.logger.warning(f"Failed to detect max CPU cores: {e}")
# Even in fallback, try to read from sysfs before giving up
try:
with open('/sys/devices/system/cpu/possible', 'r') as f:
possible_range = f.read().strip()
max_cpu = int(possible_range.split('-')[-1])
self.device_info["max_cpu_cores"] = max_cpu + 1
decky.logger.info(f"Fallback sysfs detection found {max_cpu + 1} cores")
except (OSError, ValueError):
# Try processor database as final attempt before absolute fallback
try:
if processor_support_available:
processor_info = get_current_processor_info()
if processor_info.get("detected") and processor_info.get("max_cpu_cores"):
self.device_info["max_cpu_cores"] = processor_info["max_cpu_cores"]
decky.logger.info(f"Fallback processor database found {processor_info['max_cpu_cores']} cores")
else:
self.device_info["max_cpu_cores"] = 8 # Conservative fallback
decky.logger.warning("Used conservative fallback: 8 cores")
else:
self.device_info["max_cpu_cores"] = 8 # Conservative fallback
decky.logger.warning("Used conservative fallback: 8 cores")
except Exception:
self.device_info["max_cpu_cores"] = 8
decky.logger.warning("Used absolute last resort: 8 cores")
# Check for ryzenadj availability
self.ryzenadj_path = self._find_ryzenadj_binary()
# Initialize device-specific controller
await self._initialize_device_controller()
# Detect device-specific capabilities
await self.detect_capabilities()
decky.logger.info(f"Detected device: {self.device_info['device_name']}")
decky.logger.info(f"CPU vendor: {self.device_info['cpu_vendor']}")
decky.logger.info(f"Ryzenadj available: {bool(self.ryzenadj_path)}")
except Exception as e:
decky.logger.error(f"Hardware detection failed: {e}")
def _find_ryzenadj_binary(self) -> Optional[str]:
"""Find RyzenAdj binary in system paths"""
# Check standard system locations in order of preference
potential_paths = [
"/usr/bin/ryzenadj", # System-wide installation
"/opt/ryzenadj/bin/ryzenadj", # PowerDeck installation location
"/usr/local/bin/ryzenadj", # Alternative system location
]
for path in potential_paths:
if os.path.isfile(path) and os.access(path, os.X_OK):
decky.logger.info(f"Found RyzenAdj binary at: {path}")
return path
# Fallback to PATH search
ryzenadj_path = shutil.which('ryzenadj')
if ryzenadj_path:
decky.logger.info(f"Found RyzenAdj binary in PATH: {ryzenadj_path}")
return ryzenadj_path
decky.logger.warning("RyzenAdj binary not found - TDP control may be limited")
return None
async def _initialize_device_controller(self):
"""Initialize device-specific controller based on detected hardware"""
try:
device_name = self.device_info.get("device_name", "").lower()
# ROG Ally detection - only determines control method, not capabilities
if ("rog ally" in device_name or "rc71" in device_name or "rc72" in device_name) and ROG_ALLY_AVAILABLE:
self.device_controller = get_rog_ally_controller()
self.device_type = "rog_ally"
decky.logger.info("Initialized ROG Ally controller")
# Update device info with ROG Ally specifics (non-TDP info only)
ally_info = self.device_controller.get_device_info()
# Only copy non-TDP related device info
for key, value in ally_info.items():
if "tdp" not in key.lower() and "limit" not in key.lower():
self.device_info[key] = value
# Legion Go detection - only determines control method, not capabilities
elif ("legion" in device_name or "83e1" in device_name or "83l3" in device_name) and LEGION_AVAILABLE:
self.device_controller = get_legion_controller()
self.device_type = "legion"
decky.logger.info("Initialized Legion controller")
# Update device info with Legion specifics (non-TDP info only)
legion_info = self.device_controller.get_device_info()
# Only copy non-TDP related device info
for key, value in legion_info.items():
if "tdp" not in key.lower() and "limit" not in key.lower():
self.device_info[key] = value
# Steam Deck detection - only determines control method, not capabilities
elif ("steam deck" in device_name or "jupiter" in device_name) and STEAM_DECK_AVAILABLE:
self.device_controller = get_steam_deck_controller()
self.device_type = "steam_deck"
decky.logger.info("Initialized Steam Deck controller")
# Update device info with Steam Deck specifics (non-TDP info only)
deck_info = self.device_controller.get_device_info()
# Only copy non-TDP related device info
for key, value in deck_info.items():
if "tdp" not in key.lower() and "limit" not in key.lower():
self.device_info[key] = value
# Generic AMD/Intel device
else:
self.device_type = "generic"
decky.logger.info("Using generic power management")
# TDP limits will be set later from processor database or sysfs detection
# This ensures all devices use the same system-derived approach
decky.logger.info(f"Device controller initialized as {self.device_type} - TDP limits will be determined from processor database")
except Exception as e:
decky.logger.error(f"Failed to initialize device controller: {e}")
self.device_type = "generic"
async def read_file_safe(self, path: str) -> Optional[str]:
"""Safely read a file and return its content"""
try:
with open(path, 'r') as f:
return f.read().strip()
except OSError:
return None
async def get_cpu_vendor(self) -> Optional[str]:
"""Get CPU vendor from /proc/cpuinfo"""
try:
with open("/proc/cpuinfo", 'r') as f:
content = f.read()
for line in content.split('\n'):
if line.startswith('vendor_id'):
vendor = line.split(':')[1].strip()
if vendor == "AuthenticAMD":
return "AMD"
elif vendor == "GenuineIntel":
return "Intel"
else:
return vendor
except OSError:
pass
return None
async def detect_capabilities(self):
"""Detect what power management capabilities are available"""
try:
# Check TDP support
if self.device_info["cpu_vendor"] == "Intel":
# Intel uses RAPL
intel_rapl_paths = [
"/sys/devices/virtual/powercap/intel-rapl-mmio/intel-rapl-mmio:0",
"/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0"
]
self.device_info["supports_tdp"] = any(os.path.exists(path) for path in intel_rapl_paths)
if self.device_info["supports_tdp"]:
# Get Intel TDP limits from hardware - only update max if not already set by processor database
intel_limits = await self.get_intel_tdp_limits()
if intel_limits and self.device_info.get("max_tdp") is None:
self.device_info["min_tdp"] = intel_limits[0]
self.device_info["max_tdp"] = intel_limits[1]
self.tdp_limits = {"min": intel_limits[0], "max": intel_limits[1]}
decky.logger.info(f"Intel RAPL TDP limits detected: {intel_limits[0]}W - {intel_limits[1]}W")
else:
# AMD uses ryzenadj or device-specific methods
self.device_info["supports_tdp"] = bool(self.ryzenadj_path)
# TDP limits are already set from processor database in _set_system_derived_defaults()
# Do not override with hard-coded fallback values here
# Check CPU boost support
cpu_boost_paths = [
"/sys/devices/system/cpu/intel_pstate/no_turbo", # Intel
"/sys/devices/system/cpu/cpufreq/policy0/boost" # AMD
]
self.device_info["supports_cpu_boost"] = any(os.path.exists(path) for path in cpu_boost_paths)
# Check SMT support
self.device_info["supports_smt"] = os.path.exists("/sys/devices/system/cpu/smt/control")
# Check GPU control support - both AMD and Intel
amd_gpu_control_paths = [
"/sys/class/drm/card0/device/power_dpm_force_performance_level",
"/sys/class/drm/card1/device/power_dpm_force_performance_level"
]
amd_gpu_support = any(os.path.exists(path) for path in amd_gpu_control_paths)
# Check Intel GPU support via sysfs power manager
intel_gpu_capabilities = sysfs_power_manager.get_capabilities()
intel_gpu_support = intel_gpu_capabilities.supports_intel_gpu
self.device_info["supports_gpu_control"] = amd_gpu_support or intel_gpu_support
if self.device_info["supports_gpu_control"]:
# Get GPU frequency limits (works for both AMD and Intel)
await self.detect_gpu_limits()
# Universal power management feature detection
await self.detect_universal_power_features()
except Exception as e:
decky.logger.error(f"Capability detection failed: {e}")
async def detect_universal_power_features(self):
"""Detect universal power management features available on any device"""
try:
# PCIe ASPM support
aspm_path = "/sys/module/pcie_aspm/parameters/policy"
self.device_info["supports_pcie_aspm"] = os.path.exists(aspm_path)
# CPU C-State management
cstate_path = "/sys/devices/system/cpu/cpu0/cpuidle"
self.device_info["supports_cstate_control"] = os.path.exists(cstate_path)
# USB power management
usb_power_path = "/sys/bus/usb/devices"
self.device_info["supports_usb_power_mgmt"] = os.path.exists(usb_power_path)
# WiFi power saving detection
self.device_info["supports_wifi_power_save"] = await self.detect_wifi_interfaces()
# Memory pressure controls
self.device_info["supports_memory_tuning"] = os.path.exists("/proc/sys/vm/swappiness")
# Audio power management
audio_power_path = "/sys/class/sound"
self.device_info["supports_audio_power_mgmt"] = os.path.exists(audio_power_path)
decky.logger.info(f"Universal power features detected: ASPM={self.device_info.get('supports_pcie_aspm')}, "
f"C-States={self.device_info.get('supports_cstate_control')}, "
f"USB={self.device_info.get('supports_usb_power_mgmt')}, "
f"WiFi={self.device_info.get('supports_wifi_power_save')}, "
f"Memory={self.device_info.get('supports_memory_tuning')}, "
f"Audio={self.device_info.get('supports_audio_power_mgmt')}")
except Exception as e:
decky.logger.error(f"Universal power feature detection failed: {e}")
async def detect_wifi_interfaces(self) -> bool:
"""Detect if WiFi interfaces are available for power management"""
try:
# Check for wireless interfaces
with open("/proc/net/wireless", "r") as f:
lines = f.readlines()
return len(lines) > 2 # Header lines + at least one interface
except OSError:
return False
async def get_intel_tdp_limits(self) -> Optional[tuple]:
"""Get Intel TDP limits from RAPL"""
try:
max_power_paths = [
"/sys/devices/virtual/powercap/intel-rapl-mmio/intel-rapl-mmio:0/constraint_0_max_power_uw",
"/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0/constraint_0_max_power_uw"
]
for path in max_power_paths:
if os.path.exists(path):
with open(path, 'r') as f:
max_power_uw = int(f.read().strip())
max_tdp = max_power_uw // 1000000 # Convert to watts
return (4, max_tdp) # Min 4W, max from hardware
except (OSError, ValueError):
pass
return None
async def detect_gpu_limits(self):
"""Detect GPU frequency limits - supports both AMD and Intel GPUs"""
try:
# Check if Intel GPU is available via sysfs power manager
intel_gpu_capabilities = sysfs_power_manager.get_capabilities()
if intel_gpu_capabilities.supports_intel_gpu:
# Intel GPU limits from sysfs power manager
if intel_gpu_capabilities.gpu_min_freq_mhz and intel_gpu_capabilities.gpu_max_freq_mhz:
self.device_info["min_gpu_freq"] = intel_gpu_capabilities.gpu_min_freq_mhz
self.device_info["max_gpu_freq"] = intel_gpu_capabilities.gpu_max_freq_mhz
decky.logger.info(f"Intel GPU limits detected: {intel_gpu_capabilities.gpu_min_freq_mhz}-{intel_gpu_capabilities.gpu_max_freq_mhz} MHz")
else:
# Fallback values for Intel GPU
self.device_info["min_gpu_freq"] = 300
self.device_info["max_gpu_freq"] = 1100
decky.logger.info("Intel GPU limits using fallback values: 300-1100 MHz")
else:
# Check for AMD GPU overdrive
od_clk_path = "/sys/class/drm/card0/device/pp_od_clk_voltage"
if os.path.exists(od_clk_path):
with open(od_clk_path, 'r') as f:
content = f.read()
lines = content.split('\n')
for line in lines:
if line.startswith('SCLK:'):
parts = line.split()
if len(parts) >= 3:
min_freq = int(parts[1].replace('Mhz', ''))
max_freq = int(parts[2].replace('Mhz', ''))
self.device_info["min_gpu_freq"] = min_freq
self.device_info["max_gpu_freq"] = max_freq
decky.logger.info(f"AMD GPU limits detected: {min_freq}-{max_freq} MHz")
break
except Exception as e:
decky.logger.error(f"GPU limit detection failed: {e}")
async def load_saved_settings(self):
"""Load saved settings and profiles"""
try:
if self.settings:
decky.logger.info(f"LOAD_SETTINGS: Starting to load saved settings")
saved_settings = self.settings.get("powerDeckSettings", {})
decky.logger.info(f"LOAD_SETTINGS: Found saved settings: {saved_settings}")
if "currentProfile" in saved_settings:
old_profile = self.current_profile.copy()
self.current_profile.update(saved_settings["currentProfile"])
decky.logger.info(f"LOAD_SETTINGS: Updated current profile from {old_profile} to {self.current_profile}")
else:
decky.logger.warning(f"LOAD_SETTINGS: No currentProfile found in saved settings")
if "tdpLimits" in saved_settings:
old_limits = self.tdp_limits.copy()
self.tdp_limits.update(saved_settings["tdpLimits"])
decky.logger.info(f"LOAD_SETTINGS: Updated TDP limits from {old_limits} to {self.tdp_limits}")
if "enablePerGameProfiles" in saved_settings:
self.enable_per_game_profiles = saved_settings["enablePerGameProfiles"]
decky.logger.info(f"LOAD_SETTINGS: Set enablePerGameProfiles to {self.enable_per_game_profiles}")
if "rogAllyNativeTdpEnabled" in saved_settings:
self.rog_ally_native_tdp_enabled = saved_settings["rogAllyNativeTdpEnabled"]
decky.logger.info(f"LOAD_SETTINGS: Set rogAllyNativeTdpEnabled to {self.rog_ally_native_tdp_enabled}")
else:
# Default to True for ROG Ally devices, False for others if not found in settings
# Keep last known value or default to False to prevent unexpected UI changes
self.rog_ally_native_tdp_enabled = False
decky.logger.info(f"LOAD_SETTINGS: Set default rogAllyNativeTdpEnabled to {self.rog_ally_native_tdp_enabled} (ROG Ally device: {await self.is_rog_ally_device()})")
else:
decky.logger.error(f"LOAD_SETTINGS: self.settings is None!")
except Exception as e:
decky.logger.error(f"Failed to load saved settings: {e}")
async def save_settings(self):
"""Save current settings"""
try:
if self.settings:
# Ensure we always have complete settings structure
existing = self.settings.get("powerDeckSettings", {})
settings_data = {
**existing, # Keep any existing settings
"currentProfile": self.current_profile,
"tdpLimits": self.tdp_limits,
"enablePerGameProfiles": self.enable_per_game_profiles,
"rogAllyNativeTdpEnabled": self.rog_ally_native_tdp_enabled
}
decky.logger.info(f"SAVE_SETTINGS: Saving settings data: {settings_data}")
self.settings.set("powerDeckSettings", settings_data)
decky.logger.info(f"SAVE_SETTINGS: Settings saved successfully")
else:
decky.logger.error(f"SAVE_SETTINGS: self.settings is None!")
except Exception as e:
decky.logger.error(f"Failed to save settings: {e}")
async def get_ac_power_status_with_retry(self, max_retries: int = 5, delay_seconds: float = 2.0) -> bool:
"""Get AC power status with retry logic for initialization during boot"""
import asyncio
for attempt in range(max_retries):
try:
decky.logger.info(f"AC power detection attempt {attempt + 1}/{max_retries}")
# Check multiple common AC power supply paths for broader device compatibility
ac_paths = [
"/sys/class/power_supply/ACAD/online", # Generic/ROG Ally
"/sys/class/power_supply/ADP1/online", # Ayaneo Air and many laptops
"/sys/class/power_supply/AC/online", # Some other devices
"/sys/class/power_supply/ADP0/online" # Alternative naming
]
ac_connected = False
detected_path = None
for ac_path in ac_paths:
if os.path.exists(ac_path):
try:
with open(ac_path, 'r') as f:
ac_value = f.read().strip()
ac_connected = ac_value == "1"
detected_path = ac_path
decky.logger.info(f"AC detection via {ac_path}: {ac_connected} (value: {ac_value})")
break # Use first available path
except Exception as e:
decky.logger.warning(f"Failed to read AC power from {ac_path}: {e}")
continue
if detected_path:
# If we detect AC power, return immediately (no need to retry)
if ac_connected:
decky.logger.info(f"AC power confirmed on attempt {attempt + 1} via {detected_path}")
return True
# If AC not detected but this isn't the last attempt, continue retrying
if attempt < max_retries - 1:
decky.logger.info(f"AC not detected on attempt {attempt + 1} via {detected_path}, will retry...")
# Return False if this was the last attempt and no AC detected
elif attempt == max_retries - 1:
decky.logger.info(f"Final attempt: AC not connected via {detected_path}")
return False
else:
decky.logger.warning(f"No AC power supply paths found on attempt {attempt + 1}")
# Wait before next retry (except on last attempt)
if attempt < max_retries - 1:
decky.logger.info(f"Waiting {delay_seconds}s before retry...")
await asyncio.sleep(delay_seconds)
except Exception as e:
decky.logger.warning(f"AC power detection attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
await asyncio.sleep(delay_seconds)
# If all attempts failed to detect AC, default to AC mode for better user experience
# (Better to have higher TDP than to be stuck at low battery TDP)
decky.logger.warning("All AC power detection attempts failed, defaulting to AC mode for safety")
return True
async def load_unified_profiles(self):
"""Load settings from unified profile system instead of old settings format"""
try:
# CRITICAL: Load saved settings first (rogAllyNativeTdpEnabled, enablePerGameProfiles, etc.)
await self.load_saved_settings()
debug_log("Starting unified profile loading")
# Detect current power state with retry logic for reliable boot detection
ac_connected = await self.get_ac_power_status_with_retry()
power_mode = "ac" if ac_connected else "battery"
profile_id = f"00000000_{power_mode}"
debug_log(f"Loading unified profile for power mode: {power_mode} (AC: {ac_connected})")
decky.logger.info(f"BOOT INITIALIZATION: Power mode detected as {power_mode} (AC: {ac_connected})")
# Load the appropriate default profile
profile_data = await self.load_profile(profile_id)
if profile_data:
debug_log(f"Successfully loaded unified profile {profile_id}: {profile_data}")
# CRITICAL FIX: Use processor tdp_min as PowerDeck default (NOT default_tdp)
# PowerDeck default TDP = processor minimum TDP, range = 4W to processor max TDP
processor_min_tdp = 15 # Fallback default