Compare commits

...

226 Commits
4.7.0 ... 6.0.5

Author SHA1 Message Date
Luke D. Jones
ccf8d8df91 Prep 6.0.5 version 2024-05-10 12:44:46 +12:00
Luke D. Jones
b970d364f7 Fix test 2024-05-10 12:36:34 +12:00
Luke D. Jones
1da68ea69d Try to mitigate the lack of kbd_brightness on some laptops 2024-05-10 12:22:36 +12:00
Luke D. Jones
e62e7e8eca Cleanup sys config 2024-05-10 10:26:32 +12:00
Luke D. Jones
1b1d10c461 Try to better handle pre-2021 laptops with lightbar 2024-05-10 10:04:51 +12:00
Stefan Boca
14ea0f6d83 Update GA402XV supported aura modes 2024-05-08 19:20:17 -07:00
Luke Jones
5107a6c39c Merge branch 'FAYZER77-main-patch-34823' into 'main'
Change 733C model profile to add support for Lid LED, and remove unneeded basic zones entries

See merge request asus-linux/asusctl!183
2024-05-08 23:12:56 +00:00
FAYZER77
2c77ec9e24 Change 733C model profile to add support for Lid LED, and remove unneeded basic zones entries 2024-05-08 23:08:19 +00:00
Luke D. Jones
817a66bdf1 Prep 6.0.4 2024-05-09 11:00:51 +12:00
Luke D. Jones
664a3d5533 Match G533Q to 0x8166 keyboard ID explicitly
Should close #438
2024-05-09 10:01:48 +12:00
Luke D. Jones
37bc5e45b9 Fix: ensure property derive is on all property methods for slash 2024-05-09 09:34:02 +12:00
Luke D. Jones
a18692ef1e Fix up colour sliders
- Fixup colour sliders for UI
- Correctly drop tokio runtime
2024-05-08 22:55:11 +12:00
Luke D. Jones
1b023d0f5f Fix and prep new 6.0.2 release 2024-05-08 16:27:40 +12:00
Luke D. Jones
74f74e73c4 Update deps, point release 2024-05-07 13:56:25 +12:00
Luke D. Jones
9c7df9ad39 Update deps, point release 2024-05-07 12:58:17 +12:00
Luke D. Jones
94adf5d24d Revert back to zbus 4.1 2024-05-06 23:54:36 +12:00
Luke D. Jones
8dbdb68175 Increase tray icon sleep time 2024-05-06 23:14:51 +12:00
Luke D. Jones
89002eb5ec Use fluent-dark instead of cosmic due to compile times 2024-05-06 23:01:03 +12:00
Luke D. Jones
dc9ef8cf54 Remove unused deps 2024-05-06 13:25:07 +12:00
Luke D. Jones
667697d042 Cleanup deps 2024-05-06 10:58:11 +12:00
Luke D. Jones
bc92fa11f9 Update all cargo.toml. Support G713P 2024-05-06 09:45:35 +12:00
Luke D. Jones
f5d5681b49 Prep changelog 2024-05-05 20:52:38 +12:00
Luke D. Jones
1c8e50843b Cleanup files, prep new release 2024-05-05 20:22:56 +12:00
Luke D. Jones
487d140bd5 Anime: Better prevent await blocking. Prevent Slash taking over anime USB dev 2024-05-05 10:56:55 +12:00
Luke D. Jones
661ea8d3bf Fix fedora install instruction 2024-04-19 11:11:58 +12:00
Luke D. Jones
28d1ed6ab3 Fix broke logix 2024-04-18 14:40:39 +12:00
Luke D. Jones
903b978e86 Add missing files 2024-04-18 13:55:02 +12:00
Luke D. Jones
519f6bd46b Cleanup notifs, sys state, ac/bat commands 2024-04-18 13:48:23 +12:00
Luke D. Jones
a94a8ca28d Support the GU605M keyboard 2024-04-18 10:08:40 +12:00
Luke D. Jones
f9dca2da5d Re-add TUF keyboard support 2024-04-17 21:39:58 +12:00
Luke Jones
df88ff1acb Update asusd.service 2024-04-17 06:11:00 +00:00
Luke Jones
cb5aa0f170 Update asusd.service 2024-04-17 06:10:44 +00:00
Luke D. Jones
4ea79f966e Add updated translation + aura_support.ron 2024-04-17 14:18:27 +12:00
Luke D. Jones
b8bc1a01b3 Fix colour hex in gui 2024-04-17 12:46:36 +12:00
Luke D. Jones
0e5d1815bd Bump alpha version 2024-04-17 11:55:19 +12:00
Luke D. Jones
64e8cb65d0 Many cleanup and fix 2024-04-17 11:54:14 +12:00
Luke D. Jones
3142353f98 Fix tests 2024-04-11 13:18:03 +12:00
Luke D. Jones
484ca692ad Refactoring led support data 2024-04-10 21:14:47 +12:00
Luke D. Jones
1ebdfada96 Update discord invite 2024-04-10 18:09:41 +12:00
Luke D. Jones
3bc9dfcda1 Support GA402N keyboard 2024-04-10 17:04:21 +12:00
Luke D. Jones
895e5d2ca3 Support GA402N keyboard 2024-04-10 17:04:08 +12:00
Luke D. Jones
564992719e Fixes to slash merge 2024-04-10 09:13:26 +12:00
Luke Jones
a737d240be Merge pull request #23 from jschoubben/main
Add support for 2024 G14 Slash lighting (GA403UI)
2024-04-10 08:55:17 +12:00
Luke Jones
d89c1ebf26 Merge branch 'main' into main 2024-04-10 08:54:54 +12:00
Luke D. Jones
be7686bb46 Dump deps and version 2024-04-09 21:24:55 +12:00
Luke D. Jones
4f70055f85 Complete building 2024-04-09 21:02:09 +12:00
Luke D. Jones
91ca049298 Unify the laptop aura power stuff 2024-04-09 12:13:42 +12:00
Luke D. Jones
635d0378ac Bump deps 2024-04-06 14:10:18 +13:00
Luke D. Jones
1c729316f7 Refactor, rename, organise rog-aura stuff better 2024-04-05 21:20:34 +13:00
Luke D. Jones
4701c019a8 Major cleanup of older gui state code 2024-04-05 20:19:07 +13:00
Luke D. Jones
ca0d8bda4b Update readme. Fix tray startup 2024-04-05 16:00:20 +13:00
Luke D. Jones
a271ffbb10 rcc: run as app only on Ally 2024-04-04 09:58:40 +13:00
Luke D. Jones
00babaf949 Update translations 2024-04-03 16:15:09 +13:00
Luke D. Jones
2f844ac151 Cleanup 2024-04-03 16:15:09 +13:00
Luke D. Jones
5178bf1d1a Update readme 2024-04-03 16:15:09 +13:00
jochen@g14
116afb9b6c Initialize slash from config file 2024-03-31 01:08:26 +01:00
jochen@g14
4468a58487 Use enable/disable commands and cleanup build warnings 2024-03-31 00:34:44 +01:00
jochen@g14
2f73577e91 Fix Cargo.toml 2024-03-30 23:33:30 +01:00
jochen@g14
c1cffc8f59 Remove example file since it's not correct 2024-03-30 23:29:55 +01:00
jochen@g14
6d8f85c154 Minor changes to reflect original files 2024-03-30 23:27:33 +01:00
jochen@g14
0674e7f61c Changes after my own PR review 2024-03-30 23:23:37 +01:00
jochen@g14
fde2f3ba15 Fixed issues with asusctl-slash command 2024-03-30 21:19:55 +01:00
jochen@g14
70493d1a93 Fix error in makefile 2024-03-30 19:39:42 +01:00
jochen@g14
c20d0a76a0 Fix build after merge 2024-03-30 19:00:22 +01:00
jochen@g14
e6952e241a Merge from main 2024-03-30 18:44:15 +01:00
jochen@g14
b40812928a Imlement Display and FromStr traits for SlashMode 2024-03-30 18:42:42 +01:00
jochen@g14
8cdc9773c9 Added working implementation of the G14 Slash ledstrip 2024-03-30 18:41:31 +01:00
Luke Jones
8d30282edf Update default.md 2024-03-28 01:03:30 +00:00
Luke D. Jones
4ba44560a9 Update deps 2024-03-27 19:27:22 +13:00
jochen@g14
cdc9ca7b58 Try to implement slash bar functionality - part 1 2024-03-25 01:54:05 +01:00
Luke D. Jones
7eae7c5664 Change aura manager task to blocking. Remove idle tasks that keep hanging 2024-03-24 21:14:54 +13:00
Luke D. Jones
739a0ffa63 aura debugging 2024-03-24 10:55:20 +13:00
Luke D. Jones
637360095c Shift init actions up a few calls to prevent over-eager init 2024-03-23 23:27:26 +13:00
Luke D. Jones
4b34ab83fb Initial pass of async task sync in aura 2024-03-23 23:15:38 +13:00
Luke D. Jones
ac605cbc00 Narrow the search space of aura devices down 2024-03-23 14:30:00 +13:00
Luke D. Jones
4b38e5daa6 Further adjustments to aura 2024-03-23 13:07:20 +13:00
Luke D. Jones
1c007b4216 Small refinement to aura control init 2024-03-23 11:45:20 +13:00
Luke D. Jones
193f9dfa1e Extra logging for aura 2024-03-23 11:27:20 +13:00
Jochen@Jinbe
1366422d96 Play around and add rog-slash 2024-03-22 22:05:27 +01:00
Luke D. Jones
4e778a3d28 Refactor HidRaw 2024-03-22 19:47:24 +13:00
Luke D. Jones
be05508110 Try to ensure all aura are detected at start 2024-03-22 17:36:58 +13:00
Luke D. Jones
9119229d41 Update deps 2024-03-20 23:12:52 +13:00
Luke D. Jones
5c43c31331 Manage add/remove aura
Serialize aura config filename
2024-03-20 23:00:25 +13:00
Luke D. Jones
014604724f Fix clippy lints 2024-03-15 19:41:38 +13:00
Luke D. Jones
7d076368e9 Adjust organization of rog control src 2024-03-15 17:19:54 +13:00
Luke D. Jones
5d6ed5c365 Remove old screenshits 2024-03-14 22:17:42 +13:00
Luke D. Jones
a2b8f0f93c Minor updates 2024-03-14 22:10:14 +13:00
Luke D. Jones
5fe8416c65 Only apply fan curve for profile if *on* that profile, but still save config 2024-03-14 21:28:06 +13:00
Luke D. Jones
1b4d7a95af Minor corrections 2024-03-14 21:24:28 +13:00
Luke D. Jones
e8627fde4c Fix applying disabled and enabled fan curves 2024-03-14 21:11:18 +13:00
Luke D. Jones
6b0edc6da1 Enable fan curves 2024-03-14 17:17:55 +13:00
Luke D. Jones
f6ad631a0f Update readme 2024-03-14 11:19:31 +13:00
Luke D. Jones
f6393a3926 Further fan-curve graph work 2024-03-13 23:30:06 +13:00
Luke D. Jones
d51384c3a1 Fix the fan curve defaults again 2024-03-13 21:19:01 +13:00
Luke D. Jones
78f18959fb Populate fan curve data 2024-03-13 20:18:41 +13:00
Luke D. Jones
7a661a585e Add missing file 2024-03-13 19:14:29 +13:00
Luke D. Jones
f4f7a1e648 Check in the fan curve work 2024-03-13 18:57:38 +13:00
Luke D. Jones
b6e3e5e823 Remove a dbg 2024-03-13 14:08:43 +13:00
Luke D. Jones
41b1bd23d6 Fix fancurves 2024-03-13 14:08:08 +13:00
Luke D. Jones
69458a0595 Minor fix to graph widget 2024-03-12 22:06:56 +13:00
Luke D. Jones
5fd107df27 Initial fan graph widget 2024-03-12 21:33:39 +13:00
Luke D. Jones
2558057e9f Use mix instead of interpolate 2024-03-12 00:09:54 +13:00
Luke D. Jones
8111daaf1d Use mix instead of interpolate 2024-03-12 00:08:54 +13:00
Luke D. Jones
672acb234f Make aura settings apply instantly 2024-03-11 23:27:07 +13:00
Luke D. Jones
9725062fb9 Refactor and cleanup theming 2024-03-11 22:26:26 +13:00
Luke D. Jones
c7b1624313 Remove dbg statements 2024-03-11 12:53:38 +13:00
Luke D. Jones
67b97f1d43 Update ci and readme 2024-03-10 23:29:50 +13:00
Luke D. Jones
6498fd1349 Move rog<->slint type conversions to module 2024-03-10 21:12:36 +13:00
Luke D. Jones
e371229b6c Update support for boot_sound kernel patch 2024-03-10 20:53:03 +13:00
Luke D. Jones
0fac33a8ff Update pipeline 2024-03-09 23:49:42 +13:00
Luke D. Jones
b0da062577 Clean up debug info 2024-03-09 23:30:15 +13:00
Luke D. Jones
ca41bd59de Begin implmenting keyboard power states 2024-03-09 23:18:30 +13:00
Luke D. Jones
efcad3f6f9 Small colour correction 2024-03-06 22:41:55 +13:00
Luke D. Jones
fa2255cbaf Atempt better aura colour mix 2024-03-06 22:35:16 +13:00
Luke D. Jones
02b9bac899 Clean up the tray code 2024-03-04 13:28:19 +13:00
Luke D. Jones
a1fcf5023c Force tray process to exit if Quit 2024-03-03 22:41:57 +13:00
Luke D. Jones
2f8ea80e6d Replace shitty gtk tray with betrayer 2024-03-03 22:26:52 +13:00
Luke D. Jones
b798cf6a4e Minor adjust to rgb bright slider 2024-03-03 13:30:46 +13:00
Luke D. Jones
3da848d131 Init with colour sliders in approx position 2024-03-03 12:57:45 +13:00
Luke D. Jones
a88c33c201 MOrE 2024-03-02 23:49:11 +13:00
Luke D. Jones
7b0f037cba Trying different strategies for non-blocking UI 2024-02-25 23:21:11 +13:00
Luke D. Jones
91b1456d06 Formulate slint patterns 2024-02-25 19:24:20 +13:00
Luke D. Jones
c3b02a2bb0 Fix the IPC 2024-02-25 13:09:13 +13:00
Luke D. Jones
8e4b7d53f4 More updating to zbus 4.0.1 2024-02-24 21:56:52 +13:00
Luke D. Jones
a44145f487 Update to zbus 4.0.1 2024-02-24 21:56:29 +13:00
Luke D. Jones
bb7b3a81fb Bump version 2024-02-24 21:50:52 +13:00
Luke D. Jones
19607d71c3 Prep 5.0.8 release 2024-02-24 17:09:24 +13:00
Luke D. Jones
96f281d789 Remove the use of bytes in zbus signatures 2024-02-23 21:50:53 +13:00
Luke D. Jones
7613eded95 Sane defaults for asusd config 2024-02-23 14:40:00 +13:00
Luke D. Jones
50eccd2b1d Formatting and fixes 2024-02-23 12:36:16 +13:00
Luke Jones
ba54007102 Merge branch 'bugfix/persistent-theme' into 'main'
Reintroduce persistent dark/light mode

See merge request asus-linux/asusctl!180
2024-02-19 19:44:59 +00:00
Filip Binkiewicz
a028f5375f Reintroduce persistent dark/light mode 2024-02-19 19:27:56 +00:00
Luke Jones
9ec02cd727 Merge branch 'dearner-main-patch-22870' into 'main'
Added G814JZ to aura_support.ron (uses G814JI keymap)

See merge request asus-linux/asusctl!179
2024-02-14 01:40:26 +00:00
Chris Dearner
4b46ece09a Added G814JZ to aura_support.ron (uses G814JI keymap) 2024-02-05 12:49:49 +00:00
Luke D. Jones
086bbd0908 Fix the broken pipe error 2024-02-02 23:26:41 +13:00
Luke D. Jones
c94eaa473e Update TS bindings 2024-01-24 22:37:10 +13:00
Luke D. Jones
b1b809834b Reload and apply settings if config file externally changed 2024-01-24 12:19:34 +13:00
Luke D. Jones
84183288ec Fix inotify watch failing thanks to vim idiocy 2024-01-23 22:44:20 +13:00
Luke D. Jones
86cbef83b6 Reload asusd.ron if changed 2024-01-22 21:54:19 +13:00
Luke D. Jones
006fb632c4 Doc and feature fixes 2024-01-22 19:33:40 +13:00
Luke D. Jones
e3636ed8ce Update smithay-client-toolkit 2024-01-22 12:06:42 +13:00
Luke D. Jones
cfd207f251 Remove async-trait crate and set min rustc 1.75 2024-01-15 18:22:41 +13:00
Luke D. Jones
d4c68546e7 Added ability to change what EPP is linked with each throttle profile 2024-01-15 18:00:27 +13:00
Luke D. Jones
6f4a7e16dc Fixes to RCC 2024-01-05 14:21:31 +13:00
Luke D. Jones
f64253d633 Various bugfixes 2024-01-05 13:53:57 +13:00
Luke D. Jones
124c17aadc Add default issue template 2024-01-04 14:30:11 +13:00
Luke D. Jones
ab40f9fcbf Add FX705D led support 2024-01-04 09:23:37 +13:00
Luke D. Jones
5cdfa5a8d4 Fix to suspend process in anime thread to let custom anims run on wake 2023-12-27 11:24:39 +13:00
Luke D. Jones
ce870cd5ed Revert egui update due to a lot of issues arising from window closing 2023-12-27 10:13:26 +13:00
Luke D. Jones
4541d2e1ba Update dbus introspection 2023-12-26 11:56:47 +13:00
Luke D. Jones
b525411fd3 Minor fixes in asusctl 2023-12-25 21:24:05 +13:00
Luke D. Jones
a867496f13 Re-enable ROGCC fan curves 2023-12-24 10:30:33 +13:00
Luke D. Jones
f421b8ee3b Fix to apply led effect in rogcc 2023-12-23 21:45:19 +13:00
Luke D. Jones
82780feb4b Update readme 2023-12-23 10:37:46 +13:00
Luke D. Jones
1e5443e206 Bugfix release 2023-12-22 11:39:17 +13:00
Luke D. Jones
027a591d26 Add cargo-vendor-filterer to pipeline 2023-12-17 21:44:33 +13:00
Luke D. Jones
e90375828d Fix: nuke some async deadlocks in fan-curves 2023-12-17 21:41:07 +13:00
Luke D. Jones
75b4d67072 Fix: force Anime power/wakeup disabled to prevent idiotic random wakes 2023-12-15 19:15:14 +13:00
Luke D. Jones
9aa332de3b New release 2023-12-15 11:50:49 +13:00
Luke D. Jones
5efd7fc6a7 Fix: Corrections to dbus signature for some keyboard power settings
Closes #423
2023-12-15 11:48:20 +13:00
Luke D. Jones
0aafe24a02 Fix: correctiosn to asusd.service
Closes #424
2023-12-15 11:48:20 +13:00
Luke D. Jones
dda6d343d9 Fix: correction to switching next fan profile
Closes #425
2023-12-15 11:48:18 +13:00
Luke D. Jones
6f39307080 remember how to tag releases 2023-12-12 22:00:37 +13:00
Luke Jones
ef63789faa Merge branch 'main' into 'main'
Added missing button, and fixed layout for Strix G18

See merge request asus-linux/asusctl!176
2023-12-12 08:58:31 +00:00
Sunehildeep Singh
c422e77ba6 Added missing button, and fixed layout for Strix G18 2023-12-12 08:58:31 +00:00
Luke D. Jones
3c234dd3c4 Release 5.0.0 2023-12-12 21:54:24 +13:00
Luke Jones
c420dd820a Merge branch '419-support-for-strix-g18-aura-g814ji-already-done-need-merge' into 'main'
Draft: Resolve "Support For Strix G18 AURA (G814JI) - Already Done, need merge"

Closes #419

See merge request asus-linux/asusctl!175
2023-12-10 20:03:55 +00:00
Luke D. Jones
a3e6fec163 Add g814ji and layout 2023-12-11 08:56:17 +13:00
Luke D. Jones
9b4e76be87 Update examples 2023-12-11 08:49:32 +13:00
Luke D. Jones
7b2125cbdf fic async deadlock in platform control 2023-12-08 20:06:22 +13:00
Luke D. Jones
694a644cc6 Revert "Fix: change epp change watch to a loop to prevent deadlock"
This reverts commit c06f78990f.
2023-12-08 20:06:22 +13:00
Luke D. Jones
922aa0c352 platform example testing 2023-12-08 17:33:27 +13:00
Luke D. Jones
c06f78990f Fix: change epp change watch to a loop to prevent deadlock 2023-12-07 20:04:21 +13:00
Luke D. Jones
5c8bb6e6ea Ensure thermal policy is set on resume and relaod 2023-12-05 19:26:49 +13:00
Luke Jones
993131d0a9 Merge branch 'fluke/dbus-refactor' into 'main'
Fluke/dbus refactor

See merge request asus-linux/asusctl!173
2023-12-03 20:44:01 +00:00
Luke Jones
0a69c23288 Fluke/dbus refactor 2023-12-03 20:44:01 +00:00
Luke D. Jones
f6e4cc0626 Cleanup after changes from Platform dbus rework 2023-11-18 22:36:55 +13:00
Luke D. Jones
1f696508e7 rog-platform: refactor all related parts 2023-11-18 21:57:46 +13:00
Luke D. Jones
fa043adc99 rog-platform: add CPU and GPU tunings
rog-platform: add tunables to supported dat

Anime: fixes to how some power options work
2023-11-17 17:16:03 +13:00
Luke D. Jones
b9c2d929b3 anime: rework sleep logic 2023-11-16 13:57:42 +13:00
Luke D. Jones
eda1e920df Update changelog 2023-11-15 18:29:35 +13:00
Luke D. Jones
0de2c9e424 Anime: remove sleep animation config 2023-11-15 18:27:58 +13:00
Luke D. Jones
e88e7be8ae Anime: expose new options in CLI 2023-11-15 17:45:52 +13:00
Luke D. Jones
e470d3acc0 Anime: add dbus methods 2023-11-15 17:23:44 +13:00
Luke D. Jones
f5b3f0bc38 Fix lints on examples 2023-11-15 17:23:35 +13:00
Luke D. Jones
19497c94e0 Anime: fix data struct 2023-11-15 16:56:50 +13:00
Luke D. Jones
670eee23e8 Anime: small cleanup 2023-11-15 16:45:30 +13:00
Luke D. Jones
26309776e9 Fix test 2023-11-15 14:47:52 +13:00
Luke D. Jones
a7d5057976 Anime: propagate property config 2023-11-15 14:46:42 +13:00
Luke D. Jones
8eb9b1d4eb Anime: refactor power stuff 2023-11-15 14:29:38 +13:00
Luke D. Jones
71ee9e43ba Fix gnome-45 extension version 2023-11-14 16:49:17 +13:00
Luke D. Jones
f1b0e1288a Add missing crates 2023-11-13 11:28:34 +13:00
Luke D. Jones
35c7fd10b3 Drop sysfs_class and create dmi_id for getting identifying info with udev 2023-11-08 14:00:35 +13:00
Luke D. Jones
4c50dc259c rog-control-center: ensure brightness slider works correctly 2023-11-08 13:59:07 +13:00
Luke D. Jones
0fd0aeff88 Support Rog Ally LED modes (basic) 2023-11-07 17:24:38 +13:00
Luke Jones
fd37f41ef1 Merge branch 'sctk-0.16.1' into 'main'
cargo update -p smithay-client-toolkit v0.16.0 -> v0.16.1

Closes #407

See merge request asus-linux/asusctl!172
2023-10-11 06:30:37 +00:00
Cole Mickens
1307997122 cargo update -p smithay-client-toolkit v0.16.0 -> v0.16.1 2023-10-11 08:15:04 +02:00
Luke Jones
85187d2d8d Merge branch 'add_laptop_G513RW' into 'main'
Added preliminary support for G513RW

See merge request asus-linux/asusctl!171
2023-09-16 05:51:15 +00:00
Edwin Clement
e29a568195 Added preliminary support for G513RW 2023-09-15 20:03:02 -04:00
Luke D. Jones
6c375a9951 Prep new release 2023-09-08 13:22:15 +12:00
Luke D. Jones
4641e19c43 Fix bad keybaord layout 2023-09-04 10:19:57 +12:00
Luke D. Jones
91f0c2ea14 Fix loading of fan curves
Closes #402

Signed-off-by: Luke D. Jones <luke@ljones.dev>
2023-09-04 10:18:48 +12:00
Luke Jones
b4a8cb9de2 Merge branch 'srivatsarog-main-patch-78688' into 'main'
Update aura_support.ron

See merge request asus-linux/asusctl!169
2023-09-03 08:45:39 +00:00
Luke Jones
67bbcdb964 Merge branch 'main' into 'srivatsarog-main-patch-78688'
# Conflicts:
#   rog-aura/data/aura_support.ron
2023-09-03 08:37:52 +00:00
Luke Jones
8acfe0a9e8 Merge branch 'main' into 'main'
aura: Support for G733PZ

See merge request asus-linux/asusctl!167
2023-09-03 08:36:20 +00:00
Luke D. Jones
5f6e6ec382 gex: rename gnome-44, add gnome-45 2023-08-31 14:36:01 +12:00
Luke D. Jones
cf92526d87 Set cargo resolver 2023-08-31 12:42:31 +12:00
Luke D. Jones
f290594562 Prep release 2023-08-26 21:40:45 +12:00
Luke D. Jones
423bd54f79 Fixes: bugfixes in aura config loading 2023-08-26 21:35:38 +12:00
Luke Jones
ea0eaef8a6 Update README.md 2023-08-24 10:22:26 +00:00
Luke Jones
ef62a26148 Merge branch 'main' into 'main'
add aura support for GU603VV

See merge request asus-linux/asusctl!170
2023-08-20 06:13:20 +00:00
Yifan Zhu
2f916fa4e5 add aura support for GU603VV 2023-08-20 06:13:20 +00:00
Luke D. Jones
e42fd10404 Update deps 2023-08-14 13:20:40 +12:00
Luke D. Jones
93edd1b632 Add gv601v singlezone advanced 2023-08-13 18:22:21 +12:00
Luke D. Jones
6957a08d83 Fix: Corrections in anime detection
Closes #387
2023-08-11 09:48:22 +12:00
Luke D. Jones
98569b98e7 Remove a dbg!() x2 2023-08-10 09:50:01 +12:00
Luke D. Jones
573568d6e2 Remove a dbg!() 2023-08-10 09:49:13 +12:00
Luke D. Jones
3ec37a4dac Fix: For anime look for usbraw device before hidraw device
Closes #387
2023-08-02 14:14:08 +12:00
Luke D. Jones
11483b28a6 Fix: Further refine the CLI for fan curve control
Should close #385
2023-08-01 19:30:33 +12:00
Luke D. Jones
2cce83d164 Fix: asusd should reload defualt fan-curves if the config file fails
Closes #385
2023-08-01 09:30:54 +12:00
Luke D. Jones
42b92f3b87 Fix: reimplement fetching of fan curves on CLI
Partial close of #385
2023-08-01 09:18:27 +12:00
gabi
b652fd15a2 Update aura_support.ron 2023-07-28 06:16:39 +00:00
Luke D. Jones
9154aaa97c Add distro packaging dir + spec file for fedora 2023-07-27 10:13:10 +12:00
Interfector18
9e65921c0a aura: Support for G733PZ 2023-07-24 17:44:59 +02:00
Luke D. Jones
8d8b5e5f51 aura: support GV601V LED modes 2023-07-24 14:07:01 +12:00
Luke D. Jones
9418b63454 Bump new release 2023-07-24 10:23:05 +12:00
227 changed files with 16726 additions and 15850 deletions

View File

@@ -2,11 +2,17 @@
set -e
echo 'find -name \*.slint | xargs slint-tr-extractor -o rog-control-center/translations/en/rog-control-center.po'
find -name \*.slint | xargs slint-tr-extractor -o rog-control-center/translations/en/rog-control-center.po
echo '+cargo +nightly fmt --all -- --check'
cargo +nightly fmt --all -- --check
echo '+cargo clippy --all -- -D warnings'
cargo clippy --all -- -D warnings
echo '+cargo test --all'
cargo test --all
echo '+cargo cranky'
cargo cranky

9
.gitignore vendored
View File

@@ -14,7 +14,8 @@ vendor_*
node-modules
bindings/ts/*.d.ts
bindings/ts/*.js.map
desktop-extensions/gnome/dist
desktop-extensions/gnome/node_modules
desktop-extensions/gnome/schemas/gschemas.compiled
desktop-extensions/gnome/*.zip
desktop-extensions/gnome*/dist
desktop-extensions/gnome*/@types/gir-generated
desktop-extensions/gnome*/node_modules
desktop-extensions/gnome*/schemas/gschemas.compiled
desktop-extensions/gnome*/*.zip

View File

@@ -17,7 +17,7 @@ image: rust:latest
- target/release/.cargo-lock
before_script:
- apt-get update -qq && apt-get install -y -qq libudev-dev libgtk-3-dev grep llvm clang libclang-dev libsdl2-dev libsdl2-gfx-dev
- apt-get update -qq && apt-get install -y -qq libinput-dev libseat-dev libudev-dev libgtk-3-dev grep llvm clang libclang-dev libsdl2-dev libsdl2-gfx-dev
stages:
- format
@@ -59,11 +59,12 @@ release:
- tags
<<: *rust_cache
script:
- cargo install cargo-vendor-filterer
- make && make vendor
artifacts:
paths:
- vendor_asusctl*.tar.xz
- cargo-config
- vendor_asusctl*.tar.xz
- cargo-config
pages:
stage: deploy

View File

@@ -0,0 +1,32 @@
## Issue description
(** I can not support distros which are outdated by default. This includes Ubuntu at least 50% of the time, and definitely includes Mint. **)
(Summarize the bug encountered)
## Steps to reproduce
(How can the issue be reproduced)
## What is the current bug behavior?
(What actually happens)
## What is the expected correct behavior?
(What you should see instead)
## Relevant logs and/or screenshots
(run `journalctl -b -u asusd > ~/asusd.log` and attach `~/asusd.log`)
(Paste any relevant logs - use code blocks (```) to format console output, logs, and code, as
it's very hard to read otherwise.)
## System details
- Distro:
- Kernel: (`uname -r`)
- Desktop:
- Xorg or wayland: ??
/label ~bug ~reproducable ~needs-investigation

File diff suppressed because it is too large Load Diff

4231
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,57 @@
[workspace]
members = ["asusctl", "asusd", "asusd-user", "config-traits", "rog-platform", "rog-dbus", "rog-anime", "rog-aura", "rog-profiles", "rog-control-center", "simulators"]
default-members = ["asusctl", "asusd", "asusd-user", "rog-control-center"]
[workspace.package]
version = "4.7.0-RC3"
version = "6.0.5"
rust-version = "1.77"
license = "MPL-2.0"
readme = "README.md"
authors = ["Luke <luke@ljones.dev>"]
repository = "https://gitlab.com/asus-linux/asusctl"
homepage = "https://gitlab.com/asus-linux/asusctl"
description = "Laptop feature control for ASUS ROG laptops and others"
edition = "2021"
[workspace]
members = [
"asusctl",
"asusd",
"asusd-user",
"config-traits",
"cpuctl",
"dmi-id",
"rog-platform",
"rog-dbus",
"rog-anime",
"rog-aura",
"rog-profiles",
"rog-control-center",
"rog-slash",
"simulators",
]
default-members = [
"asusctl",
"asusd",
"asusd-user",
"cpuctl",
"rog-control-center",
]
resolver = "2"
[workspace.dependencies]
async-trait = "^0.1"
tokio = { version = "^1.23.0", features = ["macros", "rt-multi-thread", "time", "sync"]}
tokio = { version = "^1.36.0", default-features = false, features = [
"macros",
"sync",
"time",
"rt-multi-thread",
] }
concat-idents = "^1.1"
dirs = "^4.0"
smol = "^1.3"
mio = "0.8.11"
zbus = "~3.13.1"
logind-zbus = { version = "^3.1.0" } #, default-features = false, features = ["non_blocking"] }
zbus = "4.1"
logind-zbus = { version = "4.0.2" } #, default-features = false, features = ["non_blocking"] }
serde = "^1.0"
serde_derive = "^1.0"
serde_json = "^1.0"
toml = "^0.5.10"
ron = "*"
typeshare = "1.0.0"
@@ -27,9 +60,8 @@ env_logger = "^0.10.0"
glam = { version = "^0.22", features = ["serde"] }
gumdrop = "^0.8"
udev = "^0.7"
udev = { version = "^0.8", features = ["mio"] }
rusb = "^0.9"
sysfs-class = "^0.1.3"
inotify = "^0.10.0"
png_pong = "^0.8"
@@ -37,9 +69,11 @@ pix = "^0.13"
tinybmp = "^0.4.0"
gif = "^0.12.0"
versions = "4.1"
versions = "6.2"
notify-rust = { git = "https://github.com/flukejones/notify-rust.git", default-features = false, features = ["z"] }
notify-rust = { git = "https://github.com/flukejones/notify-rust.git", rev = "54176413b81189a3e4edbdc20a0b4f7e2e35c063", default-features = false, features = [
"z",
] }
[profile.release]
# thin = 57s, asusd = 9.0M
@@ -48,10 +82,15 @@ lto = "fat"
debug = false
opt-level = 3
panic = "abort"
codegen-units = 1
[profile.dev]
debug = true
opt-level = 1
codegen-units = 16
[profile.dev.package."*"]
opt-level = 1
codegen-units = 16
[profile.bench]
debug = false
@@ -60,4 +99,4 @@ opt-level = 3
[workspace.dependencies.cargo-husky]
version = "1"
default-features = false
features = ["user-hooks"]
features = ["user-hooks"]

View File

@@ -1,5 +1,7 @@
# asusctrl manual
**NOTE:** this manual is in need of an update in some places. If you find issues please file issue reports.
`asusd` is a utility for Linux to control many aspects of various ASUS laptops
but can also be used with non-asus laptops with reduced features.
@@ -8,11 +10,10 @@ but can also be used with non-asus laptops with reduced features.
- `asusd`: The main system daemon. It is autostarted by a udev rule and systemd unit.
- `asusd-user`: The user level daemon. Currently will run an anime sequence, with RGB keyboard sequences soon.
- `asusctl`: The CLI for interacting with the system daemon
- `asus-notify`: A notification daemon with a user systemd unit that can be enabled.
## `asusd`
`asusd` is the main system-level daemon which will control/load/save various settings in a safe way for the user, along with exposing a *safe* dbus interface for these interactions. This section covers only the daemon plus the various configuration file options.
`asusd` is the main system-level daemon which will control/load/save various settings in a safe way for the user, along with exposing a _safe_ dbus interface for these interactions. This section covers only the daemon plus the various configuration file options.
The functionality that `asusd` exposes is:
@@ -56,6 +57,7 @@ Almost all modern ASUS laptops have charging limit control now. This can be cont
```json
"bat_charge_limit": 80,
```
where the number is a percentage.
### Bios control
@@ -63,7 +65,7 @@ where the number is a percentage.
Some options that you find in Armory Crate are available under this controller, so far there is:
- POST sound: this is the sound you hear on bios boot post
- GPU MUX: this controls if the dGPU is the *only* GPU, making it the main GPU and disabling the iGPU
- GPU MUX: this controls if the dGPU is the _only_ GPU, making it the main GPU and disabling the iGPU
These options are not written to the config file as they are stored in efivars. The only way to change these is to use the exposed safe dbus methods, or use the `asusctl` CLI tool.
@@ -72,6 +74,7 @@ These options are not written to the config file as they are stored in efivars.
asusctl can support setting a power profile via platform_profile drivers. This requires [power-profiles-daemon](https://gitlab.freedesktop.org/hadess/power-profiles-daemon) v0.10.0 minimum. It also requires the kernel patch for platform_profile support to be applied form [here](https://lkml.org/lkml/2021/8/18/1022) - this patch is merged to 5.15 kernel upstream.
A common use of asusctl is to bind the `fn+f5` (fan) key to `asusctl profile -n` to cycle through the 3 profiles:
1. Balanced
2. Performance
3. Quiet
@@ -97,7 +100,7 @@ There is one more controller; the support controller. The sole pupose of this co
## asusd-user
`asusd-user` is a usermode daemon. The intended purpose is to provide a method for users to run there own custom per-key keyboard effects and modes, AniMe sequences, and possibly their own profiles - all without overwriting the *base* system config. As such some parts of the system daemon will migrate to the user daemon over time with the expectation that the Linux system runs both.
`asusd-user` is a usermode daemon. The intended purpose is to provide a method for users to run there own custom per-key keyboard effects and modes, AniMe sequences, and possibly their own profiles - all without overwriting the _base_ system config. As such some parts of the system daemon will migrate to the user daemon over time with the expectation that the Linux system runs both.
As of now only AniMe is active in this with configuration in `~/.config/rog/`. On first run defaults are created that are intended to work as examples.
@@ -177,6 +180,7 @@ An Aura config itself is a file with contents:
```
If your laptop supports multizone, `"led"` can also be `"Zone": <one of the following>`
- `SingleZone` // Keyboards with only one zone
- `ZonedKbLeft` // keyboard left
- `ZonedKbLeftMid` // keyboard left-middle
@@ -238,6 +242,7 @@ Each object in the array can be one of:
##### AsusAnimation
`AsusAnimation` is specifically for running the gif files that Armory Crate comes with. `asusctl` includes all of these in `/usr/share/asusd/anime/asus/`
```json
"AsusAnimation": {
"file": "<FILE_PATH>",
@@ -260,7 +265,7 @@ Virtually the same as `AsusAnimation` but for png files, typically created in th
##### ImageAnimation
`ImageAnimation` can play *any* gif of any size.
`ImageAnimation` can play _any_ gif of any size.
```json
"ImageAnimation": {
@@ -319,6 +324,7 @@ Must be full path: `"/usr/share/asusd/anime/asus/gaming/Controller.gif"` or `/ho
**<FLOAT>**
A number from 0.0-1.0.
- `brightness`: If it is brightness it is combined with the system daemon global brightness
- `scale`: 1.0 is the original size with lower number shrinking, larger growing
- `angle`: Rotation angle in radians
@@ -327,6 +333,7 @@ A number from 0.0-1.0.
**<TIME>**
Time is the length of time to run the gif for:
```json
"time": {
"Time": {
@@ -335,17 +342,23 @@ Time is the length of time to run the gif for:
}
},
```
A cycle is how many gif loops to run:
```json
"time": {
"Cycles": 2
},
```
`Infinite` means that this gif will never end:
```json
"time": "Infinite",
```
`Fade` allows an image or gif to fade in and out, and remain at max brightness to n time:
```json
"time": {
"Fade": {
@@ -364,6 +377,7 @@ A cycle is how many gif loops to run:
}
},
```
`show_for` can be `null`, if it is `null` then the `show_for` becomes `gif_time_length - fade_in - fade_out`.
This is period for which the gif or image will be max brightness (as set).
@@ -404,26 +418,19 @@ asusctl <command> <subcommand> --help
To switch to next/previous Aura modes you will need to bind both the aura keys (if available) to one of:
**Next**
```
asusctl led-mode -n
```
**Previous**
```
asusctl led-mode -p
```
To switch Fan/Thermal profiles you need to bind the Fn+F5 key to `asusctl profile -n`.
## User NOTIFICATIONS via dbus
If you have a notifications handler set up, or are using KDE or Gnome then you
can enable the user service to get basic notifications when something changes.
```
systemctl --user enable asus-notify.service
systemctl --user start asus-notify.service
```
# License & Trademarks
Mozilla Public License 2 (MPL-2.0)

View File

@@ -112,6 +112,8 @@ vendor:
echo 'directory = "vendor"' >> .cargo/config
mv .cargo/config ./cargo-config
rm -rf .cargo
rm -rf vendor
cargo vendor-filterer --platform x86_64-unknown-linux-gnu vendor
tar pcfJ vendor_asusctl_$(VERSION).tar.xz vendor
rm -rf vendor
@@ -121,19 +123,12 @@ bindings:
typeshare ./rog-profiles/src/ --lang=typescript --output-file=bindings/ts/profiles.ts
typeshare ./rog-platform/src/ --lang=typescript --output-file=bindings/ts/platform.ts
introspect:
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Aura -x > bindings/dbus-xml/org-asuslinux-aura-4.xml
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Anime -x > bindings/dbus-xml/org-asuslinux-anime-4.xml
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Platform -x > bindings/dbus-xml/org-asuslinux-platform-4.xml
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Power -x > bindings/dbus-xml/org-asuslinux-power-4.xml
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Profile -x > bindings/dbus-xml/org-asuslinux-profile-4.xml
gdbus introspect --system -d org.asuslinux.Daemon -o /org/asuslinux/Supported -x > bindings/dbus-xml/org-asuslinux-supported-4.xml
xmlstarlet ed -L -O -d '//interface[@name="org.freedesktop.DBus.Introspectable"]' bindings/dbus-xml/org-asuslinux-*
xmlstarlet ed -L -O -d '//interface[@name="org.freedesktop.DBus.Properties"]' bindings/dbus-xml/org-asuslinux-*
xmlstarlet ed -L -O -d '//interface[@name="org.freedesktop.DBus.Peer"]' bindings/dbus-xml/org-asuslinux-*
translate:
find -name \*.slint | xargs slint-tr-extractor -o rog-control-center/translations/en/rog-control-center.po
build:
ifeq ($(VENDORED),1)
cargo vendor
@echo "version = $(VERSION)"
tar pxf vendor_asusctl_$(VERSION).tar.xz
endif

View File

@@ -1,8 +1,8 @@
# `asusctl` for ASUS ROG
[![](https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif)](https://www.paypal.com/donate/?hosted_button_id=4V2DEPS7K6APC) - [Asus Linux Website](https://asus-linux.org/)
[Become a Patron!](https://www.patreon.com/bePatron?u=7602281) - [Asus Linux Website](https://asus-linux.org/)
**WARNING:** Many features are developed in tandem with kernel patches. If you see a feature is missing you either need a patched kernel, or v6.1 which has all my work merged upstream.
**WARNING:** Many features are developed in tandem with kernel patches. If you see a feature is missing you either need a patched kernel or latest release.
`asusd` is a utility for Linux to control many aspects of various ASUS laptops
but can also be used with non-asus laptops with reduced features.
@@ -11,27 +11,29 @@ Now includes a GUI, `rog-control-center`.
## Kernel support
**The minimum supported kernel version is 5.17**
**The minimum supported kernel version is 6.10**, which will contain the patches from [here](https://lore.kernel.org/platform-driver-x86/20240404001652.86207-1-luke@ljones.dev/). This is especially required for 2023+ devices and possibly some lat 2022 devices.
**For TUF laptops, the minimum supported kernel version is 6.1**
Z13 devices will need [these](https://lore.kernel.org/linux-input/20240416090402.31057-1-luke@ljones.dev/T/#t)
## Goals
1. To provide an interface for rootless control of some system functions most users wish to control such as fan speeds, keyboard LEDs, graphics modes.
2. Enable third-party apps to use the above with dbus methods
3. To make the above as easy as possible for new users
4. Respect the users resources: be small, light, and fast
The main goal of this work is to provide a safe and easy to use abstraction over various laptop features via DBUS, and to provide some helpful defaults and other behaviour such as toggling throttle/profile on AC/battery change.
Point 3 means that the list of supported distros is very narrow - fedora is explicitly
supported. All other distros are *not* supported (while asusd might still run fine on them).
For best support use fedora 36+ Workstation.
1. Provide safe dbus interface
2. Respect the users resources: be small, light, and fast
Point 4? asusd currently uses a tiny fraction of cpu time, and less than 1Mb of ram, the way
a system-level daemon should.
a system-level daemon should. Languages such as JS and python should never be used for system level daemons (please stop).
## Keyboard LEDs
The level of support for laptops is dependent on folks submitting data to include in [`./rog-aura/data/layouts/aura_support.ron`](./rog-aura/data/layouts/aura_support.ron), typically installed in `/usr/share/asusd/aura_support.ron`. This is because the controller used for keyboards and LEDs is used across many years and many laptop models, all with different firmware configurations - the only way to track this is with the file mentioned above. Why not just enable all by default? Because it confuses people.
See the [rog-aura readme](./rog-aura/README.md) for more details.
## Discord
[Discord server link](https://discord.gg/WTHnqabm)
[![Discord](https://img.shields.io/badge/Discord-7289DA?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/z8y99XqPb7)
## SUPPORTED LAPTOPS
@@ -42,54 +44,43 @@ to this:
Bus 001 Device 002: ID 0b05:1866 ASUSTek Computer, Inc. N-KEY Device
```
or
```
Bus 003 Device 002: ID 0b05:19b6 ASUSTek Computer, Inc. [unknown]
```
then it may work without tweaks. Technically all other functions except the LED
and AniMe parts should work regardless of your latop make.
## Implemented
- [X] System daemon
- [X] GUI app (includes tray and notifications)
- [X] Setting/modifying built-in LED modes
- [X] Per-key LED setting
- [X] Fancy LED modes (See examples) (currently being reworked)
- [X] AniMatrix display on G14 and M16 models that include it
- [X] Set battery charge limit (with kernel supporting this)
- [X] Fan curve control on supported laptops (G14/G15, some TUF like FA507)
- [X] Toggle bios setting for boot/POST sound
- [X] Toggle GPU MUX (g-sync, or called MUX on 2022+ laptops)
The list is a bit outdated as many features have been enabled in the Linux kernel with upstream patches and then supported in asusctl suite.
- [x] System daemon
- [x] GUI app (includes tray and notifications)
- [x] Setting/modifying built-in LED modes
- [x] Per-key LED setting
- [x] Fancy LED modes (See examples) (currently being reworked)
- [x] AniMatrix display on G14 and M16 models that include it
- [x] Set battery charge limit (with kernel supporting this)
- [x] Fan curve control on supported laptops (G14/G15, some TUF like FA507)
- [x] Toggle bios setting for boot/POST sound
- [x] Toggle GPU MUX (g-sync, or called MUX on 2022+ laptops)
# GUI
A gui is now in the repo - ROG Control Center. At this time it is still a WIP, but it has almost all features in place already.
![](/extra/system.png)
![](/extra/fan-curves.png)
![](/extra/keyboard.png)
**NOTE**: Xorg is not supported.
# BUILDING
Requirements are rust >= 1.57 installed from rustup.io if the distro provided version is too old, and `make`.
**Ubuntu (unsuported):**
apt install libgtk-3-dev libpango1.0-dev libgdk-pixbuf-2.0-dev libglib2.0-dev cmake libclang-dev libudev-dev libayatana-appindicator3-1
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
make
sudo make install
**popos (unsuported):**
sudo apt install cmake libclang-dev libudev-dev libgtk-3-dev libclang-dev libglib2.0-dev libatkmm-1.6-dev libpangomm-1.4-dev librust-gdk-pixbuf-dev
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"
make
sudo make install
Rust and cargo are required, they can be installed from [rustup.rs](https://rustup.rs/) or from the distro repos if newer than 1.75.
**fedora:**
dnf install cmake clang-devel systemd-devel glib2-devel cairo-devel atkmm-devel pangomm-devel gdk-pixbuf2-devel gtk3-devel libappindicator-gtk3
dnf install cmake clang-devel libinput-devel libseat-devel libgbm-devel libxkbcommon-devel systemd-devel libdrm-devel expat-devel pcre2-devel libzstd-devel gtk3-devel
make
sudo make install
@@ -98,28 +89,34 @@ Requirements are rust >= 1.57 installed from rustup.io if the distro provided ve
Works with KDE Plasma (without GTK packages)
zypper in -t pattern devel_basis
zypper in rustup make cmake systemd-devel clang-devel llvm-devel gdk-pixbuf-devel cairo-devel pango-devel freetype-devel gtk3-devel libexpat-devel libayatana-indicator3-7
zypper in rustup make cmake clang-devel libinput-devel libseat-devel libgbm-devel libxkbcommon-devel systemd-devel libdrm-devel expat-devel pcre2-devel libzstd-devel gtk3-devel
make
sudo make install
**Ubuntu, Popos (unsuported):**
instructions removed as outdated
## Installing
- Fedora copr = https://copr.fedorainfracloud.org/coprs/lukenukem/asus-linux/
- openSUSE = https://download.opensuse.org/repositories/home:/luke_nukem:/asus/
- Ubuntu = not supported due to packaging woes, but you can build and install on your own.
=======
The default init method is to use the udev rule, this ensures that the service is
started when the device is initialised and ready.
You may also need to activate the service for debian install. If running Pop!\_OS, I suggest disabling `system76-power` gnome-shell extension and systemd service.
## Upgrading
If you are upgrading from a previous installed version, you will need to restart the service or reboot.
```
$ systemctl daemon-reload && systemctl restart asusd
```
You may also need to activate the service for debian install. If running Pop!_OS, I suggest disabling `system76-power` gnome-shell extension and systemd service.
## Uninstalling
Run `sudo make uninstall` in the source repo, and remove `/etc/asusd/`.
@@ -136,7 +133,7 @@ Dbus introsepction XML requires with `make introspection` requires `anime_sim` t
## AniMe Matrix simulator
A simulator using SDL2 can be built using `cargo build --package rog_simulators` and run with `./target/debug/anime_sim`. Once started `asusd` will need restarting to pick it up. If running this sim on a laptop *with* the display, the simulated display will be used instead of the physical display.
A simulator using SDL2 can be built using `cargo build --package rog_simulators` and run with `./target/debug/anime_sim`. Once started `asusd` will need restarting to pick it up. If running this sim on a laptop _with_ the display, the simulated display will be used instead of the physical display.
## Supporting more laptops

View File

@@ -1,26 +1,28 @@
[package]
name = "asusctl"
license = "MPL-2.0"
authors = ["Luke D Jones <luke@ljones.dev>"]
edition = "2021"
license.workspace = true
version.workspace = true
readme.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
edition.workspace = true
[dependencies]
rog_anime = { path = "../rog-anime" }
rog_slash = { path = "../rog-slash" }
rog_aura = { path = "../rog-aura" }
rog_dbus = { path = "../rog-dbus" }
rog_profiles = { path = "../rog-profiles" }
rog_platform = { path = "../rog-platform" }
asusd = { path = "../asusd" }
dmi_id = { path = "../dmi-id" }
ron.workspace = true
gumdrop.workspace = true
toml.workspace = true
sysfs-class.workspace = true
zbus.workspace = true
[dev-dependencies]
gif.workspace = true
tinybmp.workspace = true
glam.workspace = true
rog_dbus = { path = "../rog-dbus" }
cargo-husky.workspace = true
cargo-husky.workspace = true

View File

@@ -5,12 +5,14 @@ use std::process::exit;
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimeDiagonal, AnimeType};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
fn main() -> Result<(), Box<dyn Error>> {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let args: Vec<String> = env::args().into_iter().collect();
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("Usage: <filepath> <brightness>");
println!("e.g, asusctl/examples/doom_large.png 0.8");
@@ -26,11 +28,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let anime_type = get_anime_type()?;
client
.proxies()
.anime()
.write(matrix.into_data_buffer(anime_type)?)
.unwrap();
proxy.write(matrix.into_data_buffer(anime_type)?).unwrap();
Ok(())
}

View File

@@ -3,7 +3,8 @@ use std::time::Duration;
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimeDiagonal, AnimeType};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
// In usable data:
// Top row start at 1, ends at 32
@@ -11,26 +12,25 @@ use rog_dbus::RogDbusClientBlocking;
// 74w x 36h diagonal used by the windows app
fn main() {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
for step in (2..50).rev() {
let mut matrix = AnimeDiagonal::new(AnimeType::GA401, None);
for c in (0..60).into_iter().step_by(step) {
for c in (0..60).step_by(step) {
for i in matrix.get_mut().iter_mut() {
i[c] = 50;
}
}
for c in (0..35).into_iter().step_by(step) {
for c in (0..35).step_by(step) {
for i in &mut matrix.get_mut()[c] {
*i = 50;
}
}
let anime_type = get_anime_type().unwrap();
client
.proxies()
.anime()
proxy
.write(matrix.into_data_buffer(anime_type).unwrap())
.unwrap();
sleep(Duration::from_millis(300));

View File

@@ -4,12 +4,14 @@ use std::thread::sleep;
use rog_anime::usb::get_anime_type;
use rog_anime::{ActionData, ActionLoader, Sequences};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
fn main() {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let args: Vec<String> = env::args().into_iter().collect();
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
println!("Please supply filepath and brightness");
return;
@@ -33,11 +35,7 @@ fn main() {
for action in seq.iter() {
if let ActionData::Animation(frames) = action {
for frame in frames.frames() {
client
.proxies()
.anime()
.write(frame.frame().clone())
.unwrap();
proxy.write(frame.frame().clone()).unwrap();
sleep(frame.delay());
}
}

View File

@@ -2,7 +2,8 @@ use std::convert::TryFrom;
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimeDataBuffer, AnimeGrid};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
// In usable data:
// Top row start at 1, ends at 32
@@ -10,7 +11,9 @@ use rog_dbus::RogDbusClientBlocking;
// 74w x 36h diagonal used by the windows app
fn main() {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let anime_type = get_anime_type().unwrap();
let mut matrix = AnimeGrid::new(anime_type);
let tmp = matrix.get_mut();
@@ -43,5 +46,5 @@ fn main() {
let matrix = <AnimeDataBuffer>::try_from(matrix).unwrap();
client.proxies().anime().write(matrix).unwrap();
proxy.write(matrix).unwrap();
}

View File

@@ -1,12 +1,14 @@
use rog_anime::usb::get_anime_type;
use rog_anime::AnimeDataBuffer;
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
// In usable data:
// Top row start at 1, ends at 32
fn main() {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let anime_type = get_anime_type().unwrap();
let mut matrix = AnimeDataBuffer::new(anime_type);
matrix.data_mut()[1] = 100; // start = 1
@@ -127,5 +129,5 @@ fn main() {
matrix.data_mut()[1244] = 100; // end
println!("{:?}", &matrix);
client.proxies().anime().write(matrix).unwrap();
proxy.write(matrix).unwrap();
}

View File

@@ -6,12 +6,14 @@ use std::process::exit;
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
fn main() -> Result<(), Box<dyn Error>> {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let args: Vec<String> = env::args().into_iter().collect();
let args: Vec<String> = env::args().collect();
if args.len() != 7 {
println!("Usage: <filepath> <scale> <angle> <x pos> <y pos> <brightness>");
println!("e.g, asusctl/examples/doom_large.png 0.9 0.4 0.0 0.0 0.8");
@@ -31,11 +33,7 @@ fn main() -> Result<(), Box<dyn Error>> {
anime_type,
)?;
client
.proxies()
.anime()
.write(<AnimeDataBuffer>::try_from(&matrix)?)
.unwrap();
proxy.write(<AnimeDataBuffer>::try_from(&matrix)?).unwrap();
Ok(())
}

View File

@@ -9,12 +9,14 @@ use std::time::Duration;
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use zbus::blocking::Connection;
fn main() -> Result<(), Box<dyn Error>> {
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
let args: Vec<String> = env::args().into_iter().collect();
let args: Vec<String> = env::args().collect();
if args.len() != 7 {
println!("Usage: <filepath> <scale> <angle> <x pos> <y pos> <brightness>");
println!("e.g, asusctl/examples/doom_large.png 0.9 0.4 0.0 0.0 0.8");
@@ -41,11 +43,7 @@ fn main() -> Result<(), Box<dyn Error>> {
}
matrix.update();
client
.proxies()
.anime()
.write(<AnimeDataBuffer>::try_from(&matrix)?)
.unwrap();
proxy.write(<AnimeDataBuffer>::try_from(&matrix)?).unwrap();
sleep(Duration::from_micros(500));
}
}

View File

@@ -1,16 +1,17 @@
//! Using a combination of key-colour array plus a key layout to generate
//! outputs.
use rog_aura::advanced::LedCode;
use rog_aura::effects::{AdvancedEffects, Effect};
use rog_aura::layouts::KeyLayout;
use rog_aura::keyboard::{KeyLayout, LedCode};
use rog_aura::Colour;
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_aura::AuraProxyBlocking;
use zbus::blocking::Connection;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let layout = KeyLayout::default_layout();
let (client, _) = RogDbusClientBlocking::new().unwrap();
let conn = Connection::system().unwrap();
let proxy = AuraProxyBlocking::new(&conn).unwrap();
let mut seq = AdvancedEffects::new(true);
@@ -62,7 +63,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
seq.next_state(&layout);
let packets = seq.create_packets();
client.proxies().led().direct_addressing_raw(packets)?;
proxy.direct_addressing_raw(packets)?;
std::thread::sleep(std::time::Duration::from_millis(33));
}
}

View File

@@ -17,10 +17,28 @@ pub struct AnimeCommand {
help = "set global base brightness value <Off, Low, Med, High>"
)]
pub brightness: Option<Brightness>,
#[options(meta = "", help = "set global (image) brightness value")]
pub image_brightness: Option<f32>,
#[options(help = "clear the display")]
pub clear: bool,
#[options(
no_short,
meta = "",
help = "turn the anime off when external power is unplugged"
)]
pub off_when_unplugged: Option<bool>,
#[options(
no_short,
meta = "",
help = "turn the anime off when the laptop suspends"
)]
pub off_when_suspended: Option<bool>,
#[options(
no_short,
meta = "",
help = "turn the anime off when the lid is closed"
)]
pub off_when_lid_closed: Option<bool>,
#[options(no_short, meta = "", help = "Off with his head!!!")]
pub off_with_his_head: Option<bool>,
#[options(command)]
pub command: Option<AnimeActions>,
}
@@ -43,15 +61,27 @@ pub enum AnimeActions {
pub struct Builtins {
#[options(help = "print help message")]
pub help: bool,
#[options(meta = "", help = " <GlitchConstruction, StaticEmergence>")]
#[options(
meta = "",
help = "Default is used if unspecified, <default:GlitchConstruction, StaticEmergence>"
)]
pub boot: AnimBooting,
#[options(meta = "", help = "<BinaryBannerScroll, RogLogoGlitch>")]
#[options(
meta = "",
help = "Default is used if unspecified, <default:BinaryBannerScroll, RogLogoGlitch>"
)]
pub awake: AnimAwake,
#[options(meta = "", help = "<BannerSwipe, Starfield>")]
#[options(
meta = "",
help = "Default is used if unspecified, <default:BannerSwipe, Starfield>"
)]
pub sleep: AnimSleeping,
#[options(meta = "", help = "<GlitchOut, SeeYa>")]
#[options(
meta = "",
help = "Default is used if unspecified, <default:GlitchOut, SeeYa>"
)]
pub shutdown: AnimShutdown,
#[options(meta = "", help = "set/apply the animations")]
#[options(meta = "", help = "set/apply the animations <true/false>")]
pub set: Option<bool>,
}

View File

@@ -10,10 +10,10 @@ pub struct LedPowerCommand1 {
pub help: bool,
#[options(meta = "", help = "Control if LEDs enabled while awake <true/false>")]
pub awake: Option<bool>,
#[options(meta = "", help = "Use with awake option <true/false>")]
pub keyboard: Option<bool>,
#[options(meta = "", help = "Use with awake option <true/false>")]
pub lightbar: Option<bool>,
#[options(help = "Use with awake option, if excluded defaults to false")]
pub keyboard: bool,
#[options(help = "Use with awake option, if excluded defaults to false")]
pub lightbar: bool,
#[options(meta = "", help = "Control boot animations <true/false>")]
pub boot: Option<bool>,
#[options(meta = "", help = "Control suspend animations <true/false>")]
@@ -59,14 +59,14 @@ pub struct AuraPowerStates {
#[derive(Options)]
pub struct LedBrightness {
level: Option<u32>,
level: Option<u8>,
}
impl LedBrightness {
pub fn new(level: Option<u32>) -> Self {
pub fn new(level: Option<u8>) -> Self {
LedBrightness { level }
}
pub fn level(&self) -> Option<u32> {
pub fn level(&self) -> Option<u8> {
self.level
}
}
@@ -87,6 +87,7 @@ impl FromStr for LedBrightness {
}
}
}
#[allow(clippy::to_string_trait_impl)]
impl ToString for LedBrightness {
fn to_string(&self) -> String {
let s = match self.level {
@@ -214,29 +215,29 @@ pub struct MultiColourSpeed {
#[derive(Options)]
pub enum SetAuraBuiltin {
#[options(help = "set a single static colour")]
Static(SingleColour),
Static(SingleColour), // 0
#[options(help = "pulse between one or two colours")]
Breathe(TwoColourSpeed),
Breathe(TwoColourSpeed), // 1
#[options(help = "strobe through all colours")]
Strobe(SingleSpeed),
Strobe(SingleSpeed), // 2
#[options(help = "rainbow cycling in one of four directions")]
Rainbow(SingleSpeedDirection),
Rainbow(SingleSpeedDirection), // 3
#[options(help = "rain pattern mimicking raindrops")]
Stars(TwoColourSpeed),
Stars(TwoColourSpeed), // 4
#[options(help = "rain pattern of three preset colours")]
Rain(SingleSpeed),
Rain(SingleSpeed), // 5
#[options(help = "pressed keys are highlighted to fade")]
Highlight(SingleColourSpeed),
Highlight(SingleColourSpeed), // 6
#[options(help = "pressed keys generate horizontal laser")]
Laser(SingleColourSpeed),
Laser(SingleColourSpeed), // 7
#[options(help = "pressed keys ripple outwards like a splash")]
Ripple(SingleColourSpeed),
Ripple(SingleColourSpeed), // 8
#[options(help = "set a rapid pulse")]
Pulse(SingleColour),
Pulse(SingleColour), // 10
#[options(help = "set a vertical line zooming from left")]
Comet(SingleColour),
Comet(SingleColour), // 11
#[options(help = "set a wide vertical line zooming from left")]
Flash(SingleColour),
Flash(SingleColour), // 12
}
impl Default for SetAuraBuiltin {

View File

@@ -1,8 +1,10 @@
use gumdrop::Options;
use rog_platform::platform::ThrottlePolicy;
use crate::anime_cli::AnimeCommand;
use crate::aura_cli::{LedBrightness, LedPowerCommand1, LedPowerCommand2, SetAuraBuiltin};
use crate::profiles_cli::{FanCurveCommand, ProfileCommand};
use crate::fan_curve_cli::FanCurveCommand;
use crate::slash_cli::SlashCommand;
#[derive(Default, Options)]
pub struct CliStart {
@@ -40,10 +42,30 @@ pub enum CliCommand {
Graphics(GraphicsCommand),
#[options(name = "anime", help = "Manage AniMe Matrix")]
Anime(AnimeCommand),
#[options(name = "slash", help = "Manage Slash Ledbar")]
Slash(SlashCommand),
#[options(help = "Change bios settings")]
Bios(BiosCommand),
}
#[derive(Debug, Clone, Options)]
pub struct ProfileCommand {
#[options(help = "print help message")]
pub help: bool,
#[options(help = "toggle to next profile in list")]
pub next: bool,
#[options(help = "list available profiles")]
pub list: bool,
#[options(help = "get profile")]
pub profile_get: bool,
#[options(meta = "", help = "set the active profile")]
pub profile_set: Option<ThrottlePolicy>,
}
#[derive(Options)]
pub struct LedModeCommand {
#[options(help = "print help message")]

View File

@@ -0,0 +1,49 @@
use gumdrop::Options;
use rog_platform::platform::ThrottlePolicy;
use rog_profiles::fan_curve_set::CurveData;
use rog_profiles::FanCurvePU;
#[derive(Debug, Clone, Options)]
pub struct FanCurveCommand {
#[options(help = "print help message")]
pub help: bool,
#[options(help = "get enabled fan profiles")]
pub get_enabled: bool,
#[options(help = "set the active profile's fan curve to default")]
pub default: bool,
#[options(
meta = "",
help = "profile to modify fan-curve for. Shows data if no options provided"
)]
pub mod_profile: Option<ThrottlePolicy>,
#[options(
meta = "",
help = "enable or disable <true/false> fan all curves for a profile. `--mod_profile` \
required"
)]
pub enable_fan_curves: Option<bool>,
#[options(
meta = "",
help = "enable or disable <true/false> a single fan curve for a profile. `--mod_profile` \
and `--fan` required"
)]
pub enable_fan_curve: Option<bool>,
#[options(
meta = "",
help = "select fan <cpu/gpu/mid> to modify. `--mod_profile` required"
)]
pub fan: Option<FanCurvePU>,
#[options(
meta = "",
help = "data format = 30c:1%,49c:2%,59c:3%,69c:4%,79c:31%,89c:49%,99c:56%,109c:58%. \
`--mod-profile` required. If '%' is omitted the fan range is 0-255"
)]
pub data: Option<CurveData>,
}

View File

@@ -5,26 +5,35 @@ use std::process::Command;
use std::thread::sleep;
use anime_cli::{AnimeActions, AnimeCommand};
use asusd::ctrl_fancurves::FAN_CURVE_ZBUS_NAME;
use aura_cli::{LedPowerCommand1, LedPowerCommand2};
use dmi_id::DMIID;
use fan_curve_cli::FanCurveCommand;
use gumdrop::{Opt, Options};
use profiles_cli::{FanCurveCommand, ProfileCommand};
use rog_anime::usb::get_anime_type;
use rog_anime::{AnimTime, AnimeDataBuffer, AnimeDiagonal, AnimeGif, AnimeImage, AnimeType, Vec2};
use rog_aura::power::KbAuraPowerState;
use rog_aura::usb::{AuraDevRog1, AuraDevTuf, AuraDevice, AuraPowerDev};
use rog_aura::{self, AuraEffect};
use rog_dbus::RogDbusClientBlocking;
use rog_platform::platform::GpuMode;
use rog_platform::supported::*;
use rog_aura::keyboard::{AuraPowerState, LaptopAuraPower};
use rog_aura::{self, AuraDeviceType, AuraEffect, PowerZones};
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use rog_dbus::zbus_aura::AuraProxyBlocking;
use rog_dbus::zbus_fan_curves::FanCurvesProxyBlocking;
use rog_dbus::zbus_platform::PlatformProxyBlocking;
use rog_dbus::zbus_slash::SlashProxyBlocking;
use rog_platform::platform::{GpuMode, Properties, ThrottlePolicy};
use rog_profiles::error::ProfileError;
use rog_slash::SlashMode;
use ron::ser::PrettyConfig;
use zbus::blocking::Connection;
use crate::aura_cli::{AuraPowerStates, LedBrightness};
use crate::cli_opts::*;
use crate::slash_cli::SlashCommand;
mod anime_cli;
mod aura_cli;
mod cli_opts;
mod profiles_cli;
mod fan_curve_cli;
mod slash_cli;
fn main() {
let args: Vec<String> = args().skip(1).collect();
@@ -42,44 +51,51 @@ fn main() {
}
};
if let Ok((dbus, _)) = RogDbusClientBlocking::new().map_err(|e| {
print_error_help(&e, None);
let conn = Connection::system().unwrap();
if let Ok(platform_proxy) = PlatformProxyBlocking::new(&conn).map_err(|e| {
check_service("asusd");
println!("\nError: {e}\n");
print_info();
}) {
if let Ok(supported) = dbus
.proxies()
.supported()
.supported_functions()
.map_err(|e| {
print_error_help(&e, None);
})
{
if parsed.version {
println!("asusctl v{}", env!("CARGO_PKG_VERSION"));
println!();
print_info();
}
let self_version = env!("CARGO_PKG_VERSION");
let asusd_version = platform_proxy.version().unwrap();
if asusd_version != self_version {
println!("Version mismatch: asusctl = {self_version}, asusd = {asusd_version}");
return;
}
if let Err(err) = do_parsed(&parsed, &supported, &dbus) {
print_error_help(&*err, Some(&supported));
}
let supported_properties = platform_proxy.supported_properties().unwrap();
let supported_interfaces = platform_proxy.supported_interfaces().unwrap();
if parsed.version {
println!("asusctl v{}", env!("CARGO_PKG_VERSION"));
println!();
print_info();
}
if let Err(err) = do_parsed(&parsed, &supported_interfaces, &supported_properties, conn) {
print_error_help(&*err, &supported_interfaces, &supported_properties);
}
}
}
fn print_error_help(err: &dyn std::error::Error, supported: Option<&SupportedFunctions>) {
fn print_error_help(
err: &dyn std::error::Error,
supported_interfaces: &[String],
supported_properties: &[Properties],
) {
check_service("asusd");
println!("\nError: {}\n", err);
print_info();
if let Some(supported) = supported {
println!();
println!("Supported laptop functions:\n\n{}", supported);
}
println!();
println!("Supported interfaces:\n\n{:#?}\n", supported_interfaces);
println!("Supported properties:\n\n{:#?}\n", supported_properties);
}
fn print_info() {
let dmi = sysfs_class::DmiId::default();
let board_name = dmi.board_name().expect("Could not get board_name");
let prod_family = dmi.product_family().expect("Could not get product_family");
let dmi = DMIID::new().unwrap_or_default();
let board_name = dmi.board_name;
let prod_family = dmi.product_family;
println!("asusctl version: {}", env!("CARGO_PKG_VERSION"));
println!(" Product family: {}", prod_family.trim());
println!(" Board name: {}", board_name.trim());
@@ -102,22 +118,68 @@ fn check_service(name: &str) -> bool {
false
}
fn find_aura_iface() -> Result<Vec<AuraProxyBlocking<'static>>, Box<dyn std::error::Error>> {
let conn = zbus::blocking::Connection::system().unwrap();
let f = zbus::blocking::fdo::ObjectManagerProxy::new(
&conn,
"org.asuslinux.Daemon",
"/org/asuslinux",
)
.unwrap();
let interfaces = f.get_managed_objects().unwrap();
let mut aura_paths = Vec::new();
for v in interfaces.iter() {
// let o: Vec<zbus::names::OwnedInterfaceName> = v.1.keys().map(|e|
// e.to_owned()).collect(); println!("{}, {:?}", v.0, o);
for k in v.1.keys() {
if k.as_str() == "org.asuslinux.Aura" {
println!("Found aura device at {}, {}", v.0, k);
aura_paths.push(v.0.clone());
}
}
}
if aura_paths.len() > 1 {
println!("Multiple aura devices found: {aura_paths:?}");
println!("TODO: enable selection");
}
if !aura_paths.is_empty() {
let mut ctrl = Vec::new();
for path in aura_paths {
ctrl.push(
AuraProxyBlocking::builder(&conn)
.path(path.clone())?
.destination("org.asuslinux.Daemon")?
.build()?,
);
}
return Ok(ctrl);
}
Err("No Aura interface".into())
}
fn do_parsed(
parsed: &CliStart,
supported: &SupportedFunctions,
dbus: &RogDbusClientBlocking<'_>,
supported_interfaces: &[String],
supported_properties: &[Properties],
conn: Connection,
) -> Result<(), Box<dyn std::error::Error>> {
match &parsed.command {
Some(CliCommand::LedMode(mode)) => handle_led_mode(dbus, &supported.keyboard_led, mode)?,
Some(CliCommand::LedPow1(pow)) => handle_led_power1(dbus, &supported.keyboard_led, pow)?,
Some(CliCommand::LedPow2(pow)) => handle_led_power2(dbus, &supported.keyboard_led, pow)?,
Some(CliCommand::Profile(cmd)) => handle_profile(dbus, &supported.platform_profile, cmd)?,
Some(CliCommand::LedMode(mode)) => handle_led_mode(&find_aura_iface()?, mode)?,
Some(CliCommand::LedPow1(pow)) => handle_led_power1(&find_aura_iface()?, pow)?,
Some(CliCommand::LedPow2(pow)) => handle_led_power2(&find_aura_iface()?, pow)?,
Some(CliCommand::Profile(cmd)) => {
handle_throttle_profile(&conn, supported_properties, cmd)?
}
Some(CliCommand::FanCurve(cmd)) => {
handle_fan_curve(dbus, &supported.platform_profile, cmd)?;
handle_fan_curve(&conn, supported_interfaces, cmd)?;
}
Some(CliCommand::Graphics(_)) => do_gfx(),
Some(CliCommand::Anime(cmd)) => handle_anime(dbus, &supported.anime_ctrl, cmd)?,
Some(CliCommand::Bios(cmd)) => handle_bios_option(dbus, &supported.rog_bios_ctrl, cmd)?,
Some(CliCommand::Anime(cmd)) => handle_anime(&conn, cmd)?,
Some(CliCommand::Slash(cmd)) => handle_slash(&conn, cmd)?,
Some(CliCommand::Bios(cmd)) => {
handle_platform_properties(&conn, supported_properties, cmd)?
}
None => {
if (!parsed.show_supported
&& parsed.kbd_bright.is_none()
@@ -129,21 +191,25 @@ fn do_parsed(
println!("{}", CliStart::usage());
println!();
if let Some(cmdlist) = CliStart::command_list() {
let dev_type = if let Ok(proxy) = find_aura_iface() {
// TODO: commands on all?
proxy
.first()
.unwrap()
.device_type()
.unwrap_or(AuraDeviceType::Unknown)
} else {
AuraDeviceType::Unknown
};
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
for command in commands.iter().filter(|command| {
if !matches!(
supported.keyboard_led.dev_id,
AuraDevice::X1854
| AuraDevice::X1869
| AuraDevice::X1866
| AuraDevice::Tuf
) && command.trim().starts_with("led-pow-1")
if !dev_type.is_old_laptop()
&& !dev_type.is_tuf_laptop()
&& command.trim().starts_with("led-pow-1")
{
return false;
}
if supported.keyboard_led.dev_id != AuraDevice::X19b6
&& command.trim().starts_with("led-pow-2")
{
if !dev_type.is_new_laptop() && command.trim().starts_with("led-pow-2") {
return false;
}
true
@@ -160,34 +226,67 @@ fn do_parsed(
}
if let Some(brightness) = &parsed.kbd_bright {
match brightness.level() {
None => {
let level = dbus.proxies().led().led_brightness()?;
println!("Current keyboard led brightness: {}", level);
if let Ok(aura) = find_aura_iface() {
for aura in aura.iter() {
match brightness.level() {
None => {
let level = aura.brightness()?;
println!("Current keyboard led brightness: {level:?}");
}
Some(level) => aura.set_brightness(rog_aura::LedBrightness::from(level))?,
}
}
Some(level) => dbus
.proxies()
.led()
.set_brightness(<rog_aura::LedBrightness>::from(level))?,
} else {
println!("No aura interface found");
}
}
if parsed.next_kbd_bright {
dbus.proxies().led().next_led_brightness()?;
if let Ok(aura) = find_aura_iface() {
for aura in aura.iter() {
let brightness = aura.brightness()?;
aura.set_brightness(brightness.next())?;
}
} else {
println!("No aura interface found");
}
}
if parsed.prev_kbd_bright {
dbus.proxies().led().prev_led_brightness()?;
if let Ok(aura) = find_aura_iface() {
for aura in aura.iter() {
let brightness = aura.brightness()?;
aura.set_brightness(brightness.prev())?;
}
} else {
println!("No aura interface found");
}
}
if parsed.show_supported {
println!("Supported laptop functions:\n\n{}", supported);
println!("Supported Core Functions:\n{:#?}", supported_interfaces);
println!(
"Supported Platform Properties:\n{:#?}",
supported_properties
);
if let Ok(aura) = find_aura_iface() {
// TODO: multiple RGB check
let bright = aura.first().unwrap().supported_brightness()?;
let modes = aura.first().unwrap().supported_basic_modes()?;
let zones = aura.first().unwrap().supported_basic_zones()?;
let power = aura.first().unwrap().supported_power_zones()?;
println!("Supported Keyboard Brightness:\n{:#?}", bright);
println!("Supported Aura Modes:\n{:#?}", modes);
println!("Supported Aura Zones:\n{:#?}", zones);
println!("Supported Aura Power Zones:\n{:#?}", power);
} else {
println!("No aura interface found");
}
}
if let Some(chg_limit) = parsed.chg_limit {
dbus.proxies()
.charge()
.set_charge_control_end_threshold(chg_limit)?;
let proxy = PlatformProxyBlocking::new(&conn)?;
proxy.set_charge_control_end_threshold(chg_limit)?;
}
Ok(())
@@ -201,16 +300,15 @@ fn do_gfx() {
println!("This command will be removed in future");
}
fn handle_anime(
dbus: &RogDbusClientBlocking<'_>,
_supported: &AnimeSupportedFunctions,
cmd: &AnimeCommand,
) -> Result<(), Box<dyn std::error::Error>> {
fn handle_anime(conn: &Connection, cmd: &AnimeCommand) -> Result<(), Box<dyn std::error::Error>> {
if (cmd.command.is_none()
&& cmd.enable_display.is_none()
&& cmd.enable_powersave_anim.is_none()
&& cmd.brightness.is_none()
&& cmd.image_brightness.is_none()
&& cmd.off_when_lid_closed.is_none()
&& cmd.off_when_suspended.is_none()
&& cmd.off_when_unplugged.is_none()
&& cmd.off_with_his_head.is_none()
&& !cmd.clear)
|| cmd.help
{
@@ -219,18 +317,27 @@ fn handle_anime(
println!("\n{}", lst);
}
}
let proxy = AnimeProxyBlocking::new(conn)?;
if let Some(enable) = cmd.enable_display {
dbus.proxies().anime().set_enable_display(enable)?;
proxy.set_enable_display(enable)?;
}
if let Some(enable) = cmd.enable_powersave_anim {
dbus.proxies().anime().set_builtins_enabled(enable)?;
proxy.set_builtins_enabled(enable)?;
}
if let Some(bright) = cmd.brightness {
dbus.proxies().anime().set_brightness(bright)?;
proxy.set_brightness(bright)?;
}
if let Some(bright) = cmd.image_brightness {
verify_brightness(bright);
dbus.proxies().anime().set_image_brightness(bright)?;
if let Some(enable) = cmd.off_when_lid_closed {
proxy.set_off_when_lid_closed(enable)?;
}
if let Some(enable) = cmd.off_when_suspended {
proxy.set_off_when_suspended(enable)?;
}
if let Some(enable) = cmd.off_when_unplugged {
proxy.set_off_when_unplugged(enable)?;
}
if cmd.off_with_his_head.is_some() {
println!("Did Alice _really_ make it back from Wonderland?");
}
let mut anime_type = get_anime_type()?;
@@ -243,7 +350,7 @@ fn handle_anime(
if cmd.clear {
let data = vec![255u8; anime_type.data_length()];
let tmp = AnimeDataBuffer::from_vec(anime_type, data)?;
dbus.proxies().anime().write(tmp)?;
proxy.write(tmp)?;
}
if let Some(action) = cmd.command.as_ref() {
@@ -267,9 +374,7 @@ fn handle_anime(
anime_type,
)?;
dbus.proxies()
.anime()
.write(<AnimeDataBuffer>::try_from(&matrix)?)?;
proxy.write(<AnimeDataBuffer>::try_from(&matrix)?)?;
}
AnimeActions::PixelImage(image) => {
if image.help_requested() || image.path.is_empty() {
@@ -288,9 +393,7 @@ fn handle_anime(
anime_type,
)?;
dbus.proxies()
.anime()
.write(matrix.into_data_buffer(anime_type)?)?;
proxy.write(matrix.into_data_buffer(anime_type)?)?;
}
AnimeActions::Gif(gif) => {
if gif.help_requested() || gif.path.is_empty() {
@@ -315,7 +418,7 @@ fn handle_anime(
let mut loops = gif.loops as i32;
loop {
for frame in matrix.frames() {
dbus.proxies().anime().write(frame.frame().clone())?;
proxy.write(frame.frame().clone())?;
sleep(frame.delay());
}
if loops >= 0 {
@@ -346,7 +449,7 @@ fn handle_anime(
let mut loops = gif.loops as i32;
loop {
for frame in matrix.frames() {
dbus.proxies().anime().write(frame.frame().clone())?;
proxy.write(frame.frame().clone())?;
sleep(frame.delay());
}
if loops >= 0 {
@@ -367,12 +470,12 @@ fn handle_anime(
return Ok(());
}
dbus.proxies().anime().set_builtin_animations(
builtins.boot,
builtins.awake,
builtins.sleep,
builtins.shutdown,
)?;
proxy.set_builtin_animations(rog_anime::Animations {
boot: builtins.boot,
awake: builtins.awake,
sleep: builtins.sleep,
shutdown: builtins.shutdown,
})?;
}
}
}
@@ -388,9 +491,48 @@ fn verify_brightness(brightness: f32) {
}
}
fn handle_slash(conn: &Connection, cmd: &SlashCommand) -> Result<(), Box<dyn std::error::Error>> {
if (cmd.brightness.is_none()
&& cmd.interval.is_none()
&& cmd.slash_mode.is_none()
&& !cmd.list
&& !cmd.enable
&& !cmd.disable)
|| cmd.help
{
println!("Missing arg or command\n\n{}", cmd.self_usage());
if let Some(lst) = cmd.self_command_list() {
println!("\n{}", lst);
}
}
let proxy = SlashProxyBlocking::new(conn)?;
if cmd.enable {
proxy.set_enabled(true)?;
}
if cmd.disable {
proxy.set_enabled(false)?;
}
if let Some(brightness) = cmd.brightness {
proxy.set_brightness(brightness)?;
}
if let Some(interval) = cmd.interval {
proxy.set_interval(interval)?;
}
if let Some(slash_mode) = cmd.slash_mode {
proxy.set_slash_mode(slash_mode)?;
}
if cmd.list {
let res = SlashMode::list();
for p in &res {
println!("{:?}", p);
}
}
Ok(())
}
fn handle_led_mode(
dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions,
aura: &[AuraProxyBlocking],
mode: &LedModeCommand,
) -> Result<(), Box<dyn std::error::Error>> {
if mode.command.is_none() && !mode.prev_mode && !mode.next_mode {
@@ -402,8 +544,10 @@ fn handle_led_mode(
if let Some(cmdlist) = LedModeCommand::command_list() {
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
// TODO: multiple rgb check
let modes = aura.first().unwrap().supported_basic_modes()?;
for command in commands.iter().filter(|command| {
for mode in &supported.basic_modes {
for mode in &modes {
if command
.trim()
.starts_with(&<&str>::from(mode).to_lowercase())
@@ -411,9 +555,10 @@ fn handle_led_mode(
return true;
}
}
if !supported.basic_zones.is_empty() && command.trim().starts_with("multi") {
return true;
}
// TODO
// if !supported.basic_zones.is_empty() && command.trim().starts_with("multi") {
// return true;
// }
false
}) {
println!("{}", command);
@@ -429,51 +574,67 @@ fn handle_led_mode(
return Ok(());
}
if mode.next_mode {
dbus.proxies().led().next_led_mode()?;
for aura in aura {
let mode = aura.led_mode()?;
let modes = aura.supported_basic_modes()?;
let mut pos = modes.iter().position(|m| *m == mode).unwrap() + 1;
if pos >= modes.len() {
pos = 0;
}
aura.set_led_mode(modes[pos])?;
}
} else if mode.prev_mode {
dbus.proxies().led().prev_led_mode()?;
for aura in aura {
let mode = aura.led_mode()?;
let modes = aura.supported_basic_modes()?;
let mut pos = modes.iter().position(|m| *m == mode).unwrap();
if pos == 0 {
pos = modes.len() - 1;
} else {
pos -= 1;
}
aura.set_led_mode(modes[pos])?;
}
} else if let Some(mode) = mode.command.as_ref() {
if mode.help_requested() {
println!("{}", mode.self_usage());
return Ok(());
}
dbus.proxies()
.led()
.set_led_mode(&<AuraEffect>::from(mode))?;
for aura in aura {
aura.set_led_mode_data(<AuraEffect>::from(mode))?;
}
}
Ok(())
}
fn handle_led_power1(
dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions,
aura: &[AuraProxyBlocking],
power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> {
if power.awake.is_none()
&& power.sleep.is_none()
&& power.boot.is_none()
&& power.keyboard.is_none()
&& power.lightbar.is_none()
{
if !power.help {
println!("Missing arg or command\n");
for aura in aura {
let dev_type = aura.device_type()?;
if !dev_type.is_old_laptop() && !dev_type.is_tuf_laptop() {
println!("This option applies only to keyboards 2021+");
}
println!("{}\n", power.self_usage());
return Ok(());
}
if matches!(
supported.dev_id,
AuraDevice::X1854 | AuraDevice::X1869 | AuraDevice::X1866
) {
handle_led_power_1_do_1866(dbus, power)?;
return Ok(());
}
if power.awake.is_none()
&& power.sleep.is_none()
&& power.boot.is_none()
&& !power.keyboard
&& !power.lightbar
{
if !power.help {
println!("Missing arg or command\n");
}
println!("{}\n", power.self_usage());
return Ok(());
}
if matches!(supported.dev_id, AuraDevice::Tuf) {
handle_led_power_1_do_tuf(dbus, power)?;
return Ok(());
if dev_type.is_old_laptop() || dev_type.is_tuf_laptop() {
handle_led_power_1_do_1866(aura, power)?;
return Ok(());
}
}
println!("These options are for keyboards of product ID 0x1866 or TUF only");
@@ -481,143 +642,105 @@ fn handle_led_power1(
}
fn handle_led_power_1_do_1866(
dbus: &RogDbusClientBlocking<'_>,
aura: &AuraProxyBlocking,
power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> {
let mut enabled: Vec<AuraDevRog1> = Vec::new();
let mut disabled: Vec<AuraDevRog1> = Vec::new();
let mut check = |e: Option<bool>, a: AuraDevRog1| {
if let Some(arg) = e {
if arg {
enabled.push(a);
} else {
disabled.push(a);
}
}
};
check(power.awake, AuraDevRog1::Awake);
check(power.boot, AuraDevRog1::Boot);
check(power.sleep, AuraDevRog1::Sleep);
check(power.keyboard, AuraDevRog1::Keyboard);
check(power.lightbar, AuraDevRog1::Lightbar);
let data = AuraPowerDev {
old_rog: enabled,
..Default::default()
};
dbus.proxies().led().set_led_power(data, true)?;
let data = AuraPowerDev {
old_rog: disabled,
..Default::default()
};
dbus.proxies().led().set_led_power(data, false)?;
Ok(())
}
fn handle_led_power_1_do_tuf(
dbus: &RogDbusClientBlocking<'_>,
power: &LedPowerCommand1,
) -> Result<(), Box<dyn std::error::Error>> {
let mut enabled: Vec<AuraDevTuf> = Vec::new();
let mut disabled: Vec<AuraDevTuf> = Vec::new();
let mut check = |e: Option<bool>, a: AuraDevTuf| {
if let Some(arg) = e {
if arg {
enabled.push(a);
} else {
disabled.push(a);
}
}
};
check(power.awake, AuraDevTuf::Awake);
check(power.boot, AuraDevTuf::Boot);
check(power.sleep, AuraDevTuf::Sleep);
check(power.keyboard, AuraDevTuf::Keyboard);
let data = AuraPowerDev {
tuf: enabled,
..Default::default()
};
dbus.proxies().led().set_led_power(data, true)?;
let data = AuraPowerDev {
tuf: disabled,
..Default::default()
};
dbus.proxies().led().set_led_power(data, false)?;
let mut states = Vec::new();
if power.keyboard {
states.push(AuraPowerState {
zone: PowerZones::Keyboard,
boot: power.boot.unwrap_or_default(),
awake: power.awake.unwrap_or_default(),
sleep: power.sleep.unwrap_or_default(),
shutdown: false,
});
}
if power.lightbar {
states.push(AuraPowerState {
zone: PowerZones::Lightbar,
boot: power.boot.unwrap_or_default(),
awake: power.awake.unwrap_or_default(),
sleep: power.sleep.unwrap_or_default(),
shutdown: false,
});
}
let states = LaptopAuraPower { states };
aura.set_led_power(states)?;
Ok(())
}
fn handle_led_power2(
dbus: &RogDbusClientBlocking<'_>,
supported: &LedSupportedFunctions,
aura: &[AuraProxyBlocking],
power: &LedPowerCommand2,
) -> Result<(), Box<dyn std::error::Error>> {
if power.command().is_none() {
if !power.help {
println!("Missing arg or command\n");
for aura in aura {
let dev_type = aura.device_type()?;
if !dev_type.is_new_laptop() {
println!("This option applies only to keyboards 2021+");
continue;
}
println!("{}\n", power.self_usage());
println!("Commands available");
if let Some(cmdlist) = LedPowerCommand2::command_list() {
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
for command in &commands {
println!("{}", command);
if power.command().is_none() {
if !power.help {
println!("Missing arg or command\n");
}
}
println!("{}\n", power.self_usage());
println!("Commands available");
println!("\nHelp can also be requested on commands, e.g: boot --help");
return Ok(());
}
if let Some(cmdlist) = LedPowerCommand2::command_list() {
let commands: Vec<String> = cmdlist.lines().map(|s| s.to_owned()).collect();
for command in &commands {
println!("{}", command);
}
}
if let Some(pow) = power.command.as_ref() {
if pow.help_requested() {
println!("{}", pow.self_usage());
println!("\nHelp can also be requested on commands, e.g: boot --help");
return Ok(());
}
if supported.dev_id != AuraDevice::X19b6 {
println!("This option applies only to keyboards with product ID 0x19b6");
}
let set = |power: &mut KbAuraPowerState, set_to: &AuraPowerStates| {
power.boot = set_to.boot;
power.awake = set_to.awake;
power.sleep = set_to.sleep;
power.shutdown = set_to.shutdown;
};
let mut enabled = dbus.proxies().led().led_power()?;
if let Some(cmd) = &power.command {
match cmd {
aura_cli::SetAuraZoneEnabled::Keyboard(k) => set(&mut enabled.rog.keyboard, k),
aura_cli::SetAuraZoneEnabled::Logo(l) => set(&mut enabled.rog.logo, l),
aura_cli::SetAuraZoneEnabled::Lightbar(l) => set(&mut enabled.rog.lightbar, l),
aura_cli::SetAuraZoneEnabled::Lid(l) => set(&mut enabled.rog.lid, l),
aura_cli::SetAuraZoneEnabled::RearGlow(r) => set(&mut enabled.rog.rear_glow, r),
if let Some(pow) = power.command.as_ref() {
if pow.help_requested() {
println!("{}", pow.self_usage());
return Ok(());
}
}
dbus.proxies().led().set_led_power(enabled, true)?;
let mut states = aura.led_power()?;
let mut set = |zone: PowerZones, set_to: &AuraPowerStates| {
for state in states.states.iter_mut() {
if state.zone == zone {
state.boot = set_to.boot;
state.awake = set_to.awake;
state.sleep = set_to.sleep;
state.shutdown = set_to.shutdown;
break;
}
}
};
if let Some(cmd) = &power.command {
match cmd {
aura_cli::SetAuraZoneEnabled::Keyboard(k) => set(PowerZones::Keyboard, k),
aura_cli::SetAuraZoneEnabled::Logo(l) => set(PowerZones::Logo, l),
aura_cli::SetAuraZoneEnabled::Lightbar(l) => set(PowerZones::Lightbar, l),
aura_cli::SetAuraZoneEnabled::Lid(l) => set(PowerZones::Lid, l),
aura_cli::SetAuraZoneEnabled::RearGlow(r) => set(PowerZones::RearGlow, r),
}
}
aura.set_led_power(states)?;
}
}
Ok(())
}
fn handle_profile(
dbus: &RogDbusClientBlocking<'_>,
supported: &PlatformProfileFunctions,
fn handle_throttle_profile(
conn: &Connection,
supported: &[Properties],
cmd: &ProfileCommand,
) -> Result<(), Box<dyn std::error::Error>> {
if !supported.platform_profile {
if !supported.contains(&Properties::ThrottlePolicy) {
println!("Profiles not supported by either this kernel or by the laptop.");
return Err(ProfileError::NotSupported.into());
}
@@ -634,35 +757,36 @@ fn handle_profile(
return Ok(());
}
let proxy = PlatformProxyBlocking::new(conn)?;
let current = proxy.throttle_thermal_policy()?;
if cmd.next {
dbus.proxies().profile().next_profile()?;
proxy.set_throttle_thermal_policy(current.next())?;
} else if let Some(profile) = cmd.profile_set {
dbus.proxies().profile().set_active_profile(profile)?;
proxy.set_throttle_thermal_policy(profile)?;
}
if cmd.list {
let res = dbus.proxies().profile().profiles()?;
let res = ThrottlePolicy::list();
for p in &res {
println!("{:?}", p);
}
}
if cmd.profile_get {
let res = dbus.proxies().profile().active_profile()?;
println!("Active profile is {:?}", res);
println!("Active profile is {current:?}");
}
Ok(())
}
fn handle_fan_curve(
dbus: &RogDbusClientBlocking<'_>,
supported: &PlatformProfileFunctions,
conn: &Connection,
supported: &[String],
cmd: &FanCurveCommand,
) -> Result<(), Box<dyn std::error::Error>> {
if supported.fans.is_empty() {
if !supported.contains(&FAN_CURVE_ZBUS_NAME.to_string()) {
println!("Fan-curves not supported by either this kernel or by the laptop.");
println!("This requires kernel 5.17 or the fan curve patch listed in the readme.");
return Err(ProfileError::NotSupported.into());
}
@@ -678,49 +802,66 @@ fn handle_fan_curve(
return Ok(());
}
if (cmd.enabled.is_some() || cmd.fan.is_some() || cmd.data.is_some())
if (cmd.enable_fan_curves.is_some() || cmd.fan.is_some() || cmd.data.is_some())
&& cmd.mod_profile.is_none()
{
println!("--enabled, --fan, and --data options require --mod-profile");
println!(
"--enable-fan-curves, --enable-fan-curve, --fan, and --data options require \
--mod-profile"
);
return Ok(());
}
let plat_proxy = PlatformProxyBlocking::new(conn)?;
let fan_proxy = FanCurvesProxyBlocking::new(conn)?;
if cmd.get_enabled {
// TODO:
// let res = dbus.proxies().profile().enabled_fan_profiles()?;
// println!("{:?}", res);
let profile = plat_proxy.throttle_thermal_policy()?;
let curves = fan_proxy.fan_curve_data(profile)?;
for curve in curves.iter() {
println!("{}", String::from(curve));
}
}
if cmd.default {
dbus.proxies().profile().set_active_curve_to_defaults()?;
let active = plat_proxy.throttle_thermal_policy()?;
fan_proxy.set_curves_to_defaults(active)?;
}
if let Some(profile) = cmd.mod_profile {
if cmd.enabled.is_none() && cmd.data.is_none() {
let data = dbus.proxies().profile().fan_curve_data(profile)?;
let data = toml::to_string(&data)?;
println!("\nFan curves for {:?}\n\n{}", profile, data);
if cmd.enable_fan_curves.is_none() && cmd.data.is_none() {
let data = fan_proxy.fan_curve_data(profile)?;
let ron = ron::ser::to_string_pretty(&data, PrettyConfig::new().depth_limit(4))?;
println!("\nFan curves for {:?}\n\n{}", profile, ron);
}
if let Some(enabled) = cmd.enabled {
dbus.proxies()
.profile()
.set_fan_curves_enabled(profile, enabled)?;
if let Some(enabled) = cmd.enable_fan_curves {
fan_proxy.set_fan_curves_enabled(profile, enabled)?;
}
if let Some(enabled) = cmd.enable_fan_curve {
if let Some(fan) = cmd.fan {
fan_proxy.set_profile_fan_curve_enabled(profile, fan, enabled)?;
} else {
println!(
"--enable-fan-curves, --enable-fan-curve, --fan, and --data options require \
--mod-profile"
);
}
}
if let Some(mut curve) = cmd.data.clone() {
let fan = cmd.fan.unwrap_or_default();
curve.set_fan(fan);
dbus.proxies().profile().set_fan_curve(profile, curve)?;
fan_proxy.set_fan_curve(profile, curve)?;
}
}
Ok(())
}
fn handle_bios_option(
dbus: &RogDbusClientBlocking<'_>,
supported: &RogBiosSupportedFunctions,
fn handle_platform_properties(
conn: &Connection,
supported: &[Properties],
cmd: &BiosCommand,
) -> Result<(), Box<dyn std::error::Error>> {
{
@@ -737,42 +878,42 @@ fn handle_bios_option(
let usage: Vec<String> = BiosCommand::usage().lines().map(|s| s.to_owned()).collect();
for line in usage.iter().filter(|line| {
line.contains("sound") && supported.post_sound
|| line.contains("GPU") && supported.gpu_mux
|| line.contains("panel") && supported.panel_overdrive
line.contains("sound") && supported.contains(&Properties::PostAnimationSound)
|| line.contains("GPU") && supported.contains(&Properties::GpuMuxMode)
|| line.contains("panel") && supported.contains(&Properties::PanelOd)
}) {
println!("{}", line);
}
}
let proxy = PlatformProxyBlocking::new(conn)?;
if let Some(opt) = cmd.post_sound_set {
dbus.proxies().rog_bios().set_post_boot_sound(opt)?;
proxy.set_boot_sound(opt)?;
}
if cmd.post_sound_get {
let res = dbus.proxies().rog_bios().post_boot_sound()? == 1;
let res = proxy.boot_sound()?;
println!("Bios POST sound on: {}", res);
}
if let Some(opt) = cmd.gpu_mux_mode_set {
println!("Rebuilding initrd to include drivers");
dbus.proxies()
.rog_bios()
.set_gpu_mux_mode(GpuMode::from_mux(opt))?;
proxy.set_gpu_mux_mode(GpuMode::from_mux(opt))?;
println!(
"The mode change is not active until you reboot, on boot the bios will make the \
required change"
);
}
if cmd.gpu_mux_mode_get {
let res = dbus.proxies().rog_bios().gpu_mux_mode()?;
let res = proxy.gpu_mux_mode()?;
println!("Bios GPU MUX: {:?}", res);
}
if let Some(opt) = cmd.panel_overdrive_set {
dbus.proxies().rog_bios().set_panel_od(opt)?;
proxy.set_panel_od(opt)?;
}
if cmd.panel_overdrive_get {
let res = dbus.proxies().rog_bios().panel_od()?;
let res = proxy.panel_od()?;
println!("Panel overdrive on: {}", res);
}
}

View File

@@ -1,52 +0,0 @@
use gumdrop::Options;
use rog_profiles::fan_curve_set::CurveData;
use rog_profiles::{FanCurvePU, Profile};
#[derive(Debug, Clone, Options)]
pub struct ProfileCommand {
#[options(help = "print help message")]
pub help: bool,
#[options(help = "toggle to next profile in list")]
pub next: bool,
#[options(help = "list available profiles")]
pub list: bool,
#[options(help = "get profile")]
pub profile_get: bool,
#[options(meta = "", help = "set the active profile")]
pub profile_set: Option<Profile>,
}
#[derive(Debug, Clone, Options)]
pub struct FanCurveCommand {
#[options(help = "print help message")]
pub help: bool,
#[options(help = "get enabled fan profiles")]
pub get_enabled: bool,
#[options(help = "set the active profile's fan curve to default")]
pub default: bool,
#[options(
meta = "",
help = "profile to modify fan-curve for. Shows data if no options provided"
)]
pub mod_profile: Option<Profile>,
#[options(
meta = "",
help = "enable or disable <true/false> fan curve. `mod_profile` required"
)]
pub enabled: Option<bool>,
#[options(
meta = "",
help = "select fan <cpu/gpu/mid> to modify. `mod_profile` required"
)]
pub fan: Option<FanCurvePU>,
#[options(
meta = "",
help = "data format = 30c:1%,49c:2%,59c:3%,69c:4%,79c:31%,89c:49%,99c:56%,109c:58%.
`--mod-profile` required. If '%' is omitted the fan range is 0-255"
)]
pub data: Option<CurveData>,
}

20
asusctl/src/slash_cli.rs Normal file
View File

@@ -0,0 +1,20 @@
use gumdrop::Options;
use rog_slash::SlashMode;
#[derive(Options)]
pub struct SlashCommand {
#[options(help = "print help message")]
pub help: bool,
#[options(help = "Enable the Slash Ledbar")]
pub enable: bool,
#[options(help = "Ddisable the Slash Ledbar")]
pub disable: bool,
#[options(meta = "", help = "Set brightness value <0-255>")]
pub brightness: Option<u8>,
#[options(meta = "", help = "Set interval value <0-255>")]
pub interval: Option<u8>,
#[options(help = "Set SlashMode (so 'list' for all options)")]
pub slash_mode: Option<SlashMode>,
#[options(help = "list available animations")]
pub list: bool,
}

View File

@@ -1,10 +1,12 @@
[package]
name = "asusd-user"
license = "MPL-2.0"
license.workspace = true
version.workspace = true
authors = ["Luke D Jones <luke@ljones.dev>"]
edition = "2021"
description = "Usermode daemon for user settings, anime, per-key lighting"
readme.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
edition.workspace = true
[[bin]]
name = "asusd-user"
@@ -16,8 +18,8 @@ smol.workspace = true
# serialisation
serde.workspace = true
serde_json.workspace = true
serde_derive.workspace = true
ron.workspace = true
rog_anime = { path = "../rog-anime" }
rog_aura = { path = "../rog-aura" }
@@ -26,10 +28,10 @@ rog_platform = { path = "../rog-platform" }
config-traits = { path = "../config-traits" }
zbus.workspace = true
# cli and logging
log.workspace = true
env_logger.workspace = true
[dev-dependencies]
cargo-husky.workspace = true
cargo-husky.workspace = true
[package.metadata.cargo-machete]
ignored = ["serde"]

View File

@@ -3,8 +3,8 @@ use std::time::Duration;
use config_traits::{StdConfig, StdConfigLoad};
use rog_anime::{ActionLoader, AnimTime, AnimeType, Fade, Sequences as AnimeSequences, Vec2};
use rog_aura::advanced::LedCode;
use rog_aura::effects::{AdvancedEffects as AuraSequences, Breathe, DoomFlicker, Effect, Static};
use rog_aura::keyboard::LedCode;
use rog_aura::{Colour, Speed};
use serde_derive::{Deserialize, Serialize};

View File

@@ -7,9 +7,10 @@ use std::time::{Duration, Instant};
use config_traits::StdConfig;
use rog_anime::error::AnimeError;
use rog_anime::{ActionData, ActionLoader, AnimTime, Fade, Sequences, Vec2};
use rog_dbus::RogDbusClientBlocking;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use ron::ser::PrettyConfig;
use serde_derive::{Deserialize, Serialize};
use zbus::dbus_interface;
use zbus::interface;
use zbus::zvariant::{ObjectPath, Type};
use crate::config::ConfigAnime;
@@ -61,14 +62,14 @@ pub enum TimeType {
/// thread and a zbus server behind `Arc<Mutex<T>>`
pub struct CtrlAnimeInner<'a> {
sequences: Sequences,
client: RogDbusClientBlocking<'a>,
client: AnimeProxyBlocking<'a>,
do_early_return: Arc<AtomicBool>,
}
impl<'a> CtrlAnimeInner<'static> {
pub fn new(
sequences: Sequences,
client: RogDbusClientBlocking<'static>,
client: AnimeProxyBlocking<'static>,
do_early_return: Arc<AtomicBool>,
) -> Result<Self, Error> {
Ok(Self {
@@ -93,19 +94,13 @@ impl<'a> CtrlAnimeInner<'static> {
return Ok(true); // Do safe exit
}
self.client
.proxies()
.anime()
.write(output)
.map_err(|e| AnimeError::Dbus(format!("{}", e)))
.map(|_| false)
});
}
ActionData::Image(image) => {
self.client
.proxies()
.anime()
.write(image.as_ref().clone())
.ok();
self.client.write(image.as_ref().clone()).ok();
}
ActionData::Pause(duration) => {
let start = Instant::now();
@@ -132,7 +127,7 @@ impl<'a> CtrlAnimeInner<'static> {
pub struct CtrlAnime<'a> {
config: Arc<Mutex<ConfigAnime>>,
client: RogDbusClientBlocking<'a>,
client: AnimeProxyBlocking<'a>,
inner: Arc<Mutex<CtrlAnimeInner<'a>>>,
/// Must be the same Atomic as in CtrlAnimeInner
inner_early_return: Arc<AtomicBool>,
@@ -142,7 +137,7 @@ impl CtrlAnime<'static> {
pub fn new(
config: Arc<Mutex<ConfigAnime>>,
inner: Arc<Mutex<CtrlAnimeInner<'static>>>,
client: RogDbusClientBlocking<'static>,
client: AnimeProxyBlocking<'static>,
inner_early_return: Arc<AtomicBool>,
) -> Result<Self, Error> {
Ok(CtrlAnime {
@@ -175,7 +170,7 @@ impl CtrlAnime<'static> {
// - Do actions
// - Write config if required
// - Unset inner_early_return
#[dbus_interface(name = "org.asuslinux.Daemon")]
#[interface(name = "org.asuslinux.Daemon")]
impl CtrlAnime<'static> {
pub fn insert_asus_gif(
&mut self,
@@ -205,11 +200,12 @@ impl CtrlAnime<'static> {
config.anime.push(action);
config.write();
let json = serde_json::to_string_pretty(&*config).expect("Parse config to JSON failed");
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
.expect("Parse config to RON failed");
// Release the inner run loop again
self.inner_early_return.store(false, Ordering::SeqCst);
return Ok(json);
return Ok(ron);
}
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
}
@@ -250,12 +246,11 @@ impl CtrlAnime<'static> {
config.anime.push(action);
config.write();
let json =
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
.expect("Parse config to RON failed");
// Release the inner run loop again
self.inner_early_return.store(false, Ordering::SeqCst);
return Ok(json);
return Ok(ron);
}
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
}
@@ -295,12 +290,11 @@ impl CtrlAnime<'static> {
config.anime.push(action);
config.write();
let json =
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
.expect("Parse config to RON failed");
// Release the inner run loop again
self.inner_early_return.store(false, Ordering::SeqCst);
return Ok(json);
return Ok(ron);
}
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
}
@@ -320,12 +314,11 @@ impl CtrlAnime<'static> {
config.anime.push(action);
config.write();
let json =
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
.expect("Parse config to RON failed");
// Release the inner run loop again
self.inner_early_return.store(false, Ordering::SeqCst);
return Ok(json);
return Ok(ron);
}
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
}
@@ -343,12 +336,11 @@ impl CtrlAnime<'static> {
}
config.write();
let json =
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
.expect("Parse config to RON failed");
// Release the inner run loop again
self.inner_early_return.store(false, Ordering::SeqCst);
return Ok(json);
return Ok(ron);
}
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
}
@@ -356,13 +348,13 @@ impl CtrlAnime<'static> {
pub fn set_state(&mut self, on: bool) -> zbus::fdo::Result<()> {
// Operations here need to be in specific order
if on {
self.client.proxies().anime().set_enable_display(on).ok();
self.client.set_enable_display(on).ok();
// Let the inner loop run
self.inner_early_return.store(false, Ordering::SeqCst);
} else {
// Must make the inner run loop return early
self.inner_early_return.store(true, Ordering::SeqCst);
self.client.proxies().anime().set_enable_display(on).ok();
self.client.set_enable_display(on).ok();
}
Ok(())
}

View File

@@ -5,12 +5,14 @@ use std::sync::{Arc, Mutex};
use asusd_user::config::*;
use asusd_user::ctrl_anime::{CtrlAnime, CtrlAnimeInner};
use asusd_user::DBUS_NAME;
use config_traits::{StdConfig, StdConfigLoad};
use rog_anime::usb::get_anime_type;
use rog_aura::aura_detection::LaptopLedData;
use rog_aura::layouts::KeyLayout;
use rog_dbus::RogDbusClientBlocking;
use rog_aura::aura_detection::LedSupportData;
use rog_aura::keyboard::KeyLayout;
use rog_dbus::zbus_anime::AnimeProxyBlocking;
use rog_dbus::zbus_aura::AuraProxyBlocking;
use rog_dbus::zbus_platform::PlatformProxyBlocking;
use rog_dbus::DBUS_NAME;
use smol::Executor;
use zbus::Connection;
@@ -33,22 +35,26 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" rog-dbus v{}", rog_dbus::VERSION);
println!("rog-platform v{}", rog_platform::VERSION);
let (client, _) = RogDbusClientBlocking::new()?;
let supported = client.proxies().supported().supported_functions()?;
let conn = zbus::blocking::Connection::system().unwrap();
let platform_proxy = PlatformProxyBlocking::new(&conn).unwrap();
let supported = platform_proxy
.supported_interfaces()
.unwrap_or_default()
.contains(&"Anime".to_string());
let config = ConfigBase::new().load();
let executor = Executor::new();
let early_return = Arc::new(AtomicBool::new(false));
// Set up the anime data and run loop/thread
if supported.anime_ctrl.0 {
if supported {
if let Some(cfg) = config.active_anime {
let anime_type = get_anime_type()?;
let anime_config = ConfigAnime::new().set_name(cfg).load();
let anime = anime_config.create(anime_type)?;
let anime_config = Arc::new(Mutex::new(anime_config));
let anime_proxy_blocking = AnimeProxyBlocking::new(&conn).unwrap();
executor
.spawn(async move {
// Create server
@@ -57,12 +63,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Inner behind mutex required for thread safety
let inner = Arc::new(Mutex::new(
CtrlAnimeInner::new(anime, client, early_return.clone()).unwrap(),
CtrlAnimeInner::new(
anime,
anime_proxy_blocking.clone(),
early_return.clone(),
)
.unwrap(),
));
// Need new client object for dbus control part
let (client, _) = RogDbusClientBlocking::new().unwrap();
let anime_control =
CtrlAnime::new(anime_config, inner.clone(), client, early_return).unwrap();
let anime_control = CtrlAnime::new(
anime_config,
inner.clone(),
anime_proxy_blocking,
early_return,
)
.unwrap();
anime_control.add_to_server(&mut connection).await;
loop {
if let Ok(inner) = inner.clone().try_lock() {
@@ -79,7 +94,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut aura_config = ConfigAura::new().set_name(cfg).load();
// let baord_name = std::fs::read_to_string(BOARD_NAME)?;
let led_support = LaptopLedData::get_data();
let led_support = LedSupportData::get_data("");
let layout = KeyLayout::find_layout(led_support, PathBuf::from(DATA_DIR))
.map_err(|e| {
@@ -87,22 +102,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
})
.unwrap_or_else(|_| KeyLayout::default_layout());
let aura_proxy_blocking = AuraProxyBlocking::new(&conn).unwrap();
executor
.spawn(async move {
// Create server
let (client, _) = RogDbusClientBlocking::new().unwrap();
// let connection = Connection::session().await.unwrap();
// connection.request_name(DBUS_NAME).await.unwrap();
loop {
aura_config.aura.next_state(&layout);
let packets = aura_config.aura.create_packets();
client
.proxies()
.led()
.direct_addressing_raw(packets)
.unwrap();
aura_proxy_blocking.direct_addressing_raw(packets).unwrap();
std::thread::sleep(std::time::Duration::from_millis(33));
}
})

View File

@@ -6,6 +6,4 @@ pub mod ctrl_anime;
pub mod zbus_anime;
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
pub static VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@@ -21,9 +21,9 @@
//! …consequently `zbus-xmlgen` did not generate code for the above interfaces.
#![allow(clippy::too_many_arguments)]
use zbus::dbus_proxy;
use zbus::proxy;
#[dbus_proxy(
#[proxy(
interface = "org.asuslinux.Daemon",
default_path = "/org/asuslinux/Anime"
)]

View File

@@ -1,13 +1,13 @@
[package]
name = "asusd"
license = "MPL-2.0"
license.workspace = true
version.workspace = true
readme = "README.md"
authors = ["Luke <luke@ljones.dev>"]
repository = "https://gitlab.com/asus-linux/asus-nb-ctrl"
homepage = "https://gitlab.com/asus-linux/asus-nb-ctrl"
description = "A daemon app for ASUS GX502 and similar laptops to control missing features"
edition = "2021"
readme.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
description.workspace = true
edition.workspace = true
[[bin]]
name = "asusd"
@@ -16,13 +16,18 @@ path = "src/daemon.rs"
[dependencies]
config-traits = { path = "../config-traits" }
rog_anime = { path = "../rog-anime", features = ["dbus"] }
rog_slash = { path = "../rog-slash", features = ["dbus"] }
rog_aura = { path = "../rog-aura", features = ["dbus"] }
rog_platform = { path = "../rog-platform" }
rog_profiles = { path = "../rog-profiles" }
rog_dbus = { path = "../rog-dbus" }
dmi_id = { path = "../dmi-id" }
futures-lite = "*"
udev.workspace = true
inotify.workspace = true
async-trait.workspace = true
mio.workspace = true
tokio.workspace = true
# console-subscriber = "0.2.0"
# cli and logging
log.workspace = true
@@ -35,12 +40,10 @@ logind-zbus.workspace = true
serde.workspace = true
serde_derive.workspace = true
# Device control
sysfs-class.workspace = true # used for backlight control and baord ID
concat-idents.workspace = true
systemd-zbus = "*"
[dev-dependencies]
cargo-husky.workspace = true
cargo-husky.workspace = true
[package.metadata.cargo-machete]
ignored = ["serde"]

View File

@@ -1,83 +1,159 @@
use config_traits::{StdConfig, StdConfigLoad2};
use config_traits::{StdConfig, StdConfigLoad1};
use rog_platform::cpu::CPUEPP;
use rog_platform::platform::ThrottlePolicy;
use serde_derive::{Deserialize, Serialize};
const CONFIG_FILE: &str = "asusd.ron";
#[derive(Deserialize, Serialize, Default, Debug)]
#[derive(Deserialize, Serialize, Debug, PartialEq, PartialOrd)]
pub struct Config {
/// Save charge limit for restoring on boot
pub bat_charge_limit: u8,
/// Save charge limit for restoring on boot/resume
pub charge_control_end_threshold: u8,
pub panel_od: bool,
pub boot_sound: bool,
pub mini_led_mode: bool,
pub disable_nvidia_powerd_on_battery: bool,
/// An optional command/script to run when power is changed to AC
pub ac_command: String,
/// An optional command/script to run when power is changed to battery
pub bat_command: String,
/// Set true if energy_performance_preference should be set if the
/// throttle/platform profile is changed
pub throttle_policy_linked_epp: bool,
/// Which throttle/profile to use on battery power
pub throttle_policy_on_battery: ThrottlePolicy,
/// Which throttle/profile to use on AC power
pub throttle_policy_on_ac: ThrottlePolicy,
/// The energy_performance_preference for this throttle/platform profile
pub throttle_quiet_epp: CPUEPP,
/// The energy_performance_preference for this throttle/platform profile
pub throttle_balanced_epp: CPUEPP,
/// The energy_performance_preference for this throttle/platform profile
pub throttle_performance_epp: CPUEPP,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ppt_pl1_spl: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ppt_pl2_sppt: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ppt_fppt: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ppt_apu_sppt: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub ppt_platform_sppt: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub nv_dynamic_boost: Option<u8>,
/// Defaults to `None` if not supported
#[serde(skip_serializing_if = "Option::is_none", default)]
pub nv_temp_target: Option<u8>,
/// Temporary state for AC/Batt
#[serde(skip)]
pub last_power_plugged: u8,
}
impl Default for Config {
fn default() -> Self {
Self {
charge_control_end_threshold: 100,
panel_od: false,
boot_sound: false,
mini_led_mode: false,
disable_nvidia_powerd_on_battery: true,
ac_command: Default::default(),
bat_command: Default::default(),
throttle_policy_linked_epp: true,
throttle_policy_on_battery: ThrottlePolicy::Quiet,
throttle_policy_on_ac: ThrottlePolicy::Performance,
throttle_quiet_epp: CPUEPP::Power,
throttle_balanced_epp: CPUEPP::BalancePower,
throttle_performance_epp: CPUEPP::Performance,
ppt_pl1_spl: Default::default(),
ppt_pl2_sppt: Default::default(),
ppt_fppt: Default::default(),
ppt_apu_sppt: Default::default(),
ppt_platform_sppt: Default::default(),
nv_dynamic_boost: Default::default(),
nv_temp_target: Default::default(),
last_power_plugged: Default::default(),
}
}
}
impl StdConfig for Config {
fn new() -> Self {
Config {
bat_charge_limit: 100,
panel_od: false,
mini_led_mode: false,
charge_control_end_threshold: 100,
disable_nvidia_powerd_on_battery: true,
throttle_policy_on_battery: ThrottlePolicy::Quiet,
throttle_policy_on_ac: ThrottlePolicy::Performance,
ac_command: String::new(),
bat_command: String::new(),
..Default::default()
}
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name(&self) -> String {
CONFIG_FILE.to_owned()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
}
impl StdConfigLoad2<Config458, Config462> for Config {}
impl StdConfigLoad1<Config507> for Config {}
#[derive(Deserialize, Serialize)]
pub struct Config462 {
pub struct Config507 {
/// Save charge limit for restoring on boot
pub bat_charge_limit: u8,
pub charge_control_end_threshold: u8,
pub panel_od: bool,
pub mini_led_mode: bool,
pub disable_nvidia_powerd_on_battery: bool,
pub ac_command: String,
pub bat_command: String,
pub platform_policy_linked_epp: bool,
pub platform_policy_on_battery: ThrottlePolicy,
pub platform_policy_on_ac: ThrottlePolicy,
//
pub ppt_pl1_spl: Option<u8>,
pub ppt_pl2_sppt: Option<u8>,
pub ppt_fppt: Option<u8>,
pub ppt_apu_sppt: Option<u8>,
pub ppt_platform_sppt: Option<u8>,
pub nv_dynamic_boost: Option<u8>,
pub nv_temp_target: Option<u8>,
}
impl From<Config462> for Config {
fn from(c: Config462) -> Self {
impl From<Config507> for Config {
fn from(c: Config507) -> Self {
Self {
bat_charge_limit: c.bat_charge_limit,
charge_control_end_threshold: c.charge_control_end_threshold,
panel_od: c.panel_od,
mini_led_mode: false,
disable_nvidia_powerd_on_battery: true,
ac_command: String::new(),
bat_command: String::new(),
}
}
}
#[derive(Deserialize, Serialize)]
pub struct Config458 {
/// Save charge limit for restoring on boot
pub bat_charge_limit: u8,
pub panel_od: bool,
pub ac_command: String,
pub bat_command: String,
}
impl From<Config458> for Config {
fn from(c: Config458) -> Self {
Self {
bat_charge_limit: c.bat_charge_limit,
panel_od: c.panel_od,
mini_led_mode: false,
disable_nvidia_powerd_on_battery: true,
boot_sound: false,
disable_nvidia_powerd_on_battery: c.disable_nvidia_powerd_on_battery,
ac_command: c.ac_command,
bat_command: c.bat_command,
mini_led_mode: c.mini_led_mode,
throttle_policy_linked_epp: true,
throttle_policy_on_battery: c.platform_policy_on_battery,
throttle_policy_on_ac: c.platform_policy_on_ac,
throttle_quiet_epp: CPUEPP::Power,
throttle_balanced_epp: CPUEPP::BalancePower,
throttle_performance_epp: CPUEPP::Performance,
ppt_pl1_spl: c.ppt_pl1_spl,
ppt_pl2_sppt: c.ppt_pl2_sppt,
ppt_fppt: c.ppt_fppt,
ppt_apu_sppt: c.ppt_apu_sppt,
ppt_platform_sppt: c.ppt_platform_sppt,
nv_dynamic_boost: c.nv_dynamic_boost,
nv_temp_target: c.nv_temp_target,
last_power_plugged: 0,
}
}
}

View File

@@ -3,7 +3,9 @@ use std::time::Duration;
use config_traits::{StdConfig, StdConfigLoad2};
use rog_anime::error::AnimeError;
use rog_anime::usb::Brightness;
use rog_anime::{ActionData, ActionLoader, AnimTime, Animations, AnimeType, Fade, Vec2};
use rog_anime::{
ActionData, ActionLoader, AnimTime, Animations, AnimeType, DeviceState, Fade, Vec2,
};
use serde_derive::{Deserialize, Serialize};
const CONFIG_FILE: &str = "anime.ron";
@@ -24,7 +26,6 @@ impl From<AnimeConfigV460> for AnimeConfig {
system: c.system,
boot: c.boot,
wake: c.wake,
sleep: c.sleep,
shutdown: c.shutdown,
..Default::default()
}
@@ -32,25 +33,32 @@ impl From<AnimeConfigV460> for AnimeConfig {
}
#[derive(Deserialize, Serialize, Debug)]
pub struct AnimeConfigV5 {
pub struct AnimeConfigV472 {
pub model_override: Option<AnimeType>,
pub system: Vec<ActionLoader>,
pub boot: Vec<ActionLoader>,
pub wake: Vec<ActionLoader>,
pub sleep: Vec<ActionLoader>,
pub shutdown: Vec<ActionLoader>,
pub brightness: f32,
pub awake_enabled: bool,
pub boot_anim_enabled: bool,
pub display_enabled: bool,
pub display_brightness: Brightness,
pub builtin_anims_enabled: bool,
pub builtin_anims: Animations,
}
impl From<AnimeConfigV5> for AnimeConfig {
fn from(c: AnimeConfigV5) -> AnimeConfig {
impl From<AnimeConfigV472> for AnimeConfig {
fn from(c: AnimeConfigV472) -> AnimeConfig {
AnimeConfig {
system: c.system,
boot: c.boot,
wake: c.wake,
sleep: c.sleep,
shutdown: c.shutdown,
model_override: c.model_override,
display_enabled: c.display_enabled,
display_brightness: c.display_brightness,
builtin_anims_enabled: c.builtin_anims_enabled,
builtin_anims: c.builtin_anims,
..Default::default()
}
}
@@ -61,7 +69,6 @@ pub struct AnimeConfigCached {
pub system: Vec<ActionData>,
pub boot: Vec<ActionData>,
pub wake: Vec<ActionData>,
pub sleep: Vec<ActionData>,
pub shutdown: Vec<ActionData>,
}
@@ -89,12 +96,6 @@ impl AnimeConfigCached {
}
self.wake = wake;
let mut sleep = Vec::with_capacity(config.sleep.len());
for ani in &config.sleep {
sleep.push(ActionData::from_anime_action(anime_type, ani)?);
}
self.sleep = sleep;
let mut shutdown = Vec::with_capacity(config.shutdown.len());
for ani in &config.shutdown {
shutdown.push(ActionData::from_anime_action(anime_type, ani)?);
@@ -105,18 +106,21 @@ impl AnimeConfigCached {
}
/// Config for base system actions for the anime display
#[derive(Deserialize, Serialize, Debug)]
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AnimeConfig {
pub model_override: Option<AnimeType>,
pub system: Vec<ActionLoader>,
pub boot: Vec<ActionLoader>,
pub wake: Vec<ActionLoader>,
pub sleep: Vec<ActionLoader>,
pub shutdown: Vec<ActionLoader>,
pub brightness: f32,
// pub brightness: f32,
pub display_enabled: bool,
pub display_brightness: Brightness,
pub builtin_anims_enabled: bool,
pub off_when_unplugged: bool,
pub off_when_suspended: bool,
pub off_when_lid_closed: bool,
pub brightness_on_battery: Brightness,
pub builtin_anims: Animations,
}
@@ -127,12 +131,15 @@ impl Default for AnimeConfig {
system: Vec::new(),
boot: Vec::new(),
wake: Vec::new(),
sleep: Vec::new(),
shutdown: Vec::new(),
brightness: 1.0,
// brightness: 1.0,
display_enabled: true,
display_brightness: Brightness::Med,
builtin_anims_enabled: true,
off_when_unplugged: true,
off_when_suspended: true,
off_when_lid_closed: true,
brightness_on_battery: Brightness::Low,
builtin_anims: Animations::default(),
}
}
@@ -143,16 +150,31 @@ impl StdConfig for AnimeConfig {
Self::create_default()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name(&self) -> String {
CONFIG_FILE.to_owned()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
}
impl StdConfigLoad2<AnimeConfigV460, AnimeConfigV5> for AnimeConfig {}
impl StdConfigLoad2<AnimeConfigV460, AnimeConfigV472> for AnimeConfig {}
impl From<&AnimeConfig> for DeviceState {
fn from(config: &AnimeConfig) -> Self {
DeviceState {
display_enabled: config.display_enabled,
display_brightness: config.display_brightness,
builtin_anims_enabled: config.builtin_anims_enabled,
builtin_anims: config.builtin_anims,
off_when_unplugged: config.off_when_unplugged,
off_when_suspended: config.off_when_suspended,
off_when_lid_closed: config.off_when_lid_closed,
brightness_on_battery: config.brightness_on_battery,
}
}
}
impl AnimeConfig {
// fn clamp_config_brightness(mut config: &mut AnimeConfig) {
@@ -193,14 +215,6 @@ impl AnimeConfig {
Duration::from_secs(2),
)),
}],
sleep: vec![ActionLoader::ImageAnimation {
file: "/usr/share/asusd/anime/custom/sonic-wait.gif".into(),
scale: 0.9,
angle: 0.0,
translation: Vec2::new(3.0, 2.0),
brightness: 1.0,
time: AnimTime::Infinite,
}],
shutdown: vec![ActionLoader::ImageAnimation {
file: "/usr/share/asusd/anime/custom/sonic-wait.gif".into(),
scale: 0.9,
@@ -209,7 +223,6 @@ impl AnimeConfig {
brightness: 1.0,
time: AnimTime::Infinite,
}],
brightness: 1.0,
..Default::default()
}
}

View File

@@ -8,25 +8,19 @@ use std::sync::Arc;
use std::thread::sleep;
use ::zbus::export::futures_util::lock::Mutex;
use config_traits::{StdConfig, StdConfigLoad2};
use log::{error, info, warn};
use rog_anime::error::AnimeError;
use rog_anime::usb::{get_anime_type, pkt_flush, pkt_set_enable_powersave_anim, pkts_for_init};
use rog_anime::usb::{
get_anime_type, pkt_flush, pkt_set_brightness, pkt_set_enable_display,
pkt_set_enable_powersave_anim, pkts_for_init, Brightness,
};
use rog_anime::{ActionData, AnimeDataBuffer, AnimePacketType, AnimeType};
use rog_platform::hid_raw::HidRaw;
use rog_platform::supported::AnimeSupportedFunctions;
use rog_platform::usb_raw::USBRaw;
use self::config::{AnimeConfig, AnimeConfigCached};
use crate::error::RogError;
use crate::GetSupported;
impl GetSupported for CtrlAnime {
type A = AnimeSupportedFunctions;
fn get_supported() -> Self::A {
AnimeSupportedFunctions(HidRaw::new("193b").is_ok())
}
}
enum Node {
Usb(USBRaw),
@@ -46,6 +40,13 @@ impl Node {
}
Ok(())
}
pub fn set_builtins_enabled(&self, enabled: bool, bright: Brightness) -> Result<(), RogError> {
self.write_bytes(&pkt_set_enable_powersave_anim(enabled))?;
self.write_bytes(&pkt_set_enable_display(enabled))?;
self.write_bytes(&pkt_set_brightness(bright))?;
self.write_bytes(&pkt_set_enable_powersave_anim(enabled))
}
}
pub struct CtrlAnime {
@@ -62,17 +63,34 @@ pub struct CtrlAnime {
impl CtrlAnime {
#[inline]
pub fn new(config: AnimeConfig) -> Result<CtrlAnime, RogError> {
let hid = HidRaw::new("193b").ok();
pub fn new() -> Result<CtrlAnime, RogError> {
let usb = USBRaw::new(0x193b).ok();
let node = if hid.is_some() {
unsafe { Node::Hid(hid.unwrap_unchecked()) }
} else if usb.is_some() {
let hid = HidRaw::new("193b").ok();
let node = if usb.is_some() {
info!("Anime using the USB interface");
unsafe { Node::Usb(usb.unwrap_unchecked()) }
} else if hid.is_some() {
info!("Anime using the HID interface");
unsafe { Node::Hid(hid.unwrap_unchecked()) }
} else {
return Err(RogError::Anime(AnimeError::NoDevice));
};
// TODO: something better to set wakeups disabled
// if matches!(node, Node::Usb(_)) {
// if let Ok(mut enumerator) = udev::Enumerator::new() {
// enumerator.match_subsystem("usb").ok();
// enumerator.match_attribute("idProduct", "193b").ok();
// if let Ok(mut enumer) = enumerator.scan_devices() {
// if let Some(mut dev) = enumer.next() {
// dev.set_attribute_value("power/wakeup", "disabled").ok();
// }
// }
// }
// }
let config = AnimeConfig::new().load();
let mut anime_type = get_anime_type()?;
if let AnimeType::Unknown = anime_type {
if let Some(model) = config.model_override {
@@ -230,6 +248,14 @@ impl CtrlAnime {
})
.ok();
}
lock.node
.write_bytes(&pkt_set_enable_powersave_anim(
lock.config.builtin_anims_enabled,
))
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
})
.ok();
}
// Loop ended, set the atmonics
thread_running.store(false, Ordering::SeqCst);
@@ -243,7 +269,7 @@ impl CtrlAnime {
/// global brightness set in config.
fn write_data_buffer(&self, mut buffer: AnimeDataBuffer) -> Result<(), RogError> {
for led in buffer.data_mut().iter_mut() {
let mut bright = *led as f32 * self.config.brightness;
let mut bright = *led as f32;
if bright > 254.0 {
bright = 254.0;
}

View File

@@ -1,228 +1,300 @@
use std::sync::atomic::Ordering;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::warn;
use logind_zbus::manager::ManagerProxy;
use rog_anime::usb::{
pkt_set_brightness, pkt_set_builtin_animations, pkt_set_enable_display,
pkt_set_enable_powersave_anim, AnimAwake, AnimBooting, AnimShutdown, AnimSleeping, Brightness,
pkt_set_enable_powersave_anim, Brightness,
};
use rog_anime::{AnimeDataBuffer, DeviceState};
use rog_anime::{Animations, AnimeDataBuffer, DeviceState};
use zbus::export::futures_util::lock::Mutex;
use zbus::{dbus_interface, Connection, SignalContext};
use zbus::{interface, CacheProperties, Connection, SignalContext};
use super::config::AnimeConfig;
use super::CtrlAnime;
use crate::error::RogError;
pub(super) const ZBUS_PATH: &str = "/org/asuslinux/Anime";
pub const ANIME_ZBUS_NAME: &str = "Anime";
pub const ANIME_ZBUS_PATH: &str = "/org/asuslinux";
async fn get_logind_manager<'a>() -> ManagerProxy<'a> {
let connection = Connection::system()
.await
.expect("Controller could not create dbus connection");
ManagerProxy::builder(&connection)
.cache_properties(CacheProperties::No)
.build()
.await
.expect("Controller could not create ManagerProxy")
}
#[derive(Clone)]
pub struct CtrlAnimeZbus(pub Arc<Mutex<CtrlAnime>>);
/// The struct with the main dbus methods requires this trait
#[async_trait]
impl crate::ZbusRun for CtrlAnimeZbus {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
Self::add_to_server_helper(self, ANIME_ZBUS_PATH, server).await;
}
}
// None of these calls can be guarnateed to succeed unless we loop until okay
// If the try_lock *does* succeed then any other thread trying to lock will not
// grab it until we finish.
#[dbus_interface(name = "org.asuslinux.Daemon")]
#[interface(name = "org.asuslinux.Anime")]
impl CtrlAnimeZbus {
/// Writes a data stream of length. Will force system thread to exit until
/// it is restarted
async fn write(&self, input: AnimeDataBuffer) -> zbus::fdo::Result<()> {
let lock = self.0.lock().await;
lock.thread_exit.store(true, Ordering::SeqCst);
lock.write_data_buffer(input).map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
err
})?;
self.0
.lock()
.await
.thread_exit
.store(true, Ordering::SeqCst);
self.0
.lock()
.await
.write_data_buffer(input)
.map_err(|err| {
warn!("ctrl_anime::run_animation:callback {}", err);
err
})?;
Ok(())
}
/// Set the global AniMe brightness
async fn set_image_brightness(&self, bright: f32) {
let mut lock = self.0.lock().await;
let mut bright = bright;
if bright < 0.0 {
bright = 0.0;
} else if bright > 1.0 {
bright = 1.0;
}
lock.config.brightness = bright;
lock.config.write();
/// Set base brightness level
#[zbus(property)]
async fn brightness(&self) -> Brightness {
self.0.lock().await.config.display_brightness
}
/// Set base brightness level
// TODO: enum for brightness
async fn set_brightness(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
brightness: Brightness,
) {
let mut lock = self.0.lock().await;
lock.node
#[zbus(property)]
async fn set_brightness(&self, brightness: Brightness) {
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_brightness(brightness))
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
warn!("ctrl_anime::set_brightness {}", err);
})
.ok();
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(brightness != Brightness::Off))
.map_err(|err| {
warn!("ctrl_anime::set_brightness {}", err);
})
.ok();
lock.config.display_brightness = brightness;
lock.config.write();
Self::notify_device_state(
&ctxt,
DeviceState {
display_enabled: lock.config.display_enabled,
display_brightness: lock.config.display_brightness,
builtin_anims_enabled: lock.config.builtin_anims_enabled,
builtin_anims: lock.config.builtin_anims,
},
)
.await
.ok();
self.0.lock().await.config.display_enabled = brightness != Brightness::Off;
self.0.lock().await.config.display_brightness = brightness;
self.0.lock().await.config.write();
}
#[zbus(property)]
async fn builtins_enabled(&self) -> bool {
let lock = self.0.lock().await;
lock.config.builtin_anims_enabled
}
/// Enable the builtin animations or not. This is quivalent to "Powersave
/// animations" in Armory crate
async fn set_builtins_enabled(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
enabled: bool,
) {
let mut lock = self.0.lock().await;
lock.node
.write_bytes(&pkt_set_enable_powersave_anim(enabled))
#[zbus(property)]
async fn set_builtins_enabled(&self, enabled: bool) {
let brightness = self.0.lock().await.config.display_brightness;
self.0
.lock()
.await
.node
.set_builtins_enabled(enabled, brightness)
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
warn!("ctrl_anime::set_builtins_enabled {}", err);
})
.ok();
lock.config.builtin_anims_enabled = enabled;
lock.config.write();
if enabled {
lock.thread_exit.store(true, Ordering::Release);
if !enabled {
let anime_type = self.0.lock().await.anime_type;
let data = vec![255u8; anime_type.data_length()];
if let Ok(tmp) = AnimeDataBuffer::from_vec(anime_type, data).map_err(|err| {
warn!("ctrl_anime::set_builtins_enabled {}", err);
}) {
self.0
.lock()
.await
.node
.write_bytes(tmp.data())
.map_err(|err| {
warn!("ctrl_anime::set_builtins_enabled {}", err);
})
.ok();
}
}
Self::notify_device_state(
&ctxt,
DeviceState {
display_enabled: lock.config.display_enabled,
display_brightness: lock.config.display_brightness,
builtin_anims_enabled: lock.config.builtin_anims_enabled,
builtin_anims: lock.config.builtin_anims,
},
)
.await
.ok();
self.0.lock().await.config.builtin_anims_enabled = enabled;
self.0.lock().await.config.write();
if enabled {
self.0
.lock()
.await
.thread_exit
.store(true, Ordering::Release);
}
}
#[zbus(property)]
async fn builtin_animations(&self) -> Animations {
self.0.lock().await.config.builtin_anims
}
/// Set which builtin animation is used for each stage
async fn set_builtin_animations(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
boot: AnimBooting,
awake: AnimAwake,
sleep: AnimSleeping,
shutdown: AnimShutdown,
) {
let mut lock = self.0.lock().await;
lock.node
#[zbus(property)]
async fn set_builtin_animations(&self, settings: Animations) {
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_builtin_animations(
settings.boot,
settings.awake,
settings.sleep,
settings.shutdown,
))
.map_err(|err| {
warn!("ctrl_anime::run_animation:callback {}", err);
})
.ok();
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_enable_powersave_anim(true))
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
warn!("ctrl_anime::run_animation:callback {}", err);
})
.ok();
lock.node
.write_bytes(&pkt_set_builtin_animations(boot, awake, sleep, shutdown))
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
})
.ok();
lock.config.builtin_anims.boot = boot;
lock.config.builtin_anims.sleep = sleep;
lock.config.builtin_anims.awake = awake;
lock.config.builtin_anims.shutdown = shutdown;
lock.config.write();
self.0.lock().await.config.display_enabled = true;
self.0.lock().await.config.builtin_anims = settings;
self.0.lock().await.config.write();
}
Self::notify_device_state(
&ctxt,
DeviceState {
display_enabled: lock.config.display_enabled,
display_brightness: lock.config.display_brightness,
builtin_anims_enabled: lock.config.builtin_anims_enabled,
builtin_anims: lock.config.builtin_anims,
},
)
.await
.ok();
#[zbus(property)]
async fn enable_display(&self) -> bool {
self.0.lock().await.config.display_enabled
}
/// Set whether the AniMe is enabled at all
async fn set_enable_display(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
enabled: bool,
) {
let mut lock = self.0.lock().await;
lock.node
#[zbus(property)]
async fn set_enable_display(&self, enabled: bool) {
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(enabled))
.map_err(|err| {
warn!("rog_anime::run_animation:callback {}", err);
warn!("ctrl_anime::run_animation:callback {}", err);
})
.ok();
lock.config.display_enabled = enabled;
lock.config.write();
self.0.lock().await.config.display_enabled = enabled;
self.0.lock().await.config.write();
}
Self::notify_device_state(
&ctxt,
DeviceState {
display_enabled: lock.config.display_enabled,
display_brightness: lock.config.display_brightness,
builtin_anims_enabled: lock.config.builtin_anims_enabled,
builtin_anims: lock.config.builtin_anims,
},
)
.await
.ok();
#[zbus(property)]
async fn off_when_unplugged(&self) -> bool {
self.0.lock().await.config.off_when_unplugged
}
/// Set if to turn the AniMe Matrix off when external power is unplugged
#[zbus(property)]
async fn set_off_when_unplugged(&self, enabled: bool) {
let manager = get_logind_manager().await;
let pow = manager.on_external_power().await.unwrap_or_default();
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(!pow && !enabled))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
})
.ok();
self.0.lock().await.config.off_when_unplugged = enabled;
self.0.lock().await.config.write();
}
#[zbus(property)]
async fn off_when_suspended(&self) -> bool {
self.0.lock().await.config.off_when_suspended
}
/// Set if to turn the AniMe Matrix off when the laptop is suspended
#[zbus(property)]
async fn set_off_when_suspended(&self, enabled: bool) {
self.0.lock().await.config.off_when_suspended = enabled;
self.0.lock().await.config.write();
}
#[zbus(property)]
async fn off_when_lid_closed(&self) -> bool {
self.0.lock().await.config.off_when_lid_closed
}
/// Set if to turn the AniMe Matrix off when the lid is closed
#[zbus(property)]
async fn set_off_when_lid_closed(&self, enabled: bool) {
let manager = get_logind_manager().await;
let lid = manager.lid_closed().await.unwrap_or_default();
self.0
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(lid && !enabled))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
})
.ok();
self.0.lock().await.config.off_when_lid_closed = enabled;
self.0.lock().await.config.write();
}
/// The main loop is the base system set action if the user isn't running
/// the user daemon
async fn run_main_loop(&self, start: bool) {
if start {
let lock = self.0.lock().await;
lock.thread_exit.store(true, Ordering::SeqCst);
CtrlAnime::run_thread(self.0.clone(), lock.cache.system.clone(), false).await;
self.0
.lock()
.await
.thread_exit
.store(true, Ordering::SeqCst);
CtrlAnime::run_thread(
self.0.clone(),
self.0.lock().await.cache.system.clone(),
false,
)
.await;
}
}
/// Get the device state as stored by asusd
// #[dbus_interface(property)]
// #[zbus(property)]
async fn device_state(&self) -> DeviceState {
let lock = self.0.lock().await;
DeviceState {
display_enabled: lock.config.display_enabled,
display_brightness: lock.config.display_brightness,
builtin_anims_enabled: lock.config.builtin_anims_enabled,
builtin_anims: lock.config.builtin_anims,
}
DeviceState::from(&self.0.lock().await.config)
}
/// Notify listeners of the status of AniMe LED power and factory
/// system-status animations
#[dbus_interface(signal)]
async fn notify_device_state(ctxt: &SignalContext<'_>, data: DeviceState) -> zbus::Result<()>;
}
#[async_trait]
impl crate::CtrlTask for CtrlAnimeZbus {
fn zbus_path() -> &'static str {
ZBUS_PATH
ANIME_ZBUS_PATH
}
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
@@ -231,36 +303,164 @@ impl crate::CtrlTask for CtrlAnimeZbus {
let inner3 = self.0.clone();
let inner4 = self.0.clone();
self.create_sys_event_tasks(
move || {
move |sleeping| {
// on_sleep
let inner1 = inner1.clone();
let inner = inner1.clone();
async move {
let lock = inner1.lock().await;
CtrlAnime::run_thread(inner1.clone(), lock.cache.sleep.clone(), true).await;
let config = inner.lock().await.config.clone();
if config.display_enabled {
inner
.lock()
.await
.thread_exit
.store(true, Ordering::Release); // ensure clean slate
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(
!(sleeping && config.off_when_suspended),
))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_suspended {}", err);
})
.ok();
if config.builtin_anims_enabled {
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_powersave_anim(
!(sleeping && config.off_when_suspended),
))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_suspended {}", err);
})
.ok();
} else if !sleeping && !config.builtin_anims_enabled {
// Run custom wake animation
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_powersave_anim(false))
.ok(); // ensure builtins are disabled
CtrlAnime::run_thread(
inner.clone(),
inner.lock().await.cache.wake.clone(),
true,
)
.await;
}
}
}
},
move || {
// on_wake
let inner2 = inner2.clone();
async move {
let lock = inner2.lock().await;
CtrlAnime::run_thread(inner2.clone(), lock.cache.wake.clone(), true).await;
}
},
move || {
move |shutting_down| {
// on_shutdown
let inner3 = inner3.clone();
let inner = inner2.clone();
async move {
let lock = inner3.lock().await;
CtrlAnime::run_thread(inner3.clone(), lock.cache.shutdown.clone(), true).await;
let AnimeConfig {
display_enabled,
builtin_anims_enabled,
..
} = inner.lock().await.config;
if display_enabled && !builtin_anims_enabled {
if shutting_down {
CtrlAnime::run_thread(
inner.clone(),
inner.lock().await.cache.shutdown.clone(),
true,
)
.await;
} else {
CtrlAnime::run_thread(
inner.clone(),
inner.lock().await.cache.boot.clone(),
true,
)
.await;
}
}
}
},
move || {
// on_boot
let inner4 = inner4.clone();
move |lid_closed| {
let inner = inner3.clone();
// on lid change
async move {
let lock = inner4.lock().await;
CtrlAnime::run_thread(inner4.clone(), lock.cache.boot.clone(), true).await;
let AnimeConfig {
off_when_lid_closed,
builtin_anims_enabled,
..
} = inner.lock().await.config;
if off_when_lid_closed {
if builtin_anims_enabled {
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_powersave_anim(!lid_closed))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_suspended {}", err);
})
.ok();
}
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(!lid_closed))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
})
.ok();
}
}
},
move |power_plugged| {
let inner = inner4.clone();
// on power change
async move {
let AnimeConfig {
off_when_unplugged,
builtin_anims_enabled,
brightness_on_battery,
..
} = inner.lock().await.config;
if off_when_unplugged {
if builtin_anims_enabled {
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_powersave_anim(power_plugged))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_suspended {}", err);
})
.ok();
}
inner
.lock()
.await
.node
.write_bytes(&pkt_set_enable_display(power_plugged))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_unplugged {}", err);
})
.ok();
} else {
inner
.lock()
.await
.node
.write_bytes(&pkt_set_brightness(brightness_on_battery))
.map_err(|err| {
warn!("create_sys_event_tasks::off_when_unplugged {}", err);
})
.ok();
}
}
},
)
@@ -270,30 +470,52 @@ impl crate::CtrlTask for CtrlAnimeZbus {
}
}
#[async_trait]
impl crate::Reloadable for CtrlAnimeZbus {
async fn reload(&mut self) -> Result<(), RogError> {
if let Some(lock) = self.0.try_lock() {
let anim = &lock.config.builtin_anims;
lock.node
.write_bytes(&pkt_set_enable_display(lock.config.display_enabled))?;
lock.node.write_bytes(&pkt_set_enable_powersave_anim(
// Set builtins
if lock.config.builtin_anims_enabled {
lock.node.write_bytes(&pkt_set_builtin_animations(
anim.boot,
anim.awake,
anim.sleep,
anim.shutdown,
))?;
}
// Builtins enabled or na?
lock.node.set_builtins_enabled(
lock.config.builtin_anims_enabled,
))?;
lock.node.write_bytes(&pkt_set_builtin_animations(
anim.boot,
anim.awake,
anim.sleep,
anim.shutdown,
))?;
lock.config.display_brightness,
)?;
if lock.config.builtin_anims_enabled && !lock.cache.boot.is_empty() {
let manager = get_logind_manager().await;
let lid_closed = manager.lid_closed().await.unwrap_or_default();
let power_plugged = manager.on_external_power().await.unwrap_or_default();
let turn_off = (lid_closed && lock.config.off_when_lid_closed)
|| (!power_plugged && lock.config.off_when_unplugged);
lock.node
.write_bytes(&pkt_set_enable_display(!turn_off))
.map_err(|err| {
warn!("create_sys_event_tasks::reload {}", err);
})
.ok();
if turn_off || !lock.config.display_enabled {
lock.node.write_bytes(&pkt_set_enable_display(false))?;
// early return so we don't run animation thread
return Ok(());
}
if !lock.config.builtin_anims_enabled && !lock.cache.boot.is_empty() {
lock.node
.write_bytes(&pkt_set_enable_powersave_anim(false))
.ok();
let action = lock.cache.boot.clone();
CtrlAnime::run_thread(self.0.clone(), action, true).await;
}
let action = lock.cache.boot.clone();
CtrlAnime::run_thread(self.0.clone(), action, true).await;
}
Ok(())
}

View File

@@ -1,166 +1,60 @@
use std::collections::{BTreeMap, HashSet};
use std::collections::BTreeMap;
use config_traits::{StdConfig, StdConfigLoad};
use log::warn;
use rog_aura::aura_detection::{LaptopLedData, ASUS_KEYBOARD_DEVICES};
use rog_aura::power::AuraPower;
use rog_aura::usb::{AuraDevRog1, AuraDevTuf, AuraDevice, AuraPowerDev};
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Direction, LedBrightness, Speed, GRADIENT};
use rog_platform::hid_raw::HidRaw;
use log::{debug, info, warn};
use rog_aura::aura_detection::LedSupportData;
use rog_aura::keyboard::LaptopAuraPower;
use rog_aura::{
AuraDeviceType, AuraEffect, AuraModeNum, AuraZone, Direction, LedBrightness, Speed, GRADIENT,
};
use serde_derive::{Deserialize, Serialize};
const CONFIG_FILE: &str = "aura.ron";
/// Enable/disable LED control in various states such as
/// when the device is awake, suspended, shutting down or
/// booting.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuraPowerConfig {
AuraDevTuf(HashSet<AuraDevTuf>),
AuraDevRog1(HashSet<AuraDevRog1>),
AuraDevRog2(AuraPower),
}
impl AuraPowerConfig {
/// Invalid for TUF laptops
pub fn to_bytes(control: &Self) -> [u8; 4] {
match control {
AuraPowerConfig::AuraDevTuf(_) => [0, 0, 0, 0],
AuraPowerConfig::AuraDevRog1(c) => {
let c: Vec<AuraDevRog1> = c.iter().copied().collect();
AuraDevRog1::to_bytes(&c)
}
AuraPowerConfig::AuraDevRog2(c) => c.to_bytes(),
}
}
pub fn to_tuf_bool_array(control: &Self) -> Option<[bool; 5]> {
if let Self::AuraDevTuf(c) = control {
return Some([
true,
c.contains(&AuraDevTuf::Boot),
c.contains(&AuraDevTuf::Awake),
c.contains(&AuraDevTuf::Sleep),
c.contains(&AuraDevTuf::Keyboard),
]);
}
if let Self::AuraDevRog1(c) = control {
return Some([
true,
c.contains(&AuraDevRog1::Boot),
c.contains(&AuraDevRog1::Awake),
c.contains(&AuraDevRog1::Sleep),
c.contains(&AuraDevRog1::Keyboard),
]);
}
None
}
pub fn set_tuf(&mut self, power: AuraDevTuf, on: bool) {
if let Self::AuraDevTuf(p) = self {
if on {
p.insert(power);
} else {
p.remove(&power);
}
}
}
pub fn set_0x1866(&mut self, power: AuraDevRog1, on: bool) {
if let Self::AuraDevRog1(p) = self {
if on {
p.insert(power);
} else {
p.remove(&power);
}
}
}
pub fn set_0x19b6(&mut self, power: AuraPower) {
if let Self::AuraDevRog2(p) = self {
*p = power;
}
}
}
impl From<&AuraPowerConfig> for AuraPowerDev {
fn from(config: &AuraPowerConfig) -> Self {
match config {
AuraPowerConfig::AuraDevTuf(d) => AuraPowerDev {
tuf: d.iter().copied().collect(),
..Default::default()
},
AuraPowerConfig::AuraDevRog1(d) => AuraPowerDev {
old_rog: d.iter().copied().collect(),
..Default::default()
},
AuraPowerConfig::AuraDevRog2(d) => AuraPowerDev {
rog: d.clone(),
..Default::default()
},
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone)]
#[derive(Deserialize, Serialize, Default, Debug, Clone)]
// #[serde(default)]
pub struct AuraConfig {
pub config_name: String,
pub brightness: LedBrightness,
pub current_mode: AuraModeNum,
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub multizone: Option<BTreeMap<AuraModeNum, Vec<AuraEffect>>>,
pub multizone_on: bool,
pub enabled: AuraPowerConfig,
pub enabled: LaptopAuraPower,
}
impl StdConfig for AuraConfig {
/// Detect the keyboard type and load from default DB if data available
fn new() -> Self {
warn!("AuraConfig: creating new config");
let mut prod_id = AuraDevice::Unknown;
for prod in ASUS_KEYBOARD_DEVICES {
if HidRaw::new(prod.into()).is_ok() {
prod_id = prod;
break;
}
panic!("This should not be used");
}
fn file_name(&self) -> String {
if self.config_name.is_empty() {
panic!("Config file name should not be empty");
}
Self::create_default(prod_id, &LaptopLedData::get_data())
self.config_name.to_owned()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
fn file_name(&self) -> String {
CONFIG_FILE.to_owned()
}
}
impl StdConfigLoad for AuraConfig {}
impl AuraConfig {
pub fn create_default(prod_id: AuraDevice, support_data: &LaptopLedData) -> Self {
/// Detect the keyboard type and load from default DB if data available
pub fn new(prod_id: &str) -> Self {
info!("Setting up AuraConfig for {prod_id:?}");
// create a default config here
let enabled = if prod_id == AuraDevice::X19b6 {
AuraPowerConfig::AuraDevRog2(AuraPower::new_all_on())
} else if prod_id == AuraDevice::Tuf {
AuraPowerConfig::AuraDevTuf(HashSet::from([
AuraDevTuf::Awake,
AuraDevTuf::Boot,
AuraDevTuf::Sleep,
AuraDevTuf::Keyboard,
]))
} else {
AuraPowerConfig::AuraDevRog1(HashSet::from([
AuraDevRog1::Awake,
AuraDevRog1::Boot,
AuraDevRog1::Sleep,
AuraDevRog1::Keyboard,
AuraDevRog1::Lightbar,
]))
};
let device_type = AuraDeviceType::from(prod_id);
if device_type == AuraDeviceType::Unknown {
warn!("idProduct:{prod_id:?} is unknown");
}
let support_data = LedSupportData::get_data(prod_id);
let enabled = LaptopAuraPower::new(device_type, &support_data);
let mut config = AuraConfig {
config_name: format!("aura_{prod_id}.ron"),
brightness: LedBrightness::Med,
current_mode: AuraModeNum::Static,
builtins: BTreeMap::new(),
@@ -170,6 +64,7 @@ impl AuraConfig {
};
for n in &support_data.basic_modes {
debug!("creating default for {n}");
config
.builtins
.insert(*n, AuraEffect::default_with_mode(*n));
@@ -239,15 +134,13 @@ impl AuraConfig {
#[cfg(test)]
mod tests {
use rog_aura::aura_detection::LaptopLedData;
use rog_aura::usb::AuraDevice;
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Colour};
use super::AuraConfig;
#[test]
fn set_multizone_4key_config() {
let mut config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
let mut config = AuraConfig::new("19b6");
let effect = AuraEffect {
colour1: Colour {
@@ -337,7 +230,7 @@ mod tests {
#[test]
fn set_multizone_multimode_config() {
let mut config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
let mut config = AuraConfig::new("19b6");
let effect = AuraEffect {
zone: AuraZone::Key1,

View File

@@ -1,126 +1,241 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use config_traits::{StdConfig, StdConfigLoad};
use log::{info, warn};
use rog_aura::advanced::{LedUsbPackets, UsbPackets};
use rog_aura::aura_detection::{LaptopLedData, ASUS_KEYBOARD_DEVICES};
use rog_aura::usb::{AuraDevice, LED_APPLY, LED_SET};
use rog_aura::{AuraEffect, AuraZone, Direction, LedBrightness, Speed, GRADIENT, LED_MSG_LEN};
use dmi_id::DMIID;
use inotify::Inotify;
use log::{debug, info, warn};
use rog_aura::aura_detection::LedSupportData;
use rog_aura::keyboard::{LedUsbPackets, UsbPackets};
use rog_aura::usb::{LED_APPLY, LED_SET};
use rog_aura::{
AuraDeviceType, AuraEffect, Direction, LedBrightness, Speed, GRADIENT, LED_MSG_LEN,
};
use rog_platform::hid_raw::HidRaw;
use rog_platform::keyboard_led::KeyboardLed;
use rog_platform::supported::LedSupportedFunctions;
use rog_platform::keyboard_led::KeyboardBacklight;
use zbus::zvariant::OwnedObjectPath;
use super::config::{AuraConfig, AuraPowerConfig};
use super::config::AuraConfig;
use crate::ctrl_aura::manager::{dbus_path_for_dev, dbus_path_for_tuf};
use crate::error::RogError;
use crate::GetSupported;
impl GetSupported for CtrlKbdLed {
type A = LedSupportedFunctions;
#[derive(Debug)]
pub enum LEDNode {
/// Brightness and/or TUF RGB controls
KbdLed(KeyboardBacklight),
/// Raw HID handle
Rog(Option<KeyboardBacklight>, HidRaw),
}
fn get_supported() -> Self::A {
// let mode = <&str>::from(&<AuraModes>::from(*mode));
let laptop = LaptopLedData::get_data();
let mut prod_id = AuraDevice::Unknown;
for prod in ASUS_KEYBOARD_DEVICES {
if HidRaw::new(prod.into()).is_ok() {
prod_id = prod;
break;
impl LEDNode {
// TODO: move various methods upwards to this
pub fn set_brightness(&self, value: u8) -> Result<(), RogError> {
match self {
LEDNode::KbdLed(k) => k.set_brightness(value)?,
LEDNode::Rog(k, _) => {
if let Some(k) = k {
k.set_brightness(value)?
} else {
debug!("No brightness control found");
}
}
}
Ok(())
}
let rgb = KeyboardLed::new();
if let Ok(p) = rgb.as_ref() {
if p.has_kbd_rgb_mode() {
prod_id = AuraDevice::Tuf;
pub fn get_brightness(&self) -> Result<u8, RogError> {
Ok(match self {
LEDNode::KbdLed(k) => k.get_brightness()?,
LEDNode::Rog(k, _) => {
if let Some(k) = k {
k.get_brightness()?
} else {
debug!("No brightness control found");
return Err(RogError::MissingFunction(
"No keyboard brightness control found".to_string(),
));
}
}
}
})
}
LedSupportedFunctions {
dev_id: prod_id,
brightness: rgb.is_ok(),
basic_modes: laptop.basic_modes,
basic_zones: laptop.basic_zones,
advanced_type: laptop.advanced_type.into(),
power_zones: laptop.power_zones,
pub fn monitor_brightness(&self) -> Result<Inotify, RogError> {
Ok(match self {
LEDNode::KbdLed(k) => k.monitor_brightness()?,
LEDNode::Rog(k, _) => {
if let Some(k) = k {
k.monitor_brightness()?
} else {
debug!("No brightness control found");
return Err(RogError::MissingFunction(
"No keyboard brightness control found".to_string(),
));
}
}
})
}
pub fn has_brightness_control(&self) -> bool {
match self {
LEDNode::KbdLed(k) => k.has_brightness(),
LEDNode::Rog(k, _) => {
if let Some(k) = k {
k.has_brightness()
} else {
false
}
}
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum LEDNode {
KbdLed(KeyboardLed),
Rog(HidRaw),
None,
}
/// Individual controller for one Aura device
pub struct CtrlKbdLed {
// TODO: config stores the keyboard type as an AuraPower, use or update this
pub led_prod: AuraDevice,
pub led_type: AuraDeviceType,
pub led_node: LEDNode,
pub kd_brightness: KeyboardLed,
pub supported_modes: LaptopLedData,
pub flip_effect_write: bool,
pub supported_data: LedSupportData, // TODO: is storing this really required?
pub per_key_mode_active: bool,
pub config: AuraConfig,
pub dbus_path: OwnedObjectPath,
}
impl CtrlKbdLed {
pub fn new(supported_modes: LaptopLedData) -> Result<Self, RogError> {
let mut led_prod = AuraDevice::Unknown;
let mut usb_node = None;
for prod in ASUS_KEYBOARD_DEVICES {
match HidRaw::new(prod.into()) {
Ok(node) => {
led_prod = prod;
usb_node = Some(node);
info!(
"Looked for keyboard controller 0x{}: Found",
<&str>::from(prod)
);
break;
pub fn find_all() -> Result<Vec<Self>, RogError> {
info!("Searching for all Aura devices");
let mut devices = Vec::new();
let mut found = HashSet::new(); // track and ensure we use only one hidraw per prod_id
let mut enumerator = udev::Enumerator::new().map_err(|err| {
warn!("{}", err);
err
})?;
enumerator.match_subsystem("hidraw").map_err(|err| {
warn!("{}", err);
err
})?;
for end_point in enumerator.scan_devices()? {
// usb_device gives us a product and vendor ID
if let Some(usb_device) =
end_point.parent_with_subsystem_devtype("usb", "usb_device")?
{
// The asus_wmi driver latches MCU that controls the USB endpoints
if let Some(parent) = end_point.parent() {
if let Some(driver) = parent.driver() {
// There is a tree of devices added so filter by driver
if driver != "asus" {
continue;
}
} else {
continue;
}
}
Err(err) => info!(
"Looked for keyboard controller 0x{}: {err}",
<&str>::from(prod)
),
// Device is something like 002, while its parent is the MCU
// Think of it like the device is an endpoint of the USB device attached
let mut prod_id = String::new();
if let Some(usb_id) = usb_device.attribute_value("idProduct") {
prod_id = usb_id.to_string_lossy().to_string();
let aura_dev = AuraDeviceType::from(prod_id.as_str());
if aura_dev == AuraDeviceType::Unknown || found.contains(&aura_dev) {
log::debug!("Unknown or invalid device: {usb_id:?}, skipping");
continue;
}
found.insert(aura_dev);
}
let dev_node = if let Some(dev_node) = usb_device.devnode() {
dev_node
} else {
debug!("Device has no devnode, skipping");
continue;
};
info!("AuraControl found device at: {:?}", dev_node);
let dbus_path = dbus_path_for_dev(&usb_device).unwrap_or_default();
let dev = HidRaw::from_device(end_point)?;
let mut dev = Self::from_hidraw(dev, dbus_path)?;
dev.config = Self::init_config(&prod_id);
devices.push(dev);
}
}
let rgb_led = KeyboardLed::new()?;
// Check for a TUF laptop LED. Assume there is only ever one.
if let Ok(kbd_backlight) = KeyboardBacklight::new() {
if kbd_backlight.has_kbd_rgb_mode() {
// Extra sure double-check that this isn't a laptop with crap
// ACPI with borked return on the TUF rgb methods
let dmi = DMIID::new().unwrap_or_default();
info!("Found a TUF with product family: {}", dmi.product_family);
info!("and board name: {}", dmi.board_name);
if usb_node.is_none() && !rgb_led.has_kbd_rgb_mode() {
let dmi = sysfs_class::DmiId::default();
if let Ok(prod_family) = dmi.product_family() {
if prod_family.contains("TUF") {
warn!(
"kbd_rgb_mode was not found in the /sys/. You require a minimum 6.1 \
kernel and a supported TUF laptop"
);
if dmi.product_family.contains("TUF") {
info!("AuraControl found a TUF laptop keyboard");
let ctrl = CtrlKbdLed {
led_type: AuraDeviceType::LaptopTuf,
led_node: LEDNode::KbdLed(kbd_backlight),
supported_data: LedSupportData::get_data("tuf"),
per_key_mode_active: false,
config: Self::init_config("tuf"),
dbus_path: dbus_path_for_tuf(),
};
devices.push(ctrl);
}
}
return Err(RogError::NoAuraKeyboard);
}
let led_node = if let Some(rog) = usb_node {
info!("Found ROG USB keyboard");
LEDNode::Rog(rog)
} else if rgb_led.has_kbd_rgb_mode() {
info!("Found TUF keyboard");
LEDNode::KbdLed(rgb_led.clone())
} else {
LEDNode::None
let dmi = DMIID::new().unwrap_or_default();
warn!("No asus::kbd_backlight found for {} ??", dmi.product_family);
}
info!("Found {} Aura devices", devices.len());
Ok(devices)
}
/// The generated data from this function has a default config. This config
/// should be overwritten. The reason for the default config is because
/// of async issues between this and udev/hidraw
pub fn from_hidraw(device: HidRaw, dbus_path: OwnedObjectPath) -> Result<Self, RogError> {
let rgb_led = KeyboardBacklight::new()
.map_err(|e| {
log::error!(
"{} is missing a keyboard backlight brightness control: {e:?}",
device.prod_id()
);
})
.ok();
let prod_id = AuraDeviceType::from(device.prod_id());
if prod_id == AuraDeviceType::Unknown {
log::error!("{} is AuraDevice::Unknown", device.prod_id());
return Err(RogError::NoAuraNode);
}
// New loads data from the DB also
// let config = Self::init_config(prod_id, data);
let data = LedSupportData::get_data(device.prod_id());
let ctrl = CtrlKbdLed {
led_type: prod_id,
led_node: LEDNode::Rog(rgb_led, device),
supported_data: data.clone(),
per_key_mode_active: false,
config: AuraConfig::default(),
dbus_path,
};
Ok(ctrl)
}
let mut config_init = AuraConfig::create_default(led_prod, &supported_modes);
pub fn init_config(prod_id: &str) -> AuraConfig {
// New loads data from the DB also
let mut config_init = AuraConfig::new(prod_id);
// config_init.set_filename(prod_id);
let mut config_loaded = config_init.clone().load();
// update the initialised data with what we loaded from disk
for mode in &mut config_init.builtins {
// update init values from loaded values if they exist
if let Some(loaded) = config_loaded.builtins.get(mode.0) {
*mode.1 = loaded.clone();
}
}
// Then replace just incase the initialised data contains new modes added
config_loaded.builtins = config_init.builtins;
if let (Some(mut multizone_init), Some(multizone_loaded)) =
@@ -130,9 +245,10 @@ impl CtrlKbdLed {
// update init values from loaded values if they exist
if let Some(loaded) = multizone_loaded.get(mode.0) {
let mut new_set = Vec::new();
let data = LedSupportData::get_data(prod_id);
// only reuse a zone mode if the mode is supported
for mode in loaded {
if supported_modes.basic_modes.contains(&mode.mode) {
if data.basic_modes.contains(&mode.mode) {
new_set.push(mode.clone());
}
}
@@ -142,62 +258,21 @@ impl CtrlKbdLed {
*multizone_loaded = multizone_init;
}
let ctrl = CtrlKbdLed {
led_prod,
led_node, // on TUF this is the same as rgb_led / kd_brightness
kd_brightness: rgb_led, // If was none then we already returned above
supported_modes,
flip_effect_write: false,
per_key_mode_active: false,
config: config_loaded,
};
Ok(ctrl)
}
pub(super) fn get_brightness(&self) -> Result<u8, RogError> {
self.kd_brightness
.get_brightness()
.map_err(RogError::Platform)
}
pub(super) fn set_brightness(&self, brightness: LedBrightness) -> Result<(), RogError> {
self.kd_brightness
.set_brightness(brightness as u8)
.map_err(RogError::Platform)
}
pub fn next_brightness(&mut self) -> Result<(), RogError> {
let mut bright = (self.config.brightness as u32) + 1;
if bright > 3 {
bright = 0;
}
self.config.brightness = <LedBrightness>::from(bright);
self.config.write();
self.set_brightness(self.config.brightness)
}
pub fn prev_brightness(&mut self) -> Result<(), RogError> {
let mut bright = self.config.brightness as u32;
if bright == 0 {
bright = 3;
} else {
bright -= 1;
}
self.config.brightness = <LedBrightness>::from(bright);
self.config.write();
self.set_brightness(self.config.brightness)
config_loaded
}
/// Set combination state for boot animation/sleep animation/all leds/keys
/// leds/side leds LED active
pub(super) fn set_power_states(&mut self) -> Result<(), RogError> {
if let LEDNode::KbdLed(platform) = &mut self.led_node {
if let Some(pwr) = AuraPowerConfig::to_tuf_bool_array(&self.config.enabled) {
let buf = [1, pwr[1] as u8, pwr[2] as u8, pwr[3] as u8, pwr[4] as u8];
platform.set_kbd_rgb_state(&buf)?;
}
} else if let LEDNode::Rog(hid_raw) = &self.led_node {
let bytes = AuraPowerConfig::to_bytes(&self.config.enabled);
if let LEDNode::KbdLed(_platform) = &mut self.led_node {
// TODO: tuf bool array
// if let Some(pwr) =
// AuraPowerConfig::to_tuf_bool_array(&self.config.enabled) {
// let buf = [1, pwr[1] as u8, pwr[2] as u8, pwr[3] as u8,
// pwr[4] as u8]; platform.set_kbd_rgb_state(&buf)?;
// }
} else if let LEDNode::Rog(_, hid_raw) = &self.led_node {
let bytes = self.config.enabled.to_bytes(self.led_type);
let message = [0x5d, 0xbd, 0x01, bytes[0], bytes[1], bytes[2], bytes[3]];
hid_raw.write_bytes(&message)?;
@@ -208,29 +283,6 @@ impl CtrlKbdLed {
Ok(())
}
/// Set an Aura effect if the effect mode or zone is supported.
///
/// On success the aura config file is read to refresh cached values, then
/// the effect is stored and config written to disk.
pub(crate) fn set_effect(&mut self, effect: AuraEffect) -> Result<(), RogError> {
if !self.supported_modes.basic_modes.contains(&effect.mode)
|| effect.zone != AuraZone::None
&& !self.supported_modes.basic_zones.contains(&effect.zone)
{
return Err(RogError::AuraEffectNotSupported);
}
self.write_mode(&effect)?;
self.config.read(); // refresh config if successful
self.config.set_builtin(effect);
if self.config.brightness == LedBrightness::Off {
self.config.brightness = LedBrightness::Med;
}
self.config.write();
self.set_brightness(self.config.brightness)?;
Ok(())
}
/// Write an effect block. This is for per-key, but can be repurposed to
/// write the raw factory mode packets - when doing this it is expected that
/// only the first `Vec` (`effect[0]`) is valid.
@@ -245,20 +297,20 @@ impl CtrlKbdLed {
if pkt_type != PER_KEY_TYPE {
self.per_key_mode_active = false;
if let LEDNode::Rog(hid_raw) = &self.led_node {
if let LEDNode::Rog(_, hid_raw) = &self.led_node {
hid_raw.write_bytes(&effect[0])?;
hid_raw.write_bytes(&LED_SET)?;
// hid_raw.write_bytes(&LED_APPLY)?;
}
} else {
if !self.per_key_mode_active {
if let LEDNode::Rog(hid_raw) = &self.led_node {
if let LEDNode::Rog(_, hid_raw) = &self.led_node {
let init = LedUsbPackets::get_init_msg();
hid_raw.write_bytes(&init)?;
}
self.per_key_mode_active = true;
}
if let LEDNode::Rog(hid_raw) = &self.led_node {
if let LEDNode::Rog(_, hid_raw) = &self.led_node {
for row in effect.iter() {
hid_raw.write_bytes(row)?;
}
@@ -270,47 +322,11 @@ impl CtrlKbdLed {
tuf.set_kbd_rgb_mode(&[0, 0, r, g, b, 0])?;
}
}
self.flip_effect_write = !self.flip_effect_write;
}
Ok(())
}
pub(super) fn toggle_mode(&mut self, reverse: bool) -> Result<(), RogError> {
let current = self.config.current_mode;
if let Some(idx) = self
.supported_modes
.basic_modes
.iter()
.position(|v| *v == current)
{
let mut idx = idx;
// goes past end of array
if reverse {
if idx == 0 {
idx = self.supported_modes.basic_modes.len() - 1;
} else {
idx -= 1;
}
} else {
idx += 1;
if idx == self.supported_modes.basic_modes.len() {
idx = 0;
}
}
let next = self.supported_modes.basic_modes[idx];
self.config.read();
// if self.config.builtins.contains_key(&next) {
self.config.current_mode = next;
self.write_current_config_mode()?;
// }
self.config.write();
}
Ok(())
}
fn write_mode(&mut self, mode: &AuraEffect) -> Result<(), RogError> {
pub fn write_mode(&mut self, mode: &AuraEffect) -> Result<(), RogError> {
if let LEDNode::KbdLed(platform) = &self.led_node {
let buf = [
1,
@@ -321,7 +337,7 @@ impl CtrlKbdLed {
mode.speed as u8,
];
platform.set_kbd_rgb_mode(&buf)?;
} else if let LEDNode::Rog(hid_raw) = &self.led_node {
} else if let LEDNode::Rog(_, hid_raw) = &self.led_node {
let bytes: [u8; LED_MSG_LEN] = mode.into();
hid_raw.write_bytes(&bytes)?;
hid_raw.write_bytes(&LED_SET)?;
@@ -374,7 +390,7 @@ impl CtrlKbdLed {
/// exists.
fn create_multizone_default(&mut self) -> Result<(), RogError> {
let mut default = vec![];
for (i, tmp) in self.supported_modes.basic_zones.iter().enumerate() {
for (i, tmp) in self.supported_data.basic_zones.iter().enumerate() {
default.push(AuraEffect {
mode: self.config.current_mode,
zone: *tmp,
@@ -401,112 +417,48 @@ impl CtrlKbdLed {
#[cfg(test)]
mod tests {
use rog_aura::aura_detection::{LaptopLedData, PowerZones};
use rog_aura::usb::AuraDevice;
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Colour};
use rog_platform::keyboard_led::KeyboardLed;
use rog_aura::aura_detection::LedSupportData;
use rog_aura::{AuraDeviceType, AuraModeNum, AuraZone, PowerZones};
use rog_platform::hid_raw::HidRaw;
use rog_platform::keyboard_led::KeyboardBacklight;
use zbus::zvariant::OwnedObjectPath;
use super::CtrlKbdLed;
use crate::ctrl_aura::config::AuraConfig;
use crate::ctrl_aura::controller::LEDNode;
#[test]
// #[ignore = "Must be manually run due to detection stage"]
fn check_set_mode_errors() {
// Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
let supported_modes = LaptopLedData {
board_name: String::new(),
layout_name: "ga401".to_owned(),
basic_modes: vec![AuraModeNum::Static],
basic_zones: vec![],
advanced_type: rog_aura::AdvancedAuraType::None,
power_zones: vec![PowerZones::Keyboard, PowerZones::RearGlow],
};
let mut controller = CtrlKbdLed {
led_prod: AuraDevice::X19b6,
led_node: LEDNode::None,
kd_brightness: KeyboardLed::default(),
supported_modes,
flip_effect_write: false,
per_key_mode_active: false,
config,
};
let mut effect = AuraEffect {
colour1: Colour {
r: 0xff,
g: 0x00,
b: 0xff,
},
zone: AuraZone::None,
..Default::default()
};
// This error comes from write_bytes because we don't have a keyboard node
// stored
assert_eq!(
controller
.set_effect(effect.clone())
.unwrap_err()
.to_string(),
"No supported Aura keyboard"
);
effect.mode = AuraModeNum::Laser;
assert_eq!(
controller
.set_effect(effect.clone())
.unwrap_err()
.to_string(),
"Aura effect not supported"
);
effect.mode = AuraModeNum::Static;
effect.zone = AuraZone::Key2;
assert_eq!(
controller
.set_effect(effect.clone())
.unwrap_err()
.to_string(),
"Aura effect not supported"
);
controller.supported_modes.basic_zones.push(AuraZone::Key2);
assert_eq!(
controller.set_effect(effect).unwrap_err().to_string(),
"No supported Aura keyboard"
);
}
#[test]
#[ignore = "Unable to run in CI as the HIDRAW device is required"]
fn create_multizone_if_no_config() {
// Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
let supported_modes = LaptopLedData {
board_name: String::new(),
let config = AuraConfig::new("19b6");
let supported_basic_modes = LedSupportData {
device_name: String::new(),
product_id: String::new(),
layout_name: "ga401".to_owned(),
basic_modes: vec![AuraModeNum::Static],
basic_zones: vec![],
advanced_type: rog_aura::AdvancedAuraType::None,
advanced_type: rog_aura::keyboard::AdvancedAuraType::None,
power_zones: vec![PowerZones::Keyboard, PowerZones::RearGlow],
};
let mut controller = CtrlKbdLed {
led_prod: AuraDevice::X19b6,
led_node: LEDNode::None,
kd_brightness: KeyboardLed::default(),
supported_modes,
flip_effect_write: false,
led_type: AuraDeviceType::LaptopPost2021,
led_node: LEDNode::Rog(
Some(KeyboardBacklight::default()),
HidRaw::new("19b6").unwrap(),
),
supported_data: supported_basic_modes,
per_key_mode_active: false,
config,
dbus_path: OwnedObjectPath::default(),
};
assert!(controller.config.multizone.is_none());
assert!(controller.create_multizone_default().is_err());
assert!(controller.config.multizone.is_none());
controller.supported_modes.basic_zones.push(AuraZone::Key1);
controller.supported_modes.basic_zones.push(AuraZone::Key2);
controller.supported_data.basic_zones.push(AuraZone::Key1);
controller.supported_data.basic_zones.push(AuraZone::Key2);
assert!(controller.create_multizone_default().is_ok());
assert!(controller.config.multizone.is_some());
@@ -519,25 +471,30 @@ mod tests {
}
#[test]
#[ignore = "Unable to run in CI as the HIDRAW device is required"]
// TODO: use sim device
fn next_mode_create_multizone_if_no_config() {
// Checking to ensure set_mode errors when unsupported modes are tried
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
let supported_modes = LaptopLedData {
board_name: String::new(),
let config = AuraConfig::new("19b6");
let supported_basic_modes = LedSupportData {
device_name: String::new(),
product_id: String::new(),
layout_name: "ga401".to_owned(),
basic_modes: vec![AuraModeNum::Static],
basic_zones: vec![AuraZone::Key1, AuraZone::Key2],
advanced_type: rog_aura::AdvancedAuraType::None,
advanced_type: rog_aura::keyboard::AdvancedAuraType::None,
power_zones: vec![PowerZones::Keyboard, PowerZones::RearGlow],
};
let mut controller = CtrlKbdLed {
led_prod: AuraDevice::X19b6,
led_node: LEDNode::None,
kd_brightness: KeyboardLed::default(),
supported_modes,
flip_effect_write: false,
led_type: AuraDeviceType::LaptopPost2021,
led_node: LEDNode::Rog(
Some(KeyboardBacklight::default()),
HidRaw::new("19b6").unwrap(),
),
supported_data: supported_basic_modes,
per_key_mode_active: false,
config,
dbus_path: OwnedObjectPath::default(),
};
assert!(controller.config.multizone.is_none());

View File

@@ -0,0 +1,187 @@
// Plan:
// - Manager has udev monitor on USB looking for ROG devices
// - If a device is found, add it to watch
// - Add it to Zbus server
// - If udev sees device removed then remove the zbus path
use std::collections::HashSet;
use log::{debug, error, info, warn};
use mio::{Events, Interest, Poll, Token};
use rog_aura::AuraDeviceType;
use rog_platform::hid_raw::HidRaw;
use tokio::task::spawn_blocking;
use udev::{Device, MonitorBuilder};
use zbus::object_server::SignalContext;
use zbus::zvariant::{ObjectPath, OwnedObjectPath};
use zbus::Connection;
use crate::ctrl_aura::controller::CtrlKbdLed;
use crate::ctrl_aura::trait_impls::{CtrlAuraZbus, AURA_ZBUS_PATH};
use crate::error::RogError;
use crate::{CtrlTask, Reloadable};
pub struct AuraManager {
_connection: Connection,
}
impl AuraManager {
pub async fn new(connection: Connection) -> Result<Self, RogError> {
let conn_copy = connection.clone();
let mut interfaces = HashSet::new();
// Do the initial keyboard detection:
let all = CtrlKbdLed::find_all()?;
for ctrl in all {
let path = ctrl.dbus_path.clone();
interfaces.insert(path.clone()); // ensure we record the initial stuff
let sig_ctx = CtrlAuraZbus::signal_context(&connection)?;
let sig_ctx2 = sig_ctx.clone();
let zbus = CtrlAuraZbus::new(ctrl, sig_ctx);
start_tasks(zbus, connection.clone(), sig_ctx2, path).await?;
}
let manager = Self {
_connection: connection,
};
// detect all plugged in aura devices (eventually)
// only USB devices are detected for here
spawn_blocking(move || {
let mut monitor = MonitorBuilder::new()?.match_subsystem("hidraw")?.listen()?;
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(1024);
poll.registry()
.register(&mut monitor, Token(0), Interest::READABLE)?;
loop {
if poll.poll(&mut events, None).is_err() {
continue;
}
for event in monitor.iter() {
let parent = if let Some(parent) =
event.parent_with_subsystem_devtype("usb", "usb_device")?
{
parent
} else {
continue;
};
let action = if let Some(action) = event.action() {
action
} else {
continue;
};
let id_product = if let Some(id_product) = parent.attribute_value("idProduct") {
id_product.to_string_lossy()
} else {
continue;
};
let path = if let Some(path) = dbus_path_for_dev(&parent) {
path
} else {
continue;
};
let aura_device = AuraDeviceType::from(&*id_product);
if aura_device == AuraDeviceType::Unknown {
warn!("idProduct:{id_product:?} is unknown, not using");
continue;
}
if action == "remove" {
if interfaces.remove(&path) {
info!("AuraManager removing: {path:?}");
let conn_copy = conn_copy.clone();
tokio::spawn(async move {
let res = conn_copy
.object_server()
.remove::<CtrlAuraZbus, _>(&path)
.await
.map_err(|e| {
error!("Failed to remove {path:?}, {e:?}");
e
})?;
info!("AuraManager removed: {path:?}, {res}");
Ok::<(), RogError>(())
});
}
} else if action == "add" {
if interfaces.contains(&path) {
debug!("Already a ctrl at {path:?}");
continue;
}
// Need to check the driver is asus to prevent using hid_generic
if let Some(p2) = event.parent() {
if let Some(driver) = p2.driver() {
// There is a tree of devices added so filter by driver
if driver != "asus" {
debug!("{id_product:?} driver was not asus, skipping");
continue;
}
} else {
continue;
}
}
if let Some(dev_node) = event.devnode() {
if let Ok(raw) = HidRaw::from_device(event.device())
.map_err(|e| error!("device path error: {e:?}"))
{
if let Ok(mut ctrl) = CtrlKbdLed::from_hidraw(raw, path.clone()) {
ctrl.config = CtrlKbdLed::init_config(&id_product);
interfaces.insert(path.clone());
info!("AuraManager starting device at: {dev_node:?}, {path:?}");
let sig_ctx = CtrlAuraZbus::signal_context(&conn_copy)?;
let zbus = CtrlAuraZbus::new(ctrl, sig_ctx);
let sig_ctx = CtrlAuraZbus::signal_context(&conn_copy)?;
let conn_copy = conn_copy.clone();
tokio::spawn(async move {
start_tasks(zbus, conn_copy.clone(), sig_ctx, path).await
});
}
}
}
};
}
}
// Required for return type on spawn
#[allow(unreachable_code)]
Ok::<(), RogError>(())
});
Ok(manager)
}
}
pub(crate) fn dbus_path_for_dev(parent: &Device) -> Option<OwnedObjectPath> {
if let Some(filename) = super::filename_partial(parent) {
return Some(
ObjectPath::from_str_unchecked(&format!("{AURA_ZBUS_PATH}/{filename}")).into(),
);
}
None
}
pub(crate) fn dbus_path_for_tuf() -> OwnedObjectPath {
ObjectPath::from_str_unchecked(&format!("{AURA_ZBUS_PATH}/tuf")).into()
}
async fn start_tasks(
mut zbus: CtrlAuraZbus,
connection: Connection,
_signal_ctx: SignalContext<'static>,
path: OwnedObjectPath,
) -> Result<(), RogError> {
// let task = zbus.clone();
// let signal_ctx = signal_ctx.clone();
zbus.reload()
.await
.unwrap_or_else(|err| warn!("Controller error: {}", err));
connection.object_server().at(path, zbus).await.unwrap();
// TODO: skip this until we keep handles to tasks so they can be killed
// task.create_tasks(signal_ctx).await
Ok(())
}

View File

@@ -1,4 +1,29 @@
use udev::Device;
use zbus::zvariant::{ObjectPath, OwnedObjectPath};
pub mod config;
pub mod controller;
pub mod manager;
/// Implements `CtrlTask`, `Reloadable`, `ZbusRun`
pub mod trait_impls;
/// Returns only the Device details concatenated in a form usable for
/// adding/appending to a filename
pub(super) fn filename_partial(parent: &Device) -> Option<OwnedObjectPath> {
if let Some(id_product) = parent.attribute_value("idProduct") {
let id_product = id_product.to_string_lossy();
let path = if let Some(devnum) = parent.attribute_value("devnum") {
let devnum = devnum.to_string_lossy();
if let Some(devpath) = parent.attribute_value("devpath") {
let devpath = devpath.to_string_lossy();
format!("{id_product}_{devnum}_{devpath}")
} else {
format!("{id_product}_{devnum}")
}
} else {
format!("{id_product}")
};
return Some(ObjectPath::from_str_unchecked(&path).into());
}
None
}

View File

@@ -1,308 +1,302 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_aura::advanced::UsbPackets;
use rog_aura::usb::{AuraDevice, AuraPowerDev};
use rog_aura::{AuraEffect, AuraModeNum, LedBrightness};
use log::{debug, error, info, warn};
use rog_aura::keyboard::{LaptopAuraPower, UsbPackets};
use rog_aura::{AuraDeviceType, AuraEffect, AuraModeNum, AuraZone, LedBrightness, PowerZones};
use zbus::export::futures_util::lock::{Mutex, MutexGuard};
use zbus::export::futures_util::StreamExt;
use zbus::{dbus_interface, Connection, SignalContext};
use zbus::fdo::Error as ZbErr;
use zbus::{interface, SignalContext};
use super::controller::CtrlKbdLed;
use crate::error::RogError;
use crate::CtrlTask;
pub(super) const ZBUS_PATH: &str = "/org/asuslinux/Aura";
pub const AURA_ZBUS_NAME: &str = "Aura";
pub const AURA_ZBUS_PATH: &str = "/org/asuslinux";
#[derive(Clone)]
pub struct CtrlKbdLedZbus(pub Arc<Mutex<CtrlKbdLed>>);
pub struct CtrlAuraZbus(Arc<Mutex<CtrlKbdLed>>, SignalContext<'static>);
impl CtrlAuraZbus {
pub fn new(controller: CtrlKbdLed, signal: SignalContext<'static>) -> Self {
Self(Arc::new(Mutex::new(controller)), signal)
}
impl CtrlKbdLedZbus {
fn update_config(lock: &mut CtrlKbdLed) -> Result<(), RogError> {
let bright = lock.kd_brightness.get_brightness()?;
let bright = lock.led_node.get_brightness().unwrap_or_default();
lock.config.read();
lock.config.brightness = (bright as u32).into();
lock.config.brightness = bright.into();
lock.config.write();
Ok(())
}
}
#[async_trait]
impl crate::ZbusRun for CtrlKbdLedZbus {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
}
}
/// The main interface for changing, reading, or notfying signals
/// The main interface for changing, reading, or notfying
///
/// LED commands are split between Brightness, Modes, Per-Key
#[dbus_interface(name = "org.asuslinux.Daemon")]
impl CtrlKbdLedZbus {
/// Set the keyboard brightness level (0-3)
async fn set_brightness(&mut self, brightness: LedBrightness) {
#[interface(name = "org.asuslinux.Aura")]
impl CtrlAuraZbus {
/// Return the device type for this Aura keyboard
#[zbus(property)]
async fn device_type(&self) -> AuraDeviceType {
let ctrl = self.0.lock().await;
ctrl.set_brightness(brightness)
.map_err(|err| warn!("{}", err))
.ok();
ctrl.led_type
}
/// Return the current LED brightness
#[zbus(property)]
async fn brightness(&self) -> Result<LedBrightness, ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.led_node.get_brightness().map(|n| n.into())?)
}
/// Set the keyboard brightness level (0-3)
#[zbus(property)]
async fn set_brightness(&mut self, brightness: LedBrightness) -> Result<(), ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.led_node.set_brightness(brightness.into())?)
}
/// Total levels of brightness available
#[zbus(property)]
async fn supported_brightness(&self) -> Vec<LedBrightness> {
vec![
LedBrightness::Off,
LedBrightness::Low,
LedBrightness::Med,
LedBrightness::High,
]
}
/// The total available modes
#[zbus(property)]
async fn supported_basic_modes(&self) -> Result<Vec<AuraModeNum>, ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.config.builtins.keys().cloned().collect())
}
#[zbus(property)]
async fn supported_basic_zones(&self) -> Result<Vec<AuraZone>, ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.supported_data.basic_zones.clone())
}
#[zbus(property)]
async fn supported_power_zones(&self) -> Result<Vec<PowerZones>, ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.supported_data.power_zones.clone())
}
/// The current mode data
#[zbus(property)]
async fn led_mode(&self) -> Result<AuraModeNum, ZbErr> {
let ctrl = self.0.lock().await;
Ok(ctrl.config.current_mode)
}
/// Set an Aura effect if the effect mode or zone is supported.
///
/// On success the aura config file is read to refresh cached values, then
/// the effect is stored and config written to disk.
#[zbus(property)]
async fn set_led_mode(&mut self, num: AuraModeNum) -> Result<(), ZbErr> {
let mut ctrl = self.0.lock().await;
ctrl.config.current_mode = num;
ctrl.write_current_config_mode()?;
if ctrl.config.brightness == LedBrightness::Off {
ctrl.config.brightness = LedBrightness::Med;
}
if ctrl.led_node.has_brightness_control() {
ctrl.led_node
.set_brightness(ctrl.config.brightness.into())?;
}
ctrl.config.write();
self.led_mode_data_invalidate(&self.1).await.ok();
Ok(())
}
/// The current mode data
#[zbus(property)]
async fn led_mode_data(&self) -> Result<AuraEffect, ZbErr> {
let ctrl = self.0.lock().await;
let mode = ctrl.config.current_mode;
match ctrl.config.builtins.get(&mode) {
Some(effect) => Ok(effect.clone()),
None => Err(ZbErr::Failed("Could not get the current effect".into())),
}
}
/// Set an Aura effect if the effect mode or zone is supported.
///
/// On success the aura config file is read to refresh cached values, then
/// the effect is stored and config written to disk.
#[zbus(property)]
async fn set_led_mode_data(&mut self, effect: AuraEffect) -> Result<(), ZbErr> {
let mut ctrl = self.0.lock().await;
if !ctrl.supported_data.basic_modes.contains(&effect.mode)
|| effect.zone != AuraZone::None
&& !ctrl.supported_data.basic_zones.contains(&effect.zone)
{
return Err(ZbErr::NotSupported(format!(
"The Aura effect is not supported: {effect:?}"
)));
}
ctrl.write_mode(&effect)?;
if ctrl.config.brightness == LedBrightness::Off {
ctrl.config.brightness = LedBrightness::Med;
}
if ctrl.led_node.has_brightness_control() {
ctrl.led_node
.set_brightness(ctrl.config.brightness.into())?;
}
ctrl.config.set_builtin(effect);
ctrl.config.write();
self.led_mode_invalidate(&self.1).await.ok();
Ok(())
}
/// Get the data set for every mode available
async fn all_mode_data(&self) -> BTreeMap<AuraModeNum, AuraEffect> {
let ctrl = self.0.lock().await;
ctrl.config.builtins.clone()
}
// As property doesn't work for AuraPowerDev (complexity of serialization?)
#[zbus(property)]
async fn led_power(&self) -> LaptopAuraPower {
let ctrl = self.0.lock().await;
ctrl.config.enabled.clone()
}
/// Set a variety of states, input is array of enum.
/// `enabled` sets if the sent array should be disabled or enabled
///
/// For Modern ROG devices the "enabled" flag is ignored.
async fn set_led_power(
&mut self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
options: AuraPowerDev,
enabled: bool,
) -> zbus::fdo::Result<()> {
#[zbus(property)]
async fn set_led_power(&mut self, options: LaptopAuraPower) -> Result<(), ZbErr> {
let mut ctrl = self.0.lock().await;
for p in options.tuf {
ctrl.config.enabled.set_tuf(p, enabled);
for opt in options.states {
let zone = opt.zone;
for config in ctrl.config.enabled.states.iter_mut() {
if config.zone == zone {
*config = opt;
}
}
}
for p in options.old_rog {
ctrl.config.enabled.set_0x1866(p, enabled);
}
ctrl.config.enabled.set_0x19b6(options.rog);
ctrl.config.write();
ctrl.set_power_states().map_err(|e| {
Ok(ctrl.set_power_states().map_err(|e| {
warn!("{}", e);
e
})?;
Self::notify_power_states(&ctxt, &AuraPowerDev::from(&ctrl.config.enabled))
.await
.unwrap_or_else(|err| warn!("{}", err));
Ok(())
}
async fn set_led_mode(
&mut self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
effect: AuraEffect,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.set_effect(effect).map_err(|e| {
warn!("{}", e);
e
})?;
ctrl.set_brightness(ctrl.config.brightness).map_err(|e| {
warn!("{}", e);
e
})?;
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
Self::notify_led(&ctxt, mode.clone())
.await
.unwrap_or_else(|err| warn!("{}", err));
}
Ok(())
}
async fn next_led_mode(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.toggle_mode(false).map_err(|e| {
warn!("{}", e);
e
})?;
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
Self::notify_led(&ctxt, mode.clone())
.await
.unwrap_or_else(|err| warn!("{}", err));
}
Ok(())
}
async fn prev_led_mode(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.toggle_mode(true).map_err(|e| {
warn!("{}", e);
e
})?;
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
Self::notify_led(&ctxt, mode.clone())
.await
.unwrap_or_else(|err| warn!("{}", err));
}
Ok(())
}
async fn next_led_brightness(&self) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.next_brightness().map_err(|e| {
warn!("{}", e);
e
})?;
Ok(())
}
async fn prev_led_brightness(&self) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.prev_brightness().map_err(|e| {
warn!("{}", e);
e
})?;
Ok(())
}
/// Return the device type for this Aura keyboard
async fn device_type(&self) -> AuraDevice {
let ctrl = self.0.lock().await;
ctrl.led_prod
}
// As property doesn't work for AuraPowerDev (complexity of serialization?)
// #[dbus_interface(property)]
async fn led_power(&self) -> AuraPowerDev {
let ctrl = self.0.lock().await;
AuraPowerDev::from(&ctrl.config.enabled)
}
/// Return the current mode data
async fn led_mode(&self) -> AuraModeNum {
let ctrl = self.0.lock().await;
ctrl.config.current_mode
}
/// Return a list of available modes
async fn led_modes(&self) -> BTreeMap<AuraModeNum, AuraEffect> {
let ctrl = self.0.lock().await;
ctrl.config.builtins.clone()
})?)
}
/// On machine that have some form of either per-key keyboard or per-zone
/// this can be used to write custom effects over dbus. The input is a
/// nested `Vec<Vec<8>>` where `Vec<u8>` is a raw USB packet
async fn direct_addressing_raw(&self, data: UsbPackets) -> zbus::fdo::Result<()> {
async fn direct_addressing_raw(&self, data: UsbPackets) -> Result<(), ZbErr> {
let mut ctrl = self.0.lock().await;
ctrl.write_effect_block(&data)?;
Ok(())
}
/// Return the current LED brightness
#[dbus_interface(property)]
async fn led_brightness(&self) -> i8 {
let ctrl = self.0.lock().await;
ctrl.get_brightness().map(|n| n as i8).unwrap_or(-1)
}
#[dbus_interface(signal)]
async fn notify_led(signal_ctxt: &SignalContext<'_>, data: AuraEffect) -> zbus::Result<()>;
#[dbus_interface(signal)]
async fn notify_power_states(
signal_ctxt: &SignalContext<'_>,
data: &AuraPowerDev,
) -> zbus::Result<()>;
}
#[async_trait]
impl CtrlTask for CtrlKbdLedZbus {
impl CtrlTask for CtrlAuraZbus {
fn zbus_path() -> &'static str {
ZBUS_PATH
"/org/asuslinux"
}
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
let load_save = |start: bool, mut lock: MutexGuard<'_, CtrlKbdLed>| {
// If waking up
if !start {
info!("CtrlKbdLedTask reloading brightness and modes");
lock.set_brightness(lock.config.brightness)
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
.ok();
lock.write_current_config_mode()
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
.ok();
} else if start {
Self::update_config(&mut lock)
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
.ok();
}
};
let load_save =
|start: bool, mut lock: MutexGuard<'_, CtrlKbdLed>| -> Result<(), RogError> {
// If waking up
if !start {
info!("CtrlKbdLedTask reloading brightness and modes");
if lock.led_node.has_brightness_control() {
lock.led_node
.set_brightness(lock.config.brightness.into())
.map_err(|e| {
error!("CtrlKbdLedTask: {e}");
e
})?;
}
lock.write_current_config_mode().map_err(|e| {
error!("CtrlKbdLedTask: {e}");
e
})?;
} else if start {
Self::update_config(&mut lock).map_err(|e| {
error!("CtrlKbdLedTask: {e}");
e
})?;
}
Ok(())
};
let inner1 = self.0.clone();
let inner2 = self.0.clone();
let inner3 = self.0.clone();
let inner4 = self.0.clone();
self.create_sys_event_tasks(
// Loop so that we do aquire the lock but also don't block other
// threads (prevents potential deadlocks)
move || {
move |sleeping| {
let inner1 = inner1.clone();
async move {
let lock = inner1.lock().await;
load_save(true, lock);
load_save(sleeping, lock).unwrap(); // unwrap as we want to
// bomb out of the task
}
},
move || {
let inner2 = inner2.clone();
async move {
let lock = inner2.lock().await;
load_save(false, lock);
}
},
move || {
move |_shutting_down| {
let inner3 = inner3.clone();
async move {
let lock = inner3.lock().await;
load_save(false, lock);
load_save(false, lock).unwrap(); // unwrap as we want to
// bomb out of the task
}
},
move || {
let inner4 = inner4.clone();
async move {
let lock = inner4.lock().await;
load_save(false, lock);
}
move |_lid_closed| {
// on lid change
async move {}
},
move |_power_plugged| {
// power change
async move {}
},
)
.await;
let ctrl2 = self.0.clone();
let ctrl = self.0.lock().await;
let watch = ctrl.kd_brightness.monitor_brightness()?;
tokio::spawn(async move {
let mut buffer = [0; 32];
watch
.into_event_stream(&mut buffer)
.unwrap()
.for_each(|_| async {
if let Some(lock) = ctrl2.try_lock() {
load_save(true, lock);
}
})
.await;
});
if ctrl.led_node.has_brightness_control() {
let watch = ctrl.led_node.monitor_brightness()?;
tokio::spawn(async move {
let mut buffer = [0; 32];
watch
.into_event_stream(&mut buffer)
.unwrap()
.for_each(|_| async {
if let Some(lock) = ctrl2.try_lock() {
load_save(true, lock).unwrap(); // unwrap as we want to
// bomb out of the task
}
})
.await;
});
}
Ok(())
}
}
#[async_trait]
impl crate::Reloadable for CtrlKbdLedZbus {
impl crate::Reloadable for CtrlAuraZbus {
async fn reload(&mut self) -> Result<(), RogError> {
let mut ctrl = self.0.lock().await;
debug!("reloading keyboard mode");
ctrl.write_current_config_mode()?;
debug!("reloading power states");
ctrl.set_power_states().map_err(|err| warn!("{err}")).ok();
Ok(())
}

286
asusd/src/ctrl_fancurves.rs Normal file
View File

@@ -0,0 +1,286 @@
use std::path::PathBuf;
use std::sync::Arc;
use config_traits::{StdConfig, StdConfigLoad};
use futures_lite::StreamExt;
use log::{debug, error, info, warn};
use rog_platform::platform::{RogPlatform, ThrottlePolicy};
use rog_profiles::error::ProfileError;
use rog_profiles::fan_curve_set::CurveData;
use rog_profiles::{find_fan_curve_node, FanCurvePU, FanCurveProfiles};
use serde_derive::{Deserialize, Serialize};
use tokio::sync::Mutex;
use zbus::{interface, Connection, SignalContext};
use crate::error::RogError;
use crate::{CtrlTask, CONFIG_PATH_BASE};
pub const FAN_CURVE_ZBUS_NAME: &str = "FanCurves";
pub const FAN_CURVE_ZBUS_PATH: &str = "/org/asuslinux";
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct FanCurveConfig {
pub profiles: FanCurveProfiles,
#[serde(skip)]
pub current: u8,
}
impl StdConfig for FanCurveConfig {
/// Create a new config. The defaults are zeroed so the device must be read
/// to get the actual device defaults.
fn new() -> Self {
Self::default()
}
fn file_name(&self) -> String {
"fan_curves.ron".to_owned()
}
fn config_dir() -> std::path::PathBuf {
PathBuf::from(CONFIG_PATH_BASE)
}
}
impl StdConfigLoad for FanCurveConfig {}
#[derive(Debug, Clone)]
pub struct CtrlFanCurveZbus {
config: Arc<Mutex<FanCurveConfig>>,
platform: RogPlatform,
}
// Non-zbus-derive impl
impl CtrlFanCurveZbus {
pub fn new() -> Result<Self, RogError> {
let platform = RogPlatform::new()?;
if platform.has_throttle_thermal_policy() {
info!("Device has profile control available");
find_fan_curve_node()?;
info!("Device has fan curves available");
let mut config = FanCurveConfig::new().load();
let mut fan_curves = FanCurveProfiles::default();
// Only do defaults if the config doesn't already exist\
if config.profiles.balanced.is_empty() || !config.file_path().exists() {
info!("Fetching default fan curves");
let current = platform.get_throttle_thermal_policy()?;
for this in [
ThrottlePolicy::Balanced,
ThrottlePolicy::Performance,
ThrottlePolicy::Quiet,
] {
// For each profile we need to switch to it before we
// can read the existing values from hardware. The ACPI method used
// for this is what limits us.
platform.set_throttle_thermal_policy(this.into())?;
let mut dev = find_fan_curve_node()?;
fan_curves.set_active_curve_to_defaults(this, &mut dev)?;
info!("{this:?}:");
for curve in fan_curves.get_fan_curves_for(this) {
info!("{}", String::from(curve));
}
}
platform.set_throttle_thermal_policy(current)?;
config.profiles = fan_curves;
config.write();
} else {
info!("Fan curves previously stored, loading...");
config = config.load();
}
return Ok(Self {
config: Arc::new(Mutex::new(config)),
platform,
});
}
Err(ProfileError::NotSupported.into())
}
}
#[interface(name = "org.asuslinux.FanCurves")]
impl CtrlFanCurveZbus {
/// Set all fan curves for a profile to enabled status. Will also activate a
/// fan curve if in the same profile mode
async fn set_fan_curves_enabled(
&mut self,
profile: ThrottlePolicy,
enabled: bool,
) -> zbus::fdo::Result<()> {
self.config
.lock()
.await
.profiles
.set_profile_curves_enabled(profile, enabled);
self.config
.lock()
.await
.profiles
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
self.config.lock().await.write();
Ok(())
}
/// Set a single fan curve for a profile to enabled status. Will also
/// activate a fan curve if in the same profile mode
async fn set_profile_fan_curve_enabled(
&mut self,
profile: ThrottlePolicy,
fan: FanCurvePU,
enabled: bool,
) -> zbus::fdo::Result<()> {
self.config
.lock()
.await
.profiles
.set_profile_fan_curve_enabled(profile, fan, enabled);
self.config
.lock()
.await
.profiles
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
self.config.lock().await.write();
Ok(())
}
/// Get the fan-curve data for the currently active ThrottlePolicy
async fn fan_curve_data(
&mut self,
profile: ThrottlePolicy,
) -> zbus::fdo::Result<Vec<CurveData>> {
let curve = self
.config
.lock()
.await
.profiles
.get_fan_curves_for(profile)
.to_vec();
Ok(curve)
}
/// Set the fan curve for the specified profile.
/// Will also activate the fan curve if the user is in the same mode.
async fn set_fan_curve(
&mut self,
profile: ThrottlePolicy,
curve: CurveData,
) -> zbus::fdo::Result<()> {
self.config
.lock()
.await
.profiles
.save_fan_curve(curve, profile)?;
let active: ThrottlePolicy = self.platform.get_throttle_thermal_policy()?.into();
if active == profile {
self.config
.lock()
.await
.profiles
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
}
self.config.lock().await.write();
Ok(())
}
/// Reset the stored (self) and device curves to the defaults of the
/// platform.
///
/// Each platform_profile has a different default and the default can be
/// read only for the currently active profile.
async fn set_curves_to_defaults(&mut self, profile: ThrottlePolicy) -> zbus::fdo::Result<()> {
let active = self.platform.get_throttle_thermal_policy()?;
self.platform.set_throttle_thermal_policy(profile.into())?;
self.config
.lock()
.await
.profiles
.set_active_curve_to_defaults(profile, &mut find_fan_curve_node()?)?;
self.platform.set_throttle_thermal_policy(active)?;
self.config.lock().await.write();
Ok(())
}
/// Reset the stored (self) and device curve to the defaults of the
/// platform.
///
/// Each platform_profile has a different default and the defualt can be
/// read only for the currently active profile.
async fn reset_profile_curves(&self, profile: ThrottlePolicy) -> zbus::fdo::Result<()> {
let active = self.platform.get_throttle_thermal_policy()?;
self.platform.set_throttle_thermal_policy(profile.into())?;
self.config
.lock()
.await
.profiles
.set_active_curve_to_defaults(active.into(), &mut find_fan_curve_node()?)?;
self.platform.set_throttle_thermal_policy(active)?;
self.config.lock().await.write();
Ok(())
}
}
impl crate::ZbusRun for CtrlFanCurveZbus {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, FAN_CURVE_ZBUS_PATH, server).await;
}
}
impl CtrlTask for CtrlFanCurveZbus {
fn zbus_path() -> &'static str {
FAN_CURVE_ZBUS_PATH
}
async fn create_tasks(&self, _signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
let watch_throttle_thermal_policy = self.platform.monitor_throttle_thermal_policy()?;
let platform = self.platform.clone();
let config = self.config.clone();
let fan_curves = self.config.clone();
tokio::spawn(async move {
let mut buffer = [0; 32];
if let Ok(mut stream) = watch_throttle_thermal_policy.into_event_stream(&mut buffer) {
while (stream.next().await).is_some() {
debug!("watch_throttle_thermal_policy changed");
if let Ok(profile) = platform.get_throttle_thermal_policy().map_err(|e| {
error!("get_throttle_thermal_policy error: {e}");
}) {
if profile != config.lock().await.current {
fan_curves
.lock()
.await
.profiles
.write_profile_curve_to_platform(
profile.into(),
&mut find_fan_curve_node().unwrap(),
)
.map_err(|e| warn!("write_profile_curve_to_platform, {}", e))
.ok();
config.lock().await.current = profile;
}
}
}
}
});
Ok(())
}
}
impl crate::Reloadable for CtrlFanCurveZbus {
/// Fetch the active profile and use that to set all related components up
async fn reload(&mut self) -> Result<(), RogError> {
let active = self.platform.get_throttle_thermal_policy()?.into();
let mut config = self.config.lock().await;
if let Ok(mut device) = find_fan_curve_node() {
config
.profiles
.write_profile_curve_to_platform(active, &mut device)?;
}
Ok(())
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,287 +0,0 @@
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_platform::power::AsusPower;
use rog_platform::supported::ChargeSupportedFunctions;
use systemd_zbus::{ManagerProxy as SystemdProxy, Mode, UnitFileState};
use tokio::time::sleep;
use zbus::export::futures_util::lock::Mutex;
use zbus::{dbus_interface, Connection, SignalContext};
use crate::config::Config;
use crate::error::RogError;
use crate::{CtrlTask, GetSupported};
const ZBUS_PATH: &str = "/org/asuslinux/Power";
const NVIDIA_POWERD: &str = "nvidia-powerd.service";
impl GetSupported for CtrlPower {
type A = ChargeSupportedFunctions;
fn get_supported() -> Self::A {
ChargeSupportedFunctions {
charge_level_set: if let Ok(power) = AsusPower::new() {
power.has_charge_control_end_threshold()
} else {
false
},
}
}
}
#[derive(Clone)]
pub struct CtrlPower {
power: AsusPower,
config: Arc<Mutex<Config>>,
}
#[dbus_interface(name = "org.asuslinux.Daemon")]
impl CtrlPower {
async fn set_charge_control_end_threshold(
&mut self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
limit: u8,
) -> zbus::fdo::Result<()> {
if !(20..=100).contains(&limit) {
return Err(RogError::ChargeLimit(limit))?;
}
self.set(limit)
.map_err(|err| {
warn!("CtrlCharge: set_limit {}", err);
err
})
.ok();
Self::notify_charge_control_end_threshold(&ctxt, limit)
.await
.ok();
Ok(())
}
fn charge_control_end_threshold(&self) -> u8 {
loop {
if let Some(mut config) = self.config.try_lock() {
let limit = self
.power
.get_charge_control_end_threshold()
.map_err(|err| {
warn!("CtrlCharge: get_charge_control_end_threshold {}", err);
err
})
.unwrap_or(100);
config.read();
config.bat_charge_limit = limit;
config.write();
return config.bat_charge_limit;
}
}
}
fn mains_online(&self) -> bool {
if self.power.has_online() {
if let Ok(v) = self.power.get_online() {
return v == 1;
}
}
false
}
#[dbus_interface(signal)]
async fn notify_charge_control_end_threshold(
ctxt: &SignalContext<'_>,
limit: u8,
) -> zbus::Result<()>;
#[dbus_interface(signal)]
async fn notify_mains_online(ctxt: &SignalContext<'_>, on: bool) -> zbus::Result<()>;
}
#[async_trait]
impl crate::ZbusRun for CtrlPower {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
}
}
#[async_trait]
impl crate::Reloadable for CtrlPower {
async fn reload(&mut self) -> Result<(), RogError> {
if let Some(mut config) = self.config.try_lock() {
config.read();
self.set(config.bat_charge_limit)?;
}
Ok(())
}
}
impl CtrlPower {
// task_watch_item!(charge_control_end_threshold power);
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
Ok(CtrlPower {
power: AsusPower::new()?,
config,
})
}
pub(super) fn set(&self, limit: u8) -> Result<(), RogError> {
if !(20..=100).contains(&limit) {
return Err(RogError::ChargeLimit(limit));
}
self.power.set_charge_control_end_threshold(limit)?;
info!("Battery charge limit: {}", limit);
if let Some(mut config) = self.config.try_lock() {
config.read();
config.bat_charge_limit = limit;
config.write();
}
Ok(())
}
}
#[async_trait]
impl CtrlTask for CtrlPower {
fn zbus_path() -> &'static str {
ZBUS_PATH
}
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
let conn = zbus::Connection::system().await?;
let sysd1 = SystemdProxy::new(&conn).await?;
let sysd2 = sysd1.clone();
let sysd3 = sysd1.clone();
let power1 = self.clone();
let power2 = self.clone();
self.create_sys_event_tasks(
move || async {},
move || {
let power = power1.clone();
let sysd = sysd1.clone();
async move {
info!("CtrlCharge reloading charge limit");
let lock = power.config.lock().await;
power
.set(lock.bat_charge_limit)
.map_err(|err| {
warn!("CtrlCharge: set_limit {}", err);
err
})
.ok();
if lock.disable_nvidia_powerd_on_battery {
if let Ok(value) = power.power.get_online() {
do_nvidia_powerd_action(&sysd, value == 1).await;
}
}
}
},
move || async {},
move || {
let power = power2.clone();
let sysd = sysd2.clone();
async move {
info!("CtrlCharge reloading charge limit");
let lock = power.config.lock().await;
power
.set(lock.bat_charge_limit)
.map_err(|err| {
warn!("CtrlCharge: set_limit {}", err);
err
})
.ok();
if lock.disable_nvidia_powerd_on_battery {
if let Ok(value) = power.power.get_online() {
do_nvidia_powerd_action(&sysd, value == 1).await;
}
}
}
},
)
.await;
let config = self.config.clone();
// self.watch_charge_control_end_threshold(signal_ctxt.clone())
// .await?;
let ctrl = self.clone();
tokio::spawn(async move {
let mut online = 10;
loop {
if let Ok(value) = ctrl.power.get_online() {
if online != value {
online = value;
let mut config = config.lock().await;
config.read();
if config.disable_nvidia_powerd_on_battery {
do_nvidia_powerd_action(&sysd3, value == 1).await;
}
Self::notify_mains_online(&signal_ctxt, value == 1)
.await
.unwrap();
let mut prog: Vec<&str> = Vec::new();
if value == 1 {
// AC ONLINE
prog = config.ac_command.split_whitespace().collect();
} else if value == 0 {
// BATTERY
prog = config.bat_command.split_whitespace().collect();
}
if prog.len() > 1 {
let mut cmd = Command::new(prog[0]);
for arg in prog.iter().skip(1) {
cmd.arg(*arg);
}
if let Err(e) = cmd.spawn() {
if value == 1 {
error!("AC power command error: {e}");
} else {
error!("Battery power command error: {e}");
}
}
}
}
}
// The inotify doesn't pick up events when the kernel changes internal value
// so we need to watch it with a thread and sleep unfortunately
sleep(Duration::from_secs(1)).await;
}
});
Ok(())
}
}
async fn do_nvidia_powerd_action(proxy: &SystemdProxy<'_>, ac_on: bool) {
if let Ok(res) = proxy.get_unit_file_state(NVIDIA_POWERD).await {
if res == UnitFileState::Enabled {
if ac_on {
proxy
.start_unit(NVIDIA_POWERD, Mode::Replace)
.await
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
.ok();
} else {
proxy
.stop_unit(NVIDIA_POWERD, Mode::Replace)
.await
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
.ok();
}
}
}
}

View File

@@ -1,60 +0,0 @@
use std::path::PathBuf;
use config_traits::{StdConfig, StdConfigLoad};
use rog_profiles::fan_curve_set::CurveData;
use rog_profiles::Profile;
use serde_derive::{Deserialize, Serialize};
use crate::CONFIG_PATH_BASE;
const CONFIG_FILE: &str = "profile.ron";
const CONFIG_FAN_FILE: &str = "fan_curves.ron";
#[derive(Deserialize, Serialize, Debug)]
pub struct ProfileConfig {
/// For restore on boot
pub active_profile: Profile,
}
impl StdConfig for ProfileConfig {
fn new() -> Self {
Self {
active_profile: Profile::Balanced,
}
}
fn config_dir() -> std::path::PathBuf {
PathBuf::from(CONFIG_PATH_BASE)
}
fn file_name(&self) -> String {
CONFIG_FILE.to_owned()
}
}
impl StdConfigLoad for ProfileConfig {}
#[derive(Deserialize, Serialize, Debug, Default)]
pub struct FanCurveConfig {
pub balanced: Vec<CurveData>,
pub performance: Vec<CurveData>,
pub quiet: Vec<CurveData>,
}
impl StdConfig for FanCurveConfig {
/// Create a new config. The defaults are zeroed so the device must be read
/// to get the actual device defaults.
fn new() -> Self {
Self::default()
}
fn config_dir() -> std::path::PathBuf {
PathBuf::from(CONFIG_PATH_BASE)
}
fn file_name(&self) -> String {
CONFIG_FAN_FILE.to_owned()
}
}
impl StdConfigLoad for FanCurveConfig {}

View File

@@ -1,171 +0,0 @@
use config_traits::{StdConfig, StdConfigLoad};
use log::{info, warn};
use rog_platform::platform::AsusPlatform;
use rog_platform::supported::PlatformProfileFunctions;
use rog_profiles::error::ProfileError;
use rog_profiles::{FanCurveProfiles, Profile};
use super::config::{FanCurveConfig, ProfileConfig};
use crate::error::RogError;
use crate::GetSupported;
// TODO: macro wrapper for warn/info/error log macros to add module name
const MOD_NAME: &str = "CtrlPlatformProfile";
pub struct FanCurves {
config_file: FanCurveConfig,
profiles: FanCurveProfiles,
}
impl FanCurves {
pub fn update_profiles_from_config(&mut self) {
self.profiles.balanced = self.config_file.balanced.clone();
self.profiles.performance = self.config_file.performance.clone();
self.profiles.quiet = self.config_file.quiet.clone();
}
pub fn update_config_from_profiles(&mut self) {
self.config_file.balanced = self.profiles.balanced.clone();
self.config_file.performance = self.profiles.performance.clone();
self.config_file.quiet = self.profiles.quiet.clone();
}
pub fn profiles(&self) -> &FanCurveProfiles {
&self.profiles
}
pub fn profiles_mut(&mut self) -> &mut FanCurveProfiles {
&mut self.profiles
}
}
pub struct CtrlPlatformProfile {
pub profile_config: ProfileConfig,
pub fan_curves: Option<FanCurves>,
pub platform: AsusPlatform,
}
impl GetSupported for CtrlPlatformProfile {
type A = PlatformProfileFunctions;
fn get_supported() -> Self::A {
if !Profile::is_platform_profile_supported() {
warn!(
"platform_profile kernel interface not found, your laptop does not support this, \
or the interface is missing."
);
}
let res = FanCurveProfiles::supported_fans();
if res.is_err() {
info!(
"fan curves kernel interface not found, your laptop does not support this, or the \
interface is missing."
);
}
PlatformProfileFunctions {
platform_profile: Profile::is_platform_profile_supported(),
fans: res.unwrap_or_default(),
}
}
}
impl CtrlPlatformProfile {
pub fn new(config: ProfileConfig) -> Result<Self, RogError> {
let platform = AsusPlatform::new()?;
if platform.has_platform_profile() || platform.has_throttle_thermal_policy() {
info!("{MOD_NAME}: Device has profile control available");
let mut controller = CtrlPlatformProfile {
profile_config: config,
fan_curves: None,
platform,
};
if FanCurveProfiles::get_device().is_ok() {
info!("{MOD_NAME}: Device has fan curves available");
let fan_config = FanCurveConfig::new();
// Only do defaults if the config doesn't already exist
if !fan_config.file_path().exists() {
info!("{MOD_NAME}: Fetching default fan curves");
controller.fan_curves = Some(FanCurves {
config_file: fan_config,
profiles: FanCurveProfiles::default(),
});
for _ in [Profile::Balanced, Profile::Performance, Profile::Quiet] {
// For each profile we need to switch to it before we
// can read the existing values from hardware. The ACPI method used
// for this is what limits us.
let next =
Profile::get_next_profile(controller.profile_config.active_profile);
Profile::set_profile(next)
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
.ok();
controller.profile_config.active_profile = next;
// Make sure to set the baseline to default
controller.set_active_curve_to_defaults()?;
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
if let Some(curves) = controller.fan_curves.as_ref() {
info!("{MOD_NAME}: {active:?}:");
for curve in curves.profiles().get_fan_curves_for(active) {
info!("{}", String::from(curve));
}
}
}
if let Some(curves) = controller.fan_curves.as_ref() {
curves.config_file.write();
}
} else {
info!("{MOD_NAME}: Fan curves previously stored, loading...");
let mut fan_curves = FanCurves {
config_file: fan_config.load(),
profiles: FanCurveProfiles::default(),
};
fan_curves.update_profiles_from_config();
controller.fan_curves = Some(fan_curves);
}
}
return Ok(controller);
}
Err(ProfileError::NotSupported.into())
}
pub fn save_config(&mut self) {
self.profile_config.write();
if let Some(fans) = self.fan_curves.as_mut() {
fans.update_config_from_profiles();
fans.config_file.write(); // config write
}
}
/// Set the curve for the active profile active
pub(super) fn write_profile_curve_to_platform(&mut self) -> Result<(), RogError> {
if let Some(curves) = &mut self.fan_curves {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.profiles_mut().write_profile_curve_to_platform(
self.profile_config.active_profile,
&mut device,
)?;
}
}
Ok(())
}
pub(super) fn set_active_curve_to_defaults(&mut self) -> Result<(), RogError> {
if let Some(curves) = self.fan_curves.as_mut() {
if let Ok(mut device) = FanCurveProfiles::get_device() {
curves.profiles_mut().set_active_curve_to_defaults(
self.profile_config.active_profile,
&mut device,
)?;
curves.update_config_from_profiles();
}
}
Ok(())
}
}

View File

@@ -1,4 +0,0 @@
pub mod config;
pub mod controller;
/// Implements `CtrlTask`, Reloadable, `ZbusRun`
pub mod trait_impls;

View File

@@ -1,332 +0,0 @@
use std::str::FromStr;
use std::sync::Arc;
use async_trait::async_trait;
use config_traits::StdConfig;
use log::{error, info, warn};
use rog_profiles::fan_curve_set::CurveData;
use rog_profiles::{FanCurvePU, FanCurveProfiles, Profile};
use zbus::export::futures_util::lock::Mutex;
use zbus::export::futures_util::StreamExt;
use zbus::fdo::Error;
use zbus::{dbus_interface, Connection, SignalContext};
use super::controller::CtrlPlatformProfile;
use crate::error::RogError;
use crate::CtrlTask;
const MOD_NAME: &str = "ProfileZbus";
const ZBUS_PATH: &str = "/org/asuslinux/Profile";
const UNSUPPORTED_MSG: &str =
"Fan curves are not supported on this laptop or you require a patched kernel";
#[derive(Clone)]
pub struct ProfileZbus(pub Arc<Mutex<CtrlPlatformProfile>>);
#[dbus_interface(name = "org.asuslinux.Daemon")]
impl ProfileZbus {
/// Fetch profile names
fn profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
if let Ok(profiles) = Profile::get_profile_names() {
return Ok(profiles);
}
Err(Error::Failed(
"Failed to get all profile details".to_owned(),
))
}
/// Toggle to next platform_profile. Names provided by `Profiles`.
/// If fan-curves are supported will also activate a fan curve for profile.
async fn next_profile(&mut self, #[zbus(signal_context)] ctxt: SignalContext<'_>) {
let mut ctrl = self.0.lock().await;
let next = Profile::get_next_profile(ctrl.profile_config.active_profile);
Profile::set_profile(next)
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
.ok();
ctrl.profile_config.active_profile = next;
ctrl.save_config();
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
.await
.ok();
}
/// Fetch the active profile name
async fn active_profile(&mut self) -> zbus::fdo::Result<Profile> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
Ok(ctrl.profile_config.active_profile)
}
/// Set this platform_profile name as active
async fn set_active_profile(
&self,
#[zbus(signal_context)] ctxt: SignalContext<'_>,
profile: Profile,
) {
let mut ctrl = self.0.lock().await;
// Read first just incase the user has modified the config before calling this
ctrl.profile_config.read();
Profile::set_profile(profile)
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
.ok();
ctrl.profile_config.active_profile = profile;
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("{MOD_NAME}: write_profile_curve_to_platform, {}", e))
.ok();
ctrl.save_config();
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
.await
.ok();
}
/// Set all fan curves for a profile to enabled status. Will also activate a
/// fan curve if in the same profile mode
async fn set_fan_curves_enabled(
&mut self,
profile: Profile,
enabled: bool,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_curves {
curves
.profiles_mut()
.set_profile_curves_enabled(profile, enabled);
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("{MOD_NAME}: write_profile_curve_to_platform, {}", e))
.ok();
ctrl.save_config();
Ok(())
} else {
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
}
}
/// Set a single fan curve for a profile to enabled status. Will also
/// activate a fan curve if in the same profile mode
async fn set_profile_fan_curve_enabled(
&mut self,
profile: Profile,
fan: FanCurvePU,
enabled: bool,
) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_curves {
curves
.profiles_mut()
.set_profile_fan_curve_enabled(profile, fan, enabled);
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("{MOD_NAME}: write_profile_curve_to_platform, {}", e))
.ok();
ctrl.save_config();
Ok(())
} else {
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
}
}
/// Get the fan-curve data for the currently active Profile
async fn fan_curve_data(&mut self, profile: Profile) -> zbus::fdo::Result<Vec<CurveData>> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_curves {
let curve = curves.profiles().get_fan_curves_for(profile);
return Ok(curve.to_vec());
}
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
}
/// Set the fan curve for the specified profile.
/// Will also activate the fan curve if the user is in the same mode.
async fn set_fan_curve(&self, profile: Profile, curve: CurveData) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
if let Some(curves) = &mut ctrl.fan_curves {
curves
.profiles_mut()
.save_fan_curve(curve, profile)
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
} else {
return Err(Error::Failed(UNSUPPORTED_MSG.to_owned()));
}
ctrl.write_profile_curve_to_platform()
.map_err(|e| warn!("{MOD_NAME}: Profile::set_profile, {}", e))
.ok();
ctrl.save_config();
Ok(())
}
/// Reset the stored (self) and device curve to the defaults of the
/// platform.
///
/// Each platform_profile has a different default and the defualt can be
/// read only for the currently active profile.
async fn set_active_curve_to_defaults(&self) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
ctrl.set_active_curve_to_defaults()
.map_err(|e| warn!("{MOD_NAME}: Profile::set_active_curve_to_defaults, {}", e))
.ok();
ctrl.save_config();
Ok(())
}
/// Reset the stored (self) and device curve to the defaults of the
/// platform.
///
/// Each platform_profile has a different default and the defualt can be
/// read only for the currently active profile.
async fn reset_profile_curves(&self, profile: Profile) -> zbus::fdo::Result<()> {
let mut ctrl = self.0.lock().await;
ctrl.profile_config.read();
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
Profile::set_profile(profile)
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
.ok();
ctrl.set_active_curve_to_defaults()
.map_err(|e| warn!("{MOD_NAME}: Profile::set_active_curve_to_defaults, {}", e))
.ok();
Profile::set_profile(active)
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
.ok();
ctrl.save_config();
Ok(())
}
#[dbus_interface(signal)]
async fn notify_profile(signal_ctxt: &SignalContext<'_>, profile: Profile) -> zbus::Result<()> {
}
}
#[async_trait]
impl crate::ZbusRun for ProfileZbus {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
}
}
#[async_trait]
impl CtrlTask for ProfileZbus {
fn zbus_path() -> &'static str {
ZBUS_PATH
}
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
let ctrl = self.0.clone();
let sig_ctx = signal_ctxt.clone();
let watch = self
.0
.lock()
.await
.platform
.monitor_throttle_thermal_policy()?;
tokio::spawn(async move {
let mut buffer = [0; 32];
if let Ok(stream) = watch.into_event_stream(&mut buffer) {
stream
.for_each(|_| async {
let mut lock = ctrl.lock().await;
if let Ok(profile) =
lock.platform.get_throttle_thermal_policy().map_err(|e| {
error!("{MOD_NAME}: get_throttle_thermal_policy error: {e}");
})
{
let new_profile = Profile::from_throttle_thermal_policy(profile);
if new_profile != lock.profile_config.active_profile {
info!("{MOD_NAME}: platform_profile changed to {new_profile}");
lock.profile_config.active_profile = new_profile;
lock.write_profile_curve_to_platform().unwrap();
lock.save_config();
Profile::set_profile(lock.profile_config.active_profile)
.map_err(|e| {
error!("Profile::set_profile() error: {e}");
})
.ok();
Self::notify_profile(&sig_ctx, lock.profile_config.active_profile)
.await
.ok();
}
}
})
.await;
}
});
let ctrl = self.0.clone();
let watch = self.0.lock().await.platform.monitor_platform_profile()?;
tokio::spawn(async move {
let mut buffer = [0; 32];
if let Ok(stream) = watch.into_event_stream(&mut buffer) {
stream
.for_each(|_| async {
let mut lock = ctrl.lock().await;
if let Ok(profile) = lock.platform.get_platform_profile().map_err(|e| {
error!("get_platform_profile error: {e}");
}) {
if let Ok(new_profile) = Profile::from_str(&profile).map_err(|e| {
error!("Profile::from_str(&profile) error: {e}");
}) {
if new_profile != lock.profile_config.active_profile {
info!("{MOD_NAME}: platform_profile changed to {new_profile}");
lock.profile_config.active_profile = new_profile;
lock.write_profile_curve_to_platform().unwrap();
lock.save_config();
Profile::set_profile(lock.profile_config.active_profile)
.map_err(|e| {
error!("Profile::set_profile() error: {e}");
})
.ok();
Self::notify_profile(
&signal_ctxt,
lock.profile_config.active_profile,
)
.await
.ok();
}
}
}
})
.await;
}
});
Ok(())
}
}
#[async_trait]
impl crate::Reloadable for ProfileZbus {
/// Fetch the active profile and use that to set all related components up
async fn reload(&mut self) -> Result<(), RogError> {
let mut ctrl = self.0.lock().await;
let active = ctrl.profile_config.active_profile;
if let Some(curves) = &mut ctrl.fan_curves {
if let Ok(mut device) = FanCurveProfiles::get_device() {
// There is a possibility that the curve was default zeroed, so this call
// initialises the data from system read and we need to save it
// after
curves
.profiles_mut()
.write_profile_curve_to_platform(active, &mut device)?;
ctrl.profile_config.write();
}
}
Ok(())
}
}

View File

@@ -0,0 +1,51 @@
use config_traits::{StdConfig, StdConfigLoad};
use rog_slash::{DeviceState, SlashMode};
use serde_derive::{Deserialize, Serialize};
const CONFIG_FILE: &str = "slash.ron";
/// Config for base system actions for the anime display
#[derive(Deserialize, Serialize, Debug)]
pub struct SlashConfig {
pub slash_enabled: bool,
pub slash_brightness: u8,
pub slash_interval: u8,
pub slash_mode: SlashMode,
}
impl Default for SlashConfig {
fn default() -> Self {
SlashConfig {
slash_enabled: true,
slash_brightness: 255,
slash_interval: 0,
slash_mode: SlashMode::Bounce,
}
}
}
impl StdConfig for SlashConfig {
fn new() -> Self {
Self::default()
}
fn file_name(&self) -> String {
CONFIG_FILE.to_owned()
}
fn config_dir() -> std::path::PathBuf {
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
}
}
impl StdConfigLoad for SlashConfig {}
impl From<&SlashConfig> for DeviceState {
fn from(config: &SlashConfig) -> Self {
DeviceState {
slash_enabled: config.slash_enabled,
slash_brightness: config.slash_brightness,
slash_interval: config.slash_interval,
slash_mode: config.slash_mode,
}
}
}

View File

@@ -0,0 +1,98 @@
pub mod config;
pub mod trait_impls;
use config_traits::{StdConfig, StdConfigLoad};
use rog_platform::hid_raw::HidRaw;
use rog_platform::usb_raw::USBRaw;
use rog_slash::error::SlashError;
use rog_slash::usb::{get_slash_type, pkt_set_mode, pkt_set_options, pkts_for_init};
use rog_slash::{SlashMode, SlashType};
use crate::ctrl_slash::config::SlashConfig;
use crate::error::RogError;
enum Node {
Usb(USBRaw),
Hid(HidRaw),
}
impl Node {
pub fn write_bytes(&self, message: &[u8]) -> Result<(), RogError> {
// TODO: map and pass on errors
match self {
Node::Usb(u) => {
u.write_bytes(message).ok();
}
Node::Hid(h) => {
h.write_bytes(message).ok();
}
}
Ok(())
}
}
pub struct CtrlSlash {
node: Node,
config: SlashConfig,
}
impl CtrlSlash {
#[inline]
pub fn new() -> Result<CtrlSlash, RogError> {
let slash_type = get_slash_type()?;
if matches!(slash_type, SlashType::Unknown | SlashType::Unsupported) {
return Err(RogError::Slash(SlashError::NoDevice));
}
let usb = USBRaw::new(rog_slash::usb::PROD_ID).ok();
let hid = HidRaw::new(rog_slash::usb::PROD_ID_STR).ok();
let node = if usb.is_some() {
unsafe { Node::Usb(usb.unwrap_unchecked()) }
} else if hid.is_some() {
unsafe { Node::Hid(hid.unwrap_unchecked()) }
} else {
return Err(RogError::NotSupported);
};
let ctrl = CtrlSlash {
node,
config: SlashConfig::new().load(),
};
ctrl.do_initialization()?;
Ok(ctrl)
}
fn do_initialization(&self) -> Result<(), RogError> {
let init_packets = pkts_for_init();
self.node.write_bytes(&init_packets[0])?;
self.node.write_bytes(&init_packets[1])?;
// Apply config upon initialization
let option_packets = pkt_set_options(
self.config.slash_enabled,
self.config.slash_brightness,
self.config.slash_interval,
);
self.node.write_bytes(&option_packets)?;
let mode_packets = pkt_set_mode(self.config.slash_mode);
self.node.write_bytes(&mode_packets[0])?;
self.node.write_bytes(&mode_packets[1])?;
Ok(())
}
pub fn set_options(&self, enabled: bool, brightness: u8, interval: u8) -> Result<(), RogError> {
let command_packets = pkt_set_options(enabled, brightness, interval);
self.node.write_bytes(&command_packets)?;
Ok(())
}
pub fn set_slash_mode(&self, slash_mode: SlashMode) -> Result<(), RogError> {
let command_packets = pkt_set_mode(slash_mode);
self.node.write_bytes(&command_packets[0])?;
self.node.write_bytes(&command_packets[1])?;
Ok(())
}
}

View File

@@ -0,0 +1,165 @@
use std::sync::Arc;
use config_traits::StdConfig;
use log::warn;
use rog_slash::usb::{pkt_set_mode, pkt_set_options};
use rog_slash::{DeviceState, SlashMode};
use zbus::export::futures_util::lock::Mutex;
use zbus::{interface, Connection, SignalContext};
use crate::ctrl_slash::CtrlSlash;
use crate::error::RogError;
pub const SLASH_ZBUS_NAME: &str = "Slash";
pub const SLASH_ZBUS_PATH: &str = "/org/asuslinux";
#[derive(Clone)]
pub struct CtrlSlashZbus(pub Arc<Mutex<CtrlSlash>>);
/// The struct with the main dbus methods requires this trait
impl crate::ZbusRun for CtrlSlashZbus {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, SLASH_ZBUS_PATH, server).await;
}
}
#[interface(name = "org.asuslinux.Slash")]
impl CtrlSlashZbus {
/// Get enabled or not
#[zbus(property)]
async fn enabled(&self) -> bool {
let lock = self.0.lock().await;
lock.config.slash_enabled
}
/// Set enabled true or false
#[zbus(property)]
async fn set_enabled(&self, enabled: bool) {
let mut lock = self.0.lock().await;
let brightness = if enabled && lock.config.slash_brightness == 0 {
0x88
} else {
lock.config.slash_brightness
};
lock.node
.write_bytes(&pkt_set_options(
enabled,
brightness,
lock.config.slash_interval,
))
.map_err(|err| {
warn!("ctrl_slash::set_options {}", err);
})
.ok();
lock.config.slash_enabled = enabled;
lock.config.slash_brightness = brightness;
lock.config.write();
}
/// Get brightness level
#[zbus(property)]
async fn brightness(&self) -> u8 {
let lock = self.0.lock().await;
lock.config.slash_brightness
}
/// Set brightness level
#[zbus(property)]
async fn set_brightness(&self, brightness: u8) {
let mut lock = self.0.lock().await;
let enabled = brightness > 0;
lock.node
.write_bytes(&pkt_set_options(
enabled,
brightness,
lock.config.slash_interval,
))
.map_err(|err| {
warn!("ctrl_slash::set_options {}", err);
})
.ok();
lock.config.slash_enabled = enabled;
lock.config.slash_brightness = brightness;
lock.config.write();
}
#[zbus(property)]
async fn interval(&self) -> u8 {
let lock = self.0.lock().await;
lock.config.slash_interval
}
/// Set interval between slash animations (0-255)
#[zbus(property)]
async fn set_interval(&self, interval: u8) {
let mut lock = self.0.lock().await;
lock.node
.write_bytes(&pkt_set_options(
lock.config.slash_enabled,
lock.config.slash_brightness,
interval,
))
.map_err(|err| {
warn!("ctrl_slash::set_options {}", err);
})
.ok();
lock.config.slash_interval = interval;
lock.config.write();
}
#[zbus(property)]
async fn slash_mode(&self) -> u8 {
let lock = self.0.lock().await;
lock.config.slash_interval
}
/// Set interval between slash animations (0-255)
#[zbus(property)]
async fn set_slash_mode(&self, slash_mode: SlashMode) {
let mut lock = self.0.lock().await;
let command_packets = pkt_set_mode(slash_mode);
lock.node
.write_bytes(&command_packets[0])
.map_err(|err| {
warn!("ctrl_slash::set_options {}", err);
})
.ok();
lock.node
.write_bytes(&command_packets[1])
.map_err(|err| {
warn!("ctrl_slash::set_options {}", err);
})
.ok();
lock.config.slash_mode = slash_mode;
lock.config.write();
}
/// Get the device state as stored by asusd
// #[zbus(property)]
async fn device_state(&self) -> DeviceState {
let lock = self.0.lock().await;
DeviceState::from(&lock.config)
}
}
impl crate::CtrlTask for CtrlSlashZbus {
fn zbus_path() -> &'static str {
SLASH_ZBUS_PATH
}
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
Ok(())
}
}
impl crate::Reloadable for CtrlSlashZbus {
async fn reload(&mut self) -> Result<(), RogError> {
Ok(())
}
}

View File

@@ -1,49 +0,0 @@
use async_trait::async_trait;
use serde_derive::{Deserialize, Serialize};
use zbus::zvariant::Type;
use zbus::{dbus_interface, Connection};
use crate::ctrl_anime::CtrlAnime;
use crate::ctrl_aura::controller::CtrlKbdLed;
use crate::ctrl_platform::CtrlPlatform;
use crate::ctrl_power::CtrlPower;
use crate::ctrl_profiles::controller::CtrlPlatformProfile;
use crate::GetSupported;
#[derive(Serialize, Deserialize, Debug, Type)]
pub struct SupportedFunctions(rog_platform::supported::SupportedFunctions);
#[dbus_interface(name = "org.asuslinux.Daemon")]
impl SupportedFunctions {
pub fn supported_functions(
&self,
) -> zbus::fdo::Result<&rog_platform::supported::SupportedFunctions> {
Ok(&self.0)
}
#[dbus_interface(out_args("answer", "question"))]
fn meaning_of_life(&self) -> zbus::fdo::Result<(i32, String)> {
Ok((42, String::from("Meaning of life")))
}
}
#[async_trait]
impl crate::ZbusRun for SupportedFunctions {
async fn add_to_server(self, server: &mut Connection) {
Self::add_to_server_helper(self, "/org/asuslinux/Supported", server).await;
}
}
impl GetSupported for SupportedFunctions {
type A = SupportedFunctions;
fn get_supported() -> Self::A {
Self(rog_platform::supported::SupportedFunctions {
anime_ctrl: CtrlAnime::get_supported(),
keyboard_led: CtrlKbdLed::get_supported(),
charge_ctrl: CtrlPower::get_supported(),
platform_profile: CtrlPlatformProfile::get_supported(),
rog_bios_ctrl: CtrlPlatform::get_supported(),
})
}
}

View File

@@ -1,39 +1,30 @@
use std::env;
use std::error::Error;
use std::io::Write;
use std::sync::Arc;
use std::time::Duration;
use ::zbus::export::futures_util::lock::Mutex;
use ::zbus::Connection;
use asusd::config::Config;
use asusd::ctrl_anime::config::AnimeConfig;
use asusd::ctrl_anime::trait_impls::CtrlAnimeZbus;
use asusd::ctrl_anime::CtrlAnime;
use asusd::ctrl_aura::controller::CtrlKbdLed;
use asusd::ctrl_aura::trait_impls::CtrlKbdLedZbus;
use asusd::ctrl_aura::manager::AuraManager;
use asusd::ctrl_fancurves::CtrlFanCurveZbus;
use asusd::ctrl_platform::CtrlPlatform;
use asusd::ctrl_power::CtrlPower;
use asusd::ctrl_profiles::config::ProfileConfig;
use asusd::ctrl_profiles::controller::CtrlPlatformProfile;
use asusd::ctrl_profiles::trait_impls::ProfileZbus;
use asusd::ctrl_supported::SupportedFunctions;
use asusd::{print_board_info, CtrlTask, GetSupported, Reloadable, ZbusRun};
use config_traits::{StdConfig, StdConfigLoad, StdConfigLoad2};
use log::{error, info, warn};
use rog_aura::aura_detection::LaptopLedData;
use rog_dbus::DBUS_NAME;
use rog_profiles::Profile;
use tokio::time::sleep;
use zbus::SignalContext;
use asusd::ctrl_slash::trait_impls::CtrlSlashZbus;
use asusd::ctrl_slash::CtrlSlash;
use asusd::{print_board_info, start_tasks, CtrlTask, DBUS_NAME};
use config_traits::{StdConfig, StdConfigLoad1};
use log::{error, info};
use zbus::fdo::ObjectManager;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// console_subscriber::init();
let mut logger = env_logger::Builder::new();
logger
.parse_default_env()
.target(env_logger::Target::Stdout)
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
.format_timestamp(None)
.init();
let is_service = match env::var_os("IS_SERVICE") {
@@ -52,8 +43,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
info!(" daemon v{}", asusd::VERSION);
info!(" rog-anime v{}", rog_anime::VERSION);
info!(" rog-slash v{}", rog_slash::VERSION);
info!(" rog-aura v{}", rog_aura::VERSION);
info!(" rog-dbus v{}", rog_dbus::VERSION);
info!(" rog-profiles v{}", rog_profiles::VERSION);
info!("rog-platform v{}", rog_platform::VERSION);
@@ -63,19 +54,39 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// The actual main loop for the daemon
async fn start_daemon() -> Result<(), Box<dyn Error>> {
let supported = SupportedFunctions::get_supported();
// let supported = SupportedFunctions::get_supported();
print_board_info();
println!("{:?}", supported.supported_functions());
// println!("{:?}", supported.supported_functions());
// Start zbus server
let mut connection = Connection::system().await?;
connection
.object_server()
.at("/org/asuslinux", ObjectManager)
.await
.unwrap();
let config = Config::new().load();
let cfg_path = config.file_path();
let config = Arc::new(Mutex::new(config));
supported.add_to_server(&mut connection).await;
// supported.add_to_server(&mut connection).await;
match CtrlPlatform::new(config.clone()) {
match CtrlFanCurveZbus::new() {
Ok(ctrl) => {
let sig_ctx = CtrlFanCurveZbus::signal_context(&connection)?;
start_tasks(ctrl, &mut connection, sig_ctx).await?;
}
Err(err) => {
error!("FanCurves: {}", err);
}
}
match CtrlPlatform::new(
config.clone(),
&cfg_path,
CtrlPlatform::signal_context(&connection)?,
) {
Ok(ctrl) => {
let sig_ctx = CtrlPlatform::signal_context(&connection)?;
start_tasks(ctrl, &mut connection, sig_ctx).await?;
@@ -85,33 +96,7 @@ async fn start_daemon() -> Result<(), Box<dyn Error>> {
}
}
match CtrlPower::new(config.clone()) {
Ok(ctrl) => {
let sig_ctx = CtrlPower::signal_context(&connection)?;
start_tasks(ctrl, &mut connection, sig_ctx).await?;
}
Err(err) => {
error!("CtrlPower: {}", err);
}
}
if Profile::is_platform_profile_supported() {
let profile_config = ProfileConfig::new().load();
match CtrlPlatformProfile::new(profile_config) {
Ok(ctrl) => {
let zbus = ProfileZbus(Arc::new(Mutex::new(ctrl)));
let sig_ctx = ProfileZbus::signal_context(&connection)?;
start_tasks(zbus, &mut connection, sig_ctx).await?;
}
Err(err) => {
error!("Profile control: {}", err);
}
}
} else {
warn!("platform_profile support not found");
}
match CtrlAnime::new(AnimeConfig::new().load()) {
match CtrlAnime::new() {
Ok(ctrl) => {
let zbus = CtrlAnimeZbus(Arc::new(Mutex::new(ctrl)));
let sig_ctx = CtrlAnimeZbus::signal_context(&connection)?;
@@ -122,44 +107,28 @@ async fn start_daemon() -> Result<(), Box<dyn Error>> {
}
}
let laptop = LaptopLedData::get_data();
// CtrlKbdLed deviates from the config pattern above due to requiring a keyboard
// detection first
match CtrlKbdLed::new(laptop) {
match CtrlSlash::new() {
Ok(ctrl) => {
let zbus = CtrlKbdLedZbus(Arc::new(Mutex::new(ctrl)));
let sig_ctx = CtrlKbdLedZbus::signal_context(&connection)?;
let zbus = CtrlSlashZbus(Arc::new(Mutex::new(ctrl)));
// Currently, the Slash has no need for a loop watching power events, however,
// it could be cool to have the slash do some power-on/off animation
// (It has a built-in power on animation which plays when u plug in the power
// supply)
let sig_ctx = CtrlSlashZbus::signal_context(&connection)?;
start_tasks(zbus, &mut connection, sig_ctx).await?;
}
Err(err) => {
error!("Keyboard control: {}", err);
info!("AniMe control: {}", err);
}
}
let _ = AuraManager::new(connection.clone()).await?;
// Request dbus name after finishing initalizing all functions
connection.request_name(DBUS_NAME).await?;
loop {
// This is just a blocker to idle and ensure the reator reacts
sleep(Duration::from_millis(1000)).await;
connection.executor().tick().await;
}
}
async fn start_tasks<T>(
mut zbus: T,
connection: &mut Connection,
signal_ctx: SignalContext<'static>,
) -> Result<(), Box<dyn Error>>
where
T: ZbusRun + Reloadable + CtrlTask + Clone,
{
let task = zbus.clone();
zbus.reload()
.await
.unwrap_or_else(|err| warn!("Controller error: {}", err));
zbus.add_to_server(connection).await;
task.create_tasks(signal_ctx).await.ok();
Ok(())
}

View File

@@ -5,6 +5,7 @@ use config_traits::ron;
use rog_anime::error::AnimeError;
use rog_platform::error::PlatformError;
use rog_profiles::error::ProfileError;
use rog_slash::error::SlashError;
#[derive(Debug)]
pub enum RogError {
@@ -31,6 +32,7 @@ pub enum RogError {
NoAuraKeyboard,
NoAuraNode,
Anime(AnimeError),
Slash(SlashError),
Platform(PlatformError),
SystemdUnitAction(String),
SystemdUnitWaitTimeout(String),
@@ -72,6 +74,7 @@ impl fmt::Display for RogError {
RogError::NoAuraKeyboard => write!(f, "No supported Aura keyboard"),
RogError::NoAuraNode => write!(f, "No Aura keyboard node found"),
RogError::Anime(deets) => write!(f, "AniMe Matrix error: {}", deets),
RogError::Slash(deets) => write!(f, "Slash error: {}", deets),
RogError::Platform(deets) => write!(f, "Asus Platform error: {}", deets),
RogError::SystemdUnitAction(action) => {
write!(f, "systemd unit action {} failed", action)
@@ -103,6 +106,12 @@ impl From<AnimeError> for RogError {
}
}
impl From<SlashError> for RogError {
fn from(err: SlashError) -> Self {
RogError::Slash(err)
}
}
impl From<PlatformError> for RogError {
fn from(err: PlatformError) -> Self {
RogError::Platform(err)

View File

@@ -5,30 +5,32 @@ pub mod config;
pub mod ctrl_anime;
/// Keyboard LED brightness control, RGB, and LED display modes
pub mod ctrl_aura;
/// Control platform profiles + fan-curves if available
pub mod ctrl_fancurves;
/// Control ASUS bios function such as boot sound, Optimus/Dedicated gfx mode
pub mod ctrl_platform;
/// Control of battery charge level
pub mod ctrl_power;
/// Control platform profiles + fan-curves if available
pub mod ctrl_profiles;
/// Fetch all supported functions for the laptop
pub mod ctrl_supported;
/// Control of Slash led bar
pub mod ctrl_slash;
pub mod error;
use std::future::Future;
use std::time::Duration;
use async_trait::async_trait;
use dmi_id::DMIID;
use futures_lite::stream::StreamExt;
use log::{debug, info, warn};
use logind_zbus::manager::ManagerProxy;
use zbus::export::futures_util::StreamExt;
use tokio::time::sleep;
use zbus::zvariant::ObjectPath;
use zbus::{Connection, SignalContext};
use zbus::{CacheProperties, Connection, SignalContext};
use crate::error::RogError;
const CONFIG_PATH_BASE: &str = "/etc/asusd/";
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
pub static DBUS_PATH: &str = "/org/asuslinux/Daemon";
pub static DBUS_IFACE: &str = "org.asuslinux.Daemon";
/// This macro adds a function which spawns an `inotify` task on the passed in
/// `Executor`.
@@ -46,14 +48,54 @@ const CONFIG_PATH_BASE: &str = "/etc/asusd/";
/// # Example
///
/// ```ignore
/// impl CtrlRogBios {
/// impl RogPlatform {
/// task_watch_item!(panel_od platform);
/// task_watch_item!(gpu_mux_mode platform);
/// }
/// ```
/// ```\
/// // TODO: this is kind of useless if it can't trigger some action
#[macro_export]
macro_rules! task_watch_item {
($name:ident $name_str:literal $self_inner:ident) => {
concat_idents::concat_idents!(fn_name = watch_, $name {
async fn fn_name(
&self,
signal_ctxt: SignalContext<'static>,
) -> Result<(), RogError> {
use zbus::export::futures_util::StreamExt;
let ctrl = self.clone();
concat_idents::concat_idents!(watch_fn = monitor_, $name {
match self.$self_inner.watch_fn() {
Ok(watch) => {
tokio::spawn(async move {
let mut buffer = [0; 32];
watch.into_event_stream(&mut buffer).unwrap().for_each(|_| async {
if let Ok(value) = ctrl.$name() { // get new value from zbus method
if ctrl.config.lock().await.$name != value {
log::debug!("{} was changed to {} externally", $name_str, value);
concat_idents::concat_idents!(notif_fn = $name, _changed {
ctrl.notif_fn(&signal_ctxt).await.ok();
});
let mut lock = ctrl.config.lock().await;
lock.$name = value;
lock.write();
}
}
}).await;
});
}
Err(e) => info!("inotify watch failed: {}. You can ignore this if your device does not support the feature", e),
}
});
Ok(())
}
});
};
}
#[macro_export]
macro_rules! task_watch_item_notify {
($name:ident $self_inner:ident) => {
concat_idents::concat_idents!(fn_name = watch_, $name {
async fn fn_name(
@@ -69,9 +111,8 @@ macro_rules! task_watch_item {
tokio::spawn(async move {
let mut buffer = [0; 32];
watch.into_event_stream(&mut buffer).unwrap().for_each(|_| async {
let value = ctrl.$name();
concat_idents::concat_idents!(notif_fn = notify_, $name {
Self::notif_fn(&signal_ctxt, value).await.ok();
concat_idents::concat_idents!(notif_fn = $name, _changed {
ctrl.notif_fn(&signal_ctxt).await.ok();
});
}).await;
});
@@ -88,42 +129,48 @@ macro_rules! task_watch_item {
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn print_board_info() {
let dmi = sysfs_class::DmiId::default();
let board_name = dmi.board_name().expect("Could not get board_name");
let prod_family = dmi.product_family().expect("Could not get product_family");
info!("Product family: {}", prod_family.trim());
info!("Board name: {}", board_name.trim());
let dmi = DMIID::new().unwrap_or_default();
info!("Product family: {}", dmi.product_family);
info!("Board name: {}", dmi.board_name);
}
#[async_trait]
pub trait Reloadable {
async fn reload(&mut self) -> Result<(), RogError>;
fn reload(&mut self) -> impl Future<Output = Result<(), RogError>> + Send;
}
#[async_trait]
pub trait ZbusRun {
async fn add_to_server(self, server: &mut Connection);
pub trait ReloadAndNotify {
type Data: Send;
async fn add_to_server_helper(
fn reload_and_notify(
&mut self,
signal_context: &SignalContext<'static>,
data: Self::Data,
) -> impl Future<Output = Result<(), RogError>> + Send;
}
pub trait ZbusRun {
fn add_to_server(self, server: &mut Connection) -> impl Future<Output = ()> + Send;
fn add_to_server_helper(
iface: impl zbus::Interface,
path: &str,
server: &mut Connection,
) {
server
.object_server()
.at(&ObjectPath::from_str_unchecked(path), iface)
.await
.map_err(|err| {
warn!("{}: add_to_server {}", path, err);
err
})
.ok();
) -> impl Future<Output = ()> + Send {
async move {
server
.object_server()
.at(&ObjectPath::from_str_unchecked(path), iface)
.await
.map_err(|err| {
warn!("{}: add_to_server {}", path, err);
err
})
.ok();
}
}
}
/// Set up a task to run on the async executor
#[async_trait]
pub trait CtrlTask {
fn zbus_path() -> &'static str;
@@ -134,7 +181,10 @@ pub trait CtrlTask {
/// Implement to set up various tasks that may be required, using the
/// `Executor`. No blocking loops are allowed, or they must be run on a
/// separate thread.
async fn create_tasks(&self, signal: SignalContext<'static>) -> Result<(), RogError>;
fn create_tasks(
&self,
signal: SignalContext<'static>,
) -> impl Future<Output = Result<(), RogError>> + Send;
// /// Create a timed repeating task
// async fn repeating_task(&self, millis: u64, mut task: impl FnMut() + Send +
@@ -152,74 +202,89 @@ pub trait CtrlTask {
///
/// The closures can potentially block, so execution time should be the
/// minimal possible such as save a variable.
async fn create_sys_event_tasks<
Fut1,
Fut2,
Fut3,
Fut4,
F1: Send + 'static,
F2: Send + 'static,
F3: Send + 'static,
F4: Send + 'static,
>(
fn create_sys_event_tasks<Fut1, Fut2, Fut3, Fut4, F1, F2, F3, F4>(
&self,
mut on_sleep: F1,
mut on_wake: F2,
mut on_shutdown: F3,
mut on_boot: F4,
) where
F1: FnMut() -> Fut1,
F2: FnMut() -> Fut2,
F3: FnMut() -> Fut3,
F4: FnMut() -> Fut4,
mut on_prepare_for_sleep: F1,
mut on_prepare_for_shutdown: F2,
mut on_lid_change: F3,
mut on_external_power_change: F4,
) -> impl Future<Output = ()> + Send
where
F1: FnMut(bool) -> Fut1 + Send + 'static,
F2: FnMut(bool) -> Fut2 + Send + 'static,
F3: FnMut(bool) -> Fut3 + Send + 'static,
F4: FnMut(bool) -> Fut4 + Send + 'static,
Fut1: Future<Output = ()> + Send,
Fut2: Future<Output = ()> + Send,
Fut3: Future<Output = ()> + Send,
Fut4: Future<Output = ()> + Send,
{
let connection = Connection::system()
.await
.expect("Controller could not create dbus connection");
async {
let connection = Connection::system()
.await
.expect("Controller could not create dbus connection");
let manager = ManagerProxy::new(&connection)
.await
.expect("Controller could not create ManagerProxy");
let manager = ManagerProxy::builder(&connection)
.cache_properties(CacheProperties::No)
.build()
.await
.expect("Controller could not create ManagerProxy");
tokio::spawn(async move {
if let Ok(mut notif) = manager.receive_prepare_for_sleep().await {
while let Some(event) = notif.next().await {
if let Ok(args) = event.args() {
if args.start {
debug!("Doing on_sleep()");
on_sleep().await;
} else if !args.start() {
debug!("Doing on_wake()");
on_wake().await;
let manager1 = manager.clone();
tokio::spawn(async move {
if let Ok(mut notif) = manager1.receive_prepare_for_shutdown().await {
while let Some(event) = notif.next().await {
// blocks thread :|
if let Ok(args) = event.args() {
debug!("Doing on_prepare_for_shutdown({})", args.start);
on_prepare_for_shutdown(args.start).await;
}
}
}
}
});
});
let manager = ManagerProxy::new(&connection)
.await
.expect("Controller could not create ManagerProxy");
tokio::spawn(async move {
if let Ok(mut notif) = manager.receive_prepare_for_shutdown().await {
while let Some(event) = notif.next().await {
if let Ok(args) = event.args() {
if args.start {
debug!("Doing on_shutdown()");
on_shutdown().await;
} else if !args.start() {
debug!("Doing on_boot()");
on_boot().await;
let manager2 = manager.clone();
tokio::spawn(async move {
if let Ok(mut notif) = manager2.receive_prepare_for_sleep().await {
while let Some(event) = notif.next().await {
// blocks thread :|
if let Ok(args) = event.args() {
debug!("Doing on_prepare_for_sleep({})", args.start);
on_prepare_for_sleep(args.start).await;
}
}
}
}
});
});
let manager3 = manager.clone();
tokio::spawn(async move {
let mut last_power = manager3.on_external_power().await.unwrap_or_default();
loop {
if let Ok(next) = manager3.on_external_power().await {
if next != last_power {
last_power = next;
on_external_power_change(next).await;
}
}
sleep(Duration::from_secs(2)).await;
}
});
tokio::spawn(async move {
let mut last_lid = manager.lid_closed().await.unwrap_or_default();
// need to loop on these as they don't emit signals
loop {
if let Ok(next) = manager.lid_closed().await {
if next != last_lid {
last_lid = next;
on_lid_change(next).await;
}
}
sleep(Duration::from_secs(2)).await;
}
});
}
}
}
@@ -228,3 +293,22 @@ pub trait GetSupported {
fn get_supported() -> Self::A;
}
pub async fn start_tasks<T>(
mut zbus: T,
connection: &mut Connection,
signal_ctx: SignalContext<'static>,
) -> Result<(), RogError>
where
T: ZbusRun + Reloadable + CtrlTask + Clone,
{
let zbus_clone = zbus.clone();
zbus.reload()
.await
.unwrap_or_else(|err| warn!("Controller error: {}", err));
zbus.add_to_server(connection).await;
zbus_clone.create_tasks(signal_ctx).await.ok();
Ok(())
}

View File

@@ -1,65 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<!--
Writes a data stream of length. Will force system thread to exit until
it is restarted
-->
<method name="Write">
<arg name="input" type="(ays)" direction="in"/>
</method>
<!--
Set the global AniMe brightness
-->
<method name="SetImageBrightness">
<arg name="bright" type="d" direction="in"/>
</method>
<!--
Set base brightness level
-->
<method name="SetBrightness">
<arg name="brightness" type="s" direction="in"/>
</method>
<!--
Enable the builtin animations or not
-->
<method name="SetBuiltinsEnabled">
<arg name="enabled" type="b" direction="in"/>
</method>
<!--
Set which builtin animation is used for each stage
-->
<method name="SetBuiltinAnimations">
<arg name="boot" type="s" direction="in"/>
<arg name="awake" type="s" direction="in"/>
<arg name="sleep" type="s" direction="in"/>
<arg name="shutdown" type="s" direction="in"/>
</method>
<!--
Set whether the AniMe is enabled at all
-->
<method name="SetEnableDisplay">
<arg name="enabled" type="b" direction="in"/>
</method>
<!--
The main loop is the base system set action if the user isn't running
the user daemon
-->
<method name="RunMainLoop">
<arg name="start" type="b" direction="in"/>
</method>
<!--
Get the device state as stored by asusd
-->
<method name="DeviceState">
<arg type="bsb(ssss)" direction="out"/>
</method>
<!--
Notify listeners of the status of AniMe LED power and factory
system-status animations
-->
<signal name="NotifyDeviceState">
<arg name="data" type="(bsb(ssss))"/>
</signal>
</interface>
</node>

View File

@@ -1,71 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<!--
Set the keyboard brightness level (0-3)
-->
<method name="SetBrightness">
<arg name="brightness" type="s" direction="in"/>
</method>
<!--
Set a variety of states, input is array of enum.
`enabled` sets if the sent array should be disabled or enabled
For Modern ROG devices the "enabled" flag is ignored.
-->
<method name="SetLedPower">
<arg name="options" type="(asas((sbbbb)(sbbbb)(sbbbb)(sbbbb)(sbbbb)))" direction="in"/>
<arg name="enabled" type="b" direction="in"/>
</method>
<method name="SetLedMode">
<arg name="effect" type="(ss(yyy)(yyy)ss)" direction="in"/>
</method>
<method name="NextLedMode">
</method>
<method name="PrevLedMode">
</method>
<method name="NextLedBrightness">
</method>
<method name="PrevLedBrightness">
</method>
<!--
Return the device type for this Aura keyboard
-->
<method name="DeviceType">
<arg type="s" direction="out"/>
</method>
<method name="LedPower">
<arg type="asas((sbbbb)(sbbbb)(sbbbb)(sbbbb)(sbbbb))" direction="out"/>
</method>
<!--
Return the current mode data
-->
<method name="LedMode">
<arg type="s" direction="out"/>
</method>
<!--
Return a list of available modes
-->
<method name="LedModes">
<arg type="a{s(ss(yyy)(yyy)ss)}" direction="out"/>
</method>
<!--
On machine that have some form of either per-key keyboard or per-zone
this can be used to write custom effects over dbus. The input is a
nested `Vec<Vec<8>>` where `Vec<u8>` is a raw USB packet
-->
<method name="DirectAddressingRaw">
<arg name="data" type="aay" direction="in"/>
</method>
<signal name="NotifyLed">
<arg name="data" type="(ss(yyy)(yyy)ss)"/>
</signal>
<signal name="NotifyPowerStates">
<arg name="data" type="(asas((sbbbb)(sbbbb)(sbbbb)(sbbbb)(sbbbb)))"/>
</signal>
<!--
Return the current LED brightness
-->
<property name="LedBrightness" type="n" access="read"/>
</interface>
</node>

View File

@@ -1,67 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<method name="SetGpuMuxMode">
<arg name="mode" type="u" direction="in"/>
</method>
<method name="GpuMuxMode">
<arg type="u" direction="out"/>
</method>
<signal name="NotifyGpuMuxMode">
<arg name="mode" type="u"/>
</signal>
<method name="SetPostBootSound">
<arg name="on" type="b" direction="in"/>
</method>
<method name="PostBootSound">
<arg type="n" direction="out"/>
</method>
<signal name="NotifyPostBootSound">
<arg name="on" type="b"/>
</signal>
<method name="SetPanelOd">
<arg name="overdrive" type="b" direction="in"/>
</method>
<!--
Get the `panel_od` value from platform. Updates the stored value in
internal config also.
-->
<method name="PanelOd">
<arg type="b" direction="out"/>
</method>
<signal name="NotifyPanelOd">
<arg name="overdrive" type="b"/>
</signal>
<method name="SetMiniLedMode">
<arg name="on" type="b" direction="in"/>
</method>
<!--
Get the `panel_od` value from platform. Updates the stored value in
internal config also.
-->
<method name="MiniLedMode">
<arg type="b" direction="out"/>
</method>
<signal name="NotifyMiniLedMode">
<arg name="on" type="b"/>
</signal>
<method name="SetDgpuDisable">
<arg name="disable" type="b" direction="in"/>
</method>
<method name="DgpuDisable">
<arg type="b" direction="out"/>
</method>
<signal name="NotifyDgpuDisable">
<arg name="disable" type="b"/>
</signal>
<method name="SetEgpuEnable">
<arg name="enable" type="b" direction="in"/>
</method>
<method name="EgpuEnable">
<arg type="b" direction="out"/>
</method>
<signal name="NotifyEgpuEnable">
<arg name="enable" type="b"/>
</signal>
</interface>
</node>

View File

@@ -1,20 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<method name="SetChargeControlEndThreshold">
<arg name="limit" type="y" direction="in"/>
</method>
<method name="ChargeControlEndThreshold">
<arg type="y" direction="out"/>
</method>
<method name="MainsOnline">
<arg type="b" direction="out"/>
</method>
<signal name="NotifyChargeControlEndThreshold">
<arg name="limit" type="y"/>
</signal>
<signal name="NotifyMainsOnline">
<arg name="on" type="b"/>
</signal>
</interface>
</node>

View File

@@ -1,80 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<!--
Fetch profile names
-->
<method name="Profiles">
<arg type="as" direction="out"/>
</method>
<!--
Toggle to next platform_profile. Names provided by `Profiles`.
If fan-curves are supported will also activate a fan curve for profile.
-->
<method name="NextProfile">
</method>
<!--
Fetch the active profile name
-->
<method name="ActiveProfile">
<arg type="s" direction="out"/>
</method>
<!--
Set this platform_profile name as active
-->
<method name="SetActiveProfile">
<arg name="profile" type="s" direction="in"/>
</method>
<!--
Get a list of profiles that have fan-curves enabled.
-->
<method name="EnabledFanProfiles">
<arg type="as" direction="out"/>
</method>
<!--
Set a profile fan curve enabled status. Will also activate a fan curve
if in the same profile mode
-->
<method name="SetFanCurveEnabled">
<arg name="profile" type="s" direction="in"/>
<arg name="enabled" type="b" direction="in"/>
</method>
<!--
Get the fan-curve data for the currently active Profile
-->
<method name="FanCurveData">
<arg name="profile" type="s" direction="in"/>
<arg type="(b(s(yyyyyyyy)(yyyyyyyy))(s(yyyyyyyy)(yyyyyyyy)))" direction="out"/>
</method>
<!--
Set the fan curve for the specified profile.
Will also activate the fan curve if the user is in the same mode.
-->
<method name="SetFanCurve">
<arg name="profile" type="s" direction="in"/>
<arg name="curve" type="(s(yyyyyyyy)(yyyyyyyy))" direction="in"/>
</method>
<!--
Reset the stored (self) and device curve to the defaults of the
platform.
Each platform_profile has a different default and the defualt can be
read only for the currently active profile.
-->
<method name="SetActiveCurveToDefaults">
</method>
<!--
Reset the stored (self) and device curve to the defaults of the
platform.
Each platform_profile has a different default and the defualt can be
read only for the currently active profile.
-->
<method name="ResetProfileCurves">
<arg name="profile" type="s" direction="in"/>
</method>
<signal name="NotifyProfile">
<arg name="profile" type="s"/>
</signal>
</interface>
</node>

View File

@@ -1,12 +0,0 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.asuslinux.Daemon">
<method name="SupportedFunctions">
<arg type="b(b)(bb)(sbasassas)(bbbbbb)" direction="out"/>
</method>
<method name="MeaningOfLife">
<arg name="answer" type="i" direction="out"/>
<arg name="question" type="s" direction="out"/>
</method>
</interface>
</node>

View File

@@ -1,53 +0,0 @@
/*
Generated by typeshare 1.6.0
*/
export enum AnimBooting {
GlitchConstruction = "GlitchConstruction",
StaticEmergence = "StaticEmergence",
}
export enum AnimAwake {
BinaryBannerScroll = "BinaryBannerScroll",
RogLogoGlitch = "RogLogoGlitch",
}
export enum AnimSleeping {
BannerSwipe = "BannerSwipe",
Starfield = "Starfield",
}
export enum AnimShutdown {
GlitchOut = "GlitchOut",
SeeYa = "SeeYa",
}
export interface Animations {
boot: AnimBooting;
awake: AnimAwake;
sleep: AnimSleeping;
shutdown: AnimShutdown;
}
/** Base LED brightness of the display */
export enum Brightness {
Off = "Off",
Low = "Low",
Med = "Med",
High = "High",
}
export interface DeviceState {
display_enabled: boolean;
display_brightness: Brightness;
builtin_anims_enabled: boolean;
builtin_anims: Animations;
}
export enum AnimeType {
GA401 = "GA401",
GA402 = "GA402",
GU604 = "GU604",
Unknown = "Unknown",
}

View File

@@ -1,232 +0,0 @@
/*
Generated by typeshare 1.6.0
*/
/** Represents the per-key raw USB packets */
export type UsbPackets = number[][];
/**
* A `UsbPackets` contains all data to change the full set of keyboard
* key colours individually.
*
* Each row of the internal array is a full HID packet that can be sent
* to the keyboard EC. One row controls one group of keys, these keys are not
* necessarily all on the same row of the keyboard, with some splitting between
* two rows.
*/
export interface LedUsbPackets {
/** The packet data used to send data to the USB keyboard */
usb_packets: UsbPackets;
/**
* Wether or not this packet collection is zoned. The determines which
* starting bytes are used and what the indexing is for lightbar RGB
* colours
*/
zoned: boolean;
}
export interface Colour {
r: number;
g: number;
b: number;
}
/** Enum of modes that convert to the actual number required by a USB HID packet */
export enum AuraModeNum {
Static = "Static",
Breathe = "Breathe",
Strobe = "Strobe",
Rainbow = "Rainbow",
Star = "Star",
Rain = "Rain",
Highlight = "Highlight",
Laser = "Laser",
Ripple = "Ripple",
Pulse = "Pulse",
Comet = "Comet",
Flash = "Flash",
}
/** Base effects have no zoning, while multizone is 1-4 */
export enum AuraZone {
/** Used if keyboard has no zones, or if setting all */
None = "None",
/** Leftmost zone */
Key1 = "Key1",
/** Zone after leftmost */
Key2 = "Key2",
/** Zone second from right */
Key3 = "Key3",
/** Rightmost zone */
Key4 = "Key4",
/** Logo on the lid (or elsewhere?) */
Logo = "Logo",
/** The left part of a lightbar (typically on the front of laptop) */
BarLeft = "BarLeft",
/** The right part of a lightbar */
BarRight = "BarRight",
}
export enum Speed {
Low = "Low",
Med = "Med",
High = "High",
}
/**
* Used for Rainbow mode.
*
* Enum corresponds to the required integer value
*/
export enum Direction {
Right = "Right",
Left = "Left",
Up = "Up",
Down = "Down",
}
/**
* Default factory modes structure. This easily converts to an USB HID packet
* with:
* ```rust
* // let bytes: [u8; LED_MSG_LEN] = mode.into();
* ```
*/
export interface AuraEffect {
/** The effect type */
mode: AuraModeNum;
/** `AuraZone::None` for no zone or zoneless keyboards */
zone: AuraZone;
/** Primary colour for all modes */
colour1: Colour;
/** Secondary colour in some modes like Breathing or Stars */
colour2: Colour;
/** One of three speeds for modes that support speed (most that animate) */
speed: Speed;
/** Up, down, left, right. Only Rainbow mode seems to use this */
direction: Direction;
}
/** The powerr zones this laptop supports */
export enum PowerZones {
/** The logo on some laptop lids */
Logo = "Logo",
/** The full keyboard (not zones) */
Keyboard = "Keyboard",
/** The lightbar, typically on the front of the laptop */
Lightbar = "Lightbar",
/** The leds that may be placed around the edge of the laptop lid */
Lid = "Lid",
/** The led strip on the rear of some laptops */
RearGlow = "RearGlow",
}
export interface KbAuraPowerState {
zone: PowerZones;
boot: boolean;
awake: boolean;
sleep: boolean;
shutdown: boolean;
}
/**
* Track and control the Aura keyboard power state
*
* # Bits for newer 0x18c6, 0x19B6, 0x1a30, keyboard models
*
* | Byte 1 | Byte 2 | Byte 3 | Byte 4 | Label |
* |--------|---------|---------|---------|----------|
* |00000001| 00000000| 00000000| 00000000|boot_logo_|
* |00000010| 00000000| 00000000| 00000000|boot_keyb_|
* |00000100| 00000000| 00000000| 00000000|awake_logo|
* |00001000| 00000000| 00000000| 00000000|awake_keyb|
* |00010000| 00000000| 00000000| 00000000|sleep_logo|
* |00100000| 00000000| 00000000| 00000000|sleep_keyb|
* |01000000| 00000000| 00000000| 00000000|shut_logo_|
* |10000000| 00000000| 00000000| 00000000|shut_keyb_|
* |00000000| 00000010| 00000000| 00000000|boot_bar__|
* |00000000| 00000100| 00000000| 00000000|awake_bar_|
* |00000000| 00001000| 00000000| 00000000|sleep_bar_|
* |00000000| 00010000| 00000000| 00000000|shut_bar__|
* |00000000| 00000000| 00000001| 00000000|boot_lid__|
* |00000000| 00000000| 00000010| 00000000|awkae_lid_|
* |00000000| 00000000| 00000100| 00000000|sleep_lid_|
* |00000000| 00000000| 00001000| 00000000|shut_lid__|
* |00000000| 00000000| 00000000| 00000001|boot_rear_|
* |00000000| 00000000| 00000000| 00000010|awake_rear|
* |00000000| 00000000| 00000000| 00000100|sleep_rear|
* |00000000| 00000000| 00000000| 00001000|shut_rear_|
*/
export interface AuraPower {
keyboard: KbAuraPowerState;
logo: KbAuraPowerState;
lightbar: KbAuraPowerState;
lid: KbAuraPowerState;
rear_glow: KbAuraPowerState;
}
export enum AuraDevTuf {
Boot = "Boot",
Awake = "Awake",
Sleep = "Sleep",
Keyboard = "Keyboard",
}
/**
* # Bits for older 0x1866 keyboard model
*
* Keybord and Lightbar require Awake, Boot and Sleep apply to both
* Keybord and Lightbar regardless of if either are enabled (or Awake is
* enabled)
*
* | Byte 1 | Byte 2 | Byte 3 | function | hex |
* |------------|------------|------------|----------|----------|
* | 0000, 0000 | 0000, 0000 | 0000, 0010 | Awake | 00,00,02 |
* | 0000, 1000 | 0000, 0000 | 0000, 0000 | Keyboard | 08,00,00 |
* | 0000, 0100 | 0000, 0101 | 0000, 0000 | Lightbar | 04,05,00 |
* | 1100, 0011 | 0001, 0010 | 0000, 1001 | Boot/Sht | c3,12,09 |
* | 0011, 0000 | 0000, 1000 | 0000, 0100 | Sleep | 30,08,04 |
* | 1111, 1111 | 0001, 1111 | 0000, 1111 | all on | |
*/
export enum AuraDevRog1 {
Awake = "Awake",
Keyboard = "Keyboard",
Lightbar = "Lightbar",
Boot = "Boot",
Sleep = "Sleep",
}
/** This struct is intended as a helper to pass args to generic dbus interface */
export interface AuraPowerDev {
/**
* TUF laptops use a similar style of control to the older ROG devices but
* through WMI
*/
tuf: AuraDevTuf[];
/**
* Pre-0x19b6 devices use a different smaller scheme to the newer ROG
* devices
*/
old_rog: AuraDevRog1[];
/** ASUS standardised control scheme from 2020 onwards */
rog: AuraPower;
}
export enum LedBrightness {
Off = "Off",
Low = "Low",
Med = "Med",
High = "High",
}
export enum AuraDevice {
Tuf = "Tuf",
X1854 = "X1854",
X1869 = "X1869",
X1866 = "X1866",
X18c6 = "X18c6",
X19b6 = "X19b6",
X1a30 = "X1a30",
Unknown = "Unknown",
}

View File

@@ -1,58 +0,0 @@
/*
Generated by typeshare 1.6.0
*/
export type AnimeSupportedFunctions = boolean;
export interface ChargeSupportedFunctions {
charge_level_set: boolean;
}
export interface PlatformProfileFunctions {
platform_profile: boolean;
fan_curves: boolean;
}
export enum AdvancedAura {
None = "None",
Zoned = "Zoned",
PerKey = "PerKey",
}
export interface LedSupportedFunctions {
dev_id: AuraDevice;
brightness: boolean;
basic_modes: AuraModeNum[];
basic_zones: AuraZone[];
advanced_type: AdvancedAura;
power_zones: PowerZones[];
}
export interface RogBiosSupportedFunctions {
post_sound: boolean;
gpu_mux: boolean;
panel_overdrive: boolean;
dgpu_disable: boolean;
egpu_enable: boolean;
mini_led_mode: boolean;
}
export interface SupportedFunctions {
anime_ctrl: AnimeSupportedFunctions;
charge_ctrl: ChargeSupportedFunctions;
platform_profile: PlatformProfileFunctions;
keyboard_led: LedSupportedFunctions;
rog_bios_ctrl: RogBiosSupportedFunctions;
}
export enum GpuMode {
Discrete = "Discrete",
Optimus = "Optimus",
Integrated = "Integrated",
Egpu = "Egpu",
Vfio = "Vfio",
Ultimate = "Ultimate",
Error = "Error",
NotSupported = "NotSupported",
}

View File

@@ -1,35 +0,0 @@
/*
Generated by typeshare 1.6.0
*/
export enum FanCurvePU {
CPU = "CPU",
GPU = "GPU",
}
export interface CurveData {
fan: FanCurvePU;
pwm: [number, number, number, number, number, number, number, number];
temp: [number, number, number, number, number, number, number, number];
}
/** A `FanCurveSet` contains both CPU and GPU fan curve data */
export interface FanCurveSet {
enabled: boolean;
cpu: CurveData;
gpu: CurveData;
}
/** Main purpose of `FanCurves` is to enable restoring state on system boot */
export interface FanCurveProfiles {
balanced: FanCurveSet;
performance: FanCurveSet;
quiet: FanCurveSet;
}
export enum Profile {
Balanced = "Balanced",
Performance = "Performance",
Quiet = "Quiet",
}

View File

@@ -1,18 +1,18 @@
[package]
name = "config-traits"
license = "MPL-2.0"
authors = ["Luke D Jones <luke@ljones.dev>"]
edition = "2021"
license.workspace = true
version.workspace = true
readme.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
edition.workspace = true
[dependencies]
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
toml.workspace = true
ron.workspace = true
log.workspace = true
[dev-dependencies]
cargo-husky.workspace = true
cargo-husky.workspace = true

View File

@@ -3,10 +3,7 @@
//! updating them from previous versions where fields or names are changed in
//! some way.
//!
//! The end canonical file format is `.ron` as this supports rust types well,
//! and includes the ability to add commenting, and is less verbose than `json`.
//! Currently the crate will also try to parse from `json` and `toml` if the
//! `ron` parsing fails, then update to `ron` format.
//! The end canonical file format is `.ron` as this supports rust types well
use std::fs::{self, create_dir, File, OpenOptions};
use std::io::{Read, Write};
@@ -92,6 +89,7 @@ where
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(self.file_path())
.unwrap_or_else(|e| panic!("Could not open {:?} {e}", self.file_path()))
}
@@ -109,6 +107,20 @@ where
}
}
/// Open and parse the config file to self from ron format
fn read_new(&self) -> Option<Self> {
if let Ok(data) = fs::read_to_string(self.file_path()) {
if data.is_empty() {
warn!("File is empty {:?}", self.file_path());
} else if let Ok(data) = ron::from_str(&data) {
return Some(data);
} else {
warn!("Could not deserialise {:?}", self.file_path());
}
}
None
}
/// Write the config file data to pretty ron format
fn write(&self) {
let mut file = match File::create(self.file_path()) {
@@ -206,21 +218,9 @@ macro_rules! std_config_load {
if let Ok(data) = ron::from_str(&buf) {
self = data;
log::info!("Parsed RON for {:?}", std::any::type_name::<Self>());
} else if let Ok(data) = serde_json::from_str(&buf) {
self = data;
log::info!("Parsed JSON for {:?}", std::any::type_name::<Self>());
} else if let Ok(data) = toml::from_str(&buf) {
self = data;
log::info!("Parsed TOML for {:?}", std::any::type_name::<Self>());
} $(else if let Ok(data) = ron::from_str::<$generic>(&buf) {
} $(else if let Ok(data) = ron::from_str::<$generic>(&buf) {
self = data.into();
log::info!("New version failed, trying previous: Parsed RON for {:?}", std::any::type_name::<$generic>());
} else if let Ok(data) = serde_json::from_str::<$generic>(&buf) {
self = data.into();
log::info!("New version failed, trying previous: Parsed JSON for {:?}", std::any::type_name::<$generic>());
} else if let Ok(data) = toml::from_str::<$generic>(&buf) {
self = data.into();
log::info!("Newvious version failed, trying previous: Parsed TOML for {:?}", std::any::type_name::<$generic>());
})* else {
self.rename_file_old();
self = Self::new();

11
cpuctl/Cargo.toml Normal file
View File

@@ -0,0 +1,11 @@
[package]
name = "cpuctl"
license.workspace = true
version.workspace = true
readme.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
edition.workspace = true
[dependencies]

14
cpuctl/src/lib.rs Normal file
View File

@@ -0,0 +1,14 @@
pub fn add(left: usize, right: usize) -> usize {
left + right
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let result = add(2, 2);
assert_eq!(result, 4);
}
}

View File

@@ -1,6 +1,3 @@
#ACTION=="add|change", SUBSYSTEM=="input", ENV{ID_VENDOR_ID}=="0b05", ENV{ID_MODEL_ID}=="1[89][a-zA-Z0-9][a-zA-Z0-9]|193b", ENV{ID_TYPE}=="hid", TAG+="systemd", ENV{SYSTEMD_WANTS}="asusd.service"
#ACTION=="add|remove", SUBSYSTEM=="input", ENV{ID_VENDOR_ID}=="0b05", ENV{ID_MODEL_ID}=="1[89][a-zA-Z0-9][a-zA-Z0-9]|193b", RUN+="systemctl restart asusd.service"
ENV{DMI_VENDOR}="$attr{[dmi/id]sys_vendor}"
ENV{DMI_VENDOR}!="ASUSTeK COMPUTER INC.", GOTO="asusd_end"

View File

@@ -1,19 +1,18 @@
[Unit]
Description=ASUS Notebook Control
StartLimitInterval=200
StartLimitBurst=2
Before=multi-user.target
After=power-profiles-daemon.service
After=nvidia-powerd.service
StartLimitInterval=500
StartLimitBurst=5
After=nvidia-powerd.service systemd-udevd.service
[Service]
Environment=IS_SERVICE=1
Environment=RUST_LOG="info"
ExecStartPre=/bin/sleep 2
# required to prevent init issues with hid_asus and MCU
ExecStartPre=/bin/sleep 1
ExecStart=/usr/bin/asusd
Restart=on-failure
RestartSec=1
Type=dbus
BusName=org.asuslinux.Daemon
SELinuxContext=system_u:system_r:unconfined_t:s0
#SELinuxContext=system_u:object_r:modules_object_t:s0
#SELinuxContext=system_u:object_r:modules_object_t:s0

View File

@@ -1,25 +0,0 @@
/* eslint-env node */
module.exports = {
extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
root: true,
"rules": {
// enable additional rules
"indent": ["error", 4],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
// override configuration set by extending "eslint:recommended"
"no-empty": "warn",
"no-cond-assign": ["error", "always"],
// disable rules from base configurations
"for-direction": "off",
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/ban-ts-comment": "off"
}
};

View File

@@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View File

@@ -1,21 +0,0 @@
# asusctl
Requires `asusd` to be installed and running.
## build and install
```
npm install
npm run build && gnome-extensions install asusctl-gnome@asus-linux.org.zip --force
npm run build && gnome-extensions enable asusctl-gnome@asus-linux.org.zip
```
You will need to restart Gnome after installing or updating
## development
```
npm run build
gnome-extensions install asusctl-gnome@asus-linux.org.zip --force
MUTTER_DEBUG_DUMMY_MODE_SPECS=1366x768 dbus-run-session -- gnome-shell --nested --wayland
```

View File

@@ -1,65 +0,0 @@
const { build } = require("esbuild");
const fs = require("fs");
const path = require("path");
var exec = require('child_process').exec;
const AdmZip = require("adm-zip");
const metadata = require("./src/metadata.json");
build({
entryPoints: ['src/extension.ts'],
outdir: 'dist',
bundle: true,
// Do not remove the functions `enable()`, `disable()` and `init()`
treeShaking: false,
// firefox60 // Since GJS 1.53.90
// firefox68 // Since GJS 1.63.90
// firefox78 // Since GJS 1.65.90
// firefox91 // Since GJS 1.71.1
// firefox102 // Since GJS 1.73.2
target: "firefox78",
platform: "node",
// platform: "neutral",
// mainFields: ['main'],
// conditions: ['require', 'default'],
// format: 'cjs',
external: ['gi://*', 'system', 'gettext', 'cairo'],
}).then(() => {
const metaSrc = path.resolve(__dirname, "src/metadata.json");
const metaDist = path.resolve(__dirname, "dist/metadata.json");
const schemaSrc = path.resolve(__dirname, "schemas");
const schemaDist = path.resolve(__dirname, "dist/schemas");
const dbusXmlSrc = path.resolve(__dirname, "../../bindings/dbus-xml");
const dbusXmlDist = path.resolve(__dirname, "dist/resources/dbus");
const zipFilename = `${metadata.uuid}.zip`;
const zipDist = path.resolve(__dirname, zipFilename);
exec('glib-compile-schemas schemas/',
(error, stdout, stderr) => {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
});
fs.copyFileSync(metaSrc, metaDist);
fs.cpSync(schemaSrc, schemaDist, { recursive: true }, (err) => {
if (err) {
console.error(err);
}
});
fs.cpSync(dbusXmlSrc, dbusXmlDist, { recursive: true }, (err) => {
if (err) {
console.error(err);
}
});
const zip = new AdmZip();
zip.addLocalFolder(path.resolve(__dirname, "dist"));
zip.writeZip(zipDist);
console.log(`Build complete. Zip file: ${zipFilename}\n`);
console.log(`Install with: gnome-extensions install ${zipFilename}`)
console.log(`Update with: gnome-extensions install ${zipFilename} --force`)
console.log(`Enable with: gnome-extensions enable ${metadata.uuid} --user`)
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +0,0 @@
{
"name": "asusctl-gnome",
"version": "4.7.0",
"description": "asusctl-gnome a gnome extension exposing some of the base features of asusd in a helpful and easy to use way",
"main": "dist/extension.js",
"scripts": {
"clear": "rm -rf dist",
"build:app": "node esbuild.js",
"build": "yarn run clear && yarn run build:app",
"validate": "tsc --noEmit"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.60.1",
"@typescript-eslint/parser": "^5.60.1",
"adm-zip": "^0.5.10",
"esbuild": "^0.17.19",
"eslint": "^8.44.0",
"typescript": "^5.1.6"
},
"repository": {
"type": "git",
"url": "git+ssh://git@gitlab.com/asus-linux/asusctl.git"
},
"keywords": [
"gnome-shell",
"extension",
"asusctl",
"asus",
"rog",
"gnome",
"gjs",
"typescript"
],
"author": "Armas Spann, Marco Laux, Luke Jones",
"license": "MPL-2",
"bugs": {
"url": "https://gitlab.com/asus-linux/asusctl/issues"
},
"homepage": "https://gitlab.com/asus-linux/asusctl/desktop-extensions/gnome#readme"
}

View File

@@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<schemalist gettext-domain="AsusctlGnomeExtension">
<schema id="org.gnome.shell.extensions.asusctl-gnome" path="/org/gnome/shell/extensions/asusctl-gnome/" >
<key type="b" name="mini-led-enabled">
<default>false</default>
</key>
<key type="b" name="panel-od-enabled">
<default>false</default>
</key>
<key type="b" name="anime-power">
<default>false</default>
</key>
<key name="charge-level" type="u">
<range min="20" max="100"/>
<default>100</default>
</key>
<key type="s" name="primary-quickmenu-toggle">
<default>"mini-led"</default>
</key>
</schema>
</schemalist>

View File

@@ -1 +0,0 @@
../../../bindings/ts

View File

@@ -1,114 +0,0 @@
// REF: https://gjs.guide/extensions/development/creating.html
import { AnimeDbus } from "./modules/dbus/animatrix";
import { Power } from "./modules/dbus/power";
import { Supported } from "./modules/dbus/supported";
import { Platform } from "./modules/dbus/platform";
import { QuickPanelOd } from "./modules/quick_toggles/panel_od";
import { IndicateMiniLed } from "./modules/indicators/mini_led";
import { QuickMiniLed } from "./modules/quick_toggles/mini_led";
import { SliderChargeLevel } from "./modules/sliders/charge";
import { QuickAnimePower } from "./modules/quick_toggles/anime_power";
import { FeatureMenuToggle } from "./modules/quick_menus/laptop_features";
import { AuraDbus } from "./modules/dbus/aura";
import { AuraMenuToggle } from "./modules/quick_menus/aura";
class Extension {
private _indicateMiniLed: typeof IndicateMiniLed;
private _quickMiniLed: typeof QuickMiniLed;
private _quickPanelOd: typeof QuickPanelOd;
private _quickAnimePower: typeof QuickAnimePower;
private _featureMenuToggle: typeof FeatureMenuToggle;
private _auraModeMenuToggle: typeof AuraMenuToggle;
private _sliderCharge: typeof SliderChargeLevel;
public dbus_supported: Supported = new Supported;
public dbus_power: Power = new Power;
public dbus_aura: AuraDbus = new AuraDbus;
public dbus_anime: AnimeDbus = new AnimeDbus;
public dbus_platform: Platform = new Platform;
constructor() {
this._indicateMiniLed = null;
this._quickMiniLed = null;
this._quickPanelOd = null;
this._quickAnimePower = null;
this._sliderCharge = null;
this.dbus_supported.start();
this.dbus_aura.start();
this.dbus_platform.start();
this.dbus_power.start();
this.dbus_anime.start();
}
enable() {
if (this._featureMenuToggle == null) {
this._featureMenuToggle = new FeatureMenuToggle(this.dbus_supported, this.dbus_platform, this.dbus_anime);
}
if (this._auraModeMenuToggle == null) {
this._auraModeMenuToggle = new AuraMenuToggle(this.dbus_aura);
}
if (this.dbus_supported.supported.rog_bios_ctrl.mini_led_mode) {
// if (this._quickMiniLed == null) {
// this._quickMiniLed = new QuickMiniLed(this.dbus_platform);
// this.dbus_platform.notifyMiniLedSubscribers.push(this._quickMiniLed);
// }
if (this._indicateMiniLed == null) {
this._indicateMiniLed = new IndicateMiniLed(this.dbus_platform);
}
}
// if (this.dbus_supported.supported.rog_bios_ctrl.panel_overdrive) {
// if (this._quickPanelOd == null) {
// this._quickPanelOd = new QuickPanelOd(this.dbus_platform);
// this.dbus_platform.notifyPanelOdSubscribers.push(this._quickPanelOd);
// }
// }
// if (this.dbus_supported.supported.anime_ctrl) {
// if (this._quickAnimePower == null) {
// this._quickAnimePower = new QuickAnimePower(this._dbus_anime);
// }
// }
if (this.dbus_supported.supported.charge_ctrl.charge_level_set) {
if (this._sliderCharge == null) {
this._sliderCharge = new SliderChargeLevel(this.dbus_power);
}
}
}
disable() {
if (this._indicateMiniLed != null) {
this._indicateMiniLed.destroy();
this._indicateMiniLed = null;
}
if (this._quickMiniLed != null) {
this._quickMiniLed.destroy();
this._quickMiniLed = null;
}
if (this._quickPanelOd != null) {
this._quickPanelOd.destroy();
this._quickPanelOd = null;
}
if (this._quickAnimePower != null) {
this._quickAnimePower.destroy();
this._quickAnimePower = null;
}
if (this._sliderCharge != null) {
this._sliderCharge.destroy();
this._sliderCharge = null;
}
this.dbus_power.stop();
this.dbus_platform.stop();
this.dbus_anime.stop();
this.dbus_aura.stop();
this.dbus_supported.stop();
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function init() {
return new Extension();
}

View File

@@ -1,11 +0,0 @@
{
"name": "asusctl-gnome",
"description": "asusctl-gnome a gnome extension exposing some of the base features of asusd in a helpful and easy to use way",
"uuid": "asusctl-gnome@asus-linux.org",
"uuid-dev": "asusctl-gnome-dev@asus-linux.org",
"settings-schema": "org.gnome.shell.extensions.asusctl-gnome",
"version": "4.3.2",
"shell-version": [
"43", "44"
]
}

View File

@@ -1,119 +0,0 @@
import { DbusBase } from "./base";
import { DeviceState, AnimBooting, Brightness, AnimAwake, AnimSleeping, AnimShutdown } from "../../bindings/anime";
export class AnimeDbus extends DbusBase {
deviceState: DeviceState = {
display_enabled: false,
display_brightness: Brightness.Med,
builtin_anims_enabled: false,
builtin_anims: {
boot: AnimBooting.GlitchConstruction,
awake: AnimAwake.BinaryBannerScroll,
sleep: AnimSleeping.BannerSwipe,
shutdown: AnimShutdown.GlitchOut
},
};
// TODO: interface or something to enforce requirement of "sync()" method
public notifyAnimeStateSubscribers: any[] = [];
constructor() {
super("org-asuslinux-anime-4", "/org/asuslinux/Anime");
}
public setEnableDisplay(state: boolean | null) {
if (this.isRunning()) {
try {
// if null, toggle the current state
state = (state == null ? !this.deviceState.display_enabled : state);
if (this.deviceState.display_enabled !== state) {
this.deviceState.display_enabled = state;
}
return this.dbus_proxy.SetEnableDisplaySync(state);
} catch (e) {
//@ts-ignore
log("AniMe DBus set power failed!", e);
}
}
}
public setPowersaveAnim(state: boolean | null) {
if (this.isRunning()) {
try {
// if null, toggle the current state
state = (state == null ? !this.deviceState.builtin_anims_enabled : state);
if (this.deviceState.builtin_anims_enabled !== state) {
this.deviceState.builtin_anims_enabled = state;
}
return this.dbus_proxy.SetEnableBuiltinsSync(state);
} catch (e) {
//@ts-ignore
log("AniMe DBus set builtins failed!", e);
}
}
}
public setBrightness(brightness: Brightness) {
if (this.isRunning()) {
try {
if (this.deviceState.display_brightness !== brightness) {
this.deviceState.display_brightness = brightness;
}
return this.dbus_proxy.SetBrightnessSync(brightness);
} catch (e) {
//@ts-ignore
log("AniMe DBus set brightness failed!", e);
}
}
}
_parseData(data: any) {
if (data.length > 0) {
this.deviceState.display_enabled = data[0];
this.deviceState.display_brightness = Brightness[data[1] as Brightness];
this.deviceState.builtin_anims_enabled = data[2];
this.deviceState.builtin_anims.boot = AnimBooting[data[3][0] as AnimBooting];
this.deviceState.builtin_anims.awake = AnimAwake[data[3][1] as AnimAwake];
this.deviceState.builtin_anims.sleep = AnimSleeping[data[3][2] as AnimSleeping];
this.deviceState.builtin_anims.shutdown = AnimShutdown[data[3][2] as AnimShutdown];
}
}
public getDeviceState() {
if (this.isRunning()) {
try {
// janky shit going on with DeviceStateSync
this._parseData(this.dbus_proxy.DeviceStateSync());
} catch (e) {
//@ts-ignore
log("Failed to fetch DeviceState!", e);
}
}
return this.deviceState;
}
async start() {
await super.start();
this.getDeviceState();
this.dbus_proxy.connectSignal(
"NotifyDeviceState",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(proxy: any = null, name: string, data: string) => {
if (proxy) {
// idiot xml parsing mneans the get is not nested while this is
this._parseData(data[0]);
this.notifyAnimeStateSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
}
async stop() {
await super.stop();
}
}

View File

@@ -1,284 +0,0 @@
import { AuraDevRog1, AuraDevTuf, AuraDevice, AuraEffect, AuraModeNum, AuraPower, AuraPowerDev, AuraZone, Direction, PowerZones, Speed } from "../../bindings/aura";
import { DbusBase } from "./base";
export class AuraDbus extends DbusBase {
public device: AuraDevice = AuraDevice.Unknown;
public current_aura_mode: AuraModeNum = AuraModeNum.Static;
public aura_modes: Map<AuraModeNum, AuraEffect> = new Map;
public leds_powered: AuraPowerDev = {
tuf: [],
old_rog: [],
rog: {
keyboard: {
zone: PowerZones.Keyboard,
boot: false,
awake: false,
sleep: false,
shutdown: false
},
logo: {
zone: PowerZones.Logo,
boot: false,
awake: false,
sleep: false,
shutdown: false
},
lightbar: {
zone: PowerZones.Lightbar,
boot: false,
awake: false,
sleep: false,
shutdown: false
},
lid: {
zone: PowerZones.Lid,
boot: false,
awake: false,
sleep: false,
shutdown: false
},
rear_glow: {
zone: PowerZones.RearGlow,
boot: false,
awake: false,
sleep: false,
shutdown: false
},
}
};
// TODO: interface or something to enforce requirement of "sync()" method
public notifyAuraModeSubscribers: any[] = [];
public notifyAuraPowerSubscribers: any[] = [];
constructor() {
super("org-asuslinux-aura-4", "/org/asuslinux/Aura");
}
public getDevice() {
if (this.isRunning()) {
try {
this.device = AuraDevice[this.dbus_proxy.DeviceTypeSync() as AuraDevice];
//@ts-ignore
log("LED device: " + this.device);
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
_parsePowerStates(data: any[]) {
const power: AuraPowerDev = this.leds_powered;
power.tuf = data[0].map((value: string) => {
return AuraDevTuf[value as AuraDevTuf];
});
power.old_rog = data[1].map((value: string) => {
return AuraDevRog1[value as AuraDevRog1];
});
power.rog = {
keyboard: {
zone: PowerZones[data[2][0][0] as PowerZones],
boot: data[2][0][1],
awake: data[2][0][2],
sleep: data[2][0][3],
shutdown: data[2][0][4]
},
logo: {
zone: PowerZones[data[2][1][0] as PowerZones],
boot: data[2][1][1],
awake: data[2][1][2],
sleep: data[2][1][3],
shutdown: data[2][1][4]
},
lightbar: {
zone: PowerZones[data[2][2][0] as PowerZones],
boot: data[2][2][1],
awake: data[2][2][2],
sleep: data[2][2][3],
shutdown: data[2][2][4]
},
lid: {
zone: PowerZones[data[2][3][0] as PowerZones],
boot: data[2][3][1],
awake: data[2][3][2],
sleep: data[2][3][3],
shutdown: data[2][3][4]
},
rear_glow: {
zone: PowerZones[data[2][4][0] as PowerZones],
boot: data[2][4][1],
awake: data[2][4][2],
sleep: data[2][4][3],
shutdown: data[2][4][4]
}
};
return power;
}
public getLedPower() {
if (this.isRunning()) {
try {
const data = this.dbus_proxy.LedPowerSync();
this.leds_powered = this._parsePowerStates(data);
//@ts-ignore
log("LED power tuf: " + this.leds_powered.tuf);
//@ts-ignore
log("LED power x1866: " + this.leds_powered.old_rog);
//@ts-ignore
log("LED power x19b6: " + this.leds_powered.rog);
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
public getLedMode() {
if (this.isRunning()) {
try {
this.current_aura_mode = AuraModeNum[this.dbus_proxy.LedModeSync() as AuraModeNum];
//@ts-ignore
log("Current LED mode:", this.current_aura_mode);
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
public setLedMode(mode: AuraEffect) {
if (this.isRunning()) {
try {
this.dbus_proxy.SetLedModeSync([
mode.mode,
mode.zone,
[mode.colour1.r, mode.colour1.g, mode.colour1.b],
[mode.colour2.r, mode.colour2.g, mode.colour2.b],
mode.speed,
mode.direction]);
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
_parseAuraEffect(data: any[]) {
const aura: AuraEffect = {
mode: AuraModeNum[data[0] as AuraModeNum],
zone: AuraZone[data[1] as AuraZone],
colour1: {
r: parseInt(data[2][0]),
g: parseInt(data[2][1]),
b: parseInt(data[2][2]),
},
colour2: {
r: parseInt(data[3][0]),
g: parseInt(data[3][1]),
b: parseInt(data[3][2]),
},
speed: Speed[data[4] as Speed],
direction: Direction[data[5] as Direction],
};
return aura;
}
// Return a list of the available modes, and the current settings for each
public getLedModes() {
// {'Breathe': ('Breathe', 'None', (166, 0, 0), (0, 0, 0), 'Med', 'Right'),
// 'Comet': ('Comet', 'None', (166, 0, 0), (0, 0, 0), 'Med', 'Right'),
// 'Static': ('Static', 'None', (78, 0, 0), (0, 0, 0), 'Med', 'Right'),
// 'Strobe': ('Strobe', 'None', (166, 0, 0), (0, 0, 0), 'Med', 'Right')}
if (this.isRunning()) {
try {
const _data = this.dbus_proxy.LedModesSync();
for (const key in _data[0]) {
const data = _data[0][key];
const aura: AuraEffect = this._parseAuraEffect(data);
this.aura_modes.set(AuraModeNum[key as AuraModeNum], aura);
}
for (const [key, value] of this.aura_modes) {
//@ts-ignore
log(key, value.zone, value.colour1.r, value.speed, value.direction);
}
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
async start() {
try {
await super.start();
this.getDevice();
this.getLedPower();
this.getLedMode();
this.getLedModes();
//@ts-ignore
log("Current LED mode data:", this.aura_modes.get(this.current_aura_mode)?.speed);
this.dbus_proxy.connectSignal(
"NotifyLed",
(proxy: any = null, name: string, data: any) => {
if (proxy) {
const aura: AuraEffect = this._parseAuraEffect(data[0]);
this.current_aura_mode = aura.mode;
this.aura_modes.set(aura.mode, aura);
//@ts-ignore
log("LED data has changed to ", aura.mode, aura.zone, aura.colour1.r, aura.speed, aura.direction);
this.notifyAuraModeSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
this.dbus_proxy.connectSignal(
"NotifyPowerStates",
(proxy: any = null, name: string, data: any) => {
if (proxy) {
const power: AuraPowerDev = this._parsePowerStates(data[0]);
this.leds_powered = power;
switch (this.device) {
case AuraDevice.Tuf:
//@ts-ignore
log("LED power has changed to ", this.leds_powered.tuf);
break;
case AuraDevice.X1854:
case AuraDevice.X1869:
case AuraDevice.X18c6:
//@ts-ignore
log("LED power has changed to ", this.leds_powered.old_rog);
break;
case AuraDevice.X19b6:
case AuraDevice.X1a30:
//@ts-ignore
log("LED power has changed to ", this.leds_powered.rog);
break;
default:
break;
}
//@ts-ignore
log("LED power has changed to ", this.leds_powered.rog);
this.notifyAuraPowerSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
} catch (e) {
//@ts-ignore
log("Supported DBus initialization failed!", e);
}
}
async stop() {
await super.stop();
}
}

View File

@@ -1,52 +0,0 @@
declare const imports: any;
import * as Resources from "../resources";
const { Gio } = imports.gi;
export class DbusBase {
dbus_proxy: any = null; // type: Gio.DbusProxy
connected = false;
xml_resource = "";
dbus_path = "";
constructor(resource: string, dbus_path: string) {
this.xml_resource = resource;
this.dbus_path = dbus_path;
}
async start() {
//@ts-ignore
log(`Starting ${this.dbus_path} dbus module`);
try {
const xml = Resources.File.DBus(this.xml_resource);
this.dbus_proxy = new Gio.DBusProxy.makeProxyWrapper(xml)(
Gio.DBus.system,
"org.asuslinux.Daemon",
this.dbus_path,
);
this.connected = true;
//@ts-ignore
log(`${this.dbus_path} client started successfully.`);
} catch (e) {
//@ts-ignore
logError(`${this.xml_resource} dbus init failed!`, e);
}
}
async stop() {
//@ts-ignore
log(`Stopping ${this.xml_resource} dbus module`);
if (this.connected) {
this.dbus_proxy.destroy();
this.connected = false;
this.dbus_proxy = null;
}
}
isRunning(): boolean {
return this.connected;
}
}

View File

@@ -1,202 +0,0 @@
import * as bios from "../../bindings/platform";
import { DbusBase } from "./base";
// TODO: add callbacks for notifications
export class Platform extends DbusBase {
bios: bios.RogBiosSupportedFunctions = {
post_sound: false,
gpu_mux: false,
panel_overdrive: false,
dgpu_disable: false,
egpu_enable: false,
mini_led_mode: false
};
// TODO: interface or something to enforce requirement of "sync()" method
public notifyPanelOdSubscribers: any[] = [];
public notifyPostBootSoundSubscribers: any[] = [];
public notifyMiniLedSubscribers: any[] = [];
public notifyGpuMuxSubscribers: any[] = [];
constructor() {
super("org-asuslinux-platform-4", "/org/asuslinux/Platform");
}
public getPostBootSound() {
if (this.isRunning()) {
try {
this.bios.post_sound = this.dbus_proxy.PostBootSoundSync() == "true" ? true : false;
} catch (e) {
//@ts-ignore
log("Failed to get POST Boot Sound state!", e);
}
}
return this.bios.post_sound;
}
public setPostBootSound(state: boolean) {
if (this.isRunning()) {
try {
if (state !== this.bios.post_sound) {
this.bios.post_sound = state;
}
return this.dbus_proxy.SetPostBootSoundSync(state);
} catch (e) {
//@ts-ignore
log("Platform DBus set Post Boot Sound failed!", e);
}
}
}
public getGpuMuxMode() {
if (this.isRunning()) {
try {
this.bios.gpu_mux = this.dbus_proxy.GpuMuxModeSync() == "true" ? true : false;
} catch (e) {
//@ts-ignore
log("Failed to get MUX state!", e);
}
}
return this.bios.gpu_mux;
}
public setGpuMuxMode(state: boolean) {
if (this.isRunning()) {
try {
if (!state !== this.bios.gpu_mux) {
this.bios.gpu_mux = !state;
}
return this.dbus_proxy.SetGpuMuxModeSync(!state);
} catch (e) {
//@ts-ignore
log("Switching the MUX failed!", e);
}
}
}
public getPanelOd() {
if (this.isRunning()) {
try {
this.bios.panel_overdrive = this.dbus_proxy.PanelOdSync() == "true" ? true : false;
} catch (e) {
//@ts-ignore
log("Failed to get Overdrive state!", e);
}
}
return this.bios.panel_overdrive;
}
public setPanelOd(state: boolean) {
if (this.isRunning()) {
try {
if (state !== this.bios.panel_overdrive) {
this.bios.panel_overdrive = state;
}
return this.dbus_proxy.SetPanelOdSync(state);
} catch (e) {
//@ts-ignore
log("Overdrive DBus set overdrive state failed!", e);
}
}
}
public getMiniLedMode() {
if (this.isRunning()) {
try {
this.bios.mini_led_mode = this.dbus_proxy.MiniLedModeSync() == "true" ? true : false;
} catch (e) {
//@ts-ignore
log("Failed to get Overdrive state!", e);
}
}
return this.bios.mini_led_mode;
}
public setMiniLedMode(state: boolean) {
if (this.isRunning()) {
try {
if (state !== this.bios.mini_led_mode) {
this.bios.mini_led_mode = state;
}
return this.dbus_proxy.SetMiniLedModeSync(state);
} catch (e) {
//@ts-ignore
log("setMiniLedMode failed!", e);
}
}
}
async start() {
try {
await super.start();
this.getPostBootSound();
this.dbus_proxy.connectSignal(
"NotifyPostBootSound",
(proxy: any = null, _name: string, data: boolean) => {
if (proxy) {
//@ts-ignore
log(`PostBootSound changed to ${data}`);
this.notifyPostBootSoundSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
this.getPanelOd();
this.dbus_proxy.connectSignal(
"NotifyPanelOd",
(proxy: any = null, _name: string, data: boolean) => {
if (proxy) {
//@ts-ignore
log(`NotifyPanelOd has changed to ${data}.`);
this.notifyPanelOdSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
this.getMiniLedMode();
this.dbus_proxy.connectSignal(
"NotifyMiniLedMode",
(proxy: any = null, _name: string, data: boolean) => {
if (proxy) {
//@ts-ignore
log(`MiniLedMode has changed to ${data}.`);
this.notifyMiniLedSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
this.getGpuMuxMode();
this.dbus_proxy.connectSignal(
"NotifyGpuMuxMode",
(proxy: any = null, _name: string, data: boolean) => {
if (proxy) {
//@ts-ignore
log(`MUX has changed to ${data}.`);
this.notifyGpuMuxSubscribers.forEach(sub => {
sub.sync();
});
}
}
);
} catch (e) {
//@ts-ignore
log("Platform DBus init failed!", e);
}
}
async stop() {
await super.stop();
this.bios.post_sound = false;
this.bios.panel_overdrive = false;
this.bios.mini_led_mode = false;
this.bios.gpu_mux = false;
}
}

View File

@@ -1,99 +0,0 @@
import { DbusBase } from "./base";
// function getMethods(obj: { [x: string]: { toString: () => string; }; }) {
// var result = [];
// for (var id in obj) {
// try {
// if (typeof(obj[id]) == "function") {
// result.push(id + ": " + obj[id].toString());
// }
// } catch (err) {
// result.push(id + ": inaccessible");
// }
// }
// return result;
// }
export class Power extends DbusBase {
chargeLimit = 100;
mainsOnline = false;
constructor() {
super("org-asuslinux-power-4", "/org/asuslinux/Power");
}
public getChargingLimit() {
if (this.isRunning()) {
try {
this.chargeLimit = this.dbus_proxy.ChargeControlEndThresholdSync();
} catch (e) {
//@ts-ignore
log("Failed to fetch Charging Limit!", e);
}
}
return this.chargeLimit;
}
public setChargingLimit(limit: number) {
if (this.isRunning()) {
try {
if (limit > 0 && this.chargeLimit !== limit) {
// update state
this.chargeLimit = limit;
}
return this.dbus_proxy.SetChargeControlEndThresholdSync(limit);
} catch (e) {
//@ts-ignore
log("Profile DBus set power profile failed!", e);
}
}
}
public getMainsOnline() {
if (this.isRunning()) {
try {
this.mainsOnline = this.dbus_proxy.MainsOnlineSync();
} catch (e) {
//@ts-ignore
log("Failed to fetch MainsLonline!", e);
}
}
return this.mainsOnline;
}
async start() {
try {
await super.start();
this.getChargingLimit();
this.dbus_proxy.connectSignal(
"NotifyChargeControlEndThreshold",
(proxy: any = null, name: string, data: string) => {
if (proxy) {
//@ts-ignore
log(`Charging Limit has changed to ${data}% (${name}).`);
this.chargeLimit = parseInt(data);
}
}
);
this.dbus_proxy.connectSignal(
"NotifyMainsOnline",
(proxy: any = null, name: string, data: string) => {
if (proxy) {
//@ts-ignore
log(`NotifyMainsOnline has changed to ${data}% (${name}).`);
this.mainsOnline = parseInt(data) == 1 ? true : false;
}
}
);
} catch (e) {
//@ts-ignore
log("Charging Limit DBus initialization failed!", e);
}
}
async stop() {
await super.stop();
}
}

View File

@@ -1,106 +0,0 @@
import { SupportedFunctions, AdvancedAura } from "../../bindings/platform";
import { AuraDevice, AuraModeNum, AuraZone, PowerZones } from "../../bindings/aura";
import { DbusBase } from "./base";
export class Supported extends DbusBase {
// False,
// (True,),
// (True, True),
// ('X19b6',
// True,
// ['Static',
// 'Breathe',
// 'Strobe',
// 'Rainbow',
// 'Star',
// 'Rain',
// 'Highlight',
// 'Laser',
// 'Ripple',
// 'Pulse',
// 'Comet',
// 'Flash'],
// [],
// 'PerKey',
// ['Keyboard', 'Lightbar', 'Logo', 'RearGlow']),
// (False, True, True, True, False, True)
supported: SupportedFunctions = {
anime_ctrl: false,
charge_ctrl: {
charge_level_set: false
},
platform_profile: {
platform_profile: false,
fan_curves: false
},
keyboard_led: {
dev_id: AuraDevice.Unknown,
brightness: false,
basic_modes: [],
basic_zones: [],
advanced_type: AdvancedAura.None
},
rog_bios_ctrl: {
post_sound: false,
gpu_mux: false,
panel_overdrive: false,
dgpu_disable: false,
egpu_enable: false,
mini_led_mode: false
}
};
constructor() {
super("org-asuslinux-supported-4", "/org/asuslinux/Supported");
}
public getSupported() {
if (this.isRunning()) {
try {
const _data = this.dbus_proxy.SupportedFunctionsSync();
this.supported.anime_ctrl = _data[0];
this.supported.charge_ctrl.charge_level_set = _data[1];
this.supported.platform_profile.platform_profile = _data[2][0];
this.supported.platform_profile.fan_curves = _data[2][1];
this.supported.keyboard_led.dev_id = AuraDevice[_data[3][0] as AuraDevice];
this.supported.keyboard_led.brightness = _data[3][1];
this.supported.keyboard_led.basic_modes = _data[3][2].map(function (value: string) {
return AuraModeNum[value as AuraModeNum];
});
this.supported.keyboard_led.basic_zones = _data[3][3].map(function (value: string) {
return AuraZone[value as AuraZone];
});
this.supported.keyboard_led.advanced_type = AdvancedAura[_data[3][4] as AdvancedAura];
this.supported.keyboard_led.power_zones = _data[3][5].map(function (value: string) {
return PowerZones[value as PowerZones];
});
this.supported.rog_bios_ctrl.post_sound = _data[4][0];
this.supported.rog_bios_ctrl.gpu_mux = _data[4][1];
this.supported.rog_bios_ctrl.panel_overdrive = _data[4][2];
this.supported.rog_bios_ctrl.dgpu_disable = _data[4][3];
this.supported.rog_bios_ctrl.egpu_enable = _data[4][4];
this.supported.rog_bios_ctrl.mini_led_mode = _data[4][5];
} catch (e) {
//@ts-ignore
log("Failed to fetch supported functionalities", e);
}
}
}
async start() {
try {
await super.start();
this.getSupported();
} catch (e) {
//@ts-ignore
log("Supported DBus initialization failed!", e);
}
}
async stop() {
await super.stop();
}
}

View File

@@ -1,15 +0,0 @@
declare const imports: any;
const { QuickToggle } = imports.ui.quickSettings;
const QuickSettingsMenu = imports.ui.main.panel.statusArea.quickSettings;
export function addQuickSettingsItems(items: [typeof QuickToggle], width = 1) {
// Add the items with the built-in function
QuickSettingsMenu._addItems(items, width);
// Ensure the tile(s) are above the background apps menu
for (const item of items) {
QuickSettingsMenu.menu._grid.set_child_below_sibling(item,
QuickSettingsMenu._backgroundApps.quickSettingsItems[0]);
}
}

View File

@@ -1,28 +0,0 @@
declare const imports: any;
// REF: https://gjs.guide/extensions/development/creating.html
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const { SystemIndicator } = imports.ui.quickSettings;
const QuickSettingsMenu = imports.ui.main.panel.statusArea.quickSettings;
export const IndicateMiniLed = GObject.registerClass(
class IndicateMiniLed extends SystemIndicator {
constructor() {
super();
// Create the icon for the indicator
this._indicator = this._addIndicator();
this._indicator.icon_name = "selection-mode-symbolic";
// Showing the indicator when the feature is enabled
this._settings = ExtensionUtils.getSettings();
this._settings.bind("mini-led-enabled",
this._indicator, "visible",
Gio.SettingsBindFlags.DEFAULT);
// Add the indicator to the panel and the toggle to the menu
QuickSettingsMenu._indicators.add_child(this);
}
});

View File

@@ -1,86 +0,0 @@
declare const imports: any;
import { AnimeDbus } from "../dbus/animatrix";
const { GObject } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const PopupMenu = imports.ui.popupMenu;
export const MenuToggleAnimePower = GObject.registerClass(
class MenuToggleAnimePower extends PopupMenu.PopupSwitchMenuItem {
private _dbus_anime: AnimeDbus;
public toggle_callback = () => {};
constructor(dbus_anime: AnimeDbus) {
super(
"AniMatrix Display Power", dbus_anime.deviceState.display_enabled
);
this._dbus_anime = dbus_anime;
this.label = "AniMatrix Display Power";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"toggled", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this.sync();
}
_toggleMode() {
this._dbus_anime.getDeviceState();
if (this.state !== this._dbus_anime.deviceState.display_enabled)
this._dbus_anime.setEnableDisplay(this.state);
this.toggle_callback();
}
sync() {
this._dbus_anime.getDeviceState();
const checked = this._dbus_anime.deviceState.display_enabled;
this.setToggleState(checked);
}
});
export const MenuToggleAnimeBuiltins = GObject.registerClass(
class MenuToggleAnimeBuiltins extends PopupMenu.PopupSwitchMenuItem {
private _dbus_anime: AnimeDbus;
public toggle_callback = () => {};
constructor(dbus_anime: AnimeDbus) {
super(
"AniMatrix Powersave Animation", dbus_anime.deviceState.builtin_anims_enabled
);
this._dbus_anime = dbus_anime;
this.label = "AniMatrix Powersave Animation";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"toggled", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this.sync();
}
_toggleMode() {
this._dbus_anime.getDeviceState();
if (this.state !== this._dbus_anime.deviceState.builtin_anims_enabled)
this._dbus_anime.setPowersaveAnim(this.state);
this.toggle_callback();
}
sync() {
this._dbus_anime.getDeviceState();
const checked = this._dbus_anime.deviceState.display_enabled;
this.setToggleState(checked);
}
});

View File

@@ -1,46 +0,0 @@
declare const imports: any;
import { Platform } from "../dbus/platform";
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const PopupMenu = imports.ui.popupMenu;
export const MenuToggleMiniLed = GObject.registerClass(
class MenuToggleMiniLed extends PopupMenu.PopupSwitchMenuItem {
private _dbus_platform: Platform;
public toggle_callback = () => {};
constructor(dbus_platform: Platform) {
super("MiniLED", dbus_platform.bios.mini_led_mode);
this._dbus_platform = dbus_platform;
this.label = "MiniLED";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"toggled", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this.sync();
}
_toggleMode() {
this._dbus_platform.getMiniLedMode();
const state = this._dbus_platform.bios.mini_led_mode;
if (this.state !== state)
this._dbus_platform.setMiniLedMode(this.state);
this.toggle_callback();
}
sync() {
this._dbus_platform.getMiniLedMode();
const toggled = this._dbus_platform.bios.mini_led_mode;
this.setToggleState(toggled);
}
});

View File

@@ -1,46 +0,0 @@
declare const imports: any;
import { Platform } from "../dbus/platform";
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const PopupMenu = imports.ui.popupMenu;
export const MenuTogglePanelOd = GObject.registerClass(
class MenuTogglePanelOd extends PopupMenu.PopupSwitchMenuItem {
private _dbus_platform: Platform;
public toggle_callback = () => {};
constructor(dbus_platform: Platform) {
super("Panel Overdrive", dbus_platform.bios.panel_overdrive);
this._dbus_platform = dbus_platform;
this.label = "Panel Overdrive";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"toggled", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this.sync();
}
_toggleMode() {
this._dbus_platform.getPanelOd();
const state = this._dbus_platform.bios.panel_overdrive;
if (this.state !== state)
this._dbus_platform.setPanelOd(this.state);
this.toggle_callback();
}
sync() {
this._dbus_platform.getPanelOd();
const toggled = this._dbus_platform.bios.panel_overdrive;
this.setToggleState(toggled);
}
});

View File

@@ -1,86 +0,0 @@
declare const imports: any;
// REF: https://gjs.guide/extensions/development/creating.html
import { addQuickSettingsItems } from "../helpers";
import { AuraDbus } from "../dbus/aura";
import { AuraEffect, AuraModeNum } from "../../bindings/aura";
const { GObject } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
// const Me = ExtensionUtils.getCurrentExtension();
// const Main = imports.ui.main;
const PopupMenu = imports.ui.popupMenu;
const QuickSettings = imports.ui.quickSettings;
export const AuraMenuToggle = GObject.registerClass(
class AuraMenuToggle extends QuickSettings.QuickMenuToggle {
private _dbus_aura: AuraDbus;
private _last_mode: AuraModeNum = AuraModeNum.Static;
constructor(dbus_aura: AuraDbus) {
super({
title: "Aura Modes",
iconName: "selection-mode-symbolic",
toggleMode: true,
});
this._dbus_aura = dbus_aura;
this.connectObject(
"destroy", () => this._settings.run_dispose(),
this);
this.menu.setHeader("selection-mode-symbolic", this._dbus_aura.current_aura_mode);
this._settings = ExtensionUtils.getSettings();
this._itemsSection = new PopupMenu.PopupMenuSection();
this._dbus_aura.aura_modes.forEach((mode, key) => {
this._itemsSection.addAction(key, () => {
this._dbus_aura.setLedMode(mode);
this.sync();
}, "");
});
this.menu.addMenuItem(this._itemsSection);
// Add an entry-point for more settings
// this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// const settingsItem = this.menu.addAction("More Settings",
// () => ExtensionUtils.openPrefs());
// // Ensure the settings are unavailable when the screen is locked
// settingsItem.visible = Main.sessionMode.allowSettings;
// this.menu._settingsActions[Me.uuid] = settingsItem;
this.connectObject(
"clicked", () => {
let mode: AuraEffect | undefined;
if (this._dbus_aura.current_aura_mode == AuraModeNum.Static) {
mode = this._dbus_aura.aura_modes.get(this._last_mode);
} else {
mode = this._dbus_aura.aura_modes.get(AuraModeNum.Static);
}
if (mode != undefined) {
this._dbus_aura.setLedMode(mode);
this.sync();
}
},
this);
this._dbus_aura.notifyAuraModeSubscribers.push(this);
this.sync();
addQuickSettingsItems([this]);
}
sync() {
const checked = this._dbus_aura.current_aura_mode != AuraModeNum.Static;
this.title = this._dbus_aura.current_aura_mode;
if (this._last_mode != this._dbus_aura.current_aura_mode && this._dbus_aura.current_aura_mode != AuraModeNum.Static) {
this._last_mode = this._dbus_aura.current_aura_mode;
}
if (this.checked !== checked)
this.set({ checked });
}
});

View File

@@ -1,179 +0,0 @@
declare const imports: any;
// REF: https://gjs.guide/extensions/development/creating.html
import { AnimeDbus } from "../dbus/animatrix";
import { Supported } from "../dbus/supported";
import { Platform } from "../dbus/platform";
import { addQuickSettingsItems } from "../helpers";
import { MenuToggleAnimeBuiltins, MenuToggleAnimePower } from "../menu_toggles/anime";
import { MenuTogglePanelOd } from "../menu_toggles/panel_od";
import { MenuToggleMiniLed } from "../menu_toggles/mini_led";
const { GObject } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
// const Me = ExtensionUtils.getCurrentExtension();
// const Main = imports.ui.main;
const PopupMenu = imports.ui.popupMenu;
const QuickSettings = imports.ui.quickSettings;
export const FeatureMenuToggle = GObject.registerClass(
class FeatureMenuToggle extends QuickSettings.QuickMenuToggle {
private _dbus_supported: Supported;
private _dbus_platform: Platform;
private _dbus_anime: AnimeDbus;
public miniLed: typeof MenuToggleMiniLed;
public panelOd: typeof MenuTogglePanelOd;
public animeDisplayPower: typeof MenuToggleAnimePower;
public animePowersaveAnim: typeof MenuToggleAnimeBuiltins;
private primary = "mini-led";
constructor(dbus_supported: Supported, dbus_platform: Platform, dbus_anime: AnimeDbus) {
super({
title: "Laptop",
iconName: "selection-mode-symbolic",
toggleMode: true,
});
this._dbus_supported = dbus_supported;
this._dbus_platform = dbus_platform;
this._dbus_anime = dbus_anime;
this.menu.setHeader("selection-mode-symbolic", "Laptop features");
this._settings = ExtensionUtils.getSettings();
this.primary = this._settings.get_string("primary-quickmenu-toggle");
// TODO: temporary block
if (this.primary == "mini-led" && !this._dbus_supported.supported.rog_bios_ctrl.mini_led_mode) {
this.primary = "panel-od";
} else if (this.primary == "panel-od" && !this._dbus_supported.supported.rog_bios_ctrl.panel_overdrive) {
this.primary = "anime-power";
} else if (this.primary == "anime-power" && !this._dbus_supported.supported.anime_ctrl) {
this.primary = "mini-led";
} else if (this.primary.length == 0) {
this.primary = "panel-od";
}
this.connectObject(
"destroy", () => this._settings.run_dispose(),
this);
this._settings.connect('changed::primary-quickmenu-toggle',
this.sync);
this._settings.set_string("primary-quickmenu-toggle", this.primary);
this._itemsSection = new PopupMenu.PopupMenuSection();
if (this._dbus_supported.supported.rog_bios_ctrl.mini_led_mode) {
if (this.miniLed == null) {
this.miniLed = new MenuToggleMiniLed(this._dbus_platform);
this._dbus_platform.notifyMiniLedSubscribers.push(this.miniLed);
this._itemsSection.addMenuItem(this.miniLed);
this._dbus_platform.notifyMiniLedSubscribers.push(this);
this.miniLed.toggle_callback = () => {
this.primary = "mini-led";
this.sync();
}
}
}
if (this._dbus_supported.supported.rog_bios_ctrl.panel_overdrive) {
if (this.panelOd == null) {
this.panelOd = new MenuTogglePanelOd(this._dbus_platform);
this._dbus_platform.notifyPanelOdSubscribers.push(this.panelOd);
this._itemsSection.addMenuItem(this.panelOd);
this._dbus_platform.notifyPanelOdSubscribers.push(this);
this.panelOd.toggle_callback = () => {
this.primary = "panel-od";
this.sync();
}
}
}
if (this._dbus_supported.supported.anime_ctrl) {
if (this.animeDisplayPower == null) {
this.animeDisplayPower = new MenuToggleAnimePower(this._dbus_anime);
this._dbus_anime.notifyAnimeStateSubscribers.push(this.animeDisplayPower);
this._itemsSection.addMenuItem(this.animeDisplayPower);
this._dbus_anime.notifyAnimeStateSubscribers.push(this);
this.animeDisplayPower.toggle_callback = () => {
this.primary = "anime-power";
this.sync();
}
}
if (this.animePowersaveAnim == null) {
this.animePowersaveAnim = new MenuToggleAnimeBuiltins(this._dbus_anime);
this._dbus_anime.notifyAnimeStateSubscribers.push(this.animePowersaveAnim);
this._itemsSection.addMenuItem(this.animePowersaveAnim);
}
}
this.connectObject(
"clicked", () => {
this._toggle();
},
this);
this.menu.addMenuItem(this._itemsSection);
// // Add an entry-point for more settings
// this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// const settingsItem = this.menu.addAction("More Settings",
// () => ExtensionUtils.openPrefs());
// // Ensure the settings are unavailable when the screen is locked
// settingsItem.visible = Main.sessionMode.allowSettings;
// this.menu._settingsActions[Me.uuid] = settingsItem;
this.sync();
addQuickSettingsItems([this]);
}
_toggle() {
if (this.primary == "mini-led" && this.miniLed != null) {
this._dbus_platform.getMiniLedMode();
const checked = this._dbus_platform.bios.mini_led_mode;
if (this.checked !== checked)
this._dbus_platform.setMiniLedMode(this.checked);
}
if (this.primary == "panel-od" && this.panelOd != null) {
this._dbus_platform.getPanelOd();
const checked = this._dbus_platform.bios.panel_overdrive;
if (this.checked !== checked)
this._dbus_platform.setPanelOd(this.checked);
}
if (this.primary == "anime-power" && this.animeDisplayPower != null) {
this._dbus_anime.getDeviceState();
const checked = this._dbus_anime.deviceState.display_enabled;
if (this.checked !== checked)
this._dbus_anime.setEnableDisplay(this.checked);
}
}
sync() {
let checked = false;
if (this.primary == "mini-led" && this.miniLed != null) {
this.title = this.miniLed.label;
checked = this._dbus_platform.bios.mini_led_mode;
}
if (this.primary == "panel-od" && this.panelOd != null) {
this.title = this.panelOd.label;
checked = this._dbus_platform.bios.panel_overdrive;
}
if (this.primary == "anime-power" && this.animeDisplayPower != null) {
this.title = this.animeDisplayPower.label;
checked = this._dbus_anime.deviceState.display_enabled;
}
// if (this.animePowersaveAnim != null) {
// }
if (this.checked !== checked)
this.set({ checked });
}
});

View File

@@ -1,56 +0,0 @@
declare const imports: any;
import { AnimeDbus } from "../dbus/animatrix";
import { addQuickSettingsItems } from "../helpers";
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const { QuickToggle } = imports.ui.quickSettings;
export const QuickAnimePower = GObject.registerClass(
class QuickAnimePower extends QuickToggle {
private _dbus_anime: AnimeDbus;
constructor(dbus_anime: AnimeDbus) {
super({
title: "AniMatrix Power",
iconName: "selection-mode-symbolic",
toggleMode: true,
});
this._dbus_anime = dbus_anime;
this.label = "AniMatrix Power";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"clicked", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this._settings.bind("anime-power",
this, "checked",
Gio.SettingsBindFlags.DEFAULT);
this.sync();
addQuickSettingsItems([this]);
}
_toggleMode() {
this._dbus_anime.getDeviceState();
const checked = this._dbus_anime.deviceState.display_enabled;
if (this.checked !== checked)
this._dbus_anime.setEnableDisplay(this.checked);
}
sync() {
this._dbus_anime.getDeviceState();
const checked = this._dbus_anime.deviceState.display_enabled;
if (this.checked !== checked)
this.set({ checked });
}
});

View File

@@ -1,54 +0,0 @@
declare const imports: any;
import { Platform } from "../dbus/platform";
import { addQuickSettingsItems } from "../helpers";
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const { QuickToggle } = imports.ui.quickSettings;
export const QuickMiniLed = GObject.registerClass(
class QuickMiniLed extends QuickToggle {
private _dbus_platform: Platform;
constructor(dbus_platform: Platform) {
super({
title: "MiniLED",
iconName: "selection-mode-symbolic",
toggleMode: true,
});
this._dbus_platform = dbus_platform;
this.label = "MiniLED";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"clicked", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this._settings.bind("mini-led-enabled",
this, "checked",
Gio.SettingsBindFlags.DEFAULT);
this.sync();
addQuickSettingsItems([this]);
}
_toggleMode() {
const checked = this._dbus_platform.getMiniLedMode();
if (this.checked !== checked)
this._dbus_platform.setMiniLedMode(this.checked);
}
sync() {
const checked = this._dbus_platform.getMiniLedMode();
if (this.checked !== checked)
this.set({ checked });
}
});

View File

@@ -1,54 +0,0 @@
declare const imports: any;
import { Platform } from "../dbus/platform";
import { addQuickSettingsItems } from "../helpers";
const { GObject, Gio } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const { QuickToggle } = imports.ui.quickSettings;
export const QuickPanelOd = GObject.registerClass(
class QuickPanelOd extends QuickToggle {
private _dbus_platform: Platform;
constructor(dbus_platform: Platform) {
super({
title: "Panel Overdrive",
iconName: "selection-mode-symbolic",
toggleMode: true,
});
this._dbus_platform = dbus_platform;
this.label = "Panel Overdrive";
this._settings = ExtensionUtils.getSettings();
this.connectObject(
"destroy", () => this._settings.run_dispose(),
"clicked", () => this._toggleMode(),
this);
this.connect("destroy", () => {
this.destroy();
});
this._settings.bind("panel-od-enabled",
this, "checked",
Gio.SettingsBindFlags.DEFAULT);
this.sync();
addQuickSettingsItems([this]);
}
_toggleMode() {
const checked = this._dbus_platform.getPanelOd();
if (this.checked !== checked)
this._dbus_platform.setPanelOd(this.checked);
}
sync() {
const checked = this._dbus_platform.getPanelOd();
if (this.checked !== checked)
this.set({ checked });
}
});

View File

@@ -1,20 +0,0 @@
declare const imports: any;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const GLib = imports.gi.GLib;
export class File {
public static DBus(name: string) {
const file = `${Me.path}/resources/dbus/${name}.xml`;
try {
const [_ok, bytes] = GLib.file_get_contents(file);
if (!_ok)
//@ts-ignore
log(`Couldn't read contents of "${file}"`);
return _ok ? imports.byteArray.toString(bytes) : null;
} catch (e) {
//@ts-ignore
log(`Failed to load "${file}"`, e);
}
}
}

View File

@@ -1,60 +0,0 @@
import { Power } from "../dbus/power";
import { addQuickSettingsItems } from "../helpers";
declare const imports: any;
const { GObject } = imports.gi;
const ExtensionUtils = imports.misc.extensionUtils;
const QuickSettings = imports.ui.quickSettings;
export const SliderChargeLevel = GObject.registerClass(
class SliderChargeLevel extends QuickSettings.QuickSlider {
private _dbus_power: Power;
constructor(dbus_power: Power) {
super({
iconName: "selection-mode-symbolic",
});
this._dbus_power = dbus_power;
this._sliderChangedId = this.slider.connect("drag-end",
this._onSliderChanged.bind(this));
// Binding the slider to a GSettings key
this._settings = ExtensionUtils.getSettings();
this._settings.connect("changed::charge-level",
this._onSettingsChanged.bind(this));
// Set an accessible name for the slider
this.slider.accessible_name = "Charge level";
this._sync();
this._onSettingsChanged();
addQuickSettingsItems([this], 2);
}
_onSettingsChanged() {
// Prevent the slider from emitting a change signal while being updated
this.slider.block_signal_handler(this._sliderChangedId);
this.slider.value = this._settings.get_uint("charge-level") / 100.0;
this.slider.unblock_signal_handler(this._sliderChangedId);
}
_onSliderChanged() {
// Assuming our GSettings holds values between 0..100, adjust for the
// slider taking values between 0..1
const percent = Math.floor(this.slider.value * 100);
const stored = Math.floor(this._settings.get_uint("charge-level") / 100.0);
if (this.slider.value !== stored)
this._dbus_power.setChargingLimit(percent);
this._settings.set_uint("charge-level", percent);
}
_sync() {
const value = this._dbus_power.getChargingLimit();
if (this.slider.value !== value / 100)
this._settings.set_uint("charge-level", value);
}
});

Some files were not shown because too many files have changed in this diff Show More