Compare commits
221 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c14768182c | ||
|
|
ef7e2135bf | ||
|
|
2b58e259de | ||
|
|
ba03e8feb8 | ||
|
|
7771c6b8da | ||
|
|
04c9285ee6 | ||
|
|
bf4141e4b8 | ||
|
|
233315f668 | ||
|
|
8332fb12f1 | ||
|
|
594e69f9b7 | ||
|
|
0aac0ce495 | ||
|
|
e24b4858a4 | ||
|
|
cf2b459e48 | ||
|
|
895179fdad | ||
|
|
fe3e8792eb | ||
|
|
1916641e2e | ||
|
|
3ea0737be9 | ||
|
|
c67373a830 | ||
|
|
41cbf4d353 | ||
|
|
7a4c14f7b8 | ||
|
|
f52a4d464a | ||
|
|
aa71592a31 | ||
|
|
dc6e8f8dcb | ||
|
|
1a4836246f | ||
|
|
ab80b0742f | ||
|
|
6926aeed20 | ||
|
|
f95e42e4b9 | ||
|
|
82bee6b86e | ||
|
|
bd9bc8bcff | ||
|
|
8a6d364304 | ||
|
|
64d99a3e05 | ||
|
|
59f54b76f6 | ||
|
|
6f36d91281 | ||
|
|
e9f1fa01fc | ||
|
|
0d3a5d266b | ||
|
|
cc28cee8bd | ||
|
|
6ebf0c2bb2 | ||
|
|
77c658c94e | ||
|
|
df64a51372 | ||
|
|
0657c6cc74 | ||
|
|
f116905e85 | ||
|
|
e515741efa | ||
|
|
d516abdc92 | ||
|
|
ece565de1c | ||
|
|
eb83d1a835 | ||
|
|
7d0f15d738 | ||
|
|
8010da0891 | ||
|
|
aa500c35c4 | ||
|
|
2af33a0416 | ||
|
|
9b4ed6eb62 | ||
|
|
47c1ca9fe4 | ||
|
|
3cd624daf0 | ||
|
|
fa16864a3e | ||
|
|
bfc31b06d5 | ||
|
|
d854f7da1b | ||
|
|
6d746b21a5 | ||
|
|
226c083a51 | ||
|
|
de59d00949 | ||
|
|
7ff01f12e9 | ||
|
|
fbc248177a | ||
|
|
fc3d7653f5 | ||
|
|
2dc70ea6af | ||
|
|
01345b28a5 | ||
|
|
4eeacea832 | ||
|
|
6bf0fdd117 | ||
|
|
7fcde7df17 | ||
|
|
543b0b817f | ||
|
|
5a7d31fdf6 | ||
|
|
301c532b65 | ||
|
|
df7ae4d014 | ||
|
|
96ceef1bdb | ||
|
|
bc72b93625 | ||
|
|
03b338bdfa | ||
|
|
7a51cd1c70 | ||
|
|
0449a4b06b | ||
|
|
bc46fa2b1e | ||
|
|
759ddeb270 | ||
|
|
538e111e78 | ||
|
|
45ab568f7a | ||
|
|
b32089843a | ||
|
|
d960aacf4f | ||
|
|
1c48ab227d | ||
|
|
6528ec95c2 | ||
|
|
53ee6015d0 | ||
|
|
ad150903af | ||
|
|
c29afaf751 | ||
|
|
cec4016862 | ||
|
|
c697d94a00 | ||
|
|
35438e2e77 | ||
|
|
716b524d70 | ||
|
|
cffd5672b2 | ||
|
|
82bb032336 | ||
|
|
ae4f7f9949 | ||
|
|
875ff6d354 | ||
|
|
842fa48fac | ||
|
|
8a63dce85f | ||
|
|
01386599f4 | ||
|
|
4310b4b742 | ||
|
|
89f4dd6ec4 | ||
|
|
85e0b79fb9 | ||
|
|
fba5f26f7e | ||
|
|
90b0fc434d | ||
|
|
6743d5bc78 | ||
|
|
def0259d24 | ||
|
|
a678f54f59 | ||
|
|
ebe7e61355 | ||
|
|
bda58c9695 | ||
|
|
e335133bf8 | ||
|
|
47432524e1 | ||
|
|
707b3bcc2d | ||
|
|
60014b8a40 | ||
|
|
2e4ce27f6b | ||
|
|
b8384c55c3 | ||
|
|
dfe1f02101 | ||
|
|
7c2fb0be81 | ||
|
|
b05f680650 | ||
|
|
2a9a436f9c | ||
|
|
0d6faf3fda | ||
|
|
aede000218 | ||
|
|
176ab0a639 | ||
|
|
4efb2caa56 | ||
|
|
6f81f86483 | ||
|
|
b64b8a38e4 | ||
|
|
ff56170ac5 | ||
|
|
733f1f827e | ||
|
|
ac903a05da | ||
|
|
838e6f789b | ||
|
|
d462393e8b | ||
|
|
e98cf8d50b | ||
|
|
eb173fc9dc | ||
|
|
50756046cf | ||
|
|
629bdc2213 | ||
|
|
39bbe33831 | ||
|
|
00bd556d7a | ||
|
|
12061ea9df | ||
|
|
580ed72e73 | ||
|
|
c01f0892a5 | ||
|
|
0fed34b12e | ||
|
|
0af68baf7b | ||
|
|
161e3c4d3b | ||
|
|
4720af2cb8 | ||
|
|
06d37aa009 | ||
|
|
c6fa860b2e | ||
|
|
4fe9ab70e5 | ||
|
|
920e4e86f5 | ||
|
|
720dc0c177 | ||
|
|
b3a555cab9 | ||
|
|
cf13b4f71b | ||
|
|
cd0b9fe350 | ||
|
|
82900f4645 | ||
|
|
703bba9ffd | ||
|
|
73706154a4 | ||
|
|
c9b2a0c777 | ||
|
|
54cc51fe5d | ||
|
|
81645d0777 | ||
|
|
d61c180ee5 | ||
|
|
a668800fd9 | ||
|
|
3bdc11c994 | ||
|
|
b496139063 | ||
|
|
607483629a | ||
|
|
5c8d138cef | ||
|
|
e3db1f7c4c | ||
|
|
de3b803f14 | ||
|
|
0558f919c4 | ||
|
|
68ea73c847 | ||
|
|
96ddb7132d | ||
|
|
d36ac44603 | ||
|
|
5d06c87943 | ||
|
|
588e3c0102 | ||
|
|
6ce32c1cab | ||
|
|
a23c51e5db | ||
|
|
3845071ba3 | ||
|
|
a48b3634bf | ||
|
|
806882b2e9 | ||
|
|
9ac3c46fe6 | ||
|
|
6817a1c027 | ||
|
|
cf2be1b12b | ||
|
|
9ffeb19c8c | ||
|
|
a7f6e8bd24 | ||
|
|
f61f62c219 | ||
|
|
bb70fd7b71 | ||
|
|
b80c860b7a | ||
|
|
3c7544f034 | ||
|
|
6746c2b654 | ||
|
|
8d59f89438 | ||
|
|
5753160e91 | ||
|
|
622cd9d943 | ||
|
|
2daa7f0811 | ||
|
|
05c53df0ed | ||
|
|
a7419cbc4c | ||
|
|
67ad38a7e6 | ||
|
|
e572ae2c62 | ||
|
|
24962eedc1 | ||
|
|
368d279ca5 | ||
|
|
9e4cc329ed | ||
|
|
d4702a166a | ||
|
|
925c709097 | ||
|
|
411788f72c | ||
|
|
4e4ea0035e | ||
|
|
0063f3f0fc | ||
|
|
fe6231ad4e | ||
|
|
4cdb06959b | ||
|
|
781ad30eb5 | ||
|
|
84d056f2ed | ||
|
|
3a2f2c99f4 | ||
|
|
cddff32757 | ||
|
|
1b427c6c07 | ||
|
|
6ba645f727 | ||
|
|
772538bc8a | ||
|
|
855d4dc701 | ||
|
|
3095e181eb | ||
|
|
ee020085f8 | ||
|
|
b70137eec8 | ||
|
|
aa4d79c6f5 | ||
|
|
ab8393a807 | ||
|
|
b8c83a1a72 | ||
|
|
8cee0e6735 | ||
|
|
c482208d3c | ||
|
|
708712e00a | ||
|
|
25ee250542 | ||
|
|
b921b68c57 |
6
.gitignore
vendored
@@ -1,2 +1,6 @@
|
||||
/target
|
||||
vendor.tar.xz
|
||||
vendor.tar.xz
|
||||
cargo-config
|
||||
.idea
|
||||
vendor-*
|
||||
vendor_*
|
||||
|
||||
26
.gitlab-ci.yml
Normal file
@@ -0,0 +1,26 @@
|
||||
image: rustdocker/rust:stable
|
||||
|
||||
before_script:
|
||||
- apt-get update -qq && apt-get install -y -qq libdbus-1-dev libclang-dev libudev-dev
|
||||
|
||||
stages:
|
||||
- test
|
||||
- build
|
||||
|
||||
test:
|
||||
script:
|
||||
- cargo check #+nightly check --features "clippy"
|
||||
|
||||
build:
|
||||
only:
|
||||
- main
|
||||
script:
|
||||
- make && make vendor
|
||||
artifacts:
|
||||
paths:
|
||||
- vendor_asus-nb-ctrl_*.tar.xz
|
||||
- cargo-config
|
||||
|
||||
variables:
|
||||
GIT_SUBMODULE_STRATEGY: normal
|
||||
|
||||
256
CHANGELOG.md
@@ -6,6 +6,262 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
# [3.6.0] - 2021-05-15
|
||||
### Changed
|
||||
- Add GX550L led modes
|
||||
- Don't save compute/vfio modes. Option in config for this is removed.
|
||||
- Store a temporary non-serialised option in config for if compute/vfio is active
|
||||
for informational purposes only (will not apply on boot)
|
||||
- Save state for LEDs enabled + sleep animation enabled
|
||||
- Save state for AnimMe enabled + boot animation enabled
|
||||
- Add extra config options and dbus methods
|
||||
- Add power state signals for anime and led
|
||||
- Refactor to use channels for dbus signal handler send/recv
|
||||
- Split out profiles independant parts to a rog-profiles crate
|
||||
- Cleanup dependencies
|
||||
- Fix some dbus Supported issues
|
||||
|
||||
# [3.5.2] - 2021-05-15
|
||||
### Changed
|
||||
- Bugfix: prevent the hang on compute/integrated mode change
|
||||
|
||||
# [3.5.1] - 2021-04-25
|
||||
### Changed
|
||||
+ Anime:
|
||||
- Fix using multiple configs
|
||||
|
||||
# [3.5.0] - 2021-04-25
|
||||
### Changed
|
||||
+ Keyboard:
|
||||
- Split out all aura functionality that isn't dependent on the daemon in to a
|
||||
new crate `rog-aura` (incomplete)
|
||||
- Keyboard LED control now includes:
|
||||
+ Enable/disable LED's while laptop is awake
|
||||
+ Enable/disable LED animation while laptop is suspended and AC plugged in
|
||||
- Properly reload the last used keyboard mode on boot
|
||||
+ Graphics:
|
||||
- Correctly enable compute mode for nvidia plus no-reboot or logout if switching
|
||||
from vfio/integrated/compute.
|
||||
- Add asusd config option to not save compute/vfio mode switch.
|
||||
+ Anime:
|
||||
- Enable basic multiple user anime configs (asusd-user must still be restarted)
|
||||
+ Profiles:
|
||||
- Enable dbus methods for freq min/max, fan curve, fan preset, CPU turbo enable.
|
||||
These options will apply to the active profile if no profile name is specified.
|
||||
|
||||
# [3.4.1] - 2021-04-11
|
||||
### Changed
|
||||
- Fix anime init sequence
|
||||
|
||||
# [3.4.0] - 2021-04-11
|
||||
### Changed
|
||||
- Revert zbus to 1.9.1
|
||||
- Use enum to show power states, and catch missing pci path for nvidia.
|
||||
- Partial user-daemon for anime/per-key done, `asusd-user`. Includes asusd-user systemd unit.
|
||||
- user-daemon provides dbus emthods to insert anime actions, remove from index, set leds on/off
|
||||
+ Config file is stored in `~/.config/rog/rog-user.cfg`
|
||||
- AniMe display parts split out to individual crate in preparation for publishing
|
||||
on crates.io
|
||||
|
||||
# [3.3.0] - 2021-04-3
|
||||
### Changed
|
||||
- Add ledmodes for G733QS
|
||||
- Add ledmodes for GA401Q
|
||||
- Default to vfio disabled in configuration. Will now hard-error if enabled and
|
||||
the kernel modules are builtin. To enable vfio switching `"gfx_vfio_enable": false,`
|
||||
must be changed to `true` in `/etc/asusd/asusd.conf`
|
||||
|
||||
# [3.2.4] - 2021-03-24
|
||||
### Changed
|
||||
- Ignore vfio-builtin error if switching to integrated
|
||||
|
||||
# [3.2.3] - 2021-03-24
|
||||
### Changed
|
||||
- Better handling of session tracking
|
||||
### Added
|
||||
- List all profile data
|
||||
- Get active profile name
|
||||
- Get active profile data
|
||||
|
||||
# [3.2.2] - 2021-03-23
|
||||
### Changed
|
||||
- Fix brightness control, again, for non-RGB keyboards
|
||||
|
||||
# [3.2.1] - 2021-03-21
|
||||
### Changed
|
||||
- Fix brightness control
|
||||
- Large cleanup of code relating to LED controls
|
||||
|
||||
# [3.2.0] - 2021-03-21
|
||||
### Changed
|
||||
- Refactor keyboard LED handling
|
||||
- Added --list for profiles (Thanks @aqez)
|
||||
- Added --remove for profiles (Thanks @aqez)
|
||||
- Added a graphics mode: vfio. This attaches Nvidia devices to vfio module.
|
||||
### Broken
|
||||
- Per-key LED modes, which need thinking about how to go ahead with for future
|
||||
|
||||
# [3.1.7] - 2021-03-11
|
||||
### Changed
|
||||
- Refactor many parts of daemon
|
||||
- Switch out session monitoring to logind-zbus
|
||||
|
||||
# [3.1.6] - 2021-03-11
|
||||
### Changed
|
||||
- Graphics switching will now wait until all users logged out before switching
|
||||
|
||||
### Changed
|
||||
- Further tweaks to gfx switching
|
||||
- More logging on gfx switching
|
||||
- Filter bios help according to supported modes
|
||||
- Prevent gfx mode switching if in dedicated/G-Sync mode
|
||||
|
||||
# [3.1.4] - 2021-03-10
|
||||
### Changed
|
||||
- Notify through dbus if user changes profile manually
|
||||
- Better help on CLI, show help only for supported items
|
||||
- Bugfix to gfx switcher
|
||||
|
||||
# [3.1.3] - 2021-03-10
|
||||
### Changed
|
||||
- Hotfix: gracefully handle removing modules in use caused by display-manager not
|
||||
fully shutdown at the time of trying to remove modules. It will now retry every
|
||||
250ms per module
|
||||
|
||||
# [3.1.2] - 2021-03-10
|
||||
### Changed
|
||||
- Test and create /etc/X11/xorg.conf.d/ if it doesn't exist
|
||||
- Hotfix to better report module issues
|
||||
|
||||
# [3.1.1] - 2021-03-10
|
||||
### Changed
|
||||
- Add missing nvidia module nvidia_uvm to gfx ctrl list
|
||||
|
||||
# [3.1.0] - 2021-03-09
|
||||
### Added
|
||||
- GU502LU led-modes
|
||||
### Changed
|
||||
- Graphics switching is now rebootless, the daemon will now restart the
|
||||
display-manager to switch modes instead. Caveats are:
|
||||
+ There is no confirmation from the daemon, the program issuing the command
|
||||
must confirm the request.
|
||||
+ systemd only
|
||||
- Laptops with dedicated Nvidia mode:
|
||||
+ You still must reboot for the bios to switch modes
|
||||
+ On boot if dedicated mode is active then asusd will update the required configs
|
||||
to put display-manager in nvidia mode
|
||||
|
||||
# [3.0.0] - 2021-02-22
|
||||
### Added
|
||||
- G531GD led modes
|
||||
|
||||
# [3.0.0] - 2021-02-14
|
||||
### Changed
|
||||
- Write set+apply after each array in multizone
|
||||
- Remove misc bad logic
|
||||
- Use same code path as 0x1866 device to configure led support for 0x1854 device
|
||||
- Remove duplicate code
|
||||
- Set correct speeds for multizone
|
||||
- Remove dbus crate in favour of zbus. This removes the external dbus lib requirement.
|
||||
- Huge internal refactor
|
||||
- BREAKING CHANGE: Anime code refactor. DBUS method names have changed
|
||||
- Cleanup fan and cpu control + configs
|
||||
|
||||
# [2.2.2] - 2021-01-31
|
||||
### Changed
|
||||
- Fix for dedicated gfx capable laptops in integrated mode
|
||||
- Fix for 0x1854 device
|
||||
|
||||
# [2.2.1] - 2021-01-27
|
||||
### Added
|
||||
- Add ROG Zephyrus M15 LED config
|
||||
### Changed
|
||||
- Bugfixes
|
||||
- Fix reboot/restartx status for GFX switching
|
||||
- Update readme
|
||||
- Change CLI arg tag for fan modes
|
||||
- Make dracut include the nvidia modules in initramfs
|
||||
|
||||
# [2.2.0] - 2021-01-26
|
||||
### Added
|
||||
- Dbus command to fetch all supported functions of the laptop. That is, all the
|
||||
functions that asusd supports for the currently running laptop.
|
||||
- Bios setting toggles for:
|
||||
+ Dedicated gfx toggle (support depends on the laptop)
|
||||
+ Bios boot POST sound toggle
|
||||
### Changed
|
||||
- added config option for dedicated gfx mode on laptops with it to enable
|
||||
switching directly to dedicated using `asusctl graphics -m nvidia`
|
||||
|
||||
# [2.1.2] - 2021-01-10
|
||||
### Changed
|
||||
- Adjust gfx controller to assume that the graphics driver is loaded if the
|
||||
mode is set for nvidia/hybrid
|
||||
|
||||
# [2.1.1] - 2021-01-09
|
||||
### Changed
|
||||
- Updates to dependencies
|
||||
|
||||
# [2.1.0] - 2020-10-25
|
||||
### Added
|
||||
- Option to turn off AniMe display (@asere)
|
||||
### Changed
|
||||
- Change option -k to show current LED bright (@asere)
|
||||
- Correctly disable GFX control via config
|
||||
- Panic and exit if config can't be parsed
|
||||
- Add DBUS method to toggle to next fan/thermal profile
|
||||
- Add DBUS method to toggle to next/prev Aura mode
|
||||
|
||||
# [2.0.5] - 2020-09-29
|
||||
### Changed
|
||||
- Bugfixes
|
||||
|
||||
# [2.0.4] - 2020-09-24
|
||||
### Changed
|
||||
- Better and more verbose error handling and logging in many places.
|
||||
- Fix timeout for client waiting on reply for graphics switching
|
||||
|
||||
# [2.0.2] - 2020-09-21
|
||||
### Changed
|
||||
- graphics options via CLI are now a command block:
|
||||
+ `asusctl graphics`
|
||||
+ -m Mode <nvidia, hybrid, compute, integrated>
|
||||
+ -g Get current mode
|
||||
+ -f Force reboot or restart display manager without confirmation
|
||||
|
||||
# [2.0.0] - 2020-09-21
|
||||
### Changed
|
||||
- Code refactor to spawn less tasks. Main loop will run only as fast as
|
||||
it receives events
|
||||
- No-longer using tokio or async, reducing resource use
|
||||
### Added
|
||||
- A basic user daemon has been added for user notifications over dbus (XDG spec)
|
||||
- Added a user systemd service for notifications (asus-notify)
|
||||
- Graphics mode handling <iGPU only, dGPU only, or hybrid>, see asusctl --help
|
||||
### BREAKING CHANGES
|
||||
- asusd.conf has changed slightly and will overwrite old configs
|
||||
- All DBUS methods/signals/paths etc, are all updated and changed
|
||||
|
||||
# [1.1.2] - 2020-09-10
|
||||
### Changed
|
||||
- Bump rog-fan-curve to new versiont o support GA401IV
|
||||
|
||||
# [1.1.1] - 2020-09-10
|
||||
### Changed
|
||||
- Correction to AMD turbo setting
|
||||
|
||||
# [1.1.0] - 2020-09-10
|
||||
### Changed
|
||||
- Uses string instead of debug print for some errors
|
||||
- Add interface num arg for LED controller (should help support
|
||||
older laptops better)
|
||||
- Some slightly better error messages
|
||||
- Fix an idiotic mistake in `for i in 0..2.. if i > 0` -_-
|
||||
- Remove "unsupported" warning on laptop ctrl
|
||||
- Silence warning about AniMe not existing
|
||||
- Adjust the turbo-toggle CLI arg
|
||||
- Version bump for new release with fancurves
|
||||
|
||||
## [1.0.2] - 2020-08-13
|
||||
### Changed
|
||||
- Bugfixes to led brightness watcher
|
||||
|
||||
1262
Cargo.lock
generated
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["asus-nb-ctrl", "asus-nb"]
|
||||
members = ["asusctl", "asus-notify", "daemon", "daemon-user", "rog-types", "rog-dbus", "rog-anime", "rog-aura", "rog-profiles"]
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
|
||||
395
MANUAL.md
Normal file
@@ -0,0 +1,395 @@
|
||||
# asusctrl manual
|
||||
|
||||
`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.
|
||||
|
||||
## Programs Available
|
||||
|
||||
- `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.
|
||||
|
||||
The functionality that `asusd` exposes is:
|
||||
|
||||
- graphics switching
|
||||
- anime control
|
||||
- led keyboard control (aura)
|
||||
- charge limiting
|
||||
- bios/efivar control
|
||||
- profiles (fan/cpu)
|
||||
|
||||
each of these will be detailed in sections.
|
||||
|
||||
### Graphics switching
|
||||
|
||||
`asusd` can switch graphics modes between:
|
||||
- `integrated`, uses the iGPU only and force-disables the dGPU
|
||||
- `compute`, enables Nvidia without Xorg. Useful for ML/Cuda
|
||||
- `hybrid`, enables Nvidia prime-offload mode
|
||||
- `nvidia`, uses the Nvidia gpu only
|
||||
- `vfio`, binds the Nvidia gpu to vfio for VM pass-through
|
||||
|
||||
Switching to/from Hybrid and Nvidia modes requires a logout only (no reboot). Switching between integrated/compute/vfio does not require a logout and is instant.
|
||||
|
||||
#### Required actions in distro
|
||||
|
||||
**Rebootless note:** You must edit `/etc/default/grub` to remove `nvidia-drm.modeset=1`
|
||||
from the line `GRUB_CMDLINE_LINUX=` and then recreate your grub config. In fedora
|
||||
you can do this with `sudo grub2-mkconfig -o /etc/grub2.cfg` - other distro may be
|
||||
similar but with a different config location. It's possible that graphics driver updates
|
||||
may change this.
|
||||
|
||||
This switcher conflicts with other gpu switchers like optimus-manager, suse-prime
|
||||
or ubuntu-prime, system76-power, and bbswitch. If you have issues with `asusd`
|
||||
always defaulting to `integrated` mode on boot then you will need to check for
|
||||
stray configs blocking nvidia modules from loading in:
|
||||
- `/etc/modprobe.d/`
|
||||
- `/usr/lib/modprope.d/`
|
||||
|
||||
#### Config options
|
||||
|
||||
1. `"gfx_mode": "<MODE>",`: MODE can be <Integrated, Hybrid, Compute, Nvidia, vfio>
|
||||
2. `"gfx_last_mode": "Nvidia",`: currently unused
|
||||
3. `"gfx_managed": true,`: enable or disable graphics switching controller
|
||||
4. `"gfx_vfio_enable": false,`: enable vfio switching for Nvidia GPU passthrough
|
||||
5. `"gfx_save_compute_vfio": false,`: wether or not to save the vfio state (so it sticks between boots)
|
||||
|
||||
#### Graphics switching notes
|
||||
|
||||
**G-Sync note:** Some laptops are capable of using the dGPU as the sole GPU in the system which is generally to enable g-sync on the laptop display panel. This is controlled by the bios/efivar control and will be covered in that section.
|
||||
|
||||
**vfio note:** The vfio modules *must not* be compiled into the kernel, they need
|
||||
to be separate modules. If you don't plan to use vfio mode then you can ignore this
|
||||
otherwise you may need a custom built kernel.
|
||||
|
||||
### AniMe control
|
||||
|
||||
Controller for the fancy AniMe matrix display on the lid of some machines. This controller is a work in progress.
|
||||
|
||||
#### Config options
|
||||
|
||||
If you have an AniMe device a few system-level config options are enabled for you in `/etc/asusd/anime.conf`;
|
||||
|
||||
1. `"system": [],`: currently unused, is intended to be a default continuous sequence in future versions
|
||||
2. `"boot": [],`: a sequence that plays on system boot (when asusd is loaded)
|
||||
3. `"wake": [],`: a sequence that plays when waking from suspend
|
||||
4. `"shutdown": [],`: a sequence that plays when shutdown begins
|
||||
5. `"brightness": <FLOAT>`: global brightness control, where `<FLOAT> is 0.0-1.0
|
||||
|
||||
Some default examples are provided but are minimal. The full range of configuration options will be covered in another section of this manual.
|
||||
|
||||
### Led keyboard control
|
||||
|
||||
The LED controller (e.g, aura) enables setting many of the factory modes available if a laptop supports them. It also enables per-key RGB settings but this is a WIP and will likely be similar to how AniMe sequences can be created.
|
||||
|
||||
#### Supported laptops
|
||||
|
||||
Models GA401, GA502, GU502 support LED brightness change only (no RGB). However the GA401Q model can actually use three modes; static, breathe, and pulse, plus also use red to control the LED brightness intensity.
|
||||
|
||||
All models that have any form of LED mode control need to be enabled via the config file at `/etc/asusd/asusd-ledmodes.toml`. Unfortunately ASUS doesn't provide any easy way to find all the supported modes for all laptops (not even through Armory Crate and its various files, that progrma downloads only the required settings for the laptop it runs on) so each model must be added as needed.
|
||||
|
||||
#### Config options
|
||||
|
||||
The defaults are located at `/etc/asusd/asusd-ledmodes.toml`, and on `asusd` start it creates `/etc/asusd/aura.conf` whcih stores the per-mode settings. If you edit the defaults file you must remove `/etc/asusd/aura.conf` and restart `asusd.service` with `systemctl restart asusd`.
|
||||
|
||||
##### /etc/asusd/asusd-ledmodes.toml
|
||||
|
||||
Example:
|
||||
```toml
|
||||
[[led_data]]
|
||||
prod_family = "ROG Zephyrus M15"
|
||||
board_names = ["GU502LU"]
|
||||
standard = ["Static", "Breathe", "Strobe", "Pulse"]
|
||||
multizone = false
|
||||
per_key = false
|
||||
```
|
||||
|
||||
1. `prod_family`: you can find this in `journalctl -b -u asusd`, or `cat /sys/class/dmi/id/product_name`. It should be copied as written. There can be multiple `led-data` groups of the same `prod_family` with differing `board_names`.
|
||||
2. `board_names`: is an array of board names in this product family. Find this in the journal as above or by `cat /sys/class/dmi/id/board_name`.
|
||||
3. `standard` are the factory preset modes, the names should corrospond to Armory Crate names
|
||||
4. `multizone`: some keyboards have 4 zones of LED control, this enables setting a colour in each zone. The keyboard must support this or it has no effect.
|
||||
5. `per_key`: enable per-key RGB effects. The keyboard must support this or it has no effect.
|
||||
|
||||
##### /etc/asusd/aura.conf
|
||||
|
||||
This file can be manually edited if desired, but the `asusctl` CLI tool, or dbus methods are the preferred method. Any manual changes to this file mean that the `asusd.service` will need to be restarted, or you need to cycle between modes to force a reload.
|
||||
|
||||
### Charge control
|
||||
|
||||
Almost all modern ASUS laptops have charging limit control now. This can be controlled in `/etc/asusd/asusd.conf`.
|
||||
|
||||
```json
|
||||
"bat_charge_limit": 80,
|
||||
```
|
||||
where the number is a percentage.
|
||||
|
||||
### Bios control
|
||||
|
||||
Some options that you find in Armory Crate are available under this controller, so far there is:
|
||||
|
||||
- POST sound: this is the sound you here on bios boot post
|
||||
- G-Sync: this controls if the dGPU (Nvidia) 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.
|
||||
|
||||
### Profiles
|
||||
|
||||
Profiles provide a method setting up various basic CPU and fan settings in profile blocks which can then be switched between or cycled through. The CPU controls so far are:
|
||||
|
||||
- Min/Max percentage of CPU frequency (Intel only for now)
|
||||
- CPU turbo boost enable or disable
|
||||
- Fan presets. These are 0: Normal, 1: Boost, 2: Silent.
|
||||
- Fan curves, override fan-preset. AMD only.
|
||||
|
||||
#### Config options
|
||||
|
||||
Example:
|
||||
```json
|
||||
"toggle_profiles": [
|
||||
"normal",
|
||||
"boost",
|
||||
"silent"
|
||||
],
|
||||
"power_profiles": {
|
||||
"boost": {
|
||||
"min_percentage": 0,
|
||||
"max_percentage": 100,
|
||||
"turbo": true,
|
||||
"fan_preset": 1,
|
||||
"fan_curve": null
|
||||
},
|
||||
"normal": {
|
||||
"min_percentage": 0,
|
||||
"max_percentage": 100,
|
||||
"turbo": true,
|
||||
"fan_preset": 0,
|
||||
"fan_curve": null
|
||||
},
|
||||
"silent": {
|
||||
"min_percentage": 0,
|
||||
"max_percentage": 100,
|
||||
"turbo": true,
|
||||
"fan_preset": 2,
|
||||
"fan_curve": null
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
1. `"toggle_profiles": [],`: these are the profile names that will be cycled through when using a provided next/prev dbus method.
|
||||
2. `"power_profiles": {}`: all the available profiles.
|
||||
|
||||
#### Fan curves
|
||||
|
||||
**fan_curve note:** This is a WIP. Currently it relies on `acpi_call` kernel module which is ancient and hacky, not intended for this purpose. A proper kernel driver is in progress.
|
||||
|
||||
See [this document](https://github.com/cronosun/atrofac/blob/master/ADVANCED.md#limits) for details on the string format required, e.g, `"fan_curve": "30c:0%,40c:5%,50c:10%,60c:20%,70c:35%,80c:55%,90c:65%,100c:65%"`.
|
||||
|
||||
### Support controller
|
||||
|
||||
There is one more controller; the support controller. The sole pupose of this controller is to querie all the other controllers for information about their support level for the host laptop. Returns a json string.
|
||||
|
||||
## 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.
|
||||
|
||||
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.
|
||||
|
||||
The main config is `~/.config/rog/rog-user.cfg`
|
||||
|
||||
#### Config options: AniMe
|
||||
|
||||
`~/.config/rog/rog-user.cfg` contains a setting `"active_anime": "<FILENAME>"` where `<FILENAME>` is the name of the AniMe config to use, located in the same directory and without the file postfix, e.g, `"active_anime": "anime-doom"`
|
||||
|
||||
An AniMe config itself is a file with contents:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "<FILENAME>",
|
||||
"anime": []
|
||||
}
|
||||
```
|
||||
|
||||
`<FILENAME>` is used as a reference internally. `"anime": []` is an array of sequences (WIP).
|
||||
|
||||
##### "anime" array options
|
||||
|
||||
Each object in the array can be one of:
|
||||
|
||||
1. AsusAnimation
|
||||
2. ImageAnimation
|
||||
3. Image
|
||||
4. Pause
|
||||
|
||||
##### 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>",
|
||||
"time": <TIME>,
|
||||
"brightness": <FLOAT>
|
||||
}
|
||||
```
|
||||
|
||||
##### ImageAnimation
|
||||
|
||||
`ImageAnimation` can play *any* gif of any size.
|
||||
|
||||
```json
|
||||
"ImageAnimation": {
|
||||
"file": "<FILE_PATH>",
|
||||
"scale": <FLOAT>,
|
||||
"angle": <FLOAT>,
|
||||
"translation": [
|
||||
<FLOAT>,
|
||||
<FLOAT>
|
||||
],
|
||||
"time": <TIME>,
|
||||
"brightness": <FLOAT>
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
##### Image
|
||||
|
||||
`Image` currently requires 8bit greyscale png. It will be able to use most in future.
|
||||
|
||||
```json
|
||||
{
|
||||
"Image": {
|
||||
"file": "<FILE_PATH>",
|
||||
"scale": <FLOAT>,
|
||||
"angle": <FLOAT>,
|
||||
"translation": [
|
||||
<FLOAT>,
|
||||
<FLOAT>
|
||||
],
|
||||
"brightness": <FLOAT>
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
##### Pause
|
||||
|
||||
A `Pause` is handy for after an `Image` to hold the `Image` on the AniMe for a period.
|
||||
|
||||
```json
|
||||
{
|
||||
"Pause": {
|
||||
"secs": <INT>,
|
||||
"nanos": <INT>
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
##### Options for objects
|
||||
|
||||
**<FILE_PATH>**
|
||||
|
||||
Must be full path: `"/usr/share/asusd/anime/asus/gaming/Controller.gif"` or `/home/luke/Downloads/random.gif`.
|
||||
|
||||
**<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
|
||||
- `translation`: Shift the image X -/+, and y -/+
|
||||
|
||||
**<TIME>**
|
||||
|
||||
Time is the length of time to run the gif for:
|
||||
```json
|
||||
"time": {
|
||||
"Time": {
|
||||
"secs": 5,
|
||||
"nanos": 0
|
||||
}
|
||||
},
|
||||
```
|
||||
A cycle is how many gif loops to run:
|
||||
```json
|
||||
"time": {
|
||||
"Cycles": 2
|
||||
},
|
||||
```
|
||||
`Infinite` means that this gif will never end:
|
||||
```json
|
||||
"time": "Infinite",
|
||||
```
|
||||
|
||||
**<INT>**
|
||||
|
||||
A plain non-float integer.
|
||||
|
||||
## asusctl
|
||||
|
||||
`asusctl` is a commandline interface which intends to be the main method of interacting with `asusd`. I can be used in any place a terminal app can be used.
|
||||
|
||||
This program will query `asusd` for the `Support` level of the laptop and show or hide options according to this support level.
|
||||
|
||||
Most commands are self-explanatory.
|
||||
|
||||
### CLI Usage and help
|
||||
|
||||
Commands are given by:
|
||||
|
||||
```
|
||||
asusctl <option> <command> <command-options>
|
||||
```
|
||||
|
||||
Help is available through:
|
||||
|
||||
```
|
||||
asusctl --help
|
||||
asusctl <command> --help
|
||||
```
|
||||
|
||||
Some commands may have subcommands:
|
||||
|
||||
```
|
||||
asusctl <command> <subcommand> --help
|
||||
```
|
||||
|
||||
### Keybinds
|
||||
|
||||
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)
|
||||
|
||||
---
|
||||
|
||||
ASUS and ROG Trademark is either a US registered trademark or trademark of ASUSTeK Computer Inc. in the United States and/or other countries.
|
||||
|
||||
Reference to any ASUS products, services, processes, or other information and/or use of ASUS Trademarks does not constitute or imply endorsement, sponsorship, or recommendation thereof by ASUS.
|
||||
|
||||
The use of ROG and ASUS trademarks within this website and associated tools and libraries is only to provide a recognisable identifier to users to enable them to associate that these tools will work with ASUS ROG laptops.
|
||||
|
||||
---
|
||||
88
Makefile
@@ -1,32 +1,38 @@
|
||||
prefix ?= /usr
|
||||
sysconfdir ?= /etc
|
||||
VERSION := $(shell grep -Pm1 'version = "(\d.\d.\d)"' daemon/Cargo.toml | cut -d'"' -f2)
|
||||
|
||||
INSTALL = install
|
||||
INSTALL_PROGRAM = ${INSTALL} -D -m 0755
|
||||
INSTALL_DATA = ${INSTALL} -D -m 0644
|
||||
|
||||
prefix = /usr
|
||||
exec_prefix = $(prefix)
|
||||
bindir = $(exec_prefix)/bin
|
||||
libdir = $(exec_prefix)/lib
|
||||
includedir = $(prefix)/include
|
||||
datarootdir = $(prefix)/share
|
||||
datadir = $(datarootdir)
|
||||
libdir = $(exec_prefix)/lib
|
||||
zshcpl = $(datarootdir)/zsh/site-functions
|
||||
|
||||
SRC = Cargo.toml Cargo.lock Makefile $(shell find -type f -wholename '**/src/*.rs')
|
||||
BIN_C := asusctl
|
||||
BIN_D := asusd
|
||||
BIN_U := asusd-user
|
||||
BIN_N := asus-notify
|
||||
LEDCFG := asusd-ledmodes.toml
|
||||
X11CFG := 90-nvidia-screen-G05.conf
|
||||
PMRULES := 90-asusd-nvidia-pm.rules
|
||||
|
||||
.PHONY: all clean distclean install uninstall update
|
||||
|
||||
BIN_C=asusctl
|
||||
BIN_D=asusd
|
||||
LEDCONFIG=asusd-ledmodes.toml
|
||||
SRC := Cargo.toml Cargo.lock Makefile $(shell find -type f -wholename '**/src/*.rs')
|
||||
|
||||
DEBUG ?= 0
|
||||
ifeq ($(DEBUG),0)
|
||||
ARGS += "--release"
|
||||
ARGS += --release
|
||||
TARGET = release
|
||||
endif
|
||||
|
||||
VENDORED ?= 0
|
||||
ifeq ($(VENDORED),1)
|
||||
ARGS += "--frozen"
|
||||
ARGS += --frozen
|
||||
endif
|
||||
|
||||
all: target/release/$(BIN_D)
|
||||
all: build
|
||||
|
||||
clean:
|
||||
cargo clean
|
||||
@@ -34,20 +40,43 @@ clean:
|
||||
distclean:
|
||||
rm -rf .cargo vendor vendor.tar.xz
|
||||
|
||||
install: all
|
||||
install -D -m 0755 "target/release/$(BIN_C)" "$(DESTDIR)$(bindir)/$(BIN_C)"
|
||||
install -D -m 0755 "target/release/$(BIN_D)" "$(DESTDIR)$(bindir)/$(BIN_D)"
|
||||
install -D -m 0644 "data/$(BIN_D).rules" "$(DESTDIR)/lib/udev/rules.d/99-$(BIN_D).rules"
|
||||
install -D -m 0644 "data/$(LEDCONFIG)" "$(DESTDIR)$(sysconfdir)/asusd/$(LEDCONFIG)"
|
||||
install -D -m 0644 "data/$(BIN_D).conf" "$(DESTDIR)$(sysconfdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
install -D -m 0644 "data/$(BIN_D).service" "$(DESTDIR)/lib/systemd/system/$(BIN_D).service"
|
||||
install:
|
||||
$(INSTALL_PROGRAM) "./target/release/$(BIN_C)" "$(DESTDIR)$(bindir)/$(BIN_C)"
|
||||
$(INSTALL_PROGRAM) "./target/release/$(BIN_D)" "$(DESTDIR)$(bindir)/$(BIN_D)"
|
||||
$(INSTALL_PROGRAM) "./target/release/$(BIN_U)" "$(DESTDIR)$(bindir)/$(BIN_U)"
|
||||
$(INSTALL_PROGRAM) "./target/release/$(BIN_N)" "$(DESTDIR)$(bindir)/$(BIN_N)"
|
||||
$(INSTALL_DATA) "./data/$(PMRULES)" "$(DESTDIR)$(libdir)/udev/rules.d/$(PMRULES)"
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).rules" "$(DESTDIR)$(libdir)/udev/rules.d/99-$(BIN_D).rules"
|
||||
$(INSTALL_DATA) "./data/$(LEDCFG)" "$(DESTDIR)/etc/asusd/$(LEDCFG)"
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).conf" "$(DESTDIR)$(datarootdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
$(INSTALL_DATA) "./data/$(X11CFG)" "$(DESTDIR)$(datarootdir)/X11/xorg.conf.d/$(X11CFG)"
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).service" "$(DESTDIR)$(libdir)/systemd/system/$(BIN_D).service"
|
||||
$(INSTALL_DATA) "./data/$(BIN_N).service" "$(DESTDIR)$(libdir)/systemd/user/$(BIN_N).service"
|
||||
$(INSTALL_DATA) "./data/$(BIN_U).service" "$(DESTDIR)$(libdir)/systemd/user/$(BIN_U).service"
|
||||
$(INSTALL_DATA) "./data/icons/asus_notif_yellow.png" "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_yellow.png"
|
||||
$(INSTALL_DATA) "./data/icons/asus_notif_green.png" "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_green.png"
|
||||
$(INSTALL_DATA) "./data/icons/asus_notif_red.png" "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_red.png"
|
||||
$(INSTALL_DATA) "./data/_asusctl" "$(DESTDIR)$(zshcpl)/_asusctl"
|
||||
$(INSTALL_DATA) "./data/completions/asusctl.fish" "$(DESTDIR)$(datarootdir)/fish/vendor_completions.d/asusctl.fish"
|
||||
cd data && find "./anime" -type f -exec install -Dm 755 "{}" "$(DESTDIR)$(datarootdir)/asusd/{}" \;
|
||||
|
||||
uninstall:
|
||||
rm -f "$(DESTDIR)$(bindir)/$(BIN_C)"
|
||||
rm -f "$(DESTDIR)$(bindir)/$(BIN_D)"
|
||||
rm -f "$(DESTDIR)/lib/udev/rules.d/99-$(BIN_D).rules"
|
||||
rm -f "$(DESTDIR)$(sysconfdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
rm -f "$(DESTDIR)/lib/systemd/system/$(BIN_D).service"
|
||||
rm -f "$(DESTDIR)$(bindir)/$(BIN_N)"
|
||||
rm -f "$(DESTDIR)$(libdir)/udev/rules.d/$(PMRULES)"
|
||||
rm -f "$(DESTDIR)$(libdir)/udev/rules.d/99-$(BIN_D).rules"
|
||||
rm -f "$(DESTDIR)/etc/asusd/$(LEDCFG)"
|
||||
rm -f "$(DESTDIR)$(datarootdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
rm -f "$(DESTDIR)$(datarootdir)/X11/xorg.conf.d/$(X11CFG)"
|
||||
rm -f "$(DESTDIR)$(libdir)/systemd/system/$(BIN_D).service"
|
||||
rm -r "$(DESTDIR)$(libdir)/systemd/user/$(BIN_N).service"
|
||||
rm -r "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_yellow.png"
|
||||
rm -r "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_green.png"
|
||||
rm -r "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/asus_notif_red.png"
|
||||
rm -f "$(DESTDIR)$(zshcpl)/_asusctl"
|
||||
rm -f "$(DESTDIR)$(datarootdir)/fish/vendor_completions.d/asusctl.fish"
|
||||
rm -rf "$(DESTDIR)$(datarootdir)/asusd"
|
||||
|
||||
update:
|
||||
cargo update
|
||||
@@ -56,11 +85,16 @@ vendor:
|
||||
mkdir -p .cargo
|
||||
cargo vendor | head -n -1 > .cargo/config
|
||||
echo 'directory = "vendor"' >> .cargo/config
|
||||
tar pcfJ vendor.tar.xz vendor
|
||||
mv .cargo/config ./cargo-config
|
||||
rm -rf .cargo
|
||||
tar pcfJ vendor_asusctl_$(VERSION).tar.xz vendor
|
||||
rm -rf vendor
|
||||
|
||||
target/release/$(BIN_D): $(SRC)
|
||||
build:
|
||||
ifeq ($(VENDORED),1)
|
||||
tar pxf vendor.tar.xz
|
||||
@echo "version = $(VERSION)"
|
||||
tar pxf vendor_asusctl_$(VERSION).tar.xz
|
||||
endif
|
||||
cargo build $(ARGS)
|
||||
|
||||
.PHONY: all clean distclean install uninstall update build
|
||||
|
||||
293
README.md
@@ -1,123 +1,76 @@
|
||||
# ASUS NB Ctrl
|
||||
# `asusctl` for ASUS ROG
|
||||
|
||||
[](https://www.paypal.com/donate/?hosted_button_id=4V2DEPS7K6APC) - [Asus Linux Website](https://asus-linux.org/)
|
||||
|
||||
`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.
|
||||
|
||||
## 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
|
||||
|
||||
Point 3 means that the list of supported distros is very narrow - fedora is explicitly
|
||||
supported, while Ubuntu and openSUSE are level-2 support. All other distros are *not*
|
||||
supported (while asusd might still run fine on them). For best support use fedora 32+ Workstation.
|
||||
|
||||
Point 4? asusd currently uses a tiny fraction of cpu time, and less than 1Mb of ram, the way
|
||||
a system-level daemon should.
|
||||
|
||||
**NOTICE:**
|
||||
|
||||
This program requires the kernel patch in `./kernel-patch/` to be applied.
|
||||
As of 04/08/2020 these have been submitted to lkml.
|
||||
|
||||
The patch enables the following in kernel:
|
||||
|
||||
- All hotkeys (FN+Key combos)
|
||||
- Control of keyboard brightness using FN+Key combos (not RGB)
|
||||
- FN+F5 (fan) to toggle fan modes
|
||||
|
||||
You will not get RGB control in kernel (yet), and asusd is still required to
|
||||
change modes and RGB settings. The previous version of this program is named
|
||||
`rog-core` and takes full control of the interfaces required - if you can't
|
||||
apply the kernel patches then `rog-core` is still highly usable.
|
||||
|
||||
Many other patches for these laptops, AMD and Intel based, are working their way
|
||||
in to the kernel.
|
||||
|
||||
---
|
||||
asusd is a utility for Linux to control many aspects of various ASUS laptops.
|
||||
Various patches are required for keyboard support. See [this post](https://asus-linux.org/blog/updates-2021-05-06/) for details on status and which kernels will have which patches.
|
||||
|
||||
## Discord
|
||||
|
||||
[Discord server link](https://discord.gg/PVyFzWj)
|
||||
[Discord server link](https://discord.gg/ngbdKabAnP)
|
||||
|
||||
## SUPPORTED LAPTOPS
|
||||
|
||||
If your laptop is not in the following lists, it may still work with fan-mode switching and charge limit control.
|
||||
|
||||
**Please help test or provide info for:**
|
||||
|
||||
- GL703(0x1869)
|
||||
- GL553/GL753 (device = 0x1854) (attempted support from researching 2nd-hand info, multizone may work)
|
||||
|
||||
**Laptop support is modified on a per-case basis** as the EC for the keyboard varies
|
||||
a little between models, e.g, some RGB modes are missing, or it's a single colour.
|
||||
As far as I can see, the EC does not give us a way to find what modes are supported.
|
||||
|
||||
### ANIME AND OTHER FUNCTIONS
|
||||
|
||||
**AniMe device check is performed on start, if your device has one it will be detected.**
|
||||
|
||||
**NOTE:** If charge limit or fan modes are not working, then you may require a kernel newer than 5.6.10.
|
||||
|
||||
- [X] AniMe Matrix display
|
||||
- [X] Power profile switching on fan-mode (FN+F5)
|
||||
- [X] Intel
|
||||
- [X] Turbo enale/disable
|
||||
- [X] Min frequency percentage
|
||||
- [X] Max frequency percentage
|
||||
- [X] AMD
|
||||
- [X] Turbo enale/disable
|
||||
- [X] Battery charge limit
|
||||
|
||||
**NOTE:** GA14/GA401 and GA15/GA502/GU502, You will need kernel [patches](https://lab.retarded.farm/zappel/asus-rog-zephyrus-g14/-/tree/master/kernel_patches).
|
||||
|
||||
### KEYBOARD BACKLIGHT MODES
|
||||
|
||||
Models GA401, GA502, GU502 support LED brightness change only (no RGB).
|
||||
|
||||
| MODEL | STATIC | BREATHING | STROBE | RAINBOW | STAR | RAIN | HIGHLIGHT | LASER | RIPPLE | PULSE | COMET | FLASH | ZONES | PER-KEY RGB |
|
||||
|:------:|:------:|:---------:|:------:|:-------:|:----:|:----:|:---------:|:-----:|:------:|:-----:|:-----:|:-----:|:-----:|:-----------:|
|
||||
| G512LI | X | X | X | X | | | | | | | | | | |
|
||||
| G712LI | X | X | X | X | | | | | | | | | | |
|
||||
| GM501 | X | X | X | X | | | | | | | | | X | |
|
||||
| GX531 | X | X | X | X | | | | | | | | | X | |
|
||||
| G512 | X | X | X | X | | | | | | | | | X | |
|
||||
| G712 | X | X | X | X | | | | | | | | | X | |
|
||||
| GX502 | X | X | X | X | X | X | X | X | X | X | X | X | | X |
|
||||
| GX701 | X | X | X | X | X | X | X | X | X | X | X | X | | X |
|
||||
| G531 | X | X | X | X | X | X | X | X | X | X | X | X | X | X |
|
||||
| G731 | X | X | X | X | X | X | X | X | X | X | X | X | X | X |
|
||||
| G532 | X | X | X | X | X | X | X | X | X | X | X | X | | X |
|
||||
|
||||
It is highly likely this doesn't cover all models.
|
||||
|
||||
For editing the `/etc/asusd/asusd-ledmodes.toml`, the LED Mode numbers are as follows:
|
||||
Most ASUS gaming laptops that have a USB keyboard. If `lsusb` shows something similar
|
||||
to this:
|
||||
|
||||
```
|
||||
0 STATIC
|
||||
1 BREATHING
|
||||
2 STROBE
|
||||
3 RAINBOW
|
||||
4 STAR
|
||||
5 RAIN
|
||||
6 HIGHLIGHT
|
||||
7 LASER
|
||||
8 RIPPLE
|
||||
10 PULSE
|
||||
11 COMET
|
||||
12 FLASH
|
||||
13 MULTISTATIC
|
||||
255 PER_KEY
|
||||
Bus 001 Device 002: ID 0b05:1866 ASUSTek Computer, Inc. N-KEY Device
|
||||
```
|
||||
|
||||
then it may work without tweaks. Technically all other functions except the LED
|
||||
and AniMe parts should work regardless of your latop make. Eventually this project
|
||||
will probably suffer another rename once it becomes generic enough to do so.
|
||||
|
||||
## Implemented
|
||||
|
||||
- [X] Daemon
|
||||
- [X] System daemon
|
||||
- [X] User notifications daemon
|
||||
- [X] Setting/modifying built-in LED modes
|
||||
- [X] Per-key LED setting
|
||||
- [X] Fancy LED modes (See examples)
|
||||
- [X] Fancy LED modes (See examples) (currently being reworked)
|
||||
- [X] Saving settings for reload
|
||||
- [X] Logging - required for journalctl
|
||||
- [X] AniMatrix display on G14 models that include it
|
||||
- [X] AniMatrix display on G14 models that include it (currently being reworked)
|
||||
- [X] Set battery charge limit (with kernel supporting this)
|
||||
- [X] Fan curve control on G14 + G15 thanks to @Yarn1
|
||||
- [X] Graphics mode switching between iGPU, dGPU, on-demand, and vfio (for VM pass-through)
|
||||
+ [X] Requires only a logout/login
|
||||
- [X] Toggle bios setting for boot/POST sound
|
||||
- [X] Toggle bios setting for "dedicated gfx" mode on supported laptops (g-sync)
|
||||
|
||||
## Requirements for compiling
|
||||
# BUILDING
|
||||
|
||||
- `rustc` + `cargo` + `make`
|
||||
- `libusb-1.0-0-dev`
|
||||
- `libdbus-1-dev`
|
||||
- `llvm`
|
||||
- `libclang-dev`
|
||||
- `libudev-dev`
|
||||
Requirements are rust >= 1.47 installed from rustup.io if the distro provided version is too old, and `make`.
|
||||
|
||||
**Ubuntu*:** `apt install libclang-dev libudev-dev`
|
||||
|
||||
**fedora:** `dnf install clang-devel systemd-devel`
|
||||
|
||||
## Installing
|
||||
|
||||
Download repositories are available [here](https://download.opensuse.org/repositories/home:/luke_nukem:/asus/) for the latest versions of Fedora, Ubuntu, and openSUSE.
|
||||
|
||||
---
|
||||
|
||||
Run `make` then `sudo make install` then reboot.
|
||||
|
||||
The default init method is to use the udev rule, this ensures that the service is
|
||||
@@ -129,147 +82,33 @@ If you are upgrading from a previous installed version, you will need to restart
|
||||
$ 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, or at least limiting use of the power-management parts as `asusd` lets you set the same things
|
||||
(one or the other will overwrite pstates). I will create a shell extension at some point similar to system76, but using
|
||||
the asusd parts. It is safe to leave `system76-power.service` enabled and use for switching between graphics modes.
|
||||
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.
|
||||
|
||||
If you would like to run this daemon on another non-ASUS laptop you can. You'll
|
||||
have all features available except the LED and AniMe control (further controllers
|
||||
can be added on request). You will need to install the alternative service from
|
||||
`data/asusd-alt.service`.
|
||||
|
||||
## Uninstalling
|
||||
|
||||
Run `sudo make uninstall` in the source repo, and remove `/etc/asusd.conf`.
|
||||
Run `sudo make uninstall` in the source repo, and remove `/etc/asusd/`.
|
||||
|
||||
## Updating
|
||||
# OTHER
|
||||
|
||||
Occasionally you need to remove `/etc/asusd.conf` and restart the daemon to create a new one. You *can* back up the old
|
||||
one and copy settings back over (then restart daemon again).
|
||||
|
||||
# Usage
|
||||
|
||||
**NOTE! Fan mode toggling requires a newer kernel**. I'm unsure when the patches required for it got merged - I've
|
||||
tested with the 5.6.6 kernel and above only. To see if the fan-mode changed cat either:
|
||||
|
||||
- `cat /sys/devices/platform/asus-nb-wmi/throttle_thermal_policy` or
|
||||
- `cat /sys/devices/platform/asus-nb-wmi/fan_boost_mode`
|
||||
|
||||
The numbers are 0 = Normal/Balanced, 1 = Boost, 2 = Silent.
|
||||
|
||||
Running the program as a daemon manually will require root. Standard (non-daemon) mode expects to be communicating with
|
||||
the daemon mode over dbus.
|
||||
|
||||
Commands are given by:
|
||||
|
||||
```
|
||||
asusctl <option> <command> <command-options>
|
||||
```
|
||||
|
||||
Help is available through:
|
||||
|
||||
```
|
||||
asusctl --help
|
||||
asusctl <command> --help
|
||||
```
|
||||
|
||||
Some commands may have subcommands:
|
||||
|
||||
```
|
||||
asusctl <command> <subcommand> --help
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
```
|
||||
$ asusctl --help
|
||||
Usage: asusctl [OPTIONS]
|
||||
|
||||
Optional arguments:
|
||||
-h, --help print help message
|
||||
-v, --version show program version number
|
||||
-k, --kbd-bright VAL <off, low, med, high>
|
||||
-p, --pwr-profile PWR <silent, normal, boost>
|
||||
-c, --chg-limit CHRG <20-100>
|
||||
|
||||
Available commands:
|
||||
led-mode Set the keyboard lighting from built-in modes
|
||||
|
||||
$ asusctl led-mode --help
|
||||
Usage: asusctl led-mode [OPTIONS]
|
||||
|
||||
Optional arguments:
|
||||
-h, --help print help message
|
||||
|
||||
Available commands:
|
||||
static set a single static colour
|
||||
breathe pulse between one or two colours
|
||||
strobe strobe through all colours
|
||||
rainbow rainbow cycling in one of four directions
|
||||
star rain pattern mimicking raindrops
|
||||
rain rain pattern of three preset colours
|
||||
highlight pressed keys are highlighted to fade
|
||||
laser pressed keys generate horizontal laser
|
||||
ripple pressed keys ripple outwards like a splash
|
||||
pulse set a rapid pulse
|
||||
comet set a vertical line zooming from left
|
||||
flash set a wide vertical line zooming from left
|
||||
multi-static 4-zone multi-colour
|
||||
|
||||
$ asusctl led-mode static --help
|
||||
Usage: asusctl led-mode static [OPTIONS]
|
||||
|
||||
Optional arguments:
|
||||
-h, --help print help message
|
||||
-c HEX set the RGB value e.g, ff00ff
|
||||
|
||||
$ asusctl led-mode star --help
|
||||
Usage: asusctl led-mode star [OPTIONS]
|
||||
|
||||
Optional arguments:
|
||||
-h, --help print help message
|
||||
-c HEX set the first RGB value e.g, ff00ff
|
||||
-C HEX set the second RGB value e.g, ff00ff
|
||||
-s SPEED set the speed: low, med, high
|
||||
```
|
||||
|
||||
## Daemon mode
|
||||
|
||||
If the daemon service is enabled then on boot the following will be reloaded from save:
|
||||
|
||||
- LED brightness
|
||||
- Last used built-in mode
|
||||
- fan-boost/thermal mode
|
||||
- battery charging limit
|
||||
|
||||
The daemon also saves the settings per mode as the keyboard does not do this
|
||||
itself - this means cycling through modes with the Aura keys will use the
|
||||
settings that were used via CLI.
|
||||
|
||||
Daemon mode creates a config file at `/etc/asusd.conf` which you can edit a
|
||||
little of. Most parts will be byte arrays, but you can adjust things like
|
||||
`mode_performance`.
|
||||
|
||||
### DBUS Input
|
||||
|
||||
See [README_DBUS.md](./README_DBUS.md).
|
||||
|
||||
### AniMe input
|
||||
|
||||
You will want to look at what MeuMeu has done with [https://github.com/Meumeu/ZephyrusBling/](https://github.com/Meumeu/ZephyrusBling/)
|
||||
|
||||
### Wireshark captures
|
||||
|
||||
TODO: see `./wireshark_data/` for some captures.
|
||||
|
||||
### Supporting more laptops
|
||||
## Supporting more laptops
|
||||
|
||||
Please file a support request.
|
||||
|
||||
## License
|
||||
# License & Trademarks
|
||||
|
||||
Mozilla Public License 2 (MPL-2.0)
|
||||
|
||||
# Credits
|
||||
---
|
||||
|
||||
- [flukejones](https://github.com/flukejones/), project maintainer.
|
||||
- [tuxuser](https://github.com/tuxuser/)
|
||||
- [aspann](https://github.com/aspann)
|
||||
- [meumeu](https://github.com/Meumeu)
|
||||
- Anyone missed? Please contact me
|
||||
ASUS and ROG Trademark is either a US registered trademark or trademark of ASUSTeK Computer Inc. in the United States and/or other countries.
|
||||
|
||||
Reference to any ASUS products, services, processes, or other information and/or use of ASUS Trademarks does not constitute or imply endorsement, sponsorship, or recommendation thereof by ASUS.
|
||||
|
||||
The use of ROG and ASUS trademarks within this website and associated tools and libraries is only to provide a recognisable identifier to users to enable them to associate that these tools will work with ASUS ROG laptops.
|
||||
|
||||
---
|
||||
158
README_DBUS.md
@@ -1,158 +0,0 @@
|
||||
# DBUS Guide
|
||||
|
||||
```rust
|
||||
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
|
||||
pub static DBUS_PATH: &str = "/org/asuslinux/Daemon";
|
||||
pub static DBUS_IFACE: &str = "org.asuslinux.Daemon";
|
||||
```
|
||||
|
||||
## Methods
|
||||
|
||||
- `SetKeyBacklight`
|
||||
- `GetKeyBacklight`
|
||||
- `AnimatrixWrite`
|
||||
- `SetFanMode`
|
||||
- `GetFanMode`
|
||||
- `SetChargeLimit`
|
||||
- `GetChargeLimit`
|
||||
- `GetKeyBacklightModes`
|
||||
|
||||
## Signals
|
||||
|
||||
- `KeyBacklightChanged`
|
||||
- `FanModeChanged`
|
||||
- `ChargeLimitChanged`
|
||||
|
||||
## Method Inputs
|
||||
|
||||
### SetKeyBacklight
|
||||
|
||||
This method expects a string of JSON as input. The JSON is of format such:
|
||||
|
||||
```
|
||||
{
|
||||
"Static": {
|
||||
"colour": [ 255, 0, 0]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The possible contents of a mode are:
|
||||
|
||||
- `"colour": [u8, u8, u8],`
|
||||
- `"speed": <String>,` <Low, Med, High>
|
||||
- `"direction": <String>,` <Up, Down, Left, Right>
|
||||
|
||||
Modes may or may not be available for a specific laptop (TODO: dbus getter for
|
||||
supported modes). Modes are:
|
||||
|
||||
- `"Static": { "colour": <colour> },`
|
||||
- `"Pulse": { "colour": <colour> },`
|
||||
- `"Comet": { "colour": <colour> },`
|
||||
- `"Flash": { "colour": <colour> },`
|
||||
- `"Strobe": { "speed": <speed> },`
|
||||
- `"Rain": { "speed": <speed> },`
|
||||
- `"Laser": { "colour": <colour>, "speed": <speed> },`
|
||||
- `"Ripple": { "colour": <colour>, "speed": <speed> },`
|
||||
- `"Highlight": { "colour": <colour>, "speed": <speed> },`
|
||||
- `"Rainbow": { "direction": <direction>, "speed": <speed> },`
|
||||
- `"Breathe": { "colour": <colour>, "colour2": <colour>, "speed": <speed> },`
|
||||
- `"Star": { "colour": <colour>, "colour2": <colour>, "speed": <speed> },`
|
||||
- `"MultiStatic": { "colour1": <colour>, "colour2": <colour>, , "colour3": <colour>, "colour4": <colour> },`
|
||||
|
||||
Additionally to the above there is `"RGB": [[u8; 64]; 11]` which is for per-key
|
||||
setting of LED's but this requires some refactoring to make it easily useable over
|
||||
dbus.
|
||||
|
||||
Lastly, there is `"LedBrightness": <u8>` which accepts 0-3 for off, low, med, high.
|
||||
|
||||
### GetKeyBacklight
|
||||
|
||||
This method will return a JSON string in the same format as accepted by `SetKeyBacklight`.
|
||||
|
||||
### GetKeyBacklightModes
|
||||
|
||||
Will return a JSON string array of modes that this laptop accepts. The mode data
|
||||
within this will be the current settings per mode. Good for:
|
||||
|
||||
- Getting supported modes
|
||||
- Getting all mode settings
|
||||
|
||||
### AnimatrixWrite
|
||||
|
||||
Used to write data to the AniMe display if available. Currently is takes `[[u8; 640]; 2]`
|
||||
which must be the byte data that will be written directly to the USB device.
|
||||
|
||||
### SetFanMode
|
||||
|
||||
Accepts an integer from the following:
|
||||
|
||||
- `0`: Normal
|
||||
- `1`: Boost mode
|
||||
- `2`: Silent mode
|
||||
|
||||
### GetFanMode
|
||||
|
||||
Returns the integer set from above.
|
||||
|
||||
### SetChargeLimit
|
||||
|
||||
Accepts an integer in the range of 20-100.
|
||||
|
||||
### GetChargeLimit
|
||||
|
||||
Returns the integer set from above.
|
||||
|
||||
## Signal Outs
|
||||
|
||||
### KeyBacklightChanged
|
||||
|
||||
When emitted, it will emit the JSON data of the mode changed to, e.g:
|
||||
|
||||
```
|
||||
{
|
||||
"Static": {
|
||||
"colour": [ 255, 0, 0]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### FanModeChanged
|
||||
|
||||
When emitted, it will include the integer the fan mode was changed to.
|
||||
|
||||
### ChargeLimitChanged
|
||||
|
||||
When emitted, it will include the integer the charging limit was changed to.
|
||||
|
||||
## dbus-send examples
|
||||
|
||||
```
|
||||
dbus-send --system --type=method_call --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.asuslinux.Daemon.SetKeyBacklight string:'{"Static": {"colour": [ 80, 0, 40]}}'
|
||||
```
|
||||
|
||||
```
|
||||
dbus-send --system --type=method_call --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.asuslinux.Daemon.SetKeyBacklight string:'{"Star":{"colour":[0,255,255],"colour2":[0,0,0],"speed":"Med"}}'
|
||||
```
|
||||
|
||||
**Note:** setting colour2 to `[0,0,255]` activates random star colour. Colour2 has no effect on the
|
||||
mode otherwise.
|
||||
```
|
||||
dbus-send --system --type=method_call --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.asuslinux.Daemon.SetKeyBacklight string:'{"Star":{"colour":[0,255,255],"colour2":[0,0,255],"speed":"Med"}}'
|
||||
```
|
||||
|
||||
```
|
||||
dbus-send --system --type=method_call --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.asuslinux.Daemon.SetKeyBacklight string:'{"LedBrightness":3}'
|
||||
```
|
||||
|
||||
```
|
||||
dbus-send --system --type=method_call --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.asuslinux.Daemon.SetFanMode byte:'2'
|
||||
```
|
||||
|
||||
Monitoring dbus while sending commands via `rog-core` will give you the json structure if you are otherwise unsure, e.g: `dbus-monitor --system |grep -A2 asuslinux`.
|
||||
|
||||
## Getting an introspection .xml
|
||||
|
||||
```
|
||||
dbus-send --system --print-reply --dest=org.asuslinux.Daemon /org/asuslinux/Daemon org.freedesktop.DBus.Introspectable.Introspect > xml/dbus-0.14.4.xml
|
||||
```
|
||||
@@ -1,70 +0,0 @@
|
||||
%if %{defined fedora}
|
||||
%global debug_package %{nil}
|
||||
%endif
|
||||
|
||||
# Use hardening ldflags.
|
||||
%global rustflags -Clink-arg=-Wl,-z,relro,-z,now
|
||||
Name: asus-nb-ctrl
|
||||
Version: 1.0.0
|
||||
Release: 0
|
||||
Summary: Text editor for terminal
|
||||
License: MPLv2
|
||||
Group: Productivity/Text/Editors
|
||||
URL: https://gitlab.com/asus-linux/asus-nb-ctrl
|
||||
Source: %{name}-%{version}.tar.gz
|
||||
# cargo vendor &&
|
||||
# tar cfJ vendor.tar.xz vendor
|
||||
Source1: vendor.tar.xz
|
||||
BuildRequires: clang-devel
|
||||
BuildRequires: cargo
|
||||
BuildRequires: rust
|
||||
BuildRequires: rust-std-static
|
||||
BuildRequires: pkgconfig(dbus-1)
|
||||
BuildRequires: pkgconfig(libudev)
|
||||
|
||||
%description
|
||||
ASUS Laptop control
|
||||
|
||||
%prep
|
||||
%setup -q -n %name-next
|
||||
%setup -q -n %name-next -D -T -a 1
|
||||
|
||||
mkdir .cargo
|
||||
cat >.cargo/config <<EOF
|
||||
[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
||||
EOF
|
||||
|
||||
%build
|
||||
export RUSTFLAGS="%{rustflags}"
|
||||
RUST_BACKTRACE=1 cargo build --release
|
||||
|
||||
%install
|
||||
export RUSTFLAGS="%{rustflags}"
|
||||
|
||||
mkdir -p "%{buildroot}%{_bindir}"
|
||||
install -D -m 0755 target/release/asusd %{buildroot}%{_bindir}/asusd
|
||||
install -D -m 0755 target/release/asusctl %{buildroot}%{_bindir}/asusctl
|
||||
install -D -m 0644 data/asusd.rules %{buildroot}%{_udevrulesdir}/90-asusd.rules
|
||||
install -D -m 0644 data/asusd.conf %{buildroot}%{_sysconfdir}/dbus-1/system.d/asusd.conf
|
||||
install -D -m 0644 data/asusd.service %{buildroot}%{_unitdir}/asusd.service
|
||||
install -D -m 0644 data/asusd-ledmodes.toml %{buildroot}%{_sysconfdir}/asusd/asusd-ledmodes.toml
|
||||
|
||||
mkdir -p "%{buildroot}%{_datadir}/licenses/%{name}"
|
||||
cp LICENSE "%{buildroot}%{_datadir}/licenses/%{name}/"
|
||||
|
||||
mkdir -p "%{buildroot}/bin"
|
||||
|
||||
%files
|
||||
%license LICENSE
|
||||
%{_bindir}/asusd
|
||||
%{_bindir}/asusctl
|
||||
%{_unitdir}/asusd.service
|
||||
%{_udevrulesdir}/90-asusd.rules
|
||||
%{_sysconfdir}/dbus-1/system.d/asusd.conf
|
||||
%{_sysconfdir}/asusd/asusd-ledmodes.toml
|
||||
|
||||
%changelog
|
||||
1016
asus-nb-ctrl/Cargo.lock
generated
@@ -1,128 +0,0 @@
|
||||
use asus_nb::aura_modes::AuraModes;
|
||||
use log::{error, warn};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
pub static CONFIG_PATH: &str = "/etc/asusd/asusd.conf";
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct Config {
|
||||
pub power_profile: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub kbd_led_brightness: u8,
|
||||
pub kbd_backlight_mode: u8,
|
||||
pub kbd_backlight_modes: Vec<AuraModes>,
|
||||
pub power_profiles: FanModeProfile,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// `load` will attempt to read the config, but if it is not found it
|
||||
/// will create a new default config and write that out.
|
||||
pub fn load(mut self, supported_led_modes: &[u8]) -> Self {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&CONFIG_PATH)
|
||||
.unwrap(); // okay to cause panic here
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
self = Config::create_default(&mut file, &supported_led_modes);
|
||||
} else {
|
||||
self = serde_json::from_str(&buf).unwrap_or_else(|_| {
|
||||
warn!("Could not deserialise {}", CONFIG_PATH);
|
||||
Config::create_default(&mut file, &supported_led_modes)
|
||||
});
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
fn create_default(file: &mut File, supported_led_modes: &[u8]) -> Self {
|
||||
// create a default config here
|
||||
let mut c = Config::default();
|
||||
c.bat_charge_limit = 100;
|
||||
c.kbd_backlight_mode = 0;
|
||||
c.kbd_led_brightness = 1;
|
||||
|
||||
for n in supported_led_modes {
|
||||
c.kbd_backlight_modes.push(AuraModes::from(*n))
|
||||
}
|
||||
|
||||
// Should be okay to unwrap this as is since it is a Default
|
||||
let json = serde_json::to_string_pretty(&c).unwrap();
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|_| panic!("Could not write {}", CONFIG_PATH));
|
||||
c
|
||||
}
|
||||
|
||||
pub fn read(&mut self) {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&CONFIG_PATH)
|
||||
.unwrap_or_else(|err| panic!("Error reading {}: {}", CONFIG_PATH, err));
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("File is empty {}", CONFIG_PATH);
|
||||
} else {
|
||||
let x: Config = serde_json::from_str(&buf)
|
||||
.unwrap_or_else(|_| panic!("Could not deserialise {}", CONFIG_PATH));
|
||||
*self = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self) {
|
||||
let mut file = File::create(CONFIG_PATH).expect("Couldn't overwrite config");
|
||||
let json = serde_json::to_string_pretty(self).expect("Parse config to JSON failed");
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write config: {}", err));
|
||||
}
|
||||
|
||||
pub fn set_mode_data(&mut self, mode: AuraModes) {
|
||||
let byte: u8 = (&mode).into();
|
||||
for (index, n) in self.kbd_backlight_modes.iter().enumerate() {
|
||||
if byte == u8::from(n) {
|
||||
// Consume it, OMNOMNOMNOM
|
||||
self.kbd_backlight_modes[index] = mode;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_led_mode_data(&self, num: u8) -> Option<&AuraModes> {
|
||||
for mode in &self.kbd_backlight_modes {
|
||||
if u8::from(mode) == num {
|
||||
return Some(mode);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct FanModeProfile {
|
||||
pub normal: CPUSettings,
|
||||
pub boost: CPUSettings,
|
||||
pub silent: CPUSettings,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct CPUSettings {
|
||||
pub min_percentage: u8,
|
||||
pub max_percentage: u8,
|
||||
pub no_turbo: bool,
|
||||
}
|
||||
|
||||
impl Default for CPUSettings {
|
||||
fn default() -> Self {
|
||||
CPUSettings {
|
||||
min_percentage: 0,
|
||||
max_percentage: 100,
|
||||
no_turbo: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,225 +0,0 @@
|
||||
const INIT_STR: &str = "ASUS Tech.Inc.";
|
||||
const PACKET_SIZE: usize = 640;
|
||||
|
||||
// Only these two packets must be 17 bytes
|
||||
const DEV_PAGE: u8 = 0x5e;
|
||||
// These bytes are in [1] position of the array
|
||||
const WRITE: u8 = 0xc0;
|
||||
const INIT: u8 = 0xc2;
|
||||
const APPLY: u8 = 0xc3;
|
||||
const SET: u8 = 0xc4;
|
||||
|
||||
use crate::config::Config;
|
||||
use asus_nb::error::AuraError;
|
||||
use log::{error, info, warn};
|
||||
use rusb::{Device, DeviceHandle};
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum AnimatrixCommand {
|
||||
Apply,
|
||||
Set,
|
||||
WriteImage(Vec<Vec<u8>>),
|
||||
//ReloadLast,
|
||||
}
|
||||
|
||||
pub struct CtrlAnimeDisplay {
|
||||
handle: DeviceHandle<rusb::GlobalContext>,
|
||||
initialised: bool,
|
||||
}
|
||||
|
||||
use ::dbus::{nonblock::SyncConnection, tree::Signal};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Controller for CtrlAnimeDisplay {
|
||||
type A = Vec<Vec<u8>>;
|
||||
|
||||
/// Spawns two tasks which continuously check for changes
|
||||
fn spawn_task_loop(
|
||||
mut self,
|
||||
_: Arc<Mutex<Config>>,
|
||||
mut recv: Receiver<Self::A>,
|
||||
_: Option<Arc<SyncConnection>>,
|
||||
_: Option<Arc<Signal<()>>>,
|
||||
) -> Vec<JoinHandle<()>> {
|
||||
vec![tokio::spawn(async move {
|
||||
while let Some(image) = recv.recv().await {
|
||||
self.do_command(AnimatrixCommand::WriteImage(image))
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
})]
|
||||
}
|
||||
|
||||
async fn reload_from_config(&mut self, _: &mut Config) -> Result<(), Box<dyn Error>> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlAnimeDisplay {
|
||||
#[inline]
|
||||
pub fn new() -> Result<CtrlAnimeDisplay, Box<dyn Error>> {
|
||||
// We don't expect this ID to ever change
|
||||
let device = CtrlAnimeDisplay::get_device(0x0b05, 0x193b).map_err(|err| {
|
||||
warn!("Could not get AniMe display handle: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
let mut device = device.open()?;
|
||||
device.reset()?;
|
||||
|
||||
device.set_auto_detach_kernel_driver(true).map_err(|err| {
|
||||
error!("Auto-detach kernel driver failed: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
device.claim_interface(0).map_err(|err| {
|
||||
error!("Could not claim device interface: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
info!("Device has an AniMe Matrix display");
|
||||
Ok(CtrlAnimeDisplay {
|
||||
handle: device,
|
||||
initialised: false,
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_device(vendor: u16, product: u16) -> Result<Device<rusb::GlobalContext>, rusb::Error> {
|
||||
for device in rusb::devices()?.iter() {
|
||||
let device_desc = device.device_descriptor()?;
|
||||
if device_desc.vendor_id() == vendor && device_desc.product_id() == product {
|
||||
return Ok(device);
|
||||
}
|
||||
}
|
||||
Err(rusb::Error::NoDevice)
|
||||
}
|
||||
|
||||
pub async fn do_command(&mut self, command: AnimatrixCommand) -> Result<(), AuraError> {
|
||||
if !self.initialised {
|
||||
self.do_initialization().await?
|
||||
}
|
||||
|
||||
match command {
|
||||
AnimatrixCommand::WriteImage(effect) => self.write_image(effect).await?,
|
||||
AnimatrixCommand::Set => self.do_set().await?,
|
||||
AnimatrixCommand::Apply => self.do_apply().await?,
|
||||
//AnimatrixCommand::ReloadLast => self.reload_last_builtin(&config).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Should only be used if the bytes you are writing are verified correct
|
||||
#[inline]
|
||||
async fn write_bytes(&self, message: &[u8]) -> Result<(), AuraError> {
|
||||
let prev = std::time::Instant::now();
|
||||
match self.handle.write_control(
|
||||
0x21, // request_type
|
||||
0x09, // request
|
||||
0x35e, // value
|
||||
0x00, // index
|
||||
message,
|
||||
Duration::from_millis(200),
|
||||
) {
|
||||
Ok(_) => {
|
||||
println!(
|
||||
"{:?}",
|
||||
std::time::Instant::now().duration_since(prev).as_micros()
|
||||
);
|
||||
}
|
||||
Err(err) => match err {
|
||||
rusb::Error::Timeout => {}
|
||||
_ => error!("Failed to write to led interrupt: {:?}", err),
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write an Animatrix image
|
||||
///
|
||||
/// The expected input here is *two* Vectors, 640 bytes in length. The two vectors
|
||||
/// are each one half of the full image write.
|
||||
///
|
||||
/// After each write a flush is written, it is assumed that this tells the device to
|
||||
/// go ahead and display the written bytes
|
||||
///
|
||||
/// # Note:
|
||||
/// The vectors are expected to contain the full sequence of bytes as follows
|
||||
///
|
||||
/// - Write pane 1: 0x5e 0xc0 0x02 0x01 0x00 0x73 0x02 .. <led brightness>
|
||||
/// - Write pane 2: 0x5e 0xc0 0x02 0x74 0x02 0x73 0x02 .. <led brightness>
|
||||
///
|
||||
/// Where led brightness is 0..255, low to high
|
||||
#[inline]
|
||||
async fn write_image(&mut self, image: Vec<Vec<u8>>) -> Result<(), AuraError> {
|
||||
for row in image.iter() {
|
||||
self.write_bytes(row).await?;
|
||||
}
|
||||
self.do_flush().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn do_initialization(&mut self) -> Result<(), AuraError> {
|
||||
let mut init = [0; PACKET_SIZE];
|
||||
init[0] = DEV_PAGE; // This is the USB page we're using throughout
|
||||
for (idx, byte) in INIT_STR.as_bytes().iter().enumerate() {
|
||||
init[idx + 1] = *byte
|
||||
}
|
||||
self.write_bytes(&init).await?;
|
||||
|
||||
// clear the init array and write other init message
|
||||
for ch in init.iter_mut() {
|
||||
*ch = 0;
|
||||
}
|
||||
init[0] = DEV_PAGE; // write it to be sure?
|
||||
init[1] = INIT;
|
||||
|
||||
self.write_bytes(&init).await?;
|
||||
self.initialised = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn do_flush(&mut self) -> Result<(), AuraError> {
|
||||
let mut flush = [0; PACKET_SIZE];
|
||||
flush[0] = DEV_PAGE;
|
||||
flush[1] = WRITE;
|
||||
flush[2] = 0x03;
|
||||
|
||||
self.write_bytes(&flush).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn do_set(&mut self) -> Result<(), AuraError> {
|
||||
let mut flush = [0; PACKET_SIZE];
|
||||
flush[0] = DEV_PAGE;
|
||||
flush[1] = SET;
|
||||
flush[2] = 0x01;
|
||||
flush[3] = 0x80;
|
||||
|
||||
self.write_bytes(&flush).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn do_apply(&mut self) -> Result<(), AuraError> {
|
||||
let mut flush = [0; PACKET_SIZE];
|
||||
flush[0] = DEV_PAGE;
|
||||
flush[1] = APPLY;
|
||||
flush[2] = 0x01;
|
||||
flush[3] = 0x80;
|
||||
|
||||
self.write_bytes(&flush).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use crate::config::Config;
|
||||
use log::{error, info, warn};
|
||||
use std::error::Error;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
static BAT_CHARGE_PATH: &str = "/sys/class/power_supply/BAT0/charge_control_end_threshold";
|
||||
|
||||
pub struct CtrlCharge {
|
||||
path: &'static str,
|
||||
}
|
||||
|
||||
use ::dbus::{nonblock::SyncConnection, tree::Signal};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Controller for CtrlCharge {
|
||||
type A = u8;
|
||||
|
||||
/// Spawns two tasks which continuously check for changes
|
||||
fn spawn_task_loop(
|
||||
self,
|
||||
config: Arc<Mutex<Config>>,
|
||||
mut recv: Receiver<Self::A>,
|
||||
_: Option<Arc<SyncConnection>>,
|
||||
_: Option<Arc<Signal<()>>>,
|
||||
) -> Vec<JoinHandle<()>> {
|
||||
vec![tokio::spawn(async move {
|
||||
while let Some(n) = recv.recv().await {
|
||||
let mut config = config.lock().await;
|
||||
self.set_charge_limit(n, &mut config)
|
||||
.unwrap_or_else(|err| warn!("{:?}", err));
|
||||
}
|
||||
})]
|
||||
}
|
||||
|
||||
async fn reload_from_config(&mut self, config: &mut Config) -> Result<(), Box<dyn Error>> {
|
||||
config.read();
|
||||
info!("Reloaded battery charge limit");
|
||||
self.set_charge_limit(config.bat_charge_limit, config)
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlCharge {
|
||||
pub fn new() -> Result<Self, Box<dyn Error>> {
|
||||
let path = CtrlCharge::get_battery_path()?;
|
||||
info!("Device has battery charge threshold control");
|
||||
Ok(CtrlCharge { path })
|
||||
}
|
||||
|
||||
fn get_battery_path() -> Result<&'static str, std::io::Error> {
|
||||
if Path::new(BAT_CHARGE_PATH).exists() {
|
||||
Ok(BAT_CHARGE_PATH)
|
||||
} else {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"Charge control not available",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_charge_limit(
|
||||
&self,
|
||||
limit: u8,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
if limit < 20 || limit > 100 {
|
||||
warn!(
|
||||
"Unable to set battery charge limit, must be between 20-100: requested {}",
|
||||
limit
|
||||
);
|
||||
}
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(self.path)
|
||||
.map_err(|err| {
|
||||
warn!("Failed to open battery charge limit path: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
file.write_all(limit.to_string().as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write to {}, {:?}", BAT_CHARGE_PATH, err));
|
||||
info!("Battery charge limit: {}", limit);
|
||||
|
||||
config.read();
|
||||
config.bat_charge_limit = limit;
|
||||
config.write();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
use crate::config::Config;
|
||||
use log::{error, info, warn};
|
||||
use std::error::Error;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
static FAN_TYPE_1_PATH: &str = "/sys/devices/platform/asus-nb-wmi/throttle_thermal_policy";
|
||||
static FAN_TYPE_2_PATH: &str = "/sys/devices/platform/asus-nb-wmi/fan_boost_mode";
|
||||
static AMD_BOOST_PATH: &str = "/sys/devices/system/cpu/cpufreq/boost";
|
||||
|
||||
pub struct CtrlFanAndCPU {
|
||||
path: &'static str,
|
||||
}
|
||||
|
||||
use ::dbus::{nonblock::SyncConnection, tree::Signal};
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Controller for CtrlFanAndCPU {
|
||||
type A = u8;
|
||||
|
||||
/// Spawns two tasks which continuously check for changes
|
||||
fn spawn_task_loop(
|
||||
self,
|
||||
config: Arc<Mutex<Config>>,
|
||||
mut recv: Receiver<Self::A>,
|
||||
_: Option<Arc<SyncConnection>>,
|
||||
_: Option<Arc<Signal<()>>>,
|
||||
) -> Vec<JoinHandle<()>> {
|
||||
let gate1 = Arc::new(Mutex::new(self));
|
||||
let gate2 = gate1.clone();
|
||||
let config1 = config.clone();
|
||||
// spawn an endless loop
|
||||
vec![
|
||||
tokio::spawn(async move {
|
||||
while let Some(mode) = recv.recv().await {
|
||||
let mut config = config1.lock().await;
|
||||
let mut lock = gate1.lock().await;
|
||||
lock.set_fan_mode(mode, &mut config)
|
||||
.unwrap_or_else(|err| warn!("{:?}", err));
|
||||
}
|
||||
}),
|
||||
// need to watch file path
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::delay_for(std::time::Duration::from_millis(100)).await;
|
||||
let mut lock = gate2.lock().await;
|
||||
let mut config = config.lock().await;
|
||||
lock.fan_mode_check_change(&mut config)
|
||||
.unwrap_or_else(|err| warn!("{:?}", err));
|
||||
}
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
async fn reload_from_config(&mut self, config: &mut Config) -> Result<(), Box<dyn Error>> {
|
||||
let mut file = OpenOptions::new().write(true).open(self.path)?;
|
||||
file.write_all(format!("{:?}\n", config.power_profile).as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write to {}, {:?}", self.path, err));
|
||||
self.set_pstate_for_fan_mode(FanLevel::from(config.power_profile), config)?;
|
||||
info!(
|
||||
"Reloaded fan mode: {:?}",
|
||||
FanLevel::from(config.power_profile)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlFanAndCPU {
|
||||
pub fn new() -> Result<Self, Box<dyn Error>> {
|
||||
let path = CtrlFanAndCPU::get_fan_path()?;
|
||||
info!("Device has thermal throttle control");
|
||||
Ok(CtrlFanAndCPU { path })
|
||||
}
|
||||
|
||||
fn get_fan_path() -> Result<&'static str, std::io::Error> {
|
||||
if Path::new(FAN_TYPE_1_PATH).exists() {
|
||||
Ok(FAN_TYPE_1_PATH)
|
||||
} else if Path::new(FAN_TYPE_2_PATH).exists() {
|
||||
Ok(FAN_TYPE_2_PATH)
|
||||
} else {
|
||||
Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"Fan mode not available",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn fan_mode_check_change(
|
||||
&mut self,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let mut file = OpenOptions::new().read(true).open(self.path)?;
|
||||
let mut buf = [0u8; 1];
|
||||
file.read_exact(&mut buf)?;
|
||||
if let Some(num) = char::from(buf[0]).to_digit(10) {
|
||||
if config.power_profile != num as u8 {
|
||||
config.read();
|
||||
config.power_profile = num as u8;
|
||||
config.write();
|
||||
self.set_pstate_for_fan_mode(FanLevel::from(config.power_profile), config)?;
|
||||
info!(
|
||||
"Fan mode was changed: {:?}",
|
||||
FanLevel::from(config.power_profile)
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let err = std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Fan-level could not be parsed",
|
||||
);
|
||||
Err(Box::new(err))
|
||||
}
|
||||
|
||||
pub(super) fn set_fan_mode(
|
||||
&mut self,
|
||||
n: u8,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let mut fan_ctrl = OpenOptions::new().write(true).open(self.path)?;
|
||||
config.read();
|
||||
config.power_profile = n;
|
||||
config.write();
|
||||
fan_ctrl
|
||||
.write_all(format!("{:?}\n", config.power_profile).as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write to {}, {:?}", self.path, err));
|
||||
info!(
|
||||
"Fan mode set to: {:?}",
|
||||
FanLevel::from(config.power_profile)
|
||||
);
|
||||
self.set_pstate_for_fan_mode(FanLevel::from(n), config)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_pstate_for_fan_mode(
|
||||
&self,
|
||||
mode: FanLevel,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
// Set CPU pstate
|
||||
if let Ok(pstate) = intel_pstate::PState::new() {
|
||||
match mode {
|
||||
FanLevel::Normal => {
|
||||
pstate.set_min_perf_pct(config.power_profiles.normal.min_percentage)?;
|
||||
pstate.set_max_perf_pct(config.power_profiles.normal.max_percentage)?;
|
||||
pstate.set_no_turbo(config.power_profiles.normal.no_turbo)?;
|
||||
info!(
|
||||
"Intel CPU Power: min: {:?}%, max: {:?}%, turbo: {:?}",
|
||||
config.power_profiles.normal.min_percentage,
|
||||
config.power_profiles.normal.max_percentage,
|
||||
!config.power_profiles.normal.no_turbo
|
||||
);
|
||||
}
|
||||
FanLevel::Boost => {
|
||||
pstate.set_min_perf_pct(config.power_profiles.boost.min_percentage)?;
|
||||
pstate.set_max_perf_pct(config.power_profiles.boost.max_percentage)?;
|
||||
pstate.set_no_turbo(config.power_profiles.boost.no_turbo)?;
|
||||
info!(
|
||||
"Intel CPU Power: min: {:?}%, max: {:?}%, turbo: {:?}",
|
||||
config.power_profiles.boost.min_percentage,
|
||||
config.power_profiles.boost.max_percentage,
|
||||
!config.power_profiles.boost.no_turbo
|
||||
);
|
||||
}
|
||||
FanLevel::Silent => {
|
||||
pstate.set_min_perf_pct(config.power_profiles.silent.min_percentage)?;
|
||||
pstate.set_max_perf_pct(config.power_profiles.silent.max_percentage)?;
|
||||
pstate.set_no_turbo(config.power_profiles.silent.no_turbo)?;
|
||||
info!(
|
||||
"Intel CPU Power: min: {:?}%, max: {:?}%, turbo: {:?}",
|
||||
config.power_profiles.silent.min_percentage,
|
||||
config.power_profiles.silent.max_percentage,
|
||||
!config.power_profiles.silent.no_turbo
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("Setting pstate for AMD CPU");
|
||||
// must be AMD CPU
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(AMD_BOOST_PATH)
|
||||
.map_err(|err| {
|
||||
warn!("Failed to open AMD boost: {:?}", err);
|
||||
err
|
||||
})?;
|
||||
match mode {
|
||||
FanLevel::Normal => {
|
||||
let boost = if config.power_profiles.normal.no_turbo {
|
||||
"0"
|
||||
} else {
|
||||
"1"
|
||||
}; // opposite of Intel
|
||||
file.write_all(boost.as_bytes()).unwrap_or_else(|err| {
|
||||
error!("Could not write to {}, {:?}", AMD_BOOST_PATH, err)
|
||||
});
|
||||
info!("AMD CPU Turbo: {:?}", boost);
|
||||
}
|
||||
FanLevel::Boost => {
|
||||
let boost = if config.power_profiles.boost.no_turbo {
|
||||
"0"
|
||||
} else {
|
||||
"1"
|
||||
};
|
||||
file.write_all(boost.as_bytes()).unwrap_or_else(|err| {
|
||||
error!("Could not write to {}, {:?}", AMD_BOOST_PATH, err)
|
||||
});
|
||||
info!("AMD CPU Turbo: {:?}", boost);
|
||||
}
|
||||
FanLevel::Silent => {
|
||||
let boost = if config.power_profiles.silent.no_turbo {
|
||||
"0"
|
||||
} else {
|
||||
"1"
|
||||
};
|
||||
file.write_all(boost.as_bytes()).unwrap_or_else(|err| {
|
||||
error!("Could not write to {}, {:?}", AMD_BOOST_PATH, err)
|
||||
});
|
||||
info!("AMD CPU Turbo: {:?}", boost);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FanLevel {
|
||||
Normal,
|
||||
Boost,
|
||||
Silent,
|
||||
}
|
||||
|
||||
impl FromStr for FanLevel {
|
||||
type Err = RogError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, RogError> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"normal" => Ok(FanLevel::Normal),
|
||||
"boost" => Ok(FanLevel::Boost),
|
||||
"silent" => Ok(FanLevel::Silent),
|
||||
_ => Err(RogError::ParseFanLevel),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for FanLevel {
|
||||
fn from(n: u8) -> Self {
|
||||
match n {
|
||||
0 => FanLevel::Normal,
|
||||
1 => FanLevel::Boost,
|
||||
2 => FanLevel::Silent,
|
||||
_ => FanLevel::Normal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FanLevel> for u8 {
|
||||
fn from(n: FanLevel) -> Self {
|
||||
match n {
|
||||
FanLevel::Normal => 0,
|
||||
FanLevel::Boost => 1,
|
||||
FanLevel::Silent => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
// Only these two packets must be 17 bytes
|
||||
static LED_APPLY: [u8; 17] = [0x5d, 0xb4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
static LED_SET: [u8; 17] = [0x5d, 0xb5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
|
||||
use crate::{config::Config, error::RogError};
|
||||
use asus_nb::{
|
||||
aura_brightness_bytes, aura_modes::AuraModes, fancy::KeyColourArray, DBUS_IFACE, DBUS_PATH,
|
||||
LED_MSG_LEN,
|
||||
};
|
||||
use dbus::{channel::Sender, nonblock::SyncConnection, tree::Signal};
|
||||
use log::{info, warn};
|
||||
use std::error::Error;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
pub struct CtrlKbdBacklight {
|
||||
led_node: String,
|
||||
kbd_node: String,
|
||||
bright_node: String,
|
||||
supported_modes: Vec<u8>,
|
||||
flip_effect_write: bool,
|
||||
}
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Controller for CtrlKbdBacklight {
|
||||
type A = AuraModes;
|
||||
|
||||
/// Spawns two tasks which continuously check for changes
|
||||
fn spawn_task_loop(
|
||||
self,
|
||||
config: Arc<Mutex<Config>>,
|
||||
mut recv: Receiver<Self::A>,
|
||||
connection: Option<Arc<SyncConnection>>,
|
||||
signal: Option<Arc<Signal<()>>>,
|
||||
) -> Vec<JoinHandle<()>> {
|
||||
let gate1 = Arc::new(Mutex::new(self));
|
||||
let gate2 = gate1.clone();
|
||||
|
||||
let config1 = config.clone();
|
||||
vec![
|
||||
tokio::spawn(async move {
|
||||
while let Some(command) = recv.recv().await {
|
||||
let mut config = config1.lock().await;
|
||||
let mut lock = gate1.lock().await;
|
||||
match &command {
|
||||
AuraModes::PerKey(_) => {
|
||||
lock.do_command(command, &mut config)
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
_ => {
|
||||
let json = serde_json::to_string(&command).unwrap();
|
||||
lock.do_command(command, &mut config)
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
connection
|
||||
.as_ref()
|
||||
.expect("LED Controller must have DBUS connection")
|
||||
.send(
|
||||
signal
|
||||
.as_ref()
|
||||
.expect("LED Controller must have DBUS signal")
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(json),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
tokio::time::delay_for(std::time::Duration::from_millis(100)).await;
|
||||
let mut lock = gate2.lock().await;
|
||||
let mut config = config.lock().await;
|
||||
lock.let_bright_check_change(&mut config)
|
||||
.unwrap_or_else(|err| warn!("{:?}", err));
|
||||
}
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
async fn reload_from_config(&mut self, config: &mut Config) -> Result<(), Box<dyn Error>> {
|
||||
// set current mode (if any)
|
||||
if self.supported_modes.len() > 1 {
|
||||
if self.supported_modes.contains(&config.kbd_backlight_mode) {
|
||||
let mode = config
|
||||
.get_led_mode_data(config.kbd_backlight_mode)
|
||||
.ok_or(RogError::NotSupported)?
|
||||
.to_owned();
|
||||
self.write_mode(&mode).await?;
|
||||
info!("Reloaded last used mode");
|
||||
} else {
|
||||
warn!(
|
||||
"An unsupported mode was set: {}, reset to first mode available",
|
||||
<&str>::from(&<AuraModes>::from(config.kbd_backlight_mode))
|
||||
);
|
||||
for (idx, mode) in config.kbd_backlight_modes.iter_mut().enumerate() {
|
||||
if !self.supported_modes.contains(&mode.into()) {
|
||||
config.kbd_backlight_modes.remove(idx);
|
||||
config.write();
|
||||
break;
|
||||
}
|
||||
}
|
||||
config.kbd_backlight_mode = self.supported_modes[0];
|
||||
// TODO: do a recursive call with a boxed dyn future later
|
||||
let mode = config
|
||||
.get_led_mode_data(config.kbd_backlight_mode)
|
||||
.ok_or(RogError::NotSupported)?
|
||||
.to_owned();
|
||||
self.write_mode(&mode).await?;
|
||||
info!("Reloaded last used mode");
|
||||
}
|
||||
}
|
||||
|
||||
// Reload brightness
|
||||
let bright = config.kbd_led_brightness;
|
||||
let bytes = aura_brightness_bytes(bright);
|
||||
self.write_bytes(&bytes).await?;
|
||||
info!("Reloaded last used brightness");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlKbdBacklight {
|
||||
#[inline]
|
||||
pub fn new(id_product: &str, supported_modes: Vec<u8>) -> Result<Self, std::io::Error> {
|
||||
Ok(CtrlKbdBacklight {
|
||||
led_node: Self::scan_led_node(id_product)?,
|
||||
kbd_node: Self::scan_kbd_node(id_product)?,
|
||||
// brightness node path should always be constant but this *might* change?
|
||||
bright_node: "/sys/class/leds/asus::kbd_backlight/brightness".to_string(),
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_led_node(id_product: &str) -> Result<String, std::io::Error> {
|
||||
let mut enumerator = udev::Enumerator::new()?;
|
||||
enumerator.match_subsystem("hidraw")?;
|
||||
|
||||
for device in enumerator.scan_devices()? {
|
||||
if let Some(parent) = device.parent_with_subsystem_devtype("usb", "usb_device")? {
|
||||
if parent.attribute_value("idProduct").unwrap() == id_product {
|
||||
// && device.parent().unwrap().sysnum().unwrap() == 3
|
||||
if let Some(dev_node) = device.devnode() {
|
||||
info!("Using device at: {:?} for LED control", dev_node);
|
||||
return Ok(dev_node.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let err = std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"ASUS LED device node not found",
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
|
||||
fn scan_kbd_node(id_product: &str) -> Result<String, std::io::Error> {
|
||||
let mut enumerator = udev::Enumerator::new()?;
|
||||
enumerator.match_subsystem("input")?;
|
||||
enumerator.match_property("ID_MODEL_ID", id_product)?;
|
||||
|
||||
for device in enumerator.scan_devices()? {
|
||||
if let Some(dev_node) = device.devnode() {
|
||||
if let Some(inum) = device.property_value("ID_USB_INTERFACE_NUM") {
|
||||
if inum == "02" {
|
||||
info!("Using device at: {:?} for keyboard polling", dev_node);
|
||||
return Ok(dev_node.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let err = std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"ASUS N-Key Consumer Device node not found",
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
|
||||
fn let_bright_check_change(&mut self, config: &mut Config) -> Result<(), Box<dyn Error>> {
|
||||
let mut file = OpenOptions::new().read(true).open(&self.bright_node)?;
|
||||
let mut buf = [0u8; 1];
|
||||
file.read_exact(&mut buf)?;
|
||||
if let Some(num) = char::from(buf[0]).to_digit(10) {
|
||||
if config.kbd_led_brightness != num as u8 {
|
||||
config.read();
|
||||
config.kbd_led_brightness = num as u8;
|
||||
config.write();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let err = std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"LED brightness could not be parsed",
|
||||
);
|
||||
Err(Box::new(err))
|
||||
}
|
||||
|
||||
pub async fn do_command(
|
||||
&mut self,
|
||||
mode: AuraModes,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
self.set_and_save(mode, config).await
|
||||
}
|
||||
|
||||
/// Should only be used if the bytes you are writing are verified correct
|
||||
#[inline]
|
||||
async fn write_bytes(&self, message: &[u8]) -> Result<(), Box<dyn Error>> {
|
||||
if let Ok(mut file) = OpenOptions::new().write(true).open(&self.led_node) {
|
||||
file.write_all(message).unwrap();
|
||||
return Ok(());
|
||||
}
|
||||
Err(Box::new(RogError::NotSupported))
|
||||
}
|
||||
|
||||
/// Write an effect block
|
||||
#[inline]
|
||||
async fn write_effect(&mut self, effect: &[Vec<u8>]) -> Result<(), Box<dyn Error>> {
|
||||
if self.flip_effect_write {
|
||||
for row in effect.iter().rev() {
|
||||
self.write_bytes(row).await?;
|
||||
}
|
||||
} else {
|
||||
for row in effect.iter() {
|
||||
self.write_bytes(row).await?;
|
||||
}
|
||||
}
|
||||
self.flip_effect_write = !self.flip_effect_write;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Used to set a builtin mode and save the settings for it
|
||||
///
|
||||
/// This needs to be universal so that settings applied by dbus stick
|
||||
#[inline]
|
||||
async fn set_and_save(
|
||||
&mut self,
|
||||
mode: AuraModes,
|
||||
config: &mut Config,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
match mode {
|
||||
AuraModes::LedBrightness(n) => {
|
||||
let bytes: [u8; LED_MSG_LEN] = (&mode).into();
|
||||
self.write_bytes(&bytes).await?;
|
||||
config.read();
|
||||
config.kbd_led_brightness = n;
|
||||
config.write();
|
||||
info!("LED brightness set to {:#?}", n);
|
||||
}
|
||||
AuraModes::PerKey(v) => {
|
||||
if v.is_empty() || v[0].is_empty() {
|
||||
let bytes = KeyColourArray::get_init_msg();
|
||||
self.write_bytes(&bytes).await?;
|
||||
} else {
|
||||
self.write_effect(&v).await?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
config.read();
|
||||
let mode_num: u8 = u8::from(&mode);
|
||||
self.write_mode(&mode).await?;
|
||||
config.kbd_backlight_mode = mode_num;
|
||||
config.set_mode_data(mode);
|
||||
config.write();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
async fn write_mode(&mut self, mode: &AuraModes) -> Result<(), Box<dyn Error>> {
|
||||
match mode {
|
||||
AuraModes::PerKey(v) => {
|
||||
if v.is_empty() || v[0].is_empty() {
|
||||
let bytes = KeyColourArray::get_init_msg();
|
||||
self.write_bytes(&bytes).await?;
|
||||
} else {
|
||||
self.write_effect(v).await?;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let mode_num: u8 = u8::from(mode);
|
||||
match mode {
|
||||
AuraModes::MultiStatic(_) => {
|
||||
if self.supported_modes.contains(&mode_num) {
|
||||
let bytes: [[u8; LED_MSG_LEN]; 4] = mode.into();
|
||||
for array in bytes.iter() {
|
||||
self.write_bytes(array).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if self.supported_modes.contains(&mode_num) {
|
||||
let bytes: [u8; LED_MSG_LEN] = mode.into();
|
||||
self.write_bytes(&bytes).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.write_bytes(&LED_SET).await?;
|
||||
// Changes won't persist unless apply is set
|
||||
self.write_bytes(&LED_APPLY).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
use daemon::{
|
||||
config::Config, ctrl_anime::CtrlAnimeDisplay, ctrl_charge::CtrlCharge,
|
||||
ctrl_fan_cpu::CtrlFanAndCPU, ctrl_leds::CtrlKbdBacklight, dbus::dbus_create_tree,
|
||||
laptops::match_laptop,
|
||||
};
|
||||
|
||||
use dbus::{
|
||||
channel::Sender,
|
||||
nonblock::{Process, SyncConnection},
|
||||
tree::Signal,
|
||||
};
|
||||
use dbus_tokio::connection;
|
||||
|
||||
use asus_nb::{DBUS_IFACE, DBUS_NAME, DBUS_PATH};
|
||||
use daemon::Controller;
|
||||
use log::LevelFilter;
|
||||
use log::{error, info, warn};
|
||||
use std::error::Error;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[tokio::main]
|
||||
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut logger = env_logger::Builder::new();
|
||||
logger
|
||||
.target(env_logger::Target::Stdout)
|
||||
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
|
||||
.filter(None, LevelFilter::Info)
|
||||
.init();
|
||||
|
||||
info!("Version: {}", daemon::VERSION);
|
||||
start_daemon().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Timing is such that:
|
||||
// - interrupt write is minimum 1ms (sometimes lower)
|
||||
// - read interrupt must timeout, minimum of 1ms
|
||||
// - for a single usb packet, 2ms total.
|
||||
// - to maintain constant times of 1ms, per-key colours should use
|
||||
// the effect endpoint so that the complete colour block is written
|
||||
// as fast as 1ms per row of the matrix inside it. (10ms total time)
|
||||
//
|
||||
// DBUS processing takes 6ms if not tokiod
|
||||
pub async fn start_daemon() -> Result<(), Box<dyn Error>> {
|
||||
let laptop = match_laptop();
|
||||
let mut config = if let Some(laptop) = laptop.as_ref() {
|
||||
Config::default().load(laptop.supported_modes())
|
||||
} else {
|
||||
Config::default().load(&[])
|
||||
};
|
||||
|
||||
let mut led_control = if let Some(laptop) = laptop {
|
||||
CtrlKbdBacklight::new(laptop.usb_product(), laptop.supported_modes().to_owned())
|
||||
.map_or_else(
|
||||
|err| {
|
||||
error!("{}", err);
|
||||
None
|
||||
},
|
||||
Some,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mut charge_control = CtrlCharge::new().map_or_else(
|
||||
|err| {
|
||||
error!("{}", err);
|
||||
None
|
||||
},
|
||||
Some,
|
||||
);
|
||||
|
||||
let mut fan_control = CtrlFanAndCPU::new().map_or_else(
|
||||
|err| {
|
||||
error!("{}", err);
|
||||
None
|
||||
},
|
||||
Some,
|
||||
);
|
||||
|
||||
// Reload settings
|
||||
if let Some(ctrl) = fan_control.as_mut() {
|
||||
ctrl.reload_from_config(&mut config)
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Fan mode: {}", err));
|
||||
}
|
||||
|
||||
if let Some(ctrl) = charge_control.as_mut() {
|
||||
ctrl.reload_from_config(&mut config)
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Battery charge limit: {}", err));
|
||||
}
|
||||
|
||||
if let Some(ctrl) = led_control.as_mut() {
|
||||
ctrl.reload_from_config(&mut config)
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Reload settings: {}", err));
|
||||
}
|
||||
|
||||
let (resource, connection) = connection::new_system_sync()?;
|
||||
tokio::spawn(async {
|
||||
let err = resource.await;
|
||||
panic!("Lost connection to D-Bus: {}", err);
|
||||
});
|
||||
|
||||
connection
|
||||
.request_name(DBUS_NAME, false, true, true)
|
||||
.await?;
|
||||
|
||||
let config = Arc::new(Mutex::new(config));
|
||||
let (
|
||||
tree,
|
||||
aura_command_recv,
|
||||
animatrix_recv,
|
||||
fan_mode_recv,
|
||||
charge_limit_recv,
|
||||
led_changed_signal,
|
||||
fanmode_signal,
|
||||
charge_limit_signal,
|
||||
) = dbus_create_tree(config.clone());
|
||||
|
||||
// We add the tree to the connection so that incoming method calls will be handled.
|
||||
tree.start_receive_send(&*connection);
|
||||
|
||||
// Send boot signals
|
||||
send_boot_signals(
|
||||
connection.clone(),
|
||||
config.clone(),
|
||||
fanmode_signal.clone(),
|
||||
charge_limit_signal.clone(),
|
||||
led_changed_signal.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// For helping with processing signals
|
||||
start_signal_task(
|
||||
connection.clone(),
|
||||
config.clone(),
|
||||
fanmode_signal,
|
||||
charge_limit_signal,
|
||||
);
|
||||
|
||||
// Begin all tasks
|
||||
let mut handles = Vec::new();
|
||||
if let Ok(ctrl) = CtrlAnimeDisplay::new() {
|
||||
handles.append(&mut ctrl.spawn_task_loop(config.clone(), animatrix_recv, None, None));
|
||||
}
|
||||
|
||||
if let Some(ctrl) = fan_control.take() {
|
||||
handles.append(&mut ctrl.spawn_task_loop(config.clone(), fan_mode_recv, None, None));
|
||||
}
|
||||
|
||||
if let Some(ctrl) = charge_control.take() {
|
||||
handles.append(&mut ctrl.spawn_task_loop(config.clone(), charge_limit_recv, None, None));
|
||||
}
|
||||
|
||||
if let Some(ctrl) = led_control.take() {
|
||||
handles.append(&mut ctrl.spawn_task_loop(
|
||||
config.clone(),
|
||||
aura_command_recv,
|
||||
Some(connection.clone()),
|
||||
Some(led_changed_signal),
|
||||
));
|
||||
}
|
||||
|
||||
connection.process_all();
|
||||
for handle in handles {
|
||||
handle.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO: Move these in to the controllers tasks
|
||||
fn start_signal_task(
|
||||
connection: Arc<SyncConnection>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
fanmode_signal: Arc<Signal<()>>,
|
||||
charge_limit_signal: Arc<Signal<()>>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
// Some small things we need to track, without passing all sorts of stuff around
|
||||
let mut last_fan_mode = config.lock().await.power_profile;
|
||||
let mut last_charge_limit = config.lock().await.bat_charge_limit;
|
||||
loop {
|
||||
// Use tokio sleep to not hold up other threads
|
||||
tokio::time::delay_for(std::time::Duration::from_millis(500)).await;
|
||||
|
||||
let config = config.lock().await;
|
||||
if config.power_profile != last_fan_mode {
|
||||
last_fan_mode = config.power_profile;
|
||||
connection
|
||||
.send(
|
||||
fanmode_signal
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(last_fan_mode),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
}
|
||||
|
||||
if config.bat_charge_limit != last_charge_limit {
|
||||
last_charge_limit = config.bat_charge_limit;
|
||||
connection
|
||||
.send(
|
||||
charge_limit_signal
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(last_charge_limit),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn send_boot_signals(
|
||||
connection: Arc<SyncConnection>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
fanmode_signal: Arc<Signal<()>>,
|
||||
charge_limit_signal: Arc<Signal<()>>,
|
||||
led_changed_signal: Arc<Signal<()>>,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let config = config.lock().await;
|
||||
|
||||
if let Some(data) = config.get_led_mode_data(config.kbd_backlight_mode) {
|
||||
connection
|
||||
.send(
|
||||
led_changed_signal
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(serde_json::to_string(data)?),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
}
|
||||
|
||||
connection
|
||||
.send(
|
||||
fanmode_signal
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(config.power_profile),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
|
||||
connection
|
||||
.send(
|
||||
charge_limit_signal
|
||||
.msg(&DBUS_PATH.into(), &DBUS_IFACE.into())
|
||||
.append1(config.bat_charge_limit),
|
||||
)
|
||||
.unwrap_or_else(|_| 0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
use crate::config::Config;
|
||||
use asus_nb::{aura_modes::AuraModes, DBUS_IFACE, DBUS_PATH};
|
||||
use dbus::tree::{Factory, MTSync, Method, MethodErr, Signal, Tree};
|
||||
use log::warn;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{
|
||||
mpsc::{channel, Receiver, Sender},
|
||||
Mutex,
|
||||
};
|
||||
|
||||
fn set_keyboard_backlight(sender: Mutex<Sender<AuraModes>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
// method for ledmessage
|
||||
.method("SetKeyBacklight", (), {
|
||||
move |m| {
|
||||
let json: &str = m.msg.read1()?;
|
||||
if let Ok(mut lock) = sender.try_lock() {
|
||||
if let Ok(data) = serde_json::from_str(json) {
|
||||
lock.try_send(data).unwrap_or_else(|err| {
|
||||
warn!("SetKeyBacklight over mpsc failed: {}", err)
|
||||
});
|
||||
} else {
|
||||
warn!("SetKeyBacklight could not deserialise");
|
||||
}
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock daemon for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.inarg::<&str, _>("json")
|
||||
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
|
||||
}
|
||||
|
||||
fn get_keyboard_backlight(config: Arc<Mutex<Config>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
.method("GetKeyBacklight", (), {
|
||||
move |m| {
|
||||
if let Ok(lock) = config.try_lock() {
|
||||
for mode in &lock.kbd_backlight_modes {
|
||||
if lock.kbd_backlight_mode == <u8>::from(mode) {
|
||||
let mode = serde_json::to_string(&mode).unwrap();
|
||||
let mret = m.msg.method_return().append1(mode);
|
||||
return Ok(vec![mret]);
|
||||
}
|
||||
}
|
||||
Err(MethodErr::failed(
|
||||
"Keyboard LED mode set to an invalid mode",
|
||||
))
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock config for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.outarg::<&str, _>("json")
|
||||
}
|
||||
|
||||
fn get_keyboard_backlight_modes(config: Arc<Mutex<Config>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
.method("GetKeyBacklightModes", (), {
|
||||
move |m| {
|
||||
if let Ok(lock) = config.try_lock() {
|
||||
let mode = serde_json::to_string(&lock.kbd_backlight_modes).unwrap();
|
||||
let mret = m.msg.method_return().append1(mode);
|
||||
Ok(vec![mret])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock config for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.outarg::<&str, _>("json")
|
||||
}
|
||||
|
||||
fn set_animatrix(
|
||||
sender: Mutex<Sender<Vec<Vec<u8>>>>, // need mutex only to get interior mutability in MTSync
|
||||
) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
// method for ledmessage
|
||||
.method("AnimatrixWrite", (), {
|
||||
move |m| {
|
||||
let mut iter = m.msg.iter_init();
|
||||
let byte_array: Vec<Vec<u8>> = vec![iter.read()?, iter.read()?];
|
||||
if let Ok(mut lock) = sender.try_lock() {
|
||||
// Ignore errors if the channel is already full
|
||||
lock.try_send(byte_array).unwrap_or_else(|_err| {});
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock daemon for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.inarg::<Vec<u8>, _>("bytearray1")
|
||||
.inarg::<Vec<u8>, _>("bytearray2")
|
||||
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
|
||||
}
|
||||
|
||||
fn set_fan_mode(sender: Mutex<Sender<u8>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
// method for ledmessage
|
||||
.method("SetFanMode", (), {
|
||||
move |m| {
|
||||
if let Ok(mut lock) = sender.try_lock() {
|
||||
let mut iter = m.msg.iter_init();
|
||||
let byte: u8 = iter.read()?;
|
||||
lock.try_send(byte).unwrap_or_else(|_err| {});
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock daemon for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.inarg::<u8, _>("mode")
|
||||
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
|
||||
}
|
||||
|
||||
fn get_fan_mode(config: Arc<Mutex<Config>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
.method("GetFanMode", (), {
|
||||
move |m| {
|
||||
if let Ok(lock) = config.try_lock() {
|
||||
let mret = m.msg.method_return().append1(lock.power_profile);
|
||||
Ok(vec![mret])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock config for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.outarg::<u8, _>("mode")
|
||||
}
|
||||
|
||||
fn get_charge_limit(config: Arc<Mutex<Config>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
.method("GetChargeLimit", (), {
|
||||
move |m| {
|
||||
if let Ok(lock) = config.try_lock() {
|
||||
let mret = m.msg.method_return().append1(lock.bat_charge_limit);
|
||||
Ok(vec![mret])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock config for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.outarg::<u8, _>("limit")
|
||||
}
|
||||
|
||||
fn set_charge_limit(sender: Mutex<Sender<u8>>) -> Method<MTSync, ()> {
|
||||
let factory = Factory::new_sync::<()>();
|
||||
factory
|
||||
// method for ledmessage
|
||||
.method("SetChargeLimit", (), {
|
||||
move |m| {
|
||||
if let Ok(mut lock) = sender.try_lock() {
|
||||
let mut iter = m.msg.iter_init();
|
||||
let byte: u8 = iter.read()?;
|
||||
lock.try_send(byte).unwrap_or_else(|_err| {});
|
||||
Ok(vec![])
|
||||
} else {
|
||||
Err(MethodErr::failed("Could not lock daemon for access"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.inarg::<u8, _>("limit")
|
||||
.annotate("org.freedesktop.DBus.Method.NoReply", "true")
|
||||
}
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
pub fn dbus_create_tree(
|
||||
config: Arc<Mutex<Config>>,
|
||||
) -> (
|
||||
Tree<MTSync, ()>,
|
||||
Receiver<AuraModes>,
|
||||
Receiver<Vec<Vec<u8>>>,
|
||||
Receiver<u8>,
|
||||
Receiver<u8>,
|
||||
Arc<Signal<()>>,
|
||||
Arc<Signal<()>>,
|
||||
Arc<Signal<()>>,
|
||||
) {
|
||||
let (aura_command_send, aura_command_recv) = channel::<AuraModes>(1);
|
||||
let (animatrix_send, animatrix_recv) = channel::<Vec<Vec<u8>>>(1);
|
||||
let (fan_mode_send, fan_mode_recv) = channel::<u8>(1);
|
||||
let (charge_send, charge_recv) = channel::<u8>(1);
|
||||
|
||||
let factory = Factory::new_sync::<()>();
|
||||
|
||||
let key_backlight_changed = Arc::new(
|
||||
factory
|
||||
.signal("KeyBacklightChanged", ())
|
||||
.sarg::<&str, _>("json"),
|
||||
);
|
||||
let chrg_limit_changed = Arc::new(
|
||||
factory
|
||||
.signal("ChargeLimitChanged", ())
|
||||
.sarg::<u8, _>("limit"),
|
||||
);
|
||||
let fanmode_changed = Arc::new(factory.signal("FanModeChanged", ()).sarg::<u8, _>("mode"));
|
||||
|
||||
let tree = factory
|
||||
.tree(())
|
||||
.add(
|
||||
factory.object_path(DBUS_PATH, ()).introspectable().add(
|
||||
factory
|
||||
.interface(DBUS_IFACE, ())
|
||||
.add_m(set_keyboard_backlight(Mutex::new(aura_command_send)))
|
||||
.add_m(set_animatrix(Mutex::new(animatrix_send)))
|
||||
.add_m(set_fan_mode(Mutex::new(fan_mode_send)))
|
||||
.add_m(set_charge_limit(Mutex::new(charge_send)))
|
||||
.add_m(get_fan_mode(config.clone()))
|
||||
.add_m(get_charge_limit(config.clone()))
|
||||
.add_m(get_keyboard_backlight(config.clone()))
|
||||
.add_m(get_keyboard_backlight_modes(config))
|
||||
.add_s(key_backlight_changed.clone())
|
||||
.add_s(fanmode_changed.clone())
|
||||
.add_s(chrg_limit_changed.clone()),
|
||||
),
|
||||
)
|
||||
.add(factory.object_path("/", ()).introspectable());
|
||||
(
|
||||
tree,
|
||||
aura_command_recv,
|
||||
animatrix_recv,
|
||||
fan_mode_recv,
|
||||
charge_recv,
|
||||
key_backlight_changed,
|
||||
fanmode_changed,
|
||||
chrg_limit_changed,
|
||||
)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RogError {
|
||||
ParseFanLevel,
|
||||
NotSupported,
|
||||
}
|
||||
|
||||
impl std::error::Error for RogError {}
|
||||
|
||||
impl fmt::Display for RogError {
|
||||
// This trait requires `fmt` with this exact signature.
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
RogError::ParseFanLevel => write!(f, "Parse error"),
|
||||
RogError::NotSupported => write!(f, "Not supported"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
use asus_nb::aura_modes::{AuraModes, BREATHING, STATIC, STROBE};
|
||||
use log::{info, warn};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Read;
|
||||
|
||||
pub static LEDMODE_CONFIG_PATH: &str = "/etc/asusd/asusd-ledmodes.toml";
|
||||
|
||||
static HELP_ADDRESS: &str = "https://gitlab.com/asus-linux/asus-nb-ctrl";
|
||||
|
||||
pub struct LaptopBase {
|
||||
usb_product: String,
|
||||
supported_modes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl LaptopBase {
|
||||
pub fn usb_product(&self) -> &str {
|
||||
&self.usb_product
|
||||
}
|
||||
pub fn supported_modes(&self) -> &[u8] {
|
||||
&self.supported_modes
|
||||
}
|
||||
}
|
||||
|
||||
pub fn match_laptop() -> Option<LaptopBase> {
|
||||
for device in rusb::devices().unwrap().iter() {
|
||||
let device_desc = device.device_descriptor().unwrap();
|
||||
if device_desc.vendor_id() == 0x0b05 {
|
||||
match device_desc.product_id() {
|
||||
0x1866 => {
|
||||
let laptop = select_1866_device("1866".to_owned());
|
||||
print_modes(&laptop.supported_modes);
|
||||
return Some(laptop);
|
||||
}
|
||||
0x1869 => return Some(select_1866_device("1869".to_owned())),
|
||||
0x1854 => {
|
||||
info!("Found GL753 or similar");
|
||||
return Some(LaptopBase {
|
||||
usb_product: "1854".to_string(),
|
||||
supported_modes: vec![STATIC, BREATHING, STROBE],
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn select_1866_device(prod: String) -> LaptopBase {
|
||||
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 prod_name = dmi.product_name().expect("Could not get product_name");
|
||||
|
||||
info!("Product name: {}", prod_name.trim());
|
||||
info!("Board name: {}", board_name.trim());
|
||||
|
||||
let mut laptop = LaptopBase {
|
||||
usb_product: prod,
|
||||
supported_modes: vec![],
|
||||
};
|
||||
|
||||
if let Some(modes) = LEDModeGroup::load_from_config() {
|
||||
if let Some(led_modes) = modes.matcher(&prod_family, &board_name) {
|
||||
laptop.supported_modes = led_modes;
|
||||
return laptop;
|
||||
}
|
||||
}
|
||||
|
||||
warn!(
|
||||
"Unsupported laptop, please request support at {}",
|
||||
HELP_ADDRESS
|
||||
);
|
||||
warn!("Continuing with minimal support");
|
||||
|
||||
laptop
|
||||
}
|
||||
|
||||
fn print_modes(supported_modes: &[u8]) {
|
||||
if !supported_modes.is_empty() {
|
||||
info!("Supported Keyboard LED modes are:");
|
||||
for mode in supported_modes {
|
||||
let mode = <&str>::from(&<AuraModes>::from(*mode));
|
||||
info!("- {}", mode);
|
||||
}
|
||||
info!(
|
||||
"If these modes are incorrect or missing please request support at {}",
|
||||
HELP_ADDRESS
|
||||
);
|
||||
} else {
|
||||
info!("No RGB control available");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct LEDModeGroup {
|
||||
led_modes: Vec<LEDModes>,
|
||||
}
|
||||
|
||||
impl LEDModeGroup {
|
||||
/// Consumes the LEDModes
|
||||
fn matcher(self, prod_family: &str, board_name: &str) -> Option<Vec<u8>> {
|
||||
for led_modes in self.led_modes {
|
||||
if prod_family.contains(&led_modes.prod_family) {
|
||||
for board in led_modes.board_names {
|
||||
if board_name.contains(&board) {
|
||||
info!("Matched to {} {}", led_modes.prod_family, board);
|
||||
return Some(led_modes.led_modes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn load_from_config() -> Option<Self> {
|
||||
if let Ok(mut file) = OpenOptions::new().read(true).open(&LEDMODE_CONFIG_PATH) {
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("{} is empty", LEDMODE_CONFIG_PATH);
|
||||
} else {
|
||||
return Some(toml::from_str(&buf).unwrap_or_else(|_| {
|
||||
panic!("Could not deserialise {}", LEDMODE_CONFIG_PATH)
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!("Does {} exist?", LEDMODE_CONFIG_PATH);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct LEDModes {
|
||||
prod_family: String,
|
||||
board_names: Vec<String>,
|
||||
led_modes: Vec<u8>,
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
#![deny(unused_must_use)]
|
||||
/// Configuration loading, saving
|
||||
pub mod config;
|
||||
///
|
||||
pub mod ctrl_anime;
|
||||
///
|
||||
pub mod ctrl_charge;
|
||||
///
|
||||
pub mod ctrl_fan_cpu;
|
||||
///
|
||||
pub mod ctrl_leds;
|
||||
///
|
||||
pub mod dbus;
|
||||
/// Laptop matching to determine capabilities
|
||||
pub mod laptops;
|
||||
|
||||
mod error;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config::Config;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc::Receiver, Mutex};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
pub static VERSION: &str = "1.0.2";
|
||||
|
||||
use ::dbus::{nonblock::SyncConnection, tree::Signal};
|
||||
|
||||
#[async_trait]
|
||||
pub trait Controller {
|
||||
type A;
|
||||
|
||||
async fn reload_from_config(&mut self, config: &mut Config) -> Result<(), Box<dyn Error>>;
|
||||
|
||||
/// Spawn an infinitely running task (usually) which checks a Receiver for input,
|
||||
/// and may send a signal over dbus
|
||||
fn spawn_task_loop(
|
||||
self,
|
||||
config: Arc<Mutex<Config>>,
|
||||
recv: Receiver<Self::A>,
|
||||
connection: Option<Arc<SyncConnection>>,
|
||||
signal: Option<Arc<Signal<()>>>,
|
||||
) -> Vec<JoinHandle<()>>;
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
use asus_nb::{
|
||||
cli_options::{LedBrightness, SetAuraBuiltin},
|
||||
core_dbus::AuraDbusClient,
|
||||
};
|
||||
use daemon::ctrl_fan_cpu::FanLevel;
|
||||
use gumdrop::Options;
|
||||
use log::LevelFilter;
|
||||
use std::io::Write;
|
||||
|
||||
#[derive(Options)]
|
||||
struct CLIStart {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(help = "show program version number")]
|
||||
version: bool,
|
||||
#[options(meta = "VAL", help = "<off, low, med, high>")]
|
||||
kbd_bright: Option<LedBrightness>,
|
||||
#[options(meta = "PWR", help = "<silent, normal, boost>")]
|
||||
pwr_profile: Option<FanLevel>,
|
||||
#[options(meta = "CHRG", help = "<20-100>")]
|
||||
chg_limit: Option<u8>,
|
||||
#[options(command)]
|
||||
command: Option<Command>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
enum Command {
|
||||
#[options(help = "Set the keyboard lighting from built-in modes")]
|
||||
LedMode(LedModeCommand),
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
struct LedModeCommand {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(command, required)]
|
||||
command: Option<SetAuraBuiltin>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut logger = env_logger::Builder::new();
|
||||
logger
|
||||
.target(env_logger::Target::Stdout)
|
||||
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
|
||||
.filter(None, LevelFilter::Info)
|
||||
.init();
|
||||
|
||||
let parsed = CLIStart::parse_args_default_or_exit();
|
||||
|
||||
if parsed.version {
|
||||
println!("Version: {}", daemon::VERSION);
|
||||
}
|
||||
|
||||
let writer = AuraDbusClient::new()?;
|
||||
|
||||
if let Some(Command::LedMode(mode)) = parsed.command {
|
||||
if let Some(command) = mode.command {
|
||||
writer.write_builtin_mode(&command.into())?
|
||||
}
|
||||
}
|
||||
if let Some(brightness) = parsed.kbd_bright {
|
||||
writer.write_brightness(brightness.level())?;
|
||||
}
|
||||
if let Some(fan_level) = parsed.pwr_profile {
|
||||
writer.write_fan_mode(fan_level.into())?;
|
||||
}
|
||||
if let Some(chg_limit) = parsed.chg_limit {
|
||||
writer.write_charge_limit(chg_limit)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
use asus_nb::anime_dbus::AniMeDbusWriter;
|
||||
use asus_nb::anime_matrix::{AniMeMatrix, AniMePacketType, HEIGHT, WIDTH};
|
||||
use tinybmp::{Bmp, Pixel};
|
||||
|
||||
fn main() {
|
||||
let mut writer = AniMeDbusWriter::new().unwrap();
|
||||
|
||||
let bmp =
|
||||
Bmp::from_slice(include_bytes!("non-skewed_r.bmp")).expect("Failed to parse BMP image");
|
||||
let pixels: Vec<Pixel> = bmp.into_iter().collect();
|
||||
//assert_eq!(pixels.len(), 56 * 56);
|
||||
|
||||
// Try an outline, top and right
|
||||
let mut matrix = AniMeMatrix::new();
|
||||
|
||||
// Aligned left
|
||||
for px in pixels {
|
||||
if (px.x as usize / 2) < WIDTH && (px.y as usize) < HEIGHT && px.x % 2 == 0 {
|
||||
matrix.get_mut()[px.y as usize][px.x as usize / 2] = px.color as u8;
|
||||
}
|
||||
}
|
||||
|
||||
// Throw an alignment border up
|
||||
// {
|
||||
// let tmp = matrix.get_mut();
|
||||
// for x in tmp[0].iter_mut() {
|
||||
// *x = 0xff;
|
||||
// }
|
||||
// for row in tmp.iter_mut() {
|
||||
// row[row.len() - 1] = 0xff;
|
||||
// }
|
||||
// }
|
||||
|
||||
matrix.debug_print();
|
||||
|
||||
let mut matrix: AniMePacketType = AniMePacketType::from(matrix);
|
||||
// println!("{:?}", matrix[0].to_vec());
|
||||
// println!("{:?}", matrix[1].to_vec());
|
||||
|
||||
writer.write_image(&mut matrix).unwrap();
|
||||
}
|
||||
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
|
Before Width: | Height: | Size: 2.7 KiB |
|
Before Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 7.6 KiB |
@@ -1,78 +0,0 @@
|
||||
use crate::anime_matrix::AniMePacketType;
|
||||
use crate::{DBUS_IFACE, DBUS_NAME, DBUS_PATH};
|
||||
use dbus::channel::Sender;
|
||||
use dbus::{blocking::Connection, Message};
|
||||
use std::error::Error;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::{thread, time::Duration};
|
||||
|
||||
pub const ANIME_PANE1_PREFIX: [u8; 7] = [0x5e, 0xc0, 0x02, 0x01, 0x00, 0x73, 0x02];
|
||||
pub const ANIME_PANE2_PREFIX: [u8; 7] = [0x5e, 0xc0, 0x02, 0x74, 0x02, 0x73, 0x02];
|
||||
|
||||
/// Interface for the AniMe dot-matrix display
|
||||
///
|
||||
/// The resolution is 34x56 (1904) but only 1,215 LEDs in the top-left are used.
|
||||
/// The display is available only on select GA401 models.
|
||||
///
|
||||
/// Actual image ration when displayed is stretched width.
|
||||
///
|
||||
/// Data structure should be nested array of [[u8; 33]; 56]
|
||||
pub struct AniMeDbusWriter {
|
||||
connection: Box<Connection>,
|
||||
block_time: u64,
|
||||
stop: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AniMeDbusWriter {
|
||||
#[inline]
|
||||
pub fn new() -> Result<Self, Box<dyn Error>> {
|
||||
let connection = Connection::new_system()?;
|
||||
Ok(AniMeDbusWriter {
|
||||
connection: Box::new(connection),
|
||||
block_time: 25,
|
||||
stop: Arc::new(AtomicBool::new(false)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_image_to_buf(_buf: &mut AniMePacketType, _image_data: &[u8]) {
|
||||
unimplemented!("Image format is in progress of being worked out")
|
||||
}
|
||||
|
||||
/// Write an Animatrix image
|
||||
///
|
||||
/// The expected input here is *two* Vectors, 640 bytes in length. The two vectors
|
||||
/// are each one half of the full image write.
|
||||
///
|
||||
/// After each write a flush is written, it is assumed that this tells the device to
|
||||
/// go ahead and display the written bytes
|
||||
///
|
||||
/// # Note:
|
||||
/// The vectors are expected to contain the full sequence of bytes as follows
|
||||
///
|
||||
/// - Write packet 1: 0x5e 0xc0 0x02 0x01 0x00 0x73 0x02 .. <led brightness>
|
||||
/// - Write packet 2: 0x5e 0xc0 0x02 0x74 0x02 0x73 0x02 .. <led brightness>
|
||||
///
|
||||
/// Where led brightness is 0..255, low to high
|
||||
#[inline]
|
||||
pub fn write_image(&mut self, image: &mut AniMePacketType) -> Result<(), Box<dyn Error>> {
|
||||
if image[0][0] != ANIME_PANE1_PREFIX[0] && image[0][6] != ANIME_PANE1_PREFIX[6] {
|
||||
image[0][..7].copy_from_slice(&ANIME_PANE1_PREFIX);
|
||||
}
|
||||
if image[1][0] != ANIME_PANE2_PREFIX[0] && image[1][6] != ANIME_PANE2_PREFIX[6] {
|
||||
image[1][..7].copy_from_slice(&ANIME_PANE2_PREFIX);
|
||||
}
|
||||
|
||||
let mut msg = Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "AnimatrixWrite")?
|
||||
.append2(image[0].to_vec(), image[1].to_vec());
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
thread::sleep(Duration::from_millis(self.block_time));
|
||||
if self.stop.load(Ordering::Relaxed) {
|
||||
panic!("Got signal to stop!");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
pub const WIDTH: usize = 34; // Width is definitely 34 items
|
||||
pub const HEIGHT: usize = 56;
|
||||
pub type AniMeBufferType = [[u8; WIDTH]; HEIGHT];
|
||||
pub type AniMePacketType = [[u8; 640]; 2];
|
||||
const BLOCK_START: usize = 7;
|
||||
const BLOCK_END: usize = 634;
|
||||
use yansi_term::Colour::RGB;
|
||||
|
||||
/// Helper structure for writing images.
|
||||
///
|
||||
/// See the examples for ways to write an image to `AniMeMatrix` format.
|
||||
pub struct AniMeMatrix(AniMeBufferType);
|
||||
|
||||
impl Default for AniMeMatrix {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl AniMeMatrix {
|
||||
pub fn new() -> Self {
|
||||
AniMeMatrix([[0u8; WIDTH]; HEIGHT])
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &AniMeBufferType {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self) -> &mut AniMeBufferType {
|
||||
&mut self.0
|
||||
}
|
||||
|
||||
pub fn fill_with(&mut self, fill: u8) {
|
||||
for row in self.0.iter_mut() {
|
||||
for x in row.iter_mut() {
|
||||
*x = fill;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn debug_print(&self) {
|
||||
// this is the index from right. It is used to progressively shorten rows
|
||||
let mut prog_row_len = WIDTH - 2;
|
||||
|
||||
for (count, row) in self.0.iter().enumerate() {
|
||||
// Write the top block of LEDs (first 7 rows)
|
||||
if count < 6 {
|
||||
if count % 2 != 0 {
|
||||
print!(" ");
|
||||
} else {
|
||||
print!(" ");
|
||||
}
|
||||
let tmp = if count == 0 || count == 1 || count == 3 || count == 5 {
|
||||
row[1..].iter()
|
||||
} else {
|
||||
row.iter()
|
||||
};
|
||||
for x in tmp {
|
||||
print!(" {}", RGB(*x, *x, *x).paint(&format!("{:#04X}", x)));
|
||||
}
|
||||
|
||||
println!();
|
||||
} else {
|
||||
// Switch to next block (looks like )
|
||||
if count % 2 != 0 {
|
||||
// Row after 6 is only 1 less, then rows after 7 follow pattern
|
||||
if count == 7 {
|
||||
prog_row_len -= 1;
|
||||
} else {
|
||||
prog_row_len -= 2;
|
||||
}
|
||||
} else {
|
||||
prog_row_len += 1; // if count 6, 0
|
||||
}
|
||||
|
||||
let index = row.len() - prog_row_len;
|
||||
|
||||
if count % 2 == 0 {
|
||||
print!(" ");
|
||||
}
|
||||
for (i, x) in row.iter().enumerate() {
|
||||
if i >= index {
|
||||
print!(" {}", RGB(*x, *x, *x).paint(&format!("{:#04X}", x)));
|
||||
} else {
|
||||
print!(" ");
|
||||
}
|
||||
}
|
||||
println!();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AniMeMatrix> for AniMePacketType {
|
||||
/// Do conversion from the nested Vec in AniMeMatrix to the two required
|
||||
/// packets suitable for sending over USB
|
||||
#[inline]
|
||||
fn from(anime: AniMeMatrix) -> Self {
|
||||
let mut buffers = [[0; 640]; 2];
|
||||
|
||||
let mut write_index = BLOCK_START;
|
||||
let mut write_block = &mut buffers[0];
|
||||
let mut block1_done = false;
|
||||
|
||||
// this is the index from right. It is used to progressively shorten rows
|
||||
let mut prog_row_len = WIDTH - 2;
|
||||
|
||||
for (count, row) in anime.0.iter().enumerate() {
|
||||
// Write the top block of LEDs (first 7 rows)
|
||||
if count < 6 {
|
||||
for (i, x) in row.iter().enumerate() {
|
||||
// Rows 0, 1, 3, 5 are short and misaligned
|
||||
if count == 0 || count == 1 || count == 3 || count == 5 {
|
||||
if i > 0 {
|
||||
write_block[write_index - 1] = *x;
|
||||
}
|
||||
} else {
|
||||
write_block[write_index] = *x;
|
||||
}
|
||||
write_index += 1;
|
||||
}
|
||||
} else {
|
||||
// Switch to next block (looks like )
|
||||
if count % 2 != 0 {
|
||||
// Row after 6 is only 1 less, then rows after 7 follow pattern
|
||||
if count == 7 {
|
||||
prog_row_len -= 1;
|
||||
} else {
|
||||
prog_row_len -= 2;
|
||||
}
|
||||
} else {
|
||||
prog_row_len += 1; // if count 6, 0
|
||||
}
|
||||
|
||||
let index = row.len() - prog_row_len;
|
||||
for n in row.iter().skip(index) {
|
||||
// Require a special case to catch the correct end-of-packet which is
|
||||
// 6 bytes from the end
|
||||
if write_index == BLOCK_END && !block1_done {
|
||||
block1_done = true;
|
||||
write_block = &mut buffers[1];
|
||||
write_index = BLOCK_START;
|
||||
}
|
||||
|
||||
write_block[write_index] = *n;
|
||||
write_index += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
buffers
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::anime_matrix::{AniMeMatrix, AniMePacketType};
|
||||
|
||||
#[test]
|
||||
fn check_data_alignment() {
|
||||
let mut matrix = AniMeMatrix::new();
|
||||
{
|
||||
let tmp = matrix.get_mut();
|
||||
for row in tmp.iter_mut() {
|
||||
row[row.len() - 1] = 0xff;
|
||||
}
|
||||
}
|
||||
|
||||
let matrix: AniMePacketType = AniMePacketType::from(matrix);
|
||||
|
||||
// The bytes at the right of the initial AniMeMatrix should always end up aligned in the
|
||||
// same place after conversion to data packets
|
||||
|
||||
// Check against manually worked out right align
|
||||
assert_eq!(
|
||||
matrix[0].to_vec(),
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
.to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
matrix[1].to_vec(),
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0,
|
||||
0, 0, 0, 0
|
||||
]
|
||||
.to_vec()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
use crate::cli_options;
|
||||
use crate::cli_options::SetAuraBuiltin;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
pub const STATIC: u8 = 0x00;
|
||||
pub const BREATHING: u8 = 0x01;
|
||||
pub const STROBE: u8 = 0x02;
|
||||
pub const RAINBOW: u8 = 0x03;
|
||||
pub const STAR: u8 = 0x04;
|
||||
pub const RAIN: u8 = 0x05;
|
||||
pub const HIGHLIGHT: u8 = 0x06;
|
||||
pub const LASER: u8 = 0x07;
|
||||
pub const RIPPLE: u8 = 0x08;
|
||||
pub const PULSE: u8 = 0x0a;
|
||||
pub const COMET: u8 = 0x0b;
|
||||
pub const FLASH: u8 = 0x0c;
|
||||
pub const MULTISTATIC: u8 = 0x0d;
|
||||
pub const PER_KEY: u8 = 0xff;
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
pub struct Colour(pub u8, pub u8, pub u8);
|
||||
impl From<cli_options::Colour> for Colour {
|
||||
fn from(c: cli_options::Colour) -> Self {
|
||||
Colour(c.0, c.1, c.2)
|
||||
}
|
||||
}
|
||||
impl Default for Colour {
|
||||
fn default() -> Self {
|
||||
Colour(128, 0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Deserialize, Serialize)]
|
||||
pub enum Speed {
|
||||
Low = 0xe1,
|
||||
Med = 0xeb,
|
||||
High = 0xf5,
|
||||
}
|
||||
impl From<cli_options::Speed> for Speed {
|
||||
fn from(s: cli_options::Speed) -> Self {
|
||||
match s {
|
||||
cli_options::Speed::Low => Speed::Low,
|
||||
cli_options::Speed::Med => Speed::Med,
|
||||
cli_options::Speed::High => Speed::High,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for Speed {
|
||||
fn default() -> Self {
|
||||
Speed::Med
|
||||
}
|
||||
}
|
||||
|
||||
/// Used for Rainbow mode.
|
||||
///
|
||||
/// Enum corresponds to the required integer value
|
||||
#[derive(Copy, Clone, Deserialize, Serialize)]
|
||||
pub enum Direction {
|
||||
Right,
|
||||
Left,
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
impl From<cli_options::Direction> for Direction {
|
||||
fn from(s: cli_options::Direction) -> Self {
|
||||
match s {
|
||||
cli_options::Direction::Right => Direction::Right,
|
||||
cli_options::Direction::Left => Direction::Left,
|
||||
cli_options::Direction::Up => Direction::Up,
|
||||
cli_options::Direction::Down => Direction::Down,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Default for Direction {
|
||||
fn default() -> Self {
|
||||
Direction::Right
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct TwoColourSpeed {
|
||||
pub colour: Colour,
|
||||
pub colour2: Colour,
|
||||
pub speed: Speed,
|
||||
}
|
||||
impl From<cli_options::TwoColourSpeed> for TwoColourSpeed {
|
||||
fn from(mode: cli_options::TwoColourSpeed) -> Self {
|
||||
TwoColourSpeed {
|
||||
colour: mode.colour.into(),
|
||||
colour2: mode.colour2.into(),
|
||||
speed: mode.speed.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct SingleSpeed {
|
||||
pub speed: Speed,
|
||||
}
|
||||
impl From<cli_options::SingleSpeed> for SingleSpeed {
|
||||
fn from(mode: cli_options::SingleSpeed) -> Self {
|
||||
SingleSpeed {
|
||||
speed: mode.speed.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct SingleColour {
|
||||
pub colour: Colour,
|
||||
}
|
||||
impl From<cli_options::SingleColour> for SingleColour {
|
||||
fn from(mode: cli_options::SingleColour) -> Self {
|
||||
SingleColour {
|
||||
colour: mode.colour.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct MultiColour {
|
||||
pub colour1: Colour,
|
||||
pub colour2: Colour,
|
||||
pub colour3: Colour,
|
||||
pub colour4: Colour,
|
||||
}
|
||||
impl From<cli_options::MultiColour> for MultiColour {
|
||||
fn from(mode: cli_options::MultiColour) -> Self {
|
||||
MultiColour {
|
||||
colour1: mode.colour1.into(),
|
||||
colour2: mode.colour2.into(),
|
||||
colour3: mode.colour3.into(),
|
||||
colour4: mode.colour4.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct SingleSpeedDirection {
|
||||
pub direction: Direction,
|
||||
pub speed: Speed,
|
||||
}
|
||||
impl From<cli_options::SingleSpeedDirection> for SingleSpeedDirection {
|
||||
fn from(mode: cli_options::SingleSpeedDirection) -> Self {
|
||||
SingleSpeedDirection {
|
||||
direction: mode.direction.into(),
|
||||
speed: mode.speed.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, Deserialize, Serialize)]
|
||||
pub struct SingleColourSpeed {
|
||||
pub colour: Colour,
|
||||
pub speed: Speed,
|
||||
}
|
||||
impl From<cli_options::SingleColourSpeed> for SingleColourSpeed {
|
||||
fn from(mode: cli_options::SingleColourSpeed) -> Self {
|
||||
SingleColourSpeed {
|
||||
colour: mode.colour.into(),
|
||||
speed: mode.speed.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Deserialize, Serialize)]
|
||||
pub enum AuraModes {
|
||||
Static(SingleColour),
|
||||
Breathe(TwoColourSpeed),
|
||||
Strobe(SingleSpeed),
|
||||
Rainbow(SingleSpeedDirection),
|
||||
Star(TwoColourSpeed),
|
||||
Rain(SingleSpeed),
|
||||
Highlight(SingleColourSpeed),
|
||||
Laser(SingleColourSpeed),
|
||||
Ripple(SingleColourSpeed),
|
||||
Pulse(SingleColour),
|
||||
Comet(SingleColour),
|
||||
Flash(SingleColour),
|
||||
MultiStatic(MultiColour),
|
||||
LedBrightness(u8),
|
||||
// TODO: use a serializable structure for this (KeyColourArray)
|
||||
PerKey(Vec<Vec<u8>>),
|
||||
}
|
||||
|
||||
impl From<SetAuraBuiltin> for AuraModes {
|
||||
fn from(mode: SetAuraBuiltin) -> Self {
|
||||
match mode {
|
||||
SetAuraBuiltin::Static(x) => AuraModes::Static(x.into()),
|
||||
SetAuraBuiltin::Breathe(x) => AuraModes::Breathe(x.into()),
|
||||
SetAuraBuiltin::Strobe(x) => AuraModes::Strobe(x.into()),
|
||||
SetAuraBuiltin::Rainbow(x) => AuraModes::Rainbow(x.into()),
|
||||
SetAuraBuiltin::Star(x) => AuraModes::Star(x.into()),
|
||||
SetAuraBuiltin::Rain(x) => AuraModes::Rain(x.into()),
|
||||
SetAuraBuiltin::Highlight(x) => AuraModes::Highlight(x.into()),
|
||||
SetAuraBuiltin::Laser(x) => AuraModes::Laser(x.into()),
|
||||
SetAuraBuiltin::Ripple(x) => AuraModes::Ripple(x.into()),
|
||||
SetAuraBuiltin::Pulse(x) => AuraModes::Pulse(x.into()),
|
||||
SetAuraBuiltin::Comet(x) => AuraModes::Comet(x.into()),
|
||||
SetAuraBuiltin::Flash(x) => AuraModes::Flash(x.into()),
|
||||
SetAuraBuiltin::MultiStatic(x) => AuraModes::MultiStatic(x.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Very specific mode conversion required because numbering isn't linear
|
||||
impl From<AuraModes> for u8 {
|
||||
fn from(mode: AuraModes) -> Self {
|
||||
u8::from(&mode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Very specific mode conversion required because numbering isn't linear
|
||||
impl From<&mut AuraModes> for u8 {
|
||||
fn from(mode: &mut AuraModes) -> Self {
|
||||
u8::from(&*mode)
|
||||
}
|
||||
}
|
||||
|
||||
/// Very specific mode conversion required because numbering isn't linear
|
||||
impl From<&AuraModes> for u8 {
|
||||
fn from(mode: &AuraModes) -> Self {
|
||||
match mode {
|
||||
AuraModes::Static(_) => STATIC,
|
||||
AuraModes::Breathe(_) => BREATHING,
|
||||
AuraModes::Strobe(_) => STROBE,
|
||||
AuraModes::Rainbow(_) => RAINBOW,
|
||||
AuraModes::Star(_) => STAR,
|
||||
AuraModes::Rain(_) => RAIN,
|
||||
AuraModes::Highlight(_) => HIGHLIGHT,
|
||||
AuraModes::Laser(_) => LASER,
|
||||
AuraModes::Ripple(_) => RIPPLE,
|
||||
AuraModes::Pulse(_) => PULSE,
|
||||
AuraModes::Comet(_) => COMET,
|
||||
AuraModes::Flash(_) => FLASH,
|
||||
AuraModes::MultiStatic(_) => MULTISTATIC,
|
||||
AuraModes::PerKey(_) => PER_KEY,
|
||||
_ => panic!("Invalid mode"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&AuraModes> for &str {
|
||||
fn from(mode: &AuraModes) -> Self {
|
||||
match mode {
|
||||
AuraModes::Static(_) => "Static",
|
||||
AuraModes::Breathe(_) => "Breathing",
|
||||
AuraModes::Strobe(_) => "Strobing",
|
||||
AuraModes::Rainbow(_) => "Rainbow",
|
||||
AuraModes::Star(_) => "Stars",
|
||||
AuraModes::Rain(_) => "Rain",
|
||||
AuraModes::Highlight(_) => "Keypress Highlight",
|
||||
AuraModes::Laser(_) => "Keypress Laser",
|
||||
AuraModes::Ripple(_) => "Keypress Ripple",
|
||||
AuraModes::Pulse(_) => "Pulse",
|
||||
AuraModes::Comet(_) => "Comet",
|
||||
AuraModes::Flash(_) => "Flash",
|
||||
AuraModes::MultiStatic(_) => "4-Zone Static Colours",
|
||||
AuraModes::PerKey(_) => "RGB per-key",
|
||||
_ => panic!("Invalid mode"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Exists to convert back from correct bytes. PER_KEY byte intentionally left off as it
|
||||
/// does not correspond to an actual pre-set mode, nor does brightness.
|
||||
impl From<u8> for AuraModes {
|
||||
fn from(byte: u8) -> Self {
|
||||
match byte {
|
||||
STATIC => AuraModes::Static(SingleColour::default()),
|
||||
BREATHING => AuraModes::Breathe(TwoColourSpeed::default()),
|
||||
STROBE => AuraModes::Strobe(SingleSpeed::default()),
|
||||
RAINBOW => AuraModes::Rainbow(SingleSpeedDirection::default()),
|
||||
STAR => AuraModes::Star(TwoColourSpeed::default()),
|
||||
RAIN => AuraModes::Rain(SingleSpeed::default()),
|
||||
HIGHLIGHT => AuraModes::Highlight(SingleColourSpeed::default()),
|
||||
LASER => AuraModes::Laser(SingleColourSpeed::default()),
|
||||
RIPPLE => AuraModes::Ripple(SingleColourSpeed::default()),
|
||||
PULSE => AuraModes::Pulse(SingleColour::default()),
|
||||
COMET => AuraModes::Comet(SingleColour::default()),
|
||||
FLASH => AuraModes::Flash(SingleColour::default()),
|
||||
MULTISTATIC => AuraModes::MultiStatic(MultiColour::default()),
|
||||
PER_KEY => AuraModes::PerKey(vec![]),
|
||||
_ => panic!("Invalid mode byte"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
use crate::error::AuraError;
|
||||
use gumdrop::Options;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct LedBrightness {
|
||||
level: u8,
|
||||
}
|
||||
impl LedBrightness {
|
||||
pub fn level(&self) -> u8 {
|
||||
self.level
|
||||
}
|
||||
}
|
||||
impl FromStr for LedBrightness {
|
||||
type Err = AuraError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.to_lowercase();
|
||||
match s.as_str() {
|
||||
"off" => Ok(LedBrightness { level: 0x00 }),
|
||||
"low" => Ok(LedBrightness { level: 0x01 }),
|
||||
"med" => Ok(LedBrightness { level: 0x02 }),
|
||||
"high" => Ok(LedBrightness { level: 0x03 }),
|
||||
_ => {
|
||||
println!("Missing required argument, must be one of:\noff,low,med,high\n");
|
||||
Err(AuraError::ParseBrightness)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Colour(pub u8, pub u8, pub u8);
|
||||
impl Default for Colour {
|
||||
fn default() -> Self {
|
||||
Colour(255, 0, 0)
|
||||
}
|
||||
}
|
||||
impl FromStr for Colour {
|
||||
type Err = AuraError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
if s.len() < 6 {
|
||||
return Err(AuraError::ParseColour);
|
||||
}
|
||||
let r = u8::from_str_radix(&s[0..2], 16).or(Err(AuraError::ParseColour))?;
|
||||
let g = u8::from_str_radix(&s[2..4], 16).or(Err(AuraError::ParseColour))?;
|
||||
let b = u8::from_str_radix(&s[4..6], 16).or(Err(AuraError::ParseColour))?;
|
||||
Ok(Colour(r, g, b))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum Speed {
|
||||
Low = 0xe1,
|
||||
Med = 0xeb,
|
||||
High = 0xf5,
|
||||
}
|
||||
impl Default for Speed {
|
||||
fn default() -> Self {
|
||||
Speed::Med
|
||||
}
|
||||
}
|
||||
impl FromStr for Speed {
|
||||
type Err = AuraError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.to_lowercase();
|
||||
match s.as_str() {
|
||||
"low" => Ok(Speed::Low),
|
||||
"med" => Ok(Speed::Med),
|
||||
"high" => Ok(Speed::High),
|
||||
_ => Err(AuraError::ParseSpeed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Used for Rainbow mode.
|
||||
///
|
||||
/// Enum corresponds to the required integer value
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub enum Direction {
|
||||
Right,
|
||||
Left,
|
||||
Up,
|
||||
Down,
|
||||
}
|
||||
impl Default for Direction {
|
||||
fn default() -> Self {
|
||||
Direction::Right
|
||||
}
|
||||
}
|
||||
impl FromStr for Direction {
|
||||
type Err = AuraError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.to_lowercase();
|
||||
match s.as_str() {
|
||||
"right" => Ok(Direction::Right),
|
||||
"up" => Ok(Direction::Up),
|
||||
"down" => Ok(Direction::Down),
|
||||
"left" => Ok(Direction::Left),
|
||||
_ => Err(AuraError::ParseDirection),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct TwoColourSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "HEX", help = "set the first RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
#[options(no_long, meta = "HEX", help = "set the second RGB value e.g, ff00ff")]
|
||||
pub colour2: Colour,
|
||||
#[options(no_long, help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct SingleSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "WORD", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct SingleColour {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct MultiColour {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour1: Colour,
|
||||
#[options(meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour2: Colour,
|
||||
#[options(meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour3: Colour,
|
||||
#[options(meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour4: Colour,
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct SingleSpeedDirection {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(
|
||||
no_long,
|
||||
meta = "DIR",
|
||||
help = "set the direction: up, down, left, right"
|
||||
)]
|
||||
pub direction: Direction,
|
||||
#[options(no_long, help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Default, Options, Deserialize, Serialize)]
|
||||
pub struct SingleColourSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "HEX", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
#[options(no_long, help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
/// Byte value for setting the built-in mode.
|
||||
///
|
||||
/// Enum corresponds to the required integer value
|
||||
#[derive(Options, Deserialize, Serialize)]
|
||||
pub enum SetAuraBuiltin {
|
||||
#[options(help = "set a single static colour")]
|
||||
Static(SingleColour),
|
||||
#[options(help = "pulse between one or two colours")]
|
||||
Breathe(TwoColourSpeed),
|
||||
#[options(help = "strobe through all colours")]
|
||||
Strobe(SingleSpeed),
|
||||
#[options(help = "rainbow cycling in one of four directions")]
|
||||
Rainbow(SingleSpeedDirection),
|
||||
#[options(help = "rain pattern mimicking raindrops")]
|
||||
Star(TwoColourSpeed),
|
||||
#[options(help = "rain pattern of three preset colours")]
|
||||
Rain(SingleSpeed),
|
||||
#[options(help = "pressed keys are highlighted to fade")]
|
||||
Highlight(SingleColourSpeed),
|
||||
#[options(help = "pressed keys generate horizontal laser")]
|
||||
Laser(SingleColourSpeed),
|
||||
#[options(help = "pressed keys ripple outwards like a splash")]
|
||||
Ripple(SingleColourSpeed),
|
||||
#[options(help = "set a rapid pulse")]
|
||||
Pulse(SingleColour),
|
||||
#[options(help = "set a vertical line zooming from left")]
|
||||
Comet(SingleColour),
|
||||
#[options(help = "set a wide vertical line zooming from left")]
|
||||
Flash(SingleColour),
|
||||
#[options(help = "4-zone multi-colour")]
|
||||
MultiStatic(MultiColour),
|
||||
}
|
||||
|
||||
impl Default for SetAuraBuiltin {
|
||||
fn default() -> Self {
|
||||
SetAuraBuiltin::Static(SingleColour {
|
||||
help: false,
|
||||
colour: Colour(255, 0, 0),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
use super::*;
|
||||
use crate::fancy::KeyColourArray;
|
||||
use dbus::channel::Sender;
|
||||
use dbus::{blocking::Connection, channel::Token, Message};
|
||||
use std::error::Error;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use std::{thread, time::Duration};
|
||||
|
||||
/// Simplified way to write a effect block
|
||||
pub struct AuraDbusClient {
|
||||
connection: Box<Connection>,
|
||||
block_time: u64,
|
||||
stop: Arc<AtomicBool>,
|
||||
stop_token: Token,
|
||||
}
|
||||
|
||||
impl AuraDbusClient {
|
||||
#[inline]
|
||||
pub fn new() -> Result<Self, Box<dyn Error>> {
|
||||
let connection = Connection::new_system()?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let stopper2 = stop.clone();
|
||||
let match_rule = dbus::message::MatchRule::new_signal(DBUS_IFACE, "KeyBacklightChanged");
|
||||
let stop_token = connection.add_match(match_rule, move |_: (), _, msg| {
|
||||
if msg.read1::<&str>().is_ok() {
|
||||
stopper2.store(true, Ordering::Relaxed);
|
||||
}
|
||||
true
|
||||
})?;
|
||||
|
||||
Ok(AuraDbusClient {
|
||||
connection: Box::new(connection),
|
||||
block_time: 33333,
|
||||
stop,
|
||||
stop_token,
|
||||
})
|
||||
}
|
||||
|
||||
/// This method must always be called before the very first write to initialise
|
||||
/// the keyboard LED EC in the correct mode
|
||||
#[inline]
|
||||
pub fn init_effect(&self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mode = AuraModes::PerKey(vec![vec![]]);
|
||||
let mut msg =
|
||||
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")?
|
||||
.append1(serde_json::to_string(&mode)?);
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a single colour block.
|
||||
///
|
||||
/// Intentionally blocks for 10ms after sending to allow the block to
|
||||
/// be written to the keyboard EC. This should not be async.
|
||||
#[inline]
|
||||
pub fn write_colour_block(
|
||||
&mut self,
|
||||
key_colour_array: &KeyColourArray,
|
||||
) -> Result<(), Box<dyn Error>> {
|
||||
let group = key_colour_array.get();
|
||||
let mut vecs = Vec::with_capacity(group.len());
|
||||
for v in group {
|
||||
vecs.push(v.to_vec());
|
||||
}
|
||||
let mode = AuraModes::PerKey(vecs);
|
||||
let mut msg =
|
||||
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")?
|
||||
.append1(serde_json::to_string(&mode)?);
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
thread::sleep(Duration::from_micros(self.block_time));
|
||||
self.connection.process(Duration::from_micros(500))?;
|
||||
if self.stop.load(Ordering::Relaxed) {
|
||||
self.connection.remove_match(self.stop_token)?;
|
||||
println!("Keyboard backlight was changed, exiting");
|
||||
std::process::exit(1)
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn write_keyboard_leds(&self, mode: &AuraModes) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut msg =
|
||||
Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetKeyBacklight")?
|
||||
.append1(serde_json::to_string(mode)?);
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn write_fan_mode(&self, level: u8) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut msg = Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetFanMode")?
|
||||
.append1(level);
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn write_charge_limit(&self, level: u8) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut msg = Message::new_method_call(DBUS_NAME, DBUS_PATH, DBUS_IFACE, "SetChargeLimit")?
|
||||
.append1(level);
|
||||
msg.set_no_reply(true);
|
||||
self.connection.send(msg).unwrap();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn write_builtin_mode(&self, mode: &AuraModes) -> Result<(), Box<dyn std::error::Error>> {
|
||||
self.write_keyboard_leds(mode)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn write_brightness(&self, level: u8) -> Result<String, Box<dyn std::error::Error>> {
|
||||
self.write_keyboard_leds(&AuraModes::LedBrightness(level))?;
|
||||
Ok(String::new())
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use std::fmt;
|
||||
|
||||
pub enum AuraError {
|
||||
ParseColour,
|
||||
ParseSpeed,
|
||||
ParseDirection,
|
||||
ParseBrightness,
|
||||
}
|
||||
|
||||
impl fmt::Display for AuraError {
|
||||
// This trait requires `fmt` with this exact signature.
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
AuraError::ParseColour => write!(f, "Could not parse colour"),
|
||||
AuraError::ParseSpeed => write!(f, "Could not parse speed"),
|
||||
AuraError::ParseDirection => write!(f, "Could not parse direction"),
|
||||
AuraError::ParseBrightness => write!(f, "Could not parse brightness"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,252 +0,0 @@
|
||||
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
|
||||
pub static DBUS_PATH: &str = "/org/asuslinux/Daemon";
|
||||
pub static DBUS_IFACE: &str = "org.asuslinux.Daemon";
|
||||
pub const LED_MSG_LEN: usize = 17;
|
||||
|
||||
pub mod aura_modes;
|
||||
use aura_modes::AuraModes;
|
||||
|
||||
/// Contains mostly only what is required for parsing CLI options
|
||||
pub mod cli_options;
|
||||
|
||||
/// Enables you to create fancy RGB effects
|
||||
pub mod fancy;
|
||||
|
||||
/// The main dbus group for system controls, e.g, fan control, keyboard LED's
|
||||
pub mod core_dbus;
|
||||
|
||||
/// Specific dbus for writing to the AniMe Matrix display (if supported)
|
||||
pub mod anime_dbus;
|
||||
|
||||
/// Helper functions for the AniMe display
|
||||
pub mod anime_matrix;
|
||||
|
||||
pub mod error;
|
||||
|
||||
// static LED_INIT1: [u8; 2] = [0x5d, 0xb9];
|
||||
// static LED_INIT2: &str = "]ASUS Tech.Inc."; // ] == 0x5d
|
||||
// static LED_INIT3: [u8; 6] = [0x5d, 0x05, 0x20, 0x31, 0, 0x08];
|
||||
// static LED_INIT4: &str = "^ASUS Tech.Inc."; // ^ == 0x5e
|
||||
// static LED_INIT5: [u8; 6] = [0x5e, 0x05, 0x20, 0x31, 0, 0x08];
|
||||
|
||||
/// Writes aout the correct byte string for brightness
|
||||
///
|
||||
/// The HID descriptor looks like:
|
||||
///
|
||||
/// ```ignore
|
||||
/// 0x06, 0x31, 0xFF, // Usage Page (Vendor Defined 0xFF31)
|
||||
/// 0x09, 0x76, // Usage (0x76)
|
||||
/// 0xA1, 0x01, // Collection (Application)
|
||||
/// 0x85, 0x5A, // Report ID (90)
|
||||
/// 0x19, 0x00, // Usage Minimum (0x00)
|
||||
/// 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
|
||||
/// 0x15, 0x00, // Logical Minimum (0)
|
||||
/// 0x26, 0xFF, 0x00, // Logical Maximum (255)
|
||||
/// 0x75, 0x08, // Report Size (8)
|
||||
/// 0x95, 0x05, // Report Count (5)
|
||||
/// 0x81, 0x00, // Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
|
||||
/// 0x19, 0x00, // Usage Minimum (0x00)
|
||||
/// 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
|
||||
/// 0x15, 0x00, // Logical Minimum (0)
|
||||
/// 0x26, 0xFF, 0x00, // Logical Maximum (255)
|
||||
/// 0x75, 0x08, // Report Size (8)
|
||||
/// 0x95, 0x3F, // Report Count (63)
|
||||
/// 0xB1, 0x00, // Feature (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
|
||||
/// 0xC0, // End Collection
|
||||
/// ```
|
||||
pub fn aura_brightness_bytes(brightness: u8) -> [u8; 17] {
|
||||
// TODO: check brightness range
|
||||
[
|
||||
0x5A, 0xBA, 0xC5, 0xC4, brightness, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
]
|
||||
}
|
||||
|
||||
/// Parses `AuraCommands` in to packet data
|
||||
///
|
||||
/// Byte structure:
|
||||
///
|
||||
/// ```ignore
|
||||
/// | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12|
|
||||
/// |---|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
/// |5d |b3 |00 |03 |ff |00 |00 |00 |00 |00 |00 |ff |00 |
|
||||
/// ```
|
||||
///
|
||||
/// Bytes 0 and 1 should always be 5d, b3
|
||||
///
|
||||
/// On multizone laptops byte 2 is the zone number, RGB in usual
|
||||
/// place, byte 3 set to zero
|
||||
///
|
||||
/// Byte 3 sets the mode type:
|
||||
/// - 00 = static
|
||||
/// - 01 = breathe (can set two colours)
|
||||
/// - 02 = strobe (through all colours)
|
||||
/// - 03 = rainbow
|
||||
/// - 04 = star (byte 9 sets rain colour)
|
||||
/// - 05 = rain keys, red, white, turquoise
|
||||
/// - 06 = pressed keys light up and fade
|
||||
/// - 07 = pressed key emits laser
|
||||
/// - 08 = pressed key emits water ripple
|
||||
/// - 09 = no effect/not used
|
||||
/// - 0a fast pulse (no speed setting)
|
||||
/// - 0b vertical line racing to right (no speed setting)
|
||||
/// - 0c wider vertical line racing to right (no speed setting)
|
||||
///
|
||||
/// Bytes 4, 5, 6 are Red, Green, Blue
|
||||
///
|
||||
/// Byte 7 sets speed from
|
||||
/// - 0x00 = Off
|
||||
/// - 0xe1 = Slow
|
||||
/// - 0xeb = Medium
|
||||
/// - 0xf5 = Fast
|
||||
///
|
||||
/// Byte 8 sets rainbow direction:
|
||||
/// - 0x00 = rightwards
|
||||
/// - 0x01 = leftwards
|
||||
/// - 0x02 = upwards
|
||||
/// - 0x03 = downwards
|
||||
///
|
||||
/// Bytes 10, 11, 12 are Red, Green, Blue for second colour if mode supports it
|
||||
///
|
||||
/// The HID descriptor looks like:
|
||||
/// ```ignore
|
||||
/// 0x06, 0x31, 0xFF, // Usage Page (Vendor Defined 0xFF31)
|
||||
/// 0x09, 0x79, // Usage (0x79)
|
||||
/// 0xA1, 0x01, // Collection (Application)
|
||||
/// 0x85, 0x5D, // Report ID (93)
|
||||
/// 0x19, 0x00, // Usage Minimum (0x00)
|
||||
/// 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
|
||||
/// 0x15, 0x00, // Logical Minimum (0)
|
||||
/// 0x26, 0xFF, 0x00, // Logical Maximum (255)
|
||||
/// 0x75, 0x08, // Report Size (8)
|
||||
/// 0x95, 0x1F, // Report Count (31)
|
||||
/// 0x81, 0x00, // Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position)
|
||||
/// 0x19, 0x00, // Usage Minimum (0x00)
|
||||
/// 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
|
||||
/// 0x15, 0x00, // Logical Minimum (0)
|
||||
/// 0x26, 0xFF, 0x00, // Logical Maximum (255)
|
||||
/// 0x75, 0x08, // Report Size (8)
|
||||
/// 0x95, 0x3F, // Report Count (63)
|
||||
/// 0x91, 0x00, // Output (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
|
||||
/// 0x19, 0x00, // Usage Minimum (0x00)
|
||||
/// 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF)
|
||||
/// 0x15, 0x00, // Logical Minimum (0)
|
||||
/// 0x26, 0xFF, 0x00, // Logical Maximum (255)
|
||||
/// 0x75, 0x08, // Report Size (8)
|
||||
/// 0x95, 0x3F, // Report Count (63)
|
||||
/// 0xB1, 0x00, // Feature (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile)
|
||||
/// 0xC0, // End Collection
|
||||
/// ```
|
||||
///
|
||||
/// This descriptor is also used for the per-key LED settings
|
||||
impl From<&AuraModes> for [u8; LED_MSG_LEN] {
|
||||
fn from(mode: &AuraModes) -> Self {
|
||||
let mut msg = [0u8; LED_MSG_LEN];
|
||||
msg[0] = 0x5d;
|
||||
msg[1] = 0xb3;
|
||||
match mode {
|
||||
AuraModes::LedBrightness(n) => return aura_brightness_bytes(*n),
|
||||
AuraModes::Static(_) => msg[3] = 0x00,
|
||||
AuraModes::Breathe(_) => msg[3] = 0x01,
|
||||
AuraModes::Strobe(_) => msg[3] = 0x02,
|
||||
AuraModes::Rainbow(_) => msg[3] = 0x03,
|
||||
AuraModes::Star(_) => msg[3] = 0x04,
|
||||
AuraModes::Rain(_) => msg[3] = 0x05,
|
||||
AuraModes::Highlight(_) => msg[3] = 0x06,
|
||||
AuraModes::Laser(_) => msg[3] = 0x07,
|
||||
AuraModes::Ripple(_) => msg[3] = 0x08,
|
||||
AuraModes::Pulse(_) => msg[3] = 0x0a,
|
||||
AuraModes::Comet(_) => msg[3] = 0x0b,
|
||||
AuraModes::Flash(_) => msg[3] = 0x0c,
|
||||
_ => panic!("Mode not convertable to 1D array: {}", <&str>::from(mode)),
|
||||
}
|
||||
|
||||
match mode {
|
||||
AuraModes::Rainbow(settings) => {
|
||||
msg[7] = settings.speed as u8;
|
||||
msg[8] = settings.direction as u8;
|
||||
}
|
||||
AuraModes::Star(settings) => {
|
||||
msg[4] = settings.colour.0;
|
||||
msg[5] = settings.colour.1;
|
||||
msg[6] = settings.colour.2;
|
||||
msg[7] = settings.speed as u8;
|
||||
msg[9] = settings.colour2.2;
|
||||
}
|
||||
AuraModes::Breathe(settings) => {
|
||||
msg[4] = settings.colour.0;
|
||||
msg[5] = settings.colour.1;
|
||||
msg[6] = settings.colour.2;
|
||||
msg[7] = settings.speed as u8;
|
||||
msg[10] = settings.colour2.0;
|
||||
msg[11] = settings.colour2.1;
|
||||
msg[12] = settings.colour2.2;
|
||||
}
|
||||
AuraModes::Strobe(settings) | AuraModes::Rain(settings) => {
|
||||
msg[7] = settings.speed as u8;
|
||||
}
|
||||
AuraModes::Highlight(settings)
|
||||
| AuraModes::Laser(settings)
|
||||
| AuraModes::Ripple(settings) => {
|
||||
msg[4] = settings.colour.0;
|
||||
msg[5] = settings.colour.1;
|
||||
msg[6] = settings.colour.2;
|
||||
msg[7] = settings.speed as u8;
|
||||
}
|
||||
AuraModes::Static(settings)
|
||||
| AuraModes::Pulse(settings)
|
||||
| AuraModes::Comet(settings)
|
||||
| AuraModes::Flash(settings) => {
|
||||
msg[4] = settings.colour.0;
|
||||
msg[5] = settings.colour.1;
|
||||
msg[6] = settings.colour.2;
|
||||
}
|
||||
_ => panic!("Mode not convertable to 1D array: {}", <&str>::from(mode)),
|
||||
}
|
||||
msg
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AuraModes> for [u8; LED_MSG_LEN] {
|
||||
#[inline]
|
||||
fn from(mode: AuraModes) -> Self {
|
||||
<[u8; LED_MSG_LEN]>::from(&mode)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AuraModes> for [[u8; LED_MSG_LEN]; 4] {
|
||||
#[inline]
|
||||
fn from(mode: AuraModes) -> Self {
|
||||
<[[u8; LED_MSG_LEN]; 4]>::from(&mode)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&AuraModes> for [[u8; LED_MSG_LEN]; 4] {
|
||||
#[inline]
|
||||
fn from(mode: &AuraModes) -> Self {
|
||||
let mut msg = [[0u8; LED_MSG_LEN]; 4];
|
||||
for (i, row) in msg.iter_mut().enumerate() {
|
||||
row[0] = 0x5d;
|
||||
row[1] = 0xb3;
|
||||
row[2] = i as u8 + 1;
|
||||
}
|
||||
|
||||
match mode {
|
||||
AuraModes::MultiStatic(settings) => {
|
||||
msg[0][4] = settings.colour1.0;
|
||||
msg[0][5] = settings.colour1.1;
|
||||
msg[0][6] = settings.colour1.2;
|
||||
msg[1][4] = settings.colour2.0;
|
||||
msg[1][5] = settings.colour2.1;
|
||||
msg[1][6] = settings.colour2.2;
|
||||
msg[2][4] = settings.colour3.0;
|
||||
msg[2][5] = settings.colour3.1;
|
||||
msg[2][6] = settings.colour3.2;
|
||||
msg[3][4] = settings.colour4.0;
|
||||
msg[3][5] = settings.colour4.1;
|
||||
msg[3][6] = settings.colour4.2;
|
||||
}
|
||||
_ => panic!("Mode not convertable to 2D array: {}", <&str>::from(mode)),
|
||||
}
|
||||
msg
|
||||
}
|
||||
}
|
||||
20
asus-notify/Cargo.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "asus-notify"
|
||||
version = "3.0.0"
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
# serialisation
|
||||
serde_json = "^1.0"
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
rog_types = { path = "../rog-types" }
|
||||
daemon = { path = "../daemon" }
|
||||
|
||||
[dependencies.notify-rust]
|
||||
version = "^4.3"
|
||||
default-features = false
|
||||
features = ["z"]
|
||||
110
asus-notify/src/main.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
use notify_rust::{Hint, Notification, NotificationHandle};
|
||||
use rog_dbus::{DbusProxies, Signals};
|
||||
use rog_profiles::profiles::{FanLevel, Profile};
|
||||
use std::error::Error;
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("asus-notify version {}", env!("CARGO_PKG_VERSION"));
|
||||
println!(" daemon version {}", daemon::VERSION);
|
||||
println!(" rog-dbus version {}", rog_dbus::VERSION);
|
||||
|
||||
let (proxies, conn) = DbusProxies::new()?;
|
||||
let signals = Signals::new(&proxies)?;
|
||||
|
||||
let mut last_profile_notif: Option<NotificationHandle> = None;
|
||||
let mut last_led_notif: Option<NotificationHandle> = None;
|
||||
let mut last_gfx_notif: Option<NotificationHandle> = None;
|
||||
let mut last_chrg_notif: Option<NotificationHandle> = None;
|
||||
|
||||
let recv = proxies.setup_recv(conn);
|
||||
let mut err_count = 0;
|
||||
loop {
|
||||
sleep(Duration::from_millis(100));
|
||||
if let Err(err) = recv.next_signal() {
|
||||
if err_count < 3 {
|
||||
err_count += 1;
|
||||
println!("{}", err);
|
||||
}
|
||||
if err_count == 3 {
|
||||
err_count += 1;
|
||||
println!("Max error count reached. Spooling silently.");
|
||||
}
|
||||
sleep(Duration::from_millis(2000));
|
||||
continue;
|
||||
}
|
||||
err_count = 0;
|
||||
|
||||
if let Ok(vendor) = signals.gfx_vendor.try_recv() {
|
||||
if let Some(notif) = last_gfx_notif.take() {
|
||||
notif.close();
|
||||
}
|
||||
let x = do_notif(&format!(
|
||||
"Graphics mode changed to {}",
|
||||
<&str>::from(vendor)
|
||||
))?;
|
||||
last_gfx_notif = Some(x);
|
||||
}
|
||||
|
||||
if let Ok(limit) = signals.charge.try_recv() {
|
||||
if let Some(notif) = last_chrg_notif.take() {
|
||||
notif.close();
|
||||
}
|
||||
let x = do_notif(&format!("Battery charge limit changed to {}", limit))?;
|
||||
last_chrg_notif = Some(x);
|
||||
}
|
||||
|
||||
if let Ok(profile) = signals.profile.try_recv() {
|
||||
if let Some(notif) = last_profile_notif.take() {
|
||||
notif.close();
|
||||
}
|
||||
let x = do_thermal_notif(&profile)?;
|
||||
last_profile_notif = Some(x);
|
||||
}
|
||||
|
||||
if let Ok(ledmode) = signals.led_mode.try_recv() {
|
||||
if let Some(notif) = last_led_notif.take() {
|
||||
notif.close();
|
||||
}
|
||||
let x = do_notif(&format!(
|
||||
"Keyboard LED mode changed to {}",
|
||||
ledmode.mode_name()
|
||||
))?;
|
||||
last_led_notif = Some(x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn do_thermal_notif(profile: &Profile) -> Result<NotificationHandle, Box<dyn Error>> {
|
||||
let fan = profile.fan_preset;
|
||||
let turbo = if profile.turbo { "enabled" } else { "disabled" };
|
||||
let icon = match fan {
|
||||
FanLevel::Normal => "asus_notif_yellow",
|
||||
FanLevel::Boost => "asus_notif_red",
|
||||
FanLevel::Silent => "asus_notif_green",
|
||||
};
|
||||
let x = Notification::new()
|
||||
.summary("ASUS ROG")
|
||||
.body(&format!(
|
||||
"Thermal profile changed to {}, turbo {}",
|
||||
profile.name.to_uppercase(),
|
||||
turbo
|
||||
))
|
||||
.hint(Hint::Resident(true))
|
||||
.timeout(2000)
|
||||
.hint(Hint::Category("device".into()))
|
||||
//.hint(Hint::Transient(true))
|
||||
.icon(icon)
|
||||
.show()?;
|
||||
Ok(x)
|
||||
}
|
||||
|
||||
fn do_notif(body: &str) -> Result<NotificationHandle, Box<dyn Error>> {
|
||||
let x = Notification::new()
|
||||
.summary("ASUS ROG")
|
||||
.body(body)
|
||||
.timeout(2000)
|
||||
.show()?;
|
||||
Ok(x)
|
||||
}
|
||||
23
asusctl/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "asusctl"
|
||||
version = "3.5.0"
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2018"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_aura = { path = "../rog-aura" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
rog_types = { path = "../rog-types" }
|
||||
rog_fan_curve = { version = "^0.1", features = ["serde"] }
|
||||
gumdrop = "^0.8"
|
||||
yansi-term = "^0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
tinybmp = "^0.2.3"
|
||||
glam = "0.14.0"
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
gif = "^0.11.2"
|
||||
26
asusctl/examples/anime-diag-png.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use std::{env, error::Error, path::Path, process::exit};
|
||||
|
||||
use rog_anime::{AnimeDataBuffer, AnimeDiagonal};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Usage: <filepath> <brightness>");
|
||||
println!("e.g, asusctl/examples/doom_large.png 0.8");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
let matrix =
|
||||
AnimeDiagonal::from_png(Path::new(&args[1]), None, args[2].parse::<f32>().unwrap())?;
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::from(&matrix))
|
||||
.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
32
asusctl/examples/anime-diag.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::{thread::sleep, time::Duration};
|
||||
|
||||
use rog_anime::{AnimeDataBuffer, AnimeDiagonal};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
|
||||
// 74w x 36h diagonal used by the windows app
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
|
||||
for step in (2..50).rev() {
|
||||
let mut matrix = AnimeDiagonal::new(None);
|
||||
for c in (0..60).into_iter().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 i in matrix.get_mut()[c].iter_mut() {
|
||||
*i = 50;
|
||||
}
|
||||
}
|
||||
|
||||
let m = <AnimeDataBuffer>::from(&matrix);
|
||||
client.proxies().anime().write(m).unwrap();
|
||||
sleep(Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
42
asusctl/examples/anime-gif.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::{env, path::Path, thread::sleep};
|
||||
|
||||
use rog_anime::{ActionData, AnimeAction, Sequences};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Please supply filepath and brightness");
|
||||
return;
|
||||
}
|
||||
|
||||
let path = Path::new(&args[1]);
|
||||
let brightness = args[2].parse::<f32>().unwrap();
|
||||
let mut seq = Sequences::new();
|
||||
seq.insert(
|
||||
0,
|
||||
&AnimeAction::AsusAnimation {
|
||||
file: path.into(),
|
||||
time: rog_anime::AnimTime::Infinite,
|
||||
brightness,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
loop {
|
||||
for action in seq.iter() {
|
||||
if let ActionData::Animation(frames) = action {
|
||||
for frame in frames.frames() {
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(frame.frame().clone())
|
||||
.unwrap();
|
||||
sleep(frame.delay());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
44
asusctl/examples/anime-grid.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use rog_anime::{AnimeDataBuffer, AnimeGrid};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
|
||||
// 74w x 36h diagonal used by the windows app
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
let mut matrix = AnimeGrid::new(None);
|
||||
let tmp = matrix.get_mut();
|
||||
|
||||
let mut i = 0;
|
||||
for (y, row) in tmp.iter_mut().enumerate() {
|
||||
if y % 2 == 0 && i + 1 != row.len() - 1 {
|
||||
i += 1;
|
||||
dbg!(i);
|
||||
}
|
||||
row[row.len() - i] = 0x22;
|
||||
if i > 5 {
|
||||
row[row.len() - i + 5] = 0x22;
|
||||
}
|
||||
if i > 10 {
|
||||
row[row.len() - i + 10] = 0x22;
|
||||
}
|
||||
|
||||
if i > 15 {
|
||||
row[row.len() - i + 15] = 0x22;
|
||||
}
|
||||
|
||||
if i > 20 {
|
||||
row[row.len() - i + 20] = 0x22;
|
||||
}
|
||||
|
||||
if i > 25 {
|
||||
row[row.len() - i + 25] = 0x22;
|
||||
}
|
||||
}
|
||||
|
||||
let matrix = <AnimeDataBuffer>::from(matrix);
|
||||
|
||||
client.proxies().anime().write(matrix).unwrap();
|
||||
}
|
||||
129
asusctl/examples/anime-outline.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use rog_anime::AnimeDataBuffer;
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
let mut matrix = AnimeDataBuffer::new();
|
||||
matrix.get_mut()[1] = 100; // start = 1
|
||||
for n in matrix.get_mut()[2..32].iter_mut() {
|
||||
*n = 250;
|
||||
}
|
||||
matrix.get_mut()[32] = 100; // end
|
||||
matrix.get_mut()[34] = 100; // start x = 0
|
||||
matrix.get_mut()[66] = 100; // end
|
||||
matrix.get_mut()[69] = 100; // start x = 1
|
||||
matrix.get_mut()[101] = 100; // end
|
||||
matrix.get_mut()[102] = 100; // start
|
||||
matrix.get_mut()[134] = 100; // end
|
||||
matrix.get_mut()[137] = 100; // start
|
||||
matrix.get_mut()[169] = 100; // end
|
||||
matrix.get_mut()[170] = 100; // start
|
||||
matrix.get_mut()[202] = 100; // end
|
||||
matrix.get_mut()[204] = 100; // start
|
||||
matrix.get_mut()[236] = 100; // end
|
||||
matrix.get_mut()[237] = 100; // start
|
||||
matrix.get_mut()[268] = 100; // end
|
||||
matrix.get_mut()[270] = 100; // start
|
||||
matrix.get_mut()[301] = 100; // end
|
||||
matrix.get_mut()[302] = 100; // start
|
||||
matrix.get_mut()[332] = 100; // end
|
||||
matrix.get_mut()[334] = 100; // start
|
||||
matrix.get_mut()[364] = 100; // end
|
||||
matrix.get_mut()[365] = 100; // start
|
||||
matrix.get_mut()[394] = 100; // end
|
||||
matrix.get_mut()[396] = 100; // start
|
||||
matrix.get_mut()[425] = 100; // end
|
||||
matrix.get_mut()[426] = 100; // start
|
||||
matrix.get_mut()[454] = 100; // end
|
||||
matrix.get_mut()[456] = 100; // start
|
||||
matrix.get_mut()[484] = 100; // end
|
||||
matrix.get_mut()[485] = 100; // start
|
||||
matrix.get_mut()[512] = 100; // end
|
||||
matrix.get_mut()[514] = 100; // start
|
||||
matrix.get_mut()[541] = 100; // end
|
||||
matrix.get_mut()[542] = 100; // start
|
||||
matrix.get_mut()[568] = 100; // end
|
||||
matrix.get_mut()[570] = 100; // start
|
||||
matrix.get_mut()[596] = 100; // end
|
||||
matrix.get_mut()[597] = 100; // start
|
||||
matrix.get_mut()[622] = 100; // end
|
||||
matrix.get_mut()[624] = 100; // start
|
||||
matrix.get_mut()[649] = 100; // end
|
||||
matrix.get_mut()[650] = 100; // start
|
||||
matrix.get_mut()[674] = 100; // end
|
||||
matrix.get_mut()[676] = 100; // start
|
||||
matrix.get_mut()[700] = 100; // end
|
||||
matrix.get_mut()[701] = 100; // start
|
||||
matrix.get_mut()[724] = 100; // end
|
||||
matrix.get_mut()[726] = 100; // start
|
||||
matrix.get_mut()[749] = 100; // end
|
||||
matrix.get_mut()[750] = 100; // start
|
||||
matrix.get_mut()[772] = 100; // end
|
||||
matrix.get_mut()[774] = 100; // start
|
||||
matrix.get_mut()[796] = 100; // end
|
||||
matrix.get_mut()[797] = 100; // start
|
||||
matrix.get_mut()[818] = 100; // end
|
||||
matrix.get_mut()[820] = 100; // start
|
||||
matrix.get_mut()[841] = 100; // end
|
||||
matrix.get_mut()[842] = 100; // start
|
||||
matrix.get_mut()[862] = 100; // end
|
||||
matrix.get_mut()[864] = 100; // start
|
||||
matrix.get_mut()[884] = 100; // end
|
||||
matrix.get_mut()[885] = 100; // start
|
||||
matrix.get_mut()[904] = 100; // end
|
||||
matrix.get_mut()[906] = 100; // start
|
||||
matrix.get_mut()[925] = 100; // end
|
||||
matrix.get_mut()[926] = 100; // start
|
||||
matrix.get_mut()[944] = 100; // end
|
||||
matrix.get_mut()[946] = 100; // start
|
||||
matrix.get_mut()[964] = 100; // end
|
||||
matrix.get_mut()[965] = 100; // start
|
||||
matrix.get_mut()[982] = 100; // end
|
||||
matrix.get_mut()[984] = 100; // start
|
||||
matrix.get_mut()[1001] = 100; // end
|
||||
matrix.get_mut()[1002] = 100; // start
|
||||
matrix.get_mut()[1018] = 100; // end
|
||||
matrix.get_mut()[1020] = 100; // start
|
||||
matrix.get_mut()[1036] = 100; // end
|
||||
matrix.get_mut()[1037] = 100; // start
|
||||
matrix.get_mut()[1052] = 100; // end
|
||||
matrix.get_mut()[1054] = 100; // start
|
||||
matrix.get_mut()[1069] = 100; // end
|
||||
matrix.get_mut()[1070] = 100; // start
|
||||
matrix.get_mut()[1084] = 100; // end
|
||||
matrix.get_mut()[1086] = 100; // start
|
||||
matrix.get_mut()[1100] = 100; // end
|
||||
matrix.get_mut()[1101] = 100; // start
|
||||
matrix.get_mut()[1114] = 100; // end
|
||||
matrix.get_mut()[1116] = 100; // start
|
||||
matrix.get_mut()[1129] = 100; // end
|
||||
matrix.get_mut()[1130] = 100; // start
|
||||
matrix.get_mut()[1142] = 100; // end
|
||||
matrix.get_mut()[1144] = 100; // start
|
||||
matrix.get_mut()[1156] = 100; // end
|
||||
matrix.get_mut()[1157] = 100; // start
|
||||
matrix.get_mut()[1168] = 100; // end
|
||||
matrix.get_mut()[1170] = 100; // start
|
||||
matrix.get_mut()[1181] = 100; // end
|
||||
matrix.get_mut()[1182] = 100; // start
|
||||
matrix.get_mut()[1192] = 100; // end
|
||||
matrix.get_mut()[1194] = 100; // start
|
||||
matrix.get_mut()[1204] = 100; // end
|
||||
matrix.get_mut()[1205] = 100; // start
|
||||
matrix.get_mut()[1214] = 100; // end
|
||||
matrix.get_mut()[1216] = 100; // start
|
||||
matrix.get_mut()[1225] = 100; // end
|
||||
matrix.get_mut()[1226] = 100; // start
|
||||
matrix.get_mut()[1234] = 100; // end
|
||||
matrix.get_mut()[1236] = 100; // start
|
||||
for n in matrix.get_mut()[1237..1244].iter_mut() {
|
||||
*n = 250;
|
||||
}
|
||||
matrix.get_mut()[1244] = 100; // end
|
||||
println!("{:?}", &matrix);
|
||||
|
||||
client.proxies().anime().write(matrix).unwrap();
|
||||
}
|
||||
36
asusctl/examples/anime-png.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use std::{env, error::Error, path::Path, process::exit};
|
||||
|
||||
use rog_anime::{
|
||||
AnimeDataBuffer, {AnimeImage, Vec2},
|
||||
};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().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");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
let matrix = AnimeImage::from_png(
|
||||
Path::new(&args[1]),
|
||||
args[2].parse::<f32>().unwrap(),
|
||||
args[3].parse::<f32>().unwrap(),
|
||||
Vec2::new(
|
||||
args[4].parse::<f32>().unwrap(),
|
||||
args[5].parse::<f32>().unwrap(),
|
||||
),
|
||||
args[6].parse::<f32>().unwrap(),
|
||||
)?;
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::from(&matrix))
|
||||
.unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
45
asusctl/examples/anime-spinning.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::{
|
||||
env, error::Error, f32::consts::PI, path::Path, process::exit, thread::sleep, time::Duration,
|
||||
};
|
||||
|
||||
use rog_anime::{
|
||||
AnimeDataBuffer, {AnimeImage, Vec2},
|
||||
};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().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");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
let mut matrix = AnimeImage::from_png(
|
||||
Path::new(&args[1]),
|
||||
args[2].parse::<f32>().unwrap(),
|
||||
args[3].parse::<f32>().unwrap(),
|
||||
Vec2::new(
|
||||
args[4].parse::<f32>().unwrap(),
|
||||
args[5].parse::<f32>().unwrap(),
|
||||
),
|
||||
args[6].parse::<f32>().unwrap(),
|
||||
)?;
|
||||
|
||||
loop {
|
||||
matrix.angle += 0.05;
|
||||
if matrix.angle > PI * 2.0 {
|
||||
matrix.angle = 0.0
|
||||
}
|
||||
matrix.update();
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::from(&matrix))
|
||||
.unwrap();
|
||||
sleep(Duration::from_micros(500));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
use asus_nb::{
|
||||
core_dbus::AuraDbusClient,
|
||||
fancy::{GX502Layout, Key, KeyColourArray, KeyLayout},
|
||||
};
|
||||
use rog_aura::{GX502Layout, Key, KeyColourArray, KeyLayout};
|
||||
use rog_dbus::RogDbusClient;
|
||||
use std::collections::LinkedList;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -54,7 +52,7 @@ impl Ball {
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut writer = AuraDbusClient::new()?;
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let mut colours = KeyColourArray::new();
|
||||
|
||||
@@ -62,7 +60,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let mut balls = [Ball::new(2, 1, 12), Ball::new(4, 6, 12)];
|
||||
|
||||
writer.init_effect()?;
|
||||
dbus.proxies().led().init_effect()?;
|
||||
|
||||
let rows = layout.get_rows();
|
||||
loop {
|
||||
@@ -89,10 +87,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
*c.2 = 255;
|
||||
};
|
||||
}
|
||||
dbus.proxies().led().set_per_key(&colours)?;
|
||||
|
||||
writer.write_colour_block(&colours)?;
|
||||
|
||||
// can change 100 times per second, so need to slow it down
|
||||
//std::thread::sleep(std::time::Duration::from_millis(30));
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
use asus_nb::{
|
||||
core_dbus::AuraDbusClient,
|
||||
fancy::{GX502Layout, KeyColourArray, KeyLayout},
|
||||
};
|
||||
use rog_aura::{GX502Layout, KeyColourArray, KeyLayout};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut writer = AuraDbusClient::new()?;
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let layout = GX502Layout::default();
|
||||
|
||||
writer.init_effect()?;
|
||||
dbus.proxies().led().init_effect()?;
|
||||
let rows = layout.get_rows();
|
||||
|
||||
let mut column = 0;
|
||||
@@ -25,7 +23,6 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
column += 1;
|
||||
}
|
||||
|
||||
writer.write_colour_block(&key_colours)?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(30));
|
||||
dbus.proxies().led().set_per_key(&key_colours)?;
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
use asus_nb::{
|
||||
core_dbus::AuraDbusClient,
|
||||
fancy::{GX502Layout, Key, KeyColourArray, KeyLayout},
|
||||
};
|
||||
use rog_aura::{GX502Layout, Key, KeyColourArray, KeyLayout};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut writer = AuraDbusClient::new()?;
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let mut key_colours = KeyColourArray::new();
|
||||
let layout = GX502Layout::default();
|
||||
|
||||
writer.init_effect()?;
|
||||
dbus.proxies().led().init_effect()?;
|
||||
let rows = layout.get_rows();
|
||||
loop {
|
||||
for (r, row) in rows.iter().enumerate() {
|
||||
@@ -48,7 +46,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
*key_colours.key(Key::S).unwrap().0 = 255;
|
||||
*key_colours.key(Key::D).unwrap().0 = 255;
|
||||
|
||||
writer.write_colour_block(&key_colours)?;
|
||||
dbus.proxies().led().set_per_key(&key_colours)?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,31 @@
|
||||
use asus_nb::{
|
||||
core_dbus::AuraDbusClient,
|
||||
fancy::{Key, KeyColourArray},
|
||||
};
|
||||
use rog_aura::{Key, KeyColourArray};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut writer = AuraDbusClient::new()?;
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let mut key_colours = KeyColourArray::new();
|
||||
|
||||
writer.init_effect()?;
|
||||
dbus.proxies().led().init_effect()?;
|
||||
loop {
|
||||
let count = 49;
|
||||
for _ in 0..count {
|
||||
*key_colours.key(Key::ROG).unwrap().0 += 5;
|
||||
*key_colours.key(Key::Rog).unwrap().0 += 5;
|
||||
*key_colours.key(Key::L).unwrap().0 += 5;
|
||||
*key_colours.key(Key::I).unwrap().0 += 5;
|
||||
*key_colours.key(Key::N).unwrap().0 += 5;
|
||||
*key_colours.key(Key::U).unwrap().0 += 5;
|
||||
*key_colours.key(Key::X).unwrap().0 += 5;
|
||||
writer.write_colour_block(&key_colours)?;
|
||||
dbus.proxies().led().set_per_key(&key_colours)?;
|
||||
}
|
||||
for _ in 0..count {
|
||||
*key_colours.key(Key::ROG).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::Rog).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::L).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::I).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::N).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::U).unwrap().0 -= 5;
|
||||
*key_colours.key(Key::X).unwrap().0 -= 5;
|
||||
writer.write_colour_block(&key_colours)?;
|
||||
dbus.proxies().led().set_per_key(&key_colours)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
use asus_nb::{
|
||||
core_dbus::AuraDbusClient,
|
||||
fancy::{GX502Layout, KeyColourArray, KeyLayout},
|
||||
};
|
||||
use rog_aura::{GX502Layout, KeyColourArray, KeyLayout};
|
||||
use rog_dbus::RogDbusClient;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut writer = AuraDbusClient::new()?;
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let mut key_colours = KeyColourArray::new();
|
||||
let layout = GX502Layout::default();
|
||||
|
||||
writer.init_effect()?;
|
||||
dbus.proxies().led().init_effect()?;
|
||||
let rows = layout.get_rows();
|
||||
|
||||
let mut fade = 50;
|
||||
@@ -23,7 +21,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
|
||||
writer.write_colour_block(&key_colours)?;
|
||||
dbus.proxies().led().set_per_key(&key_colours)?;
|
||||
|
||||
if flip {
|
||||
if fade > 1 {
|
||||
BIN
asusctl/examples/controller.gif
Normal file
|
After Width: | Height: | Size: 32 KiB |
BIN
asusctl/examples/doom.png
Normal file
|
After Width: | Height: | Size: 140 KiB |
BIN
asusctl/examples/ferris.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
asusctl/examples/nudoom.png
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
asusctl/examples/rust.png
Normal file
|
After Width: | Height: | Size: 29 KiB |
92
asusctl/src/anime_cli.rs
Normal file
@@ -0,0 +1,92 @@
|
||||
use gumdrop::Options;
|
||||
use rog_aura::error::Error;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum AnimeStatusValue {
|
||||
On,
|
||||
Off,
|
||||
}
|
||||
impl FromStr for AnimeStatusValue {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.to_lowercase();
|
||||
match s.as_str() {
|
||||
"on" => Ok(AnimeStatusValue::On),
|
||||
"off" => Ok(AnimeStatusValue::Off),
|
||||
_ => {
|
||||
print!("Invalid argument, must be one of: on, off");
|
||||
Err(Error::ParseAnime)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<AnimeStatusValue> for bool {
|
||||
fn from(value: AnimeStatusValue) -> Self {
|
||||
match value {
|
||||
AnimeStatusValue::On => true,
|
||||
AnimeStatusValue::Off => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct AnimeLeds {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(
|
||||
no_long,
|
||||
required,
|
||||
short = "b",
|
||||
meta = "",
|
||||
help = "set all leds brightness value"
|
||||
)]
|
||||
led_brightness: u8,
|
||||
}
|
||||
impl AnimeLeds {
|
||||
pub fn led_brightness(&self) -> u8 {
|
||||
self.led_brightness
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct AnimeCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "turn on/off the panel (accept/reject write requests)"
|
||||
)]
|
||||
pub turn: Option<AnimeStatusValue>,
|
||||
#[options(meta = "", help = "turn on/off the panel at boot (with Asus effect)")]
|
||||
pub boot: Option<AnimeStatusValue>,
|
||||
#[options(command)]
|
||||
pub command: Option<AnimeActions>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub enum AnimeActions {
|
||||
#[options(help = "change all leds brightness")]
|
||||
Leds(AnimeLeds),
|
||||
#[options(help = "display an 8bit greyscale png")]
|
||||
Image(AnimeImage),
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct AnimeImage {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(meta = "", help = "full path to the png to display")]
|
||||
pub path: String,
|
||||
#[options(meta = "", default = "1.0", help = "scale 1.0 == normal")]
|
||||
pub scale: f32,
|
||||
#[options(meta = "", default = "0.0", help = "x position (float)")]
|
||||
pub x_pos: f32,
|
||||
#[options(meta = "", default = "0.0", help = "y position (float)")]
|
||||
pub y_pos: f32,
|
||||
#[options(meta = "", default = "0.0", help = "the angle in radians")]
|
||||
pub angle: f32,
|
||||
#[options(meta = "", default = "1.0", help = "brightness 0.0-1.0")]
|
||||
pub bright: f32,
|
||||
}
|
||||
327
asusctl/src/aura_cli.rs
Normal file
@@ -0,0 +1,327 @@
|
||||
use gumdrop::Options;
|
||||
use rog_aura::{error::Error, AuraEffect, AuraModeNum, AuraZone, Colour, Direction, Speed};
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct LedBrightness {
|
||||
level: Option<u32>,
|
||||
}
|
||||
impl LedBrightness {
|
||||
pub fn new(level: Option<u32>) -> Self {
|
||||
LedBrightness { level }
|
||||
}
|
||||
|
||||
pub fn level(&self) -> Option<u32> {
|
||||
self.level
|
||||
}
|
||||
}
|
||||
impl FromStr for LedBrightness {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.to_lowercase();
|
||||
match s.as_str() {
|
||||
"off" => Ok(LedBrightness { level: Some(0x00) }),
|
||||
"low" => Ok(LedBrightness { level: Some(0x01) }),
|
||||
"med" => Ok(LedBrightness { level: Some(0x02) }),
|
||||
"high" => Ok(LedBrightness { level: Some(0x03) }),
|
||||
_ => {
|
||||
print!("Invalid argument, must be one of: off, low, med, high");
|
||||
Err(Error::ParseBrightness)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ToString for LedBrightness {
|
||||
fn to_string(&self) -> String {
|
||||
let s = match self.level {
|
||||
Some(0x00) => "low",
|
||||
Some(0x01) => "med",
|
||||
Some(0x02) => "high",
|
||||
_ => "unknown",
|
||||
};
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Options, Default)]
|
||||
pub struct SingleSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "WORD", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
#[derive(Debug, Clone, Options, Default)]
|
||||
pub struct SingleSpeedDirection {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "", help = "set the direction: up, down, left, right")]
|
||||
pub direction: Direction,
|
||||
#[options(no_long, meta = "", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Options)]
|
||||
pub struct SingleColour {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Options)]
|
||||
pub struct SingleColourSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
#[options(no_long, meta = "", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Options, Default)]
|
||||
pub struct TwoColourSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(no_long, meta = "", help = "set the first RGB value e.g, ff00ff")]
|
||||
pub colour: Colour,
|
||||
#[options(no_long, meta = "", help = "set the second RGB value e.g, ff00ff")]
|
||||
pub colour2: Colour,
|
||||
#[options(no_long, meta = "", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Options)]
|
||||
pub struct MultiColour {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(short = "a", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour1: Colour,
|
||||
#[options(short = "b", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour2: Colour,
|
||||
#[options(short = "c", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour3: Colour,
|
||||
#[options(short = "d", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour4: Colour,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Options)]
|
||||
pub struct MultiColourSpeed {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(short = "a", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour1: Colour,
|
||||
#[options(short = "b", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour2: Colour,
|
||||
#[options(short = "c", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour3: Colour,
|
||||
#[options(short = "d", meta = "", help = "set the RGB value e.g, ff00ff")]
|
||||
pub colour4: Colour,
|
||||
#[options(no_long, meta = "", help = "set the speed: low, med, high")]
|
||||
pub speed: Speed,
|
||||
}
|
||||
|
||||
/// Byte value for setting the built-in mode.
|
||||
///
|
||||
/// Enum corresponds to the required integer value
|
||||
#[derive(Options)]
|
||||
pub enum SetAuraBuiltin {
|
||||
#[options(help = "set a single static colour")]
|
||||
Static(SingleColour),
|
||||
#[options(help = "pulse between one or two colours")]
|
||||
Breathe(TwoColourSpeed),
|
||||
#[options(help = "strobe through all colours")]
|
||||
Strobe(SingleSpeed),
|
||||
#[options(help = "rainbow cycling in one of four directions")]
|
||||
Rainbow(SingleSpeedDirection),
|
||||
#[options(help = "rain pattern mimicking raindrops")]
|
||||
Star(TwoColourSpeed),
|
||||
#[options(help = "rain pattern of three preset colours")]
|
||||
Rain(SingleSpeed),
|
||||
#[options(help = "pressed keys are highlighted to fade")]
|
||||
Highlight(SingleColourSpeed),
|
||||
#[options(help = "pressed keys generate horizontal laser")]
|
||||
Laser(SingleColourSpeed),
|
||||
#[options(help = "pressed keys ripple outwards like a splash")]
|
||||
Ripple(SingleColourSpeed),
|
||||
#[options(help = "set a rapid pulse")]
|
||||
Pulse(SingleColour),
|
||||
#[options(help = "set a vertical line zooming from left")]
|
||||
Comet(SingleColour),
|
||||
#[options(help = "set a wide vertical line zooming from left")]
|
||||
Flash(SingleColour),
|
||||
#[options(help = "4-zone multi-colour")]
|
||||
MultiStatic(MultiColour),
|
||||
#[options(help = "4-zone multi-colour breathing")]
|
||||
MultiBreathe(MultiColourSpeed),
|
||||
}
|
||||
|
||||
impl Default for SetAuraBuiltin {
|
||||
fn default() -> Self {
|
||||
SetAuraBuiltin::Static(SingleColour::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SingleColour> for AuraEffect {
|
||||
fn from(aura: &SingleColour) -> Self {
|
||||
Self {
|
||||
colour1: aura.colour,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SingleSpeed> for AuraEffect {
|
||||
fn from(aura: &SingleSpeed) -> Self {
|
||||
Self {
|
||||
speed: aura.speed,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SingleColourSpeed> for AuraEffect {
|
||||
fn from(aura: &SingleColourSpeed) -> Self {
|
||||
Self {
|
||||
colour1: aura.colour,
|
||||
speed: aura.speed,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&TwoColourSpeed> for AuraEffect {
|
||||
fn from(aura: &TwoColourSpeed) -> Self {
|
||||
Self {
|
||||
colour1: aura.colour,
|
||||
colour2: aura.colour2,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SingleSpeedDirection> for AuraEffect {
|
||||
fn from(aura: &SingleSpeedDirection) -> Self {
|
||||
Self {
|
||||
speed: aura.speed,
|
||||
direction: aura.direction,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SetAuraBuiltin> for AuraEffect {
|
||||
fn from(aura: &SetAuraBuiltin) -> Self {
|
||||
match aura {
|
||||
SetAuraBuiltin::Static(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Static;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Breathe(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Breathe;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Strobe(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Strobe;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Rainbow(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Rainbow;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Star(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Star;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Rain(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Rain;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Highlight(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Highlight;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Laser(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Laser;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Ripple(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Ripple;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Pulse(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Pulse;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Comet(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Comet;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Flash(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Flash;
|
||||
data
|
||||
}
|
||||
_ => AuraEffect::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&SetAuraBuiltin> for Vec<AuraEffect> {
|
||||
fn from(aura: &SetAuraBuiltin) -> Vec<AuraEffect> {
|
||||
let mut zones = vec![AuraEffect::default(); 4];
|
||||
match aura {
|
||||
SetAuraBuiltin::MultiStatic(data) => {
|
||||
zones[0].mode = AuraModeNum::Static;
|
||||
zones[0].zone = AuraZone::One;
|
||||
zones[0].colour1 = data.colour1;
|
||||
|
||||
zones[1].mode = AuraModeNum::Static;
|
||||
zones[1].zone = AuraZone::Two;
|
||||
zones[1].colour1 = data.colour2;
|
||||
|
||||
zones[2].mode = AuraModeNum::Static;
|
||||
zones[2].zone = AuraZone::Three;
|
||||
zones[2].colour1 = data.colour3;
|
||||
|
||||
zones[3].mode = AuraModeNum::Static;
|
||||
zones[3].zone = AuraZone::Four;
|
||||
zones[3].colour1 = data.colour4;
|
||||
}
|
||||
SetAuraBuiltin::MultiBreathe(data) => {
|
||||
zones[0].mode = AuraModeNum::Breathe;
|
||||
zones[0].zone = AuraZone::One;
|
||||
zones[0].colour1 = data.colour1;
|
||||
zones[0].speed = data.speed;
|
||||
|
||||
zones[1].mode = AuraModeNum::Breathe;
|
||||
zones[1].zone = AuraZone::Two;
|
||||
zones[1].colour1 = data.colour2;
|
||||
zones[1].speed = data.speed;
|
||||
|
||||
zones[2].mode = AuraModeNum::Breathe;
|
||||
zones[2].zone = AuraZone::Three;
|
||||
zones[2].colour1 = data.colour3;
|
||||
zones[2].speed = data.speed;
|
||||
|
||||
zones[3].mode = AuraModeNum::Breathe;
|
||||
zones[3].zone = AuraZone::Four;
|
||||
zones[3].colour1 = data.colour4;
|
||||
zones[3].speed = data.speed;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
zones
|
||||
}
|
||||
}
|
||||
573
asusctl/src/main.rs
Normal file
@@ -0,0 +1,573 @@
|
||||
mod anime_cli;
|
||||
mod aura_cli;
|
||||
mod profiles_cli;
|
||||
|
||||
use crate::aura_cli::{LedBrightness, SetAuraBuiltin};
|
||||
use anime_cli::{AnimeActions, AnimeCommand};
|
||||
use gumdrop::{Opt, Options};
|
||||
use profiles_cli::ProfileCommand;
|
||||
use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2, ANIME_DATA_LEN};
|
||||
use rog_aura::{self, AuraEffect};
|
||||
use rog_dbus::RogDbusClient;
|
||||
use rog_profiles::profiles::Profile;
|
||||
use rog_types::{
|
||||
gfx_vendors::GfxVendors,
|
||||
supported::{
|
||||
FanCpuSupportedFunctions, LedSupportedFunctions, RogBiosSupportedFunctions,
|
||||
SupportedFunctions,
|
||||
},
|
||||
};
|
||||
use std::{env::args, path::Path};
|
||||
use yansi_term::Colour::Green;
|
||||
use yansi_term::Colour::Red;
|
||||
|
||||
#[derive(Default, Options)]
|
||||
struct CliStart {
|
||||
#[options(help_flag, help = "print help message")]
|
||||
help: bool,
|
||||
#[options(help = "show program version number")]
|
||||
version: bool,
|
||||
#[options(help = "show supported functions of this laptop")]
|
||||
show_supported: bool,
|
||||
#[options(meta = "", help = "<off, low, med, high>")]
|
||||
kbd_bright: Option<LedBrightness>,
|
||||
#[options(meta = "", help = "<20-100>")]
|
||||
chg_limit: Option<u8>,
|
||||
#[options(command)]
|
||||
command: Option<CliCommand>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
enum CliCommand {
|
||||
#[options(help = "Set the keyboard lighting from built-in modes")]
|
||||
LedMode(LedModeCommand),
|
||||
#[options(help = "Create and configure profiles")]
|
||||
Profile(ProfileCommand),
|
||||
#[options(help = "Set the graphics mode")]
|
||||
Graphics(GraphicsCommand),
|
||||
#[options(name = "anime", help = "Manage AniMe Matrix")]
|
||||
Anime(AnimeCommand),
|
||||
#[options(help = "Change bios settings")]
|
||||
Bios(BiosCommand),
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
struct LedModeCommand {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(help = "switch to next aura mode")]
|
||||
next_mode: bool,
|
||||
#[options(help = "switch to previous aura mode")]
|
||||
prev_mode: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "set the keyboard LED to enabled while the device is awake"
|
||||
)]
|
||||
awake_enable: Option<bool>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "set the keyboard LED suspend animation to enabled while the device is suspended"
|
||||
)]
|
||||
sleep_enable: Option<bool>,
|
||||
#[options(command)]
|
||||
command: Option<SetAuraBuiltin>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
struct GraphicsCommand {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set graphics mode: <nvidia, hybrid, compute, integrated>"
|
||||
)]
|
||||
mode: Option<GfxVendors>,
|
||||
#[options(help = "Get the current mode")]
|
||||
get: bool,
|
||||
#[options(help = "Get the current power status")]
|
||||
pow: bool,
|
||||
#[options(help = "Do not ask for confirmation")]
|
||||
force: bool,
|
||||
}
|
||||
|
||||
#[derive(Options, Debug)]
|
||||
struct BiosCommand {
|
||||
#[options(help = "print help message")]
|
||||
help: bool,
|
||||
#[options(meta = "", no_long, help = "set bios POST sound <true/false>")]
|
||||
post_sound_set: Option<bool>,
|
||||
#[options(no_long, help = "read bios POST sound")]
|
||||
post_sound_get: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
no_long,
|
||||
help = "activate dGPU dedicated/G-Sync <true/false>"
|
||||
)]
|
||||
dedicated_gfx_set: Option<bool>,
|
||||
#[options(no_long, help = "get GPU mode")]
|
||||
dedicated_gfx_get: bool,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<String> = args().skip(1).collect();
|
||||
|
||||
let parsed: CliStart;
|
||||
let missing_argument_k = gumdrop::Error::missing_argument(Opt::Short('k'));
|
||||
match CliStart::parse_args_default(&args) {
|
||||
Ok(p) => {
|
||||
parsed = p;
|
||||
}
|
||||
Err(err) if err.to_string() == missing_argument_k.to_string() => {
|
||||
parsed = CliStart {
|
||||
kbd_bright: Some(LedBrightness::new(None)),
|
||||
..Default::default()
|
||||
};
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("source {}", err);
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
let (dbus, _) = RogDbusClient::new()?;
|
||||
|
||||
let supported = dbus.proxies().supported().get_supported_functions()?;
|
||||
|
||||
if parsed.help {
|
||||
print_supported_help(&supported, &parsed);
|
||||
println!("\nSee https://asus-linux.org/faq/ for additional help");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
if parsed.version {
|
||||
println!(" asusctl v{}", env!("CARGO_PKG_VERSION"));
|
||||
println!(" rog-dbus v{}", rog_dbus::VERSION);
|
||||
println!("rog-types v{}", rog_types::VERSION);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match parsed.command {
|
||||
Some(CliCommand::LedMode(mode)) => handle_led_mode(&dbus, &supported.keyboard_led, &mode)?,
|
||||
Some(CliCommand::Profile(cmd)) => handle_profile(&dbus, &supported.fan_cpu_ctrl, &cmd)?,
|
||||
Some(CliCommand::Graphics(cmd)) => do_gfx(&dbus, &supported.rog_bios_ctrl, cmd)?,
|
||||
Some(CliCommand::Anime(cmd)) => {
|
||||
if (cmd.command.is_none() && cmd.boot.is_none() && cmd.turn.is_none()) || cmd.help {
|
||||
println!("Missing arg or command\n\n{}", cmd.self_usage());
|
||||
if let Some(lst) = cmd.self_command_list() {
|
||||
println!("\n{}", lst);
|
||||
}
|
||||
}
|
||||
if let Some(anime_turn) = cmd.turn {
|
||||
dbus.proxies().anime().toggle_on(anime_turn.into())?
|
||||
}
|
||||
if let Some(anime_boot) = cmd.boot {
|
||||
dbus.proxies().anime().toggle_boot_on(anime_boot.into())?
|
||||
}
|
||||
if let Some(action) = cmd.command {
|
||||
match action {
|
||||
AnimeActions::Leds(anime_leds) => {
|
||||
let data = AnimeDataBuffer::from_vec(
|
||||
[anime_leds.led_brightness(); ANIME_DATA_LEN].to_vec(),
|
||||
);
|
||||
dbus.proxies().anime().write(data)?;
|
||||
}
|
||||
AnimeActions::Image(image) => {
|
||||
if image.help_requested() {
|
||||
println!("Missing arg or command\n\n{}", image.self_usage());
|
||||
if let Some(lst) = image.self_command_list() {
|
||||
println!("\n{}", lst);
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let matrix = AnimeImage::from_png(
|
||||
Path::new(&image.path),
|
||||
image.scale,
|
||||
image.angle,
|
||||
Vec2::new(image.x_pos, image.y_pos),
|
||||
image.bright,
|
||||
)?;
|
||||
|
||||
dbus.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::from(&matrix))
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(CliCommand::Bios(cmd)) => handle_bios_option(&dbus, &supported.rog_bios_ctrl, &cmd)?,
|
||||
None => {
|
||||
if (!parsed.show_supported && parsed.kbd_bright.is_none() && parsed.chg_limit.is_none())
|
||||
|| parsed.help
|
||||
{
|
||||
println!("{}", CliStart::usage());
|
||||
println!();
|
||||
println!("{}", CliStart::command_list().unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(brightness) = parsed.kbd_bright {
|
||||
match brightness.level() {
|
||||
None => {
|
||||
let level = dbus.proxies().led().get_led_brightness()?;
|
||||
println!("Current keyboard led brightness: {}", level.to_string());
|
||||
}
|
||||
Some(level) => dbus
|
||||
.proxies()
|
||||
.led()
|
||||
.set_led_brightness(<rog_aura::LedBrightness>::from(level))?,
|
||||
}
|
||||
}
|
||||
|
||||
if parsed.show_supported {
|
||||
let dat = dbus.proxies().supported().get_supported_functions()?;
|
||||
println!("Supported laptop functions:\n{:?}", dat);
|
||||
}
|
||||
|
||||
if let Some(chg_limit) = parsed.chg_limit {
|
||||
dbus.proxies().charge().write_limit(chg_limit)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_supported_help(supported: &SupportedFunctions, parsed: &CliStart) {
|
||||
// As help option don't work with `parse_args_default`
|
||||
// we will call `parse_args_default_or_exit` instead
|
||||
let usage: Vec<String> = parsed.self_usage().lines().map(|s| s.to_string()).collect();
|
||||
for line in usage.iter().filter(|line| {
|
||||
if line.contains("--fan-mode") && !supported.fan_cpu_ctrl.stock_fan_modes {
|
||||
return false;
|
||||
}
|
||||
if line.contains("--chg-limit") && !supported.charge_ctrl.charge_level_set {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}) {
|
||||
println!("{}", line);
|
||||
}
|
||||
|
||||
// command strings are in order of the struct
|
||||
let commands: Vec<String> = CliCommand::usage().lines().map(|s| s.to_string()).collect();
|
||||
println!("\nCommands available");
|
||||
for line in commands.iter().filter(|line| {
|
||||
if line.contains("profile")
|
||||
&& !supported.fan_cpu_ctrl.stock_fan_modes
|
||||
&& !supported.fan_cpu_ctrl.fan_curve_set
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if line.contains("led-mode") && !supported.keyboard_led.stock_led_modes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if line.contains("bios")
|
||||
&& (!supported.rog_bios_ctrl.dedicated_gfx_toggle
|
||||
|| !supported.rog_bios_ctrl.post_sound_toggle)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if line.contains("anime") && !supported.anime_ctrl.0 {
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}) {
|
||||
println!("{}", line);
|
||||
}
|
||||
|
||||
if !supported.fan_cpu_ctrl.stock_fan_modes {
|
||||
println!("Note: Fan mode control is not supported by this laptop");
|
||||
}
|
||||
if !supported.charge_ctrl.charge_level_set {
|
||||
println!("Note: Charge control is not supported by this laptop");
|
||||
}
|
||||
}
|
||||
|
||||
fn do_gfx(
|
||||
dbus: &RogDbusClient,
|
||||
supported: &RogBiosSupportedFunctions,
|
||||
command: GraphicsCommand,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if command.mode.is_none() && !command.get && !command.pow && !command.force || command.help {
|
||||
println!("{}", command.self_usage());
|
||||
}
|
||||
|
||||
if let Some(mode) = command.mode {
|
||||
if supported.dedicated_gfx_toggle && dbus.proxies().rog_bios().get_dedicated_gfx()? == 1 {
|
||||
println!("You can not change modes until you turn dedicated/G-Sync off and reboot");
|
||||
std::process::exit(-1);
|
||||
}
|
||||
|
||||
println!("If anything fails check `journalctl -b -u asusd`\n");
|
||||
|
||||
dbus.proxies().gfx().gfx_write_mode(&mode).map_err(|err|{
|
||||
println!("Graphics mode change error. You may be in an invalid state.");
|
||||
println!("Check mode with `asusctl graphics -g` and switch to opposite\nmode to correct it, e.g: if integrated, switch to hybrid, or if nvidia, switch to integrated.\n");
|
||||
err
|
||||
})?;
|
||||
let res = dbus.gfx_wait_changed()?;
|
||||
println!(
|
||||
"Graphics mode changed to {}. User action required is: {}",
|
||||
<&str>::from(mode),
|
||||
<&str>::from(&res)
|
||||
);
|
||||
std::process::exit(0)
|
||||
}
|
||||
if command.get {
|
||||
let res = dbus.proxies().gfx().gfx_get_mode()?;
|
||||
println!("Current graphics mode: {}", <&str>::from(res));
|
||||
}
|
||||
if command.pow {
|
||||
let res = dbus.proxies().gfx().gfx_get_pwr()?;
|
||||
match res {
|
||||
rog_types::gfx_vendors::GfxPower::Active => {
|
||||
println!("Current power status: {}", Red.paint(<&str>::from(&res)))
|
||||
}
|
||||
_ => println!("Current power status: {}", Green.paint(<&str>::from(&res))),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_led_mode(
|
||||
dbus: &RogDbusClient,
|
||||
supported: &LedSupportedFunctions,
|
||||
mode: &LedModeCommand,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if mode.command.is_none()
|
||||
&& !mode.prev_mode
|
||||
&& !mode.next_mode
|
||||
&& mode.sleep_enable.is_none()
|
||||
&& mode.awake_enable.is_none()
|
||||
{
|
||||
if !mode.help {
|
||||
println!("Missing arg or command\n");
|
||||
}
|
||||
println!("{}\n", mode.self_usage());
|
||||
println!("Commands available");
|
||||
|
||||
let commands: Vec<String> = LedModeCommand::command_list()
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
for command in commands.iter().filter(|command| {
|
||||
for mode in &supported.stock_led_modes {
|
||||
if command.contains(<&str>::from(mode)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if supported.multizone_led_mode {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}) {
|
||||
println!("{}", command);
|
||||
}
|
||||
|
||||
println!("\nHelp can also be requested on modes, e.g: static --help");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if mode.next_mode && mode.prev_mode {
|
||||
println!("Please specify either next or previous");
|
||||
return Ok(());
|
||||
}
|
||||
if mode.next_mode {
|
||||
dbus.proxies().led().next_led_mode()?;
|
||||
} else if mode.prev_mode {
|
||||
dbus.proxies().led().prev_led_mode()?;
|
||||
} else if let Some(mode) = mode.command.as_ref() {
|
||||
if mode.help_requested() {
|
||||
println!("{}", mode.self_usage());
|
||||
return Ok(());
|
||||
}
|
||||
match mode {
|
||||
SetAuraBuiltin::MultiStatic(_) | SetAuraBuiltin::MultiBreathe(_) => {
|
||||
let zones = <Vec<AuraEffect>>::from(mode);
|
||||
for eff in zones {
|
||||
dbus.proxies().led().set_led_mode(&eff)?
|
||||
}
|
||||
}
|
||||
_ => dbus
|
||||
.proxies()
|
||||
.led()
|
||||
.set_led_mode(&<AuraEffect>::from(mode))?,
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(enable) = mode.awake_enable {
|
||||
dbus.proxies().led().set_awake_enabled(enable)?;
|
||||
}
|
||||
|
||||
if let Some(enable) = mode.sleep_enable {
|
||||
dbus.proxies().led().set_sleep_enabled(enable)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_profile(
|
||||
dbus: &RogDbusClient,
|
||||
supported: &FanCpuSupportedFunctions,
|
||||
cmd: &ProfileCommand,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if !cmd.next
|
||||
&& !cmd.create // TODO
|
||||
&& !cmd.list
|
||||
&& cmd.profile.is_none()
|
||||
&& !cmd.active_name
|
||||
&& !cmd.active_data
|
||||
&& !cmd.profiles_data
|
||||
&& cmd.remove.is_none()
|
||||
&& cmd.curve.is_none() // TODO
|
||||
&& cmd.fan_preset.is_none() // TODO
|
||||
&& cmd.turbo.is_none() // TODO
|
||||
&& cmd.max_percentage.is_none() // TODO
|
||||
&& cmd.min_percentage.is_none()
|
||||
// TODO
|
||||
{
|
||||
if !cmd.help {
|
||||
println!("Missing arg or command\n");
|
||||
}
|
||||
let usage: Vec<String> = ProfileCommand::usage()
|
||||
.lines()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
for line in usage
|
||||
.iter()
|
||||
.filter(|line| !line.contains("--curve") || supported.fan_curve_set)
|
||||
{
|
||||
println!("{}", line);
|
||||
}
|
||||
|
||||
if let Some(lst) = cmd.self_command_list() {
|
||||
println!("\n{}", lst);
|
||||
}
|
||||
|
||||
println!("Note: turbo, frequency, fan preset and fan curve options will apply to");
|
||||
println!(" to the currently active profile unless a profile name is specified");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
if cmd.next {
|
||||
dbus.proxies().profile().next_fan()?;
|
||||
}
|
||||
if let Some(profile) = &cmd.remove {
|
||||
dbus.proxies().profile().remove(profile)?
|
||||
}
|
||||
if cmd.list {
|
||||
let profile_names = dbus.proxies().profile().profile_names()?;
|
||||
println!("Available profiles are {:?}", profile_names);
|
||||
}
|
||||
if cmd.active_name {
|
||||
println!(
|
||||
"Active profile: {:?}",
|
||||
dbus.proxies().profile().active_name()?
|
||||
);
|
||||
}
|
||||
if cmd.active_data {
|
||||
println!("Active profile:");
|
||||
println!("{:?}", dbus.proxies().profile().active_data()?);
|
||||
}
|
||||
if cmd.profiles_data {
|
||||
println!("Profiles:");
|
||||
for s in dbus.proxies().profile().all_profile_data()?.lines() {
|
||||
println!("{}", s);
|
||||
}
|
||||
}
|
||||
|
||||
let mut set_profile = false;
|
||||
let mut profile;
|
||||
if cmd.create {
|
||||
profile = Profile::default();
|
||||
set_profile = true;
|
||||
} else {
|
||||
profile = dbus.proxies().profile().active_data()?;
|
||||
}
|
||||
|
||||
if let Some(turbo) = cmd.turbo {
|
||||
set_profile = true;
|
||||
profile.turbo = turbo;
|
||||
}
|
||||
if let Some(min) = cmd.min_percentage {
|
||||
set_profile = true;
|
||||
profile.min_percentage = min;
|
||||
}
|
||||
if let Some(max) = cmd.max_percentage {
|
||||
set_profile = true;
|
||||
profile.max_percentage = max;
|
||||
}
|
||||
if let Some(preset) = cmd.fan_preset {
|
||||
set_profile = true;
|
||||
profile.fan_preset = preset;
|
||||
}
|
||||
if let Some(ref curve) = cmd.curve {
|
||||
set_profile = true;
|
||||
profile.fan_curve = curve.as_config_string();
|
||||
}
|
||||
if let Some(ref name) = cmd.profile {
|
||||
set_profile = true;
|
||||
profile.name = name.clone();
|
||||
}
|
||||
if set_profile {
|
||||
dbus.proxies().profile().new_or_modify(&profile)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_bios_option(
|
||||
dbus: &RogDbusClient,
|
||||
supported: &RogBiosSupportedFunctions,
|
||||
cmd: &BiosCommand,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
{
|
||||
if (cmd.dedicated_gfx_set.is_none()
|
||||
&& !cmd.dedicated_gfx_get
|
||||
&& cmd.post_sound_set.is_none()
|
||||
&& !cmd.post_sound_get)
|
||||
|| cmd.help
|
||||
{
|
||||
println!("Missing arg or command\n");
|
||||
|
||||
let usage: Vec<String> = BiosCommand::usage()
|
||||
.lines()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
|
||||
for line in usage.iter().filter(|line| {
|
||||
!line.contains("sound") && !supported.post_sound_toggle
|
||||
|| !line.contains("GPU") && !supported.dedicated_gfx_toggle
|
||||
}) {
|
||||
println!("{}", line);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(opt) = cmd.post_sound_set {
|
||||
dbus.proxies().rog_bios().set_post_sound(opt)?;
|
||||
}
|
||||
if cmd.post_sound_get {
|
||||
let res = dbus.proxies().rog_bios().get_post_sound()? == 1;
|
||||
println!("Bios POST sound on: {}", res);
|
||||
}
|
||||
if let Some(opt) = cmd.dedicated_gfx_set {
|
||||
println!("Rebuilding initrd to include drivers");
|
||||
dbus.proxies().rog_bios().set_dedicated_gfx(opt)?;
|
||||
println!("The mode change is not active until you reboot, on boot the bios will make the required change");
|
||||
if opt {
|
||||
println!(
|
||||
"NOTE: on reboot your display manager will be forced to use Nvidia drivers"
|
||||
);
|
||||
} else {
|
||||
println!("NOTE: after reboot you can then select regular graphics modes");
|
||||
}
|
||||
}
|
||||
if cmd.dedicated_gfx_get {
|
||||
let res = dbus.proxies().rog_bios().get_dedicated_gfx()? == 1;
|
||||
println!("Bios dedicated GPU on: {}", res);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
53
asusctl/src/profiles_cli.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
use gumdrop::Options;
|
||||
use rog_fan_curve::{Curve, Fan};
|
||||
use rog_profiles::profiles::FanLevel;
|
||||
|
||||
#[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 = "create the profile if it doesn't exist")]
|
||||
pub create: bool,
|
||||
#[options(meta = "", help = "remove a profile by name")]
|
||||
pub remove: Option<String>,
|
||||
#[options(help = "list available profiles")]
|
||||
pub list: bool,
|
||||
#[options(help = "get active profile name")]
|
||||
pub active_name: bool,
|
||||
#[options(help = "get active profile data")]
|
||||
pub active_data: bool,
|
||||
#[options(help = "get all profile data")]
|
||||
pub profiles_data: bool,
|
||||
|
||||
// Options for profile
|
||||
#[options(meta = "", help = "enable or disable cpu turbo")]
|
||||
pub turbo: Option<bool>,
|
||||
#[options(meta = "", help = "set min cpu scaling (intel)")]
|
||||
pub min_percentage: Option<u8>,
|
||||
#[options(meta = "", help = "set max cpu scaling (intel)")]
|
||||
pub max_percentage: Option<u8>,
|
||||
|
||||
#[options(meta = "", help = "<silent, normal, boost>")]
|
||||
pub fan_preset: Option<FanLevel>,
|
||||
#[options(
|
||||
meta = "",
|
||||
parse(try_from_str = "parse_fan_curve"),
|
||||
help = "set fan curve"
|
||||
)]
|
||||
pub curve: Option<Curve>,
|
||||
#[options(free)]
|
||||
pub profile: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_fan_curve(data: &str) -> Result<Curve, String> {
|
||||
let curve = Curve::from_config_str(data)?;
|
||||
if let Err(err) = curve.check_safety(Fan::Cpu) {
|
||||
return Err(format!("Unsafe curve {:?}", err));
|
||||
}
|
||||
if let Err(err) = curve.check_safety(Fan::Gpu) {
|
||||
return Err(format!("Unsafe curve {:?}", err));
|
||||
}
|
||||
Ok(curve)
|
||||
}
|
||||
30
daemon-user/Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "daemon-user"
|
||||
version = "1.1.1"
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2018"
|
||||
description = "Usermode daemon for user settings, anime, per-key lighting"
|
||||
|
||||
[lib]
|
||||
name = "rog_user"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "asusd-user"
|
||||
path = "src/daemon.rs"
|
||||
|
||||
[dependencies]
|
||||
# serialisation
|
||||
serde = "^1.0"
|
||||
serde_json = "^1.0"
|
||||
serde_derive = "^1.0"
|
||||
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_types = { path = "../rog-types" }
|
||||
|
||||
dirs = "3.0.1"
|
||||
|
||||
zbus = "^1.9.1"
|
||||
zvariant = "^2.6"
|
||||
zvariant_derive = "^2.6"
|
||||
14
daemon-user/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# daemon-user
|
||||
|
||||
This crate is for the binary of `asusd-user` and its helper lib.
|
||||
|
||||
The purpose of `asusd-user` is to run in userland and provide the user + third-party apps an interface for such things as creating AniMe sequences (and more in future, see todo list).
|
||||
|
||||
`asusd-user` should try to be as simple as possible while allowing a decent degree of control.
|
||||
|
||||
## TODO
|
||||
|
||||
- [ ] CLI for basic settings/interaction
|
||||
- [ ] RGB keyboard per-key programs
|
||||
- [ ] User profiles (fan, cpu etc). These would be replacing the system-daemon profiles only when the user is active, otherwise system-daemon defaults to system settings.
|
||||
- [ ] Audio EQ visualiser - for use with anime + keyboard lighting
|
||||
353
daemon-user/src/ctrl_anime.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
use rog_anime::{ActionData, AnimTime, AnimeAction, Sequences, Vec2};
|
||||
use rog_dbus::RogDbusClient;
|
||||
//use crate::dbus::DbusEvents;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use std::{
|
||||
path::Path,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Mutex,
|
||||
},
|
||||
};
|
||||
use std::{sync::Arc, thread::sleep, time::Instant};
|
||||
use zbus::dbus_interface;
|
||||
use zvariant::ObjectPath;
|
||||
use zvariant_derive::Type;
|
||||
|
||||
use crate::{error::Error, user_config::UserAnimeConfig};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Type)]
|
||||
pub enum TimeType {
|
||||
Timer,
|
||||
Count,
|
||||
Infinite,
|
||||
}
|
||||
|
||||
/// The inner object exists to allow the zbus proxy to share it with a runner thread
|
||||
/// and a zbus server behind `Arc<Mutex<T>>`
|
||||
pub struct CtrlAnimeInner<'a> {
|
||||
sequences: Sequences,
|
||||
client: RogDbusClient<'a>,
|
||||
do_early_return: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl<'a> CtrlAnimeInner<'static> {
|
||||
pub fn new(
|
||||
sequences: Sequences,
|
||||
client: RogDbusClient<'static>,
|
||||
do_early_return: &'static AtomicBool,
|
||||
) -> Result<Self, Error> {
|
||||
Ok(Self {
|
||||
sequences,
|
||||
client,
|
||||
do_early_return,
|
||||
})
|
||||
}
|
||||
/// To be called on each main loop iteration to pump out commands to the anime
|
||||
pub fn run(&self) -> Result<(), Error> {
|
||||
if self.do_early_return.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for action in self.sequences.iter() {
|
||||
match action {
|
||||
ActionData::Animation(frames) => {
|
||||
let mut count = 0;
|
||||
let start = Instant::now();
|
||||
'animation: loop {
|
||||
for frame in frames.frames() {
|
||||
if self.do_early_return.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
self.client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(frame.frame().clone())
|
||||
.unwrap();
|
||||
if let AnimTime::Time(time) = frames.duration() {
|
||||
if Instant::now().duration_since(start) > time {
|
||||
break 'animation;
|
||||
}
|
||||
}
|
||||
sleep(frame.delay());
|
||||
}
|
||||
if let AnimTime::Cycles(times) = frames.duration() {
|
||||
count += 1;
|
||||
if count >= times {
|
||||
break 'animation;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionData::Image(image) => {
|
||||
self.client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(image.as_ref().clone())
|
||||
.unwrap();
|
||||
}
|
||||
ActionData::Pause(duration) => {
|
||||
let start = Instant::now();
|
||||
'pause: loop {
|
||||
if self.do_early_return.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
if Instant::now().duration_since(start) > *duration {
|
||||
break 'pause;
|
||||
}
|
||||
sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
ActionData::AudioEq => {}
|
||||
ActionData::SystemInfo => {}
|
||||
ActionData::TimeDate => {}
|
||||
ActionData::Matrix => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnime<'a> {
|
||||
config: Arc<Mutex<UserAnimeConfig>>,
|
||||
client: RogDbusClient<'a>,
|
||||
inner: Arc<Mutex<CtrlAnimeInner<'a>>>,
|
||||
/// Must be the same Atomic as in CtrlAnimeInner
|
||||
inner_early_return: &'a AtomicBool,
|
||||
}
|
||||
|
||||
impl<'a> CtrlAnime<'static> {
|
||||
pub fn new(
|
||||
config: Arc<Mutex<UserAnimeConfig>>,
|
||||
inner: Arc<Mutex<CtrlAnimeInner<'static>>>,
|
||||
client: RogDbusClient<'static>,
|
||||
inner_early_return: &'static AtomicBool,
|
||||
) -> Result<Self, Error> {
|
||||
Ok(CtrlAnime {
|
||||
config,
|
||||
client,
|
||||
inner,
|
||||
inner_early_return,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Anime"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
println!("CtrlAnime: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
// The pattern for a zbus method is:
|
||||
// - Get config lock if required
|
||||
// - Set inner_early_return to stop the inner run loop temporarily
|
||||
// - Do actions
|
||||
// - Write config if required
|
||||
// - Unset inner_early_return
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlAnime<'static> {
|
||||
pub fn insert_asus_gif(
|
||||
&mut self,
|
||||
index: u32,
|
||||
file: String,
|
||||
time: TimeType,
|
||||
count: u32,
|
||||
brightness: f32,
|
||||
) -> zbus::fdo::Result<String> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
let time: AnimTime = match time {
|
||||
TimeType::Timer => AnimTime::Time(Duration::from_millis(count as u64)),
|
||||
TimeType::Count => AnimTime::Cycles(count),
|
||||
TimeType::Infinite => AnimTime::Infinite,
|
||||
};
|
||||
let file = Path::new(&file);
|
||||
let action = AnimeAction::AsusAnimation {
|
||||
file: file.into(),
|
||||
brightness,
|
||||
time,
|
||||
};
|
||||
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Ok(mut controller) = self.inner.lock() {
|
||||
controller
|
||||
.sequences
|
||||
.insert(index as usize, &action)
|
||||
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
|
||||
}
|
||||
config.anime.push(action);
|
||||
config.write()?;
|
||||
|
||||
let json = serde_json::to_string_pretty(&*config).expect("Parse config to JSON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn insert_image_gif(
|
||||
&mut self,
|
||||
index: u32,
|
||||
file: String,
|
||||
scale: f32,
|
||||
angle: f32,
|
||||
xy: (f32, f32),
|
||||
time: TimeType,
|
||||
count: u32,
|
||||
brightness: f32,
|
||||
) -> zbus::fdo::Result<String> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
let time: AnimTime = match time {
|
||||
TimeType::Timer => AnimTime::Time(Duration::from_millis(count as u64)),
|
||||
TimeType::Count => AnimTime::Cycles(count),
|
||||
TimeType::Infinite => AnimTime::Infinite,
|
||||
};
|
||||
let file = Path::new(&file);
|
||||
let translation = Vec2::new(xy.0, xy.1);
|
||||
let action = AnimeAction::ImageAnimation {
|
||||
file: file.into(),
|
||||
scale,
|
||||
angle,
|
||||
translation,
|
||||
brightness,
|
||||
time,
|
||||
};
|
||||
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Ok(mut controller) = self.inner.lock() {
|
||||
controller
|
||||
.sequences
|
||||
.insert(index as usize, &action)
|
||||
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
|
||||
}
|
||||
config.anime.push(action);
|
||||
config.write()?;
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
|
||||
pub fn insert_image(
|
||||
&mut self,
|
||||
index: u32,
|
||||
file: String,
|
||||
scale: f32,
|
||||
angle: f32,
|
||||
xy: (f32, f32),
|
||||
brightness: f32,
|
||||
) -> zbus::fdo::Result<String> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
let file = Path::new(&file);
|
||||
let action = AnimeAction::Image {
|
||||
file: file.into(),
|
||||
scale,
|
||||
angle,
|
||||
translation: Vec2::new(xy.0, xy.1),
|
||||
brightness,
|
||||
};
|
||||
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Ok(mut controller) = self.inner.lock() {
|
||||
controller
|
||||
.sequences
|
||||
.insert(index as usize, &action)
|
||||
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
|
||||
}
|
||||
config.anime.push(action);
|
||||
config.write()?;
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
|
||||
pub fn insert_pause(&mut self, index: u32, millis: u64) -> zbus::fdo::Result<String> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
let action = AnimeAction::Pause(Duration::from_millis(millis));
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Ok(mut controller) = self.inner.lock() {
|
||||
controller
|
||||
.sequences
|
||||
.insert(index as usize, &action)
|
||||
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
|
||||
}
|
||||
config.anime.push(action);
|
||||
config.write()?;
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
|
||||
pub fn remove_item(&mut self, index: u32) -> zbus::fdo::Result<String> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
|
||||
if let Ok(mut controller) = self.inner.lock() {
|
||||
controller.sequences.remove_item(index as usize);
|
||||
}
|
||||
if (index as usize) < config.anime.len() {
|
||||
config.anime.remove(index as usize);
|
||||
}
|
||||
config.write()?;
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
|
||||
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().toggle_on(on)?;
|
||||
// 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().toggle_on(on)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
74
daemon-user/src/daemon.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use rog_dbus::RogDbusClient;
|
||||
use rog_user::{
|
||||
ctrl_anime::{CtrlAnime, CtrlAnimeInner},
|
||||
user_config::*,
|
||||
DBUS_NAME,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::thread;
|
||||
use zbus::{fdo, Connection};
|
||||
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
/// The anime loop needs an atomic to make it exit early if required
|
||||
static ANIME_INNER_EARLY_RETURN: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!(" user daemon v{}", rog_user::VERSION);
|
||||
println!(" rog-anime v{}", rog_anime::VERSION);
|
||||
println!(" rog-dbus v{}", rog_dbus::VERSION);
|
||||
println!(" rog-types v{}", rog_types::VERSION);
|
||||
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
let supported = client.proxies().supported().get_supported_functions()?;
|
||||
|
||||
let mut config = UserConfig::new();
|
||||
config.load_config()?;
|
||||
|
||||
let anime_config = UserAnimeConfig::load_config(config.active_anime)?;
|
||||
let anime = anime_config.create_anime()?;
|
||||
|
||||
let anime_config = Arc::new(Mutex::new(anime_config));
|
||||
|
||||
// Create server
|
||||
let connection = Connection::new_session()?;
|
||||
fdo::DBusProxy::new(&connection)?
|
||||
.request_name(DBUS_NAME, fdo::RequestNameFlags::ReplaceExisting.into())?;
|
||||
let mut server = zbus::ObjectServer::new(&connection);
|
||||
|
||||
// Set up the anime data and run loop/thread
|
||||
if supported.anime_ctrl.0 {
|
||||
// Inner behind mutex required for thread safety
|
||||
let inner = Arc::new(Mutex::new(CtrlAnimeInner::new(
|
||||
anime,
|
||||
client,
|
||||
&ANIME_INNER_EARLY_RETURN,
|
||||
)?));
|
||||
// Need new client object for dbus control part
|
||||
let (client, _) = RogDbusClient::new().unwrap();
|
||||
let anime_control = CtrlAnime::new(
|
||||
anime_config,
|
||||
inner.clone(),
|
||||
client,
|
||||
&ANIME_INNER_EARLY_RETURN,
|
||||
)?;
|
||||
anime_control.add_to_server(&mut server);
|
||||
// Thread using inner
|
||||
let _anime_thread = thread::Builder::new()
|
||||
.name("Anime User".into())
|
||||
.spawn(move || loop {
|
||||
if let Ok(inner) = inner.try_lock() {
|
||||
inner.run().unwrap();
|
||||
}
|
||||
})?;
|
||||
}
|
||||
|
||||
if supported.keyboard_led.per_key_led_mode {}
|
||||
|
||||
loop {
|
||||
if let Err(err) = server.try_handle_next() {
|
||||
println!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
45
daemon-user/src/error.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::fmt;
|
||||
|
||||
use rog_anime::error::AnimeError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
Io(std::io::Error),
|
||||
ConfigLoadFail,
|
||||
ConfigLockFail,
|
||||
XdgVars,
|
||||
Anime(AnimeError),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
// This trait requires `fmt` with this exact signature.
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
Error::Io(err) => write!(f, "Failed to open: {}", err),
|
||||
Error::ConfigLoadFail => write!(f, "Failed to load user config"),
|
||||
Error::ConfigLockFail => write!(f, "Failed to lock user config"),
|
||||
Error::XdgVars => write!(f, "XDG environment vars appear unset"),
|
||||
Error::Anime(err) => write!(f, "Anime error: {}", err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
Error::Io(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<AnimeError> for Error {
|
||||
fn from(err: AnimeError) -> Self {
|
||||
Error::Anime(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for zbus::fdo::Error {
|
||||
fn from(err: Error) -> Self {
|
||||
zbus::fdo::Error::Failed(format!("Anime zbus error: {}", err))
|
||||
}
|
||||
}
|
||||
11
daemon-user/src/lib.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
pub mod user_config;
|
||||
|
||||
pub mod error;
|
||||
|
||||
pub mod ctrl_anime;
|
||||
|
||||
pub mod zbus_anime;
|
||||
|
||||
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
|
||||
|
||||
pub static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
203
daemon-user/src/user_config.rs
Normal file
@@ -0,0 +1,203 @@
|
||||
use std::{
|
||||
fs::{create_dir, OpenOptions},
|
||||
io::{Read, Write},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use rog_anime::{AnimTime, AnimeAction, Sequences, Vec2};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct UserAnimeConfig {
|
||||
pub name: String,
|
||||
pub anime: Vec<AnimeAction>,
|
||||
}
|
||||
|
||||
impl UserAnimeConfig {
|
||||
pub fn create_anime(&self) -> Result<Sequences, Error> {
|
||||
let mut seq = Sequences::new();
|
||||
|
||||
for (idx, action) in self.anime.iter().enumerate() {
|
||||
seq.insert(idx, action)?;
|
||||
}
|
||||
|
||||
Ok(seq)
|
||||
}
|
||||
|
||||
pub fn write(&self) -> Result<(), Error> {
|
||||
let mut path = if let Some(dir) = dirs::config_dir() {
|
||||
dir
|
||||
} else {
|
||||
return Err(Error::XdgVars);
|
||||
};
|
||||
|
||||
path.push("rog");
|
||||
if !path.exists() {
|
||||
create_dir(path.clone())?;
|
||||
}
|
||||
let name = self.name.clone();
|
||||
path.push(name + ".cfg");
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&path)?;
|
||||
|
||||
let json = serde_json::to_string_pretty(&self).unwrap();
|
||||
file.write_all(json.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_config(name: String) -> Result<UserAnimeConfig, Error> {
|
||||
let mut path = if let Some(dir) = dirs::config_dir() {
|
||||
dir
|
||||
} else {
|
||||
return Err(Error::XdgVars);
|
||||
};
|
||||
|
||||
path.push("rog");
|
||||
if !path.exists() {
|
||||
create_dir(path.clone())?;
|
||||
}
|
||||
|
||||
path.push(name.clone() + ".cfg");
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&path)?;
|
||||
|
||||
let mut buf = String::new();
|
||||
|
||||
if let Ok(read_len) = file.read_to_string(&mut buf) {
|
||||
if read_len == 0 {
|
||||
let default = UserAnimeConfig {
|
||||
name,
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_string_pretty(&default).unwrap();
|
||||
file.write_all(json.as_bytes())?;
|
||||
return Ok(default);
|
||||
} else if let Ok(data) = serde_json::from_str::<UserAnimeConfig>(&buf) {
|
||||
return Ok(data);
|
||||
}
|
||||
}
|
||||
Err(Error::ConfigLoadFail)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UserAnimeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: "default".to_string(),
|
||||
anime: vec![
|
||||
AnimeAction::AsusAnimation {
|
||||
file: "/usr/share/asusd/anime/asus/rog/Sunset.gif".into(),
|
||||
brightness: 0.5,
|
||||
time: AnimTime::Cycles(1),
|
||||
},
|
||||
AnimeAction::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-run.gif".into(),
|
||||
scale: 0.9,
|
||||
angle: 0.65,
|
||||
translation: Vec2::default(),
|
||||
brightness: 0.5,
|
||||
time: AnimTime::Time(Duration::from_secs(5)),
|
||||
},
|
||||
AnimeAction::Image {
|
||||
file: "/usr/share/asusd/anime/custom/rust.png".into(),
|
||||
scale: 1.0,
|
||||
angle: 0.0,
|
||||
translation: Vec2::default(),
|
||||
brightness: 0.6,
|
||||
},
|
||||
AnimeAction::Pause(Duration::from_secs(6)),
|
||||
AnimeAction::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: 0.5,
|
||||
time: AnimTime::Cycles(2),
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
pub struct UserConfig {
|
||||
/// Name of active anime config file in the user config directory
|
||||
pub active_anime: String,
|
||||
}
|
||||
|
||||
impl UserConfig {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
active_anime: "anime-default".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_config(&mut self) -> Result<(), Error> {
|
||||
let mut path = if let Some(dir) = dirs::config_dir() {
|
||||
dir
|
||||
} else {
|
||||
return Err(Error::XdgVars);
|
||||
};
|
||||
|
||||
path.push("rog");
|
||||
if !path.exists() {
|
||||
create_dir(path.clone())?;
|
||||
}
|
||||
|
||||
path.push("rog-user.cfg");
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&path)?;
|
||||
|
||||
let mut buf = String::new();
|
||||
|
||||
if let Ok(read_len) = file.read_to_string(&mut buf) {
|
||||
if read_len == 0 {
|
||||
let json = serde_json::to_string_pretty(&self).unwrap();
|
||||
file.write_all(json.as_bytes())?;
|
||||
} else if let Ok(data) = serde_json::from_str::<UserConfig>(&buf) {
|
||||
self.active_anime = data.active_anime;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn write(&self) -> Result<(), Error> {
|
||||
let mut path = if let Some(dir) = dirs::config_dir() {
|
||||
dir
|
||||
} else {
|
||||
return Err(Error::XdgVars);
|
||||
};
|
||||
|
||||
path.push("rog");
|
||||
if !path.exists() {
|
||||
create_dir(path.clone())?;
|
||||
}
|
||||
|
||||
path.push("rog-user.cfg");
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&path)?;
|
||||
|
||||
let json = serde_json::to_string_pretty(&self).unwrap();
|
||||
file.write_all(json.as_bytes())?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
69
daemon-user/src/zbus_anime.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! # DBus interface proxy for: `org.asuslinux.Daemon`
|
||||
//!
|
||||
//! This code was generated by `zbus-xmlgen` `1.0.0` from DBus introspection data.
|
||||
//! Source: `Interface '/org/asuslinux/Anime' from service 'org.asuslinux.Daemon' on session bus`.
|
||||
//!
|
||||
//! You may prefer to adapt it, instead of using it verbatim.
|
||||
//!
|
||||
//! More information can be found in the
|
||||
//! [Writing a client proxy](https://dbus.pages.freedesktop.org/zbus/client.html)
|
||||
//! section of the zbus documentation.
|
||||
//!
|
||||
//! This DBus object implements
|
||||
//! [standard DBus interfaces](https://dbus.freedesktop.org/doc/dbus-specification.html),
|
||||
//! (`org.freedesktop.DBus.*`) for which the following zbus proxies can be used:
|
||||
//!
|
||||
//! * [`zbus::fdo::PeerProxy`]
|
||||
//! * [`zbus::fdo::IntrospectableProxy`]
|
||||
//! * [`zbus::fdo::PropertiesProxy`]
|
||||
//!
|
||||
//! …consequently `zbus-xmlgen` did not generate code for the above interfaces.
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use zbus::dbus_proxy;
|
||||
|
||||
#[dbus_proxy(interface = "org.asuslinux.Daemon")]
|
||||
trait Daemon {
|
||||
/// InsertAsusGif method
|
||||
fn insert_asus_gif(
|
||||
&self,
|
||||
index: u32,
|
||||
file: &str,
|
||||
time: u32,
|
||||
count: u32,
|
||||
brightness: f64,
|
||||
) -> zbus::Result<String>;
|
||||
|
||||
/// InsertImage method
|
||||
fn insert_image(
|
||||
&self,
|
||||
index: u32,
|
||||
file: &str,
|
||||
scale: f64,
|
||||
angle: f64,
|
||||
xy: &(f64, f64),
|
||||
brightness: f64,
|
||||
) -> zbus::Result<String>;
|
||||
|
||||
/// InsertImageGif method
|
||||
fn insert_image_gif(
|
||||
&self,
|
||||
index: u32,
|
||||
file: &str,
|
||||
scale: f64,
|
||||
angle: f64,
|
||||
xy: &(f64, f64),
|
||||
time: u32,
|
||||
count: u32,
|
||||
brightness: f64,
|
||||
) -> zbus::Result<String>;
|
||||
|
||||
/// InsertPause method
|
||||
fn insert_pause(&self, index: u32, millis: u64) -> zbus::Result<String>;
|
||||
|
||||
/// RemoveItem method
|
||||
fn remove_item(&self, index: u32) -> zbus::Result<String>;
|
||||
|
||||
/// SetState method
|
||||
fn set_state(&self, on: bool) -> zbus::Result<()>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "asus-nb-ctrl"
|
||||
version = "1.0.2"
|
||||
name = "daemon"
|
||||
version = "3.6.0"
|
||||
license = "MPL-2.0"
|
||||
readme = "README.md"
|
||||
authors = ["Luke <luke@ljones.dev>"]
|
||||
@@ -13,37 +13,34 @@ edition = "2018"
|
||||
name = "daemon"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "asusctl"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "asusd"
|
||||
path = "src/daemon.rs"
|
||||
|
||||
[dependencies]
|
||||
asus-nb = { path = "../asus-nb" }
|
||||
rusb = "^0.6.0"
|
||||
udev = "^0.4.0"
|
||||
async-trait = "0.1.36"
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_aura = { path = "../rog-aura" }
|
||||
rog_types = { path = "../rog-types" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rusb = "^0.8"
|
||||
udev = "^0.6"
|
||||
|
||||
# cli and logging
|
||||
gumdrop = "^0.8.0"
|
||||
log = "^0.4.8"
|
||||
env_logger = "^0.7.1"
|
||||
log = "^0.4"
|
||||
env_logger = "^0.8"
|
||||
|
||||
# async
|
||||
dbus = { version = "^0.8.2", features = ["futures"] }
|
||||
dbus-tokio = "^0.5.1"
|
||||
tokio = { version = "^0.2.4", features = ["rt-threaded", "sync"] }
|
||||
zbus = "^1.9.1"
|
||||
zvariant = "^2.6"
|
||||
zvariant_derive = { version = "^2.6" }
|
||||
logind-zbus = "^0.7.1"
|
||||
|
||||
# serialisation
|
||||
serde = "^1.0"
|
||||
serde_derive = "^1.0"
|
||||
serde_json = "^1.0"
|
||||
toml = "0.4.6"
|
||||
toml = "^0.5"
|
||||
|
||||
# Device control
|
||||
sysfs-class = "^0.1.2" # used for backlight control and baord ID
|
||||
# cpu power management
|
||||
intel-pstate = "^0.2.1"
|
||||
rog_fan_curve = { version = "0.1", features = ["serde"] }
|
||||
169
daemon/src/config.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
use log::{error, info, warn};
|
||||
use rog_profiles::profiles::{FanLevel, Profile};
|
||||
use rog_types::gfx_vendors::GfxVendors;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
use crate::config_old::*;
|
||||
use crate::VERSION;
|
||||
|
||||
pub static CONFIG_PATH: &str = "/etc/asusd/asusd.conf";
|
||||
pub static AURA_CONFIG_PATH: &str = "/etc/asusd/asusd.conf";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Config {
|
||||
pub gfx_mode: GfxVendors,
|
||||
/// Only for informational purposes.
|
||||
#[serde(skip)]
|
||||
pub gfx_tmp_mode: Option<GfxVendors>,
|
||||
pub gfx_managed: bool,
|
||||
pub gfx_vfio_enable: bool,
|
||||
pub active_profile: String,
|
||||
pub toggle_profiles: Vec<String>,
|
||||
#[serde(skip)]
|
||||
pub curr_fan_mode: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub power_profiles: BTreeMap<String, Profile>,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
let mut pwr = BTreeMap::new();
|
||||
pwr.insert(
|
||||
"normal".into(),
|
||||
Profile::new(
|
||||
"normal".into(),
|
||||
0,
|
||||
100,
|
||||
true,
|
||||
FanLevel::Normal,
|
||||
"".to_string(),
|
||||
),
|
||||
);
|
||||
pwr.insert(
|
||||
"boost".into(),
|
||||
Profile::new(
|
||||
"boost".into(),
|
||||
0,
|
||||
100,
|
||||
true,
|
||||
FanLevel::Boost,
|
||||
"".to_string(),
|
||||
),
|
||||
);
|
||||
pwr.insert(
|
||||
"silent".into(),
|
||||
Profile::new(
|
||||
"silent".into(),
|
||||
0,
|
||||
100,
|
||||
true,
|
||||
FanLevel::Silent,
|
||||
"".to_string(),
|
||||
),
|
||||
);
|
||||
|
||||
Config {
|
||||
gfx_mode: GfxVendors::Hybrid,
|
||||
gfx_tmp_mode: None,
|
||||
gfx_managed: true,
|
||||
gfx_vfio_enable: false,
|
||||
active_profile: "normal".into(),
|
||||
toggle_profiles: vec!["normal".into(), "boost".into(), "silent".into()],
|
||||
curr_fan_mode: 0,
|
||||
bat_charge_limit: 100,
|
||||
power_profiles: pwr,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// `load` will attempt to read the config, and panic if the dir is missing
|
||||
pub fn load() -> Self {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&CONFIG_PATH)
|
||||
.unwrap_or_else(|_| panic!("The directory /etc/asusd/ is missing")); // okay to cause panic here
|
||||
let mut buf = String::new();
|
||||
if let Ok(read_len) = file.read_to_string(&mut buf) {
|
||||
if read_len == 0 {
|
||||
return Config::create_default(&mut file);
|
||||
} else {
|
||||
if let Ok(data) = serde_json::from_str(&buf) {
|
||||
return data;
|
||||
} else if let Ok(data) = serde_json::from_str::<ConfigV352>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
} else if let Ok(data) = serde_json::from_str::<ConfigV341>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
} else if let Ok(data) = serde_json::from_str::<ConfigV324>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
} else if let Ok(data) = serde_json::from_str::<ConfigV317>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
}
|
||||
warn!("Could not deserialise {}", CONFIG_PATH);
|
||||
panic!("Please remove {} then restart asusd", CONFIG_PATH);
|
||||
}
|
||||
}
|
||||
Config::create_default(&mut file)
|
||||
}
|
||||
|
||||
fn create_default(file: &mut File) -> Self {
|
||||
let config = Config::default();
|
||||
// Should be okay to unwrap this as is since it is a Default
|
||||
let json = serde_json::to_string_pretty(&config).unwrap();
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|_| panic!("Could not write {}", CONFIG_PATH));
|
||||
config
|
||||
}
|
||||
|
||||
pub fn read(&mut self) {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&CONFIG_PATH)
|
||||
.unwrap_or_else(|err| panic!("Error reading {}: {}", CONFIG_PATH, err));
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("File is empty {}", CONFIG_PATH);
|
||||
} else {
|
||||
let x: Config = serde_json::from_str(&buf)
|
||||
.unwrap_or_else(|_| panic!("Could not deserialise {}", CONFIG_PATH));
|
||||
*self = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_new() -> Result<Config, Box<dyn std::error::Error>> {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&CONFIG_PATH)
|
||||
.unwrap_or_else(|err| panic!("Error reading {}: {}", CONFIG_PATH, err));
|
||||
let mut buf = String::new();
|
||||
file.read_to_string(&mut buf)?;
|
||||
let x: Config = serde_json::from_str(&buf)?;
|
||||
Ok(x)
|
||||
}
|
||||
|
||||
pub fn write(&self) {
|
||||
let mut file = File::create(CONFIG_PATH).expect("Couldn't overwrite config");
|
||||
let json = serde_json::to_string_pretty(self).expect("Parse config to JSON failed");
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write config: {}", err));
|
||||
}
|
||||
}
|
||||
237
daemon/src/config_anime.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
use crate::VERSION;
|
||||
use log::{error, info, warn};
|
||||
use rog_anime::{error::AnimeError, ActionData, AnimTime, AnimeAction, Vec2};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
use std::time::Duration;
|
||||
|
||||
pub static ANIME_CONFIG_PATH: &str = "/etc/asusd/anime.conf";
|
||||
pub static ANIME_CACHE_PATH: &str = "/etc/asusd/anime-cache.conf";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfigV341 {
|
||||
pub system: Option<AnimeAction>,
|
||||
pub boot: Option<AnimeAction>,
|
||||
pub suspend: Option<AnimeAction>,
|
||||
pub shutdown: Option<AnimeAction>,
|
||||
}
|
||||
|
||||
impl AnimeConfigV341 {
|
||||
pub(crate) fn into_current(self) -> AnimeConfig {
|
||||
AnimeConfig {
|
||||
system: if let Some(ani) = self.system {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
boot: if let Some(ani) = self.boot {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
wake: if let Some(ani) = self.suspend {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
shutdown: if let Some(ani) = self.shutdown {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfigV352 {
|
||||
pub system: Vec<AnimeAction>,
|
||||
pub boot: Vec<AnimeAction>,
|
||||
pub wake: Vec<AnimeAction>,
|
||||
pub shutdown: Vec<AnimeAction>,
|
||||
pub brightness: f32,
|
||||
}
|
||||
|
||||
impl AnimeConfigV352 {
|
||||
pub(crate) fn into_current(self) -> AnimeConfig {
|
||||
AnimeConfig {
|
||||
system: self.system,
|
||||
boot: self.boot,
|
||||
wake: self.wake,
|
||||
shutdown: self.shutdown,
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Default)]
|
||||
pub struct AnimeConfigCached {
|
||||
pub system: Vec<ActionData>,
|
||||
pub boot: Vec<ActionData>,
|
||||
pub wake: Vec<ActionData>,
|
||||
pub shutdown: Vec<ActionData>,
|
||||
}
|
||||
|
||||
impl AnimeConfigCached {
|
||||
pub fn init_from_config(&mut self, config: &AnimeConfig) -> Result<(), AnimeError> {
|
||||
let mut sys = Vec::with_capacity(config.system.len());
|
||||
for ani in config.system.iter() {
|
||||
sys.push(ActionData::from_anime_action(ani)?);
|
||||
}
|
||||
self.system = sys;
|
||||
|
||||
let mut boot = Vec::with_capacity(config.boot.len());
|
||||
for ani in config.boot.iter() {
|
||||
boot.push(ActionData::from_anime_action(ani)?);
|
||||
}
|
||||
self.boot = boot;
|
||||
|
||||
let mut wake = Vec::with_capacity(config.wake.len());
|
||||
for ani in config.wake.iter() {
|
||||
wake.push(ActionData::from_anime_action(ani)?);
|
||||
}
|
||||
self.wake = wake;
|
||||
|
||||
let mut shutdown = Vec::with_capacity(config.shutdown.len());
|
||||
for ani in config.shutdown.iter() {
|
||||
shutdown.push(ActionData::from_anime_action(ani)?);
|
||||
}
|
||||
self.shutdown = shutdown;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Config for base system actions for the anime display
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfig {
|
||||
pub system: Vec<AnimeAction>,
|
||||
pub boot: Vec<AnimeAction>,
|
||||
pub wake: Vec<AnimeAction>,
|
||||
pub shutdown: Vec<AnimeAction>,
|
||||
pub brightness: f32,
|
||||
pub awake_enabled: bool,
|
||||
pub boot_anim_enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for AnimeConfig {
|
||||
fn default() -> Self {
|
||||
AnimeConfig {
|
||||
system: Vec::new(),
|
||||
boot: Vec::new(),
|
||||
wake: Vec::new(),
|
||||
shutdown: Vec::new(),
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimeConfig {
|
||||
/// `load` will attempt to read the config, and panic if the dir is missing
|
||||
pub fn load() -> Self {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&ANIME_CONFIG_PATH)
|
||||
.unwrap_or_else(|_| {
|
||||
panic!(
|
||||
"The file {} or directory /etc/asusd/ is missing",
|
||||
ANIME_CONFIG_PATH
|
||||
)
|
||||
}); // okay to cause panic here
|
||||
let mut buf = String::new();
|
||||
if let Ok(read_len) = file.read_to_string(&mut buf) {
|
||||
if read_len == 0 {
|
||||
return AnimeConfig::create_default(&mut file);
|
||||
} else {
|
||||
if let Ok(data) = serde_json::from_str(&buf) {
|
||||
return data;
|
||||
} else if let Ok(data) = serde_json::from_str::<AnimeConfigV341>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
} else if let Ok(data) = serde_json::from_str::<AnimeConfigV352>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated config version to: {}", VERSION);
|
||||
return config;
|
||||
}
|
||||
warn!("Could not deserialise {}", ANIME_CONFIG_PATH);
|
||||
panic!("Please remove {} then restart asusd", ANIME_CONFIG_PATH);
|
||||
}
|
||||
}
|
||||
AnimeConfig::create_default(&mut file)
|
||||
}
|
||||
|
||||
fn create_default(file: &mut File) -> Self {
|
||||
// create a default config here
|
||||
let config = AnimeConfig {
|
||||
system: vec![],
|
||||
boot: vec![AnimeAction::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-run.gif".into(),
|
||||
scale: 0.9,
|
||||
angle: 0.65,
|
||||
translation: Vec2::default(),
|
||||
brightness: 1.0,
|
||||
time: AnimTime::Time(Duration::from_secs(5)),
|
||||
}],
|
||||
wake: vec![AnimeAction::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-run.gif".into(),
|
||||
scale: 0.9,
|
||||
angle: 0.65,
|
||||
translation: Vec2::default(),
|
||||
brightness: 1.0,
|
||||
time: AnimTime::Time(Duration::from_secs(5)),
|
||||
}],
|
||||
shutdown: vec![AnimeAction::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,
|
||||
}],
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
};
|
||||
// Should be okay to unwrap this as is since it is a Default
|
||||
let json = serde_json::to_string_pretty(&config).unwrap();
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|_| panic!("Could not write {}", ANIME_CONFIG_PATH));
|
||||
config
|
||||
}
|
||||
|
||||
pub fn read(&mut self) {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&ANIME_CONFIG_PATH)
|
||||
.unwrap_or_else(|err| panic!("Error reading {}: {}", ANIME_CONFIG_PATH, err));
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("File is empty {}", ANIME_CONFIG_PATH);
|
||||
} else {
|
||||
let x: AnimeConfig = serde_json::from_str(&buf)
|
||||
.unwrap_or_else(|_| panic!("Could not deserialise {}", ANIME_CONFIG_PATH));
|
||||
*self = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self) {
|
||||
let mut file = File::create(ANIME_CONFIG_PATH).expect("Couldn't overwrite config");
|
||||
let json = serde_json::to_string_pretty(self).expect("Parse config to JSON failed");
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write config: {}", err));
|
||||
}
|
||||
}
|
||||
267
daemon/src/config_aura.rs
Normal file
@@ -0,0 +1,267 @@
|
||||
use crate::laptops::LaptopLedData;
|
||||
use log::{error, info, warn};
|
||||
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, LedBrightness};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
|
||||
pub static AURA_CONFIG_PATH: &str = "/etc/asusd/aura.conf";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AuraConfigV320 {
|
||||
pub brightness: u32,
|
||||
pub current_mode: AuraModeNum,
|
||||
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
|
||||
pub multizone: Option<AuraMultiZone>,
|
||||
}
|
||||
|
||||
impl AuraConfigV320 {
|
||||
pub(crate) fn into_current(self) -> AuraConfig {
|
||||
AuraConfig {
|
||||
brightness: <LedBrightness>::from(self.brightness),
|
||||
current_mode: self.current_mode,
|
||||
builtins: self.builtins,
|
||||
multizone: self.multizone,
|
||||
awake_enabled: true,
|
||||
sleep_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AuraConfigV352 {
|
||||
pub brightness: LedBrightness,
|
||||
pub current_mode: AuraModeNum,
|
||||
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
|
||||
pub multizone: Option<AuraMultiZone>,
|
||||
}
|
||||
|
||||
impl AuraConfigV352 {
|
||||
pub(crate) fn into_current(self) -> AuraConfig {
|
||||
AuraConfig {
|
||||
brightness: self.brightness,
|
||||
current_mode: self.current_mode,
|
||||
builtins: self.builtins,
|
||||
multizone: self.multizone,
|
||||
awake_enabled: true,
|
||||
sleep_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AuraConfig {
|
||||
pub brightness: LedBrightness,
|
||||
pub current_mode: AuraModeNum,
|
||||
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
|
||||
pub multizone: Option<AuraMultiZone>,
|
||||
pub awake_enabled: bool,
|
||||
pub sleep_anim_enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for AuraConfig {
|
||||
fn default() -> Self {
|
||||
AuraConfig {
|
||||
brightness: LedBrightness::Med,
|
||||
current_mode: AuraModeNum::Static,
|
||||
builtins: BTreeMap::new(),
|
||||
multizone: None,
|
||||
awake_enabled: true,
|
||||
sleep_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AuraConfig {
|
||||
/// `load` will attempt to read the config, and panic if the dir is missing
|
||||
pub fn load(supported_led_modes: &LaptopLedData) -> Self {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.open(&AURA_CONFIG_PATH)
|
||||
.unwrap_or_else(|_| {
|
||||
panic!(
|
||||
"The file {} or directory /etc/asusd/ is missing",
|
||||
AURA_CONFIG_PATH
|
||||
)
|
||||
}); // okay to cause panic here
|
||||
let mut buf = String::new();
|
||||
if let Ok(read_len) = file.read_to_string(&mut buf) {
|
||||
if read_len == 0 {
|
||||
return AuraConfig::create_default(&mut file, &supported_led_modes);
|
||||
} else {
|
||||
if let Ok(data) = serde_json::from_str(&buf) {
|
||||
return data;
|
||||
} else if let Ok(data) = serde_json::from_str::<AuraConfigV320>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated AuraConfig version");
|
||||
return config;
|
||||
} else if let Ok(data) = serde_json::from_str::<AuraConfigV352>(&buf) {
|
||||
let config = data.into_current();
|
||||
config.write();
|
||||
info!("Updated AuraConfig version");
|
||||
return config;
|
||||
}
|
||||
warn!("Could not deserialise {}", AURA_CONFIG_PATH);
|
||||
panic!("Please remove {} then restart asusd", AURA_CONFIG_PATH);
|
||||
}
|
||||
}
|
||||
AuraConfig::create_default(&mut file, &supported_led_modes)
|
||||
}
|
||||
|
||||
fn create_default(file: &mut File, support_data: &LaptopLedData) -> Self {
|
||||
// create a default config here
|
||||
let mut config = AuraConfig::default();
|
||||
|
||||
for n in &support_data.standard {
|
||||
config
|
||||
.builtins
|
||||
.insert(*n, AuraEffect::default_with_mode(*n));
|
||||
}
|
||||
|
||||
// Should be okay to unwrap this as is since it is a Default
|
||||
let json = serde_json::to_string(&config).unwrap();
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|_| panic!("Could not write {}", AURA_CONFIG_PATH));
|
||||
config
|
||||
}
|
||||
|
||||
pub fn read(&mut self) {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&AURA_CONFIG_PATH)
|
||||
.unwrap_or_else(|err| panic!("Error reading {}: {}", AURA_CONFIG_PATH, err));
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("File is empty {}", AURA_CONFIG_PATH);
|
||||
} else {
|
||||
let x: AuraConfig = serde_json::from_str(&buf)
|
||||
.unwrap_or_else(|_| panic!("Could not deserialise {}", AURA_CONFIG_PATH));
|
||||
*self = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self) {
|
||||
let mut file = File::create(AURA_CONFIG_PATH).expect("Couldn't overwrite config");
|
||||
let json = serde_json::to_string_pretty(self).expect("Parse config to JSON failed");
|
||||
file.write_all(json.as_bytes())
|
||||
.unwrap_or_else(|err| error!("Could not write config: {}", err));
|
||||
}
|
||||
|
||||
/// Multipurpose, will accecpt AuraEffect with zones and put in the correct store
|
||||
pub fn set_builtin(&mut self, effect: AuraEffect) {
|
||||
match effect.zone() {
|
||||
AuraZone::None => {
|
||||
self.builtins.insert(*effect.mode(), effect);
|
||||
}
|
||||
_ => {
|
||||
if let Some(multi) = self.multizone.as_mut() {
|
||||
multi.set(effect)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_multizone(&self, aura_type: AuraModeNum) -> Option<&[AuraEffect; 4]> {
|
||||
if let Some(multi) = &self.multizone {
|
||||
if aura_type == AuraModeNum::Static {
|
||||
return Some(multi.static_());
|
||||
} else if aura_type == AuraModeNum::Breathe {
|
||||
return Some(multi.breathe());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AuraMultiZone {
|
||||
static_: [AuraEffect; 4],
|
||||
breathe: [AuraEffect; 4],
|
||||
}
|
||||
|
||||
impl AuraMultiZone {
|
||||
pub fn set(&mut self, effect: AuraEffect) {
|
||||
if effect.mode == AuraModeNum::Static {
|
||||
match effect.zone {
|
||||
AuraZone::None => {}
|
||||
AuraZone::One => self.static_[0] = effect,
|
||||
AuraZone::Two => self.static_[1] = effect,
|
||||
AuraZone::Three => self.static_[2] = effect,
|
||||
AuraZone::Four => self.static_[3] = effect,
|
||||
}
|
||||
} else if effect.mode == AuraModeNum::Breathe {
|
||||
match effect.zone {
|
||||
AuraZone::None => {}
|
||||
AuraZone::One => self.breathe[0] = effect,
|
||||
AuraZone::Two => self.breathe[1] = effect,
|
||||
AuraZone::Three => self.breathe[2] = effect,
|
||||
AuraZone::Four => self.breathe[3] = effect,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn static_(&self) -> &[AuraEffect; 4] {
|
||||
&self.static_
|
||||
}
|
||||
|
||||
pub fn breathe(&self) -> &[AuraEffect; 4] {
|
||||
&self.breathe
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AuraMultiZone {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
static_: [
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::One,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::Two,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::Three,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::Four,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
breathe: [
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Breathe,
|
||||
zone: AuraZone::One,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Breathe,
|
||||
zone: AuraZone::Two,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Breathe,
|
||||
zone: AuraZone::Three,
|
||||
..Default::default()
|
||||
},
|
||||
AuraEffect {
|
||||
mode: AuraModeNum::Breathe,
|
||||
zone: AuraZone::Four,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
160
daemon/src/config_old.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use rog_fan_curve::Curve;
|
||||
use rog_profiles::profiles::Profile;
|
||||
use rog_types::gfx_vendors::GfxVendors;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// for parsing old v3.1.7 config
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct ConfigV317 {
|
||||
pub gfx_mode: GfxVendors,
|
||||
pub gfx_managed: bool,
|
||||
pub active_profile: String,
|
||||
pub toggle_profiles: Vec<String>,
|
||||
#[serde(skip)]
|
||||
pub curr_fan_mode: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub kbd_led_brightness: u8,
|
||||
pub kbd_backlight_mode: u8,
|
||||
#[serde(skip)]
|
||||
pub kbd_backlight_modes: Option<bool>,
|
||||
pub power_profiles: BTreeMap<String, ProfileV317>,
|
||||
}
|
||||
|
||||
impl ConfigV317 {
|
||||
pub(crate) fn into_current(self) -> Config {
|
||||
Config {
|
||||
gfx_mode: GfxVendors::Hybrid,
|
||||
gfx_tmp_mode: None,
|
||||
gfx_managed: self.gfx_managed,
|
||||
gfx_vfio_enable: false,
|
||||
active_profile: self.active_profile,
|
||||
toggle_profiles: self.toggle_profiles,
|
||||
curr_fan_mode: self.curr_fan_mode,
|
||||
bat_charge_limit: self.bat_charge_limit,
|
||||
power_profiles: ProfileV317::transform_map(self.power_profiles),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct ConfigV324 {
|
||||
pub gfx_mode: GfxVendors,
|
||||
pub gfx_managed: bool,
|
||||
pub active_profile: String,
|
||||
pub toggle_profiles: Vec<String>,
|
||||
#[serde(skip)]
|
||||
pub curr_fan_mode: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub power_profiles: BTreeMap<String, ProfileV317>,
|
||||
}
|
||||
|
||||
impl ConfigV324 {
|
||||
pub(crate) fn into_current(self) -> Config {
|
||||
Config {
|
||||
gfx_mode: GfxVendors::Hybrid,
|
||||
gfx_tmp_mode: None,
|
||||
gfx_managed: self.gfx_managed,
|
||||
gfx_vfio_enable: false,
|
||||
active_profile: self.active_profile,
|
||||
toggle_profiles: self.toggle_profiles,
|
||||
curr_fan_mode: self.curr_fan_mode,
|
||||
bat_charge_limit: self.bat_charge_limit,
|
||||
power_profiles: ProfileV317::transform_map(self.power_profiles),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct ConfigV341 {
|
||||
pub gfx_mode: GfxVendors,
|
||||
pub gfx_managed: bool,
|
||||
pub gfx_vfio_enable: bool,
|
||||
pub active_profile: String,
|
||||
pub toggle_profiles: Vec<String>,
|
||||
#[serde(skip)]
|
||||
pub curr_fan_mode: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub power_profiles: BTreeMap<String, ProfileV317>,
|
||||
}
|
||||
|
||||
impl ConfigV341 {
|
||||
pub(crate) fn into_current(self) -> Config {
|
||||
Config {
|
||||
gfx_mode: GfxVendors::Hybrid,
|
||||
gfx_tmp_mode: None,
|
||||
gfx_managed: self.gfx_managed,
|
||||
gfx_vfio_enable: false,
|
||||
active_profile: self.active_profile,
|
||||
toggle_profiles: self.toggle_profiles,
|
||||
curr_fan_mode: self.curr_fan_mode,
|
||||
bat_charge_limit: self.bat_charge_limit,
|
||||
power_profiles: ProfileV317::transform_map(self.power_profiles),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct ConfigV352 {
|
||||
pub gfx_mode: GfxVendors,
|
||||
pub gfx_last_mode: GfxVendors,
|
||||
pub gfx_managed: bool,
|
||||
pub gfx_vfio_enable: bool,
|
||||
pub gfx_save_compute_vfio: bool,
|
||||
pub active_profile: String,
|
||||
pub toggle_profiles: Vec<String>,
|
||||
#[serde(skip)]
|
||||
pub curr_fan_mode: u8,
|
||||
pub bat_charge_limit: u8,
|
||||
pub power_profiles: BTreeMap<String, ProfileV317>,
|
||||
}
|
||||
|
||||
impl ConfigV352 {
|
||||
pub(crate) fn into_current(self) -> Config {
|
||||
Config {
|
||||
gfx_mode: GfxVendors::Hybrid,
|
||||
gfx_tmp_mode: None,
|
||||
gfx_managed: self.gfx_managed,
|
||||
gfx_vfio_enable: false,
|
||||
active_profile: self.active_profile,
|
||||
toggle_profiles: self.toggle_profiles,
|
||||
curr_fan_mode: self.curr_fan_mode,
|
||||
bat_charge_limit: self.bat_charge_limit,
|
||||
power_profiles: ProfileV317::transform_map(self.power_profiles),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ProfileV317 {
|
||||
pub min_percentage: u8,
|
||||
pub max_percentage: u8,
|
||||
pub turbo: bool,
|
||||
pub fan_preset: u8,
|
||||
pub fan_curve: Option<Curve>,
|
||||
}
|
||||
|
||||
impl ProfileV317 {
|
||||
fn into_current(self, name: String) -> Profile {
|
||||
Profile {
|
||||
name,
|
||||
min_percentage: self.min_percentage,
|
||||
max_percentage: self.max_percentage,
|
||||
turbo: self.turbo,
|
||||
fan_preset: self.fan_preset.into(),
|
||||
fan_curve: self
|
||||
.fan_curve
|
||||
.map_or_else(|| "".to_string(), |c| c.as_config_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_map(map: BTreeMap<String, ProfileV317>) -> BTreeMap<String, Profile> {
|
||||
let mut new_map = BTreeMap::new();
|
||||
map.iter().for_each(|(k, v)| {
|
||||
new_map.insert(k.to_string(), v.clone().into_current(k.to_string()));
|
||||
});
|
||||
new_map
|
||||
}
|
||||
}
|
||||
467
daemon/src/ctrl_anime.rs
Normal file
@@ -0,0 +1,467 @@
|
||||
use log::{error, info, warn};
|
||||
use logind_zbus::ManagerProxy;
|
||||
use rog_anime::{
|
||||
usb::{
|
||||
pkt_for_apply, pkt_for_flush, pkt_for_set_boot, pkt_for_set_on, pkts_for_init, PROD_ID,
|
||||
VENDOR_ID,
|
||||
},
|
||||
ActionData, AnimTime, AnimeDataBuffer, AnimePacketType, AnimePowerStates, ANIME_DATA_LEN,
|
||||
};
|
||||
use rog_types::supported::AnimeSupportedFunctions;
|
||||
use rusb::{Device, DeviceHandle};
|
||||
use std::{
|
||||
error::Error,
|
||||
sync::{Arc, Mutex},
|
||||
thread::sleep,
|
||||
time::Instant,
|
||||
};
|
||||
use std::{
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use zbus::{dbus_interface, Connection};
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
use crate::{
|
||||
config_anime::{AnimeConfig, AnimeConfigCached},
|
||||
error::RogError,
|
||||
GetSupported,
|
||||
};
|
||||
|
||||
impl GetSupported for CtrlAnime {
|
||||
type A = AnimeSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
AnimeSupportedFunctions(CtrlAnime::get_device(VENDOR_ID, PROD_ID).is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnime {
|
||||
handle: DeviceHandle<rusb::GlobalContext>,
|
||||
cache: AnimeConfigCached,
|
||||
config: AnimeConfig,
|
||||
// set to force thread to exit
|
||||
thread_exit: Arc<AtomicBool>,
|
||||
// Set to false when the thread exits
|
||||
thread_running: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl CtrlAnime {
|
||||
#[inline]
|
||||
pub fn new(config: AnimeConfig) -> Result<CtrlAnime, Box<dyn Error>> {
|
||||
// We don't expect this ID to ever change
|
||||
let device = CtrlAnime::get_device(0x0b05, 0x193b)?;
|
||||
|
||||
let mut device = device.open()?;
|
||||
device.reset()?;
|
||||
|
||||
device.set_auto_detach_kernel_driver(true).map_err(|err| {
|
||||
error!("Auto-detach kernel driver failed: {}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
device.claim_interface(0).map_err(|err| {
|
||||
error!("Could not claim device interface: {}", err);
|
||||
err
|
||||
})?;
|
||||
|
||||
info!("Device has an AniMe Matrix display");
|
||||
let mut cache = AnimeConfigCached::default();
|
||||
cache.init_from_config(&config)?;
|
||||
|
||||
let ctrl = CtrlAnime {
|
||||
handle: device,
|
||||
cache,
|
||||
config,
|
||||
thread_exit: Arc::new(AtomicBool::new(false)),
|
||||
thread_running: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
ctrl.do_initialization();
|
||||
|
||||
Ok(ctrl)
|
||||
}
|
||||
|
||||
fn get_device(vendor: u16, product: u16) -> Result<Device<rusb::GlobalContext>, rusb::Error> {
|
||||
for device in rusb::devices()?.iter() {
|
||||
let device_desc = device.device_descriptor()?;
|
||||
if device_desc.vendor_id() == vendor && device_desc.product_id() == product {
|
||||
return Ok(device);
|
||||
}
|
||||
}
|
||||
Err(rusb::Error::NoDevice)
|
||||
}
|
||||
|
||||
/// Start an action thread. This is classed as a singleton and there should be only
|
||||
/// one running - so the thread uses atomics to signal run/exit.
|
||||
///
|
||||
/// Because this also writes to the usb device, other write tries (display only) *must*
|
||||
/// get the mutex lock and set the thread_exit atomic.
|
||||
fn run_thread(inner: Arc<Mutex<CtrlAnime>>, actions: Vec<ActionData>, mut once: bool) {
|
||||
if actions.is_empty() {
|
||||
warn!("AniMe system actions was empty");
|
||||
return;
|
||||
}
|
||||
// Loop rules:
|
||||
// - Lock the mutex **only when required**. That is, the lock must be held for the shortest duration possible.
|
||||
// - An AtomicBool used for thread exit should be checked in every loop, including nested
|
||||
|
||||
// The only reason for this outer thread is to prevent blocking while waiting for the
|
||||
// next spawned thread to exit
|
||||
std::thread::Builder::new()
|
||||
.name("AniMe system thread start".into())
|
||||
.spawn(move || {
|
||||
info!("AniMe system thread started");
|
||||
// Getting copies of these Atomics is done *in* the thread to ensure
|
||||
// we don't block other threads/main
|
||||
let thread_exit;
|
||||
let thread_running;
|
||||
// First two loops are to ensure we *do* aquire a lock on the mutex
|
||||
// The reason the loop is required is because the USB writes can block
|
||||
// for up to 10ms. We can't fail to get the atomics.
|
||||
loop {
|
||||
if let Ok(lock) = inner.try_lock() {
|
||||
thread_exit = lock.thread_exit.clone();
|
||||
thread_running = lock.thread_running.clone();
|
||||
// Make any running loop exit first
|
||||
thread_exit.store(true, Ordering::SeqCst);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
// wait for other threads to set not running so we know they exited
|
||||
if !thread_running.load(Ordering::SeqCst) {
|
||||
thread_exit.store(false, Ordering::SeqCst);
|
||||
info!("AniMe forced a thread to exit");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
'main: loop {
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
for action in actions.iter() {
|
||||
match action {
|
||||
ActionData::Animation(frames) => {
|
||||
let mut count = 0;
|
||||
let start = Instant::now();
|
||||
'animation: loop {
|
||||
for frame in frames.frames() {
|
||||
if let Ok(lock) = inner.try_lock() {
|
||||
lock.write_data_buffer(frame.frame().clone());
|
||||
}
|
||||
if let AnimTime::Time(time) = frames.duration() {
|
||||
if Instant::now().duration_since(start) > time {
|
||||
break 'animation;
|
||||
}
|
||||
}
|
||||
sleep(frame.delay());
|
||||
// Need to check for early exit condition here or it might run
|
||||
// until end of gif or time
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
if let AnimTime::Cycles(times) = frames.duration() {
|
||||
count += 1;
|
||||
if count >= times {
|
||||
break 'animation;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ActionData::Image(image) => {
|
||||
once = false;
|
||||
if let Ok(lock) = inner.try_lock() {
|
||||
lock.write_data_buffer(image.as_ref().clone())
|
||||
}
|
||||
}
|
||||
ActionData::Pause(duration) => sleep(*duration),
|
||||
ActionData::AudioEq => {}
|
||||
ActionData::SystemInfo => {}
|
||||
ActionData::TimeDate => {}
|
||||
ActionData::Matrix => {}
|
||||
}
|
||||
}
|
||||
if once || actions.is_empty() {
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
// Clear the display on exit
|
||||
if let Ok(lock) = inner.try_lock() {
|
||||
let data = AnimeDataBuffer::from_vec([0u8; ANIME_DATA_LEN].to_vec());
|
||||
lock.write_data_buffer(data);
|
||||
}
|
||||
// Loop ended, set the atmonics
|
||||
thread_exit.store(false, Ordering::SeqCst);
|
||||
thread_running.store(false, Ordering::SeqCst);
|
||||
info!("AniMe system thread exited");
|
||||
})
|
||||
.map(|err| info!("AniMe system thread: {:?}", err))
|
||||
.ok();
|
||||
}
|
||||
|
||||
fn write_bytes(&self, message: &[u8]) {
|
||||
match self.handle.write_control(
|
||||
0x21, // request_type
|
||||
0x09, // request
|
||||
0x35e, // value
|
||||
0x00, // index
|
||||
message,
|
||||
Duration::from_millis(200),
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(err) => match err {
|
||||
rusb::Error::Timeout => {}
|
||||
_ => error!("Failed to write to led interrupt: {}", err),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Write only a data packet. This will modify the leds brightness using the
|
||||
/// global brightness set in config.
|
||||
fn write_data_buffer(&self, mut buffer: AnimeDataBuffer) {
|
||||
for led in buffer.get_mut()[7..].iter_mut() {
|
||||
let mut bright = *led as f32 * self.config.brightness;
|
||||
if bright > 254.0 {
|
||||
bright = 254.0;
|
||||
}
|
||||
*led = bright as u8;
|
||||
}
|
||||
let data = AnimePacketType::from(buffer);
|
||||
for row in data.iter() {
|
||||
self.write_bytes(row);
|
||||
}
|
||||
self.write_bytes(&pkt_for_flush());
|
||||
}
|
||||
|
||||
fn do_initialization(&self) {
|
||||
let pkts = pkts_for_init();
|
||||
self.write_bytes(&pkts[0]);
|
||||
self.write_bytes(&pkts[1]);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnimeTask<'a> {
|
||||
inner: Arc<Mutex<CtrlAnime>>,
|
||||
_c: Connection,
|
||||
manager: ManagerProxy<'a>,
|
||||
}
|
||||
|
||||
impl<'a> CtrlAnimeTask<'a> {
|
||||
pub fn new(inner: Arc<Mutex<CtrlAnime>>) -> Self {
|
||||
let connection = Connection::new_system().unwrap();
|
||||
|
||||
let manager = ManagerProxy::new(&connection).unwrap();
|
||||
|
||||
let c1 = inner.clone();
|
||||
// Run this action when the system starts shutting down
|
||||
manager
|
||||
.connect_prepare_for_shutdown(move |shutdown| {
|
||||
if shutdown {
|
||||
'outer: loop {
|
||||
if let Ok(lock) = c1.try_lock() {
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
CtrlAnime::run_thread(c1.clone(), lock.cache.shutdown.clone(), false);
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| {
|
||||
warn!("CtrlAnimeTask: new() {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
|
||||
let c1 = inner.clone();
|
||||
// Run this action when the system wakes up from sleep
|
||||
manager
|
||||
.connect_prepare_for_sleep(move |sleep| {
|
||||
if !sleep {
|
||||
// wait a fraction for things to wake up properly
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
'outer: loop {
|
||||
if let Ok(lock) = c1.try_lock() {
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
CtrlAnime::run_thread(c1.clone(), lock.cache.wake.clone(), true);
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.map_err(|err| {
|
||||
warn!("CtrlAnimeTask: new() {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
|
||||
Self {
|
||||
inner,
|
||||
_c: connection,
|
||||
manager,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> crate::CtrlTask for CtrlAnimeTask<'a> {
|
||||
fn do_task(&self) -> Result<(), RogError> {
|
||||
if let Ok(mut lock) = self.inner.try_lock() {
|
||||
// Refresh the config and cache incase the user has edited it
|
||||
let config = AnimeConfig::load();
|
||||
lock.cache
|
||||
.init_from_config(&config)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlAnimeTask: do_task {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
// Check for signals on each task iteration, this will run the callbacks
|
||||
// if any signal is recieved
|
||||
self.manager.next_signal()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnimeReloader(pub Arc<Mutex<CtrlAnime>>);
|
||||
|
||||
impl crate::Reloadable for CtrlAnimeReloader {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Ok(lock) = self.0.try_lock() {
|
||||
lock.write_bytes(&pkt_for_set_on(lock.config.awake_enabled));
|
||||
lock.write_bytes(&pkt_for_apply());
|
||||
lock.write_bytes(&pkt_for_set_boot(lock.config.boot_anim_enabled));
|
||||
lock.write_bytes(&pkt_for_apply());
|
||||
|
||||
let action = lock.cache.boot.clone();
|
||||
CtrlAnime::run_thread(self.0.clone(), action, true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnimeZbus(pub Arc<Mutex<CtrlAnime>>);
|
||||
|
||||
/// The struct with the main dbus methods requires this trait
|
||||
impl crate::ZbusAdd for CtrlAnimeZbus {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Anime"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlAnimeDisplay: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
// 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")]
|
||||
impl CtrlAnimeZbus {
|
||||
/// Writes a data stream of length. Will force system thread to exit until it is restarted
|
||||
fn write(&self, input: AnimeDataBuffer) {
|
||||
'outer: loop {
|
||||
if let Ok(lock) = self.0.try_lock() {
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
lock.write_data_buffer(input);
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_brightness(&self, bright: f32) {
|
||||
'outer: loop {
|
||||
if let Ok(mut lock) = self.0.try_lock() {
|
||||
let mut bright = bright;
|
||||
if bright < 0.0 {
|
||||
bright = 0.0
|
||||
} else if bright > 254.0 {
|
||||
bright = 254.0;
|
||||
}
|
||||
lock.config.brightness = bright;
|
||||
lock.config.write();
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_on_off(&self, status: bool) {
|
||||
'outer: loop {
|
||||
if let Ok(mut lock) = self.0.try_lock() {
|
||||
lock.write_bytes(&pkt_for_set_on(status));
|
||||
lock.config.awake_enabled = status;
|
||||
lock.config.write();
|
||||
|
||||
let states = AnimePowerStates {
|
||||
enabled: lock.config.awake_enabled,
|
||||
boot_anim_enabled: lock.config.boot_anim_enabled,
|
||||
};
|
||||
self.notify_power_states(&states)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_boot_on_off(&self, on: bool) {
|
||||
'outer: loop {
|
||||
if let Ok(mut lock) = self.0.try_lock() {
|
||||
lock.write_bytes(&pkt_for_set_boot(on));
|
||||
lock.write_bytes(&pkt_for_apply());
|
||||
lock.config.boot_anim_enabled = on;
|
||||
lock.config.write();
|
||||
|
||||
let states = AnimePowerStates {
|
||||
enabled: lock.config.awake_enabled,
|
||||
boot_anim_enabled: lock.config.boot_anim_enabled,
|
||||
};
|
||||
self.notify_power_states(&states)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The main loop is the base system set action if the user isn't running
|
||||
/// the user daemon
|
||||
fn run_main_loop(&self, start: bool) {
|
||||
if start {
|
||||
'outer: loop {
|
||||
if let Ok(lock) = self.0.try_lock() {
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
CtrlAnime::run_thread(self.0.clone(), lock.cache.system.clone(), false);
|
||||
break 'outer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(property)]
|
||||
fn awake_enabled(&self) -> bool {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
return ctrl.config.awake_enabled;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[dbus_interface(property)]
|
||||
fn boot_enabled(&self) -> bool {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
return ctrl.config.boot_anim_enabled;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_power_states(&self, data: &AnimePowerStates) -> zbus::Result<()>;
|
||||
}
|
||||
123
daemon/src/ctrl_charge.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use crate::{config::Config, error::RogError, GetSupported};
|
||||
//use crate::dbus::DbusEvents;
|
||||
use log::{info, warn};
|
||||
use rog_types::supported::ChargeSupportedFunctions;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use zbus::dbus_interface;
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
static BAT_CHARGE_PATH: &str = "/sys/class/power_supply/BAT0/charge_control_end_threshold";
|
||||
|
||||
impl GetSupported for CtrlCharge {
|
||||
type A = ChargeSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
ChargeSupportedFunctions {
|
||||
charge_level_set: CtrlCharge::get_battery_path().is_ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlCharge {
|
||||
config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlCharge {
|
||||
pub fn set_limit(&mut self, limit: u8) {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
self.set(limit, &mut config)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
self.notify_charge(limit)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn limit(&self) -> i8 {
|
||||
if let Ok(config) = self.config.try_lock() {
|
||||
return config.bat_charge_limit as i8;
|
||||
}
|
||||
-1
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
pub fn notify_charge(&self, limit: u8) -> zbus::Result<()> {}
|
||||
}
|
||||
|
||||
impl crate::ZbusAdd for CtrlCharge {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Charge"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlCharge {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
config.read();
|
||||
self.set(config.bat_charge_limit, &mut config)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlCharge {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
CtrlCharge::get_battery_path()?;
|
||||
Ok(CtrlCharge { config })
|
||||
}
|
||||
|
||||
fn get_battery_path() -> Result<&'static str, RogError> {
|
||||
if Path::new(BAT_CHARGE_PATH).exists() {
|
||||
Ok(BAT_CHARGE_PATH)
|
||||
} else {
|
||||
Err(RogError::MissingFunction(
|
||||
"Charge control not available, you may require a v5.8.10 series kernel or newer"
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set(&self, limit: u8, config: &mut Config) -> Result<(), RogError> {
|
||||
if !(20..=100).contains(&limit) {
|
||||
warn!(
|
||||
"Unable to set battery charge limit, must be between 20-100: requested {}",
|
||||
limit
|
||||
);
|
||||
}
|
||||
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.open(BAT_CHARGE_PATH)
|
||||
.map_err(|err| RogError::Path(BAT_CHARGE_PATH.into(), err))?;
|
||||
file.write_all(limit.to_string().as_bytes())
|
||||
.map_err(|err| RogError::Write(BAT_CHARGE_PATH.into(), err))?;
|
||||
info!("Battery charge limit: {}", limit);
|
||||
|
||||
config.read();
|
||||
config.bat_charge_limit = limit;
|
||||
config.write();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
642
daemon/src/ctrl_gfx/controller.rs
Normal file
@@ -0,0 +1,642 @@
|
||||
use ::zbus::Connection;
|
||||
use ctrl_gfx::error::GfxError;
|
||||
use ctrl_gfx::*;
|
||||
use ctrl_rog_bios::CtrlRogBios;
|
||||
use log::{error, info, warn};
|
||||
use logind_zbus::{
|
||||
types::{SessionClass, SessionInfo, SessionState, SessionType},
|
||||
ManagerProxy, SessionProxy,
|
||||
};
|
||||
use rog_types::gfx_vendors::{GfxPower, GfxRequiredUserAction, GfxVendors};
|
||||
use std::{io::Write, ops::Add, path::Path, time::Instant};
|
||||
use std::{iter::FromIterator, thread::JoinHandle};
|
||||
use std::{process::Command, thread::sleep, time::Duration};
|
||||
use std::{str::FromStr, sync::mpsc};
|
||||
use std::{sync::Arc, sync::Mutex};
|
||||
use sysfs_class::{PciDevice, SysClass};
|
||||
use system::{GraphicsDevice, PciBus};
|
||||
|
||||
use crate::*;
|
||||
|
||||
const THREAD_TIMEOUT_MSG: &str = "GFX: thread time exceeded 3 minutes, exiting";
|
||||
|
||||
pub struct CtrlGraphics {
|
||||
bus: PciBus,
|
||||
_amd: Vec<GraphicsDevice>,
|
||||
_intel: Vec<GraphicsDevice>,
|
||||
nvidia: Vec<GraphicsDevice>,
|
||||
#[allow(dead_code)]
|
||||
other: Vec<GraphicsDevice>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
thread_kill: Arc<Mutex<Option<mpsc::Sender<bool>>>>,
|
||||
}
|
||||
|
||||
impl Reloadable for CtrlGraphics {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
self.auto_power()?;
|
||||
info!("GFX: Reloaded gfx mode: {:?}", self.get_gfx_mode()?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlGraphics {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> std::io::Result<CtrlGraphics> {
|
||||
let bus = PciBus::new()?;
|
||||
info!("GFX: Rescanning PCI bus");
|
||||
bus.rescan()?;
|
||||
let devs = PciDevice::all()?;
|
||||
|
||||
let functions = |parent: &PciDevice| -> Vec<PciDevice> {
|
||||
let mut functions = Vec::new();
|
||||
if let Some(parent_slot) = parent.id().split('.').next() {
|
||||
for func in devs.iter() {
|
||||
if let Some(func_slot) = func.id().split('.').next() {
|
||||
if func_slot == parent_slot {
|
||||
info!("GFX: {}: Function for {}", func.id(), parent.id());
|
||||
functions.push(func.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
functions
|
||||
};
|
||||
|
||||
let mut amd = Vec::new();
|
||||
let mut intel = Vec::new();
|
||||
let mut nvidia = Vec::new();
|
||||
let mut other = Vec::new();
|
||||
for dev in devs.iter() {
|
||||
let c = dev.class()?;
|
||||
if 0x03 == (c >> 16) & 0xFF {
|
||||
match dev.vendor()? {
|
||||
0x1002 => {
|
||||
info!("GFX: {}: AMD graphics", dev.id());
|
||||
amd.push(GraphicsDevice::new(dev.id().to_owned(), functions(&dev)));
|
||||
}
|
||||
0x10DE => {
|
||||
info!("GFX: {}: NVIDIA graphics", dev.id());
|
||||
nvidia.push(GraphicsDevice::new(dev.id().to_owned(), functions(&dev)));
|
||||
}
|
||||
0x8086 => {
|
||||
info!("GFX: {}: Intel graphics", dev.id());
|
||||
intel.push(GraphicsDevice::new(dev.id().to_owned(), functions(&dev)));
|
||||
}
|
||||
vendor => {
|
||||
info!("GFX: {}: Other({:X}) graphics", dev.id(), vendor);
|
||||
other.push(GraphicsDevice::new(dev.id().to_owned(), functions(&dev)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CtrlGraphics {
|
||||
bus,
|
||||
_amd: amd,
|
||||
_intel: intel,
|
||||
nvidia,
|
||||
other,
|
||||
config,
|
||||
thread_kill: Arc::new(Mutex::new(None)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bus(&self) -> PciBus {
|
||||
self.bus.clone()
|
||||
}
|
||||
|
||||
pub fn devices(&self) -> Vec<GraphicsDevice> {
|
||||
self.nvidia.clone()
|
||||
}
|
||||
|
||||
/// Save the selected `Vendor` mode to config
|
||||
fn save_gfx_mode(vendor: GfxVendors, config: Arc<Mutex<Config>>) {
|
||||
if let Ok(mut config) = config.lock() {
|
||||
config.gfx_mode = vendor;
|
||||
config.write();
|
||||
}
|
||||
}
|
||||
|
||||
/// Associated method to get which vendor mode is set
|
||||
pub fn get_gfx_mode(&self) -> Result<GfxVendors, RogError> {
|
||||
if let Ok(config) = self.config.lock() {
|
||||
if let Some(mode) = config.gfx_tmp_mode {
|
||||
return Ok(mode);
|
||||
}
|
||||
return Ok(config.gfx_mode);
|
||||
}
|
||||
// TODO: Error here
|
||||
Ok(GfxVendors::Hybrid)
|
||||
}
|
||||
|
||||
pub(super) fn get_runtime_status() -> Result<GfxPower, RogError> {
|
||||
let path = Path::new("/sys/bus/pci/devices/0000:01:00.0/power/runtime_status");
|
||||
if path.exists() {
|
||||
let buf = std::fs::read_to_string(path).map_err(|err| {
|
||||
RogError::Read(
|
||||
"/sys/bus/pci/devices/0000:01:00.0/power/runtime_status".to_string(),
|
||||
err,
|
||||
)
|
||||
})?;
|
||||
Ok(GfxPower::from_str(&buf)?)
|
||||
} else {
|
||||
Ok(GfxPower::Off)
|
||||
}
|
||||
}
|
||||
|
||||
/// Some systems have a fallback service to load nouveau if nvidia fails
|
||||
fn toggle_fallback_service(vendor: GfxVendors) -> Result<(), RogError> {
|
||||
let action = if vendor == GfxVendors::Nvidia {
|
||||
info!("GFX: Enabling nvidia-fallback.service");
|
||||
"enable"
|
||||
} else {
|
||||
info!("GFX: Disabling nvidia-fallback.service");
|
||||
"disable"
|
||||
};
|
||||
|
||||
let status = Command::new("systemctl")
|
||||
.arg(action)
|
||||
.arg("nvidia-fallback.service")
|
||||
.status()
|
||||
.map_err(|err| RogError::Command("systemctl".into(), err))?;
|
||||
|
||||
if !status.success() {
|
||||
// Error is ignored in case this service is removed
|
||||
warn!(
|
||||
"systemctl: {} (ignore warning if service does not exist!)",
|
||||
status
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the appropriate xorg config for the chosen mode
|
||||
fn write_xorg_conf(vendor: GfxVendors) -> Result<(), RogError> {
|
||||
let text = if vendor == GfxVendors::Nvidia {
|
||||
[PRIMARY_GPU_BEGIN, PRIMARY_GPU_NVIDIA, PRIMARY_GPU_END].concat()
|
||||
} else {
|
||||
[PRIMARY_GPU_BEGIN, PRIMARY_GPU_END].concat()
|
||||
};
|
||||
|
||||
if !Path::new(XORG_PATH).exists() {
|
||||
std::fs::create_dir(XORG_PATH).map_err(|err| RogError::Write(XORG_PATH.into(), err))?;
|
||||
}
|
||||
|
||||
let file = XORG_PATH.to_string().add(XORG_FILE);
|
||||
info!("GFX: Writing {}", file);
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(&file)
|
||||
.map_err(|err| RogError::Write(file, err))?;
|
||||
|
||||
file.write_all(&text)
|
||||
.and_then(|_| file.sync_all())
|
||||
.map_err(|err| RogError::Write(MODPROBE_PATH.into(), err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates the full modprobe.conf required for vfio pass-through
|
||||
fn get_vfio_conf(devices: &[GraphicsDevice]) -> Vec<u8> {
|
||||
let mut vifo = MODPROBE_VFIO.to_vec();
|
||||
for (d_count, dev) in devices.iter().enumerate() {
|
||||
for (f_count, func) in dev.functions().iter().enumerate() {
|
||||
let vendor = func.vendor().unwrap();
|
||||
let device = func.device().unwrap();
|
||||
unsafe {
|
||||
vifo.append(format!("{:x}", vendor).as_mut_vec());
|
||||
}
|
||||
vifo.append(&mut vec![b':']);
|
||||
unsafe {
|
||||
vifo.append(format!("{:x}", device).as_mut_vec());
|
||||
}
|
||||
if f_count < dev.functions().len() - 1 {
|
||||
vifo.append(&mut vec![b',']);
|
||||
}
|
||||
}
|
||||
if d_count < dev.functions().len() - 1 {
|
||||
vifo.append(&mut vec![b',']);
|
||||
}
|
||||
}
|
||||
let mut conf = MODPROBE_INTEGRATED.to_vec();
|
||||
conf.append(&mut vifo);
|
||||
conf
|
||||
}
|
||||
|
||||
fn write_modprobe_conf(vendor: GfxVendors, devices: &[GraphicsDevice]) -> Result<(), RogError> {
|
||||
info!("GFX: Writing {}", MODPROBE_PATH);
|
||||
let content = match vendor {
|
||||
GfxVendors::Nvidia | GfxVendors::Hybrid => {
|
||||
let mut base = MODPROBE_BASE.to_vec();
|
||||
base.append(&mut MODPROBE_DRM_MODESET.to_vec());
|
||||
base
|
||||
}
|
||||
GfxVendors::Vfio => Self::get_vfio_conf(devices),
|
||||
GfxVendors::Integrated => MODPROBE_INTEGRATED.to_vec(),
|
||||
GfxVendors::Compute => MODPROBE_BASE.to_vec(),
|
||||
};
|
||||
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.write(true)
|
||||
.open(MODPROBE_PATH)
|
||||
.map_err(|err| RogError::Path(MODPROBE_PATH.into(), err))?;
|
||||
|
||||
file.write_all(&content)
|
||||
.and_then(|_| file.sync_all())
|
||||
.map_err(|err| RogError::Write(MODPROBE_PATH.into(), err))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unbind_remove_nvidia(devices: &[GraphicsDevice]) -> Result<(), RogError> {
|
||||
// Unbind NVIDIA graphics devices and their functions
|
||||
let unbinds = devices.iter().map(|dev| dev.unbind());
|
||||
// Remove NVIDIA graphics devices and their functions
|
||||
let removes = devices.iter().map(|dev| dev.remove());
|
||||
Result::from_iter(unbinds.chain(removes))
|
||||
.map_err(|err| RogError::Command("device unbind error".into(), err))
|
||||
}
|
||||
|
||||
fn unbind_only(devices: &[GraphicsDevice]) -> Result<(), RogError> {
|
||||
let unbinds = devices.iter().map(|dev| dev.unbind());
|
||||
Result::from_iter(unbinds)
|
||||
.map_err(|err| RogError::Command("device unbind error".into(), err))
|
||||
}
|
||||
|
||||
fn do_driver_action(driver: &str, action: &str) -> Result<(), GfxError> {
|
||||
let mut cmd = Command::new(action);
|
||||
cmd.arg(driver);
|
||||
|
||||
let mut count = 0;
|
||||
const MAX_TRIES: i32 = 6;
|
||||
loop {
|
||||
if count > MAX_TRIES {
|
||||
let msg = format!("{} {} failed for unknown reason", action, driver);
|
||||
error!("GFX: {}", msg);
|
||||
return Ok(()); //Err(RogError::Modprobe(msg));
|
||||
}
|
||||
|
||||
let output = cmd
|
||||
.output()
|
||||
.map_err(|err| GfxError::Command(format!("{:?}", cmd), err))?;
|
||||
if !output.status.success() {
|
||||
if output
|
||||
.stderr
|
||||
.ends_with("is not currently loaded\n".as_bytes())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if output.stderr.ends_with("is builtin.\n".as_bytes()) {
|
||||
return Err(GfxError::VfioBuiltin);
|
||||
}
|
||||
if output.stderr.ends_with("Permission denied\n".as_bytes()) {
|
||||
warn!(
|
||||
"{} {} failed: {:?}",
|
||||
action,
|
||||
driver,
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
warn!("GFX: It may be safe to ignore the above error, run `lsmod |grep {}` to confirm modules loaded", driver);
|
||||
return Ok(());
|
||||
}
|
||||
if String::from_utf8_lossy(&output.stderr)
|
||||
.contains(&format!("Module {} not found", driver))
|
||||
{
|
||||
return Err(GfxError::MissingModule(driver.into()));
|
||||
}
|
||||
if count >= MAX_TRIES {
|
||||
let msg = format!(
|
||||
"{} {} failed: {:?}",
|
||||
action,
|
||||
driver,
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Err(GfxError::Modprobe(msg));
|
||||
}
|
||||
} else if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
count += 1;
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
|
||||
fn do_display_manager_action(action: &str) -> Result<(), RogError> {
|
||||
let mut cmd = Command::new("systemctl");
|
||||
cmd.arg(action);
|
||||
cmd.arg(DISPLAY_MANAGER);
|
||||
|
||||
let status = cmd
|
||||
.status()
|
||||
.map_err(|err| RogError::Command(format!("{:?}", cmd), err))?;
|
||||
if !status.success() {
|
||||
let msg = format!(
|
||||
"systemctl {} {} failed: {:?}",
|
||||
action, DISPLAY_MANAGER, status
|
||||
);
|
||||
return Err(GfxError::DisplayManagerAction(msg, status).into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_display_manager_state(state: &str) -> Result<(), RogError> {
|
||||
let mut cmd = Command::new("systemctl");
|
||||
cmd.arg("is-active");
|
||||
cmd.arg(DISPLAY_MANAGER);
|
||||
|
||||
let mut count = 0;
|
||||
|
||||
while count <= 5 {
|
||||
let output = cmd
|
||||
.output()
|
||||
.map_err(|err| RogError::Command(format!("{:?}", cmd), err))?;
|
||||
if output.stdout.starts_with(state.as_bytes()) {
|
||||
return Ok(());
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(500));
|
||||
count += 1;
|
||||
}
|
||||
Err(GfxError::DisplayManagerTimeout(state.into()).into())
|
||||
}
|
||||
|
||||
/// Determine if we need to logout/thread. Integrated<->Vfio mode does not
|
||||
/// require logout.
|
||||
fn logout_required(&self, vendor: GfxVendors) -> GfxRequiredUserAction {
|
||||
if let Ok(config) = self.config.lock() {
|
||||
let current = config.gfx_mode;
|
||||
if matches!(
|
||||
current,
|
||||
GfxVendors::Integrated | GfxVendors::Vfio | GfxVendors::Compute
|
||||
) && matches!(
|
||||
vendor,
|
||||
GfxVendors::Integrated | GfxVendors::Vfio | GfxVendors::Compute
|
||||
) {
|
||||
return GfxRequiredUserAction::None;
|
||||
}
|
||||
}
|
||||
GfxRequiredUserAction::Logout
|
||||
}
|
||||
|
||||
/// Write the config changes and add/remove drivers and devices depending
|
||||
/// on selected mode:
|
||||
///
|
||||
/// Tasks:
|
||||
/// - write xorg config
|
||||
/// - write modprobe config
|
||||
/// - rescan for devices
|
||||
/// + add drivers
|
||||
/// + or remove drivers and devices
|
||||
///
|
||||
/// The daemon needs direct access to this function when it detects that the
|
||||
pub fn do_vendor_tasks(
|
||||
vendor: GfxVendors,
|
||||
vfio_enable: bool,
|
||||
devices: &[GraphicsDevice],
|
||||
bus: &PciBus,
|
||||
) -> Result<(), RogError> {
|
||||
// Rescan before doing remove or add drivers
|
||||
bus.rescan()?;
|
||||
//
|
||||
Self::write_xorg_conf(vendor)?;
|
||||
// Write different modprobe to enable boot control to work
|
||||
Self::write_modprobe_conf(vendor, devices)?;
|
||||
|
||||
match vendor {
|
||||
GfxVendors::Nvidia | GfxVendors::Hybrid | GfxVendors::Compute => {
|
||||
if vfio_enable {
|
||||
for driver in VFIO_DRIVERS.iter() {
|
||||
Self::do_driver_action(driver, "rmmod")?;
|
||||
}
|
||||
}
|
||||
for driver in NVIDIA_DRIVERS.iter() {
|
||||
Self::do_driver_action(driver, "modprobe")?;
|
||||
}
|
||||
}
|
||||
GfxVendors::Vfio => {
|
||||
if vfio_enable {
|
||||
Self::do_driver_action("nouveau", "rmmod")?;
|
||||
for driver in NVIDIA_DRIVERS.iter() {
|
||||
Self::do_driver_action(driver, "rmmod")?;
|
||||
}
|
||||
Self::unbind_only(&devices)?;
|
||||
Self::do_driver_action("vfio-pci", "modprobe")?;
|
||||
} else {
|
||||
return Err(GfxError::VfioDisabled.into());
|
||||
}
|
||||
}
|
||||
GfxVendors::Integrated => {
|
||||
Self::do_driver_action("nouveau", "rmmod")?;
|
||||
if vfio_enable {
|
||||
for driver in VFIO_DRIVERS.iter() {
|
||||
Self::do_driver_action(driver, "rmmod")?;
|
||||
}
|
||||
}
|
||||
for driver in NVIDIA_DRIVERS.iter() {
|
||||
Self::do_driver_action(driver, "rmmod")?;
|
||||
}
|
||||
Self::unbind_remove_nvidia(&devices)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if the user has any graphical uiser sessions that are active or online
|
||||
fn graphical_user_sessions_exist(
|
||||
connection: &Connection,
|
||||
sessions: &[SessionInfo],
|
||||
) -> Result<bool, RogError> {
|
||||
for session in sessions {
|
||||
let session_proxy = SessionProxy::new(connection, session)?;
|
||||
if session_proxy.get_class()? == SessionClass::User {
|
||||
match session_proxy.get_type()? {
|
||||
SessionType::X11 | SessionType::Wayland | SessionType::MIR => {
|
||||
match session_proxy.get_state()? {
|
||||
SessionState::Online | SessionState::Active => return Ok(true),
|
||||
SessionState::Closing | SessionState::Invalid => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Spools until all user sessions are ended then switches to requested mode
|
||||
fn fire_starter(
|
||||
vendor: GfxVendors,
|
||||
devices: Vec<GraphicsDevice>,
|
||||
bus: PciBus,
|
||||
thread_stop: mpsc::Receiver<bool>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
) -> Result<String, RogError> {
|
||||
info!("GFX: display-manager thread started");
|
||||
|
||||
const SLEEP_PERIOD: Duration = Duration::from_millis(100);
|
||||
let start_time = Instant::now();
|
||||
|
||||
let connection = Connection::new_system()?;
|
||||
let manager = ManagerProxy::new(&connection)?;
|
||||
let mut sessions = manager.list_sessions()?;
|
||||
|
||||
loop {
|
||||
let tmp = manager.list_sessions()?;
|
||||
if !tmp.iter().eq(&sessions) {
|
||||
info!("GFX thread: Sessions list changed");
|
||||
sessions = tmp;
|
||||
}
|
||||
|
||||
if !Self::graphical_user_sessions_exist(&connection, &sessions)? {
|
||||
break;
|
||||
}
|
||||
|
||||
if let Ok(stop) = thread_stop.try_recv() {
|
||||
if stop {
|
||||
return Ok("Graphics mode change was cancelled".into());
|
||||
}
|
||||
}
|
||||
// exit if 3 minutes pass
|
||||
if Instant::now().duration_since(start_time).as_secs() > 180 {
|
||||
warn!("{}", THREAD_TIMEOUT_MSG);
|
||||
return Ok(THREAD_TIMEOUT_MSG.into());
|
||||
}
|
||||
|
||||
// Don't spin at max speed
|
||||
sleep(SLEEP_PERIOD);
|
||||
}
|
||||
|
||||
info!("GFX thread: all graphical user sessions ended, continuing");
|
||||
Self::do_display_manager_action("stop")?;
|
||||
Self::wait_display_manager_state("inactive")?;
|
||||
|
||||
let vfio_enable = if let Ok(mut config) = config.try_lock() {
|
||||
// Since we have a lock, reset tmp to none. This thread should only ever run
|
||||
// for Integrated, Hybrid, or Nvidia. Tmp is also only for informational
|
||||
config.gfx_tmp_mode = None;
|
||||
//
|
||||
config.gfx_vfio_enable
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
Self::do_vendor_tasks(vendor, vfio_enable, &devices, &bus)?;
|
||||
Self::do_display_manager_action("restart")?;
|
||||
// Save selected mode in case of reboot
|
||||
Self::save_gfx_mode(vendor, config);
|
||||
info!("GFX thread: display-manager started");
|
||||
|
||||
let v: &str = vendor.into();
|
||||
info!("GFX thread: Graphics mode changed to {} successfully", v);
|
||||
Ok(format!("Graphics mode changed to {} successfully", v))
|
||||
}
|
||||
|
||||
/// Before starting a new thread the old one *must* be cancelled
|
||||
fn cancel_thread(&self) {
|
||||
if let Ok(lock) = self.thread_kill.lock() {
|
||||
if let Some(tx) = lock.as_ref() {
|
||||
// Cancel the running thread
|
||||
info!("GFX: Cancelling previous thread");
|
||||
tx.send(true)
|
||||
.map_err(|err| {
|
||||
warn!("GFX thread: {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thread is used only in cases where a logout is required
|
||||
fn setup_thread(&mut self, vendor: GfxVendors) {
|
||||
let config = self.config.clone();
|
||||
let devices = self.nvidia.clone();
|
||||
let bus = self.bus.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
if let Ok(mut lock) = self.thread_kill.lock() {
|
||||
*lock = Some(tx);
|
||||
}
|
||||
let killer = self.thread_kill.clone();
|
||||
|
||||
let _join: JoinHandle<()> = std::thread::spawn(move || {
|
||||
Self::fire_starter(vendor, devices, bus, rx, config)
|
||||
.map_err(|err| {
|
||||
error!("GFX: {}", err);
|
||||
})
|
||||
.ok();
|
||||
// clear the tx/rx when done
|
||||
if let Ok(mut lock) = killer.try_lock() {
|
||||
*lock = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Initiates a mode change by starting a thread that will wait until all
|
||||
/// graphical sessions are exited before performing the tasks required
|
||||
/// to switch modes.
|
||||
///
|
||||
/// For manually calling (not on boot/startup) via dbus
|
||||
pub fn set_gfx_config(
|
||||
&mut self,
|
||||
vendor: GfxVendors,
|
||||
) -> Result<GfxRequiredUserAction, RogError> {
|
||||
if let Ok(gsync) = CtrlRogBios::get_gfx_mode() {
|
||||
if gsync == 1 {
|
||||
return Err(GfxError::GsyncModeActive.into());
|
||||
}
|
||||
}
|
||||
|
||||
let vfio_enable = if let Ok(config) = self.config.try_lock() {
|
||||
config.gfx_vfio_enable
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
if !vfio_enable && matches!(vendor, GfxVendors::Vfio) {
|
||||
return Err(GfxError::VfioDisabled.into());
|
||||
}
|
||||
|
||||
// Must always cancel any thread running
|
||||
self.cancel_thread();
|
||||
// determine which method we need here
|
||||
let action_required = self.logout_required(vendor);
|
||||
if matches!(action_required, GfxRequiredUserAction::Logout) {
|
||||
// Yeah need the thread to check if all users are logged out
|
||||
info!("GFX: mode change requires a logout to complete");
|
||||
self.setup_thread(vendor);
|
||||
} else {
|
||||
// Okay cool, we can switch on/off vfio
|
||||
info!("GFX: mode change does not require logout");
|
||||
let devices = self.nvidia.clone();
|
||||
let bus = self.bus.clone();
|
||||
Self::do_vendor_tasks(vendor, vfio_enable, &devices, &bus)?;
|
||||
info!("GFX: Graphics mode changed to {}", <&str>::from(vendor));
|
||||
if matches!(vendor, GfxVendors::Vfio | GfxVendors::Compute) {
|
||||
if let Ok(mut config) = self.config.try_lock() {
|
||||
config.gfx_tmp_mode = Some(vendor);
|
||||
};
|
||||
}
|
||||
}
|
||||
// TODO: undo if failed? Save last mode, catch errors...
|
||||
Ok(action_required)
|
||||
}
|
||||
|
||||
/// Used only on boot to set correct mode
|
||||
fn auto_power(&mut self) -> Result<(), RogError> {
|
||||
let vendor = self.get_gfx_mode()?;
|
||||
let devices = self.nvidia.clone();
|
||||
let bus = self.bus.clone();
|
||||
|
||||
let vfio_enable = if let Ok(config) = self.config.try_lock() {
|
||||
config.gfx_vfio_enable
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
Self::do_vendor_tasks(vendor, vfio_enable, &devices, &bus)?;
|
||||
Self::toggle_fallback_service(vendor)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
58
daemon/src/ctrl_gfx/error.rs
Normal file
@@ -0,0 +1,58 @@
|
||||
use std::fmt;
|
||||
use std::{error, process::ExitStatus};
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum GfxError {
|
||||
ParseVendor,
|
||||
ParsePower,
|
||||
Bus(String, std::io::Error),
|
||||
DisplayManagerAction(String, ExitStatus),
|
||||
DisplayManagerTimeout(String),
|
||||
GsyncModeActive,
|
||||
VfioBuiltin,
|
||||
VfioDisabled,
|
||||
MissingModule(String),
|
||||
Modprobe(String),
|
||||
Command(String, std::io::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for GfxError {
|
||||
// This trait requires `fmt` with this exact signature.
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
GfxError::ParseVendor => write!(f, "Could not parse vendor name"),
|
||||
GfxError::ParsePower => write!(f, "Could not parse dGPU power status"),
|
||||
GfxError::Bus(func, error) => write!(f, "Bus error: {}: {}", func, error),
|
||||
GfxError::DisplayManagerAction(action, status) => {
|
||||
write!(f, "Display-manager action {} failed: {}", action, status)
|
||||
}
|
||||
GfxError::DisplayManagerTimeout(state) => {
|
||||
write!(f, "Timed out waiting for display-manager {} state", state)
|
||||
}
|
||||
GfxError::GsyncModeActive => write!(
|
||||
f,
|
||||
"Can not switch gfx modes when dedicated/G-Sync mode is active"
|
||||
),
|
||||
GfxError::VfioBuiltin => write!(
|
||||
f,
|
||||
"Can not switch to vfio mode if the modules are built in to kernel"
|
||||
),
|
||||
GfxError::VfioDisabled => {
|
||||
write!(f, "Can not switch to vfio mode if disabled in config file")
|
||||
}
|
||||
GfxError::MissingModule(m) => write!(f, "The module {} is missing", m),
|
||||
GfxError::Modprobe(detail) => write!(f, "Modprobe error: {}", detail),
|
||||
GfxError::Command(func, error) => write!(f, "Command exec error: {}: {}", func, error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for GfxError {}
|
||||
|
||||
impl From<GfxError> for RogError {
|
||||
fn from(err: GfxError) -> Self {
|
||||
RogError::GfxSwitching(err)
|
||||
}
|
||||
}
|
||||
62
daemon/src/ctrl_gfx/mod.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
pub mod error;
|
||||
|
||||
pub mod controller;
|
||||
|
||||
pub mod system;
|
||||
|
||||
pub mod zbus_gfx;
|
||||
|
||||
const NVIDIA_DRIVERS: [&str; 4] = ["nvidia_drm", "nvidia_modeset", "nvidia_uvm", "nvidia"];
|
||||
|
||||
const VFIO_DRIVERS: [&str; 5] = [
|
||||
"vfio-pci",
|
||||
"vfio_iommu_type1",
|
||||
"vfio_virqfd",
|
||||
"vfio_mdev",
|
||||
"vfio",
|
||||
];
|
||||
|
||||
const DISPLAY_MANAGER: &str = "display-manager.service";
|
||||
|
||||
const MODPROBE_PATH: &str = "/etc/modprobe.d/asusd.conf";
|
||||
|
||||
static MODPROBE_BASE: &[u8] = br#"# Automatically generated by asusd
|
||||
# If you have issues with i2c_nvidia_gpu, copy the 2 lines below to a
|
||||
# new blacklist file and uncomment
|
||||
#blacklist i2c_nvidia_gpu
|
||||
#alias i2c_nvidia_gpu off
|
||||
blacklist nouveau
|
||||
alias nouveau off
|
||||
options nvidia NVreg_DynamicPowerManagement=0x02
|
||||
"#;
|
||||
|
||||
static MODPROBE_DRM_MODESET: &[u8] = br#"
|
||||
options nvidia-drm modeset=1
|
||||
"#;
|
||||
|
||||
static MODPROBE_INTEGRATED: &[u8] = br#"# Automatically generated by asusd
|
||||
blacklist i2c_nvidia_gpu
|
||||
blacklist nvidia
|
||||
blacklist nvidia-drm
|
||||
blacklist nvidia-modeset
|
||||
blacklist nouveau
|
||||
alias nouveau off
|
||||
"#;
|
||||
|
||||
static MODPROBE_VFIO: &[u8] = br#"options vfio-pci ids="#;
|
||||
|
||||
const XORG_FILE: &str = "90-nvidia-primary.conf";
|
||||
const XORG_PATH: &str = "/etc/X11/xorg.conf.d/";
|
||||
|
||||
static PRIMARY_GPU_BEGIN: &[u8] = br#"# Automatically generated by asusd
|
||||
Section "OutputClass"
|
||||
Identifier "nvidia"
|
||||
MatchDriver "nvidia-drm"
|
||||
Driver "nvidia"
|
||||
Option "AllowEmptyInitialConfiguration" "true""#;
|
||||
|
||||
static PRIMARY_GPU_NVIDIA: &[u8] = br#"
|
||||
Option "PrimaryGPU" "true""#;
|
||||
|
||||
static PRIMARY_GPU_END: &[u8] = br#"
|
||||
EndSection"#;
|
||||
160
daemon/src/ctrl_gfx/system.rs
Normal file
@@ -0,0 +1,160 @@
|
||||
use log::{error, info, warn};
|
||||
use std::fs::read_to_string;
|
||||
use std::{fs::write, io, path::PathBuf};
|
||||
use sysfs_class::{PciDevice, SysClass};
|
||||
|
||||
pub struct Module {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl Module {
|
||||
fn parse(line: &str) -> io::Result<Module> {
|
||||
let mut parts = line.split(' ');
|
||||
|
||||
let name = parts
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "module name not found"))?;
|
||||
|
||||
Ok(Module {
|
||||
name: name.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn all() -> io::Result<Vec<Module>> {
|
||||
let mut modules = Vec::new();
|
||||
|
||||
let data = read_to_string("/proc/modules")?;
|
||||
for line in data.lines() {
|
||||
let module = Module::parse(line)?;
|
||||
modules.push(module);
|
||||
}
|
||||
|
||||
Ok(modules)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PciBus {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl PciBus {
|
||||
pub fn new() -> io::Result<PciBus> {
|
||||
let path = PathBuf::from("/sys/bus/pci");
|
||||
if path.is_dir() {
|
||||
Ok(PciBus { path })
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
"pci directory not found",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Will rescan the device tree, which adds all removed devices back
|
||||
pub fn rescan(&self) -> io::Result<()> {
|
||||
write(self.path.join("rescan"), "1")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GraphicsDevice {
|
||||
_id: String,
|
||||
functions: Vec<PciDevice>,
|
||||
}
|
||||
|
||||
impl GraphicsDevice {
|
||||
pub fn new(id: String, functions: Vec<PciDevice>) -> GraphicsDevice {
|
||||
GraphicsDevice { _id: id, functions }
|
||||
}
|
||||
|
||||
pub fn exists(&self) -> bool {
|
||||
self.functions.iter().any(|func| func.path().exists())
|
||||
}
|
||||
|
||||
pub fn functions(&self) -> &[PciDevice] {
|
||||
&self.functions
|
||||
}
|
||||
|
||||
pub fn unbind(&self) -> Result<(), std::io::Error> {
|
||||
for func in self.functions.iter() {
|
||||
if func.path().exists() {
|
||||
match func.driver() {
|
||||
Ok(driver) => {
|
||||
info!("{}: Unbinding {}", driver.id(), func.id());
|
||||
unsafe {
|
||||
driver.unbind(&func).map_err(|err| {
|
||||
error!("gfx unbind: {}", err);
|
||||
err
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Err(err) => match err.kind() {
|
||||
io::ErrorKind::NotFound => (),
|
||||
_ => {
|
||||
error!("gfx driver: {:?}, {}", func.path(), err);
|
||||
return Err(err);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn rebind(&self) -> Result<(), std::io::Error> {
|
||||
for func in self.functions.iter() {
|
||||
if func.path().exists() {
|
||||
match func.driver() {
|
||||
Ok(driver) => {
|
||||
info!("{}: Binding {}", driver.id(), func.id());
|
||||
unsafe {
|
||||
driver.bind(&func).map_err(|err| {
|
||||
error!("gfx bind: {}", err);
|
||||
err
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Err(err) => match err.kind() {
|
||||
io::ErrorKind::NotFound => (),
|
||||
_ => {
|
||||
error!("gfx driver: {:?}, {}", func.path(), err);
|
||||
return Err(err);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&self) -> Result<(), std::io::Error> {
|
||||
for func in self.functions.iter() {
|
||||
if func.path().exists() {
|
||||
match func.driver() {
|
||||
Ok(driver) => {
|
||||
error!("{}: in use by {}", func.id(), driver.id());
|
||||
}
|
||||
Err(why) => match why.kind() {
|
||||
std::io::ErrorKind::NotFound => {
|
||||
info!("{}: Removing", func.id());
|
||||
unsafe {
|
||||
// ignore errors and carry on
|
||||
if let Err(err) = func.remove() {
|
||||
error!("gfx remove: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
error!("Remove device failed");
|
||||
}
|
||||
},
|
||||
}
|
||||
} else {
|
||||
warn!("{}: Already removed", func.id());
|
||||
}
|
||||
}
|
||||
info!("Removed all gfx devices");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
56
daemon/src/ctrl_gfx/zbus_gfx.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
use ::zbus::dbus_interface;
|
||||
use log::{error, info, warn};
|
||||
use rog_types::gfx_vendors::{GfxPower, GfxRequiredUserAction, GfxVendors};
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
use crate::ZbusAdd;
|
||||
|
||||
use super::controller::CtrlGraphics;
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlGraphics {
|
||||
fn vendor(&self) -> zbus::fdo::Result<GfxVendors> {
|
||||
self.get_gfx_mode().map_err(|err| {
|
||||
error!("GFX: {}", err);
|
||||
zbus::fdo::Error::Failed(format!("GFX fail: {}", err))
|
||||
})
|
||||
}
|
||||
|
||||
fn power(&self) -> zbus::fdo::Result<GfxPower> {
|
||||
Self::get_runtime_status().map_err(|err| {
|
||||
error!("GFX: {}", err);
|
||||
zbus::fdo::Error::Failed(format!("GFX fail: {}", err))
|
||||
})
|
||||
}
|
||||
|
||||
fn set_vendor(&mut self, vendor: GfxVendors) -> zbus::fdo::Result<GfxRequiredUserAction> {
|
||||
info!("GFX: Switching gfx mode to {}", <&str>::from(vendor));
|
||||
let msg = self.set_gfx_config(vendor).map_err(|err| {
|
||||
error!("GFX: {}", err);
|
||||
zbus::fdo::Error::Failed(format!("GFX fail: {}", err))
|
||||
})?;
|
||||
self.notify_gfx(&vendor)
|
||||
.unwrap_or_else(|err| warn!("GFX: {}", err));
|
||||
self.notify_action(&msg)
|
||||
.unwrap_or_else(|err| warn!("GFX: {}", err));
|
||||
Ok(msg)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_gfx(&self, vendor: &GfxVendors) -> zbus::Result<()> {}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_action(&self, action: &GfxRequiredUserAction) -> zbus::Result<()> {}
|
||||
}
|
||||
|
||||
impl ZbusAdd for CtrlGraphics {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(&ObjectPath::from_str_unchecked("/org/asuslinux/Gfx"), self)
|
||||
.map_err(|err| {
|
||||
warn!("GFX: CtrlGraphics: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
343
daemon/src/ctrl_leds/controller.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
// Only these two packets must be 17 bytes
|
||||
static KBD_BRIGHT_PATH: &str = "/sys/class/leds/asus::kbd_backlight/brightness";
|
||||
|
||||
use crate::{
|
||||
config_aura::AuraConfig,
|
||||
error::RogError,
|
||||
laptops::{LaptopLedData, ASUS_KEYBOARD_DEVICES},
|
||||
};
|
||||
use log::{info, warn};
|
||||
use rog_aura::{
|
||||
usb::{
|
||||
LED_APPLY, LED_AWAKE_OFF_SLEEP_OFF, LED_AWAKE_OFF_SLEEP_ON, LED_AWAKE_ON_SLEEP_OFF,
|
||||
LED_AWAKE_ON_SLEEP_ON, LED_SET,
|
||||
},
|
||||
AuraEffect, LedBrightness, LED_MSG_LEN,
|
||||
};
|
||||
use rog_types::supported::LedSupportedFunctions;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::GetSupported;
|
||||
|
||||
impl GetSupported for CtrlKbdLed {
|
||||
type A = LedSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
// let mode = <&str>::from(&<AuraModes>::from(*mode));
|
||||
let multizone_led_mode = false;
|
||||
let per_key_led_mode = false;
|
||||
let laptop = LaptopLedData::get_data();
|
||||
let stock_led_modes = laptop.standard;
|
||||
|
||||
LedSupportedFunctions {
|
||||
brightness_set: CtrlKbdLed::get_kbd_bright_path().is_some(),
|
||||
stock_led_modes,
|
||||
multizone_led_mode,
|
||||
per_key_led_mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlKbdLed {
|
||||
pub led_node: Option<String>,
|
||||
pub bright_node: String,
|
||||
pub supported_modes: LaptopLedData,
|
||||
pub flip_effect_write: bool,
|
||||
pub config: AuraConfig,
|
||||
}
|
||||
|
||||
pub struct CtrlKbdLedTask(pub Arc<Mutex<CtrlKbdLed>>);
|
||||
|
||||
impl crate::CtrlTask for CtrlKbdLedTask {
|
||||
fn do_task(&self) -> Result<(), RogError> {
|
||||
if let Ok(mut lock) = self.0.try_lock() {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&lock.bright_node)
|
||||
.map_err(|err| match err.kind() {
|
||||
std::io::ErrorKind::NotFound => {
|
||||
RogError::MissingLedBrightNode((&lock.bright_node).into(), err)
|
||||
}
|
||||
_ => RogError::Path((&lock.bright_node).into(), err),
|
||||
})?;
|
||||
let mut buf = [0u8; 1];
|
||||
file.read_exact(&mut buf)
|
||||
.map_err(|err| RogError::Read("buffer".into(), err))?;
|
||||
if let Some(num) = char::from(buf[0]).to_digit(10) {
|
||||
if lock.config.brightness != num.into() {
|
||||
lock.config.read();
|
||||
lock.config.brightness = num.into();
|
||||
lock.config.write();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
return Err(RogError::ParseLed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlKbdLedReloader(pub Arc<Mutex<CtrlKbdLed>>);
|
||||
|
||||
impl crate::Reloadable for CtrlKbdLedReloader {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
let current = ctrl.config.current_mode;
|
||||
if let Some(mode) = ctrl.config.builtins.get(¤t).cloned() {
|
||||
ctrl.do_command(mode).ok();
|
||||
}
|
||||
|
||||
ctrl.set_states_enabled(ctrl.config.awake_enabled, ctrl.config.sleep_anim_enabled)
|
||||
.map_err(|err| warn!("{}", err))
|
||||
.ok();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlKbdLedZbus(pub Arc<Mutex<CtrlKbdLed>>);
|
||||
|
||||
impl CtrlKbdLedZbus {
|
||||
pub fn new(inner: Arc<Mutex<CtrlKbdLed>>) -> Self {
|
||||
Self(inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlKbdLed {
|
||||
#[inline]
|
||||
pub fn new(supported_modes: LaptopLedData, config: AuraConfig) -> Result<Self, RogError> {
|
||||
// TODO: return error if *all* nodes are None
|
||||
let mut led_node = None;
|
||||
for prod in ASUS_KEYBOARD_DEVICES.iter() {
|
||||
match Self::find_led_node(prod) {
|
||||
Ok(node) => {
|
||||
led_node = Some(node);
|
||||
break;
|
||||
}
|
||||
Err(err) => warn!("led_node: {}", err),
|
||||
}
|
||||
}
|
||||
|
||||
let bright_node = Self::get_kbd_bright_path();
|
||||
|
||||
if led_node.is_none() && bright_node.is_none() {
|
||||
return Err(RogError::MissingFunction(
|
||||
"All keyboard features missing, you may require a v5.11 series kernel or newer"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
if bright_node.is_none() {
|
||||
return Err(RogError::MissingFunction(
|
||||
"No brightness control, you may require a v5.11 series kernel or newer".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let ctrl = CtrlKbdLed {
|
||||
led_node,
|
||||
bright_node: bright_node.unwrap(), // If was none then we already returned above
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
config,
|
||||
};
|
||||
Ok(ctrl)
|
||||
}
|
||||
|
||||
fn get_kbd_bright_path() -> Option<String> {
|
||||
if Path::new(KBD_BRIGHT_PATH).exists() {
|
||||
return Some(KBD_BRIGHT_PATH.to_string());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn get_brightness(&self) -> Result<u8, RogError> {
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(&self.bright_node)
|
||||
.map_err(|err| match err.kind() {
|
||||
std::io::ErrorKind::NotFound => {
|
||||
RogError::MissingLedBrightNode((&self.bright_node).into(), err)
|
||||
}
|
||||
_ => RogError::Path((&self.bright_node).into(), err),
|
||||
})?;
|
||||
let mut buf = [0u8; 1];
|
||||
file.read_exact(&mut buf)
|
||||
.map_err(|err| RogError::Read("buffer".into(), err))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
pub(super) fn set_brightness(&self, brightness: LedBrightness) -> Result<(), RogError> {
|
||||
let path = Path::new(&self.bright_node);
|
||||
let mut file =
|
||||
OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&path)
|
||||
.map_err(|err| match err.kind() {
|
||||
std::io::ErrorKind::NotFound => {
|
||||
RogError::MissingLedBrightNode((&self.bright_node).into(), err)
|
||||
}
|
||||
_ => RogError::Path((&self.bright_node).into(), err),
|
||||
})?;
|
||||
file.write_all(&[brightness.as_char_code()])
|
||||
.map_err(|err| RogError::Read("buffer".into(), err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set if awake/on LED active, and/or sleep animation active
|
||||
pub(super) fn set_states_enabled(&self, awake: bool, sleep: bool) -> Result<(), RogError> {
|
||||
let bytes = if awake && sleep {
|
||||
LED_AWAKE_ON_SLEEP_ON
|
||||
} else if awake && !sleep {
|
||||
LED_AWAKE_ON_SLEEP_OFF
|
||||
} else if !awake && sleep {
|
||||
LED_AWAKE_OFF_SLEEP_ON
|
||||
} else if !awake && !sleep {
|
||||
LED_AWAKE_OFF_SLEEP_OFF
|
||||
} else {
|
||||
LED_AWAKE_ON_SLEEP_ON
|
||||
};
|
||||
self.write_bytes(&bytes)?;
|
||||
self.write_bytes(&LED_SET)?;
|
||||
// Changes won't persist unless apply is set
|
||||
self.write_bytes(&LED_APPLY)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_led_node(id_product: &str) -> Result<String, RogError> {
|
||||
let mut enumerator = udev::Enumerator::new().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
RogError::Udev("enumerator failed".into(), err)
|
||||
})?;
|
||||
enumerator.match_subsystem("hidraw").map_err(|err| {
|
||||
warn!("{}", err);
|
||||
RogError::Udev("match_subsystem failed".into(), err)
|
||||
})?;
|
||||
|
||||
for device in enumerator.scan_devices().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
RogError::Udev("scan_devices failed".into(), err)
|
||||
})? {
|
||||
if let Some(parent) = device
|
||||
.parent_with_subsystem_devtype("usb", "usb_device")
|
||||
.map_err(|err| {
|
||||
warn!("{}", err);
|
||||
RogError::Udev("parent_with_subsystem_devtype failed".into(), err)
|
||||
})?
|
||||
{
|
||||
if parent
|
||||
.attribute_value("idProduct")
|
||||
.ok_or_else(|| RogError::NotFound("LED idProduct".into()))?
|
||||
== id_product
|
||||
{
|
||||
if let Some(dev_node) = device.devnode() {
|
||||
info!("Using device at: {:?} for LED control", dev_node);
|
||||
return Ok(dev_node.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(RogError::MissingFunction(
|
||||
"ASUS LED device node not found".into(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn do_command(&mut self, mode: AuraEffect) -> Result<(), RogError> {
|
||||
self.set_and_save(mode)
|
||||
}
|
||||
|
||||
/// Should only be used if the bytes you are writing are verified correct
|
||||
#[inline]
|
||||
fn write_bytes(&self, message: &[u8]) -> Result<(), RogError> {
|
||||
if let Some(led_node) = &self.led_node {
|
||||
if let Ok(mut file) = OpenOptions::new().write(true).open(led_node) {
|
||||
// println!("write: {:02x?}", &message);
|
||||
return file
|
||||
.write_all(message)
|
||||
.map_err(|err| RogError::Write("write_bytes".into(), err));
|
||||
}
|
||||
}
|
||||
Err(RogError::NotSupported)
|
||||
}
|
||||
|
||||
/// Write an effect block
|
||||
#[inline]
|
||||
fn _write_effect(&mut self, effect: &[Vec<u8>]) -> Result<(), RogError> {
|
||||
if self.flip_effect_write {
|
||||
for row in effect.iter().rev() {
|
||||
self.write_bytes(row)?;
|
||||
}
|
||||
} else {
|
||||
for row in effect.iter() {
|
||||
self.write_bytes(row)?;
|
||||
}
|
||||
}
|
||||
self.flip_effect_write = !self.flip_effect_write;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Used to set a builtin mode and save the settings for it
|
||||
///
|
||||
/// This needs to be universal so that settings applied by dbus stick
|
||||
#[inline]
|
||||
fn set_and_save(&mut self, mode: AuraEffect) -> Result<(), RogError> {
|
||||
self.config.read();
|
||||
self.write_mode(&mode)?;
|
||||
self.config.current_mode = *mode.mode();
|
||||
self.config.set_builtin(mode);
|
||||
self.config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn toggle_mode(&mut self, reverse: bool) -> Result<(), RogError> {
|
||||
let current = self.config.current_mode;
|
||||
if let Some(idx) = self
|
||||
.supported_modes
|
||||
.standard
|
||||
.iter()
|
||||
.position(|v| *v == current)
|
||||
{
|
||||
let mut idx = idx;
|
||||
// goes past end of array
|
||||
if reverse {
|
||||
if idx == 0 {
|
||||
idx = self.supported_modes.standard.len() - 1;
|
||||
} else {
|
||||
idx -= 1;
|
||||
}
|
||||
} else {
|
||||
idx += 1;
|
||||
if idx == self.supported_modes.standard.len() {
|
||||
idx = 0;
|
||||
}
|
||||
}
|
||||
let next = self.supported_modes.standard[idx];
|
||||
|
||||
self.config.read();
|
||||
if let Some(data) = self.config.builtins.get(&next) {
|
||||
self.write_mode(&data)?;
|
||||
self.config.current_mode = next;
|
||||
}
|
||||
self.config.write();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_mode(&self, mode: &AuraEffect) -> Result<(), RogError> {
|
||||
if !self.supported_modes.standard.contains(&mode.mode()) {
|
||||
return Err(RogError::NotSupported);
|
||||
}
|
||||
let bytes: [u8; LED_MSG_LEN] = mode.into();
|
||||
self.write_bytes(&bytes)?;
|
||||
self.write_bytes(&LED_SET)?;
|
||||
// Changes won't persist unless apply is set
|
||||
self.write_bytes(&LED_APPLY)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
2
daemon/src/ctrl_leds/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod controller;
|
||||
pub mod zbus;
|
||||
165
daemon/src/ctrl_leds/zbus.rs
Normal file
@@ -0,0 +1,165 @@
|
||||
use log::{error, warn};
|
||||
use rog_aura::{AuraEffect, LedBrightness, LedPowerStates};
|
||||
use zbus::dbus_interface;
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
use super::controller::CtrlKbdLedZbus;
|
||||
|
||||
impl crate::ZbusAdd for CtrlKbdLedZbus {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(&ObjectPath::from_str_unchecked("/org/asuslinux/Led"), self)
|
||||
.map_err(|err| {
|
||||
error!("DbusKbdLed: add_to_server {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// The main interface for changing, reading, or notfying signals
|
||||
///
|
||||
/// LED commands are split between Brightness, Modes, Per-Key
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlKbdLedZbus {
|
||||
/// Set the keyboard brightness level (0-3)
|
||||
fn set_brightness(&mut self, brightness: LedBrightness) {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
ctrl.set_brightness(brightness)
|
||||
.map_err(|err| warn!("{}", err))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the keyboard LED to enabled while the device is awake
|
||||
fn set_awake_enabled(&mut self, enabled: bool) {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
ctrl.set_states_enabled(enabled, ctrl.config.sleep_anim_enabled)
|
||||
.map_err(|err| warn!("{}", err))
|
||||
.ok();
|
||||
ctrl.config.awake_enabled = enabled;
|
||||
ctrl.config.write();
|
||||
|
||||
let states = LedPowerStates {
|
||||
enabled: ctrl.config.awake_enabled,
|
||||
sleep_anim_enabled: ctrl.config.sleep_anim_enabled,
|
||||
};
|
||||
self.notify_power_states(&states)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the keyboard LED suspend animation to enabled while the device is suspended
|
||||
fn set_sleep_enabled(&mut self, enabled: bool) {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
ctrl.set_states_enabled(ctrl.config.awake_enabled, enabled)
|
||||
.map_err(|err| warn!("{}", err))
|
||||
.ok();
|
||||
ctrl.config.sleep_anim_enabled = enabled;
|
||||
ctrl.config.write();
|
||||
let states = LedPowerStates {
|
||||
enabled: ctrl.config.awake_enabled,
|
||||
sleep_anim_enabled: ctrl.config.sleep_anim_enabled,
|
||||
};
|
||||
self.notify_power_states(&states)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
|
||||
fn set_led_mode(&mut self, effect: AuraEffect) {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
match ctrl.do_command(effect) {
|
||||
Ok(_) => {
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
self.notify_led(mode.clone())
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn next_led_mode(&self) {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
ctrl.toggle_mode(false)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
self.notify_led(mode.clone())
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prev_led_mode(&self) {
|
||||
if let Ok(mut ctrl) = self.0.try_lock() {
|
||||
ctrl.toggle_mode(true)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
self.notify_led(mode.clone())
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(property)]
|
||||
fn awake_enabled(&self) -> bool {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
return ctrl.config.awake_enabled;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[dbus_interface(property)]
|
||||
fn sleep_enabled(&self) -> bool {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
return ctrl.config.sleep_anim_enabled;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Return the current mode data
|
||||
#[dbus_interface(property)]
|
||||
fn led_mode(&self) -> String {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
if let Ok(json) = serde_json::to_string(&mode) {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!("SetKeyBacklight could not deserialise");
|
||||
"SetKeyBacklight could not deserialise".to_string()
|
||||
}
|
||||
|
||||
/// Return a list of available modes
|
||||
#[dbus_interface(property)]
|
||||
fn led_modes(&self) -> String {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
if let Ok(json) = serde_json::to_string(&ctrl.config.builtins) {
|
||||
return json;
|
||||
}
|
||||
}
|
||||
warn!("SetKeyBacklight could not deserialise");
|
||||
"SetKeyBacklight could not serialise".to_string()
|
||||
}
|
||||
|
||||
/// Return the current LED brightness
|
||||
#[dbus_interface(property)]
|
||||
fn led_brightness(&self) -> i8 {
|
||||
if let Ok(ctrl) = self.0.try_lock() {
|
||||
return ctrl.get_brightness().map(|n| n as i8).unwrap_or(-1);
|
||||
}
|
||||
warn!("SetKeyBacklight could not serialise");
|
||||
-1
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_led(&self, data: AuraEffect) -> zbus::Result<()>;
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_power_states(&self, data: &LedPowerStates) -> zbus::Result<()>;
|
||||
}
|
||||
100
daemon/src/ctrl_profiles/controller.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use crate::error::RogError;
|
||||
use crate::{config::Config, GetSupported};
|
||||
use log::info;
|
||||
use rog_profiles::profiles::Profile;
|
||||
use rog_types::supported::FanCpuSupportedFunctions;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub struct CtrlFanAndCpu {
|
||||
pub config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
impl GetSupported for CtrlFanAndCpu {
|
||||
type A = FanCpuSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
FanCpuSupportedFunctions {
|
||||
stock_fan_modes: Profile::get_fan_path().is_ok(),
|
||||
min_max_freq: Profile::get_intel_supported(),
|
||||
fan_curve_set: rog_fan_curve::Board::from_board_name().is_some(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlFanAndCpu {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Ok(mut cfg) = self.config.clone().try_lock() {
|
||||
let active = cfg.active_profile.clone();
|
||||
if let Some(existing) = cfg.power_profiles.get_mut(&active) {
|
||||
existing.set_system_all()?;
|
||||
cfg.write();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlFanAndCpu {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
Profile::get_fan_path()?;
|
||||
info!("Device has thermal throttle control");
|
||||
Ok(CtrlFanAndCpu { config })
|
||||
}
|
||||
|
||||
/// Toggle to next profile in list
|
||||
pub(super) fn do_next_profile(&mut self, config: &mut Config) -> Result<(), RogError> {
|
||||
config.read();
|
||||
|
||||
let mut i = config
|
||||
.toggle_profiles
|
||||
.iter()
|
||||
.position(|x| x == &config.active_profile)
|
||||
.map(|i| i + 1)
|
||||
.unwrap_or(0);
|
||||
if i >= config.toggle_profiles.len() {
|
||||
i = 0;
|
||||
}
|
||||
|
||||
let new_profile = config
|
||||
.toggle_profiles
|
||||
.get(i)
|
||||
.unwrap_or(&config.active_profile)
|
||||
.clone();
|
||||
|
||||
self.set_active(&new_profile)?;
|
||||
|
||||
info!("Profile was changed: {}", &new_profile);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn set_active(&mut self, profile: &str) -> Result<(), RogError> {
|
||||
if let Ok(mut cfg) = self.config.clone().try_lock() {
|
||||
cfg.read();
|
||||
|
||||
if let Some(existing) = cfg.power_profiles.get_mut(profile) {
|
||||
existing.set_system_all()?;
|
||||
cfg.active_profile = existing.name.clone();
|
||||
cfg.write();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn new_or_modify(&mut self, profile: &Profile) -> Result<(), RogError> {
|
||||
if let Ok(mut cfg) = self.config.clone().try_lock() {
|
||||
cfg.read();
|
||||
|
||||
if let Some(existing) = cfg.power_profiles.get_mut(&profile.name) {
|
||||
*existing = profile.clone();
|
||||
existing.set_system_all()?;
|
||||
} else {
|
||||
cfg.power_profiles
|
||||
.insert(profile.name.clone(), profile.clone());
|
||||
}
|
||||
cfg.active_profile = profile.name.clone();
|
||||
cfg.write();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
3
daemon/src/ctrl_profiles/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod zbus;
|
||||
|
||||
pub mod controller;
|
||||
170
daemon/src/ctrl_profiles/zbus.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
use log::warn;
|
||||
use rog_profiles::profiles::Profile;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use zbus::{dbus_interface, fdo::Error};
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
use super::controller::CtrlFanAndCpu;
|
||||
|
||||
pub struct FanAndCpuZbus {
|
||||
inner: Arc<Mutex<CtrlFanAndCpu>>,
|
||||
}
|
||||
|
||||
impl FanAndCpuZbus {
|
||||
pub fn new(inner: Arc<Mutex<CtrlFanAndCpu>>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl FanAndCpuZbus {
|
||||
/// Create new profile and make active
|
||||
fn set_profile(&self, profile: String) {
|
||||
if let Ok(mut ctrl) = self.inner.try_lock() {
|
||||
ctrl.set_active(&profile)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
// Do notification
|
||||
if let Ok(cfg) = ctrl.config.clone().try_lock() {
|
||||
// Do notify
|
||||
if let Some(profile) = cfg.power_profiles.get(&cfg.active_profile) {
|
||||
self.notify_profile(&profile)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// New or modify profile details and make active, will create if it does not exist
|
||||
fn new_or_modify(&self, profile: Profile) {
|
||||
if let Ok(mut ctrl) = self.inner.try_lock() {
|
||||
ctrl.new_or_modify(&profile)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
// Do notification
|
||||
if let Ok(cfg) = ctrl.config.clone().try_lock() {
|
||||
// Do notify
|
||||
if let Some(profile) = cfg.power_profiles.get(&cfg.active_profile) {
|
||||
self.notify_profile(&profile)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the active profile name
|
||||
fn next_profile(&mut self) {
|
||||
if let Ok(mut ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.clone().try_lock() {
|
||||
cfg.read();
|
||||
ctrl.do_next_profile(&mut cfg)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
if let Some(profile) = cfg.power_profiles.get(&cfg.active_profile) {
|
||||
self.notify_profile(&profile)
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the active profile name
|
||||
fn active_name(&mut self) -> zbus::fdo::Result<String> {
|
||||
if let Ok(ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.try_lock() {
|
||||
cfg.read();
|
||||
return Ok(cfg.active_profile.clone());
|
||||
}
|
||||
}
|
||||
Err(Error::Failed(
|
||||
"Failed to get active profile name".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
// TODO: Profile can't implement Type because of Curve
|
||||
/// Fetch the active profile details
|
||||
fn active_data(&mut self) -> zbus::fdo::Result<Profile> {
|
||||
if let Ok(ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.try_lock() {
|
||||
cfg.read();
|
||||
if let Some(profile) = cfg.power_profiles.get(&cfg.active_profile) {
|
||||
return Ok(profile.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error::Failed(
|
||||
"Failed to get active profile details".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Fetch all profile data
|
||||
fn profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
|
||||
if let Ok(ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.try_lock() {
|
||||
cfg.read();
|
||||
return Ok(cfg.power_profiles.values().cloned().collect());
|
||||
}
|
||||
}
|
||||
Err(Error::Failed(
|
||||
"Failed to get all profile details".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn profile_names(&self) -> zbus::fdo::Result<Vec<String>> {
|
||||
if let Ok(ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.try_lock() {
|
||||
cfg.read();
|
||||
let profile_names = cfg.power_profiles.keys().cloned().collect::<Vec<String>>();
|
||||
return Ok(profile_names);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Failed("Failed to get all profile names".to_string()))
|
||||
}
|
||||
|
||||
fn remove(&self, profile: &str) -> zbus::fdo::Result<()> {
|
||||
if let Ok(ctrl) = self.inner.try_lock() {
|
||||
if let Ok(mut cfg) = ctrl.config.try_lock() {
|
||||
cfg.read();
|
||||
|
||||
if !cfg.power_profiles.contains_key(profile) {
|
||||
return Err(Error::Failed("Invalid profile specified".to_string()));
|
||||
}
|
||||
|
||||
if cfg.power_profiles.keys().len() == 1 {
|
||||
return Err(Error::Failed("Cannot delete the last profile".to_string()));
|
||||
}
|
||||
|
||||
if cfg.active_profile == *profile {
|
||||
return Err(Error::Failed(
|
||||
"Cannot delete the active profile".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
cfg.power_profiles.remove(profile);
|
||||
cfg.write();
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::Failed("Failed to lock configuration".to_string()))
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
fn notify_profile(&self, profile: &Profile) -> zbus::Result<()> {}
|
||||
}
|
||||
|
||||
impl crate::ZbusAdd for FanAndCpuZbus {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Profile"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("DbusFanAndCpu: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
340
daemon/src/ctrl_rog_bios.rs
Normal file
@@ -0,0 +1,340 @@
|
||||
use crate::{config::Config, error::RogError, GetSupported};
|
||||
use log::{error, info, warn};
|
||||
use rog_types::supported::RogBiosSupportedFunctions;
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::BufRead;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use zbus::dbus_interface;
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
const INITRAMFS_PATH: &str = "/usr/sbin/update-initramfs";
|
||||
const DRACUT_PATH: &str = "/usr/bin/dracut";
|
||||
|
||||
static ASUS_SWITCH_GRAPHIC_MODE: &str =
|
||||
"/sys/firmware/efi/efivars/AsusSwitchGraphicMode-607005d5-3f75-4b2e-98f0-85ba66797a3e";
|
||||
static ASUS_POST_LOGO_SOUND: &str =
|
||||
"/sys/firmware/efi/efivars/AsusPostLogoSound-607005d5-3f75-4b2e-98f0-85ba66797a3e";
|
||||
|
||||
pub struct CtrlRogBios {
|
||||
_config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
impl GetSupported for CtrlRogBios {
|
||||
type A = RogBiosSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
RogBiosSupportedFunctions {
|
||||
post_sound_toggle: CtrlRogBios::check_path_exists(ASUS_POST_LOGO_SOUND).is_ok(),
|
||||
dedicated_gfx_toggle: CtrlRogBios::check_path_exists(ASUS_SWITCH_GRAPHIC_MODE).is_ok(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlRogBios {
|
||||
pub fn set_dedicated_graphic_mode(&mut self, dedicated: bool) {
|
||||
self.set_gfx_mode(dedicated)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: set_asus_switch_graphic_mode {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
self.notify_dedicated_graphic_mode(dedicated)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: notify_asus_switch_graphic_mode {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
pub fn dedicated_graphic_mode(&self) -> i8 {
|
||||
Self::get_gfx_mode()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: get_gfx_mode {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
pub fn notify_dedicated_graphic_mode(&self, dedicated: bool) -> zbus::Result<()> {}
|
||||
|
||||
// // // // // // // // // //
|
||||
|
||||
pub fn set_post_boot_sound(&mut self, on: bool) {
|
||||
Self::set_boot_sound(on)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: set_post_boot_sound {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
self.notify_post_boot_sound(on)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: notify_post_boot_sound {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
|
||||
pub fn post_boot_sound(&self) -> i8 {
|
||||
Self::get_boot_sound()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: get_boot_sound {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(-1)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
pub fn notify_post_boot_sound(&self, dedicated: bool) -> zbus::Result<()> {}
|
||||
}
|
||||
|
||||
impl crate::ZbusAdd for CtrlRogBios {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/RogBios"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlRogBios {
|
||||
fn reload(&mut self) -> Result<(), RogError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlRogBios {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
match CtrlRogBios::check_path_exists(ASUS_SWITCH_GRAPHIC_MODE) {
|
||||
Ok(_) => {
|
||||
CtrlRogBios::set_path_mutable(ASUS_SWITCH_GRAPHIC_MODE)?;
|
||||
}
|
||||
Err(err) => {
|
||||
info!("ROG Switchable Graphics (bios) not detected: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlRogBios::check_path_exists(ASUS_POST_LOGO_SOUND) {
|
||||
Ok(_) => {
|
||||
CtrlRogBios::set_path_mutable(ASUS_POST_LOGO_SOUND)?;
|
||||
}
|
||||
Err(err) => {
|
||||
info!("ROG boot sound toggle (bios) not detected: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(CtrlRogBios { _config: config })
|
||||
}
|
||||
|
||||
fn set_path_mutable(path: &str) -> Result<(), RogError> {
|
||||
let output = Command::new("/usr/bin/chattr")
|
||||
.arg("-i")
|
||||
.arg(path)
|
||||
.output()
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
info!("Set {} writeable: status: {}", path, output.status);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_path_exists(path: &str) -> Result<(), RogError> {
|
||||
if Path::new(path).exists() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RogError::MissingFunction(path.into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_dedicated_gfx_toggle() -> bool {
|
||||
if CtrlRogBios::check_path_exists(ASUS_SWITCH_GRAPHIC_MODE).is_ok() {
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn get_gfx_mode() -> Result<i8, RogError> {
|
||||
let path = ASUS_SWITCH_GRAPHIC_MODE;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(path)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
let mut data = Vec::new();
|
||||
file.read_to_end(&mut data)
|
||||
.map_err(|err| RogError::Read(path.into(), err))?;
|
||||
|
||||
let idx = data.len() - 1;
|
||||
Ok(data[idx] as i8)
|
||||
}
|
||||
|
||||
pub(super) fn set_gfx_mode(&self, dedicated: bool) -> Result<(), RogError> {
|
||||
let path = ASUS_SWITCH_GRAPHIC_MODE;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
let mut data = Vec::new();
|
||||
file.read_to_end(&mut data).unwrap();
|
||||
|
||||
let idx = data.len() - 1;
|
||||
if dedicated {
|
||||
data[idx] = 1;
|
||||
info!("Set system-level graphics mode: Dedicated Nvidia");
|
||||
} else {
|
||||
data[idx] = 0;
|
||||
info!("Set system-level graphics mode: Optimus");
|
||||
}
|
||||
file.write_all(&data)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
self.update_initramfs(dedicated)?;
|
||||
|
||||
// if let Ok(ded) = CtrlRogBios::get_gfx_mode() {
|
||||
// if let Ok(vendor) = CtrlGraphics::get_vendor() {
|
||||
// if ded == 1 && vendor != "nvidia" {
|
||||
// warn!("Dedicated GFX toggle is on but driver mode is not nvidia \nSetting to nvidia driver mode");
|
||||
// CtrlGraphics::set_gfx_config(&GfxVendors::Nvidia)
|
||||
// .unwrap_or_else(|err| warn!("Gfx controller: {}", err));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_boot_sound() -> Result<i8, RogError> {
|
||||
let path = ASUS_POST_LOGO_SOUND;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.open(path)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
let mut data = Vec::new();
|
||||
file.read_to_end(&mut data)
|
||||
.map_err(|err| RogError::Read(path.into(), err))?;
|
||||
|
||||
let idx = data.len() - 1;
|
||||
Ok(data[idx] as i8)
|
||||
}
|
||||
|
||||
pub(super) fn set_boot_sound(on: bool) -> Result<(), RogError> {
|
||||
let path = ASUS_POST_LOGO_SOUND;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
let mut data = Vec::new();
|
||||
file.read_to_end(&mut data)
|
||||
.map_err(|err| RogError::Read(path.into(), err))?;
|
||||
|
||||
let idx = data.len() - 1;
|
||||
if on {
|
||||
data[idx] = 1;
|
||||
info!("Set boot POST sound on");
|
||||
} else {
|
||||
data[idx] = 0;
|
||||
info!("Set boot POST sound off");
|
||||
}
|
||||
file.write_all(&data)
|
||||
.map_err(|err| RogError::Path(path.into(), err))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// required for g-sync mode
|
||||
fn update_initramfs(&self, dedicated: bool) -> Result<(), RogError> {
|
||||
let mut initfs_cmd = None;
|
||||
|
||||
if Path::new(INITRAMFS_PATH).exists() {
|
||||
let mut cmd = Command::new("update-initramfs");
|
||||
cmd.arg("-u");
|
||||
initfs_cmd = Some(cmd);
|
||||
info!("Using initramfs update command 'update-initramfs'");
|
||||
} else if Path::new(DRACUT_PATH).exists() {
|
||||
let mut cmd = Command::new("dracut");
|
||||
cmd.arg("-f");
|
||||
cmd.arg("-q");
|
||||
initfs_cmd = Some(cmd);
|
||||
info!("Using initramfs update command 'dracut'");
|
||||
}
|
||||
|
||||
if let Some(mut cmd) = initfs_cmd {
|
||||
info!("Updating initramfs");
|
||||
|
||||
// If switching to Nvidia dedicated we need these modules included
|
||||
if Path::new(DRACUT_PATH).exists() && dedicated {
|
||||
cmd.arg("--add-drivers");
|
||||
cmd.arg("nvidia nvidia-drm nvidia-modeset nvidia-uvm");
|
||||
info!("System uses dracut, forcing nvidia modules to be included in init");
|
||||
} else if Path::new(INITRAMFS_PATH).exists() {
|
||||
let modules = vec![
|
||||
"nvidia\n",
|
||||
"nvidia-drm\n",
|
||||
"nvidia-modeset\n",
|
||||
"nvidia-uvm\n",
|
||||
];
|
||||
|
||||
let module_include = Path::new("/etc/initramfs-tools/modules");
|
||||
|
||||
if dedicated {
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open(module_include)
|
||||
.map_err(|err| {
|
||||
RogError::Write(module_include.to_string_lossy().to_string(), err)
|
||||
})?;
|
||||
// add nvidia modules to module_include
|
||||
file.write_all(modules.concat().as_bytes()).unwrap();
|
||||
} else {
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.open(module_include)
|
||||
.map_err(|err| {
|
||||
RogError::Write(module_include.to_string_lossy().to_string(), err)
|
||||
})?;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
// remove modules
|
||||
for line in std::io::BufReader::new(file).lines().flatten() {
|
||||
if !modules.contains(&line.as_str()) {
|
||||
buf.append(&mut line.as_bytes().to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(module_include)
|
||||
.map_err(|err| {
|
||||
RogError::Write(module_include.to_string_lossy().to_string(), err)
|
||||
})?;
|
||||
std::io::BufWriter::new(file).write_all(&buf).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
let status = cmd
|
||||
.status()
|
||||
.map_err(|err| RogError::Write(format!("{:?}", cmd), err))?;
|
||||
if !status.success() {
|
||||
error!("Ram disk update failed");
|
||||
return Err(RogError::Initramfs("Ram disk update failed".into()));
|
||||
} else {
|
||||
info!("Successfully updated initramfs");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
60
daemon/src/ctrl_supported.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use log::warn;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use zbus::dbus_interface;
|
||||
use zvariant::ObjectPath;
|
||||
use zvariant_derive::Type;
|
||||
|
||||
use crate::{
|
||||
ctrl_anime::CtrlAnime, ctrl_charge::CtrlCharge, ctrl_leds::controller::CtrlKbdLed,
|
||||
ctrl_profiles::controller::CtrlFanAndCpu, ctrl_rog_bios::CtrlRogBios, GetSupported,
|
||||
};
|
||||
|
||||
use rog_types::supported::{
|
||||
AnimeSupportedFunctions, ChargeSupportedFunctions, FanCpuSupportedFunctions,
|
||||
LedSupportedFunctions, RogBiosSupportedFunctions,
|
||||
};
|
||||
|
||||
#[derive(Serialize, Deserialize, Type)]
|
||||
pub struct SupportedFunctions {
|
||||
pub anime_ctrl: AnimeSupportedFunctions,
|
||||
pub charge_ctrl: ChargeSupportedFunctions,
|
||||
pub fan_cpu_ctrl: FanCpuSupportedFunctions,
|
||||
pub keyboard_led: LedSupportedFunctions,
|
||||
pub rog_bios_ctrl: RogBiosSupportedFunctions,
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl SupportedFunctions {
|
||||
fn supported_functions(&self) -> &SupportedFunctions {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ZbusAdd for SupportedFunctions {
|
||||
fn add_to_server(self, server: &mut zbus::ObjectServer) {
|
||||
server
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Supported"),
|
||||
self,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("SupportedFunctions: add_to_server {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
impl GetSupported for SupportedFunctions {
|
||||
type A = SupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
SupportedFunctions {
|
||||
anime_ctrl: CtrlAnime::get_supported(),
|
||||
keyboard_led: CtrlKbdLed::get_supported(),
|
||||
charge_ctrl: CtrlCharge::get_supported(),
|
||||
fan_cpu_ctrl: CtrlFanAndCpu::get_supported(),
|
||||
rog_bios_ctrl: CtrlRogBios::get_supported(),
|
||||
}
|
||||
}
|
||||
}
|
||||
228
daemon/src/daemon.rs
Normal file
@@ -0,0 +1,228 @@
|
||||
use daemon::ctrl_leds::controller::{
|
||||
CtrlKbdLed, CtrlKbdLedReloader, CtrlKbdLedTask, CtrlKbdLedZbus,
|
||||
};
|
||||
use daemon::{
|
||||
config::Config, ctrl_supported::SupportedFunctions, laptops::print_board_info, GetSupported,
|
||||
};
|
||||
use daemon::{config_anime::AnimeConfig, config_aura::AuraConfig, ctrl_charge::CtrlCharge};
|
||||
use daemon::{ctrl_anime::*, ctrl_gfx::controller::CtrlGraphics};
|
||||
use daemon::{
|
||||
ctrl_profiles::{controller::CtrlFanAndCpu, zbus::FanAndCpuZbus},
|
||||
laptops::LaptopLedData,
|
||||
};
|
||||
|
||||
use daemon::{CtrlTask, Reloadable, ZbusAdd};
|
||||
use log::LevelFilter;
|
||||
use log::{error, info, warn};
|
||||
use rog_dbus::DBUS_NAME;
|
||||
use rog_types::gfx_vendors::GfxVendors;
|
||||
use std::error::Error;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use daemon::ctrl_rog_bios::CtrlRogBios;
|
||||
use std::convert::Into;
|
||||
use zbus::fdo;
|
||||
use zbus::Connection;
|
||||
use zvariant::ObjectPath;
|
||||
|
||||
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut logger = env_logger::Builder::new();
|
||||
logger
|
||||
.target(env_logger::Target::Stdout)
|
||||
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
|
||||
.filter(None, LevelFilter::Info)
|
||||
.init();
|
||||
|
||||
info!(" daemon v{}", daemon::VERSION);
|
||||
info!(" rog-anime v{}", rog_anime::VERSION);
|
||||
info!(" rog-aura v{}", rog_aura::VERSION);
|
||||
info!(" rog-dbus v{}", rog_dbus::VERSION);
|
||||
info!("rog-profiles v{}", rog_profiles::VERSION);
|
||||
info!(" rog-types v{}", rog_types::VERSION);
|
||||
|
||||
start_daemon()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The actual main loop for the daemon
|
||||
fn start_daemon() -> Result<(), Box<dyn Error>> {
|
||||
let supported = SupportedFunctions::get_supported();
|
||||
print_board_info();
|
||||
println!("{}", serde_json::to_string_pretty(&supported).unwrap());
|
||||
|
||||
// Collect tasks for task thread
|
||||
let mut tasks: Vec<Box<dyn CtrlTask + Send>> = Vec::new();
|
||||
// Start zbus server
|
||||
let connection = Connection::new_system()?;
|
||||
fdo::DBusProxy::new(&connection)?
|
||||
.request_name(DBUS_NAME, fdo::RequestNameFlags::ReplaceExisting.into())?;
|
||||
let mut object_server = zbus::ObjectServer::new(&connection);
|
||||
|
||||
let config = Config::load();
|
||||
let enable_gfx_switching = config.gfx_managed;
|
||||
let config = Arc::new(Mutex::new(config));
|
||||
|
||||
supported.add_to_server(&mut object_server);
|
||||
|
||||
match CtrlRogBios::new(config.clone()) {
|
||||
Ok(mut ctrl) => {
|
||||
// Do a reload of any settings
|
||||
ctrl.reload()
|
||||
.unwrap_or_else(|err| warn!("Battery charge limit: {}", err));
|
||||
// Then register to dbus server
|
||||
ctrl.add_to_server(&mut object_server);
|
||||
}
|
||||
Err(err) => {
|
||||
error!("rog_bios_control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlCharge::new(config.clone()) {
|
||||
Ok(mut ctrl) => {
|
||||
// Do a reload of any settings
|
||||
ctrl.reload()
|
||||
.unwrap_or_else(|err| warn!("Battery charge limit: {}", err));
|
||||
// Then register to dbus server
|
||||
ctrl.add_to_server(&mut object_server);
|
||||
}
|
||||
Err(err) => {
|
||||
error!("charge_control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlFanAndCpu::new(config.clone()) {
|
||||
Ok(mut ctrl) => {
|
||||
ctrl.reload()
|
||||
.unwrap_or_else(|err| warn!("Profile control: {}", err));
|
||||
let tmp = Arc::new(Mutex::new(ctrl));
|
||||
FanAndCpuZbus::new(tmp).add_to_server(&mut object_server);
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Profile control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlAnime::new(AnimeConfig::load()) {
|
||||
Ok(ctrl) => {
|
||||
let inner = Arc::new(Mutex::new(ctrl));
|
||||
|
||||
let mut reload = CtrlAnimeReloader(inner.clone());
|
||||
reload
|
||||
.reload()
|
||||
.unwrap_or_else(|err| warn!("AniMe: {}", err));
|
||||
|
||||
let zbus = CtrlAnimeZbus(inner.clone());
|
||||
zbus.add_to_server(&mut object_server);
|
||||
|
||||
tasks.push(Box::new(CtrlAnimeTask::new(inner)));
|
||||
}
|
||||
Err(err) => {
|
||||
error!("AniMe control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let laptop = LaptopLedData::get_data();
|
||||
let aura_config = AuraConfig::load(&laptop);
|
||||
match CtrlKbdLed::new(laptop, aura_config) {
|
||||
Ok(ctrl) => {
|
||||
let inner = Arc::new(Mutex::new(ctrl));
|
||||
|
||||
let mut reload = CtrlKbdLedReloader(inner.clone());
|
||||
reload
|
||||
.reload()
|
||||
.unwrap_or_else(|err| warn!("Keyboard LED control: {}", err));
|
||||
|
||||
CtrlKbdLedZbus::new(inner.clone()).add_to_server(&mut object_server);
|
||||
let task = CtrlKbdLedTask(inner);
|
||||
tasks.push(Box::new(task));
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Keyboard control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Graphics switching requires some checks on boot specifically for g-sync capable laptops
|
||||
if enable_gfx_switching {
|
||||
match CtrlGraphics::new(config.clone()) {
|
||||
Ok(mut ctrl) => {
|
||||
// Need to check if a laptop has the dedicated gfx switch
|
||||
if CtrlRogBios::has_dedicated_gfx_toggle() {
|
||||
if let Ok(ded) = CtrlRogBios::get_gfx_mode() {
|
||||
if let Ok(config) = config.lock() {
|
||||
if ded == 1 {
|
||||
warn!("Dedicated GFX toggle is on but driver mode is not nvidia \nSetting to nvidia driver mode");
|
||||
let devices = ctrl.devices();
|
||||
let bus = ctrl.bus();
|
||||
CtrlGraphics::do_vendor_tasks(
|
||||
GfxVendors::Nvidia,
|
||||
false,
|
||||
&devices,
|
||||
&bus,
|
||||
)?;
|
||||
} else if ded == 0 {
|
||||
info!("Dedicated GFX toggle is off");
|
||||
let devices = ctrl.devices();
|
||||
let bus = ctrl.bus();
|
||||
CtrlGraphics::do_vendor_tasks(
|
||||
config.gfx_mode,
|
||||
false,
|
||||
&devices,
|
||||
&bus,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ctrl.reload()
|
||||
.unwrap_or_else(|err| error!("Gfx controller: {}", err));
|
||||
ctrl.add_to_server(&mut object_server);
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Gfx control: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: implement messaging between threads to check fails
|
||||
|
||||
// Run tasks
|
||||
let handle = std::thread::Builder::new()
|
||||
.name("asusd watch".to_string())
|
||||
.spawn(move || loop {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
|
||||
for ctrl in tasks.iter() {
|
||||
ctrl.do_task()
|
||||
.map_err(|err| {
|
||||
warn!("do_task error: {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
});
|
||||
|
||||
// Run zbus server
|
||||
object_server
|
||||
.with(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Charge"),
|
||||
|obj: &CtrlCharge| {
|
||||
let x = obj.limit();
|
||||
obj.notify_charge(x as u8)
|
||||
},
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("object_server notify_charge error: {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
// Loop to check errors and iterate zbus server
|
||||
loop {
|
||||
if let Err(err) = &handle {
|
||||
error!("{}", err);
|
||||
}
|
||||
if let Err(err) = object_server.try_handle_next() {
|
||||
error!("{}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
105
daemon/src/error.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use rog_fan_curve::CurveError;
|
||||
use rog_profiles::error::ProfileError;
|
||||
use rog_types::error::GraphicsError;
|
||||
use std::convert::From;
|
||||
use std::fmt;
|
||||
|
||||
use crate::ctrl_gfx::error::GfxError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RogError {
|
||||
ParseFanLevel,
|
||||
ParseVendor,
|
||||
ParseLed,
|
||||
MissingProfile(String),
|
||||
Udev(String, std::io::Error),
|
||||
Path(String, std::io::Error),
|
||||
Read(String, std::io::Error),
|
||||
Write(String, std::io::Error),
|
||||
NotSupported,
|
||||
NotFound(String),
|
||||
FanCurve(CurveError),
|
||||
DoTask(String),
|
||||
MissingFunction(String),
|
||||
MissingLedBrightNode(String, std::io::Error),
|
||||
ReloadFail(String),
|
||||
GfxSwitching(GfxError),
|
||||
Profiles(ProfileError),
|
||||
Initramfs(String),
|
||||
Modprobe(String),
|
||||
Command(String, std::io::Error),
|
||||
Io(std::io::Error),
|
||||
Zbus(zbus::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for RogError {
|
||||
// This trait requires `fmt` with this exact signature.
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
RogError::ParseFanLevel => write!(f, "Parse profile error"),
|
||||
RogError::ParseVendor => write!(f, "Parse gfx vendor error"),
|
||||
RogError::ParseLed => write!(f, "Parse LED error"),
|
||||
RogError::MissingProfile(profile) => write!(f, "Profile does not exist {}", profile),
|
||||
RogError::Udev(deets, error) => write!(f, "udev {}: {}", deets, error),
|
||||
RogError::Path(path, error) => write!(f, "Path {}: {}", path, error),
|
||||
RogError::Read(path, error) => write!(f, "Read {}: {}", path, error),
|
||||
RogError::Write(path, error) => write!(f, "Write {}: {}", path, error),
|
||||
RogError::NotSupported => write!(f, "Not supported"),
|
||||
RogError::NotFound(deets) => write!(f, "Not found: {}", deets),
|
||||
RogError::FanCurve(err) => write!(f, "Custom fan-curve error: {}", err),
|
||||
RogError::DoTask(deets) => write!(f, "Task error: {}", deets),
|
||||
RogError::MissingFunction(deets) => write!(f, "Missing functionality: {}", deets),
|
||||
RogError::MissingLedBrightNode(path, error) => write!(f, "Led node at {} is missing, please check you have the required patch or dkms module installed: {}", path, error),
|
||||
RogError::ReloadFail(deets) => write!(f, "Task error: {}", deets),
|
||||
RogError::GfxSwitching(deets) => write!(f, "Graphics switching error: {}", deets),
|
||||
RogError::Profiles(deets) => write!(f, "Profile error: {}", deets),
|
||||
RogError::Initramfs(detail) => write!(f, "Initiramfs error: {}", detail),
|
||||
RogError::Modprobe(detail) => write!(f, "Modprobe error: {}", detail),
|
||||
RogError::Command(func, error) => write!(f, "Command exec error: {}: {}", func, error),
|
||||
RogError::Io(detail) => write!(f, "std::io error: {}", detail),
|
||||
RogError::Zbus(detail) => write!(f, "Zbus error: {}", detail),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RogError {}
|
||||
|
||||
impl From<CurveError> for RogError {
|
||||
fn from(err: CurveError) -> Self {
|
||||
RogError::FanCurve(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<GraphicsError> for RogError {
|
||||
fn from(err: GraphicsError) -> Self {
|
||||
match err {
|
||||
GraphicsError::ParseVendor => RogError::GfxSwitching(GfxError::ParseVendor),
|
||||
GraphicsError::ParsePower => RogError::GfxSwitching(GfxError::ParsePower),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProfileError> for RogError {
|
||||
fn from(err: ProfileError) -> Self {
|
||||
RogError::Profiles(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<zbus::Error> for RogError {
|
||||
fn from(err: zbus::Error) -> Self {
|
||||
RogError::Zbus(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for RogError {
|
||||
fn from(err: std::io::Error) -> Self {
|
||||
RogError::Io(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RogError> for zbus::fdo::Error {
|
||||
#[inline]
|
||||
fn from(err: RogError) -> Self {
|
||||
zbus::fdo::Error::Failed(format!("{}", err))
|
||||
}
|
||||
}
|
||||
105
daemon/src/laptops.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use log::{info, warn};
|
||||
use rog_aura::AuraModeNum;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Read;
|
||||
|
||||
pub const ASUS_LED_MODE_CONF: &str = "/etc/asusd/asusd-ledmodes.toml";
|
||||
pub const ASUS_KEYBOARD_DEVICES: [&str; 4] = ["1866", "1869", "1854", "19b6"];
|
||||
|
||||
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_name = dmi.product_name().expect("Could not get product_name");
|
||||
let prod_family = dmi.product_family().expect("Could not get product_family");
|
||||
|
||||
info!("Product name: {}", prod_name.trim());
|
||||
info!("Product family: {}", prod_family.trim());
|
||||
info!("Board name: {}", board_name.trim());
|
||||
}
|
||||
|
||||
pub fn print_modes(supported_modes: &[u8]) {
|
||||
if !supported_modes.is_empty() {
|
||||
info!("Supported Keyboard LED modes are:");
|
||||
for mode in supported_modes {
|
||||
let mode = <&str>::from(&<AuraModeNum>::from(*mode));
|
||||
info!("- {}", mode);
|
||||
}
|
||||
info!(
|
||||
"If these modes are incorrect you can edit {}",
|
||||
ASUS_LED_MODE_CONF
|
||||
);
|
||||
} else {
|
||||
info!("No RGB control available");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct LedSupportFile {
|
||||
led_data: Vec<LaptopLedData>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct LaptopLedData {
|
||||
pub prod_family: String,
|
||||
pub board_names: Vec<String>,
|
||||
pub standard: Vec<AuraModeNum>,
|
||||
pub multizone: bool,
|
||||
pub per_key: bool,
|
||||
}
|
||||
|
||||
impl LaptopLedData {
|
||||
pub fn get_data() -> Self {
|
||||
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");
|
||||
|
||||
if let Some(modes) = LedSupportFile::load_from_config() {
|
||||
if let Some(data) = modes.matcher(&prod_family, &board_name) {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
info!("Using generic LED control for keyboard brightness only");
|
||||
LaptopLedData {
|
||||
prod_family,
|
||||
board_names: vec![board_name],
|
||||
standard: vec![],
|
||||
multizone: false,
|
||||
per_key: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LedSupportFile {
|
||||
/// Consumes the LEDModes
|
||||
fn matcher(self, prod_family: &str, board_name: &str) -> Option<LaptopLedData> {
|
||||
for config in self.led_data {
|
||||
if prod_family.contains(&config.prod_family) {
|
||||
for board in &config.board_names {
|
||||
if board_name.contains(board) {
|
||||
info!("Matched to {} {}", config.prod_family, board);
|
||||
return Some(config);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn load_from_config() -> Option<Self> {
|
||||
if let Ok(mut file) = OpenOptions::new().read(true).open(&ASUS_LED_MODE_CONF) {
|
||||
let mut buf = String::new();
|
||||
if let Ok(l) = file.read_to_string(&mut buf) {
|
||||
if l == 0 {
|
||||
warn!("{} is empty", ASUS_LED_MODE_CONF);
|
||||
} else {
|
||||
return Some(toml::from_str(&buf).unwrap_or_else(|_| {
|
||||
panic!("Could not deserialise {}", ASUS_LED_MODE_CONF)
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
warn!("Does {} exist?", ASUS_LED_MODE_CONF);
|
||||
None
|
||||
}
|
||||
}
|
||||
65
daemon/src/lib.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
#![deny(unused_must_use)]
|
||||
/// Configuration loading, saving
|
||||
pub mod config;
|
||||
pub mod config_anime;
|
||||
pub mod config_aura;
|
||||
pub(crate) mod config_old;
|
||||
/// Control of AniMe matrix display
|
||||
pub mod ctrl_anime;
|
||||
/// Control of battery charge level
|
||||
pub mod ctrl_charge;
|
||||
/// GPU switching and power
|
||||
pub mod ctrl_gfx;
|
||||
/// Keyboard LED brightness control, RGB, and LED display modes
|
||||
pub mod ctrl_leds;
|
||||
/// Control CPU min/max freq and turbo, fan mode, fan curves
|
||||
///
|
||||
/// Intel machines can control:
|
||||
/// - CPU min/max frequency
|
||||
/// - CPU turbo enable/disable
|
||||
/// - Fan mode (normal, boost, silent)
|
||||
///
|
||||
/// AMD machines can control:
|
||||
/// - CPU turbo enable/disable
|
||||
/// - Fan mode (normal, boost, silent)
|
||||
/// - Fan min/max RPM curve
|
||||
pub mod ctrl_profiles;
|
||||
/// Control ASUS bios function such as boot sound, Optimus/Dedicated gfx mode
|
||||
pub mod ctrl_rog_bios;
|
||||
/// Laptop matching to determine capabilities
|
||||
pub mod laptops;
|
||||
|
||||
/// Fetch all supported functions for the laptop
|
||||
pub mod ctrl_supported;
|
||||
|
||||
mod error;
|
||||
|
||||
use crate::error::RogError;
|
||||
use config::Config;
|
||||
use zbus::ObjectServer;
|
||||
|
||||
pub static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub trait Reloadable {
|
||||
fn reload(&mut self) -> Result<(), RogError>;
|
||||
}
|
||||
|
||||
pub trait ZbusAdd {
|
||||
fn add_to_server(self, server: &mut ObjectServer);
|
||||
}
|
||||
|
||||
pub trait CtrlTask {
|
||||
fn do_task(&self) -> Result<(), RogError>;
|
||||
}
|
||||
|
||||
pub trait CtrlTaskComplex {
|
||||
type A;
|
||||
|
||||
fn do_task(&mut self, config: &mut Config, event: Self::A);
|
||||
}
|
||||
|
||||
pub trait GetSupported {
|
||||
type A;
|
||||
|
||||
fn get_supported() -> Self::A;
|
||||
}
|
||||
7
data/90-asusd-nvidia-pm.rules
Normal file
@@ -0,0 +1,7 @@
|
||||
# Enable runtime PM for NVIDIA VGA/3D controller devices on driver bind
|
||||
ACTION=="bind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", TEST=="power/control", ATTR{power/control}="auto"
|
||||
ACTION=="bind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030200", TEST=="power/control", ATTR{power/control}="auto"
|
||||
|
||||
# Disable runtime PM for NVIDIA VGA/3D controller devices on driver unbind
|
||||
ACTION=="unbind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030000", TEST=="power/control", ATTR{power/control}="on"
|
||||
ACTION=="unbind", SUBSYSTEM=="pci", ATTR{vendor}=="0x10de", ATTR{class}=="0x030200", TEST=="power/control", ATTR{power/control}="on"
|
||||
4
data/90-nvidia-screen-G05.conf
Normal file
@@ -0,0 +1,4 @@
|
||||
Section "ServerLayout"
|
||||
Identifier "layout"
|
||||
Option "AllowNVIDIAGPUScreens"
|
||||
EndSection
|
||||
50
data/_asusctl
Normal file
@@ -0,0 +1,50 @@
|
||||
function _asusctl() {
|
||||
local line
|
||||
|
||||
_arguments -C \
|
||||
{-h,--help}'[print help message]' \
|
||||
{-v,--version}'[print version number]' \
|
||||
{-k,--kbd-bright}':[Set keyboard brightness (off, low, med, high)]' \
|
||||
{-p,--pwr-profile}':[Set power profile (silent, normal, boost)]' \
|
||||
{-c,--chg-limit}':[Set charging limit (20-100)]' \
|
||||
': :((led-mode\:"Set the keyboard lighting from built-in modes" profile\:"Create and configure profiles" graphics\:"Set the graphics mode"))' \
|
||||
'*::arg:->args'
|
||||
case $line[1] in
|
||||
led-mode)
|
||||
_arguments ': :((static\:"set a single static colour"
|
||||
breathe\:"pulse between one or two colours"
|
||||
strobe\:"strobe through all colours"
|
||||
rainbow\:"rainbow cycling in one of four directions"
|
||||
star\:"rain pattern mimicking raindrops"
|
||||
rain\:"rain pattern of three preset colours"
|
||||
highlight\:"pressed keys are highlighted to fade"
|
||||
laser\:"pressed keys generate horizontal laser"
|
||||
ripple\:"pressed keys ripple outwards like a splash"
|
||||
pulse\:"set a rapid pulse"
|
||||
comet\:"set a vertical line zooming from left"
|
||||
flash\:"set a wide vertical line zooming from left"
|
||||
multi-static\:"4-zone multi-colour"))' \
|
||||
{-h,--help}'[print help message]' \
|
||||
'-c:[set the RGB value e.g, ff00ff]' \
|
||||
'-s:[set the speed (low, med, high)]'
|
||||
;;
|
||||
profile)
|
||||
_arguments {-h,--help}'[print help message]' \
|
||||
{-c,--create}"[create the profile if it doesn't exist]" \
|
||||
{-t,--turbo}':[enable or disable cpu turbo]' \
|
||||
{-m,--min-percentage}':[set min cpu scaling (intel)]' \
|
||||
{-M,--max-percentage}':[set max cpu scaling (intel)]' \
|
||||
{-p,--preset}':[<silent, normal, boost>]' \
|
||||
{-C,--curve}':[set fan curve]'
|
||||
|
||||
;;
|
||||
graphics)
|
||||
_arguments {-h,--help}'[print help message]' \
|
||||
{-m,--mode}':[Set graphics mode (nvidia, hybrid, compute, integrated)]' \
|
||||
{-g,--get}'[Get the current mode]' \
|
||||
{-p,--pow}'[Get the current power status]' \
|
||||
{-f,--force}'[Do not ask for confirmation]'
|
||||
;;
|
||||
esac
|
||||
}
|
||||
compdef _asusctl asusctl
|
||||
BIN
data/anime/asus/festive/Cupid.gif
Executable file
|
After Width: | Height: | Size: 72 KiB |
BIN
data/anime/asus/festive/Firework.gif
Executable file
|
After Width: | Height: | Size: 61 KiB |
BIN
data/anime/asus/festive/Halloween.gif
Executable file
|
After Width: | Height: | Size: 137 KiB |
BIN
data/anime/asus/festive/Happy Holiday.gif
Executable file
|
After Width: | Height: | Size: 109 KiB |
BIN
data/anime/asus/festive/Happy new year.gif
Executable file
|
After Width: | Height: | Size: 99 KiB |