Compare commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
51e12b1426 | ||
|
|
b1c9682121 | ||
|
|
05281eb3dc | ||
|
|
2fd66f8e67 | ||
|
|
fdf3b4e8cb | ||
|
|
8db2c7e7ef | ||
|
|
cc010a8eea | ||
|
|
d09431da65 | ||
|
|
51d2512944 | ||
|
|
e4c96df66e | ||
|
|
48f3fc5310 | ||
|
|
30a58299a6 | ||
|
|
d420ae5400 | ||
|
|
ac66096e58 | ||
|
|
4427d1de97 | ||
|
|
6a43681bee | ||
|
|
a3d8211460 | ||
|
|
cfc679cbc8 | ||
|
|
bf170553f9 | ||
|
|
08969ecb13 | ||
|
|
eae8280062 | ||
|
|
c61cbf239c | ||
|
|
58e4bac3c8 | ||
|
|
34a9c88d91 | ||
|
|
61c33c8fec | ||
|
|
9dec8293cd | ||
|
|
0c85948556 | ||
|
|
ad4949d2ac | ||
|
|
d8ef68836d | ||
|
|
223c6f7532 | ||
|
|
a9fa1cd2a2 | ||
|
|
7cf0170de7 | ||
|
|
fae8cdd2bf | ||
|
|
c5f640b2a9 | ||
|
|
af0beccb4a | ||
|
|
d05d9db8a2 | ||
|
|
dd461eaa16 | ||
|
|
5e61ca20cb | ||
|
|
d58af23ebb | ||
|
|
85b860a138 | ||
|
|
016aff7169 | ||
|
|
370cb79078 | ||
|
|
d9a9187506 | ||
|
|
a320c12bdd | ||
|
|
3fa1e681d9 | ||
|
|
c778ab8a39 | ||
|
|
e32d424eda | ||
|
|
1e52b4dd2a | ||
|
|
c175a54a01 | ||
|
|
3f3e93c87d | ||
|
|
1621537d77 | ||
|
|
10d9d0a45a | ||
|
|
e11c39e933 | ||
|
|
a1eae4c3a2 | ||
|
|
de0af29b6d | ||
|
|
8cf09e69af | ||
|
|
3e826e87cd | ||
|
|
920f0d7217 | ||
|
|
e7349c7bf4 | ||
|
|
1c59b82ff7 | ||
|
|
af5b5cc6b5 | ||
|
|
d120c6ecd7 | ||
|
|
09789fdf2f | ||
|
|
4d78e87447 | ||
|
|
55f2d11721 | ||
|
|
3309cdb6ba | ||
|
|
10fe1430fe | ||
|
|
83c607d995 | ||
|
|
faebecacb6 | ||
|
|
ebd5d37039 | ||
|
|
34e5fa1403 | ||
|
|
d1ca64d1c1 | ||
|
|
7d3f5db206 | ||
|
|
91a8bb9c3c | ||
|
|
ae430e84c7 | ||
|
|
f9e7c4ef94 | ||
|
|
d3a84dd451 | ||
|
|
653015b2e7 | ||
|
|
8ac8f04128 | ||
|
|
80c70ebcdc | ||
|
|
792f368175 | ||
|
|
859dbee1f1 | ||
|
|
8f3b81c368 | ||
|
|
0274183730 | ||
|
|
c9f54224bb | ||
|
|
02c705d41e | ||
|
|
76bbc9d023 | ||
|
|
780ca53931 | ||
|
|
fc86c6190e | ||
|
|
2dd0ed6d59 | ||
|
|
1f06629838 | ||
|
|
c477560632 | ||
|
|
548160f7f8 | ||
|
|
a86a380dc7 | ||
|
|
d9fdaf1930 | ||
|
|
102feccb2e | ||
|
|
1b86bca19a | ||
|
|
fed28527ae | ||
|
|
2aa770a07b | ||
|
|
4362c0a015 | ||
|
|
2983ac89e6 | ||
|
|
4a6e072946 | ||
|
|
ac6a2e5b3f | ||
|
|
e01da7ae87 | ||
|
|
70540ff041 | ||
|
|
3ecec25fce | ||
|
|
2f5736e67d | ||
|
|
97db033eb8 | ||
|
|
c972a975fd | ||
|
|
42a05a7a67 | ||
|
|
2a72842a7a | ||
|
|
c97df82538 | ||
|
|
6b120731a3 | ||
|
|
d39d2777d1 | ||
|
|
afece72444 | ||
|
|
6031d95fe8 | ||
|
|
84f2400bef | ||
|
|
e7f6e0580c | ||
|
|
689321da1a | ||
|
|
b220f2ac8b | ||
|
|
6489fb56ab | ||
|
|
003cc942d8 | ||
|
|
9c30b33b39 | ||
|
|
405b9a91a7 | ||
|
|
526941eb33 | ||
|
|
34f7faf0a8 | ||
|
|
4068465ee6 | ||
|
|
9405f28525 | ||
|
|
571f4cbc7d | ||
|
|
e8f68f8fc4 | ||
|
|
4591d171d6 | ||
|
|
3185ce8b5e | ||
|
|
e575512ebb | ||
|
|
4f8c2a72e9 | ||
|
|
3c6021a290 | ||
|
|
dafa377cbe | ||
|
|
7ed47f7b7e | ||
|
|
bd52a23bec | ||
|
|
e84ab41fe6 | ||
|
|
41d5e79f83 | ||
|
|
c13734cbc9 | ||
|
|
e78402c860 | ||
|
|
2ce80eeaef | ||
|
|
551bdc2d65 | ||
|
|
f507bdb343 | ||
|
|
395aa62bda | ||
|
|
d2b2876a79 | ||
|
|
8bb7d39c76 | ||
|
|
e296217f21 | ||
|
|
c0257f4be2 | ||
|
|
7b88b61b22 | ||
|
|
ab61787ee7 | ||
|
|
219a65ae27 | ||
|
|
94d4665185 | ||
|
|
ce97171d5a | ||
|
|
a22f590395 | ||
|
|
a520c5c5e1 | ||
|
|
cab26bbf41 | ||
|
|
6c8159c5f7 | ||
|
|
df0e9cef9b | ||
|
|
7a6ab3b35a | ||
|
|
aa5addb5d9 | ||
|
|
b67d06ce43 | ||
|
|
8d9a580f50 | ||
|
|
45eb77f431 | ||
|
|
2be6fe3ff9 | ||
|
|
a380900ec8 | ||
|
|
bca788c5e6 | ||
|
|
e77aaa3675 | ||
|
|
d25894149b | ||
|
|
68eec2b28b | ||
|
|
694aaf1f0e | ||
|
|
5caa4ce0ae | ||
|
|
af5b26c934 | ||
|
|
6997bc7600 | ||
|
|
9eedbf60a8 | ||
|
|
6294646922 | ||
|
|
42797b1a43 | ||
|
|
8c3751aba0 | ||
|
|
f40353725e | ||
|
|
3f0d71f788 | ||
|
|
f2ba7ce630 | ||
|
|
edc3d50136 | ||
|
|
a7a600035a | ||
|
|
3f05806563 | ||
|
|
2fb19ee66d | ||
|
|
d91ca5fbb3 | ||
|
|
7173f33d5f | ||
|
|
b3f9e1fe21 | ||
|
|
401ba918ad | ||
|
|
82d5a768f8 | ||
|
|
835109c81a | ||
|
|
d5f2c12fe7 | ||
|
|
11f169b080 | ||
|
|
96d23b16fc | ||
|
|
26db18e250 | ||
|
|
8fee7e1a9b | ||
|
|
e7cf98889b | ||
|
|
3fdff2a92b | ||
|
|
4d5a485933 | ||
|
|
b9cbbb857b | ||
|
|
56de0f2c74 | ||
|
|
68fe0532ce | ||
|
|
3edde418a2 | ||
|
|
923f281bf6 | ||
|
|
9ea276ba77 | ||
|
|
cfb0f9b734 | ||
|
|
993930eb82 | ||
|
|
17d6cb5be0 | ||
|
|
bb725ee451 | ||
|
|
b5ce7b0fa0 | ||
|
|
58de6a025d | ||
|
|
e6937cb49c | ||
|
|
7ac9e5a806 | ||
|
|
89630878af | ||
|
|
8b2012fad3 | ||
|
|
07ddaf5e4c | ||
|
|
4d10096ba2 | ||
|
|
5e9699613d | ||
|
|
b56a3a795f | ||
|
|
70fac068d0 | ||
|
|
d138bd9464 | ||
|
|
e14e3dfa21 | ||
|
|
30541ae4af | ||
|
|
74bace639c | ||
|
|
dda21a54ff | ||
|
|
d8f42c769c | ||
|
|
7b8e178723 | ||
|
|
b1c42efa82 | ||
|
|
acd5d4406d | ||
|
|
83548a859f | ||
|
|
79598fffa6 | ||
|
|
72e62127b3 | ||
|
|
67010a57f2 | ||
|
|
daa221a158 | ||
|
|
aca1e3054e | ||
|
|
6b5734d535 | ||
|
|
de8700f8e0 | ||
|
|
e101e5c5f4 | ||
|
|
8d22602761 | ||
|
|
f452ce1f1e | ||
|
|
3281da7f5c | ||
|
|
08c7fd7676 | ||
|
|
2e62616b46 | ||
|
|
9be4c4d3a5 | ||
|
|
f5698771e4 | ||
|
|
151a2c1754 | ||
|
|
13693a0a53 | ||
|
|
451280edd2 | ||
|
|
c997057a37 | ||
|
|
f8900e531a | ||
|
|
6e5b57fd7c | ||
|
|
408e474130 | ||
|
|
ef707ec217 | ||
|
|
8b12760dde | ||
|
|
cae64639bd | ||
|
|
be696d116b | ||
|
|
23969121e5 | ||
|
|
4da2d7129a | ||
|
|
2be5ad0b7d | ||
|
|
f44ab75c64 | ||
|
|
7aa05dc609 | ||
|
|
7b81d140ec | ||
|
|
1be1d56599 | ||
|
|
2df0a78eb2 | ||
|
|
c3253dceac | ||
|
|
ef068eca81 | ||
|
|
f9ae811702 | ||
|
|
ea0098d705 | ||
|
|
4991a146d5 | ||
|
|
849250bfa8 | ||
|
|
d83f1d4cce | ||
|
|
4c7e71f21f | ||
|
|
107f85b818 | ||
|
|
3a466b4c38 | ||
|
|
08663fa339 | ||
|
|
8e86872aa7 | ||
|
|
2d059e9ff5 | ||
|
|
9f77c54955 | ||
|
|
f827c3e493 | ||
|
|
ae2f2fac41 | ||
|
|
1f70d36e74 | ||
|
|
7d27bfdcaf | ||
|
|
023d61a1e9 | ||
|
|
85d90a7f95 | ||
|
|
e0295eebde | ||
|
|
ebc9143593 | ||
|
|
e7c8fd748c | ||
|
|
aff601f61a | ||
|
|
0c5089fa79 | ||
|
|
e5556f3706 | ||
|
|
09c7f8541e | ||
|
|
8eb2ef438c | ||
|
|
34abe14151 | ||
|
|
90e37c198f | ||
|
|
1373283947 | ||
|
|
065616a18b | ||
|
|
53cd55a2a0 | ||
|
|
079be37fff | ||
|
|
806a8c57d4 | ||
|
|
797e769cc3 | ||
|
|
822a72e246 | ||
|
|
58b564b385 | ||
|
|
7aa9e2f6a4 | ||
|
|
f645686d87 | ||
|
|
6fcaa5d3d4 | ||
|
|
5d19e17a0b | ||
|
|
52a9f1ac1d | ||
|
|
3dec5e3225 | ||
|
|
90ded1612a | ||
|
|
7ab9fb7c28 | ||
|
|
6f499c68e2 | ||
|
|
19beba8fd7 | ||
|
|
f7e33802c8 | ||
|
|
c03d94105c | ||
|
|
632d56737b | ||
|
|
8801b93973 | ||
|
|
390a2b988e | ||
|
|
a66d7a64e6 | ||
|
|
a8596d3350 | ||
|
|
8a5dabee95 | ||
|
|
da859468d3 | ||
|
|
3e4583bbe9 | ||
|
|
b47440dd72 | ||
|
|
357a05f7ec | ||
|
|
f2fdb8195c | ||
|
|
8a0275d962 | ||
|
|
ef1fd9f579 | ||
|
|
f6b95d94bc | ||
|
|
2a65e6d359 | ||
|
|
83f87ba22c | ||
|
|
01321f5200 | ||
|
|
3a5851939e | ||
|
|
7d929e626e | ||
|
|
d8e0c77951 | ||
|
|
78ddb8ffb6 | ||
|
|
db37f35d09 | ||
|
|
d8f5fe4fd0 | ||
|
|
015fade4c0 | ||
|
|
da14b51e80 | ||
|
|
7a5ac01d1c | ||
|
|
5e6d64e965 | ||
|
|
c425fa41aa | ||
|
|
781157299f | ||
|
|
0f30317bb4 | ||
|
|
1f1bc0a7b9 | ||
|
|
60c8a6608a | ||
|
|
86adaf8c6b | ||
|
|
731688d16e | ||
|
|
63b66c48d8 | ||
|
|
ea19e511c0 | ||
|
|
f5e401cff8 | ||
|
|
bc8c7f318b | ||
|
|
585750007d | ||
|
|
6e80ac976a | ||
|
|
c70f18fcf4 | ||
|
|
d3e6aa2be2 | ||
|
|
b7a869c514 | ||
|
|
19362b950a | ||
|
|
0a4c31fb36 | ||
|
|
fef7694b48 | ||
|
|
60206e21df | ||
|
|
b9b77c66ce | ||
|
|
745a0e39d7 | ||
|
|
23bdadab56 | ||
|
|
47a4844ce8 | ||
|
|
8741be6cba | ||
|
|
4656a03ea9 | ||
|
|
5763eb828e | ||
|
|
6a5c20a165 | ||
|
|
fac166f186 | ||
|
|
091291bfa2 | ||
|
|
288fde67e8 | ||
|
|
ce30b77328 | ||
|
|
8c4e404f23 | ||
|
|
e8a4713f6e | ||
|
|
b4b23afc10 | ||
|
|
8f32e82d14 | ||
|
|
cf391bdd80 | ||
|
|
7120d6a9db | ||
|
|
4d80ab639e | ||
|
|
95bbd2852e | ||
|
|
4b0a934e51 | ||
|
|
ee5d86003b | ||
|
|
bc11b60147 | ||
|
|
801a4697ea | ||
|
|
628a970e6f | ||
|
|
566ea942dc | ||
|
|
e047c2d54e | ||
|
|
3fdd3d22e2 | ||
|
|
08e0fa9206 | ||
|
|
ed9e6ce676 | ||
|
|
a7bf07130e | ||
|
|
7c31662698 | ||
|
|
15df06a0bc | ||
|
|
47b5f8db7b | ||
|
|
0e763987aa | ||
|
|
37e8ea27d0 | ||
|
|
67d63256c2 | ||
|
|
ee185cf20a | ||
|
|
3552e05e4c | ||
|
|
735bb55b78 | ||
|
|
60f8a50a97 | ||
|
|
ffd01814b0 | ||
|
|
c511910b8f | ||
|
|
5c38f8f0d8 | ||
|
|
d512442325 | ||
|
|
43f54c90d2 | ||
|
|
57a99b478a | ||
|
|
3f402fbde7 | ||
|
|
98140c1f71 | ||
|
|
f00de85e38 | ||
|
|
b686b12c6a | ||
|
|
e4b903b13c | ||
|
|
72f576a70e | ||
|
|
c4f2c7be63 | ||
|
|
75b75fd223 | ||
|
|
391b18a5ac | ||
|
|
8de0f8e87c | ||
|
|
adb0b76559 | ||
|
|
b6df25c02c | ||
|
|
620186db1c | ||
|
|
21fac8046e | ||
|
|
de7c35f587 | ||
|
|
a23c979045 | ||
|
|
13da7287b1 | ||
|
|
e8398df9fc | ||
|
|
8303682bd7 | ||
|
|
8125d1a124 | ||
|
|
110ff5e12e | ||
|
|
24afcba20a | ||
|
|
d5f41d12e8 | ||
|
|
d640dd66e2 | ||
|
|
05bd9f57d6 | ||
|
|
60ab476ec7 | ||
|
|
bcae285ab3 | ||
|
|
cd67176b41 | ||
|
|
98eba54621 | ||
|
|
c530627078 | ||
|
|
f961947e1e | ||
|
|
e9e6628b21 | ||
|
|
c7684d6fe1 | ||
|
|
7d475ab403 | ||
|
|
143adcbbe4 | ||
|
|
ca8b6a33ba | ||
|
|
2f73cdb0f9 | ||
|
|
d1e06d9ef1 | ||
|
|
0ed78e2202 | ||
|
|
64818c586b | ||
|
|
578f5cad4a | ||
|
|
d2ff277b16 | ||
|
|
df4f9b3f8e | ||
|
|
be7f53a9ae | ||
|
|
6ed91a105e | ||
|
|
0db3c3af5a | ||
|
|
23748504e6 | ||
|
|
f74fecddd8 | ||
|
|
618a30c2ab | ||
|
|
b5116474c7 | ||
|
|
91e7239866 | ||
|
|
1dddb5fb3c | ||
|
|
8ddf592ffc | ||
|
|
59a1117ed3 | ||
|
|
3bb6fa1e59 | ||
|
|
5af98ac911 | ||
|
|
f197196c21 | ||
|
|
ce5595bc16 | ||
|
|
1406111f22 | ||
|
|
bfdada6792 | ||
|
|
5326ad85d8 | ||
|
|
f9dd245481 | ||
|
|
20677a9090 | ||
|
|
d54cb7507a | ||
|
|
d6b313b582 | ||
|
|
f31cdb413b | ||
|
|
69faf55b2b | ||
|
|
4d9e42205f | ||
|
|
5df69d73c7 | ||
|
|
4704f8485b | ||
|
|
809c216a5c | ||
|
|
415a40e436 | ||
|
|
d233f1d73f | ||
|
|
9a7019a2ce | ||
|
|
07b1623c5e | ||
|
|
681437acb1 | ||
|
|
a183a586cb | ||
|
|
af62b51ef5 | ||
|
|
f640451257 | ||
|
|
a56252c361 | ||
|
|
38141ea5c7 | ||
|
|
d24d1c178b | ||
|
|
93673e5786 | ||
|
|
2f3b1571e5 | ||
|
|
65703f0fc4 | ||
|
|
4e674af4ed | ||
|
|
f9c2d7c63a | ||
|
|
968d85d738 | ||
|
|
d230b61c0b | ||
|
|
59047a8d0e | ||
|
|
81493ac4be | ||
|
|
cf33f9a3bd | ||
|
|
d2f65b169c | ||
|
|
fa1f7358b7 | ||
|
|
8208bb0b9d | ||
|
|
daa516babe | ||
|
|
6c2a9836eb | ||
|
|
bd3e6a56ca | ||
|
|
ea2ee1711c | ||
|
|
2890cdd457 | ||
|
|
e4dfb43b5e | ||
|
|
3926d561c0 |
@@ -13,6 +13,7 @@ build/
|
|||||||
.kotlin
|
.kotlin
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
### IntelliJ IDEA ###
|
||||||
|
.idea/
|
||||||
.idea/modules.xml
|
.idea/modules.xml
|
||||||
.idea/jarRepositories.xml
|
.idea/jarRepositories.xml
|
||||||
.idea/compiler.xml
|
.idea/compiler.xml
|
||||||
@@ -77,6 +78,8 @@ shine-solana/shine/scripts/**/TEMP_*.md
|
|||||||
|
|
||||||
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
||||||
ESP32/esp32-config-tool/
|
ESP32/esp32-config-tool/
|
||||||
|
ESP32/local-sketches/
|
||||||
|
ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/
|
||||||
ESP32/**/.git/
|
ESP32/**/.git/
|
||||||
ESP32/**/.idea/
|
ESP32/**/.idea/
|
||||||
ESP32-wallet/.idea/
|
ESP32-wallet/.idea/
|
||||||
@@ -102,11 +105,46 @@ ESP32/**/*.d
|
|||||||
ESP32/**/*.a
|
ESP32/**/*.a
|
||||||
|
|
||||||
# Полные серверные бэкапы (тяжёлые архивы, не коммитим)
|
# Полные серверные бэкапы (тяжёлые архивы, не коммитим)
|
||||||
server-backup/archive/**
|
deploy/backup/archive/**
|
||||||
!server-backup/archive/.gitkeep
|
!deploy/backup/archive/.gitkeep
|
||||||
|
SHiNE-bundle-*.zip
|
||||||
|
|
||||||
# Локальная дев-обвязка Claude (дев-сервер shine-UI, сессии, планы) — не коммитим
|
# Локальная дев-обвязка AI-агентов (сессии, планы, настройки) — не коммитим
|
||||||
|
.agents/
|
||||||
|
.codex/
|
||||||
.claude/
|
.claude/
|
||||||
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
||||||
*.bak.png
|
*.bak.png
|
||||||
shine-UI/assets/navbar_preview.png
|
shine-UI/assets/navbar_preview.png
|
||||||
|
|
||||||
|
# Private local configuration: keep on disk, never push to GitHub
|
||||||
|
/SHiNE-server/src/main/resources/application.properties
|
||||||
|
/application.properties
|
||||||
|
/deploy/backup/scheme/
|
||||||
|
/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env
|
||||||
|
**/.env
|
||||||
|
**/.env.*
|
||||||
|
!**/.env.example
|
||||||
|
!**/.env.sample
|
||||||
|
|
||||||
|
# Private key files and local credential stores (never commit)
|
||||||
|
*.key
|
||||||
|
*.pem
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
*.jwk
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
|
*keypair*.json
|
||||||
|
|
||||||
|
# Private production runbooks and target-specific wrappers (keep locally)
|
||||||
|
/SHiNE-server/application.properties
|
||||||
|
/deploy/PRODUCTION_SERVERS.md
|
||||||
|
/deploy/DEPLOY_SERVER_INSTRUCTIONS.md
|
||||||
|
/deploy/scripts/production_shineupme_server.sh
|
||||||
|
/deploy/scripts/production_shineupme_ui.sh
|
||||||
|
/deploy/scripts/production_server2_server.sh
|
||||||
|
/deploy/scripts/production_server2_ui.sh
|
||||||
|
|
||||||
|
# Локальная история разработки форматов blockchain; не публиковать
|
||||||
|
/protocol-format-history/
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
# Default ignored files
|
|
||||||
/shelf/
|
|
||||||
/workspace.xml
|
|
||||||
# Editor-based HTTP Client requests
|
|
||||||
/httpRequests/
|
|
||||||
# Datasource local storage ignored files
|
|
||||||
/dataSources/
|
|
||||||
/dataSources.local.xml
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
shine-server-server
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<component name="ArtifactManager">
|
|
||||||
<artifact type="jar" build-on-make="true" name="server:jar">
|
|
||||||
<output-path>$PROJECT_DIR$/out/artifacts/server_jar</output-path>
|
|
||||||
<root id="archive" name="server.jar">
|
|
||||||
<element id="directory" name="META-INF">
|
|
||||||
<element id="file-copy" path="$PROJECT_DIR$/META-INF/MANIFEST.MF" />
|
|
||||||
</element>
|
|
||||||
</root>
|
|
||||||
</artifact>
|
|
||||||
</component>
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
|
||||||
<component name="GradleSettings">
|
|
||||||
<option name="linkedExternalProjectsSettings">
|
|
||||||
<GradleProjectSettings>
|
|
||||||
<option name="externalProjectPath" value="$PROJECT_DIR$" />
|
|
||||||
<option name="gradleHome" value="" />
|
|
||||||
<option name="modules">
|
|
||||||
<set>
|
|
||||||
<option value="$PROJECT_DIR$" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-blockchain" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-config" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-crypto" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-db" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-geo" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-log" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-net-protocol" />
|
|
||||||
<option value="$PROJECT_DIR$/shine-server-net-server" />
|
|
||||||
</set>
|
|
||||||
</option>
|
|
||||||
</GradleProjectSettings>
|
|
||||||
</option>
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
|
||||||
<component name="FrameworkDetectionExcludesConfiguration">
|
|
||||||
<file type="web" url="file://$PROJECT_DIR$" />
|
|
||||||
</component>
|
|
||||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17 (2)" project-jdk-type="JavaSDK">
|
|
||||||
<output url="file://$PROJECT_DIR$/out" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project version="4">
|
|
||||||
<component name="VcsDirectoryMappings">
|
|
||||||
<mapping directory="" vcs="Git" />
|
|
||||||
</component>
|
|
||||||
</project>
|
|
||||||
@@ -1,160 +1,33 @@
|
|||||||
# AGENTS
|
# Актуальная архитектура SHiNE
|
||||||
|
|
||||||
## Язык проекта
|
Начинать с [Blockchain](docs/Blockchain/README.md) и [общей архитектуры](docs/ARCHITECTURE.md). Активный runtime CORE/CONTENT, App=test5599. Прямая межсерверная репликация блоков не используется. Не менять протокол или независимые подсистемы без согласования. Интеграционную приёмку и production deploy выполнять отдельно с разрешения пользователя.
|
||||||
- По умолчанию использовать русский язык во всех пользовательских текстах и технических пояснениях.
|
|
||||||
- Пояснения к коммитам, PR и merge-запросам писать на русском языке.
|
|
||||||
- Комментарии в коде, встроенные справки, документацию и инструкции писать по возможности на русском языке.
|
|
||||||
|
|
||||||
## Примечание
|
---
|
||||||
- Если внешний инструмент/интеграция требует английский формат, допускается английский, но рядом желательно дать краткое пояснение на русском.
|
|
||||||
|
|
||||||
## Структура проекта (кратко)
|
# Инструкции для агентов SHiNE
|
||||||
- Серверный код SHiNE находится в папке `SHiNE-server/`.
|
|
||||||
- Код клиентского UI SHiNE находится в папке `shine-UI/`.
|
|
||||||
- Веб-панель администратора сервера (управление Solana PDA сервера) находится в `shine-UI/`:
|
|
||||||
- точка входа `shine-UI/server-ui.html`;
|
|
||||||
- остальные файлы серверного UI — в `shine-UI/server-ui/`.
|
|
||||||
- Локальный Telegram-бот агента-кодера находится в папке `SHiNE-agent-bot-coder/` и не является кодом основного серверного приложения.
|
|
||||||
- Solana/Anchor-модуль находится в папке `shine-solana/shine/` и ведётся отдельно от основного server/UI деплоя.
|
|
||||||
|
|
||||||
## Сервис агента-кодера
|
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
|
||||||
- В проекте есть локальный Telegram-бот-сервис агента-кодера в папке `SHiNE-agent-bot-coder/`.
|
|
||||||
- Сервис принимает сообщения из Telegram, ведёт историю диалога, ставит задачи в очередь и вызывает Codex CLI для обработки запросов по проекту.
|
|
||||||
- Автоматически читаемые инструкции для Codex внутри сервиса держать в `SHiNE-agent-bot-coder/AGENTS.md`.
|
|
||||||
- Подробные служебные правила Telegram-обработчика, его очередь, история, systemd-запуск и особенности ответов описывать в `SHiNE-agent-bot-coder/AGENT.md`.
|
|
||||||
- Если в сообщениях пользователя встречается «агент MD» или похожая формулировка про файл инструкций Codex, считать, что имеется в виду автоматически читаемый `AGENTS.md`.
|
|
||||||
|
|
||||||
## ESP32 UI homeserver
|
## Сначала определить область работы
|
||||||
- Для UI-скетча устройства `ESP32-S3-Touch-AMOLED-2.16` документ-спецификация и Arduino-скетч должны всегда оставаться синхронными.
|
|
||||||
- Актуальный документ по экранной логике, состояниям, кнопкам, полям, статусам и ограничениям UI считать источником истины для скетча.
|
|
||||||
- При изменении документа обязательно в том же наборе изменений приводить в соответствие скетч.
|
|
||||||
- При изменении скетча обязательно в том же наборе изменений обновлять документ, если поменялись экраны, тексты, переходы, статусы, кнопки, поля или поведение.
|
|
||||||
- Для нового ESP32 UI-прототипа homeserver использовать русский язык как основной и отдельно следить, чтобы текст реально отображался на устройстве, а не только логически присутствовал в коде.
|
|
||||||
|
|
||||||
## Solana-модуль
|
| Область | Код | Правила и документация |
|
||||||
- В проекте есть отдельный Solana/Anchor-модуль в папке `shine-solana/shine/`.
|
| --- | --- | --- |
|
||||||
- Модуль логически связан с SHiNE, но не должен автоматически подключаться к сборке или деплою основного сервера без отдельного решения.
|
| Сервер, WebSocket/API, PostgreSQL | `SHiNE-server/` | `SHiNE-server/AGENTS.md`, `docs/API/` |
|
||||||
- В Solana-модуле действуют локальные инструкции `shine-solana/shine/AGENTS.md`; при изменениях внутри модуля сначала читать их.
|
| Блокчейн, Arweave | `SHiNE-server/shine-server-blockchain/` | `docs/Blockchain/README.md` |
|
||||||
- В git добавлять исходники, lock-файлы, настройки проекта и документацию Solana-модуля, но не добавлять локальные ключи, `.git`, `.idea`, `.gradle`, `target`, `node_modules`, `test-ledger`, логи, временные run-отчёты и `.env`-конфиги.
|
| Личные сообщения | сервер и `shine-UI/` | `docs/Personal_Messages/README.md`, локальный `AGENTS.md` |
|
||||||
- Для Solana deploy/push использовать правила из локального `shine-solana/shine/AGENTS.md`; не смешивать deploy Solana-модуля с `deployServer`/`deployUI` основного проекта.
|
| Браузерный UI | `shine-UI/` | `shine-UI/AGENTS.md`, `docs/UI-Design/README.md` |
|
||||||
- Для регистрации пользователей в Solana (программа `shine_users`) единая актуальная инструкция по деплою/инициализации, адресам программ, и куда их прописывать в UI/сервере находится в:
|
| Solana/Anchor | `shine-solana/shine/` | локальный `AGENTS.md`, `docs/Solana_Architecture/README.md` |
|
||||||
- `Dev_Docs/Инициализация_Solana_регистрации/README.md`
|
| ESP32 | `ESP32/` | `ESP32/AGENTS.md`, инструкции конкретного устройства |
|
||||||
- Этот файл считать основной справкой (single source of truth) по деплою и первичной инициализации Solana-регистрации в текущем проекте.
|
| Деплой и резервные копии | `deploy/` | `deploy/AGENTS.md`, `deploy/backup/AGENTS.md` |
|
||||||
- Актуальная архитектурная справка по устройству Solana-программ, PDA-счетам, ролям DAO и движению средств находится в:
|
| Тестовый издатель | `tools/test-publisher/` | локальный `AGENTS.md` |
|
||||||
- `Dev_Docs/Solana_Architecture/README.md`
|
|
||||||
- Документ формата пользовательской PDA-записи `shine_users` находится в:
|
|
||||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`
|
|
||||||
|
|
||||||
## Документация блокчейна
|
Общий каталог — `docs/README.md`; карта компонентов и потоков данных — `docs/ARCHITECTURE.md`. Правила сопровождения документов — `docs/CONTRIBUTING_DOCS.md`; после правки документации запускать `python3 scripts/check_docs.py`. Планы в `TODO/` не считать описанием действующего поведения или разрешением на реализацию.
|
||||||
- Актуальная документация по форматам блокчейна находится в `Dev_Docs/Blockchain/README.md`.
|
|
||||||
- Это точка входа (оглавление), рядом расположены детальные файлы по форматам, типам каналов и командным сообщениям.
|
|
||||||
- При любом изменении кода, связанного с блокчейном (формат блока, типы каналов, правила чтения/записи, команды), обязательно обновлять соответствующие документы в `Dev_Docs/Blockchain/`.
|
|
||||||
- Дополнительно обязательно вести `Dev_Docs/Blockchain/CHANGELOG.md`: дописывать изменения построчно с указанием даты/времени и хэша коммита, после которого внесено изменение.
|
|
||||||
- Перед любым изменением формата блокчейна обязательно заранее предупреждать пользователя, что формат будет изменён.
|
|
||||||
- Изменять формат блокчейна можно только после явного подтверждения пользователя (без подтверждения формат не менять).
|
|
||||||
- Добавление любых данных в блокчейн выполнять только через операцию `AddBlock`.
|
|
||||||
- Перед каждым `AddBlock` обязательно проверять/актуализировать текущее состояние вершины блокчейна (`last global number/hash`) и использовать его при формировании блока.
|
|
||||||
|
|
||||||
## Документация личных сообщений (DM)
|
## Постоянные правила
|
||||||
- Актуальная документация по логике личных сообщений находится в `Dev_Docs/Personal_Messages/Протокол_DM_v1.md`.
|
|
||||||
- Точный байтовый формат DM находится в `Dev_Docs/Personal_Messages/Формат_DM_v1.md`.
|
|
||||||
- При любом изменении кода, связанного с личными сообщениями (формат подписанного DM-блока, типы DM-сообщений, правила доставки/ACK/read-receipt, роутинг по сессиям, UI-логика чатов), обязательно обновлять оба документа:
|
|
||||||
- `Dev_Docs/Personal_Messages/Протокол_DM_v1.md`
|
|
||||||
- `Dev_Docs/Personal_Messages/Формат_DM_v1.md`
|
|
||||||
- Логика личных сообщений в коде должна всегда соответствовать этим документам.
|
|
||||||
- Документ по личным сообщениям обязан поддерживаться в актуальном состоянии.
|
|
||||||
|
|
||||||
## Документация API сервера
|
- Прежде чем править подсистему, прочитать её локальный `AGENTS.md` и действующую документацию через `docs/README.md`. Архивные отчёты и старые планы не использовать как текущий контракт. При расхождении документа с кодом проверить реализацию и исправить документ либо явно отметить неопределённость.
|
||||||
- Актуальная документация по публичному JSON/WebSocket API сервера находится в `Dev_Docs/API/`.
|
- Изменение поведения, формата, API, конфигурации или пользовательского сценария сопровождать обновлением соответствующего документа в том же наборе изменений. Не выдавать план, черновик или тестовое состояние за действующую функцию.
|
||||||
- При любом изменении серверного API/эндпоинтов/операций `op` обязательно обновлять соответствующие документы в `Dev_Docs/API/`.
|
- Формат блокчейна и контракт серверного API изменять только после отдельного явного согласия пользователя; документировать изменения в `docs/Blockchain/` и `docs/API/`. Для добавления блока использовать `AddBlock` с актуальной вершиной цепочки.
|
||||||
- Перед изменением самого серверного API обязательно явно предупредить пользователя, какие операции, поля запросов/ответов или коды ошибок будут изменены, и запросить отдельное подтверждение.
|
- Любые изменения и деплой production (`shineup.me`, `server2.shineup.me`) — только после отдельного явного согласия пользователя. Перед деплоем прочитать `deploy/AGENTS.md` и проверить резервную копию. Для деплоя использовать скрипты `deploy/scripts/`.
|
||||||
- Без явного подтверждения пользователя формат серверного API не менять; допускается только приведение документации в соответствие уже существующему коду.
|
- Секреты, приватные ключи, локальные конфиги, сборочные артефакты и логи не добавлять в git.
|
||||||
- Если добавляется новая операция `op`, нужно обновить общий список операций в `Dev_Docs/API/09_Operations_Index.md` или создать его, если файла ещё нет.
|
- Коммиты, версии и merge выполнять по `COMMIT_AND_VERSION_RULES.md`. Не делать коммит или push без необходимости для задачи.
|
||||||
|
|
||||||
## Документация Figma
|
|
||||||
- Актуальная документация по переносу экранов SHiNE в Figma и обратному переносу из Figma в код находится в `Dev_Docs/Figma/`.
|
|
||||||
- Точка входа: `Dev_Docs/Figma/README.md`.
|
|
||||||
- Подробный рабочий регламент: `Dev_Docs/Figma/TRANSFER_UI_SCREENS.md`.
|
|
||||||
- Для экранов регистрации, входа и других чувствительных UI-flow по умолчанию переносить экраны в Figma по одному, а не пачкой, если пользователь отдельно не подтвердил иной способ.
|
|
||||||
|
|
||||||
## Версионирование
|
|
||||||
- Единый файл версий проекта: `VERSION.properties` (в корне репозитория).
|
|
||||||
- Перед каждым новым коммитом обязательно увеличивать версии в `VERSION.properties`:
|
|
||||||
- `client.version` — версия клиентского UI.
|
|
||||||
- `server.version` — версия серверной части.
|
|
||||||
- Базовое правило инкремента: `+1` по последнему числовому сегменту (patch), если не оговорено иное.
|
|
||||||
- Обычные коммиты делать стандартным `git commit`; переменная `$GITEA_TOKEN` для коммитов не нужна и не используется.
|
|
||||||
|
|
||||||
## Deploy
|
|
||||||
- Все документы и заметки по деплою хранить в папке `Deploy/`.
|
|
||||||
- Production-хост SHiNE: `player@shineup.me` (`178.208.64.62`).
|
|
||||||
- Второй production-хост SHiNE: `player@193.8.215.70` (`server2.shineup.me`).
|
|
||||||
- Базовый путь на сервере для SHiNE: `/home/player` (проекты SHiNE размещать в `/home/player/SHiNE/...`).
|
|
||||||
- По возможности все справки, комментарии и примечания в конфигах/документах писать на русском языке.
|
|
||||||
- Для операций `git push` при необходимости использовать токен из переменной окружения `$GITEA_TOKEN`.
|
|
||||||
- Любые изменения и любой деплой на production `shineup.me` выполнять только после отдельного явного подтверждения пользователя.
|
|
||||||
- Если пользователь пишет просто `задеплой` без уточнения production/test, по умолчанию деплоить на `server2.shineup.me`.
|
|
||||||
- Default server deploy: `./gradlew deployServer` или `./gradlew deployServerTest2`.
|
|
||||||
- Default UI deploy: `./gradlew deployUI` или `./gradlew deployUITest2`.
|
|
||||||
- Production server deploy: `./gradlew deployServerProduction`.
|
|
||||||
- Production UI deploy: `./gradlew deployUIProduction`.
|
|
||||||
- Для локального запуска использовать `./gradlew startLocal` (или `startLocalWithBuild`).
|
|
||||||
- Сначала предлагать локальную проверку, а деплой на сервер выполнять по запросу пользователя.
|
|
||||||
- Для временной бесплатной загрузки аватаров в Arweave секретный JWK нельзя хранить в git и нельзя прописывать в репозиторный `application.properties`.
|
|
||||||
- Для продовой настройки тестового Arweave-кошелька JWK-файл нужно хранить только на сервере, например: `/home/player/SHiNE/secrets/test-free-avatar-wallet.json`.
|
|
||||||
- Для этой временной фичи на проде должны быть заданы параметры `test.freeAvatar.walletJwkPath` и `test.freeAvatar.walletAddress` через серверный override-конфиг/секреты на хосте.
|
|
||||||
- После изменения продовых значений `test.freeAvatar.*` нужно заново выполнить серверный деплой или перезапуск сервера, чтобы настройки были перечитаны приложением.
|
|
||||||
- При таких изменениях в git допускается коммитить только документацию и код чтения настроек, но не сам JWK, не содержимое секрета и не реальные приватные ключи.
|
|
||||||
|
|
||||||
## Логи звонков (установка соединения)
|
|
||||||
- Специальный поток диагностики установки звонков идёт через `CallDeliveryReport` (клиент → сервер).
|
|
||||||
- На проде специальный файл для звонков:
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/call-delivery-events.log`
|
|
||||||
- Общий серверный лог (и ротации) на проде:
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/app.log`
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/app.YYYY-MM-DD.log`
|
|
||||||
- Для анализа причин недозвона в первую очередь фильтровать записи по ключам:
|
|
||||||
- `CallDeliveryReport`
|
|
||||||
- `call_connected`
|
|
||||||
- `outgoing_failed`
|
|
||||||
- `incoming_failed`
|
|
||||||
- `call_busy`
|
|
||||||
- `call_declined`
|
|
||||||
- `unknown_error`
|
|
||||||
- В этих записях искать поля `reason`, `failureStage`, `pcConnectionState`, `pcIceConnectionState`, `routeLabel`, `configuredTurnHosts*`, `reachableTurnHosts*`.
|
|
||||||
|
|
||||||
## Недопроверенные фичи (обязательно)
|
|
||||||
- Папка для учёта недопроверенных фич: `Dev_Docs/Pending_Features/`.
|
|
||||||
- По каждой новой доработке, которая требует ручной проверки, добавлять отдельный markdown-файл в `Dev_Docs/Pending_Features/`.
|
|
||||||
- Рекомендуемый формат имени файла: `YYYY-MM-DD_HHMM_<short-feature-name>.md`.
|
|
||||||
- Имена новых файлов и краткие описания фич по возможности писать на русском языке.
|
|
||||||
- Внутри файла обязательно указывать:
|
|
||||||
- краткое описание фичи;
|
|
||||||
- что именно проверять;
|
|
||||||
- ожидаемый результат;
|
|
||||||
- статус (например: `pending`, `in_progress`, `done`).
|
|
||||||
- После подтверждения, что фича проверена и работает корректно, соответствующий файл удалять.
|
|
||||||
- В `Dev_Docs/Pending_Features/README.md` вести краткий регламент и поддерживать актуальность.
|
|
||||||
|
|
||||||
## Будущие фичи / TODO
|
|
||||||
- Папка для задач, сознательно отложенных на будущее: `TODO/`.
|
|
||||||
- Точка входа по планам: `TODO/README.md`.
|
|
||||||
- Внутри планы разделены по горизонтам: `near/`, `medium/`, `far/` и тематическим подпапкам.
|
|
||||||
- Если пользователь спрашивает, какие есть планы или что можно продолжить, сначала читать `TODO/README.md`, затем при необходимости конкретные файлы из подпапок.
|
|
||||||
- Файлы из этой папки не считать активными задачами и не начинать реализацию без явной просьбы пользователя.
|
|
||||||
- Старую папку `Dev_Docs/Future_Features/` считать выведенной из использования и больше не использовать для новых записей.
|
|
||||||
- Если часть кода временно отключена или закомментирована, либо удалена как временная заглушка, в TODO-файле подробно описывать:
|
|
||||||
- какие файлы и участки отключены;
|
|
||||||
- что осталось в коде как заготовка;
|
|
||||||
- какие документы нужно обновить при возврате;
|
|
||||||
- с какого сценария продолжать разработку;
|
|
||||||
- из какого коммита брать последнюю полную реализацию.
|
|
||||||
|
|
||||||
## Коммуникация по новым задачам (обязательно)
|
|
||||||
- При получении нового задания сначала кратко пересказать задачу своими словами.
|
|
||||||
- До начала реализации задать недостающие уточняющие вопросы (если они есть).
|
|
||||||
- Если есть уместные идеи/улучшения — кратко предложить их; если полезных идей нет, ничего дополнительно не предлагать.
|
|
||||||
- Добавлять краткую оценку фичи (насколько это полезно/удачно по мнению исполнителя).
|
|
||||||
- После этого обязательно запросить подтверждение от пользователя, что задача понята верно, и только после подтверждения переходить к реализации.
|
|
||||||
- Если вопросов нет, явно написать в формате: «Я всё понял, начинаю делать?» и ждать подтверждения.
|
|
||||||
- Без подтверждения пользователя реализацию не начинать.
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# SHiNE 0.9 Alpha — Software Status / Статус программного обеспечения
|
||||||
|
|
||||||
|
## Русский
|
||||||
|
|
||||||
|
**SHiNE 0.9 Alpha — ранняя публичная версия программного обеспечения проекта SHiNE, находящегося в активной разработке. Это не стабильный релиз версии 1.0.**
|
||||||
|
|
||||||
|
- Некоторые функции могут отсутствовать, быть реализованы частично или работать некорректно. Возможны ошибки, сбои, потеря данных и ещё не выявленные уязвимости безопасности.
|
||||||
|
- Протоколы, программные интерфейсы, форматы данных, пользовательский интерфейс и документация продолжают развиваться. Совместимость с будущими версиями и бесперебойная работа не гарантируются.
|
||||||
|
- Используйте программное обеспечение с учётом его текущего состояния. Храните резервные копии важных данных, безопасно храните пароли и ключи и не рискуйте значительными денежными средствами при использовании экспериментальных функций.
|
||||||
|
|
||||||
|
Альфа-версия предназначена для раннего использования, тестирования, получения обратной связи и совместного развития экосистемы SHiNE. Сообщения об ошибках и предложения по улучшению приветствуются.
|
||||||
|
|
||||||
|
**Статус Alpha не означает, что публичные записи являются временными или будут удалены при выходе следующей версии.** Перед публикацией ознакомьтесь с [предупреждением о публичных данных](PUBLIC_DATA_WARNING.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
**SHiNE 0.9 Alpha is an early public release of the SHiNE software, which is under active development. It is not the stable 1.0 release.**
|
||||||
|
|
||||||
|
- Some features may be missing, partially implemented or may not work correctly. Errors, failures, data loss and undiscovered security vulnerabilities are possible.
|
||||||
|
- Protocols, APIs, data formats, the user interface and documentation continue to evolve. Compatibility with future versions and uninterrupted operation are not guaranteed.
|
||||||
|
- Use the software with due regard for its current state. Keep backups of important data, store passwords and keys securely, and avoid risking significant funds when using experimental features.
|
||||||
|
|
||||||
|
The alpha release is intended for early use, testing, feedback and collaborative development of the SHiNE ecosystem. Bug reports and suggestions for improvement are welcome.
|
||||||
|
|
||||||
|
**Alpha status does not mean that public records are temporary or will be deleted when the next version is released.** Before publishing, read the [public data warning](PUBLIC_DATA_WARNING.md).
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
@shine-UI/AGENTS.md
|
@shine-UI/AGENTS.md
|
||||||
|
|
||||||
## Справка по подпроектам
|
## Справка по подпроектам
|
||||||
- При работе внутри `SHiNE-agent-bot-coder/` — читать `SHiNE-agent-bot-coder/AGENTS.md` и `SHiNE-agent-bot-coder/AGENT.md`.
|
- При работе с локальным агентом-кодером — читать внешние файлы `../SHiNE-agent-bot-coder/AGENTS.md` и `../SHiNE-agent-bot-coder/AGENT.md`.
|
||||||
- При работе внутри `shine-solana/shine/` — читать `shine-solana/shine/AGENTS.md`.
|
- При работе внутри `shine-solana/shine/` — читать `shine-solana/shine/AGENTS.md`.
|
||||||
- При работе внутри `shine-UI/server-ui/` — читать `shine-UI/AGENTS.md`.
|
- При работе внутри `shine-UI/server-ui/` — читать `shine-UI/AGENTS.md`.
|
||||||
- При работе внутри `SHiNE-server/` — читать `SHiNE-server/AGENTS.md`.
|
- При работе внутри `SHiNE-server/` — читать `SHiNE-server/AGENTS.md`.
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Правила коммитов, merge и версионирования
|
||||||
|
|
||||||
|
Этот файл является единым источником правил для:
|
||||||
|
- коммитов;
|
||||||
|
- merge в `main`;
|
||||||
|
- изменения версий в `VERSION.properties`;
|
||||||
|
- `git push` из этого репозитория.
|
||||||
|
|
||||||
|
## Язык
|
||||||
|
|
||||||
|
- Пояснения к коммитам, PR и merge-запросам писать на русском языке.
|
||||||
|
|
||||||
|
## Где хранится версия
|
||||||
|
|
||||||
|
- Единый файл версий проекта: `VERSION.properties` в корне репозитория.
|
||||||
|
- Основные поля:
|
||||||
|
- `client.version` — версия клиентского UI.
|
||||||
|
- `server.version` — версия серверной части.
|
||||||
|
|
||||||
|
## Базовое правило для обычных коммитов
|
||||||
|
|
||||||
|
- Версии обновляются только вместе с изменениями соответствующего продукта: UI — `client.version`, сервер — `server.version`.
|
||||||
|
- Если менялся только UI, увеличивать только `client.version`.
|
||||||
|
- Если менялся только сервер, увеличивать только `server.version`.
|
||||||
|
- Если менялись и UI, и сервер, увеличивать обе версии.
|
||||||
|
- Для обычных коммитов вне `main` использовать стандартный patch-инкремент: `+1` к последнему числовому сегменту.
|
||||||
|
- Пример: `1.2.346` → `1.2.347`.
|
||||||
|
|
||||||
|
- Коммиты только с документацией, настройками процесса или служебными файлами не требуют изменения `VERSION.properties`.
|
||||||
|
|
||||||
|
## Правило для `main`
|
||||||
|
|
||||||
|
- Ветка `main` предназначена только для стабильных версий.
|
||||||
|
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
|
||||||
|
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
|
||||||
|
- При merge рабочей ветки в `main` не нужно дополнительно изменять `VERSION.properties` и создавать отдельный коммит только ради версии.
|
||||||
|
- Версия в `main` приходит из уже подготовленного коммита рабочей ветки; после merge достаточно проверить, что она соответствует слитым изменениям.
|
||||||
|
|
||||||
|
## Правила для git commit и git push
|
||||||
|
|
||||||
|
- Обычные коммиты делать стандартным `git commit`; токен для локального коммита не нужен и не используется.
|
||||||
|
- Для операций `git push` при необходимости использовать токен из переменной окружения `$GITEA_TOKEN`.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
СИЯНИЕ SHiNE
|
||||||
|
|
||||||
|
Русский
|
||||||
|
|
||||||
|
Авторские права (C) 2026 Айдар Гареев (Aidar Gareev).
|
||||||
|
|
||||||
|
Собственный исходный код SHiNE распространяется на условиях
|
||||||
|
GNU Affero General Public License версии 3 или любой последующей версии
|
||||||
|
(AGPL-3.0-or-later), опубликованной Free Software Foundation.
|
||||||
|
|
||||||
|
Сторонние компоненты сохраняют свои соответствующие лицензии.
|
||||||
|
См. файлы LICENSE и THIRD_PARTY_NOTICES.md.
|
||||||
|
|
||||||
|
----------------------------------------------------------------
|
||||||
|
|
||||||
|
English
|
||||||
|
|
||||||
|
Copyright (C) 2026 Aidar Gareev (Айдар Гареев).
|
||||||
|
|
||||||
|
The original SHiNE source code is licensed under the
|
||||||
|
GNU Affero General Public License, either version 3 of the License, or
|
||||||
|
(at your option) any later version published by the Free Software Foundation
|
||||||
|
(AGPL-3.0-or-later).
|
||||||
|
|
||||||
|
Third-party components retain their respective licenses.
|
||||||
|
See LICENSE and THIRD_PARTY_NOTICES.md.
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
# Production-серверы SHiNE
|
|
||||||
|
|
||||||
## Короткий ответ
|
|
||||||
|
|
||||||
По текущим данным репозитория у SHiNE описаны **два production-контура**:
|
|
||||||
|
|
||||||
- `player@shineup.me`
|
|
||||||
- домен `shineup.me`
|
|
||||||
- IP `178.208.64.62`
|
|
||||||
|
|
||||||
и
|
|
||||||
|
|
||||||
- `player@193.8.215.70`
|
|
||||||
- домен `server2.shineup.me`
|
|
||||||
- IP `193.8.215.70`
|
|
||||||
|
|
||||||
## 1. Основной production-хост
|
|
||||||
|
|
||||||
- SSH: `player@shineup.me`
|
|
||||||
- домен: `shineup.me`
|
|
||||||
- IP: `178.208.64.62`
|
|
||||||
- пользователь: `player`
|
|
||||||
- базовый путь: `/home/player`
|
|
||||||
|
|
||||||
Основные каталоги:
|
|
||||||
|
|
||||||
- проект SHiNE: `/home/player/SHiNE`
|
|
||||||
- серверный jar: `/home/player/SHiNE/shine-server/shine-server.jar`
|
|
||||||
- UI: `/home/player/SHiNE/shine-ui`
|
|
||||||
- данные: `/home/player/SHiNE/shine-server/data/`
|
|
||||||
- логи: `/home/player/SHiNE/shine-server/logs/app.log`
|
|
||||||
|
|
||||||
Сервисы:
|
|
||||||
|
|
||||||
- `shine-server.service`
|
|
||||||
- `caddy.service`
|
|
||||||
|
|
||||||
Caddy:
|
|
||||||
|
|
||||||
- активный конфиг: `/etc/caddy/Caddyfile`
|
|
||||||
- UI root: `/home/player/SHiNE/shine-ui`
|
|
||||||
- `/ws` проксируется на `127.0.0.1:7070`
|
|
||||||
|
|
||||||
Deploy:
|
|
||||||
|
|
||||||
- `./gradlew deployServerProduction`
|
|
||||||
- `./gradlew deployUIProduction`
|
|
||||||
|
|
||||||
Правило:
|
|
||||||
|
|
||||||
- любые изменения на `shineup.me` делать только после отдельного подтверждения пользователя.
|
|
||||||
|
|
||||||
## 2. Второй production-сервер
|
|
||||||
|
|
||||||
- SSH: `player@193.8.215.70`
|
|
||||||
- домен: `server2.shineup.me`
|
|
||||||
- IP: `193.8.215.70`
|
|
||||||
- пользователь: `player`
|
|
||||||
- базовый путь: `/home/player`
|
|
||||||
|
|
||||||
Роль:
|
|
||||||
|
|
||||||
- второй production-контур SHiNE;
|
|
||||||
- использовать как production-сервер, несмотря на исторические имена deploy-задач
|
|
||||||
`deployServerTest2` / `deployUITest2`.
|
|
||||||
|
|
||||||
Основные каталоги:
|
|
||||||
|
|
||||||
- проект SHiNE: `/home/player/SHiNE`
|
|
||||||
- серверный jar: `/home/player/SHiNE/shine-server/shine-server.jar`
|
|
||||||
- UI: `/home/player/SHiNE/shine-ui`
|
|
||||||
- данные: `/home/player/SHiNE/shine-server/data/`
|
|
||||||
- логи: `/home/player/SHiNE/shine-server/logs/app.log`
|
|
||||||
|
|
||||||
## 3. Связанные публичные production-публикации на том же хосте
|
|
||||||
|
|
||||||
На этом же production-хосте есть отдельная публикация для `shine_payments`:
|
|
||||||
|
|
||||||
- каталог: `/home/player/sites/test-solana-tickets.shineup.me`
|
|
||||||
- домены:
|
|
||||||
- `https://test-solana-tickets.shineup.me`
|
|
||||||
- `https://test-solana-tickets.shiningpeople.ru`
|
|
||||||
|
|
||||||
Это не второй production-хост SHiNE, а отдельный сайт на том же сервере.
|
|
||||||
|
|
||||||
## 4. Какие серверы не считать production
|
|
||||||
|
|
||||||
Не production:
|
|
||||||
|
|
||||||
- `t1.shineup.me`
|
|
||||||
- `t2.shineup.me`
|
|
||||||
- `t3.shineup.me`
|
|
||||||
- `t4.shineup.me`
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
# Deploy
|
|
||||||
|
|
||||||
Подробности о том, где что задеплоено в SHiNE, нужно искать в папке `Deploy/`.
|
|
||||||
|
|
||||||
Эта папка служит краткой картой окружений:
|
|
||||||
|
|
||||||
- [TEST_SERVERS.md](/home/ai/work/SHiNE/SHiNE-server-sha256/Deploy/TEST_SERVERS.md) — тестовые стенды;
|
|
||||||
- [PRODUCTION_SERVERS.md](/home/ai/work/SHiNE/SHiNE-server-sha256/Deploy/PRODUCTION_SERVERS.md) — production-контур и связанные публичные публикации.
|
|
||||||
|
|
||||||
Ниже краткая сводка.
|
|
||||||
|
|
||||||
## Основные публичные контуры
|
|
||||||
|
|
||||||
- Production SHiNE:
|
|
||||||
- `player@shineup.me`
|
|
||||||
- домен `shineup.me`
|
|
||||||
- IP `178.208.64.62`
|
|
||||||
- Второй production SHiNE:
|
|
||||||
- `player@193.8.215.70`
|
|
||||||
- домен `server2.shineup.me`
|
|
||||||
- IP `193.8.215.70`
|
|
||||||
## Отдельный quad-devnet стенд
|
|
||||||
|
|
||||||
На отдельном VPS `178.208.90.249` подняты 4 независимых test/devnet-инстанса:
|
|
||||||
|
|
||||||
- `t1.shineup.me`
|
|
||||||
- `t2.shineup.me`
|
|
||||||
- `t3.shineup.me`
|
|
||||||
- `t4.shineup.me`
|
|
||||||
|
|
||||||
## Важно
|
|
||||||
|
|
||||||
- Production-контура SHiNE сейчас два: `shineup.me` и `server2.shineup.me`.
|
|
||||||
- `t1..t4.shineup.me` — это отдельные тестовые/devnet-контуры, не production.
|
|
||||||
- Любые изменения на `shineup.me` делать только после отдельного подтверждения пользователя.
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
# Тестовые серверы SHiNE
|
|
||||||
|
|
||||||
Этот файл описывает тестовые стенды, которые сейчас фигурируют в проекте.
|
|
||||||
|
|
||||||
## 1. Исторический `test2`, теперь второй production-сервер
|
|
||||||
|
|
||||||
- SSH: `player@193.8.215.70`
|
|
||||||
- Домен: `server2.shineup.me`
|
|
||||||
- IP: `193.8.215.70`
|
|
||||||
- Назначение: второй production-контур SHiNE
|
|
||||||
|
|
||||||
Структура:
|
|
||||||
|
|
||||||
- каталог SHiNE: `/home/player/SHiNE`
|
|
||||||
- сервер: `/home/player/SHiNE/shine-server/shine-server.jar`
|
|
||||||
- UI: `/home/player/SHiNE/shine-ui`
|
|
||||||
- данные: `/home/player/SHiNE/shine-server/data/`
|
|
||||||
- логи: `/home/player/SHiNE/shine-server/logs/app.log`
|
|
||||||
|
|
||||||
Сервисы:
|
|
||||||
|
|
||||||
- `shine-server.service`
|
|
||||||
- `caddy.service`
|
|
||||||
|
|
||||||
Deploy:
|
|
||||||
|
|
||||||
- `./gradlew deployServer`
|
|
||||||
- `./gradlew deployServerTest2`
|
|
||||||
- `./gradlew deployUI`
|
|
||||||
- `./gradlew deployUITest2`
|
|
||||||
|
|
||||||
Примечания:
|
|
||||||
|
|
||||||
- этот хост больше не считать test-контуром;
|
|
||||||
- исторические имена deploy-задач `deployServerTest2` / `deployUITest2` сохранены, но сам хост считать production;
|
|
||||||
- задача `deployUITest2` по умолчанию выкладывает UI на `server2.shineup.me`, а не на `t2.shineup.me`;
|
|
||||||
- при описании окружений перечислять его как второй production-сервер.
|
|
||||||
|
|
||||||
## 2. Отдельный quad-devnet стенд `t1..t4`
|
|
||||||
|
|
||||||
- VPS: `178.208.90.249`
|
|
||||||
- пользователь: `player`
|
|
||||||
- назначение: 4 независимых SHiNE-инстанса на Solana `devnet`
|
|
||||||
|
|
||||||
Домены и логины:
|
|
||||||
|
|
||||||
- `server_t1` -> `https://t1.shineup.me`
|
|
||||||
- `server_t2` -> `https://t2.shineup.me`
|
|
||||||
- `server_t3` -> `https://t3.shineup.me`
|
|
||||||
- `server_t4` -> `https://t4.shineup.me`
|
|
||||||
|
|
||||||
Каталоги:
|
|
||||||
|
|
||||||
- `/home/player/t1/server`
|
|
||||||
- `/home/player/t1/UI`
|
|
||||||
- `/home/player/t2/server`
|
|
||||||
- `/home/player/t2/UI`
|
|
||||||
- `/home/player/t3/server`
|
|
||||||
- `/home/player/t3/UI`
|
|
||||||
- `/home/player/t4/server`
|
|
||||||
- `/home/player/t4/UI`
|
|
||||||
|
|
||||||
Подробная памятка на самом VPS:
|
|
||||||
|
|
||||||
- `/home/player/Agents.md`
|
|
||||||
|
|
||||||
Порты и systemd:
|
|
||||||
|
|
||||||
- `t1` -> `7101` -> `shine-t1.service`
|
|
||||||
- `t2` -> `7102` -> `shine-t2.service`
|
|
||||||
- `t3` -> `7103` -> `shine-t3.service`
|
|
||||||
- `t4` -> `7104` -> `shine-t4.service`
|
|
||||||
|
|
||||||
Что важно по конфигу каждого инстанса:
|
|
||||||
|
|
||||||
- отдельный `/home/player/tX/server/application.properties`
|
|
||||||
- `server.port=710X`
|
|
||||||
- `server.SHiNE.login=server_tX`
|
|
||||||
- `db.path=data/shine.sqlite`
|
|
||||||
- `solana.cluster=devnet`
|
|
||||||
- `solana.rpcUrl=https://api.devnet.solana.com`
|
|
||||||
- `server.ui.indexPath=/home/player/tX/UI/index.html`
|
|
||||||
- `server.info.url=https://tX.shineup.me`
|
|
||||||
|
|
||||||
UI каждого инстанса:
|
|
||||||
|
|
||||||
- живёт в отдельной копии `shine-UI`;
|
|
||||||
- использует свой `js/deploy-config.js`;
|
|
||||||
- по умолчанию смотрит именно на свой `tX.shineup.me`.
|
|
||||||
|
|
||||||
Caddy на стенде:
|
|
||||||
|
|
||||||
- конфиг: `/etc/caddy/Caddyfile`
|
|
||||||
- статика: `/home/player/tX/UI`
|
|
||||||
- `/ws` проксируется на `127.0.0.1:710X`
|
|
||||||
|
|
||||||
Operational-нюанс:
|
|
||||||
|
|
||||||
- при одновременных рестартах возможны `HTTP 429` от `api.devnet.solana.com`;
|
|
||||||
- поэтому сервисы `shine-t1..shine-t4` лучше перезапускать по одному, с паузой.
|
|
||||||
|
|
||||||
## 3. Что проверять первым делом
|
|
||||||
|
|
||||||
Для любого test-контура полезны такие быстрые проверки:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -I https://server2.shineup.me
|
|
||||||
curl -I https://t1.shineup.me
|
|
||||||
curl -I https://t2.shineup.me
|
|
||||||
curl -I https://t3.shineup.me
|
|
||||||
curl -I https://t4.shineup.me
|
|
||||||
```
|
|
||||||
|
|
||||||
Для quad-devnet VPS:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo systemctl --no-pager --full status caddy shine-t1 shine-t2 shine-t3 shine-t4
|
|
||||||
```
|
|
||||||
|
|
||||||
Для второго production-контура:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo systemctl --no-pager --full status shine-server caddy
|
|
||||||
```
|
|
||||||
@@ -8,12 +8,12 @@
|
|||||||
|
|
||||||
## Синхронизация со спецификацией
|
## Синхронизация со спецификацией
|
||||||
|
|
||||||
- При изменении экранов, кнопок, переходов, статусов или текстов обязательно обновлять соответствующую спецификацию в `ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/`.
|
- При изменении экранов, кнопок, переходов, статусов или текстов обновлять соответствующую спецификацию в `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/`.
|
||||||
|
|
||||||
## Сборка ESP32
|
## Сборка ESP32
|
||||||
|
|
||||||
- Основной способ проверки и прошивки скетчей для `ESP32-S3-Touch-AMOLED-2.16` - `main-device/burn.sh`.
|
- Основной способ проверки и прошивки скетчей для `ESP32-S3-Touch-AMOLED-2.16` - `main-device/burn.sh`.
|
||||||
- Не собирать эти скетчи напрямую через `arduino-cli compile` без `burn.sh`, потому что скрипт добавляет нужные локальные библиотеки и конфиги из `official-demo/examples/Arduino-v3.3.5/libraries`.
|
- Не собирать эти скетчи напрямую через `arduino-cli compile` без `burn.sh`, потому что скрипт добавляет нужные библиотеки и конфиги из `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5/libraries`.
|
||||||
- Если сборка падает по `lv_conf.h` или `TouchDrvCSTXXX.hpp`, сначала проверять именно `burn.sh` и его `--library` пути, а не считать, что файл пропал из репозитория.
|
- Если сборка падает по `lv_conf.h` или `TouchDrvCSTXXX.hpp`, сначала проверять именно `burn.sh` и его `--library` пути, а не считать, что файл пропал из репозитория.
|
||||||
|
|
||||||
## Диагностика ESP32
|
## Диагностика ESP32
|
||||||
|
|||||||
@@ -32,27 +32,24 @@ ls -l /dev/ttyACM0
|
|||||||
|
|
||||||
## 3) Структура подпроекта (эталон)
|
## 3) Структура подпроекта (эталон)
|
||||||
|
|
||||||
- `official-demo/` — официальный repo Waveshare (примеры+библиотеки)
|
- `main-device/` — актуальная прошивка регистрации и `burn.sh`
|
||||||
- `original-firmware/` — backup/restore заводской прошивки
|
- `old_version/` — старые версии homeserver
|
||||||
- `main-device/` — прошивки и `burn.sh`
|
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/` — официальный repo Waveshare (примеры+библиотеки)
|
||||||
- `reference/` — заметки и ссылки
|
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/` — заметки и спецификации
|
||||||
|
|
||||||
## 4) Бэкап перед любыми экспериментами
|
## 4) Бэкап перед любыми экспериментами
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ESP32-S3-Touch-AMOLED-2.16/original-firmware
|
cd ESP32-S3-Touch-AMOLED-2.16/main-device
|
||||||
./backup_factory.sh
|
./burn.sh registration-signer
|
||||||
```
|
```
|
||||||
|
|
||||||
Ожидаемый результат:
|
Ожидаемый результат:
|
||||||
- `factory-full-16mb.bin`
|
- резервная копия заводской прошивки хранится отдельно от Git-проектов
|
||||||
- `factory-full-16mb.bin.sha256`
|
|
||||||
|
|
||||||
Восстановление:
|
Восстановление:
|
||||||
|
|
||||||
```bash
|
Восстановление выполняется из локального каталога backup конкретной платы.
|
||||||
./restore_factory_backup.sh
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5) Деплой (прошивка) — стандарт
|
## 5) Деплой (прошивка) — стандарт
|
||||||
|
|
||||||
@@ -67,7 +64,7 @@ cd ESP32-S3-Touch-AMOLED-2.16/main-device
|
|||||||
- `hello` — базовый экран
|
- `hello` — базовый экран
|
||||||
- `widgets` — экран+touch+IMU (официальный пример)
|
- `widgets` — экран+touch+IMU (официальный пример)
|
||||||
- `audio` — тест аудио тракта
|
- `audio` — тест аудио тракта
|
||||||
- `simple` — кастомный интеграционный тест (экран, touch, запись/воспроизведение, VU, tilt)
|
- `registration-signer` — актуальный скетч регистрации SHiNE
|
||||||
|
|
||||||
## 6) Как писать код под эту плату (важно)
|
## 6) Как писать код под эту плату (важно)
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,26 @@
|
|||||||
# ESP32-S3-Touch-AMOLED-2.16
|
# ESP32-S3-Touch-AMOLED-2.16
|
||||||
|
|
||||||
Подпроект для Waveshare `ESP32-S3-Touch-AMOLED-2.16`.
|
Подпроект SHiNE для платы Waveshare `ESP32-S3-Touch-AMOLED-2.16`.
|
||||||
|
|
||||||
Структура:
|
В основном проекте оставлен только актуальный рабочий скетч регистрации:
|
||||||
|
|
||||||
- `official-demo/` — официальный репозиторий примеров Waveshare
|
- `main-device/shine_registration_signer/shine_registration_signer.ino`
|
||||||
- `original-firmware/` — резервная копия заводской прошивки
|
- `main-device/burn.sh` — сборка и прошивка
|
||||||
- `main-device/` — скрипты быстрой проверки устройства и основной скетч `shine_homeserver_main/`
|
- `old_version/` — две старые версии homeserver, сохранённые только для истории
|
||||||
- `reference/` — локальные заметки по документации и железу
|
|
||||||
- `main-device/shine_homeserver_main/` — основной рабочий скетч ESP32-проекта `SHiNE`
|
|
||||||
|
|
||||||
Примечание по git:
|
Примеры Waveshare, библиотеки и справочные документы находятся в отдельном репозитории `SKETCH`:
|
||||||
|
|
||||||
- `official-demo/` держать как локальный внешний checkout из `https://github.com/waveshareteam/ESP32-S3-Touch-AMOLED-2.16`, в основной git его не добавлять.
|
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`
|
||||||
- `original-firmware/*.bin` — локальный дамп конкретной платы, в git не добавлять.
|
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/`
|
||||||
- `.arduino-build/` и готовые `.bin/.elf/.map` — сборочные артефакты, в git не добавлять.
|
|
||||||
|
Локальные сборочные артефакты (`.arduino-build/`, `.bin`, `.elf`, `.map`) в Git не добавляются.
|
||||||
|
|
||||||
Быстрый старт:
|
Быстрый старт:
|
||||||
|
|
||||||
1. Сделать backup текущей прошивки:
|
1. Убедиться, что рядом с `SHiNE-product` существует `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`.
|
||||||
- `cd original-firmware && ./backup_factory.sh`
|
2. Перейти в `main-device`.
|
||||||
2. Залить тест экрана/тача:
|
3. Собрать и прошить актуальный скетч:
|
||||||
- `cd ../main-device && ./burn.sh widgets`
|
|
||||||
3. Залить тест динамика:
|
`./burn.sh registration-signer`
|
||||||
- `cd ../main-device && ./burn.sh audio`
|
|
||||||
4. Залить основной UI:
|
Для тестового режима регистратора можно использовать `REGISTRAR_DEV_UNENCRYPTED=1`, но такой вариант нельзя использовать на рабочем устройстве.
|
||||||
- `cd ../main-device && ./burn.sh shine-homeserver-main`
|
|
||||||
|
|||||||
@@ -1,52 +1,14 @@
|
|||||||
# Main Device
|
# Main Device
|
||||||
|
|
||||||
Основной скетч homeserver и старые тестовые скетчи для быстрой проверки платы.
|
В этой папке оставлен только актуальный скетч `shine_registration_signer`.
|
||||||
`burn.sh` теперь:
|
|
||||||
- сам пытается найти USB-порт ESP32;
|
|
||||||
- сначала делает быструю инкрементальную сборку;
|
|
||||||
- если быстрая сборка не удалась, автоматически повторяет полную `clean`-сборку.
|
|
||||||
|
|
||||||
Для режимов `widgets`, `audio` и `hello` рядом должен лежать локальный checkout `official-demo/` из официального репозитория Waveshare. В основной git он не добавляется, потому что это большой внешний набор примеров, библиотек, прошивок и артефактов.
|
`burn.sh` поддерживает режимы:
|
||||||
|
|
||||||
Режимы:
|
- `registration-signer` — рабочий скетч регистрации SHiNE;
|
||||||
- `widgets` — экран + touch + IMU (пример `05_LVGL_Widgets`)
|
- `hello`, `widgets`, `audio` — официальные тесты Waveshare из репозитория `SKETCH`.
|
||||||
- `audio` — динамик/аудио-кодек (пример `07_ES8311`)
|
|
||||||
- `hello` — базовый тест экрана (пример `01_HelloWorld`)
|
|
||||||
- `simple` — простой кастомный тест: экран + touch + запись/проигрывание + наклон (IMU)
|
|
||||||
- `argon2` — генерация masterSecret через Argon2id с SD-картой как памятью (тест скорости)
|
|
||||||
- `homeserver-ui` — совместимый алиас, указывает на `shine_homeserver_main/`
|
|
||||||
- `shine-homeserver-main` — основной скетч проекта `SHiNE` для ESP32, текущая рабочая версия UI
|
|
||||||
- `shine-homeserver-ui-main` — старое имя основного скетча, оставлено как совместимый алиас
|
|
||||||
- `legacy-homeserver-ui` — старый UI-прототип `shine_homeserver_ui/`, оставлен как тестовый и не является основным
|
|
||||||
- `text-test` — диагностический экран рендера текста: default font, U8g2 ASCII, U8g2 кириллица, кнопки с подписями
|
|
||||||
- `gfx-text-test` — тот же тест рендера текста, но уже внутри новой папки `test_sketches/`
|
|
||||||
- `gfx-layout-test` — тест геометрии и нижних рядов кнопок
|
|
||||||
- `lvgl-basic-test` — минимальный экран на `LVGL` с текстом и кнопками
|
|
||||||
- `lvgl-interaction-test` — экран на `LVGL` с большим числом кнопок и сообщением о нажатой кнопке
|
|
||||||
- `lvgl-touch-debug-test` — точечная диагностика touch: сырые координаты, маркер точки и большая тест-кнопка `LVGL`
|
|
||||||
- `lvgl-official-based-test` — наш минимальный экран, но на максимально близкой к официальному `LVGL_Widgets` инициализации
|
|
||||||
- `lvgl-subserver-touch-test` — старый гибридный тест: `LVGL`-интерфейс, но display/touch init и raw touch-read взяты из старого `shine_homeserver_ui`; подтверждено на устройстве, touch работает, зелёных линий по краям нет
|
|
||||||
- `lvgl-russian-font-test` — тест кастомного `LVGL`-шрифта с кириллицей: русские кнопки, длинные подписи и статусы
|
|
||||||
- `lvgl-nav-minimal-test` — старое имя основного скетча, теперь ведёт на `shine_homeserver_main/` для совместимости
|
|
||||||
|
|
||||||
Запуск:
|
Официальные библиотеки должны находиться в соседнем репозитории:
|
||||||
|
|
||||||
- `./burn.sh widgets`
|
`SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`
|
||||||
- `./burn.sh audio`
|
|
||||||
- `./burn.sh hello`
|
Если репозитории расположены иначе, перед запуском укажите путь через переменную `DEMO_BASE`.
|
||||||
- `./burn.sh simple`
|
|
||||||
- `./burn.sh homeserver-ui`
|
|
||||||
- `./burn.sh shine-homeserver-main`
|
|
||||||
- `./burn.sh shine-homeserver-ui-main`
|
|
||||||
- `./burn.sh legacy-homeserver-ui`
|
|
||||||
- `./burn.sh text-test`
|
|
||||||
- `./burn.sh gfx-text-test`
|
|
||||||
- `./burn.sh gfx-layout-test`
|
|
||||||
- `./burn.sh lvgl-basic-test`
|
|
||||||
- `./burn.sh lvgl-interaction-test`
|
|
||||||
- `./burn.sh lvgl-touch-debug-test`
|
|
||||||
- `./burn.sh lvgl-official-based-test`
|
|
||||||
- `./burn.sh lvgl-subserver-touch-test`
|
|
||||||
- `./burn.sh lvgl-russian-font-test`
|
|
||||||
- `./burn.sh lvgl-nav-minimal-test`
|
|
||||||
- `./flash_shine_homeserver_main.sh` - автоматически находит USB-порт и заливает `shine_homeserver_main`
|
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <stdint.h>
|
|
||||||
#include <stddef.h>
|
|
||||||
|
|
||||||
// BLAKE2b state
|
|
||||||
struct B2State {
|
|
||||||
uint64_t h[8], t[2], f[2];
|
|
||||||
uint8_t buf[128];
|
|
||||||
size_t buflen, outlen;
|
|
||||||
};
|
|
||||||
@@ -3,7 +3,7 @@ set -euo pipefail
|
|||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
BOARD_DIR="$(cd "${ROOT_DIR}/.." && pwd)"
|
BOARD_DIR="$(cd "${ROOT_DIR}/.." && pwd)"
|
||||||
DEMO_BASE="${BOARD_DIR}/official-demo/examples/Arduino-v3.3.5"
|
DEMO_BASE="${DEMO_BASE:-${BOARD_DIR}/../../../../SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5}"
|
||||||
MODE="${1:-widgets}"
|
MODE="${1:-widgets}"
|
||||||
PORT="${PORT:-}"
|
PORT="${PORT:-}"
|
||||||
FQBN="${FQBN:-esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi}"
|
FQBN="${FQBN:-esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi}"
|
||||||
@@ -32,39 +32,16 @@ case "${MODE}" in
|
|||||||
hello) SKETCH_DIR="${DEMO_BASE}/examples/01_HelloWorld" ;;
|
hello) SKETCH_DIR="${DEMO_BASE}/examples/01_HelloWorld" ;;
|
||||||
widgets) SKETCH_DIR="${DEMO_BASE}/examples/05_LVGL_Widgets" ;;
|
widgets) SKETCH_DIR="${DEMO_BASE}/examples/05_LVGL_Widgets" ;;
|
||||||
audio) SKETCH_DIR="${DEMO_BASE}/examples/07_ES8311" ;;
|
audio) SKETCH_DIR="${DEMO_BASE}/examples/07_ES8311" ;;
|
||||||
simple) SKETCH_DIR="${ROOT_DIR}/simple_av_test" ;;
|
registration-signer) SKETCH_DIR="${ROOT_DIR}/shine_registration_signer" ;;
|
||||||
argon2) SKETCH_DIR="${ROOT_DIR}/argon2_sd_test" ;;
|
|
||||||
homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
|
||||||
shine-homeserver-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
|
||||||
shine-homeserver-ui-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
|
||||||
legacy-homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_ui" ;;
|
|
||||||
text-test) SKETCH_DIR="${ROOT_DIR}/text_render_test" ;;
|
|
||||||
gfx-text-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/gfx_text_render_test" ;;
|
|
||||||
gfx-layout-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/gfx_button_layout_test" ;;
|
|
||||||
lvgl-basic-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_basic_test" ;;
|
|
||||||
lvgl-interaction-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_interaction_test" ;;
|
|
||||||
lvgl-touch-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_touch_debug_test" ;;
|
|
||||||
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
|
|
||||||
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
|
|
||||||
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
|
|
||||||
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
|
||||||
*)
|
*)
|
||||||
echo "Unknown mode: ${MODE}" >&2
|
echo "Unknown mode: ${MODE}" >&2
|
||||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test" >&2
|
echo "Use one of: registration-signer, hello, widgets, audio" >&2
|
||||||
exit 2
|
exit 2
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
if [[ -z "${PORT}" ]]; then
|
|
||||||
if ! PORT="$(detect_port)"; then
|
|
||||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
|
||||||
exit 3
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== Mode: ${MODE}"
|
echo "== Mode: ${MODE}"
|
||||||
echo "== Sketch: ${SKETCH_DIR}"
|
echo "== Sketch: ${SKETCH_DIR}"
|
||||||
echo "== Port: ${PORT}"
|
|
||||||
echo "== FQBN: ${FQBN}"
|
echo "== FQBN: ${FQBN}"
|
||||||
|
|
||||||
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
||||||
@@ -81,12 +58,31 @@ compile_args=(
|
|||||||
"${SKETCH_DIR}"
|
"${SKETCH_DIR}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if [[ "${MODE}" == "registration-signer" && "${REGISTRAR_DEV_UNENCRYPTED:-0}" == "1" ]]; then
|
||||||
|
echo "WARNING: test-only registrar build; plaintext NVS, never provision a production key" >&2
|
||||||
|
compile_args=(--build-property "compiler.cpp.extra_flags=-DSHINE_REGISTRAR_INSECURE_DEV" "${compile_args[@]}")
|
||||||
|
fi
|
||||||
|
|
||||||
echo "== Compile: fast incremental build"
|
echo "== Compile: fast incremental build"
|
||||||
if ! arduino-cli compile "${compile_args[@]}"; then
|
if ! arduino-cli compile "${compile_args[@]}"; then
|
||||||
echo "== Compile: fast build failed, retrying clean build"
|
echo "== Compile: fast build failed, retrying clean build"
|
||||||
arduino-cli compile --clean "${compile_args[@]}"
|
arduino-cli compile --clean "${compile_args[@]}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${NO_UPLOAD:-0}" == "1" ]]; then
|
||||||
|
echo "== Done: compiled without upload (NO_UPLOAD=1)."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${PORT}" ]]; then
|
||||||
|
if ! PORT="$(detect_port)"; then
|
||||||
|
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||||
|
exit 3
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "== Port: ${PORT}"
|
||||||
|
|
||||||
arduino-cli upload \
|
arduino-cli upload \
|
||||||
-p "${PORT}" \
|
-p "${PORT}" \
|
||||||
--fqbn "${FQBN}" \
|
--fqbn "${FQBN}" \
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# SHiNE Registration Signer 1.0
|
||||||
|
|
||||||
|
Самостоятельный скетч для Waveshare ESP32-S3-Touch-AMOLED-2.16, не использует старые функции homeserver или кошелька. Сохраняет только подписанные сертификаты, а не произвольные сообщения. LVGL 8, тот же драйвер CO5300, CST92xx, AXP2101 и распиновка SDMMC 1-bit (CLK 2, CMD 1, D0 3) из старого скетча. GPIO2 освобождается после запуска дисплея.
|
||||||
|
|
||||||
|
## Сборка
|
||||||
|
|
||||||
|
В окружении разработчика с уже установленными библиотеками платы (Arduino ESP32 core 3.3.5, официальный demo libraries, LVGL, sodium) установить дополнительные Arduino-библиотеки `WebSockets` (Links2004) и `ArduinoJson` 7.x:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
arduino-cli lib install WebSockets ArduinoJson
|
||||||
|
cd ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device
|
||||||
|
NO_UPLOAD=1 ./burn.sh registration-signer
|
||||||
|
```
|
||||||
|
|
||||||
|
Сертификаты TLS проверяются через встроенный публичный CA `registrar_ca.h` (ISRG Root X1). Если endpoint использует другой CA, заменить trust anchor на проверенный корень, пересобрать. Не отключать проверку. `wss://host[:port]/ws`, без `ws://`. Для действительного TLS нужен SNTP. Неверный сертификат должен приводить к отказу соединения.
|
||||||
|
|
||||||
|
### Хранение ключа в прототипе
|
||||||
|
|
||||||
|
32-байтный secret seed Ed25519 в Base58 и сохранённые пароли Wi-Fi записываются во внутреннюю NVS ESP32 без требования Secure Boot, Flash Encryption или NVS Encryption. Экран VIEW KEYS показывает приватный ключ. Устройство следует использовать только как прототип с тестовым ключом, пока не настроено защищённое хранение.
|
||||||
|
|
||||||
|
## Установка
|
||||||
|
|
||||||
|
1. Вставить новую SD-карту FAT, включить устройство, открыть SETTINGS. В WI-FI выбрать доступную сеть и ввести пароль; сеть сохраняется только после успешного подключения. Настроить SERVER URL (достаточно хоста `t2.shineup.me`, прошивка добавит `wss://` и `/ws`) и NAMESPACE (без @). В SECRET KEY BASE58 ввести 32-байтный Ed25519 seed в Base58; прошивка сама восстанавливает полный секретный и публичный ключи. VIEW KEYS показывает публичный ключ и 32-байтный seed в Base58. Для настройки Solana registrar_pubkey использовать показанный публичный ключ. Все поля отображаются открытым текстом, а при повторном редактировании прежнее значение сохраняется целиком.
|
||||||
|
2. В Solana установить соответствующий публичный ключ нового namespace; в серверном конфиге выбрать external, настроить Resend и Turbo как раньше. Подключить устройство; проверить `/status`.
|
||||||
|
3. Главный экран показывает состояние Wi-Fi и авторизованного подключения к серверу, причину OFFLINE и время после последнего успешного Ping. Кнопка PING отправляет внеочередной запрос.
|
||||||
|
|
||||||
|
## SD формат 1.0
|
||||||
|
|
||||||
|
`/registrations/example.free.txt` — бинарный файл: major=1 (u8), minor=0 (u8), длина полного логина (u8), ASCII логин с @, Unix ms (u64 BE), длина raw signed DataItem (u32 BE), raw ANS-104. Имя в lowercase, оригинальный регистр сохраняется внутри. Внутренний и внешний Ed25519 уже в DataItem. SD не содержит приватного ключа. Email SHA-256 — часть публичного сертификата.
|
||||||
|
|
||||||
|
При совпадении всех полей включая оригинальный регистр, ключи и email hash возвращаются сохранённые bytes после проверки обеих подписей; при несовпадении 409. Новая выдача: файл .tmp, flush/close, rename, повторное чтение и сравнение, обновление NVS учёта, только затем отправка. Незавершённый .tmp блокирует выдачу до ручного разбора. Не удалять ранее выданные записи. Утрата истории относительно счётчика NVS блокирует выдачу. Перед каждой выдачей пересчитывается история; большие SD-архивы потребуют оптимизации индекса, иначе возможно превышение серверного тайм-аута. Не извлекать SD во время работы.
|
||||||
|
|
||||||
|
Лимит: 10 новых сертификатов за скользящие 5 часов. Время выдачи хранится на SD, в NVS — максимальная отметка и счётчик. При откате часов выдача блокируется. Повтор сохранённого сертификата не расходует квоту. Это защита от скомпрометированного сервера, а не полноценная защита от физического удаления/подмены SD или подмены NTP; не давать посторонним физический доступ.
|
||||||
|
|
||||||
|
`App=test5599` — текущая эпоха проекта, `certificate_v1.h` должен изменяться согласованно с `ShineProtocolTags.CORE_NAMESPACE`, если эпоха будет изменена. Ранее подписанная запись для login остаётся неизменной; новый сертификат для того же login автоматически не создаётся.
|
||||||
|
|
||||||
|
## Приёмка
|
||||||
|
|
||||||
|
До production проверить: сборку обеих частей, экран/клавиатуру и SD после инициализации AMOLED, WSS и отклонение неверной CA/hostname, авторизацию верного/чужого ключа, перезагрузку, повтор запроса с теми же данными, конфликт регистра, лимит 10/5ч после перезапуска, отключение сети/SD и потерю ответа, ошибку NVS, Pause, публикацию Turbo и импорт, статус. `host-tests/run.sh` сравнивает сертификат с Java reference vector. Host-тест не заменяет сборку ESP/проверку реального устройства.
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace regkey {
|
||||||
|
static constexpr char ALPHABET[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
||||||
|
|
||||||
|
inline std::string encode(const uint8_t *data, size_t length) {
|
||||||
|
size_t zeros = 0;
|
||||||
|
while (zeros < length && data[zeros] == 0) ++zeros;
|
||||||
|
std::vector<uint8_t> digits;
|
||||||
|
for (size_t i = zeros; i < length; ++i) {
|
||||||
|
unsigned carry = data[i];
|
||||||
|
for (auto &digit : digits) {
|
||||||
|
carry += 256U * digit;
|
||||||
|
digit = carry % 58U;
|
||||||
|
carry /= 58U;
|
||||||
|
}
|
||||||
|
while (carry) { digits.push_back(carry % 58U); carry /= 58U; }
|
||||||
|
}
|
||||||
|
std::string result(zeros, '1');
|
||||||
|
for (auto it = digits.rbegin(); it != digits.rend(); ++it) result += ALPHABET[*it];
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool decode32(const char *text, uint8_t out[32]) {
|
||||||
|
if (!text || !*text) return false;
|
||||||
|
const size_t length = strlen(text);
|
||||||
|
if (length > 45) return false;
|
||||||
|
size_t zeros = 0;
|
||||||
|
while (zeros < length && text[zeros] == '1') ++zeros;
|
||||||
|
std::vector<uint8_t> bytes;
|
||||||
|
for (size_t i = zeros; i < length; ++i) {
|
||||||
|
const char *found = strchr(ALPHABET, text[i]);
|
||||||
|
if (!found) return false;
|
||||||
|
unsigned carry = found - ALPHABET;
|
||||||
|
for (auto &byte : bytes) {
|
||||||
|
carry += 58U * byte;
|
||||||
|
byte = carry & 255U;
|
||||||
|
carry >>= 8U;
|
||||||
|
}
|
||||||
|
while (carry) { bytes.push_back(carry & 255U); carry >>= 8U; }
|
||||||
|
if (zeros + bytes.size() > 32) return false;
|
||||||
|
}
|
||||||
|
if (zeros + bytes.size() != 32) return false;
|
||||||
|
memset(out, 0, 32);
|
||||||
|
for (size_t i = 0; i < bytes.size(); ++i) out[31 - i] = bytes[i];
|
||||||
|
return encode(out, 32) == text;
|
||||||
|
}
|
||||||
|
} // namespace regkey
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
#include <cstring>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <sodium.h>
|
||||||
|
#include <mbedtls/sha512.h>
|
||||||
|
|
||||||
|
// Точное соответствие FreeRegistrationCertificateV1.java / Ans104DataItem.java.
|
||||||
|
namespace regv1 {
|
||||||
|
using Bytes=std::vector<uint8_t>;
|
||||||
|
inline Bytes bytes(const std::string &s){return Bytes(s.begin(),s.end());}
|
||||||
|
inline void append(Bytes &a,const Bytes &b){a.insert(a.end(),b.begin(),b.end());}
|
||||||
|
inline void append(Bytes &a,const uint8_t *p,size_t n){a.insert(a.end(),p,p+n);}
|
||||||
|
inline void integer(Bytes &a,uint64_t n,unsigned count,bool little){for(unsigned i=0;i<count;i++)a.push_back(uint8_t(n>>(8*(little?i:count-1-i))));}
|
||||||
|
inline Bytes sha384(const Bytes &a){uint8_t digest[64]={};mbedtls_sha512(a.data(),a.size(),digest,1);return Bytes(digest,digest+48);}
|
||||||
|
inline Bytes combineHash(const Bytes &a,const Bytes &b){Bytes t=a;append(t,b);return sha384(t);}
|
||||||
|
inline Bytes blob(const Bytes &a){return combineHash(sha384(bytes("blob"+std::to_string(a.size()))),sha384(a));}
|
||||||
|
inline void avro(Bytes &a,uint64_t n){n*=2;while(n>127){a.push_back((n&127)|128);n>>=7;}a.push_back(n);}
|
||||||
|
inline void avroString(Bytes &a,const std::string &s){avro(a,s.size());append(a,bytes(s));}
|
||||||
|
inline Bytes tags(){Bytes a;avro(a,3);avroString(a,"App");avroString(a,"test5599");avroString(a,"t");avroString(a,"reg");avroString(a,"Protocol");avroString(a,"SHiNE-Free-Registration-V1");avro(a,0);return a;}
|
||||||
|
inline Bytes outerMessage(const Bytes &owner,const Bytes &data){Bytes a=sha384(bytes("list8"));for(const auto &v:std::vector<Bytes>{bytes("dataitem"),bytes("1"),bytes("2"),owner,{}, {},tags(),data})a=combineHash(a,blob(v));return a;}
|
||||||
|
inline bool validLogin(const std::string &login){auto at=login.find('@');if(login.size()>30||at==0||at==std::string::npos||at+1==login.size())return false;for(size_t i=0;i<login.size();i++){if(i==at)continue;char c=login[i];if(!((c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='_'||(i<at&&c>='A'&&c<='Z')))return false;}return true;}
|
||||||
|
inline Bytes identity(const std::string &login,const Bytes &root,const Bytes &chain,const Bytes &client){if(!validLogin(login)||root.size()!=32||chain.size()!=32||client.size()!=32)return {};Bytes a={1,0,uint8_t(login.size())};append(a,bytes(login));append(a,root);append(a,chain);append(a,client);return a;}
|
||||||
|
inline Bytes innerMessage(const Bytes &fields){Bytes a=bytes("SHiNE_FREE_REG_V1");a.push_back(0);append(a,fields);return a;}
|
||||||
|
inline Bytes sign(const Bytes &msg,const uint8_t secret[64]){Bytes sig(64);if(crypto_sign_detached(sig.data(),nullptr,msg.data(),msg.size(),secret)!=0)return {};return sig;}
|
||||||
|
inline Bytes issue(const Bytes &fields,const Bytes &emailHash,const uint8_t owner[32],const uint8_t secret[64]){if(fields.empty()||emailHash.size()!=32)return {};Bytes inner=sign(innerMessage(fields),secret);if(inner.size()!=64)return {};Bytes data=fields;append(data,inner);append(data,emailHash);Bytes pub(owner,owner+32),outer=sign(outerMessage(pub,data),secret);if(outer.size()!=64)return {};Bytes result={2,0};append(result,outer);append(result,pub);result.push_back(0);result.push_back(0);integer(result,3,8,true);Bytes t=tags();integer(result,t.size(),8,true);append(result,t);append(result,data);return result;}
|
||||||
|
inline bool matches(const Bytes &raw,const Bytes &fields,const Bytes &emailHash,const uint8_t owner[32]){Bytes t=tags();size_t off=116+t.size();if(fields.empty()||emailHash.size()!=32||raw.size()!=off+fields.size()+96||raw[0]!=2||raw[1]!=0||memcmp(raw.data()+66,owner,32))return false;Bytes head={0,0};integer(head,3,8,true);integer(head,t.size(),8,true);append(head,t);if(memcmp(raw.data()+98,head.data(),head.size())||memcmp(raw.data()+off,fields.data(),fields.size())||memcmp(raw.data()+off+fields.size()+64,emailHash.data(),32))return false;Bytes inner=innerMessage(fields),data(raw.begin()+off,raw.end()),pub(owner,owner+32),outer=outerMessage(pub,data);return crypto_sign_verify_detached(raw.data()+off+fields.size(),inner.data(),inner.size(),owner)==0&&crypto_sign_verify_detached(raw.data()+2,outer.data(),outer.size(),owner)==0;}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#include "certificate_v1.h"
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstdio>
|
||||||
|
int main(){using namespace regv1;assert(sodium_init()>=0);uint8_t seed[32],pub[32],secret[64];Bytes r(32),b(32),c(32),e(32);for(int i=0;i<32;i++){seed[i]=i;r[i]=i+32;b[i]=i+64;c[i]=i+96;e[i]=i+128;}assert(crypto_sign_seed_keypair(pub,secret,seed)==0);auto fields=identity("Example@free",r,b,c);auto raw=issue(fields,e,pub,secret);assert(matches(raw,fields,e,pub));auto bad=raw;bad[2]^=1;assert(!matches(bad,fields,e,pub));bad=raw;bad.back()^=1;assert(!matches(bad,fields,e,pub));assert(!validLogin("../evil@free"));assert(!validLogin("Example@Free"));for(auto v:raw)printf("%02x",v);puts("");}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||||
|
TMP=$(mktemp -d)
|
||||||
|
trap 'rm -rf "$TMP"' EXIT
|
||||||
|
# Linux: g++, libsodium-dev, libmbedtls-dev (mbedTLS 3.x).
|
||||||
|
g++ -std=c++17 -I"$HERE/.." "$HERE/certificate_vector.cpp" -lsodium -lmbedcrypto -o "$TMP/vector"
|
||||||
|
"$TMP/vector" > "$TMP/actual.hex"
|
||||||
|
cmp "$HERE/certificate_v1.hex" "$TMP/actual.hex"
|
||||||
|
echo 'PASS: ESP32 certificate equals Java reference vector, tamper rejection'
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#pragma once
|
||||||
|
// Публичный trust anchor ISRG Root X1. Заменить при использовании другой доверенной CA.
|
||||||
|
static const char REGISTRAR_CA[] = R"PEM(
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
||||||
|
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
||||||
|
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
||||||
|
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
||||||
|
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
||||||
|
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
||||||
|
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
||||||
|
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
||||||
|
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
||||||
|
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
||||||
|
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
||||||
|
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
||||||
|
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
||||||
|
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
||||||
|
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
||||||
|
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
||||||
|
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
||||||
|
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
||||||
|
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
||||||
|
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
||||||
|
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
||||||
|
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
||||||
|
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
||||||
|
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
||||||
|
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
||||||
|
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
||||||
|
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
||||||
|
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
||||||
|
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
)PEM";
|
||||||
@@ -0,0 +1,377 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <Preferences.h>
|
||||||
|
#include <SD_MMC.h>
|
||||||
|
#include <WebSocketsClient.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <Arduino_GFX_Library.h>
|
||||||
|
#include <TouchDrvCSTXXX.hpp>
|
||||||
|
#include <lvgl.h>
|
||||||
|
#include <mbedtls/base64.h>
|
||||||
|
#include <mbedtls/sha256.h>
|
||||||
|
#include <sdkconfig.h>
|
||||||
|
#include <esp_flash_encrypt.h>
|
||||||
|
#include <esp_secure_boot.h>
|
||||||
|
#include <driver/gpio.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <algorithm>
|
||||||
|
#define XPOWERS_CHIP_AXP2101
|
||||||
|
#include "XPowersLib.h"
|
||||||
|
#include "certificate_v1.h"
|
||||||
|
#include "registrar_ca.h"
|
||||||
|
#include "base58_key.h"
|
||||||
|
|
||||||
|
enum Screen {HOME,MENU,WIFI_OVERVIEW,WIFI_SCAN,EDITOR,KEYS};
|
||||||
|
enum EditKind {EDIT_WIFI,EDIT_URL,EDIT_NAMESPACE,EDIT_SECRET};
|
||||||
|
using regv1::Bytes;
|
||||||
|
static constexpr uint64_t WINDOW_MS=5ULL*60*60*1000;
|
||||||
|
static constexpr size_t LIMIT=10;
|
||||||
|
static Preferences prefs;
|
||||||
|
static WebSocketsClient ws;
|
||||||
|
static String ssid,wifiPass,endpoint,ns,host,path,lastLogin="-",lastError="";
|
||||||
|
static uint16_t port=443;
|
||||||
|
static uint8_t seed[32]={},owner[32]={},secret[64]={};
|
||||||
|
static bool uiReady=false,keyReady=false,sdReady=false,paused=false,authorized=false,connecting=false,secureStorage=false;
|
||||||
|
static uint32_t seq=0,pingAt=0,pingSent=0,authAt=0,wifiAt=0,refreshAt=0;
|
||||||
|
static String pingId,authId,serverReason="Waiting for Wi-Fi";
|
||||||
|
static uint32_t lastPingAckAt=0,wsAttemptAt=0;
|
||||||
|
static std::vector<uint64_t> recent;
|
||||||
|
static uint64_t total=0,lastRecorded=0;
|
||||||
|
static Arduino_DataBus *bus=new Arduino_ESP32QSPI(12,38,4,5,6,7);
|
||||||
|
static Arduino_CO5300 *gfx=new Arduino_CO5300(bus,2,0,480,480,0,0,0,0);
|
||||||
|
static TouchDrvCST92xx touch;
|
||||||
|
static XPowersPMU power;
|
||||||
|
static bool powerReady=false;
|
||||||
|
static lv_disp_draw_buf_t drawBuf;
|
||||||
|
|
||||||
|
static String b64(const uint8_t *p,size_t n){size_t len=0;std::vector<uint8_t> b(4*((n+2)/3)+1);if(mbedtls_base64_encode(b.data(),b.size(),&len,p,n))return "";b[len]=0;return String((char*)b.data());}
|
||||||
|
static bool decode(const String &s,Bytes &b,size_t expected){if(s.length()>4*((expected+2)/3))return false;b.resize(expected);size_t n=0;return !mbedtls_base64_decode(b.data(),b.size(),&n,(const uint8_t*)s.c_str(),s.length())&&n==expected;}
|
||||||
|
static uint64_t nowMs(){struct timeval tv;gettimeofday(&tv,nullptr);return tv.tv_sec>1700000000LL?uint64_t(tv.tv_sec)*1000+tv.tv_usec/1000:0;}
|
||||||
|
static bool safeTime(){uint64_t t=nowMs();return t&&t>=lastRecorded;}
|
||||||
|
static bool validNamespace(const String &s){return regv1::validLogin(std::string("x@")+s.c_str());}
|
||||||
|
static String filename(const String &login){String f=login;f.toLowerCase();f.replace('@','.');return "/registrations/"+f+".txt";}
|
||||||
|
static uint64_t readInt(const Bytes &b,size_t off,size_t n){uint64_t v=0;for(size_t i=0;i<n;i++)v=(v<<8)|b[off+i];return v;}
|
||||||
|
static void keepTime(uint64_t t){recent.push_back(t);std::sort(recent.begin(),recent.end());if(recent.size()>LIMIT)recent.erase(recent.begin());lastRecorded=std::max(lastRecorded,t);}
|
||||||
|
static size_t used(){uint64_t t=nowMs();size_t n=0;for(auto v:recent)if(v>t||t-v<WINDOW_MS)n++;return n;}
|
||||||
|
static bool readRecord(const String &path,String &login,uint64_t &when,Bytes &raw){
|
||||||
|
File f=SD_MMC.open(path,FILE_READ);if(!f||f.isDirectory()||f.size()<16||f.size()>8192)return false;
|
||||||
|
Bytes b(f.size());if(f.read(b.data(),b.size())!=b.size())return false;f.close();
|
||||||
|
size_t n=b[2];if(b[0]!=1||b[1]!=0||n==0||n>30||b.size()<15+n)return false;
|
||||||
|
login="";for(size_t i=0;i<n;i++)login+=(char)b[3+i];if(!regv1::validLogin(login.c_str())||filename(login)!=path)return false;
|
||||||
|
when=readInt(b,3+n,8);size_t len=readInt(b,11+n,4);if(when<1700000000000ULL||len==0||len>4096||b.size()!=15+n+len)return false;
|
||||||
|
raw.assign(b.begin()+15+n,b.end());return true;
|
||||||
|
}
|
||||||
|
static bool loadHistory(){
|
||||||
|
recent.clear();total=0;lastRecorded=prefs.getULong64("lastIssue",0);
|
||||||
|
if(!SD_MMC.exists("/registrations")&&!SD_MMC.mkdir("/registrations"))return false;
|
||||||
|
File dir=SD_MMC.open("/registrations");if(!dir||!dir.isDirectory())return false;
|
||||||
|
for(File f=dir.openNextFile();f;f=dir.openNextFile()){
|
||||||
|
String name=f.name();bool isDir=f.isDirectory();f.close();if(isDir)continue;
|
||||||
|
if(name.endsWith(".tmp")){lastError="Interrupted SD write; inspect card";return false;}
|
||||||
|
if(!name.endsWith(".txt"))continue;
|
||||||
|
String p=name.startsWith("/")?name:String("/registrations/")+name;
|
||||||
|
String login;uint64_t t;Bytes raw;if(!readRecord(p,login,t,raw))return false;keepTime(t);total++;
|
||||||
|
}
|
||||||
|
// NVS сохраняет минимальный счётчик; утрата файлов не сбрасывает лимит молча.
|
||||||
|
if(total<prefs.getULong64("issued",0))return false;
|
||||||
|
if(total!=prefs.getULong64("issued",0)&&prefs.putULong64("issued",total)!=8)return false;
|
||||||
|
if(lastRecorded!=prefs.getULong64("lastIssue",0)&&prefs.putULong64("lastIssue",lastRecorded)!=8)return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
static bool storeRecord(const String &login,uint64_t when,const Bytes &raw){
|
||||||
|
String target=filename(login),tmp=target+".tmp";if(SD_MMC.exists(target)||SD_MMC.exists(tmp))return false;
|
||||||
|
Bytes b={1,0,uint8_t(login.length())};regv1::append(b,regv1::bytes(login.c_str()));regv1::integer(b,when,8,false);regv1::integer(b,raw.size(),4,false);regv1::append(b,raw);
|
||||||
|
File f=SD_MMC.open(tmp,FILE_WRITE);if(!f)return false;bool ok=f.write(b.data(),b.size())==b.size();f.flush();f.close();
|
||||||
|
if(!ok||!SD_MMC.rename(tmp,target))return false;
|
||||||
|
String check;uint64_t t;Bytes data;if(!readRecord(target,check,t,data)||check!=login||t!=when||data!=raw)return false;
|
||||||
|
keepTime(when);total++;lastLogin=login;
|
||||||
|
return prefs.putULong64("lastIssue",lastRecorded)==8&&prefs.putULong64("issued",total)==8;
|
||||||
|
}
|
||||||
|
static String nextId(){return "esp-"+String(++seq);}
|
||||||
|
static void sendJson(JsonDocument &d){String s;serializeJson(d,s);if(!ws.sendTXT(s))ws.disconnect();}
|
||||||
|
static void request(const char *op,const String &id,JsonDocument &d){d["op"]=op;d["requestId"]=id;sendJson(d);}
|
||||||
|
static void result(const String &id,int status,const Bytes &raw={}){JsonDocument d;d["status"]=status;d["payload"].to<JsonObject>();if(status==200)d["payload"]["dataItemB64"]=b64(raw.data(),raw.size());request("RegistrarSignResult",id,d);}
|
||||||
|
static void signRegistration(const String &id,JsonObjectConst p){
|
||||||
|
if(!authorized||!keyReady||!sdReady){result(id,503);return;}
|
||||||
|
String login=p["login"]|"";if(!regv1::validLogin(login.c_str())){result(id,400);return;}
|
||||||
|
if(login.substring(login.indexOf('@')+1)!=ns){result(id,403);return;}
|
||||||
|
Bytes root,chain,client,email;
|
||||||
|
if(!decode(p["rootPublicKey"]|"",root,32)||!decode(p["blockchainPublicKey"]|"",chain,32)||!decode(p["clientPublicKey"]|"",client,32)||!decode(p["emailSha256"]|"",email,32)){result(id,400);return;}
|
||||||
|
if(!loadHistory()){sdReady=false;lastError="SD history unavailable";result(id,500);return;}
|
||||||
|
Bytes identity=regv1::identity(login.c_str(),root,chain,client);String file=filename(login);
|
||||||
|
if(SD_MMC.exists(file)){
|
||||||
|
String old;uint64_t when;Bytes raw;if(!readRecord(file,old,when,raw)){sdReady=false;result(id,500);return;}
|
||||||
|
if(old!=login||!regv1::matches(raw,identity,email,owner)){result(id,409);return;}
|
||||||
|
result(id,200,raw);return;
|
||||||
|
}
|
||||||
|
uint64_t issuedAt=nowMs();if(!issuedAt||issuedAt<lastRecorded){result(id,503);return;}if(used()>=LIMIT){result(id,429);return;}
|
||||||
|
// Проверка SD перед подписанием: карта не должна быть извлечена или заменена незаметно.
|
||||||
|
if(!SD_MMC.exists("/registrations")){sdReady=false;result(id,500);return;}
|
||||||
|
Bytes raw=regv1::issue(identity,email,owner,secret);
|
||||||
|
if(raw.empty()||!storeRecord(login,issuedAt,raw)){sdReady=false;lastError="SD/NVS commit failed";result(id,500);return;}
|
||||||
|
result(id,200,raw);
|
||||||
|
}
|
||||||
|
static void event(WStype_t type,uint8_t *payload,size_t len){
|
||||||
|
if(type==WStype_DISCONNECTED){authorized=false;pingId="";if(WiFi.status()==WL_CONNECTED&&(serverReason.startsWith("Connecting")||serverReason=="Connected and authorized"))serverReason="WebSocket disconnected; retrying";return;}
|
||||||
|
if(type==WStype_ERROR){authorized=false;serverReason="TLS/WebSocket connection error";return;}
|
||||||
|
if(type==WStype_CONNECTED){authorized=false;pingId="";authAt=millis();serverReason="Requesting registrar challenge";authId=nextId();JsonDocument d;d["payload"]["namespace"]=ns;request("RegistrarChallenge",authId,d);return;}
|
||||||
|
if(type!=WStype_TEXT||len>8192)return;
|
||||||
|
JsonDocument d;if(deserializeJson(d,payload,len))return;
|
||||||
|
String op=d["op"]|"",id=d["requestId"]|"";int status=d["status"]|0;JsonObjectConst p=d["payload"].as<JsonObjectConst>();
|
||||||
|
if(op=="RegistrarChallenge"&&id==authId&&!authorized){
|
||||||
|
String nonce=p["nonce"]|"",server=p["serverLogin"]|"";if(status!=200||nonce.length()!=43||server.isEmpty()||server.length()>128||!safeTime()){serverReason=status!=200?"Challenge rejected: "+String(status):"Invalid server challenge";ws.disconnect();return;}
|
||||||
|
for(size_t i=0;i<nonce.length();i++){char c=nonce[i];if(!isalnum((unsigned char)c)&&c!='_'&&c!='-'){ws.disconnect();return;}}
|
||||||
|
uint64_t t=nowMs();String msg="SHINE_REGISTRAR_CONNECT_V1:"+server+":"+ns+":"+String((unsigned long long)t)+":"+nonce;
|
||||||
|
Bytes sig=regv1::sign(regv1::bytes(msg.c_str()),secret);if(sig.size()!=64){ws.disconnect();return;}
|
||||||
|
JsonDocument out;out["payload"]["version"]="1.0";out["payload"]["namespace"]=ns;out["payload"]["timeMs"]=t;out["payload"]["signatureB64"]=b64(sig.data(),sig.size());authId=nextId();serverReason="Authenticating registrar";request("RegistrarConnect",authId,out);
|
||||||
|
}else if(op=="RegistrarConnect"&&id==authId){if(status!=200){serverReason="Registrar auth rejected: "+String(status);lastError=serverReason;ws.disconnect();return;}authorized=true;pingAt=millis();serverReason="Connected and authorized";lastError="";}
|
||||||
|
else if(op=="Ping"&&authorized&&id==pingId){if(status==200){pingId="";lastPingAckAt=millis();serverReason="Connected and authorized";}else{serverReason="Ping rejected: "+String(status);ws.disconnect();}}
|
||||||
|
else if(op=="RegistrarSignRegistration"&&authorized&&!id.isEmpty())signRegistration(id,p);
|
||||||
|
}
|
||||||
|
static bool parseEndpoint(){if(!endpoint.startsWith("wss://"))return false;int slash=endpoint.indexOf('/',6);String authority=slash<0?endpoint.substring(6):endpoint.substring(6,slash);path=slash<0?"/ws":endpoint.substring(slash);if(path!="/ws"||authority.isEmpty())return false;int colon=authority.indexOf(':');host=colon<0?authority:authority.substring(0,colon);long n=colon<0?443:authority.substring(colon+1).toInt();if(n<1||n>65535||host.isEmpty())return false;for(size_t i=0;i<host.length();i++){char c=host[i];if(!isalnum((unsigned char)c)&&c!='.'&&c!='-')return false;}port=n;return true;}
|
||||||
|
static void stopNetwork(){ws.disconnect();connecting=false;authorized=false;pingId="";serverReason="Reconnecting after settings change";}
|
||||||
|
static constexpr int MAX_WIFI_PROFILES=8;
|
||||||
|
static String knownSsids[MAX_WIFI_PROFILES],knownPasswords[MAX_WIFI_PROFILES];
|
||||||
|
static uint32_t wifiScanAt=0,wifiConnectAt=0;
|
||||||
|
static bool wifiScanning=false,wifiTrying=false;
|
||||||
|
static int wifiCandidate=-1,wifiOrder[MAX_WIFI_PROFILES],wifiOrderCount=0,wifiOrderPos=0;
|
||||||
|
static void saveWifiProfiles(){
|
||||||
|
bool ok=true;
|
||||||
|
for(int i=0;i<MAX_WIFI_PROFILES;i++){
|
||||||
|
String a="net"+String(i),b="pass"+String(i);
|
||||||
|
ok=prefs.putString(a.c_str(),knownSsids[i])==knownSsids[i].length()&&ok;
|
||||||
|
ok=prefs.putString(b.c_str(),knownPasswords[i])==knownPasswords[i].length()&&ok;
|
||||||
|
}
|
||||||
|
if(!ok)lastError="Wi-Fi storage failed";
|
||||||
|
}
|
||||||
|
static void rememberWifi(const String &name,const String &pass){
|
||||||
|
if(name.isEmpty())return;
|
||||||
|
int slot=-1;
|
||||||
|
for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==name){slot=i;break;}
|
||||||
|
if(slot<0)for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i].isEmpty()){slot=i;break;}
|
||||||
|
if(slot<0){for(int i=0;i<MAX_WIFI_PROFILES-1;i++){knownSsids[i]=knownSsids[i+1];knownPasswords[i]=knownPasswords[i+1];}slot=MAX_WIFI_PROFILES-1;}
|
||||||
|
knownSsids[slot]=name;knownPasswords[slot]=pass;saveWifiProfiles();
|
||||||
|
}
|
||||||
|
static void beginWifiCandidate(int index){
|
||||||
|
wifiCandidate=index;wifiTrying=true;wifiConnectAt=millis();
|
||||||
|
WiFi.disconnect(false,false);WiFi.begin(knownSsids[index].c_str(),knownPasswords[index].c_str());
|
||||||
|
}
|
||||||
|
static void manageWifi(){
|
||||||
|
if(WiFi.status()==WL_CONNECTED){if(wifiTrying&&wifiCandidate>=0){ssid=knownSsids[wifiCandidate];wifiPass=knownPasswords[wifiCandidate];prefs.putString("ssid",ssid);prefs.putString("wifiPass",wifiPass);}wifiTrying=false;wifiScanning=false;return;}
|
||||||
|
if(wifiTrying){
|
||||||
|
if(millis()-wifiConnectAt<12000)return;
|
||||||
|
wifiTrying=false;WiFi.disconnect(false,false);
|
||||||
|
if(++wifiOrderPos<wifiOrderCount){beginWifiCandidate(wifiOrder[wifiOrderPos]);return;}
|
||||||
|
WiFi.scanDelete();wifiScanAt=millis();return;
|
||||||
|
}
|
||||||
|
if(wifiScanning){
|
||||||
|
int count=WiFi.scanComplete();if(count==WIFI_SCAN_RUNNING)return;
|
||||||
|
wifiScanning=false;
|
||||||
|
wifiOrderCount=0;wifiOrderPos=0;
|
||||||
|
if(count>0){
|
||||||
|
for(int pass=0;pass<2;pass++)for(int i=0;i<MAX_WIFI_PROFILES;i++){
|
||||||
|
if(knownSsids[i].isEmpty()||(pass==0)!=(knownSsids[i]==ssid))continue;
|
||||||
|
for(int j=0;j<count;j++)if(knownSsids[i]==WiFi.SSID(j)){wifiOrder[wifiOrderCount++]=i;break;}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WiFi.scanDelete();wifiScanAt=millis();
|
||||||
|
if(wifiOrderCount)beginWifiCandidate(wifiOrder[0]);return;
|
||||||
|
}
|
||||||
|
if(wifiScanAt&&millis()-wifiScanAt<15000)return;
|
||||||
|
bool any=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(!knownSsids[i].isEmpty())any=true;
|
||||||
|
if(!any)return;
|
||||||
|
WiFi.mode(WIFI_STA);WiFi.scanNetworks(true);wifiScanning=true;wifiScanAt=millis();
|
||||||
|
}
|
||||||
|
static void manageNetwork(){
|
||||||
|
manageWifi();
|
||||||
|
if(WiFi.status()!=WL_CONNECTED){if(connecting){ws.disconnect();connecting=false;}authorized=false;serverReason="Waiting for Wi-Fi";return;}
|
||||||
|
if(!keyReady||!validNamespace(ns)||!parseEndpoint()||!safeTime()){if(connecting){ws.disconnect();connecting=false;}authorized=false;serverReason=!keyReady?"Registration key missing":!validNamespace(ns)?"Invalid namespace":!parseEndpoint()?"Invalid server address":"Waiting for network time (NTP)";return;}
|
||||||
|
if(!connecting){serverReason="Connecting to "+host+":"+String(port)+" (TLS)";wsAttemptAt=millis();ws.beginSslWithCA(host.c_str(),port,path.c_str(),REGISTRAR_CA);ws.onEvent(event);ws.setReconnectInterval(5000);connecting=true;}
|
||||||
|
ws.loop();
|
||||||
|
if(!ws.isConnected()&&millis()-wsAttemptAt>15000&&(serverReason.startsWith("Connecting")||serverReason.startsWith("WebSocket disconnected")))serverReason="Cannot reach "+host+" (DNS/TLS/port)";
|
||||||
|
if(ws.isConnected()&&!authorized&&millis()-authAt>12000){serverReason="Registrar auth timed out";ws.disconnect();return;}
|
||||||
|
if(authorized&&!pingId.isEmpty()&&millis()-pingSent>10000){serverReason="Ping timed out";ws.disconnect();return;}
|
||||||
|
if(authorized&&pingId.isEmpty()&&millis()-pingAt>=45000){JsonDocument d;d["payload"]["ts"]=nowMs();pingId=nextId();pingAt=pingSent=millis();request("Ping",pingId,d);}
|
||||||
|
}
|
||||||
|
static void flushDisplay(lv_disp_drv_t *d,const lv_area_t *a,lv_color_t *c){
|
||||||
|
#if LV_COLOR_16_SWAP
|
||||||
|
gfx->draw16bitBeRGBBitmap(a->x1,a->y1,(uint16_t*)&c->full,a->x2-a->x1+1,a->y2-a->y1+1);
|
||||||
|
#else
|
||||||
|
gfx->draw16bitRGBBitmap(a->x1,a->y1,(uint16_t*)&c->full,a->x2-a->x1+1,a->y2-a->y1+1);
|
||||||
|
#endif
|
||||||
|
lv_disp_flush_ready(d);
|
||||||
|
}
|
||||||
|
static void readTouch(lv_indev_drv_t *,lv_indev_data_t *d){int16_t x=0,y=0;d->state=touch.getPoint(&x,&y,1)>0?LV_INDEV_STATE_PR:LV_INDEV_STATE_REL;d->point.x=x;d->point.y=y;}
|
||||||
|
static void tick(void *){lv_tick_inc(2);}
|
||||||
|
static void home();
|
||||||
|
static void settings();
|
||||||
|
static lv_obj_t *button(lv_obj_t *parent,const char *label,lv_event_cb_t cb){lv_obj_t *b=lv_btn_create(parent);lv_obj_t *l=lv_label_create(b);lv_label_set_text(l,label);lv_obj_center(l);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,nullptr);return b;}
|
||||||
|
static Screen screen=HOME;
|
||||||
|
static EditKind editKind=EDIT_URL;
|
||||||
|
static int menuIndex=0,scanCount=0,keyboardPage=0;
|
||||||
|
static String scanNames[20],selectedWifi,editValue,uiMessage;
|
||||||
|
static bool keyboardSymbols=false,keyboardShift=false;
|
||||||
|
static lv_obj_t *editorInput=nullptr,*keyboard=nullptr,*statusLabel=nullptr,*editorHint=nullptr;
|
||||||
|
static void drawScreen();
|
||||||
|
static void baseScreen(Screen next){screen=next;lv_obj_clean(lv_scr_act());statusLabel=nullptr;editorInput=nullptr;keyboard=nullptr;editorHint=nullptr;lv_obj_set_style_bg_color(lv_scr_act(),lv_color_hex(0x101820),0);lv_obj_set_style_text_color(lv_scr_act(),lv_color_hex(0xe4f0ef),0);}
|
||||||
|
static void title(const char *s){auto l=lv_label_create(lv_scr_act());lv_label_set_text(l,s);lv_obj_align(l,LV_ALIGN_TOP_MID,0,14);}
|
||||||
|
static void message(const String &s,int y){auto l=lv_label_create(lv_scr_act());lv_obj_set_width(l,440);lv_label_set_long_mode(l,LV_LABEL_LONG_WRAP);lv_label_set_text(l,s.c_str());lv_obj_set_pos(l,20,y);}
|
||||||
|
static void updateHome();
|
||||||
|
static void sendPingNow(){
|
||||||
|
if(!authorized||!ws.isConnected()){serverReason="Ping unavailable: server offline";updateHome();return;}
|
||||||
|
if(!pingId.isEmpty()){serverReason="Ping already pending";updateHome();return;}
|
||||||
|
JsonDocument d;d["payload"]["ts"]=nowMs();pingId=nextId();pingAt=pingSent=millis();serverReason="Ping sent; awaiting reply";request("Ping",pingId,d);updateHome();
|
||||||
|
}
|
||||||
|
static void updateHome(){
|
||||||
|
if(!statusLabel)return;
|
||||||
|
bool wifiOnline=WiFi.status()==WL_CONNECTED,serverOnline=authorized&&ws.isConnected();
|
||||||
|
String s="Wi-Fi: "+String(wifiOnline?"#28B463 ONLINE#":"#E74C3C OFFLINE#");
|
||||||
|
if(wifiOnline)s+=" ("+WiFi.SSID()+")";
|
||||||
|
s+="\nServer: "+String(serverOnline?"#28B463 ONLINE#":"#E74C3C OFFLINE#");
|
||||||
|
s+="\n"+serverReason;
|
||||||
|
s+="\nLast ping: "+String(lastPingAckAt?String((millis()-lastPingAckAt)/1000)+"s ago":"never");
|
||||||
|
s+="\nSD card: "+String(sdReady?"OK":"ERROR")+"\nNamespace: @"+ns;
|
||||||
|
s+="\nKey: "+String(keyReady?"SET":"NOT SET")+"\nIssued: "+String((unsigned long long)total);
|
||||||
|
s+="\nLast 5 hours: "+String(used())+"/10\nLast: "+lastLogin;
|
||||||
|
s+="\n"+String(serverOnline&&sdReady&&safeTime()?"READY":"NOT READY");
|
||||||
|
if(!lastError.isEmpty())s+="\n"+lastError;
|
||||||
|
if(powerReady&&power.isBatteryConnect())s+="\nBattery: "+String(power.getBatteryPercent())+"%";
|
||||||
|
lv_label_set_text(statusLabel,s.c_str());
|
||||||
|
}
|
||||||
|
static void home(){
|
||||||
|
baseScreen(HOME);title("SHiNE REGISTRAR 1.0");statusLabel=lv_label_create(lv_scr_act());
|
||||||
|
lv_obj_set_width(statusLabel,440);lv_label_set_long_mode(statusLabel,LV_LABEL_LONG_WRAP);lv_obj_set_pos(statusLabel,20,60);
|
||||||
|
lv_label_set_recolor(statusLabel,true);lv_obj_set_style_text_font(statusLabel,&lv_font_montserrat_16,0);
|
||||||
|
lv_obj_set_style_text_line_space(statusLabel,3,0);
|
||||||
|
auto b=button(lv_scr_act(),"SETTINGS",[](lv_event_t*){settings();});lv_obj_set_size(b,190,54);lv_obj_align(b,LV_ALIGN_BOTTOM_LEFT,20,-20);
|
||||||
|
b=button(lv_scr_act(),"PING",[](lv_event_t*){sendPingNow();});lv_obj_set_size(b,190,54);lv_obj_align(b,LV_ALIGN_BOTTOM_RIGHT,-20,-20);updateHome();
|
||||||
|
}
|
||||||
|
static void menuItem(lv_obj_t *parent,const char *label,int y,lv_event_cb_t cb){auto b=button(parent,label,cb);lv_obj_set_size(b,436,96);lv_obj_set_pos(b,22,y);lv_obj_set_style_bg_color(b,lv_color_hex(0x355C7D),0);}
|
||||||
|
static void openEditor(EditKind kind,const String &value){editKind=kind;editValue=value;uiMessage="";keyboardSymbols=false;keyboardShift=false;keyboardPage=0;drawScreen();}
|
||||||
|
static void settings(){screen=MENU;menuIndex=0;drawScreen();}
|
||||||
|
static void wifiOverview(){screen=WIFI_OVERVIEW;drawScreen();}
|
||||||
|
static void wifiScan(){
|
||||||
|
uiMessage="Scanning networks...";scanCount=0;
|
||||||
|
wifiScanning=false;wifiTrying=false;WiFi.scanDelete();WiFi.mode(WIFI_STA);int count=WiFi.scanNetworks();
|
||||||
|
for(int i=0;i<count&&scanCount<20;i++){String name=WiFi.SSID(i);if(name.isEmpty())continue;bool duplicate=false;for(int j=0;j<scanCount;j++)if(scanNames[j]==name)duplicate=true;if(!duplicate)scanNames[scanCount++]=name;}
|
||||||
|
WiFi.scanDelete();uiMessage=scanCount?String("Found ")+scanCount+" networks":"No networks found";drawScreen();
|
||||||
|
}
|
||||||
|
static void editorError(const String &error){uiMessage=error;if(editorHint)lv_label_set_text(editorHint,uiMessage.c_str());}
|
||||||
|
static void saveEditor(){
|
||||||
|
String value=lv_textarea_get_text(editorInput);
|
||||||
|
if(editKind==EDIT_WIFI){
|
||||||
|
if(selectedWifi.isEmpty()){editorError("Select a network first");return;}
|
||||||
|
wifiScanning=false;wifiTrying=false;WiFi.scanDelete();WiFi.disconnect(false,false);WiFi.begin(selectedWifi.c_str(),value.c_str());
|
||||||
|
uint32_t started=millis();while(WiFi.status()!=WL_CONNECTED&&millis()-started<12000)delay(100);
|
||||||
|
if(WiFi.status()!=WL_CONNECTED){WiFi.disconnect(false,false);editorError("Connection failed; check password");return;}
|
||||||
|
ssid=selectedWifi;wifiPass=value;rememberWifi(ssid,wifiPass);bool saved=prefs.putString("ssid",ssid)==ssid.length()&&prefs.putString("wifiPass",wifiPass)==wifiPass.length();bool profileSaved=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==ssid){String a="net"+String(i),b="pass"+String(i);profileSaved=prefs.getString(a.c_str(),"")==ssid&&prefs.getString(b.c_str(),"")==wifiPass;}if(!saved||!profileSaved||prefs.getString("ssid","")!=ssid||prefs.getString("wifiPass","")!=wifiPass){editorError("Wi-Fi connected but storage failed");return;}wifiTrying=false;wifiScanning=false;wifiScanAt=0;uiMessage="Connected: "+WiFi.localIP().toString();wifiOverview();return;
|
||||||
|
}
|
||||||
|
if(editKind==EDIT_URL){value.trim();String normalized=value.startsWith("wss://")?value:String("wss://")+value+"/ws";String previous=endpoint;endpoint=normalized;bool valid=parseEndpoint();endpoint=previous;parseEndpoint();if(!valid){editorError("Enter host, e.g. t2.shineup.me");return;}if(prefs.putString("endpoint",normalized)!=normalized.length()){editorError("Server storage failed");return;}endpoint=normalized;stopNetwork();uiMessage="Server address saved";settings();return;}
|
||||||
|
if(editKind==EDIT_NAMESPACE){if(!validNamespace(value)){editorError("Invalid namespace");return;}if(prefs.putString("namespace",value)!=value.length()){editorError("Namespace storage failed");return;}ns=value;stopNetwork();uiMessage="Namespace saved";settings();return;}
|
||||||
|
uint8_t newSeed[32]={},newOwner[32]={},newSecret[64]={};
|
||||||
|
if(!regkey::decode32(value.c_str(),newSeed)){editorError("Enter a 32-byte Base58 seed");return;}
|
||||||
|
if(crypto_sign_seed_keypair(newOwner,newSecret,newSeed)!=0){
|
||||||
|
sodium_memzero(newSeed,32);editorError("Key generation failed");return;
|
||||||
|
}
|
||||||
|
if(prefs.putBytes("seed",newSeed,32)!=32||prefs.getBytesLength("seed")!=32){
|
||||||
|
sodium_memzero(newSeed,32);sodium_memzero(newSecret,64);editorError("Key storage failed");return;
|
||||||
|
}
|
||||||
|
stopNetwork();memcpy(seed,newSeed,32);memcpy(secret,newSecret,64);memcpy(owner,newOwner,32);
|
||||||
|
sodium_memzero(newSeed,32);sodium_memzero(newSecret,64);prefs.remove("secretKey");prefs.remove("keyPassword");keyReady=true;
|
||||||
|
uiMessage="Registration key saved";settings();
|
||||||
|
}
|
||||||
|
static void keyCb(lv_event_t *e){const char *token=(const char*)lv_event_get_user_data(e);if(!token||!editorInput)return;String key=token;if(key=="<SAVE>"){saveEditor();return;}if(key=="<CANCEL>"){if(editKind==EDIT_WIFI)wifiOverview();else settings();return;}if(key=="<DEL>"){lv_textarea_del_char(editorInput);return;}if(key=="<CLR>"){lv_textarea_set_text(editorInput,"");return;}if(key=="<MODE>"){editValue=lv_textarea_get_text(editorInput);keyboardSymbols=!keyboardSymbols;keyboardPage=0;drawScreen();return;}if(key=="<SHIFT>"){editValue=lv_textarea_get_text(editorInput);keyboardShift=!keyboardShift;drawScreen();return;}if(key=="<PAGE>"){editValue=lv_textarea_get_text(editorInput);keyboardPage=1-keyboardPage;drawScreen();return;}if(key=="<SPACE>")key=" ";if(keyboardShift&&!keyboardSymbols)key.toUpperCase();lv_textarea_set_cursor_pos(editorInput,LV_TEXTAREA_CURSOR_LAST);lv_textarea_add_text(editorInput,key.c_str());}
|
||||||
|
static void keyButton(const char *label,const char *token,int x,int y,int w,int h){auto b=lv_btn_create(lv_scr_act());lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);lv_obj_set_style_bg_color(b,lv_color_hex(0x2A6F97),0);auto l=lv_label_create(b);lv_label_set_text(l,label);lv_obj_center(l);lv_obj_add_event_cb(b,keyCb,LV_EVENT_CLICKED,(void*)token);}
|
||||||
|
static void keyRow(const char *const *tokens,int count,int y){for(int i=0;i<count;i++){String label=tokens[i];if(label=="<SPACE>")label="SPACE";if(keyboardShift&&!keyboardSymbols)label.toUpperCase();keyButton(label.c_str(),tokens[i],20+i*92,y,84,62);}}
|
||||||
|
static void drawKeyboard(){
|
||||||
|
static const char *a0[]={"q","w","e","r","t"},*a1[]={"a","s","d","f","g"},*a2[]={"z","x","c","v","b"};
|
||||||
|
static const char *b0[]={"y","u","i","o","p"},*b1[]={"h","j","k","l"},*b2[]={"n","m",".","-"};
|
||||||
|
static const char *s0[]={"1","2","3","4","5"},*s1[]={"://","/",":","_","@"},*s2[]={".com",".net",".org",".me",".io"};
|
||||||
|
static const char *t0[]={"6","7","8","9","0"},*t1[]={"?","!","=","+","-"},*t2[]={"<SPACE>","#","~",":","/"};
|
||||||
|
if(!keyboardSymbols){if(!keyboardPage){keyRow(a0,5,120);keyRow(a1,5,188);keyRow(a2,5,256);}else{keyRow(b0,5,120);keyRow(b1,4,188);keyRow(b2,4,256);}}
|
||||||
|
else{if(!keyboardPage){keyRow(s0,5,120);keyRow(s1,5,188);keyRow(s2,5,256);}else{keyRow(t0,5,120);keyRow(t1,5,188);keyRow(t2,5,256);}}
|
||||||
|
keyButton(keyboardSymbols?"ABC":"123","<MODE>",20,328,84,62);keyButton(keyboardShift?"SHIFT*":"SHIFT","<SHIFT>",112,328,84,62);keyButton("DEL","<DEL>",204,328,76,62);keyButton("SAVE","<SAVE>",288,328,76,62);keyButton("CANCEL","<CANCEL>",372,328,88,62);
|
||||||
|
keyButton("OTHER KEYS", "<PAGE>",20,400,150,55);
|
||||||
|
editorHint=lv_label_create(lv_scr_act());lv_obj_set_width(editorHint,280);lv_obj_set_pos(editorHint,185,405);lv_label_set_text(editorHint,uiMessage.isEmpty()?"Page 1 / 2":uiMessage.c_str());
|
||||||
|
}
|
||||||
|
static void menuSelectCb(lv_event_t *e){
|
||||||
|
int item=(int)(intptr_t)lv_event_get_user_data(e);
|
||||||
|
if(item==0){screen=WIFI_OVERVIEW;drawScreen();}
|
||||||
|
else if(item==1){String display=endpoint;if(display.startsWith("wss://"))display.remove(0,6);if(display.endsWith("/ws"))display.remove(display.length()-3);screen=EDITOR;openEditor(EDIT_URL,display);}
|
||||||
|
else if(item==2){screen=EDITOR;openEditor(EDIT_NAMESPACE,ns);}
|
||||||
|
else if(item==3){screen=EDITOR;openEditor(EDIT_SECRET,keyReady?String(regkey::encode(seed,32).c_str()):String(""));}
|
||||||
|
else {screen=KEYS;drawScreen();}
|
||||||
|
}
|
||||||
|
static void wifiSelectCb(lv_event_t *e){
|
||||||
|
int i=(int)(intptr_t)lv_event_get_user_data(e);
|
||||||
|
if(i<0||i>=scanCount)return;
|
||||||
|
selectedWifi=scanNames[i];String saved;
|
||||||
|
for(int j=0;j<MAX_WIFI_PROFILES;j++)if(knownSsids[j]==selectedWifi)saved=knownPasswords[j];
|
||||||
|
screen=EDITOR;openEditor(EDIT_WIFI,saved);
|
||||||
|
}
|
||||||
|
static void drawScreen(){
|
||||||
|
if(screen==HOME){home();return;}
|
||||||
|
if(screen==MENU){
|
||||||
|
baseScreen(MENU);title("SETTINGS");message(uiMessage.isEmpty()?"Select an item":uiMessage,55);
|
||||||
|
const char *labels[]={"WI-FI","SERVER URL","NAMESPACE","SECRET KEY BASE58","VIEW KEYS"};
|
||||||
|
for(int i=0;i<2;i++){
|
||||||
|
int index=menuIndex+i;auto b=lv_btn_create(lv_scr_act());lv_obj_set_size(b,300,104);lv_obj_set_pos(b,20,115+i*122);lv_obj_set_style_bg_color(b,lv_color_hex(0x355C7D),0);
|
||||||
|
auto l=lv_label_create(b);lv_label_set_text(l,labels[index]);lv_obj_center(l);lv_obj_add_event_cb(b,menuSelectCb,LV_EVENT_CLICKED,(void*)(intptr_t)index);
|
||||||
|
}
|
||||||
|
auto up=button(lv_scr_act(),"UP",[](lv_event_t*){if(menuIndex>0){menuIndex--;drawScreen();}});lv_obj_set_size(up,115,96);lv_obj_set_pos(up,345,120);
|
||||||
|
auto down=button(lv_scr_act(),"DOWN",[](lv_event_t*){if(menuIndex<3){menuIndex++;drawScreen();}});lv_obj_set_size(down,115,96);lv_obj_set_pos(down,345,246);
|
||||||
|
message(String("Items ")+String(menuIndex+1)+"-"+String(menuIndex+2)+" of 5",365);
|
||||||
|
auto back=button(lv_scr_act(),"BACK",[](lv_event_t*){home();});lv_obj_set_size(back,200,60);lv_obj_align(back,LV_ALIGN_BOTTOM_MID,0,-8);return;
|
||||||
|
}
|
||||||
|
if(screen==WIFI_OVERVIEW){
|
||||||
|
baseScreen(WIFI_OVERVIEW);title("WI-FI");message(WiFi.status()==WL_CONNECTED?String("ONLINE: ")+WiFi.SSID():"OFFLINE",65);
|
||||||
|
int saved=0;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(!knownSsids[i].isEmpty())saved++;
|
||||||
|
message("Saved networks: "+String(saved),100);message(uiMessage,135);
|
||||||
|
auto b=button(lv_scr_act(),"SELECT NETWORK",[](lv_event_t*){screen=WIFI_SCAN;wifiScan();});lv_obj_set_size(b,436,68);lv_obj_set_pos(b,22,195);
|
||||||
|
b=button(lv_scr_act(),"BACK",[](lv_event_t*){settings();});lv_obj_set_size(b,200,65);lv_obj_align(b,LV_ALIGN_BOTTOM_MID,0,-25);return;
|
||||||
|
}
|
||||||
|
if(screen==WIFI_SCAN){
|
||||||
|
baseScreen(WIFI_SCAN);title("SELECT NETWORK");message(uiMessage,55);
|
||||||
|
auto list=lv_obj_create(lv_scr_act());lv_obj_set_pos(list,15,90);lv_obj_set_size(list,450,280);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);
|
||||||
|
for(int i=0;i<scanCount;i++){
|
||||||
|
auto b=lv_btn_create(list);lv_obj_set_width(b,LV_PCT(100));auto l=lv_label_create(b);lv_label_set_text(l,scanNames[i].c_str());lv_obj_center(l);
|
||||||
|
lv_obj_add_event_cb(b,wifiSelectCb,LV_EVENT_CLICKED,(void*)(intptr_t)i);
|
||||||
|
}
|
||||||
|
auto b=button(lv_scr_act(),"SCAN AGAIN",[](lv_event_t*){wifiScan();});lv_obj_set_size(b,210,65);lv_obj_set_pos(b,20,390);
|
||||||
|
b=button(lv_scr_act(),"BACK",[](lv_event_t*){wifiOverview();});lv_obj_set_size(b,210,65);lv_obj_set_pos(b,250,390);return;
|
||||||
|
}
|
||||||
|
if(screen==EDITOR){
|
||||||
|
baseScreen(EDITOR);title(editKind==EDIT_WIFI?"ENTER WI-FI PASSWORD":editKind==EDIT_URL?"SERVER URL":editKind==EDIT_NAMESPACE?"NAMESPACE":"SECRET KEY BASE58");
|
||||||
|
editorInput=lv_textarea_create(lv_scr_act());lv_obj_set_size(editorInput,436,58);lv_obj_set_pos(editorInput,22,48);lv_textarea_set_one_line(editorInput,true);
|
||||||
|
lv_textarea_set_max_length(editorInput,editKind==EDIT_URL?250:128);lv_textarea_set_password_mode(editorInput,false);
|
||||||
|
lv_textarea_set_text(editorInput,editValue.c_str());lv_textarea_set_cursor_pos(editorInput,LV_TEXTAREA_CURSOR_LAST);drawKeyboard();return;
|
||||||
|
}
|
||||||
|
if(screen==KEYS){
|
||||||
|
baseScreen(KEYS);title("REGISTRATION KEYS");auto panel=lv_obj_create(lv_scr_act());lv_obj_set_pos(panel,12,55);lv_obj_set_size(panel,456,340);
|
||||||
|
String pub=keyReady?String(regkey::encode(owner,32).c_str()):"Not set",priv=keyReady?String(regkey::encode(seed,32).c_str()):"Not set";
|
||||||
|
auto l=lv_label_create(panel);lv_obj_set_width(l,LV_PCT(100));lv_label_set_long_mode(l,LV_LABEL_LONG_WRAP);
|
||||||
|
lv_label_set_text(l,(String("Public key (Base58):\n")+pub+"\n\nSecret seed (Base58, 32 bytes):\n"+priv).c_str());
|
||||||
|
auto b=button(lv_scr_act(),"BACK",[](lv_event_t*){settings();});lv_obj_set_size(b,200,65);lv_obj_align(b,LV_ALIGN_BOTTOM_MID,0,-12);return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
void setup(){Serial.begin(115200);sodium_init();Wire.begin(15,14);powerReady=power.begin(Wire,AXP2101_SLAVE_ADDRESS,15,14);if(powerReady){power.disableIRQ(XPOWERS_AXP2101_ALL_IRQ);power.setChargeTargetVoltage(3);power.enableBattDetection();power.enableBattVoltageMeasure();}
|
||||||
|
gfx->begin();bus->writeC8D8(0x36,0xA0);gfx->setBrightness(180);gfx->fillScreen(0);touch.setPins(11,-1);touch.begin(Wire,CST92XX_SLAVE_ADDRESS,15,14);touch.setMaxCoordinates(480,480);touch.setSwapXY(true);touch.setMirrorXY(true,false);
|
||||||
|
lv_init();const uint32_t count=480*40;auto a=(lv_color_t*)heap_caps_malloc(count*sizeof(lv_color_t),MALLOC_CAP_DMA);auto b=(lv_color_t*)heap_caps_malloc(count*sizeof(lv_color_t),MALLOC_CAP_DMA);if(!a||!b)return;lv_disp_draw_buf_init(&drawBuf,a,b,count);static lv_disp_drv_t disp;lv_disp_drv_init(&disp);disp.hor_res=480;disp.ver_res=480;disp.flush_cb=flushDisplay;disp.draw_buf=&drawBuf;lv_disp_drv_register(&disp);static lv_indev_drv_t input;lv_indev_drv_init(&input);input.type=LV_INDEV_TYPE_POINTER;input.read_cb=readTouch;lv_indev_drv_register(&input);const esp_timer_create_args_t args={.callback=tick,.name="registrar_tick"};esp_timer_handle_t timer;esp_timer_create(&args,&timer);esp_timer_start_periodic(timer,2000);
|
||||||
|
#if defined(CONFIG_NVS_ENCRYPTION) && CONFIG_NVS_ENCRYPTION
|
||||||
|
secureStorage=esp_flash_encryption_enabled()&&esp_secure_boot_enabled();
|
||||||
|
#else
|
||||||
|
secureStorage=false;
|
||||||
|
#endif
|
||||||
|
if(!prefs.begin("shine-reg-v1",false)){home();lastError="NVS unavailable";uiReady=true;return;}ssid=prefs.getString("ssid","");wifiPass=prefs.getString("wifiPass","");endpoint=prefs.getString("endpoint","");ns=prefs.getString("namespace","free");paused=false;prefs.remove("paused");for(int i=0;i<MAX_WIFI_PROFILES;i++){String a="net"+String(i),b="pass"+String(i);knownSsids[i]=prefs.getString(a.c_str(),"");knownPasswords[i]=prefs.getString(b.c_str(),"");}if(!ssid.isEmpty()){bool found=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==ssid)found=true;if(!found){knownSsids[0]=ssid;knownPasswords[0]=wifiPass;}}
|
||||||
|
if(prefs.getBytesLength("seed")==32&&prefs.getBytes("seed",seed,32)==32){
|
||||||
|
keyReady=crypto_sign_seed_keypair(owner,secret,seed)==0;
|
||||||
|
}else if(prefs.getBytesLength("secretKey")==64&&prefs.getBytes("secretKey",secret,64)==64){
|
||||||
|
uint8_t checkSecret[64];memcpy(seed,secret,32);
|
||||||
|
keyReady=crypto_sign_seed_keypair(owner,checkSecret,seed)==0&&sodium_memcmp(secret,checkSecret,64)==0;
|
||||||
|
sodium_memzero(checkSecret,64);
|
||||||
|
}
|
||||||
|
gpio_reset_pin(GPIO_NUM_2);pinMode(1,INPUT_PULLUP);pinMode(3,INPUT_PULLUP);SD_MMC.setPins(2,1,3);sdReady=SD_MMC.begin("/sdcard",true)&&loadHistory();if(!sdReady&&lastError.isEmpty())lastError="SD history unavailable";
|
||||||
|
WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(true);configTime(0,0,"pool.ntp.org","time.cloudflare.com");home();uiReady=true;}
|
||||||
|
void loop(){if(!uiReady){delay(1000);return;}lv_timer_handler();manageNetwork();if(millis()-refreshAt>1000){refreshAt=millis();updateHome();}delay(5);}
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
/*
|
|
||||||
* ESPRESSIF MIT License
|
|
||||||
*
|
|
||||||
* Copyright (c) 2018 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
|
|
||||||
*
|
|
||||||
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
|
|
||||||
* it is free of charge, to any person obtaining a copy of this software and associated
|
|
||||||
* documentation files (the "Software"), to deal in the Software without restriction, including
|
|
||||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
|
|
||||||
* to do so, subject to the following conditions:
|
|
||||||
*
|
|
||||||
* The above copyright notice and this permission notice shall be included in all copies or
|
|
||||||
* substantial portions of the Software.
|
|
||||||
*
|
|
||||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
||||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
||||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
||||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
||||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef _AUDIO_HAL_H_
|
|
||||||
#define _AUDIO_HAL_H_
|
|
||||||
|
|
||||||
#define AUDIO_HAL_VOL_DEFAULT 60
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select media hal codec mode
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_CODEC_MODE_ENCODE = 1, /*!< select adc */
|
|
||||||
AUDIO_HAL_CODEC_MODE_DECODE, /*!< select dac */
|
|
||||||
AUDIO_HAL_CODEC_MODE_BOTH, /*!< select both adc and dac */
|
|
||||||
AUDIO_HAL_CODEC_MODE_LINE_IN, /*!< set adc channel */
|
|
||||||
} audio_hal_codec_mode_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select adc channel for input mic signal
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_ADC_INPUT_LINE1 = 0x00, /*!< mic input to adc channel 1 */
|
|
||||||
AUDIO_HAL_ADC_INPUT_LINE2, /*!< mic input to adc channel 2 */
|
|
||||||
AUDIO_HAL_ADC_INPUT_ALL, /*!< mic input to both channels of adc */
|
|
||||||
AUDIO_HAL_ADC_INPUT_DIFFERENCE, /*!< mic input to adc difference channel */
|
|
||||||
} audio_hal_adc_input_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select channel for dac output
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_DAC_OUTPUT_LINE1 = 0x00, /*!< dac output signal to channel 1 */
|
|
||||||
AUDIO_HAL_DAC_OUTPUT_LINE2, /*!< dac output signal to channel 2 */
|
|
||||||
AUDIO_HAL_DAC_OUTPUT_ALL, /*!< dac output signal to both channels */
|
|
||||||
} audio_hal_dac_output_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select operating mode i.e. start or stop for audio codec chip
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_CTRL_STOP = 0x00, /*!< set stop mode */
|
|
||||||
AUDIO_HAL_CTRL_START = 0x01, /*!< set start mode */
|
|
||||||
} audio_hal_ctrl_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select I2S interface operating mode i.e. master or slave for audio codec chip
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_MODE_SLAVE = 0x00, /*!< set slave mode */
|
|
||||||
AUDIO_HAL_MODE_MASTER = 0x01, /*!< set master mode */
|
|
||||||
} audio_hal_iface_mode_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select I2S interface samples per second
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_08K_SAMPLES, /*!< set to 8k samples per second */
|
|
||||||
AUDIO_HAL_11K_SAMPLES, /*!< set to 11.025k samples per second */
|
|
||||||
AUDIO_HAL_16K_SAMPLES, /*!< set to 16k samples in per second */
|
|
||||||
AUDIO_HAL_22K_SAMPLES, /*!< set to 22.050k samples per second */
|
|
||||||
AUDIO_HAL_24K_SAMPLES, /*!< set to 24k samples in per second */
|
|
||||||
AUDIO_HAL_32K_SAMPLES, /*!< set to 32k samples in per second */
|
|
||||||
AUDIO_HAL_44K_SAMPLES, /*!< set to 44.1k samples per second */
|
|
||||||
AUDIO_HAL_48K_SAMPLES, /*!< set to 48k samples per second */
|
|
||||||
} audio_hal_iface_samples_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select I2S interface number of bits per sample
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_BIT_LENGTH_16BITS = 1, /*!< set 16 bits per sample */
|
|
||||||
AUDIO_HAL_BIT_LENGTH_24BITS, /*!< set 24 bits per sample */
|
|
||||||
AUDIO_HAL_BIT_LENGTH_32BITS, /*!< set 32 bits per sample */
|
|
||||||
} audio_hal_iface_bits_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select I2S interface format for audio codec chip
|
|
||||||
*/
|
|
||||||
typedef enum {
|
|
||||||
AUDIO_HAL_I2S_NORMAL = 0, /*!< set normal I2S format */
|
|
||||||
AUDIO_HAL_I2S_LEFT, /*!< set all left format */
|
|
||||||
AUDIO_HAL_I2S_RIGHT, /*!< set all right format */
|
|
||||||
AUDIO_HAL_I2S_DSP, /*!< set dsp/pcm format */
|
|
||||||
} audio_hal_iface_format_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief I2s interface configuration for audio codec chip
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
audio_hal_iface_mode_t mode; /*!< audio codec chip mode */
|
|
||||||
audio_hal_iface_format_t fmt; /*!< I2S interface format */
|
|
||||||
audio_hal_iface_samples_t samples; /*!< I2S interface samples per second */
|
|
||||||
audio_hal_iface_bits_t bits; /*!< i2s interface number of bits per sample */
|
|
||||||
} audio_hal_codec_i2s_iface_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure media hal for initialization of audio codec chip
|
|
||||||
*/
|
|
||||||
typedef struct {
|
|
||||||
audio_hal_adc_input_t adc_input; /*!< set adc channel */
|
|
||||||
audio_hal_dac_output_t dac_output; /*!< set dac channel */
|
|
||||||
audio_hal_codec_mode_t codec_mode; /*!< select codec mode: adc, dac or both */
|
|
||||||
audio_hal_codec_i2s_iface_t i2s_iface; /*!< set I2S interface configuration */
|
|
||||||
} audio_hal_codec_config_t;
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif //__AUDIO_HAL_H__
|
|
||||||
@@ -1,549 +0,0 @@
|
|||||||
/*
|
|
||||||
* ESPRESSIF MIT License
|
|
||||||
*
|
|
||||||
* Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
|
|
||||||
*
|
|
||||||
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
|
|
||||||
* it is free of charge, to any person obtaining a copy of this software and associated
|
|
||||||
* documentation files (the "Software"), to deal in the Software without restriction, including
|
|
||||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
|
|
||||||
* to do so, subject to the following conditions:
|
|
||||||
*
|
|
||||||
* The above copyright notice and this permission notice shall be included in all copies or
|
|
||||||
* substantial portions of the Software.
|
|
||||||
*
|
|
||||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
||||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
||||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
||||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
||||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifdef ESP32
|
|
||||||
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <string.h>
|
|
||||||
#include "esp_log.h"
|
|
||||||
#include "es7210.h"
|
|
||||||
|
|
||||||
|
|
||||||
#define I2S_DSP_MODE_A 0
|
|
||||||
#define MCLK_DIV_FRE 256
|
|
||||||
|
|
||||||
|
|
||||||
#define ES7210_MCLK_SOURCE FROM_CLOCK_DOUBLE_PIN /* In master mode, 0 : MCLK from pad 1 : MCLK from clock doubler */
|
|
||||||
#define FROM_PAD_PIN 0
|
|
||||||
#define FROM_CLOCK_DOUBLE_PIN 1
|
|
||||||
|
|
||||||
|
|
||||||
static TwoWire *es7210wire;
|
|
||||||
static es7210_gain_value_t gain;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Clock coefficient structer
|
|
||||||
*/
|
|
||||||
struct _coeff_div_es7210 {
|
|
||||||
uint32_t mclk; /* mclk frequency */
|
|
||||||
uint32_t lrck; /* lrck */
|
|
||||||
uint8_t ss_ds;
|
|
||||||
uint8_t adc_div; /* adcclk divider */
|
|
||||||
uint8_t dll; /* dll_bypass */
|
|
||||||
uint8_t doubler; /* doubler enable */
|
|
||||||
uint8_t osr; /* adc osr */
|
|
||||||
uint8_t mclk_src; /* select mclk source */
|
|
||||||
uint32_t lrck_h; /* The high 4 bits of lrck */
|
|
||||||
uint32_t lrck_l; /* The low 8 bits of lrck */
|
|
||||||
};
|
|
||||||
|
|
||||||
static const char *TAG = "ES7210";
|
|
||||||
|
|
||||||
static es7210_input_mics_t mic_select = (es7210_input_mics_t)(ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2 | ES7210_INPUT_MIC3 | ES7210_INPUT_MIC4);
|
|
||||||
|
|
||||||
/* Codec hifi mclk clock divider coefficients
|
|
||||||
* MEMBER REG
|
|
||||||
* mclk: 0x03
|
|
||||||
* lrck: standard
|
|
||||||
* ss_ds: --
|
|
||||||
* adc_div: 0x02
|
|
||||||
* dll: 0x06
|
|
||||||
* doubler: 0x02
|
|
||||||
* osr: 0x07
|
|
||||||
* mclk_src: 0x03
|
|
||||||
* lrckh: 0x04
|
|
||||||
* lrckl: 0x05
|
|
||||||
*/
|
|
||||||
static const struct _coeff_div_es7210 coeff_div[] = {
|
|
||||||
//mclk lrck ss_ds adc_div dll doubler osr mclk_src lrckh lrckl
|
|
||||||
/* 8k */
|
|
||||||
{12288000, 8000 , 0x00, 0x03, 0x01, 0x00, 0x20, 0x00, 0x06, 0x00},
|
|
||||||
{16384000, 8000 , 0x00, 0x04, 0x01, 0x00, 0x20, 0x00, 0x08, 0x00},
|
|
||||||
{19200000, 8000 , 0x00, 0x1e, 0x00, 0x01, 0x28, 0x00, 0x09, 0x60},
|
|
||||||
{4096000, 8000 , 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00},
|
|
||||||
|
|
||||||
/* 11.025k */
|
|
||||||
{11289600, 11025, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00},
|
|
||||||
|
|
||||||
/* 12k */
|
|
||||||
{12288000, 12000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00},
|
|
||||||
{19200000, 12000, 0x00, 0x14, 0x00, 0x01, 0x28, 0x00, 0x06, 0x40},
|
|
||||||
|
|
||||||
/* 16k */
|
|
||||||
{4096000, 16000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00},
|
|
||||||
{19200000, 16000, 0x00, 0x0a, 0x00, 0x00, 0x1e, 0x00, 0x04, 0x80},
|
|
||||||
{16384000, 16000, 0x00, 0x02, 0x01, 0x00, 0x20, 0x00, 0x04, 0x00},
|
|
||||||
{12288000, 16000, 0x00, 0x03, 0x01, 0x01, 0x20, 0x00, 0x03, 0x00},
|
|
||||||
|
|
||||||
/* 22.05k */
|
|
||||||
{11289600, 22050, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00},
|
|
||||||
|
|
||||||
/* 24k */
|
|
||||||
{12288000, 24000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00},
|
|
||||||
{19200000, 24000, 0x00, 0x0a, 0x00, 0x01, 0x28, 0x00, 0x03, 0x20},
|
|
||||||
|
|
||||||
/* 32k */
|
|
||||||
{12288000, 32000, 0x00, 0x03, 0x00, 0x00, 0x20, 0x00, 0x01, 0x80},
|
|
||||||
{16384000, 32000, 0x00, 0x01, 0x01, 0x00, 0x20, 0x00, 0x02, 0x00},
|
|
||||||
{19200000, 32000, 0x00, 0x05, 0x00, 0x00, 0x1e, 0x00, 0x02, 0x58},
|
|
||||||
|
|
||||||
/* 44.1k */
|
|
||||||
{11289600, 44100, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00},
|
|
||||||
|
|
||||||
/* 48k */
|
|
||||||
{12288000, 48000, 0x00, 0x01, 0x01, 0x01, 0x20, 0x00, 0x01, 0x00},
|
|
||||||
{19200000, 48000, 0x00, 0x05, 0x00, 0x01, 0x28, 0x00, 0x01, 0x90},
|
|
||||||
|
|
||||||
/* 64k */
|
|
||||||
{16384000, 64000, 0x01, 0x01, 0x01, 0x00, 0x20, 0x00, 0x01, 0x00},
|
|
||||||
{19200000, 64000, 0x00, 0x05, 0x00, 0x01, 0x1e, 0x00, 0x01, 0x2c},
|
|
||||||
|
|
||||||
/* 88.2k */
|
|
||||||
{11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80},
|
|
||||||
|
|
||||||
/* 96k */
|
|
||||||
{12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x20, 0x00, 0x00, 0x80},
|
|
||||||
{19200000, 96000, 0x01, 0x05, 0x00, 0x01, 0x28, 0x00, 0x00, 0xc8},
|
|
||||||
};
|
|
||||||
|
|
||||||
static esp_err_t es7210_write_reg(uint8_t reg_addr, uint8_t data)
|
|
||||||
{
|
|
||||||
|
|
||||||
es7210wire->beginTransmission(ES7210_ADDR);
|
|
||||||
es7210wire->write(reg_addr);
|
|
||||||
es7210wire->write(data);
|
|
||||||
return es7210wire->endTransmission();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
static esp_err_t es7210_update_reg_bit(uint8_t reg_addr, uint8_t update_bits, uint8_t data)
|
|
||||||
{
|
|
||||||
uint8_t regv;
|
|
||||||
regv = es7210_read_reg(reg_addr);
|
|
||||||
regv = (regv & (~update_bits)) | (update_bits & data);
|
|
||||||
return es7210_write_reg(reg_addr, regv);
|
|
||||||
}
|
|
||||||
|
|
||||||
static int get_coeff(uint32_t mclk, uint32_t lrck)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) {
|
|
||||||
if (coeff_div[i].lrck == lrck && coeff_div[i].mclk == mclk)
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
int8_t get_es7210_mclk_src(void)
|
|
||||||
{
|
|
||||||
return ES7210_MCLK_SOURCE;
|
|
||||||
}
|
|
||||||
|
|
||||||
int es7210_read_reg(uint8_t reg_addr)
|
|
||||||
{
|
|
||||||
uint8_t data;
|
|
||||||
es7210wire->beginTransmission(ES7210_ADDR);
|
|
||||||
es7210wire->write(reg_addr);
|
|
||||||
es7210wire->endTransmission(false);
|
|
||||||
es7210wire->requestFrom(ES7210_ADDR, (size_t)1);
|
|
||||||
data = es7210wire->read();
|
|
||||||
return (int)data;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_config_sample(audio_hal_iface_samples_t sample)
|
|
||||||
{
|
|
||||||
uint8_t regv;
|
|
||||||
int coeff;
|
|
||||||
int sample_fre = 0;
|
|
||||||
int mclk_fre = 0;
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
switch (sample) {
|
|
||||||
case AUDIO_HAL_08K_SAMPLES:
|
|
||||||
sample_fre = 8000;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_11K_SAMPLES:
|
|
||||||
sample_fre = 11025;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_16K_SAMPLES:
|
|
||||||
sample_fre = 16000;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_22K_SAMPLES:
|
|
||||||
sample_fre = 22050;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_24K_SAMPLES:
|
|
||||||
sample_fre = 24000;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_32K_SAMPLES:
|
|
||||||
sample_fre = 32000;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_44K_SAMPLES:
|
|
||||||
sample_fre = 44100;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_48K_SAMPLES:
|
|
||||||
sample_fre = 48000;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ESP_LOGE(TAG, "Unable to configure sample rate %dHz", sample_fre);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
mclk_fre = sample_fre * MCLK_DIV_FRE;
|
|
||||||
coeff = get_coeff(mclk_fre, sample_fre);
|
|
||||||
if (coeff < 0) {
|
|
||||||
ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_fre, mclk_fre);
|
|
||||||
return ESP_FAIL;
|
|
||||||
}
|
|
||||||
/* Set clock parammeters */
|
|
||||||
if (coeff >= 0) {
|
|
||||||
/* Set adc_div & doubler & dll */
|
|
||||||
regv = es7210_read_reg(ES7210_MAINCLK_REG02) & 0x00;
|
|
||||||
regv |= coeff_div[coeff].adc_div;
|
|
||||||
regv |= coeff_div[coeff].doubler << 6;
|
|
||||||
regv |= coeff_div[coeff].dll << 7;
|
|
||||||
ret |= es7210_write_reg(ES7210_MAINCLK_REG02, regv);
|
|
||||||
/* Set osr */
|
|
||||||
regv = coeff_div[coeff].osr;
|
|
||||||
ret |= es7210_write_reg(ES7210_OSR_REG07, regv);
|
|
||||||
/* Set lrck */
|
|
||||||
regv = coeff_div[coeff].lrck_h;
|
|
||||||
ret |= es7210_write_reg(ES7210_LRCK_DIVH_REG04, regv);
|
|
||||||
regv = coeff_div[coeff].lrck_l;
|
|
||||||
ret |= es7210_write_reg(ES7210_LRCK_DIVL_REG05, regv);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_mic_select(es7210_input_mics_t mic)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
mic_select = mic;
|
|
||||||
if (mic_select & (ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2 | ES7210_INPUT_MIC3 | ES7210_INPUT_MIC4)) {
|
|
||||||
for (int i = 0; i < 4; i++) {
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43 + i, 0x10, 0x00);
|
|
||||||
}
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff);
|
|
||||||
if (mic_select & ES7210_INPUT_MIC1) {
|
|
||||||
ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC1");
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00);
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x10, 0x10);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC2) {
|
|
||||||
ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC2");
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x0b, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B, 0x00);
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x10, 0x10);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC3) {
|
|
||||||
ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC3");
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00);
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x10, 0x10);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC4) {
|
|
||||||
ESP_LOGI(TAG, "Enable ES7210_INPUT_MIC4");
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_CLOCK_OFF_REG01, 0x15, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0x00);
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x10, 0x10);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
ESP_LOGE(TAG, "Microphone selection error");
|
|
||||||
return ESP_FAIL;
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_init(TwoWire *tw, audio_hal_codec_config_t *codec_cfg)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
|
|
||||||
es7210wire = tw;
|
|
||||||
|
|
||||||
ret |= es7210_write_reg(ES7210_RESET_REG00, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_RESET_REG00, 0x41);
|
|
||||||
ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x1f);
|
|
||||||
ret |= es7210_write_reg(ES7210_TIME_CONTROL0_REG09, 0x30); /* Set chip state cycle */
|
|
||||||
ret |= es7210_write_reg(ES7210_TIME_CONTROL1_REG0A, 0x30); /* Set power on state cycle */
|
|
||||||
// ret |= es7210_write_reg(ES7210_ADC12_HPF2_REG23, 0x2a); /* Quick setup */
|
|
||||||
// ret |= es7210_write_reg(ES7210_ADC12_HPF1_REG22, 0x0a);
|
|
||||||
// ret |= es7210_write_reg(ES7210_ADC34_HPF2_REG20, 0x0a);
|
|
||||||
// ret |= es7210_write_reg(ES7210_ADC34_HPF1_REG21, 0x2a);
|
|
||||||
/* Set master/slave audio interface */
|
|
||||||
audio_hal_codec_i2s_iface_t *i2s_cfg = & (codec_cfg->i2s_iface);
|
|
||||||
switch (i2s_cfg->mode) {
|
|
||||||
case AUDIO_HAL_MODE_MASTER: /* MASTER MODE */
|
|
||||||
ESP_LOGI(TAG, "ES7210 in Master mode");
|
|
||||||
// ret |= es7210_update_reg_bit(ES7210_MODE_CONFIG_REG08, 0x01, 0x01);
|
|
||||||
ret |= es7210_write_reg(ES7210_MODE_CONFIG_REG08, 0x20);
|
|
||||||
/* Select clock source for internal mclk */
|
|
||||||
switch (get_es7210_mclk_src()) {
|
|
||||||
case FROM_PAD_PIN:
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00);
|
|
||||||
break;
|
|
||||||
case FROM_CLOCK_DOUBLE_PIN:
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x80);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MASTER_CLK_REG03, 0x80, 0x00);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_MODE_SLAVE: /* SLAVE MODE */
|
|
||||||
ESP_LOGI(TAG, "ES7210 in Slave mode");
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0xC3); /* Select power off analog, vdda = 3.3V, close vx20ff, VMID select 5KΩ start */
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC12_BIAS_REG41, 0x70); /* Select 2.87v */
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC34_BIAS_REG42, 0x70); /* Select 2.87v */
|
|
||||||
ret |= es7210_write_reg(ES7210_OSR_REG07, 0x20);
|
|
||||||
ret |= es7210_write_reg(ES7210_MAINCLK_REG02, 0xc1); /* Set the frequency division coefficient and use dll except clock doubler, and need to set 0xc1 to clear the state */
|
|
||||||
ret |= es7210_config_sample(i2s_cfg->samples);
|
|
||||||
ret |= es7210_mic_select(mic_select);
|
|
||||||
ret |= es7210_adc_set_gain_all(GAIN_0DB);
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_deinit()
|
|
||||||
{
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_config_fmt(audio_hal_iface_format_t fmt)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
uint8_t adc_iface = 0;
|
|
||||||
adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11);
|
|
||||||
adc_iface &= 0xfc;
|
|
||||||
switch (fmt) {
|
|
||||||
case AUDIO_HAL_I2S_NORMAL:
|
|
||||||
ESP_LOGD(TAG, "ES7210 in I2S Format");
|
|
||||||
adc_iface |= 0x00;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_I2S_LEFT:
|
|
||||||
case AUDIO_HAL_I2S_RIGHT:
|
|
||||||
ESP_LOGD(TAG, "ES7210 in LJ Format");
|
|
||||||
adc_iface |= 0x01;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_I2S_DSP:
|
|
||||||
if (I2S_DSP_MODE_A) {
|
|
||||||
ESP_LOGD(TAG, "ES7210 in DSP-A Format");
|
|
||||||
adc_iface |= 0x03;
|
|
||||||
} else {
|
|
||||||
ESP_LOGD(TAG, "ES7210 in DSP-B Format");
|
|
||||||
adc_iface |= 0x13;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
adc_iface &= 0xfc;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface);
|
|
||||||
/* Force ADC1/2 output to SDOUT1 and ADC3/4 output to SDOUT2 */
|
|
||||||
ret |= es7210_write_reg(ES7210_SDP_INTERFACE2_REG12, 0x00);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_set_bits(audio_hal_iface_bits_t bits)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
uint8_t adc_iface = 0;
|
|
||||||
adc_iface = es7210_read_reg(ES7210_SDP_INTERFACE1_REG11);
|
|
||||||
adc_iface &= 0x1f;
|
|
||||||
switch (bits) {
|
|
||||||
case AUDIO_HAL_BIT_LENGTH_16BITS:
|
|
||||||
adc_iface |= 0x60;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_BIT_LENGTH_24BITS:
|
|
||||||
adc_iface |= 0x00;
|
|
||||||
break;
|
|
||||||
case AUDIO_HAL_BIT_LENGTH_32BITS:
|
|
||||||
adc_iface |= 0x80;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
adc_iface |= 0x60;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
ret |= es7210_write_reg(ES7210_SDP_INTERFACE1_REG11, adc_iface);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
ret |= es7210_set_bits(iface->bits);
|
|
||||||
ret |= es7210_config_fmt(iface->fmt);
|
|
||||||
ret |= es7210_config_sample(iface->samples);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_start(uint8_t clock_reg_value)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, clock_reg_value);
|
|
||||||
ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x00);
|
|
||||||
// ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0x40);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0x00);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0x00);
|
|
||||||
ret |= es7210_mic_select(mic_select);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_stop(void)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC1_POWER_REG47, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC2_POWER_REG48, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC3_POWER_REG49, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC4_POWER_REG4A, 0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC12_POWER_REG4B,0xff);
|
|
||||||
ret |= es7210_write_reg(ES7210_MIC34_POWER_REG4C, 0xff);
|
|
||||||
// ret |= es7210_write_reg(ES7210_ANALOG_REG40, 0xc0);
|
|
||||||
ret |= es7210_write_reg(ES7210_CLOCK_OFF_REG01, 0x7f);
|
|
||||||
ret |= es7210_write_reg(ES7210_POWER_DOWN_REG06, 0x07);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state)
|
|
||||||
{
|
|
||||||
static uint8_t regv;
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
// ESP_LOGW(TAG, "ES7210 only supports ADC mode");
|
|
||||||
ret = es7210_read_reg(ES7210_CLOCK_OFF_REG01);
|
|
||||||
if ((ret != 0x7f) && (ret != 0xff)) {
|
|
||||||
regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01);
|
|
||||||
}
|
|
||||||
if (ctrl_state == AUDIO_HAL_CTRL_START) {
|
|
||||||
ESP_LOGI(TAG, "The ES7210_CLOCK_OFF_REG01 value before stop is %x",regv);
|
|
||||||
ret |= es7210_start(regv);
|
|
||||||
} else {
|
|
||||||
ESP_LOGW(TAG, "The codec is about to stop");
|
|
||||||
regv = es7210_read_reg(ES7210_CLOCK_OFF_REG01);
|
|
||||||
ret |= es7210_stop();
|
|
||||||
}
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_set_gain(es7210_input_mics_t mic_mask, es7210_gain_value_t gain)
|
|
||||||
{
|
|
||||||
esp_err_t ret_val = ESP_OK;
|
|
||||||
|
|
||||||
if (gain < GAIN_0DB) {
|
|
||||||
gain = GAIN_0DB;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (gain > GAIN_37_5DB) {
|
|
||||||
gain = GAIN_37_5DB;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mic_mask & ES7210_INPUT_MIC1) {
|
|
||||||
ret_val |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_mask & ES7210_INPUT_MIC2) {
|
|
||||||
ret_val |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_mask & ES7210_INPUT_MIC3) {
|
|
||||||
ret_val |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_mask & ES7210_INPUT_MIC4) {
|
|
||||||
ret_val |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x0f, gain);
|
|
||||||
}
|
|
||||||
|
|
||||||
return ret_val;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_set_gain_all(es7210_gain_value_t gain)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
uint32_t max_gain_vaule = 14;
|
|
||||||
if (gain < 0) {
|
|
||||||
gain = (es7210_gain_value_t) 0;
|
|
||||||
} else if (gain > max_gain_vaule) {
|
|
||||||
gain = (es7210_gain_value_t) max_gain_vaule;
|
|
||||||
}
|
|
||||||
ESP_LOGD(TAG, "SET: gain:%d", gain);
|
|
||||||
if (mic_select & ES7210_INPUT_MIC1) {
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC1_GAIN_REG43, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC2) {
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC2_GAIN_REG44, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC3) {
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC3_GAIN_REG45, 0x0f, gain);
|
|
||||||
}
|
|
||||||
if (mic_select & ES7210_INPUT_MIC4) {
|
|
||||||
ret |= es7210_update_reg_bit(ES7210_MIC4_GAIN_REG46, 0x0f, gain);
|
|
||||||
}
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_get_gain(es7210_input_mics_t mic_mask, es7210_gain_value_t *gain)
|
|
||||||
{
|
|
||||||
int regv = 0;
|
|
||||||
uint8_t gain_value;
|
|
||||||
if (mic_mask & ES7210_INPUT_MIC1) {
|
|
||||||
regv = es7210_read_reg(ES7210_MIC1_GAIN_REG43);
|
|
||||||
} else if (mic_mask & ES7210_INPUT_MIC2) {
|
|
||||||
regv = es7210_read_reg(ES7210_MIC2_GAIN_REG44);
|
|
||||||
} else if (mic_mask & ES7210_INPUT_MIC3) {
|
|
||||||
regv = es7210_read_reg(ES7210_MIC3_GAIN_REG45);
|
|
||||||
} else if (mic_mask & ES7210_INPUT_MIC4) {
|
|
||||||
regv = es7210_read_reg(ES7210_MIC4_GAIN_REG46);
|
|
||||||
} else {
|
|
||||||
ESP_LOGE(TAG, "No MIC selected");
|
|
||||||
return ESP_FAIL;
|
|
||||||
}
|
|
||||||
if (regv == ESP_FAIL) {
|
|
||||||
return regv;
|
|
||||||
}
|
|
||||||
gain_value = (regv & 0x0f); /* Retain the last four bits for gain */
|
|
||||||
*gain = (es7210_gain_value_t) gain_value;
|
|
||||||
ESP_LOGI(TAG, "GET: gain_value:%d", gain_value);
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_adc_set_volume(int volume)
|
|
||||||
{
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
ESP_LOGD(TAG, "ADC can adjust gain");
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es7210_set_mute(bool enable)
|
|
||||||
{
|
|
||||||
ESP_LOGD(TAG, "ES7210 SetMute :%d", enable);
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
void es7210_read_all(void)
|
|
||||||
{
|
|
||||||
for (int i = 0; i <= 0x4E; i++) {
|
|
||||||
uint8_t reg = es7210_read_reg(i);
|
|
||||||
ets_printf("REG:%02x, %02x\n", reg, i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,260 +0,0 @@
|
|||||||
/*
|
|
||||||
* ESPRESSIF MIT License
|
|
||||||
*
|
|
||||||
* Copyright (c) 2021 <ESPRESSIF SYSTEMS (SHANGHAI) CO., LTD>
|
|
||||||
*
|
|
||||||
* Permission is hereby granted for use on all ESPRESSIF SYSTEMS products, in which case,
|
|
||||||
* it is free of charge, to any person obtaining a copy of this software and associated
|
|
||||||
* documentation files (the "Software"), to deal in the Software without restriction, including
|
|
||||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
||||||
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished
|
|
||||||
* to do so, subject to the following conditions:
|
|
||||||
*
|
|
||||||
* The above copyright notice and this permission notice shall be included in all copies or
|
|
||||||
* substantial portions of the Software.
|
|
||||||
*
|
|
||||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
||||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
||||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
||||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
||||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef _ES7210_H
|
|
||||||
#define _ES7210_H
|
|
||||||
|
|
||||||
#include "audio_hal.h"
|
|
||||||
#include <Wire.h>
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ES7210_AD1_AD0_00 = 0x40,
|
|
||||||
ES7210_AD1_AD0_01 = 0x41,
|
|
||||||
ES7210_AD1_AD0_10 = 0x42,
|
|
||||||
ES7210_AD1_AD0_11 = 0x43,
|
|
||||||
} es7210_address_t;
|
|
||||||
|
|
||||||
/* ES7210 address*/
|
|
||||||
#define ES7210_ADDR ES7210_AD1_AD0_00
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define ES7210_RESET_REG00 0x00 /* Reset control */
|
|
||||||
#define ES7210_CLOCK_OFF_REG01 0x01 /* Used to turn off the ADC clock */
|
|
||||||
#define ES7210_MAINCLK_REG02 0x02 /* Set ADC clock frequency division */
|
|
||||||
#define ES7210_MASTER_CLK_REG03 0x03 /* MCLK source $ SCLK division */
|
|
||||||
#define ES7210_LRCK_DIVH_REG04 0x04 /* lrck_divh */
|
|
||||||
#define ES7210_LRCK_DIVL_REG05 0x05 /* lrck_divl */
|
|
||||||
#define ES7210_POWER_DOWN_REG06 0x06 /* power down */
|
|
||||||
#define ES7210_OSR_REG07 0x07
|
|
||||||
#define ES7210_MODE_CONFIG_REG08 0x08 /* Set master/slave & channels */
|
|
||||||
#define ES7210_TIME_CONTROL0_REG09 0x09 /* Set Chip intial state period*/
|
|
||||||
#define ES7210_TIME_CONTROL1_REG0A 0x0A /* Set Power up state period */
|
|
||||||
#define ES7210_SDP_INTERFACE1_REG11 0x11 /* Set sample & fmt */
|
|
||||||
#define ES7210_SDP_INTERFACE2_REG12 0x12 /* Pins state */
|
|
||||||
#define ES7210_ADC_AUTOMUTE_REG13 0x13 /* Set mute */
|
|
||||||
#define ES7210_ADC34_MUTERANGE_REG14 0x14 /* Set mute range */
|
|
||||||
#define ES7210_ADC34_HPF2_REG20 0x20 /* HPF */
|
|
||||||
#define ES7210_ADC34_HPF1_REG21 0x21
|
|
||||||
#define ES7210_ADC12_HPF1_REG22 0x22
|
|
||||||
#define ES7210_ADC12_HPF2_REG23 0x23
|
|
||||||
#define ES7210_ANALOG_REG40 0x40 /* ANALOG Power */
|
|
||||||
#define ES7210_MIC12_BIAS_REG41 0x41
|
|
||||||
#define ES7210_MIC34_BIAS_REG42 0x42
|
|
||||||
#define ES7210_MIC1_GAIN_REG43 0x43
|
|
||||||
#define ES7210_MIC2_GAIN_REG44 0x44
|
|
||||||
#define ES7210_MIC3_GAIN_REG45 0x45
|
|
||||||
#define ES7210_MIC4_GAIN_REG46 0x46
|
|
||||||
#define ES7210_MIC1_POWER_REG47 0x47
|
|
||||||
#define ES7210_MIC2_POWER_REG48 0x48
|
|
||||||
#define ES7210_MIC3_POWER_REG49 0x49
|
|
||||||
#define ES7210_MIC4_POWER_REG4A 0x4A
|
|
||||||
#define ES7210_MIC12_POWER_REG4B 0x4B /* MICBias & ADC & PGA Power */
|
|
||||||
#define ES7210_MIC34_POWER_REG4C 0x4C
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ES7210_INPUT_MIC1 = 0x01,
|
|
||||||
ES7210_INPUT_MIC2 = 0x02,
|
|
||||||
ES7210_INPUT_MIC3 = 0x04,
|
|
||||||
ES7210_INPUT_MIC4 = 0x08
|
|
||||||
} es7210_input_mics_t;
|
|
||||||
|
|
||||||
typedef enum gain_value{
|
|
||||||
GAIN_0DB = 0,
|
|
||||||
GAIN_3DB,
|
|
||||||
GAIN_6DB,
|
|
||||||
GAIN_9DB,
|
|
||||||
GAIN_12DB,
|
|
||||||
GAIN_15DB,
|
|
||||||
GAIN_18DB,
|
|
||||||
GAIN_21DB,
|
|
||||||
GAIN_24DB,
|
|
||||||
GAIN_27DB,
|
|
||||||
GAIN_30DB,
|
|
||||||
GAIN_33DB,
|
|
||||||
GAIN_34_5DB,
|
|
||||||
GAIN_36DB,
|
|
||||||
GAIN_37_5DB,
|
|
||||||
} es7210_gain_value_t;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* @brief Initialize ES7210 ADC chip
|
|
||||||
*
|
|
||||||
* @param[in] codec_cfg: configuration of ES7210
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
* - ESP_FAIL
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_init(TwoWire *tw, audio_hal_codec_config_t *codec_cfg);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Deinitialize ES7210 ADC chip
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
* - ESP_FAIL
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_deinit();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure ES7210 ADC mode and I2S interface
|
|
||||||
*
|
|
||||||
* @param[in] mode: codec mode
|
|
||||||
* @param[in] iface: I2S config
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_FAIL Parameter error
|
|
||||||
* - ESP_OK Success
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_config_i2s(audio_hal_codec_mode_t mode, audio_hal_codec_i2s_iface_t *iface);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Control ES7210 ADC chip
|
|
||||||
*
|
|
||||||
* @param[in] mode: codec mode
|
|
||||||
* @param[in] ctrl_state: start or stop progress
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_FAIL Parameter error
|
|
||||||
* - ESP_OK Success
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_ctrl_state(audio_hal_codec_mode_t mode, audio_hal_ctrl_t ctrl_state);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set gain of given mask
|
|
||||||
*
|
|
||||||
* @param[in] mic_mask Mask of MIC channel
|
|
||||||
*
|
|
||||||
* @param[in] gain: gain
|
|
||||||
*
|
|
||||||
* gain : value
|
|
||||||
* GAIN_0DB : 1
|
|
||||||
* GAIN_3DB : 2
|
|
||||||
* GAIN_6DB : 3
|
|
||||||
* ·
|
|
||||||
* ·
|
|
||||||
* ·
|
|
||||||
* GAIN_30DB : 10
|
|
||||||
* GAIN_33DB : 11
|
|
||||||
* GAIN_34_5DB : 12
|
|
||||||
* GAIN_36DB : 13
|
|
||||||
* GAIN_37_5DB : 14
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
* - ESP_FAIL
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_set_gain(es7210_input_mics_t mic_mask, es7210_gain_value_t gain);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set gain (Note: the enabled microphone sets the same gain)
|
|
||||||
*
|
|
||||||
* @param[in] gain: gain
|
|
||||||
*
|
|
||||||
* gain : value
|
|
||||||
* GAIN_0DB : 1
|
|
||||||
* GAIN_3DB : 2
|
|
||||||
* GAIN_6DB : 3
|
|
||||||
* ·
|
|
||||||
* ·
|
|
||||||
* ·
|
|
||||||
* GAIN_30DB : 10
|
|
||||||
* GAIN_33DB : 11
|
|
||||||
* GAIN_34_5DB : 12
|
|
||||||
* GAIN_36DB : 13
|
|
||||||
* GAIN_37_5DB : 14
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
* - ESP_FAIL
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_set_gain_all(es7210_gain_value_t gain);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Get MIC gain
|
|
||||||
*
|
|
||||||
* @param mic_mask Selected MIC
|
|
||||||
* @param gain Pointer to `es7210_gain_value_t`
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
* - ESP_FAIL
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_get_gain(es7210_input_mics_t mic_mask, es7210_gain_value_t *gain);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set volume
|
|
||||||
*
|
|
||||||
* @param[in] volume: volume
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_adc_set_volume(int volume);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set ES7210 ADC mute status
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_FAIL
|
|
||||||
* - ESP_OK
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_set_mute(bool enable);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Select ES7210 mic
|
|
||||||
*
|
|
||||||
* @param[in] mic: mics
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_FAIL
|
|
||||||
* - ESP_OK
|
|
||||||
*/
|
|
||||||
esp_err_t es7210_mic_select(es7210_input_mics_t mic);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Read regs of ES7210
|
|
||||||
*
|
|
||||||
* @param[in] reg_addr: reg_addr
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_FAIL
|
|
||||||
* - ESP_OK
|
|
||||||
*/
|
|
||||||
int es7210_read_reg(uint8_t reg_addr);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Read all regs of ES7210
|
|
||||||
*/
|
|
||||||
void es7210_read_all(void);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#endif /* _ES7210_H_ */
|
|
||||||
@@ -1,443 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: Apache-2.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <string.h>
|
|
||||||
#include "es8311.h"
|
|
||||||
#include "driver/gpio.h"
|
|
||||||
#include "esp_log.h"
|
|
||||||
#include "esp_err.h"
|
|
||||||
#include "esp_check.h"
|
|
||||||
#include "es8311_reg.h"
|
|
||||||
#include "esp32-hal-i2c.h"
|
|
||||||
|
|
||||||
|
|
||||||
typedef struct {
|
|
||||||
unsigned int port;
|
|
||||||
uint16_t dev_addr;
|
|
||||||
} es8311_dev_t;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Clock coefficient structure
|
|
||||||
*/
|
|
||||||
struct _coeff_div {
|
|
||||||
uint32_t mclk; /* mclk frequency */
|
|
||||||
uint32_t rate; /* sample rate */
|
|
||||||
uint8_t pre_div; /* the pre divider with range from 1 to 8 */
|
|
||||||
uint8_t pre_multi; /* the pre multiplier with 0: 1x, 1: 2x, 2: 4x, 3: 8x selection */
|
|
||||||
uint8_t adc_div; /* adcclk divider */
|
|
||||||
uint8_t dac_div; /* dacclk divider */
|
|
||||||
uint8_t fs_mode; /* double speed or single speed, =0, ss, =1, ds */
|
|
||||||
uint8_t lrck_h; /* adclrck divider and daclrck divider */
|
|
||||||
uint8_t lrck_l;
|
|
||||||
uint8_t bclk_div; /* sclk divider */
|
|
||||||
uint8_t adc_osr; /* adc osr */
|
|
||||||
uint8_t dac_osr; /* dac osr */
|
|
||||||
};
|
|
||||||
|
|
||||||
/* codec hifi mclk clock divider coefficients */
|
|
||||||
static const struct _coeff_div coeff_div[] = {
|
|
||||||
/*!<mclk rate pre_div mult adc_div dac_div fs_mode lrch lrcl bckdiv osr */
|
|
||||||
/* 8k */
|
|
||||||
{12288000, 8000, 0x06, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 8000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x05, 0xff, 0x18, 0x10, 0x10},
|
|
||||||
{16384000, 8000, 0x08, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{8192000, 8000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 8000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{4096000, 8000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2048000, 8000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 8000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1024000, 8000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 11.025k */
|
|
||||||
{11289600, 11025, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{5644800, 11025, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2822400, 11025, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1411200, 11025, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 12k */
|
|
||||||
{12288000, 12000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 12000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 12000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 12000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 16k */
|
|
||||||
{12288000, 16000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 16000, 0x03, 0x01, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
|
|
||||||
{16384000, 16000, 0x04, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{8192000, 16000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 16000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{4096000, 16000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 16000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2048000, 16000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 16000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1024000, 16000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 22.05k */
|
|
||||||
{11289600, 22050, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{5644800, 22050, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2822400, 22050, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1411200, 22050, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{705600, 22050, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 24k */
|
|
||||||
{12288000, 24000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 24000, 0x03, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 24000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 24000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 24000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 32k */
|
|
||||||
{12288000, 32000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 32000, 0x03, 0x02, 0x03, 0x03, 0x00, 0x02, 0xff, 0x0c, 0x10, 0x10},
|
|
||||||
{16384000, 32000, 0x02, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{8192000, 32000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 32000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{4096000, 32000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 32000, 0x03, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2048000, 32000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 32000, 0x03, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
|
|
||||||
{1024000, 32000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 44.1k */
|
|
||||||
{11289600, 44100, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{5644800, 44100, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2822400, 44100, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1411200, 44100, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 48k */
|
|
||||||
{12288000, 48000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 48000, 0x03, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 48000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 48000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 48000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 64k */
|
|
||||||
{12288000, 64000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 64000, 0x03, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
|
|
||||||
{16384000, 64000, 0x01, 0x00, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{8192000, 64000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 64000, 0x01, 0x02, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
|
|
||||||
{4096000, 64000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 64000, 0x01, 0x03, 0x03, 0x03, 0x01, 0x01, 0x7f, 0x06, 0x10, 0x10},
|
|
||||||
{2048000, 64000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0xbf, 0x03, 0x18, 0x18},
|
|
||||||
{1024000, 64000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 88.2k */
|
|
||||||
{11289600, 88200, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{5644800, 88200, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{2822400, 88200, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1411200, 88200, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
|
|
||||||
|
|
||||||
/* 96k */
|
|
||||||
{12288000, 96000, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{18432000, 96000, 0x03, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{6144000, 96000, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{3072000, 96000, 0x01, 0x03, 0x01, 0x01, 0x00, 0x00, 0xff, 0x04, 0x10, 0x10},
|
|
||||||
{1536000, 96000, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00, 0x7f, 0x02, 0x10, 0x10},
|
|
||||||
};
|
|
||||||
|
|
||||||
static const char *TAG = "ES8311";
|
|
||||||
|
|
||||||
static inline esp_err_t es8311_write_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t data)
|
|
||||||
{
|
|
||||||
es8311_dev_t *es = (es8311_dev_t *) dev;
|
|
||||||
const uint8_t write_buf[2] = {reg_addr, data};
|
|
||||||
return i2cWrite(es->port, es->dev_addr, write_buf, sizeof(write_buf), 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
static inline esp_err_t es8311_read_reg(es8311_handle_t dev, uint8_t reg_addr, uint8_t *reg_value)
|
|
||||||
{
|
|
||||||
es8311_dev_t *es = (es8311_dev_t *) dev;
|
|
||||||
size_t readCount = 0;
|
|
||||||
return i2cWriteReadNonStop(es->port, es->dev_addr, ®_addr, 1, reg_value, 1, 1000, &readCount);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* look for the coefficient in coeff_div[] table
|
|
||||||
*/
|
|
||||||
static int get_coeff(uint32_t mclk, uint32_t rate)
|
|
||||||
{
|
|
||||||
for (int i = 0; i < (sizeof(coeff_div) / sizeof(coeff_div[0])); i++) {
|
|
||||||
if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) {
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency)
|
|
||||||
{
|
|
||||||
uint8_t regv;
|
|
||||||
|
|
||||||
/* Get clock coefficients from coefficient table */
|
|
||||||
int coeff = get_coeff(mclk_frequency, sample_frequency);
|
|
||||||
|
|
||||||
if (coeff < 0) {
|
|
||||||
ESP_LOGE(TAG, "Unable to configure sample rate %dHz with %dHz MCLK", sample_frequency, mclk_frequency);
|
|
||||||
return ESP_ERR_INVALID_ARG;
|
|
||||||
}
|
|
||||||
|
|
||||||
const struct _coeff_div *const selected_coeff = &coeff_div[coeff];
|
|
||||||
|
|
||||||
/* register 0x02 */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG02, ®v), TAG, "I2C read/write error");
|
|
||||||
regv &= 0x07;
|
|
||||||
regv |= (selected_coeff->pre_div - 1) << 5;
|
|
||||||
regv |= selected_coeff->pre_multi << 3;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG02, regv), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x03 */
|
|
||||||
const uint8_t reg03 = (selected_coeff->fs_mode << 6) | selected_coeff->adc_osr;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG03, reg03), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x04 */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG04, selected_coeff->dac_osr), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x05 */
|
|
||||||
const uint8_t reg05 = ((selected_coeff->adc_div - 1) << 4) | (selected_coeff->dac_div - 1);
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG05, reg05), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x06 */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®v), TAG, "I2C read/write error");
|
|
||||||
regv &= 0xE0;
|
|
||||||
|
|
||||||
if (selected_coeff->bclk_div < 19) {
|
|
||||||
regv |= (selected_coeff->bclk_div - 1) << 0;
|
|
||||||
} else {
|
|
||||||
regv |= (selected_coeff->bclk_div) << 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, regv), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x07 */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG07, ®v), TAG, "I2C read/write error");
|
|
||||||
regv &= 0xC0;
|
|
||||||
regv |= selected_coeff->lrck_h << 0;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG07, regv), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* register 0x08 */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG08, selected_coeff->lrck_l), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
static esp_err_t es8311_clock_config(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, es8311_resolution_t res)
|
|
||||||
{
|
|
||||||
uint8_t reg06;
|
|
||||||
uint8_t reg01 = 0x3F; // Enable all clocks
|
|
||||||
int mclk_hz;
|
|
||||||
|
|
||||||
/* Select clock source for internal MCLK and determine its frequency */
|
|
||||||
if (clk_cfg->mclk_from_mclk_pin) {
|
|
||||||
mclk_hz = clk_cfg->mclk_frequency;
|
|
||||||
} else {
|
|
||||||
mclk_hz = clk_cfg->sample_frequency * (int)res * 2;
|
|
||||||
reg01 |= BIT(7); // Select BCLK (a.k.a. SCK) pin
|
|
||||||
}
|
|
||||||
|
|
||||||
if (clk_cfg->mclk_inverted) {
|
|
||||||
reg01 |= BIT(6); // Invert MCLK pin
|
|
||||||
}
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG01, reg01), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_CLK_MANAGER_REG06, ®06), TAG, "I2C read/write error");
|
|
||||||
if (clk_cfg->sclk_inverted) {
|
|
||||||
reg06 |= BIT(5);
|
|
||||||
} else {
|
|
||||||
reg06 &= ~BIT(5);
|
|
||||||
}
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_CLK_MANAGER_REG06, reg06), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
/* Configure clock dividers */
|
|
||||||
return es8311_sample_frequency_config(dev, mclk_hz, clk_cfg->sample_frequency);
|
|
||||||
}
|
|
||||||
|
|
||||||
static esp_err_t es8311_resolution_config(const es8311_resolution_t res, uint8_t *reg)
|
|
||||||
{
|
|
||||||
switch (res) {
|
|
||||||
case ES8311_RESOLUTION_16:
|
|
||||||
*reg |= (3 << 2);
|
|
||||||
break;
|
|
||||||
case ES8311_RESOLUTION_18:
|
|
||||||
*reg |= (2 << 2);
|
|
||||||
break;
|
|
||||||
case ES8311_RESOLUTION_20:
|
|
||||||
*reg |= (1 << 2);
|
|
||||||
break;
|
|
||||||
case ES8311_RESOLUTION_24:
|
|
||||||
*reg |= (0 << 2);
|
|
||||||
break;
|
|
||||||
case ES8311_RESOLUTION_32:
|
|
||||||
*reg |= (4 << 2);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
return ESP_ERR_INVALID_ARG;
|
|
||||||
}
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
static esp_err_t es8311_fmt_config(es8311_handle_t dev, const es8311_resolution_t res_in, const es8311_resolution_t res_out)
|
|
||||||
{
|
|
||||||
uint8_t reg09 = 0; // SDP In
|
|
||||||
uint8_t reg0a = 0; // SDP Out
|
|
||||||
|
|
||||||
ESP_LOGI(TAG, "ES8311 in Slave mode and I2S format");
|
|
||||||
uint8_t reg00;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_RESET_REG00, ®00), TAG, "I2C read/write error");
|
|
||||||
reg00 &= 0xBF;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, reg00), TAG, "I2C read/write error"); // Slave serial port - default
|
|
||||||
|
|
||||||
/* Setup SDP In and Out resolution */
|
|
||||||
es8311_resolution_config(res_in, ®09);
|
|
||||||
es8311_resolution_config(res_out, ®0a);
|
|
||||||
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPIN_REG09, reg09), TAG, "I2C read/write error");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SDPOUT_REG0A, reg0a), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic)
|
|
||||||
{
|
|
||||||
uint8_t reg14 = 0x1A; // enable analog MIC and max PGA gain
|
|
||||||
|
|
||||||
/* PDM digital microphone enable or disable */
|
|
||||||
if (digital_mic) {
|
|
||||||
reg14 |= BIT(6);
|
|
||||||
}
|
|
||||||
es8311_write_reg(dev, ES8311_ADC_REG17, 0xC8); // Set ADC gain @todo move this to ADC config section
|
|
||||||
|
|
||||||
return es8311_write_reg(dev, ES8311_SYSTEM_REG14, reg14);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in, const es8311_resolution_t res_out)
|
|
||||||
{
|
|
||||||
ESP_RETURN_ON_FALSE(
|
|
||||||
(clk_cfg->sample_frequency >= 8000) && (clk_cfg->sample_frequency <= 96000),
|
|
||||||
ESP_ERR_INVALID_ARG, TAG, "ES8311 init needs frequency in interval [8000; 96000] Hz"
|
|
||||||
);
|
|
||||||
if (!clk_cfg->mclk_from_mclk_pin) {
|
|
||||||
ESP_RETURN_ON_FALSE(res_out == res_in, ESP_ERR_INVALID_ARG, TAG, "Resolution IN/OUT must be equal if MCLK is taken from SCK pin");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* Reset ES8311 to its default */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x1F), TAG, "I2C read/write error");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x00), TAG, "I2C read/write error");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_RESET_REG00, 0x80), TAG, "I2C read/write error"); // Power-on command
|
|
||||||
|
|
||||||
/* Setup clock: source, polarity and clock dividers */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_clock_config(dev, clk_cfg, res_out), TAG, "");
|
|
||||||
|
|
||||||
/* Setup audio format (fmt): master/slave, resolution, I2S */
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_fmt_config(dev, res_in, res_out), TAG, "");
|
|
||||||
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0D, 0x01), TAG, "I2C read/write error"); // Power up analog circuitry - NOT default
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG0E, 0x02), TAG, "I2C read/write error"); // Enable analog PGA, enable ADC modulator - NOT default
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG12, 0x00), TAG, "I2C read/write error"); // power-up DAC - NOT default
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_SYSTEM_REG13, 0x10), TAG, "I2C read/write error"); // Enable output to HP drive - NOT default
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_ADC_REG1C, 0x6A), TAG, "I2C read/write error"); // ADC Equalizer bypass, cancel DC offset in digital domain
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_write_reg(dev, ES8311_DAC_REG37, 0x08), TAG, "I2C read/write error"); // Bypass DAC equalizer - NOT default
|
|
||||||
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
void es8311_delete(es8311_handle_t dev)
|
|
||||||
{
|
|
||||||
free(dev);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set)
|
|
||||||
{
|
|
||||||
if (volume < 0) {
|
|
||||||
volume = 0;
|
|
||||||
} else if (volume > 100) {
|
|
||||||
volume = 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
int reg32;
|
|
||||||
if (volume == 0) {
|
|
||||||
reg32 = 0;
|
|
||||||
} else {
|
|
||||||
reg32 = ((volume) * 256 / 100) - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// provide user with real volume set
|
|
||||||
if (volume_set != NULL) {
|
|
||||||
*volume_set = volume;
|
|
||||||
}
|
|
||||||
return es8311_write_reg(dev, ES8311_DAC_REG32, reg32);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume)
|
|
||||||
{
|
|
||||||
uint8_t reg32;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG32, ®32), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
if (reg32 == 0) {
|
|
||||||
*volume = 0;
|
|
||||||
} else {
|
|
||||||
*volume = ((reg32 * 100) / 256) + 1;
|
|
||||||
}
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_voice_mute(es8311_handle_t dev, bool mute)
|
|
||||||
{
|
|
||||||
uint8_t reg31;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG31, ®31), TAG, "I2C read/write error");
|
|
||||||
|
|
||||||
if (mute) {
|
|
||||||
reg31 |= BIT(6) | BIT(5);
|
|
||||||
} else {
|
|
||||||
reg31 &= ~(BIT(6) | BIT(5));
|
|
||||||
}
|
|
||||||
|
|
||||||
return es8311_write_reg(dev, ES8311_DAC_REG31, reg31);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db)
|
|
||||||
{
|
|
||||||
return es8311_write_reg(dev, ES8311_ADC_REG16, gain_db); // ADC gain scale up
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade)
|
|
||||||
{
|
|
||||||
uint8_t reg37;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_DAC_REG37, ®37), TAG, "I2C read/write error");
|
|
||||||
reg37 &= 0x0F;
|
|
||||||
reg37 |= (fade << 4);
|
|
||||||
return es8311_write_reg(dev, ES8311_DAC_REG37, reg37);
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade)
|
|
||||||
{
|
|
||||||
uint8_t reg15;
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_read_reg(dev, ES8311_ADC_REG15, ®15), TAG, "I2C read/write error");
|
|
||||||
reg15 &= 0x0F;
|
|
||||||
reg15 |= (fade << 4);
|
|
||||||
return es8311_write_reg(dev, ES8311_ADC_REG15, reg15);
|
|
||||||
}
|
|
||||||
|
|
||||||
void es8311_register_dump(es8311_handle_t dev)
|
|
||||||
{
|
|
||||||
for (int reg = 0; reg < 0x4A; reg++) {
|
|
||||||
uint8_t value;
|
|
||||||
ESP_ERROR_CHECK(es8311_read_reg(dev, reg, &value));
|
|
||||||
printf("REG:%02x: %02x", reg, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr)
|
|
||||||
{
|
|
||||||
es8311_dev_t *sensor = (es8311_dev_t *) calloc(1, sizeof(es8311_dev_t));
|
|
||||||
sensor->port = port;
|
|
||||||
sensor->dev_addr = dev_addr;
|
|
||||||
return (es8311_handle_t) sensor;
|
|
||||||
}
|
|
||||||
@@ -1,227 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: Apache-2.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @file
|
|
||||||
* @brief ES8311 driver
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
#include "esp_types.h"
|
|
||||||
#include "esp_err.h"
|
|
||||||
|
|
||||||
/* ES8311 address: CE pin low - 0x18, CE pin high - 0x19 */
|
|
||||||
#define ES8311_ADDRRES_0 0x18u // Leaving this here for backward compatibility
|
|
||||||
#define ES8311_ADDRESS_0 0x18u
|
|
||||||
#define ES8311_ADDRESS_1 0x19u
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
extern "C" {
|
|
||||||
#endif
|
|
||||||
|
|
||||||
typedef void *es8311_handle_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ES8311_MIC_GAIN_MIN = -1,
|
|
||||||
ES8311_MIC_GAIN_0DB,
|
|
||||||
ES8311_MIC_GAIN_6DB,
|
|
||||||
ES8311_MIC_GAIN_12DB,
|
|
||||||
ES8311_MIC_GAIN_18DB,
|
|
||||||
ES8311_MIC_GAIN_24DB,
|
|
||||||
ES8311_MIC_GAIN_30DB,
|
|
||||||
ES8311_MIC_GAIN_36DB,
|
|
||||||
ES8311_MIC_GAIN_42DB,
|
|
||||||
ES8311_MIC_GAIN_MAX
|
|
||||||
} es8311_mic_gain_t;
|
|
||||||
|
|
||||||
typedef enum {
|
|
||||||
ES8311_FADE_OFF = 0,
|
|
||||||
ES8311_FADE_4LRCK, // 4LRCK means ramp 0.25dB/4LRCK
|
|
||||||
ES8311_FADE_8LRCK,
|
|
||||||
ES8311_FADE_16LRCK,
|
|
||||||
ES8311_FADE_32LRCK,
|
|
||||||
ES8311_FADE_64LRCK,
|
|
||||||
ES8311_FADE_128LRCK,
|
|
||||||
ES8311_FADE_256LRCK,
|
|
||||||
ES8311_FADE_512LRCK,
|
|
||||||
ES8311_FADE_1024LRCK,
|
|
||||||
ES8311_FADE_2048LRCK,
|
|
||||||
ES8311_FADE_4096LRCK,
|
|
||||||
ES8311_FADE_8192LRCK,
|
|
||||||
ES8311_FADE_16384LRCK,
|
|
||||||
ES8311_FADE_32768LRCK,
|
|
||||||
ES8311_FADE_65536LRCK
|
|
||||||
} es8311_fade_t;
|
|
||||||
|
|
||||||
typedef enum es8311_resolution_t {
|
|
||||||
ES8311_RESOLUTION_16 = 16,
|
|
||||||
ES8311_RESOLUTION_18 = 18,
|
|
||||||
ES8311_RESOLUTION_20 = 20,
|
|
||||||
ES8311_RESOLUTION_24 = 24,
|
|
||||||
ES8311_RESOLUTION_32 = 32
|
|
||||||
} es8311_resolution_t;
|
|
||||||
|
|
||||||
typedef struct es8311_clock_config_t {
|
|
||||||
bool mclk_inverted;
|
|
||||||
bool sclk_inverted;
|
|
||||||
bool mclk_from_mclk_pin; // true: from MCLK pin (pin no. 2), false: from SCLK pin (pin no. 6)
|
|
||||||
int mclk_frequency; // This parameter is ignored if MCLK is taken from SCLK pin
|
|
||||||
int sample_frequency; // in Hz
|
|
||||||
} es8311_clock_config_t;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Initialize ES8311
|
|
||||||
*
|
|
||||||
* There are two ways of providing Master Clock (MCLK) signal to ES8311 in Slave Mode:
|
|
||||||
* 1. From MCLK pin:
|
|
||||||
* For flexible scenarios. A clock signal from I2S master is routed to MCLK pin.
|
|
||||||
* Its frequency must be defined in clk_cfg->mclk_frequency parameter.
|
|
||||||
* 2. From SCLK pin:
|
|
||||||
* For simpler scenarios. ES8311 takes its clock from SCK pin. MCLK pin does not have to be connected.
|
|
||||||
* In this case, res_in must equal res_out; clk_cfg->mclk_frequency parameter is ignored
|
|
||||||
* and MCLK is calculated as MCLK = clk_cfg->sample_frequency * res_out * 2.
|
|
||||||
* Not all sampling frequencies are supported in this mode.
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] clk_cfg Clock configuration
|
|
||||||
* @param[in] res_in Input serial port resolution
|
|
||||||
* @param[in] res_out Output serial port resolution
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - ESP_ERR_INVALID_ARG Sample frequency or resolution invalid
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_init(es8311_handle_t dev, const es8311_clock_config_t *const clk_cfg, const es8311_resolution_t res_in,
|
|
||||||
const es8311_resolution_t res_out);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set output volume
|
|
||||||
*
|
|
||||||
* Volume paramter out of <0, 100> interval will be truncated.
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] volume Set volume (0 ~ 100)
|
|
||||||
* @param[out] volume_set Volume that was set. Same as volume, unless volume is outside of <0, 100> interval.
|
|
||||||
* This parameter can be set to NULL, if user does not need this information.
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_voice_volume_set(es8311_handle_t dev, int volume, int *volume_set);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Get output volume
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[out] volume get volume (0 ~ 100)
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_voice_volume_get(es8311_handle_t dev, int *volume);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Print out ES8311 register content
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
*/
|
|
||||||
void es8311_register_dump(es8311_handle_t dev);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Mute ES8311 output
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] enable true: mute, false: don't mute
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_voice_mute(es8311_handle_t dev, bool enable);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Set Microphone gain
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] gain_db Microphone gain
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_microphone_gain_set(es8311_handle_t dev, es8311_mic_gain_t gain_db);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure microphone
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] digital_mic Set to true for digital microphone
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else fail
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_microphone_config(es8311_handle_t dev, bool digital_mic);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure sampling frequency
|
|
||||||
*
|
|
||||||
* @note This function is called by es8311_init().
|
|
||||||
* Call this function explicitly only if you want to change sample frequency during runtime.
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] mclk_frequency MCLK frequency in [Hz] (MCLK or SCLK pin, depending on bit register01[7])
|
|
||||||
* @param[in] sample_frequency Required sample frequency in [Hz], e.g. 44100, 22050...
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - ESP_ERR_INVALID_ARG cannot set clock dividers for given MCLK and sampling frequency
|
|
||||||
* - Else I2C read/write error
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_sample_frequency_config(es8311_handle_t dev, int mclk_frequency, int sample_frequency);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure fade in/out for ADC: voice
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] fade Fade ramp rate
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else I2C read/write error
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_voice_fade(es8311_handle_t dev, const es8311_fade_t fade);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Configure fade in/out for DAC: microphone
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
* @param[in] fade Fade ramp rate
|
|
||||||
* @return
|
|
||||||
* - ESP_OK success
|
|
||||||
* - Else I2C read/write error
|
|
||||||
*/
|
|
||||||
esp_err_t es8311_microphone_fade(es8311_handle_t dev, const es8311_fade_t fade);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Create ES8311 object and return its handle
|
|
||||||
*
|
|
||||||
* @param[in] port I2C port number
|
|
||||||
* @param[in] dev_addr I2C device address of ES8311
|
|
||||||
*
|
|
||||||
* @return
|
|
||||||
* - NULL Fail
|
|
||||||
* - Others Success
|
|
||||||
*/
|
|
||||||
es8311_handle_t es8311_create(const unsigned int port, const uint16_t dev_addr);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Delete ES8311 object
|
|
||||||
*
|
|
||||||
* @param dev ES8311 handle
|
|
||||||
*/
|
|
||||||
void es8311_delete(es8311_handle_t dev);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: Apache-2.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
|
|
||||||
/*
|
|
||||||
* ES8311_REGISTER NAME_REG_REGISTER ADDRESS
|
|
||||||
*/
|
|
||||||
#define ES8311_RESET_REG00 0x00 /*reset digital,csm,clock manager etc.*/
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Clock Scheme Register definition
|
|
||||||
*/
|
|
||||||
#define ES8311_CLK_MANAGER_REG01 0x01 /* select clk src for mclk, enable clock for codec */
|
|
||||||
#define ES8311_CLK_MANAGER_REG02 0x02 /* clk divider and clk multiplier */
|
|
||||||
#define ES8311_CLK_MANAGER_REG03 0x03 /* adc fsmode and osr */
|
|
||||||
#define ES8311_CLK_MANAGER_REG04 0x04 /* dac osr */
|
|
||||||
#define ES8311_CLK_MANAGER_REG05 0x05 /* clk divier for adc and dac */
|
|
||||||
#define ES8311_CLK_MANAGER_REG06 0x06 /* bclk inverter and divider */
|
|
||||||
#define ES8311_CLK_MANAGER_REG07 0x07 /* tri-state, lrck divider */
|
|
||||||
#define ES8311_CLK_MANAGER_REG08 0x08 /* lrck divider */
|
|
||||||
/*
|
|
||||||
* SDP
|
|
||||||
*/
|
|
||||||
#define ES8311_SDPIN_REG09 0x09 /* dac serial digital port */
|
|
||||||
#define ES8311_SDPOUT_REG0A 0x0A /* adc serial digital port */
|
|
||||||
/*
|
|
||||||
* SYSTEM
|
|
||||||
*/
|
|
||||||
#define ES8311_SYSTEM_REG0B 0x0B /* system */
|
|
||||||
#define ES8311_SYSTEM_REG0C 0x0C /* system */
|
|
||||||
#define ES8311_SYSTEM_REG0D 0x0D /* system, power up/down */
|
|
||||||
#define ES8311_SYSTEM_REG0E 0x0E /* system, power up/down */
|
|
||||||
#define ES8311_SYSTEM_REG0F 0x0F /* system, low power */
|
|
||||||
#define ES8311_SYSTEM_REG10 0x10 /* system */
|
|
||||||
#define ES8311_SYSTEM_REG11 0x11 /* system */
|
|
||||||
#define ES8311_SYSTEM_REG12 0x12 /* system, Enable DAC */
|
|
||||||
#define ES8311_SYSTEM_REG13 0x13 /* system */
|
|
||||||
#define ES8311_SYSTEM_REG14 0x14 /* system, select DMIC, select analog pga gain */
|
|
||||||
/*
|
|
||||||
* ADC
|
|
||||||
*/
|
|
||||||
#define ES8311_ADC_REG15 0x15 /* ADC, adc ramp rate, dmic sense */
|
|
||||||
#define ES8311_ADC_REG16 0x16 /* ADC */
|
|
||||||
#define ES8311_ADC_REG17 0x17 /* ADC, volume */
|
|
||||||
#define ES8311_ADC_REG18 0x18 /* ADC, alc enable and winsize */
|
|
||||||
#define ES8311_ADC_REG19 0x19 /* ADC, alc maxlevel */
|
|
||||||
#define ES8311_ADC_REG1A 0x1A /* ADC, alc automute */
|
|
||||||
#define ES8311_ADC_REG1B 0x1B /* ADC, alc automute, adc hpf s1 */
|
|
||||||
#define ES8311_ADC_REG1C 0x1C /* ADC, equalizer, hpf s2 */
|
|
||||||
/*
|
|
||||||
* DAC
|
|
||||||
*/
|
|
||||||
#define ES8311_DAC_REG31 0x31 /* DAC, mute */
|
|
||||||
#define ES8311_DAC_REG32 0x32 /* DAC, volume */
|
|
||||||
#define ES8311_DAC_REG33 0x33 /* DAC, offset */
|
|
||||||
#define ES8311_DAC_REG34 0x34 /* DAC, drc enable, drc winsize */
|
|
||||||
#define ES8311_DAC_REG35 0x35 /* DAC, drc maxlevel, minilevel */
|
|
||||||
#define ES8311_DAC_REG37 0x37 /* DAC, ramprate */
|
|
||||||
/*
|
|
||||||
*GPIO
|
|
||||||
*/
|
|
||||||
#define ES8311_GPIO_REG44 0x44 /* GPIO, dac2adc for test */
|
|
||||||
#define ES8311_GP_REG45 0x45 /* GP CONTROL */
|
|
||||||
/*
|
|
||||||
* CHIP
|
|
||||||
*/
|
|
||||||
#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */
|
|
||||||
#define ES8311_CHD2_REGFE 0xFE /* CHIP ID2 */
|
|
||||||
#define ES8311_CHVER_REGFF 0xFF /* VERSION */
|
|
||||||
#define ES8311_CHD1_REGFD 0xFD /* CHIP ID1 */
|
|
||||||
|
|
||||||
#define ES8311_MAX_REGISTER 0xFF
|
|
||||||
@@ -1,272 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <math.h>
|
|
||||||
#include "ESP_I2S.h"
|
|
||||||
#include "esp_check.h"
|
|
||||||
#include "Arduino_GFX_Library.h"
|
|
||||||
#include "pin_config.h"
|
|
||||||
#include "TouchDrvCSTXXX.hpp"
|
|
||||||
#include "SensorQMI8658.hpp"
|
|
||||||
#include "es8311.h"
|
|
||||||
#include "es7210.h"
|
|
||||||
|
|
||||||
static const int DISP_W = 480;
|
|
||||||
static const int DISP_H = 480;
|
|
||||||
static const int SAFE = 20;
|
|
||||||
static const uint32_t SAMPLE_RATE = 16000;
|
|
||||||
static const size_t REC_SECONDS = 2;
|
|
||||||
static const size_t AUDIO_BYTES = SAMPLE_RATE * REC_SECONDS * 2 * 2;
|
|
||||||
static const int I2C_NUM = 0;
|
|
||||||
|
|
||||||
I2SClass i2s;
|
|
||||||
TouchDrvCST92xx touch;
|
|
||||||
SensorQMI8658 qmi;
|
|
||||||
IMUdata acc;
|
|
||||||
|
|
||||||
Arduino_DataBus *bus = new Arduino_ESP32QSPI(LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(bus, LCD_RESET, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
uint8_t *audioBuf = nullptr;
|
|
||||||
size_t audioLen = 0;
|
|
||||||
bool touchIrq = false;
|
|
||||||
String statusLine = "Ready";
|
|
||||||
String tiltLine = "Tilt: FLAT";
|
|
||||||
String audioLine = "Audio: empty";
|
|
||||||
uint32_t lastTiltMs = 0;
|
|
||||||
bool micReady = false;
|
|
||||||
|
|
||||||
void IRAM_ATTR onTouchInt() { touchIrq = true; }
|
|
||||||
|
|
||||||
esp_err_t codecInit() {
|
|
||||||
es8311_handle_t esHandle = es8311_create(I2C_NUM, ES8311_ADDRRES_0);
|
|
||||||
ESP_RETURN_ON_FALSE(esHandle, ESP_FAIL, "AV", "es8311 create failed");
|
|
||||||
const es8311_clock_config_t clk = {
|
|
||||||
.mclk_inverted = false,
|
|
||||||
.sclk_inverted = false,
|
|
||||||
.mclk_from_mclk_pin = true,
|
|
||||||
.mclk_frequency = SAMPLE_RATE * 256,
|
|
||||||
.sample_frequency = SAMPLE_RATE,
|
|
||||||
};
|
|
||||||
ESP_ERROR_CHECK(es8311_init(esHandle, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16));
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_sample_frequency_config(esHandle, clk.mclk_frequency, clk.sample_frequency), "AV", "clock cfg failed");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_microphone_config(esHandle, false), "AV", "mic cfg failed");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_voice_volume_set(esHandle, 90, NULL), "AV", "volume failed");
|
|
||||||
ESP_RETURN_ON_ERROR(es8311_microphone_gain_set(esHandle, (es8311_mic_gain_t)6), "AV", "mic gain failed");
|
|
||||||
return ESP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
esp_err_t micInit() {
|
|
||||||
audio_hal_codec_config_t cfg = {
|
|
||||||
.adc_input = AUDIO_HAL_ADC_INPUT_ALL,
|
|
||||||
.codec_mode = AUDIO_HAL_CODEC_MODE_ENCODE,
|
|
||||||
.i2s_iface = {
|
|
||||||
.mode = AUDIO_HAL_MODE_SLAVE,
|
|
||||||
.fmt = AUDIO_HAL_I2S_NORMAL,
|
|
||||||
.samples = AUDIO_HAL_16K_SAMPLES,
|
|
||||||
.bits = AUDIO_HAL_BIT_LENGTH_16BITS,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
esp_err_t ret = ESP_OK;
|
|
||||||
ret |= es7210_adc_init(&Wire, &cfg);
|
|
||||||
ret |= es7210_adc_config_i2s(cfg.codec_mode, &cfg.i2s_iface);
|
|
||||||
ret |= es7210_adc_set_gain(
|
|
||||||
(es7210_input_mics_t)(ES7210_INPUT_MIC1 | ES7210_INPUT_MIC2),
|
|
||||||
(es7210_gain_value_t)GAIN_24DB);
|
|
||||||
ret |= es7210_adc_set_gain(
|
|
||||||
(es7210_input_mics_t)(ES7210_INPUT_MIC3 | ES7210_INPUT_MIC4),
|
|
||||||
(es7210_gain_value_t)GAIN_24DB);
|
|
||||||
ret |= es7210_adc_ctrl_state(cfg.codec_mode, AUDIO_HAL_CTRL_START);
|
|
||||||
return ret;
|
|
||||||
}
|
|
||||||
|
|
||||||
void drawStaticUi() {
|
|
||||||
gfx->fillScreen(RGB565_BLACK);
|
|
||||||
gfx->setTextSize(2);
|
|
||||||
gfx->setTextColor(RGB565_WHITE);
|
|
||||||
gfx->setCursor(SAFE + 16, SAFE + 10);
|
|
||||||
gfx->println("Simple AV + Tilt Test");
|
|
||||||
|
|
||||||
gfx->drawRect(24, 76, 132, 64, RGB565_GREEN);
|
|
||||||
gfx->setCursor(44, 100);
|
|
||||||
gfx->println("RECORD");
|
|
||||||
|
|
||||||
gfx->drawRect(174, 76, 132, 64, RGB565_YELLOW);
|
|
||||||
gfx->setCursor(212, 100);
|
|
||||||
gfx->println("PLAY");
|
|
||||||
|
|
||||||
gfx->drawRect(324, 76, 132, 64, RGB565_CYAN);
|
|
||||||
gfx->setCursor(360, 100);
|
|
||||||
gfx->println("BEEP");
|
|
||||||
}
|
|
||||||
|
|
||||||
void drawDynamic() {
|
|
||||||
gfx->fillRect(20, 166, 440, 140, RGB565_BLACK);
|
|
||||||
gfx->setTextSize(2);
|
|
||||||
gfx->setTextColor(RGB565_WHITE);
|
|
||||||
gfx->setCursor(28, 178);
|
|
||||||
gfx->println(statusLine);
|
|
||||||
gfx->setTextColor(RGB565_CYAN);
|
|
||||||
gfx->setCursor(28, 212);
|
|
||||||
gfx->println(tiltLine);
|
|
||||||
gfx->setTextColor(RGB565_ORANGE);
|
|
||||||
gfx->setCursor(28, 246);
|
|
||||||
gfx->println(audioLine);
|
|
||||||
gfx->drawRect(28, 278, 300, 20, RGB565_DARKGREY);
|
|
||||||
}
|
|
||||||
|
|
||||||
void updateTilt() {
|
|
||||||
if (!qmi.getDataReady()) return;
|
|
||||||
if (!qmi.getAccelerometer(acc.x, acc.y, acc.z)) return;
|
|
||||||
String next = "Tilt: FLAT";
|
|
||||||
if (acc.x > 0.8f) next = "Tilt: RIGHT";
|
|
||||||
else if (acc.x < -0.8f) next = "Tilt: LEFT";
|
|
||||||
else if (acc.y > 0.8f) next = "Tilt: UP";
|
|
||||||
else if (acc.y < -0.8f) next = "Tilt: DOWN";
|
|
||||||
if (next != tiltLine) {
|
|
||||||
tiltLine = next;
|
|
||||||
drawDynamic();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void playBeep() {
|
|
||||||
static int16_t tone[16000];
|
|
||||||
for (int i = 0; i < 8000; ++i) {
|
|
||||||
float s = sinf(2.0f * 3.1415926f * 440.0f * ((float)i / SAMPLE_RATE));
|
|
||||||
int16_t v = (int16_t)(s * 6000.0f);
|
|
||||||
tone[i * 2] = v;
|
|
||||||
tone[i * 2 + 1] = v;
|
|
||||||
}
|
|
||||||
statusLine = "Playing test beep...";
|
|
||||||
drawDynamic();
|
|
||||||
i2s.write((uint8_t *)tone, 8000 * 2 * sizeof(int16_t));
|
|
||||||
statusLine = "Beep done";
|
|
||||||
drawDynamic();
|
|
||||||
}
|
|
||||||
|
|
||||||
void recordAudio() {
|
|
||||||
if (!audioBuf || !micReady) {
|
|
||||||
statusLine = "No audio buffer";
|
|
||||||
drawDynamic();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
statusLine = "Recording 2 sec...";
|
|
||||||
drawDynamic();
|
|
||||||
size_t total = 0;
|
|
||||||
uint16_t peakAll = 0;
|
|
||||||
while (total < AUDIO_BYTES) {
|
|
||||||
size_t chunk = min((size_t)4096, AUDIO_BYTES - total);
|
|
||||||
size_t got = i2s.readBytes((char *)(audioBuf + total), chunk);
|
|
||||||
if (!got) break;
|
|
||||||
total += got;
|
|
||||||
|
|
||||||
int16_t *s = (int16_t *)(audioBuf + total - got);
|
|
||||||
size_t n = got / sizeof(int16_t);
|
|
||||||
uint16_t peak = 0;
|
|
||||||
for (size_t i = 0; i < n; i++) {
|
|
||||||
uint16_t a = (uint16_t)abs((int)s[i]);
|
|
||||||
if (a > peak) peak = a;
|
|
||||||
}
|
|
||||||
if (peak > peakAll) peakAll = peak;
|
|
||||||
|
|
||||||
int bar = map((int)peak, 0, 20000, 0, 296);
|
|
||||||
if (bar < 0) bar = 0;
|
|
||||||
if (bar > 296) bar = 296;
|
|
||||||
gfx->fillRect(30, 280, 296, 16, RGB565_BLACK);
|
|
||||||
uint16_t c = (peak > 12000) ? RGB565_RED : ((peak > 6000) ? RGB565_YELLOW : RGB565_GREEN);
|
|
||||||
gfx->fillRect(30, 280, bar, 16, c);
|
|
||||||
}
|
|
||||||
audioLen = total;
|
|
||||||
audioLine = (total > 0) ? "Audio: recorded" : "Audio: empty";
|
|
||||||
if (total > 0) {
|
|
||||||
statusLine = String("Record done, peak=") + String((int)peakAll);
|
|
||||||
} else {
|
|
||||||
statusLine = "Record failed";
|
|
||||||
}
|
|
||||||
drawDynamic();
|
|
||||||
}
|
|
||||||
|
|
||||||
void playAudio() {
|
|
||||||
if (!audioLen) {
|
|
||||||
statusLine = "No recording. Try BEEP.";
|
|
||||||
drawDynamic();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
statusLine = "Playing recording...";
|
|
||||||
drawDynamic();
|
|
||||||
size_t wrote = i2s.write(audioBuf, audioLen);
|
|
||||||
statusLine = (wrote > 0) ? "Play done" : "Play failed";
|
|
||||||
drawDynamic();
|
|
||||||
}
|
|
||||||
|
|
||||||
void handleTouch() {
|
|
||||||
if (!touchIrq) return;
|
|
||||||
touchIrq = false;
|
|
||||||
int16_t x[1];
|
|
||||||
int16_t y[1];
|
|
||||||
uint8_t touched = touch.getPoint(x, y, 1);
|
|
||||||
if (!touched) return;
|
|
||||||
|
|
||||||
int px = x[0];
|
|
||||||
int py = y[0];
|
|
||||||
if (py < 76 || py > 140) return;
|
|
||||||
if (px >= 24 && px <= 156) recordAudio();
|
|
||||||
else if (px >= 174 && px <= 306) playAudio();
|
|
||||||
else if (px >= 324 && px <= 456) playBeep();
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
pinMode(PA, OUTPUT);
|
|
||||||
digitalWrite(PA, HIGH);
|
|
||||||
|
|
||||||
if (!gfx->begin()) Serial.println("gfx begin failed");
|
|
||||||
bus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(200);
|
|
||||||
|
|
||||||
pinMode(TP_RST, OUTPUT);
|
|
||||||
digitalWrite(TP_RST, LOW);
|
|
||||||
delay(30);
|
|
||||||
digitalWrite(TP_RST, HIGH);
|
|
||||||
delay(50);
|
|
||||||
touch.setPins(TP_RST, TP_INT);
|
|
||||||
touch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
|
||||||
touch.setMaxCoordinates(480, 480);
|
|
||||||
touch.setSwapXY(true);
|
|
||||||
touch.setMirrorXY(true, false);
|
|
||||||
attachInterrupt(TP_INT, onTouchInt, FALLING);
|
|
||||||
|
|
||||||
if (qmi.begin(Wire, QMI8658_L_SLAVE_ADDRESS, IIC_SDA, IIC_SCL)) {
|
|
||||||
qmi.configAccelerometer(SensorQMI8658::ACC_RANGE_4G, SensorQMI8658::ACC_ODR_1000Hz, SensorQMI8658::LPF_MODE_0);
|
|
||||||
qmi.enableAccelerometer();
|
|
||||||
} else {
|
|
||||||
tiltLine = "Tilt: IMU not found";
|
|
||||||
}
|
|
||||||
|
|
||||||
i2s.setPins(9, 45, 8, 10, 42);
|
|
||||||
if (!i2s.begin(I2S_MODE_STD, SAMPLE_RATE, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO, I2S_STD_SLOT_BOTH)) {
|
|
||||||
statusLine = "I2S init failed";
|
|
||||||
} else if (codecInit() != ESP_OK) {
|
|
||||||
statusLine = "ES8311 init failed";
|
|
||||||
} else if (micInit() != ESP_OK) {
|
|
||||||
statusLine = "ES7210 init failed";
|
|
||||||
} else {
|
|
||||||
micReady = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
audioBuf = (uint8_t *)ps_malloc(AUDIO_BYTES);
|
|
||||||
if (!audioBuf) statusLine = "No PSRAM buffer";
|
|
||||||
|
|
||||||
drawStaticUi();
|
|
||||||
drawDynamic();
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
handleTouch();
|
|
||||||
if (millis() - lastTiltMs > 120) {
|
|
||||||
lastTiltMs = millis();
|
|
||||||
updateTilt();
|
|
||||||
}
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
# Test Sketches
|
|
||||||
|
|
||||||
Набор старых отдельных диагностических скетчей для `Waveshare ESP32-S3-Touch-AMOLED-2.16`.
|
|
||||||
|
|
||||||
Скетчи в этой папке нужны для быстрой проверки конкретных гипотез и не являются основным UI проекта.
|
|
||||||
Основной скетч сейчас лежит в `main-device/shine_homeserver_main/`.
|
|
||||||
|
|
||||||
## Список
|
|
||||||
|
|
||||||
- `gfx_text_render_test/` - проверка рендера текста через `Arduino_GFX` и сравнение с `U8g2`
|
|
||||||
- `gfx_button_layout_test/` - проверка геометрии кнопок, особенно нижних рядов и широких кнопок
|
|
||||||
- `lvgl_basic_test/` - минимальный тест `LVGL` с заголовком, текстом и кнопками
|
|
||||||
- `lvgl_interaction_test/` - расширенный тест `LVGL` с 9 кнопками, touch-вводом и статусом нажатия
|
|
||||||
- `lvgl_touch_debug_test/` - диагностика touch: сырые координаты, точка касания и одна большая кнопка `LVGL`
|
|
||||||
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
|
||||||
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
|
||||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
|
||||||
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
|
||||||
|
|
||||||
## Запуск
|
|
||||||
|
|
||||||
Использовать через `burn.sh`:
|
|
||||||
|
|
||||||
- `./burn.sh gfx-text-test`
|
|
||||||
- `./burn.sh gfx-layout-test`
|
|
||||||
- `./burn.sh lvgl-basic-test`
|
|
||||||
- `./burn.sh lvgl-interaction-test`
|
|
||||||
- `./burn.sh lvgl-touch-debug-test`
|
|
||||||
- `./burn.sh lvgl-official-based-test`
|
|
||||||
- `./burn.sh lvgl-subserver-touch-test`
|
|
||||||
- `./burn.sh lvgl-russian-font-test`
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
|
|
||||||
#define PIN_LCD_CS 12
|
|
||||||
#define PIN_LCD_SCLK 38
|
|
||||||
#define PIN_LCD_D0 4
|
|
||||||
#define PIN_LCD_D1 5
|
|
||||||
#define PIN_LCD_D2 6
|
|
||||||
#define PIN_LCD_D3 7
|
|
||||||
#define PIN_LCD_RST 2
|
|
||||||
#define PIN_I2C_SDA 15
|
|
||||||
#define PIN_I2C_SCL 14
|
|
||||||
|
|
||||||
#define DISP_W 480
|
|
||||||
#define DISP_H 480
|
|
||||||
|
|
||||||
#define C_BG 0x0841u
|
|
||||||
#define C_PANEL 0x1082u
|
|
||||||
#define C_CARD 0x18C3u
|
|
||||||
#define C_BORDER 0x39C7u
|
|
||||||
#define C_TEXT 0xFFFFu
|
|
||||||
#define C_OK 0x3666u
|
|
||||||
#define C_WARN 0xECA0u
|
|
||||||
#define C_BUTTON 0x2145u
|
|
||||||
#define C_BUTTON2 0x3186u
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
|
|
||||||
gfx->fillRoundRect(x, y, w, h, radius, fill);
|
|
||||||
gfx->drawRoundRect(x, y, w, h, radius, border);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) {
|
|
||||||
gfx->setFont();
|
|
||||||
gfx->setTextSize(size);
|
|
||||||
gfx->setTextColor(color);
|
|
||||||
gfx->setCursor(x, y);
|
|
||||||
gfx->print(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawButton(int x, int y, int w, int h, uint16_t fill, const char *label, uint8_t size = 2) {
|
|
||||||
drawPanel(x, y, w, h, fill, C_BORDER, 12);
|
|
||||||
gfx->setFont();
|
|
||||||
gfx->setTextSize(size);
|
|
||||||
gfx->setTextColor(C_TEXT);
|
|
||||||
int textW = strlen(label) * 6 * size;
|
|
||||||
int textX = x + (w - textW) / 2;
|
|
||||||
if (textX < x + 8) {
|
|
||||||
textX = x + 8;
|
|
||||||
}
|
|
||||||
int textY = y + (h + 8 * size) / 2 - 2;
|
|
||||||
gfx->setCursor(textX, textY);
|
|
||||||
gfx->print(label);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawScreen() {
|
|
||||||
gfx->fillScreen(C_BG);
|
|
||||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
|
||||||
drawText(24, 42, "BUTTON LAYOUT TEST", C_TEXT, 2);
|
|
||||||
drawText(24, 70, "Check bottom and wide buttons", C_WARN, 1);
|
|
||||||
|
|
||||||
drawButton(20, 110, 136, 52, C_BUTTON, "STATUS");
|
|
||||||
drawButton(172, 110, 136, 52, C_BUTTON, "CONNECT");
|
|
||||||
drawButton(324, 110, 136, 52, C_BUTTON, "ACCOUNT");
|
|
||||||
|
|
||||||
drawButton(20, 180, 136, 52, C_BUTTON, "WALLET");
|
|
||||||
drawButton(172, 180, 136, 52, C_BUTTON, "REQUESTS");
|
|
||||||
drawButton(324, 180, 136, 52, C_BUTTON, "SETTINGS");
|
|
||||||
|
|
||||||
drawButton(20, 270, 212, 48, C_BUTTON2, "BACK");
|
|
||||||
drawButton(248, 270, 212, 48, C_OK, "REFRESH");
|
|
||||||
|
|
||||||
drawButton(20, 338, 440, 40, C_BUTTON2, "FULL WIDTH BUTTON", 2);
|
|
||||||
drawButton(20, 390, 440, 56, C_OK, "REGISTER DEVICE", 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
drawScreen();
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
delay(1000);
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include <U8g2lib.h>
|
|
||||||
|
|
||||||
#define PIN_LCD_CS 12
|
|
||||||
#define PIN_LCD_SCLK 38
|
|
||||||
#define PIN_LCD_D0 4
|
|
||||||
#define PIN_LCD_D1 5
|
|
||||||
#define PIN_LCD_D2 6
|
|
||||||
#define PIN_LCD_D3 7
|
|
||||||
#define PIN_LCD_RST 2
|
|
||||||
#define PIN_I2C_SDA 15
|
|
||||||
#define PIN_I2C_SCL 14
|
|
||||||
|
|
||||||
#define DISP_W 480
|
|
||||||
#define DISP_H 480
|
|
||||||
|
|
||||||
#define C_BG 0x0841u
|
|
||||||
#define C_PANEL 0x1082u
|
|
||||||
#define C_CARD 0x18C3u
|
|
||||||
#define C_BORDER 0x39C7u
|
|
||||||
#define C_TEXT 0xFFFFu
|
|
||||||
#define C_MUTE 0xBDF7u
|
|
||||||
#define C_OK 0x3666u
|
|
||||||
#define C_WARN 0xECA0u
|
|
||||||
#define C_BUTTON 0x2145u
|
|
||||||
#define C_BUTTON2 0x3186u
|
|
||||||
|
|
||||||
#define FONT_BODY u8g2_font_9x15_t_cyrillic
|
|
||||||
#define FONT_SMALL u8g2_font_6x13_t_cyrillic
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
|
|
||||||
gfx->fillRoundRect(x, y, w, h, radius, fill);
|
|
||||||
gfx->drawRoundRect(x, y, w, h, radius, border);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawDefaultText(int x, int y, const char *text, uint16_t color, uint8_t size = 1) {
|
|
||||||
gfx->setFont();
|
|
||||||
gfx->setTextSize(size);
|
|
||||||
gfx->setTextColor(color);
|
|
||||||
gfx->setCursor(x, y);
|
|
||||||
gfx->print(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawU8Text(int x, int y, const String &text, uint16_t color, const uint8_t *font) {
|
|
||||||
gfx->setTextSize(1);
|
|
||||||
gfx->setFont(font);
|
|
||||||
gfx->setTextColor(color);
|
|
||||||
gfx->setCursor(x, y);
|
|
||||||
gfx->print(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawButton(int x, int y, int w, int h, uint16_t fill, const String &label, const uint8_t *font, bool useDefaultFont = false) {
|
|
||||||
drawPanel(x, y, w, h, fill, C_BORDER, 12);
|
|
||||||
if (useDefaultFont) {
|
|
||||||
drawDefaultText(x + 14, y + 30, label.c_str(), C_TEXT, 2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
drawU8Text(x + 14, y + 32, label, C_TEXT, font);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawScreen() {
|
|
||||||
gfx->fillScreen(C_BG);
|
|
||||||
|
|
||||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
|
||||||
drawDefaultText(28, 42, "TEXT TEST 123", C_TEXT, 2);
|
|
||||||
drawU8Text(28, 72, "Default ASCII above", C_MUTE, (const uint8_t *)FONT_SMALL);
|
|
||||||
|
|
||||||
drawPanel(24, 90, 432, 72, C_CARD, C_BORDER, 12);
|
|
||||||
drawDefaultText(38, 118, "A: Default font ABC123", C_TEXT, 2);
|
|
||||||
drawDefaultText(38, 146, "Visible? then base path OK", C_WARN, 1);
|
|
||||||
|
|
||||||
drawPanel(24, 174, 432, 84, C_CARD, C_BORDER, 12);
|
|
||||||
drawU8Text(38, 204, "B: U8g2 ASCII abc123", C_TEXT, (const uint8_t *)FONT_BODY);
|
|
||||||
drawU8Text(38, 230, "C: Русский текст 123", C_OK, (const uint8_t *)FONT_BODY);
|
|
||||||
|
|
||||||
drawPanel(24, 270, 432, 84, C_CARD, C_BORDER, 12);
|
|
||||||
drawU8Text(38, 298, "D: Мелкий шрифт кнопок", C_TEXT, (const uint8_t *)FONT_SMALL);
|
|
||||||
drawU8Text(38, 320, "Если это видно, FONT_SMALL жив", C_MUTE, (const uint8_t *)FONT_SMALL);
|
|
||||||
|
|
||||||
drawButton(24, 368, 128, 72, C_BUTTON, "BTN 1", nullptr, true);
|
|
||||||
drawButton(176, 368, 128, 72, C_OK, "abc123", (const uint8_t *)FONT_BODY);
|
|
||||||
drawButton(328, 368, 128, 72, C_BUTTON2, "Русский", (const uint8_t *)FONT_BODY);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->setUTF8Print(true);
|
|
||||||
drawScreen();
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
delay(1000);
|
|
||||||
}
|
|
||||||
@@ -1,125 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include "pin_config.h"
|
|
||||||
|
|
||||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t gDrawBuf;
|
|
||||||
static lv_color_t *gBuf1 = nullptr;
|
|
||||||
static lv_color_t *gBuf2 = nullptr;
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void lvglRounderCb(lv_disp_drv_t *dispDrv, lv_area_t *area) {
|
|
||||||
LV_UNUSED(dispDrv);
|
|
||||||
if (area->x1 % 2 != 0) area->x1--;
|
|
||||||
if (area->y1 % 2 != 0) area->y1--;
|
|
||||||
if (area->x2 % 2 == 0) area->x2++;
|
|
||||||
if (area->y2 % 2 == 0) area->y2++;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
|
||||||
uint32_t w = area->x2 - area->x1 + 1;
|
|
||||||
uint32_t h = area->y2 - area->y1 + 1;
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#endif
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createUi() {
|
|
||||||
lv_obj_set_style_bg_color(lv_scr_act(), lv_color_hex(0x0B1320), 0);
|
|
||||||
lv_obj_set_style_bg_opa(lv_scr_act(), LV_OPA_COVER, 0);
|
|
||||||
|
|
||||||
lv_obj_t *title = lv_label_create(lv_scr_act());
|
|
||||||
lv_label_set_text(title, "LVGL BASIC TEST");
|
|
||||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
|
||||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 18);
|
|
||||||
|
|
||||||
lv_obj_t *subtitle = lv_label_create(lv_scr_act());
|
|
||||||
lv_label_set_text(subtitle, "If this text is visible, LVGL path works.");
|
|
||||||
lv_obj_set_width(subtitle, 420);
|
|
||||||
lv_label_set_long_mode(subtitle, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_color(subtitle, lv_color_hex(0xD5DCE5), 0);
|
|
||||||
lv_obj_set_style_text_font(subtitle, &lv_font_montserrat_16, 0);
|
|
||||||
lv_obj_align(subtitle, LV_ALIGN_TOP_MID, 0, 58);
|
|
||||||
|
|
||||||
const char *labels[3] = {"Button One", "Second Button", "Bottom Action"};
|
|
||||||
const lv_color_t colors[3] = {
|
|
||||||
lv_color_hex(0x2B4C7E),
|
|
||||||
lv_color_hex(0x2E8B57),
|
|
||||||
lv_color_hex(0xB45F06),
|
|
||||||
};
|
|
||||||
const lv_coord_t ys[3] = {150, 236, 340};
|
|
||||||
const lv_coord_t hs[3] = {58, 58, 64};
|
|
||||||
|
|
||||||
for (int i = 0; i < 3; i++) {
|
|
||||||
lv_obj_t *btn = lv_btn_create(lv_scr_act());
|
|
||||||
lv_obj_set_size(btn, 360, hs[i]);
|
|
||||||
lv_obj_align(btn, LV_ALIGN_TOP_MID, 0, ys[i]);
|
|
||||||
lv_obj_set_style_radius(btn, 14, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, colors[i], 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0x7F96B0), 0);
|
|
||||||
|
|
||||||
lv_obj_t *label = lv_label_create(btn);
|
|
||||||
lv_label_set_text(label, labels[i]);
|
|
||||||
lv_obj_set_style_text_font(label, &lv_font_montserrat_20, 0);
|
|
||||||
lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(label);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
uint32_t screenWidth = gfx->width();
|
|
||||||
uint32_t screenHeight = gfx->height();
|
|
||||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
|
||||||
|
|
||||||
static lv_disp_drv_t dispDrv;
|
|
||||||
lv_disp_drv_init(&dispDrv);
|
|
||||||
dispDrv.hor_res = screenWidth;
|
|
||||||
dispDrv.ver_res = screenHeight;
|
|
||||||
dispDrv.flush_cb = lvglFlushCb;
|
|
||||||
dispDrv.rounder_cb = lvglRounderCb;
|
|
||||||
dispDrv.draw_buf = &gDrawBuf;
|
|
||||||
lv_disp_drv_register(&dispDrv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
|
||||||
.callback = &lvglTick,
|
|
||||||
.name = "lvgl_tick"};
|
|
||||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
|
||||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
|
||||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
|
||||||
|
|
||||||
createUi();
|
|
||||||
Serial.println("LVGL basic test ready");
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include "pin_config.h"
|
|
||||||
#include "TouchDrvCSTXXX.hpp"
|
|
||||||
|
|
||||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t gDrawBuf;
|
|
||||||
static lv_color_t *gBuf1 = nullptr;
|
|
||||||
static lv_color_t *gBuf2 = nullptr;
|
|
||||||
static lv_obj_t *gStatusLabel = nullptr;
|
|
||||||
static uint32_t gPressCount = 0;
|
|
||||||
|
|
||||||
static TouchDrvCST92xx gTouch;
|
|
||||||
static int16_t gTouchX[5];
|
|
||||||
static int16_t gTouchY[5];
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
|
||||||
uint32_t w = area->x2 - area->x1 + 1;
|
|
||||||
uint32_t h = area->y2 - area->y1 + 1;
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#endif
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
|
||||||
LV_UNUSED(indevDrv);
|
|
||||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
|
||||||
if (touched > 0) {
|
|
||||||
data->state = LV_INDEV_STATE_PR;
|
|
||||||
data->point.x = gTouchX[0];
|
|
||||||
data->point.y = gTouchY[0];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void buttonEventCb(lv_event_t *event) {
|
|
||||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
lv_obj_t *btn = lv_event_get_target(event);
|
|
||||||
const char *name = (const char *)lv_event_get_user_data(event);
|
|
||||||
gPressCount++;
|
|
||||||
|
|
||||||
lv_obj_set_style_outline_width(btn, 4, 0);
|
|
||||||
lv_obj_set_style_outline_color(btn, lv_color_hex(0xFFF3B0), 0);
|
|
||||||
lv_obj_set_style_outline_pad(btn, 2, 0);
|
|
||||||
|
|
||||||
String status = "Pressed: ";
|
|
||||||
status += name;
|
|
||||||
status += " (#";
|
|
||||||
status += String(gPressCount);
|
|
||||||
status += ")";
|
|
||||||
lv_label_set_text(gStatusLabel, status.c_str());
|
|
||||||
|
|
||||||
Serial.println(status);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createButton(lv_obj_t *parent, const char *labelText, lv_coord_t col, lv_coord_t row, uint32_t colorHex) {
|
|
||||||
static const lv_coord_t kStartX = 22;
|
|
||||||
static const lv_coord_t kStartY = 122;
|
|
||||||
static const lv_coord_t kButtonW = 134;
|
|
||||||
static const lv_coord_t kButtonH = 64;
|
|
||||||
static const lv_coord_t kGapX = 18;
|
|
||||||
static const lv_coord_t kGapY = 16;
|
|
||||||
|
|
||||||
lv_obj_t *btn = lv_btn_create(parent);
|
|
||||||
lv_obj_set_size(btn, kButtonW, kButtonH);
|
|
||||||
lv_obj_set_pos(btn, kStartX + col * (kButtonW + kGapX), kStartY + row * (kButtonH + kGapY));
|
|
||||||
lv_obj_set_style_radius(btn, 16, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, lv_color_hex(colorHex), 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0x7F96B0), 0);
|
|
||||||
lv_obj_set_style_shadow_width(btn, 0, 0);
|
|
||||||
lv_obj_add_event_cb(btn, buttonEventCb, LV_EVENT_CLICKED, (void *)labelText);
|
|
||||||
|
|
||||||
lv_obj_t *label = lv_label_create(btn);
|
|
||||||
lv_label_set_text(label, labelText);
|
|
||||||
lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(label);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createUi() {
|
|
||||||
lv_obj_t *screen = lv_scr_act();
|
|
||||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
|
||||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
|
||||||
|
|
||||||
lv_obj_t *title = lv_label_create(screen);
|
|
||||||
lv_label_set_text(title, "LVGL INTERACTION TEST");
|
|
||||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
|
||||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 14);
|
|
||||||
|
|
||||||
lv_obj_t *subtitle = lv_label_create(screen);
|
|
||||||
lv_label_set_text(subtitle, "Tap buttons. Bottom label must change on every press.");
|
|
||||||
lv_obj_set_width(subtitle, 420);
|
|
||||||
lv_label_set_long_mode(subtitle, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_color(subtitle, lv_color_hex(0xD5DCE5), 0);
|
|
||||||
lv_obj_set_style_text_font(subtitle, &lv_font_montserrat_14, 0);
|
|
||||||
lv_obj_align(subtitle, LV_ALIGN_TOP_MID, 0, 48);
|
|
||||||
|
|
||||||
createButton(screen, "Status", 0, 0, 0x355C7D);
|
|
||||||
createButton(screen, "Connect", 1, 0, 0x2A9D8F);
|
|
||||||
createButton(screen, "Wallet", 2, 0, 0x457B9D);
|
|
||||||
createButton(screen, "Requests", 0, 1, 0xE76F51);
|
|
||||||
createButton(screen, "Settings", 1, 1, 0x8D5A97);
|
|
||||||
createButton(screen, "Register", 2, 1, 0x6A994E);
|
|
||||||
createButton(screen, "Approve", 0, 2, 0xBC6C25);
|
|
||||||
createButton(screen, "Reject", 1, 2, 0xB56576);
|
|
||||||
createButton(screen, "Back", 2, 2, 0x6C757D);
|
|
||||||
|
|
||||||
lv_obj_t *statusPanel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(statusPanel, 436, 56);
|
|
||||||
lv_obj_align(statusPanel, LV_ALIGN_BOTTOM_MID, 0, -16);
|
|
||||||
lv_obj_set_style_radius(statusPanel, 14, 0);
|
|
||||||
lv_obj_set_style_bg_color(statusPanel, lv_color_hex(0x162033), 0);
|
|
||||||
lv_obj_set_style_border_width(statusPanel, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(statusPanel, lv_color_hex(0x415A77), 0);
|
|
||||||
lv_obj_set_style_pad_all(statusPanel, 10, 0);
|
|
||||||
|
|
||||||
gStatusLabel = lv_label_create(statusPanel);
|
|
||||||
lv_label_set_text(gStatusLabel, "Pressed: none");
|
|
||||||
lv_obj_set_style_text_font(gStatusLabel, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gStatusLabel, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(gStatusLabel);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
pinMode(TP_RST, OUTPUT);
|
|
||||||
pinMode(TP_INT, INPUT);
|
|
||||||
digitalWrite(TP_RST, LOW);
|
|
||||||
delay(30);
|
|
||||||
digitalWrite(TP_RST, HIGH);
|
|
||||||
delay(50);
|
|
||||||
delay(1000);
|
|
||||||
|
|
||||||
gTouch.setPins(TP_RST, TP_INT);
|
|
||||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
|
||||||
if (!touchOk) {
|
|
||||||
Serial.println("Touch init failed");
|
|
||||||
} else {
|
|
||||||
Serial.print("Touch model: ");
|
|
||||||
Serial.println(gTouch.getModelName());
|
|
||||||
gTouch.sleep();
|
|
||||||
gTouch.reset();
|
|
||||||
gTouch.setMaxCoordinates(480, 480);
|
|
||||||
gTouch.setSwapXY(true);
|
|
||||||
gTouch.setMirrorXY(true, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->fillScreen(0x0000);
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
uint32_t screenWidth = gfx->width();
|
|
||||||
uint32_t screenHeight = gfx->height();
|
|
||||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
|
||||||
|
|
||||||
static lv_disp_drv_t dispDrv;
|
|
||||||
lv_disp_drv_init(&dispDrv);
|
|
||||||
dispDrv.hor_res = screenWidth;
|
|
||||||
dispDrv.ver_res = screenHeight;
|
|
||||||
dispDrv.flush_cb = lvglFlushCb;
|
|
||||||
dispDrv.draw_buf = &gDrawBuf;
|
|
||||||
lv_disp_drv_register(&dispDrv);
|
|
||||||
|
|
||||||
static lv_indev_drv_t indevDrv;
|
|
||||||
lv_indev_drv_init(&indevDrv);
|
|
||||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
|
||||||
indevDrv.read_cb = lvglTouchRead;
|
|
||||||
lv_indev_drv_register(&indevDrv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
|
||||||
.callback = &lvglTick,
|
|
||||||
.name = "lvgl_tick"};
|
|
||||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
|
||||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
|
||||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
|
||||||
|
|
||||||
createUi();
|
|
||||||
Serial.println("LVGL interaction test ready");
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
#include <lvgl.h>
|
|
||||||
#include "Arduino_GFX_Library.h"
|
|
||||||
#include "pin_config.h"
|
|
||||||
#include "TouchDrvCSTXXX.hpp"
|
|
||||||
#include "lv_conf.h"
|
|
||||||
#include "HWCDC.h"
|
|
||||||
#include <Wire.h>
|
|
||||||
|
|
||||||
HWCDC USBSerial;
|
|
||||||
|
|
||||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t draw_buf;
|
|
||||||
static lv_color_t *buf1 = nullptr;
|
|
||||||
static lv_color_t *buf2 = nullptr;
|
|
||||||
static lv_obj_t *status_label = nullptr;
|
|
||||||
static uint32_t click_count = 0;
|
|
||||||
|
|
||||||
Arduino_DataBus *bus = new Arduino_ESP32QSPI(
|
|
||||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
|
||||||
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
bus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
TouchDrvCST92xx touch;
|
|
||||||
int16_t touch_x[5], touch_y[5];
|
|
||||||
bool isPressed = false;
|
|
||||||
uint32_t screenWidth = 0;
|
|
||||||
uint32_t screenHeight = 0;
|
|
||||||
|
|
||||||
#if LV_USE_LOG != 0
|
|
||||||
void my_print(const char *buf) {
|
|
||||||
USBSerial.printf(buf);
|
|
||||||
USBSerial.flush();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
static void example_lvgl_rounder_cb(struct _lv_disp_drv_t *disp_drv, lv_area_t *area) {
|
|
||||||
LV_UNUSED(disp_drv);
|
|
||||||
if (area->x1 % 2 != 0) area->x1--;
|
|
||||||
if (area->y1 % 2 != 0) area->y1--;
|
|
||||||
if (area->x2 % 2 == 0) area->x2++;
|
|
||||||
if (area->y2 % 2 == 0) area->y2++;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p) {
|
|
||||||
uint32_t w = (area->x2 - area->x1 + 1);
|
|
||||||
uint32_t h = (area->y2 - area->y1 + 1);
|
|
||||||
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&color_p->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&color_p->full, w, h);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void example_increase_lvgl_tick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void my_touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data) {
|
|
||||||
LV_UNUSED(indev_driver);
|
|
||||||
if (isPressed) {
|
|
||||||
uint8_t touched = touch.getPoint(touch_x, touch_y, touch.getSupportTouchPoint());
|
|
||||||
if (touched) {
|
|
||||||
isPressed = false;
|
|
||||||
data->state = LV_INDEV_STATE_PR;
|
|
||||||
data->point.x = touch_x[0];
|
|
||||||
data->point.y = touch_y[0];
|
|
||||||
USBSerial.print("Touch x=");
|
|
||||||
USBSerial.print(touch_x[0]);
|
|
||||||
USBSerial.print(" y=");
|
|
||||||
USBSerial.println(touch_y[0]);
|
|
||||||
} else {
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void button_event_cb(lv_event_t *event) {
|
|
||||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char *name = (const char *)lv_event_get_user_data(event);
|
|
||||||
click_count++;
|
|
||||||
String text = "Pressed: ";
|
|
||||||
text += name;
|
|
||||||
text += " (#";
|
|
||||||
text += String(click_count);
|
|
||||||
text += ")";
|
|
||||||
lv_label_set_text(status_label, text.c_str());
|
|
||||||
USBSerial.println(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static lv_obj_t *make_button(lv_obj_t *parent, const char *label_text, lv_coord_t x, lv_coord_t y, lv_coord_t w, lv_coord_t h, lv_color_t bg) {
|
|
||||||
lv_obj_t *btn = lv_btn_create(parent);
|
|
||||||
lv_obj_set_size(btn, w, h);
|
|
||||||
lv_obj_set_pos(btn, x, y);
|
|
||||||
lv_obj_set_style_radius(btn, 16, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, bg, 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0x8AA4BF), 0);
|
|
||||||
lv_obj_set_style_shadow_width(btn, 0, 0);
|
|
||||||
lv_obj_add_event_cb(btn, button_event_cb, LV_EVENT_CLICKED, (void *)label_text);
|
|
||||||
|
|
||||||
lv_obj_t *label = lv_label_create(btn);
|
|
||||||
lv_label_set_text(label, label_text);
|
|
||||||
lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(label);
|
|
||||||
return btn;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void create_ui() {
|
|
||||||
lv_obj_t *screen = lv_scr_act();
|
|
||||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
|
||||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
|
||||||
|
|
||||||
lv_obj_t *title = lv_label_create(screen);
|
|
||||||
lv_label_set_text(title, "LVGL OFFICIAL BASED TEST");
|
|
||||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_20, 0);
|
|
||||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 14);
|
|
||||||
|
|
||||||
lv_obj_t *hint = lv_label_create(screen);
|
|
||||||
lv_label_set_text(hint, "Based on official LVGL_Widgets init. Tap buttons and watch the status.");
|
|
||||||
lv_obj_set_width(hint, 430);
|
|
||||||
lv_label_set_long_mode(hint, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
|
|
||||||
lv_obj_set_style_text_color(hint, lv_color_hex(0xD4DDE7), 0);
|
|
||||||
lv_obj_align(hint, LV_ALIGN_TOP_MID, 0, 44);
|
|
||||||
|
|
||||||
make_button(screen, "Status", 22, 120, 136, 60, lv_color_hex(0x355C7D));
|
|
||||||
make_button(screen, "Connect", 174, 120, 136, 60, lv_color_hex(0x2A9D8F));
|
|
||||||
make_button(screen, "Wallet", 326, 120, 132, 60, lv_color_hex(0x457B9D));
|
|
||||||
|
|
||||||
make_button(screen, "Requests", 22, 196, 136, 60, lv_color_hex(0xE76F51));
|
|
||||||
make_button(screen, "Settings",174, 196, 136, 60, lv_color_hex(0x8D5A97));
|
|
||||||
make_button(screen, "Register",326, 196, 132, 60, lv_color_hex(0x6A994E));
|
|
||||||
|
|
||||||
make_button(screen, "Approve", 22, 272, 136, 60, lv_color_hex(0xBC6C25));
|
|
||||||
make_button(screen, "Reject", 174, 272, 136, 60, lv_color_hex(0xB56576));
|
|
||||||
make_button(screen, "Back", 326, 272, 132, 60, lv_color_hex(0x6C757D));
|
|
||||||
|
|
||||||
lv_obj_t *bottom_btn = make_button(screen, "Bottom Action", 22, 350, 436, 64, lv_color_hex(0x1D6F42));
|
|
||||||
lv_obj_set_style_text_font(lv_obj_get_child(bottom_btn, 0), &lv_font_montserrat_20, 0);
|
|
||||||
|
|
||||||
lv_obj_t *status_panel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(status_panel, 436, 42);
|
|
||||||
lv_obj_set_pos(status_panel, 22, 426);
|
|
||||||
lv_obj_set_style_radius(status_panel, 12, 0);
|
|
||||||
lv_obj_set_style_bg_color(status_panel, lv_color_hex(0x17263A), 0);
|
|
||||||
lv_obj_set_style_border_width(status_panel, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(status_panel, lv_color_hex(0x496582), 0);
|
|
||||||
lv_obj_set_style_pad_all(status_panel, 6, 0);
|
|
||||||
|
|
||||||
status_label = lv_label_create(status_panel);
|
|
||||||
lv_label_set_text(status_label, "Pressed: none");
|
|
||||||
lv_obj_set_style_text_font(status_label, &lv_font_montserrat_16, 0);
|
|
||||||
lv_obj_set_style_text_color(status_label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(status_label);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
USBSerial.begin(115200);
|
|
||||||
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
digitalWrite(TP_RST, LOW);
|
|
||||||
delay(30);
|
|
||||||
digitalWrite(TP_RST, HIGH);
|
|
||||||
delay(50);
|
|
||||||
delay(1000);
|
|
||||||
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
touch.setPins(TP_RST, TP_INT);
|
|
||||||
bool result = touch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
|
||||||
if (result == false) {
|
|
||||||
USBSerial.println("touch is not online...");
|
|
||||||
while (1) delay(1000);
|
|
||||||
}
|
|
||||||
USBSerial.print("Touch model: ");
|
|
||||||
USBSerial.println(touch.getModelName());
|
|
||||||
touch.sleep();
|
|
||||||
touch.reset();
|
|
||||||
touch.setMaxCoordinates(480, 480);
|
|
||||||
touch.setSwapXY(true);
|
|
||||||
touch.setMirrorXY(true, false);
|
|
||||||
attachInterrupt(
|
|
||||||
TP_INT, []() {
|
|
||||||
isPressed = true;
|
|
||||||
},
|
|
||||||
FALLING);
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gfx->setBrightness(200);
|
|
||||||
bus->writeC8D8(0x36, 0xA0);
|
|
||||||
|
|
||||||
screenWidth = gfx->width();
|
|
||||||
screenHeight = gfx->height();
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
buf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
buf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
|
|
||||||
#if LV_USE_LOG != 0
|
|
||||||
lv_log_register_print_cb(my_print);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
lv_disp_draw_buf_init(&draw_buf, buf1, buf2, screenWidth * screenHeight / 4);
|
|
||||||
|
|
||||||
static lv_disp_drv_t disp_drv;
|
|
||||||
lv_disp_drv_init(&disp_drv);
|
|
||||||
disp_drv.hor_res = screenWidth;
|
|
||||||
disp_drv.ver_res = screenHeight;
|
|
||||||
disp_drv.flush_cb = my_disp_flush;
|
|
||||||
disp_drv.rounder_cb = example_lvgl_rounder_cb;
|
|
||||||
disp_drv.draw_buf = &draw_buf;
|
|
||||||
disp_drv.sw_rotate = 1;
|
|
||||||
lv_disp_drv_register(&disp_drv);
|
|
||||||
|
|
||||||
static lv_indev_drv_t indev_drv;
|
|
||||||
lv_indev_drv_init(&indev_drv);
|
|
||||||
indev_drv.type = LV_INDEV_TYPE_POINTER;
|
|
||||||
indev_drv.read_cb = my_touchpad_read;
|
|
||||||
lv_indev_drv_register(&indev_drv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t lvgl_tick_timer_args = {
|
|
||||||
.callback = &example_increase_lvgl_tick,
|
|
||||||
.name = "lvgl_tick"
|
|
||||||
};
|
|
||||||
|
|
||||||
esp_timer_handle_t lvgl_tick_timer = NULL;
|
|
||||||
esp_timer_create(&lvgl_tick_timer_args, &lvgl_tick_timer);
|
|
||||||
esp_timer_start_periodic(lvgl_tick_timer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
|
||||||
|
|
||||||
create_ui();
|
|
||||||
USBSerial.println("LVGL official based test ready");
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <lvgl.h>
|
|
||||||
LV_FONT_DECLARE(lv_font_ru_18);
|
|
||||||
LV_FONT_DECLARE(lv_font_ru_24);
|
|
||||||
@@ -1,264 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include <TouchDrvCSTXXX.hpp>
|
|
||||||
#include "lv_font_ru.h"
|
|
||||||
|
|
||||||
#define PIN_LCD_CS 12
|
|
||||||
#define PIN_LCD_SCLK 38
|
|
||||||
#define PIN_LCD_D0 4
|
|
||||||
#define PIN_LCD_D1 5
|
|
||||||
#define PIN_LCD_D2 6
|
|
||||||
#define PIN_LCD_D3 7
|
|
||||||
#define PIN_LCD_RST 2
|
|
||||||
#define PIN_I2C_SDA 15
|
|
||||||
#define PIN_I2C_SCL 14
|
|
||||||
#define PIN_TP_INT 11
|
|
||||||
|
|
||||||
#define DISP_W 480
|
|
||||||
#define DISP_H 480
|
|
||||||
#define LVGL_TICK_MS 2
|
|
||||||
#define TEST_VERSION "v1-ru-font"
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t gDrawBuf;
|
|
||||||
static lv_color_t *gBuf1 = nullptr;
|
|
||||||
static lv_color_t *gBuf2 = nullptr;
|
|
||||||
static lv_obj_t *gStatusLabel = nullptr;
|
|
||||||
static lv_obj_t *gTouchLabel = nullptr;
|
|
||||||
static uint32_t gClickCount = 0;
|
|
||||||
static bool gTouchActive = false;
|
|
||||||
static int16_t gLastX = -1;
|
|
||||||
static int16_t gLastY = -1;
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
TouchDrvCST92xx gTouch;
|
|
||||||
|
|
||||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
|
||||||
uint32_t w = area->x2 - area->x1 + 1;
|
|
||||||
uint32_t h = area->y2 - area->y1 + 1;
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#endif
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(LVGL_TICK_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void updateTouchLabel() {
|
|
||||||
if (!gTouchLabel) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
char text[96];
|
|
||||||
if (gTouchActive) {
|
|
||||||
snprintf(text, sizeof(text), "Касание: x=%d y=%d", gLastX, gLastY);
|
|
||||||
} else {
|
|
||||||
snprintf(text, sizeof(text), "Касание: нет x=%d y=%d", gLastX, gLastY);
|
|
||||||
}
|
|
||||||
lv_label_set_text(gTouchLabel, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
|
||||||
LV_UNUSED(indevDrv);
|
|
||||||
int16_t x = 0;
|
|
||||||
int16_t y = 0;
|
|
||||||
bool touching = gTouch.getPoint(&x, &y, 1) > 0;
|
|
||||||
|
|
||||||
if (touching) {
|
|
||||||
gTouchActive = true;
|
|
||||||
gLastX = x;
|
|
||||||
gLastY = y;
|
|
||||||
data->state = LV_INDEV_STATE_PR;
|
|
||||||
data->point.x = x;
|
|
||||||
data->point.y = y;
|
|
||||||
} else {
|
|
||||||
gTouchActive = false;
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
data->point.x = gLastX >= 0 ? gLastX : 0;
|
|
||||||
data->point.y = gLastY >= 0 ? gLastY : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateTouchLabel();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void buttonEventCb(lv_event_t *event) {
|
|
||||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char *name = (const char *)lv_event_get_user_data(event);
|
|
||||||
gClickCount++;
|
|
||||||
|
|
||||||
char text[128];
|
|
||||||
snprintf(text, sizeof(text), "Нажато: %s (%lu)", name, (unsigned long)gClickCount);
|
|
||||||
lv_label_set_text(gStatusLabel, text);
|
|
||||||
Serial.println(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static lv_obj_t *makeButton(lv_obj_t *parent,
|
|
||||||
const char *labelText,
|
|
||||||
lv_coord_t x,
|
|
||||||
lv_coord_t y,
|
|
||||||
lv_coord_t w,
|
|
||||||
lv_coord_t h,
|
|
||||||
uint32_t bgColor) {
|
|
||||||
lv_obj_t *btn = lv_btn_create(parent);
|
|
||||||
lv_obj_set_size(btn, w, h);
|
|
||||||
lv_obj_set_pos(btn, x, y);
|
|
||||||
lv_obj_set_style_radius(btn, 16, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, lv_color_hex(bgColor), 0);
|
|
||||||
lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0x6F8BA4), 0);
|
|
||||||
lv_obj_set_style_shadow_width(btn, 0, 0);
|
|
||||||
lv_obj_set_style_pad_all(btn, 4, 0);
|
|
||||||
lv_obj_add_event_cb(btn, buttonEventCb, LV_EVENT_CLICKED, (void *)labelText);
|
|
||||||
|
|
||||||
lv_obj_t *label = lv_label_create(btn);
|
|
||||||
lv_label_set_text(label, labelText);
|
|
||||||
lv_obj_set_width(label, w - 12);
|
|
||||||
lv_label_set_long_mode(label, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_align(label, LV_TEXT_ALIGN_CENTER, 0);
|
|
||||||
lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_set_style_text_font(label, &lv_font_ru_18, 0);
|
|
||||||
lv_obj_center(label);
|
|
||||||
return btn;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createUi() {
|
|
||||||
lv_obj_t *screen = lv_scr_act();
|
|
||||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x08131E), 0);
|
|
||||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_pad_all(screen, 0, 0);
|
|
||||||
lv_obj_set_scrollbar_mode(screen, LV_SCROLLBAR_MODE_OFF);
|
|
||||||
|
|
||||||
lv_obj_t *title = lv_label_create(screen);
|
|
||||||
lv_label_set_text(title, "Русский тест LVGL");
|
|
||||||
lv_obj_set_style_text_font(title, &lv_font_ru_24, 0);
|
|
||||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
|
|
||||||
|
|
||||||
lv_obj_t *version = lv_label_create(screen);
|
|
||||||
lv_label_set_text(version, "Версия: " TEST_VERSION);
|
|
||||||
lv_obj_set_style_text_font(version, &lv_font_ru_18, 0);
|
|
||||||
lv_obj_set_style_text_color(version, lv_color_hex(0xD8E0EA), 0);
|
|
||||||
lv_obj_align(version, LV_ALIGN_TOP_MID, 0, 42);
|
|
||||||
|
|
||||||
lv_obj_t *hint = lv_label_create(screen);
|
|
||||||
lv_label_set_text(hint, "Проверка кириллицы, длинных слов, кнопок и нажатий.");
|
|
||||||
lv_obj_set_width(hint, 436);
|
|
||||||
lv_label_set_long_mode(hint, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_font(hint, &lv_font_ru_18, 0);
|
|
||||||
lv_obj_set_style_text_color(hint, lv_color_hex(0xD8E0EA), 0);
|
|
||||||
lv_obj_align(hint, LV_ALIGN_TOP_MID, 0, 72);
|
|
||||||
|
|
||||||
makeButton(screen, "Статус", 22, 126, 136, 62, 0x355C7D);
|
|
||||||
makeButton(screen, "Подключение", 172, 126, 136, 62, 0x2A9D8F);
|
|
||||||
makeButton(screen, "Кошелёк", 322, 126, 136, 62, 0x457B9D);
|
|
||||||
|
|
||||||
makeButton(screen, "Запросы", 22, 204, 136, 62, 0xE76F51);
|
|
||||||
makeButton(screen, "Настройки", 172, 204, 136, 62, 0x8D5A97);
|
|
||||||
makeButton(screen, "Регистрация", 322, 204, 136, 62, 0x6A994E);
|
|
||||||
|
|
||||||
makeButton(screen, "Разрешить", 22, 282, 136, 62, 0xBC6C25);
|
|
||||||
makeButton(screen, "Отклонить", 172, 282, 136, 62, 0xB56576);
|
|
||||||
makeButton(screen, "Назад", 322, 282, 136, 62, 0x6C757D);
|
|
||||||
|
|
||||||
makeButton(screen, "Проверка переноса русского текста", 22, 360, 436, 64, 0x1D6F42);
|
|
||||||
|
|
||||||
lv_obj_t *statusPanel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(statusPanel, 436, 24);
|
|
||||||
lv_obj_set_pos(statusPanel, 22, 428);
|
|
||||||
lv_obj_set_style_radius(statusPanel, 10, 0);
|
|
||||||
lv_obj_set_style_bg_color(statusPanel, lv_color_hex(0x162435), 0);
|
|
||||||
lv_obj_set_style_bg_opa(statusPanel, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(statusPanel, 1, 0);
|
|
||||||
lv_obj_set_style_border_color(statusPanel, lv_color_hex(0x4D6986), 0);
|
|
||||||
lv_obj_set_style_pad_all(statusPanel, 2, 0);
|
|
||||||
|
|
||||||
gStatusLabel = lv_label_create(statusPanel);
|
|
||||||
lv_label_set_text(gStatusLabel, "Нажато: ничего");
|
|
||||||
lv_obj_set_style_text_font(gStatusLabel, &lv_font_ru_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gStatusLabel, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(gStatusLabel);
|
|
||||||
|
|
||||||
lv_obj_t *touchPanel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(touchPanel, 436, 24);
|
|
||||||
lv_obj_set_pos(touchPanel, 22, 454);
|
|
||||||
lv_obj_set_style_radius(touchPanel, 10, 0);
|
|
||||||
lv_obj_set_style_bg_color(touchPanel, lv_color_hex(0x162435), 0);
|
|
||||||
lv_obj_set_style_bg_opa(touchPanel, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(touchPanel, 1, 0);
|
|
||||||
lv_obj_set_style_border_color(touchPanel, lv_color_hex(0x4D6986), 0);
|
|
||||||
lv_obj_set_style_pad_all(touchPanel, 2, 0);
|
|
||||||
|
|
||||||
gTouchLabel = lv_label_create(touchPanel);
|
|
||||||
lv_label_set_text(gTouchLabel, "Касание: нет x=-1 y=-1");
|
|
||||||
lv_obj_set_style_text_font(gTouchLabel, &lv_font_ru_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gTouchLabel, lv_color_hex(0xD8E0EA), 0);
|
|
||||||
lv_obj_center(gTouchLabel);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->fillScreen(0x0000);
|
|
||||||
|
|
||||||
gTouch.setPins(PIN_TP_INT, -1);
|
|
||||||
gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
gTouch.setMaxCoordinates(DISP_W, DISP_H);
|
|
||||||
gTouch.setSwapXY(true);
|
|
||||||
gTouch.setMirrorXY(true, false);
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
uint32_t screenWidth = gfx->width();
|
|
||||||
uint32_t screenHeight = gfx->height();
|
|
||||||
uint32_t bufPixels = screenWidth * 40;
|
|
||||||
gBuf1 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
gBuf2 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
|
|
||||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, bufPixels);
|
|
||||||
|
|
||||||
static lv_disp_drv_t dispDrv;
|
|
||||||
lv_disp_drv_init(&dispDrv);
|
|
||||||
dispDrv.hor_res = screenWidth;
|
|
||||||
dispDrv.ver_res = screenHeight;
|
|
||||||
dispDrv.flush_cb = lvglFlushCb;
|
|
||||||
dispDrv.draw_buf = &gDrawBuf;
|
|
||||||
lv_disp_drv_register(&dispDrv);
|
|
||||||
|
|
||||||
static lv_indev_drv_t indevDrv;
|
|
||||||
lv_indev_drv_init(&indevDrv);
|
|
||||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
|
||||||
indevDrv.read_cb = lvglTouchRead;
|
|
||||||
lv_indev_drv_register(&indevDrv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t tickArgs = {
|
|
||||||
.callback = &lvglTick,
|
|
||||||
.name = "lvgl_tick"};
|
|
||||||
esp_timer_handle_t tickTimer = nullptr;
|
|
||||||
esp_timer_create(&tickArgs, &tickTimer);
|
|
||||||
esp_timer_start_periodic(tickTimer, LVGL_TICK_MS * 1000);
|
|
||||||
|
|
||||||
createUi();
|
|
||||||
Serial.println("Русский LVGL font test ready: " TEST_VERSION);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,256 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include <TouchDrvCSTXXX.hpp>
|
|
||||||
|
|
||||||
// Подтверждено на устройстве: LVGL-рендер работает вместе с touch-путём из shine_homeserver_ui.
|
|
||||||
|
|
||||||
#define PIN_LCD_CS 12
|
|
||||||
#define PIN_LCD_SCLK 38
|
|
||||||
#define PIN_LCD_D0 4
|
|
||||||
#define PIN_LCD_D1 5
|
|
||||||
#define PIN_LCD_D2 6
|
|
||||||
#define PIN_LCD_D3 7
|
|
||||||
#define PIN_LCD_RST 2
|
|
||||||
#define PIN_I2C_SDA 15
|
|
||||||
#define PIN_I2C_SCL 14
|
|
||||||
#define PIN_TP_INT 11
|
|
||||||
|
|
||||||
#define DISP_W 480
|
|
||||||
#define DISP_H 480
|
|
||||||
#define LVGL_TICK_MS 2
|
|
||||||
#define TEST_VERSION "v1-subtouch"
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t gDrawBuf;
|
|
||||||
static lv_color_t *gBuf1 = nullptr;
|
|
||||||
static lv_color_t *gBuf2 = nullptr;
|
|
||||||
static lv_obj_t *gStatusLabel = nullptr;
|
|
||||||
static lv_obj_t *gTouchLabel = nullptr;
|
|
||||||
static lv_obj_t *gVersionLabel = nullptr;
|
|
||||||
static uint32_t gClickCount = 0;
|
|
||||||
static bool gTouchActive = false;
|
|
||||||
static int16_t gLastX = -1;
|
|
||||||
static int16_t gLastY = -1;
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
TouchDrvCST92xx gTouch;
|
|
||||||
|
|
||||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
|
||||||
uint32_t w = area->x2 - area->x1 + 1;
|
|
||||||
uint32_t h = area->y2 - area->y1 + 1;
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#endif
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(LVGL_TICK_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void updateTouchLabel() {
|
|
||||||
if (!gTouchLabel) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
char text[96];
|
|
||||||
if (gTouchActive) {
|
|
||||||
snprintf(text, sizeof(text), "Touch: pressed x=%d y=%d", gLastX, gLastY);
|
|
||||||
} else {
|
|
||||||
snprintf(text, sizeof(text), "Touch: released x=%d y=%d", gLastX, gLastY);
|
|
||||||
}
|
|
||||||
lv_label_set_text(gTouchLabel, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
|
||||||
LV_UNUSED(indevDrv);
|
|
||||||
int16_t x = 0;
|
|
||||||
int16_t y = 0;
|
|
||||||
bool touching = gTouch.getPoint(&x, &y, 1) > 0;
|
|
||||||
|
|
||||||
if (touching) {
|
|
||||||
gTouchActive = true;
|
|
||||||
gLastX = x;
|
|
||||||
gLastY = y;
|
|
||||||
data->state = LV_INDEV_STATE_PR;
|
|
||||||
data->point.x = x;
|
|
||||||
data->point.y = y;
|
|
||||||
} else {
|
|
||||||
gTouchActive = false;
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
data->point.x = gLastX >= 0 ? gLastX : 0;
|
|
||||||
data->point.y = gLastY >= 0 ? gLastY : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateTouchLabel();
|
|
||||||
}
|
|
||||||
|
|
||||||
static void buttonEventCb(lv_event_t *event) {
|
|
||||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const char *name = (const char *)lv_event_get_user_data(event);
|
|
||||||
gClickCount++;
|
|
||||||
|
|
||||||
char text[96];
|
|
||||||
snprintf(text, sizeof(text), "Pressed: %s (#%lu)", name, (unsigned long)gClickCount);
|
|
||||||
lv_label_set_text(gStatusLabel, text);
|
|
||||||
Serial.println(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static lv_obj_t *makeButton(lv_obj_t *parent,
|
|
||||||
const char *labelText,
|
|
||||||
lv_coord_t x,
|
|
||||||
lv_coord_t y,
|
|
||||||
lv_coord_t w,
|
|
||||||
lv_coord_t h,
|
|
||||||
uint32_t bgColor) {
|
|
||||||
lv_obj_t *btn = lv_btn_create(parent);
|
|
||||||
lv_obj_set_size(btn, w, h);
|
|
||||||
lv_obj_set_pos(btn, x, y);
|
|
||||||
lv_obj_set_style_radius(btn, 16, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, lv_color_hex(bgColor), 0);
|
|
||||||
lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0x6F8BA4), 0);
|
|
||||||
lv_obj_set_style_shadow_width(btn, 0, 0);
|
|
||||||
lv_obj_add_event_cb(btn, buttonEventCb, LV_EVENT_CLICKED, (void *)labelText);
|
|
||||||
|
|
||||||
lv_obj_t *label = lv_label_create(btn);
|
|
||||||
lv_label_set_text(label, labelText);
|
|
||||||
lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_center(label);
|
|
||||||
return btn;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createUi() {
|
|
||||||
lv_obj_t *screen = lv_scr_act();
|
|
||||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x07111C), 0);
|
|
||||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_pad_all(screen, 0, 0);
|
|
||||||
lv_obj_set_scrollbar_mode(screen, LV_SCROLLBAR_MODE_OFF);
|
|
||||||
|
|
||||||
gVersionLabel = lv_label_create(screen);
|
|
||||||
lv_label_set_text(gVersionLabel, "LVGL + subserver touch " TEST_VERSION);
|
|
||||||
lv_obj_set_style_text_font(gVersionLabel, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gVersionLabel, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_align(gVersionLabel, LV_ALIGN_TOP_MID, 0, 12);
|
|
||||||
|
|
||||||
lv_obj_t *subtitle = lv_label_create(screen);
|
|
||||||
lv_label_set_text(subtitle, "Touch path comes from shine_homeserver_ui. Tap buttons and watch status.");
|
|
||||||
lv_obj_set_width(subtitle, 436);
|
|
||||||
lv_label_set_long_mode(subtitle, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_font(subtitle, &lv_font_montserrat_14, 0);
|
|
||||||
lv_obj_set_style_text_color(subtitle, lv_color_hex(0xD6DEE7), 0);
|
|
||||||
lv_obj_align(subtitle, LV_ALIGN_TOP_MID, 0, 42);
|
|
||||||
|
|
||||||
makeButton(screen, "Status", 22, 110, 136, 62, 0x355C7D);
|
|
||||||
makeButton(screen, "Connect", 172, 110, 136, 62, 0x2A9D8F);
|
|
||||||
makeButton(screen, "Wallet", 322, 110, 136, 62, 0x457B9D);
|
|
||||||
|
|
||||||
makeButton(screen, "Requests", 22, 188, 136, 62, 0xE76F51);
|
|
||||||
makeButton(screen, "Settings", 172, 188, 136, 62, 0x8D5A97);
|
|
||||||
makeButton(screen, "Register", 322, 188, 136, 62, 0x6A994E);
|
|
||||||
|
|
||||||
makeButton(screen, "Approve", 22, 266, 136, 62, 0xBC6C25);
|
|
||||||
makeButton(screen, "Reject", 172, 266, 136, 62, 0xB56576);
|
|
||||||
makeButton(screen, "Back", 322, 266, 136, 62, 0x6C757D);
|
|
||||||
|
|
||||||
makeButton(screen, "Bottom Action", 22, 346, 436, 68, 0x1D6F42);
|
|
||||||
|
|
||||||
lv_obj_t *statusPanel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(statusPanel, 436, 26);
|
|
||||||
lv_obj_set_pos(statusPanel, 22, 420);
|
|
||||||
lv_obj_set_style_radius(statusPanel, 10, 0);
|
|
||||||
lv_obj_set_style_bg_color(statusPanel, lv_color_hex(0x162435), 0);
|
|
||||||
lv_obj_set_style_bg_opa(statusPanel, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(statusPanel, 1, 0);
|
|
||||||
lv_obj_set_style_border_color(statusPanel, lv_color_hex(0x4D6986), 0);
|
|
||||||
lv_obj_set_style_pad_all(statusPanel, 2, 0);
|
|
||||||
|
|
||||||
gStatusLabel = lv_label_create(statusPanel);
|
|
||||||
lv_label_set_text(gStatusLabel, "Pressed: none");
|
|
||||||
lv_obj_set_style_text_font(gStatusLabel, &lv_font_montserrat_14, 0);
|
|
||||||
lv_obj_set_style_text_color(gStatusLabel, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(gStatusLabel);
|
|
||||||
|
|
||||||
lv_obj_t *touchPanel = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(touchPanel, 436, 26);
|
|
||||||
lv_obj_set_pos(touchPanel, 22, 450);
|
|
||||||
lv_obj_set_style_radius(touchPanel, 10, 0);
|
|
||||||
lv_obj_set_style_bg_color(touchPanel, lv_color_hex(0x162435), 0);
|
|
||||||
lv_obj_set_style_bg_opa(touchPanel, LV_OPA_COVER, 0);
|
|
||||||
lv_obj_set_style_border_width(touchPanel, 1, 0);
|
|
||||||
lv_obj_set_style_border_color(touchPanel, lv_color_hex(0x4D6986), 0);
|
|
||||||
lv_obj_set_style_pad_all(touchPanel, 2, 0);
|
|
||||||
|
|
||||||
gTouchLabel = lv_label_create(touchPanel);
|
|
||||||
lv_label_set_text(gTouchLabel, "Touch: released x=-1 y=-1");
|
|
||||||
lv_obj_set_style_text_font(gTouchLabel, &lv_font_montserrat_14, 0);
|
|
||||||
lv_obj_set_style_text_color(gTouchLabel, lv_color_hex(0xD6DEE7), 0);
|
|
||||||
lv_obj_center(gTouchLabel);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->fillScreen(0x0000);
|
|
||||||
|
|
||||||
gTouch.setPins(PIN_TP_INT, -1);
|
|
||||||
gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
gTouch.setMaxCoordinates(DISP_W, DISP_H);
|
|
||||||
gTouch.setSwapXY(true);
|
|
||||||
gTouch.setMirrorXY(true, false);
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
uint32_t screenWidth = gfx->width();
|
|
||||||
uint32_t screenHeight = gfx->height();
|
|
||||||
uint32_t bufPixels = screenWidth * 40;
|
|
||||||
gBuf1 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
gBuf2 = (lv_color_t *)heap_caps_malloc(bufPixels * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
|
|
||||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, bufPixels);
|
|
||||||
|
|
||||||
static lv_disp_drv_t dispDrv;
|
|
||||||
lv_disp_drv_init(&dispDrv);
|
|
||||||
dispDrv.hor_res = screenWidth;
|
|
||||||
dispDrv.ver_res = screenHeight;
|
|
||||||
dispDrv.flush_cb = lvglFlushCb;
|
|
||||||
dispDrv.draw_buf = &gDrawBuf;
|
|
||||||
lv_disp_drv_register(&dispDrv);
|
|
||||||
|
|
||||||
static lv_indev_drv_t indevDrv;
|
|
||||||
lv_indev_drv_init(&indevDrv);
|
|
||||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
|
||||||
indevDrv.read_cb = lvglTouchRead;
|
|
||||||
lv_indev_drv_register(&indevDrv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t tickArgs = {
|
|
||||||
.callback = &lvglTick,
|
|
||||||
.name = "lvgl_tick"};
|
|
||||||
esp_timer_handle_t tickTimer = nullptr;
|
|
||||||
esp_timer_create(&tickArgs, &tickTimer);
|
|
||||||
esp_timer_start_periodic(tickTimer, LVGL_TICK_MS * 1000);
|
|
||||||
|
|
||||||
createUi();
|
|
||||||
Serial.println("LVGL + subserver touch test ready: " TEST_VERSION);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include "pin_config.h"
|
|
||||||
#include "TouchDrvCSTXXX.hpp"
|
|
||||||
|
|
||||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
|
||||||
|
|
||||||
static lv_disp_draw_buf_t gDrawBuf;
|
|
||||||
static lv_color_t *gBuf1 = nullptr;
|
|
||||||
static lv_color_t *gBuf2 = nullptr;
|
|
||||||
static lv_obj_t *gRawLabel = nullptr;
|
|
||||||
static lv_obj_t *gEventLabel = nullptr;
|
|
||||||
static lv_obj_t *gMarker = nullptr;
|
|
||||||
|
|
||||||
static TouchDrvCST92xx gTouch;
|
|
||||||
static int16_t gTouchX[5];
|
|
||||||
static int16_t gTouchY[5];
|
|
||||||
static bool gTouchPressed = false;
|
|
||||||
static uint32_t gRawTouchCount = 0;
|
|
||||||
static uint32_t gLvglButtonCount = 0;
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
|
||||||
uint32_t w = area->x2 - area->x1 + 1;
|
|
||||||
uint32_t h = area->y2 - area->y1 + 1;
|
|
||||||
#if (LV_COLOR_16_SWAP != 0)
|
|
||||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#else
|
|
||||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
|
||||||
#endif
|
|
||||||
lv_disp_flush_ready(disp);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTick(void *arg) {
|
|
||||||
LV_UNUSED(arg);
|
|
||||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
|
||||||
LV_UNUSED(indevDrv);
|
|
||||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
|
||||||
if (touched > 0) {
|
|
||||||
data->state = LV_INDEV_STATE_PR;
|
|
||||||
data->point.x = gTouchX[0];
|
|
||||||
data->point.y = gTouchY[0];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
data->state = LV_INDEV_STATE_REL;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void bigButtonEventCb(lv_event_t *event) {
|
|
||||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
gLvglButtonCount++;
|
|
||||||
String status = "LVGL button clicked: ";
|
|
||||||
status += String(gLvglButtonCount);
|
|
||||||
lv_label_set_text(gEventLabel, status.c_str());
|
|
||||||
Serial.println(status);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void updateRawTouchState() {
|
|
||||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
|
||||||
if (touched > 0) {
|
|
||||||
gTouchPressed = true;
|
|
||||||
gRawTouchCount++;
|
|
||||||
|
|
||||||
String line1 = "RAW pressed";
|
|
||||||
String line2 = "x=" + String(gTouchX[0]) + " y=" + String(gTouchY[0]) + " n=" + String(gRawTouchCount);
|
|
||||||
String text = line1 + "\n" + line2;
|
|
||||||
lv_label_set_text(gRawLabel, text.c_str());
|
|
||||||
|
|
||||||
int markerX = gTouchX[0] - 8;
|
|
||||||
int markerY = gTouchY[0] - 8;
|
|
||||||
if (markerX < 0) markerX = 0;
|
|
||||||
if (markerY < 0) markerY = 0;
|
|
||||||
lv_obj_set_pos(gMarker, markerX, markerY);
|
|
||||||
lv_obj_clear_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (gTouchPressed) {
|
|
||||||
gTouchPressed = false;
|
|
||||||
lv_label_set_text(gRawLabel, "RAW released\nTouch ended");
|
|
||||||
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static void createUi() {
|
|
||||||
lv_obj_t *screen = lv_scr_act();
|
|
||||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x000000), 0);
|
|
||||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
|
||||||
|
|
||||||
lv_obj_t *title = lv_label_create(screen);
|
|
||||||
lv_label_set_text(title, "LVGL TOUCH DEBUG");
|
|
||||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
|
||||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 12);
|
|
||||||
|
|
||||||
gRawLabel = lv_label_create(screen);
|
|
||||||
lv_label_set_text(gRawLabel, "RAW released\nTouch not seen yet");
|
|
||||||
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0x9EE493), 0);
|
|
||||||
lv_obj_align(gRawLabel, LV_ALIGN_TOP_LEFT, 16, 56);
|
|
||||||
|
|
||||||
gEventLabel = lv_label_create(screen);
|
|
||||||
lv_label_set_text(gEventLabel, "LVGL button clicked: 0");
|
|
||||||
lv_obj_set_style_text_font(gEventLabel, &lv_font_montserrat_18, 0);
|
|
||||||
lv_obj_set_style_text_color(gEventLabel, lv_color_hex(0xFFD166), 0);
|
|
||||||
lv_obj_align(gEventLabel, LV_ALIGN_TOP_LEFT, 16, 118);
|
|
||||||
|
|
||||||
lv_obj_t *btn = lv_btn_create(screen);
|
|
||||||
lv_obj_set_size(btn, 360, 110);
|
|
||||||
lv_obj_align(btn, LV_ALIGN_CENTER, 0, 36);
|
|
||||||
lv_obj_set_style_radius(btn, 18, 0);
|
|
||||||
lv_obj_set_style_bg_color(btn, lv_color_hex(0x2A9D8F), 0);
|
|
||||||
lv_obj_set_style_border_width(btn, 3, 0);
|
|
||||||
lv_obj_set_style_border_color(btn, lv_color_hex(0xBDE0FE), 0);
|
|
||||||
lv_obj_add_event_cb(btn, bigButtonEventCb, LV_EVENT_CLICKED, nullptr);
|
|
||||||
|
|
||||||
lv_obj_t *btnLabel = lv_label_create(btn);
|
|
||||||
lv_label_set_text(btnLabel, "Tap Here");
|
|
||||||
lv_obj_set_style_text_font(btnLabel, &lv_font_montserrat_24, 0);
|
|
||||||
lv_obj_set_style_text_color(btnLabel, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_center(btnLabel);
|
|
||||||
|
|
||||||
lv_obj_t *hint = lv_label_create(screen);
|
|
||||||
lv_label_set_text(hint, "Need both: RAW coords change and LVGL button click.");
|
|
||||||
lv_obj_set_width(hint, 430);
|
|
||||||
lv_label_set_long_mode(hint, LV_LABEL_LONG_WRAP);
|
|
||||||
lv_obj_set_style_text_font(hint, &lv_font_montserrat_16, 0);
|
|
||||||
lv_obj_set_style_text_color(hint, lv_color_hex(0xD9D9D9), 0);
|
|
||||||
lv_obj_align(hint, LV_ALIGN_BOTTOM_MID, 0, -34);
|
|
||||||
|
|
||||||
gMarker = lv_obj_create(screen);
|
|
||||||
lv_obj_set_size(gMarker, 16, 16);
|
|
||||||
lv_obj_set_style_radius(gMarker, LV_RADIUS_CIRCLE, 0);
|
|
||||||
lv_obj_set_style_bg_color(gMarker, lv_color_hex(0xFF4D6D), 0);
|
|
||||||
lv_obj_set_style_border_width(gMarker, 2, 0);
|
|
||||||
lv_obj_set_style_border_color(gMarker, lv_color_hex(0xFFFFFF), 0);
|
|
||||||
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(IIC_SDA, IIC_SCL);
|
|
||||||
|
|
||||||
pinMode(TP_RST, OUTPUT);
|
|
||||||
pinMode(TP_INT, INPUT);
|
|
||||||
digitalWrite(TP_RST, LOW);
|
|
||||||
delay(30);
|
|
||||||
digitalWrite(TP_RST, HIGH);
|
|
||||||
delay(50);
|
|
||||||
delay(1000);
|
|
||||||
|
|
||||||
gTouch.setPins(TP_RST, TP_INT);
|
|
||||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
|
||||||
if (!touchOk) {
|
|
||||||
Serial.println("Touch init failed");
|
|
||||||
} else {
|
|
||||||
Serial.print("Touch model: ");
|
|
||||||
Serial.println(gTouch.getModelName());
|
|
||||||
gTouch.sleep();
|
|
||||||
gTouch.reset();
|
|
||||||
gTouch.setMaxCoordinates(480, 480);
|
|
||||||
gTouch.setSwapXY(true);
|
|
||||||
gTouch.setMirrorXY(true, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->fillScreen(0x0000);
|
|
||||||
|
|
||||||
lv_init();
|
|
||||||
|
|
||||||
uint32_t screenWidth = gfx->width();
|
|
||||||
uint32_t screenHeight = gfx->height();
|
|
||||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
|
||||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
|
||||||
|
|
||||||
static lv_disp_drv_t dispDrv;
|
|
||||||
lv_disp_drv_init(&dispDrv);
|
|
||||||
dispDrv.hor_res = screenWidth;
|
|
||||||
dispDrv.ver_res = screenHeight;
|
|
||||||
dispDrv.flush_cb = lvglFlushCb;
|
|
||||||
dispDrv.draw_buf = &gDrawBuf;
|
|
||||||
lv_disp_drv_register(&dispDrv);
|
|
||||||
|
|
||||||
static lv_indev_drv_t indevDrv;
|
|
||||||
lv_indev_drv_init(&indevDrv);
|
|
||||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
|
||||||
indevDrv.read_cb = lvglTouchRead;
|
|
||||||
lv_indev_drv_register(&indevDrv);
|
|
||||||
|
|
||||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
|
||||||
.callback = &lvglTick,
|
|
||||||
.name = "lvgl_tick"};
|
|
||||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
|
||||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
|
||||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
|
||||||
|
|
||||||
createUi();
|
|
||||||
Serial.println("LVGL touch debug test ready");
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
updateRawTouchState();
|
|
||||||
lv_timer_handler();
|
|
||||||
delay(5);
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include <U8g2lib.h>
|
|
||||||
|
|
||||||
#define PIN_LCD_CS 12
|
|
||||||
#define PIN_LCD_SCLK 38
|
|
||||||
#define PIN_LCD_D0 4
|
|
||||||
#define PIN_LCD_D1 5
|
|
||||||
#define PIN_LCD_D2 6
|
|
||||||
#define PIN_LCD_D3 7
|
|
||||||
#define PIN_LCD_RST 2
|
|
||||||
#define PIN_I2C_SDA 15
|
|
||||||
#define PIN_I2C_SCL 14
|
|
||||||
|
|
||||||
#define DISP_W 480
|
|
||||||
#define DISP_H 480
|
|
||||||
|
|
||||||
#define C_BG 0x0841u
|
|
||||||
#define C_PANEL 0x1082u
|
|
||||||
#define C_CARD 0x18C3u
|
|
||||||
#define C_BORDER 0x39C7u
|
|
||||||
#define C_TEXT 0xFFFFu
|
|
||||||
#define C_MUTE 0xBDF7u
|
|
||||||
#define C_OK 0x3666u
|
|
||||||
#define C_WARN 0xECA0u
|
|
||||||
#define C_BAD 0xD145u
|
|
||||||
#define C_BUTTON 0x2145u
|
|
||||||
#define C_BUTTON2 0x3186u
|
|
||||||
|
|
||||||
#define FONT_HEAD u8g2_font_10x20_t_cyrillic
|
|
||||||
#define FONT_BODY u8g2_font_9x15_t_cyrillic
|
|
||||||
#define FONT_SMALL u8g2_font_6x13_t_cyrillic
|
|
||||||
|
|
||||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
|
||||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
||||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
|
||||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
||||||
|
|
||||||
static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
|
|
||||||
gfx->fillRoundRect(x, y, w, h, radius, fill);
|
|
||||||
gfx->drawRoundRect(x, y, w, h, radius, border);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawDefaultText(int x, int y, const char *text, uint16_t color, uint8_t size = 1) {
|
|
||||||
gfx->setFont();
|
|
||||||
gfx->setTextSize(size);
|
|
||||||
gfx->setTextColor(color);
|
|
||||||
gfx->setCursor(x, y);
|
|
||||||
gfx->print(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawU8Text(int x, int y, const String &text, uint16_t color, const uint8_t *font) {
|
|
||||||
gfx->setTextSize(1);
|
|
||||||
gfx->setFont(font);
|
|
||||||
gfx->setTextColor(color);
|
|
||||||
gfx->setCursor(x, y);
|
|
||||||
gfx->print(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawButton(int x, int y, int w, int h, uint16_t fill, const String &label, const uint8_t *font, bool useDefaultFont = false) {
|
|
||||||
drawPanel(x, y, w, h, fill, C_BORDER, 12);
|
|
||||||
if (useDefaultFont) {
|
|
||||||
drawDefaultText(x + 14, y + 30, label.c_str(), C_TEXT, 2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
drawU8Text(x + 14, y + 32, label, C_TEXT, font);
|
|
||||||
}
|
|
||||||
|
|
||||||
static void drawScreen() {
|
|
||||||
gfx->fillScreen(C_BG);
|
|
||||||
|
|
||||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
|
||||||
drawDefaultText(28, 42, "TEXT TEST 123", C_TEXT, 2);
|
|
||||||
drawU8Text(28, 72, "Default ASCII above", C_MUTE, (const uint8_t *)FONT_SMALL);
|
|
||||||
|
|
||||||
drawPanel(24, 90, 432, 72, C_CARD, C_BORDER, 12);
|
|
||||||
drawDefaultText(38, 118, "A: Default font ABC123", C_TEXT, 2);
|
|
||||||
drawDefaultText(38, 146, "Visible? then base path OK", C_WARN, 1);
|
|
||||||
|
|
||||||
drawPanel(24, 174, 432, 84, C_CARD, C_BORDER, 12);
|
|
||||||
drawU8Text(38, 204, "B: U8g2 ASCII abc123", C_TEXT, (const uint8_t *)FONT_BODY);
|
|
||||||
drawU8Text(38, 230, "C: Русский текст 123", C_OK, (const uint8_t *)FONT_BODY);
|
|
||||||
|
|
||||||
drawPanel(24, 270, 432, 84, C_CARD, C_BORDER, 12);
|
|
||||||
drawU8Text(38, 298, "D: Мелкий шрифт кнопок", C_TEXT, (const uint8_t *)FONT_SMALL);
|
|
||||||
drawU8Text(38, 320, "Если это видно, FONT_SMALL жив", C_MUTE, (const uint8_t *)FONT_SMALL);
|
|
||||||
|
|
||||||
drawButton(24, 368, 128, 72, C_BUTTON, "BTN 1", nullptr, true);
|
|
||||||
drawButton(176, 368, 128, 72, C_OK, "abc123", (const uint8_t *)FONT_BODY);
|
|
||||||
drawButton(328, 368, 128, 72, C_BUTTON2, "Русский", (const uint8_t *)FONT_BODY);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Serial.begin(115200);
|
|
||||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
|
||||||
|
|
||||||
gfx->begin();
|
|
||||||
gBus->writeC8D8(0x36, 0xA0);
|
|
||||||
gfx->setBrightness(220);
|
|
||||||
gfx->setUTF8Print(true);
|
|
||||||
|
|
||||||
drawScreen();
|
|
||||||
|
|
||||||
Serial.println();
|
|
||||||
Serial.println("=== text_render_test ===");
|
|
||||||
Serial.println("A: default Arduino_GFX font");
|
|
||||||
Serial.println("B: U8g2 ASCII");
|
|
||||||
Serial.println("C: U8g2 Cyrillic");
|
|
||||||
Serial.println("Buttons: default / ASCII / Cyrillic");
|
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
|
||||||
delay(1000);
|
|
||||||
}
|
|
||||||
@@ -1,784 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file lv_conf.h
|
|
||||||
* Configuration file for v8.4.0
|
|
||||||
*/
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Copy this file as `lv_conf.h`
|
|
||||||
* 1. simply next to the `lvgl` folder
|
|
||||||
* 2. or any other places and
|
|
||||||
* - define `LV_CONF_INCLUDE_SIMPLE`
|
|
||||||
* - add the path as include path
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* clang-format off */
|
|
||||||
#if 1 /*Set it to "1" to enable content*/
|
|
||||||
|
|
||||||
#ifndef LV_CONF_H
|
|
||||||
#define LV_CONF_H
|
|
||||||
|
|
||||||
#include <stdint.h>
|
|
||||||
|
|
||||||
/*====================
|
|
||||||
COLOR SETTINGS
|
|
||||||
*====================*/
|
|
||||||
|
|
||||||
/*Color depth: 1 (1 byte per pixel), 8 (RGB332), 16 (RGB565), 32 (ARGB8888)*/
|
|
||||||
#define LV_COLOR_DEPTH 16
|
|
||||||
|
|
||||||
/*Swap the 2 bytes of RGB565 color. Useful if the display has an 8-bit interface (e.g. SPI)*/
|
|
||||||
#define LV_COLOR_16_SWAP 0
|
|
||||||
|
|
||||||
/*Enable features to draw on transparent background.
|
|
||||||
*It's required if opa, and transform_* style properties are used.
|
|
||||||
*Can be also used if the UI is above another layer, e.g. an OSD menu or video player.*/
|
|
||||||
#define LV_COLOR_SCREEN_TRANSP 0
|
|
||||||
|
|
||||||
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
|
|
||||||
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
|
|
||||||
#define LV_COLOR_MIX_ROUND_OFS 0
|
|
||||||
|
|
||||||
/*Images pixels with this color will not be drawn if they are chroma keyed)*/
|
|
||||||
#define LV_COLOR_CHROMA_KEY lv_color_hex(0x00ff00) /*pure green*/
|
|
||||||
|
|
||||||
/*=========================
|
|
||||||
MEMORY SETTINGS
|
|
||||||
*=========================*/
|
|
||||||
|
|
||||||
/*1: use custom malloc/free, 0: use the built-in `lv_mem_alloc()` and `lv_mem_free()`*/
|
|
||||||
#define LV_MEM_CUSTOM 0
|
|
||||||
#if LV_MEM_CUSTOM == 0
|
|
||||||
/*Size of the memory available for `lv_mem_alloc()` in bytes (>= 2kB)*/
|
|
||||||
#define LV_MEM_SIZE (48U * 1024U) /*[bytes]*/
|
|
||||||
|
|
||||||
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
|
|
||||||
#define LV_MEM_ADR 0 /*0: unused*/
|
|
||||||
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
|
|
||||||
#if LV_MEM_ADR == 0
|
|
||||||
#undef LV_MEM_POOL_INCLUDE
|
|
||||||
#undef LV_MEM_POOL_ALLOC
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#else /*LV_MEM_CUSTOM*/
|
|
||||||
#define LV_MEM_CUSTOM_INCLUDE <stdlib.h> /*Header for the dynamic memory function*/
|
|
||||||
#define LV_MEM_CUSTOM_ALLOC malloc
|
|
||||||
#define LV_MEM_CUSTOM_FREE free
|
|
||||||
#define LV_MEM_CUSTOM_REALLOC realloc
|
|
||||||
#endif /*LV_MEM_CUSTOM*/
|
|
||||||
|
|
||||||
/*Number of the intermediate memory buffer used during rendering and other internal processing mechanisms.
|
|
||||||
*You will see an error log message if there wasn't enough buffers. */
|
|
||||||
#define LV_MEM_BUF_MAX_NUM 16
|
|
||||||
|
|
||||||
/*Use the standard `memcpy` and `memset` instead of LVGL's own functions. (Might or might not be faster).*/
|
|
||||||
#define LV_MEMCPY_MEMSET_STD 0
|
|
||||||
|
|
||||||
/*====================
|
|
||||||
HAL SETTINGS
|
|
||||||
*====================*/
|
|
||||||
|
|
||||||
/*Default display refresh period. LVG will redraw changed areas with this period time*/
|
|
||||||
#define LV_DISP_DEF_REFR_PERIOD 10 /*[ms]*/
|
|
||||||
|
|
||||||
/*Input device read period in milliseconds*/
|
|
||||||
#define LV_INDEV_DEF_READ_PERIOD 10 /*[ms]*/
|
|
||||||
|
|
||||||
/*Use a custom tick source that tells the elapsed time in milliseconds.
|
|
||||||
*It removes the need to manually update the tick with `lv_tick_inc()`)*/
|
|
||||||
#define LV_TICK_CUSTOM 0
|
|
||||||
#if LV_TICK_CUSTOM
|
|
||||||
#define LV_TICK_CUSTOM_INCLUDE "Arduino.h" /*Header for the system time function*/
|
|
||||||
#define LV_TICK_CUSTOM_SYS_TIME_EXPR (millis()) /*Expression evaluating to current system time in ms*/
|
|
||||||
/*If using lvgl as ESP32 component*/
|
|
||||||
// #define LV_TICK_CUSTOM_INCLUDE "esp_timer.h"
|
|
||||||
// #define LV_TICK_CUSTOM_SYS_TIME_EXPR ((esp_timer_get_time() / 1000LL))
|
|
||||||
#endif /*LV_TICK_CUSTOM*/
|
|
||||||
|
|
||||||
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
|
|
||||||
*(Not so important, you can adjust it to modify default sizes and spaces)*/
|
|
||||||
#define LV_DPI_DEF 130 /*[px/inch]*/
|
|
||||||
|
|
||||||
/*=======================
|
|
||||||
* FEATURE CONFIGURATION
|
|
||||||
*=======================*/
|
|
||||||
|
|
||||||
/*-------------
|
|
||||||
* Drawing
|
|
||||||
*-----------*/
|
|
||||||
|
|
||||||
/*Enable complex draw engine.
|
|
||||||
*Required to draw shadow, gradient, rounded corners, circles, arc, skew lines, image transformations or any masks*/
|
|
||||||
#define LV_DRAW_COMPLEX 1
|
|
||||||
#if LV_DRAW_COMPLEX != 0
|
|
||||||
|
|
||||||
/*Allow buffering some shadow calculation.
|
|
||||||
*LV_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
|
|
||||||
*Caching has LV_SHADOW_CACHE_SIZE^2 RAM cost*/
|
|
||||||
#define LV_SHADOW_CACHE_SIZE 0
|
|
||||||
|
|
||||||
/* Set number of maximally cached circle data.
|
|
||||||
* The circumference of 1/4 circle are saved for anti-aliasing
|
|
||||||
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
|
|
||||||
* 0: to disable caching */
|
|
||||||
#define LV_CIRCLE_CACHE_SIZE 4
|
|
||||||
#endif /*LV_DRAW_COMPLEX*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Simple layers" are used when a widget has `style_opa < 255` to buffer the widget into a layer
|
|
||||||
* and blend it as an image with the given opacity.
|
|
||||||
* Note that `bg_opa`, `text_opa` etc don't require buffering into layer)
|
|
||||||
* The widget can be buffered in smaller chunks to avoid using large buffers.
|
|
||||||
*
|
|
||||||
* - LV_LAYER_SIMPLE_BUF_SIZE: [bytes] the optimal target buffer size. LVGL will try to allocate it
|
|
||||||
* - LV_LAYER_SIMPLE_FALLBACK_BUF_SIZE: [bytes] used if `LV_LAYER_SIMPLE_BUF_SIZE` couldn't be allocated.
|
|
||||||
*
|
|
||||||
* Both buffer sizes are in bytes.
|
|
||||||
* "Transformed layers" (where transform_angle/zoom properties are used) use larger buffers
|
|
||||||
* and can't be drawn in chunks. So these settings affects only widgets with opacity.
|
|
||||||
*/
|
|
||||||
#define LV_LAYER_SIMPLE_BUF_SIZE (24 * 1024)
|
|
||||||
#define LV_LAYER_SIMPLE_FALLBACK_BUF_SIZE (3 * 1024)
|
|
||||||
|
|
||||||
/*Default image cache size. Image caching keeps the images opened.
|
|
||||||
*If only the built-in image formats are used there is no real advantage of caching. (I.e. if no new image decoder is added)
|
|
||||||
*With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images.
|
|
||||||
*However the opened images might consume additional RAM.
|
|
||||||
*0: to disable caching*/
|
|
||||||
#define LV_IMG_CACHE_DEF_SIZE 0
|
|
||||||
|
|
||||||
/*Number of stops allowed per gradient. Increase this to allow more stops.
|
|
||||||
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
|
|
||||||
#define LV_GRADIENT_MAX_STOPS 2
|
|
||||||
|
|
||||||
/*Default gradient buffer size.
|
|
||||||
*When LVGL calculates the gradient "maps" it can save them into a cache to avoid calculating them again.
|
|
||||||
*LV_GRAD_CACHE_DEF_SIZE sets the size of this cache in bytes.
|
|
||||||
*If the cache is too small the map will be allocated only while it's required for the drawing.
|
|
||||||
*0 mean no caching.*/
|
|
||||||
#define LV_GRAD_CACHE_DEF_SIZE 0
|
|
||||||
|
|
||||||
/*Allow dithering the gradients (to achieve visual smooth color gradients on limited color depth display)
|
|
||||||
*LV_DITHER_GRADIENT implies allocating one or two more lines of the object's rendering surface
|
|
||||||
*The increase in memory consumption is (32 bits * object width) plus 24 bits * object width if using error diffusion */
|
|
||||||
#define LV_DITHER_GRADIENT 0
|
|
||||||
#if LV_DITHER_GRADIENT
|
|
||||||
/*Add support for error diffusion dithering.
|
|
||||||
*Error diffusion dithering gets a much better visual result, but implies more CPU consumption and memory when drawing.
|
|
||||||
*The increase in memory consumption is (24 bits * object's width)*/
|
|
||||||
#define LV_DITHER_ERROR_DIFFUSION 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Maximum buffer size to allocate for rotation.
|
|
||||||
*Only used if software rotation is enabled in the display driver.*/
|
|
||||||
#define LV_DISP_ROT_MAX_BUF (10*1024)
|
|
||||||
|
|
||||||
/*-------------
|
|
||||||
* GPU
|
|
||||||
*-----------*/
|
|
||||||
|
|
||||||
/*Use Arm's 2D acceleration library Arm-2D */
|
|
||||||
#define LV_USE_GPU_ARM2D 0
|
|
||||||
|
|
||||||
/*Use STM32's DMA2D (aka Chrom Art) GPU*/
|
|
||||||
#define LV_USE_GPU_STM32_DMA2D 0
|
|
||||||
#if LV_USE_GPU_STM32_DMA2D
|
|
||||||
/*Must be defined to include path of CMSIS header of target processor
|
|
||||||
e.g. "stm32f7xx.h" or "stm32f4xx.h"*/
|
|
||||||
#define LV_GPU_DMA2D_CMSIS_INCLUDE
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Enable RA6M3 G2D GPU*/
|
|
||||||
#define LV_USE_GPU_RA6M3_G2D 0
|
|
||||||
#if LV_USE_GPU_RA6M3_G2D
|
|
||||||
/*include path of target processor
|
|
||||||
e.g. "hal_data.h"*/
|
|
||||||
#define LV_GPU_RA6M3_G2D_INCLUDE "hal_data.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Use SWM341's DMA2D GPU*/
|
|
||||||
#define LV_USE_GPU_SWM341_DMA2D 0
|
|
||||||
#if LV_USE_GPU_SWM341_DMA2D
|
|
||||||
#define LV_GPU_SWM341_DMA2D_INCLUDE "SWM341.h"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Use NXP's PXP GPU iMX RTxxx platforms*/
|
|
||||||
#define LV_USE_GPU_NXP_PXP 0
|
|
||||||
#if LV_USE_GPU_NXP_PXP
|
|
||||||
/*1: Add default bare metal and FreeRTOS interrupt handling routines for PXP (lv_gpu_nxp_pxp_osa.c)
|
|
||||||
* and call lv_gpu_nxp_pxp_init() automatically during lv_init(). Note that symbol SDK_OS_FREE_RTOS
|
|
||||||
* has to be defined in order to use FreeRTOS OSA, otherwise bare-metal implementation is selected.
|
|
||||||
*0: lv_gpu_nxp_pxp_init() has to be called manually before lv_init()
|
|
||||||
*/
|
|
||||||
#define LV_USE_GPU_NXP_PXP_AUTO_INIT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Use NXP's VG-Lite GPU iMX RTxxx platforms*/
|
|
||||||
#define LV_USE_GPU_NXP_VG_LITE 0
|
|
||||||
|
|
||||||
/*Use SDL renderer API*/
|
|
||||||
#define LV_USE_GPU_SDL 0
|
|
||||||
#if LV_USE_GPU_SDL
|
|
||||||
#define LV_GPU_SDL_INCLUDE_PATH <SDL2/SDL.h>
|
|
||||||
/*Texture cache size, 8MB by default*/
|
|
||||||
#define LV_GPU_SDL_LRU_SIZE (1024 * 1024 * 8)
|
|
||||||
/*Custom blend mode for mask drawing, disable if you need to link with older SDL2 lib*/
|
|
||||||
#define LV_GPU_SDL_CUSTOM_BLEND_MODE (SDL_VERSION_ATLEAST(2, 0, 6))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*-------------
|
|
||||||
* Logging
|
|
||||||
*-----------*/
|
|
||||||
|
|
||||||
/*Enable the log module*/
|
|
||||||
#define LV_USE_LOG 0
|
|
||||||
#if LV_USE_LOG
|
|
||||||
|
|
||||||
/*How important log should be added:
|
|
||||||
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
|
|
||||||
*LV_LOG_LEVEL_INFO Log important events
|
|
||||||
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
|
|
||||||
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
|
|
||||||
*LV_LOG_LEVEL_USER Only logs added by the user
|
|
||||||
*LV_LOG_LEVEL_NONE Do not log anything*/
|
|
||||||
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
|
|
||||||
|
|
||||||
/*1: Print the log with 'printf';
|
|
||||||
*0: User need to register a callback with `lv_log_register_print_cb()`*/
|
|
||||||
#define LV_LOG_PRINTF 0
|
|
||||||
|
|
||||||
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
|
|
||||||
#define LV_LOG_TRACE_MEM 1
|
|
||||||
#define LV_LOG_TRACE_TIMER 1
|
|
||||||
#define LV_LOG_TRACE_INDEV 1
|
|
||||||
#define LV_LOG_TRACE_DISP_REFR 1
|
|
||||||
#define LV_LOG_TRACE_EVENT 1
|
|
||||||
#define LV_LOG_TRACE_OBJ_CREATE 1
|
|
||||||
#define LV_LOG_TRACE_LAYOUT 1
|
|
||||||
#define LV_LOG_TRACE_ANIM 1
|
|
||||||
|
|
||||||
#endif /*LV_USE_LOG*/
|
|
||||||
|
|
||||||
/*-------------
|
|
||||||
* Asserts
|
|
||||||
*-----------*/
|
|
||||||
|
|
||||||
/*Enable asserts if an operation is failed or an invalid data is found.
|
|
||||||
*If LV_USE_LOG is enabled an error message will be printed on failure*/
|
|
||||||
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
|
|
||||||
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
|
|
||||||
#define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/
|
|
||||||
#define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
|
|
||||||
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
|
|
||||||
|
|
||||||
/*Add a custom handler when assert happens e.g. to restart the MCU*/
|
|
||||||
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
|
|
||||||
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
|
|
||||||
|
|
||||||
/*-------------
|
|
||||||
* Others
|
|
||||||
*-----------*/
|
|
||||||
|
|
||||||
/*1: Show CPU usage and FPS count*/
|
|
||||||
#define LV_USE_PERF_MONITOR 0
|
|
||||||
#if LV_USE_PERF_MONITOR
|
|
||||||
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*1: Show the used memory and the memory fragmentation
|
|
||||||
* Requires LV_MEM_CUSTOM = 0*/
|
|
||||||
#define LV_USE_MEM_MONITOR 0
|
|
||||||
#if LV_USE_MEM_MONITOR
|
|
||||||
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*1: Draw random colored rectangles over the redrawn areas*/
|
|
||||||
#define LV_USE_REFR_DEBUG 0
|
|
||||||
|
|
||||||
/*Change the built in (v)snprintf functions*/
|
|
||||||
#define LV_SPRINTF_CUSTOM 0
|
|
||||||
#if LV_SPRINTF_CUSTOM
|
|
||||||
#define LV_SPRINTF_INCLUDE <stdio.h>
|
|
||||||
#define lv_snprintf snprintf
|
|
||||||
#define lv_vsnprintf vsnprintf
|
|
||||||
#else /*LV_SPRINTF_CUSTOM*/
|
|
||||||
#define LV_SPRINTF_USE_FLOAT 0
|
|
||||||
#endif /*LV_SPRINTF_CUSTOM*/
|
|
||||||
|
|
||||||
#define LV_USE_USER_DATA 1
|
|
||||||
|
|
||||||
/*Garbage Collector settings
|
|
||||||
*Used if lvgl is bound to higher level language and the memory is managed by that language*/
|
|
||||||
#define LV_ENABLE_GC 0
|
|
||||||
#if LV_ENABLE_GC != 0
|
|
||||||
#define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/
|
|
||||||
#endif /*LV_ENABLE_GC*/
|
|
||||||
|
|
||||||
/*=====================
|
|
||||||
* COMPILER SETTINGS
|
|
||||||
*====================*/
|
|
||||||
|
|
||||||
/*For big endian systems set to 1*/
|
|
||||||
#define LV_BIG_ENDIAN_SYSTEM 0
|
|
||||||
|
|
||||||
/*Define a custom attribute to `lv_tick_inc` function*/
|
|
||||||
#define LV_ATTRIBUTE_TICK_INC
|
|
||||||
|
|
||||||
/*Define a custom attribute to `lv_timer_handler` function*/
|
|
||||||
#define LV_ATTRIBUTE_TIMER_HANDLER
|
|
||||||
|
|
||||||
/*Define a custom attribute to `lv_disp_flush_ready` function*/
|
|
||||||
#define LV_ATTRIBUTE_FLUSH_READY
|
|
||||||
|
|
||||||
/*Required alignment size for buffers*/
|
|
||||||
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
|
|
||||||
|
|
||||||
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
|
|
||||||
* E.g. __attribute__((aligned(4)))*/
|
|
||||||
#define LV_ATTRIBUTE_MEM_ALIGN
|
|
||||||
|
|
||||||
/*Attribute to mark large constant arrays for example font's bitmaps*/
|
|
||||||
#define LV_ATTRIBUTE_LARGE_CONST
|
|
||||||
|
|
||||||
/*Compiler prefix for a big array declaration in RAM*/
|
|
||||||
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
|
|
||||||
|
|
||||||
/*Place performance critical functions into a faster memory (e.g RAM)*/
|
|
||||||
#define LV_ATTRIBUTE_FAST_MEM
|
|
||||||
|
|
||||||
/*Prefix variables that are used in GPU accelerated operations, often these need to be placed in RAM sections that are DMA accessible*/
|
|
||||||
#define LV_ATTRIBUTE_DMA
|
|
||||||
|
|
||||||
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
|
|
||||||
*should also appear on LVGL binding API such as Micropython.*/
|
|
||||||
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
|
|
||||||
|
|
||||||
/*Extend the default -32k..32k coordinate range to -4M..4M by using int32_t for coordinates instead of int16_t*/
|
|
||||||
#define LV_USE_LARGE_COORD 0
|
|
||||||
|
|
||||||
/*==================
|
|
||||||
* FONT USAGE
|
|
||||||
*===================*/
|
|
||||||
|
|
||||||
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
|
|
||||||
*https://fonts.google.com/specimen/Montserrat*/
|
|
||||||
#define LV_FONT_MONTSERRAT_8 1
|
|
||||||
#define LV_FONT_MONTSERRAT_10 1
|
|
||||||
#define LV_FONT_MONTSERRAT_12 1
|
|
||||||
#define LV_FONT_MONTSERRAT_14 1
|
|
||||||
#define LV_FONT_MONTSERRAT_16 1
|
|
||||||
#define LV_FONT_MONTSERRAT_18 1
|
|
||||||
#define LV_FONT_MONTSERRAT_20 1
|
|
||||||
#define LV_FONT_MONTSERRAT_22 1
|
|
||||||
#define LV_FONT_MONTSERRAT_24 1
|
|
||||||
#define LV_FONT_MONTSERRAT_26 1
|
|
||||||
#define LV_FONT_MONTSERRAT_28 1
|
|
||||||
#define LV_FONT_MONTSERRAT_30 1
|
|
||||||
#define LV_FONT_MONTSERRAT_32 1
|
|
||||||
#define LV_FONT_MONTSERRAT_34 1
|
|
||||||
#define LV_FONT_MONTSERRAT_36 1
|
|
||||||
#define LV_FONT_MONTSERRAT_38 1
|
|
||||||
#define LV_FONT_MONTSERRAT_40 1
|
|
||||||
#define LV_FONT_MONTSERRAT_42 1
|
|
||||||
#define LV_FONT_MONTSERRAT_44 1
|
|
||||||
#define LV_FONT_MONTSERRAT_46 1
|
|
||||||
#define LV_FONT_MONTSERRAT_48 1
|
|
||||||
|
|
||||||
/*Demonstrate special features*/
|
|
||||||
#define LV_FONT_MONTSERRAT_12_SUBPX 0
|
|
||||||
#define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/
|
|
||||||
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/
|
|
||||||
#define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/
|
|
||||||
|
|
||||||
/*Pixel perfect monospace fonts*/
|
|
||||||
#define LV_FONT_UNSCII_8 0
|
|
||||||
#define LV_FONT_UNSCII_16 0
|
|
||||||
|
|
||||||
/*Optionally declare custom fonts here.
|
|
||||||
*You can use these fonts as default font too and they will be available globally.
|
|
||||||
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
|
|
||||||
#define LV_FONT_CUSTOM_DECLARE
|
|
||||||
|
|
||||||
/*Always set a default font*/
|
|
||||||
#define LV_FONT_DEFAULT &lv_font_montserrat_14
|
|
||||||
|
|
||||||
/*Enable handling large font and/or fonts with a lot of characters.
|
|
||||||
*The limit depends on the font size, font face and bpp.
|
|
||||||
*Compiler error will be triggered if a font needs it.*/
|
|
||||||
#define LV_FONT_FMT_TXT_LARGE 0
|
|
||||||
|
|
||||||
/*Enables/disables support for compressed fonts.*/
|
|
||||||
#define LV_USE_FONT_COMPRESSED 0
|
|
||||||
|
|
||||||
/*Enable subpixel rendering*/
|
|
||||||
#define LV_USE_FONT_SUBPX 0
|
|
||||||
#if LV_USE_FONT_SUBPX
|
|
||||||
/*Set the pixel order of the display. Physical order of RGB channels. Doesn't matter with "normal" fonts.*/
|
|
||||||
#define LV_FONT_SUBPX_BGR 0 /*0: RGB; 1:BGR order*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Enable drawing placeholders when glyph dsc is not found*/
|
|
||||||
#define LV_USE_FONT_PLACEHOLDER 1
|
|
||||||
|
|
||||||
/*=================
|
|
||||||
* TEXT SETTINGS
|
|
||||||
*=================*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Select a character encoding for strings.
|
|
||||||
* Your IDE or editor should have the same character encoding
|
|
||||||
* - LV_TXT_ENC_UTF8
|
|
||||||
* - LV_TXT_ENC_ASCII
|
|
||||||
*/
|
|
||||||
#define LV_TXT_ENC LV_TXT_ENC_UTF8
|
|
||||||
|
|
||||||
/*Can break (wrap) texts on these chars*/
|
|
||||||
#define LV_TXT_BREAK_CHARS " ,.;:-_"
|
|
||||||
|
|
||||||
/*If a word is at least this long, will break wherever "prettiest"
|
|
||||||
*To disable, set to a value <= 0*/
|
|
||||||
#define LV_TXT_LINE_BREAK_LONG_LEN 0
|
|
||||||
|
|
||||||
/*Minimum number of characters in a long word to put on a line before a break.
|
|
||||||
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
|
|
||||||
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
|
|
||||||
|
|
||||||
/*Minimum number of characters in a long word to put on a line after a break.
|
|
||||||
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
|
|
||||||
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
|
|
||||||
|
|
||||||
/*The control character to use for signalling text recoloring.*/
|
|
||||||
#define LV_TXT_COLOR_CMD "#"
|
|
||||||
|
|
||||||
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
|
|
||||||
*The direction will be processed according to the Unicode Bidirectional Algorithm:
|
|
||||||
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
|
|
||||||
#define LV_USE_BIDI 0
|
|
||||||
#if LV_USE_BIDI
|
|
||||||
/*Set the default direction. Supported values:
|
|
||||||
*`LV_BASE_DIR_LTR` Left-to-Right
|
|
||||||
*`LV_BASE_DIR_RTL` Right-to-Left
|
|
||||||
*`LV_BASE_DIR_AUTO` detect texts base direction*/
|
|
||||||
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Enable Arabic/Persian processing
|
|
||||||
*In these languages characters should be replaced with an other form based on their position in the text*/
|
|
||||||
#define LV_USE_ARABIC_PERSIAN_CHARS 0
|
|
||||||
|
|
||||||
/*==================
|
|
||||||
* WIDGET USAGE
|
|
||||||
*================*/
|
|
||||||
|
|
||||||
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
|
|
||||||
|
|
||||||
#define LV_USE_ARC 1
|
|
||||||
|
|
||||||
#define LV_USE_BAR 1
|
|
||||||
|
|
||||||
#define LV_USE_BTN 1
|
|
||||||
|
|
||||||
#define LV_USE_BTNMATRIX 1
|
|
||||||
|
|
||||||
#define LV_USE_CANVAS 1
|
|
||||||
|
|
||||||
#define LV_USE_CHECKBOX 1
|
|
||||||
|
|
||||||
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
|
|
||||||
|
|
||||||
#define LV_USE_IMG 1 /*Requires: lv_label*/
|
|
||||||
|
|
||||||
#define LV_USE_LABEL 1
|
|
||||||
#if LV_USE_LABEL
|
|
||||||
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
|
|
||||||
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define LV_USE_LINE 1
|
|
||||||
|
|
||||||
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
|
|
||||||
#if LV_USE_ROLLER
|
|
||||||
#define LV_ROLLER_INF_PAGES 7 /*Number of extra "pages" when the roller is infinite*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
|
|
||||||
|
|
||||||
#define LV_USE_SWITCH 1
|
|
||||||
|
|
||||||
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
|
|
||||||
#if LV_USE_TEXTAREA != 0
|
|
||||||
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define LV_USE_TABLE 1
|
|
||||||
|
|
||||||
/*==================
|
|
||||||
* EXTRA COMPONENTS
|
|
||||||
*==================*/
|
|
||||||
|
|
||||||
/*-----------
|
|
||||||
* Widgets
|
|
||||||
*----------*/
|
|
||||||
#define LV_USE_ANIMIMG 1
|
|
||||||
|
|
||||||
#define LV_USE_CALENDAR 1
|
|
||||||
#if LV_USE_CALENDAR
|
|
||||||
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
|
|
||||||
#if LV_CALENDAR_WEEK_STARTS_MONDAY
|
|
||||||
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
|
|
||||||
#else
|
|
||||||
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
|
|
||||||
#define LV_USE_CALENDAR_HEADER_ARROW 1
|
|
||||||
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
|
|
||||||
#endif /*LV_USE_CALENDAR*/
|
|
||||||
|
|
||||||
#define LV_USE_CHART 1
|
|
||||||
|
|
||||||
#define LV_USE_COLORWHEEL 1
|
|
||||||
|
|
||||||
#define LV_USE_IMGBTN 1
|
|
||||||
|
|
||||||
#define LV_USE_KEYBOARD 1
|
|
||||||
|
|
||||||
#define LV_USE_LED 1
|
|
||||||
|
|
||||||
#define LV_USE_LIST 1
|
|
||||||
|
|
||||||
#define LV_USE_MENU 1
|
|
||||||
|
|
||||||
#define LV_USE_METER 1
|
|
||||||
|
|
||||||
#define LV_USE_MSGBOX 1
|
|
||||||
|
|
||||||
#define LV_USE_SPAN 1
|
|
||||||
#if LV_USE_SPAN
|
|
||||||
/*A line text can contain maximum num of span descriptor */
|
|
||||||
#define LV_SPAN_SNIPPET_STACK_SIZE 64
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define LV_USE_SPINBOX 1
|
|
||||||
|
|
||||||
#define LV_USE_SPINNER 1
|
|
||||||
|
|
||||||
#define LV_USE_TABVIEW 1
|
|
||||||
|
|
||||||
#define LV_USE_TILEVIEW 1
|
|
||||||
|
|
||||||
#define LV_USE_WIN 1
|
|
||||||
|
|
||||||
/*-----------
|
|
||||||
* Themes
|
|
||||||
*----------*/
|
|
||||||
|
|
||||||
/*A simple, impressive and very complete theme*/
|
|
||||||
#define LV_USE_THEME_DEFAULT 1
|
|
||||||
#if LV_USE_THEME_DEFAULT
|
|
||||||
|
|
||||||
/*0: Light mode; 1: Dark mode*/
|
|
||||||
#define LV_THEME_DEFAULT_DARK 0
|
|
||||||
|
|
||||||
/*1: Enable grow on press*/
|
|
||||||
#define LV_THEME_DEFAULT_GROW 1
|
|
||||||
|
|
||||||
/*Default transition time in [ms]*/
|
|
||||||
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
|
|
||||||
#endif /*LV_USE_THEME_DEFAULT*/
|
|
||||||
|
|
||||||
/*A very simple theme that is a good starting point for a custom theme*/
|
|
||||||
#define LV_USE_THEME_BASIC 1
|
|
||||||
|
|
||||||
/*A theme designed for monochrome displays*/
|
|
||||||
#define LV_USE_THEME_MONO 1
|
|
||||||
|
|
||||||
/*-----------
|
|
||||||
* Layouts
|
|
||||||
*----------*/
|
|
||||||
|
|
||||||
/*A layout similar to Flexbox in CSS.*/
|
|
||||||
#define LV_USE_FLEX 1
|
|
||||||
|
|
||||||
/*A layout similar to Grid in CSS.*/
|
|
||||||
#define LV_USE_GRID 1
|
|
||||||
|
|
||||||
/*---------------------
|
|
||||||
* 3rd party libraries
|
|
||||||
*--------------------*/
|
|
||||||
|
|
||||||
/*File system interfaces for common APIs */
|
|
||||||
|
|
||||||
/*API for fopen, fread, etc*/
|
|
||||||
#define LV_USE_FS_STDIO 0
|
|
||||||
#if LV_USE_FS_STDIO
|
|
||||||
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
|
||||||
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
|
||||||
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*API for open, read, etc*/
|
|
||||||
#define LV_USE_FS_POSIX 0
|
|
||||||
#if LV_USE_FS_POSIX
|
|
||||||
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
|
||||||
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
|
||||||
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*API for CreateFile, ReadFile, etc*/
|
|
||||||
#define LV_USE_FS_WIN32 0
|
|
||||||
#if LV_USE_FS_WIN32
|
|
||||||
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
|
||||||
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
|
||||||
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
|
|
||||||
#define LV_USE_FS_FATFS 0
|
|
||||||
#if LV_USE_FS_FATFS
|
|
||||||
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
|
||||||
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*API for LittleFS (library needs to be added separately). Uses lfs_file_open, lfs_file_read, etc*/
|
|
||||||
#define LV_USE_FS_LITTLEFS 0
|
|
||||||
#if LV_USE_FS_LITTLEFS
|
|
||||||
#define LV_FS_LITTLEFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
|
||||||
#define LV_FS_LITTLEFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*PNG decoder library*/
|
|
||||||
#define LV_USE_PNG 0
|
|
||||||
|
|
||||||
/*BMP decoder library*/
|
|
||||||
#define LV_USE_BMP 0
|
|
||||||
|
|
||||||
/* JPG + split JPG decoder library.
|
|
||||||
* Split JPG is a custom format optimized for embedded systems. */
|
|
||||||
#define LV_USE_SJPG 0
|
|
||||||
|
|
||||||
/*GIF decoder library*/
|
|
||||||
#define LV_USE_GIF 0
|
|
||||||
|
|
||||||
/*QR code library*/
|
|
||||||
#define LV_USE_QRCODE 1
|
|
||||||
|
|
||||||
/*FreeType library*/
|
|
||||||
#define LV_USE_FREETYPE 0
|
|
||||||
#if LV_USE_FREETYPE
|
|
||||||
/*Memory used by FreeType to cache characters [bytes] (-1: no caching)*/
|
|
||||||
#define LV_FREETYPE_CACHE_SIZE (16 * 1024)
|
|
||||||
#if LV_FREETYPE_CACHE_SIZE >= 0
|
|
||||||
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
|
|
||||||
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
|
|
||||||
/* if font size >= 256, must be configured as image cache */
|
|
||||||
#define LV_FREETYPE_SBIT_CACHE 0
|
|
||||||
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
|
|
||||||
/* (0:use system defaults) */
|
|
||||||
#define LV_FREETYPE_CACHE_FT_FACES 0
|
|
||||||
#define LV_FREETYPE_CACHE_FT_SIZES 0
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Tiny TTF library*/
|
|
||||||
#define LV_USE_TINY_TTF 0
|
|
||||||
#if LV_USE_TINY_TTF
|
|
||||||
/*Load TTF data from files*/
|
|
||||||
#define LV_TINY_TTF_FILE_SUPPORT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Rlottie library*/
|
|
||||||
#define LV_USE_RLOTTIE 0
|
|
||||||
|
|
||||||
/*FFmpeg library for image decoding and playing videos
|
|
||||||
*Supports all major image formats so do not enable other image decoder with it*/
|
|
||||||
#define LV_USE_FFMPEG 0
|
|
||||||
#if LV_USE_FFMPEG
|
|
||||||
/*Dump input information to stderr*/
|
|
||||||
#define LV_FFMPEG_DUMP_FORMAT 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*-----------
|
|
||||||
* Others
|
|
||||||
*----------*/
|
|
||||||
|
|
||||||
/*1: Enable API to take snapshot for object*/
|
|
||||||
#define LV_USE_SNAPSHOT 0
|
|
||||||
|
|
||||||
/*1: Enable Monkey test*/
|
|
||||||
#define LV_USE_MONKEY 0
|
|
||||||
|
|
||||||
/*1: Enable grid navigation*/
|
|
||||||
#define LV_USE_GRIDNAV 0
|
|
||||||
|
|
||||||
/*1: Enable lv_obj fragment*/
|
|
||||||
#define LV_USE_FRAGMENT 0
|
|
||||||
|
|
||||||
/*1: Support using images as font in label or span widgets */
|
|
||||||
#define LV_USE_IMGFONT 0
|
|
||||||
|
|
||||||
/*1: Enable a published subscriber based messaging system */
|
|
||||||
#define LV_USE_MSG 0
|
|
||||||
|
|
||||||
/*1: Enable Pinyin input method*/
|
|
||||||
/*Requires: lv_keyboard*/
|
|
||||||
#define LV_USE_IME_PINYIN 0
|
|
||||||
#if LV_USE_IME_PINYIN
|
|
||||||
/*1: Use default thesaurus*/
|
|
||||||
/*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesauruss*/
|
|
||||||
#define LV_IME_PINYIN_USE_DEFAULT_DICT 1
|
|
||||||
/*Set the maximum number of candidate panels that can be displayed*/
|
|
||||||
/*This needs to be adjusted according to the size of the screen*/
|
|
||||||
#define LV_IME_PINYIN_CAND_TEXT_NUM 6
|
|
||||||
|
|
||||||
/*Use 9 key input(k9)*/
|
|
||||||
#define LV_IME_PINYIN_USE_K9_MODE 1
|
|
||||||
#if LV_IME_PINYIN_USE_K9_MODE == 1
|
|
||||||
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3
|
|
||||||
#endif // LV_IME_PINYIN_USE_K9_MODE
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*==================
|
|
||||||
* EXAMPLES
|
|
||||||
*==================*/
|
|
||||||
|
|
||||||
/*Enable the examples to be built with the library*/
|
|
||||||
#define LV_BUILD_EXAMPLES 1
|
|
||||||
|
|
||||||
/*===================
|
|
||||||
* DEMO USAGE
|
|
||||||
====================*/
|
|
||||||
|
|
||||||
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
|
|
||||||
#define LV_USE_DEMO_WIDGETS 1
|
|
||||||
#if LV_USE_DEMO_WIDGETS
|
|
||||||
#define LV_DEMO_WIDGETS_SLIDESHOW 1
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Demonstrate the usage of encoder and keyboard*/
|
|
||||||
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 0
|
|
||||||
|
|
||||||
/*Benchmark your system*/
|
|
||||||
#define LV_USE_DEMO_BENCHMARK 1
|
|
||||||
#if LV_USE_DEMO_BENCHMARK
|
|
||||||
/*Use RGB565A8 images with 16 bit color depth instead of ARGB8565*/
|
|
||||||
#define LV_DEMO_BENCHMARK_RGB565A8 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*Stress test for LVGL*/
|
|
||||||
#define LV_USE_DEMO_STRESS 1
|
|
||||||
|
|
||||||
/*Music player demo*/
|
|
||||||
#define LV_USE_DEMO_MUSIC 1
|
|
||||||
#if LV_USE_DEMO_MUSIC
|
|
||||||
#define LV_DEMO_MUSIC_SQUARE 0
|
|
||||||
#define LV_DEMO_MUSIC_LANDSCAPE 0
|
|
||||||
#define LV_DEMO_MUSIC_ROUND 0
|
|
||||||
#define LV_DEMO_MUSIC_LARGE 0
|
|
||||||
#define LV_DEMO_MUSIC_AUTO_PLAY 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/*--END OF LV_CONF_H--*/
|
|
||||||
|
|
||||||
#endif /*LV_CONF_H*/
|
|
||||||
|
|
||||||
#endif /*End of "Content enable"*/
|
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
|
// Remote AddBlock body is the existing type/subtype/version + semantic body.
|
||||||
|
// This helper has no network/state dependencies; hashes and Ed25519 are supplied
|
||||||
|
// by the existing firmware crypto libraries (or the offline vector test).
|
||||||
|
namespace shine_core {
|
||||||
|
using Bytes = std::vector<uint8_t>;
|
||||||
|
using Hash = bool (*)(const uint8_t*, size_t, uint8_t*);
|
||||||
|
using Sign = bool (*)(const Bytes&, const uint8_t*, uint8_t*);
|
||||||
|
inline void putBE(Bytes& out, uint64_t n, unsigned count) {
|
||||||
|
for (unsigned i=count; i>0; --i) out.push_back(uint8_t(n >> ((i-1)*8)));
|
||||||
|
}
|
||||||
|
inline void putLE(Bytes& out, uint64_t n, unsigned count) {
|
||||||
|
for (unsigned i=0; i<count; ++i) out.push_back(uint8_t(n >> (i*8)));
|
||||||
|
}
|
||||||
|
inline uint32_t getBE(const uint8_t* p) {
|
||||||
|
return (uint32_t(p[0])<<24)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<8)|p[3];
|
||||||
|
}
|
||||||
|
inline Bytes text(const std::string& s) { return Bytes(s.begin(),s.end()); }
|
||||||
|
inline void avroLong(Bytes& out, size_t n) {
|
||||||
|
uint64_t x=uint64_t(n)*2;
|
||||||
|
while (x>=128) { out.push_back(uint8_t(x)|0x80); x>>=7; }
|
||||||
|
out.push_back(uint8_t(x));
|
||||||
|
}
|
||||||
|
inline void avroString(Bytes& out,const std::string& s) {
|
||||||
|
avroLong(out,s.size());out.insert(out.end(),s.begin(),s.end());
|
||||||
|
}
|
||||||
|
inline bool deepBlob(const Bytes& data,Hash sha384,uint8_t* out) {
|
||||||
|
Bytes tag=text("blob"+std::to_string(data.size()));uint8_t pair[96];
|
||||||
|
return sha384(tag.data(),tag.size(),pair)&&sha384(data.data(),data.size(),pair+48)&&sha384(pair,96,out);
|
||||||
|
}
|
||||||
|
inline bool makeItem(const Bytes& data,const Bytes& tags,size_t count,const uint8_t* owner,const uint8_t* secret,
|
||||||
|
Hash sha384,Sign sign,Bytes& out) {
|
||||||
|
const Bytes children[]={text("dataitem"),text("1"),text("2"),Bytes(owner,owner+32),Bytes(),Bytes(),tags,data};
|
||||||
|
const Bytes list=text("list8");uint8_t acc[48],pair[96],sig[64];
|
||||||
|
if(!sha384(list.data(),list.size(),acc))return false;
|
||||||
|
for(const Bytes& child:children){
|
||||||
|
std::copy(acc,acc+48,pair);
|
||||||
|
if(!deepBlob(child,sha384,pair+48)||!sha384(pair,96,acc))return false;
|
||||||
|
}
|
||||||
|
if(!sign(Bytes(acc,acc+48),secret,sig))return false;
|
||||||
|
out.clear();putLE(out,2,2);out.insert(out.end(),sig,sig+64);out.insert(out.end(),owner,owner+32);
|
||||||
|
out.push_back(0);out.push_back(0);putLE(out,count,8);putLE(out,tags.size(),8);
|
||||||
|
out.insert(out.end(),tags.begin(),tags.end());out.insert(out.end(),data.begin(),data.end());return true;
|
||||||
|
}
|
||||||
|
inline bool buildPair(uint16_t type,uint16_t subtype,uint16_t version,const Bytes& body,
|
||||||
|
uint32_t number,uint64_t timestamp,const uint8_t* prev,const uint8_t* owner,const uint8_t* secret,
|
||||||
|
const std::string& app,Hash sha256,Hash sha384,Sign sign,Bytes& out) {
|
||||||
|
constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647;
|
||||||
|
const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4;
|
||||||
|
const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130);
|
||||||
|
if((version!=1&&!(header&&(version==2||version==3)))||number>MAX_NUMBER||header!=(number==0)||(type==0&&!header&&!tech)||body.size()>8*1024*1024-124)return false;
|
||||||
|
if(header&&std::any_of(prev,prev+32,[](uint8_t b){return b!=0;}))return false;
|
||||||
|
const size_t prefix=fixed?40:(tech||channel?44:0),offset=fixed?0:4;
|
||||||
|
if(body.size()<prefix)return false;
|
||||||
|
uint32_t code=0,previous=0;
|
||||||
|
if(prefix){
|
||||||
|
if(tech&&getBE(body.data())!=0)return false;
|
||||||
|
code=type==3?CONNECTION:type==4?PROFILE:tech?TECH:getBE(body.data());
|
||||||
|
previous=getBE(body.data()+offset);
|
||||||
|
if(previous>=number||(channel&&(code>MAX_NUMBER||(code>0&&(code>=number||previous<code)))))return false;
|
||||||
|
}
|
||||||
|
Bytes content{1};putBE(content,type,2);putBE(content,subtype,2);putBE(content,version,2);
|
||||||
|
content.insert(content.end(),body.begin()+prefix,body.end());
|
||||||
|
Bytes contentItem,coreItem;uint8_t contentHash[32],contentId[32];
|
||||||
|
if(!makeItem(content,Bytes{0},0,owner,secret,sha384,sign,contentItem)||
|
||||||
|
!sha256(content.data(),content.size(),contentHash)||!sha256(contentItem.data()+2,64,contentId))return false;
|
||||||
|
Bytes core{1};core.insert(core.end(),prev,prev+32);putBE(core,number,4);putBE(core,timestamp,8);
|
||||||
|
core.insert(core.end(),contentHash,contentHash+32);core.insert(core.end(),contentId,contentId+32);
|
||||||
|
if(prefix){putBE(core,code,4);putBE(core,previous,4);core.insert(core.end(),body.begin()+offset+4,body.begin()+offset+36);}
|
||||||
|
Bytes tags;const size_t count=prefix?3:2;avroLong(tags,count);avroString(tags,"App");avroString(tags,app);
|
||||||
|
avroString(tags,"n");avroString(tags,std::to_string(number));
|
||||||
|
if(prefix){avroString(tags,"l");avroString(tags,code==PROFILE?"P":code==CONNECTION?"C":code==TECH?"T":std::to_string(code));}
|
||||||
|
tags.push_back(0);
|
||||||
|
if(!makeItem(core,tags,count,owner,secret,sha384,sign,coreItem))return false;
|
||||||
|
out.clear();putBE(out,coreItem.size(),4);out.insert(out.end(),coreItem.begin(),coreItem.end());out.insert(out.end(),contentItem.begin(),contentItem.end());return true;
|
||||||
|
}
|
||||||
|
} // namespace shine_core
|
||||||
@@ -9,6 +9,8 @@
|
|||||||
#include <TouchDrvCSTXXX.hpp>
|
#include <TouchDrvCSTXXX.hpp>
|
||||||
#include <mbedtls/gcm.h>
|
#include <mbedtls/gcm.h>
|
||||||
#include <mbedtls/sha256.h>
|
#include <mbedtls/sha256.h>
|
||||||
|
#include <mbedtls/sha512.h>
|
||||||
|
#include "shine_core_content.h"
|
||||||
#include <mbedtls/base64.h>
|
#include <mbedtls/base64.h>
|
||||||
#include <Ed25519.h>
|
#include <Ed25519.h>
|
||||||
#include <sodium.h>
|
#include <sodium.h>
|
||||||
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> preimage;
|
|
||||||
preimage.reserve(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
|
||||||
appendUint16BE(preimage, 0);
|
|
||||||
preimage.insert(preimage.end(), prevHash32, prevHash32 + 32);
|
|
||||||
int32_t blockSize = (int32_t)(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
|
||||||
appendInt32BE(preimage, blockSize);
|
|
||||||
appendInt32BE(preimage, nextBlockNumber);
|
|
||||||
appendInt64BE(preimage, (int64_t)(shineNowMs() / 1000ULL));
|
|
||||||
appendUint16BE(preimage, msgType);
|
|
||||||
appendUint16BE(preimage, msgSubType);
|
|
||||||
appendUint16BE(preimage, msgVersion);
|
|
||||||
preimage.insert(preimage.end(), bodyBytes.begin(), bodyBytes.end());
|
|
||||||
|
|
||||||
uint8_t blockchainSeed[32] = {};
|
uint8_t blockchainSeed[32] = {};
|
||||||
uint8_t blockchainPub[32] = {};
|
uint8_t blockchainPub[32] = {};
|
||||||
uint8_t blockchainSec[64] = {};
|
uint8_t blockchainSec[64] = {};
|
||||||
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t hash32[32] = {};
|
std::vector<uint8_t> fullBlock;
|
||||||
sha256calc(preimage.data(), preimage.size(), hash32);
|
const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||||
uint8_t signature[64] = {};
|
return mbedtls_sha256(data, len, out, 0) == 0;
|
||||||
if (!signMessageEd25519(std::vector<uint8_t>(hash32, hash32 + 32), blockchainSec, signature)) {
|
};
|
||||||
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign AddBlock hash\",\"requestId\":\"")
|
const auto hash384 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||||
|
uint8_t buffer[64] = {};
|
||||||
|
if (mbedtls_sha512(data, len, buffer, 1) != 0) return false;
|
||||||
|
memcpy(out, buffer, 48);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
const auto sign = +[](const std::vector<uint8_t>& data, const uint8_t* key, uint8_t* sig) -> bool {
|
||||||
|
return signMessageEd25519(data, key, sig);
|
||||||
|
};
|
||||||
|
// Same semantic remote body and signal contract; only the signed wire bytes change.
|
||||||
|
if (resolvedBlockchainName != blockchainName || nextBlockNumber < 0 ||
|
||||||
|
!shine_core::buildPair(msgType, msgSubType, msgVersion, bodyBytes, (uint32_t)nextBlockNumber,
|
||||||
|
shineNowMs()/1000ULL, prevHash32, blockchainPub, blockchainSec,
|
||||||
|
"test5599", hash256, hash384, sign, fullBlock)) {
|
||||||
|
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign CORE/CONTENT pair\",\"requestId\":\"")
|
||||||
+ jsonEscape(item.signalRequestId) + "\"}";
|
+ jsonEscape(item.signalRequestId) + "\"}";
|
||||||
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
|
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> fullBlock = preimage;
|
|
||||||
fullBlock.push_back(0x01);
|
|
||||||
fullBlock.push_back(0x00);
|
|
||||||
fullBlock.insert(fullBlock.end(), signature, signature + 64);
|
|
||||||
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||||
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
|
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
|
||||||
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
|
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
|
||||||
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
|
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
|
||||||
String addBlockResp;
|
String addBlockResp;
|
||||||
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||||
|
const bool uncertain = !addBlockOk;
|
||||||
|
if (uncertain) {
|
||||||
|
// Retry the identical container, not the semantic request or a new timestamp.
|
||||||
|
addBlockResp = "";
|
||||||
|
addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||||
|
}
|
||||||
uint64_t statusCode = 0;
|
uint64_t statusCode = 0;
|
||||||
jsonInt64Field(addBlockResp, "status", statusCode);
|
jsonInt64Field(addBlockResp, "status", statusCode);
|
||||||
String serverLastHash;
|
String serverLastHash;
|
||||||
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
jsonStringField(addBlockResp, "message", errorMessage);
|
jsonStringField(addBlockResp, "message", errorMessage);
|
||||||
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
|
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
|
||||||
|
|
||||||
|
if (uncertain && (!addBlockOk || statusCode != 200)) {
|
||||||
|
const String readReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||||
|
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "}";
|
||||||
|
String readResp, readBytes;
|
||||||
|
uint64_t readStatus = 0;
|
||||||
|
if (shineWsRequest(gShineWs, "GetBlockchainBlock", readReq, readResp, SHINE_RPC_TIMEOUT_MS)) {
|
||||||
|
jsonInt64Field(readResp, "status", readStatus);
|
||||||
|
jsonStringField(readResp, "blockBytesB64", readBytes);
|
||||||
|
if (readStatus == 200 && readBytes == bytesToBase64String(fullBlock.data(), fullBlock.size())) {
|
||||||
|
jsonStringField(readResp, "blockHash", serverLastHash);
|
||||||
|
serverLastNumber = (uint64_t)nextBlockNumber;
|
||||||
|
addBlockOk = true;
|
||||||
|
statusCode = 200;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!addBlockOk || statusCode != 200) {
|
||||||
|
errorCode = "addblock_outcome_unknown";
|
||||||
|
errorMessage = "AddBlock outcome unknown; refresh history before retrying";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!addBlockOk || statusCode != 200) {
|
if (!addBlockOk || statusCode != 200) {
|
||||||
if (errorCode.isEmpty()) {
|
if (errorCode.isEmpty()) {
|
||||||
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
|
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# Factory Firmware Backup
|
|
||||||
|
|
||||||
Здесь хранится полный дамп флеша текущего состояния платы.
|
|
||||||
|
|
||||||
Файлы:
|
|
||||||
- `factory-full-16mb.bin` — полный дамп флеша `0x000000..0xFFFFFF`
|
|
||||||
- `factory-full-16mb.bin.sha256` — контрольная сумма
|
|
||||||
|
|
||||||
Скрипты:
|
|
||||||
- `backup_factory.sh` — снять резервную копию
|
|
||||||
- `restore_factory_backup.sh` — восстановить резервную копию на плату
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
PORT="${PORT:-/dev/ttyACM0}"
|
|
||||||
ESPTOOL="${ESPTOOL:-$HOME/.arduino15/packages/esp32/tools/esptool_py/5.1.0/esptool}"
|
|
||||||
BAUD="${BAUD:-921600}"
|
|
||||||
OUT_BIN="${ROOT_DIR}/factory-full-16mb.bin"
|
|
||||||
|
|
||||||
echo "== Port: ${PORT}"
|
|
||||||
echo "== Output: ${OUT_BIN}"
|
|
||||||
echo "== Esptool: ${ESPTOOL}"
|
|
||||||
echo "== Baud: ${BAUD}"
|
|
||||||
|
|
||||||
"${ESPTOOL}" --port "${PORT}" --baud "${BAUD}" read-flash 0 0x1000000 "${OUT_BIN}"
|
|
||||||
sha256sum "${OUT_BIN}" | tee "${OUT_BIN}.sha256"
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "== Backup done."
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
PORT="${PORT:-/dev/ttyACM0}"
|
|
||||||
ESPTOOL="${ESPTOOL:-$HOME/.arduino15/packages/esp32/tools/esptool_py/5.1.0/esptool}"
|
|
||||||
IN_BIN="${IN_BIN:-${ROOT_DIR}/factory-full-16mb.bin}"
|
|
||||||
|
|
||||||
if [[ ! -f "${IN_BIN}" ]]; then
|
|
||||||
echo "Backup file not found: ${IN_BIN}" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== Port: ${PORT}"
|
|
||||||
echo "== Input: ${IN_BIN}"
|
|
||||||
echo "== Esptool: ${ESPTOOL}"
|
|
||||||
|
|
||||||
"${ESPTOOL}" --port "${PORT}" --baud 921600 write-flash 0 "${IN_BIN}"
|
|
||||||
|
|
||||||
echo
|
|
||||||
echo "== Restore done."
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
# Reference Notes
|
|
||||||
|
|
||||||
Модель: Waveshare `ESP32-S3-Touch-AMOLED-2.16` (SKU 33969/33970)
|
|
||||||
|
|
||||||
Полезные страницы:
|
|
||||||
- Product: https://www.waveshare.com/product/arduino/boards-kits/esp32-s3/esp32-s3-touch-amoled-2.16.htm
|
|
||||||
- Docs home: https://docs.waveshare.com/ESP32-S3-Touch-AMOLED-2.16
|
|
||||||
- Arduino setup: https://docs.waveshare.com/ESP32-S3-Touch-AMOLED-2.16/Development-Environment-Setup-Arduino
|
|
||||||
- Official examples: https://github.com/waveshareteam/ESP32-S3-Touch-AMOLED-2.16
|
|
||||||
|
|
||||||
Ключевое по железу (по документации):
|
|
||||||
- ESP32-S3R8, 16MB flash, 8MB PSRAM
|
|
||||||
- AMOLED 2.16" 480x480
|
|
||||||
- Capacitive touch (CST9220)
|
|
||||||
- IMU QMI8658
|
|
||||||
- Audio codec ES8311 (playback) и ES7210 (microphones)
|
|
||||||
- TF slot (SD), сейчас без карты
|
|
||||||
@@ -1,353 +0,0 @@
|
|||||||
# SHiNE ESP32 Homeserver UI Nav Minimal Spec
|
|
||||||
|
|
||||||
Легаси-спецификация старого навигационного теста для `Waveshare ESP32-S3-Touch-AMOLED-2.16`.
|
|
||||||
Актуальный основной скетч теперь находится в `../main-device/shine_homeserver_main/`; этот документ оставлен только как историческая справка по старому тестовому UI.
|
|
||||||
|
|
||||||
## Цель
|
|
||||||
|
|
||||||
Этот прототип проверяет базовую механику экранов, крупных кнопок, свайпов, первичную настройку Wi-Fi и настройку серверных адресов через общий экран редактирования текста.
|
|
||||||
|
|
||||||
На этом этапе отсутствуют:
|
|
||||||
- логин/пароль учётной записи SHiNE;
|
|
||||||
- PIN;
|
|
||||||
- кошелёк;
|
|
||||||
- QR;
|
|
||||||
- регистрация;
|
|
||||||
- PDA update/create транзакции;
|
|
||||||
- входящие запросы.
|
|
||||||
|
|
||||||
## Экраны
|
|
||||||
|
|
||||||
Прототип содержит 10 экранов:
|
|
||||||
- `HOME`
|
|
||||||
- `SETTINGS_MENU`
|
|
||||||
- `WIFI_SCREEN`
|
|
||||||
- `SERVER_SCREEN`
|
|
||||||
- `ACCOUNT_SCREEN`
|
|
||||||
- `ACCOUNT_HOMESERVER_SCREEN`
|
|
||||||
- `ACCOUNT_SECRET_SCREEN`
|
|
||||||
- `SECRET_SHOW_SCREEN`
|
|
||||||
- `SECRET_GENERATE_*`
|
|
||||||
- `TEXT_EDIT_SCREEN`
|
|
||||||
- `REGISTER_ACCOUNT_PLACEHOLDER`
|
|
||||||
|
|
||||||
## HOME
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- сверху слева значение homeserver или `homeserver not set`;
|
|
||||||
- ниже значение логина или `login not set`;
|
|
||||||
- справа от строки логина индикатор статуса Solana-аккаунта:
|
|
||||||
- зелёный — все ключи совпадают;
|
|
||||||
- красный — есть mismatch;
|
|
||||||
- белый контур — пользователь не найден в Solana PDA;
|
|
||||||
- рядом с индикатором краткий текст ошибки, если статус не зелёный;
|
|
||||||
- третьей строкой `secret not set`, если секрет ещё не помечен как установленный;
|
|
||||||
- сверху справа один ряд индикаторов:
|
|
||||||
- процент батареи;
|
|
||||||
- иконка батареи;
|
|
||||||
- индикатор Wi-Fi уровня сигнала;
|
|
||||||
- по центру крупный текст `STATUS`;
|
|
||||||
- одна строка Wi-Fi вида `Wi-Fi (<ssid>) connected/disconnected`;
|
|
||||||
- кнопка баланса вида `Balance: <value SOL>` или `Balance: failed to load`, по нажатию выполняет повторный запрос;
|
|
||||||
- строка `SHiNE: <server> connected/account not configured/unavailable`;
|
|
||||||
- при отсутствии пользователя в Solana PDA слева снизу появляется кнопка `REGISTER ACCOUNT`;
|
|
||||||
- снизу кнопку `SETTINGS`, уменьшенную примерно до половины ширины экрана и сдвинутую к правому краю.
|
|
||||||
- внизу на тёмной полосе подпись `SHiNE homeserver (v.0.18)`.
|
|
||||||
|
|
||||||
Строка Wi-Fi на `HOME`:
|
|
||||||
- `Wi-Fi (not configured) not configured`
|
|
||||||
- `Wi-Fi (<saved_ssid>) disconnected`
|
|
||||||
- `Wi-Fi (<current_ssid>) connected`
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- кнопка `REGISTER ACCOUNT` -> `REGISTER_ACCOUNT_PLACEHOLDER`, только если пользователь не найден;
|
|
||||||
- кнопка `SETTINGS` -> `SETTINGS_MENU`;
|
|
||||||
- свайп влево -> `SETTINGS_MENU`.
|
|
||||||
|
|
||||||
Примечание:
|
|
||||||
- поведение `REGISTER ACCOUNT -> REGISTER_ACCOUNT_PLACEHOLDER` относится к старой тестовой версии и не является актуальным для основного скетча.
|
|
||||||
|
|
||||||
Фоновая логика:
|
|
||||||
- пока открыт `HOME`, экран сам обновляется примерно раз в секунду;
|
|
||||||
- при наличии `login + secret + homeserver` и Wi-Fi устройство читает Solana `user_pda` напрямую через RPC;
|
|
||||||
- сравниваются `root key`, `blockchain key`, `client key` и `homeserver` session-запись типа `100`;
|
|
||||||
- для строки `SHiNE:` устройство держит отдельную WebSocket-сессию с сервером SHiNE:
|
|
||||||
- авторизация через `AuthChallenge/CreateAuthSession` или `SessionChallenge/SessionLogin`;
|
|
||||||
- session key = публичный `homeserver key`;
|
|
||||||
- подтверждение создания сессии подписывается `client key`;
|
|
||||||
- heartbeat выполняется `Ping` раз в минуту.
|
|
||||||
|
|
||||||
## SETTINGS_MENU
|
|
||||||
|
|
||||||
Показывает вертикальное меню из 3 пунктов:
|
|
||||||
- `Wi-Fi`
|
|
||||||
- `Server`
|
|
||||||
- `Account`
|
|
||||||
|
|
||||||
Одновременно видны только 2 пункта.
|
|
||||||
|
|
||||||
Начальное состояние:
|
|
||||||
- `Wi-Fi`
|
|
||||||
- `Server`
|
|
||||||
|
|
||||||
После свайпа вверх:
|
|
||||||
- `Server`
|
|
||||||
- `Account`
|
|
||||||
|
|
||||||
После свайпа вниз:
|
|
||||||
- `Wi-Fi`
|
|
||||||
- `Server`
|
|
||||||
|
|
||||||
Обе видимые карточки меню имеют одинаковый цвет.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- нажатие `Wi-Fi` -> `WIFI_SCREEN`;
|
|
||||||
- нажатие `Server` -> `SERVER_SCREEN`;
|
|
||||||
- нажатие `Account` -> `ACCOUNT_SCREEN`;
|
|
||||||
- свайп вправо -> `HOME`.
|
|
||||||
|
|
||||||
## WIFI_SCREEN
|
|
||||||
|
|
||||||
Экран содержит 2 внутренних режима.
|
|
||||||
|
|
||||||
### 1. Overview
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- текущий Wi-Fi статус;
|
|
||||||
- сохранённый SSID и число известных сетей;
|
|
||||||
- статусное сообщение;
|
|
||||||
- кнопку `SELECT NETWORK`;
|
|
||||||
- кнопку `CLEAR SAVED WI-FI`;
|
|
||||||
- кнопку `BACK`.
|
|
||||||
|
|
||||||
### 2. Scan Results
|
|
||||||
|
|
||||||
После `SELECT NETWORK` выполняется скан доступных Wi-Fi сетей.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- заголовок `SELECT NETWORK`;
|
|
||||||
- количество или результат сканирования;
|
|
||||||
- список найденных SSID как крупные кнопки;
|
|
||||||
- кнопку `SCAN AGAIN`;
|
|
||||||
- кнопку `BACK`.
|
|
||||||
|
|
||||||
Нажатие на SSID открывает `TEXT_EDIT_SCREEN` для ввода пароля.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
- если для выбранного SSID пароль уже был сохранён раньше, он сразу подставляется в поле ввода;
|
|
||||||
- если пароль меняют для другого SSID, старые сохранённые пароли других сетей не теряются;
|
|
||||||
- после успешного подключения выбранная сеть становится текущей `wifi_ssid/wifi_pass`;
|
|
||||||
- одновременно хранится до `8` известных сетей `SSID -> password`;
|
|
||||||
- `CLEAR SAVED WI-FI` очищает все сохранённые сети и текущую сеть.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- свайп вправо из любого режима `WIFI_SCREEN` -> `SETTINGS_MENU`
|
|
||||||
- кнопка `BACK` -> `SETTINGS_MENU`
|
|
||||||
|
|
||||||
## SERVER_SCREEN
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- статусное сообщение;
|
|
||||||
- текущий `Solana RPC` адрес;
|
|
||||||
- кнопку `SOLANA RPC`;
|
|
||||||
- текущий `SHiNE server login` или уже резолвленный адрес;
|
|
||||||
- кнопку `SHiNE SERVER LOGIN`, если обычный `user PDA` ещё не зарегистрирован.
|
|
||||||
|
|
||||||
Значения по умолчанию:
|
|
||||||
- Solana RPC: `https://api.mainnet-beta.solana.com`
|
|
||||||
- SHiNE server login: `shineupme`
|
|
||||||
|
|
||||||
Нажатие на любую из двух кнопок открывает `TEXT_EDIT_SCREEN`.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- свайп вправо -> `SETTINGS_MENU`
|
|
||||||
|
|
||||||
## ACCOUNT_SCREEN
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- заголовок `ACCOUNT`;
|
|
||||||
- статусное сообщение;
|
|
||||||
- кнопку `Login (<value|not set>)`;
|
|
||||||
- кнопку `Homeserver (<value|not set>)`;
|
|
||||||
- кнопку `Secret (<*****|not set>)`.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- свайп вправо -> `SETTINGS_MENU`
|
|
||||||
- `Login` -> `TEXT_EDIT_SCREEN`
|
|
||||||
- `Homeserver` -> `ACCOUNT_HOMESERVER_SCREEN`
|
|
||||||
- `Secret` -> `ACCOUNT_SECRET_SCREEN`
|
|
||||||
|
|
||||||
## ACCOUNT_HOMESERVER_SCREEN
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- текущий `homeserver`;
|
|
||||||
- рекомендацию оставить `homeserver1`, если устройство одно;
|
|
||||||
- кнопку `USE HOMESERVER1`;
|
|
||||||
- кнопку `EDIT MANUALLY`;
|
|
||||||
- кнопку `BACK`.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- `USE HOMESERVER1` -> сохраняет `homeserver1` и возвращает в `ACCOUNT_SCREEN`
|
|
||||||
- `EDIT MANUALLY` -> `TEXT_EDIT_SCREEN`
|
|
||||||
- свайп вправо -> `ACCOUNT_SCREEN`
|
|
||||||
|
|
||||||
## ACCOUNT_SECRET_SCREEN
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- кнопку `SHOW SECRET` или серую `SECRET NOT SET`, если секрета ещё нет;
|
|
||||||
- кнопку `ENTER SECRET MANUALLY (NOT RECOMMENDED)`;
|
|
||||||
- кнопку `GENERATE SECRET`.
|
|
||||||
|
|
||||||
Переходы:
|
|
||||||
- свайп вправо -> `ACCOUNT_SCREEN`
|
|
||||||
- `SHOW SECRET` -> экран просмотра секрета
|
|
||||||
- `ENTER SECRET MANUALLY (NOT RECOMMENDED)` -> `TEXT_EDIT_SCREEN`
|
|
||||||
- `GENERATE SECRET` -> экран подтверждения генерации
|
|
||||||
|
|
||||||
## SECRET_SHOW_SCREEN
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- заголовок `SECRET`;
|
|
||||||
- вертикально прокручиваемый список ключей;
|
|
||||||
- `Secret (base58)`;
|
|
||||||
- `Root key (base58)`;
|
|
||||||
- `Root key priv (base58)`;
|
|
||||||
- `Blockchain key (base58)`;
|
|
||||||
- `Blockchain key priv (base58)`;
|
|
||||||
- `Client key (base58)`;
|
|
||||||
- `Client key priv (base58)`;
|
|
||||||
- `Homeserver key (base58)`;
|
|
||||||
- `Homeserver key priv (base58)`;
|
|
||||||
- для каждого поля показывается формула derivation;
|
|
||||||
- значения ключей показываются полными строками увеличенным шрифтом;
|
|
||||||
- кнопку `BACK`.
|
|
||||||
|
|
||||||
## TEXT_EDIT_SCREEN
|
|
||||||
|
|
||||||
Общий экран редактирования строковых значений.
|
|
||||||
|
|
||||||
Используется для:
|
|
||||||
- пароля Wi-Fi;
|
|
||||||
- Solana RPC;
|
|
||||||
- SHiNE server login.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- заголовок;
|
|
||||||
- поле ввода, уже заполненное старым значением;
|
|
||||||
- новые символы всегда добавляются только в конец текста;
|
|
||||||
- визуальный курсор не показывается;
|
|
||||||
- пароль Wi-Fi показывается открыто, без маскировки точками;
|
|
||||||
- кнопки `SAVE`, `CANCEL`, `DEL`, `CLR`;
|
|
||||||
- большую экранную клавиатуру.
|
|
||||||
|
|
||||||
## REGISTER_ACCOUNT_PLACEHOLDER
|
|
||||||
|
|
||||||
Временный экран-заглушка регистрации.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
- заголовок `REGISTER ACCOUNT`;
|
|
||||||
- сообщение, что регистрационный flow пока не реализован;
|
|
||||||
- кнопку `BACK`.
|
|
||||||
|
|
||||||
## Клавиатура
|
|
||||||
|
|
||||||
Клавиатура единая для всех текстовых вводов.
|
|
||||||
|
|
||||||
Особенности:
|
|
||||||
- занимает нижнюю часть экрана;
|
|
||||||
- разбита на 2 страницы;
|
|
||||||
- переключение страниц выполняется свайпом влево/вправо внутри `TEXT_EDIT_SCREEN`;
|
|
||||||
- страница 1 содержит в основном буквы и базовые URL-символы;
|
|
||||||
- страница 2 содержит цифры и дополнительные URL/символьные кнопки;
|
|
||||||
- на символьных страницах должны быть доступны как минимум `!` и отдельная кнопка `SPACE`;
|
|
||||||
- переключение `ABC/123` и `SHIFT` не должно очищать уже введённый текст;
|
|
||||||
- переключение страниц клавиатуры свайпом тоже не должно очищать уже введённый текст, включая цифры, символы и уже набранные заглавные буквы;
|
|
||||||
- есть специальные действия `DEL` и `CLR`.
|
|
||||||
|
|
||||||
## Хранение Wi-Fi
|
|
||||||
|
|
||||||
Используется `Preferences` (NVS памяти ESP32):
|
|
||||||
- `wifi_ssid`
|
|
||||||
- `wifi_pass`
|
|
||||||
- `wifi_known_good`
|
|
||||||
- до `8` сохранённых пар `SSID -> password`
|
|
||||||
|
|
||||||
При старте устройства, если сохранён SSID, выполняется попытка подключения к текущей сохранённой сети.
|
|
||||||
|
|
||||||
Если пользователь уже вводил пароль для сети раньше:
|
|
||||||
- при повторном выборе этого SSID старый пароль сразу подставляется в editor screen;
|
|
||||||
- сохранение пароля для другой сети не удаляет уже сохранённые пароли остальных сетей.
|
|
||||||
|
|
||||||
Если сеть раньше уже была успешно подключена и помечена как валидная:
|
|
||||||
- после потери связи устройство автоматически пытается переподключиться;
|
|
||||||
- первые повторные попытки идут раз в `10` секунд;
|
|
||||||
- если связи нет долго, интервал увеличивается до `30` секунд.
|
|
||||||
- пока открыт `HOME`, экран сам обновляется примерно раз в секунду и подтягивает актуальные:
|
|
||||||
- статус Wi-Fi;
|
|
||||||
- SSID;
|
|
||||||
- уровень сигнала;
|
|
||||||
- процент батареи.
|
|
||||||
|
|
||||||
## Хранение серверов
|
|
||||||
|
|
||||||
Используется `Preferences` (NVS памяти ESP32):
|
|
||||||
- `solana_rpc`
|
|
||||||
- `shine_server_login`
|
|
||||||
|
|
||||||
## Хранение аккаунта
|
|
||||||
|
|
||||||
Используется `Preferences` (NVS памяти ESP32):
|
|
||||||
- `login`
|
|
||||||
- `homeserver`
|
|
||||||
- `secret_set`
|
|
||||||
|
|
||||||
## Детали клавиатуры
|
|
||||||
|
|
||||||
- клавиатура занимает примерно `2/3`-`3/4` высоты экрана;
|
|
||||||
- сверху остаются только заголовок и поле ввода;
|
|
||||||
- буквы занимают 3 ряда;
|
|
||||||
- половина букв находится на левой странице, половина на правой;
|
|
||||||
- на правой странице кнопки тоже стоят в ровных колонках, без сдвига рядов вправо;
|
|
||||||
- отдельный режим `symbols` тоже разделён на 2 страницы;
|
|
||||||
- в режиме `symbols` на правой странице есть отдельная кнопка `SPACE` и отдельная кнопка `!`;
|
|
||||||
- 3 основных ряда клавиш и нижний служебный ряд увеличены по высоте;
|
|
||||||
- клавиши дополнительно увеличены по высоте по сравнению с предыдущим промежуточным вариантом;
|
|
||||||
- четвёртый ряд содержит:
|
|
||||||
- переключение `ABC/123`
|
|
||||||
- `SHIFT`
|
|
||||||
- `DEL`
|
|
||||||
- `SAVE`
|
|
||||||
- `CANCEL`
|
|
||||||
- ниже рамки клавиатурного блока остаётся отдельная тёмная полоса с версией `SHiNE homeserver (v.0.18)`.
|
|
||||||
|
|
||||||
## Жесты
|
|
||||||
|
|
||||||
Поддерживаются направления:
|
|
||||||
- `SWIPE_LEFT`
|
|
||||||
- `SWIPE_RIGHT`
|
|
||||||
- `SWIPE_UP`
|
|
||||||
- `SWIPE_DOWN`
|
|
||||||
|
|
||||||
Маршруты:
|
|
||||||
- `HOME`: свайп влево -> `SETTINGS_MENU`
|
|
||||||
- `SETTINGS_MENU`: свайп вправо -> `HOME`
|
|
||||||
- `SETTINGS_MENU`: свайп вверх/вниз -> прокрутка списка
|
|
||||||
- `WIFI_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
|
||||||
- `SERVER_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
|
||||||
- `ACCOUNT_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
|
||||||
- `ACCOUNT_HOMESERVER_SCREEN`: свайп вправо -> `ACCOUNT_SCREEN`
|
|
||||||
- `ACCOUNT_SECRET_SCREEN`: свайп вправо -> `ACCOUNT_SCREEN`
|
|
||||||
- `TEXT_EDIT_SCREEN`: свайп влево/вправо -> переключение страниц клавиатуры
|
|
||||||
- переключение страниц клавиатуры срабатывает только если свайп начался в зоне самой клавиатуры, а не по всему экрану редактора
|
|
||||||
|
|
||||||
## Особенность обработки жестов
|
|
||||||
|
|
||||||
- если палец ушёл из зоны обычного тапа и жест определяется как свайп, случайное попадание на кнопку по пути не должно превращать свайп в нажатие;
|
|
||||||
- приоритет у свайпа, а не у `click`.
|
|
||||||
- одно непрерывное касание может вызвать не более одного действия кнопки;
|
|
||||||
- скольжение пальцем по экранной клавиатуре не должно вызывать цепочку из нескольких нажатий;
|
|
||||||
- периодический refresh на `HOME` не должен срабатывать во время активного касания.
|
|
||||||
|
|
||||||
## Язык
|
|
||||||
|
|
||||||
Пока интерфейс отображается в ASCII/English, чтобы использовать подтверждённый рабочий шрифтовой путь на устройстве.
|
|
||||||
@@ -1,681 +0,0 @@
|
|||||||
# SHiNE ESP32 Homeserver UI Spec
|
|
||||||
|
|
||||||
## Назначение
|
|
||||||
|
|
||||||
Этот документ описывает актуальный UI-прототип homeserver `SHiNE` для платы `Waveshare ESP32-S3-Touch-AMOLED-2.16`.
|
|
||||||
Актуальный основной Arduino-скетч лежит в `../main-device/shine_homeserver_main/`.
|
|
||||||
|
|
||||||
Документ является источником истины для Arduino-скетча:
|
|
||||||
|
|
||||||
- если меняется этот документ, должен меняться и скетч;
|
|
||||||
- если меняется скетч, должен обновляться и этот документ;
|
|
||||||
- экраны, кнопки, поля, статусы, переходы и тексты не должны расходиться.
|
|
||||||
|
|
||||||
## Текущий объём реализации
|
|
||||||
|
|
||||||
Текущая реализация является интерактивным прототипом экрана устройства, пригодным для ручной проверки на железе.
|
|
||||||
|
|
||||||
Что уже входит в прототип:
|
|
||||||
|
|
||||||
- локальный UI на тач-экране;
|
|
||||||
- хранение настроек и секретов во внутренней памяти `ESP32` через `NVS`;
|
|
||||||
- экранный UI устройства работает на английском языке, потому что кириллица на этом шрифтовом пути пока не поддерживается стабильно;
|
|
||||||
- экран пополнения с реальным `solana:` URI и рисованием QR-кода через `LVGL`;
|
|
||||||
- реальное подключение к `Wi-Fi` по сохранённым `SSID/паролю`;
|
|
||||||
- реальная проверка доступности `API`, `RPC` и `WS`-адресов;
|
|
||||||
- реальное чтение баланса кошелька из `Solana RPC`;
|
|
||||||
- проверка обязательных условий перед регистрацией;
|
|
||||||
- живая on-chain регистрация серверного `user_pda` в `shine_users` по нажатию кнопки на главном экране;
|
|
||||||
- живой экран заявок на подключение новых устройств через доверенную homeserver-сессию;
|
|
||||||
- PIN-блокировка (в текущей временной сборке вход по PIN отключён, устройство открывает `HOME` сразу после старта);
|
|
||||||
- базовые настройки, статус и главный экран;
|
|
||||||
- сохранение `PDA` и `tx signature` после успешной регистрации.
|
|
||||||
- создание и возобновление серверной сессии `SHiNE` через WebSocket с `sessionType = 100` и `clientPlatform = "ESP32"`.
|
|
||||||
|
|
||||||
Что пока считается именно прототипом, а не финальной интеграцией:
|
|
||||||
|
|
||||||
- пока реализован только сценарий заявок на подключение устройств через доверенную сессию;
|
|
||||||
- другие типы входящих запросов на подпись и произвольные approval-flow на этом устройстве ещё не подключены.
|
|
||||||
|
|
||||||
## Основная идея устройства
|
|
||||||
|
|
||||||
Устройство работает как отдельный homeserver:
|
|
||||||
|
|
||||||
- хранит секрет на самом устройстве;
|
|
||||||
- позволяет ввести логин, секрет и имя homeserver;
|
|
||||||
- показывает адрес кошелька устройства;
|
|
||||||
- позволяет пополнить баланс перед регистрацией;
|
|
||||||
- после выполнения условий даёт зарегистрировать устройство как homeserver;
|
|
||||||
- после авторизации в SHiNE может подтверждать заявки на подключение новых устройств пользователя.
|
|
||||||
|
|
||||||
`SD`-карта не нужна для постоянного хранения секрета в этом прототипе.
|
|
||||||
Основное сохранение идёт во внутреннюю flash-память через `NVS`.
|
|
||||||
|
|
||||||
## Данные, которые хранятся на устройстве
|
|
||||||
|
|
||||||
Прототип хранит:
|
|
||||||
|
|
||||||
- `PIN`;
|
|
||||||
- `Wi-Fi SSID`;
|
|
||||||
- `Wi-Fi password`;
|
|
||||||
- `login`;
|
|
||||||
- `session/homeserver name`;
|
|
||||||
- `master secret`;
|
|
||||||
- `wallet address`;
|
|
||||||
- `user pda address`;
|
|
||||||
- `registration signature`;
|
|
||||||
- `balance`;
|
|
||||||
- `server login` для первичной привязки;
|
|
||||||
- `resolved server api url` / `rpc url` / `ws url` после чтения PDA сервера;
|
|
||||||
- флаги:
|
|
||||||
`wifiReady`, `serversReady`, `secretReady`, `registered`, `online`.
|
|
||||||
|
|
||||||
Для первой регистрации обычного `user PDA` устройство берёт `createdAtMs` из NTP прямо перед отправкой транзакции в Solana. При последующих обновлениях `user PDA` устройство так же берёт актуальный `updatedAtMs` из NTP перед отправкой update-транзакции. Дальше в `user PDA` сохраняется `accessServers`, где по умолчанию лежит `shineupme`.
|
|
||||||
|
|
||||||
## Правило серверной сессии SHiNE
|
|
||||||
|
|
||||||
При подключении к серверу `SHiNE` устройство должно авторизовываться как homeserver-сеанс:
|
|
||||||
|
|
||||||
- `sessionType = 100`
|
|
||||||
- `clientPlatform = "ESP32"`
|
|
||||||
- `clientInfo = "ESP32 homeserver:<homeserverName>"`
|
|
||||||
|
|
||||||
Это относится и к `CreateAuthSession`, и к `SessionLogin`.
|
|
||||||
|
|
||||||
## Правила готовности к регистрации
|
|
||||||
|
|
||||||
Кнопка регистрации доступна только если одновременно выполнены условия:
|
|
||||||
|
|
||||||
1. настроен и подтверждён `Wi-Fi`;
|
|
||||||
2. задан и подтверждён `SHiNE server login`;
|
|
||||||
3. задан логин;
|
|
||||||
4. сгенерирован или введён секрет;
|
|
||||||
5. баланс кошелька не меньше `0.20 SOL`;
|
|
||||||
6. устройство ещё не зарегистрировано.
|
|
||||||
|
|
||||||
Если хотя бы одно условие не выполнено, главный экран показывает, чего именно не хватает.
|
|
||||||
|
|
||||||
## Экранная модель
|
|
||||||
|
|
||||||
В прототипе используются следующие экраны:
|
|
||||||
|
|
||||||
1. `LOCK`
|
|
||||||
2. `HOME`
|
|
||||||
3. `STATUS`
|
|
||||||
4. `CONNECTION`
|
|
||||||
5. `WIFI_EDIT`
|
|
||||||
6. `SERVERS`
|
|
||||||
7. `ACCOUNT`
|
|
||||||
8. `WALLET`
|
|
||||||
9. `WALLET_QR`
|
|
||||||
10. `WALLET_SIGN_REQUEST`
|
|
||||||
11. `REQUESTS`
|
|
||||||
12. `REQUEST_DETAIL`
|
|
||||||
13. `SETTINGS`
|
|
||||||
14. `PIN_EDIT`
|
|
||||||
15. `TEXT_INPUT`
|
|
||||||
16. `CONFIRM`
|
|
||||||
17. `REGISTER_ACCOUNT_CONFIRM`
|
|
||||||
18. `REGISTER_ACCOUNT_RESULT`
|
|
||||||
|
|
||||||
## Общие правила интерфейса
|
|
||||||
|
|
||||||
- Верхняя строка всегда показывает краткий статус устройства:
|
|
||||||
`PIN`, `Wi-Fi`, `сервер`, `регистрация`.
|
|
||||||
- В правом верхнем углу рядом с батареей:
|
|
||||||
- сначала процент заряда;
|
|
||||||
- затем, если устройство реально заряжается, маленькая иконка молнии;
|
|
||||||
- затем контур батареи;
|
|
||||||
- затем индикатор `Wi-Fi`.
|
|
||||||
- Основной язык прототипа: английский.
|
|
||||||
- Для вывода текста в текущей временной сборке используется стандартный шрифт `Arduino_GFX`.
|
|
||||||
- Русские строки в UI устройства пока не использовать.
|
|
||||||
- Кнопки крупные, с тач-ориентированным размером.
|
|
||||||
- Опасные действия подтверждаются отдельным диалогом.
|
|
||||||
- После изменения данных конфигурация сразу сохраняется в `NVS`.
|
|
||||||
|
|
||||||
## Экран LOCK
|
|
||||||
|
|
||||||
Назначение:
|
|
||||||
|
|
||||||
- экран блокировки предусмотрен в UI, но в текущей временной сборке после запуска пропускается;
|
|
||||||
- вход по PIN временно отключён для отладки остальных экранов.
|
|
||||||
|
|
||||||
Отображается:
|
|
||||||
|
|
||||||
- заголовок `SHiNE Device`;
|
|
||||||
- статус `Устройство заблокировано`;
|
|
||||||
- поле ввода PIN в виде маски;
|
|
||||||
- кнопки цифровой клавиатуры;
|
|
||||||
- кнопки `Стереть` и `Открыть`.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- если PIN введён верно, открывается `HOME`;
|
|
||||||
- если PIN неверный, показывается ошибка `Неверный PIN`;
|
|
||||||
- в текущей временной сборке этот экран не показывается автоматически при старте.
|
|
||||||
|
|
||||||
## Экран HOME
|
|
||||||
|
|
||||||
Это основной экран устройства.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- крупный статус регистрации;
|
|
||||||
- имя логина;
|
|
||||||
- имя homeserver;
|
|
||||||
- строку `Wi-Fi: <SSID> connected|disconnected`;
|
|
||||||
- строку `SHiNE: <server address> connected|unavailable`;
|
|
||||||
- короткий статус баланса.
|
|
||||||
|
|
||||||
Особенности верхнего блока:
|
|
||||||
|
|
||||||
- зелёный/контурный статусный кружок аккаунта расположен слева от строки логина;
|
|
||||||
- блок `STATUS` поднят выше относительно предыдущей версии;
|
|
||||||
- если состояние хорошее, слово `connected` в строках `Wi-Fi` и `SHiNE` показывается зелёным.
|
|
||||||
|
|
||||||
В зоне кошелька:
|
|
||||||
|
|
||||||
- вместо старых двух кнопок `баланс` и `QR` показывается одна широкая кнопка;
|
|
||||||
- текст кнопки: `Wallet: <selected wallet name>`;
|
|
||||||
- доступные имена:
|
|
||||||
- `ClientKey`
|
|
||||||
- `RootKey`
|
|
||||||
- либо сохранённое имя `custom`-кошелька;
|
|
||||||
- после старта устройства баланс активного выбранного кошелька пытается загрузиться автоматически, если уже есть секрет и `Wi-Fi`;
|
|
||||||
- нажатие на эту кнопку открывает экран `WALLET`.
|
|
||||||
|
|
||||||
Нижние кнопки:
|
|
||||||
|
|
||||||
- `Статус`
|
|
||||||
- `Подключение`
|
|
||||||
- `Аккаунт`
|
|
||||||
- `Wallet`
|
|
||||||
- `Запросы`
|
|
||||||
- `Настройки`
|
|
||||||
|
|
||||||
Дополнительная большая кнопка:
|
|
||||||
|
|
||||||
- `REGISTER ACCOUNT`
|
|
||||||
- либо жёлтая `ADD HOMESERVER`
|
|
||||||
- либо жёлтая `FIX HOMESERVER PASSWORD`
|
|
||||||
|
|
||||||
Если регистрация уже сделана:
|
|
||||||
|
|
||||||
- если пользователь создан, но в `PDA` ещё нет сессии текущего homeserver, показывается жёлтая кнопка `ADD HOMESERVER`;
|
|
||||||
- если в `PDA` есть homeserver с тем же именем, но с другим ключом, показывается жёлтая кнопка `FIX HOMESERVER PASSWORD`;
|
|
||||||
- если и пользователь, и homeserver-сессия уже корректны, вместо призыва к регистрации показывается статус `Homeserver активен`.
|
|
||||||
- две нижние кнопки внизу экрана не прилегают вплотную друг к другу, между ними есть небольшой зазор.
|
|
||||||
|
|
||||||
## Экран REGISTER_ACCOUNT_CONFIRM
|
|
||||||
|
|
||||||
Показывает предварительную проверку перед отправкой транзакции регистрации.
|
|
||||||
|
|
||||||
Отображается:
|
|
||||||
|
|
||||||
- повторный `login`;
|
|
||||||
- сообщение о том, что логин свободен или уже занят;
|
|
||||||
- баланс кошелька с проверкой порога `0.020 SOL`;
|
|
||||||
- имя homeserver;
|
|
||||||
- пометка, если используется стандартное значение `homeserver1`;
|
|
||||||
- отдельное предупреждение, если `Wi-Fi` не подключён.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `ЗАРЕГИСТРИРОВАТЬ В СИЯНИИ`
|
|
||||||
- `BACK`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- если `Wi-Fi` не подключён, на экране прямо показывается уведомление об этом и кнопка регистрации недоступна;
|
|
||||||
- если `login` уже занят в `shine_users`, регистрация недоступна;
|
|
||||||
- если баланс меньше `0.020 SOL`, на экране показывается соответствующая ошибка;
|
|
||||||
- если все проверки пройдены, кнопка регистрации активна и запускает on-chain регистрацию.
|
|
||||||
|
|
||||||
## Экран REGISTER_ACCOUNT_RESULT
|
|
||||||
|
|
||||||
Показывает результат отправки регистрации.
|
|
||||||
|
|
||||||
Отображается:
|
|
||||||
|
|
||||||
- текст успеха или ошибки;
|
|
||||||
- подробное сообщение;
|
|
||||||
- при успехе краткий `user_pda`;
|
|
||||||
- при успехе краткий `tx signature`.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `BACK HOME`
|
|
||||||
- `ACCOUNT`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- после успешной регистрации данные `user_pda` и `tx signature` сохраняются в `NVS`;
|
|
||||||
- при ошибке на экране показывается причина отказа;
|
|
||||||
- если ошибку вернул `sendTransaction`, экран старается показать не только общий текст, но и детали `RPC`/preflight/simulate-логов.
|
|
||||||
|
|
||||||
## Экран HOMESERVER_PDA_CONFIRM
|
|
||||||
|
|
||||||
Показывает, что именно не так с homeserver-секцией уже существующей пользовательской `PDA`.
|
|
||||||
|
|
||||||
Отображается:
|
|
||||||
|
|
||||||
- причина (`homeserver` отсутствует в `PDA` или ключ не совпадает с локальным секретом);
|
|
||||||
- `login`;
|
|
||||||
- имя `homeserver`;
|
|
||||||
- короткое пояснение, что именно будет сделано.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `ADD HOMESERVER` или `FIX HOMESERVER PASSWORD`
|
|
||||||
- `BACK`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- если `Wi-Fi` не подключён, действие недоступно;
|
|
||||||
- экран не создаёт нового пользователя, а запускает `update_user_pda`;
|
|
||||||
- при `ADD HOMESERVER` в блок `sessions` добавляется запись `session_type=100`;
|
|
||||||
- при `FIX HOMESERVER PASSWORD` обновляется публичный ключ уже существующей записи `homeserver`.
|
|
||||||
|
|
||||||
## Экран HOMESERVER_PDA_RESULT
|
|
||||||
|
|
||||||
Показывает результат обновления `sessions` в пользовательской `PDA`.
|
|
||||||
|
|
||||||
Отображается:
|
|
||||||
|
|
||||||
- успех или ошибка;
|
|
||||||
- короткое сообщение;
|
|
||||||
- при успехе краткий `tx signature`.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `BACK HOME`
|
|
||||||
- `ACCOUNT`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- при ошибке текст ошибки сохраняется в ту же USB/NVS-диагностику, что и регистрация;
|
|
||||||
- после успешного обновления выполняется повторная проверка `PDA`, и основной экран должен перейти в состояние `ok`.
|
|
||||||
|
|
||||||
## Экран STATUS
|
|
||||||
|
|
||||||
Показывает сводку:
|
|
||||||
|
|
||||||
- логин;
|
|
||||||
- homeserver;
|
|
||||||
- есть ли секрет;
|
|
||||||
- зарегистрировано ли устройство;
|
|
||||||
- подключён ли Wi-Fi;
|
|
||||||
- доступны ли серверы;
|
|
||||||
- хватает ли баланса;
|
|
||||||
- находится ли устройство онлайн;
|
|
||||||
- краткий отпечаток `PDA` или `tx`.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Назад`
|
|
||||||
- `Обновить статус`
|
|
||||||
|
|
||||||
`Обновить статус` в прототипе не делает сеть, а просто перерисовывает текущие вычисленные состояния.
|
|
||||||
|
|
||||||
## Экран CONNECTION
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- `Wi-Fi`: готов / не готов;
|
|
||||||
- `Серверы`: готовы / не готовы;
|
|
||||||
- `Онлайн`: да / нет.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Wi-Fi`
|
|
||||||
- `Серверы`
|
|
||||||
- `Подключить`
|
|
||||||
- `Отключить`
|
|
||||||
- `Назад`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `Подключить` переводит устройство в `online=true`, если `Wi-Fi` реально подключён и серверы реально проверены;
|
|
||||||
- `Отключить` переводит устройство в `online=false`.
|
|
||||||
|
|
||||||
## Экран WIFI_EDIT
|
|
||||||
|
|
||||||
Поля:
|
|
||||||
|
|
||||||
- `SSID`
|
|
||||||
- `Пароль`
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Изменить SSID`
|
|
||||||
- `Изменить пароль`
|
|
||||||
- `Проверить`
|
|
||||||
- `Сбросить`
|
|
||||||
- `Назад`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `Проверить` делает реальную попытку подключения к `Wi-Fi`;
|
|
||||||
- `Сбросить` очищает обе строки и ставит `wifiReady=false`.
|
|
||||||
|
|
||||||
## Экран SERVERS
|
|
||||||
|
|
||||||
Поля:
|
|
||||||
|
|
||||||
- `API URL`
|
|
||||||
- `RPC URL`
|
|
||||||
- `WS URL`
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Изменить API`
|
|
||||||
- `Изменить RPC`
|
|
||||||
- `Изменить WS`
|
|
||||||
- `Проверить`
|
|
||||||
- `Тестовые`
|
|
||||||
- `Назад`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `Тестовые` подставляет дефолтные тестовые значения;
|
|
||||||
- `Проверить` делает реальные сетевые проверки:
|
|
||||||
- `API URL` должен отвечать по `HTTP/HTTPS`;
|
|
||||||
- `RPC URL` должен отвечать на `Solana JSON-RPC`;
|
|
||||||
- `WS URL` должен принимать `TCP/TLS`-соединение.
|
|
||||||
|
|
||||||
## Экран ACCOUNT
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- логин;
|
|
||||||
- имя homeserver;
|
|
||||||
- статус секрета;
|
|
||||||
- короткий отпечаток секрета;
|
|
||||||
- статус регистрации;
|
|
||||||
- короткий отпечаток `PDA` или `tx`.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Изменить логин`
|
|
||||||
- `Секрет`
|
|
||||||
- `Имя homeserver`
|
|
||||||
- `Сгенерировать`
|
|
||||||
- `Очистить`
|
|
||||||
- `Назад`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `Сгенерировать` создаёт новый `master secret` и пересчитывает из него `device`-кошелёк;
|
|
||||||
- `Очистить` удаляет секрет, адрес кошелька, `PDA`, `tx`, регистрацию и онлайн-статус;
|
|
||||||
- логин приводится к нижнему регистру и trim.
|
|
||||||
- после успешной регистрации на экране сохраняются и отображаются краткие отпечатки `PDA` и `TX`.
|
|
||||||
|
|
||||||
## Экран WALLET
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- кнопку `Wallet: <selected wallet name>`;
|
|
||||||
- строку текущего статуса/баланса активного кошелька;
|
|
||||||
- сокращённый публичный ключ активного кошелька.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Wallet: <selected wallet name>`
|
|
||||||
- `SHOW BALANCE`
|
|
||||||
- `SHOW WALLET QR`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- верхняя кнопка открывает экран выбора кошелька `WALLET_SELECT`;
|
|
||||||
- `Показать баланс кошелька` читает реальный баланс именно активного выбранного кошелька из `Solana RPC`;
|
|
||||||
- `Показать QR-код кошелька` открывает экран `WALLET_QR`;
|
|
||||||
- этот экран не меняет логику Solana-регистрации пользователя: on-chain регистрация и проверки `PDA` по-прежнему завязаны на `client key`.
|
|
||||||
|
|
||||||
## Экран WALLET_SELECT
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- строку `Current: <selected wallet name>`;
|
|
||||||
- три кнопки выбора:
|
|
||||||
- `ClientKey`
|
|
||||||
- `RootKey`
|
|
||||||
- `Custom` или `Custom: <имя>`;
|
|
||||||
- у текущего выбора видна галочка.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `ClientKey` активирует кошелёк, выведенный из suffix `client.key`;
|
|
||||||
- `RootKey` активирует кошелёк, выведенный из suffix `root.key`;
|
|
||||||
- `Custom` использует derivation:
|
|
||||||
`sha256(base64(secret32) + "|wallet." + customName)`;
|
|
||||||
- если имя `custom`-кошелька ещё не задано, нажатие `Custom` открывает экран текстового ввода;
|
|
||||||
- если `custom` уже выбран, повторное нажатие на него открывает экран редактирования имени;
|
|
||||||
- после выбора кошелька устройство возвращается на экран `WALLET`.
|
|
||||||
|
|
||||||
## Экран WALLET_QR
|
|
||||||
|
|
||||||
Экран показывает:
|
|
||||||
|
|
||||||
- крупный реальный `QR` для строки `solana:<wallet_address>`;
|
|
||||||
- снизу крупный текст самого адреса кошелька.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- отдельная текстовая подсказка возврата не показывается;
|
|
||||||
- возврат на главный экран выполняется обычным тапом по экрану.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- QR-код для строки вида:
|
|
||||||
`solana:<wallet>`;
|
|
||||||
- мелкую подпись с полным адресом кошелька под QR.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- QR должен быть сканируемым, а не декоративным;
|
|
||||||
- адрес кошелька берётся из текущего активного выбранного кошелька;
|
|
||||||
- нажатие в любую точку экрана возвращает пользователя на `WALLET`.
|
|
||||||
|
|
||||||
## Экран WALLET_SIGN_REQUEST
|
|
||||||
|
|
||||||
Экран показывается, когда браузерное wallet-расширение присылает на ESP32 запрос `sign_transaction`.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- заголовок `SIGN REQUEST`;
|
|
||||||
- вопрос о подписи транзакции текущим активным кошельком;
|
|
||||||
- сокращённый публичный ключ кошелька;
|
|
||||||
- комментарий, присланный полем `comment`;
|
|
||||||
- две кнопки:
|
|
||||||
- `REJECT`
|
|
||||||
- `APPROVE`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- если пользователь нажимает `APPROVE`, ESP32 подписывает транзакцию текущим активным кошельком и отправляет ответ в расширение;
|
|
||||||
- если пользователь нажимает `REJECT`, ESP32 отправляет отказ `rejected_by_user`;
|
|
||||||
- пока запрос активен, свайпом этот экран не закрывается;
|
|
||||||
- после ответа расширению устройство возвращается на предыдущий экран.
|
|
||||||
|
|
||||||
## Экран REQUESTS
|
|
||||||
|
|
||||||
Экран доступен только если homeserver уже авторизован в SHiNE.
|
|
||||||
|
|
||||||
Показывает:
|
|
||||||
|
|
||||||
- слева сверху кнопку `REFRESH`;
|
|
||||||
- заголовок `REQUESTS:` немного правее стандартного левого положения;
|
|
||||||
- справа сверху только большую цифру числа активных заявок;
|
|
||||||
- ниже прокручиваемый список активных pairing-заявок;
|
|
||||||
- на экране одновременно видны примерно две плитки.
|
|
||||||
|
|
||||||
Каждая плитка показывает:
|
|
||||||
|
|
||||||
- код подключения из `10` цифр в виде `5` пар: `XX XX XX XX XX`;
|
|
||||||
- строку `Session: <platform/name>`;
|
|
||||||
- строку `Kind: Client session` или `Kind: Wallet session`.
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- список берётся из живой операции `ListTrustedDeviceLoginRequests`;
|
|
||||||
- если заявок нет, экран показывает `No active requests`;
|
|
||||||
- отдельная строка вида `Active requests: N` на этом экране не показывается;
|
|
||||||
- вертикальный скролл позволяет просматривать все активные заявки;
|
|
||||||
- нажатие по плитке открывает `REQUEST_DETAIL`;
|
|
||||||
- свайп вправо возвращает в `SETTINGS`.
|
|
||||||
|
|
||||||
## Экран REQUEST_DETAIL
|
|
||||||
|
|
||||||
Показывает детали выбранной pairing-заявки:
|
|
||||||
|
|
||||||
- вопрос `Connect session ...?`;
|
|
||||||
- код подключения `XX XX XX XX XX`;
|
|
||||||
- строку `Session: <platform/name>`;
|
|
||||||
- строку `Kind: Client session` или `Kind: Wallet session`;
|
|
||||||
- пояснение:
|
|
||||||
- для client session: `Only client key will be transferred. No additional keys will be sent.`
|
|
||||||
- для wallet session: `No keys will be transferred.`
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `YES`
|
|
||||||
- `NO`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- `YES` подтверждает заявку:
|
|
||||||
- для client session устройство передаёт только `client key`;
|
|
||||||
- для wallet session устройство выпускает отдельную `wallet-session` без передачи ключей;
|
|
||||||
- `NO` отклоняет заявку;
|
|
||||||
- после любого решения устройство возвращается в список `REQUESTS` и обновляет его;
|
|
||||||
- свайп вправо возвращает в `REQUESTS`.
|
|
||||||
|
|
||||||
## Экран SETTINGS
|
|
||||||
|
|
||||||
Показывает вертикальное меню крупных пунктов.
|
|
||||||
|
|
||||||
Если homeserver ещё не авторизован в SHiNE:
|
|
||||||
|
|
||||||
- `1. Wi-Fi`
|
|
||||||
- `2. Server`
|
|
||||||
- `3. Account`
|
|
||||||
|
|
||||||
Если homeserver уже авторизован:
|
|
||||||
|
|
||||||
- `1. Device requests`
|
|
||||||
- `2. Wi-Fi`
|
|
||||||
- `3. Server`
|
|
||||||
- `4. Account`
|
|
||||||
|
|
||||||
Поведение:
|
|
||||||
|
|
||||||
- одновременно видны только две карточки;
|
|
||||||
- список листается свайпом вверх/вниз;
|
|
||||||
- свайп вправо возвращает на `HOME`;
|
|
||||||
- пункт `Device requests` должен быть первым и появляется только для авторизованного homeserver.
|
|
||||||
|
|
||||||
## Экран PIN_EDIT
|
|
||||||
|
|
||||||
Используется для ввода нового PIN.
|
|
||||||
|
|
||||||
Правила:
|
|
||||||
|
|
||||||
- допустимы только цифры;
|
|
||||||
- длина PIN: 4..8 символов;
|
|
||||||
- после сохранения новый PIN немедленно пишется в `NVS`.
|
|
||||||
|
|
||||||
## Экран TEXT_INPUT
|
|
||||||
|
|
||||||
Это общий экран редактирования текстовых полей.
|
|
||||||
|
|
||||||
Используется для:
|
|
||||||
|
|
||||||
- `SSID`
|
|
||||||
- `Пароль Wi-Fi`
|
|
||||||
- `Логин`
|
|
||||||
- `Имя homeserver`
|
|
||||||
- `API URL`
|
|
||||||
- `RPC URL`
|
|
||||||
- `WS URL`
|
|
||||||
|
|
||||||
Состав экрана:
|
|
||||||
|
|
||||||
- заголовок поля;
|
|
||||||
- текущее значение;
|
|
||||||
- программная клавиатура;
|
|
||||||
- кнопки `Стереть`, `OK`, `Отмена`.
|
|
||||||
|
|
||||||
## Экран CONFIRM
|
|
||||||
|
|
||||||
Это модальный экран подтверждения.
|
|
||||||
|
|
||||||
Используется для:
|
|
||||||
|
|
||||||
- регистрации;
|
|
||||||
- очистки секрета;
|
|
||||||
- полного сброса.
|
|
||||||
|
|
||||||
Кнопки:
|
|
||||||
|
|
||||||
- `Подтвердить`
|
|
||||||
- `Отмена`
|
|
||||||
|
|
||||||
## Сценарий первой настройки
|
|
||||||
|
|
||||||
Ожидаемый путь пользователя:
|
|
||||||
|
|
||||||
1. открыть устройство сразу после старта; экран PIN временно не требуется;
|
|
||||||
2. открыть `Подключение -> Wi-Fi`;
|
|
||||||
3. ввести `SSID` и пароль, нажать `Проверить`;
|
|
||||||
4. открыть `Подключение -> Серверы`;
|
|
||||||
5. проверить или задать `SHiNE server login` (по умолчанию `shineupme`);
|
|
||||||
6. открыть `Аккаунт`;
|
|
||||||
7. ввести логин;
|
|
||||||
8. задать имя homeserver;
|
|
||||||
9. сгенерировать секрет;
|
|
||||||
10. открыть `Кошелёк`;
|
|
||||||
11. при необходимости пополнить баланс;
|
|
||||||
12. вернуться на `HOME`;
|
|
||||||
13. нажать `REGISTER ACCOUNT`;
|
|
||||||
14. на экране проверки ещё раз увидеть `login`, статус свободного `PDA`, баланс, `homeserver1`, серверный login и при необходимости сообщение о неподключённом `Wi-Fi`;
|
|
||||||
15. нажать `ЗАРЕГИСТРИРОВАТЬ В СИЯНИИ`;
|
|
||||||
16. после завершения увидеть либо экран успеха с `user_pda` и `tx signature`, либо подробную ошибку;
|
|
||||||
17. после успешной регистрации увидеть статус `Homeserver активен`.
|
|
||||||
|
|
||||||
Примечание:
|
|
||||||
|
|
||||||
- устройство реально отправляет `create_user_pda` в `shine_users`, а после подтверждения сохраняет `PDA` и `tx signature`;
|
|
||||||
- при первой регистрации для обычного `user PDA` не заполняется `serverAddress`, а `accessServers` получает `shineupme` или другой выбранный `SHiNE server login`.
|
|
||||||
|
|
||||||
## Сценарий входящего запроса
|
|
||||||
|
|
||||||
1. открыть `Запросы`;
|
|
||||||
2. выбрать один из запросов;
|
|
||||||
3. прочитать детали;
|
|
||||||
4. нажать `Разрешить` или `Отклонить`;
|
|
||||||
5. убедиться, что статус запроса изменился.
|
|
||||||
|
|
||||||
## Временный режим текста
|
|
||||||
|
|
||||||
В текущей диагностической версии:
|
|
||||||
|
|
||||||
- строковые литералы экранного UI должны оставаться английскими ASCII-совместимыми;
|
|
||||||
- возвращение кириллицы допустимо только после отдельной доработки шрифтов и реальной проверки на устройстве;
|
|
||||||
- рендер выполняется стандартным шрифтом `Arduino_GFX`;
|
|
||||||
- это обходной режим, пока `U8g2`-шрифты на устройстве не начнут рисоваться стабильно.
|
|
||||||
|
|
||||||
## Критерии ручной проверки
|
|
||||||
|
|
||||||
Минимально нужно проверить:
|
|
||||||
|
|
||||||
1. устройство загружается и сразу открывает `HOME`; экран блокировки временно отключён;
|
|
||||||
2. весь экранный текст отображается читаемо на английском без замены символов;
|
|
||||||
3. ввод по экранной клавиатуре работает;
|
|
||||||
4. после перезагрузки сохранённые поля остаются в памяти;
|
|
||||||
5. секрет и адрес кошелька сохраняются на устройстве;
|
|
||||||
6. экран `QR и URI` рисует читаемый QR-код;
|
|
||||||
7. регистрация блокируется, пока условия не выполнены;
|
|
||||||
8. после выполнения условий регистрация становится доступной;
|
|
||||||
9. список запросов и экран подтверждения работают;
|
|
||||||
10. полный сброс действительно очищает сохранённое состояние.
|
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Инструкция по commit и push в Git
|
||||||
|
|
||||||
|
## Репозиторий
|
||||||
|
|
||||||
|
Работать с Git нужно из корня репозитория `SHiNE-product/`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-product
|
||||||
|
```
|
||||||
|
|
||||||
|
## Канонический Gitea
|
||||||
|
|
||||||
|
Всегда использовать этот Git-сервер и этот remote:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://git.shineup.me/Aidar/SHiNE-server.git
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка и исправление `origin`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git remote set-url origin https://git.shineup.me/Aidar/SHiNE-server.git
|
||||||
|
git remote -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Старый адрес `git2.shineup.me` не использовать.
|
||||||
|
|
||||||
|
Секреты, токены, приватные ключи, `.env`, логи и сборочные артефакты в Git не добавлять.
|
||||||
|
|
||||||
|
## Перед коммитом
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status --short --branch
|
||||||
|
git diff --check
|
||||||
|
git diff
|
||||||
|
```
|
||||||
|
|
||||||
|
Перед обычным коммитом обновить `VERSION.properties`:
|
||||||
|
|
||||||
|
- только UI — увеличить `client.version`;
|
||||||
|
- только сервер — увеличить `server.version`;
|
||||||
|
- UI и сервер — увеличить обе версии;
|
||||||
|
- в рабочей ветке использовать patch-инкремент: `1.2.346` → `1.2.347`.
|
||||||
|
|
||||||
|
Сообщения коммитов писать на русском языке.
|
||||||
|
|
||||||
|
## Commit
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add <нужные-файлы>
|
||||||
|
git commit -m "Краткое описание изменения"
|
||||||
|
```
|
||||||
|
|
||||||
|
Для локального `git commit` токен не нужен. Не использовать `git add .`, если в рабочем дереве есть непроверенные локальные файлы.
|
||||||
|
|
||||||
|
## Push
|
||||||
|
|
||||||
|
Сначала проверить ветку и remote:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git branch --show-current
|
||||||
|
git remote -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Для push использовать токен из переменной окружения `GITEA_TOKEN`; сам токен в команду, файл или историю shell не записывать. При HTTPS Git обычно запросит имя пользователя и пароль токена:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export GITEA_TOKEN='токен задаётся локально и не коммитится'
|
||||||
|
git push origin HEAD
|
||||||
|
unset GITEA_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
Если credential helper не умеет автоматически подставлять `GITEA_TOKEN`, использовать настроенный локально способ авторизации Gitea; не вставлять токен в URL remote.
|
||||||
|
|
||||||
|
После push проверить результат:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status --short --branch
|
||||||
|
git log -1 --oneline
|
||||||
|
```
|
||||||
|
|
||||||
|
## Ветка `main`
|
||||||
|
|
||||||
|
`main` предназначена для стабильных версий. По умолчанию изменения сначала коммитить в рабочей ветке, затем вливать в `main`. Для merge в `main` увеличивать вторую цифру версии и обнулять третью: `1.2.346` → `1.3.0`.
|
||||||
|
|
||||||
|
Перед push в `main` отдельно проверить diff, версию и отсутствие секретов.
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero General Public License from time to time. Such new versions
|
||||||
|
will be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU Affero General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU Affero General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU Affero General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# SHiNE — Public Data and Immutability Warning / Предупреждение о публичных данных и их неизменяемости
|
||||||
|
|
||||||
|
## Русский
|
||||||
|
|
||||||
|
**Прежде чем опубликовать что-либо в SHiNE, учитывайте, что публичные данные могут сохраниться навсегда. Полное удаление опубликованных данных из децентрализованной сети может оказаться крайне затруднительным или невозможным.**
|
||||||
|
|
||||||
|
SHiNE разделяет личную переписку и публичные данные:
|
||||||
|
|
||||||
|
- Личные сообщения и их вложения предназначены для приватного обмена. Они не являются публичными публикациями пользовательского блокчейна; для защиты содержимого личной переписки предусмотрено сквозное шифрование. Получатели, однако, могут сохранить или передать полученные материалы другим лицам.
|
||||||
|
- Публичные публикации, сведения профиля, публичные взаимодействия и другие публичные записи пользовательского блокчейна подписываются цифровой подписью и предназначены для долговременного хранения, в том числе в сети Arweave. Такие записи могут независимо храниться, копироваться, проверяться и распространяться другими участниками сети.
|
||||||
|
|
||||||
|
Уже опубликованные записи не предназначены для перезаписи. Редактирование создаёт новую запись и не уничтожает предыдущую. Удаление или скрытие данных в интерфейсе, прекращение их распространения отдельным сервером или закрытие учётной записи не гарантируют удаления оригинальных записей, истории и копий у других участников.
|
||||||
|
|
||||||
|
Файлы, связанные с публичными записями, могут храниться отдельно от блокчейна. Их доступность зависит от используемого хранилища и наличия копий. Удаление файла из одного хранилища не гарантирует исчезновения всех его копий или соответствующих записей в блокчейне.
|
||||||
|
|
||||||
|
Публичные материалы могут использоваться и распространяться другими лицами на условиях предоставленных вами лицензий, включая CC BY-NC 4.0 и SHiNE Commercial Distribution License (SCDL), если вы предоставили соответствующие разрешения. Удаление публикации само по себе не отменяет ранее предоставленных лицензионных прав. Это не ограничивает права, которые не могут быть исключены в силу применимого законодательства.
|
||||||
|
|
||||||
|
**Публикуйте осознанно.** Не размещайте в публичном блокчейне пароли, закрытые ключи, конфиденциальную информацию, персональные данные, которые не предназначены для публичного доступа, или материалы, на публикацию и лицензирование которых у вас нет необходимых прав. Перед публикацией проверьте её содержимое, вложения и выбранный режим доступа.
|
||||||
|
|
||||||
|
**Относитесь к каждой публичной записи как к потенциально необратимой — даже в версии 0.9 Alpha.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
**Before publishing anything on SHiNE, bear in mind that public data may remain available forever. Completely removing published data from a decentralized network may be extremely difficult or impossible.**
|
||||||
|
|
||||||
|
SHiNE distinguishes between private correspondence and public data:
|
||||||
|
|
||||||
|
- Direct messages and their attachments are intended for private exchange. They are not public publications in a user's blockchain; end-to-end encryption is designed to protect the contents of private correspondence. Recipients may, however, retain or share the materials they receive.
|
||||||
|
- Public posts, profile information, public interactions and other public records in a user's blockchain are digitally signed and intended for long-term storage, including on the Arweave network. Other network participants may independently store, copy, verify and distribute such records.
|
||||||
|
|
||||||
|
Published records are not designed to be overwritten. Editing creates a new record and does not destroy the previous one. Deleting or hiding data in the interface, stopping its distribution by an individual server, or closing an account does not guarantee removal of the original records, their history or copies held by other participants.
|
||||||
|
|
||||||
|
Files associated with public records may be stored separately from the blockchain. Their availability depends on the storage system used and the existence of copies. Removing a file from one storage location does not guarantee the disappearance of all its copies or the corresponding blockchain records.
|
||||||
|
|
||||||
|
Public materials may be used and distributed by others under the licenses you have granted, including CC BY-NC 4.0 and the SHiNE Commercial Distribution License (SCDL), if you have granted the relevant permissions. Deleting a publication does not in itself revoke previously granted license rights. This does not limit rights that cannot be excluded under applicable law.
|
||||||
|
|
||||||
|
**Publish responsibly.** Do not put passwords, private keys, confidential information, personal data not intended for public access, or materials you lack the necessary rights to publish and license into the public blockchain. Before publishing, check the content, attachments and selected access mode.
|
||||||
|
|
||||||
|
**Treat every public record as potentially irreversible — even in version 0.9 Alpha.**
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
# Задание для Айдара: навести порядок в инструкциях агентов SHiNE
|
|
||||||
|
|
||||||
## Кратко
|
|
||||||
Нужно согласовать и оформить единый порядок инструкций для Codex/Telegram-агентов в проекте SHiNE, чтобы агенты стабильно понимали структуру проекта, границы ответственности и правила работы с сервером, UI, Solana-модулем, Telegram-ботом и игроками.
|
|
||||||
|
|
||||||
## Зачем это нужно
|
|
||||||
Сейчас проект состоит из нескольких связанных, но разных частей:
|
|
||||||
|
|
||||||
- основной сервер `SHiNE-server/`;
|
|
||||||
- UI `shine-UI/`;
|
|
||||||
- Solana/Anchor-модуль `shine-solana/shine/`;
|
|
||||||
- Telegram-агент-кодер `SHiNE-agent-bot-coder/`;
|
|
||||||
- TURN-сервер;
|
|
||||||
- документация `Dev_Docs/`;
|
|
||||||
- отдельные рабочие папки игроков `Players/`.
|
|
||||||
|
|
||||||
Без явных инструкций агент может путать эти зоны: например, смешать деплой Solana с деплоем сервера, изменить код от имени игрока, не обновить документацию API/DM/блокчейна или неправильно трактовать файл инструкций.
|
|
||||||
|
|
||||||
## Что предлагается сделать
|
|
||||||
1. Утвердить корневой `AGENTS.md` как главный набор правил проекта.
|
|
||||||
2. Проверить и при необходимости уточнить локальный `AGENTS.md` внутри `shine-solana/shine/`.
|
|
||||||
3. Оставить отдельные служебные инструкции Telegram-агента в `SHiNE-agent-bot-coder/AGENT.md`.
|
|
||||||
4. Оставить автоматически читаемые инструкции Telegram-агента в `SHiNE-agent-bot-coder/AGENTS.md`.
|
|
||||||
5. Явно закрепить режим игроков:
|
|
||||||
- игроки могут задавать вопросы, просить анализ, идеи и ТЗ;
|
|
||||||
- игроки не меняют код проекта напрямую;
|
|
||||||
- материалы игроков сохраняются только в `Players/<username>/`.
|
|
||||||
6. Зафиксировать правило: если пользователь говорит «агент MD» или похожую формулировку, считать, что речь про автоматически читаемый `AGENTS.md`.
|
|
||||||
7. Добавить простой процесс согласования изменений инструкций:
|
|
||||||
- Дима или другой участник готовит предложение;
|
|
||||||
- Айдар получает уведомление/заявку;
|
|
||||||
- Айдар отвечает: одобрить, отклонить или попросить доработать;
|
|
||||||
- только после одобрения агент вносит изменения в проектные инструкции.
|
|
||||||
|
|
||||||
## Предлагаемая логика уведомления Айдару
|
|
||||||
Минимальный вариант без сложной разработки:
|
|
||||||
|
|
||||||
1. Агент готовит текст заявки.
|
|
||||||
2. Текст отправляется Айдару в Telegram или в общий рабочий чат.
|
|
||||||
3. В заявке явно указаны варианты ответа:
|
|
||||||
- `одобрить`;
|
|
||||||
- `отклонить`;
|
|
||||||
- `доработать: ...`.
|
|
||||||
4. После ответа Айдара агент либо выполняет согласованные правки, либо фиксирует, что задача отклонена/нужна доработка.
|
|
||||||
|
|
||||||
Более удобный вариант на будущее:
|
|
||||||
|
|
||||||
- добавить в Telegram-бота команду или сценарий согласования задач, например:
|
|
||||||
- `/approve <id>`;
|
|
||||||
- `/reject <id> причина`;
|
|
||||||
- `/revise <id> комментарий`.
|
|
||||||
|
|
||||||
Но для начала достаточно простого текстового согласования через Telegram.
|
|
||||||
|
|
||||||
## Что нужно от Айдара
|
|
||||||
Подтвердить, что такой порядок подходит:
|
|
||||||
|
|
||||||
1. Корневой `AGENTS.md` остается главным правилом проекта.
|
|
||||||
2. Для Solana, Telegram-агента и игроков сохраняются отдельные локальные правила.
|
|
||||||
3. Игроки не меняют код напрямую, а готовят материалы и предложения.
|
|
||||||
4. Изменения инструкций выполняются только после явного одобрения Айдара.
|
|
||||||
5. Уведомления Айдару на первом этапе можно делать простым текстом в Telegram, без отдельной сложной системы заявок.
|
|
||||||
|
|
||||||
## Ожидаемый результат
|
|
||||||
После одобрения:
|
|
||||||
|
|
||||||
- агенты будут стабильнее понимать границы проекта;
|
|
||||||
- снизится риск случайных изменений не в той части системы;
|
|
||||||
- появится понятный порядок согласования задач от игроков;
|
|
||||||
- Айдар будет явно контролировать изменения в инструкциях и правилах работы агентов.
|
|
||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
|
Before Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 93 KiB |
|
Before Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 70 KiB |
|
Before Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 28 KiB |
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
|
|
||||||
@@ -1,7 +1,29 @@
|
|||||||
# SHiNE
|
# SHiNE
|
||||||
|
|
||||||
## План запуска DAO
|
SHiNE — проект децентрализованного общения: браузерный клиент, сервер, пользовательские блокчейны, личные сообщения и интеграция с Solana и Arweave. Репозиторий содержит также экспериментальные компоненты для ESP32 и браузерное расширение кошелька.
|
||||||
|
|
||||||
План запуска DAO зафиксирован в [DAO_запуск/README.md](DAO_запуск/README.md).
|
> **Статус:** активная разработка и подготовка к публичному запуску. Исходный код доступен для изучения; самостоятельный запуск возможен, но инструкции по установке ещё дорабатываются. Не все описанные в планах возможности реализованы.
|
||||||
|
|
||||||
Это рабочий список задач по `этап1` и `этап2`. Дальше ведём его как основной чек-лист запуска DAO и отмечаем в нём выполненные пункты по мере готовности.
|
## Как устроен проект
|
||||||
|
|
||||||
|
| Компонент | Назначение |
|
||||||
|
| --- | --- |
|
||||||
|
| [`shine-UI/`](shine-UI/) | Браузерный клиент и панель администратора сервера |
|
||||||
|
| [`SHiNE-server/`](SHiNE-server/) | WebSocket/HTTP сервер, PostgreSQL, блокчейн, доставка сообщений |
|
||||||
|
| [`shine-solana/shine/`](shine-solana/shine/) | Anchor-программы и инструменты Solana |
|
||||||
|
| [`SHiNE-browser-plugin-wallet/`](SHiNE-browser-plugin-wallet/) | Браузерное расширение кошелька |
|
||||||
|
| [`ESP32/`](ESP32/) | Прошивки и прототипы устройств |
|
||||||
|
| [`deploy/`](deploy/) | Скрипты и инструкции по развёртыванию |
|
||||||
|
|
||||||
|
Архитектура и границы компонентов описаны в [общей схеме](docs/ARCHITECTURE.md). Пользовательские блоки проектируются для публикации в Arweave; подробности и текущие ограничения тестового контура приведены в [документации блокчейна](docs/Blockchain/README.md).
|
||||||
|
|
||||||
|
## Самостоятельный запуск
|
||||||
|
|
||||||
|
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Для `./gradlew startLocal` скопируйте `application.properties.example` в `SHiNE-server/application.properties` и заполните параметры своей среды. При `java -jar` внешний `application.properties` ищется в текущем рабочем каталоге. Встроенный файл необязателен. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
|
||||||
|
|
||||||
|
## Документация
|
||||||
|
|
||||||
|
- [Каталог документации](docs/README.md) — действующие спецификации, инструкции и планы.
|
||||||
|
- [Общая архитектура](docs/ARCHITECTURE.md) — компоненты и потоки данных.
|
||||||
|
- [API](docs/API/09_Operations_Index.md), [формат блокчейна](docs/Blockchain/README.md), [личные сообщения](docs/Personal_Messages/README.md), [Solana](docs/Solana_Architecture/README.md).
|
||||||
|
- [Правила обновления документации](docs/CONTRIBUTING_DOCS.md).
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
TELEGRAM_BOT_TOKEN=replace_me
|
|
||||||
OPENAI_API_KEY=replace_me
|
|
||||||
ALLOWED_TELEGRAM_USERNAME=AidarKC
|
|
||||||
ALLOWED_TELEGRAM_PLAYERS=malvviiina:Милана,zodiaktechnika32:Сергей,oidasyda:Иван,blackbyrd1:Ворон,dimasol1:Дима
|
|
||||||
ALLOWED_TELEGRAM_CHANNEL_USERNAME=shine_writing
|
|
||||||
BOT_USERNAME=aidar_su_bot
|
|
||||||
OPENAI_TRANSCRIBE_MODEL=gpt-4o-mini-transcribe
|
|
||||||
TELEGRAM_FILE_DOWNLOAD_TIMEOUT_SECONDS=300
|
|
||||||
OPENAI_TRANSCRIBE_TIMEOUT_SECONDS=900
|
|
||||||
OPENAI_TTS_MODEL=gpt-4o-mini-tts
|
|
||||||
OPENAI_TTS_VOICE=alloy
|
|
||||||
OPENAI_TTS_RESPONSE_FORMAT=opus
|
|
||||||
OPENAI_TTS_TIMEOUT_SECONDS=180
|
|
||||||
OPENAI_TTS_CHUNK_CHARS=3500
|
|
||||||
CODEX_BIN=/home/ai/.cache/JetBrains/IntelliJIdea2026.1/aia/codex/bin/codex-x86_64-unknown-linux-musl
|
|
||||||
CODEX_WORKDIR=/home/ai/work/SHiNE/SHiNE-server-sha256
|
|
||||||
CODEX_TIMEOUT_SECONDS=900
|
|
||||||
MAX_RETRIES=3
|
|
||||||
DATA_DIR=./data
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
.env
|
|
||||||
data/
|
|
||||||
logs/
|
|
||||||
run/
|
|
||||||
__pycache__/
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
# AGENT.md для SHiNE-agent-bot-coder
|
|
||||||
|
|
||||||
Ты запущен как обработчик входящего Telegram-сообщения от пользователя.
|
|
||||||
|
|
||||||
## Контекст
|
|
||||||
- `SHiNE-agent-bot-coder` — локальный Telegram-бот-сервис агента-кодера для работы с этим проектом.
|
|
||||||
- Сервис принимает входящие сообщения от пользователя Telegram, сохраняет историю, ставит задачи в очередь и последовательно запускает Codex CLI в рабочем проекте.
|
|
||||||
- Текстовые сообщения обрабатываются напрямую, voice/audio сначала распознаются через OpenAI transcription, затем передаются как текстовая задача.
|
|
||||||
- История диалога хранится в JSONL-файле, путь передаётся в промпте.
|
|
||||||
- Сообщение может быть текстом или результатом распознавания голосового.
|
|
||||||
- Ответ пойдёт пользователю в Telegram как обычное текстовое сообщение.
|
|
||||||
- Единственная рабочая реализация сервиса — Python-скрипт `py_bot_service.py`; старая Java-реализация удалена как нерабочая и не должна восстанавливаться без отдельного решения Айдара.
|
|
||||||
- В репозитории также есть отдельный Solana/Anchor-модуль `shine-solana/shine/`; он логически связан с SHiNE, но не должен автоматически подключаться к основному серверному deploy без отдельной команды.
|
|
||||||
- Перед изменениями внутри `shine-solana/shine/` читать локальные инструкции `shine-solana/shine/AGENTS.md`; в git не добавлять локальные ключи, `.git`, `.idea`, `.gradle`, `target`, `node_modules`, `test-ledger`, логи, временные run-отчёты и `.env`-конфиги.
|
|
||||||
|
|
||||||
## Авторитет команд и история
|
|
||||||
- Основной пользователь и источник команд — Айдар: `@AidarKC` / `@aidarkc`.
|
|
||||||
- Дополнительно разрешены игроки из whitelist (`ALLOWED_TELEGRAM_PLAYERS`), каждый со своей отдельной историей и рабочей папкой `Players/<username>/`.
|
|
||||||
- Игроки работают в режиме вопросов/анализа/подготовки материалов: в промпте явно задано правило не менять код проекта и писать материалы только в своей папке.
|
|
||||||
- Для неизвестных пользователей в личном чате сервис отвечает вежливым отказом.
|
|
||||||
- В Telegram-канале/группе `@shine_writing` сервис выполняет сообщения только от Айдара, а ответы отправляет в тот же чат.
|
|
||||||
- Если Telegram сообщает о миграции обычной группы в supergroup, сервис должен запомнить новый `chat_id` и отправлять ответы уже туда.
|
|
||||||
- На события подключения/отключения пользователей (join/leave) сервис не отвечает и ничего не отправляет.
|
|
||||||
|
|
||||||
## Очередь и состояние
|
|
||||||
- Входящие задачи записываются в файловую очередь и обрабатываются строго по одной, чтобы не смешивать изменения в проекте.
|
|
||||||
- Сервис ведёт состояние активной задачи и текущего файла истории, а после рестарта продолжает незавершённую обработку с учётом сохранённого состояния.
|
|
||||||
- Истории диалогов хранятся в JSONL по каждому разрешённому username отдельно: `data/history/<username>/`.
|
|
||||||
- Архив истории после `/new`: `data/history/<username>/archive/`.
|
|
||||||
- После `/new` для этого же пользователя должен сбрасываться и контекст продолжения Codex-сессии; следующий запрос запускается как новая сессия, не через resume.
|
|
||||||
- Для просмотра истории игрока открывать файлы в его папке истории по username.
|
|
||||||
- Дедупликация входящих Telegram update нужна, чтобы одно сообщение не попало в обработку повторно.
|
|
||||||
- Если Codex молчит во время активной задачи 2 минуты подряд, сервис отправляет аварийный статус с общим временем работы задачи; при дальнейшем молчании повторяет статус каждые 2 минуты.
|
|
||||||
- После успешной обработки задачи из личного чата Айдара сервис должен отправить публичный итоговый отчёт в группу `@shine_writing`: первым сообщением исходный запрос, вторым сообщением-ответом итоговый ответ Codex. Промежуточные статусы в группу не дублировать.
|
|
||||||
- Для приватных voice/audio-запросов в публичном отчёте первым сообщением отправлять исходный Telegram voice/audio-файл с подписью, где указан распознанный текст. В пользовательском тексте отчёта не показывать Telegram `file_id`.
|
|
||||||
- Озвучивание финальных ответов настраивается персонально для каждого Telegram-пользователя командами `/voice_on`, `/voice_off`; для новых пользователей оно включено по умолчанию.
|
|
||||||
- Адаптация текста перед озвучкой настраивается персонально командами `/voice_rewrite_on`, `/voice_rewrite_off`. Если она включена, сервис перед TTS вызывает дешёвую текстовую модель OpenAI и делает голосовую версию без длинных хэшей, путей, команд и технического шума, сохраняя смысл и порядок исходного ответа.
|
|
||||||
- Режим личных ответов настраивается персонально командами `/single_message_on`, `/single_message_off`: либо одно редактируемое сообщение по этапам, либо отдельные сообщения как раньше.
|
|
||||||
- Команда `/settings` должна сразу показывать текущее состояние всех персональных настроек пользователя и список команд для их изменения.
|
|
||||||
- Если озвучивание включено, после полного текстового финального ответа сервис дополнительно отправляет voice-файл с синтезированной речью через OpenAI TTS даже для текстовых запросов. Voice отправляется в исходный чат, а также в известный личный чат пользователя и в общий чат `@shine_writing`, если они отличаются и доступны. Промежуточные статусы не озвучивать.
|
|
||||||
- Команда `/status` должна показывать состояние очереди и персональные настройки: voice-ответы, адаптацию текста перед озвучкой и режим одного сообщения в личке.
|
|
||||||
|
|
||||||
## Правила голосовой версии ответа
|
|
||||||
- Текстовый финальный ответ должен оставаться полноценным: в нём можно указывать команды, пути, хэши коммитов, номера версий, результаты проверок и другие технические детали.
|
|
||||||
- Голосовую версию финального ответа нужно делать короче и проще для восприятия на слух. Основной механизм — персонально включаемая адаптация текста через дополнительный OpenAI-вызов перед TTS.
|
|
||||||
- В голосовой версии не зачитывать длинные хэши коммитов, токены, file_id, длинные команды, полные пути и другие строки, которые человек всё равно не сможет надёжно запомнить на слух.
|
|
||||||
- Для commit/push в голосовой версии достаточно сказать краткий итог: что коммит сделан, что именно изменено, проверки прошли без ошибок, push выполнен, рабочее дерево чистое.
|
|
||||||
- Если пользователю нужны точные команды, хэши или подробности, они должны оставаться в текстовом ответе.
|
|
||||||
|
|
||||||
## Планы и отложенные фичи
|
|
||||||
- Планы проекта по отложенным фичам хранятся в `TODO/`.
|
|
||||||
- Внутри есть три горизонта:
|
|
||||||
- `near/` - ближайшие планы, обычно сегодня/завтра;
|
|
||||||
- `medium/` - среднесрочные планы, обычно недели или 1-2 месяца;
|
|
||||||
- `far/` - дальнее будущее без понятного срока.
|
|
||||||
- Если пользователь спрашивает, какие есть планы или что можно продолжить, нужно смотреть эти три папки и отвечать кратким списком по горизонтам.
|
|
||||||
- Файлы из `TODO/` не начинать реализовывать без явной команды пользователя.
|
|
||||||
- После реализации фичи, требующей ручной проверки, нужно добавить отдельный файл в `Dev_Docs/Pending_Features/`.
|
|
||||||
|
|
||||||
## Центр задач и предложений
|
|
||||||
- Сервис хранит простые задачи и предложения в `data/task_center/items.json`.
|
|
||||||
- Айдар может смотреть список через `/tasks` или естественные фразы вроде «покажи мои задачи», «покажи задачи Миланы».
|
|
||||||
- Айдар может ставить задачи игрокам фразой вида «поставь задачу Милане: ...».
|
|
||||||
- Игроки могут отправлять предложения Айдару фразой вида `предложение: ...`, `идея: ...` или `заявка: ...`.
|
|
||||||
- Статусы меняются фразами с ID: `одобрить TC-0001`, `отклонить TC-0001`, `доработать TC-0001`, `закрыть TC-0001`.
|
|
||||||
- После финального ответа в личном чате сервис добавляет короткое напоминание, если у пользователя есть активные задачи или предложения.
|
|
||||||
|
|
||||||
## Локальный запуск и systemd
|
|
||||||
- Основной запуск сервиса выполняется Python-скриптом `py_bot_service.py` из папки `SHiNE-agent-bot-coder/`.
|
|
||||||
- Локальные секреты и параметры должны храниться в `.env`, этот файл не коммитится.
|
|
||||||
- Для проверки Codex без Telegram можно использовать self-test режим сервиса.
|
|
||||||
- Для постоянного локального запуска используется user-level systemd service `shine-agent-bot-coder`; скрипты установки лежат в `SHiNE-agent-bot-coder/scripts/systemd/`.
|
|
||||||
- Если меняется логика сервиса, после изменений нужно проверить запуск локально и при необходимости перезапустить user systemd service.
|
|
||||||
- Команда Telegram `/restart` (`/restart_service`) доступна только Айдару и выполняет отложенный рестарт после текущей задачи, до взятия следующей. Аварийный жёсткий рестарт доступен только Айдару командами `/restart_hard`, `/restart_now`, `/restart_force`.
|
|
||||||
|
|
||||||
## Правила ответа
|
|
||||||
- Пиши содержательно и коротко.
|
|
||||||
- Не упоминай внутренние служебные детали, файловую систему и технические логи.
|
|
||||||
- Если запрос требует действий с кодом/проектом, выполняй их в рабочей директории.
|
|
||||||
- Если для ответа данных недостаточно, задай ровно один уточняющий вопрос.
|
|
||||||
- Если была ошибка предыдущего запуска, в промпте будет пометка retry — учти это и продолжи с учётом текущего состояния проекта.
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
# AGENTS
|
|
||||||
|
|
||||||
## Назначение
|
|
||||||
- Это автоматически читаемые инструкции Codex для папки `SHiNE-agent-bot-coder/`.
|
|
||||||
- `SHiNE-agent-bot-coder` — локальный Telegram-бот-сервис агента-кодера для работы с проектом SHiNE.
|
|
||||||
- Если пользователь говорит «агент MD», «агент с MD» или похожим образом про файл инструкций Codex, считать, что имеется в виду `AGENTS.md`.
|
|
||||||
|
|
||||||
## Связанные инструкции
|
|
||||||
- Подробные служебные правила Telegram-обработчика лежат в `AGENT.md`.
|
|
||||||
- `AGENT.md` используется самим сервисом как файл инструкций, который передаётся в промпт обработчика входящих Telegram-сообщений.
|
|
||||||
- При изменении логики сервиса сначала читать `AGENT.md`, затем код `py_bot_service.py`.
|
|
||||||
|
|
||||||
## Планы и задачи
|
|
||||||
- Отложенные задачи проекта лежат в `../TODO/`.
|
|
||||||
- Точка входа по планам: `../TODO/README.md`.
|
|
||||||
- Горизонты планов:
|
|
||||||
- `near/` - ближайшие планы;
|
|
||||||
- `medium/` - среднесрочные планы;
|
|
||||||
- `far/` - дальнее будущее.
|
|
||||||
- Если пользователь спрашивает, какие есть планы или что можно продолжить, кратко перечислять задачи по этим горизонтам.
|
|
||||||
- Не начинать реализацию задач из `TODO` без явной команды пользователя.
|
|
||||||
|
|
||||||
## Проверка после изменений
|
|
||||||
- Если меняется логика Telegram-бота, проверить локальный запуск или self-test, когда это уместно.
|
|
||||||
- Если меняется только документация или инструкции, достаточно проверить, что ссылки на документы актуальны.
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
@AGENTS.md
|
|
||||||
@AGENT.md
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
# Промпты для режима игроков (на согласование)
|
|
||||||
|
|
||||||
## 1) Базовый служебный промпт (добавка к задаче игрока)
|
|
||||||
|
|
||||||
```text
|
|
||||||
Режим игрока (обязательно):
|
|
||||||
- Пользователь: <Имя> (@<username>).
|
|
||||||
- Рабочая папка игрока: <project>/Players/<username>
|
|
||||||
- Код проекта не изменять.
|
|
||||||
- Можно отвечать на вопросы по проекту, предлагать идеи и готовить ТЗ.
|
|
||||||
- Если нужны правки кода, описывать предложение текстом и сохранять материалы только в папке игрока.
|
|
||||||
```
|
|
||||||
|
|
||||||
## 2) Приветственное сообщение игроку (один раз)
|
|
||||||
|
|
||||||
```text
|
|
||||||
Привет, <Имя>.
|
|
||||||
Можно задавать вопросы по проекту, просить анализ, идеи и подготовку готового ТЗ.
|
|
||||||
Команда /new начинает новую сессию и архивирует текущую историю.
|
|
||||||
```
|
|
||||||
|
|
||||||
## 3) Отказ неизвестному пользователю
|
|
||||||
|
|
||||||
```text
|
|
||||||
Извините, доступ к этому агенту пока не выдан. Обратитесь к Айдару.
|
|
||||||
```
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
# SHiNE-agent-bot-coder
|
|
||||||
|
|
||||||
Локальный Telegram-бот-сервис для пользователя `ai`:
|
|
||||||
- принимает сообщения от `@AidarKC`;
|
|
||||||
- поддерживает whitelist игроков (`ALLOWED_TELEGRAM_PLAYERS`) с отдельными историями;
|
|
||||||
- ведёт историю диалога в `JSONL`;
|
|
||||||
- ставит задачи в файловую очередь;
|
|
||||||
- обрабатывает задачи строго последовательно;
|
|
||||||
- поддерживает текстовые и голосовые сообщения (voice/audio через OpenAI transcription);
|
|
||||||
- вызывает Codex CLI и отправляет ответ в Telegram;
|
|
||||||
- в личном чате умеет работать в двух персонально переключаемых режимах: через одно редактируемое статусное сообщение или через отдельные сообщения по этапам;
|
|
||||||
- умеет персонально для каждого пользователя озвучивать финальный ответ через OpenAI TTS;
|
|
||||||
- при рестарте восстанавливает незавершённые задачи;
|
|
||||||
- отправляет аварийный статус только если Codex молчит 2 минуты подряд во время активной задачи;
|
|
||||||
- принимает сообщения из канала/группы `@shine_writing`, выполняет команды только от `@AidarKC`;
|
|
||||||
- учитывает миграцию обычной Telegram-группы в supergroup и перенаправляет ответы на новый `chat_id`.
|
|
||||||
|
|
||||||
Рабочая реализация сервиса — только `py_bot_service.py`. Старая Java-реализация удалена, потому что не заработала и больше не используется.
|
|
||||||
|
|
||||||
## Структура
|
|
||||||
- `.env` — локальные секреты и параметры запуска (не коммитится);
|
|
||||||
- `data/py_queue.jsonl` — очередь Python-сервиса;
|
|
||||||
- `data/py_state.json` — текущее состояние Python-сервиса;
|
|
||||||
- `data/py_processed_updates.log` — дедуп входящих update;
|
|
||||||
- `data/history/<username>/*.jsonl` — активные истории по пользователям;
|
|
||||||
- `data/history/<username>/archive/*.jsonl` — архивы после `/new`.
|
|
||||||
|
|
||||||
## Локальный запуск
|
|
||||||
1. Скопировать пример:
|
|
||||||
- `cp .env.example .env`
|
|
||||||
2. Заполнить секреты в `.env`.
|
|
||||||
- `TELEGRAM_BOT_TOKEN` — токен рабочего Telegram-бота.
|
|
||||||
- `ALLOWED_TELEGRAM_USERNAME` — пользователь, чьи сообщения выполняются как команды.
|
|
||||||
- `ALLOWED_TELEGRAM_PLAYERS` — whitelist игроков в формате `username:Имя,username2:Имя2`.
|
|
||||||
- `ALLOWED_TELEGRAM_CHANNEL_USERNAME` — канал, из которого принимаются `channel_post`; обычные group/supergroup-сообщения обрабатываются как `message`.
|
|
||||||
- `TELEGRAM_API_BASE_URL` — базовый URL Bot API; по умолчанию `https://api.telegram.org`. Для очень больших voice/audio можно поднять локальный `telegram-bot-api` и направить бота туда.
|
|
||||||
- `TELEGRAM_FILE_DOWNLOAD_TIMEOUT_SECONDS` — тайм-аут скачивания voice/audio из Telegram, по умолчанию 300 секунд.
|
|
||||||
- `OPENAI_TRANSCRIBE_TIMEOUT_SECONDS` — тайм-аут распознавания voice/audio в OpenAI, по умолчанию 900 секунд.
|
|
||||||
- `OPENAI_TRANSCRIBE_MAX_UPLOAD_BYTES` — безопасный лимит размера одного куска для OpenAI transcription, по умолчанию `24 MiB`.
|
|
||||||
- `OPENAI_TRANSCRIBE_MAX_CHUNK_SECONDS` — максимальная длина одного куска при длинном аудио, по умолчанию `900` секунд.
|
|
||||||
- `OPENAI_TRANSCRIBE_OVERLAP_SECONDS` — перекрытие соседних кусков для более ровной склейки текста, по умолчанию `2` секунды.
|
|
||||||
- `OPENAI_TRANSCRIBE_REENCODE_BITRATE_KBPS` — битрейт локального пережатия длинного аудио через `ffmpeg`, по умолчанию `24`.
|
|
||||||
- `OPENAI_TRANSCRIBE_FFMPEG_TIMEOUT_SECONDS` — тайм-аут локальной обработки длинного аудио через `ffmpeg`/`ffprobe`, по умолчанию `1800`.
|
|
||||||
- `FFMPEG_BIN` и `FFPROBE_BIN` — пути к локальным бинарям `ffmpeg`/`ffprobe`, если они не лежат в `PATH`.
|
|
||||||
- `OPENAI_TTS_MODEL` — модель синтеза речи, по умолчанию `gpt-4o-mini-tts`.
|
|
||||||
- `OPENAI_TTS_VOICE` — голос синтеза речи, по умолчанию `alloy`.
|
|
||||||
- `OPENAI_TTS_RESPONSE_FORMAT` — аудиоформат для Telegram voice, по умолчанию `opus`.
|
|
||||||
- `OPENAI_TTS_TIMEOUT_SECONDS` — тайм-аут генерации одного фрагмента речи, по умолчанию 180 секунд.
|
|
||||||
- `OPENAI_TTS_CHUNK_CHARS` — максимальный размер одного фрагмента озвучки, по умолчанию 3500 символов.
|
|
||||||
3. Запуск:
|
|
||||||
- `python3 SHiNE-agent-bot-coder/py_bot_service.py`
|
|
||||||
|
|
||||||
## Быстрый self-test Codex (без Telegram)
|
|
||||||
```bash
|
|
||||||
python3 SHiNE-agent-bot-coder/py_bot_service.py --selftest-codex "Ответь одной строкой: Codex работает"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Длинные voice/audio
|
|
||||||
- Если аудио короткое, бот отправляет его в OpenAI как раньше.
|
|
||||||
- Если аудио большое или длинное, бот локально пережимает его через `ffmpeg`, при необходимости режет на куски и распознаёт последовательно.
|
|
||||||
- Если Telegram заранее сообщает большой размер файла, бот больше не отказывается сразу: сначала явно пишет, что пробует скачать файл, затем отдельно сообщает, удалось ли скачивание, и только после успешной загрузки переходит к подготовке аудио и OpenAI.
|
|
||||||
- Для очень больших файлов упираемся не только в OpenAI, но и в лимит обычного облачного Telegram Bot API на скачивание файла ботом. Для таких случаев нужно использовать локальный `telegram-bot-api` сервер и указать его через `TELEGRAM_API_BASE_URL`.
|
|
||||||
|
|
||||||
## Статусы в личке
|
|
||||||
- Для `private`-чата бот поддерживает персональную настройку режима ответа.
|
|
||||||
- По умолчанию он старается не засорять переписку промежуточными сообщениями: создаёт одно статусное сообщение и редактирует его по этапам.
|
|
||||||
- Если включить `/single_message_off`, бот возвращается к старому режиму и отправляет отдельные сообщения по этапам и финальный ответ отдельно.
|
|
||||||
- Если финальный текст в режиме одного сообщения не помещается целиком, бот оставляет первую часть в отредактированном статусном сообщении и отправляет максимум ещё одно дополнительное текстовое сообщение с хвостом ответа.
|
|
||||||
- Голосовой ответ, если он включён, всегда приходит отдельным новым сообщением.
|
|
||||||
|
|
||||||
## Запуск как systemd-сервис
|
|
||||||
Файлы для установки:
|
|
||||||
- `scripts/systemd/shine-agent-bot-coder.service`
|
|
||||||
- `scripts/systemd/install-local-systemd.sh`
|
|
||||||
|
|
||||||
Установка:
|
|
||||||
- `bash SHiNE-agent-bot-coder/scripts/systemd/install-local-systemd.sh`
|
|
||||||
|
|
||||||
Проверка:
|
|
||||||
- `systemctl --user status shine-agent-bot-coder --no-pager`
|
|
||||||
- `journalctl --user -u shine-agent-bot-coder -f`
|
|
||||||
|
|
||||||
Перезапуск после изменений:
|
|
||||||
- `systemctl --user restart shine-agent-bot-coder`
|
|
||||||
|
|
||||||
## Telegram-команды
|
|
||||||
- `/status` — активная задача и размер очереди.
|
|
||||||
- `/settings` — текущие пользовательские настройки и команды для их изменения.
|
|
||||||
- `/queue` — список задач в очереди.
|
|
||||||
- `/stop` — остановить текущую задачу.
|
|
||||||
- `/cancel <id|all>` — удалить задачу по id/префиксу или очистить очередь.
|
|
||||||
- `/new` — архивировать текущую историю, сбросить продолжение Codex-сессии для этого пользователя и начать новый диалог.
|
|
||||||
- `/voice_on` — включить озвучивание финальных ответов для текущего пользователя.
|
|
||||||
- `/voice_off` — выключить озвучивание финальных ответов для текущего пользователя.
|
|
||||||
- `/voice_rewrite_on` — включить адаптацию текста перед озвучкой.
|
|
||||||
- `/voice_rewrite_off` — выключить адаптацию текста перед озвучкой.
|
|
||||||
- `/single_message_on` — вести ответ в личке через одно редактируемое сообщение.
|
|
||||||
- `/single_message_off` — слать отдельные сообщения по этапам и отдельный финальный ответ.
|
|
||||||
- `/restart` или `/restart_service` — отложенный рестарт после текущей задачи, до взятия следующей (только для Айдара).
|
|
||||||
- `/restart_hard` — жёсткий рестарт прямо сейчас (только для Айдара).
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
ROOT_DIR="/home/ai/work/SHiNE/SHiNE-server-sha256"
|
|
||||||
SERVICE_DIR="${ROOT_DIR}/SHiNE-agent-bot-coder"
|
|
||||||
UNIT_SRC="${SERVICE_DIR}/scripts/systemd/shine-agent-bot-coder.service"
|
|
||||||
UNIT_DST="${HOME}/.config/systemd/user/shine-agent-bot-coder.service"
|
|
||||||
|
|
||||||
echo "[1/6] Проверка python3..."
|
|
||||||
command -v python3 >/dev/null 2>&1 || { echo "python3 не найден"; exit 1; }
|
|
||||||
|
|
||||||
echo "[2/6] Подготовка папки логов..."
|
|
||||||
mkdir -p "${SERVICE_DIR}/logs"
|
|
||||||
|
|
||||||
echo "[3/6] Копирование user systemd unit..."
|
|
||||||
mkdir -p "$(dirname "${UNIT_DST}")"
|
|
||||||
cp "${UNIT_SRC}" "${UNIT_DST}"
|
|
||||||
|
|
||||||
echo "[4/6] daemon-reload..."
|
|
||||||
systemctl --user daemon-reload
|
|
||||||
|
|
||||||
echo "[5/6] enable + start..."
|
|
||||||
systemctl --user enable --now shine-agent-bot-coder
|
|
||||||
|
|
||||||
echo "[6/6] Статус:"
|
|
||||||
systemctl --user status shine-agent-bot-coder --no-pager
|
|
||||||
|
|
||||||
echo "Готово. Логи: journalctl --user -u shine-agent-bot-coder -f"
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=SHiNE Agent Bot Coder (Telegram + Codex queue worker)
|
|
||||||
After=network-online.target
|
|
||||||
Wants=network-online.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=simple
|
|
||||||
WorkingDirectory=/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-agent-bot-coder
|
|
||||||
EnvironmentFile=/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-agent-bot-coder/.env
|
|
||||||
ExecStart=/usr/bin/python3 /home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-agent-bot-coder/py_bot_service.py
|
|
||||||
Restart=always
|
|
||||||
RestartSec=5
|
|
||||||
TimeoutStopSec=20
|
|
||||||
SuccessExitStatus=143 0
|
|
||||||
StandardOutput=append:/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-agent-bot-coder/logs/service.log
|
|
||||||
StandardError=append:/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-agent-bot-coder/logs/service.log
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=default.target
|
|
||||||