Compare commits
559 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1aa1c62e40 | ||
|
|
3a18ef4c7b | ||
|
|
9dcce77302 | ||
|
|
995df9b51b | ||
|
|
84c8babdb7 | ||
|
|
1014f97b6f | ||
|
|
3c023be57d | ||
|
|
eff20c84d6 | ||
|
|
f8984eb7e9 | ||
|
|
2ffd2a1e1f | ||
|
|
341bd081f8 | ||
|
|
52af4203a1 | ||
|
|
e5a6088392 | ||
|
|
6ee5dfb352 | ||
|
|
3f8336fc5e | ||
|
|
8fc7e8f3a7 | ||
|
|
098b1f2668 | ||
|
|
20df3ad2f2 | ||
|
|
7aaadad6da | ||
|
|
be60c1ba02 | ||
|
|
698a8e8677 | ||
|
|
ce6420eeac | ||
|
|
f5f5e4f720 | ||
|
|
c08503826b | ||
|
|
685345d656 | ||
|
|
59aab24a4a | ||
|
|
c3f0e61ebc | ||
|
|
c143536cd0 | ||
|
|
2a168e93d3 | ||
|
|
c3570a23f1 | ||
|
|
9db6cb5545 | ||
|
|
836575c0a8 | ||
|
|
61f2216c25 | ||
|
|
7f5b3ef376 | ||
|
|
257471a36c | ||
|
|
568f3e848f | ||
|
|
0c9b58755f | ||
|
|
1b47fb7873 | ||
|
|
df93209839 | ||
|
|
11ee7827e9 | ||
|
|
c337de5139 | ||
|
|
d55c2befed | ||
|
|
4cd9918e1a | ||
|
|
3a900f23fe | ||
|
|
aee465aced | ||
|
|
192e5ccaa3 | ||
|
|
f164583792 | ||
|
|
b4d657b866 | ||
|
|
f7bf7aeef9 | ||
|
|
2cd4c4850f | ||
|
|
805ccfe451 | ||
|
|
5655f63dff | ||
|
|
a2795e4d78 | ||
|
|
0684c16bf5 | ||
|
|
a08ca3af98 | ||
|
|
efa379e778 | ||
|
|
5cbf0816fe | ||
|
|
2951d3926c | ||
|
|
eb19d59d52 | ||
|
|
3e4d594b05 | ||
|
|
ae8ce83583 | ||
|
|
5c3348a9f5 | ||
|
|
f299ffeb6e | ||
|
|
21c468cf02 | ||
|
|
7f12f62ad5 | ||
|
|
5fb0e26331 | ||
|
|
4dd29952c8 | ||
|
|
2c006699f2 | ||
|
|
0bdf0474c9 | ||
|
|
66196ceb17 | ||
|
|
b2726f3a67 | ||
|
|
663f87d5e2 | ||
|
|
377bb4d6ad | ||
|
|
98e60db2da | ||
|
|
11ac46df11 | ||
|
|
05bec93644 | ||
|
|
c77e7cf1ce | ||
|
|
d30f7dc2ea | ||
|
|
759606fca3 | ||
|
|
25ed8bdeed | ||
|
|
de61a15b7a | ||
|
|
16700e55f4 | ||
|
|
5833a011ce | ||
|
|
62577ee0e4 | ||
|
|
dac35996b1 | ||
|
|
5c2bcad7c6 | ||
|
|
a206591e97 | ||
|
|
81f6c18a24 | ||
|
|
bcc3d42789 | ||
|
|
36c34cb3dd | ||
|
|
9b82b875f1 | ||
|
|
bddccc696f | ||
|
|
51e9f10087 | ||
|
|
911ff8690e | ||
|
|
25823dc6b7 | ||
|
|
cba8e1a473 | ||
|
|
fb98827a1a | ||
|
|
b9296862df | ||
|
|
450205f9a9 | ||
|
|
82431ee25b | ||
|
|
f11aea02a8 | ||
|
|
2d6d669c22 | ||
|
|
f9cebf9221 | ||
|
|
a00808313e | ||
|
|
3426591d32 | ||
|
|
ef3b6636f5 | ||
|
|
ee9e0a1e31 | ||
|
|
9e84997cbf | ||
|
|
2b22f82b72 | ||
|
|
7a1b45071d | ||
|
|
ad63c429cb | ||
|
|
a790d9a499 | ||
|
|
be51a1ab77 | ||
|
|
d9a88e7cc3 | ||
|
|
d785e17f95 | ||
|
|
efe64119c6 | ||
|
|
128bc3fce1 | ||
|
|
2123f369ad | ||
|
|
2b7a2a5be3 | ||
|
|
1d9e89ef3d | ||
|
|
4011b3ebd4 | ||
|
|
f7456f0144 | ||
|
|
2ed2d82e03 | ||
|
|
d40f4733e2 | ||
|
|
98dc155e41 | ||
|
|
fd3384decc | ||
|
|
a1a9c7077a | ||
|
|
62aa1fe04f | ||
|
|
a7b98c67ee | ||
|
|
e7bbd99178 | ||
|
|
e2d3f99d91 | ||
|
|
1cad5afc0d | ||
|
|
fd31ac458d | ||
|
|
6292b3361d | ||
|
|
ab7a4bbad3 | ||
|
|
0f2d89858e | ||
|
|
19ffcf3376 | ||
|
|
72c0b24ead | ||
|
|
0ddfe76c31 | ||
|
|
c05c8ba648 | ||
|
|
ccdc576319 | ||
|
|
39b16ffc91 | ||
|
|
72ff1ab3ab | ||
|
|
e7c4619ee9 | ||
|
|
71fcb382ea | ||
|
|
e5b2e3ef11 | ||
|
|
dfd39522a8 | ||
|
|
2759c28196 | ||
|
|
207e199016 | ||
|
|
5f8cbdb94b | ||
|
|
0853c16d5e | ||
|
|
0be04726ca | ||
|
|
a672a86cc4 | ||
|
|
c7ff3b44dc | ||
|
|
f0ebda9ecd | ||
|
|
b984176cd0 | ||
|
|
599b1cc9ad | ||
|
|
d93df8752e | ||
|
|
8a9564bbfa | ||
|
|
5455e345b2 | ||
|
|
520101fea1 | ||
|
|
e866b4eeb1 | ||
|
|
c5c46738ee | ||
|
|
27ed95bd3e | ||
|
|
ea9ca79a8f | ||
|
|
4a97f173be | ||
|
|
8f35220c5f | ||
|
|
c3880d055d | ||
|
|
b661f67084 | ||
|
|
abd2ca8601 | ||
|
|
0905ed8ad4 | ||
|
|
c1268d4aad | ||
|
|
5ed47abc32 | ||
|
|
718bb8b86f | ||
|
|
5ab9642b79 | ||
|
|
14acab9a9c | ||
|
|
c5c5a9ac67 | ||
|
|
b84bc61f3d | ||
|
|
b4e38e0814 | ||
|
|
e4dd485dd4 | ||
|
|
ab1d75e5ec | ||
|
|
e4c5df6cca | ||
|
|
9ee7ee26a2 | ||
|
|
e8ebdacb91 | ||
|
|
b97921fea2 | ||
|
|
a3423195a6 | ||
|
|
f55edfbae0 | ||
|
|
3e065b6715 | ||
|
|
f14d1ad61e | ||
|
|
85d4e9cabd | ||
|
|
e47a9cffd7 | ||
|
|
ca93dc7215 | ||
|
|
93a646773c | ||
|
|
1cba693469 | ||
|
|
166149b351 | ||
|
|
1b11b6d8fb | ||
|
|
02568299df | ||
|
|
acdc93596c | ||
|
|
22e26adfb6 | ||
|
|
4730e645ba | ||
|
|
d203fab70d | ||
|
|
792fae3ed7 | ||
|
|
e443ab00c9 | ||
|
|
aee54f5756 | ||
|
|
00904e9603 | ||
|
|
b1212585e2 | ||
|
|
faca084cff | ||
|
|
89dc0b3501 | ||
|
|
ea988279a8 | ||
|
|
219bd559b6 | ||
|
|
ad1ef9b8a2 | ||
|
|
59795c605c | ||
|
|
a36ac2b6d3 | ||
|
|
a20837f252 | ||
|
|
1353fe3fdb | ||
|
|
770bd12a5c | ||
|
|
af2f5592f0 | ||
|
|
9686c41ac4 | ||
|
|
fbdb0514d2 | ||
|
|
1f5650d26b | ||
|
|
14db97c476 | ||
|
|
66a501ecf6 | ||
|
|
6b129763d4 | ||
|
|
a0368d4345 | ||
|
|
f2f090a88f | ||
|
|
6c7e1a6467 | ||
|
|
92ca7bc70d | ||
|
|
dd1e6b845b | ||
|
|
882fa9bed8 | ||
|
|
9c7dfb4030 | ||
|
|
f855908c82 | ||
|
|
293a087b8a | ||
|
|
fd72a04bb8 | ||
|
|
f131a3fa70 | ||
|
|
ccf8d8df91 | ||
|
|
b970d364f7 | ||
|
|
1da68ea69d | ||
|
|
e62e7e8eca | ||
|
|
1b1d10c461 | ||
|
|
14ea0f6d83 | ||
|
|
5107a6c39c | ||
|
|
2c77ec9e24 | ||
|
|
817a66bdf1 | ||
|
|
664a3d5533 | ||
|
|
37bc5e45b9 | ||
|
|
a18692ef1e | ||
|
|
1b023d0f5f | ||
|
|
74f74e73c4 | ||
|
|
9c7df9ad39 | ||
|
|
94adf5d24d | ||
|
|
8dbdb68175 | ||
|
|
89002eb5ec | ||
|
|
dc9ef8cf54 | ||
|
|
667697d042 | ||
|
|
bc92fa11f9 | ||
|
|
f5d5681b49 | ||
|
|
1c8e50843b | ||
|
|
487d140bd5 | ||
|
|
661ea8d3bf | ||
|
|
28d1ed6ab3 | ||
|
|
903b978e86 | ||
|
|
519f6bd46b | ||
|
|
a94a8ca28d | ||
|
|
f9dca2da5d | ||
|
|
df88ff1acb | ||
|
|
cb5aa0f170 | ||
|
|
4ea79f966e | ||
|
|
b8bc1a01b3 | ||
|
|
0e5d1815bd | ||
|
|
64e8cb65d0 | ||
|
|
7122fbaca8 | ||
|
|
3142353f98 | ||
|
|
484ca692ad | ||
|
|
1ebdfada96 | ||
|
|
3bc9dfcda1 | ||
|
|
895e5d2ca3 | ||
|
|
564992719e | ||
|
|
a737d240be | ||
|
|
d89c1ebf26 | ||
|
|
be7686bb46 | ||
|
|
4f70055f85 | ||
|
|
91ca049298 | ||
|
|
635d0378ac | ||
|
|
1c729316f7 | ||
|
|
4701c019a8 | ||
|
|
ca0d8bda4b | ||
|
|
a271ffbb10 | ||
|
|
00babaf949 | ||
|
|
2f844ac151 | ||
|
|
5178bf1d1a | ||
|
|
116afb9b6c | ||
|
|
4468a58487 | ||
|
|
2f73577e91 | ||
|
|
c1cffc8f59 | ||
|
|
6d8f85c154 | ||
|
|
0674e7f61c | ||
|
|
fde2f3ba15 | ||
|
|
70493d1a93 | ||
|
|
c20d0a76a0 | ||
|
|
e6952e241a | ||
|
|
b40812928a | ||
|
|
8cdc9773c9 | ||
|
|
8d30282edf | ||
|
|
4ba44560a9 | ||
|
|
cdc9ca7b58 | ||
|
|
7eae7c5664 | ||
|
|
739a0ffa63 | ||
|
|
637360095c | ||
|
|
4b34ab83fb | ||
|
|
ac605cbc00 | ||
|
|
4b38e5daa6 | ||
|
|
1c007b4216 | ||
|
|
193f9dfa1e | ||
|
|
1366422d96 | ||
|
|
4e778a3d28 | ||
|
|
be05508110 | ||
|
|
9119229d41 | ||
|
|
5c43c31331 | ||
|
|
014604724f | ||
|
|
7d076368e9 | ||
|
|
5d6ed5c365 | ||
|
|
a2b8f0f93c | ||
|
|
5fe8416c65 | ||
|
|
1b4d7a95af | ||
|
|
e8627fde4c | ||
|
|
6b0edc6da1 | ||
|
|
f6ad631a0f | ||
|
|
f6393a3926 | ||
|
|
d51384c3a1 | ||
|
|
78f18959fb | ||
|
|
7a661a585e | ||
|
|
f4f7a1e648 | ||
|
|
b6e3e5e823 | ||
|
|
41b1bd23d6 | ||
|
|
69458a0595 | ||
|
|
5fd107df27 | ||
|
|
2558057e9f | ||
|
|
8111daaf1d | ||
|
|
672acb234f | ||
|
|
9725062fb9 | ||
|
|
c7b1624313 | ||
|
|
67b97f1d43 | ||
|
|
6498fd1349 | ||
|
|
e371229b6c | ||
|
|
0fac33a8ff | ||
|
|
b0da062577 | ||
|
|
ca41bd59de | ||
|
|
efcad3f6f9 | ||
|
|
fa2255cbaf | ||
|
|
02b9bac899 | ||
|
|
a1fcf5023c | ||
|
|
2f8ea80e6d | ||
|
|
b798cf6a4e | ||
|
|
3da848d131 | ||
|
|
a88c33c201 | ||
|
|
7b0f037cba | ||
|
|
91b1456d06 | ||
|
|
c3b02a2bb0 | ||
|
|
8e4b7d53f4 | ||
|
|
a44145f487 | ||
|
|
bb7b3a81fb | ||
|
|
19607d71c3 | ||
|
|
96f281d789 | ||
|
|
7613eded95 | ||
|
|
50eccd2b1d | ||
|
|
ba54007102 | ||
|
|
a028f5375f | ||
|
|
9ec02cd727 | ||
|
|
4b46ece09a | ||
|
|
086bbd0908 | ||
|
|
c94eaa473e | ||
|
|
b1b809834b | ||
|
|
84183288ec | ||
|
|
86cbef83b6 | ||
|
|
006fb632c4 | ||
|
|
e3636ed8ce | ||
|
|
cfd207f251 | ||
|
|
d4c68546e7 | ||
|
|
6f4a7e16dc | ||
|
|
f64253d633 | ||
|
|
124c17aadc | ||
|
|
ab40f9fcbf | ||
|
|
5cdfa5a8d4 | ||
|
|
ce870cd5ed | ||
|
|
4541d2e1ba | ||
|
|
b525411fd3 | ||
|
|
a867496f13 | ||
|
|
f421b8ee3b | ||
|
|
82780feb4b | ||
|
|
1e5443e206 | ||
|
|
027a591d26 | ||
|
|
e90375828d | ||
|
|
75b4d67072 | ||
|
|
9aa332de3b | ||
|
|
5efd7fc6a7 | ||
|
|
0aafe24a02 | ||
|
|
dda6d343d9 | ||
|
|
6f39307080 | ||
|
|
ef63789faa | ||
|
|
c422e77ba6 | ||
|
|
3c234dd3c4 | ||
|
|
c420dd820a | ||
|
|
a3e6fec163 | ||
|
|
9b4e76be87 | ||
|
|
7b2125cbdf | ||
|
|
694a644cc6 | ||
|
|
922aa0c352 | ||
|
|
c06f78990f | ||
|
|
5c8bb6e6ea | ||
|
|
993131d0a9 | ||
|
|
0a69c23288 | ||
|
|
f6e4cc0626 | ||
|
|
1f696508e7 | ||
|
|
fa043adc99 | ||
|
|
b9c2d929b3 | ||
|
|
eda1e920df | ||
|
|
0de2c9e424 | ||
|
|
e88e7be8ae | ||
|
|
e470d3acc0 | ||
|
|
f5b3f0bc38 | ||
|
|
19497c94e0 | ||
|
|
670eee23e8 | ||
|
|
26309776e9 | ||
|
|
a7d5057976 | ||
|
|
8eb9b1d4eb | ||
|
|
71ee9e43ba | ||
|
|
f1b0e1288a | ||
|
|
35c7fd10b3 | ||
|
|
4c50dc259c | ||
|
|
0fd0aeff88 | ||
|
|
fd37f41ef1 | ||
|
|
1307997122 | ||
|
|
85187d2d8d | ||
|
|
e29a568195 | ||
|
|
6c375a9951 | ||
|
|
4641e19c43 | ||
|
|
91f0c2ea14 | ||
|
|
b4a8cb9de2 | ||
|
|
67bbcdb964 | ||
|
|
8acfe0a9e8 | ||
|
|
5f6e6ec382 | ||
|
|
cf92526d87 | ||
|
|
f290594562 | ||
|
|
423bd54f79 | ||
|
|
ea0eaef8a6 | ||
|
|
ef62a26148 | ||
|
|
2f916fa4e5 | ||
|
|
e42fd10404 | ||
|
|
93edd1b632 | ||
|
|
6957a08d83 | ||
|
|
98569b98e7 | ||
|
|
573568d6e2 | ||
|
|
3ec37a4dac | ||
|
|
11483b28a6 | ||
|
|
2cce83d164 | ||
|
|
42b92f3b87 | ||
|
|
b652fd15a2 | ||
|
|
9154aaa97c | ||
|
|
9e65921c0a | ||
|
|
8d8b5e5f51 | ||
|
|
9418b63454 | ||
|
|
2d396a49da | ||
|
|
a6d89a622b | ||
|
|
51bcb0082b | ||
|
|
eb54250e4d | ||
|
|
eafc831231 | ||
|
|
c625e97b7b | ||
|
|
fea56879d6 | ||
|
|
03052e129b | ||
|
|
3dbc893905 | ||
|
|
50152961c7 | ||
|
|
8be0e7e6bf | ||
|
|
d6d4a00fc3 | ||
|
|
611140716c | ||
|
|
a09f7b5275 | ||
|
|
823958492e | ||
|
|
668135eab3 | ||
|
|
622e07505d | ||
|
|
5c159d2294 | ||
|
|
6cfa09a02b | ||
|
|
95666cc40b | ||
|
|
458d58c87c | ||
|
|
7328ebdda3 | ||
|
|
14d043bbc3 | ||
|
|
98dec6403c | ||
|
|
3546f5bd21 | ||
|
|
db1683de46 | ||
|
|
669c8ac3c7 | ||
|
|
4f3a6ce1c6 | ||
|
|
6d3918ccf0 | ||
|
|
b002187b39 | ||
|
|
13965b2261 | ||
|
|
b182fbd323 | ||
|
|
19b28f202c | ||
|
|
ed51a7fa14 | ||
|
|
c94358a8f3 | ||
|
|
2a8ca0a39a | ||
|
|
83455a5ba3 | ||
|
|
bc776deb70 | ||
|
|
59b1059aee | ||
|
|
dbe80d1914 | ||
|
|
e325ebed18 | ||
|
|
a743bda6e0 | ||
|
|
15e6782e10 | ||
|
|
6b058c9922 | ||
|
|
fc8879ac24 | ||
|
|
4d2d5707a1 | ||
|
|
439c830311 | ||
|
|
91223d4ced | ||
|
|
7b17a13ce7 | ||
|
|
fca7d23a31 | ||
|
|
0122138b3b | ||
|
|
7b495e7587 | ||
|
|
970cf9ae59 | ||
|
|
ad990c6ae1 | ||
|
|
cd8cc013a4 | ||
|
|
acf41c1783 | ||
|
|
03c9f06569 | ||
|
|
036a5018e0 | ||
|
|
81529b7374 | ||
|
|
2289af3ef6 | ||
|
|
633ffdf962 | ||
|
|
cb88c9f0e2 | ||
|
|
8b77078a6f | ||
|
|
3d6d92ae7d | ||
|
|
55723b7b77 | ||
|
|
7796ba0603 | ||
|
|
d3aababef5 | ||
|
|
4611c08085 | ||
|
|
0a008a653a | ||
|
|
cd5daa17d0 | ||
|
|
a0529e0efd | ||
|
|
3e0aeea6c6 | ||
|
|
e2fb1d44b5 | ||
|
|
04543eeca0 | ||
|
|
68ee62fef1 | ||
|
|
e523e4e9a2 | ||
|
|
ea2d80cc44 | ||
|
|
40e00c4739 | ||
|
|
cdc42193d1 | ||
|
|
3a18506510 | ||
|
|
fa671e53d8 | ||
|
|
002dc8516d | ||
|
|
2a38f69cc4 | ||
|
|
a14a37d0da | ||
|
|
b105ff5180 | ||
|
|
d202fcd97a | ||
|
|
15732ecd82 | ||
|
|
8508110ba0 | ||
|
|
cafb64d57b | ||
|
|
7515eafc45 | ||
|
|
b6c6f10bdf | ||
|
|
35352a8a7c | ||
|
|
0c3bebdeb9 | ||
|
|
1394c12967 | ||
|
|
cbc1f6f5bb | ||
|
|
7ae0f896cf | ||
|
|
fb0374512d | ||
|
|
14f031ad34 |
53
.cargo-husky/hooks/post-commit
Executable file
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
ROOT_DIR=$(git rev-parse --show-toplevel)
|
||||
AURA_DATA="${ROOT_DIR}/rog-aura/data/aura_support.ron"
|
||||
SPEC_FILE="${ROOT_DIR}/distro-packaging/asusctl.spec"
|
||||
TRANSLATION="${ROOT_DIR}/rog-control-center/translations/en/rog-control-center.po"
|
||||
VERSION=$(grep -Pm1 'version = "(\d+.\d+.\d+.*)"' "${ROOT_DIR}/Cargo.toml" | cut -d'"' -f2)
|
||||
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Error: Could not extract version from Cargo.toml"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -f "$SPEC_FILE" ]; then
|
||||
echo "Error: Spec file not found at ${SPEC_FILE}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Update spec file
|
||||
sed -i "s/^%define version.*/%define version ${VERSION}/" "$SPEC_FILE"
|
||||
if git diff --quiet "$SPEC_FILE"; then
|
||||
echo "No changes to spec file"
|
||||
else
|
||||
git add "$SPEC_FILE"
|
||||
git commit --no-verify -m "chore: update spec file version to ${VERSION}"
|
||||
echo "Updated spec file version to ${VERSION}"
|
||||
fi
|
||||
|
||||
# Update translations only if UI files changed
|
||||
if git diff-tree -r HEAD@{1} HEAD --name-only | grep -q "^rog-control-center/ui/"; then
|
||||
echo 'find -name \*.slint | xargs slint-tr-extractor -o ${TRANSLATION}'
|
||||
find -name \*.slint | xargs slint-tr-extractor -o $TRANSLATION
|
||||
if git diff --quiet "$TRANSLATION"; then
|
||||
echo "No changes to translation file"
|
||||
else
|
||||
git add "$TRANSLATION"
|
||||
git commit --no-verify -m "chore: update translations"
|
||||
echo "Updated ${TRANSLATION}"
|
||||
fi
|
||||
else
|
||||
echo "No changes in rog-control-center/ui/, skipping translation update"
|
||||
fi
|
||||
|
||||
# Update aura data
|
||||
cargo test --package rog_aura --lib -- aura_detection::tests::check_data_file_parse --exact
|
||||
cargo test --package rog_aura --lib -- aura_detection::tests::find_data_file_groups --exact
|
||||
if git diff --quiet "$AURA_DATA"; then
|
||||
echo "No changes to aura data file"
|
||||
else
|
||||
git add "$AURA_DATA"
|
||||
git commit --no-verify -m "chore: update aura data"
|
||||
echo "Updated $AURA_DATA"
|
||||
fi
|
||||
@@ -1,12 +1,6 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -e
|
||||
|
||||
echo '+cargo +nightly fmt --all -- --check'
|
||||
cargo +nightly fmt --all -- --check
|
||||
echo '+cargo clippy --all -- -D warnings'
|
||||
cargo clippy --all -- -D warnings
|
||||
echo '+cargo test --all'
|
||||
cargo test --all
|
||||
echo '+cargo cranky'
|
||||
cargo cranky
|
||||
git add -u
|
||||
|
||||
13
.gitignore
vendored
@@ -8,4 +8,15 @@ vendor_*
|
||||
.vscode-ctags
|
||||
.vscode
|
||||
.~lock.*
|
||||
*.ods#
|
||||
*.ods#
|
||||
*.patch
|
||||
|
||||
# gnome extension
|
||||
node-modules
|
||||
bindings/ts/*.d.ts
|
||||
bindings/ts/*.js.map
|
||||
desktop-extensions/gnome*/dist
|
||||
desktop-extensions/gnome*/@types/gir-generated
|
||||
desktop-extensions/gnome*/node_modules
|
||||
desktop-extensions/gnome*/schemas/gschemas.compiled
|
||||
desktop-extensions/gnome*/*.zip
|
||||
|
||||
@@ -17,7 +17,7 @@ image: rust:latest
|
||||
- target/release/.cargo-lock
|
||||
|
||||
before_script:
|
||||
- apt-get update -qq && apt-get install -y -qq libudev-dev libgtk-3-dev grep llvm clang libclang-dev
|
||||
- apt-get update -qq && apt-get install -y -qq libudev-dev libgtk-3-dev grep llvm clang libclang-dev libsdl2-dev libsdl2-gfx-dev
|
||||
|
||||
stages:
|
||||
- format
|
||||
@@ -52,18 +52,19 @@ test:
|
||||
<<: *rust_cache
|
||||
script:
|
||||
- mkdir -p .git/hooks > /dev/null
|
||||
- cargo test
|
||||
- cargo test --all -- --test-threads=1
|
||||
|
||||
release:
|
||||
only:
|
||||
- tags
|
||||
<<: *rust_cache
|
||||
script:
|
||||
- cargo install cargo-vendor-filterer
|
||||
- make && make vendor
|
||||
artifacts:
|
||||
paths:
|
||||
- vendor_asusctl_*.tar.xz
|
||||
- cargo-config
|
||||
- vendor_asusctl*.tar.xz
|
||||
- cargo-config
|
||||
|
||||
pages:
|
||||
stage: deploy
|
||||
@@ -75,10 +76,10 @@ pages:
|
||||
- rm -rf public
|
||||
- mkdir public
|
||||
- cp -R target/doc/* public
|
||||
- cp misc/index.html public
|
||||
- cp extra/index.html public
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
|
||||
|
||||
variables:
|
||||
GIT_SUBMODULE_STRATEGY: normal
|
||||
|
||||
32
.gitlab/issue_templates/default.md
Normal file
@@ -0,0 +1,32 @@
|
||||
## Issue description
|
||||
|
||||
(** I can not support distros which are outdated by default. This includes Ubuntu at least 50% of the time, and definitely includes Mint. **)
|
||||
(Summarize the bug encountered)
|
||||
|
||||
## Steps to reproduce
|
||||
|
||||
(How can the issue be reproduced)
|
||||
|
||||
## What is the current bug behavior?
|
||||
|
||||
(What actually happens)
|
||||
|
||||
## What is the expected correct behavior?
|
||||
|
||||
(What you should see instead)
|
||||
|
||||
## Relevant logs and/or screenshots
|
||||
|
||||
(run `journalctl -b -u asusd > ~/asusd.log` and attach `~/asusd.log`)
|
||||
|
||||
(Paste any relevant logs - use code blocks (```) to format console output, logs, and code, as
|
||||
it's very hard to read otherwise.)
|
||||
|
||||
## System details
|
||||
|
||||
- Distro:
|
||||
- Kernel: (`uname -r`)
|
||||
- Desktop:
|
||||
- Xorg or wayland: ??
|
||||
|
||||
/label ~bug ~reproducable ~needs-investigation
|
||||
789
CHANGELOG.md
6522
Cargo.lock
generated
74
Cargo.toml
@@ -1,23 +1,53 @@
|
||||
[workspace]
|
||||
members = ["asusctl", "config-traits", "daemon", "daemon-user", "rog-platform", "rog-dbus", "rog-anime", "rog-aura", "rog-profiles", "rog-control-center"]
|
||||
|
||||
[workspace.package]
|
||||
version = "4.6.1"
|
||||
version = "6.1.13"
|
||||
rust-version = "1.82"
|
||||
license = "MPL-2.0"
|
||||
readme = "README.md"
|
||||
authors = ["Luke <luke@ljones.dev>"]
|
||||
repository = "https://gitlab.com/asus-linux/asusctl"
|
||||
homepage = "https://gitlab.com/asus-linux/asusctl"
|
||||
description = "Laptop feature control for ASUS ROG laptops and others"
|
||||
edition = "2021"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = [
|
||||
"asusctl",
|
||||
"asusd",
|
||||
"asusd-user",
|
||||
"config-traits",
|
||||
"dmi-id",
|
||||
"rog-platform",
|
||||
"rog-dbus",
|
||||
"rog-anime",
|
||||
"rog-aura",
|
||||
"rog-profiles",
|
||||
"rog-control-center",
|
||||
"rog-slash",
|
||||
"simulators",
|
||||
"rog-scsi",
|
||||
]
|
||||
|
||||
default-members = ["asusctl", "asusd", "asusd-user", "rog-control-center"]
|
||||
|
||||
[workspace.dependencies]
|
||||
async-trait = "^0.1"
|
||||
tokio = { version = "^1.23.0", features = ["macros", "rt-multi-thread", "time", "sync"]}
|
||||
tokio = { version = "^1.39.0", default-features = false, features = [
|
||||
"macros",
|
||||
"sync",
|
||||
"time",
|
||||
"rt",
|
||||
"rt-multi-thread",
|
||||
] }
|
||||
concat-idents = "^1.1"
|
||||
dirs = "^4.0"
|
||||
smol = "^1.3"
|
||||
smol = "^2.0"
|
||||
mio = "0.8.11"
|
||||
|
||||
zbus = "^3.6"
|
||||
logind-zbus = { version = "^3.1.0" } #, default-features = false, features = ["non_blocking"] }
|
||||
futures-util = "0.3.31"
|
||||
zbus = "5.5.0"
|
||||
logind-zbus = { version = "5.2.0" } #, default-features = false, features = ["non_blocking"] }
|
||||
|
||||
serde = "^1.0"
|
||||
serde_derive = "^1.0"
|
||||
serde_json = "^1.0"
|
||||
toml = "^0.5.10"
|
||||
serde = { version = "^1.0", features = ["serde_derive"] }
|
||||
ron = "*"
|
||||
|
||||
log = "^0.4"
|
||||
@@ -25,9 +55,8 @@ env_logger = "^0.10.0"
|
||||
|
||||
glam = { version = "^0.22", features = ["serde"] }
|
||||
gumdrop = "^0.8"
|
||||
udev = "^0.7"
|
||||
udev = { version = "^0.8", features = ["mio"] }
|
||||
rusb = "^0.9"
|
||||
sysfs-class = "^0.1.3"
|
||||
inotify = "^0.10.0"
|
||||
|
||||
png_pong = "^0.8"
|
||||
@@ -35,9 +64,11 @@ pix = "^0.13"
|
||||
tinybmp = "^0.4.0"
|
||||
gif = "^0.12.0"
|
||||
|
||||
versions = "4.1"
|
||||
versions = "6.2"
|
||||
|
||||
notify-rust = { git = "https://github.com/flukejones/notify-rust.git", default-features = false, features = ["z"] }
|
||||
notify-rust = { version = "4.11.5", features = ["z", "async"] }
|
||||
|
||||
sg = { git = "https://github.com/flukejones/sg-rs.git" }
|
||||
|
||||
[profile.release]
|
||||
# thin = 57s, asusd = 9.0M
|
||||
@@ -46,10 +77,15 @@ lto = "fat"
|
||||
debug = false
|
||||
opt-level = 3
|
||||
panic = "abort"
|
||||
# codegen-units = 1
|
||||
|
||||
[profile.dev]
|
||||
debug = true
|
||||
opt-level = 1
|
||||
# codegen-units = 1
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 1
|
||||
# codegen-units = 1
|
||||
|
||||
[profile.bench]
|
||||
debug = false
|
||||
@@ -58,4 +94,4 @@ opt-level = 3
|
||||
[workspace.dependencies.cargo-husky]
|
||||
version = "1"
|
||||
default-features = false
|
||||
features = ["user-hooks"]
|
||||
features = ["user-hooks"]
|
||||
|
||||
43
MANUAL.md
@@ -1,5 +1,7 @@
|
||||
# asusctrl manual
|
||||
|
||||
**NOTE:** this manual is in need of an update in some places. If you find issues please file issue reports.
|
||||
|
||||
`asusd` is a utility for Linux to control many aspects of various ASUS laptops
|
||||
but can also be used with non-asus laptops with reduced features.
|
||||
|
||||
@@ -8,11 +10,10 @@ but can also be used with non-asus laptops with reduced features.
|
||||
- `asusd`: The main system daemon. It is autostarted by a udev rule and systemd unit.
|
||||
- `asusd-user`: The user level daemon. Currently will run an anime sequence, with RGB keyboard sequences soon.
|
||||
- `asusctl`: The CLI for interacting with the system daemon
|
||||
- `asus-notify`: A notification daemon with a user systemd unit that can be enabled.
|
||||
|
||||
## `asusd`
|
||||
|
||||
`asusd` is the main system-level daemon which will control/load/save various settings in a safe way for the user, along with exposing a *safe* dbus interface for these interactions. This section covers only the daemon plus the various configuration file options.
|
||||
`asusd` is the main system-level daemon which will control/load/save various settings in a safe way for the user, along with exposing a _safe_ dbus interface for these interactions. This section covers only the daemon plus the various configuration file options.
|
||||
|
||||
The functionality that `asusd` exposes is:
|
||||
|
||||
@@ -47,7 +48,7 @@ The LED controller (e.g, aura) enables setting many of the factory modes availab
|
||||
|
||||
#### Supported laptops
|
||||
|
||||
There are over 60 supported laptops as of 01-01-2023. Please see [the rog-aura crate readme for further details](/rog-aura/README.md).
|
||||
There are over 80 supported laptops as of 01-01-2023. Please see [the rog-aura crate readme for further details](/rog-aura/README.md).
|
||||
|
||||
### Charge control
|
||||
|
||||
@@ -56,6 +57,7 @@ Almost all modern ASUS laptops have charging limit control now. This can be cont
|
||||
```json
|
||||
"bat_charge_limit": 80,
|
||||
```
|
||||
|
||||
where the number is a percentage.
|
||||
|
||||
### Bios control
|
||||
@@ -63,7 +65,7 @@ where the number is a percentage.
|
||||
Some options that you find in Armory Crate are available under this controller, so far there is:
|
||||
|
||||
- POST sound: this is the sound you hear on bios boot post
|
||||
- GPU MUX: this controls if the dGPU is the *only* GPU, making it the main GPU and disabling the iGPU
|
||||
- GPU MUX: this controls if the dGPU is the _only_ GPU, making it the main GPU and disabling the iGPU
|
||||
|
||||
These options are not written to the config file as they are stored in efivars. The only way to change these is to use the exposed safe dbus methods, or use the `asusctl` CLI tool.
|
||||
|
||||
@@ -72,6 +74,7 @@ These options are not written to the config file as they are stored in efivars.
|
||||
asusctl can support setting a power profile via platform_profile drivers. This requires [power-profiles-daemon](https://gitlab.freedesktop.org/hadess/power-profiles-daemon) v0.10.0 minimum. It also requires the kernel patch for platform_profile support to be applied form [here](https://lkml.org/lkml/2021/8/18/1022) - this patch is merged to 5.15 kernel upstream.
|
||||
|
||||
A common use of asusctl is to bind the `fn+f5` (fan) key to `asusctl profile -n` to cycle through the 3 profiles:
|
||||
|
||||
1. Balanced
|
||||
2. Performance
|
||||
3. Quiet
|
||||
@@ -97,7 +100,7 @@ There is one more controller; the support controller. The sole pupose of this co
|
||||
|
||||
## asusd-user
|
||||
|
||||
`asusd-user` is a usermode daemon. The intended purpose is to provide a method for users to run there own custom per-key keyboard effects and modes, AniMe sequences, and possibly their own profiles - all without overwriting the *base* system config. As such some parts of the system daemon will migrate to the user daemon over time with the expectation that the Linux system runs both.
|
||||
`asusd-user` is a usermode daemon. The intended purpose is to provide a method for users to run there own custom per-key keyboard effects and modes, AniMe sequences, and possibly their own profiles - all without overwriting the _base_ system config. As such some parts of the system daemon will migrate to the user daemon over time with the expectation that the Linux system runs both.
|
||||
|
||||
As of now only AniMe is active in this with configuration in `~/.config/rog/`. On first run defaults are created that are intended to work as examples.
|
||||
|
||||
@@ -177,6 +180,7 @@ An Aura config itself is a file with contents:
|
||||
```
|
||||
|
||||
If your laptop supports multizone, `"led"` can also be `"Zone": <one of the following>`
|
||||
|
||||
- `SingleZone` // Keyboards with only one zone
|
||||
- `ZonedKbLeft` // keyboard left
|
||||
- `ZonedKbLeftMid` // keyboard left-middle
|
||||
@@ -238,6 +242,7 @@ Each object in the array can be one of:
|
||||
##### AsusAnimation
|
||||
|
||||
`AsusAnimation` is specifically for running the gif files that Armory Crate comes with. `asusctl` includes all of these in `/usr/share/asusd/anime/asus/`
|
||||
|
||||
```json
|
||||
"AsusAnimation": {
|
||||
"file": "<FILE_PATH>",
|
||||
@@ -260,7 +265,7 @@ Virtually the same as `AsusAnimation` but for png files, typically created in th
|
||||
|
||||
##### ImageAnimation
|
||||
|
||||
`ImageAnimation` can play *any* gif of any size.
|
||||
`ImageAnimation` can play _any_ gif of any size.
|
||||
|
||||
```json
|
||||
"ImageAnimation": {
|
||||
@@ -319,6 +324,7 @@ Must be full path: `"/usr/share/asusd/anime/asus/gaming/Controller.gif"` or `/ho
|
||||
**<FLOAT>**
|
||||
|
||||
A number from 0.0-1.0.
|
||||
|
||||
- `brightness`: If it is brightness it is combined with the system daemon global brightness
|
||||
- `scale`: 1.0 is the original size with lower number shrinking, larger growing
|
||||
- `angle`: Rotation angle in radians
|
||||
@@ -327,6 +333,7 @@ A number from 0.0-1.0.
|
||||
**<TIME>**
|
||||
|
||||
Time is the length of time to run the gif for:
|
||||
|
||||
```json
|
||||
"time": {
|
||||
"Time": {
|
||||
@@ -335,17 +342,23 @@ Time is the length of time to run the gif for:
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
A cycle is how many gif loops to run:
|
||||
|
||||
```json
|
||||
"time": {
|
||||
"Cycles": 2
|
||||
},
|
||||
```
|
||||
|
||||
`Infinite` means that this gif will never end:
|
||||
|
||||
```json
|
||||
"time": "Infinite",
|
||||
```
|
||||
|
||||
`Fade` allows an image or gif to fade in and out, and remain at max brightness to n time:
|
||||
|
||||
```json
|
||||
"time": {
|
||||
"Fade": {
|
||||
@@ -364,6 +377,7 @@ A cycle is how many gif loops to run:
|
||||
}
|
||||
},
|
||||
```
|
||||
|
||||
`show_for` can be `null`, if it is `null` then the `show_for` becomes `gif_time_length - fade_in - fade_out`.
|
||||
This is period for which the gif or image will be max brightness (as set).
|
||||
|
||||
@@ -404,26 +418,19 @@ asusctl <command> <subcommand> --help
|
||||
|
||||
To switch to next/previous Aura modes you will need to bind both the aura keys (if available) to one of:
|
||||
**Next**
|
||||
|
||||
```
|
||||
asusctl led-mode -n
|
||||
asusctl aura -n
|
||||
```
|
||||
|
||||
**Previous**
|
||||
|
||||
```
|
||||
asusctl led-mode -p
|
||||
asusctl aura -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)
|
||||
|
||||
85
Makefile
@@ -1,4 +1,4 @@
|
||||
VERSION := $(shell /usr/bin/grep -Pm1 'version = "(\d.\d.\d)"' Cargo.toml | cut -d'"' -f2)
|
||||
VERSION := $(shell /usr/bin/grep -Pm1 'version = "(\d+.\d+.\d+.*)"' Cargo.toml | cut -d'"' -f2)
|
||||
|
||||
INSTALL = install
|
||||
INSTALL_PROGRAM = ${INSTALL} -D -m 0755
|
||||
@@ -17,12 +17,24 @@ BIN_D := asusd
|
||||
BIN_U := asusd-user
|
||||
LEDCFG := aura_support.ron
|
||||
|
||||
DESTDIR_REALPATH = $(shell realpath $(DESTDIR))
|
||||
|
||||
SRC := Cargo.toml Cargo.lock Makefile $(shell find -type f -wholename '**/src/*.rs')
|
||||
|
||||
STRIP_BINARIES ?= 0
|
||||
|
||||
DEBUG ?= 0
|
||||
ifeq ($(DEBUG),0)
|
||||
ARGS += --release
|
||||
TARGET = release
|
||||
else
|
||||
ARGS += --profile dev
|
||||
TARGET = debug
|
||||
endif
|
||||
|
||||
X11 ?= 0
|
||||
ifeq ($(X11),1)
|
||||
ARGS += --features "rog-control-center/x11"
|
||||
endif
|
||||
|
||||
VENDORED ?= 0
|
||||
@@ -38,24 +50,31 @@ clean:
|
||||
distclean:
|
||||
rm -rf .cargo vendor vendor.tar.xz
|
||||
|
||||
install-program:
|
||||
$(INSTALL_PROGRAM) "./target/release/$(BIN_ROG)" "$(DESTDIR)$(bindir)/$(BIN_ROG)"
|
||||
target/$(TARGET)/$(BIN_D): build
|
||||
target/$(TARGET)/$(BIN_C): build
|
||||
target/$(TARGET)/$(BIN_U): build
|
||||
target/$(TARGET)/$(BIN_ROG): build
|
||||
|
||||
$(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-asusd: target/$(TARGET)/$(BIN_D)
|
||||
$(INSTALL_PROGRAM) "./target/$(TARGET)/$(BIN_D)" "$(DESTDIR)$(bindir)/$(BIN_D)"
|
||||
|
||||
install-data:
|
||||
install-asusctl: target/$(TARGET)/$(BIN_C)
|
||||
$(INSTALL_PROGRAM) "./target/$(TARGET)/$(BIN_C)" "$(DESTDIR)$(bindir)/$(BIN_C)"
|
||||
|
||||
install-asusd_user: target/$(TARGET)/$(BIN_U)
|
||||
$(INSTALL_PROGRAM) "./target/$(TARGET)/$(BIN_U)" "$(DESTDIR)$(bindir)/$(BIN_U)"
|
||||
|
||||
install-rog_gui: target/$(TARGET)/$(BIN_ROG)
|
||||
$(INSTALL_PROGRAM) "./target/$(TARGET)/$(BIN_ROG)" "$(DESTDIR)$(bindir)/$(BIN_ROG)"
|
||||
|
||||
.PHONY: install-asusd install-asusctl install-asusd_user install-rog_gui
|
||||
|
||||
install-program: install-asusd install-asusctl install-asusd_user install-rog_gui
|
||||
|
||||
install-data-rog_gui:
|
||||
$(INSTALL_DATA) "./rog-control-center/data/$(BIN_ROG).desktop" "$(DESTDIR)$(datarootdir)/applications/$(BIN_ROG).desktop"
|
||||
$(INSTALL_DATA) "./rog-control-center/data/$(BIN_ROG).png" "$(DESTDIR)$(datarootdir)/icons/hicolor/512x512/apps/$(BIN_ROG).png"
|
||||
cd rog-aura/data/layouts && find . -type f -name "*.ron" -exec $(INSTALL_DATA) "{}" "$(DESTDIR)$(datarootdir)/rog-gui/layouts/{}" \;
|
||||
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).rules" "$(DESTDIR)$(libdir)/udev/rules.d/99-$(BIN_D).rules"
|
||||
$(INSTALL_DATA) "./rog-aura/data/$(LEDCFG)" "$(DESTDIR)$(datarootdir)/asusd/$(LEDCFG)"
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).conf" "$(DESTDIR)$(datarootdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).service" "$(DESTDIR)$(libdir)/systemd/system/$(BIN_D).service"
|
||||
$(INSTALL_DATA) "./data/$(BIN_U).service" "$(DESTDIR)$(libdir)/systemd/user/$(BIN_U).service"
|
||||
cd rog-aura/data/layouts && find . -type f -name "*.ron" -exec $(INSTALL_DATA) "{}" "$(DESTDIR_REALPATH)$(datarootdir)/rog-gui/layouts/{}" \;
|
||||
|
||||
$(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"
|
||||
@@ -71,9 +90,24 @@ install-data:
|
||||
$(INSTALL_DATA) "./data/icons/scalable/gpu-vfio.svg" "$(DESTDIR)$(datarootdir)/icons/hicolor/scalable/status/gpu-vfio.svg"
|
||||
$(INSTALL_DATA) "./data/icons/scalable/notification-reboot.svg" "$(DESTDIR)$(datarootdir)/icons/hicolor/scalable/status/notification-reboot.svg"
|
||||
|
||||
cd rog-anime/data && find "./anime" -type f -exec $(INSTALL_DATA) "{}" "$(DESTDIR)$(datarootdir)/asusd/{}" \;
|
||||
install-data-asusd:
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).rules" "$(DESTDIR)$(libdir)/udev/rules.d/99-$(BIN_D).rules"
|
||||
$(INSTALL_DATA) "./rog-aura/data/$(LEDCFG)" "$(DESTDIR)$(datarootdir)/asusd/$(LEDCFG)"
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).conf" "$(DESTDIR)$(datarootdir)/dbus-1/system.d/$(BIN_D).conf"
|
||||
|
||||
$(INSTALL_DATA) "./data/$(BIN_D).service" "$(DESTDIR)$(libdir)/systemd/system/$(BIN_D).service"
|
||||
|
||||
cd rog-anime/data && find "./anime" -type f -exec $(INSTALL_DATA) "{}" "$(DESTDIR_REALPATH)$(datarootdir)/asusd/{}" \;
|
||||
|
||||
install-data-asusd_user:
|
||||
$(INSTALL_DATA) "./data/$(BIN_U).service" "$(DESTDIR)$(libdir)/systemd/user/$(BIN_U).service"
|
||||
|
||||
.PHONY: install-data-asusd install-data-asusd_user
|
||||
|
||||
install-data: install-data-asusd install-data-rog_gui
|
||||
|
||||
install: install-program install-data
|
||||
$(INSTALL_DATA) "./LICENSE" "$(DESTDIR)$(datarootdir)/asusctl/LICENSE"
|
||||
|
||||
uninstall:
|
||||
rm -f "$(DESTDIR)$(bindir)/$(BIN_ROG)"
|
||||
@@ -107,18 +141,27 @@ vendor:
|
||||
echo 'directory = "vendor"' >> .cargo/config
|
||||
mv .cargo/config ./cargo-config
|
||||
rm -rf .cargo
|
||||
rm -rf vendor
|
||||
cargo vendor-filterer --all-features --platform x86_64-unknown-linux-gnu vendor
|
||||
tar pcfJ vendor_asusctl_$(VERSION).tar.xz vendor
|
||||
rm -rf vendor
|
||||
|
||||
translate:
|
||||
find -name \*.slint | xargs slint-tr-extractor -o rog-control-center/translations/en/rog-control-center.po
|
||||
|
||||
build:
|
||||
ifeq ($(VENDORED),1)
|
||||
cargo vendor
|
||||
@echo "version = $(VERSION)"
|
||||
tar pxf vendor_asusctl_$(VERSION).tar.xz
|
||||
endif
|
||||
cargo build $(ARGS)
|
||||
strip -s ./target/release/$(BIN_C)
|
||||
strip -s ./target/release/$(BIN_D)
|
||||
strip -s ./target/release/$(BIN_U)
|
||||
strip -s ./target/release/$(BIN_ROG)
|
||||
ifeq ($(STRIP_BINARIES),1)
|
||||
strip -s ./target/$(TARGET)/$(BIN_C)
|
||||
strip -s ./target/$(TARGET)/$(BIN_D)
|
||||
strip -s ./target/$(TARGET)/$(BIN_U)
|
||||
strip -s ./target/$(TARGET)/$(BIN_ROG)
|
||||
endif
|
||||
|
||||
.PHONY: all clean distclean install uninstall update build
|
||||
|
||||
.PHONY: all clean distclean install uninstall update build bindings
|
||||
|
||||
125
README.md
@@ -1,8 +1,8 @@
|
||||
# `asusctl` for ASUS ROG
|
||||
|
||||
[](https://www.paypal.com/donate/?hosted_button_id=4V2DEPS7K6APC) - [Asus Linux Website](https://asus-linux.org/)
|
||||
[](https://www.patreon.com/bePatron?u=7602281) [](https://ko-fi.com/V7V5CLU67) - [Asus Linux Website](https://asus-linux.org/)
|
||||
|
||||
**WARNING:** Many features are developed in tandem with kernel patches. If you see a feature is missing you either need a patched kernel, or v6.1 which has all my work merged upstream.
|
||||
**WARNING:** Many features are developed in tandem with kernel patches. If you see a feature is missing you either need a patched kernel or latest release.
|
||||
|
||||
`asusd` is a utility for Linux to control many aspects of various ASUS laptops
|
||||
but can also be used with non-asus laptops with reduced features.
|
||||
@@ -11,27 +11,35 @@ Now includes a GUI, `rog-control-center`.
|
||||
|
||||
## Kernel support
|
||||
|
||||
**The minimum supported kernel version is 5.17**
|
||||
Due to on-going driver work the minimum suggested kernel version is always **the latest*, as improvements and fixes are continuous.
|
||||
|
||||
**For TUF laptops, the minimum supported kernel version is 6.1**
|
||||
Support for some new features is not avilable unless you run a patched kernel with the work I am doing [in this github repo](https://github.com/flukejones/linux/tree/wip/ally-6.13). Use the linked branch, or `wip/ally-6.12`. Everything that is done here is upstreamed eventually (a long process).
|
||||
|
||||
Z13 devices will need [these](https://lore.kernel.org/linux-input/20240416090402.31057-1-luke@ljones.dev/T/#t)
|
||||
|
||||
## X11 support
|
||||
|
||||
X11 is not supported at all, as in I will not help you with X11 issues if there are any due to limited time and it being unmaintained itself. You can however build `rog-control-center` with it enabled `cargo build --features "rog-control-center/x11"`.
|
||||
|
||||
## Goals
|
||||
|
||||
1. To provide an interface for rootless control of some system functions most users wish to control such as fan speeds, keyboard LEDs, graphics modes.
|
||||
2. Enable third-party apps to use the above with dbus methods
|
||||
3. To make the above as easy as possible for new users
|
||||
4. Respect the users resources: be small, light, and fast
|
||||
The main goal of this work is to provide a safe and easy to use abstraction over various laptop features via DBUS, and to provide some helpful defaults and other behaviour such as toggling throttle/profile on AC/battery change.
|
||||
|
||||
Point 3 means that the list of supported distros is very narrow - fedora is explicitly
|
||||
supported. All other distros are *not* supported (while asusd might still run fine on them).
|
||||
For best support use fedora 36+ Workstation.
|
||||
1. Provide safe dbus interface
|
||||
2. Respect the users resources: be small, light, and fast
|
||||
|
||||
Point 4? asusd currently uses a tiny fraction of cpu time, and less than 1Mb of ram, the way
|
||||
a system-level daemon should.
|
||||
a system-level daemon should. Languages such as JS and python should never be used for system level daemons (please stop).
|
||||
|
||||
## Keyboard LEDs
|
||||
|
||||
The level of support for laptops is dependent on folks submitting data to include in [`./rog-aura/data/layouts/aura_support.ron`](./rog-aura/data/layouts/aura_support.ron), typically installed in `/usr/share/asusd/aura_support.ron`. This is because the controller used for keyboards and LEDs is used across many years and many laptop models, all with different firmware configurations - the only way to track this is with the file mentioned above. Why not just enable all by default? Because it confuses people.
|
||||
|
||||
See the [rog-aura readme](./rog-aura/README.md) for more details.
|
||||
|
||||
## Discord
|
||||
|
||||
[Discord server link](https://discord.gg/4ZKGd7Un5t)
|
||||
[](https://discord.gg/B8GftRW2Hd)
|
||||
|
||||
## SUPPORTED LAPTOPS
|
||||
|
||||
@@ -42,56 +50,43 @@ to this:
|
||||
Bus 001 Device 002: ID 0b05:1866 ASUSTek Computer, Inc. N-KEY Device
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
Bus 003 Device 002: ID 0b05:19b6 ASUSTek Computer, Inc. [unknown]
|
||||
```
|
||||
|
||||
then it may work without tweaks. Technically all other functions except the LED
|
||||
and AniMe parts should work regardless of your latop make.
|
||||
|
||||
## Implemented
|
||||
|
||||
- [X] System daemon
|
||||
- [X] GUI app
|
||||
- [X] User notifications daemon
|
||||
- [X] Setting/modifying built-in LED modes
|
||||
- [X] Per-key LED setting
|
||||
- [X] Fancy LED modes (See examples) (currently being reworked)
|
||||
- [X] Saving settings for reload
|
||||
- [X] AniMatrix display on G14 models that include it
|
||||
- [X] Set battery charge limit (with kernel supporting this)
|
||||
- [X] Fan curve control on supported laptops (G14/G15, some TUF like FA507)
|
||||
- [X] Toggle bios setting for boot/POST sound
|
||||
- [X] Toggle GPU MUX (g-sync, or called MUX on 2022+ laptops)
|
||||
The list is a bit outdated as many features have been enabled in the Linux kernel with upstream patches and then supported in asusctl suite.
|
||||
|
||||
- [x] System daemon
|
||||
- [x] GUI app (includes tray and notifications)
|
||||
- [x] Setting/modifying built-in LED modes
|
||||
- [x] Per-key LED setting
|
||||
- [x] Fancy LED modes (See examples) (currently being reworked)
|
||||
- [x] AniMatrix display on G14 and M16 models that include it
|
||||
- [x] Set battery charge limit (with kernel supporting this)
|
||||
- [x] Fan curve control on supported laptops (G14/G15, some TUF like FA507)
|
||||
- [x] Toggle bios setting for boot/POST sound
|
||||
- [x] Toggle GPU MUX (g-sync, or called MUX on 2022+ laptops)
|
||||
|
||||
# GUI
|
||||
|
||||
A gui is now in the repo - ROG Control Center. At this time it is still a WIP, but it has almost all features in place already.
|
||||
|
||||

|
||||

|
||||

|
||||
**NOTE**: Xorg is not supported.
|
||||
|
||||
# BUILDING
|
||||
|
||||
Requirements are rust >= 1.57 installed from rustup.io if the distro provided version is too old, and `make`.
|
||||
|
||||
**Ubuntu (unsuported):**
|
||||
|
||||
apt install libgtk-3-dev libpango1.0-dev libgdk-pixbuf-2.0-dev libglib2.0-dev cmake libclang-dev libudev-dev libayatana-appindicator3-1
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
source "$HOME/.cargo/env"
|
||||
make
|
||||
sudo make install
|
||||
|
||||
**popos (unsuported):**
|
||||
|
||||
sudo apt install cmake libclang-dev libudev-dev libgtk-3-dev libclang-dev libglib2.0-dev libatkmm-1.6-dev libpangomm-1.4-dev librust-gdk-pixbuf-dev
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
source "$HOME/.cargo/env"
|
||||
make
|
||||
sudo make install
|
||||
|
||||
Rust and cargo are required, they can be installed from [rustup.rs](https://rustup.rs/) or from the distro repos if newer than 1.75.
|
||||
|
||||
**fedora:**
|
||||
|
||||
dnf install cmake clang-devel systemd-devel glib2-devel cairo-devel atkmm-devel pangomm-devel gdk-pixbuf2-devel gtk3-devel libappindicator-gtk3
|
||||
dnf install cmake clang-devel libxkbcommon-devel systemd-devel expat-devel pcre2-devel libzstd-devel gtk3-devel
|
||||
make
|
||||
sudo make install
|
||||
|
||||
@@ -100,28 +95,48 @@ Requirements are rust >= 1.57 installed from rustup.io if the distro provided ve
|
||||
Works with KDE Plasma (without GTK packages)
|
||||
|
||||
zypper in -t pattern devel_basis
|
||||
zypper in rustup make cmake systemd-devel clang-devel llvm-devel gdk-pixbuf-devel cairo-devel pango-devel freetype-devel gtk3-devel libexpat-devel libayatana-indicator3-7
|
||||
zypper in rustup make cmake clang-devel libxkbcommon-devel systemd-devel expat-devel pcre2-devel libzstd-devel gtk3-devel
|
||||
make
|
||||
sudo make install
|
||||
|
||||
**Debian(unsuported):**
|
||||
|
||||
officially unsuported,but you can still try and test it by yourself(some features may not be available).
|
||||
|
||||
sudo apt install libclang-dev libudev-dev libfontconfig-dev build-essential cmake libxkbcommon-dev
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
make
|
||||
sudo make install
|
||||
|
||||
**Ubuntu, Popos (unsuported):**
|
||||
|
||||
```sh
|
||||
sudo apt install make cargo gcc pkg-config openssl libasound2-dev cmake build-essential python3 libfreetype6-dev libexpat1-dev libxcb-composite0-dev libssl-dev libx11-dev libfontconfig1-dev curl libclang-dev libudev-dev checkinstall libseat-dev libinput-dev libxkbcommon-dev libgbm-dev
|
||||
|
||||
make
|
||||
sudo make install
|
||||
```
|
||||
|
||||
## Installing
|
||||
|
||||
- Fedora copr = https://copr.fedorainfracloud.org/coprs/lukenukem/asus-linux/
|
||||
- openSUSE = https://download.opensuse.org/repositories/home:/luke_nukem:/asus/
|
||||
- Ubuntu = not supported due to packaging woes, but you can build and install on your own.
|
||||
|
||||
=======
|
||||
|
||||
The default init method is to use the udev rule, this ensures that the service is
|
||||
started when the device is initialised and ready.
|
||||
|
||||
You may also need to activate the service for debian install. If running Pop!\_OS, I suggest disabling `system76-power` gnome-shell extension and systemd service.
|
||||
|
||||
## Upgrading
|
||||
|
||||
If you are upgrading from a previous installed version, you will need to restart the service or reboot.
|
||||
|
||||
```
|
||||
$ systemctl daemon-reload && systemctl restart asusd
|
||||
```
|
||||
|
||||
You may also need to activate the service for debian install. If running Pop!_OS, I suggest disabling `system76-power` gnome-shell extension and systemd service.
|
||||
|
||||
## Uninstalling
|
||||
|
||||
Run `sudo make uninstall` in the source repo, and remove `/etc/asusd/`.
|
||||
@@ -130,8 +145,16 @@ Run `sudo make uninstall` in the source repo, and remove `/etc/asusd/`.
|
||||
|
||||
See `CONTRIBUTING.md`. Additionally, also do `cargo clean` and `cargo test` on first checkout to ensure the commit hooks are used (via `cargo-husky`).
|
||||
|
||||
Generation of the bindings with `make bindings` requires `typeshare` to be installed.
|
||||
|
||||
Dbus introsepction XML requires with `make introspection` requires `anime_sim` to be running before starting `asusd`.
|
||||
|
||||
# OTHER
|
||||
|
||||
## AniMe Matrix simulator
|
||||
|
||||
A simulator using SDL2 can be built using `cargo build --package rog_simulators` and run with `./target/debug/anime_sim`. Once started `asusd` will need restarting to pick it up. If running this sim on a laptop _with_ the display, the simulated display will be used instead of the physical display.
|
||||
|
||||
## Supporting more laptops
|
||||
|
||||
Please file a support request.
|
||||
|
||||
@@ -1,26 +1,41 @@
|
||||
[package]
|
||||
name = "asusctl"
|
||||
license = "MPL-2.0"
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_scsi = { path = "../rog-scsi" }
|
||||
rog_slash = { path = "../rog-slash" }
|
||||
rog_aura = { path = "../rog-aura" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
rog_platform = { path = "../rog-platform" }
|
||||
daemon = { path = "../daemon" }
|
||||
dmi_id = { path = "../dmi-id" }
|
||||
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
ron.workspace = true
|
||||
gumdrop.workspace = true
|
||||
toml.workspace = true
|
||||
sysfs-class.workspace = true
|
||||
zbus.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
gif.workspace = true
|
||||
tinybmp.workspace = true
|
||||
glam.workspace = true
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
|
||||
cargo-husky.workspace = true
|
||||
[package.metadata.deb]
|
||||
license-file = ["../LICENSE", "4"]
|
||||
extended-description = """\
|
||||
An utility for Linux to control many aspects of various ASUS laptops
|
||||
but can also be used with non-asus laptops with reduced features."""
|
||||
depends = "$auto"
|
||||
section = "utility"
|
||||
priority = "optional"
|
||||
assets = [
|
||||
["target/release/asusctl", "usr/bin/", "755"],
|
||||
]
|
||||
|
||||
@@ -5,12 +5,14 @@ use std::process::exit;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{AnimeDiagonal, AnimeType};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Usage: <filepath> <brightness>");
|
||||
println!("e.g, asusctl/examples/doom_large.png 0.8");
|
||||
@@ -24,13 +26,9 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
AnimeType::GA401,
|
||||
)?;
|
||||
|
||||
let anime_type = get_anime_type()?;
|
||||
let anime_type = get_anime_type();
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(matrix.into_data_buffer(anime_type)?)
|
||||
.unwrap();
|
||||
proxy.write(matrix.into_data_buffer(anime_type)?).unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ use std::time::Duration;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{AnimeDiagonal, AnimeType};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
@@ -11,26 +12,25 @@ use rog_dbus::RogDbusClientBlocking;
|
||||
// 74w x 36h diagonal used by the windows app
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
for step in (2..50).rev() {
|
||||
let mut matrix = AnimeDiagonal::new(AnimeType::GA401, None);
|
||||
for c in (0..60).into_iter().step_by(step) {
|
||||
for c in (0..60).step_by(step) {
|
||||
for i in matrix.get_mut().iter_mut() {
|
||||
i[c] = 50;
|
||||
}
|
||||
}
|
||||
|
||||
for c in (0..35).into_iter().step_by(step) {
|
||||
for c in (0..35).step_by(step) {
|
||||
for i in &mut matrix.get_mut()[c] {
|
||||
*i = 50;
|
||||
}
|
||||
}
|
||||
|
||||
let anime_type = get_anime_type().unwrap();
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
let anime_type = get_anime_type();
|
||||
proxy
|
||||
.write(matrix.into_data_buffer(anime_type).unwrap())
|
||||
.unwrap();
|
||||
sleep(Duration::from_millis(300));
|
||||
|
||||
@@ -4,12 +4,14 @@ use std::thread::sleep;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{ActionData, ActionLoader, Sequences};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() != 3 {
|
||||
println!("Please supply filepath and brightness");
|
||||
return;
|
||||
@@ -17,27 +19,20 @@ fn main() {
|
||||
|
||||
let path = Path::new(&args[1]);
|
||||
let brightness = args[2].parse::<f32>().unwrap();
|
||||
let anime_type = get_anime_type().unwrap();
|
||||
let anime_type = get_anime_type();
|
||||
let mut seq = Sequences::new(anime_type);
|
||||
seq.insert(
|
||||
0,
|
||||
&ActionLoader::AsusAnimation {
|
||||
file: path.into(),
|
||||
time: rog_anime::AnimTime::Infinite,
|
||||
brightness,
|
||||
},
|
||||
)
|
||||
seq.insert(0, &ActionLoader::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();
|
||||
proxy.write(frame.frame().clone()).unwrap();
|
||||
sleep(frame.delay());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@ use std::convert::TryFrom;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{AnimeDataBuffer, AnimeGrid};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
@@ -10,8 +11,10 @@ use rog_dbus::RogDbusClientBlocking;
|
||||
// 74w x 36h diagonal used by the windows app
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let anime_type = get_anime_type().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let anime_type = get_anime_type();
|
||||
let mut matrix = AnimeGrid::new(anime_type);
|
||||
let tmp = matrix.get_mut();
|
||||
|
||||
@@ -43,5 +46,5 @@ fn main() {
|
||||
|
||||
let matrix = <AnimeDataBuffer>::try_from(matrix).unwrap();
|
||||
|
||||
client.proxies().anime().write(matrix).unwrap();
|
||||
proxy.write(matrix).unwrap();
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::AnimeDataBuffer;
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
// In usable data:
|
||||
// Top row start at 1, ends at 32
|
||||
|
||||
fn main() {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let anime_type = get_anime_type().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
let anime_type = get_anime_type();
|
||||
let mut matrix = AnimeDataBuffer::new(anime_type);
|
||||
matrix.data_mut()[1] = 100; // start = 1
|
||||
for n in matrix.data_mut()[2..32].iter_mut() {
|
||||
@@ -127,5 +129,5 @@ fn main() {
|
||||
matrix.data_mut()[1244] = 100; // end
|
||||
println!("{:?}", &matrix);
|
||||
|
||||
client.proxies().anime().write(matrix).unwrap();
|
||||
proxy.write(matrix).unwrap();
|
||||
}
|
||||
|
||||
@@ -6,19 +6,21 @@ use std::process::exit;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() != 7 {
|
||||
println!("Usage: <filepath> <scale> <angle> <x pos> <y pos> <brightness>");
|
||||
println!("e.g, asusctl/examples/doom_large.png 0.9 0.4 0.0 0.0 0.8");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
let anime_type = get_anime_type()?;
|
||||
let anime_type = get_anime_type();
|
||||
let matrix = AnimeImage::from_png(
|
||||
Path::new(&args[1]),
|
||||
args[2].parse::<f32>().unwrap(),
|
||||
@@ -31,11 +33,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
anime_type,
|
||||
)?;
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::try_from(&matrix)?)
|
||||
.unwrap();
|
||||
proxy.write(<AnimeDataBuffer>::try_from(&matrix)?).unwrap();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -9,19 +9,21 @@ use std::time::Duration;
|
||||
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::{AnimeDataBuffer, AnimeImage, Vec2};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let args: Vec<String> = env::args().into_iter().collect();
|
||||
let args: Vec<String> = env::args().collect();
|
||||
if args.len() != 7 {
|
||||
println!("Usage: <filepath> <scale> <angle> <x pos> <y pos> <brightness>");
|
||||
println!("e.g, asusctl/examples/doom_large.png 0.9 0.4 0.0 0.0 0.8");
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
let anime_type = get_anime_type()?;
|
||||
let anime_type = get_anime_type();
|
||||
let mut matrix = AnimeImage::from_png(
|
||||
Path::new(&args[1]),
|
||||
args[2].parse::<f32>().unwrap(),
|
||||
@@ -41,11 +43,7 @@ fn main() -> Result<(), Box<dyn Error>> {
|
||||
}
|
||||
matrix.update();
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(<AnimeDataBuffer>::try_from(&matrix)?)
|
||||
.unwrap();
|
||||
proxy.write(<AnimeDataBuffer>::try_from(&matrix)?).unwrap();
|
||||
sleep(Duration::from_micros(500));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
//! Using a combination of key-colour array plus a key layout to generate
|
||||
//! outputs.
|
||||
|
||||
use rog_aura::advanced::LedCode;
|
||||
use rog_aura::effects::{AdvancedEffects, Effect};
|
||||
use rog_aura::layouts::KeyLayout;
|
||||
use rog_aura::keyboard::{KeyLayout, LedCode};
|
||||
use rog_aura::Colour;
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_dbus::zbus_aura::AuraProxyBlocking;
|
||||
use zbus::blocking::Connection;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let layout = KeyLayout::default_layout();
|
||||
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let conn = Connection::system().unwrap();
|
||||
let proxy = AuraProxyBlocking::new(&conn).unwrap();
|
||||
|
||||
let mut seq = AdvancedEffects::new(true);
|
||||
|
||||
@@ -32,7 +33,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let zone = Effect::DoomFlicker(rog_aura::effects::DoomFlicker::new(
|
||||
LedCode::SingleZone,
|
||||
Colour(200, 110, 0),
|
||||
Colour {
|
||||
r: 200,
|
||||
g: 110,
|
||||
b: 0,
|
||||
},
|
||||
100,
|
||||
10,
|
||||
));
|
||||
@@ -58,7 +63,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
seq.next_state(&layout);
|
||||
let packets = seq.create_packets();
|
||||
|
||||
client.proxies().led().direct_addressing_raw(packets)?;
|
||||
proxy.direct_addressing_raw(packets)?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(33));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,44 @@
|
||||
use gumdrop::Options;
|
||||
use rog_anime::usb::{AnimAwake, AnimBooting, AnimShutdown, AnimSleeping, Brightness};
|
||||
use rog_anime::AnimeType;
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct AnimeCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(meta = "", help = "override the display type")]
|
||||
pub override_type: Option<AnimeType>,
|
||||
#[options(meta = "", help = "enable/disable the display")]
|
||||
pub enable_display: Option<bool>,
|
||||
#[options(meta = "", help = "enable/disable the builtin run/powersave animation")]
|
||||
pub enable_powersave_anim: Option<bool>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "enable/disable the panel LEDs (does not erase last image)"
|
||||
help = "set global base brightness value <Off, Low, Med, High>"
|
||||
)]
|
||||
pub enable: Option<bool>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "enable/disable system animations (boot/sleep/shutdown)"
|
||||
)]
|
||||
pub boot_enable: Option<bool>,
|
||||
#[options(meta = "", help = "set global AniMe brightness value")]
|
||||
pub brightness: Option<f32>,
|
||||
pub brightness: Option<Brightness>,
|
||||
#[options(help = "clear the display")]
|
||||
pub clear: bool,
|
||||
#[options(
|
||||
no_short,
|
||||
meta = "",
|
||||
help = "turn the anime off when external power is unplugged"
|
||||
)]
|
||||
pub off_when_unplugged: Option<bool>,
|
||||
#[options(
|
||||
no_short,
|
||||
meta = "",
|
||||
help = "turn the anime off when the laptop suspends"
|
||||
)]
|
||||
pub off_when_suspended: Option<bool>,
|
||||
#[options(
|
||||
no_short,
|
||||
meta = "",
|
||||
help = "turn the anime off when the lid is closed"
|
||||
)]
|
||||
pub off_when_lid_closed: Option<bool>,
|
||||
#[options(no_short, meta = "", help = "Off with his head!!!")]
|
||||
pub off_with_his_head: Option<bool>,
|
||||
#[options(command)]
|
||||
pub command: Option<AnimeActions>,
|
||||
}
|
||||
@@ -32,6 +53,36 @@ pub enum AnimeActions {
|
||||
Gif(AnimeGif),
|
||||
#[options(help = "display an animated diagonal/pixel-perfect GIF")]
|
||||
PixelGif(AnimeGifDiagonal),
|
||||
#[options(help = "change which builtin animations are shown")]
|
||||
SetBuiltins(Builtins),
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct Builtins {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Default is used if unspecified, <default:GlitchConstruction, StaticEmergence>"
|
||||
)]
|
||||
pub boot: AnimBooting,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Default is used if unspecified, <default:BinaryBannerScroll, RogLogoGlitch>"
|
||||
)]
|
||||
pub awake: AnimAwake,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Default is used if unspecified, <default:BannerSwipe, Starfield>"
|
||||
)]
|
||||
pub sleep: AnimSleeping,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Default is used if unspecified, <default:GlitchOut, SeeYa>"
|
||||
)]
|
||||
pub shutdown: AnimShutdown,
|
||||
#[options(meta = "", help = "set/apply the animations <true/false>")]
|
||||
pub set: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
|
||||
@@ -4,81 +4,71 @@ use gumdrop::Options;
|
||||
use rog_aura::error::Error;
|
||||
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Colour, Direction, Speed};
|
||||
|
||||
#[derive(Options)]
|
||||
#[derive(Options, Debug)]
|
||||
pub struct LedPowerCommand1 {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(meta = "", help = "Control if LEDs enabled while awake <true/false>")]
|
||||
pub awake: Option<bool>,
|
||||
#[options(meta = "", help = "Use with awake option <true/false>")]
|
||||
pub keyboard: Option<bool>,
|
||||
#[options(meta = "", help = "Use with awake option <true/false>")]
|
||||
pub lightbar: Option<bool>,
|
||||
#[options(help = "Use with awake option, if excluded defaults to false")]
|
||||
pub keyboard: bool,
|
||||
#[options(help = "Use with awake option, if excluded defaults to false")]
|
||||
pub lightbar: bool,
|
||||
#[options(meta = "", help = "Control boot animations <true/false>")]
|
||||
pub boot: Option<bool>,
|
||||
#[options(meta = "", help = "Control suspend animations <true/false>")]
|
||||
pub sleep: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
#[derive(Options, Debug)]
|
||||
pub struct LedPowerCommand2 {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(command)]
|
||||
pub command: Option<SetAuraEnabled>,
|
||||
pub command: Option<SetAuraZoneEnabled>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub enum SetAuraEnabled {
|
||||
#[derive(Options, Debug)]
|
||||
pub enum SetAuraZoneEnabled {
|
||||
/// Applies to both old and new models
|
||||
#[options(help = "set <keyboard, logo, lightbar> to enabled while device is awake")]
|
||||
Awake(AuraEnabled),
|
||||
#[options(help = "set <keyboard, logo, lightbar> to enabled while the device is booting")]
|
||||
Boot(AuraEnabled),
|
||||
#[options(help = "set <keyboard, logo, lightbar> to animate while the device is suspended")]
|
||||
Sleep(AuraEnabled),
|
||||
#[options(help = "set <keyboard, logo, lightbar> to animate while the device is shutdown")]
|
||||
Shutdown(AuraEnabled),
|
||||
#[options(help = "")]
|
||||
Keyboard(AuraPowerStates),
|
||||
#[options(help = "")]
|
||||
Logo(AuraPowerStates),
|
||||
#[options(help = "")]
|
||||
Lightbar(AuraPowerStates),
|
||||
#[options(help = "")]
|
||||
Lid(AuraPowerStates),
|
||||
#[options(help = "")]
|
||||
RearGlow(AuraPowerStates),
|
||||
#[options(help = "")]
|
||||
Ally(AuraPowerStates),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Options)]
|
||||
pub struct AuraEnabled {
|
||||
#[derive(Debug, Clone, Options)]
|
||||
pub struct AuraPowerStates {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(meta = "", help = "<true/false>")]
|
||||
pub keyboard: Option<bool>,
|
||||
#[options(meta = "", help = "<true/false>")]
|
||||
pub logo: Option<bool>,
|
||||
#[options(meta = "", help = "<true/false>")]
|
||||
pub lightbar: Option<bool>,
|
||||
#[options(meta = "", help = "<true/false>")]
|
||||
pub lid: Option<bool>,
|
||||
#[options(help = "defaults to false if option unused")]
|
||||
pub boot: bool,
|
||||
#[options(help = "defaults to false if option unused")]
|
||||
pub awake: bool,
|
||||
#[options(help = "defaults to false if option unused")]
|
||||
pub sleep: bool,
|
||||
#[options(help = "defaults to false if option unused")]
|
||||
pub shutdown: bool,
|
||||
}
|
||||
|
||||
// impl FromStr for AuraEnabled {
|
||||
// type Err = Error;
|
||||
|
||||
// fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
// let s = s.to_lowercase();
|
||||
// Ok(Self {
|
||||
// help: false,
|
||||
// keyboard: None,
|
||||
// logo: None,
|
||||
// lightbar: None,
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct LedBrightness {
|
||||
level: Option<u32>,
|
||||
level: Option<u8>,
|
||||
}
|
||||
impl LedBrightness {
|
||||
pub fn new(level: Option<u32>) -> Self {
|
||||
pub fn new(level: Option<u8>) -> Self {
|
||||
LedBrightness { level }
|
||||
}
|
||||
|
||||
pub fn level(&self) -> Option<u32> {
|
||||
pub fn level(&self) -> Option<u8> {
|
||||
self.level
|
||||
}
|
||||
}
|
||||
@@ -99,6 +89,7 @@ impl FromStr for LedBrightness {
|
||||
}
|
||||
}
|
||||
}
|
||||
#[allow(clippy::to_string_trait_impl)]
|
||||
impl ToString for LedBrightness {
|
||||
fn to_string(&self) -> String {
|
||||
let s = match self.level {
|
||||
@@ -226,29 +217,29 @@ pub struct MultiColourSpeed {
|
||||
#[derive(Options)]
|
||||
pub enum SetAuraBuiltin {
|
||||
#[options(help = "set a single static colour")]
|
||||
Static(SingleColour),
|
||||
Static(SingleColour), // 0
|
||||
#[options(help = "pulse between one or two colours")]
|
||||
Breathe(TwoColourSpeed),
|
||||
Breathe(TwoColourSpeed), // 1
|
||||
#[options(help = "strobe through all colours")]
|
||||
Strobe(SingleSpeed),
|
||||
RainbowCycle(SingleSpeed), // 2
|
||||
#[options(help = "rainbow cycling in one of four directions")]
|
||||
Rainbow(SingleSpeedDirection),
|
||||
RainbowWave(SingleSpeedDirection), // 3
|
||||
#[options(help = "rain pattern mimicking raindrops")]
|
||||
Stars(TwoColourSpeed),
|
||||
Stars(TwoColourSpeed), // 4
|
||||
#[options(help = "rain pattern of three preset colours")]
|
||||
Rain(SingleSpeed),
|
||||
Rain(SingleSpeed), // 5
|
||||
#[options(help = "pressed keys are highlighted to fade")]
|
||||
Highlight(SingleColourSpeed),
|
||||
Highlight(SingleColourSpeed), // 6
|
||||
#[options(help = "pressed keys generate horizontal laser")]
|
||||
Laser(SingleColourSpeed),
|
||||
Laser(SingleColourSpeed), // 7
|
||||
#[options(help = "pressed keys ripple outwards like a splash")]
|
||||
Ripple(SingleColourSpeed),
|
||||
Ripple(SingleColourSpeed), // 8
|
||||
#[options(help = "set a rapid pulse")]
|
||||
Pulse(SingleColour),
|
||||
Pulse(SingleColour), // 10
|
||||
#[options(help = "set a vertical line zooming from left")]
|
||||
Comet(SingleColour),
|
||||
Comet(SingleColour), // 11
|
||||
#[options(help = "set a wide vertical line zooming from left")]
|
||||
Flash(SingleColour),
|
||||
Flash(SingleColour), // 12
|
||||
}
|
||||
|
||||
impl Default for SetAuraBuiltin {
|
||||
@@ -323,14 +314,14 @@ impl From<&SetAuraBuiltin> for AuraEffect {
|
||||
data.mode = AuraModeNum::Breathe;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Strobe(x) => {
|
||||
SetAuraBuiltin::RainbowCycle(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Strobe;
|
||||
data.mode = AuraModeNum::RainbowCycle;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Rainbow(x) => {
|
||||
SetAuraBuiltin::RainbowWave(x) => {
|
||||
let mut data: AuraEffect = x.into();
|
||||
data.mode = AuraModeNum::Rainbow;
|
||||
data.mode = AuraModeNum::RainbowWave;
|
||||
data
|
||||
}
|
||||
SetAuraBuiltin::Stars(x) => {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
use gumdrop::Options;
|
||||
use rog_platform::platform::PlatformProfile;
|
||||
|
||||
use crate::anime_cli::AnimeCommand;
|
||||
use crate::aura_cli::{LedBrightness, LedPowerCommand1, LedPowerCommand2, SetAuraBuiltin};
|
||||
use crate::profiles_cli::{FanCurveCommand, ProfileCommand};
|
||||
use crate::fan_curve_cli::FanCurveCommand;
|
||||
use crate::scsi_cli::ScsiCommand;
|
||||
use crate::slash_cli::SlashCommand;
|
||||
|
||||
#[derive(Default, Options)]
|
||||
pub struct CliStart {
|
||||
@@ -20,6 +23,8 @@ pub struct CliStart {
|
||||
pub prev_kbd_bright: bool,
|
||||
#[options(meta = "", help = "Set your battery charge limit <20-100>")]
|
||||
pub chg_limit: Option<u8>,
|
||||
#[options(help = "Toggle one-shot battery charge to 100%")]
|
||||
pub one_shot_chg: bool,
|
||||
#[options(command)]
|
||||
pub command: Option<CliCommand>,
|
||||
}
|
||||
@@ -27,11 +32,11 @@ pub struct CliStart {
|
||||
#[derive(Options)]
|
||||
pub enum CliCommand {
|
||||
#[options(help = "Set the keyboard lighting from built-in modes")]
|
||||
LedMode(LedModeCommand),
|
||||
Aura(LedModeCommand),
|
||||
#[options(help = "Set the LED power states")]
|
||||
LedPow1(LedPowerCommand1),
|
||||
AuraPowerOld(LedPowerCommand1),
|
||||
#[options(help = "Set the LED power states")]
|
||||
LedPow2(LedPowerCommand2),
|
||||
AuraPower(LedPowerCommand2),
|
||||
#[options(help = "Set or select platform_profile")]
|
||||
Profile(ProfileCommand),
|
||||
#[options(help = "Set, select, or modify fan curves if supported")]
|
||||
@@ -40,8 +45,35 @@ pub enum CliCommand {
|
||||
Graphics(GraphicsCommand),
|
||||
#[options(name = "anime", help = "Manage AniMe Matrix")]
|
||||
Anime(AnimeCommand),
|
||||
#[options(help = "Change bios settings")]
|
||||
Bios(BiosCommand),
|
||||
#[options(name = "slash", help = "Manage Slash Ledbar")]
|
||||
Slash(SlashCommand),
|
||||
#[options(name = "scsi", help = "Manage SCSI external drive")]
|
||||
Scsi(ScsiCommand),
|
||||
#[options(
|
||||
help = "Change platform settings. This is a new interface exposed by the asus-armoury \
|
||||
driver, some of the settings will be the same as the older platform interface"
|
||||
)]
|
||||
Armoury(ArmouryCommand),
|
||||
#[options(name = "backlight", help = "Set screen backlight levels")]
|
||||
Backlight(BacklightCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Options)]
|
||||
pub struct ProfileCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
|
||||
#[options(help = "toggle to next profile in list")]
|
||||
pub next: bool,
|
||||
|
||||
#[options(help = "list available profiles")]
|
||||
pub list: bool,
|
||||
|
||||
#[options(help = "get profile")]
|
||||
pub profile_get: bool,
|
||||
|
||||
#[options(meta = "", help = "set the active profile")]
|
||||
pub profile_set: Option<PlatformProfile>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
@@ -63,34 +95,30 @@ pub struct GraphicsCommand {
|
||||
}
|
||||
|
||||
#[derive(Options, Debug)]
|
||||
pub struct BiosCommand {
|
||||
pub struct ArmouryCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
short = "S",
|
||||
no_long,
|
||||
help = "set bios POST sound: asusctl -S <true/false>"
|
||||
free,
|
||||
help = "append each value name followed by the value to set. `-1` sets to default"
|
||||
)]
|
||||
pub post_sound_set: Option<bool>,
|
||||
#[options(no_long, short = "s", help = "read bios POST sound")]
|
||||
pub post_sound_get: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
short = "D",
|
||||
no_long,
|
||||
help = "Switch GPU MUX mode: 0 = Discrete, 1 = Optimus, reboot required"
|
||||
)]
|
||||
pub gpu_mux_mode_set: Option<u8>,
|
||||
#[options(no_long, short = "d", help = "get GPU mode")]
|
||||
pub gpu_mux_mode_get: bool,
|
||||
#[options(
|
||||
meta = "",
|
||||
short = "O",
|
||||
no_long,
|
||||
help = "Set device panel overdrive <true/false>"
|
||||
)]
|
||||
pub panel_overdrive_set: Option<bool>,
|
||||
#[options(no_long, short = "o", help = "get panel overdrive")]
|
||||
pub panel_overdrive_get: bool,
|
||||
pub free: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct BacklightCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(meta = "", help = "Set screen brightness <0-100>")]
|
||||
pub screenpad_brightness: Option<i32>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set screenpad gamma brightness 0.5 - 2.2, 1.0 == linear"
|
||||
)]
|
||||
pub screenpad_gamma: Option<f32>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set screenpad brightness to sync with primary display"
|
||||
)]
|
||||
pub sync_screenpad_brightness: Option<bool>,
|
||||
}
|
||||
|
||||
49
asusctl/src/fan_curve_cli.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use gumdrop::Options;
|
||||
use rog_platform::platform::PlatformProfile;
|
||||
use rog_profiles::fan_curve_set::CurveData;
|
||||
use rog_profiles::FanCurvePU;
|
||||
|
||||
#[derive(Debug, Clone, Options)]
|
||||
pub struct FanCurveCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
|
||||
#[options(help = "get enabled fan profiles")]
|
||||
pub get_enabled: bool,
|
||||
|
||||
#[options(help = "set the active profile's fan curve to default")]
|
||||
pub default: bool,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "profile to modify fan-curve for. Shows data if no options provided"
|
||||
)]
|
||||
pub mod_profile: Option<PlatformProfile>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "enable or disable <true/false> fan all curves for a profile. `--mod_profile` \
|
||||
required"
|
||||
)]
|
||||
pub enable_fan_curves: Option<bool>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "enable or disable <true/false> a single fan curve for a profile. `--mod_profile` \
|
||||
and `--fan` required"
|
||||
)]
|
||||
pub enable_fan_curve: Option<bool>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "select fan <cpu/gpu/mid> to modify. `--mod_profile` required"
|
||||
)]
|
||||
pub fan: Option<FanCurvePU>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "data format = 30c:1%,49c:2%,59c:3%,69c:4%,79c:31%,89c:49%,99c:56%,109c:58%. \
|
||||
`--mod-profile` required. If '%' is omitted the fan range is 0-255"
|
||||
)]
|
||||
pub data: Option<CurveData>,
|
||||
}
|
||||
1390
asusctl/src/main.rs
@@ -1,52 +0,0 @@
|
||||
use gumdrop::Options;
|
||||
use rog_profiles::fan_curve_set::CurveData;
|
||||
use rog_profiles::{FanCurvePU, Profile};
|
||||
|
||||
#[derive(Debug, Clone, Options)]
|
||||
pub struct ProfileCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(help = "toggle to next profile in list")]
|
||||
pub next: bool,
|
||||
#[options(help = "list available profiles")]
|
||||
pub list: bool,
|
||||
|
||||
#[options(help = "get profile")]
|
||||
pub profile_get: bool,
|
||||
#[options(meta = "", help = "set the active profile")]
|
||||
pub profile_set: Option<Profile>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Options)]
|
||||
pub struct FanCurveCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
|
||||
#[options(help = "get enabled fan profiles")]
|
||||
pub get_enabled: bool,
|
||||
#[options(help = "set the active profile's fan curve to default")]
|
||||
pub default: bool,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "profile to modify fan-curve for. Shows data if no options provided"
|
||||
)]
|
||||
pub mod_profile: Option<Profile>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "enable or disable <true/false> fan curve. `mod-profile` required"
|
||||
)]
|
||||
pub enabled: Option<bool>,
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "select fan <cpu/gpu> to modify. `mod-profile` required"
|
||||
)]
|
||||
pub fan: Option<FanCurvePU>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "data format = 30c:1%,49c:2%,59c:3%,69c:4%,79c:31%,89c:49%,99c:56%,109c:58%.
|
||||
`--mod-profile` required. If '%' is omitted the fan range is 0-255"
|
||||
)]
|
||||
pub data: Option<CurveData>,
|
||||
}
|
||||
35
asusctl/src/scsi_cli.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use gumdrop::Options;
|
||||
use rog_scsi::{AuraMode, Colour, Direction, Speed};
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct ScsiCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
|
||||
#[options(help = "Enable the SCSI drive LEDs")]
|
||||
pub enable: Option<bool>,
|
||||
|
||||
#[options(meta = "", help = "Set LED mode (so 'list' for all options)")]
|
||||
pub mode: Option<AuraMode>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set LED mode speed <slowest, slow, med, fast, fastest> (does not apply to all)"
|
||||
)]
|
||||
pub speed: Option<Speed>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set LED mode direction <forward, reverse> (does not apply to all)"
|
||||
)]
|
||||
pub direction: Option<Direction>,
|
||||
|
||||
#[options(
|
||||
meta = "",
|
||||
help = "Set LED colours <hex>, specify up to 4 with repeated arg"
|
||||
)]
|
||||
pub colours: Vec<Colour>,
|
||||
|
||||
#[options(help = "list available animations")]
|
||||
pub list: bool,
|
||||
}
|
||||
37
asusctl/src/slash_cli.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use gumdrop::Options;
|
||||
use rog_slash::SlashMode;
|
||||
|
||||
#[derive(Options)]
|
||||
pub struct SlashCommand {
|
||||
#[options(help = "print help message")]
|
||||
pub help: bool,
|
||||
#[options(help = "Enable the Slash Ledbar")]
|
||||
pub enable: bool,
|
||||
#[options(help = "Disable the Slash Ledbar")]
|
||||
pub disable: bool,
|
||||
#[options(short = "l", meta = "", help = "Set brightness value <0-255>")]
|
||||
pub brightness: Option<u8>,
|
||||
#[options(meta = "", help = "Set interval value <0-5>")]
|
||||
pub interval: Option<u8>,
|
||||
#[options(meta = "", help = "Set SlashMode (so 'list' for all options)")]
|
||||
pub mode: Option<SlashMode>,
|
||||
#[options(help = "list available animations")]
|
||||
pub list: bool,
|
||||
|
||||
#[options(short = "B", meta = "", help = "Show the animation on boot")]
|
||||
pub show_on_boot: Option<bool>,
|
||||
#[options(short = "S", meta = "", help = "Show the animation on shutdown")]
|
||||
pub show_on_shutdown: Option<bool>,
|
||||
#[options(short = "s", meta = "", help = "Show the animation on sleep")]
|
||||
pub show_on_sleep: Option<bool>,
|
||||
#[options(short = "b", meta = "", help = "Show the animation on battery")]
|
||||
pub show_on_battery: Option<bool>,
|
||||
// #[options(short = "L", meta = "", help = "Show the animation on lid closed")]
|
||||
// pub show_on_lid_closed: Option<bool>,
|
||||
#[options(
|
||||
short = "w",
|
||||
meta = "",
|
||||
help = "Show the low-battery warning animation"
|
||||
)]
|
||||
pub show_battery_warning: Option<bool>,
|
||||
}
|
||||
47
asusd-user/Cargo.toml
Normal file
@@ -0,0 +1,47 @@
|
||||
[package]
|
||||
name = "asusd-user"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "asusd-user"
|
||||
path = "src/daemon.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
local_data = []
|
||||
|
||||
[dependencies]
|
||||
dirs.workspace = true
|
||||
smol.workspace = true
|
||||
|
||||
# serialisation
|
||||
serde.workspace = true
|
||||
ron.workspace = true
|
||||
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_aura = { path = "../rog-aura" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_platform = { path = "../rog-platform" }
|
||||
config-traits = { path = "../config-traits" }
|
||||
|
||||
zbus.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[package.metadata.deb]
|
||||
license-file = ["../LICENSE", "4"]
|
||||
extended-description = """\
|
||||
An user utility for Linux to control fancy things on various ASUS laptops
|
||||
like keyboard effects or anime matrix animation cycles."""
|
||||
depends = "$auto"
|
||||
section = "utility"
|
||||
priority = "optional"
|
||||
assets = [
|
||||
["target/release/asusd-user", "usr/bin/", "755"],
|
||||
["../asusd_user-fakeinstall/usr/lib/systemd/user/*", "usr/lib/systemd/user/", "644"],
|
||||
]
|
||||
@@ -3,10 +3,10 @@ use std::time::Duration;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_anime::{ActionLoader, AnimTime, AnimeType, Fade, Sequences as AnimeSequences, Vec2};
|
||||
use rog_aura::advanced::LedCode;
|
||||
use rog_aura::effects::{AdvancedEffects as AuraSequences, Breathe, DoomFlicker, Effect, Static};
|
||||
use rog_aura::keyboard::LedCode;
|
||||
use rog_aura::{Colour, Speed};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
@@ -136,8 +136,16 @@ impl Default for ConfigAura {
|
||||
let mut seq = AuraSequences::new(false);
|
||||
let mut key = Effect::Breathe(Breathe::new(
|
||||
LedCode::W,
|
||||
Colour(255, 0, 20),
|
||||
Colour(20, 255, 0),
|
||||
Colour {
|
||||
r: 255,
|
||||
g: 0,
|
||||
b: 20,
|
||||
},
|
||||
Colour {
|
||||
r: 20,
|
||||
g: 255,
|
||||
b: 0,
|
||||
},
|
||||
Speed::Low,
|
||||
));
|
||||
|
||||
@@ -151,20 +159,25 @@ impl Default for ConfigAura {
|
||||
|
||||
let key = Effect::Breathe(Breathe::new(
|
||||
LedCode::F,
|
||||
Colour(255, 0, 0),
|
||||
Colour(255, 0, 0),
|
||||
Colour { r: 255, g: 0, b: 0 },
|
||||
Colour { r: 255, g: 0, b: 0 },
|
||||
Speed::High,
|
||||
));
|
||||
seq.push(key);
|
||||
|
||||
let mut key = Effect::Static(Static::new(LedCode::RCtrl, Colour(0, 0, 255)));
|
||||
let mut key = Effect::Static(Static::new(LedCode::RCtrl, Colour { r: 0, g: 0, b: 255 }));
|
||||
seq.push(key.clone());
|
||||
key.set_led(LedCode::LCtrl);
|
||||
seq.push(key.clone());
|
||||
key.set_led(LedCode::Esc);
|
||||
seq.push(key);
|
||||
|
||||
let key = Effect::DoomFlicker(DoomFlicker::new(LedCode::N9, Colour(0, 0, 255), 80, 40));
|
||||
let key = Effect::DoomFlicker(DoomFlicker::new(
|
||||
LedCode::N9,
|
||||
Colour { r: 0, g: 0, b: 255 },
|
||||
80,
|
||||
40,
|
||||
));
|
||||
seq.push(key);
|
||||
|
||||
Self {
|
||||
@@ -7,9 +7,10 @@ use std::time::{Duration, Instant};
|
||||
use config_traits::StdConfig;
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_anime::{ActionData, ActionLoader, AnimTime, Fade, Sequences, Vec2};
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use zbus::dbus_interface;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use ron::ser::PrettyConfig;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zbus::interface;
|
||||
use zbus::zvariant::{ObjectPath, Type};
|
||||
|
||||
use crate::config::ConfigAnime;
|
||||
@@ -22,22 +23,18 @@ pub struct Timer {
|
||||
/// animation loop count
|
||||
count: u64,
|
||||
/// Used only for `TimeType::Timer`, milliseonds to fade the image in for
|
||||
fade_in: Option<u64>,
|
||||
fade_in: u64,
|
||||
/// Used only for `TimeType::Timer`, milliseonds to fade the image out for
|
||||
fade_out: Option<u64>,
|
||||
fade_out: u64,
|
||||
}
|
||||
|
||||
impl From<Timer> for AnimTime {
|
||||
fn from(time: Timer) -> Self {
|
||||
match time.type_of {
|
||||
TimeType::Timer => {
|
||||
if time.fade_in.is_some() || time.fade_out.is_some() {
|
||||
let fade_in = time
|
||||
.fade_in
|
||||
.map_or(Duration::from_secs(0), Duration::from_millis);
|
||||
let fade_out = time
|
||||
.fade_out
|
||||
.map_or(Duration::from_secs(0), Duration::from_millis);
|
||||
if time.fade_in != 0 && time.fade_out != 0 {
|
||||
let fade_in = Duration::from_millis(time.fade_in);
|
||||
let fade_out = Duration::from_millis(time.fade_out);
|
||||
let show_for = if time.count != 0 {
|
||||
Some(Duration::from_millis(time.count))
|
||||
} else {
|
||||
@@ -65,14 +62,14 @@ pub enum TimeType {
|
||||
/// thread and a zbus server behind `Arc<Mutex<T>>`
|
||||
pub struct CtrlAnimeInner<'a> {
|
||||
sequences: Sequences,
|
||||
client: RogDbusClientBlocking<'a>,
|
||||
client: AnimeProxyBlocking<'a>,
|
||||
do_early_return: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl<'a> CtrlAnimeInner<'static> {
|
||||
impl CtrlAnimeInner<'static> {
|
||||
pub fn new(
|
||||
sequences: Sequences,
|
||||
client: RogDbusClientBlocking<'static>,
|
||||
client: AnimeProxyBlocking<'static>,
|
||||
do_early_return: Arc<AtomicBool>,
|
||||
) -> Result<Self, Error> {
|
||||
Ok(Self {
|
||||
@@ -84,7 +81,7 @@ impl<'a> CtrlAnimeInner<'static> {
|
||||
|
||||
/// To be called on each main loop iteration to pump out commands to the
|
||||
/// anime
|
||||
pub fn run(&'a self) -> Result<(), Error> {
|
||||
pub fn run(&self) -> Result<(), Error> {
|
||||
if self.do_early_return.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -97,19 +94,13 @@ impl<'a> CtrlAnimeInner<'static> {
|
||||
return Ok(true); // Do safe exit
|
||||
}
|
||||
self.client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(output)
|
||||
.map_err(|e| AnimeError::Dbus(format!("{}", e)))
|
||||
.map(|_| false)
|
||||
});
|
||||
}
|
||||
ActionData::Image(image) => {
|
||||
self.client
|
||||
.proxies()
|
||||
.anime()
|
||||
.write(image.as_ref().clone())
|
||||
.ok();
|
||||
self.client.write(image.as_ref().clone()).ok();
|
||||
}
|
||||
ActionData::Pause(duration) => {
|
||||
let start = Instant::now();
|
||||
@@ -136,7 +127,7 @@ impl<'a> CtrlAnimeInner<'static> {
|
||||
|
||||
pub struct CtrlAnime<'a> {
|
||||
config: Arc<Mutex<ConfigAnime>>,
|
||||
client: RogDbusClientBlocking<'a>,
|
||||
client: AnimeProxyBlocking<'a>,
|
||||
inner: Arc<Mutex<CtrlAnimeInner<'a>>>,
|
||||
/// Must be the same Atomic as in CtrlAnimeInner
|
||||
inner_early_return: Arc<AtomicBool>,
|
||||
@@ -146,7 +137,7 @@ impl CtrlAnime<'static> {
|
||||
pub fn new(
|
||||
config: Arc<Mutex<ConfigAnime>>,
|
||||
inner: Arc<Mutex<CtrlAnimeInner<'static>>>,
|
||||
client: RogDbusClientBlocking<'static>,
|
||||
client: AnimeProxyBlocking<'static>,
|
||||
inner_early_return: Arc<AtomicBool>,
|
||||
) -> Result<Self, Error> {
|
||||
Ok(CtrlAnime {
|
||||
@@ -160,10 +151,7 @@ impl CtrlAnime<'static> {
|
||||
pub async fn add_to_server(self, server: &mut zbus::Connection) {
|
||||
server
|
||||
.object_server()
|
||||
.at(
|
||||
&ObjectPath::from_str_unchecked("/org/asuslinux/Anime"),
|
||||
self,
|
||||
)
|
||||
.at(&ObjectPath::from_str_unchecked("/xyz/ljones/Anime"), self)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
println!("CtrlAnime: add_to_server {}", err);
|
||||
@@ -179,7 +167,7 @@ impl CtrlAnime<'static> {
|
||||
// - Do actions
|
||||
// - Write config if required
|
||||
// - Unset inner_early_return
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
#[interface(name = "xyz.ljones.Asusd")]
|
||||
impl CtrlAnime<'static> {
|
||||
pub fn insert_asus_gif(
|
||||
&mut self,
|
||||
@@ -209,11 +197,12 @@ impl CtrlAnime<'static> {
|
||||
config.anime.push(action);
|
||||
config.write();
|
||||
|
||||
let json = serde_json::to_string_pretty(&*config).expect("Parse config to JSON failed");
|
||||
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
|
||||
.expect("Parse config to RON failed");
|
||||
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
return Ok(ron);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
@@ -254,12 +243,11 @@ impl CtrlAnime<'static> {
|
||||
config.anime.push(action);
|
||||
config.write();
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
|
||||
.expect("Parse config to RON failed");
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
return Ok(ron);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
@@ -299,12 +287,11 @@ impl CtrlAnime<'static> {
|
||||
config.anime.push(action);
|
||||
config.write();
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
|
||||
.expect("Parse config to RON failed");
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
return Ok(ron);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
@@ -324,12 +311,11 @@ impl CtrlAnime<'static> {
|
||||
config.anime.push(action);
|
||||
config.write();
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
|
||||
.expect("Parse config to RON failed");
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
return Ok(ron);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
@@ -347,12 +333,11 @@ impl CtrlAnime<'static> {
|
||||
}
|
||||
config.write();
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&*config.anime).expect("Parse config to JSON failed");
|
||||
|
||||
let ron = ron::ser::to_string_pretty(&*config, PrettyConfig::new().depth_limit(4))
|
||||
.expect("Parse config to RON failed");
|
||||
// Release the inner run loop again
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
return Ok(json);
|
||||
return Ok(ron);
|
||||
}
|
||||
Err(zbus::fdo::Error::Failed("UserConfig lock fail".into()))
|
||||
}
|
||||
@@ -360,13 +345,13 @@ impl CtrlAnime<'static> {
|
||||
pub fn set_state(&mut self, on: bool) -> zbus::fdo::Result<()> {
|
||||
// Operations here need to be in specific order
|
||||
if on {
|
||||
self.client.proxies().anime().set_on_off(on).ok();
|
||||
self.client.set_enable_display(on).ok();
|
||||
// Let the inner loop run
|
||||
self.inner_early_return.store(false, Ordering::SeqCst);
|
||||
} else {
|
||||
// Must make the inner run loop return early
|
||||
self.inner_early_return.store(true, Ordering::SeqCst);
|
||||
self.client.proxies().anime().set_on_off(on).ok();
|
||||
self.client.set_enable_display(on).ok();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -3,14 +3,15 @@ use std::path::PathBuf;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use asusd_user::config::*;
|
||||
use asusd_user::ctrl_anime::{CtrlAnime, CtrlAnimeInner};
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_aura::aura_detection::LaptopLedData;
|
||||
use rog_aura::layouts::KeyLayout;
|
||||
use rog_dbus::RogDbusClientBlocking;
|
||||
use rog_user::config::*;
|
||||
use rog_user::ctrl_anime::{CtrlAnime, CtrlAnimeInner};
|
||||
use rog_user::DBUS_NAME;
|
||||
use rog_aura::aura_detection::LedSupportData;
|
||||
use rog_aura::keyboard::KeyLayout;
|
||||
use rog_dbus::zbus_anime::AnimeProxyBlocking;
|
||||
use rog_dbus::zbus_aura::AuraProxyBlocking;
|
||||
use rog_dbus::{list_iface_blocking, DBUS_NAME};
|
||||
use smol::Executor;
|
||||
use zbus::Connection;
|
||||
|
||||
@@ -28,27 +29,27 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
|
||||
.init();
|
||||
|
||||
println!(" user daemon v{}", rog_user::VERSION);
|
||||
println!(" user daemon v{}", asusd_user::VERSION);
|
||||
println!(" rog-anime v{}", rog_anime::VERSION);
|
||||
println!(" rog-dbus v{}", rog_dbus::VERSION);
|
||||
println!("rog-platform v{}", rog_platform::VERSION);
|
||||
|
||||
let (client, _) = RogDbusClientBlocking::new()?;
|
||||
let supported = client.proxies().supported().supported_functions()?;
|
||||
let conn = zbus::blocking::Connection::system().unwrap();
|
||||
|
||||
let supported = list_iface_blocking()?;
|
||||
let config = ConfigBase::new().load();
|
||||
|
||||
let executor = Executor::new();
|
||||
|
||||
let early_return = Arc::new(AtomicBool::new(false));
|
||||
// Set up the anime data and run loop/thread
|
||||
if supported.anime_ctrl.0 {
|
||||
if supported.contains(&"xyz.ljones.Anime".to_string()) {
|
||||
if let Some(cfg) = config.active_anime {
|
||||
let anime_type = get_anime_type()?;
|
||||
let anime_type = get_anime_type();
|
||||
let anime_config = ConfigAnime::new().set_name(cfg).load();
|
||||
let anime = anime_config.create(anime_type)?;
|
||||
let anime_config = Arc::new(Mutex::new(anime_config));
|
||||
|
||||
let anime_proxy_blocking = AnimeProxyBlocking::new(&conn).unwrap();
|
||||
executor
|
||||
.spawn(async move {
|
||||
// Create server
|
||||
@@ -57,12 +58,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
// Inner behind mutex required for thread safety
|
||||
let inner = Arc::new(Mutex::new(
|
||||
CtrlAnimeInner::new(anime, client, early_return.clone()).unwrap(),
|
||||
CtrlAnimeInner::new(
|
||||
anime,
|
||||
anime_proxy_blocking.clone(),
|
||||
early_return.clone(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
// Need new client object for dbus control part
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
let anime_control =
|
||||
CtrlAnime::new(anime_config, inner.clone(), client, early_return).unwrap();
|
||||
let anime_control = CtrlAnime::new(
|
||||
anime_config,
|
||||
inner.clone(),
|
||||
anime_proxy_blocking,
|
||||
early_return,
|
||||
)
|
||||
.unwrap();
|
||||
anime_control.add_to_server(&mut connection).await;
|
||||
loop {
|
||||
if let Ok(inner) = inner.clone().try_lock() {
|
||||
@@ -79,7 +89,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut aura_config = ConfigAura::new().set_name(cfg).load();
|
||||
// let baord_name = std::fs::read_to_string(BOARD_NAME)?;
|
||||
|
||||
let led_support = LaptopLedData::get_data();
|
||||
let led_support = LedSupportData::get_data("");
|
||||
|
||||
let layout = KeyLayout::find_layout(led_support, PathBuf::from(DATA_DIR))
|
||||
.map_err(|e| {
|
||||
@@ -87,22 +97,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
})
|
||||
.unwrap_or_else(|_| KeyLayout::default_layout());
|
||||
|
||||
let aura_proxy_blocking = AuraProxyBlocking::new(&conn).unwrap();
|
||||
executor
|
||||
.spawn(async move {
|
||||
// Create server
|
||||
let (client, _) = RogDbusClientBlocking::new().unwrap();
|
||||
// let connection = Connection::session().await.unwrap();
|
||||
// connection.request_name(DBUS_NAME).await.unwrap();
|
||||
|
||||
loop {
|
||||
aura_config.aura.next_state(&layout);
|
||||
let packets = aura_config.aura.create_packets();
|
||||
|
||||
client
|
||||
.proxies()
|
||||
.led()
|
||||
.direct_addressing_raw(packets)
|
||||
.unwrap();
|
||||
aura_proxy_blocking.direct_addressing_raw(packets).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(33));
|
||||
}
|
||||
})
|
||||
@@ -6,6 +6,4 @@ pub mod ctrl_anime;
|
||||
|
||||
pub mod zbus_anime;
|
||||
|
||||
pub static DBUS_NAME: &str = "org.asuslinux.Daemon";
|
||||
|
||||
pub static VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
@@ -1,8 +1,8 @@
|
||||
//! # `DBus` interface proxy for: `org.asuslinux.Daemon`
|
||||
//! # `DBus` interface proxy for: `xyz.ljones.Asusd`
|
||||
//!
|
||||
//! 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`.
|
||||
//! data. Source: `Interface '/xyz/ljones/Anime' from service
|
||||
//! 'xyz.ljones.Asusd' on session bus`.
|
||||
//!
|
||||
//! You may prefer to adapt it, instead of using it verbatim.
|
||||
//!
|
||||
@@ -21,9 +21,9 @@
|
||||
//! …consequently `zbus-xmlgen` did not generate code for the above interfaces.
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
|
||||
use zbus::dbus_proxy;
|
||||
use zbus::proxy;
|
||||
|
||||
#[dbus_proxy(interface = "org.asuslinux.Daemon")]
|
||||
#[proxy(interface = "xyz.ljones.Asusd", default_path = "/xyz/ljones/Anime")]
|
||||
trait Daemon {
|
||||
/// InsertAsusGif method
|
||||
fn insert_asus_gif(
|
||||
62
asusd/Cargo.toml
Normal file
@@ -0,0 +1,62 @@
|
||||
[package]
|
||||
name = "asusd"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
description.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "asusd"
|
||||
path = "src/daemon.rs"
|
||||
|
||||
[dependencies]
|
||||
config-traits = { path = "../config-traits" }
|
||||
rog_anime = { path = "../rog-anime", features = ["dbus"] }
|
||||
rog_slash = { path = "../rog-slash", features = ["dbus"] }
|
||||
rog_aura = { path = "../rog-aura", features = ["dbus"] }
|
||||
rog_scsi = { path = "../rog-scsi", features = ["dbus"] }
|
||||
rog_platform = { path = "../rog-platform" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
dmi_id = { path = "../dmi-id" }
|
||||
futures-lite = "*"
|
||||
udev.workspace = true
|
||||
inotify.workspace = true
|
||||
|
||||
mio.workspace = true
|
||||
tokio.workspace = true
|
||||
# console-subscriber = "0.2.0"
|
||||
|
||||
# cli and logging
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
futures-util.workspace = true
|
||||
zbus.workspace = true
|
||||
logind-zbus.workspace = true
|
||||
|
||||
# serialisation
|
||||
serde.workspace = true
|
||||
|
||||
concat-idents.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
cargo-husky.workspace = true
|
||||
|
||||
[package.metadata.deb]
|
||||
license-file = ["../LICENSE", "4"]
|
||||
extended-description = """\
|
||||
The dbus server for asusctl and rog-control-center applications."""
|
||||
depends = "$auto"
|
||||
section = "utility"
|
||||
priority = "optional"
|
||||
assets = [
|
||||
["target/release/asusd", "usr/bin/", "755"],
|
||||
["../asusd-fakeinstall/usr/lib/systemd/system/*", "usr/lib/systemd/system/", "644"],
|
||||
["../asusd-fakeinstall/usr/lib/udev/rules.d/*", "usr/lib/udev/rules.d/", "644"],
|
||||
["../asusd-fakeinstall/usr/share/asusd/*", "usr/share/share/asusd/", "644"],
|
||||
["../asusd-fakeinstall/usr/share/dbus-1/system.d/*", "usr/share/dbus-1/system.d/", "644"],
|
||||
]
|
||||
489
asusd/src/asus_armoury.rs
Normal file
@@ -0,0 +1,489 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info};
|
||||
use rog_platform::asus_armoury::{AttrValue, Attribute, FirmwareAttribute, FirmwareAttributes};
|
||||
use rog_platform::platform::{PlatformProfile, RogPlatform};
|
||||
use rog_platform::power::AsusPower;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::zvariant::{ObjectPath, OwnedObjectPath, OwnedValue, Type, Value};
|
||||
use zbus::{fdo, interface, Connection};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::RogError;
|
||||
use crate::{Reloadable, ASUS_ZBUS_PATH};
|
||||
|
||||
const MOD_NAME: &str = "asus_armoury";
|
||||
|
||||
#[derive(Debug, Default, Clone, Deserialize, Serialize, Type, Value, OwnedValue)]
|
||||
pub struct PossibleValues {
|
||||
strings: Vec<String>,
|
||||
nums: Vec<i32>,
|
||||
}
|
||||
|
||||
fn dbus_path_for_attr(attr_name: &str) -> OwnedObjectPath {
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/{attr_name}")).into()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AsusArmouryAttribute {
|
||||
attr: Attribute,
|
||||
config: Arc<Mutex<Config>>,
|
||||
/// platform control required here for access to PPD or Throttle profile
|
||||
platform: RogPlatform,
|
||||
power: AsusPower,
|
||||
}
|
||||
|
||||
impl AsusArmouryAttribute {
|
||||
pub fn new(
|
||||
attr: Attribute,
|
||||
platform: RogPlatform,
|
||||
power: AsusPower,
|
||||
config: Arc<Mutex<Config>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
attr,
|
||||
config,
|
||||
platform,
|
||||
power,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn attribute_name(&self) -> String {
|
||||
String::from(self.attr.name())
|
||||
}
|
||||
|
||||
pub async fn move_to_zbus(self, connection: &Connection) -> Result<(), RogError> {
|
||||
let path = dbus_path_for_attr(self.attr.name());
|
||||
connection
|
||||
.object_server()
|
||||
.at(path.clone(), self)
|
||||
.await
|
||||
.map_err(|e| error!("Couldn't add server at path: {path}, {e:?}"))
|
||||
.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn watch_and_notify(
|
||||
&mut self,
|
||||
signal_ctxt: SignalEmitter<'static>,
|
||||
) -> Result<(), RogError> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
let name = self.name();
|
||||
macro_rules! watch_value_notify {
|
||||
($attr_str:expr, $fn_prop_changed:ident) => {
|
||||
match self.attr.get_watcher($attr_str) {
|
||||
Ok(watch) => {
|
||||
let name = <&str>::from(name);
|
||||
let ctrl = self.clone();
|
||||
let sig = signal_ctxt.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
if let Ok(stream) = watch.into_event_stream(&mut buffer) {
|
||||
stream
|
||||
.for_each(|_| async {
|
||||
debug!("{} changed", name);
|
||||
ctrl.$fn_prop_changed(&sig).await.ok();
|
||||
})
|
||||
.await;
|
||||
} else {
|
||||
info!(
|
||||
"inotify event stream failed for {} ({}). You can ignore this if unsupported",
|
||||
name, $attr_str
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => info!(
|
||||
"inotify watch failed: {}. You can ignore this if your device does not \
|
||||
support the feature",
|
||||
e
|
||||
),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// "current_value", "default_value", "min_value", "max_value"
|
||||
watch_value_notify!("current_value", current_value_changed);
|
||||
watch_value_notify!("default_value", default_value_changed);
|
||||
watch_value_notify!("min_value", min_value_changed);
|
||||
watch_value_notify!("max_value", max_value_changed);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for AsusArmouryAttribute {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
info!("Reloading {}", self.attr.name());
|
||||
let name: FirmwareAttribute = self.attr.name().into();
|
||||
|
||||
if name.is_ppt() {
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let config = if power_plugged == 1 {
|
||||
&self.config.lock().await.ac_profile_tunings
|
||||
} else {
|
||||
&self.config.lock().await.dc_profile_tunings
|
||||
};
|
||||
if let Some(tuning) = config.get(&profile) {
|
||||
if tuning.enabled {
|
||||
if let Some(tune) = tuning.group.get(&self.name()) {
|
||||
self.attr
|
||||
.set_current_value(&AttrValue::Integer(*tune))
|
||||
.map_err(|e| {
|
||||
error!("Could not set {} value: {e:?}", self.attr.name());
|
||||
self.attr.base_path_exists();
|
||||
e
|
||||
})?;
|
||||
info!("Set {} to {:?}", self.attr.name(), tune);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle non-PPT attributes (boolean and other settings)
|
||||
if let Some(saved_value) = self.config.lock().await.armoury_settings.get(&name) {
|
||||
self.attr
|
||||
.set_current_value(&AttrValue::Integer(*saved_value))
|
||||
.map_err(|e| {
|
||||
error!("Could not set {} value: {e:?}", self.attr.name());
|
||||
self.attr.base_path_exists();
|
||||
e
|
||||
})?;
|
||||
info!("Restored armoury setting {} to {:?}", self.attr.name(), saved_value);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// If return is `-1` on a property then there is avilable value for that
|
||||
/// property
|
||||
#[interface(name = "xyz.ljones.AsusArmoury")]
|
||||
impl AsusArmouryAttribute {
|
||||
#[zbus(property)]
|
||||
fn name(&self) -> FirmwareAttribute {
|
||||
self.attr.name().into()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn available_attrs(&self) -> Vec<String> {
|
||||
let mut attrs = Vec::new();
|
||||
if !matches!(self.attr.default_value(), AttrValue::None) {
|
||||
attrs.push("default_value".to_string());
|
||||
}
|
||||
if !matches!(self.attr.min_value(), AttrValue::None) {
|
||||
attrs.push("min_value".to_string());
|
||||
}
|
||||
if !matches!(self.attr.max_value(), AttrValue::None) {
|
||||
attrs.push("max_value".to_string());
|
||||
}
|
||||
if !matches!(self.attr.scalar_increment(), AttrValue::None) {
|
||||
attrs.push("scalar_increment".to_string());
|
||||
}
|
||||
if !matches!(self.attr.possible_values(), AttrValue::None) {
|
||||
attrs.push("possible_values".to_string());
|
||||
}
|
||||
// TODO: Don't unwrap, use error
|
||||
if let Ok(value) = self.attr.current_value().map_err(|e| {
|
||||
error!("Failed to read: {e:?}");
|
||||
e
|
||||
}) {
|
||||
if !matches!(value, AttrValue::None) {
|
||||
attrs.push("current_value".to_string());
|
||||
}
|
||||
}
|
||||
attrs
|
||||
}
|
||||
|
||||
/// If return is `-1` then there is no default value
|
||||
#[zbus(property)]
|
||||
async fn default_value(&self) -> i32 {
|
||||
match self.attr.default_value() {
|
||||
AttrValue::Integer(i) => *i,
|
||||
_ => -1,
|
||||
}
|
||||
}
|
||||
|
||||
async fn restore_default(&self) -> fdo::Result<()> {
|
||||
self.attr.restore_default()?;
|
||||
if self.name().is_ppt() {
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut config = self.config.lock().await;
|
||||
let tuning = config.select_tunings(power_plugged == 1, profile);
|
||||
if let Some(tune) = tuning.group.get_mut(&self.name()) {
|
||||
if let AttrValue::Integer(i) = self.attr.default_value() {
|
||||
*tune = *i;
|
||||
}
|
||||
}
|
||||
if tuning.enabled {
|
||||
self.attr
|
||||
.set_current_value(self.attr.default_value())
|
||||
.map_err(|e| {
|
||||
error!("Could not set value: {e:?}");
|
||||
e
|
||||
})?;
|
||||
}
|
||||
config.write();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn min_value(&self) -> i32 {
|
||||
match self.attr.min_value() {
|
||||
AttrValue::Integer(i) => *i,
|
||||
_ => -1,
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn max_value(&self) -> i32 {
|
||||
match self.attr.max_value() {
|
||||
AttrValue::Integer(i) => *i,
|
||||
_ => -1,
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn scalar_increment(&self) -> i32 {
|
||||
match self.attr.scalar_increment() {
|
||||
AttrValue::Integer(i) => *i,
|
||||
_ => -1,
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn possible_values(&self) -> Vec<i32> {
|
||||
match self.attr.possible_values() {
|
||||
AttrValue::EnumInt(i) => i.clone(),
|
||||
_ => Vec::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn current_value(&self) -> fdo::Result<i32> {
|
||||
if self.name().is_ppt() {
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut config = self.config.lock().await;
|
||||
let tuning = config.select_tunings(power_plugged == 1, profile);
|
||||
if let Some(tune) = tuning.group.get(&self.name()) {
|
||||
return Ok(*tune);
|
||||
} else if let AttrValue::Integer(i) = self.attr.default_value() {
|
||||
return Ok(*i);
|
||||
}
|
||||
return Err(fdo::Error::Failed(
|
||||
"Could not read current value".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Ok(AttrValue::Integer(i)) = self.attr.current_value() {
|
||||
return Ok(i);
|
||||
}
|
||||
Err(fdo::Error::Failed(
|
||||
"Could not read current value".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_current_value(&mut self, value: i32) -> fdo::Result<()> {
|
||||
if self.name().is_ppt() {
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut config = self.config.lock().await;
|
||||
let tuning = config.select_tunings(power_plugged == 1, profile);
|
||||
|
||||
if let Some(tune) = tuning.group.get_mut(&self.name()) {
|
||||
*tune = value;
|
||||
} else {
|
||||
tuning.group.insert(self.name(), value);
|
||||
debug!("Store tuning config for {} = {:?}", self.attr.name(), value);
|
||||
}
|
||||
if tuning.enabled {
|
||||
self.attr
|
||||
.set_current_value(&AttrValue::Integer(value))
|
||||
.map_err(|e| {
|
||||
error!("Could not set value: {e:?}");
|
||||
e
|
||||
})?;
|
||||
}
|
||||
} else {
|
||||
self.attr
|
||||
.set_current_value(&AttrValue::Integer(value))
|
||||
.map_err(|e| {
|
||||
error!("Could not set value: {e:?}");
|
||||
e
|
||||
})?;
|
||||
|
||||
let has_attr = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.armoury_settings
|
||||
.contains_key(&self.name());
|
||||
if has_attr {
|
||||
if let Some(setting) = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.armoury_settings
|
||||
.get_mut(&self.name())
|
||||
{
|
||||
*setting = value
|
||||
}
|
||||
} else {
|
||||
debug!("Adding config for {}", self.attr.name());
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.armoury_settings
|
||||
.insert(self.name(), value);
|
||||
debug!("Set config for {} = {:?}", self.attr.name(), value);
|
||||
}
|
||||
}
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_attributes_zbus(
|
||||
conn: &Connection,
|
||||
platform: RogPlatform,
|
||||
power: AsusPower,
|
||||
attributes: FirmwareAttributes,
|
||||
config: Arc<Mutex<Config>>,
|
||||
) -> Result<(), RogError> {
|
||||
for attr in attributes.attributes() {
|
||||
let mut attr = AsusArmouryAttribute::new(
|
||||
attr.clone(),
|
||||
platform.clone(),
|
||||
power.clone(),
|
||||
config.clone(),
|
||||
);
|
||||
|
||||
if let Err(e) = attr.reload().await {
|
||||
error!(
|
||||
"Skipping attribute '{}' due to reload error: {e:?}",
|
||||
attr.attr.name()
|
||||
);
|
||||
// continue with others
|
||||
continue;
|
||||
}
|
||||
|
||||
let attr_name = attr.attribute_name();
|
||||
|
||||
let path = dbus_path_for_attr(attr_name.as_str());
|
||||
match zbus::object_server::SignalEmitter::new(conn, path) {
|
||||
Ok(sig) => {
|
||||
if let Err(e) = attr.watch_and_notify(sig).await {
|
||||
error!(
|
||||
"Failed to start watcher for '{}': {e:?}",
|
||||
attr.attr.name()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to create SignalEmitter for '{}': {e:?}", attr.attr.name());
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = attr.move_to_zbus(conn).await {
|
||||
error!(
|
||||
"Failed to register attribute '{attr_name}' on zbus: {e:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_config_or_default(
|
||||
attrs: &FirmwareAttributes,
|
||||
config: &mut Config,
|
||||
power_plugged: bool,
|
||||
profile: PlatformProfile,
|
||||
) {
|
||||
for attr in attrs.attributes().iter() {
|
||||
let name: FirmwareAttribute = attr.name().into();
|
||||
if name.is_ppt() {
|
||||
let tuning = config.select_tunings(power_plugged, profile);
|
||||
if !tuning.enabled {
|
||||
debug!("Tuning group is not enabled, skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(tune) = tuning.group.get(&name) {
|
||||
attr.set_current_value(&AttrValue::Integer(*tune))
|
||||
.map_err(|e| {
|
||||
error!("Failed to set {}: {e}", <&str>::from(name));
|
||||
})
|
||||
.ok();
|
||||
} else {
|
||||
let default = attr.default_value();
|
||||
attr.set_current_value(default)
|
||||
.map_err(|e| {
|
||||
error!("Failed to set {}: {e}", <&str>::from(name));
|
||||
})
|
||||
.ok();
|
||||
if let AttrValue::Integer(i) = default {
|
||||
tuning.group.insert(name, *i);
|
||||
info!(
|
||||
"Set default tuning config for {} = {:?}",
|
||||
<&str>::from(name),
|
||||
i
|
||||
);
|
||||
// config.write();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle non-PPT attributes (boolean and other settings)
|
||||
if let Some(saved_value) = config.armoury_settings.get(&name) {
|
||||
attr.set_current_value(&AttrValue::Integer(*saved_value))
|
||||
.map_err(|e| {
|
||||
error!("Failed to set {}: {e}", <&str>::from(name));
|
||||
})
|
||||
.ok();
|
||||
info!(
|
||||
"Restored armoury setting for {} = {:?}",
|
||||
<&str>::from(name),
|
||||
saved_value
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
182
asusd/src/aura_anime/config.rs
Normal file
@@ -0,0 +1,182 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_anime::usb::Brightness;
|
||||
use rog_anime::{
|
||||
ActionData, ActionLoader, AnimTime, Animations, AnimeType, DeviceState, Fade, Vec2,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "anime.ron";
|
||||
|
||||
#[derive(Debug, Clone, 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,
|
||||
anime_type: AnimeType,
|
||||
) -> Result<(), AnimeError> {
|
||||
let mut sys = Vec::with_capacity(config.system.len());
|
||||
for ani in &config.system {
|
||||
sys.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.system = sys;
|
||||
|
||||
let mut boot = Vec::with_capacity(config.boot.len());
|
||||
for ani in &config.boot {
|
||||
boot.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.boot = boot;
|
||||
|
||||
let mut wake = Vec::with_capacity(config.wake.len());
|
||||
for ani in &config.wake {
|
||||
wake.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.wake = wake;
|
||||
|
||||
let mut shutdown = Vec::with_capacity(config.shutdown.len());
|
||||
for ani in &config.shutdown {
|
||||
shutdown.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.shutdown = shutdown;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Config for base system actions for the anime display
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
pub struct AniMeConfig {
|
||||
#[serde(skip)]
|
||||
pub anime_type: AnimeType,
|
||||
pub system: Vec<ActionLoader>,
|
||||
pub boot: Vec<ActionLoader>,
|
||||
pub wake: Vec<ActionLoader>,
|
||||
pub shutdown: Vec<ActionLoader>,
|
||||
// pub brightness: f32,
|
||||
pub display_enabled: bool,
|
||||
pub display_brightness: Brightness,
|
||||
pub builtin_anims_enabled: bool,
|
||||
pub off_when_unplugged: bool,
|
||||
pub off_when_suspended: bool,
|
||||
pub off_when_lid_closed: bool,
|
||||
pub brightness_on_battery: Brightness,
|
||||
pub builtin_anims: Animations,
|
||||
}
|
||||
|
||||
impl Default for AniMeConfig {
|
||||
fn default() -> Self {
|
||||
AniMeConfig {
|
||||
anime_type: AnimeType::GA402,
|
||||
system: Vec::new(),
|
||||
boot: Vec::new(),
|
||||
wake: Vec::new(),
|
||||
shutdown: Vec::new(),
|
||||
// brightness: 1.0,
|
||||
display_enabled: true,
|
||||
display_brightness: Brightness::Med,
|
||||
builtin_anims_enabled: true,
|
||||
off_when_unplugged: true,
|
||||
off_when_suspended: true,
|
||||
off_when_lid_closed: true,
|
||||
brightness_on_battery: Brightness::Low,
|
||||
builtin_anims: Animations::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfig for AniMeConfig {
|
||||
fn new() -> Self {
|
||||
Self::create_default()
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for AniMeConfig {}
|
||||
|
||||
impl From<&AniMeConfig> for DeviceState {
|
||||
fn from(config: &AniMeConfig) -> Self {
|
||||
DeviceState {
|
||||
display_enabled: config.display_enabled,
|
||||
display_brightness: config.display_brightness,
|
||||
builtin_anims_enabled: config.builtin_anims_enabled,
|
||||
builtin_anims: config.builtin_anims,
|
||||
off_when_unplugged: config.off_when_unplugged,
|
||||
off_when_suspended: config.off_when_suspended,
|
||||
off_when_lid_closed: config.off_when_lid_closed,
|
||||
brightness_on_battery: config.brightness_on_battery,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AniMeConfig {
|
||||
// fn clamp_config_brightness(mut config: &mut AnimeConfig) {
|
||||
// if config.brightness < 0.0 || config.brightness > 1.0 {
|
||||
// warn!(
|
||||
// "Clamped brightness to [0.0 ; 1.0], was {}",
|
||||
// config.brightness
|
||||
// );
|
||||
// config.brightness = f32::max(0.0, f32::min(1.0, config.brightness));
|
||||
// }
|
||||
// }
|
||||
|
||||
fn create_default() -> Self {
|
||||
// create a default config here
|
||||
AniMeConfig {
|
||||
system: vec![],
|
||||
boot: vec![
|
||||
ActionLoader::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::Fade(Fade::new(
|
||||
Duration::from_secs(2),
|
||||
Some(Duration::from_secs(2)),
|
||||
Duration::from_secs(2),
|
||||
)),
|
||||
},
|
||||
],
|
||||
wake: vec![
|
||||
ActionLoader::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::Fade(Fade::new(
|
||||
Duration::from_secs(2),
|
||||
Some(Duration::from_secs(2)),
|
||||
Duration::from_secs(2),
|
||||
)),
|
||||
},
|
||||
],
|
||||
shutdown: vec![
|
||||
ActionLoader::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-wait.gif".into(),
|
||||
scale: 0.9,
|
||||
angle: 0.0,
|
||||
translation: Vec2::new(3.0, 2.0),
|
||||
brightness: 1.0,
|
||||
time: AnimTime::Infinite,
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
248
asusd/src/aura_anime/mod.rs
Normal file
@@ -0,0 +1,248 @@
|
||||
pub mod config;
|
||||
/// Implements `CtrlTask`, Reloadable, `ZbusRun`
|
||||
pub mod trait_impls;
|
||||
|
||||
use std::convert::TryFrom;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::thread::sleep;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info, warn};
|
||||
use rog_anime::usb::{
|
||||
pkt_flush, pkt_set_brightness, pkt_set_enable_display, pkt_set_enable_powersave_anim,
|
||||
pkts_for_init, Brightness,
|
||||
};
|
||||
use rog_anime::{ActionData, AnimeDataBuffer, AnimePacketType};
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::usb_raw::USBRaw;
|
||||
|
||||
use self::config::{AniMeConfig, AniMeConfigCached};
|
||||
use crate::error::RogError;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AniMe {
|
||||
hid: Option<Arc<Mutex<HidRaw>>>,
|
||||
usb: Option<Arc<Mutex<USBRaw>>>,
|
||||
config: Arc<Mutex<AniMeConfig>>,
|
||||
cache: AniMeConfigCached,
|
||||
// set to force thread to exit
|
||||
thread_exit: Arc<AtomicBool>,
|
||||
// Set to false when the thread exits
|
||||
thread_running: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl AniMe {
|
||||
pub fn new(
|
||||
hid: Option<Arc<Mutex<HidRaw>>>,
|
||||
usb: Option<Arc<Mutex<USBRaw>>>,
|
||||
config: Arc<Mutex<AniMeConfig>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
hid,
|
||||
usb,
|
||||
config,
|
||||
cache: AniMeConfigCached::default(),
|
||||
thread_exit: Arc::new(AtomicBool::new(false)),
|
||||
thread_running: Arc::new(AtomicBool::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Will fail if something is already holding the config lock
|
||||
async fn do_init_cache(&mut self) {
|
||||
if let Some(mut config) = self.config.try_lock() {
|
||||
if let Err(e) = self.cache.init_from_config(&config, config.anime_type) {
|
||||
error!(
|
||||
"Trying to cache the Anime Config failed, will reset to default config: {e:?}"
|
||||
);
|
||||
config.rename_file_old();
|
||||
*config = AniMeConfig::new();
|
||||
config.write();
|
||||
} else {
|
||||
debug!("Initialised AniMe cache");
|
||||
}
|
||||
} else {
|
||||
error!("AniMe Matrix could not init cache")
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialise the device if required.
|
||||
pub async fn do_initialization(&mut self) -> Result<(), RogError> {
|
||||
self.do_init_cache().await;
|
||||
let pkts = pkts_for_init();
|
||||
self.write_bytes(&pkts[0]).await?;
|
||||
self.write_bytes(&pkts[1]).await?;
|
||||
debug!("Succesfully initialised AniMe matrix display");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn write_bytes(&self, message: &[u8]) -> Result<(), RogError> {
|
||||
if let Some(hid) = &self.hid {
|
||||
hid.lock().await.write_bytes(message)?;
|
||||
} else if let Some(usb) = &self.usb {
|
||||
usb.lock().await.write_bytes(message)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write only a data packet. This will modify the leds brightness using the
|
||||
/// global brightness set in config.
|
||||
async fn write_data_buffer(&self, mut buffer: AnimeDataBuffer) -> Result<(), RogError> {
|
||||
for led in buffer.data_mut().iter_mut() {
|
||||
let mut bright = *led as f32;
|
||||
if bright > 254.0 {
|
||||
bright = 254.0;
|
||||
}
|
||||
*led = bright as u8;
|
||||
}
|
||||
let data = AnimePacketType::try_from(buffer)?;
|
||||
for row in &data {
|
||||
self.write_bytes(row).await?;
|
||||
}
|
||||
self.write_bytes(&pkt_flush()).await
|
||||
}
|
||||
|
||||
pub async fn set_builtins_enabled(
|
||||
&self,
|
||||
enabled: bool,
|
||||
bright: Brightness,
|
||||
) -> Result<(), RogError> {
|
||||
self.write_bytes(&pkt_set_enable_powersave_anim(enabled))
|
||||
.await?;
|
||||
self.write_bytes(&pkt_set_enable_display(enabled)).await?;
|
||||
self.write_bytes(&pkt_set_brightness(bright)).await?;
|
||||
self.write_bytes(&pkt_set_enable_powersave_anim(enabled))
|
||||
.await
|
||||
}
|
||||
|
||||
/// 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.
|
||||
async fn run_thread(&self, actions: Vec<ActionData>, mut once: bool) {
|
||||
if actions.is_empty() {
|
||||
warn!("AniMe system actions was empty");
|
||||
return;
|
||||
}
|
||||
|
||||
self.write_bytes(&pkt_set_enable_powersave_anim(false))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
let thread_exit = self.thread_exit.clone();
|
||||
let thread_running = self.thread_running.clone();
|
||||
let anime_type = self.config.lock().await.anime_type;
|
||||
let inner = self.clone();
|
||||
|
||||
// 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
|
||||
// TODO: turn this in to async task (maybe? COuld still risk blocking main
|
||||
// thread)
|
||||
tokio::spawn(async move {
|
||||
info!("AniMe new system thread started");
|
||||
// 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.
|
||||
while thread_running.load(Ordering::SeqCst) {
|
||||
// Make any running loop exit first
|
||||
thread_exit.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
info!("AniMe no previous system thread running (now)");
|
||||
thread_exit.store(false, Ordering::SeqCst);
|
||||
thread_running.store(true, Ordering::SeqCst);
|
||||
'main: loop {
|
||||
for action in &actions {
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
match action {
|
||||
ActionData::Animation(frames) => {
|
||||
// TODO: sort all this out
|
||||
rog_anime::run_animation(frames, &|frame| {
|
||||
if thread_exit.load(Ordering::Acquire) {
|
||||
info!("rog-anime: animation sub-loop was asked to exit");
|
||||
return Ok(true); // Do safe exit
|
||||
}
|
||||
let inner = inner.clone();
|
||||
tokio::task::spawn(async move {
|
||||
inner
|
||||
.write_data_buffer(frame)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
});
|
||||
Ok(false) // Don't exit yet
|
||||
});
|
||||
if thread_exit.load(Ordering::Acquire) {
|
||||
info!("rog-anime: sub-loop exited and main loop exiting now");
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
ActionData::Image(image) => {
|
||||
once = false;
|
||||
inner
|
||||
.write_data_buffer(image.as_ref().clone())
|
||||
.await
|
||||
.map_err(|e| error!("{}", e))
|
||||
.ok();
|
||||
}
|
||||
ActionData::Pause(duration) => sleep(*duration),
|
||||
ActionData::AudioEq
|
||||
| ActionData::SystemInfo
|
||||
| ActionData::TimeDate
|
||||
| ActionData::Matrix => {}
|
||||
}
|
||||
}
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
if once || actions.is_empty() {
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
// Clear the display on exit
|
||||
if let Ok(data) =
|
||||
AnimeDataBuffer::from_vec(anime_type, vec![0u8; anime_type.data_length()])
|
||||
.map_err(|e| error!("{}", e))
|
||||
{
|
||||
inner
|
||||
.write_data_buffer(data)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
// A write can block for many milliseconds so lets not hold the config lock for
|
||||
// the same period
|
||||
let enabled = inner.config.lock().await.builtin_anims_enabled;
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(enabled))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
// Loop ended, set the atmonics
|
||||
thread_running.store(false, Ordering::SeqCst);
|
||||
info!("AniMe system thread exited");
|
||||
})
|
||||
.await
|
||||
.map(|err| info!("AniMe system thread: {:?}", err))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
507
asusd/src/aura_anime/trait_impls.rs
Normal file
@@ -0,0 +1,507 @@
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use log::{debug, error, warn};
|
||||
use logind_zbus::manager::ManagerProxy;
|
||||
use rog_anime::usb::{
|
||||
pkt_set_brightness, pkt_set_builtin_animations, pkt_set_enable_display,
|
||||
pkt_set_enable_powersave_anim, Brightness,
|
||||
};
|
||||
use rog_anime::{Animations, AnimeDataBuffer, DeviceState};
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::proxy::CacheProperties;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use super::config::AniMeConfig;
|
||||
use super::AniMe;
|
||||
use crate::error::RogError;
|
||||
use crate::Reloadable;
|
||||
|
||||
async fn get_logind_manager<'a>() -> ManagerProxy<'a> {
|
||||
let connection = Connection::system()
|
||||
.await
|
||||
.expect("Controller could not create dbus connection");
|
||||
|
||||
ManagerProxy::builder(&connection)
|
||||
.cache_properties(CacheProperties::No)
|
||||
.build()
|
||||
.await
|
||||
.expect("Controller could not create ManagerProxy")
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AniMeZbus(AniMe);
|
||||
|
||||
impl AniMeZbus {
|
||||
pub fn new(anime: AniMe) -> Self {
|
||||
Self(anime)
|
||||
}
|
||||
|
||||
pub async fn start_tasks(
|
||||
mut self,
|
||||
connection: &Connection,
|
||||
path: OwnedObjectPath,
|
||||
) -> Result<(), RogError> {
|
||||
// let task = zbus.clone();
|
||||
self.reload()
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Controller error: {}", err));
|
||||
connection
|
||||
.object_server()
|
||||
.at(path.clone(), self)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Couldn't add server at path: {path}, {e:?}");
|
||||
e
|
||||
})?;
|
||||
debug!("start_tasks was successful");
|
||||
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.
|
||||
#[interface(name = "xyz.ljones.Anime")]
|
||||
impl AniMeZbus {
|
||||
/// Writes a data stream of length. Will force system thread to exit until
|
||||
/// it is restarted
|
||||
async fn write(&self, input: AnimeDataBuffer) -> zbus::fdo::Result<()> {
|
||||
let bright = self.0.config.lock().await.display_brightness;
|
||||
if self.0.config.lock().await.builtin_anims_enabled {
|
||||
// This clears the display, causing flickers if done indiscriminately on every
|
||||
// write. Therefore, we guard it behind a config check.
|
||||
self.0.set_builtins_enabled(false, bright).await?;
|
||||
}
|
||||
self.0.thread_exit.store(true, Ordering::SeqCst);
|
||||
self.0.write_data_buffer(input).await.map_err(|err| {
|
||||
warn!("ctrl_anime::run_animation:callback {}", err);
|
||||
err
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set base brightness level
|
||||
#[zbus(property)]
|
||||
async fn brightness(&self) -> Brightness {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.display_brightness;
|
||||
}
|
||||
Brightness::Off
|
||||
}
|
||||
|
||||
/// Set base brightness level
|
||||
#[zbus(property)]
|
||||
async fn set_brightness(&self, brightness: Brightness) {
|
||||
self.0
|
||||
.write_bytes(&pkt_set_brightness(brightness))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::set_brightness {}", err);
|
||||
})
|
||||
.ok();
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_display(brightness != Brightness::Off))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::set_brightness {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.display_enabled = brightness != Brightness::Off;
|
||||
config.display_brightness = brightness;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn builtins_enabled(&self) -> bool {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.builtin_anims_enabled;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Enable the builtin animations or not. This is quivalent to "Powersave
|
||||
/// animations" in Armory crate
|
||||
#[zbus(property)]
|
||||
async fn set_builtins_enabled(&self, enabled: bool) {
|
||||
let mut config = self.0.config.lock().await;
|
||||
let brightness = config.display_brightness;
|
||||
self.0
|
||||
.set_builtins_enabled(enabled, brightness)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::set_builtins_enabled {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
if !enabled {
|
||||
let anime_type = config.anime_type;
|
||||
let data = vec![255u8; anime_type.data_length()];
|
||||
if let Ok(tmp) = AnimeDataBuffer::from_vec(anime_type, data).map_err(|err| {
|
||||
warn!("ctrl_anime::set_builtins_enabled {}", err);
|
||||
}) {
|
||||
self.0
|
||||
.write_bytes(tmp.data())
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::set_builtins_enabled {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
config.builtin_anims_enabled = enabled;
|
||||
config.write();
|
||||
if enabled {
|
||||
self.0.thread_exit.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn builtin_animations(&self) -> Animations {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.builtin_anims;
|
||||
}
|
||||
Animations::default()
|
||||
}
|
||||
|
||||
/// Set which builtin animation is used for each stage
|
||||
#[zbus(property)]
|
||||
async fn set_builtin_animations(&self, settings: Animations) {
|
||||
self.0
|
||||
.write_bytes(&pkt_set_builtin_animations(
|
||||
settings.boot, settings.awake, settings.sleep, settings.shutdown,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(true))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.display_enabled = true;
|
||||
config.builtin_anims = settings;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn enable_display(&self) -> bool {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.display_enabled;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Set whether the AniMe is enabled at all
|
||||
#[zbus(property)]
|
||||
async fn set_enable_display(&self, enabled: bool) {
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_display(enabled))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.display_enabled = enabled;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn off_when_unplugged(&self) -> bool {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.off_when_unplugged;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Set if to turn the AniMe Matrix off when external power is unplugged
|
||||
#[zbus(property)]
|
||||
async fn set_off_when_unplugged(&self, enabled: bool) {
|
||||
let manager = get_logind_manager().await;
|
||||
let pow = manager.on_external_power().await.unwrap_or_default();
|
||||
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_display(!pow && !enabled))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.off_when_unplugged = enabled;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn off_when_suspended(&self) -> bool {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.off_when_suspended;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Set if to turn the AniMe Matrix off when the laptop is suspended
|
||||
#[zbus(property)]
|
||||
async fn set_off_when_suspended(&self, enabled: bool) {
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.off_when_suspended = enabled;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn off_when_lid_closed(&self) -> bool {
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
return config.off_when_lid_closed;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Set if to turn the AniMe Matrix off when the lid is closed
|
||||
#[zbus(property)]
|
||||
async fn set_off_when_lid_closed(&self, enabled: bool) {
|
||||
let manager = get_logind_manager().await;
|
||||
let lid = manager.lid_closed().await.unwrap_or_default();
|
||||
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_display(lid && !enabled))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.off_when_lid_closed = enabled;
|
||||
config.write();
|
||||
}
|
||||
|
||||
/// The main loop is the base system set action if the user isn't running
|
||||
/// the user daemon
|
||||
async fn run_main_loop(&self, start: bool) {
|
||||
if start {
|
||||
self.0.thread_exit.store(true, Ordering::SeqCst);
|
||||
self.0.run_thread(self.0.cache.system.clone(), false).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the device state as stored by asusd
|
||||
// #[zbus(property)]
|
||||
async fn device_state(&self) -> DeviceState {
|
||||
DeviceState::from(&*self.0.config.lock().await)
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::CtrlTask for AniMeZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
"ANIME_ZBUS_PATH"
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, _: SignalEmitter<'static>) -> Result<(), RogError> {
|
||||
let inner1 = self.0.clone();
|
||||
let inner2 = self.0.clone();
|
||||
let inner3 = self.0.clone();
|
||||
let inner4 = self.0.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move |sleeping| {
|
||||
// on_sleep
|
||||
let inner = inner1.clone();
|
||||
async move {
|
||||
let config = inner.config.lock().await.clone();
|
||||
if config.display_enabled {
|
||||
inner.thread_exit.store(true, Ordering::Release); // ensure clean slate
|
||||
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_display(
|
||||
!(sleeping && config.off_when_suspended),
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_suspended {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
if config.builtin_anims_enabled {
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(
|
||||
!(sleeping && config.off_when_suspended),
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_suspended {}", err);
|
||||
})
|
||||
.ok();
|
||||
} else if !sleeping && !config.builtin_anims_enabled {
|
||||
// Run custom wake animation
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(false))
|
||||
.await
|
||||
.ok(); // ensure builtins are disabled
|
||||
|
||||
inner.run_thread(inner.cache.wake.clone(), true).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
move |shutting_down| {
|
||||
// on_shutdown
|
||||
let inner = inner2.clone();
|
||||
async move {
|
||||
let AniMeConfig {
|
||||
display_enabled,
|
||||
builtin_anims_enabled,
|
||||
..
|
||||
} = *inner.config.lock().await;
|
||||
if display_enabled && !builtin_anims_enabled {
|
||||
if shutting_down {
|
||||
inner.run_thread(inner.cache.shutdown.clone(), true).await;
|
||||
} else {
|
||||
inner.run_thread(inner.cache.boot.clone(), true).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
move |lid_closed| {
|
||||
let inner = inner3.clone();
|
||||
// on lid change
|
||||
async move {
|
||||
let AniMeConfig {
|
||||
off_when_lid_closed,
|
||||
builtin_anims_enabled,
|
||||
..
|
||||
} = *inner.config.lock().await;
|
||||
if off_when_lid_closed {
|
||||
if builtin_anims_enabled {
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(!lid_closed))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_suspended {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_display(!lid_closed))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_lid_closed {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
move |power_plugged| {
|
||||
let inner = inner4.clone();
|
||||
// on power change
|
||||
async move {
|
||||
let AniMeConfig {
|
||||
off_when_unplugged,
|
||||
builtin_anims_enabled,
|
||||
brightness_on_battery,
|
||||
..
|
||||
} = *inner.config.lock().await;
|
||||
if off_when_unplugged {
|
||||
if builtin_anims_enabled {
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(power_plugged))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_suspended {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
inner
|
||||
.write_bytes(&pkt_set_enable_display(power_plugged))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_unplugged {}", err);
|
||||
})
|
||||
.ok();
|
||||
} else {
|
||||
inner
|
||||
.write_bytes(&pkt_set_brightness(brightness_on_battery))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::off_when_unplugged {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for AniMeZbus {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
let AniMeConfig {
|
||||
builtin_anims_enabled,
|
||||
builtin_anims,
|
||||
display_enabled,
|
||||
display_brightness,
|
||||
off_when_lid_closed,
|
||||
off_when_unplugged,
|
||||
..
|
||||
} = *self.0.config.lock().await;
|
||||
|
||||
// Set builtins
|
||||
if builtin_anims_enabled {
|
||||
self.0
|
||||
.write_bytes(&pkt_set_builtin_animations(
|
||||
builtin_anims.boot,
|
||||
builtin_anims.awake,
|
||||
builtin_anims.sleep,
|
||||
builtin_anims.shutdown,
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
// Builtins enabled or na?
|
||||
self.0
|
||||
.set_builtins_enabled(builtin_anims_enabled, display_brightness)
|
||||
.await?;
|
||||
|
||||
let manager = get_logind_manager().await;
|
||||
let lid_closed = manager.lid_closed().await.unwrap_or_default();
|
||||
let power_plugged = manager.on_external_power().await.unwrap_or_default();
|
||||
|
||||
let turn_off =
|
||||
(lid_closed && off_when_lid_closed) || (!power_plugged && off_when_unplugged);
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_display(!turn_off))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("create_sys_event_tasks::reload {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
if turn_off || !display_enabled {
|
||||
self.0.write_bytes(&pkt_set_enable_display(false)).await?;
|
||||
// early return so we don't run animation thread
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !builtin_anims_enabled && !self.0.cache.boot.is_empty() {
|
||||
self.0
|
||||
.write_bytes(&pkt_set_enable_powersave_anim(false))
|
||||
.await
|
||||
.ok();
|
||||
|
||||
let action = self.0.cache.boot.clone();
|
||||
self.0.run_thread(action, true).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
416
asusd/src/aura_laptop/config.rs
Normal file
@@ -0,0 +1,416 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use log::{debug, info, warn};
|
||||
use rog_aura::aura_detection::LedSupportData;
|
||||
use rog_aura::keyboard::LaptopAuraPower;
|
||||
use rog_aura::{
|
||||
AuraDeviceType, AuraEffect, AuraModeNum, AuraZone, Direction, LedBrightness, Speed, GRADIENT,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
#[derive(Deserialize, Serialize, Default, Debug, Clone)]
|
||||
// #[serde(default)]
|
||||
pub struct AuraConfig {
|
||||
#[serde(skip)]
|
||||
pub led_type: AuraDeviceType,
|
||||
#[serde(skip)]
|
||||
pub support_data: LedSupportData,
|
||||
pub config_name: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ally_fix: Option<bool>,
|
||||
pub brightness: LedBrightness,
|
||||
pub current_mode: AuraModeNum,
|
||||
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub multizone: Option<BTreeMap<AuraModeNum, Vec<AuraEffect>>>,
|
||||
pub multizone_on: bool,
|
||||
pub enabled: LaptopAuraPower,
|
||||
#[serde(skip)]
|
||||
pub per_key_mode_active: bool,
|
||||
}
|
||||
|
||||
impl StdConfig for AuraConfig {
|
||||
/// Detect the keyboard type and load from default DB if data available
|
||||
fn new() -> Self {
|
||||
panic!("This should not be used");
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
if self.config_name.is_empty() {
|
||||
panic!("Config file name should not be empty");
|
||||
}
|
||||
self.config_name.to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for AuraConfig {}
|
||||
|
||||
impl AuraConfig {
|
||||
/// Detect the keyboard type and load from default DB if data available
|
||||
pub fn new(prod_id: &str) -> Self {
|
||||
info!("Setting up AuraConfig for {prod_id:?}");
|
||||
// create a default config here
|
||||
let device_type = AuraDeviceType::from(prod_id);
|
||||
if device_type == AuraDeviceType::Unknown {
|
||||
warn!("idProduct:{prod_id:?} is unknown");
|
||||
}
|
||||
let support_data = LedSupportData::get_data(prod_id);
|
||||
let enabled = LaptopAuraPower::new(device_type, &support_data);
|
||||
let mut config = AuraConfig {
|
||||
led_type: device_type,
|
||||
support_data,
|
||||
config_name: format!("aura_{prod_id}.ron"),
|
||||
ally_fix: None,
|
||||
brightness: LedBrightness::Med,
|
||||
current_mode: AuraModeNum::Static,
|
||||
builtins: BTreeMap::new(),
|
||||
multizone: None,
|
||||
multizone_on: false,
|
||||
enabled,
|
||||
per_key_mode_active: false,
|
||||
};
|
||||
|
||||
for n in &config.support_data.basic_modes {
|
||||
debug!("creating default for {n}");
|
||||
config
|
||||
.builtins
|
||||
.insert(*n, AuraEffect::default_with_mode(*n));
|
||||
|
||||
if !config.support_data.basic_zones.is_empty() {
|
||||
let mut default = vec![];
|
||||
for (i, tmp) in config.support_data.basic_zones.iter().enumerate() {
|
||||
default.push(AuraEffect {
|
||||
mode: *n,
|
||||
zone: *tmp,
|
||||
colour1: *GRADIENT.get(i).unwrap_or(&GRADIENT[0]),
|
||||
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Left,
|
||||
});
|
||||
}
|
||||
if let Some(m) = config.multizone.as_mut() {
|
||||
m.insert(*n, default);
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(*n, default);
|
||||
config.multizone = Some(tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Set the mode data, current mode, and if multizone enabled.
|
||||
///
|
||||
/// Multipurpose, will accept `AuraEffect` with zones and put in the correct
|
||||
/// store.
|
||||
pub fn set_builtin(&mut self, effect: AuraEffect) {
|
||||
self.current_mode = effect.mode;
|
||||
if effect.zone() == AuraZone::None {
|
||||
self.builtins.insert(*effect.mode(), effect);
|
||||
self.multizone_on = false;
|
||||
} else {
|
||||
if let Some(multi) = self.multizone.as_mut() {
|
||||
if let Some(fx) = multi.get_mut(effect.mode()) {
|
||||
for fx in fx.iter_mut() {
|
||||
if fx.zone == effect.zone {
|
||||
*fx = effect;
|
||||
return;
|
||||
}
|
||||
}
|
||||
fx.push(effect);
|
||||
} else {
|
||||
multi.insert(*effect.mode(), vec![effect]);
|
||||
}
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(*effect.mode(), vec![effect]);
|
||||
self.multizone = Some(tmp);
|
||||
}
|
||||
self.multizone_on = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_multizone(&self, aura_type: AuraModeNum) -> Option<&[AuraEffect]> {
|
||||
if let Some(multi) = &self.multizone {
|
||||
return multi.get(&aura_type).map(|v| v.as_slice());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Create a default for the `current_mode` if multizone and no config
|
||||
/// exists.
|
||||
pub fn create_multizone_default(&mut self) -> Result<(), RogError> {
|
||||
let mut default = vec![];
|
||||
for (i, tmp) in self.support_data.basic_zones.iter().enumerate() {
|
||||
default.push(AuraEffect {
|
||||
mode: self.current_mode,
|
||||
zone: *tmp,
|
||||
colour1: *GRADIENT.get(i).unwrap_or(&GRADIENT[0]),
|
||||
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Left,
|
||||
});
|
||||
}
|
||||
if default.is_empty() {
|
||||
return Err(RogError::AuraEffectNotSupported);
|
||||
}
|
||||
|
||||
if let Some(multizones) = self.multizone.as_mut() {
|
||||
multizones.insert(self.current_mode, default);
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(self.current_mode, default);
|
||||
self.multizone = Some(tmp);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reload the config from disk then verify and update it if required.
|
||||
/// Always rewrites the file to disk.
|
||||
pub fn load_and_update_config(prod_id: &str) -> AuraConfig {
|
||||
// New loads data from the DB also
|
||||
let mut config_init = AuraConfig::new(prod_id);
|
||||
// config_init.set_filename(prod_id);
|
||||
let mut config_loaded = config_init.clone().load();
|
||||
// update the initialised data with what we loaded from disk
|
||||
for mode_init in &mut config_init.builtins {
|
||||
// update init values from loaded values if they exist
|
||||
if let Some(loaded) = config_loaded.builtins.get(mode_init.0) {
|
||||
*mode_init.1 = loaded.clone();
|
||||
}
|
||||
}
|
||||
// Then replace just incase the initialised data contains new modes added
|
||||
config_loaded.builtins = config_init.builtins;
|
||||
config_loaded.support_data = config_init.support_data;
|
||||
config_loaded.led_type = config_init.led_type;
|
||||
config_loaded.ally_fix = config_init.ally_fix;
|
||||
|
||||
for enabled_init in &mut config_init.enabled.states {
|
||||
for enabled in &mut config_loaded.enabled.states {
|
||||
if enabled.zone == enabled_init.zone {
|
||||
*enabled_init = *enabled;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
config_loaded.enabled = config_init.enabled;
|
||||
|
||||
if let (Some(mut multizone_init), Some(multizone_loaded)) =
|
||||
(config_init.multizone, config_loaded.multizone.as_mut())
|
||||
{
|
||||
for mode in multizone_init.iter_mut() {
|
||||
// update init values from loaded values if they exist
|
||||
if let Some(loaded) = multizone_loaded.get(mode.0) {
|
||||
let mut new_set = Vec::new();
|
||||
let data = LedSupportData::get_data(prod_id);
|
||||
// only reuse a zone mode if the mode is supported
|
||||
for mode in loaded {
|
||||
if data.basic_modes.contains(&mode.mode) {
|
||||
new_set.push(mode.clone());
|
||||
}
|
||||
}
|
||||
*mode.1 = new_set;
|
||||
}
|
||||
}
|
||||
*multizone_loaded = multizone_init;
|
||||
}
|
||||
|
||||
config_loaded.write();
|
||||
config_loaded
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rog_aura::keyboard::AuraPowerState;
|
||||
use rog_aura::{
|
||||
AuraEffect, AuraModeNum, AuraZone, Colour, Direction, LedBrightness, PowerZones, Speed,
|
||||
};
|
||||
|
||||
use super::AuraConfig;
|
||||
|
||||
#[test]
|
||||
fn set_multizone_4key_config() {
|
||||
std::env::set_var("BOARD_NAME", "");
|
||||
let mut config = AuraConfig::new("19b6");
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour {
|
||||
r: 0xff,
|
||||
g: 0x00,
|
||||
b: 0xff,
|
||||
},
|
||||
zone: AuraZone::Key1,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
assert!(config.multizone.is_some());
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour {
|
||||
r: 0x00,
|
||||
g: 0xff,
|
||||
b: 0xff,
|
||||
},
|
||||
zone: AuraZone::Key2,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour {
|
||||
r: 0xff,
|
||||
g: 0xff,
|
||||
b: 0x00,
|
||||
},
|
||||
zone: AuraZone::Key3,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour {
|
||||
r: 0x00,
|
||||
g: 0xff,
|
||||
b: 0x00,
|
||||
},
|
||||
zone: AuraZone::Key4,
|
||||
..Default::default()
|
||||
};
|
||||
let effect_clone = effect.clone();
|
||||
config.set_builtin(effect);
|
||||
// This should replace existing
|
||||
config.set_builtin(effect_clone);
|
||||
|
||||
let res = config.multizone.unwrap();
|
||||
let sta = res.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(sta.len(), 4);
|
||||
assert_eq!(sta[0].colour1, Colour {
|
||||
r: 0xff,
|
||||
g: 0x00,
|
||||
b: 0xff
|
||||
});
|
||||
assert_eq!(sta[1].colour1, Colour {
|
||||
r: 0x00,
|
||||
g: 0xff,
|
||||
b: 0xff
|
||||
});
|
||||
assert_eq!(sta[2].colour1, Colour {
|
||||
r: 0xff,
|
||||
g: 0xff,
|
||||
b: 0x00
|
||||
});
|
||||
assert_eq!(sta[3].colour1, Colour {
|
||||
r: 0x00,
|
||||
g: 0xff,
|
||||
b: 0x00
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_multizone_multimode_config() {
|
||||
std::env::set_var("BOARD_NAME", "");
|
||||
let mut config = AuraConfig::new("19b6");
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key1,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
assert!(config.multizone.is_some());
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key2,
|
||||
mode: AuraModeNum::Breathe,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key3,
|
||||
mode: AuraModeNum::Comet,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key4,
|
||||
mode: AuraModeNum::Pulse,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let res = config.multizone.unwrap();
|
||||
let sta = res.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Breathe).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Comet).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Pulse).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_0x1866_g531i() {
|
||||
std::env::set_var("BOARD_NAME", "G513I");
|
||||
let mut config = AuraConfig::new("1866");
|
||||
|
||||
assert_eq!(config.brightness, LedBrightness::Med);
|
||||
assert_eq!(config.builtins.len(), 5);
|
||||
assert_eq!(config.builtins.first_entry().unwrap().get(), &AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::None,
|
||||
colour1: Colour { r: 166, g: 0, b: 0 },
|
||||
colour2: Colour { r: 0, g: 0, b: 0 },
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Right
|
||||
});
|
||||
assert_eq!(config.enabled.states.len(), 1);
|
||||
assert_eq!(config.enabled.states[0], AuraPowerState {
|
||||
zone: PowerZones::KeyboardAndLightbar,
|
||||
boot: true,
|
||||
awake: true,
|
||||
sleep: true,
|
||||
shutdown: true
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_0x19b6_g634j() {
|
||||
std::env::set_var("BOARD_NAME", "G634J");
|
||||
let mut config = AuraConfig::new("19b6");
|
||||
|
||||
assert_eq!(config.brightness, LedBrightness::Med);
|
||||
assert_eq!(config.builtins.len(), 12);
|
||||
assert_eq!(config.builtins.first_entry().unwrap().get(), &AuraEffect {
|
||||
mode: AuraModeNum::Static,
|
||||
zone: AuraZone::None,
|
||||
colour1: Colour { r: 166, g: 0, b: 0 },
|
||||
colour2: Colour { r: 0, g: 0, b: 0 },
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Right
|
||||
});
|
||||
assert_eq!(config.enabled.states.len(), 4);
|
||||
assert_eq!(config.enabled.states[0], AuraPowerState {
|
||||
zone: PowerZones::Keyboard,
|
||||
boot: true,
|
||||
awake: true,
|
||||
sleep: true,
|
||||
shutdown: true
|
||||
});
|
||||
}
|
||||
}
|
||||
229
asusd/src/aura_laptop/mod.rs
Normal file
@@ -0,0 +1,229 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config::AuraConfig;
|
||||
use config_traits::StdConfig;
|
||||
use futures_util::lock::{Mutex, MutexGuard};
|
||||
use log::info;
|
||||
use rog_aura::keyboard::{AuraLaptopUsbPackets, LedUsbPackets};
|
||||
use rog_aura::usb::{AURA_LAPTOP_LED_APPLY, AURA_LAPTOP_LED_SET};
|
||||
use rog_aura::{AuraDeviceType, AuraEffect, LedBrightness, PowerZones, AURA_LAPTOP_LED_MSG_LEN};
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::keyboard_led::KeyboardBacklight;
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
pub mod config;
|
||||
pub mod trait_impls;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Aura {
|
||||
pub hid: Option<Arc<Mutex<HidRaw>>>,
|
||||
pub backlight: Option<Arc<Mutex<KeyboardBacklight>>>,
|
||||
pub config: Arc<Mutex<AuraConfig>>,
|
||||
}
|
||||
|
||||
impl Aura {
|
||||
/// Initialise the device if required.
|
||||
pub async fn do_initialization(&self) -> Result<(), RogError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn lock_config(&self) -> MutexGuard<AuraConfig> {
|
||||
self.config.lock().await
|
||||
}
|
||||
|
||||
/// Will lock the internal config and update. If anything else has locked
|
||||
/// this in scope then a deadlock can occur.
|
||||
pub async fn update_config(&self) -> Result<(), RogError> {
|
||||
let mut config = self.config.lock().await;
|
||||
let bright = if let Some(bl) = self.backlight.as_ref() {
|
||||
bl.lock().await.get_brightness().unwrap_or_default()
|
||||
} else {
|
||||
config.brightness.into()
|
||||
};
|
||||
config.read();
|
||||
config.brightness = bright.into();
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn write_current_config_mode(&self, config: &mut AuraConfig) -> Result<(), RogError> {
|
||||
if config.multizone_on {
|
||||
let mode = config.current_mode;
|
||||
let mut create = false;
|
||||
// There is no multizone config for this mode so create one here
|
||||
// using the colours of rainbow if it exists, or first available
|
||||
// mode, or random
|
||||
if config.multizone.is_none() {
|
||||
create = true;
|
||||
} else if let Some(multizones) = config.multizone.as_ref() {
|
||||
if !multizones.contains_key(&mode) {
|
||||
create = true;
|
||||
}
|
||||
}
|
||||
if create {
|
||||
info!("No user-set config for zone founding, attempting a default");
|
||||
config.create_multizone_default()?;
|
||||
}
|
||||
|
||||
if let Some(multizones) = config.multizone.as_mut() {
|
||||
if let Some(set) = multizones.get(&mode) {
|
||||
for mode in set.clone() {
|
||||
self.write_effect_and_apply(config.led_type, &mode).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mode = config.current_mode;
|
||||
if let Some(effect) = config.builtins.get(&mode).cloned() {
|
||||
self.write_effect_and_apply(config.led_type, &effect)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write the AuraEffect to the device. Will lock `backlight` or `hid`.
|
||||
///
|
||||
/// If per-key or software-mode is active it must be marked as disabled in
|
||||
/// config.
|
||||
pub async fn write_effect_and_apply(
|
||||
&self,
|
||||
dev_type: AuraDeviceType,
|
||||
mode: &AuraEffect,
|
||||
) -> Result<(), RogError> {
|
||||
if matches!(dev_type, AuraDeviceType::LaptopKeyboardTuf) {
|
||||
if let Some(platform) = &self.backlight {
|
||||
let buf = [
|
||||
1, mode.mode as u8, mode.colour1.r, mode.colour1.g, mode.colour1.b,
|
||||
mode.speed as u8,
|
||||
];
|
||||
platform.lock().await.set_kbd_rgb_mode(&buf)?;
|
||||
}
|
||||
} else if let Some(hid_raw) = &self.hid {
|
||||
let bytes: [u8; AURA_LAPTOP_LED_MSG_LEN] = mode.into();
|
||||
let hid_raw = hid_raw.lock().await;
|
||||
hid_raw.write_bytes(&bytes)?;
|
||||
hid_raw.write_bytes(&AURA_LAPTOP_LED_SET)?;
|
||||
// Changes won't persist unless apply is set
|
||||
hid_raw.write_bytes(&AURA_LAPTOP_LED_APPLY)?;
|
||||
} else {
|
||||
return Err(RogError::NoAuraKeyboard);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_brightness(&self, value: u8) -> Result<(), RogError> {
|
||||
if let Some(backlight) = &self.backlight {
|
||||
backlight.lock().await.set_brightness(value)?;
|
||||
return Ok(());
|
||||
}
|
||||
Err(RogError::MissingFunction(
|
||||
"No LED backlight control available".to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Set combination state for boot animation/sleep animation/all leds/keys
|
||||
/// leds/side leds LED active
|
||||
pub async fn set_power_states(&self, config: &AuraConfig) -> Result<(), RogError> {
|
||||
if matches!(config.led_type, rog_aura::AuraDeviceType::LaptopKeyboardTuf) {
|
||||
if let Some(backlight) = &self.backlight {
|
||||
// TODO: tuf bool array
|
||||
let buf = config.enabled.to_bytes(config.led_type);
|
||||
backlight.lock().await.set_kbd_rgb_state(&buf)?;
|
||||
}
|
||||
} else if let Some(hid_raw) = &self.hid {
|
||||
let hid_raw = hid_raw.lock().await;
|
||||
if let Some(p) = config.enabled.states.first() {
|
||||
if p.zone == PowerZones::Ally {
|
||||
let msg = [
|
||||
0x5d,
|
||||
0xd1,
|
||||
0x09,
|
||||
0x01,
|
||||
p.new_to_byte() as u8,
|
||||
0x0,
|
||||
0x0,
|
||||
];
|
||||
hid_raw.write_bytes(&msg)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = config.enabled.to_bytes(config.led_type);
|
||||
let msg = [
|
||||
0x5d, 0xbd, 0x01, bytes[0], bytes[1], bytes[2], bytes[3],
|
||||
];
|
||||
hid_raw.write_bytes(&msg)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write an effect block. This is for per-key, but can be repurposed to
|
||||
/// write the raw factory mode packets - when doing this it is expected that
|
||||
/// only the first `Vec` (`effect[0]`) is valid.
|
||||
pub async fn write_effect_block(
|
||||
&self,
|
||||
config: &mut AuraConfig,
|
||||
effect: &AuraLaptopUsbPackets,
|
||||
) -> Result<(), RogError> {
|
||||
if config.brightness == LedBrightness::Off {
|
||||
config.brightness = LedBrightness::Med;
|
||||
config.write();
|
||||
}
|
||||
|
||||
let pkt_type = effect[0][1];
|
||||
const PER_KEY_TYPE: u8 = 0xbc;
|
||||
|
||||
if let Some(hid_raw) = &self.hid {
|
||||
let hid_raw = hid_raw.lock().await;
|
||||
if pkt_type != PER_KEY_TYPE {
|
||||
config.per_key_mode_active = false;
|
||||
hid_raw.write_bytes(&effect[0])?;
|
||||
hid_raw.write_bytes(&AURA_LAPTOP_LED_SET)?;
|
||||
// hid_raw.write_bytes(&LED_APPLY)?;
|
||||
} else {
|
||||
if !config.per_key_mode_active {
|
||||
let init = LedUsbPackets::get_init_msg();
|
||||
hid_raw.write_bytes(&init)?;
|
||||
config.per_key_mode_active = true;
|
||||
}
|
||||
for row in effect.iter() {
|
||||
hid_raw.write_bytes(row)?;
|
||||
}
|
||||
}
|
||||
} else if matches!(config.led_type, rog_aura::AuraDeviceType::LaptopKeyboardTuf) {
|
||||
if let Some(tuf) = &self.backlight {
|
||||
for row in effect.iter() {
|
||||
let r = row[9];
|
||||
let g = row[10];
|
||||
let b = row[11];
|
||||
tuf.lock().await.set_kbd_rgb_mode(&[
|
||||
0, 0, r, g, b, 0,
|
||||
])?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn fix_ally_power(&mut self) -> Result<(), RogError> {
|
||||
if self.config.lock().await.led_type == AuraDeviceType::Ally {
|
||||
if let Some(hid_raw) = &self.hid {
|
||||
let mut config = self.config.lock().await;
|
||||
if config.ally_fix.is_none() {
|
||||
let msg = [
|
||||
0x5d, 0xbd, 0x01, 0xff, 0xff, 0xff, 0xff,
|
||||
];
|
||||
hid_raw.lock().await.write_bytes(&msg)?;
|
||||
info!("Reset Ally power settings to base");
|
||||
config.ally_fix = Some(true);
|
||||
}
|
||||
config.write();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
343
asusd/src/aura_laptop/trait_impls.rs
Normal file
@@ -0,0 +1,343 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use log::{debug, error, info, warn};
|
||||
use rog_aura::keyboard::{AuraLaptopUsbPackets, LaptopAuraPower};
|
||||
use rog_aura::{AuraDeviceType, AuraEffect, AuraModeNum, AuraZone, LedBrightness, PowerZones};
|
||||
use zbus::fdo::Error as ZbErr;
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use super::Aura;
|
||||
use crate::error::RogError;
|
||||
use crate::{CtrlTask, Reloadable};
|
||||
|
||||
pub const AURA_ZBUS_NAME: &str = "Aura";
|
||||
pub const AURA_ZBUS_PATH: &str = "/xyz/ljones";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuraZbus(Aura);
|
||||
|
||||
impl AuraZbus {
|
||||
pub fn new(aura: Aura) -> Self {
|
||||
Self(aura)
|
||||
}
|
||||
|
||||
pub async fn start_tasks(
|
||||
mut self,
|
||||
connection: &Connection,
|
||||
// _signal_ctx: SignalEmitter<'static>,
|
||||
path: OwnedObjectPath,
|
||||
) -> Result<(), RogError> {
|
||||
// let task = zbus.clone();
|
||||
// let signal_ctx = signal_ctx.clone();
|
||||
self.reload()
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Controller error: {}", err));
|
||||
connection
|
||||
.object_server()
|
||||
.at(path.clone(), self)
|
||||
.await
|
||||
.map_err(|e| error!("Couldn't add server at path: {path}, {e:?}"))
|
||||
.ok();
|
||||
// TODO: skip this until we keep handles to tasks so they can be killed
|
||||
// task.create_tasks(signal_ctx).await
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The main interface for changing, reading, or notfying
|
||||
///
|
||||
/// LED commands are split between Brightness, Modes, Per-Key
|
||||
#[interface(name = "xyz.ljones.Aura")]
|
||||
impl AuraZbus {
|
||||
/// Return the device type for this Aura keyboard
|
||||
#[zbus(property)]
|
||||
async fn device_type(&self) -> AuraDeviceType {
|
||||
self.0.config.lock().await.led_type
|
||||
}
|
||||
|
||||
/// Return the current LED brightness
|
||||
#[zbus(property)]
|
||||
async fn brightness(&self) -> Result<LedBrightness, ZbErr> {
|
||||
if let Some(bl) = self.0.backlight.as_ref() {
|
||||
return Ok(bl.lock().await.get_brightness().map(|n| n.into())?);
|
||||
}
|
||||
Err(ZbErr::Failed("No sysfs brightness control".to_string()))
|
||||
}
|
||||
|
||||
/// Set the keyboard brightness level (0-3)
|
||||
#[zbus(property)]
|
||||
async fn set_brightness(&mut self, brightness: LedBrightness) -> Result<(), ZbErr> {
|
||||
if let Some(bl) = self.0.backlight.as_ref() {
|
||||
return Ok(bl.lock().await.set_brightness(brightness.into())?);
|
||||
}
|
||||
Err(ZbErr::Failed("No sysfs brightness control".to_string()))
|
||||
}
|
||||
|
||||
/// Total levels of brightness available
|
||||
#[zbus(property)]
|
||||
async fn supported_brightness(&self) -> Vec<LedBrightness> {
|
||||
vec![
|
||||
LedBrightness::Off,
|
||||
LedBrightness::Low,
|
||||
LedBrightness::Med,
|
||||
LedBrightness::High,
|
||||
]
|
||||
}
|
||||
|
||||
/// The total available modes
|
||||
#[zbus(property)]
|
||||
async fn supported_basic_modes(&self) -> Result<Vec<AuraModeNum>, ZbErr> {
|
||||
let config = self.0.config.lock().await;
|
||||
Ok(config.builtins.keys().cloned().collect())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn supported_basic_zones(&self) -> Result<Vec<AuraZone>, ZbErr> {
|
||||
let config = self.0.config.lock().await;
|
||||
Ok(config.support_data.basic_zones.clone())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn supported_power_zones(&self) -> Result<Vec<PowerZones>, ZbErr> {
|
||||
let config = self.0.config.lock().await;
|
||||
Ok(config.support_data.power_zones.clone())
|
||||
}
|
||||
|
||||
/// The current mode data
|
||||
#[zbus(property)]
|
||||
async fn led_mode(&self) -> Result<AuraModeNum, ZbErr> {
|
||||
// entirely possible to deadlock here, so use try instead of lock()
|
||||
// let ctrl = self.0.lock().await;
|
||||
// Ok(config.current_mode)
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
Ok(config.current_mode)
|
||||
} else {
|
||||
Err(ZbErr::Failed("Aura control couldn't lock self".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an Aura effect if the effect mode or zone is supported.
|
||||
///
|
||||
/// On success the aura config file is read to refresh cached values, then
|
||||
/// the effect is stored and config written to disk.
|
||||
#[zbus(property)]
|
||||
async fn set_led_mode(&mut self, num: AuraModeNum) -> Result<(), ZbErr> {
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.current_mode = num;
|
||||
self.0.write_current_config_mode(&mut config).await?;
|
||||
if config.brightness == LedBrightness::Off {
|
||||
config.brightness = LedBrightness::Med;
|
||||
}
|
||||
self.0.set_brightness(config.brightness.into()).await?;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The current mode data
|
||||
#[zbus(property)]
|
||||
async fn led_mode_data(&self) -> Result<AuraEffect, ZbErr> {
|
||||
// entirely possible to deadlock here, so use try instead of lock()
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
let mode = config.current_mode;
|
||||
match config.builtins.get(&mode) {
|
||||
Some(effect) => Ok(effect.clone()),
|
||||
None => Err(ZbErr::Failed("Could not get the current effect".into())),
|
||||
}
|
||||
} else {
|
||||
Err(ZbErr::Failed("Aura control couldn't lock self".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an Aura effect if the effect mode or zone is supported.
|
||||
///
|
||||
/// On success the aura config file is read to refresh cached values, then
|
||||
/// the effect is stored and config written to disk.
|
||||
#[zbus(property)]
|
||||
async fn set_led_mode_data(&mut self, effect: AuraEffect) -> Result<(), ZbErr> {
|
||||
let mut config = self.0.config.lock().await;
|
||||
if !config.support_data.basic_modes.contains(&effect.mode)
|
||||
|| effect.zone != AuraZone::None
|
||||
&& !config.support_data.basic_zones.contains(&effect.zone)
|
||||
{
|
||||
return Err(ZbErr::NotSupported(format!(
|
||||
"The Aura effect is not supported: {effect:?}"
|
||||
)));
|
||||
}
|
||||
|
||||
self.0
|
||||
.write_effect_and_apply(config.led_type, &effect)
|
||||
.await?;
|
||||
if config.brightness == LedBrightness::Off {
|
||||
config.brightness = LedBrightness::Med;
|
||||
}
|
||||
self.0.set_brightness(config.brightness.into()).await?;
|
||||
config.set_builtin(effect);
|
||||
config.write();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the data set for every mode available
|
||||
async fn all_mode_data(&self) -> BTreeMap<AuraModeNum, AuraEffect> {
|
||||
let config = self.0.config.lock().await;
|
||||
config.builtins.clone()
|
||||
}
|
||||
|
||||
// As property doesn't work for AuraPowerDev (complexity of serialization?)
|
||||
#[zbus(property)]
|
||||
async fn led_power(&self) -> LaptopAuraPower {
|
||||
let config = self.0.config.lock().await;
|
||||
config.enabled.clone()
|
||||
}
|
||||
|
||||
/// Set a variety of states, input is array of enum.
|
||||
/// `enabled` sets if the sent array should be disabled or enabled
|
||||
///
|
||||
/// For Modern ROG devices the "enabled" flag is ignored.
|
||||
#[zbus(property)]
|
||||
async fn set_led_power(&mut self, options: LaptopAuraPower) -> Result<(), ZbErr> {
|
||||
let mut config = self.0.config.lock().await;
|
||||
for opt in options.states {
|
||||
let zone = opt.zone;
|
||||
for config in config.enabled.states.iter_mut() {
|
||||
if config.zone == zone {
|
||||
*config = opt;
|
||||
}
|
||||
}
|
||||
}
|
||||
config.write();
|
||||
Ok(self.0.set_power_states(&config).await.map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?)
|
||||
}
|
||||
|
||||
/// On machine that have some form of either per-key keyboard or per-zone
|
||||
/// this can be used to write custom effects over dbus. The input is a
|
||||
/// nested `Vec<Vec<8>>` where `Vec<u8>` is a raw USB packet
|
||||
async fn direct_addressing_raw(&self, data: AuraLaptopUsbPackets) -> Result<(), ZbErr> {
|
||||
let mut config = self.0.config.lock().await;
|
||||
self.0.write_effect_block(&mut config, &data).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlTask for AuraZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
"/xyz/ljones"
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, _: SignalEmitter<'static>) -> Result<(), RogError> {
|
||||
let inner1 = self.0.clone();
|
||||
let inner3 = self.0.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move |sleeping| {
|
||||
let inner1 = inner1.clone();
|
||||
// unwrap as we want to bomb out of the task
|
||||
async move {
|
||||
if !sleeping {
|
||||
info!("CtrlKbdLedTask reloading brightness and modes");
|
||||
if let Some(backlight) = &inner1.backlight {
|
||||
backlight
|
||||
.lock()
|
||||
.await
|
||||
.set_brightness(inner1.config.lock().await.brightness.into())
|
||||
.map_err(|e| {
|
||||
error!("CtrlKbdLedTask: {e}");
|
||||
e
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
let mut config = inner1.config.lock().await;
|
||||
inner1
|
||||
.write_current_config_mode(&mut config)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("CtrlKbdLedTask: {e}");
|
||||
e
|
||||
})
|
||||
.unwrap();
|
||||
} else if sleeping {
|
||||
inner1
|
||||
.update_config()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("CtrlKbdLedTask: {e}");
|
||||
e
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
move |_shutting_down| {
|
||||
let inner3 = inner3.clone();
|
||||
async move {
|
||||
info!("CtrlKbdLedTask reloading brightness and modes");
|
||||
if let Some(backlight) = &inner3.backlight {
|
||||
// unwrap as we want to bomb out of the task
|
||||
backlight
|
||||
.lock()
|
||||
.await
|
||||
.set_brightness(inner3.config.lock().await.brightness.into())
|
||||
.map_err(|e| {
|
||||
error!("CtrlKbdLedTask: {e}");
|
||||
e
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
},
|
||||
move |_lid_closed| {
|
||||
// on lid change
|
||||
async move {}
|
||||
},
|
||||
move |_power_plugged| {
|
||||
// power change
|
||||
async move {}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// let ctrl2 = self.0.clone();
|
||||
// let ctrl = self.0.lock().await;
|
||||
// if ctrl.led_node.has_brightness_control() {
|
||||
// let watch = ctrl.led_node.monitor_brightness()?;
|
||||
// tokio::spawn(async move {
|
||||
// let mut buffer = [0; 32];
|
||||
// watch
|
||||
// .into_event_stream(&mut buffer)
|
||||
// .unwrap()
|
||||
// .for_each(|_| async {
|
||||
// if let Some(lock) = ctrl2.try_lock() {
|
||||
// load_save(true, lock).unwrap(); // unwrap as we want
|
||||
// // to
|
||||
// // bomb out of the
|
||||
// // task
|
||||
// }
|
||||
// })
|
||||
// .await;
|
||||
// });
|
||||
// }
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Reloadable for AuraZbus {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
self.0.fix_ally_power().await?;
|
||||
debug!("reloading keyboard mode");
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0.write_current_config_mode(&mut config).await?;
|
||||
debug!("reloading power states");
|
||||
self.0
|
||||
.set_power_states(&config)
|
||||
.await
|
||||
.map_err(|err| warn!("{err}"))
|
||||
.ok();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
541
asusd/src/aura_manager.rs
Normal file
@@ -0,0 +1,541 @@
|
||||
// Plan:
|
||||
// - Manager has udev monitor on USB looking for ROG devices
|
||||
// - If a device is found, add it to watch
|
||||
// - Add it to Zbus server
|
||||
// - If udev sees device removed then remove the zbus path
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use dmi_id::DMIID;
|
||||
use futures_lite::future::block_on;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info, warn};
|
||||
use mio::{Events, Interest, Poll, Token};
|
||||
use rog_platform::error::PlatformError;
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use udev::{Device, MonitorBuilder};
|
||||
use zbus::zvariant::{ObjectPath, OwnedObjectPath};
|
||||
use zbus::Connection;
|
||||
|
||||
use crate::aura_anime::trait_impls::AniMeZbus;
|
||||
use crate::aura_laptop::trait_impls::AuraZbus;
|
||||
use crate::aura_scsi::trait_impls::ScsiZbus;
|
||||
use crate::aura_slash::trait_impls::SlashZbus;
|
||||
use crate::aura_types::DeviceHandle;
|
||||
use crate::error::RogError;
|
||||
use crate::ASUS_ZBUS_PATH;
|
||||
|
||||
const MOD_NAME: &str = "aura";
|
||||
|
||||
/// Returns only the Device details concatenated in a form usable for
|
||||
/// adding/appending to a filename
|
||||
pub fn filename_partial(parent: &Device) -> Option<OwnedObjectPath> {
|
||||
if let Some(id_product) = parent.attribute_value("idProduct") {
|
||||
let id_product = id_product.to_string_lossy();
|
||||
let mut path = if let Some(devnum) = parent.attribute_value("devnum") {
|
||||
let devnum = devnum.to_string_lossy();
|
||||
if let Some(devpath) = parent.attribute_value("devpath") {
|
||||
let devpath = devpath.to_string_lossy();
|
||||
format!("{id_product}_{devnum}_{devpath}")
|
||||
} else {
|
||||
format!("{id_product}_{devnum}")
|
||||
}
|
||||
} else {
|
||||
format!("{id_product}")
|
||||
};
|
||||
if path.contains('.') {
|
||||
warn!("dbus path for {id_product} contains `.`, removing");
|
||||
path.replace('.', "").clone_into(&mut path);
|
||||
}
|
||||
return Some(ObjectPath::from_str_unchecked(&path).into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn dbus_path_for_dev(parent: &Device) -> Option<OwnedObjectPath> {
|
||||
if let Some(filename) = filename_partial(parent) {
|
||||
return Some(
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/{filename}"))
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn dbus_path_for_tuf() -> OwnedObjectPath {
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/tuf")).into()
|
||||
}
|
||||
|
||||
fn dbus_path_for_slash() -> OwnedObjectPath {
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/slash")).into()
|
||||
}
|
||||
|
||||
fn dbus_path_for_anime() -> OwnedObjectPath {
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/anime")).into()
|
||||
}
|
||||
|
||||
fn dbus_path_for_scsi(prod_id: &str) -> OwnedObjectPath {
|
||||
ObjectPath::from_str_unchecked(&format!("{ASUS_ZBUS_PATH}/{MOD_NAME}/{prod_id}_scsi")).into()
|
||||
}
|
||||
|
||||
fn dev_prop_matches(dev: &Device, prop: &str, value: &str) -> bool {
|
||||
if let Some(p) = dev.property_value(prop) {
|
||||
return p == value;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// A device.
|
||||
///
|
||||
/// Each controller within should track its dbus path so it can be removed if
|
||||
/// required.
|
||||
pub struct AsusDevice {
|
||||
device: DeviceHandle,
|
||||
dbus_path: OwnedObjectPath,
|
||||
}
|
||||
|
||||
pub struct DeviceManager {
|
||||
_dbus_connection: Connection,
|
||||
}
|
||||
|
||||
impl DeviceManager {
|
||||
async fn init_hid_devices(
|
||||
connection: &Connection,
|
||||
device: Device,
|
||||
) -> Result<Vec<AsusDevice>, RogError> {
|
||||
let mut devices = Vec::new();
|
||||
if let Some(usb_device) = device.parent_with_subsystem_devtype("usb", "usb_device")? {
|
||||
if let Some(usb_id) = usb_device.attribute_value("idProduct") {
|
||||
if let Some(vendor_id) = usb_device.attribute_value("idVendor") {
|
||||
if vendor_id != "0b05" {
|
||||
debug!("Not ASUS vendor ID");
|
||||
return Ok(devices);
|
||||
}
|
||||
// Almost all devices are identified by the productId.
|
||||
// So let's see what we have and:
|
||||
// 1. Generate an interface path
|
||||
// 2. Create the device
|
||||
// Use the top-level endpoint, not the parent
|
||||
if let Ok(hidraw) = HidRaw::from_device(device) {
|
||||
debug!("Testing device {usb_id:?}");
|
||||
let dev = Arc::new(Mutex::new(hidraw));
|
||||
// SLASH DEVICE
|
||||
if let Ok(dev_type) = DeviceHandle::new_slash_hid(
|
||||
dev.clone(),
|
||||
usb_id.to_str().unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let DeviceHandle::Slash(slash) = dev_type.clone() {
|
||||
let path =
|
||||
dbus_path_for_dev(&usb_device).unwrap_or(dbus_path_for_slash());
|
||||
let ctrl = SlashZbus::new(slash);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
// ANIME MATRIX DEVICE
|
||||
if let Ok(dev_type) = DeviceHandle::maybe_anime_hid(
|
||||
dev.clone(),
|
||||
usb_id.to_str().unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let DeviceHandle::AniMe(anime) = dev_type.clone() {
|
||||
let path =
|
||||
dbus_path_for_dev(&usb_device).unwrap_or(dbus_path_for_anime());
|
||||
let ctrl = AniMeZbus::new(anime);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
// AURA LAPTOP DEVICE
|
||||
if let Ok(dev_type) = DeviceHandle::maybe_laptop_aura(
|
||||
Some(dev),
|
||||
usb_id.to_str().unwrap_or_default(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
if let DeviceHandle::Aura(aura) = dev_type.clone() {
|
||||
let path =
|
||||
dbus_path_for_dev(&usb_device).unwrap_or(dbus_path_for_tuf());
|
||||
let ctrl = AuraZbus::new(aura);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
/// To be called on daemon startup
|
||||
async fn init_all_hid(connection: &Connection) -> Result<Vec<AsusDevice>, RogError> {
|
||||
// track and ensure we use only one hidraw per prod_id
|
||||
// let mut interfaces = HashSet::new();
|
||||
let mut devices: Vec<AsusDevice> = Vec::new();
|
||||
|
||||
let mut enumerator = udev::Enumerator::new().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
PlatformError::Udev("enumerator failed".into(), err)
|
||||
})?;
|
||||
|
||||
enumerator.match_subsystem("hidraw").map_err(|err| {
|
||||
warn!("{}", err);
|
||||
PlatformError::Udev("match_subsystem failed".into(), err)
|
||||
})?;
|
||||
|
||||
for device in enumerator
|
||||
.scan_devices()
|
||||
.map_err(|e| PlatformError::IoPath("enumerator".to_owned(), e))?
|
||||
{
|
||||
devices.append(&mut Self::init_hid_devices(connection, device).await?);
|
||||
}
|
||||
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
async fn init_scsi(
|
||||
connection: &Connection,
|
||||
device: &Device,
|
||||
path: OwnedObjectPath,
|
||||
) -> Option<AsusDevice> {
|
||||
// "ID_MODEL_ID" "1932"
|
||||
// "ID_VENDOR_ID" "0b05"
|
||||
if dev_prop_matches(device, "ID_VENDOR_ID", "0b05") {
|
||||
if let Some(dev_node) = device.devnode() {
|
||||
let prod_id = device
|
||||
.property_value("ID_MODEL_ID")
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy();
|
||||
if let Ok(dev_type) =
|
||||
DeviceHandle::maybe_scsi(dev_node.as_os_str().to_str().unwrap(), &prod_id).await
|
||||
{
|
||||
if let DeviceHandle::Scsi(scsi) = dev_type.clone() {
|
||||
let ctrl = ScsiZbus::new(scsi);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
return Some(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
async fn init_all_scsi(connection: &Connection) -> Result<Vec<AsusDevice>, RogError> {
|
||||
// track and ensure we use only one hidraw per prod_id
|
||||
// let mut interfaces = HashSet::new();
|
||||
let mut devices: Vec<AsusDevice> = Vec::new();
|
||||
|
||||
let mut enumerator = udev::Enumerator::new().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
PlatformError::Udev("enumerator failed".into(), err)
|
||||
})?;
|
||||
|
||||
enumerator.match_subsystem("block").map_err(|err| {
|
||||
warn!("{}", err);
|
||||
PlatformError::Udev("match_subsystem failed".into(), err)
|
||||
})?;
|
||||
|
||||
let mut found = Vec::new();
|
||||
for device in enumerator
|
||||
.scan_devices()
|
||||
.map_err(|e| PlatformError::IoPath("enumerator".to_owned(), e))?
|
||||
{
|
||||
if let Some(serial) = device.property_value("ID_SERIAL_SHORT") {
|
||||
let serial = serial.to_string_lossy().to_string();
|
||||
let path = dbus_path_for_scsi(&serial);
|
||||
if found.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(dev) = Self::init_scsi(connection, &device, path.clone()).await {
|
||||
devices.push(dev);
|
||||
found.push(path);
|
||||
}
|
||||
} else {
|
||||
debug!("No serial for SCSI device: {:?}", device.devpath());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
pub async fn find_all_devices(connection: &Connection) -> Vec<AsusDevice> {
|
||||
let mut devices: Vec<AsusDevice> = Vec::new();
|
||||
// HID first, always
|
||||
if let Ok(devs) = &mut Self::init_all_hid(connection).await {
|
||||
devices.append(devs);
|
||||
}
|
||||
// USB after, need to check if HID picked something up and if so, skip it
|
||||
let mut do_anime = true;
|
||||
let mut do_slash = true;
|
||||
let mut do_kb_backlight = true;
|
||||
for dev in devices.iter() {
|
||||
if matches!(dev.device, DeviceHandle::Slash(_)) {
|
||||
do_slash = false;
|
||||
}
|
||||
if matches!(dev.device, DeviceHandle::AniMe(_)) {
|
||||
do_anime = false;
|
||||
}
|
||||
if matches!(dev.device, DeviceHandle::Aura(_) | DeviceHandle::OldAura(_)) {
|
||||
do_kb_backlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
if do_slash {
|
||||
if let Ok(dev_type) = DeviceHandle::new_slash_usb().await {
|
||||
if let DeviceHandle::Slash(slash) = dev_type.clone() {
|
||||
let path = dbus_path_for_slash();
|
||||
let ctrl = SlashZbus::new(slash);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
info!("Tested device was not Slash");
|
||||
}
|
||||
}
|
||||
|
||||
if do_anime {
|
||||
if let Ok(dev_type) = DeviceHandle::maybe_anime_usb().await {
|
||||
// TODO: this is copy/pasted
|
||||
if let DeviceHandle::AniMe(anime) = dev_type.clone() {
|
||||
let path = dbus_path_for_anime();
|
||||
let ctrl = AniMeZbus::new(anime);
|
||||
if ctrl
|
||||
.start_tasks(connection, path.clone())
|
||||
.await
|
||||
.map_err(|e| error!("Failed to start tasks: {e:?}, not adding this device"))
|
||||
.is_ok()
|
||||
{
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("Tested device was not AniMe Matrix");
|
||||
}
|
||||
}
|
||||
|
||||
if do_kb_backlight {
|
||||
// TUF AURA LAPTOP DEVICE
|
||||
// product_name = ASUS TUF Gaming F15 FX507ZE_FX507ZE
|
||||
// product_family = ASUS TUF Gaming F15
|
||||
let product_name = DMIID::new().unwrap_or_default().product_name;
|
||||
let product_family = DMIID::new().unwrap_or_default().product_family;
|
||||
info!(
|
||||
"No USB keyboard aura, system is {product_name}, try using sysfs backlight control"
|
||||
);
|
||||
if product_name.contains("TUF") || product_family.contains("TUF") {
|
||||
info!("TUF laptop, try using sysfs backlight control");
|
||||
if let Ok(dev_type) = DeviceHandle::maybe_laptop_aura(None, "tuf").await {
|
||||
if let DeviceHandle::Aura(aura) = dev_type.clone() {
|
||||
let path = dbus_path_for_tuf();
|
||||
let ctrl = AuraZbus::new(aura);
|
||||
ctrl.start_tasks(connection, path.clone()).await.unwrap();
|
||||
devices.push(AsusDevice {
|
||||
device: dev_type,
|
||||
dbus_path: path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(devs) = &mut Self::init_all_scsi(connection).await {
|
||||
devices.append(devs);
|
||||
}
|
||||
|
||||
devices
|
||||
}
|
||||
|
||||
pub async fn new(connection: Connection) -> Result<Self, RogError> {
|
||||
let conn_copy = connection.clone();
|
||||
let devices = Self::find_all_devices(&conn_copy).await;
|
||||
info!("Found {} valid devices on startup", devices.len());
|
||||
let devices = Arc::new(Mutex::new(devices));
|
||||
let manager = Self {
|
||||
_dbus_connection: connection,
|
||||
};
|
||||
|
||||
// TODO: The /sysfs/ LEDs don't cause events, so they need to be manually
|
||||
// checked for and added
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let mut monitor = MonitorBuilder::new()?.listen()?;
|
||||
let mut poll = Poll::new()?;
|
||||
let mut events = Events::with_capacity(1024);
|
||||
poll.registry()
|
||||
.register(&mut monitor, Token(0), Interest::READABLE)?;
|
||||
|
||||
let rt = tokio::runtime::Runtime::new().expect("Unable to create Runtime");
|
||||
let _enter = rt.enter();
|
||||
loop {
|
||||
if poll.poll(&mut events, None).is_err() {
|
||||
continue;
|
||||
}
|
||||
for event in monitor.iter() {
|
||||
let action = event
|
||||
.action()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
let subsys = if let Some(subsys) = event.subsystem() {
|
||||
subsys.to_string_lossy().to_string()
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let devices = devices.clone();
|
||||
let conn_copy = conn_copy.clone();
|
||||
block_on(async move {
|
||||
// SCSCI devs
|
||||
if subsys == "block" {
|
||||
if action == "remove" {
|
||||
if let Some(serial) =
|
||||
event.device().property_value("ID_SERIAL_SHORT")
|
||||
{
|
||||
let serial = serial.to_string_lossy().to_string();
|
||||
let path = dbus_path_for_scsi(&serial);
|
||||
|
||||
let index = if let Some(index) = devices
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.position(|dev| dev.dbus_path == path)
|
||||
{
|
||||
index
|
||||
} else {
|
||||
if dev_prop_matches(&event.device(), "ID_VENDOR_ID", "0b05")
|
||||
{
|
||||
warn!("No device for dbus path: {path:?}");
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
info!("removing: {path:?}");
|
||||
let dev = devices.lock().await.remove(index);
|
||||
let path = path.clone();
|
||||
if let DeviceHandle::Scsi(_) = dev.device {
|
||||
conn_copy
|
||||
.object_server()
|
||||
.remove::<ScsiZbus, _>(&path)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
} else if action == "add" {
|
||||
let evdev = event.device();
|
||||
if let Some(serial) = evdev.property_value("ID_SERIAL_SHORT") {
|
||||
let serial = serial.to_string_lossy().to_string();
|
||||
let path = dbus_path_for_scsi(&serial);
|
||||
if let Some(new_devs) =
|
||||
Self::init_scsi(&conn_copy, &evdev, path).await
|
||||
{
|
||||
devices.lock().await.append(&mut vec![new_devs]);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if subsys == "hidraw" {
|
||||
if let Some(parent) =
|
||||
event.parent_with_subsystem_devtype("usb", "usb_device")?
|
||||
{
|
||||
if action == "remove" {
|
||||
if let Some(path) = dbus_path_for_dev(&parent) {
|
||||
// Find the indexs of devices matching the path
|
||||
let removals: Vec<usize> = devices
|
||||
.lock()
|
||||
.await
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, dev)| {
|
||||
if dev.dbus_path == path {
|
||||
Some(i)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if removals.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
info!("removing: {path:?}");
|
||||
// Iter in reverse so as to not screw up indexing
|
||||
for index in removals.iter().rev() {
|
||||
let dev = devices.lock().await.remove(*index);
|
||||
let path = path.clone();
|
||||
let res = match dev.device {
|
||||
DeviceHandle::Aura(_) => {
|
||||
conn_copy
|
||||
.object_server()
|
||||
.remove::<AuraZbus, _>(&path)
|
||||
.await?
|
||||
}
|
||||
DeviceHandle::Slash(_) => {
|
||||
conn_copy
|
||||
.object_server()
|
||||
.remove::<SlashZbus, _>(&path)
|
||||
.await?
|
||||
}
|
||||
DeviceHandle::AniMe(_) => {
|
||||
conn_copy
|
||||
.object_server()
|
||||
.remove::<AniMeZbus, _>(&path)
|
||||
.await?
|
||||
}
|
||||
DeviceHandle::Scsi(_) => {
|
||||
conn_copy
|
||||
.object_server()
|
||||
.remove::<ScsiZbus, _>(&path)
|
||||
.await?
|
||||
}
|
||||
_ => todo!(),
|
||||
};
|
||||
info!("AuraManager removed: {path:?}, {res}");
|
||||
}
|
||||
}
|
||||
} else if action == "add" {
|
||||
let evdev = event.device();
|
||||
if let Ok(mut new_devs) =
|
||||
Self::init_hid_devices(&conn_copy, evdev)
|
||||
.await
|
||||
.map_err(|e| error!("Couldn't add new device: {e:?}"))
|
||||
{
|
||||
devices.lock().await.append(&mut new_devs);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok::<(), RogError>(())
|
||||
})
|
||||
.map_err(|e| error!("{e:?}"))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
// Required for return type on spawn
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), RogError>(())
|
||||
});
|
||||
Ok(manager)
|
||||
}
|
||||
}
|
||||
114
asusd/src/aura_scsi/config.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_aura::AuraDeviceType;
|
||||
use rog_scsi::{AuraEffect, AuraMode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "scsi.ron";
|
||||
|
||||
/// Config for base system actions for the anime display
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct ScsiConfig {
|
||||
#[serde(skip)]
|
||||
pub dev_type: AuraDeviceType,
|
||||
pub enabled: bool,
|
||||
pub current_mode: AuraMode,
|
||||
pub modes: BTreeMap<AuraMode, AuraEffect>,
|
||||
}
|
||||
|
||||
impl ScsiConfig {
|
||||
pub fn get_effect(&mut self, mode: AuraMode) -> Option<&AuraEffect> {
|
||||
self.modes.get(&mode)
|
||||
}
|
||||
|
||||
pub fn save_effect(&mut self, effect: AuraEffect) {
|
||||
self.current_mode = effect.mode;
|
||||
self.modes.insert(*effect.mode(), effect);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ScsiConfig {
|
||||
fn default() -> Self {
|
||||
ScsiConfig {
|
||||
enabled: true,
|
||||
current_mode: AuraMode::Static,
|
||||
dev_type: AuraDeviceType::ScsiExtDisk,
|
||||
modes: BTreeMap::from([
|
||||
(AuraMode::Off, AuraEffect::default_with_mode(AuraMode::Off)),
|
||||
(
|
||||
AuraMode::Static,
|
||||
AuraEffect::default_with_mode(AuraMode::Static),
|
||||
),
|
||||
(
|
||||
AuraMode::Breathe,
|
||||
AuraEffect::default_with_mode(AuraMode::Breathe),
|
||||
),
|
||||
(
|
||||
AuraMode::Flashing,
|
||||
AuraEffect::default_with_mode(AuraMode::Flashing),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowCycle,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowCycle),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowWave,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowWave),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowCycleBreathe,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowCycleBreathe),
|
||||
),
|
||||
(
|
||||
AuraMode::ChaseFade,
|
||||
AuraEffect::default_with_mode(AuraMode::ChaseFade),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowCycleChaseFade,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowCycleChaseFade),
|
||||
),
|
||||
(
|
||||
AuraMode::Chase,
|
||||
AuraEffect::default_with_mode(AuraMode::Chase),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowCycleChase,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowCycleChase),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowCycleWave,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowCycleWave),
|
||||
),
|
||||
(
|
||||
AuraMode::RainbowPulseChase,
|
||||
AuraEffect::default_with_mode(AuraMode::RainbowPulseChase),
|
||||
),
|
||||
(
|
||||
AuraMode::RandomFlicker,
|
||||
AuraEffect::default_with_mode(AuraMode::RandomFlicker),
|
||||
),
|
||||
(
|
||||
AuraMode::DoubleFade,
|
||||
AuraEffect::default_with_mode(AuraMode::DoubleFade),
|
||||
),
|
||||
]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfig for ScsiConfig {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for ScsiConfig {}
|
||||
45
asusd/src/aura_scsi/mod.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config::ScsiConfig;
|
||||
use futures_util::lock::{Mutex, MutexGuard};
|
||||
use rog_scsi::{AuraEffect, Device, Task};
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
pub mod config;
|
||||
pub mod trait_impls;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ScsiAura {
|
||||
device: Arc<Mutex<Device>>,
|
||||
config: Arc<Mutex<ScsiConfig>>,
|
||||
}
|
||||
|
||||
impl ScsiAura {
|
||||
pub fn new(device: Arc<Mutex<Device>>, config: Arc<Mutex<ScsiConfig>>) -> Self {
|
||||
Self { device, config }
|
||||
}
|
||||
|
||||
pub async fn lock_config(&self) -> MutexGuard<ScsiConfig> {
|
||||
self.config.lock().await
|
||||
}
|
||||
|
||||
pub async fn write_effect(&self, effect: &AuraEffect) -> Result<(), RogError> {
|
||||
let tasks: Vec<Task> = effect.into();
|
||||
for task in &tasks {
|
||||
self.device.lock().await.perform(task).ok();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialise the device if required. Locks the internal config so be wary
|
||||
/// of deadlocks.
|
||||
pub async fn do_initialization(&self) -> Result<(), RogError> {
|
||||
let config = self.config.lock().await;
|
||||
let mode = config.current_mode;
|
||||
if let Some(effect) = config.modes.get(&mode) {
|
||||
self.write_effect(effect).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
116
asusd/src/aura_scsi/trait_impls.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use log::error;
|
||||
use rog_aura::AuraDeviceType;
|
||||
use rog_scsi::{AuraEffect, AuraMode};
|
||||
use zbus::fdo::Error as ZbErr;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use super::ScsiAura;
|
||||
use crate::error::RogError;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ScsiZbus(ScsiAura);
|
||||
|
||||
impl ScsiZbus {
|
||||
pub fn new(scsi: ScsiAura) -> Self {
|
||||
Self(scsi)
|
||||
}
|
||||
|
||||
pub async fn start_tasks(
|
||||
self,
|
||||
connection: &Connection,
|
||||
path: OwnedObjectPath,
|
||||
) -> Result<(), RogError> {
|
||||
connection
|
||||
.object_server()
|
||||
.at(path.clone(), self)
|
||||
.await
|
||||
.map_err(|e| error!("Couldn't add server at path: {path}, {e:?}"))
|
||||
.ok();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[interface(name = "xyz.ljones.ScsiAura")]
|
||||
impl ScsiZbus {
|
||||
/// Return the device type for this Aura keyboard
|
||||
#[zbus(property)]
|
||||
async fn device_type(&self) -> AuraDeviceType {
|
||||
self.0.config.lock().await.dev_type
|
||||
}
|
||||
|
||||
/// Get enabled or not
|
||||
#[zbus(property)]
|
||||
async fn enabled(&self) -> bool {
|
||||
let lock = self.0.lock_config().await;
|
||||
lock.enabled
|
||||
}
|
||||
|
||||
/// Set enabled true or false
|
||||
#[zbus(property)]
|
||||
async fn set_enabled(&self, enabled: bool) {
|
||||
let mut config = self.0.lock_config().await;
|
||||
config.enabled = enabled;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn led_mode(&self) -> u8 {
|
||||
let config = self.0.lock_config().await;
|
||||
config.current_mode as u8
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_led_mode(&self, mode: AuraMode) -> Result<(), zbus::Error> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
if let Some(effect) = config.get_effect(mode) {
|
||||
self.0
|
||||
.write_effect(effect)
|
||||
.await
|
||||
.map_err(|e| zbus::Error::Failure(format!("{e:?}")))?;
|
||||
} else {
|
||||
return Err(zbus::Error::Failure("Mode data does not exist".to_string()));
|
||||
}
|
||||
config.current_mode = mode;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The current mode data
|
||||
#[zbus(property)]
|
||||
async fn led_mode_data(&self) -> Result<AuraEffect, ZbErr> {
|
||||
// entirely possible to deadlock here, so use try instead of lock()
|
||||
if let Some(config) = self.0.config.try_lock() {
|
||||
let mode = config.current_mode;
|
||||
match config.modes.get(&mode) {
|
||||
Some(effect) => Ok(effect.clone()),
|
||||
None => Err(ZbErr::Failed("Could not get the current effect".into())),
|
||||
}
|
||||
} else {
|
||||
Err(ZbErr::Failed("Aura control couldn't lock self".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an Aura effect if the effect mode or zone is supported.
|
||||
///
|
||||
/// On success the aura config file is read to refresh cached values, then
|
||||
/// the effect is stored and config written to disk.
|
||||
#[zbus(property)]
|
||||
async fn set_led_mode_data(&mut self, effect: AuraEffect) -> Result<(), ZbErr> {
|
||||
self.0.write_effect(&effect).await?;
|
||||
|
||||
let mut config = self.0.config.lock().await;
|
||||
config.save_effect(effect);
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the data set for every mode available
|
||||
async fn all_mode_data(&self) -> BTreeMap<AuraMode, AuraEffect> {
|
||||
let config = self.0.config.lock().await;
|
||||
config.modes.clone()
|
||||
}
|
||||
}
|
||||
66
asusd/src/aura_slash/config.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_slash::{DeviceState, SlashMode, SlashType};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "slash.ron";
|
||||
|
||||
/// Config for base system actions for the anime display
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct SlashConfig {
|
||||
#[serde(skip)]
|
||||
pub slash_type: SlashType,
|
||||
pub enabled: bool,
|
||||
pub brightness: u8,
|
||||
pub display_interval: u8,
|
||||
pub display_mode: SlashMode,
|
||||
pub show_on_boot: bool,
|
||||
pub show_on_shutdown: bool,
|
||||
pub show_on_sleep: bool,
|
||||
pub show_on_battery: bool,
|
||||
pub show_battery_warning: bool,
|
||||
pub show_on_lid_closed: bool,
|
||||
}
|
||||
|
||||
impl Default for SlashConfig {
|
||||
fn default() -> Self {
|
||||
SlashConfig {
|
||||
enabled: true,
|
||||
brightness: 255,
|
||||
display_interval: 0,
|
||||
display_mode: SlashMode::Bounce,
|
||||
slash_type: SlashType::Unsupported,
|
||||
show_on_boot: true,
|
||||
show_on_shutdown: true,
|
||||
show_on_sleep: true,
|
||||
show_on_battery: true,
|
||||
show_battery_warning: true,
|
||||
show_on_lid_closed: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl StdConfig for SlashConfig {
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for SlashConfig {}
|
||||
|
||||
impl From<&SlashConfig> for DeviceState {
|
||||
fn from(config: &SlashConfig) -> Self {
|
||||
DeviceState {
|
||||
slash_enabled: config.enabled,
|
||||
slash_brightness: config.brightness,
|
||||
slash_interval: config.display_interval,
|
||||
slash_mode: config.display_mode,
|
||||
}
|
||||
}
|
||||
}
|
||||
69
asusd/src/aura_slash/mod.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config::SlashConfig;
|
||||
use futures_util::lock::{Mutex, MutexGuard};
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::usb_raw::USBRaw;
|
||||
use rog_slash::usb::{slash_pkt_enable, slash_pkt_init, slash_pkt_options, slash_pkt_set_mode};
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
pub mod config;
|
||||
pub mod trait_impls;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Slash {
|
||||
hid: Option<Arc<Mutex<HidRaw>>>,
|
||||
usb: Option<Arc<Mutex<USBRaw>>>,
|
||||
config: Arc<Mutex<SlashConfig>>,
|
||||
}
|
||||
|
||||
impl Slash {
|
||||
pub fn new(
|
||||
hid: Option<Arc<Mutex<HidRaw>>>,
|
||||
usb: Option<Arc<Mutex<USBRaw>>>,
|
||||
config: Arc<Mutex<SlashConfig>>,
|
||||
) -> Self {
|
||||
Self { hid, usb, config }
|
||||
}
|
||||
|
||||
pub async fn lock_config(&self) -> MutexGuard<SlashConfig> {
|
||||
self.config.lock().await
|
||||
}
|
||||
|
||||
pub async fn write_bytes(&self, message: &[u8]) -> Result<(), RogError> {
|
||||
if let Some(hid) = &self.hid {
|
||||
hid.lock().await.write_bytes(message)?;
|
||||
} else if let Some(usb) = &self.usb {
|
||||
usb.lock().await.write_bytes(message)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialise the device if required. Locks the internal config so be wary
|
||||
/// of deadlocks.
|
||||
pub async fn do_initialization(&self) -> Result<(), RogError> {
|
||||
// Don't try to initialise these models as the asus drivers already did
|
||||
let config = self.config.lock().await;
|
||||
for pkt in &slash_pkt_init(config.slash_type) {
|
||||
self.write_bytes(pkt).await?;
|
||||
}
|
||||
self.write_bytes(&slash_pkt_enable(config.slash_type, config.enabled))
|
||||
.await?;
|
||||
|
||||
// Apply config upon initialization
|
||||
let option_packets = slash_pkt_options(
|
||||
config.slash_type,
|
||||
config.enabled,
|
||||
config.brightness,
|
||||
config.display_interval,
|
||||
);
|
||||
self.write_bytes(&option_packets).await?;
|
||||
|
||||
let mode_packets = slash_pkt_set_mode(config.slash_type, config.display_mode);
|
||||
// self.node.write_bytes(&mode_packets[0])?;
|
||||
self.write_bytes(&mode_packets[1]).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
317
asusd/src/aura_slash/trait_impls.rs
Normal file
@@ -0,0 +1,317 @@
|
||||
use config_traits::StdConfig;
|
||||
use log::{debug, error, warn};
|
||||
use rog_slash::usb::{
|
||||
slash_pkt_battery_saver, slash_pkt_boot, slash_pkt_enable, slash_pkt_lid_closed,
|
||||
slash_pkt_low_battery, slash_pkt_options, slash_pkt_save, slash_pkt_set_mode,
|
||||
slash_pkt_shutdown, slash_pkt_sleep,
|
||||
};
|
||||
use rog_slash::{DeviceState, SlashMode};
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use super::Slash;
|
||||
use crate::error::RogError;
|
||||
use crate::Reloadable;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SlashZbus(Slash);
|
||||
|
||||
impl SlashZbus {
|
||||
pub fn new(slash: Slash) -> Self {
|
||||
Self(slash)
|
||||
}
|
||||
|
||||
pub async fn start_tasks(
|
||||
mut self,
|
||||
connection: &Connection,
|
||||
path: OwnedObjectPath,
|
||||
) -> Result<(), RogError> {
|
||||
// let task = zbus.clone();
|
||||
self.reload()
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Controller error: {}", err));
|
||||
connection
|
||||
.object_server()
|
||||
.at(path.clone(), self)
|
||||
.await
|
||||
.map_err(|e| error!("Couldn't add server at path: {path}, {e:?}"))
|
||||
.ok();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[interface(name = "xyz.ljones.Slash")]
|
||||
impl SlashZbus {
|
||||
/// Get enabled or not
|
||||
#[zbus(property)]
|
||||
async fn enabled(&self) -> bool {
|
||||
let lock = self.0.lock_config().await;
|
||||
lock.enabled
|
||||
}
|
||||
|
||||
/// Set enabled true or false
|
||||
#[zbus(property)]
|
||||
async fn set_enabled(&self, enabled: bool) {
|
||||
let mut config = self.0.lock_config().await;
|
||||
let brightness = if enabled && config.brightness == 0 {
|
||||
0x88
|
||||
} else {
|
||||
config.brightness
|
||||
};
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_enable(config.slash_type, enabled))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_slash::enable {}", err);
|
||||
})
|
||||
.ok();
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_options(
|
||||
config.slash_type,
|
||||
enabled,
|
||||
brightness,
|
||||
config.display_interval,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_slash::set_options {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
config.enabled = enabled;
|
||||
config.brightness = brightness;
|
||||
config.write();
|
||||
}
|
||||
|
||||
/// Get brightness level
|
||||
#[zbus(property)]
|
||||
async fn brightness(&self) -> u8 {
|
||||
let config = self.0.lock_config().await;
|
||||
config.brightness
|
||||
}
|
||||
|
||||
/// Set brightness level
|
||||
#[zbus(property)]
|
||||
async fn set_brightness(&self, brightness: u8) {
|
||||
let mut config = self.0.lock_config().await;
|
||||
let enabled = brightness > 0;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_options(
|
||||
config.slash_type,
|
||||
enabled,
|
||||
brightness,
|
||||
config.display_interval,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_slash::set_options {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
config.enabled = enabled;
|
||||
config.brightness = brightness;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn interval(&self) -> u8 {
|
||||
let config = self.0.lock_config().await;
|
||||
config.display_interval
|
||||
}
|
||||
|
||||
/// Set interval between slash animations (0-255)
|
||||
#[zbus(property)]
|
||||
async fn set_interval(&self, interval: u8) {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_options(
|
||||
config.slash_type, config.enabled, config.brightness, interval,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("ctrl_slash::set_options {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
config.display_interval = interval;
|
||||
config.write();
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn mode(&self) -> zbus::fdo::Result<u8> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.display_interval)
|
||||
}
|
||||
|
||||
/// Set interval between slash animations (0-255)
|
||||
#[zbus(property)]
|
||||
async fn set_mode(&self, mode: SlashMode) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
|
||||
let command_packets = slash_pkt_set_mode(config.slash_type, mode);
|
||||
// self.node.write_bytes(&command_packets[0])?;
|
||||
self.0.write_bytes(&command_packets[1]).await?;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_save(config.slash_type))
|
||||
.await?;
|
||||
|
||||
config.display_mode = mode;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the device state as stored by asusd
|
||||
// #[zbus(property)]
|
||||
async fn device_state(&self) -> DeviceState {
|
||||
let config = self.0.lock_config().await;
|
||||
DeviceState::from(&*config)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_on_boot(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_on_boot)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_on_boot(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_boot(config.slash_type, enable))
|
||||
.await?;
|
||||
config.show_on_boot = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_on_sleep(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_on_sleep)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_on_sleep(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_sleep(config.slash_type, enable))
|
||||
.await?;
|
||||
config.show_on_sleep = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_on_shutdown(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_on_shutdown)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_on_shutdown(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_shutdown(config.slash_type, enable))
|
||||
.await?;
|
||||
config.show_on_shutdown = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_on_battery(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_on_battery)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_on_battery(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_battery_saver(config.slash_type, enable))
|
||||
.await?;
|
||||
config.show_on_battery = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_battery_warning(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_battery_warning)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_battery_warning(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_low_battery(config.slash_type, enable))
|
||||
.await?;
|
||||
config.show_battery_warning = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn show_on_lid_closed(&self) -> zbus::fdo::Result<bool> {
|
||||
let config = self.0.lock_config().await;
|
||||
Ok(config.show_on_lid_closed)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_show_on_lid_closed(&self, enable: bool) -> zbus::Result<()> {
|
||||
let mut config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_lid_closed(config.slash_type, enable))
|
||||
.await?;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_save(config.slash_type))
|
||||
.await?;
|
||||
config.show_on_lid_closed = enable;
|
||||
config.write();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Reloadable for SlashZbus {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
debug!("reloading slash settings");
|
||||
let config = self.0.lock_config().await;
|
||||
self.0
|
||||
.write_bytes(&slash_pkt_options(
|
||||
config.slash_type,
|
||||
config.enabled,
|
||||
config.brightness,
|
||||
config.display_interval,
|
||||
))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("set_options {}", err);
|
||||
})
|
||||
.ok();
|
||||
|
||||
macro_rules! write_bytes_with_warning {
|
||||
($packet_fn:expr, $cfg:ident, $warn_msg:expr) => {
|
||||
self.0
|
||||
.write_bytes(&$packet_fn(config.slash_type, config.$cfg))
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("{} {}", $warn_msg, err);
|
||||
})
|
||||
.ok();
|
||||
};
|
||||
}
|
||||
|
||||
write_bytes_with_warning!(slash_pkt_boot, show_on_boot, "show_on_boot");
|
||||
write_bytes_with_warning!(slash_pkt_sleep, show_on_sleep, "show_on_sleep");
|
||||
write_bytes_with_warning!(slash_pkt_shutdown, show_on_shutdown, "show_on_shutdown");
|
||||
write_bytes_with_warning!(slash_pkt_battery_saver, show_on_battery, "show_on_battery");
|
||||
write_bytes_with_warning!(
|
||||
slash_pkt_low_battery,
|
||||
show_battery_warning,
|
||||
"show_battery_warning"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
209
asusd/src/aura_types.rs
Normal file
@@ -0,0 +1,209 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info};
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_anime::usb::get_anime_type;
|
||||
use rog_anime::AnimeType;
|
||||
use rog_aura::AuraDeviceType;
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::keyboard_led::KeyboardBacklight;
|
||||
use rog_platform::usb_raw::USBRaw;
|
||||
use rog_scsi::{open_device, ScsiType};
|
||||
use rog_slash::error::SlashError;
|
||||
use rog_slash::SlashType;
|
||||
|
||||
use crate::aura_anime::config::AniMeConfig;
|
||||
use crate::aura_anime::AniMe;
|
||||
use crate::aura_laptop::config::AuraConfig;
|
||||
use crate::aura_laptop::Aura;
|
||||
use crate::aura_scsi::config::ScsiConfig;
|
||||
use crate::aura_scsi::ScsiAura;
|
||||
use crate::aura_slash::config::SlashConfig;
|
||||
use crate::aura_slash::Slash;
|
||||
use crate::error::RogError;
|
||||
|
||||
pub enum _DeviceHandle {
|
||||
/// The AniMe devices require USBRaw as they are not HID devices
|
||||
Usb(USBRaw),
|
||||
HidRaw(HidRaw),
|
||||
LedClass(KeyboardBacklight),
|
||||
/// TODO
|
||||
MulticolourLed,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum DeviceHandle {
|
||||
Aura(Aura),
|
||||
Slash(Slash),
|
||||
/// The AniMe devices require USBRaw as they are not HID devices
|
||||
AniMe(AniMe),
|
||||
Scsi(ScsiAura),
|
||||
Ally(Arc<Mutex<HidRaw>>),
|
||||
OldAura(Arc<Mutex<HidRaw>>),
|
||||
/// TUF laptops have an aditional set of attributes added to the LED /sysfs/
|
||||
TufLedClass(Arc<Mutex<HidRaw>>),
|
||||
/// TODO
|
||||
MulticolourLed,
|
||||
None,
|
||||
}
|
||||
|
||||
impl DeviceHandle {
|
||||
/// Try Slash HID. If one exists it is initialsed and returned.
|
||||
pub async fn new_slash_hid(
|
||||
device: Arc<Mutex<HidRaw>>,
|
||||
prod_id: &str,
|
||||
) -> Result<Self, RogError> {
|
||||
debug!("Testing for HIDRAW Slash");
|
||||
let slash_type = SlashType::from_dmi();
|
||||
if matches!(slash_type, SlashType::Unsupported)
|
||||
|| slash_type
|
||||
.prod_id_str()
|
||||
.to_lowercase()
|
||||
.trim_start_matches("0x")
|
||||
!= prod_id
|
||||
{
|
||||
log::info!("Unknown or invalid slash: {prod_id:?}, skipping");
|
||||
return Err(RogError::NotFound("No slash device".to_string()));
|
||||
}
|
||||
info!("Found slash type {slash_type:?}: {prod_id}");
|
||||
|
||||
let mut config = SlashConfig::new().load();
|
||||
config.slash_type = slash_type;
|
||||
let slash = Slash::new(Some(device), None, Arc::new(Mutex::new(config)));
|
||||
slash.do_initialization().await?;
|
||||
Ok(Self::Slash(slash))
|
||||
}
|
||||
|
||||
/// Try Slash USB. If one exists it is initialsed and returned.
|
||||
pub async fn new_slash_usb() -> Result<Self, RogError> {
|
||||
debug!("Testing for USB Slash");
|
||||
let slash_type = SlashType::from_dmi();
|
||||
if matches!(slash_type, SlashType::Unsupported) {
|
||||
return Err(RogError::Slash(SlashError::NoDevice));
|
||||
}
|
||||
|
||||
if let Ok(usb) = USBRaw::new(slash_type.prod_id()) {
|
||||
info!("Found Slash USB {slash_type:?}");
|
||||
|
||||
let mut config = SlashConfig::new().load();
|
||||
config.slash_type = slash_type;
|
||||
let slash = Slash::new(
|
||||
None,
|
||||
Some(Arc::new(Mutex::new(usb))),
|
||||
Arc::new(Mutex::new(config)),
|
||||
);
|
||||
slash.do_initialization().await?;
|
||||
Ok(Self::Slash(slash))
|
||||
} else {
|
||||
Err(RogError::NotFound("No slash device found".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Try AniMe Matrix HID. If one exists it is initialsed and returned.
|
||||
pub async fn maybe_anime_hid(
|
||||
_device: Arc<Mutex<HidRaw>>,
|
||||
_prod_id: &str,
|
||||
) -> Result<Self, RogError> {
|
||||
// TODO: can't use HIDRAW for anime at the moment
|
||||
Err(RogError::NotFound(
|
||||
"Can't use anime over hidraw yet. Skip.".to_string(),
|
||||
))
|
||||
|
||||
// debug!("Testing for HIDRAW AniMe");
|
||||
// let anime_type = AnimeType::from_dmi();
|
||||
// dbg!(prod_id);
|
||||
// if matches!(anime_type, AnimeType::Unsupported) || prod_id != "193b"
|
||||
// { log::info!("Unknown or invalid AniMe: {prod_id:?},
|
||||
// skipping"); return Err(RogError::NotFound("No
|
||||
// anime-matrix device".to_string())); }
|
||||
// info!("Found AniMe Matrix HIDRAW {anime_type:?}: {prod_id}");
|
||||
|
||||
// let mut config = AniMeConfig::new().load();
|
||||
// config.anime_type = anime_type;
|
||||
// let mut anime = AniMe::new(Some(device), None,
|
||||
// Arc::new(Mutex::new(config))); anime.do_initialization().
|
||||
// await?; Ok(Self::AniMe(anime))
|
||||
}
|
||||
|
||||
pub async fn maybe_anime_usb() -> Result<Self, RogError> {
|
||||
debug!("Testing for USB AniMe");
|
||||
let anime_type = get_anime_type();
|
||||
if matches!(anime_type, AnimeType::Unsupported) {
|
||||
info!("No Anime Matrix capable laptop found");
|
||||
return Err(RogError::Anime(AnimeError::NoDevice));
|
||||
}
|
||||
|
||||
if let Ok(usb) = USBRaw::new(0x193b) {
|
||||
info!("Found AniMe Matrix USB {anime_type:?}");
|
||||
|
||||
let mut config = AniMeConfig::new().load();
|
||||
config.anime_type = anime_type;
|
||||
let mut anime = AniMe::new(
|
||||
None,
|
||||
Some(Arc::new(Mutex::new(usb))),
|
||||
Arc::new(Mutex::new(config)),
|
||||
);
|
||||
anime.do_initialization().await?;
|
||||
Ok(Self::AniMe(anime))
|
||||
} else {
|
||||
Err(RogError::NotFound(
|
||||
"No AnimeMatrix device found".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn maybe_scsi(dev_node: &str, prod_id: &str) -> Result<Self, RogError> {
|
||||
debug!("Testing for SCSI");
|
||||
let prod_id = ScsiType::from(prod_id);
|
||||
if prod_id == ScsiType::Unsupported {
|
||||
log::info!("Unknown or invalid SCSI: {prod_id:?}, skipping");
|
||||
return Err(RogError::NotFound("No SCSI device".to_string()));
|
||||
}
|
||||
info!("Found SCSI device {prod_id:?} on {dev_node}");
|
||||
|
||||
let mut config = ScsiConfig::new().load();
|
||||
config.dev_type = AuraDeviceType::ScsiExtDisk;
|
||||
let dev = Arc::new(Mutex::new(open_device(dev_node)?));
|
||||
let scsi = ScsiAura::new(dev, Arc::new(Mutex::new(config)));
|
||||
scsi.do_initialization().await?;
|
||||
Ok(Self::Scsi(scsi))
|
||||
}
|
||||
|
||||
pub async fn maybe_laptop_aura(
|
||||
device: Option<Arc<Mutex<HidRaw>>>,
|
||||
prod_id: &str,
|
||||
) -> Result<Self, RogError> {
|
||||
debug!("Testing for laptop aura");
|
||||
let aura_type = AuraDeviceType::from(prod_id);
|
||||
if !matches!(
|
||||
aura_type,
|
||||
AuraDeviceType::LaptopKeyboard2021
|
||||
| AuraDeviceType::LaptopKeyboardPre2021
|
||||
| AuraDeviceType::LaptopKeyboardTuf
|
||||
) {
|
||||
log::info!("Unknown or invalid laptop aura: {prod_id:?}, skipping");
|
||||
return Err(RogError::NotFound("No laptop aura device".to_string()));
|
||||
}
|
||||
info!("Found laptop aura type {prod_id:?}");
|
||||
|
||||
let backlight = KeyboardBacklight::new()
|
||||
.map_err(|e| error!("Keyboard backlight error: {e:?}"))
|
||||
.map_or(None, |k| {
|
||||
info!("Found sysfs backlight control");
|
||||
Some(Arc::new(Mutex::new(k)))
|
||||
});
|
||||
|
||||
let mut config = AuraConfig::load_and_update_config(prod_id);
|
||||
config.led_type = aura_type;
|
||||
let aura = Aura {
|
||||
hid: device,
|
||||
backlight,
|
||||
config: Arc::new(Mutex::new(config)),
|
||||
};
|
||||
aura.do_initialization().await?;
|
||||
Ok(Self::Aura(aura))
|
||||
}
|
||||
}
|
||||
240
asusd/src/config.rs
Normal file
@@ -0,0 +1,240 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad2};
|
||||
use rog_platform::asus_armoury::FirmwareAttribute;
|
||||
use rog_platform::cpu::CPUEPP;
|
||||
use rog_platform::platform::PlatformProfile;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "asusd.ron";
|
||||
|
||||
#[derive(Default, Clone, Deserialize, Serialize, PartialEq)]
|
||||
pub struct Tuning {
|
||||
pub enabled: bool,
|
||||
pub group: HashMap<FirmwareAttribute, i32>,
|
||||
}
|
||||
type Tunings = HashMap<PlatformProfile, Tuning>;
|
||||
|
||||
#[derive(Deserialize, Serialize, PartialEq)]
|
||||
pub struct Config {
|
||||
// The current charge limit applied
|
||||
pub charge_control_end_threshold: u8,
|
||||
/// Save charge limit for restoring
|
||||
#[serde(skip)]
|
||||
pub base_charge_control_end_threshold: u8,
|
||||
pub disable_nvidia_powerd_on_battery: bool,
|
||||
/// An optional command/script to run when power is changed to AC
|
||||
pub ac_command: String,
|
||||
/// An optional command/script to run when power is changed to battery
|
||||
pub bat_command: String,
|
||||
/// Set true if energy_performance_preference should be set if the
|
||||
/// platform profile is changed
|
||||
pub platform_profile_linked_epp: bool,
|
||||
/// Which platform profile to use on battery power
|
||||
pub platform_profile_on_battery: PlatformProfile,
|
||||
/// Should the throttle policy be set on bat/ac change?
|
||||
pub change_platform_profile_on_battery: bool,
|
||||
/// Which platform profile to use on AC power
|
||||
pub platform_profile_on_ac: PlatformProfile,
|
||||
/// Should the platform profile be set on bat/ac change?
|
||||
pub change_platform_profile_on_ac: bool,
|
||||
/// The energy_performance_preference for this platform profile
|
||||
pub profile_quiet_epp: CPUEPP,
|
||||
/// The energy_performance_preference for this platform profile
|
||||
pub profile_balanced_epp: CPUEPP,
|
||||
/// The energy_performance_preference for this platform profile
|
||||
pub profile_custom_epp: CPUEPP,
|
||||
/// The energy_performance_preference for this platform profile
|
||||
pub profile_performance_epp: CPUEPP,
|
||||
pub ac_profile_tunings: Tunings,
|
||||
pub dc_profile_tunings: Tunings,
|
||||
pub armoury_settings: HashMap<FirmwareAttribute, i32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub screenpad_gamma: Option<f32>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub screenpad_sync_primary: Option<bool>,
|
||||
/// Temporary state for AC/Batt
|
||||
#[serde(skip)]
|
||||
pub last_power_plugged: u8,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn select_tunings(&mut self, power_plugged: bool, profile: PlatformProfile) -> &mut Tuning {
|
||||
let config = if power_plugged {
|
||||
&mut self.ac_profile_tunings
|
||||
} else {
|
||||
&mut self.dc_profile_tunings
|
||||
};
|
||||
config.entry(profile).or_insert_with(Tuning::default)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
charge_control_end_threshold: 100,
|
||||
base_charge_control_end_threshold: 100,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: Default::default(),
|
||||
bat_command: Default::default(),
|
||||
platform_profile_linked_epp: true,
|
||||
platform_profile_on_battery: PlatformProfile::Quiet,
|
||||
change_platform_profile_on_battery: true,
|
||||
platform_profile_on_ac: PlatformProfile::Performance,
|
||||
change_platform_profile_on_ac: true,
|
||||
profile_quiet_epp: CPUEPP::Power,
|
||||
profile_balanced_epp: CPUEPP::BalancePower,
|
||||
profile_performance_epp: CPUEPP::Performance,
|
||||
profile_custom_epp: CPUEPP::Performance,
|
||||
ac_profile_tunings: HashMap::default(),
|
||||
dc_profile_tunings: HashMap::default(),
|
||||
armoury_settings: HashMap::default(),
|
||||
last_power_plugged: Default::default(),
|
||||
screenpad_gamma: Default::default(),
|
||||
screenpad_sync_primary: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfig for Config {
|
||||
fn new() -> Self {
|
||||
Config {
|
||||
charge_control_end_threshold: 100,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
platform_profile_on_battery: PlatformProfile::Quiet,
|
||||
platform_profile_on_ac: PlatformProfile::Performance,
|
||||
ac_command: String::new(),
|
||||
bat_command: String::new(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad2<Config611, Config601> for Config {}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Config611 {
|
||||
pub charge_control_end_threshold: u8,
|
||||
#[serde(skip)]
|
||||
pub base_charge_control_end_threshold: u8,
|
||||
pub disable_nvidia_powerd_on_battery: bool,
|
||||
pub ac_command: String,
|
||||
pub bat_command: String,
|
||||
pub platform_profile_linked_epp: bool,
|
||||
pub platform_profile_on_battery: PlatformProfile,
|
||||
pub change_platform_profile_on_battery: bool,
|
||||
pub platform_profile_on_ac: PlatformProfile,
|
||||
pub change_platform_profile_on_ac: bool,
|
||||
pub profile_quiet_epp: CPUEPP,
|
||||
pub profile_balanced_epp: CPUEPP,
|
||||
pub profile_custom_epp: CPUEPP,
|
||||
pub profile_performance_epp: CPUEPP,
|
||||
pub ac_profile_tunings: Tunings,
|
||||
pub dc_profile_tunings: Tunings,
|
||||
pub armoury_settings: HashMap<FirmwareAttribute, i32>,
|
||||
#[serde(skip)]
|
||||
pub last_power_plugged: u8,
|
||||
}
|
||||
|
||||
impl From<Config611> for Config {
|
||||
fn from(c: Config611) -> Self {
|
||||
Self {
|
||||
// Restore the base charge limit
|
||||
charge_control_end_threshold: c.charge_control_end_threshold,
|
||||
base_charge_control_end_threshold: c.charge_control_end_threshold,
|
||||
disable_nvidia_powerd_on_battery: c.disable_nvidia_powerd_on_battery,
|
||||
ac_command: c.ac_command,
|
||||
bat_command: c.bat_command,
|
||||
platform_profile_linked_epp: c.platform_profile_linked_epp,
|
||||
platform_profile_on_battery: c.platform_profile_on_battery,
|
||||
change_platform_profile_on_battery: c.change_platform_profile_on_battery,
|
||||
platform_profile_on_ac: c.platform_profile_on_ac,
|
||||
change_platform_profile_on_ac: c.change_platform_profile_on_ac,
|
||||
profile_quiet_epp: c.profile_quiet_epp,
|
||||
profile_balanced_epp: c.profile_balanced_epp,
|
||||
profile_performance_epp: c.profile_performance_epp,
|
||||
profile_custom_epp: c.profile_performance_epp,
|
||||
last_power_plugged: c.last_power_plugged,
|
||||
ac_profile_tunings: HashMap::default(),
|
||||
dc_profile_tunings: HashMap::default(),
|
||||
armoury_settings: HashMap::default(),
|
||||
screenpad_gamma: None,
|
||||
screenpad_sync_primary: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct Config601 {
|
||||
pub charge_control_end_threshold: u8,
|
||||
#[serde(skip)]
|
||||
pub base_charge_control_end_threshold: u8,
|
||||
pub panel_od: bool,
|
||||
pub boot_sound: bool,
|
||||
pub mini_led_mode: bool,
|
||||
pub disable_nvidia_powerd_on_battery: bool,
|
||||
pub ac_command: String,
|
||||
pub bat_command: String,
|
||||
pub platform_profile_linked_epp: bool,
|
||||
pub platform_profile_on_battery: PlatformProfile,
|
||||
pub change_platform_profile_on_battery: bool,
|
||||
pub platform_profile_on_ac: PlatformProfile,
|
||||
pub change_platform_profile_on_ac: bool,
|
||||
pub profile_quiet_epp: CPUEPP,
|
||||
pub profile_balanced_epp: CPUEPP,
|
||||
pub profile_performance_epp: CPUEPP,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_pl1_spl: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_pl2_sppt: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_pl3_fppt: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_fppt: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_apu_sppt: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub ppt_platform_sppt: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub nv_dynamic_boost: Option<u8>,
|
||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||
pub nv_temp_target: Option<u8>,
|
||||
#[serde(skip)]
|
||||
pub last_power_plugged: u8,
|
||||
}
|
||||
|
||||
impl From<Config601> for Config {
|
||||
fn from(c: Config601) -> Self {
|
||||
Self {
|
||||
// Restore the base charge limit
|
||||
charge_control_end_threshold: c.charge_control_end_threshold,
|
||||
base_charge_control_end_threshold: c.charge_control_end_threshold,
|
||||
disable_nvidia_powerd_on_battery: c.disable_nvidia_powerd_on_battery,
|
||||
ac_command: c.ac_command,
|
||||
bat_command: c.bat_command,
|
||||
platform_profile_linked_epp: c.platform_profile_linked_epp,
|
||||
platform_profile_on_battery: c.platform_profile_on_battery,
|
||||
change_platform_profile_on_battery: c.change_platform_profile_on_battery,
|
||||
platform_profile_on_ac: c.platform_profile_on_ac,
|
||||
change_platform_profile_on_ac: c.change_platform_profile_on_ac,
|
||||
profile_quiet_epp: c.profile_quiet_epp,
|
||||
profile_balanced_epp: c.profile_balanced_epp,
|
||||
profile_performance_epp: c.profile_performance_epp,
|
||||
profile_custom_epp: c.profile_performance_epp,
|
||||
last_power_plugged: c.last_power_plugged,
|
||||
ac_profile_tunings: HashMap::default(),
|
||||
dc_profile_tunings: HashMap::default(),
|
||||
armoury_settings: HashMap::default(),
|
||||
screenpad_gamma: None,
|
||||
screenpad_sync_primary: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
348
asusd/src/ctrl_backlight.rs
Normal file
@@ -0,0 +1,348 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{info, warn};
|
||||
use rog_platform::backlight::{Backlight, BacklightType};
|
||||
use zbus::fdo::Error as FdoErr;
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::RogError;
|
||||
use crate::ASUS_ZBUS_PATH;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CtrlBacklight {
|
||||
backlights: Vec<Backlight>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
impl CtrlBacklight {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
let mut backlights = Vec::new();
|
||||
|
||||
if let Ok(primary) = Backlight::new(BacklightType::Primary) {
|
||||
info!("Found primary display backlight");
|
||||
backlights.push(primary);
|
||||
}
|
||||
|
||||
if let Ok(screenpad) = Backlight::new(BacklightType::Screenpad) {
|
||||
info!("Found screenpad backlight");
|
||||
backlights.push(screenpad);
|
||||
}
|
||||
|
||||
if backlights.is_empty() {
|
||||
return Err(RogError::MissingFunction("No backlights found".into()));
|
||||
}
|
||||
|
||||
Ok(Self { backlights, config })
|
||||
}
|
||||
|
||||
fn get_backlight(&self, device_type: &BacklightType) -> Option<&Backlight> {
|
||||
self.backlights
|
||||
.iter()
|
||||
.find(|b| b.device_type() == device_type)
|
||||
}
|
||||
|
||||
async fn set_brightness_with_sync(
|
||||
&self,
|
||||
device_type: &BacklightType,
|
||||
level: i32,
|
||||
) -> Result<(), FdoErr> {
|
||||
let sync = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.screenpad_sync_primary
|
||||
.unwrap_or_default();
|
||||
|
||||
// If sync is enabled and we're setting screenpad brightness, set primary first
|
||||
if sync && *device_type == BacklightType::Screenpad {
|
||||
if let Some(primary) = self.get_backlight(&BacklightType::Primary) {
|
||||
if let Ok(primary_max) = primary.get_max_brightness() {
|
||||
let primary_scaled = level * primary_max / 100;
|
||||
let _ = primary.set_brightness(primary_scaled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(backlight) = self.get_backlight(device_type) {
|
||||
let max = backlight.get_max_brightness().map_err(|e| {
|
||||
warn!("Failed to get max brightness: {}", e);
|
||||
FdoErr::Failed(format!("Failed to get max brightness: {}", e))
|
||||
})?;
|
||||
|
||||
let gamma = self.config.lock().await.screenpad_gamma.unwrap_or(1.0);
|
||||
let scaled = if *device_type == BacklightType::Screenpad {
|
||||
// Apply non-linear scaling with the configurable gamma value only for Screenpad
|
||||
let normalized_level = level as f32 / 100.0;
|
||||
let gamma_corrected = normalized_level.powf(gamma);
|
||||
(gamma_corrected * max as f32) as i32
|
||||
} else {
|
||||
// Linear scaling for other devices
|
||||
level * max / 100
|
||||
};
|
||||
|
||||
backlight.set_brightness(scaled).map_err(|e| {
|
||||
warn!("Failed to set brightness: {}", e);
|
||||
FdoErr::Failed(format!("Failed to set brightness: {}", e))
|
||||
})?;
|
||||
|
||||
// If sync is enabled and we're setting primary brightness, set screenpad
|
||||
// afterward
|
||||
if sync && *device_type == BacklightType::Primary {
|
||||
for other in self
|
||||
.backlights
|
||||
.iter()
|
||||
.filter(|b| b.device_type() != device_type)
|
||||
{
|
||||
if let Ok(other_max) = other.get_max_brightness() {
|
||||
let other_scaled = if other.device_type() == &BacklightType::Screenpad {
|
||||
// Apply gamma only to Screenpad
|
||||
let normalized_level = level as f32 / 100.0;
|
||||
let gamma_corrected = normalized_level.powf(gamma);
|
||||
(gamma_corrected * other_max as f32) as i32
|
||||
} else {
|
||||
// Linear scaling for other devices
|
||||
level * other_max / 100
|
||||
};
|
||||
let _ = other.set_brightness(other_scaled);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(FdoErr::NotSupported(format!(
|
||||
"Backlight {:?} not found",
|
||||
device_type
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_brightness_percent(&self, device_type: &BacklightType) -> Result<i32, FdoErr> {
|
||||
if let Some(backlight) = self.get_backlight(device_type) {
|
||||
let brightness = backlight.get_brightness().map_err(|e| {
|
||||
warn!("Failed to get brightness: {}", e);
|
||||
FdoErr::Failed(format!("Failed to get brightness: {}", e))
|
||||
})?;
|
||||
|
||||
let max = backlight.get_max_brightness().map_err(|e| {
|
||||
warn!("Failed to get max brightness: {}", e);
|
||||
FdoErr::Failed(format!("Failed to get max brightness: {}", e))
|
||||
})?;
|
||||
|
||||
if *device_type == BacklightType::Screenpad {
|
||||
let gamma = self.config.lock().await.screenpad_gamma.unwrap_or(1.0);
|
||||
let normalized = brightness as f32 / max as f32;
|
||||
let corrected = normalized.powf(1.0 / gamma);
|
||||
Ok((corrected * 100.0).round() as i32)
|
||||
} else {
|
||||
Ok(brightness * 100 / max)
|
||||
}
|
||||
} else {
|
||||
Err(FdoErr::NotSupported(format!(
|
||||
"Backlight {:?} not found",
|
||||
device_type
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_watch_primary(&self) -> Result<(), RogError> {
|
||||
if self.get_backlight(&BacklightType::Screenpad).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if let Some(sync) = self.config.lock().await.screenpad_sync_primary {
|
||||
if !sync {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(backlight) = self.get_backlight(&BacklightType::Primary) {
|
||||
let watch = backlight.monitor_brightness()?;
|
||||
|
||||
let backlights = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut last_level = 0;
|
||||
let mut buffer = [0; 32];
|
||||
use futures_lite::StreamExt;
|
||||
if let Ok(mut stream) = watch.into_event_stream(&mut buffer) {
|
||||
loop {
|
||||
let _ = stream.next().await;
|
||||
|
||||
let sync = backlights.config.lock().await.screenpad_sync_primary;
|
||||
if let Some(sync) = sync {
|
||||
if !sync {
|
||||
continue;
|
||||
}
|
||||
} else if backlights
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.screenpad_sync_primary
|
||||
.is_none()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
let level = backlights
|
||||
.get_brightness_percent(&BacklightType::Primary)
|
||||
.await
|
||||
.unwrap_or(60);
|
||||
if last_level != level {
|
||||
last_level = level;
|
||||
backlights
|
||||
.set_brightness_with_sync(&BacklightType::Screenpad, level)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
// other processes cause "MODIFY" event and make this spin 100%, so sleep
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
}
|
||||
// watch
|
||||
// .into_event_stream(&mut buffer)
|
||||
// .unwrap()
|
||||
// .for_each(|_| async {})
|
||||
// .await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[interface(name = "xyz.ljones.Backlight")]
|
||||
impl CtrlBacklight {
|
||||
#[zbus(property)]
|
||||
async fn screenpad_sync_with_primary(&self) -> bool {
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.screenpad_sync_primary
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_screenpad_sync_with_primary(&self, sync: bool) -> Result<(), zbus::Error> {
|
||||
self.config.lock().await.screenpad_sync_primary = Some(sync);
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn screenpad_gamma(&self) -> String {
|
||||
(self.config.lock().await.screenpad_gamma.unwrap_or(1.0)).to_string()
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_screenpad_gamma(&self, value: &str) -> Result<(), zbus::Error> {
|
||||
let gamma: f32 = value
|
||||
.parse()
|
||||
.map_err(|_| FdoErr::Failed("Invalid gamma value, must be a valid number".into()))?;
|
||||
|
||||
if gamma < 0.1 {
|
||||
return Err(FdoErr::Failed("Gamma value must be greater than 0".into()).into());
|
||||
}
|
||||
if gamma > 2.0 {
|
||||
return Err(FdoErr::Failed("Gamma value must be 2.0 or less".into()).into());
|
||||
}
|
||||
self.config.lock().await.screenpad_gamma = Some(gamma);
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn primary_brightness(&self) -> Result<i32, FdoErr> {
|
||||
self.get_brightness_percent(&BacklightType::Primary).await
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_primary_brightness(
|
||||
&self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
level: i32,
|
||||
) -> Result<(), zbus::Error> {
|
||||
if level > 100 {
|
||||
return Err(FdoErr::Failed("Brightness level must be 0-100".into()).into());
|
||||
}
|
||||
|
||||
self.set_brightness_with_sync(&BacklightType::Primary, level)
|
||||
.await?;
|
||||
self.primary_brightness_changed(&ctxt).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn screenpad_brightness(&self) -> Result<i32, FdoErr> {
|
||||
self.get_brightness_percent(&BacklightType::Screenpad).await
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_screenpad_brightness(
|
||||
&self,
|
||||
// #[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
level: i32,
|
||||
) -> Result<(), zbus::Error> {
|
||||
if level > 100 {
|
||||
return Err(FdoErr::Failed("Brightness level must be 0-100".into()).into());
|
||||
}
|
||||
|
||||
self.set_brightness_with_sync(&BacklightType::Screenpad, level)
|
||||
.await?;
|
||||
// self.screenpad_brightness_changed(&ctxt).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn screenpad_power(&self) -> Result<bool, FdoErr> {
|
||||
if let Some(backlight) = self.get_backlight(&BacklightType::Screenpad) {
|
||||
let power = backlight.get_bl_power().map_err(|e| {
|
||||
warn!("Failed to get backlight power: {}", e);
|
||||
FdoErr::Failed(format!("Failed to get backlight power: {}", e))
|
||||
})?;
|
||||
Ok(power == 0)
|
||||
} else {
|
||||
Err(FdoErr::NotSupported("Screenpad backlight not found".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_screenpad_power(
|
||||
&self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
power: bool,
|
||||
) -> Result<(), zbus::Error> {
|
||||
if let Some(backlight) = self.get_backlight(&BacklightType::Screenpad) {
|
||||
backlight
|
||||
.set_bl_power(if power { 0 } else { 1 })
|
||||
.map_err(|e| {
|
||||
warn!("Failed to set backlight power: {}", e);
|
||||
FdoErr::Failed(format!("Failed to set backlight power: {}", e))
|
||||
})?;
|
||||
self.screenpad_power_changed(&ctxt).await?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(FdoErr::NotSupported("Screenpad backlight not found".into()).into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ZbusRun for CtrlBacklight {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, ASUS_ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlBacklight {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
info!("Reloading backlight settings");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
289
asusd/src/ctrl_fancurves.rs
Normal file
@@ -0,0 +1,289 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use futures_lite::StreamExt;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info, warn};
|
||||
use rog_platform::platform::{PlatformProfile, RogPlatform};
|
||||
use rog_profiles::error::ProfileError;
|
||||
use rog_profiles::fan_curve_set::CurveData;
|
||||
use rog_profiles::{find_fan_curve_node, FanCurvePU, FanCurveProfiles};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use crate::error::RogError;
|
||||
use crate::{CtrlTask, CONFIG_PATH_BASE};
|
||||
|
||||
pub const FAN_CURVE_ZBUS_NAME: &str = "FanCurves";
|
||||
pub const FAN_CURVE_ZBUS_PATH: &str = "/xyz/ljones";
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Default)]
|
||||
pub struct FanCurveConfig {
|
||||
pub profiles: FanCurveProfiles,
|
||||
#[serde(skip)]
|
||||
pub current: PlatformProfile,
|
||||
}
|
||||
|
||||
impl StdConfig for FanCurveConfig {
|
||||
/// Create a new config. The defaults are zeroed so the device must be read
|
||||
/// to get the actual device defaults.
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
"fan_curves.ron".to_owned()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
PathBuf::from(CONFIG_PATH_BASE)
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for FanCurveConfig {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CtrlFanCurveZbus {
|
||||
config: Arc<Mutex<FanCurveConfig>>,
|
||||
platform: RogPlatform,
|
||||
}
|
||||
|
||||
// Non-zbus-derive impl
|
||||
impl CtrlFanCurveZbus {
|
||||
pub fn new() -> Result<Self, RogError> {
|
||||
let platform = RogPlatform::new()?;
|
||||
if platform.has_platform_profile() {
|
||||
info!("Device has profile control available");
|
||||
find_fan_curve_node()?;
|
||||
info!("Device has fan curves available");
|
||||
let mut config = FanCurveConfig::new().load();
|
||||
let mut fan_curves = FanCurveProfiles::default();
|
||||
|
||||
// Only do defaults if the config doesn't already exist\
|
||||
if config.profiles.balanced.is_empty() || !config.file_path().exists() {
|
||||
info!("Fetching default fan curves");
|
||||
|
||||
let current = platform.get_platform_profile()?;
|
||||
let profiles = platform.get_platform_profile_choices()?;
|
||||
for this in profiles {
|
||||
// For each profile we need to switch to it before we
|
||||
// can read the existing values from hardware. The ACPI method used
|
||||
// for this is what limits us.
|
||||
platform.set_platform_profile(this.into())?;
|
||||
let mut dev = find_fan_curve_node()?;
|
||||
fan_curves.set_active_curve_to_defaults(this, &mut dev)?;
|
||||
|
||||
info!("{this:?}:");
|
||||
for curve in fan_curves.get_fan_curves_for(this) {
|
||||
info!("{}", String::from(curve));
|
||||
}
|
||||
}
|
||||
platform.set_platform_profile(current.as_str())?;
|
||||
config.profiles = fan_curves;
|
||||
config.write();
|
||||
} else {
|
||||
info!("Fan curves previously stored, loading...");
|
||||
config = config.load();
|
||||
}
|
||||
|
||||
return Ok(Self {
|
||||
config: Arc::new(Mutex::new(config)),
|
||||
platform,
|
||||
});
|
||||
}
|
||||
|
||||
Err(ProfileError::NotSupported.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[interface(name = "xyz.ljones.FanCurves")]
|
||||
impl CtrlFanCurveZbus {
|
||||
/// Set all fan curves for a profile to enabled status. Will also activate a
|
||||
/// fan curve if in the same profile mode
|
||||
async fn set_fan_curves_enabled(
|
||||
&mut self,
|
||||
profile: PlatformProfile,
|
||||
enabled: bool,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.set_profile_curves_enabled(profile, enabled);
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set a single fan curve for a profile to enabled status. Will also
|
||||
/// activate a fan curve if in the same profile mode
|
||||
async fn set_profile_fan_curve_enabled(
|
||||
&mut self,
|
||||
profile: PlatformProfile,
|
||||
fan: FanCurvePU,
|
||||
enabled: bool,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.set_profile_fan_curve_enabled(profile, fan, enabled);
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the fan-curve data for the currently active ThrottlePolicy
|
||||
async fn fan_curve_data(
|
||||
&mut self,
|
||||
profile: PlatformProfile,
|
||||
) -> zbus::fdo::Result<Vec<CurveData>> {
|
||||
let curve = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.get_fan_curves_for(profile)
|
||||
.to_vec();
|
||||
Ok(curve)
|
||||
}
|
||||
|
||||
/// Set the fan curve for the specified profile.
|
||||
/// Will also activate the fan curve if the user is in the same mode.
|
||||
async fn set_fan_curve(
|
||||
&mut self,
|
||||
profile: PlatformProfile,
|
||||
curve: CurveData,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.save_fan_curve(curve, profile)?;
|
||||
let active: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
if active == profile {
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.write_profile_curve_to_platform(profile, &mut find_fan_curve_node()?)?;
|
||||
}
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reset the stored (self) and device curves to the defaults of the
|
||||
/// platform.
|
||||
///
|
||||
/// Each platform_profile has a different default and the default can be
|
||||
/// read only for the currently active profile.
|
||||
async fn set_curves_to_defaults(&mut self, profile: PlatformProfile) -> zbus::fdo::Result<()> {
|
||||
let active = self.platform.get_platform_profile()?;
|
||||
self.platform.set_platform_profile(profile.into())?;
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.set_active_curve_to_defaults(profile, &mut find_fan_curve_node()?)?;
|
||||
self.platform.set_platform_profile(active.as_str())?;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reset the stored (self) and device curve to the defaults of the
|
||||
/// platform.
|
||||
///
|
||||
/// Each platform_profile has a different default and the defualt can be
|
||||
/// read only for the currently active profile.
|
||||
async fn reset_profile_curves(&self, profile: PlatformProfile) -> zbus::fdo::Result<()> {
|
||||
let active = self.platform.get_platform_profile()?;
|
||||
|
||||
self.platform.set_platform_profile(profile.into())?;
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.set_active_curve_to_defaults(active.as_str().into(), &mut find_fan_curve_node()?)?;
|
||||
self.platform.set_platform_profile(active.as_str())?;
|
||||
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ZbusRun for CtrlFanCurveZbus {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, FAN_CURVE_ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlTask for CtrlFanCurveZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
FAN_CURVE_ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, _signal_ctxt: SignalEmitter<'static>) -> Result<(), RogError> {
|
||||
let watch_platform_profile = self.platform.monitor_platform_profile()?;
|
||||
let platform = self.platform.clone();
|
||||
let config = self.config.clone();
|
||||
let fan_curves = self.config.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
if let Ok(mut stream) = watch_platform_profile.into_event_stream(&mut buffer) {
|
||||
while (stream.next().await).is_some() {
|
||||
debug!("watch_platform_profile changed");
|
||||
if let Ok(profile) =
|
||||
platform
|
||||
.get_platform_profile()
|
||||
.map(|p| p.into())
|
||||
.map_err(|e| {
|
||||
error!("get_platform_profile error: {e}");
|
||||
})
|
||||
{
|
||||
if profile != config.lock().await.current {
|
||||
fan_curves
|
||||
.lock()
|
||||
.await
|
||||
.profiles
|
||||
.write_profile_curve_to_platform(
|
||||
profile,
|
||||
&mut find_fan_curve_node().unwrap(),
|
||||
)
|
||||
.map_err(|e| warn!("write_profile_curve_to_platform, {}", e))
|
||||
.ok();
|
||||
config.lock().await.current = profile;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlFanCurveZbus {
|
||||
/// Fetch the active profile and use that to set all related components up
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
let active = self.platform.get_platform_profile()?.into();
|
||||
let mut config = self.config.lock().await;
|
||||
if let Ok(mut device) = find_fan_curve_node() {
|
||||
config
|
||||
.profiles
|
||||
.write_profile_curve_to_platform(active, &mut device)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
862
asusd/src/ctrl_platform.rs
Normal file
@@ -0,0 +1,862 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
|
||||
use config_traits::StdConfig;
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{debug, error, info, warn};
|
||||
use rog_platform::asus_armoury::{AttrValue, FirmwareAttribute, FirmwareAttributes};
|
||||
use rog_platform::cpu::{CPUControl, CPUGovernor, CPUEPP};
|
||||
use rog_platform::platform::{PlatformProfile, Properties, RogPlatform};
|
||||
use rog_platform::power::AsusPower;
|
||||
use zbus::fdo::Error as FdoErr;
|
||||
use zbus::object_server::SignalEmitter;
|
||||
use zbus::{interface, Connection};
|
||||
|
||||
use crate::asus_armoury::set_config_or_default;
|
||||
use crate::config::Config;
|
||||
use crate::error::RogError;
|
||||
use crate::{task_watch_item, CtrlTask, ReloadAndNotify};
|
||||
|
||||
const PLATFORM_ZBUS_PATH: &str = "/xyz/ljones";
|
||||
|
||||
macro_rules! platform_get_value {
|
||||
($self:ident, $property:tt, $prop_name:literal) => {
|
||||
concat_idents::concat_idents!(has = has_, $property {
|
||||
if $self.platform.has() {
|
||||
concat_idents::concat_idents!(get = get_, $property {
|
||||
$self.platform
|
||||
.get()
|
||||
.map_err(|err| {
|
||||
warn!("{}: {}", $prop_name, err);
|
||||
FdoErr::Failed(format!("RogPlatform: {}: {}", $prop_name, err))
|
||||
})
|
||||
})
|
||||
} else {
|
||||
return Err(FdoErr::NotSupported(format!("RogPlatform: {} not supported", $prop_name)));
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CtrlPlatform {
|
||||
power: AsusPower,
|
||||
platform: RogPlatform,
|
||||
attributes: FirmwareAttributes,
|
||||
cpu_control: Option<CPUControl>,
|
||||
config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
impl CtrlPlatform {
|
||||
pub fn new(
|
||||
platform: RogPlatform,
|
||||
power: AsusPower,
|
||||
attributes: FirmwareAttributes,
|
||||
config: Arc<Mutex<Config>>,
|
||||
config_path: &Path,
|
||||
signal_context: SignalEmitter<'static>,
|
||||
) -> Result<Self, RogError> {
|
||||
let config1 = config.clone();
|
||||
let config_path = config_path.to_owned();
|
||||
|
||||
let ret_self = CtrlPlatform {
|
||||
power,
|
||||
platform,
|
||||
attributes,
|
||||
config,
|
||||
cpu_control: CPUControl::new()
|
||||
.map_err(|e| error!("Couldn't get CPU control sysfs: {e}"))
|
||||
.ok(),
|
||||
};
|
||||
let mut inotify_self = ret_self.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
use futures_util::StreamExt;
|
||||
info!("Starting inotify watch for asusd config file");
|
||||
|
||||
let mut buffer = [0; 32];
|
||||
loop {
|
||||
// vi and vim do stupid shit causing the file watch to be removed
|
||||
let inotify = inotify::Inotify::init().unwrap();
|
||||
inotify
|
||||
.watches()
|
||||
.add(
|
||||
&config_path,
|
||||
inotify::WatchMask::MODIFY
|
||||
| inotify::WatchMask::CLOSE_WRITE
|
||||
| inotify::WatchMask::ATTRIB
|
||||
| inotify::WatchMask::CREATE,
|
||||
)
|
||||
.inspect_err(|e| {
|
||||
if e.kind() == std::io::ErrorKind::NotFound {
|
||||
error!("Not found: {:?}", config_path);
|
||||
} else {
|
||||
error!("Could not set asusd config inotify: {:?}", config_path);
|
||||
}
|
||||
})
|
||||
.ok();
|
||||
let mut events = inotify.into_event_stream(&mut buffer).unwrap();
|
||||
|
||||
while let Some(ev) = events.next().await {
|
||||
if let Ok(ev) = ev {
|
||||
if ev.mask == inotify::EventMask::IGNORED {
|
||||
warn!(
|
||||
"Something modified asusd.ron vi/vim style. Now need to reload \
|
||||
inotify watch"
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let res = config1.lock().await.read_new();
|
||||
if let Some(new_cfg) = res {
|
||||
inotify_self
|
||||
.reload_and_notify(&signal_context, new_cfg)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(ret_self)
|
||||
}
|
||||
|
||||
async fn restore_charge_limit(&self) {
|
||||
let limit = self.config.lock().await.base_charge_control_end_threshold;
|
||||
if limit > 0
|
||||
&& std::mem::replace(
|
||||
&mut self.config.lock().await.charge_control_end_threshold,
|
||||
limit,
|
||||
) != limit
|
||||
{
|
||||
self.power
|
||||
.set_charge_control_end_threshold(limit)
|
||||
.map_err(|e| {
|
||||
error!("Couldn't restore charge limit: {e}");
|
||||
})
|
||||
.ok();
|
||||
self.config.lock().await.write();
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_ac_or_bat_cmd(&self, power_plugged: bool) {
|
||||
let prog: Vec<String> = if power_plugged {
|
||||
// AC ONLINE
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.ac_command
|
||||
.split_whitespace()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
} else {
|
||||
// BATTERY
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.bat_command
|
||||
.split_whitespace()
|
||||
.map(|s| s.to_string())
|
||||
.collect()
|
||||
};
|
||||
if prog.len() > 1 {
|
||||
let mut cmd = Command::new(&prog[0]);
|
||||
for arg in prog.iter().skip(1) {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
if let Err(e) = cmd.spawn() {
|
||||
if power_plugged {
|
||||
error!("AC power command error: {e}");
|
||||
} else {
|
||||
error!("Battery power command error: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_and_set_epp(&self, enegy_pref: CPUEPP, change_epp: bool) {
|
||||
if !change_epp {
|
||||
info!("ThrottlePolicy unlinked from EPP");
|
||||
return;
|
||||
}
|
||||
info!("ThrottlePolicy setting EPP");
|
||||
if let Some(cpu) = self.cpu_control.as_ref() {
|
||||
if let Ok(epp) = cpu.get_available_epp() {
|
||||
debug!("Available EPP: {epp:?}");
|
||||
if epp.contains(&enegy_pref) {
|
||||
debug!("Setting {enegy_pref:?}");
|
||||
cpu.set_epp(enegy_pref).ok();
|
||||
} else if let Ok(gov) = cpu.get_governor() {
|
||||
if gov != CPUGovernor::Powersave {
|
||||
warn!("powersave governor is not is use, trying to set.");
|
||||
cpu.set_governor(CPUGovernor::Powersave)
|
||||
.map_err(|e| error!("couldn't set powersave: {e:?}"))
|
||||
.ok();
|
||||
if epp.contains(&enegy_pref) {
|
||||
debug!("Setting {enegy_pref:?}");
|
||||
cpu.set_epp(enegy_pref)
|
||||
.map_err(|e| error!("couldn't set EPP: {e:?}"))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_config_epp_for_throttle(&self, throttle: PlatformProfile) -> CPUEPP {
|
||||
match throttle {
|
||||
PlatformProfile::Balanced => self.config.lock().await.profile_balanced_epp,
|
||||
PlatformProfile::Performance => self.config.lock().await.profile_performance_epp,
|
||||
PlatformProfile::Quiet => self.config.lock().await.profile_quiet_epp,
|
||||
PlatformProfile::LowPower => self.config.lock().await.profile_quiet_epp,
|
||||
PlatformProfile::Custom => self.config.lock().await.profile_custom_epp,
|
||||
}
|
||||
}
|
||||
|
||||
async fn update_policy_ac_or_bat(&self, power_plugged: bool, change_epp: bool) {
|
||||
if power_plugged && !self.config.lock().await.change_platform_profile_on_ac {
|
||||
debug!(
|
||||
"Power status changed but set_platform_profile_on_ac set false. Not setting the \
|
||||
thing"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if !power_plugged && !self.config.lock().await.change_platform_profile_on_battery {
|
||||
debug!(
|
||||
"Power status changed but set_platform_profile_on_battery set false. Not setting \
|
||||
the thing"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let throttle = if power_plugged {
|
||||
self.config.lock().await.platform_profile_on_ac
|
||||
} else {
|
||||
self.config.lock().await.platform_profile_on_battery
|
||||
};
|
||||
debug!("Setting {throttle:?} before EPP");
|
||||
let epp = self.get_config_epp_for_throttle(throttle).await;
|
||||
self.platform.set_platform_profile(throttle.into()).ok();
|
||||
self.check_and_set_epp(epp, change_epp);
|
||||
}
|
||||
}
|
||||
|
||||
#[interface(name = "xyz.ljones.Platform")]
|
||||
impl CtrlPlatform {
|
||||
#[zbus(property)]
|
||||
async fn version(&self) -> String {
|
||||
crate::VERSION.to_string()
|
||||
}
|
||||
|
||||
/// Returns a list of property names that this system supports
|
||||
async fn supported_properties(&self) -> Vec<Properties> {
|
||||
let mut supported = Vec::new();
|
||||
|
||||
macro_rules! platform_name {
|
||||
($property:tt, $prop_name:ty) => {
|
||||
concat_idents::concat_idents!(has = has_, $property {
|
||||
if self.platform.has() {
|
||||
supported.push($prop_name.to_owned());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! power_name {
|
||||
($property:tt, $prop_name:ty) => {
|
||||
concat_idents::concat_idents!(has = has_, $property {
|
||||
if self.power.has() {
|
||||
supported.push($prop_name.to_owned());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: automate this
|
||||
power_name!(
|
||||
charge_control_end_threshold,
|
||||
Properties::ChargeControlEndThreshold
|
||||
);
|
||||
|
||||
platform_name!(platform_profile, Properties::ThrottlePolicy);
|
||||
|
||||
supported
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
fn charge_control_end_threshold(&self) -> Result<u8, FdoErr> {
|
||||
let limit = self.power.get_charge_control_end_threshold()?;
|
||||
Ok(limit)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_charge_control_end_threshold(&mut self, limit: u8) -> Result<(), FdoErr> {
|
||||
if !(20..=100).contains(&limit) {
|
||||
return Err(RogError::ChargeLimit(limit))?;
|
||||
}
|
||||
self.power.set_charge_control_end_threshold(limit)?;
|
||||
self.config.lock().await.charge_control_end_threshold = limit;
|
||||
self.config.lock().await.base_charge_control_end_threshold = limit;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn one_shot_full_charge(&self) -> Result<(), FdoErr> {
|
||||
let base_limit = std::mem::replace(
|
||||
&mut self.config.lock().await.charge_control_end_threshold,
|
||||
100,
|
||||
);
|
||||
if base_limit != 100 {
|
||||
self.power.set_charge_control_end_threshold(100)?;
|
||||
self.config.lock().await.base_charge_control_end_threshold = base_limit;
|
||||
self.config.lock().await.write();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Toggle to next platform_profile. Names provided by `Profiles`.
|
||||
/// If fan-curves are supported will also activate a fan curve for profile.
|
||||
async fn next_platform_profile(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
) -> Result<(), FdoErr> {
|
||||
let policy: PlatformProfile =
|
||||
platform_get_value!(self, platform_profile, "platform_profile").map(|n| n.into())?;
|
||||
let choices =
|
||||
platform_get_value!(self, platform_profile_choices, "platform_profile_choices")?;
|
||||
let policy = PlatformProfile::next(policy, &choices);
|
||||
|
||||
if self.platform.has_platform_profile() {
|
||||
let change_epp = self.config.lock().await.platform_profile_linked_epp;
|
||||
let epp = self.get_config_epp_for_throttle(policy).await;
|
||||
self.check_and_set_epp(epp, change_epp);
|
||||
self.platform
|
||||
.set_platform_profile(policy.into())
|
||||
.map_err(|err| {
|
||||
warn!("platform_profile {}", err);
|
||||
FdoErr::Failed(format!("RogPlatform: platform_profile: {err}"))
|
||||
})?;
|
||||
self.enable_ppt_group_changed(&ctxt).await?;
|
||||
Ok(self.platform_profile_changed(&ctxt).await?)
|
||||
} else {
|
||||
Err(FdoErr::NotSupported(
|
||||
"RogPlatform: platform_profile not supported".to_owned(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
fn platform_profile_choices(&self) -> Result<Vec<PlatformProfile>, FdoErr> {
|
||||
platform_get_value!(self, platform_profile_choices, "platform_profile_choices")
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
fn platform_profile(&self) -> Result<PlatformProfile, FdoErr> {
|
||||
let policy: PlatformProfile = self.platform.get_platform_profile()?.as_str().into();
|
||||
Ok(policy)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_platform_profile(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
policy: PlatformProfile,
|
||||
) -> Result<(), FdoErr> {
|
||||
// TODO: watch for external changes
|
||||
if self.platform.has_platform_profile() {
|
||||
let change_epp = self.config.lock().await.platform_profile_linked_epp;
|
||||
let epp = self.get_config_epp_for_throttle(policy).await;
|
||||
self.check_and_set_epp(epp, change_epp);
|
||||
|
||||
self.config.lock().await.write();
|
||||
|
||||
let choices = self.platform.get_platform_profile_choices()?;
|
||||
if !choices.contains(&policy) {
|
||||
return Err(FdoErr::NotSupported(format!(
|
||||
"RogPlatform: platform_profile: {} not supported",
|
||||
policy
|
||||
)));
|
||||
}
|
||||
|
||||
self.platform
|
||||
.set_platform_profile(policy.into())
|
||||
.map_err(|err| {
|
||||
warn!("platform_profile {}", err);
|
||||
FdoErr::Failed(format!("RogPlatform: platform_profile: {err}"))
|
||||
})?;
|
||||
self.enable_ppt_group_changed(&ctxt).await?;
|
||||
Ok(())
|
||||
} else {
|
||||
Err(FdoErr::NotSupported(
|
||||
"RogPlatform: platform_profile not supported".to_owned(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn platform_profile_linked_epp(&self) -> Result<bool, FdoErr> {
|
||||
Ok(self.config.lock().await.platform_profile_linked_epp)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_platform_profile_linked_epp(&self, linked: bool) -> Result<(), zbus::Error> {
|
||||
self.config.lock().await.platform_profile_linked_epp = linked;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn platform_profile_on_battery(&self) -> Result<PlatformProfile, FdoErr> {
|
||||
Ok(self.config.lock().await.platform_profile_on_battery)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_platform_profile_on_battery(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
policy: PlatformProfile,
|
||||
) -> Result<(), FdoErr> {
|
||||
self.config.lock().await.platform_profile_on_battery = policy;
|
||||
self.set_platform_profile(ctxt, policy).await?;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn change_platform_profile_on_battery(&self) -> Result<bool, FdoErr> {
|
||||
Ok(self.config.lock().await.change_platform_profile_on_battery)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_change_platform_profile_on_battery(&mut self, change: bool) -> Result<(), FdoErr> {
|
||||
self.config.lock().await.change_platform_profile_on_battery = change;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn platform_profile_on_ac(&self) -> Result<PlatformProfile, FdoErr> {
|
||||
Ok(self.config.lock().await.platform_profile_on_ac)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_platform_profile_on_ac(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalEmitter<'_>,
|
||||
policy: PlatformProfile,
|
||||
) -> Result<(), FdoErr> {
|
||||
self.config.lock().await.platform_profile_on_ac = policy;
|
||||
self.set_platform_profile(ctxt, policy).await?;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn change_platform_profile_on_ac(&self) -> Result<bool, FdoErr> {
|
||||
Ok(self.config.lock().await.change_platform_profile_on_ac)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_change_platform_profile_on_ac(&mut self, change: bool) -> Result<(), FdoErr> {
|
||||
self.config.lock().await.change_platform_profile_on_ac = change;
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The energy_performance_preference for the quiet throttle/platform
|
||||
/// profile
|
||||
#[zbus(property)]
|
||||
async fn profile_quiet_epp(&self) -> Result<CPUEPP, FdoErr> {
|
||||
Ok(self.config.lock().await.profile_quiet_epp)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_profile_quiet_epp(&mut self, epp: CPUEPP) -> Result<(), FdoErr> {
|
||||
let change_pp = self.config.lock().await.platform_profile_linked_epp;
|
||||
self.config.lock().await.profile_quiet_epp = epp;
|
||||
self.check_and_set_epp(epp, change_pp);
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The energy_performance_preference for the balanced throttle/platform
|
||||
/// profile
|
||||
#[zbus(property)]
|
||||
async fn profile_balanced_epp(&self) -> Result<CPUEPP, FdoErr> {
|
||||
Ok(self.config.lock().await.profile_balanced_epp)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_profile_balanced_epp(&mut self, epp: CPUEPP) -> Result<(), FdoErr> {
|
||||
let change_pp = self.config.lock().await.platform_profile_linked_epp;
|
||||
self.config.lock().await.profile_balanced_epp = epp;
|
||||
self.check_and_set_epp(epp, change_pp);
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The energy_performance_preference for the performance throttle/platform
|
||||
/// profile
|
||||
#[zbus(property)]
|
||||
async fn profile_performance_epp(&self) -> Result<CPUEPP, FdoErr> {
|
||||
Ok(self.config.lock().await.profile_performance_epp)
|
||||
}
|
||||
|
||||
#[zbus(property)]
|
||||
async fn set_profile_performance_epp(&mut self, epp: CPUEPP) -> Result<(), FdoErr> {
|
||||
let change_pp = self.config.lock().await.platform_profile_linked_epp;
|
||||
self.config.lock().await.profile_performance_epp = epp;
|
||||
self.check_and_set_epp(epp, change_pp);
|
||||
|
||||
self.config.lock().await.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set if the PPT tuning group for the current profile is enabled
|
||||
#[zbus(property)]
|
||||
async fn enable_ppt_group(&self) -> Result<bool, FdoErr> {
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
Ok(self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.select_tunings(power_plugged == 1, profile)
|
||||
.enabled)
|
||||
}
|
||||
|
||||
/// Set if the PPT tuning group for the current profile is enabled
|
||||
#[zbus(property)]
|
||||
async fn set_enable_ppt_group(&mut self, enable: bool) -> Result<(), FdoErr> {
|
||||
let power_plugged = self
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
|
||||
if enable {
|
||||
// Clone to reduce blocking
|
||||
let tuning = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.select_tunings(power_plugged == 1, profile)
|
||||
.clone();
|
||||
|
||||
for attr in self.attributes.attributes() {
|
||||
let name: FirmwareAttribute = attr.name().into();
|
||||
if name.is_ppt() {
|
||||
// reset stored value
|
||||
if let Some(tune) = self
|
||||
.config
|
||||
.lock()
|
||||
.await
|
||||
.select_tunings(power_plugged == 1, profile)
|
||||
.group
|
||||
.get_mut(&name)
|
||||
{
|
||||
let value = tuning
|
||||
.group
|
||||
.get(&name)
|
||||
.map(|v| AttrValue::Integer(*v))
|
||||
.unwrap_or_else(|| attr.default_value().clone());
|
||||
// restore default
|
||||
attr.set_current_value(&value)?;
|
||||
if let AttrValue::Integer(i) = value {
|
||||
*tune = i
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// finally, reapply the profile to ensure acpi does the thingy
|
||||
self.platform.set_platform_profile(profile.into())?;
|
||||
}
|
||||
|
||||
self.config
|
||||
.lock()
|
||||
.await
|
||||
.select_tunings(power_plugged == 1, profile)
|
||||
.enabled = enable;
|
||||
self.config.lock().await.write();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::ZbusRun for CtrlPlatform {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, PLATFORM_ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl ReloadAndNotify for CtrlPlatform {
|
||||
type Data = Config;
|
||||
|
||||
/// Called on config file changed externally
|
||||
async fn reload_and_notify(
|
||||
&mut self,
|
||||
signal_context: &SignalEmitter<'static>,
|
||||
data: Self::Data,
|
||||
) -> Result<(), RogError> {
|
||||
let mut config = self.config.lock().await;
|
||||
if *config != data {
|
||||
info!("asusd.ron updated externally, reloading and updating internal copy");
|
||||
|
||||
let mut base_charge_control_end_threshold = None;
|
||||
|
||||
if self.power.has_charge_control_end_threshold()
|
||||
&& data.charge_control_end_threshold != config.charge_control_end_threshold
|
||||
{
|
||||
let limit = data.charge_control_end_threshold;
|
||||
warn!("setting charge_control_end_threshold to {limit}");
|
||||
self.power.set_charge_control_end_threshold(limit)?;
|
||||
self.charge_control_end_threshold_changed(signal_context)
|
||||
.await?;
|
||||
base_charge_control_end_threshold = (config.base_charge_control_end_threshold > 0)
|
||||
.then_some(config.base_charge_control_end_threshold)
|
||||
.or(Some(limit));
|
||||
}
|
||||
|
||||
if self.platform.has_platform_profile()
|
||||
&& config.platform_profile_linked_epp != data.platform_profile_linked_epp
|
||||
{
|
||||
let profile: PlatformProfile = self.platform.get_platform_profile()?.into();
|
||||
|
||||
let epp = match profile {
|
||||
PlatformProfile::Balanced => data.profile_balanced_epp,
|
||||
PlatformProfile::Performance => data.profile_performance_epp,
|
||||
PlatformProfile::Quiet => data.profile_quiet_epp,
|
||||
PlatformProfile::LowPower => data.profile_quiet_epp,
|
||||
PlatformProfile::Custom => data.profile_custom_epp,
|
||||
};
|
||||
warn!("setting epp to {epp:?}");
|
||||
self.check_and_set_epp(epp, true);
|
||||
}
|
||||
// reload_and_notify!(platform_profile, "platform_profile");
|
||||
|
||||
*config = data;
|
||||
config.base_charge_control_end_threshold =
|
||||
base_charge_control_end_threshold.unwrap_or_default();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Reloadable for CtrlPlatform {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
info!("Begin Platform settings restore");
|
||||
if self.power.has_charge_control_end_threshold() {
|
||||
// self.restore_charge_limit().await;
|
||||
let limit = self.config.lock().await.charge_control_end_threshold;
|
||||
info!("reloading charge_control_end_threshold to {limit}");
|
||||
self.power.set_charge_control_end_threshold(limit)?;
|
||||
} else {
|
||||
warn!("No charge_control_end_threshold found")
|
||||
}
|
||||
|
||||
if let Ok(power_plugged) = self.power.get_online() {
|
||||
self.config.lock().await.last_power_plugged = power_plugged;
|
||||
if self.platform.has_platform_profile() {
|
||||
let change_epp = self.config.lock().await.platform_profile_linked_epp;
|
||||
self.update_policy_ac_or_bat(power_plugged > 0, change_epp)
|
||||
.await;
|
||||
}
|
||||
self.run_ac_or_bat_cmd(power_plugged > 0).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlPlatform {
|
||||
task_watch_item!(charge_control_end_threshold "charge_control_end_threshold" power);
|
||||
}
|
||||
|
||||
impl CtrlTask for CtrlPlatform {
|
||||
fn zbus_path() -> &'static str {
|
||||
PLATFORM_ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, signal_ctxt: SignalEmitter<'static>) -> Result<(), RogError> {
|
||||
let platform1 = self.clone();
|
||||
let platform2 = self.clone();
|
||||
let platform3 = self.clone();
|
||||
let signal_ctxt_copy = signal_ctxt.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move |sleeping| {
|
||||
let platform1 = platform1.clone();
|
||||
async move {
|
||||
// This block is commented out due to some kind of issue reported. Maybe the
|
||||
// desktops used were storing a value whcih was then read here.
|
||||
// Don't store it on suspend, assume that the current config setting is desired
|
||||
// if sleeping && platform1.power.has_charge_control_end_threshold() {
|
||||
// platform1.config.lock().await.charge_control_end_threshold = platform1
|
||||
// .power
|
||||
// .get_charge_control_end_threshold()
|
||||
// .unwrap_or(100);
|
||||
// } else
|
||||
if !sleeping && platform1.power.has_charge_control_end_threshold() {
|
||||
platform1
|
||||
.power
|
||||
.set_charge_control_end_threshold(
|
||||
platform1.config.lock().await.charge_control_end_threshold,
|
||||
)
|
||||
.ok();
|
||||
}
|
||||
if let Ok(power_plugged) = platform1.power.get_online() {
|
||||
if platform1.config.lock().await.last_power_plugged != power_plugged {
|
||||
if !sleeping && platform1.platform.has_platform_profile() {
|
||||
let change_epp =
|
||||
platform1.config.lock().await.platform_profile_linked_epp;
|
||||
platform1
|
||||
.update_policy_ac_or_bat(power_plugged > 0, change_epp)
|
||||
.await;
|
||||
}
|
||||
if !sleeping {
|
||||
platform1.run_ac_or_bat_cmd(power_plugged > 0).await;
|
||||
}
|
||||
platform1.config.lock().await.last_power_plugged = power_plugged;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
move |shutting_down| {
|
||||
let platform2 = platform2.clone();
|
||||
async move {
|
||||
info!("RogPlatform reloading panel_od");
|
||||
let lock = platform2.config.lock().await;
|
||||
if shutting_down
|
||||
&& platform2.power.has_charge_control_end_threshold()
|
||||
&& lock.base_charge_control_end_threshold > 0
|
||||
{
|
||||
info!("RogPlatform restoring charge_control_end_threshold");
|
||||
platform2
|
||||
.power
|
||||
.set_charge_control_end_threshold(
|
||||
lock.base_charge_control_end_threshold,
|
||||
)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: charge_control_end_threshold {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
move |_lid_closed| {
|
||||
// on lid change
|
||||
async move {}
|
||||
},
|
||||
move |power_plugged| {
|
||||
let platform3 = platform3.clone();
|
||||
let signal_ctxt_copy = signal_ctxt.clone();
|
||||
// power change
|
||||
async move {
|
||||
if platform3.platform.has_platform_profile() {
|
||||
let change_epp = platform3.config.lock().await.platform_profile_linked_epp;
|
||||
platform3
|
||||
.update_policy_ac_or_bat(power_plugged, change_epp)
|
||||
.await;
|
||||
}
|
||||
platform3.run_ac_or_bat_cmd(power_plugged).await;
|
||||
// In case one-shot charge was used, restore the old charge limit
|
||||
if platform3.power.has_charge_control_end_threshold() && !power_plugged {
|
||||
platform3.restore_charge_limit().await;
|
||||
}
|
||||
|
||||
if let Ok(profile) = platform3
|
||||
.platform
|
||||
.get_platform_profile()
|
||||
.map(|p| p.into())
|
||||
.map_err(|e| {
|
||||
error!("Platform: get_platform_profile error: {e}");
|
||||
})
|
||||
{
|
||||
// TODO: manage this better, shouldn't need to create every time
|
||||
let attrs = FirmwareAttributes::new();
|
||||
set_config_or_default(
|
||||
&attrs,
|
||||
&mut *platform3.config.lock().await,
|
||||
power_plugged,
|
||||
profile,
|
||||
)
|
||||
.await;
|
||||
platform3
|
||||
.enable_ppt_group_changed(&signal_ctxt_copy)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
// This spawns a new task for every item.
|
||||
// TODO: find a better way to manage this
|
||||
self.watch_charge_control_end_threshold(signal_ctxt_copy.clone())
|
||||
.await?;
|
||||
|
||||
let watch_platform_profile = self.platform.monitor_platform_profile()?;
|
||||
let ctrl = self.clone();
|
||||
|
||||
// Need a copy here, not ideal. But first use in asus_armoury.rs is
|
||||
// moved to zbus
|
||||
let attrs = FirmwareAttributes::new();
|
||||
tokio::spawn(async move {
|
||||
use futures_lite::StreamExt;
|
||||
let mut buffer = [0; 32];
|
||||
if let Ok(mut stream) = watch_platform_profile.into_event_stream(&mut buffer) {
|
||||
while (stream.next().await).is_some() {
|
||||
// this blocks
|
||||
debug!("Platform: watch_platform_profile changed");
|
||||
if let Ok(profile) = ctrl
|
||||
.platform
|
||||
.get_platform_profile()
|
||||
.map(|p| p.into())
|
||||
.map_err(|e| {
|
||||
error!("Platform: get_platform_profile error: {e}");
|
||||
})
|
||||
{
|
||||
let change_epp = ctrl.config.lock().await.platform_profile_linked_epp;
|
||||
let epp = ctrl.get_config_epp_for_throttle(profile).await;
|
||||
ctrl.check_and_set_epp(epp, change_epp);
|
||||
ctrl.platform_profile_changed(&signal_ctxt_copy).await.ok();
|
||||
ctrl.enable_ppt_group_changed(&signal_ctxt_copy).await.ok();
|
||||
let power_plugged = ctrl
|
||||
.power
|
||||
.get_online()
|
||||
.map_err(|e| {
|
||||
error!("Could not get power status: {e:?}");
|
||||
e
|
||||
})
|
||||
.unwrap_or_default();
|
||||
set_config_or_default(
|
||||
&attrs,
|
||||
&mut *ctrl.config.lock().await,
|
||||
power_plugged == 1,
|
||||
profile,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
136
asusd/src/daemon.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
use std::env;
|
||||
use std::error::Error;
|
||||
use std::sync::Arc;
|
||||
|
||||
use ::zbus::Connection;
|
||||
use asusd::asus_armoury::start_attributes_zbus;
|
||||
use asusd::aura_manager::DeviceManager;
|
||||
use asusd::config::Config;
|
||||
use asusd::ctrl_backlight::CtrlBacklight;
|
||||
use asusd::ctrl_fancurves::CtrlFanCurveZbus;
|
||||
use asusd::ctrl_platform::CtrlPlatform;
|
||||
use asusd::{print_board_info, start_tasks, CtrlTask, ZbusRun, DBUS_NAME};
|
||||
use config_traits::{StdConfig, StdConfigLoad2};
|
||||
use futures_util::lock::Mutex;
|
||||
use log::{error, info};
|
||||
use rog_platform::asus_armoury::FirmwareAttributes;
|
||||
use rog_platform::platform::RogPlatform;
|
||||
use rog_platform::power::AsusPower;
|
||||
use zbus::fdo::ObjectManager;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// console_subscriber::init();
|
||||
let mut logger = env_logger::Builder::new();
|
||||
logger
|
||||
.parse_default_env()
|
||||
.target(env_logger::Target::Stdout)
|
||||
.format_timestamp(None)
|
||||
.filter_level(log::LevelFilter::Debug)
|
||||
.init();
|
||||
|
||||
let is_service = match env::var_os("IS_SERVICE") {
|
||||
Some(val) => val == "1",
|
||||
None => true,
|
||||
};
|
||||
|
||||
if !is_service {
|
||||
println!("asusd schould be only run from the right systemd service");
|
||||
println!(
|
||||
"do not run in your terminal, if you need an logs please use journalctl -b -u asusd"
|
||||
);
|
||||
println!("asusd will now exit");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
info!(" daemon v{}", asusd::VERSION);
|
||||
info!(" rog-anime v{}", rog_anime::VERSION);
|
||||
info!(" rog-slash v{}", rog_slash::VERSION);
|
||||
info!(" rog-aura v{}", rog_aura::VERSION);
|
||||
info!(" rog-profiles v{}", rog_profiles::VERSION);
|
||||
info!("rog-platform v{}", rog_platform::VERSION);
|
||||
|
||||
start_daemon().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The actual main loop for the daemon
|
||||
async fn start_daemon() -> Result<(), Box<dyn Error>> {
|
||||
// let supported = SupportedFunctions::get_supported();
|
||||
print_board_info();
|
||||
// println!("{:?}", supported.supported_functions());
|
||||
|
||||
// Start zbus server
|
||||
let mut server = Connection::system().await?;
|
||||
if let Err(e) = server.object_server().at("/", ObjectManager).await {
|
||||
error!("Failed to register ObjectManager at root '/': {e:?}");
|
||||
}
|
||||
|
||||
let config = Config::new().load();
|
||||
let cfg_path = config.file_path();
|
||||
let config = Arc::new(Mutex::new(config));
|
||||
|
||||
// supported.add_to_server(&mut connection).await;
|
||||
let platform = RogPlatform::new()?; // TODO: maybe needs async mutex?
|
||||
let power = AsusPower::new()?; // TODO: maybe needs async mutex?
|
||||
let attributes = FirmwareAttributes::new();
|
||||
if let Err(e) = start_attributes_zbus(
|
||||
&server,
|
||||
platform.clone(),
|
||||
power.clone(),
|
||||
attributes.clone(),
|
||||
config.clone(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
error!("Failed to initialize firmware attributes over zbus: {e:?}");
|
||||
}
|
||||
|
||||
match CtrlFanCurveZbus::new() {
|
||||
Ok(ctrl) => {
|
||||
let sig_ctx = CtrlFanCurveZbus::signal_context(&server)?;
|
||||
start_tasks(ctrl, &mut server, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("FanCurves: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlBacklight::new(config.clone()) {
|
||||
Ok(backlight) => {
|
||||
backlight.start_watch_primary().await?;
|
||||
backlight.add_to_server(&mut server).await;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Backlight: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlPlatform::new(
|
||||
platform,
|
||||
power,
|
||||
attributes,
|
||||
config.clone(),
|
||||
&cfg_path,
|
||||
CtrlPlatform::signal_context(&server)?,
|
||||
) {
|
||||
Ok(ctrl) => {
|
||||
let sig_ctx = CtrlPlatform::signal_context(&server)?;
|
||||
start_tasks(ctrl, &mut server, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("CtrlPlatform: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = DeviceManager::new(server.clone()).await?;
|
||||
|
||||
// Request dbus name after finishing initalizing all functions
|
||||
server.request_name(DBUS_NAME).await?;
|
||||
|
||||
info!("Startup success, begining dbus server loop");
|
||||
loop {
|
||||
// This is just a blocker to idle and ensure the reator reacts
|
||||
server.executor().tick().await;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ use config_traits::ron;
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_platform::error::PlatformError;
|
||||
use rog_profiles::error::ProfileError;
|
||||
use rog_slash::error::SlashError;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RogError {
|
||||
@@ -31,6 +32,7 @@ pub enum RogError {
|
||||
NoAuraKeyboard,
|
||||
NoAuraNode,
|
||||
Anime(AnimeError),
|
||||
Slash(SlashError),
|
||||
Platform(PlatformError),
|
||||
SystemdUnitAction(String),
|
||||
SystemdUnitWaitTimeout(String),
|
||||
@@ -72,6 +74,7 @@ impl fmt::Display for RogError {
|
||||
RogError::NoAuraKeyboard => write!(f, "No supported Aura keyboard"),
|
||||
RogError::NoAuraNode => write!(f, "No Aura keyboard node found"),
|
||||
RogError::Anime(deets) => write!(f, "AniMe Matrix error: {}", deets),
|
||||
RogError::Slash(deets) => write!(f, "Slash error: {}", deets),
|
||||
RogError::Platform(deets) => write!(f, "Asus Platform error: {}", deets),
|
||||
RogError::SystemdUnitAction(action) => {
|
||||
write!(f, "systemd unit action {} failed", action)
|
||||
@@ -103,6 +106,12 @@ impl From<AnimeError> for RogError {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SlashError> for RogError {
|
||||
fn from(err: SlashError) -> Self {
|
||||
RogError::Slash(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PlatformError> for RogError {
|
||||
fn from(err: PlatformError) -> Self {
|
||||
RogError::Platform(err)
|
||||
@@ -133,3 +142,10 @@ impl From<RogError> for zbus::fdo::Error {
|
||||
zbus::fdo::Error::Failed(format!("{}", err))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RogError> for zbus::Error {
|
||||
#[inline]
|
||||
fn from(err: RogError) -> Self {
|
||||
zbus::Error::Failure(format!("{}", err))
|
||||
}
|
||||
}
|
||||
320
asusd/src/lib.rs
Normal file
@@ -0,0 +1,320 @@
|
||||
#![deny(unused_must_use)]
|
||||
/// Configuration loading, saving
|
||||
pub mod config;
|
||||
pub mod ctrl_backlight;
|
||||
/// Control platform profiles + fan-curves if available
|
||||
pub mod ctrl_fancurves;
|
||||
/// Control ASUS bios function such as boot sound, Optimus/Dedicated gfx mode
|
||||
pub mod ctrl_platform;
|
||||
|
||||
pub mod asus_armoury;
|
||||
pub mod aura_anime;
|
||||
pub mod aura_laptop;
|
||||
pub mod aura_manager;
|
||||
pub mod aura_scsi;
|
||||
pub mod aura_slash;
|
||||
pub mod aura_types;
|
||||
pub mod error;
|
||||
|
||||
use std::future::Future;
|
||||
use std::time::Duration;
|
||||
|
||||
use dmi_id::DMIID;
|
||||
use futures_lite::stream::StreamExt;
|
||||
use log::{debug, info, warn};
|
||||
use logind_zbus::manager::ManagerProxy;
|
||||
use tokio::time::sleep;
|
||||
use zbus::object_server::{Interface, SignalEmitter};
|
||||
use zbus::proxy::CacheProperties;
|
||||
use zbus::zvariant::ObjectPath;
|
||||
use zbus::Connection;
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
const CONFIG_PATH_BASE: &str = "/etc/asusd/";
|
||||
pub const ASUS_ZBUS_PATH: &str = "/xyz/ljones";
|
||||
|
||||
pub static DBUS_NAME: &str = "xyz.ljones.Asusd";
|
||||
pub static DBUS_PATH: &str = "/xyz/ljones/Daemon";
|
||||
pub static DBUS_IFACE: &str = "xyz.ljones.Asusd";
|
||||
|
||||
/// This macro adds a function which spawns an `inotify` task on the passed in
|
||||
/// `Executor`.
|
||||
///
|
||||
/// The generated function is `watch_<name>()`. Self requires the following
|
||||
/// methods to be available:
|
||||
/// - `<name>() -> SomeValue`, functionally is a getter, but is allowed to have
|
||||
/// side effects.
|
||||
/// - `notify_<name>(SignalEmitter, SomeValue)`
|
||||
///
|
||||
/// In most cases if `SomeValue` is stored in a config then `<name>()` getter is
|
||||
/// expected to update it. The getter should *never* write back to the path or
|
||||
/// attribute that is being watched or an infinite loop will occur.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// impl RogPlatform {
|
||||
/// task_watch_item!(panel_od platform);
|
||||
/// task_watch_item!(gpu_mux_mode platform);
|
||||
/// }
|
||||
/// ```\
|
||||
/// // TODO: this is kind of useless if it can't trigger some action
|
||||
#[macro_export]
|
||||
macro_rules! task_watch_item {
|
||||
($name:ident $name_str:literal $self_inner:ident) => {
|
||||
concat_idents::concat_idents!(fn_name = watch_, $name {
|
||||
async fn fn_name(
|
||||
&self,
|
||||
signal_ctxt: SignalEmitter<'static>,
|
||||
) -> Result<(), RogError> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
let ctrl = self.clone();
|
||||
concat_idents::concat_idents!(watch_fn = monitor_, $name {
|
||||
match self.$self_inner.watch_fn() {
|
||||
Ok(watch) => {
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
watch.into_event_stream(&mut buffer).unwrap().for_each(|_| async {
|
||||
if let Ok(value) = ctrl.$name() { // get new value from zbus method
|
||||
if ctrl.config.lock().await.$name != value {
|
||||
log::debug!("{} was changed to {} externally", $name_str, value);
|
||||
concat_idents::concat_idents!(notif_fn = $name, _changed {
|
||||
ctrl.notif_fn(&signal_ctxt).await.ok();
|
||||
});
|
||||
let mut lock = ctrl.config.lock().await;
|
||||
lock.$name = value;
|
||||
lock.write();
|
||||
}
|
||||
}
|
||||
}).await;
|
||||
});
|
||||
}
|
||||
Err(e) => info!("inotify watch failed: {}. You can ignore this if your device does not support the feature", e),
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! task_watch_item_notify {
|
||||
($name:ident $self_inner:ident) => {
|
||||
concat_idents::concat_idents!(fn_name = watch_, $name {
|
||||
async fn fn_name(
|
||||
&self,
|
||||
signal_ctxt: SignalEmitter<'static>,
|
||||
) -> Result<(), RogError> {
|
||||
use futures_util::StreamExt;
|
||||
|
||||
let ctrl = self.clone();
|
||||
concat_idents::concat_idents!(watch_fn = monitor_, $name {
|
||||
match self.$self_inner.watch_fn() {
|
||||
Ok(watch) => {
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
watch.into_event_stream(&mut buffer).unwrap().for_each(|_| async {
|
||||
concat_idents::concat_idents!(notif_fn = $name, _changed {
|
||||
ctrl.notif_fn(&signal_ctxt).await.ok();
|
||||
});
|
||||
}).await;
|
||||
});
|
||||
}
|
||||
Err(e) => info!("inotify watch failed: {}. You can ignore this if your device does not support the feature", e),
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub fn print_board_info() {
|
||||
let dmi = DMIID::new().unwrap_or_default();
|
||||
info!("Product family: {}", dmi.product_family);
|
||||
info!("Board name: {}", dmi.board_name);
|
||||
}
|
||||
|
||||
pub trait Reloadable {
|
||||
fn reload(&mut self) -> impl Future<Output = Result<(), RogError>> + Send;
|
||||
}
|
||||
|
||||
pub trait ReloadAndNotify {
|
||||
type Data: Send;
|
||||
|
||||
fn reload_and_notify(
|
||||
&mut self,
|
||||
signal_context: &SignalEmitter<'static>,
|
||||
data: Self::Data,
|
||||
) -> impl Future<Output = Result<(), RogError>> + Send;
|
||||
}
|
||||
|
||||
pub trait ZbusRun {
|
||||
fn add_to_server(self, server: &mut Connection) -> impl Future<Output = ()> + Send;
|
||||
|
||||
fn add_to_server_helper(
|
||||
iface: impl Interface,
|
||||
path: &str,
|
||||
server: &mut Connection,
|
||||
) -> impl Future<Output = ()> + Send {
|
||||
async move {
|
||||
server
|
||||
.object_server()
|
||||
.at(&ObjectPath::from_str_unchecked(path), iface)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("{}: add_to_server {}", path, err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set up a task to run on the async executor
|
||||
pub trait CtrlTask {
|
||||
fn zbus_path() -> &'static str;
|
||||
|
||||
fn signal_context(connection: &Connection) -> Result<SignalEmitter<'static>, zbus::Error> {
|
||||
SignalEmitter::new(connection, Self::zbus_path())
|
||||
}
|
||||
|
||||
/// Implement to set up various tasks that may be required, using the
|
||||
/// `Executor`. No blocking loops are allowed, or they must be run on a
|
||||
/// separate thread.
|
||||
fn create_tasks(
|
||||
&self,
|
||||
signal: SignalEmitter<'static>,
|
||||
) -> impl Future<Output = Result<(), RogError>> + Send;
|
||||
|
||||
// /// Create a timed repeating task
|
||||
// async fn repeating_task(&self, millis: u64, mut task: impl FnMut() + Send +
|
||||
// 'static) { use std::time::Duration;
|
||||
// use tokio::time;
|
||||
// let mut timer = time::interval(Duration::from_millis(millis));
|
||||
// tokio::spawn(async move {
|
||||
// timer.tick().await;
|
||||
// task();
|
||||
// });
|
||||
// }
|
||||
|
||||
/// Free helper method to create tasks to run on: sleep, wake, shutdown,
|
||||
/// boot
|
||||
///
|
||||
/// The closures can potentially block, so execution time should be the
|
||||
/// minimal possible such as save a variable.
|
||||
fn create_sys_event_tasks<Fut1, Fut2, Fut3, Fut4, F1, F2, F3, F4>(
|
||||
&self,
|
||||
mut on_prepare_for_sleep: F1,
|
||||
mut on_prepare_for_shutdown: F2,
|
||||
mut on_lid_change: F3,
|
||||
mut on_external_power_change: F4,
|
||||
) -> impl Future<Output = ()> + Send
|
||||
where
|
||||
F1: FnMut(bool) -> Fut1 + Send + 'static,
|
||||
F2: FnMut(bool) -> Fut2 + Send + 'static,
|
||||
F3: FnMut(bool) -> Fut3 + Send + 'static,
|
||||
F4: FnMut(bool) -> Fut4 + Send + 'static,
|
||||
Fut1: Future<Output = ()> + Send,
|
||||
Fut2: Future<Output = ()> + Send,
|
||||
Fut3: Future<Output = ()> + Send,
|
||||
Fut4: Future<Output = ()> + Send,
|
||||
{
|
||||
async {
|
||||
let connection = Connection::system()
|
||||
.await
|
||||
.expect("Controller could not create dbus connection");
|
||||
|
||||
let manager = ManagerProxy::builder(&connection)
|
||||
.cache_properties(CacheProperties::No)
|
||||
.build()
|
||||
.await
|
||||
.expect("Controller could not create ManagerProxy");
|
||||
|
||||
let manager1 = manager.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Ok(mut notif) = manager1.receive_prepare_for_shutdown().await {
|
||||
while let Some(event) = notif.next().await {
|
||||
// blocks thread :|
|
||||
if let Ok(args) = event.args() {
|
||||
debug!("Doing on_prepare_for_shutdown({})", args.start);
|
||||
on_prepare_for_shutdown(args.start).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let manager2 = manager.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Ok(mut notif) = manager2.receive_prepare_for_sleep().await {
|
||||
while let Some(event) = notif.next().await {
|
||||
// blocks thread :|
|
||||
if let Ok(args) = event.args() {
|
||||
debug!("Doing on_prepare_for_sleep({})", args.start);
|
||||
on_prepare_for_sleep(args.start).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let manager3 = manager.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut last_power = manager3.on_external_power().await.unwrap_or_default();
|
||||
|
||||
loop {
|
||||
if let Ok(next) = manager3.on_external_power().await {
|
||||
if next != last_power {
|
||||
last_power = next;
|
||||
on_external_power_change(next).await;
|
||||
}
|
||||
}
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
});
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut last_lid = manager.lid_closed().await.unwrap_or_default();
|
||||
// need to loop on these as they don't emit signals
|
||||
loop {
|
||||
if let Ok(next) = manager.lid_closed().await {
|
||||
if next != last_lid {
|
||||
last_lid = next;
|
||||
on_lid_change(next).await;
|
||||
}
|
||||
}
|
||||
sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait GetSupported {
|
||||
type A;
|
||||
|
||||
fn get_supported() -> Self::A;
|
||||
}
|
||||
|
||||
pub async fn start_tasks<T>(
|
||||
mut zbus: T,
|
||||
connection: &mut Connection,
|
||||
signal_ctx: SignalEmitter<'static>,
|
||||
) -> Result<(), RogError>
|
||||
where
|
||||
T: ZbusRun + Reloadable + CtrlTask + Clone,
|
||||
{
|
||||
let zbus_clone = zbus.clone();
|
||||
|
||||
zbus.reload()
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Controller error: {}", err));
|
||||
zbus.add_to_server(connection).await;
|
||||
|
||||
zbus_clone.create_tasks(signal_ctx).await.ok();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,18 +1,15 @@
|
||||
[package]
|
||||
name = "config-traits"
|
||||
license = "MPL-2.0"
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_derive.workspace = true
|
||||
serde_json.workspace = true
|
||||
toml.workspace = true
|
||||
ron.workspace = true
|
||||
|
||||
log.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
cargo-husky.workspace = true
|
||||
@@ -3,10 +3,7 @@
|
||||
//! updating them from previous versions where fields or names are changed in
|
||||
//! some way.
|
||||
//!
|
||||
//! The end canonical file format is `.ron` as this supports rust types well,
|
||||
//! and includes the ability to add commenting, and is less verbose than `json`.
|
||||
//! Currently the crate will also try to parse from `json` and `toml` if the
|
||||
//! `ron` parsing fails, then update to `ron` format.
|
||||
//! The end canonical file format is `.ron` as this supports rust types well
|
||||
|
||||
use std::fs::{self, create_dir, File, OpenOptions};
|
||||
use std::io::{Read, Write};
|
||||
@@ -92,6 +89,7 @@ where
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(self.file_path())
|
||||
.unwrap_or_else(|e| panic!("Could not open {:?} {e}", self.file_path()))
|
||||
}
|
||||
@@ -109,6 +107,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Open and parse the config file to self from ron format
|
||||
fn read_new(&self) -> Option<Self> {
|
||||
if let Ok(data) = fs::read_to_string(self.file_path()) {
|
||||
if data.is_empty() {
|
||||
warn!("File is empty {:?}", self.file_path());
|
||||
} else if let Ok(data) = ron::from_str(&data) {
|
||||
return Some(data);
|
||||
} else {
|
||||
warn!("Could not deserialise {:?}", self.file_path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Write the config file data to pretty ron format
|
||||
fn write(&self) {
|
||||
let mut file = match File::create(self.file_path()) {
|
||||
@@ -134,11 +146,7 @@ where
|
||||
|
||||
/// Renames the existing file to `<file>-old`
|
||||
fn rename_file_old(&self) {
|
||||
warn!(
|
||||
"Renaming {} to {}-old and recreating config",
|
||||
self.file_name(),
|
||||
self.file_name()
|
||||
);
|
||||
warn!("Renaming {} to {}-old", self.file_name(), self.file_name());
|
||||
let mut cfg_old = self.file_path().to_string_lossy().to_string();
|
||||
cfg_old.push_str("-old");
|
||||
std::fs::rename(self.file_path(), cfg_old).unwrap_or_else(|err| {
|
||||
@@ -195,7 +203,7 @@ macro_rules! std_config_load {
|
||||
/// new one created
|
||||
pub trait $trait_name<$($generic),*>
|
||||
where
|
||||
Self: $crate::StdConfig +std::fmt::Debug + DeserializeOwned + Serialize,
|
||||
Self: $crate::StdConfig + DeserializeOwned + Serialize,
|
||||
$($generic: DeserializeOwned + Into<Self>),*
|
||||
{
|
||||
fn load(mut self) -> Self {
|
||||
@@ -206,21 +214,9 @@ macro_rules! std_config_load {
|
||||
if let Ok(data) = ron::from_str(&buf) {
|
||||
self = data;
|
||||
log::info!("Parsed RON for {:?}", std::any::type_name::<Self>());
|
||||
} else if let Ok(data) = serde_json::from_str(&buf) {
|
||||
self = data;
|
||||
log::info!("Parsed JSON for {:?}", std::any::type_name::<Self>());
|
||||
} else if let Ok(data) = toml::from_str(&buf) {
|
||||
self = data;
|
||||
log::info!("Parsed TOML for {:?}", std::any::type_name::<Self>());
|
||||
} $(else if let Ok(data) = ron::from_str::<$generic>(&buf) {
|
||||
} $(else if let Ok(data) = ron::from_str::<$generic>(&buf) {
|
||||
self = data.into();
|
||||
log::info!("New version failed, trying previous: Parsed RON for {:?}", std::any::type_name::<$generic>());
|
||||
} else if let Ok(data) = serde_json::from_str::<$generic>(&buf) {
|
||||
self = data.into();
|
||||
log::info!("New version failed, trying previous: Parsed JSON for {:?}", std::any::type_name::<$generic>());
|
||||
} else if let Ok(data) = toml::from_str::<$generic>(&buf) {
|
||||
self = data.into();
|
||||
log::info!("Newvious version failed, trying previous: Parsed TOML for {:?}", std::any::type_name::<$generic>());
|
||||
})* else {
|
||||
self.rename_file_old();
|
||||
self = Self::new();
|
||||
@@ -274,6 +270,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let _ = Test {};
|
||||
|
||||
impl crate::StdConfigLoad1<Old1> for Test {}
|
||||
}
|
||||
|
||||
@@ -323,6 +321,8 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let _ = Test {};
|
||||
|
||||
impl crate::StdConfigLoad3<Old1, Old2, Old3> for Test {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
[package]
|
||||
name = "daemon-user"
|
||||
license = "MPL-2.0"
|
||||
version.workspace = true
|
||||
authors = ["Luke D Jones <luke@ljones.dev>"]
|
||||
edition = "2021"
|
||||
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]
|
||||
dirs.workspace = true
|
||||
smol.workspace = true
|
||||
|
||||
# serialisation
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_derive.workspace = true
|
||||
|
||||
rog_anime = { path = "../rog-anime" }
|
||||
rog_aura = { path = "../rog-aura" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
rog_platform = { path = "../rog-platform" }
|
||||
config-traits = { path = "../config-traits" }
|
||||
|
||||
zbus.workspace = true
|
||||
|
||||
# cli and logging
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
cargo-husky.workspace = true
|
||||
@@ -1,50 +0,0 @@
|
||||
[package]
|
||||
name = "daemon"
|
||||
license = "MPL-2.0"
|
||||
version.workspace = true
|
||||
readme = "README.md"
|
||||
authors = ["Luke <luke@ljones.dev>"]
|
||||
repository = "https://gitlab.com/asus-linux/asus-nb-ctrl"
|
||||
homepage = "https://gitlab.com/asus-linux/asus-nb-ctrl"
|
||||
description = "A daemon app for ASUS GX502 and similar laptops to control missing features"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "daemon"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "asusd"
|
||||
path = "src/daemon.rs"
|
||||
|
||||
[dependencies]
|
||||
config-traits = { path = "../config-traits" }
|
||||
rog_anime = { path = "../rog-anime", features = ["dbus"] }
|
||||
rog_aura = { path = "../rog-aura", features = ["dbus"] }
|
||||
rog_platform = { path = "../rog-platform" }
|
||||
rog_profiles = { path = "../rog-profiles" }
|
||||
rog_dbus = { path = "../rog-dbus" }
|
||||
|
||||
async-trait.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
# cli and logging
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
zbus.workspace = true
|
||||
logind-zbus.workspace = true
|
||||
|
||||
# serialisation
|
||||
serde.workspace = true
|
||||
serde_derive.workspace = true
|
||||
|
||||
# Device control
|
||||
sysfs-class.workspace = true # used for backlight control and baord ID
|
||||
|
||||
concat-idents.workspace = true
|
||||
|
||||
systemd-zbus = "*"
|
||||
|
||||
[dev-dependencies]
|
||||
cargo-husky.workspace = true
|
||||
@@ -1,77 +0,0 @@
|
||||
use config_traits::{StdConfig, StdConfigLoad2};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "asusd.ron";
|
||||
|
||||
#[derive(Deserialize, Serialize, Default, Debug)]
|
||||
pub struct Config {
|
||||
/// Save charge limit for restoring on boot
|
||||
pub bat_charge_limit: u8,
|
||||
pub panel_od: bool,
|
||||
pub disable_nvidia_powerd_on_battery: bool,
|
||||
pub ac_command: String,
|
||||
pub bat_command: String,
|
||||
}
|
||||
|
||||
impl StdConfig for Config {
|
||||
fn new() -> Self {
|
||||
Config {
|
||||
bat_charge_limit: 100,
|
||||
panel_od: false,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: String::new(),
|
||||
bat_command: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad2<Config455, Config458> for Config {}
|
||||
|
||||
#[derive(Deserialize, Serialize, Default)]
|
||||
#[serde(default)]
|
||||
pub struct Config455 {
|
||||
/// Save charge limit for restoring on boot
|
||||
pub bat_charge_limit: u8,
|
||||
pub panel_od: bool,
|
||||
}
|
||||
|
||||
impl From<Config455> for Config {
|
||||
fn from(c: Config455) -> Self {
|
||||
Self {
|
||||
bat_charge_limit: c.bat_charge_limit,
|
||||
panel_od: c.panel_od,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: String::new(),
|
||||
bat_command: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Default)]
|
||||
pub struct Config458 {
|
||||
/// Save charge limit for restoring on boot
|
||||
pub bat_charge_limit: u8,
|
||||
pub panel_od: bool,
|
||||
pub ac_command: String,
|
||||
pub bat_command: String,
|
||||
}
|
||||
|
||||
impl From<Config458> for Config {
|
||||
fn from(c: Config458) -> Self {
|
||||
Self {
|
||||
bat_charge_limit: c.bat_charge_limit,
|
||||
panel_od: c.panel_od,
|
||||
disable_nvidia_powerd_on_battery: true,
|
||||
ac_command: c.ac_command,
|
||||
bat_command: c.bat_command,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad2};
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_anime::{ActionData, ActionLoader, AnimTime, AnimeType, Fade, Vec2};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "anime.ron";
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfigV341 {
|
||||
pub system: Option<ActionLoader>,
|
||||
pub boot: Option<ActionLoader>,
|
||||
pub suspend: Option<ActionLoader>,
|
||||
pub shutdown: Option<ActionLoader>,
|
||||
}
|
||||
|
||||
impl From<AnimeConfigV341> for AnimeConfig {
|
||||
fn from(c: AnimeConfigV341) -> AnimeConfig {
|
||||
AnimeConfig {
|
||||
system: if let Some(ani) = c.system {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
boot: if let Some(ani) = c.boot {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
wake: if let Some(ani) = c.suspend {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
shutdown: if let Some(ani) = c.shutdown.clone() {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
sleep: if let Some(ani) = c.shutdown.clone() {
|
||||
vec![ani]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfigV352 {
|
||||
pub system: Vec<ActionLoader>,
|
||||
pub boot: Vec<ActionLoader>,
|
||||
pub wake: Vec<ActionLoader>,
|
||||
pub shutdown: Vec<ActionLoader>,
|
||||
pub brightness: f32,
|
||||
}
|
||||
|
||||
impl From<AnimeConfigV352> for AnimeConfig {
|
||||
fn from(c: AnimeConfigV352) -> AnimeConfig {
|
||||
AnimeConfig {
|
||||
system: c.system,
|
||||
boot: c.boot,
|
||||
wake: c.wake,
|
||||
sleep: c.shutdown.clone(),
|
||||
shutdown: c.shutdown,
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
pub struct AnimeConfigV460 {
|
||||
pub system: Vec<ActionLoader>,
|
||||
pub boot: Vec<ActionLoader>,
|
||||
pub wake: Vec<ActionLoader>,
|
||||
pub sleep: Vec<ActionLoader>,
|
||||
pub shutdown: Vec<ActionLoader>,
|
||||
pub brightness: f32,
|
||||
}
|
||||
|
||||
impl From<AnimeConfigV460> for AnimeConfig {
|
||||
fn from(c: AnimeConfigV460) -> AnimeConfig {
|
||||
AnimeConfig {
|
||||
system: c.system,
|
||||
boot: c.boot,
|
||||
wake: c.wake,
|
||||
sleep: c.sleep,
|
||||
shutdown: c.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 sleep: Vec<ActionData>,
|
||||
pub shutdown: Vec<ActionData>,
|
||||
}
|
||||
|
||||
impl AnimeConfigCached {
|
||||
pub fn init_from_config(
|
||||
&mut self,
|
||||
config: &AnimeConfig,
|
||||
anime_type: AnimeType,
|
||||
) -> Result<(), AnimeError> {
|
||||
let mut sys = Vec::with_capacity(config.system.len());
|
||||
for ani in &config.system {
|
||||
sys.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.system = sys;
|
||||
|
||||
let mut boot = Vec::with_capacity(config.boot.len());
|
||||
for ani in &config.boot {
|
||||
boot.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.boot = boot;
|
||||
|
||||
let mut wake = Vec::with_capacity(config.wake.len());
|
||||
for ani in &config.wake {
|
||||
wake.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.wake = wake;
|
||||
|
||||
let mut sleep = Vec::with_capacity(config.sleep.len());
|
||||
for ani in &config.sleep {
|
||||
sleep.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.sleep = sleep;
|
||||
|
||||
let mut shutdown = Vec::with_capacity(config.shutdown.len());
|
||||
for ani in &config.shutdown {
|
||||
shutdown.push(ActionData::from_anime_action(anime_type, ani)?);
|
||||
}
|
||||
self.shutdown = shutdown;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Config for base system actions for the anime display
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct AnimeConfig {
|
||||
pub system: Vec<ActionLoader>,
|
||||
pub boot: Vec<ActionLoader>,
|
||||
pub wake: Vec<ActionLoader>,
|
||||
pub sleep: Vec<ActionLoader>,
|
||||
pub shutdown: Vec<ActionLoader>,
|
||||
pub brightness: f32,
|
||||
pub awake_enabled: bool,
|
||||
pub boot_anim_enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for AnimeConfig {
|
||||
fn default() -> Self {
|
||||
AnimeConfig {
|
||||
system: Vec::new(),
|
||||
boot: Vec::new(),
|
||||
wake: Vec::new(),
|
||||
sleep: Vec::new(),
|
||||
shutdown: Vec::new(),
|
||||
brightness: 1.0,
|
||||
awake_enabled: true,
|
||||
boot_anim_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfig for AnimeConfig {
|
||||
fn new() -> Self {
|
||||
Self::create_default()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad2<AnimeConfigV341, AnimeConfigV352> for AnimeConfig {}
|
||||
|
||||
impl AnimeConfig {
|
||||
// fn clamp_config_brightness(mut config: &mut AnimeConfig) {
|
||||
// if config.brightness < 0.0 || config.brightness > 1.0 {
|
||||
// warn!(
|
||||
// "Clamped brightness to [0.0 ; 1.0], was {}",
|
||||
// config.brightness
|
||||
// );
|
||||
// config.brightness = f32::max(0.0, f32::min(1.0, config.brightness));
|
||||
// }
|
||||
// }
|
||||
|
||||
fn create_default() -> Self {
|
||||
// create a default config here
|
||||
AnimeConfig {
|
||||
system: vec![],
|
||||
boot: vec![ActionLoader::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::Fade(Fade::new(
|
||||
Duration::from_secs(2),
|
||||
Some(Duration::from_secs(2)),
|
||||
Duration::from_secs(2),
|
||||
)),
|
||||
}],
|
||||
wake: vec![ActionLoader::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::Fade(Fade::new(
|
||||
Duration::from_secs(2),
|
||||
Some(Duration::from_secs(2)),
|
||||
Duration::from_secs(2),
|
||||
)),
|
||||
}],
|
||||
sleep: vec![ActionLoader::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-wait.gif".into(),
|
||||
scale: 0.9,
|
||||
angle: 0.0,
|
||||
translation: Vec2::new(3.0, 2.0),
|
||||
brightness: 1.0,
|
||||
time: AnimTime::Infinite,
|
||||
}],
|
||||
shutdown: vec![ActionLoader::ImageAnimation {
|
||||
file: "/usr/share/asusd/anime/custom/sonic-wait.gif".into(),
|
||||
scale: 0.9,
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
pub mod config;
|
||||
/// Implements `CtrlTask`, Reloadable, `ZbusRun`
|
||||
pub mod trait_impls;
|
||||
|
||||
use std::convert::TryFrom;
|
||||
use std::error::Error;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::thread::sleep;
|
||||
|
||||
use ::zbus::export::futures_util::lock::Mutex;
|
||||
use log::{error, info, warn};
|
||||
use rog_anime::error::AnimeError;
|
||||
use rog_anime::usb::{get_anime_type, pkt_for_flush, pkts_for_init};
|
||||
use rog_anime::{ActionData, AnimeDataBuffer, AnimePacketType, AnimeType};
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::supported::AnimeSupportedFunctions;
|
||||
use rog_platform::usb_raw::USBRaw;
|
||||
|
||||
use self::config::{AnimeConfig, AnimeConfigCached};
|
||||
use crate::error::RogError;
|
||||
use crate::GetSupported;
|
||||
|
||||
impl GetSupported for CtrlAnime {
|
||||
type A = AnimeSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
AnimeSupportedFunctions(HidRaw::new("193b").is_ok())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlAnime {
|
||||
node: USBRaw,
|
||||
anime_type: AnimeType,
|
||||
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>> {
|
||||
let node = USBRaw::new(0x193b)?;
|
||||
let anime_type = get_anime_type()?;
|
||||
|
||||
info!("Device has an AniMe Matrix display");
|
||||
let mut cache = AnimeConfigCached::default();
|
||||
cache.init_from_config(&config, anime_type)?;
|
||||
|
||||
let ctrl = CtrlAnime {
|
||||
node,
|
||||
anime_type,
|
||||
cache,
|
||||
config,
|
||||
thread_exit: Arc::new(AtomicBool::new(false)),
|
||||
thread_running: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
ctrl.do_initialization()?;
|
||||
|
||||
Ok(ctrl)
|
||||
}
|
||||
|
||||
// let device = CtrlAnime::get_device(0x0b05, 0x193b)?;
|
||||
|
||||
/// 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
|
||||
// TODO: turn this in to async task (maybe? COuld still risk blocking main
|
||||
// thread)
|
||||
std::thread::Builder::new()
|
||||
.name("AniMe system thread start".into())
|
||||
.spawn(move || {
|
||||
info!("AniMe new 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;
|
||||
let anime_type;
|
||||
loop {
|
||||
if let Some(lock) = inner.try_lock() {
|
||||
thread_exit = lock.thread_exit.clone();
|
||||
thread_running = lock.thread_running.clone();
|
||||
anime_type = lock.anime_type;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 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.
|
||||
while thread_running.load(Ordering::SeqCst) {
|
||||
// Make any running loop exit first
|
||||
thread_exit.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
info!("AniMe no previous system thread running (now)");
|
||||
thread_exit.store(false, Ordering::SeqCst);
|
||||
thread_running.store(true, Ordering::SeqCst);
|
||||
'main: loop {
|
||||
for action in &actions {
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
match action {
|
||||
ActionData::Animation(frames) => {
|
||||
rog_anime::run_animation(frames, &|frame| {
|
||||
if thread_exit.load(Ordering::Acquire) {
|
||||
info!("rog-anime: animation sub-loop was asked to exit");
|
||||
return Ok(true); // Do safe exit
|
||||
}
|
||||
inner
|
||||
.try_lock()
|
||||
.map(|lock| {
|
||||
lock.write_data_buffer(frame)
|
||||
.map_err(|err| {
|
||||
warn!(
|
||||
"rog_anime::run_animation:callback {}",
|
||||
err
|
||||
);
|
||||
})
|
||||
.ok();
|
||||
false // Don't exit yet
|
||||
})
|
||||
.map_or_else(
|
||||
|| {
|
||||
warn!("rog_anime::run_animation:callback failed");
|
||||
Err(AnimeError::NoFrames)
|
||||
},
|
||||
Ok,
|
||||
)
|
||||
});
|
||||
if thread_exit.load(Ordering::Acquire) {
|
||||
info!("rog-anime: sub-loop exited and main loop exiting now");
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
ActionData::Image(image) => {
|
||||
once = false;
|
||||
if let Some(lock) = inner.try_lock() {
|
||||
lock.write_data_buffer(image.as_ref().clone())
|
||||
.map_err(|e| error!("{}", e))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
ActionData::Pause(duration) => sleep(*duration),
|
||||
ActionData::AudioEq
|
||||
| ActionData::SystemInfo
|
||||
| ActionData::TimeDate
|
||||
| ActionData::Matrix => {}
|
||||
}
|
||||
}
|
||||
if thread_exit.load(Ordering::SeqCst) {
|
||||
break 'main;
|
||||
}
|
||||
if once || actions.is_empty() {
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
// Clear the display on exit
|
||||
if let Some(lock) = inner.try_lock() {
|
||||
if let Ok(data) =
|
||||
AnimeDataBuffer::from_vec(anime_type, vec![0u8; anime_type.data_length()])
|
||||
.map_err(|e| error!("{}", e))
|
||||
{
|
||||
lock.write_data_buffer(data)
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
// Loop ended, set the atmonics
|
||||
thread_running.store(false, Ordering::SeqCst);
|
||||
info!("AniMe system thread exited");
|
||||
})
|
||||
.map(|err| info!("AniMe system thread: {:?}", err))
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// 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) -> Result<(), RogError> {
|
||||
for led in buffer.data_mut().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::try_from(buffer)?;
|
||||
for row in &data {
|
||||
self.node.write_bytes(row)?;
|
||||
}
|
||||
self.node.write_bytes(&pkt_for_flush())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn do_initialization(&self) -> Result<(), RogError> {
|
||||
let pkts = pkts_for_init();
|
||||
self.node.write_bytes(&pkts[0])?;
|
||||
self.node.write_bytes(&pkts[1])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config_traits::StdConfig;
|
||||
use log::warn;
|
||||
use rog_anime::usb::{pkt_for_apply, pkt_for_set_boot, pkt_for_set_on};
|
||||
use rog_anime::{AnimeDataBuffer, AnimePowerStates};
|
||||
use zbus::export::futures_util::lock::Mutex;
|
||||
use zbus::{dbus_interface, Connection, SignalContext};
|
||||
|
||||
use super::CtrlAnime;
|
||||
use crate::error::RogError;
|
||||
|
||||
pub(super) const ZBUS_PATH: &str = "/org/asuslinux/Anime";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CtrlAnimeZbus(pub Arc<Mutex<CtrlAnime>>);
|
||||
|
||||
/// The struct with the main dbus methods requires this trait
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for CtrlAnimeZbus {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
async fn write(&self, input: AnimeDataBuffer) -> zbus::fdo::Result<()> {
|
||||
let lock = self.0.lock().await;
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
lock.write_data_buffer(input).map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
err
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set the global AniMe brightness
|
||||
async fn set_brightness(&self, bright: f32) {
|
||||
let mut lock = self.0.lock().await;
|
||||
let mut bright = bright;
|
||||
if bright < 0.0 {
|
||||
bright = 0.0;
|
||||
} else if bright > 1.0 {
|
||||
bright = 1.0;
|
||||
}
|
||||
lock.config.brightness = bright;
|
||||
lock.config.write();
|
||||
}
|
||||
|
||||
/// Set whether the AniMe is displaying images/data
|
||||
async fn set_on_off(&self, #[zbus(signal_context)] ctxt: SignalContext<'_>, status: bool) {
|
||||
let mut lock = self.0.lock().await;
|
||||
lock.node
|
||||
.write_bytes(&pkt_for_set_on(status))
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
lock.config.awake_enabled = status;
|
||||
lock.config.write();
|
||||
|
||||
Self::notify_power_states(
|
||||
&ctxt,
|
||||
AnimePowerStates {
|
||||
brightness: lock.config.brightness.floor() as u8,
|
||||
enabled: lock.config.awake_enabled,
|
||||
boot_anim_enabled: lock.config.boot_anim_enabled,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// Set whether the AniMe will show boot, suspend, or off animations
|
||||
async fn set_boot_on_off(&self, #[zbus(signal_context)] ctxt: SignalContext<'_>, on: bool) {
|
||||
let mut lock = self.0.lock().await;
|
||||
lock.node
|
||||
.write_bytes(&pkt_for_set_boot(on))
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
lock.node
|
||||
.write_bytes(&pkt_for_apply())
|
||||
.map_err(|err| {
|
||||
warn!("rog_anime::run_animation:callback {}", err);
|
||||
})
|
||||
.ok();
|
||||
lock.config.boot_anim_enabled = on;
|
||||
lock.config.write();
|
||||
|
||||
Self::notify_power_states(
|
||||
&ctxt,
|
||||
AnimePowerStates {
|
||||
brightness: lock.config.brightness.floor() as u8,
|
||||
enabled: lock.config.awake_enabled,
|
||||
boot_anim_enabled: lock.config.boot_anim_enabled,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// The main loop is the base system set action if the user isn't running
|
||||
/// the user daemon
|
||||
async fn run_main_loop(&self, start: bool) {
|
||||
if start {
|
||||
let lock = self.0.lock().await;
|
||||
lock.thread_exit.store(true, Ordering::SeqCst);
|
||||
CtrlAnime::run_thread(self.0.clone(), lock.cache.system.clone(), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get status of if the AniMe LEDs are on/displaying while system is awake
|
||||
#[dbus_interface(property)]
|
||||
async fn awake_enabled(&self) -> bool {
|
||||
let lock = self.0.lock().await;
|
||||
lock.config.awake_enabled
|
||||
}
|
||||
|
||||
/// Get the status of if factory system-status animations are enabled
|
||||
#[dbus_interface(property)]
|
||||
async fn boot_enabled(&self) -> bool {
|
||||
let lock = self.0.lock().await;
|
||||
lock.config.boot_anim_enabled
|
||||
}
|
||||
|
||||
/// Notify listeners of the status of AniMe LED power and factory
|
||||
/// system-status animations
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_power_states(
|
||||
ctxt: &SignalContext<'_>,
|
||||
data: AnimePowerStates,
|
||||
) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::CtrlTask for CtrlAnimeZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
|
||||
let inner1 = self.0.clone();
|
||||
let inner2 = self.0.clone();
|
||||
let inner3 = self.0.clone();
|
||||
let inner4 = self.0.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move || {
|
||||
// on_sleep
|
||||
let inner1 = inner1.clone();
|
||||
async move {
|
||||
let lock = inner1.lock().await;
|
||||
CtrlAnime::run_thread(inner1.clone(), lock.cache.sleep.clone(), true);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
// on_wake
|
||||
let inner2 = inner2.clone();
|
||||
async move {
|
||||
let lock = inner2.lock().await;
|
||||
CtrlAnime::run_thread(inner2.clone(), lock.cache.wake.clone(), true);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
// on_shutdown
|
||||
let inner3 = inner3.clone();
|
||||
async move {
|
||||
let lock = inner3.lock().await;
|
||||
CtrlAnime::run_thread(inner3.clone(), lock.cache.shutdown.clone(), true);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
// on_boot
|
||||
let inner4 = inner4.clone();
|
||||
async move {
|
||||
let lock = inner4.lock().await;
|
||||
CtrlAnime::run_thread(inner4.clone(), lock.cache.boot.clone(), true);
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Reloadable for CtrlAnimeZbus {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Some(lock) = self.0.try_lock() {
|
||||
lock.node
|
||||
.write_bytes(&pkt_for_set_on(lock.config.awake_enabled))?;
|
||||
lock.node.write_bytes(&pkt_for_apply())?;
|
||||
lock.node
|
||||
.write_bytes(&pkt_for_set_boot(lock.config.boot_anim_enabled))?;
|
||||
lock.node.write_bytes(&pkt_for_apply())?;
|
||||
|
||||
let action = lock.cache.boot.clone();
|
||||
CtrlAnime::run_thread(self.0.clone(), action, true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,353 +0,0 @@
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_aura::aura_detection::LaptopLedData;
|
||||
use rog_aura::usb::{AuraDevRog1, AuraDevRog2, AuraDevTuf, AuraDevice, AuraPowerDev};
|
||||
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Direction, LedBrightness, Speed, GRADIENT};
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
const CONFIG_FILE: &str = "aura.ron";
|
||||
|
||||
/// Enable/disable LED control in various states such as
|
||||
/// when the device is awake, suspended, shutting down or
|
||||
/// booting.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum AuraPowerConfig {
|
||||
AuraDevTuf(HashSet<AuraDevTuf>),
|
||||
AuraDevRog1(HashSet<AuraDevRog1>),
|
||||
AuraDevRog2(HashSet<AuraDevRog2>),
|
||||
}
|
||||
|
||||
impl AuraPowerConfig {
|
||||
/// Invalid for TUF laptops
|
||||
pub fn to_bytes(control: &Self) -> [u8; 3] {
|
||||
match control {
|
||||
AuraPowerConfig::AuraDevTuf(_) => [0, 0, 0],
|
||||
AuraPowerConfig::AuraDevRog1(c) => {
|
||||
let c: Vec<AuraDevRog1> = c.iter().copied().collect();
|
||||
AuraDevRog1::to_bytes(&c)
|
||||
}
|
||||
AuraPowerConfig::AuraDevRog2(c) => {
|
||||
let c: Vec<AuraDevRog2> = c.iter().copied().collect();
|
||||
AuraDevRog2::to_bytes(&c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_tuf_bool_array(control: &Self) -> Option<[bool; 5]> {
|
||||
if let Self::AuraDevTuf(c) = control {
|
||||
return Some([
|
||||
true,
|
||||
c.contains(&AuraDevTuf::Boot),
|
||||
c.contains(&AuraDevTuf::Awake),
|
||||
c.contains(&AuraDevTuf::Sleep),
|
||||
c.contains(&AuraDevTuf::Keyboard),
|
||||
]);
|
||||
}
|
||||
|
||||
if let Self::AuraDevRog1(c) = control {
|
||||
return Some([
|
||||
true,
|
||||
c.contains(&AuraDevRog1::Boot),
|
||||
c.contains(&AuraDevRog1::Awake),
|
||||
c.contains(&AuraDevRog1::Sleep),
|
||||
c.contains(&AuraDevRog1::Keyboard),
|
||||
]);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
pub fn set_tuf(&mut self, power: AuraDevTuf, on: bool) {
|
||||
if let Self::AuraDevTuf(p) = self {
|
||||
if on {
|
||||
p.insert(power);
|
||||
} else {
|
||||
p.remove(&power);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_0x1866(&mut self, power: AuraDevRog1, on: bool) {
|
||||
if let Self::AuraDevRog1(p) = self {
|
||||
if on {
|
||||
p.insert(power);
|
||||
} else {
|
||||
p.remove(&power);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_0x19b6(&mut self, power: AuraDevRog2, on: bool) {
|
||||
if let Self::AuraDevRog2(p) = self {
|
||||
if on {
|
||||
p.insert(power);
|
||||
} else {
|
||||
p.remove(&power);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&AuraPowerConfig> for AuraPowerDev {
|
||||
fn from(config: &AuraPowerConfig) -> Self {
|
||||
match config {
|
||||
AuraPowerConfig::AuraDevTuf(d) => AuraPowerDev {
|
||||
tuf: d.iter().copied().collect(),
|
||||
x1866: vec![],
|
||||
x19b6: vec![],
|
||||
},
|
||||
AuraPowerConfig::AuraDevRog1(d) => AuraPowerDev {
|
||||
tuf: vec![],
|
||||
x1866: d.iter().copied().collect(),
|
||||
x19b6: vec![],
|
||||
},
|
||||
AuraPowerConfig::AuraDevRog2(d) => AuraPowerDev {
|
||||
tuf: vec![],
|
||||
x1866: vec![],
|
||||
x19b6: d.iter().copied().collect(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Clone)]
|
||||
// #[serde(default)]
|
||||
pub struct AuraConfig {
|
||||
pub brightness: LedBrightness,
|
||||
pub current_mode: AuraModeNum,
|
||||
pub builtins: BTreeMap<AuraModeNum, AuraEffect>,
|
||||
pub multizone: Option<BTreeMap<AuraModeNum, Vec<AuraEffect>>>,
|
||||
pub multizone_on: bool,
|
||||
pub enabled: AuraPowerConfig,
|
||||
}
|
||||
|
||||
impl StdConfig for AuraConfig {
|
||||
fn new() -> Self {
|
||||
// Self::create_default(AuraDevice::X19b6, &LaptopLedData::get_data())
|
||||
panic!("AuraConfig::new() should not be used, use AuraConfig::create_default() instead");
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(crate::CONFIG_PATH_BASE)
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for AuraConfig {}
|
||||
|
||||
impl AuraConfig {
|
||||
pub fn create_default(prod_id: AuraDevice, support_data: &LaptopLedData) -> Self {
|
||||
// create a default config here
|
||||
let enabled = if prod_id == AuraDevice::X19b6 {
|
||||
AuraPowerConfig::AuraDevRog2(HashSet::from([
|
||||
AuraDevRog2::BootLogo,
|
||||
AuraDevRog2::BootKeyb,
|
||||
AuraDevRog2::SleepLogo,
|
||||
AuraDevRog2::SleepKeyb,
|
||||
AuraDevRog2::AwakeLogo,
|
||||
AuraDevRog2::AwakeKeyb,
|
||||
AuraDevRog2::ShutdownLogo,
|
||||
AuraDevRog2::ShutdownKeyb,
|
||||
AuraDevRog2::BootBar,
|
||||
AuraDevRog2::AwakeBar,
|
||||
AuraDevRog2::SleepBar,
|
||||
AuraDevRog2::ShutdownBar,
|
||||
]))
|
||||
} else if prod_id == AuraDevice::Tuf {
|
||||
AuraPowerConfig::AuraDevTuf(HashSet::from([
|
||||
AuraDevTuf::Awake,
|
||||
AuraDevTuf::Boot,
|
||||
AuraDevTuf::Sleep,
|
||||
AuraDevTuf::Keyboard,
|
||||
]))
|
||||
} else {
|
||||
AuraPowerConfig::AuraDevRog1(HashSet::from([
|
||||
AuraDevRog1::Awake,
|
||||
AuraDevRog1::Boot,
|
||||
AuraDevRog1::Sleep,
|
||||
AuraDevRog1::Keyboard,
|
||||
AuraDevRog1::Lightbar,
|
||||
]))
|
||||
};
|
||||
let mut config = AuraConfig {
|
||||
brightness: LedBrightness::Med,
|
||||
current_mode: AuraModeNum::Static,
|
||||
builtins: BTreeMap::new(),
|
||||
multizone: None,
|
||||
multizone_on: false,
|
||||
enabled,
|
||||
};
|
||||
|
||||
for n in &support_data.basic_modes {
|
||||
config
|
||||
.builtins
|
||||
.insert(*n, AuraEffect::default_with_mode(*n));
|
||||
|
||||
if !support_data.basic_zones.is_empty() {
|
||||
let mut default = vec![];
|
||||
for (i, tmp) in support_data.basic_zones.iter().enumerate() {
|
||||
default.push(AuraEffect {
|
||||
mode: *n,
|
||||
zone: *tmp,
|
||||
colour1: *GRADIENT.get(i).unwrap_or(&GRADIENT[0]),
|
||||
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Left,
|
||||
});
|
||||
}
|
||||
if let Some(m) = config.multizone.as_mut() {
|
||||
m.insert(*n, default);
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(*n, default);
|
||||
config.multizone = Some(tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
/// Set the mode data, current mode, and if multizone enabled.
|
||||
///
|
||||
/// Multipurpose, will accept `AuraEffect` with zones and put in the correct
|
||||
/// store.
|
||||
pub fn set_builtin(&mut self, effect: AuraEffect) {
|
||||
self.current_mode = effect.mode;
|
||||
if effect.zone() == AuraZone::None {
|
||||
self.builtins.insert(*effect.mode(), effect);
|
||||
self.multizone_on = false;
|
||||
} else {
|
||||
if let Some(multi) = self.multizone.as_mut() {
|
||||
if let Some(fx) = multi.get_mut(effect.mode()) {
|
||||
for fx in fx.iter_mut() {
|
||||
if fx.zone == effect.zone {
|
||||
*fx = effect;
|
||||
return;
|
||||
}
|
||||
}
|
||||
fx.push(effect);
|
||||
} else {
|
||||
multi.insert(*effect.mode(), vec![effect]);
|
||||
}
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(*effect.mode(), vec![effect]);
|
||||
self.multizone = Some(tmp);
|
||||
}
|
||||
self.multizone_on = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_multizone(&self, aura_type: AuraModeNum) -> Option<&[AuraEffect]> {
|
||||
if let Some(multi) = &self.multizone {
|
||||
return multi.get(&aura_type).map(|v| v.as_slice());
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rog_aura::aura_detection::LaptopLedData;
|
||||
use rog_aura::usb::AuraDevice;
|
||||
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Colour};
|
||||
|
||||
use super::AuraConfig;
|
||||
|
||||
#[test]
|
||||
fn set_multizone_4key_config() {
|
||||
let mut config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour(0xff, 0x00, 0xff),
|
||||
zone: AuraZone::Key1,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
assert!(config.multizone.is_some());
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour(0x00, 0xff, 0xff),
|
||||
zone: AuraZone::Key2,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour(0xff, 0xff, 0x00),
|
||||
zone: AuraZone::Key3,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
colour1: Colour(0x00, 0xff, 0x00),
|
||||
zone: AuraZone::Key4,
|
||||
..Default::default()
|
||||
};
|
||||
let effect_clone = effect.clone();
|
||||
config.set_builtin(effect);
|
||||
// This should replace existing
|
||||
config.set_builtin(effect_clone);
|
||||
|
||||
let res = config.multizone.unwrap();
|
||||
let sta = res.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(sta.len(), 4);
|
||||
assert_eq!(sta[0].colour1, Colour(0xff, 0x00, 0xff));
|
||||
assert_eq!(sta[1].colour1, Colour(0x00, 0xff, 0xff));
|
||||
assert_eq!(sta[2].colour1, Colour(0xff, 0xff, 0x00));
|
||||
assert_eq!(sta[3].colour1, Colour(0x00, 0xff, 0x00));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_multizone_multimode_config() {
|
||||
let mut config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key1,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
assert!(config.multizone.is_some());
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key2,
|
||||
mode: AuraModeNum::Breathe,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key3,
|
||||
mode: AuraModeNum::Comet,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let effect = AuraEffect {
|
||||
zone: AuraZone::Key4,
|
||||
mode: AuraModeNum::Pulse,
|
||||
..Default::default()
|
||||
};
|
||||
config.set_builtin(effect);
|
||||
|
||||
let res = config.multizone.unwrap();
|
||||
let sta = res.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Breathe).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Comet).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
|
||||
let sta = res.get(&AuraModeNum::Pulse).unwrap();
|
||||
assert_eq!(sta.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,528 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use log::{info, warn};
|
||||
use rog_aura::advanced::{LedUsbPackets, UsbPackets};
|
||||
use rog_aura::aura_detection::{LaptopLedData, ASUS_KEYBOARD_DEVICES};
|
||||
use rog_aura::usb::{AuraDevice, LED_APPLY, LED_SET};
|
||||
use rog_aura::{AuraEffect, AuraZone, Direction, LedBrightness, Speed, GRADIENT, LED_MSG_LEN};
|
||||
use rog_platform::hid_raw::HidRaw;
|
||||
use rog_platform::keyboard_led::KeyboardLed;
|
||||
use rog_platform::supported::LedSupportedFunctions;
|
||||
|
||||
use super::config::{AuraConfig, AuraPowerConfig};
|
||||
use crate::error::RogError;
|
||||
use crate::GetSupported;
|
||||
|
||||
impl GetSupported for CtrlKbdLed {
|
||||
type A = LedSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
// let mode = <&str>::from(&<AuraModes>::from(*mode));
|
||||
let laptop = LaptopLedData::get_data();
|
||||
let stock_led_modes = laptop.basic_modes;
|
||||
let multizone_led_mode = laptop.basic_zones;
|
||||
let advanced_type = laptop.advanced_type;
|
||||
|
||||
let mut prod_id = AuraDevice::Unknown;
|
||||
for prod in ASUS_KEYBOARD_DEVICES {
|
||||
if HidRaw::new(prod.into()).is_ok() {
|
||||
prod_id = prod;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let rgb = KeyboardLed::new();
|
||||
if let Ok(p) = rgb.as_ref() {
|
||||
if p.has_kbd_rgb_mode() {
|
||||
prod_id = AuraDevice::Tuf;
|
||||
}
|
||||
}
|
||||
|
||||
LedSupportedFunctions {
|
||||
dev_id: prod_id,
|
||||
brightness: rgb.is_ok(),
|
||||
basic_modes: stock_led_modes,
|
||||
basic_zones: multizone_led_mode,
|
||||
advanced_type: advanced_type.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, PartialOrd)]
|
||||
pub enum LEDNode {
|
||||
KbdLed(KeyboardLed),
|
||||
Rog(HidRaw),
|
||||
None,
|
||||
}
|
||||
|
||||
pub struct CtrlKbdLed {
|
||||
// TODO: config stores the keyboard type as an AuraPower, use or update this
|
||||
pub led_prod: AuraDevice,
|
||||
pub led_node: LEDNode,
|
||||
pub kd_brightness: KeyboardLed,
|
||||
pub supported_modes: LaptopLedData,
|
||||
pub flip_effect_write: bool,
|
||||
pub per_key_mode_active: bool,
|
||||
pub config: AuraConfig,
|
||||
}
|
||||
|
||||
impl CtrlKbdLed {
|
||||
pub fn new(supported_modes: LaptopLedData) -> Result<Self, RogError> {
|
||||
let mut led_prod = AuraDevice::Unknown;
|
||||
let mut usb_node = None;
|
||||
for prod in ASUS_KEYBOARD_DEVICES {
|
||||
match HidRaw::new(prod.into()) {
|
||||
Ok(node) => {
|
||||
led_prod = prod;
|
||||
usb_node = Some(node);
|
||||
info!(
|
||||
"Looked for keyboard controller 0x{}: Found",
|
||||
<&str>::from(prod)
|
||||
);
|
||||
break;
|
||||
}
|
||||
Err(err) => info!(
|
||||
"Looked for keyboard controller 0x{}: {err}",
|
||||
<&str>::from(prod)
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
let rgb_led = KeyboardLed::new()?;
|
||||
|
||||
if usb_node.is_none() && !rgb_led.has_kbd_rgb_mode() {
|
||||
let dmi = sysfs_class::DmiId::default();
|
||||
if let Ok(prod_family) = dmi.product_family() {
|
||||
if prod_family.contains("TUF") {
|
||||
warn!(
|
||||
"kbd_rgb_mode was not found in the /sys/. You require a minimum 6.1 \
|
||||
kernel and a supported TUF laptop"
|
||||
);
|
||||
}
|
||||
}
|
||||
return Err(RogError::NoAuraKeyboard);
|
||||
}
|
||||
|
||||
let led_node = if let Some(rog) = usb_node {
|
||||
info!("Found ROG USB keyboard");
|
||||
LEDNode::Rog(rog)
|
||||
} else if rgb_led.has_kbd_rgb_mode() {
|
||||
info!("Found TUF keyboard");
|
||||
LEDNode::KbdLed(rgb_led.clone())
|
||||
} else {
|
||||
LEDNode::None
|
||||
};
|
||||
|
||||
let config_init = AuraConfig::create_default(led_prod, &supported_modes);
|
||||
let mut config = config_init.clone().load();
|
||||
// Do updates of supported modes if required
|
||||
for mode in &config_init.builtins {
|
||||
if !config.builtins.contains_key(mode.0) {
|
||||
config.builtins.insert(*mode.0, mode.1.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let ctrl = CtrlKbdLed {
|
||||
led_prod,
|
||||
led_node, // on TUF this is the same as rgb_led / kd_brightness
|
||||
kd_brightness: rgb_led, // If was none then we already returned above
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
per_key_mode_active: false,
|
||||
config,
|
||||
};
|
||||
Ok(ctrl)
|
||||
}
|
||||
|
||||
pub(super) fn get_brightness(&self) -> Result<u8, RogError> {
|
||||
self.kd_brightness
|
||||
.get_brightness()
|
||||
.map_err(RogError::Platform)
|
||||
}
|
||||
|
||||
pub(super) fn set_brightness(&self, brightness: LedBrightness) -> Result<(), RogError> {
|
||||
self.kd_brightness
|
||||
.set_brightness(brightness as u8)
|
||||
.map_err(RogError::Platform)
|
||||
}
|
||||
|
||||
pub fn next_brightness(&mut self) -> Result<(), RogError> {
|
||||
let mut bright = (self.config.brightness as u32) + 1;
|
||||
if bright > 3 {
|
||||
bright = 0;
|
||||
}
|
||||
self.config.brightness = <LedBrightness>::from(bright);
|
||||
self.config.write();
|
||||
self.set_brightness(self.config.brightness)
|
||||
}
|
||||
|
||||
pub fn prev_brightness(&mut self) -> Result<(), RogError> {
|
||||
let mut bright = self.config.brightness as u32;
|
||||
if bright == 0 {
|
||||
bright = 3;
|
||||
} else {
|
||||
bright -= 1;
|
||||
}
|
||||
self.config.brightness = <LedBrightness>::from(bright);
|
||||
self.config.write();
|
||||
self.set_brightness(self.config.brightness)
|
||||
}
|
||||
|
||||
/// Set combination state for boot animation/sleep animation/all leds/keys
|
||||
/// leds/side leds LED active
|
||||
pub(super) fn set_power_states(&mut self) -> Result<(), RogError> {
|
||||
if let LEDNode::KbdLed(platform) = &mut self.led_node {
|
||||
if let Some(pwr) = AuraPowerConfig::to_tuf_bool_array(&self.config.enabled) {
|
||||
let buf = [1, pwr[1] as u8, pwr[2] as u8, pwr[3] as u8, pwr[4] as u8];
|
||||
platform.set_kbd_rgb_state(&buf)?;
|
||||
}
|
||||
} else if let LEDNode::Rog(hid_raw) = &self.led_node {
|
||||
let bytes = AuraPowerConfig::to_bytes(&self.config.enabled);
|
||||
let message = [0x5d, 0xbd, 0x01, bytes[0], bytes[1], bytes[2]];
|
||||
|
||||
hid_raw.write_bytes(&message)?;
|
||||
hid_raw.write_bytes(&LED_SET)?;
|
||||
// Changes won't persist unless apply is set
|
||||
hid_raw.write_bytes(&LED_APPLY)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set an Aura effect if the effect mode or zone is supported.
|
||||
///
|
||||
/// On success the aura config file is read to refresh cached values, then
|
||||
/// the effect is stored and config written to disk.
|
||||
pub(crate) fn set_effect(&mut self, effect: AuraEffect) -> Result<(), RogError> {
|
||||
if !self.supported_modes.basic_modes.contains(&effect.mode)
|
||||
|| effect.zone != AuraZone::None
|
||||
&& !self.supported_modes.basic_zones.contains(&effect.zone)
|
||||
{
|
||||
return Err(RogError::AuraEffectNotSupported);
|
||||
}
|
||||
|
||||
self.write_mode(&effect)?;
|
||||
self.config.read(); // refresh config if successful
|
||||
self.config.set_builtin(effect);
|
||||
self.config.write();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write an effect block. This is for per-key, but can be repurposed to
|
||||
/// write the raw factory mode packets - when doing this it is expected that
|
||||
/// only the first `Vec` (`effect[0]`) is valid.
|
||||
pub fn write_effect_block(&mut self, effect: &UsbPackets) -> Result<(), RogError> {
|
||||
let pkt_type = effect[0][1];
|
||||
const PER_KEY_TYPE: u8 = 0xbc;
|
||||
|
||||
if pkt_type != PER_KEY_TYPE {
|
||||
self.per_key_mode_active = false;
|
||||
if let LEDNode::Rog(hid_raw) = &self.led_node {
|
||||
hid_raw.write_bytes(&effect[0])?;
|
||||
hid_raw.write_bytes(&LED_SET)?;
|
||||
// hid_raw.write_bytes(&LED_APPLY)?;
|
||||
}
|
||||
} else {
|
||||
if !self.per_key_mode_active {
|
||||
if let LEDNode::Rog(hid_raw) = &self.led_node {
|
||||
let init = LedUsbPackets::get_init_msg();
|
||||
hid_raw.write_bytes(&init)?;
|
||||
}
|
||||
self.per_key_mode_active = true;
|
||||
}
|
||||
if let LEDNode::Rog(hid_raw) = &self.led_node {
|
||||
for row in effect.iter() {
|
||||
hid_raw.write_bytes(row)?;
|
||||
}
|
||||
} else if let LEDNode::KbdLed(tuf) = &self.led_node {
|
||||
for row in effect.iter() {
|
||||
let r = row[9];
|
||||
let g = row[10];
|
||||
let b = row[11];
|
||||
tuf.set_kbd_rgb_mode(&[0, 0, r, g, b, 0])?;
|
||||
}
|
||||
}
|
||||
self.flip_effect_write = !self.flip_effect_write;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn toggle_mode(&mut self, reverse: bool) -> Result<(), RogError> {
|
||||
let current = self.config.current_mode;
|
||||
if let Some(idx) = self
|
||||
.supported_modes
|
||||
.basic_modes
|
||||
.iter()
|
||||
.position(|v| *v == current)
|
||||
{
|
||||
let mut idx = idx;
|
||||
// goes past end of array
|
||||
if reverse {
|
||||
if idx == 0 {
|
||||
idx = self.supported_modes.basic_modes.len() - 1;
|
||||
} else {
|
||||
idx -= 1;
|
||||
}
|
||||
} else {
|
||||
idx += 1;
|
||||
if idx == self.supported_modes.basic_modes.len() {
|
||||
idx = 0;
|
||||
}
|
||||
}
|
||||
let next = self.supported_modes.basic_modes[idx];
|
||||
|
||||
self.config.read();
|
||||
// if self.config.builtins.contains_key(&next) {
|
||||
self.config.current_mode = next;
|
||||
self.write_current_config_mode()?;
|
||||
// }
|
||||
self.config.write();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_mode(&mut self, mode: &AuraEffect) -> Result<(), RogError> {
|
||||
if let LEDNode::KbdLed(platform) = &self.led_node {
|
||||
let buf = [
|
||||
1,
|
||||
mode.mode as u8,
|
||||
mode.colour1.0,
|
||||
mode.colour1.1,
|
||||
mode.colour1.2,
|
||||
mode.speed as u8,
|
||||
];
|
||||
platform.set_kbd_rgb_mode(&buf)?;
|
||||
} else if let LEDNode::Rog(hid_raw) = &self.led_node {
|
||||
let bytes: [u8; LED_MSG_LEN] = mode.into();
|
||||
hid_raw.write_bytes(&bytes)?;
|
||||
hid_raw.write_bytes(&LED_SET)?;
|
||||
// Changes won't persist unless apply is set
|
||||
hid_raw.write_bytes(&LED_APPLY)?;
|
||||
} else {
|
||||
return Err(RogError::NoAuraKeyboard);
|
||||
}
|
||||
self.per_key_mode_active = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn write_current_config_mode(&mut self) -> Result<(), RogError> {
|
||||
if self.config.multizone_on {
|
||||
let mode = self.config.current_mode;
|
||||
let mut create = false;
|
||||
// There is no multizone config for this mode so create one here
|
||||
// using the colours of rainbow if it exists, or first available
|
||||
// mode, or random
|
||||
if self.config.multizone.is_none() {
|
||||
create = true;
|
||||
} else if let Some(multizones) = self.config.multizone.as_ref() {
|
||||
if !multizones.contains_key(&mode) {
|
||||
create = true;
|
||||
}
|
||||
}
|
||||
if create {
|
||||
info!("No user-set config for zone founding, attempting a default");
|
||||
self.create_multizone_default()?;
|
||||
}
|
||||
|
||||
if let Some(multizones) = self.config.multizone.as_mut() {
|
||||
if let Some(set) = multizones.get(&mode) {
|
||||
for mode in set.clone() {
|
||||
self.write_mode(&mode)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mode = self.config.current_mode;
|
||||
if let Some(effect) = self.config.builtins.get(&mode).cloned() {
|
||||
self.write_mode(&effect)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create a default for the `current_mode` if multizone and no config
|
||||
/// exists.
|
||||
fn create_multizone_default(&mut self) -> Result<(), RogError> {
|
||||
let mut default = vec![];
|
||||
for (i, tmp) in self.supported_modes.basic_zones.iter().enumerate() {
|
||||
default.push(AuraEffect {
|
||||
mode: self.config.current_mode,
|
||||
zone: *tmp,
|
||||
colour1: *GRADIENT.get(i).unwrap_or(&GRADIENT[0]),
|
||||
colour2: *GRADIENT.get(GRADIENT.len() - i).unwrap_or(&GRADIENT[6]),
|
||||
speed: Speed::Med,
|
||||
direction: Direction::Left,
|
||||
});
|
||||
}
|
||||
if default.is_empty() {
|
||||
return Err(RogError::AuraEffectNotSupported);
|
||||
}
|
||||
|
||||
if let Some(multizones) = self.config.multizone.as_mut() {
|
||||
multizones.insert(self.config.current_mode, default);
|
||||
} else {
|
||||
let mut tmp = BTreeMap::new();
|
||||
tmp.insert(self.config.current_mode, default);
|
||||
self.config.multizone = Some(tmp);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rog_aura::aura_detection::LaptopLedData;
|
||||
use rog_aura::usb::AuraDevice;
|
||||
use rog_aura::{AuraEffect, AuraModeNum, AuraZone, Colour};
|
||||
use rog_platform::keyboard_led::KeyboardLed;
|
||||
|
||||
use super::CtrlKbdLed;
|
||||
use crate::ctrl_aura::config::AuraConfig;
|
||||
use crate::ctrl_aura::controller::LEDNode;
|
||||
|
||||
#[test]
|
||||
// #[ignore = "Must be manually run due to detection stage"]
|
||||
fn check_set_mode_errors() {
|
||||
// Checking to ensure set_mode errors when unsupported modes are tried
|
||||
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
|
||||
let supported_modes = LaptopLedData {
|
||||
board_name: String::new(),
|
||||
layout_name: "ga401".to_owned(),
|
||||
basic_modes: vec![AuraModeNum::Static],
|
||||
basic_zones: vec![],
|
||||
advanced_type: rog_aura::AdvancedAuraType::None,
|
||||
};
|
||||
let mut controller = CtrlKbdLed {
|
||||
led_prod: AuraDevice::X19b6,
|
||||
led_node: LEDNode::None,
|
||||
kd_brightness: KeyboardLed::default(),
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
per_key_mode_active: false,
|
||||
config,
|
||||
};
|
||||
|
||||
let mut effect = AuraEffect {
|
||||
colour1: Colour(0xff, 0x00, 0xff),
|
||||
zone: AuraZone::None,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// This error comes from write_bytes because we don't have a keyboard node
|
||||
// stored
|
||||
assert_eq!(
|
||||
controller
|
||||
.set_effect(effect.clone())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"No supported Aura keyboard"
|
||||
);
|
||||
|
||||
effect.mode = AuraModeNum::Laser;
|
||||
assert_eq!(
|
||||
controller
|
||||
.set_effect(effect.clone())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Aura effect not supported"
|
||||
);
|
||||
|
||||
effect.mode = AuraModeNum::Static;
|
||||
effect.zone = AuraZone::Key2;
|
||||
assert_eq!(
|
||||
controller
|
||||
.set_effect(effect.clone())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Aura effect not supported"
|
||||
);
|
||||
|
||||
controller.supported_modes.basic_zones.push(AuraZone::Key2);
|
||||
assert_eq!(
|
||||
controller.set_effect(effect).unwrap_err().to_string(),
|
||||
"No supported Aura keyboard"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_multizone_if_no_config() {
|
||||
// Checking to ensure set_mode errors when unsupported modes are tried
|
||||
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
|
||||
let supported_modes = LaptopLedData {
|
||||
board_name: String::new(),
|
||||
layout_name: "ga401".to_owned(),
|
||||
basic_modes: vec![AuraModeNum::Static],
|
||||
basic_zones: vec![],
|
||||
advanced_type: rog_aura::AdvancedAuraType::None,
|
||||
};
|
||||
let mut controller = CtrlKbdLed {
|
||||
led_prod: AuraDevice::X19b6,
|
||||
led_node: LEDNode::None,
|
||||
kd_brightness: KeyboardLed::default(),
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
per_key_mode_active: false,
|
||||
config,
|
||||
};
|
||||
|
||||
assert!(controller.config.multizone.is_none());
|
||||
assert!(controller.create_multizone_default().is_err());
|
||||
assert!(controller.config.multizone.is_none());
|
||||
|
||||
controller.supported_modes.basic_zones.push(AuraZone::Key1);
|
||||
controller.supported_modes.basic_zones.push(AuraZone::Key2);
|
||||
assert!(controller.create_multizone_default().is_ok());
|
||||
assert!(controller.config.multizone.is_some());
|
||||
|
||||
let m = controller.config.multizone.unwrap();
|
||||
assert!(m.contains_key(&AuraModeNum::Static));
|
||||
let e = m.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(e.len(), 2);
|
||||
assert_eq!(e[0].zone, AuraZone::Key1);
|
||||
assert_eq!(e[1].zone, AuraZone::Key2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_mode_create_multizone_if_no_config() {
|
||||
// Checking to ensure set_mode errors when unsupported modes are tried
|
||||
let config = AuraConfig::create_default(AuraDevice::X19b6, &LaptopLedData::default());
|
||||
let supported_modes = LaptopLedData {
|
||||
board_name: String::new(),
|
||||
layout_name: "ga401".to_owned(),
|
||||
basic_modes: vec![AuraModeNum::Static],
|
||||
basic_zones: vec![AuraZone::Key1, AuraZone::Key2],
|
||||
advanced_type: rog_aura::AdvancedAuraType::None,
|
||||
};
|
||||
let mut controller = CtrlKbdLed {
|
||||
led_prod: AuraDevice::X19b6,
|
||||
led_node: LEDNode::None,
|
||||
kd_brightness: KeyboardLed::default(),
|
||||
supported_modes,
|
||||
flip_effect_write: false,
|
||||
per_key_mode_active: false,
|
||||
config,
|
||||
};
|
||||
|
||||
assert!(controller.config.multizone.is_none());
|
||||
controller.config.multizone_on = true;
|
||||
// This is called in toggle_mode. It will error here because we have no
|
||||
// keyboard node in tests.
|
||||
assert_eq!(
|
||||
controller
|
||||
.write_current_config_mode()
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"No supported Aura keyboard"
|
||||
);
|
||||
assert!(controller.config.multizone.is_some());
|
||||
|
||||
let m = controller.config.multizone.unwrap();
|
||||
assert!(m.contains_key(&AuraModeNum::Static));
|
||||
let e = m.get(&AuraModeNum::Static).unwrap();
|
||||
assert_eq!(e.len(), 2);
|
||||
assert_eq!(e[0].zone, AuraZone::Key1);
|
||||
assert_eq!(e[1].zone, AuraZone::Key2);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub mod config;
|
||||
pub mod controller;
|
||||
/// Implements `CtrlTask`, `Reloadable`, `ZbusRun`
|
||||
pub mod trait_impls;
|
||||
@@ -1,327 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config_traits::StdConfig;
|
||||
use log::{error, info, warn};
|
||||
use rog_aura::advanced::UsbPackets;
|
||||
use rog_aura::usb::AuraPowerDev;
|
||||
use rog_aura::{AuraEffect, AuraModeNum, LedBrightness};
|
||||
use zbus::export::futures_util::lock::{Mutex, MutexGuard};
|
||||
use zbus::export::futures_util::StreamExt;
|
||||
use zbus::{dbus_interface, Connection, SignalContext};
|
||||
|
||||
use super::controller::CtrlKbdLed;
|
||||
use crate::error::RogError;
|
||||
use crate::CtrlTask;
|
||||
|
||||
pub(super) const ZBUS_PATH: &str = "/org/asuslinux/Aura";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CtrlKbdLedZbus(pub Arc<Mutex<CtrlKbdLed>>);
|
||||
|
||||
impl CtrlKbdLedZbus {
|
||||
fn update_config(lock: &mut CtrlKbdLed) -> Result<(), RogError> {
|
||||
let bright = lock.kd_brightness.get_brightness()?;
|
||||
lock.config.read();
|
||||
lock.config.brightness = (bright as u32).into();
|
||||
lock.config.write();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for CtrlKbdLedZbus {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The main interface for changing, reading, or notfying signals
|
||||
///
|
||||
/// LED commands are split between Brightness, Modes, Per-Key
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlKbdLedZbus {
|
||||
/// Set the keyboard brightness level (0-3)
|
||||
async fn set_brightness(&mut self, brightness: LedBrightness) {
|
||||
let ctrl = self.0.lock().await;
|
||||
ctrl.set_brightness(brightness)
|
||||
.map_err(|err| warn!("{}", err))
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// Set a variety of states, input is array of enum.
|
||||
/// `enabled` sets if the sent array should be disabled or enabled
|
||||
///
|
||||
/// ```text
|
||||
/// pub struct AuraPowerDev {
|
||||
/// pub x1866: Vec<AuraDev1866>,
|
||||
/// pub x19b6: Vec<AuraDev19b6>,
|
||||
/// }
|
||||
/// pub enum AuraDev1866 {
|
||||
/// Awake,
|
||||
/// Keyboard,
|
||||
/// Lightbar,
|
||||
/// Boot,
|
||||
/// Sleep,
|
||||
/// }
|
||||
/// enum AuraDev19b6 {
|
||||
/// BootLogo,
|
||||
/// BootKeyb,
|
||||
/// AwakeLogo,
|
||||
/// AwakeKeyb,
|
||||
/// SleepLogo,
|
||||
/// SleepKeyb,
|
||||
/// ShutdownLogo,
|
||||
/// ShutdownKeyb,
|
||||
/// AwakeBar,
|
||||
/// BootBar,
|
||||
/// SleepBar,
|
||||
/// ShutdownBar,
|
||||
/// }
|
||||
/// ```
|
||||
async fn set_leds_power(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
options: AuraPowerDev,
|
||||
enabled: bool,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
for p in options.tuf {
|
||||
ctrl.config.enabled.set_tuf(p, enabled);
|
||||
}
|
||||
for p in options.x1866 {
|
||||
ctrl.config.enabled.set_0x1866(p, enabled);
|
||||
}
|
||||
for p in options.x19b6 {
|
||||
ctrl.config.enabled.set_0x19b6(p, enabled);
|
||||
}
|
||||
|
||||
ctrl.config.write();
|
||||
|
||||
ctrl.set_power_states().map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
Self::notify_power_states(&ctxt, &AuraPowerDev::from(&ctrl.config.enabled))
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_led_mode(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
effect: AuraEffect,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
|
||||
ctrl.set_effect(effect).map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
Self::notify_led(&ctxt, mode.clone())
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next_led_mode(
|
||||
&self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
|
||||
ctrl.toggle_mode(false).map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
Self::notify_led(&ctxt, mode.clone())
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn prev_led_mode(
|
||||
&self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
|
||||
ctrl.toggle_mode(true).map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
|
||||
if let Some(mode) = ctrl.config.builtins.get(&ctrl.config.current_mode) {
|
||||
Self::notify_led(&ctxt, mode.clone())
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("{}", err));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn next_led_brightness(&self) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.next_brightness().map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn prev_led_brightness(&self) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.prev_brightness().map_err(|e| {
|
||||
warn!("{}", e);
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// As property doesn't work for AuraPowerDev (complexity of serialization?)
|
||||
// #[dbus_interface(property)]
|
||||
async fn leds_enabled(&self) -> AuraPowerDev {
|
||||
let ctrl = self.0.lock().await;
|
||||
AuraPowerDev::from(&ctrl.config.enabled)
|
||||
}
|
||||
|
||||
/// Return the current mode data
|
||||
async fn led_mode(&self) -> AuraModeNum {
|
||||
let ctrl = self.0.lock().await;
|
||||
ctrl.config.current_mode
|
||||
}
|
||||
|
||||
/// Return a list of available modes
|
||||
async fn led_modes(&self) -> BTreeMap<AuraModeNum, AuraEffect> {
|
||||
let ctrl = self.0.lock().await;
|
||||
ctrl.config.builtins.clone()
|
||||
}
|
||||
|
||||
/// On machine that have some form of either per-key keyboard or per-zone
|
||||
/// this can be used to write custom effects over dbus. The input is a
|
||||
/// nested `Vec<Vec<8>>` where `Vec<u8>` is a raw USB packet
|
||||
async fn direct_addressing_raw(&self, data: UsbPackets) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.write_effect_block(&data)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the current LED brightness
|
||||
#[dbus_interface(property)]
|
||||
async fn led_brightness(&self) -> i8 {
|
||||
let ctrl = self.0.lock().await;
|
||||
ctrl.get_brightness().map(|n| n as i8).unwrap_or(-1)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_led(signal_ctxt: &SignalContext<'_>, data: AuraEffect) -> zbus::Result<()>;
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_power_states(
|
||||
signal_ctxt: &SignalContext<'_>,
|
||||
data: &AuraPowerDev,
|
||||
) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CtrlTask for CtrlKbdLedZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, _: SignalContext<'static>) -> Result<(), RogError> {
|
||||
let load_save = |start: bool, mut lock: MutexGuard<'_, CtrlKbdLed>| {
|
||||
// If waking up
|
||||
if !start {
|
||||
info!("CtrlKbdLedTask reloading brightness and modes");
|
||||
lock.set_brightness(lock.config.brightness)
|
||||
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
|
||||
.ok();
|
||||
lock.write_current_config_mode()
|
||||
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
|
||||
.ok();
|
||||
} else if start {
|
||||
info!("CtrlKbdLedTask saving last brightness");
|
||||
Self::update_config(&mut lock)
|
||||
.map_err(|e| error!("CtrlKbdLedTask: {e}"))
|
||||
.ok();
|
||||
}
|
||||
};
|
||||
|
||||
let inner1 = self.0.clone();
|
||||
let inner2 = self.0.clone();
|
||||
let inner3 = self.0.clone();
|
||||
let inner4 = self.0.clone();
|
||||
self.create_sys_event_tasks(
|
||||
// Loop so that we do aquire the lock but also don't block other
|
||||
// threads (prevents potential deadlocks)
|
||||
move || {
|
||||
let inner1 = inner1.clone();
|
||||
async move {
|
||||
let lock = inner1.lock().await;
|
||||
load_save(true, lock);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
let inner2 = inner2.clone();
|
||||
async move {
|
||||
let lock = inner2.lock().await;
|
||||
load_save(false, lock);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
let inner3 = inner3.clone();
|
||||
async move {
|
||||
let lock = inner3.lock().await;
|
||||
load_save(false, lock);
|
||||
}
|
||||
},
|
||||
move || {
|
||||
let inner4 = inner4.clone();
|
||||
async move {
|
||||
let lock = inner4.lock().await;
|
||||
load_save(false, lock);
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let ctrl2 = self.0.clone();
|
||||
let ctrl = self.0.lock().await;
|
||||
let mut watch = ctrl.kd_brightness.monitor_brightness()?;
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
watch
|
||||
.event_stream(&mut buffer)
|
||||
.unwrap()
|
||||
.for_each(|_| async {
|
||||
if let Some(lock) = ctrl2.try_lock() {
|
||||
load_save(true, lock);
|
||||
}
|
||||
})
|
||||
.await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Reloadable for CtrlKbdLedZbus {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.write_current_config_mode()?;
|
||||
ctrl.set_power_states().map_err(|err| warn!("{err}")).ok();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,382 +0,0 @@
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config_traits::StdConfig;
|
||||
use log::{info, warn};
|
||||
use rog_platform::platform::{AsusPlatform, GpuMode};
|
||||
use rog_platform::supported::RogBiosSupportedFunctions;
|
||||
use zbus::export::futures_util::lock::Mutex;
|
||||
use zbus::{dbus_interface, Connection, SignalContext};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::RogError;
|
||||
use crate::{task_watch_item, CtrlTask, GetSupported};
|
||||
|
||||
const ZBUS_PATH: &str = "/org/asuslinux/Platform";
|
||||
const ASUS_POST_LOGO_SOUND: &str =
|
||||
"/sys/firmware/efi/efivars/AsusPostLogoSound-607005d5-3f75-4b2e-98f0-85ba66797a3e";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CtrlPlatform {
|
||||
platform: AsusPlatform,
|
||||
config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
impl GetSupported for CtrlPlatform {
|
||||
type A = RogBiosSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
let mut panel_overdrive = false;
|
||||
let mut dgpu_disable = false;
|
||||
let mut egpu_enable = false;
|
||||
let mut gpu_mux = false;
|
||||
|
||||
if let Ok(platform) = AsusPlatform::new() {
|
||||
panel_overdrive = platform.has_panel_od();
|
||||
dgpu_disable = platform.has_dgpu_disable();
|
||||
egpu_enable = platform.has_egpu_enable();
|
||||
gpu_mux = platform.has_gpu_mux_mode();
|
||||
}
|
||||
|
||||
RogBiosSupportedFunctions {
|
||||
post_sound: Path::new(ASUS_POST_LOGO_SOUND).exists(),
|
||||
gpu_mux,
|
||||
panel_overdrive,
|
||||
dgpu_disable,
|
||||
egpu_enable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlPlatform {
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
let platform = AsusPlatform::new()?;
|
||||
|
||||
if !platform.has_gpu_mux_mode() {
|
||||
info!("G-Sync Switchable Graphics or GPU MUX not detected");
|
||||
info!("Standard graphics switching will still work.");
|
||||
}
|
||||
|
||||
if Path::new(ASUS_POST_LOGO_SOUND).exists() {
|
||||
CtrlPlatform::set_path_mutable(ASUS_POST_LOGO_SOUND)?;
|
||||
} else {
|
||||
info!("Switch for POST boot sound not detected");
|
||||
}
|
||||
|
||||
Ok(CtrlPlatform { platform, 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 set_gfx_mode(&self, mode: GpuMode) -> Result<(), RogError> {
|
||||
self.platform.set_gpu_mux_mode(mode.to_mux_attr())?;
|
||||
// self.update_initramfs(enable)?;
|
||||
if mode == GpuMode::Discrete {
|
||||
info!("Set system-level graphics mode: Dedicated Nvidia");
|
||||
} else {
|
||||
info!("Set system-level graphics mode: Optimus");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_boot_sound() -> Result<i8, RogError> {
|
||||
let data = std::fs::read(ASUS_POST_LOGO_SOUND)
|
||||
.map_err(|err| RogError::Read(ASUS_POST_LOGO_SOUND.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();
|
||||
#[allow(clippy::verbose_file_reads)]
|
||||
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(())
|
||||
}
|
||||
|
||||
fn set_panel_overdrive(&self, enable: bool) -> Result<(), RogError> {
|
||||
self.platform.set_panel_od(enable).map_err(|err| {
|
||||
warn!("CtrlRogBios: set_panel_overdrive {}", err);
|
||||
err
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlPlatform {
|
||||
async fn set_gpu_mux_mode(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
mode: GpuMode,
|
||||
) {
|
||||
self.set_gfx_mode(mode)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: set_gpu_mux_mode {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
Self::notify_gpu_mux_mode(&ctxt, mode).await.ok();
|
||||
}
|
||||
|
||||
fn gpu_mux_mode(&self) -> GpuMode {
|
||||
match self.platform.get_gpu_mux_mode() {
|
||||
Ok(m) => GpuMode::from_mux(m as u8),
|
||||
Err(e) => {
|
||||
warn!("CtrlRogBios: get_gfx_mode {}", e);
|
||||
GpuMode::Error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_gpu_mux_mode(
|
||||
signal_ctxt: &SignalContext<'_>,
|
||||
mode: GpuMode,
|
||||
) -> zbus::Result<()> {
|
||||
}
|
||||
|
||||
async fn set_post_boot_sound(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
on: bool,
|
||||
) {
|
||||
Self::set_boot_sound(on)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: set_post_boot_sound {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
Self::notify_post_boot_sound(&ctxt, on).await.ok();
|
||||
}
|
||||
|
||||
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)]
|
||||
async fn notify_post_boot_sound(ctxt: &SignalContext<'_>, on: bool) -> zbus::Result<()> {}
|
||||
|
||||
async fn set_panel_od(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
overdrive: bool,
|
||||
) {
|
||||
match self.platform.set_panel_od(overdrive) {
|
||||
Ok(_) => {
|
||||
if let Some(mut lock) = self.config.try_lock() {
|
||||
lock.panel_od = overdrive;
|
||||
lock.write();
|
||||
}
|
||||
Self::notify_panel_od(&ctxt, overdrive).await.ok();
|
||||
}
|
||||
Err(err) => warn!("CtrlRogBios: set_panel_overdrive {}", err),
|
||||
};
|
||||
}
|
||||
|
||||
/// Get the `panel_od` value from platform. Updates the stored value in
|
||||
/// internal config also.
|
||||
fn panel_od(&self) -> bool {
|
||||
let od = self
|
||||
.platform
|
||||
.get_panel_od()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: get_panel_od {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if let Some(mut lock) = self.config.try_lock() {
|
||||
lock.panel_od = od;
|
||||
lock.write();
|
||||
}
|
||||
od
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_panel_od(signal_ctxt: &SignalContext<'_>, overdrive: bool) -> zbus::Result<()> {
|
||||
}
|
||||
|
||||
async fn set_dgpu_disable(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
disable: bool,
|
||||
) {
|
||||
match self.platform.set_dgpu_disable(disable) {
|
||||
Ok(_) => {
|
||||
Self::notify_dgpu_disable(&ctxt, disable).await.ok();
|
||||
}
|
||||
Err(err) => warn!("CtrlRogBios: set_dgpu_disable {}", err),
|
||||
};
|
||||
}
|
||||
|
||||
fn dgpu_disable(&self) -> bool {
|
||||
self.platform
|
||||
.get_dgpu_disable()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: get_dgpu_disable {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_dgpu_disable(
|
||||
signal_ctxt: &SignalContext<'_>,
|
||||
disable: bool,
|
||||
) -> zbus::Result<()> {
|
||||
}
|
||||
|
||||
async fn set_egpu_enable(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
enable: bool,
|
||||
) {
|
||||
match self.platform.set_egpu_enable(enable) {
|
||||
Ok(_) => {
|
||||
Self::notify_egpu_enable(&ctxt, enable).await.ok();
|
||||
}
|
||||
Err(err) => warn!("CtrlRogBios: set_egpu_enable {}", err),
|
||||
};
|
||||
}
|
||||
|
||||
fn egpu_enable(&self) -> bool {
|
||||
self.platform
|
||||
.get_egpu_enable()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlRogBios: get_egpu_enable {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_egpu_enable(signal_ctxt: &SignalContext<'_>, enable: bool) -> zbus::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for CtrlPlatform {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, "/org/asuslinux/Platform", server).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Reloadable for CtrlPlatform {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
if self.platform.has_panel_od() {
|
||||
let p = if let Some(lock) = self.config.try_lock() {
|
||||
lock.panel_od
|
||||
} else {
|
||||
false
|
||||
};
|
||||
self.set_panel_overdrive(p)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlPlatform {
|
||||
task_watch_item!(panel_od platform);
|
||||
|
||||
task_watch_item!(dgpu_disable platform);
|
||||
|
||||
task_watch_item!(egpu_enable platform);
|
||||
// NOTE: see note further below
|
||||
// task_watch_item!(gpu_mux_mode platform);
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CtrlTask for CtrlPlatform {
|
||||
fn zbus_path() -> &'static str {
|
||||
ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
|
||||
let platform1 = self.clone();
|
||||
let platform2 = self.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move || async { {} },
|
||||
move || {
|
||||
let platform1 = platform1.clone();
|
||||
async move {
|
||||
info!("CtrlRogBios reloading panel_od");
|
||||
let lock = platform1.config.lock().await;
|
||||
if platform1.platform.has_panel_od() {
|
||||
platform1
|
||||
.set_panel_overdrive(lock.panel_od)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
move || async { {} },
|
||||
move || {
|
||||
let platform2 = platform2.clone();
|
||||
async move {
|
||||
info!("CtrlRogBios reloading panel_od");
|
||||
let lock = platform2.config.lock().await;
|
||||
if platform2.platform.has_panel_od() {
|
||||
platform2
|
||||
.set_panel_overdrive(lock.panel_od)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
self.watch_panel_od(signal_ctxt.clone()).await?;
|
||||
self.watch_dgpu_disable(signal_ctxt.clone()).await?;
|
||||
self.watch_egpu_enable(signal_ctxt.clone()).await?;
|
||||
// NOTE: Can't have this as a watch because on a write to it, it reverts back to
|
||||
// booted-with value as it does not actually change until reboot.
|
||||
// self.watch_gpu_mux_mode(signal_ctxt.clone()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config_traits::StdConfig;
|
||||
use log::{error, info, warn};
|
||||
use rog_platform::power::AsusPower;
|
||||
use rog_platform::supported::ChargeSupportedFunctions;
|
||||
use systemd_zbus::{ManagerProxy as SystemdProxy, Mode, UnitFileState};
|
||||
use tokio::time::sleep;
|
||||
use zbus::export::futures_util::lock::Mutex;
|
||||
use zbus::{dbus_interface, Connection, SignalContext};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::error::RogError;
|
||||
use crate::{task_watch_item, CtrlTask, GetSupported};
|
||||
|
||||
const ZBUS_PATH: &str = "/org/asuslinux/Power";
|
||||
const NVIDIA_POWERD: &str = "nvidia-powerd.service";
|
||||
|
||||
impl GetSupported for CtrlPower {
|
||||
type A = ChargeSupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
ChargeSupportedFunctions {
|
||||
charge_level_set: if let Ok(power) = AsusPower::new() {
|
||||
power.has_charge_control_end_threshold()
|
||||
} else {
|
||||
false
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CtrlPower {
|
||||
power: AsusPower,
|
||||
config: Arc<Mutex<Config>>,
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl CtrlPower {
|
||||
async fn set_charge_control_end_threshold(
|
||||
&mut self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
limit: u8,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
if !(20..=100).contains(&limit) {
|
||||
return Err(RogError::ChargeLimit(limit))?;
|
||||
}
|
||||
self.set(limit)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
Self::notify_charge_control_end_threshold(&ctxt, limit)
|
||||
.await
|
||||
.ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn charge_control_end_threshold(&self) -> u8 {
|
||||
loop {
|
||||
if let Some(mut config) = self.config.try_lock() {
|
||||
let limit = self
|
||||
.power
|
||||
.get_charge_control_end_threshold()
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: get_charge_control_end_threshold {}", err);
|
||||
err
|
||||
})
|
||||
.unwrap_or(100);
|
||||
|
||||
config.read();
|
||||
config.bat_charge_limit = limit;
|
||||
config.write();
|
||||
|
||||
return config.bat_charge_limit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mains_online(&self) -> bool {
|
||||
if self.power.has_online() {
|
||||
if let Ok(v) = self.power.get_online() {
|
||||
return v == 1;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_charge_control_end_threshold(
|
||||
ctxt: &SignalContext<'_>,
|
||||
limit: u8,
|
||||
) -> zbus::Result<()>;
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_mains_online(ctxt: &SignalContext<'_>, on: bool) -> zbus::Result<()>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for CtrlPower {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Reloadable for CtrlPower {
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
if let Some(mut config) = self.config.try_lock() {
|
||||
config.read();
|
||||
self.set(config.bat_charge_limit)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlPower {
|
||||
task_watch_item!(charge_control_end_threshold power);
|
||||
|
||||
pub fn new(config: Arc<Mutex<Config>>) -> Result<Self, RogError> {
|
||||
Ok(CtrlPower {
|
||||
power: AsusPower::new()?,
|
||||
config,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn set(&self, limit: u8) -> Result<(), RogError> {
|
||||
if !(20..=100).contains(&limit) {
|
||||
return Err(RogError::ChargeLimit(limit));
|
||||
}
|
||||
|
||||
self.power.set_charge_control_end_threshold(limit)?;
|
||||
|
||||
info!("Battery charge limit: {}", limit);
|
||||
|
||||
if let Some(mut config) = self.config.try_lock() {
|
||||
config.read();
|
||||
config.bat_charge_limit = limit;
|
||||
config.write();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CtrlTask for CtrlPower {
|
||||
fn zbus_path() -> &'static str {
|
||||
ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
|
||||
let conn = zbus::Connection::system().await?;
|
||||
let sysd1 = SystemdProxy::new(&conn).await?;
|
||||
let sysd2 = sysd1.clone();
|
||||
let sysd3 = sysd1.clone();
|
||||
|
||||
let power1 = self.clone();
|
||||
let power2 = self.clone();
|
||||
self.create_sys_event_tasks(
|
||||
move || async {},
|
||||
move || {
|
||||
let power = power1.clone();
|
||||
let sysd = sysd1.clone();
|
||||
async move {
|
||||
info!("CtrlCharge reloading charge limit");
|
||||
let lock = power.config.lock().await;
|
||||
power
|
||||
.set(lock.bat_charge_limit)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
|
||||
if lock.disable_nvidia_powerd_on_battery {
|
||||
if let Ok(value) = power.power.get_online() {
|
||||
do_nvidia_powerd_action(&sysd, value == 1).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
move || async {},
|
||||
move || {
|
||||
let power = power2.clone();
|
||||
let sysd = sysd2.clone();
|
||||
async move {
|
||||
info!("CtrlCharge reloading charge limit");
|
||||
let lock = power.config.lock().await;
|
||||
power
|
||||
.set(lock.bat_charge_limit)
|
||||
.map_err(|err| {
|
||||
warn!("CtrlCharge: set_limit {}", err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
|
||||
if lock.disable_nvidia_powerd_on_battery {
|
||||
if let Ok(value) = power.power.get_online() {
|
||||
do_nvidia_powerd_action(&sysd, value == 1).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
let config = self.config.clone();
|
||||
self.watch_charge_control_end_threshold(signal_ctxt.clone())
|
||||
.await?;
|
||||
|
||||
let ctrl = self.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut online = 10;
|
||||
loop {
|
||||
if let Ok(value) = ctrl.power.get_online() {
|
||||
if online != value {
|
||||
online = value;
|
||||
let mut config = config.lock().await;
|
||||
config.read();
|
||||
|
||||
if config.disable_nvidia_powerd_on_battery {
|
||||
do_nvidia_powerd_action(&sysd3, value == 1).await;
|
||||
}
|
||||
|
||||
Self::notify_mains_online(&signal_ctxt, value == 1)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut prog: Vec<&str> = Vec::new();
|
||||
if value == 1 {
|
||||
// AC ONLINE
|
||||
prog = config.ac_command.split_whitespace().collect();
|
||||
} else if value == 0 {
|
||||
// BATTERY
|
||||
prog = config.bat_command.split_whitespace().collect();
|
||||
}
|
||||
|
||||
if prog.len() > 1 {
|
||||
let mut cmd = Command::new(prog[0]);
|
||||
for arg in prog.iter().skip(1) {
|
||||
cmd.arg(*arg);
|
||||
}
|
||||
if let Err(e) = cmd.spawn() {
|
||||
if value == 1 {
|
||||
error!("AC power command error: {e}");
|
||||
} else {
|
||||
error!("Battery power command error: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The inotify doesn't pick up events when the kernel changes internal value
|
||||
// so we need to watch it with a thread and sleep unfortunately
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn do_nvidia_powerd_action(proxy: &SystemdProxy<'_>, ac_on: bool) {
|
||||
if let Ok(res) = proxy.get_unit_file_state(NVIDIA_POWERD).await {
|
||||
if res == UnitFileState::Enabled {
|
||||
if ac_on {
|
||||
proxy
|
||||
.start_unit(NVIDIA_POWERD, Mode::Replace)
|
||||
.await
|
||||
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
|
||||
.ok();
|
||||
} else {
|
||||
proxy
|
||||
.stop_unit(NVIDIA_POWERD, Mode::Replace)
|
||||
.await
|
||||
.map_err(|e| error!("Error stopping {NVIDIA_POWERD}, {e:?}"))
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use rog_profiles::fan_curve_set::FanCurveSet;
|
||||
use rog_profiles::Profile;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
use crate::CONFIG_PATH_BASE;
|
||||
|
||||
const CONFIG_FILE: &str = "profile.ron";
|
||||
const CONFIG_FAN_FILE: &str = "fan_curves.ron";
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct ProfileConfig {
|
||||
/// For restore on boot
|
||||
pub active_profile: Profile,
|
||||
}
|
||||
|
||||
impl StdConfig for ProfileConfig {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
active_profile: Profile::Balanced,
|
||||
}
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
PathBuf::from(CONFIG_PATH_BASE)
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FILE.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for ProfileConfig {}
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug, Default)]
|
||||
pub struct FanCurveConfig {
|
||||
pub balanced: FanCurveSet,
|
||||
pub performance: FanCurveSet,
|
||||
pub quiet: FanCurveSet,
|
||||
}
|
||||
|
||||
impl StdConfig for FanCurveConfig {
|
||||
/// Create a new config. The defaults are zeroed so the device must be read
|
||||
/// to get the actual device defaults.
|
||||
fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn config_dir() -> std::path::PathBuf {
|
||||
PathBuf::from(CONFIG_PATH_BASE)
|
||||
}
|
||||
|
||||
fn file_name(&self) -> String {
|
||||
CONFIG_FAN_FILE.to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
impl StdConfigLoad for FanCurveConfig {}
|
||||
@@ -1,191 +0,0 @@
|
||||
use config_traits::{StdConfig, StdConfigLoad};
|
||||
use log::{info, warn};
|
||||
use rog_platform::platform::AsusPlatform;
|
||||
use rog_platform::supported::PlatformProfileFunctions;
|
||||
use rog_profiles::error::ProfileError;
|
||||
use rog_profiles::{FanCurveProfiles, Profile};
|
||||
|
||||
use super::config::{FanCurveConfig, ProfileConfig};
|
||||
use crate::error::RogError;
|
||||
use crate::GetSupported;
|
||||
|
||||
// TODO: macro wrapper for warn/info/error log macros to add module name
|
||||
const MOD_NAME: &str = "CtrlPlatformProfile";
|
||||
|
||||
pub struct FanCurves {
|
||||
config_file: FanCurveConfig,
|
||||
profiles: FanCurveProfiles,
|
||||
}
|
||||
|
||||
impl FanCurves {
|
||||
pub fn update_profiles_from_config(&mut self) {
|
||||
self.profiles.balanced = self.config_file.balanced.clone();
|
||||
self.profiles.performance = self.config_file.performance.clone();
|
||||
self.profiles.quiet = self.config_file.quiet.clone();
|
||||
}
|
||||
|
||||
pub fn update_config_from_profiles(&mut self) {
|
||||
self.config_file.balanced = self.profiles.balanced.clone();
|
||||
self.config_file.performance = self.profiles.performance.clone();
|
||||
self.config_file.quiet = self.profiles.quiet.clone();
|
||||
}
|
||||
|
||||
pub fn profiles(&self) -> &FanCurveProfiles {
|
||||
&self.profiles
|
||||
}
|
||||
|
||||
pub fn profiles_mut(&mut self) -> &mut FanCurveProfiles {
|
||||
&mut self.profiles
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CtrlPlatformProfile {
|
||||
pub profile_config: ProfileConfig,
|
||||
pub fan_curves: Option<FanCurves>,
|
||||
pub platform: AsusPlatform,
|
||||
}
|
||||
|
||||
impl GetSupported for CtrlPlatformProfile {
|
||||
type A = PlatformProfileFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
if !Profile::is_platform_profile_supported() {
|
||||
warn!(
|
||||
"platform_profile kernel interface not found, your laptop does not support this, \
|
||||
or the interface is missing."
|
||||
);
|
||||
}
|
||||
|
||||
let res = FanCurveProfiles::is_supported();
|
||||
let mut fan_curve_supported = res.is_err();
|
||||
if let Ok(r) = res {
|
||||
fan_curve_supported = r;
|
||||
};
|
||||
|
||||
if !fan_curve_supported {
|
||||
info!(
|
||||
"fan curves kernel interface not found, your laptop does not support this, or the \
|
||||
interface is missing."
|
||||
);
|
||||
}
|
||||
|
||||
PlatformProfileFunctions {
|
||||
platform_profile: Profile::is_platform_profile_supported(),
|
||||
fan_curves: fan_curve_supported,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CtrlPlatformProfile {
|
||||
pub fn new(config: ProfileConfig) -> Result<Self, RogError> {
|
||||
let platform = AsusPlatform::new()?;
|
||||
if platform.has_platform_profile() || platform.has_throttle_thermal_policy() {
|
||||
info!("{MOD_NAME}: Device has profile control available");
|
||||
|
||||
let mut controller = CtrlPlatformProfile {
|
||||
profile_config: config,
|
||||
fan_curves: None,
|
||||
platform,
|
||||
};
|
||||
if FanCurveProfiles::get_device().is_ok() {
|
||||
info!("{MOD_NAME}: Device has fan curves available");
|
||||
let fan_config = FanCurveConfig::new();
|
||||
// Only do defaults if the config doesn't already exist
|
||||
if !fan_config.file_path().exists() {
|
||||
info!("{MOD_NAME}: Fetching default fan curves");
|
||||
controller.fan_curves = Some(FanCurves {
|
||||
config_file: fan_config,
|
||||
profiles: FanCurveProfiles::default(),
|
||||
});
|
||||
for _ in [Profile::Balanced, Profile::Performance, Profile::Quiet] {
|
||||
// For each profile we need to switch to it before we
|
||||
// can read the existing values from hardware. The ACPI method used
|
||||
// for this is what limits us.
|
||||
controller.set_next_profile()?;
|
||||
// Make sure to set the baseline to default
|
||||
controller.set_active_curve_to_defaults()?;
|
||||
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
|
||||
|
||||
if let Some(curves) = controller.fan_curves.as_ref() {
|
||||
info!(
|
||||
"{MOD_NAME}: {active:?}: {}",
|
||||
String::from(curves.profiles().get_fan_curves_for(active))
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(curves) = controller.fan_curves.as_ref() {
|
||||
curves.config_file.write();
|
||||
}
|
||||
} else {
|
||||
info!("{MOD_NAME}: Fan curves previously stored, loading...");
|
||||
let mut fan_curves = FanCurves {
|
||||
config_file: fan_config.load(),
|
||||
profiles: FanCurveProfiles::default(),
|
||||
};
|
||||
fan_curves.update_profiles_from_config();
|
||||
controller.fan_curves = Some(fan_curves);
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(controller);
|
||||
}
|
||||
|
||||
Err(ProfileError::NotSupported.into())
|
||||
}
|
||||
|
||||
pub fn save_config(&mut self) {
|
||||
self.profile_config.write();
|
||||
if let Some(fans) = self.fan_curves.as_mut() {
|
||||
fans.update_config_from_profiles();
|
||||
fans.config_file.write(); // config write
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle to next profile in list. This will first read the config, switch,
|
||||
/// then write out
|
||||
pub(super) fn set_next_profile(&mut self) -> Result<(), RogError> {
|
||||
// Read first just incase the user has modified the config before calling this
|
||||
match self.profile_config.active_profile {
|
||||
Profile::Balanced => {
|
||||
Profile::set_profile(Profile::Performance)?;
|
||||
self.profile_config.active_profile = Profile::Performance;
|
||||
}
|
||||
Profile::Performance => {
|
||||
Profile::set_profile(Profile::Quiet)?;
|
||||
self.profile_config.active_profile = Profile::Quiet;
|
||||
}
|
||||
Profile::Quiet => {
|
||||
Profile::set_profile(Profile::Balanced)?;
|
||||
self.profile_config.active_profile = Profile::Balanced;
|
||||
}
|
||||
}
|
||||
self.write_profile_curve_to_platform()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set the curve for the active profile active
|
||||
pub(super) fn write_profile_curve_to_platform(&mut self) -> Result<(), RogError> {
|
||||
if let Some(curves) = &mut self.fan_curves {
|
||||
if let Ok(mut device) = FanCurveProfiles::get_device() {
|
||||
curves.profiles_mut().write_profile_curve_to_platform(
|
||||
self.profile_config.active_profile,
|
||||
&mut device,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn set_active_curve_to_defaults(&mut self) -> Result<(), RogError> {
|
||||
if let Some(curves) = self.fan_curves.as_mut() {
|
||||
if let Ok(mut device) = FanCurveProfiles::get_device() {
|
||||
curves.profiles_mut().set_active_curve_to_defaults(
|
||||
self.profile_config.active_profile,
|
||||
&mut device,
|
||||
)?;
|
||||
curves.update_config_from_profiles();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
pub mod config;
|
||||
pub mod controller;
|
||||
/// Implements `CtrlTask`, Reloadable, `ZbusRun`
|
||||
pub mod trait_impls;
|
||||
@@ -1,311 +0,0 @@
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use config_traits::StdConfig;
|
||||
use log::{error, info, warn};
|
||||
use rog_profiles::fan_curve_set::{CurveData, FanCurveSet};
|
||||
use rog_profiles::{FanCurveProfiles, Profile};
|
||||
use zbus::export::futures_util::lock::Mutex;
|
||||
use zbus::export::futures_util::StreamExt;
|
||||
use zbus::fdo::Error;
|
||||
use zbus::{dbus_interface, Connection, SignalContext};
|
||||
|
||||
use super::controller::CtrlPlatformProfile;
|
||||
use crate::error::RogError;
|
||||
use crate::CtrlTask;
|
||||
|
||||
const MOD_NAME: &str = "ProfileZbus";
|
||||
|
||||
const ZBUS_PATH: &str = "/org/asuslinux/Profile";
|
||||
const UNSUPPORTED_MSG: &str =
|
||||
"Fan curves are not supported on this laptop or you require a patched kernel";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProfileZbus(pub Arc<Mutex<CtrlPlatformProfile>>);
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl ProfileZbus {
|
||||
/// Fetch profile names
|
||||
fn profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
|
||||
if let Ok(profiles) = Profile::get_profile_names() {
|
||||
return Ok(profiles);
|
||||
}
|
||||
Err(Error::Failed(
|
||||
"Failed to get all profile details".to_owned(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Toggle to next platform_profile. Names provided by `Profiles`.
|
||||
/// If fan-curves are supported will also activate a fan curve for profile.
|
||||
async fn next_profile(&mut self, #[zbus(signal_context)] ctxt: SignalContext<'_>) {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.set_next_profile()
|
||||
.unwrap_or_else(|err| warn!("{MOD_NAME}: {}", err));
|
||||
ctrl.save_config();
|
||||
|
||||
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// Fetch the active profile name
|
||||
async fn active_profile(&mut self) -> zbus::fdo::Result<Profile> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
Ok(ctrl.profile_config.active_profile)
|
||||
}
|
||||
|
||||
/// Set this platform_profile name as active
|
||||
async fn set_active_profile(
|
||||
&self,
|
||||
#[zbus(signal_context)] ctxt: SignalContext<'_>,
|
||||
profile: Profile,
|
||||
) {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
// Read first just incase the user has modified the config before calling this
|
||||
ctrl.profile_config.read();
|
||||
Profile::set_profile(profile)
|
||||
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
|
||||
.ok();
|
||||
ctrl.profile_config.active_profile = profile;
|
||||
ctrl.write_profile_curve_to_platform()
|
||||
.map_err(|e| warn!("{MOD_NAME}: write_profile_curve_to_platform, {}", e))
|
||||
.ok();
|
||||
|
||||
ctrl.save_config();
|
||||
|
||||
Self::notify_profile(&ctxt, ctrl.profile_config.active_profile)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
/// Get a list of profiles that have fan-curves enabled.
|
||||
async fn enabled_fan_profiles(&mut self) -> zbus::fdo::Result<Vec<Profile>> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
if let Some(curves) = &mut ctrl.fan_curves {
|
||||
return Ok(curves.profiles().get_enabled_curve_profiles());
|
||||
}
|
||||
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
|
||||
}
|
||||
|
||||
/// Set a profile fan curve enabled status. Will also activate a fan curve
|
||||
/// if in the same profile mode
|
||||
async fn set_fan_curve_enabled(
|
||||
&mut self,
|
||||
profile: Profile,
|
||||
enabled: bool,
|
||||
) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
if let Some(curves) = &mut ctrl.fan_curves {
|
||||
curves
|
||||
.profiles_mut()
|
||||
.set_profile_curve_enabled(profile, enabled);
|
||||
|
||||
ctrl.write_profile_curve_to_platform()
|
||||
.map_err(|e| warn!("{MOD_NAME}: write_profile_curve_to_platform, {}", e))
|
||||
.ok();
|
||||
|
||||
ctrl.save_config();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the fan-curve data for the currently active Profile
|
||||
async fn fan_curve_data(&mut self, profile: Profile) -> zbus::fdo::Result<FanCurveSet> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
if let Some(curves) = &mut ctrl.fan_curves {
|
||||
let curve = curves.profiles().get_fan_curves_for(profile);
|
||||
return Ok(curve.clone());
|
||||
}
|
||||
Err(Error::Failed(UNSUPPORTED_MSG.to_owned()))
|
||||
}
|
||||
|
||||
/// Set the fan curve for the specified profile.
|
||||
/// Will also activate the fan curve if the user is in the same mode.
|
||||
async fn set_fan_curve(&self, profile: Profile, curve: CurveData) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
if let Some(curves) = &mut ctrl.fan_curves {
|
||||
curves
|
||||
.profiles_mut()
|
||||
.save_fan_curve(curve, profile)
|
||||
.map_err(|err| zbus::fdo::Error::Failed(err.to_string()))?;
|
||||
} else {
|
||||
return Err(Error::Failed(UNSUPPORTED_MSG.to_owned()));
|
||||
}
|
||||
ctrl.write_profile_curve_to_platform()
|
||||
.map_err(|e| warn!("{MOD_NAME}: Profile::set_profile, {}", e))
|
||||
.ok();
|
||||
ctrl.save_config();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reset the stored (self) and device curve to the defaults of the
|
||||
/// platform.
|
||||
///
|
||||
/// Each platform_profile has a different default and the defualt can be
|
||||
/// read only for the currently active profile.
|
||||
async fn set_active_curve_to_defaults(&self) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
ctrl.set_active_curve_to_defaults()
|
||||
.map_err(|e| warn!("{MOD_NAME}: Profile::set_active_curve_to_defaults, {}", e))
|
||||
.ok();
|
||||
ctrl.save_config();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reset the stored (self) and device curve to the defaults of the
|
||||
/// platform.
|
||||
///
|
||||
/// Each platform_profile has a different default and the defualt can be
|
||||
/// read only for the currently active profile.
|
||||
async fn reset_profile_curves(&self, profile: Profile) -> zbus::fdo::Result<()> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
ctrl.profile_config.read();
|
||||
let active = Profile::get_active_profile().unwrap_or(Profile::Balanced);
|
||||
|
||||
Profile::set_profile(profile)
|
||||
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
|
||||
.ok();
|
||||
ctrl.set_active_curve_to_defaults()
|
||||
.map_err(|e| warn!("{MOD_NAME}: Profile::set_active_curve_to_defaults, {}", e))
|
||||
.ok();
|
||||
|
||||
Profile::set_profile(active)
|
||||
.map_err(|e| warn!("{MOD_NAME}: set_profile, {}", e))
|
||||
.ok();
|
||||
ctrl.save_config();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[dbus_interface(signal)]
|
||||
async fn notify_profile(signal_ctxt: &SignalContext<'_>, profile: Profile) -> zbus::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for ProfileZbus {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, ZBUS_PATH, server).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl CtrlTask for ProfileZbus {
|
||||
fn zbus_path() -> &'static str {
|
||||
ZBUS_PATH
|
||||
}
|
||||
|
||||
async fn create_tasks(&self, signal_ctxt: SignalContext<'static>) -> Result<(), RogError> {
|
||||
let ctrl = self.0.clone();
|
||||
let sig_ctx = signal_ctxt.clone();
|
||||
let mut watch = self
|
||||
.0
|
||||
.lock()
|
||||
.await
|
||||
.platform
|
||||
.monitor_throttle_thermal_policy()?;
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
if let Ok(stream) = watch.event_stream(&mut buffer) {
|
||||
stream
|
||||
.for_each(|_| async {
|
||||
let mut lock = ctrl.lock().await;
|
||||
if let Ok(profile) =
|
||||
lock.platform.get_throttle_thermal_policy().map_err(|e| {
|
||||
error!("{MOD_NAME}: get_throttle_thermal_policy error: {e}");
|
||||
})
|
||||
{
|
||||
let new_profile = Profile::from_throttle_thermal_policy(profile);
|
||||
if new_profile != lock.profile_config.active_profile {
|
||||
info!("{MOD_NAME}: platform_profile changed to {new_profile}");
|
||||
lock.profile_config.active_profile = new_profile;
|
||||
lock.write_profile_curve_to_platform().unwrap();
|
||||
lock.save_config();
|
||||
Profile::set_profile(lock.profile_config.active_profile)
|
||||
.map_err(|e| {
|
||||
error!("Profile::set_profile() error: {e}");
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
Self::notify_profile(&sig_ctx, lock.profile_config.active_profile)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
let ctrl = self.0.clone();
|
||||
let mut watch = self.0.lock().await.platform.monitor_platform_profile()?;
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
if let Ok(stream) = watch.event_stream(&mut buffer) {
|
||||
stream
|
||||
.for_each(|_| async {
|
||||
let mut lock = ctrl.lock().await;
|
||||
if let Ok(profile) = lock.platform.get_platform_profile().map_err(|e| {
|
||||
error!("get_platform_profile error: {e}");
|
||||
}) {
|
||||
if let Ok(new_profile) = Profile::from_str(&profile).map_err(|e| {
|
||||
error!("Profile::from_str(&profile) error: {e}");
|
||||
}) {
|
||||
if new_profile != lock.profile_config.active_profile {
|
||||
info!("{MOD_NAME}: platform_profile changed to {new_profile}");
|
||||
lock.profile_config.active_profile = new_profile;
|
||||
lock.write_profile_curve_to_platform().unwrap();
|
||||
lock.save_config();
|
||||
Profile::set_profile(lock.profile_config.active_profile)
|
||||
.map_err(|e| {
|
||||
error!("Profile::set_profile() error: {e}");
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
Self::notify_profile(
|
||||
&signal_ctxt,
|
||||
lock.profile_config.active_profile,
|
||||
)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::Reloadable for ProfileZbus {
|
||||
/// Fetch the active profile and use that to set all related components up
|
||||
async fn reload(&mut self) -> Result<(), RogError> {
|
||||
let mut ctrl = self.0.lock().await;
|
||||
let active = ctrl.profile_config.active_profile;
|
||||
if let Some(curves) = &mut ctrl.fan_curves {
|
||||
if let Ok(mut device) = FanCurveProfiles::get_device() {
|
||||
// There is a possibility that the curve was default zeroed, so this call
|
||||
// initialises the data from system read and we need to save it
|
||||
// after
|
||||
curves
|
||||
.profiles_mut()
|
||||
.write_profile_curve_to_platform(active, &mut device)?;
|
||||
ctrl.profile_config.write();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use async_trait::async_trait;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
use zbus::zvariant::Type;
|
||||
use zbus::{dbus_interface, Connection};
|
||||
|
||||
use crate::ctrl_anime::CtrlAnime;
|
||||
use crate::ctrl_aura::controller::CtrlKbdLed;
|
||||
use crate::ctrl_platform::CtrlPlatform;
|
||||
use crate::ctrl_power::CtrlPower;
|
||||
use crate::ctrl_profiles::controller::CtrlPlatformProfile;
|
||||
use crate::GetSupported;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Type)]
|
||||
pub struct SupportedFunctions(rog_platform::supported::SupportedFunctions);
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
impl SupportedFunctions {
|
||||
pub fn supported_functions(&self) -> &rog_platform::supported::SupportedFunctions {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::ZbusRun for SupportedFunctions {
|
||||
async fn add_to_server(self, server: &mut Connection) {
|
||||
Self::add_to_server_helper(self, "/org/asuslinux/Supported", server).await;
|
||||
}
|
||||
}
|
||||
|
||||
impl GetSupported for SupportedFunctions {
|
||||
type A = SupportedFunctions;
|
||||
|
||||
fn get_supported() -> Self::A {
|
||||
Self(rog_platform::supported::SupportedFunctions {
|
||||
anime_ctrl: CtrlAnime::get_supported(),
|
||||
keyboard_led: CtrlKbdLed::get_supported(),
|
||||
charge_ctrl: CtrlPower::get_supported(),
|
||||
platform_profile: CtrlPlatformProfile::get_supported(),
|
||||
rog_bios_ctrl: CtrlPlatform::get_supported(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,165 +0,0 @@
|
||||
use std::env;
|
||||
use std::error::Error;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use ::zbus::export::futures_util::lock::Mutex;
|
||||
use ::zbus::Connection;
|
||||
use config_traits::{StdConfig, StdConfigLoad, StdConfigLoad2};
|
||||
use daemon::config::Config;
|
||||
use daemon::ctrl_anime::config::AnimeConfig;
|
||||
use daemon::ctrl_anime::trait_impls::CtrlAnimeZbus;
|
||||
use daemon::ctrl_anime::CtrlAnime;
|
||||
use daemon::ctrl_aura::controller::CtrlKbdLed;
|
||||
use daemon::ctrl_aura::trait_impls::CtrlKbdLedZbus;
|
||||
use daemon::ctrl_platform::CtrlPlatform;
|
||||
use daemon::ctrl_power::CtrlPower;
|
||||
use daemon::ctrl_profiles::config::ProfileConfig;
|
||||
use daemon::ctrl_profiles::controller::CtrlPlatformProfile;
|
||||
use daemon::ctrl_profiles::trait_impls::ProfileZbus;
|
||||
use daemon::ctrl_supported::SupportedFunctions;
|
||||
use daemon::{print_board_info, CtrlTask, GetSupported, Reloadable, ZbusRun};
|
||||
use log::{error, info, warn};
|
||||
use rog_aura::aura_detection::LaptopLedData;
|
||||
use rog_dbus::DBUS_NAME;
|
||||
use rog_profiles::Profile;
|
||||
use tokio::time::sleep;
|
||||
use zbus::SignalContext;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut logger = env_logger::Builder::new();
|
||||
logger
|
||||
.parse_default_env()
|
||||
.target(env_logger::Target::Stdout)
|
||||
.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args()))
|
||||
.init();
|
||||
|
||||
let is_service = match env::var_os("IS_SERVICE") {
|
||||
Some(val) => val == "1",
|
||||
None => false,
|
||||
};
|
||||
|
||||
if !is_service {
|
||||
println!("asusd schould be only run from the right systemd service");
|
||||
println!(
|
||||
"do not run in your terminal, if you need an logs please use journalctl -b -u asusd"
|
||||
);
|
||||
println!("asusd will now exit");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
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-platform v{}", rog_platform::VERSION);
|
||||
|
||||
start_daemon().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The actual main loop for the daemon
|
||||
async fn start_daemon() -> Result<(), Box<dyn Error>> {
|
||||
let supported = SupportedFunctions::get_supported();
|
||||
print_board_info();
|
||||
println!("{}", supported.supported_functions());
|
||||
|
||||
// Start zbus server
|
||||
let mut connection = Connection::system().await?;
|
||||
|
||||
let config = Config::new().load();
|
||||
let config = Arc::new(Mutex::new(config));
|
||||
|
||||
supported.add_to_server(&mut connection).await;
|
||||
|
||||
match CtrlPlatform::new(config.clone()) {
|
||||
Ok(ctrl) => {
|
||||
let sig_ctx = CtrlPlatform::signal_context(&connection)?;
|
||||
start_tasks(ctrl, &mut connection, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("CtrlPlatform: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
match CtrlPower::new(config.clone()) {
|
||||
Ok(ctrl) => {
|
||||
let sig_ctx = CtrlPower::signal_context(&connection)?;
|
||||
start_tasks(ctrl, &mut connection, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("CtrlPower: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
if Profile::is_platform_profile_supported() {
|
||||
let profile_config = ProfileConfig::new().load();
|
||||
match CtrlPlatformProfile::new(profile_config) {
|
||||
Ok(ctrl) => {
|
||||
let zbus = ProfileZbus(Arc::new(Mutex::new(ctrl)));
|
||||
let sig_ctx = ProfileZbus::signal_context(&connection)?;
|
||||
start_tasks(zbus, &mut connection, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Profile control: {}", err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
warn!("platform_profile support not found");
|
||||
}
|
||||
|
||||
match CtrlAnime::new(AnimeConfig::new().load()) {
|
||||
Ok(ctrl) => {
|
||||
let zbus = CtrlAnimeZbus(Arc::new(Mutex::new(ctrl)));
|
||||
let sig_ctx = CtrlAnimeZbus::signal_context(&connection)?;
|
||||
start_tasks(zbus, &mut connection, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
info!("AniMe control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
let laptop = LaptopLedData::get_data();
|
||||
// CtrlKbdLed deviates from the config pattern above due to requiring a keyboard
|
||||
// detection first
|
||||
match CtrlKbdLed::new(laptop) {
|
||||
Ok(ctrl) => {
|
||||
let zbus = CtrlKbdLedZbus(Arc::new(Mutex::new(ctrl)));
|
||||
let sig_ctx = CtrlKbdLedZbus::signal_context(&connection)?;
|
||||
start_tasks(zbus, &mut connection, sig_ctx).await?;
|
||||
}
|
||||
Err(err) => {
|
||||
error!("Keyboard control: {}", err);
|
||||
}
|
||||
}
|
||||
|
||||
// Request dbus name after finishing initalizing all functions
|
||||
connection.request_name(DBUS_NAME).await?;
|
||||
|
||||
loop {
|
||||
// This is just a blocker to idle and ensure the reator reacts
|
||||
sleep(Duration::from_millis(1000)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_tasks<T>(
|
||||
mut zbus: T,
|
||||
connection: &mut Connection,
|
||||
signal_ctx: SignalContext<'static>,
|
||||
) -> Result<(), Box<dyn Error>>
|
||||
where
|
||||
T: ZbusRun + Reloadable + CtrlTask + Clone,
|
||||
{
|
||||
let task = zbus.clone();
|
||||
|
||||
zbus.reload()
|
||||
.await
|
||||
.unwrap_or_else(|err| warn!("Controller error: {}", err));
|
||||
zbus.add_to_server(connection).await;
|
||||
|
||||
task.create_tasks(signal_ctx).await.ok();
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
#![deny(unused_must_use)]
|
||||
/// Configuration loading, saving
|
||||
pub mod config;
|
||||
/// Control of anime matrix display
|
||||
pub mod ctrl_anime;
|
||||
/// Keyboard LED brightness control, RGB, and LED display modes
|
||||
pub mod ctrl_aura;
|
||||
/// Control ASUS bios function such as boot sound, Optimus/Dedicated gfx mode
|
||||
pub mod ctrl_platform;
|
||||
/// Control of battery charge level
|
||||
pub mod ctrl_power;
|
||||
/// Control platform profiles + fan-curves if available
|
||||
pub mod ctrl_profiles;
|
||||
|
||||
/// Fetch all supported functions for the laptop
|
||||
pub mod ctrl_supported;
|
||||
|
||||
pub mod error;
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::{debug, info, warn};
|
||||
use logind_zbus::manager::ManagerProxy;
|
||||
use zbus::export::futures_util::StreamExt;
|
||||
use zbus::zvariant::ObjectPath;
|
||||
use zbus::{Connection, SignalContext};
|
||||
|
||||
use crate::error::RogError;
|
||||
|
||||
const CONFIG_PATH_BASE: &str = "/etc/asusd/";
|
||||
|
||||
/// This macro adds a function which spawns an `inotify` task on the passed in
|
||||
/// `Executor`.
|
||||
///
|
||||
/// The generated function is `watch_<name>()`. Self requires the following
|
||||
/// methods to be available:
|
||||
/// - `<name>() -> SomeValue`, functionally is a getter, but is allowed to have
|
||||
/// side effects.
|
||||
/// - `notify_<name>(SignalContext, SomeValue)`
|
||||
///
|
||||
/// In most cases if `SomeValue` is stored in a config then `<name>()` getter is
|
||||
/// expected to update it. The getter should *never* write back to the path or
|
||||
/// attribute that is being watched or an infinite loop will occur.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// impl CtrlRogBios {
|
||||
/// task_watch_item!(panel_od platform);
|
||||
/// task_watch_item!(gpu_mux_mode platform);
|
||||
/// }
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! task_watch_item {
|
||||
($name:ident $self_inner:ident) => {
|
||||
concat_idents::concat_idents!(fn_name = watch_, $name {
|
||||
async fn fn_name(
|
||||
&self,
|
||||
signal_ctxt: SignalContext<'static>,
|
||||
) -> Result<(), RogError> {
|
||||
use zbus::export::futures_util::StreamExt;
|
||||
|
||||
let ctrl = self.clone();
|
||||
concat_idents::concat_idents!(watch_fn = monitor_, $name {
|
||||
match self.$self_inner.watch_fn() {
|
||||
Ok(mut watch) => {
|
||||
tokio::spawn(async move {
|
||||
let mut buffer = [0; 32];
|
||||
watch.event_stream(&mut buffer).unwrap().for_each(|_| async {
|
||||
let value = ctrl.$name();
|
||||
concat_idents::concat_idents!(notif_fn = notify_, $name {
|
||||
Self::notif_fn(&signal_ctxt, value).await.ok();
|
||||
});
|
||||
}).await;
|
||||
});
|
||||
}
|
||||
Err(e) => info!("inotify watch failed: {}. You can ignore this if your device does not support the feature", e),
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub fn print_board_info() {
|
||||
let dmi = sysfs_class::DmiId::default();
|
||||
let board_name = dmi.board_name().expect("Could not get board_name");
|
||||
let prod_family = dmi.product_family().expect("Could not get product_family");
|
||||
|
||||
info!("Product family: {}", prod_family.trim());
|
||||
info!("Board name: {}", board_name.trim());
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Reloadable {
|
||||
async fn reload(&mut self) -> Result<(), RogError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ZbusRun {
|
||||
async fn add_to_server(self, server: &mut Connection);
|
||||
|
||||
async fn add_to_server_helper(
|
||||
iface: impl zbus::Interface,
|
||||
path: &str,
|
||||
server: &mut Connection,
|
||||
) {
|
||||
server
|
||||
.object_server()
|
||||
.at(&ObjectPath::from_str_unchecked(path), iface)
|
||||
.await
|
||||
.map_err(|err| {
|
||||
warn!("{}: add_to_server {}", path, err);
|
||||
err
|
||||
})
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
|
||||
/// Set up a task to run on the async executor
|
||||
#[async_trait]
|
||||
pub trait CtrlTask {
|
||||
fn zbus_path() -> &'static str;
|
||||
|
||||
fn signal_context(connection: &Connection) -> Result<SignalContext<'static>, zbus::Error> {
|
||||
SignalContext::new(connection, Self::zbus_path())
|
||||
}
|
||||
|
||||
/// Implement to set up various tasks that may be required, using the
|
||||
/// `Executor`. No blocking loops are allowed, or they must be run on a
|
||||
/// separate thread.
|
||||
async fn create_tasks(&self, signal: SignalContext<'static>) -> Result<(), RogError>;
|
||||
|
||||
// /// Create a timed repeating task
|
||||
// async fn repeating_task(&self, millis: u64, mut task: impl FnMut() + Send +
|
||||
// 'static) { use std::time::Duration;
|
||||
// use tokio::time;
|
||||
// let mut timer = time::interval(Duration::from_millis(millis));
|
||||
// tokio::spawn(async move {
|
||||
// timer.tick().await;
|
||||
// task();
|
||||
// });
|
||||
// }
|
||||
|
||||
/// Free helper method to create tasks to run on: sleep, wake, shutdown,
|
||||
/// boot
|
||||
///
|
||||
/// The closures can potentially block, so execution time should be the
|
||||
/// minimal possible such as save a variable.
|
||||
async fn create_sys_event_tasks<
|
||||
Fut1,
|
||||
Fut2,
|
||||
Fut3,
|
||||
Fut4,
|
||||
F1: Send + 'static,
|
||||
F2: Send + 'static,
|
||||
F3: Send + 'static,
|
||||
F4: Send + 'static,
|
||||
>(
|
||||
&self,
|
||||
mut on_sleep: F1,
|
||||
mut on_wake: F2,
|
||||
mut on_shutdown: F3,
|
||||
mut on_boot: F4,
|
||||
) where
|
||||
F1: FnMut() -> Fut1,
|
||||
F2: FnMut() -> Fut2,
|
||||
F3: FnMut() -> Fut3,
|
||||
F4: FnMut() -> Fut4,
|
||||
Fut1: Future<Output = ()> + Send,
|
||||
Fut2: Future<Output = ()> + Send,
|
||||
Fut3: Future<Output = ()> + Send,
|
||||
Fut4: Future<Output = ()> + Send,
|
||||
{
|
||||
let connection = Connection::system()
|
||||
.await
|
||||
.expect("Controller could not create dbus connection");
|
||||
|
||||
let manager = ManagerProxy::new(&connection)
|
||||
.await
|
||||
.expect("Controller could not create ManagerProxy");
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Ok(mut notif) = manager.receive_prepare_for_sleep().await {
|
||||
while let Some(event) = notif.next().await {
|
||||
if let Ok(args) = event.args() {
|
||||
if args.start {
|
||||
debug!("Doing on_sleep()");
|
||||
on_sleep().await;
|
||||
} else if !args.start() {
|
||||
debug!("Doing on_wake()");
|
||||
on_wake().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let manager = ManagerProxy::new(&connection)
|
||||
.await
|
||||
.expect("Controller could not create ManagerProxy");
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Ok(mut notif) = manager.receive_prepare_for_shutdown().await {
|
||||
while let Some(event) = notif.next().await {
|
||||
if let Ok(args) = event.args() {
|
||||
if args.start {
|
||||
debug!("Doing on_shutdown()");
|
||||
on_shutdown().await;
|
||||
} else if !args.start() {
|
||||
debug!("Doing on_boot()");
|
||||
on_boot().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub trait GetSupported {
|
||||
type A;
|
||||
|
||||
fn get_supported() -> Self::A;
|
||||
}
|
||||
@@ -3,24 +3,24 @@
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<policy group="adm">
|
||||
<allow send_destination="org.asuslinux.Daemon"/>
|
||||
<allow receive_sender="org.asuslinux.Daemon"/>
|
||||
<allow send_destination="xyz.ljones.Asusd"/>
|
||||
<allow receive_sender="xyz.ljones.Asusd"/>
|
||||
</policy>
|
||||
<policy group="sudo">
|
||||
<allow send_destination="org.asuslinux.Daemon"/>
|
||||
<allow receive_sender="org.asuslinux.Daemon"/>
|
||||
<allow send_destination="xyz.ljones.Asusd"/>
|
||||
<allow receive_sender="xyz.ljones.Asusd"/>
|
||||
</policy>
|
||||
<policy group="users">
|
||||
<allow send_destination="org.asuslinux.Daemon"/>
|
||||
<allow receive_sender="org.asuslinux.Daemon"/>
|
||||
<allow send_destination="xyz.ljones.Asusd"/>
|
||||
<allow receive_sender="xyz.ljones.Asusd"/>
|
||||
</policy>
|
||||
<policy group="wheel">
|
||||
<allow send_destination="org.asuslinux.Daemon"/>
|
||||
<allow receive_sender="org.asuslinux.Daemon"/>
|
||||
<allow send_destination="xyz.ljones.Asusd"/>
|
||||
<allow receive_sender="xyz.ljones.Asusd"/>
|
||||
</policy>
|
||||
<policy user="root">
|
||||
<allow own="org.asuslinux.Daemon"/>
|
||||
<allow send_destination="org.asuslinux.Daemon"/>
|
||||
<allow receive_sender="org.asuslinux.Daemon"/>
|
||||
<allow own="xyz.ljones.Asusd"/>
|
||||
<allow send_destination="xyz.ljones.Asusd"/>
|
||||
<allow receive_sender="xyz.ljones.Asusd"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
#ACTION=="add|change", SUBSYSTEM=="input", ENV{ID_VENDOR_ID}=="0b05", ENV{ID_MODEL_ID}=="1[89][a-zA-Z0-9][a-zA-Z0-9]|193b", ENV{ID_TYPE}=="hid", TAG+="systemd", ENV{SYSTEMD_WANTS}="asusd.service"
|
||||
#ACTION=="add|remove", SUBSYSTEM=="input", ENV{ID_VENDOR_ID}=="0b05", ENV{ID_MODEL_ID}=="1[89][a-zA-Z0-9][a-zA-Z0-9]|193b", RUN+="systemctl restart asusd.service"
|
||||
|
||||
ENV{DMI_VENDOR}="$attr{[dmi/id]sys_vendor}"
|
||||
ENV{DMI_VENDOR}!="ASUSTeK COMPUTER INC.", GOTO="asusd_end"
|
||||
|
||||
@@ -10,11 +7,14 @@ ENV{DMI_FAMILY}=="*ROG*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*Zephyrus*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*Strix*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*Vivo*ook*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*Zenbook*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*ProArt*", GOTO="asusd_start"
|
||||
ENV{DMI_FAMILY}=="*TX Gaming*", GOTO="asusd_start"
|
||||
# No match so
|
||||
GOTO="asusd_end"
|
||||
|
||||
LABEL="asusd_start"
|
||||
ACTION=="add|change", DRIVER=="asus-nb-wmi", TAG+="systemd", ENV{SYSTEMD_WANTS}="asusd.service"
|
||||
ACTION=="add|remove", DRIVER=="asus-nb-wmi", TAG+="systemd", RUN+="systemctl restart asusd.service"
|
||||
ACTION=="add|remove", DRIVER=="asus-nb-wmi", TAG+="systemd", RUN+="/usr/bin/systemctl restart asusd.service"
|
||||
|
||||
LABEL="asusd_end"
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
[Unit]
|
||||
Description=ASUS Notebook Control
|
||||
StartLimitInterval=200
|
||||
StartLimitBurst=2
|
||||
Before=multi-user.target
|
||||
After=power-profiles-daemon.service
|
||||
After=nvidia-powerd.service
|
||||
StartLimitInterval=500
|
||||
StartLimitBurst=5
|
||||
After=nvidia-powerd.service systemd-udevd.service
|
||||
|
||||
[Service]
|
||||
Environment=IS_SERVICE=1
|
||||
Environment=RUST_LOG="info"
|
||||
ExecStartPre=/bin/sleep 2
|
||||
Environment=RUST_LOG="debug"
|
||||
# required to prevent init issues with hid_asus and MCU
|
||||
ExecStartPre=/bin/sleep 1
|
||||
ExecStart=/usr/bin/asusd
|
||||
Restart=on-failure
|
||||
RestartSec=1
|
||||
Type=dbus
|
||||
BusName=org.asuslinux.Daemon
|
||||
BusName=xyz.ljones.Asusd
|
||||
SELinuxContext=system_u:system_r:unconfined_t:s0
|
||||
#SELinuxContext=system_u:object_r:modules_object_t:s0
|
||||
#SELinuxContext=system_u:object_r:modules_object_t:s0
|
||||
TimeoutSec=10
|
||||
|
||||
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 75 KiB |
1
data/icons/scalable/anime.svg
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Generator: Gravit.io --><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 512 512" width="512pt" height="512pt"><defs><clipPath id="_clipPath_8C5izdJ0sH9w7nD5UuBTlpktuZWEWJn8"><rect width="512" height="512"/></clipPath></defs><g clip-path="url(#_clipPath_8C5izdJ0sH9w7nD5UuBTlpktuZWEWJn8)"><path d=" M 113.969 270.246 C 113.969 301.718 88.456 327.231 56.985 327.231 C 25.513 327.231 0 301.718 0 270.246 C 0 238.775 25.513 213.262 56.985 213.262 C 88.456 213.262 113.969 238.775 113.969 270.246 Z M 56.985 384.215 C 41.249 384.215 28.492 396.972 28.492 412.708 C 28.492 428.443 41.249 441.2 56.985 441.2 C 72.72 441.2 85.477 428.443 85.477 412.708 C 85.477 396.972 72.72 384.215 56.985 384.215 Z M 56.985 70.8 C 25.513 70.8 0 96.313 0 127.785 C 0 159.256 25.513 184.769 56.985 184.769 C 88.456 184.769 113.969 159.256 113.969 127.785 C 113.969 96.313 88.456 70.8 56.985 70.8 Z M 199.446 241.754 C 183.71 241.754 170.954 254.51 170.954 270.246 C 170.954 285.982 183.71 298.738 199.446 298.738 C 215.182 298.738 227.938 285.982 227.938 270.246 C 227.938 254.51 215.182 241.754 199.446 241.754 Z M 199.446 384.215 C 183.71 384.215 170.954 396.972 170.954 412.708 C 170.954 428.443 183.71 441.2 199.446 441.2 C 215.182 441.2 227.938 428.443 227.938 412.708 C 227.938 396.972 215.182 384.215 199.446 384.215 Z M 199.446 70.8 C 167.975 70.8 142.462 96.313 142.462 127.785 C 142.462 159.256 167.975 184.769 199.446 184.769 C 230.918 184.769 256.431 159.256 256.431 127.785 C 256.431 96.313 230.918 70.8 199.446 70.8 Z M 339.904 241.754 C 324.169 241.754 311.412 254.51 311.412 270.246 C 311.412 285.982 324.169 298.738 339.904 298.738 C 355.64 298.738 368.397 285.982 368.397 270.246 C 368.397 254.51 355.64 241.754 339.904 241.754 Z M 339.904 384.215 C 324.169 384.215 311.412 396.972 311.412 412.708 C 311.412 428.443 324.169 441.2 339.904 441.2 C 355.64 441.2 368.397 428.443 368.397 412.708 C 368.397 396.972 355.64 384.215 339.904 384.215 Z M 339.904 70.8 C 308.433 70.8 282.92 96.313 282.92 127.785 C 282.92 159.256 308.433 184.769 339.904 184.769 C 371.376 184.769 396.889 159.256 396.889 127.785 C 396.889 96.313 371.376 70.8 339.904 70.8 Z M 482.366 241.754 C 466.63 241.754 453.874 254.51 453.874 270.246 C 453.874 285.982 466.63 298.738 482.366 298.738 C 498.102 298.738 510.858 285.982 510.858 270.246 C 510.858 254.51 498.102 241.754 482.366 241.754 Z M 482.366 384.215 C 466.63 384.215 453.874 396.972 453.874 412.708 C 453.874 428.443 466.63 441.2 482.366 441.2 C 498.102 441.2 510.858 428.443 510.858 412.708 C 510.858 396.972 498.102 384.215 482.366 384.215 Z M 482.366 99.292 C 466.63 99.292 453.874 112.049 453.874 127.785 C 453.874 143.52 466.63 156.277 482.366 156.277 C 498.102 156.277 510.858 143.52 510.858 127.785 C 510.858 112.049 498.102 99.292 482.366 99.292 Z " fill="#F2F2F2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 2.9 KiB |
1
data/icons/scalable/reboot.svg
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Generator: Gravit.io --><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="141 297.96 507.339 471.04" width="507.339pt" height="471.04pt"><g><g><g><g><path d=" M 537.075 443.463 L 537.075 443.463 L 564.723 427.335 C 504.903 324.571 375.966 285.313 269.027 337.304 L 269.027 297.96 L 237.027 297.96 L 237.027 393.96 L 333.027 393.96 L 333.027 361.96 L 292.147 361.96 C 382.665 323.563 487.612 358.486 537.075 443.463 Z " fill="rgb(221,221,221)"/><path d=" M 245.027 692.775 C 170.84 632.524 151.314 527.353 198.931 444.488 L 171.187 428.488 C 116.876 523.063 137.426 642.887 220.147 713.96 L 181.027 713.96 L 181.027 745.96 L 277.027 745.96 L 277.027 649.96 L 245.027 649.96 L 245.027 692.775 L 245.027 692.775 Z " fill="rgb(221,221,221)"/><path d=" M 580.451 499.048 L 512.579 566.936 L 535.203 589.56 L 562.403 562.36 C 551.734 661.49 468.201 736.724 368.499 737 L 368.499 769 C 487.289 768.688 585.833 677.011 594.707 558.552 L 625.715 589.56 L 648.339 566.936 L 580.451 499.048 Z " fill="rgb(221,221,221)"/></g></g></g></g></svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
1
data/icons/scalable/rog-logo.svg
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!-- Generator: Gravit.io --><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="isolation:isolate" viewBox="0 0 128 128" width="128pt" height="128pt"><defs><clipPath id="_clipPath_CHRnLOITGqiXLlZjYLaUfMylStiUiIRD"><rect width="128" height="128"/></clipPath></defs><g clip-path="url(#_clipPath_CHRnLOITGqiXLlZjYLaUfMylStiUiIRD)"><path d=" M 69.096 31.645 C 68.865 31.712 68.805 31.816 68.577 32.011 C 68.393 32.168 68.238 32.28 68.059 32.434 C 67.651 32.785 67.411 33.003 67.052 33.305 C 65.269 34.805 62.85 37.142 61.102 38.778 C 58.391 41.317 55.947 43.762 53.346 46.287 C 48.441 51.049 42.882 56.766 37.972 61.357 C 33.914 65.151 30.434 68.558 26.194 72.351 C 24.574 73.801 23.553 75.121 21.346 75.197 C 17.705 75.323 12.902 72.224 10.446 70.814 C 8.299 69.583 2.598 66.23 -0.15 66.137 L 1.864 68.903 C 3.303 71.1 5.724 75.885 6.887 78.214 C 10.881 86.213 16.273 94.589 23.136 100.161 C 24.891 101.586 26.481 102.783 28.71 104.132 C 29.687 104.723 30.685 105.215 31.778 105.834 C 32.157 106.049 34.786 107.277 35.11 107.276 C 34.39 106.554 33.649 105.673 33.064 104.985 C 30.452 101.912 24.64 95.938 22.894 92.889 C 21.428 90.329 21.091 88.761 22.72 86.192 C 24.582 83.254 28.924 79.619 31.648 77.289 C 38.277 71.62 44.256 66.485 51.191 61.102 C 54.478 58.551 57.895 55.949 61.429 53.427 C 64.896 50.954 68.381 48.57 72 46.178 L 77.465 42.7 C 77.972 42.409 82.95 39.446 83.029 39.347 L 87.9 36.66 C 89.536 35.736 91.124 34.964 92.857 34.031 C 97.94 31.294 108.035 26.833 113.82 24.792 C 115.718 24.122 117.528 23.489 119.449 22.833 L 125.205 21.03 C 124.739 20.79 118.379 20.724 117.207 20.724 C 112.491 20.723 109.598 20.855 105.095 21.211 C 101.65 21.483 95.237 22.19 92.104 22.948 C 91.54 23.084 90.872 23.142 90.304 23.292 C 89.218 23.578 87.974 23.775 86.861 24.052 C 84.567 24.623 82.484 25.271 80.328 25.914 C 78.108 26.575 76.101 27.36 74.115 28.177 C 72.942 28.659 69.397 31.029 69.096 31.645 L 69.096 31.645 Z M 115.16 43.036 L 119.345 40.899 C 120.797 40.208 122.299 39.413 123.667 38.745 C 126.441 37.389 128.04 32.995 127.999 30.179 C 127.509 30.199 125.516 31.144 124.975 31.342 C 124.603 31.479 124.259 31.596 123.911 31.744 C 121.439 32.794 118.139 34.036 115.795 35.142 C 115.115 35.463 114.457 35.729 113.769 36.024 C 113.228 36.256 112.036 36.724 111.814 36.999 C 111.07 36.962 95.925 44.467 94.037 45.443 C 91.35 46.833 87.97 48.499 85.386 49.936 C 85.08 50.106 77.204 54.275 76.891 54.676 C 76.372 54.762 70.974 57.968 70.112 58.454 C 59.43 64.482 47.599 72.065 37.367 79.004 C 34.524 80.933 30.892 83.463 28.034 85.617 L 25.739 87.329 C 25.476 87.53 25.165 87.663 25.013 87.965 C 26.033 88.843 32.791 91.628 34.403 92.209 C 43.451 95.47 51.92 97.742 61.441 99.376 L 67.483 100.3 L 72.241 100.72 L 68.366 100.378 C 69.105 100.462 69.839 100.582 70.559 100.651 C 71.624 100.753 72.679 100.84 73.776 100.949 C 75.841 101.157 78.238 101.298 80.361 101.335 C 82.999 101.381 84.453 101.516 86.617 100.603 C 88.294 99.894 89.659 99.013 90.992 97.992 C 95.957 94.187 100.375 88.235 103.899 82.849 C 107.587 77.213 110.909 70.915 113.773 64.675 C 115.231 61.498 116.599 58.182 117.888 54.804 C 118.541 53.092 119.107 51.439 119.697 49.622 C 120.023 48.617 121.212 44.945 121.302 44.125 C 119.948 44.31 96.265 57.088 94.012 58.297 C 90.956 59.938 88.029 61.647 85.064 63.258 C 82.182 64.823 79.134 66.672 76.267 68.266 C 70.441 71.504 64.575 75.11 58.757 78.479 C 57.76 79.056 50.352 83.387 50.086 83.691 C 50.584 83.611 74.07 73.525 74.639 73.29 C 75.746 72.832 98.806 62.937 99.184 62.92 C 99.052 63.454 97.624 66.118 97.264 66.901 C 96.664 68.206 95.94 69.692 95.284 70.989 C 91.565 78.346 87.529 87.178 79.411 90.439 L 78.923 90.732 C 78.488 90.742 77.299 91.225 76.775 91.369 C 75.986 91.586 75.223 91.736 74.428 91.899 C 70.686 92.665 65.028 92.266 61.129 91.656 C 56.682 90.96 53.568 90.179 49.258 89.137 C 48.229 88.889 40.792 86.799 40.362 86.516 C 40.604 86.093 44.858 83.368 45.23 83.109 C 53.46 77.389 67.13 68.983 76.02 63.925 C 76.961 63.389 77.835 62.903 78.696 62.41 C 79.411 62 80.72 61.317 81.298 60.897 L 85.457 58.616 C 86.864 57.835 88.155 57.159 89.637 56.314 C 92.438 54.716 95.275 53.376 98.032 51.823 C 98.437 51.595 114.179 43.323 115.159 43.037 L 115.16 43.036 Z " fill-rule="evenodd" fill="#F2F2F2"/></g></svg>
|
||||
|
After Width: | Height: | Size: 4.2 KiB |
@@ -135,7 +135,7 @@ impl crate::ZbusAdd for CtrlAnimeZbus {
|
||||
}
|
||||
}
|
||||
|
||||
#[dbus_interface(name = "org.asuslinux.Daemon")]
|
||||
#[dbus_interface(name = "xyz.ljones.Asusd")]
|
||||
impl CtrlAnimeZbus {
|
||||
async fn <zbus method>() {
|
||||
let lock = self.inner.lock().await;
|
||||
|
||||
143
distro-packaging/asusctl.spec
Executable file
@@ -0,0 +1,143 @@
|
||||
#
|
||||
# spec file for package asus-nb-ctrl
|
||||
#
|
||||
# Copyright (c) 2020-2025 Luke Jones <luke@ljones.dev>
|
||||
#
|
||||
# All modifications and additions to the file contributed by third parties
|
||||
# remain the property of their copyright owners, unless otherwise agreed
|
||||
# upon. The license for this file, and modifications and additions to the
|
||||
# file, is the same license as for the pristine package itself (unless the
|
||||
# license for the pristine package is not an Open Source License, in which
|
||||
# case the license is the MIT License). An "Open Source License" is a
|
||||
# license that conforms to the Open Source Definition (Version 1.9)
|
||||
# published by the Open Source Initiative.
|
||||
|
||||
# This Source Code Form is subject to the terms of the Mozilla Public
|
||||
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
%if %{defined fedora}
|
||||
%global debug_package %{nil}
|
||||
%endif
|
||||
|
||||
%define version 6.1.13
|
||||
%define specrelease %{?dist}
|
||||
%define pkg_release 9%{specrelease}
|
||||
|
||||
# Use hardening ldflags.
|
||||
%global rustflags -Clink-arg=-Wl,-z,relro,-z,now
|
||||
Name: asusctl
|
||||
Version: %{version}
|
||||
Release: %{pkg_release}
|
||||
Summary: Control fan speeds, LEDs, graphics modes, and charge levels for ASUS notebooks
|
||||
License: MPLv2
|
||||
Requires: power-profiles-daemon
|
||||
|
||||
Group: System Environment/Kernel
|
||||
|
||||
URL: https://gitlab.com/asus-linux/asusctl
|
||||
Source: https://gitlab.com/asus-linux/asusctl/-/archive/%{version}/%{name}-%{version}.tar.gz
|
||||
|
||||
%if %{defined fedora}
|
||||
BuildRequires: rust-packaging
|
||||
BuildRequires: systemd-rpm-macros
|
||||
%else
|
||||
BuildRequires: cargo-packaging
|
||||
%endif
|
||||
BuildRequires: git
|
||||
BuildRequires: clang-devel
|
||||
BuildRequires: cargo
|
||||
BuildRequires: cmake
|
||||
BuildRequires: rust
|
||||
BuildRequires: rust-std-static
|
||||
BuildRequires: pkgconfig(gbm)
|
||||
BuildRequires: pkgconfig(libinput)
|
||||
BuildRequires: pkgconfig(libseat)
|
||||
BuildRequires: pkgconfig(libudev)
|
||||
BuildRequires: pkgconfig(xkbcommon)
|
||||
BuildRequires: pkgconfig(libzstd)
|
||||
BuildRequires: desktop-file-utils
|
||||
|
||||
%description
|
||||
asus-nb-ctrl 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.
|
||||
|
||||
It provides an interface for rootless control of some system functions such as
|
||||
fan speeds, keyboard LEDs, battery charge level, and graphics modes.
|
||||
asus-nb-ctrl enables third-party apps to use the above with dbus methods.
|
||||
|
||||
%package rog-gui
|
||||
Summary: An experimental GUI for %{name}
|
||||
|
||||
%description rog-gui
|
||||
A one-stop-shop GUI tool for asusd/asusctl. It aims to provide most controls,
|
||||
a notification service, and ability to run in the background.
|
||||
|
||||
%prep
|
||||
%autosetup
|
||||
%if %{defined fedora}
|
||||
%cargo_prep
|
||||
sed -i 's|offline = true|offline = false|' .cargo/config.toml
|
||||
sed -i 's|source.crates-io|source.ignore_this|' .cargo/config.toml
|
||||
%else
|
||||
mkdir -p .cargo
|
||||
cat > .cargo/config.toml << 'EOF'
|
||||
[term]
|
||||
verbose = true
|
||||
[net]
|
||||
offline = false
|
||||
EOF
|
||||
%endif
|
||||
|
||||
%build
|
||||
export RUSTFLAGS="%{rustflags}"
|
||||
%if %{defined fedora}
|
||||
%cargo_build
|
||||
%else
|
||||
/usr/bin/cargo auditable build --release
|
||||
%endif
|
||||
|
||||
%install
|
||||
export RUSTFLAGS="%{rustflags}"
|
||||
mkdir -p "%{buildroot}/%{_bindir}" "%{buildroot}%{_docdir}"
|
||||
%make_install
|
||||
|
||||
install -D -m 0644 README.md %{buildroot}/%{_docdir}/%{name}/README.md
|
||||
install -D -m 0644 rog-anime/README.md %{buildroot}/%{_docdir}/%{name}/README-anime.md
|
||||
install -D -m 0644 rog-anime/data/diagonal-template.png %{buildroot}/%{_docdir}/%{name}/diagonal-template.png
|
||||
|
||||
desktop-file-validate %{buildroot}/%{_datadir}/applications/rog-control-center.desktop
|
||||
|
||||
%files
|
||||
%license LICENSE
|
||||
%{_bindir}/asusd
|
||||
%{_bindir}/asusd-user
|
||||
%{_bindir}/asusctl
|
||||
%{_unitdir}/asusd.service
|
||||
%{_userunitdir}/asusd-user.service
|
||||
%{_udevrulesdir}/99-asusd.rules
|
||||
#%dir %{_sysconfdir}/asusd/
|
||||
%{_datadir}/asusd/aura_support.ron
|
||||
%{_datadir}/dbus-1/system.d/asusd.conf
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_yellow.png
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_green.png
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_red.png
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_blue.png
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_orange.png
|
||||
%{_datadir}/icons/hicolor/512x512/apps/asus_notif_white.png
|
||||
%{_datadir}/icons/hicolor/scalable/status/gpu-compute.svg
|
||||
%{_datadir}/icons/hicolor/scalable/status/gpu-hybrid.svg
|
||||
%{_datadir}/icons/hicolor/scalable/status/gpu-integrated.svg
|
||||
%{_datadir}/icons/hicolor/scalable/status/gpu-nvidia.svg
|
||||
%{_datadir}/icons/hicolor/scalable/status/gpu-vfio.svg
|
||||
%{_datadir}/icons/hicolor/scalable/status/notification-reboot.svg
|
||||
%{_docdir}/%{name}/
|
||||
%{_datadir}/asusd/
|
||||
|
||||
%files rog-gui
|
||||
%{_bindir}/rog-control-center
|
||||
%{_datadir}/applications/rog-control-center.desktop
|
||||
%{_datadir}/icons/hicolor/512x512/apps/rog-control-center.png
|
||||
%{_datadir}/rog-gui
|
||||
|
||||
%changelog
|
||||
13
dmi-id/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "dmi_id"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[dependencies]
|
||||
log.workspace = true
|
||||
udev.workspace = true
|
||||
111
dmi-id/src/lib.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use log::warn;
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Clone)]
|
||||
pub struct DMIID {
|
||||
pub id_model: String,
|
||||
pub dmi_family: String,
|
||||
pub dmi_vendor: String,
|
||||
pub board_name: String,
|
||||
pub board_vendor: String,
|
||||
pub bios_date: String,
|
||||
pub bios_release: String,
|
||||
pub bios_vendor: String,
|
||||
pub bios_version: String,
|
||||
pub product_family: String,
|
||||
pub product_name: String,
|
||||
}
|
||||
|
||||
impl DMIID {
|
||||
pub fn new() -> Result<Self, String> {
|
||||
let mut enumerator = udev::Enumerator::new().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
format!("dmi enumerator failed: {err}")
|
||||
})?;
|
||||
|
||||
enumerator.match_subsystem("dmi").map_err(|err| {
|
||||
warn!("{}", err);
|
||||
format!("dmi match_subsystem failed: {err}")
|
||||
})?;
|
||||
|
||||
let mut result = enumerator.scan_devices().map_err(|err| {
|
||||
warn!("{}", err);
|
||||
format!("dmi scan_devices failed: {err}")
|
||||
})?;
|
||||
|
||||
if let Some(device) = (result).next() {
|
||||
return Ok(Self {
|
||||
id_model: device
|
||||
.property_value("ID_MODEL")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
dmi_family: device
|
||||
.property_value("DMI_FAMILY")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
dmi_vendor: device
|
||||
.property_value("DMI_VENDOR")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
board_name: device
|
||||
.attribute_value("board_name")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
board_vendor: device
|
||||
.attribute_value("board_vendor")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
bios_date: device
|
||||
.attribute_value("bios_date")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
bios_release: device
|
||||
.attribute_value("bios_release")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
bios_vendor: device
|
||||
.attribute_value("bios_vendor")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
bios_version: device
|
||||
.attribute_value("bios_version")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
product_family: device
|
||||
.attribute_value("product_family")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
product_name: device
|
||||
.attribute_value("product_name")
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or("Unknown".to_string()),
|
||||
});
|
||||
}
|
||||
Err("dmi not found".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "Does not run in docker images"]
|
||||
fn dmi_sysfs_properties_not_unknown() {
|
||||
let dmi = DMIID::new().unwrap();
|
||||
|
||||
assert_ne!(dmi.id_model, "Unknown".to_string());
|
||||
dbg!(dmi.id_model);
|
||||
assert_ne!(dmi.dmi_family, "Unknown".to_string());
|
||||
dbg!(dmi.dmi_family);
|
||||
assert_ne!(dmi.dmi_vendor, "Unknown".to_string());
|
||||
dbg!(dmi.dmi_vendor);
|
||||
assert_ne!(dmi.board_name, "Unknown".to_string());
|
||||
dbg!(dmi.board_name);
|
||||
assert_ne!(dmi.board_vendor, "Unknown".to_string());
|
||||
dbg!(dmi.board_vendor);
|
||||
assert_ne!(dmi.product_family, "Unknown".to_string());
|
||||
dbg!(dmi.product_family);
|
||||
assert_ne!(dmi.product_name, "Unknown".to_string());
|
||||
dbg!(dmi.product_name);
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 35 KiB |
BIN
extra/system.png
|
Before Width: | Height: | Size: 50 KiB |
@@ -1,21 +1,25 @@
|
||||
[package]
|
||||
name = "rog_anime"
|
||||
license = "MPL-2.0"
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
readme = "README.md"
|
||||
authors = ["Luke <luke@ljones.dev>"]
|
||||
repository = "https://gitlab.com/asus-linux/asus-nb-ctrl"
|
||||
homepage = "https://gitlab.com/asus-linux/asus-nb-ctrl"
|
||||
readme.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
homepage.workspace = true
|
||||
edition.workspace = true
|
||||
documentation = "https://docs.rs/rog-anime"
|
||||
description = "Types useful for translating images and other data for display on the ASUS AniMe Matrix display"
|
||||
keywords = ["ROG", "ASUS", "AniMe"]
|
||||
edition = "2021"
|
||||
exclude = ["data"]
|
||||
|
||||
[features]
|
||||
default = ["dbus", "detect"]
|
||||
dbus = ["zbus"]
|
||||
detect = ["sysfs-class"]
|
||||
detect = ["dmi_id"]
|
||||
|
||||
[lib]
|
||||
name = "rog_anime"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
png_pong.workspace = true
|
||||
@@ -24,15 +28,9 @@ gif.workspace = true
|
||||
log.workspace = true
|
||||
|
||||
serde.workspace = true
|
||||
serde_derive.workspace = true
|
||||
|
||||
glam.workspace = true
|
||||
|
||||
zbus = { workspace = true, optional = true }
|
||||
|
||||
sysfs-class = { workspace = true, optional = true }
|
||||
|
||||
uhid-virt = "^0.0.6"
|
||||
|
||||
[dev-dependencies]
|
||||
cargo-husky.workspace = true
|
||||
dmi_id = { path = "../dmi-id", optional = true }
|
||||
|
||||
BIN
rog-anime/data/anime/custom/cross.png
Normal file
|
After Width: | Height: | Size: 4.4 KiB |
BIN
rog-anime/data/anime/gu604/Fighting Games 2022_GU604.gif
Normal file
|
After Width: | Height: | Size: 313 KiB |
BIN
rog-anime/data/anime/gu604/Halloween II_GU604.gif
Normal file
|
After Width: | Height: | Size: 230 KiB |
BIN
rog-anime/data/anime/gu604/Infinite triangle_GU604.gif
Normal file
|
After Width: | Height: | Size: 72 KiB |
BIN
rog-anime/data/anime/gu604/Lunar new year dragon dance_GU604.gif
Normal file
|
After Width: | Height: | Size: 229 KiB |