Compare commits
27
Commits
0934105952
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8716c232e | ||
|
|
a3e330ed77 | ||
|
|
672267b991 | ||
|
|
8398442544 | ||
|
|
b29512d922 | ||
|
|
6e4525df38 | ||
|
|
60a304a93d | ||
|
|
f504553ab6 | ||
|
|
bbfe61a9ed | ||
|
|
73bc078465 | ||
|
|
8d4f1da028 | ||
|
|
1d36a757c0 | ||
|
|
648e201f5e | ||
|
|
400d308f4a | ||
|
|
1c9120a197 | ||
|
|
3b560799af | ||
|
|
3abdd8816c | ||
|
|
cf42e86322 | ||
|
|
59dbd7b035 | ||
|
|
d3e44125a2 | ||
|
|
ebb739a3a0 | ||
|
|
441347fc95 | ||
|
|
a9779cbade | ||
|
|
704d1c9c0b | ||
|
|
95bfcaa4d2 | ||
|
|
01d0be7004 | ||
|
|
a8c7c42471 |
@@ -13,6 +13,15 @@ get_code_gen:
|
||||
gen_prot:
|
||||
./alox.protogen -i prot.json -o main/uart
|
||||
|
||||
switch_to_s3:
|
||||
idf.py set-target esp32s3
|
||||
cp sdkconfig.s3 sdkconfig
|
||||
idf.py build
|
||||
|
||||
switch_to_c3:
|
||||
idf.py set-target esp32c3
|
||||
cp sdkconfig.c3 sdkconfig
|
||||
idf.py build
|
||||
|
||||
buildIdf:
|
||||
idf.py build
|
||||
@@ -20,6 +29,23 @@ buildIdf:
|
||||
flashMini:
|
||||
idf.py flash -p /dev/ttyACM0
|
||||
|
||||
flashMini2:
|
||||
idf.py flash -p /dev/ttyACM1
|
||||
|
||||
flashMini3:
|
||||
idf.py flash -p /dev/ttyACM2
|
||||
|
||||
flashCluster:
|
||||
idf.py flash -p /dev/ttyACM1
|
||||
idf.py flash -p /dev/ttyACM2
|
||||
idf.py flash -p /dev/ttyACM3
|
||||
idf.py flash -p /dev/ttyACM4
|
||||
idf.py flash -p /dev/ttyACM5
|
||||
idf.py flash -p /dev/ttyACM6
|
||||
idf.py flash -p /dev/ttyACM7
|
||||
idf.py flash -p /dev/ttyACM8
|
||||
|
||||
|
||||
monitorMini:
|
||||
idf.py monitor -p /dev/ttyACM0
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
module alox.tool
|
||||
|
||||
go 1.24.5
|
||||
|
||||
require (
|
||||
github.com/pterm/pterm v0.12.81
|
||||
go.bug.st/serial v1.6.4
|
||||
)
|
||||
|
||||
require (
|
||||
atomicgo.dev/cursor v0.2.0 // indirect
|
||||
atomicgo.dev/keyboard v0.2.9 // indirect
|
||||
atomicgo.dev/schedule v0.1.0 // indirect
|
||||
github.com/containerd/console v1.0.5 // indirect
|
||||
github.com/creack/goselect v0.1.2 // indirect
|
||||
github.com/gookit/color v1.5.4 // indirect
|
||||
github.com/lithammer/fuzzysearch v1.1.8 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
golang.org/x/sys v0.33.0 // indirect
|
||||
golang.org/x/term v0.32.0 // indirect
|
||||
golang.org/x/text v0.26.0 // indirect
|
||||
)
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg=
|
||||
atomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3QDdJtlmAxQULOmA13Gz6e2DWbSAS8RUOmNYQ=
|
||||
atomicgo.dev/cursor v0.2.0 h1:H6XN5alUJ52FZZUkI7AlJbUc1aW38GWZalpYRPpoPOw=
|
||||
atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU=
|
||||
atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8=
|
||||
atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ=
|
||||
atomicgo.dev/schedule v0.1.0 h1:nTthAbhZS5YZmgYbb2+DH8uQIZcTlIrd4eYr3UQxEjs=
|
||||
atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU=
|
||||
github.com/MarvinJWendt/testza v0.1.0/go.mod h1:7AxNvlfeHP7Z/hDQ5JtE3OKYT3XFUeLCDE2DQninSqs=
|
||||
github.com/MarvinJWendt/testza v0.2.1/go.mod h1:God7bhG8n6uQxwdScay+gjm9/LnO4D3kkcZX4hv9Rp8=
|
||||
github.com/MarvinJWendt/testza v0.2.8/go.mod h1:nwIcjmr0Zz+Rcwfh3/4UhBp7ePKVhuBExvZqnKYWlII=
|
||||
github.com/MarvinJWendt/testza v0.2.10/go.mod h1:pd+VWsoGUiFtq+hRKSU1Bktnn+DMCSrDrXDpX2bG66k=
|
||||
github.com/MarvinJWendt/testza v0.2.12/go.mod h1:JOIegYyV7rX+7VZ9r77L/eH6CfJHHzXjB69adAhzZkI=
|
||||
github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/2oUqKc6bF2c=
|
||||
github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE=
|
||||
github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4=
|
||||
github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY=
|
||||
github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk=
|
||||
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
|
||||
github.com/containerd/console v1.0.5 h1:R0ymNeydRqH2DmakFNdmjR2k0t7UPuiOV/N/27/qqsc=
|
||||
github.com/containerd/console v1.0.5/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
|
||||
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
|
||||
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ=
|
||||
github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo=
|
||||
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
|
||||
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
|
||||
github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=
|
||||
github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU=
|
||||
github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/lithammer/fuzzysearch v1.1.8 h1:/HIuJnjHuXS8bKaiTMeeDlW2/AyIWk2brx1V8LFgLN4=
|
||||
github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pterm/pterm v0.12.27/go.mod h1:PhQ89w4i95rhgE+xedAoqous6K9X+r6aSOI2eFF7DZI=
|
||||
github.com/pterm/pterm v0.12.29/go.mod h1:WI3qxgvoQFFGKGjGnJR849gU0TsEOvKn5Q8LlY1U7lg=
|
||||
github.com/pterm/pterm v0.12.30/go.mod h1:MOqLIyMOgmTDz9yorcYbcw+HsgoZo3BQfg2wtl3HEFE=
|
||||
github.com/pterm/pterm v0.12.31/go.mod h1:32ZAWZVXD7ZfG0s8qqHXePte42kdz8ECtRyEejaWgXU=
|
||||
github.com/pterm/pterm v0.12.33/go.mod h1:x+h2uL+n7CP/rel9+bImHD5lF3nM9vJj80k9ybiiTTE=
|
||||
github.com/pterm/pterm v0.12.36/go.mod h1:NjiL09hFhT/vWjQHSj1athJpx6H8cjpHXNAK5bUw8T8=
|
||||
github.com/pterm/pterm v0.12.40/go.mod h1:ffwPLwlbXxP+rxT0GsgDTzS3y3rmpAO1NMjUkGTYf8s=
|
||||
github.com/pterm/pterm v0.12.81 h1:ju+j5I2++FO1jBKMmscgh5h5DPFDFMB7epEjSoKehKA=
|
||||
github.com/pterm/pterm v0.12.81/go.mod h1:TyuyrPjnxfwP+ccJdBTeWHtd/e0ybQHkOS/TakajZCw=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ=
|
||||
github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
|
||||
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
|
||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
|
||||
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
|
||||
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
+508
@@ -0,0 +1,508 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/pterm/pterm"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
type ParserState int
|
||||
|
||||
const (
|
||||
// MISC
|
||||
UART_ECHO = 0x01
|
||||
UART_VERSION = 0x02
|
||||
UART_CLIENT_INFO = 0x03
|
||||
|
||||
// OTA
|
||||
UART_OTA_START = 0x10
|
||||
UART_OTA_PAYLOAD = 0x11
|
||||
UART_OTA_END = 0x12
|
||||
UART_OTA_STATUS = 0x13
|
||||
)
|
||||
|
||||
const (
|
||||
WAITING_FOR_START_BYTE ParserState = iota
|
||||
ESCAPED_MESSAGE_ID
|
||||
GET_MESSAGE_ID
|
||||
IN_PAYLOD
|
||||
ESCAPED_PAYLOAD_BYTE
|
||||
)
|
||||
|
||||
const (
|
||||
START_BYTE = 0xAA
|
||||
ESCAPE_BYTE = 0xBB
|
||||
END_BYTE = 0xCC
|
||||
)
|
||||
|
||||
type ParseError int
|
||||
|
||||
const (
|
||||
WRONG_CHECKSUM ParseError = iota
|
||||
UNEXPECETD_BYTE
|
||||
)
|
||||
|
||||
type MessageReceive struct {
|
||||
raw_message []byte
|
||||
parsed_message []byte
|
||||
checksum byte
|
||||
error ParseError
|
||||
state ParserState
|
||||
write_index int
|
||||
raw_write_index int
|
||||
}
|
||||
|
||||
type OTASyncManager struct {
|
||||
OTA_MessageCounter int
|
||||
OTA_PayloadMessageSequence int
|
||||
NewOTAMessage chan MessageReceive
|
||||
TimeoutMessage time.Duration
|
||||
}
|
||||
|
||||
func (ot *OTASyncManager) WaitForNextMessageTimeout() (*MessageReceive, error) {
|
||||
select {
|
||||
case msg := <-ot.NewOTAMessage:
|
||||
return &msg, nil
|
||||
case <-time.After(ot.TimeoutMessage):
|
||||
return nil, fmt.Errorf("Message Timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func initMessageReceive(mr *MessageReceive) {
|
||||
mr.raw_message = make([]byte, 1024*4)
|
||||
mr.parsed_message = make([]byte, 1024*4)
|
||||
mr.checksum = 0
|
||||
mr.error = 0
|
||||
mr.write_index = 0
|
||||
mr.raw_write_index = 0
|
||||
mr.state = WAITING_FOR_START_BYTE
|
||||
}
|
||||
|
||||
func addByteToRawBuffer(mr *MessageReceive, pbyte byte) {
|
||||
mr.raw_message[mr.raw_write_index] = pbyte
|
||||
mr.raw_write_index += 1
|
||||
}
|
||||
func addByteToParsedBuffer(mr *MessageReceive, pbyte byte) {
|
||||
mr.parsed_message[mr.write_index] = pbyte
|
||||
mr.write_index += 1
|
||||
mr.checksum ^= pbyte
|
||||
}
|
||||
|
||||
func parse_uart_ota_payload_payload(payloadBuffer []byte, payload_len int) {
|
||||
//fmt.Printf("RAW BUFFER: % 02X", payloadBuffer[:payload_len])
|
||||
if payload_len != 4 {
|
||||
fmt.Printf("Payload should be 4 is %v", payload_len)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("Sequence %v, WriteIndex %v", binary.LittleEndian.Uint16(payloadBuffer[0:1]), binary.LittleEndian.Uint16(payloadBuffer[2:3]))
|
||||
}
|
||||
|
||||
func parse_uart_version_payload(payloadBuffer []byte, payload_len int) {
|
||||
type payload_data struct {
|
||||
Version uint16
|
||||
BuildHash [7]uint8
|
||||
}
|
||||
|
||||
tableHeaders := pterm.TableData{
|
||||
{"Version", "Buildhash"},
|
||||
}
|
||||
|
||||
tableData := tableHeaders
|
||||
|
||||
tableData = append(tableData, []string{
|
||||
fmt.Sprintf("%d", binary.LittleEndian.Uint16(payloadBuffer[1:3])),
|
||||
fmt.Sprintf("%s", payloadBuffer[3:10]),
|
||||
})
|
||||
|
||||
err := pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render()
|
||||
if err != nil {
|
||||
fmt.Printf("Fehler beim Rendern der Tabelle: %s\n", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func parse_uart_client_info_payload(payloadBuffer []byte, payload_len int) {
|
||||
|
||||
type payload_data struct {
|
||||
ClientID uint8
|
||||
IsAvailable uint8
|
||||
SlotIsUsed uint8
|
||||
MACAddr [6]uint8
|
||||
LastPing uint32
|
||||
LastSuccessfulPing uint32
|
||||
Version uint16
|
||||
}
|
||||
|
||||
tableHeaders := pterm.TableData{
|
||||
{"Client ID", "Verfügbar", "Genutzt", "MAC-Adresse", "Last Ping", "Letzter Erfolg Ping", "Version"},
|
||||
}
|
||||
|
||||
tableData := tableHeaders
|
||||
|
||||
currentOffset := 2
|
||||
|
||||
const (
|
||||
ENTRY_LEN = 19
|
||||
OFFSET_MAC_ADDR = 3
|
||||
OFFSET_LAST_PING = 9
|
||||
OFFSET_LAST_SUCCESS_PING = 13
|
||||
OFFSET_VERSION = 17
|
||||
)
|
||||
|
||||
for i := 0; i < int(payloadBuffer[1]); i++ {
|
||||
if currentOffset+ENTRY_LEN > payload_len {
|
||||
fmt.Printf("Fehler: Payload zu kurz für Client-Eintrag %d\n", i)
|
||||
break
|
||||
}
|
||||
|
||||
entryBytes := payloadBuffer[currentOffset : currentOffset+ENTRY_LEN]
|
||||
|
||||
var clientData payload_data
|
||||
|
||||
clientData.ClientID = entryBytes[0]
|
||||
clientData.IsAvailable = entryBytes[1]
|
||||
clientData.SlotIsUsed = entryBytes[2]
|
||||
|
||||
copy(clientData.MACAddr[:], entryBytes[OFFSET_MAC_ADDR:OFFSET_MAC_ADDR+6])
|
||||
|
||||
clientData.LastPing = binary.LittleEndian.Uint32(entryBytes[OFFSET_LAST_PING : OFFSET_LAST_PING+4])
|
||||
clientData.LastSuccessfulPing = binary.LittleEndian.Uint32(entryBytes[OFFSET_LAST_SUCCESS_PING : OFFSET_LAST_SUCCESS_PING+4])
|
||||
clientData.Version = binary.LittleEndian.Uint16(entryBytes[OFFSET_VERSION : OFFSET_VERSION+2])
|
||||
|
||||
// Füge die geparsten Daten als String-Slice zur Tabelle hinzu
|
||||
tableData = append(tableData, []string{
|
||||
fmt.Sprintf("%d", clientData.ClientID),
|
||||
fmt.Sprintf("%d", clientData.IsAvailable),
|
||||
fmt.Sprintf("%d", clientData.SlotIsUsed),
|
||||
fmt.Sprintf("%X:%X:%X:%X:%X:%X",
|
||||
clientData.MACAddr[0], clientData.MACAddr[1], clientData.MACAddr[2],
|
||||
clientData.MACAddr[3], clientData.MACAddr[4], clientData.MACAddr[5]),
|
||||
fmt.Sprintf("%d", clientData.LastPing),
|
||||
fmt.Sprintf("%d", clientData.LastSuccessfulPing),
|
||||
fmt.Sprintf("%d", clientData.Version),
|
||||
})
|
||||
|
||||
currentOffset += ENTRY_LEN
|
||||
}
|
||||
err := pterm.DefaultTable.WithHasHeader().WithBoxed().WithData(tableData).Render()
|
||||
if err != nil {
|
||||
fmt.Printf("Fehler beim Rendern der Tabelle: %s\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func message_receive_callback(mr MessageReceive) {
|
||||
log.Printf("Message Received: % 02X\n", mr.raw_message[:mr.raw_write_index])
|
||||
switch mr.parsed_message[0] {
|
||||
case byte(UART_ECHO):
|
||||
break
|
||||
case UART_VERSION:
|
||||
parse_uart_version_payload(mr.parsed_message, mr.write_index)
|
||||
break
|
||||
case UART_CLIENT_INFO:
|
||||
parse_uart_client_info_payload(mr.parsed_message, mr.write_index)
|
||||
break
|
||||
case UART_OTA_START:
|
||||
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||
break
|
||||
case UART_OTA_PAYLOAD:
|
||||
parse_uart_ota_payload_payload(mr.parsed_message, mr.write_index)
|
||||
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||
break
|
||||
case UART_OTA_END:
|
||||
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||
break
|
||||
case UART_OTA_STATUS:
|
||||
OTA_UpdateHandler.NewOTAMessage <- mr
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func message_receive_failed_callback(mr MessageReceive) {
|
||||
log.Printf("Error Message Received: % 02X\n", mr.raw_message[:mr.raw_write_index])
|
||||
}
|
||||
|
||||
func parseByte(mr *MessageReceive, pbyte byte) {
|
||||
addByteToRawBuffer(mr, pbyte)
|
||||
switch mr.state {
|
||||
case WAITING_FOR_START_BYTE:
|
||||
if pbyte == START_BYTE {
|
||||
initMessageReceive(mr)
|
||||
mr.state = GET_MESSAGE_ID
|
||||
addByteToRawBuffer(mr, pbyte)
|
||||
}
|
||||
// ignore every other byte
|
||||
break
|
||||
case GET_MESSAGE_ID:
|
||||
if pbyte == ESCAPE_BYTE {
|
||||
mr.state = ESCAPED_MESSAGE_ID
|
||||
} else {
|
||||
addByteToParsedBuffer(mr, pbyte)
|
||||
mr.state = IN_PAYLOD
|
||||
}
|
||||
break
|
||||
case ESCAPED_MESSAGE_ID:
|
||||
addByteToParsedBuffer(mr, pbyte)
|
||||
mr.state = IN_PAYLOD
|
||||
break
|
||||
case IN_PAYLOD:
|
||||
if pbyte == ESCAPE_BYTE {
|
||||
mr.state = ESCAPED_PAYLOAD_BYTE
|
||||
break
|
||||
}
|
||||
if pbyte == START_BYTE {
|
||||
mr.error = UNEXPECETD_BYTE
|
||||
go message_receive_failed_callback(*mr)
|
||||
initMessageReceive(mr)
|
||||
return
|
||||
}
|
||||
if pbyte == END_BYTE {
|
||||
if mr.checksum != 0 { // checksum wrong
|
||||
mr.error = WRONG_CHECKSUM
|
||||
go message_receive_failed_callback(*mr)
|
||||
initMessageReceive(mr)
|
||||
return
|
||||
}
|
||||
go message_receive_callback(*mr)
|
||||
initMessageReceive(mr)
|
||||
break
|
||||
}
|
||||
// normal case
|
||||
addByteToParsedBuffer(mr, pbyte)
|
||||
break
|
||||
case ESCAPED_PAYLOAD_BYTE:
|
||||
addByteToParsedBuffer(mr, pbyte)
|
||||
mr.state = IN_PAYLOD
|
||||
break
|
||||
default:
|
||||
panic(fmt.Sprintf("unexpected main.ParserState: %#v", mr.state))
|
||||
}
|
||||
}
|
||||
|
||||
func buildMessage(payloadBuffer []byte, payload_len int, sendBuffer []byte) int {
|
||||
var writeIndex int
|
||||
checksum := byte(0x00)
|
||||
writeIndex = 0
|
||||
sendBuffer[writeIndex] = START_BYTE
|
||||
writeIndex++
|
||||
for i := range payload_len {
|
||||
b := payloadBuffer[i]
|
||||
if b == START_BYTE || b == ESCAPE_BYTE || b == END_BYTE {
|
||||
sendBuffer[writeIndex] = ESCAPE_BYTE
|
||||
writeIndex++
|
||||
}
|
||||
sendBuffer[writeIndex] = b
|
||||
writeIndex++
|
||||
checksum ^= b
|
||||
}
|
||||
if checksum == START_BYTE || checksum == ESCAPE_BYTE || checksum == END_BYTE {
|
||||
sendBuffer[writeIndex] = ESCAPE_BYTE
|
||||
writeIndex++
|
||||
}
|
||||
sendBuffer[writeIndex] = checksum
|
||||
writeIndex++
|
||||
sendBuffer[writeIndex] = END_BYTE
|
||||
writeIndex++
|
||||
return writeIndex
|
||||
}
|
||||
|
||||
func sendMessage(port serial.Port, sendBuffer []byte) {
|
||||
n, err := port.Write(sendBuffer)
|
||||
if err != nil {
|
||||
log.Printf("Could not Send %v to Serial Port", sendBuffer)
|
||||
}
|
||||
if n < len(sendBuffer) {
|
||||
log.Printf("Did not send all data %v, only send %v", len(sendBuffer), n)
|
||||
}
|
||||
fmt.Printf("Send Message % 02X\n", sendBuffer[:n])
|
||||
}
|
||||
|
||||
var (
|
||||
updatePath string
|
||||
OTA_UpdateHandler OTASyncManager
|
||||
)
|
||||
|
||||
func main() {
|
||||
flag.StringVar(&updatePath, "update", "", "Path to Updatefile")
|
||||
flag.Parse()
|
||||
|
||||
OTA_UpdateHandler = OTASyncManager{
|
||||
OTA_MessageCounter: 0,
|
||||
OTA_PayloadMessageSequence: 0,
|
||||
NewOTAMessage: make(chan MessageReceive),
|
||||
TimeoutMessage: time.Millisecond * 30000,
|
||||
}
|
||||
|
||||
mode := &serial.Mode{
|
||||
//BaudRate: 115200,
|
||||
BaudRate: 921600,
|
||||
}
|
||||
port, err := serial.Open("/dev/ttyUSB0", mode)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
ctx, cancle := context.WithCancel(context.Background())
|
||||
defer cancle()
|
||||
|
||||
go func() {
|
||||
buff := make([]byte, 1024)
|
||||
mr := MessageReceive{}
|
||||
initMessageReceive(&mr)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
default:
|
||||
n, err := port.Read(buff)
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
break
|
||||
}
|
||||
if n == 0 {
|
||||
fmt.Println("\nEOF")
|
||||
break
|
||||
}
|
||||
for _, b := range buff[:n] {
|
||||
parseByte(&mr, b)
|
||||
}
|
||||
//fmt.Printf("Empfangen: % 02X\n", string(buff[:n]))
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if updatePath != "" {
|
||||
// start update
|
||||
update, err := os.ReadFile(updatePath)
|
||||
if err != nil {
|
||||
log.Printf("Could not read Update file %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("Update Buffer read, update size %v", len(update))
|
||||
log.Printf("Gonna break it down in 200 Bytes packages will send %v packages", len(update)/200)
|
||||
|
||||
// start
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_OTA_START
|
||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
msg, err := OTA_UpdateHandler.WaitForNextMessageTimeout()
|
||||
if err != nil {
|
||||
log.Printf("Error Message not acked %v", err)
|
||||
} else {
|
||||
if msg.parsed_message[2] != 0x00 {
|
||||
log.Printf("Update Start failed %v", msg.parsed_message[2])
|
||||
return
|
||||
} else {
|
||||
log.Printf("Update Start confirmed Updating Partition %v", msg.parsed_message[1])
|
||||
}
|
||||
}
|
||||
|
||||
update_write_index := 0
|
||||
// write update parts
|
||||
for update_write_index < len(update) {
|
||||
payload_buffer = make([]byte, 1024)
|
||||
send_buffer = make([]byte, 1024)
|
||||
payload_buffer[0] = UART_OTA_PAYLOAD
|
||||
|
||||
write_len := min(200, len(update)-update_write_index)
|
||||
|
||||
//end_payload_len := min(update_write_index+200, len(update))
|
||||
|
||||
copy(payload_buffer[1:write_len+1], update[update_write_index:update_write_index+write_len])
|
||||
n = buildMessage(payload_buffer, write_len+1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
msg, err := OTA_UpdateHandler.WaitForNextMessageTimeout()
|
||||
if err != nil {
|
||||
log.Printf("Error Message not acked %v", err)
|
||||
return
|
||||
} else {
|
||||
seqCounter := binary.LittleEndian.Uint16(msg.parsed_message[1:3])
|
||||
buff_write_index := binary.LittleEndian.Uint16(msg.parsed_message[3:5])
|
||||
log.Printf("Sequenzce Counter: %d, Update buffer Write Index: %d", seqCounter, buff_write_index)
|
||||
}
|
||||
update_write_index += 200
|
||||
}
|
||||
|
||||
log.Printf("Update übertragen beende hier!!!")
|
||||
// end
|
||||
payload_buffer = make([]byte, 1024)
|
||||
send_buffer = make([]byte, 1024)
|
||||
payload_buffer[0] = UART_OTA_END
|
||||
n = buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
|
||||
_, err = OTA_UpdateHandler.WaitForNextMessageTimeout()
|
||||
if err != nil {
|
||||
log.Printf("Error Message not acked %v", err)
|
||||
return
|
||||
} else {
|
||||
log.Printf("Message Waiting hat funktionioert")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
var input string
|
||||
_, err := fmt.Scanln(&input)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not read from stdin")
|
||||
}
|
||||
fmt.Printf("Input %v", input)
|
||||
|
||||
switch input {
|
||||
case "q":
|
||||
return
|
||||
case "1":
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_ECHO
|
||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
break
|
||||
case "2":
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_VERSION
|
||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
break
|
||||
case "3":
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_CLIENT_INFO
|
||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
break
|
||||
case "4": // start update
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_OTA_START
|
||||
n := buildMessage(payload_buffer, 1, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
break
|
||||
case "5": // send payload
|
||||
payload_buffer := make([]byte, 1024)
|
||||
send_buffer := make([]byte, 1024)
|
||||
payload_buffer[0] = UART_OTA_PAYLOAD
|
||||
for i := range 200 {
|
||||
payload_buffer[i+1] = byte(i)
|
||||
}
|
||||
n := buildMessage(payload_buffer, 201, send_buffer)
|
||||
sendMessage(port, send_buffer[:n])
|
||||
break
|
||||
case "6": // end update
|
||||
default:
|
||||
fmt.Printf("Not a valid input")
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
idf_component_register(SRCS "main.c" "uart_handler.c" "communication_handler.c" "client_handler.c" "message_parser.c" "message_builder.c" "message_handler.c"
|
||||
idf_component_register(SRCS "main.c" "uart_handler.c" "communication_handler.c" "client_handler.c" "message_parser.c" "message_builder.c" "message_handler.c" "ota_update.c"
|
||||
INCLUDE_DIRS ".")
|
||||
|
||||
# Get the short Git commit hash of the current HEAD.
|
||||
|
||||
@@ -28,6 +28,7 @@ typedef struct {
|
||||
uint8_t macAddr[MAC_LENGTH];
|
||||
TickType_t lastSuccessfullPing;
|
||||
TickType_t lastPing;
|
||||
uint16_t clientVersion;
|
||||
} ClientInfo;
|
||||
|
||||
typedef struct {
|
||||
|
||||
+288
-78
@@ -1,3 +1,4 @@
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_now.h"
|
||||
#include "esp_timer.h"
|
||||
@@ -8,32 +9,123 @@
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
static const char *TAG = "ALOX - COM";
|
||||
|
||||
static struct ESP_MessageBroker mr;
|
||||
static QueueHandle_t ESP_recieved_message_queue;
|
||||
|
||||
void free_ESPNOW_MessageInfo(ESPNOW_MessageInfo *msg) {
|
||||
if (msg->esp_now_info.src_addr) {
|
||||
free(msg->esp_now_info.src_addr);
|
||||
msg->esp_now_info.src_addr = NULL;
|
||||
}
|
||||
if (msg->esp_now_info.des_addr) {
|
||||
free(msg->esp_now_info.des_addr);
|
||||
msg->esp_now_info.des_addr = NULL;
|
||||
}
|
||||
if (msg->esp_now_info.rx_ctrl) {
|
||||
free(msg->esp_now_info.rx_ctrl);
|
||||
msg->esp_now_info.rx_ctrl = NULL;
|
||||
}
|
||||
if (msg->data) {
|
||||
free(msg->data);
|
||||
msg->data = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void ESP_InitMessageBroker(QueueHandle_t msg_queue_handle) {
|
||||
mr.num_direct_callbacks = 0;
|
||||
mr.num_task_callbacks = 0;
|
||||
ESP_recieved_message_queue = msg_queue_handle;
|
||||
return;
|
||||
}
|
||||
|
||||
void ESP_RegisterFunction(CommandPages command,
|
||||
ESP_RegisterFunctionCallback callback) {
|
||||
mr.FunctionList[mr.num_direct_callbacks].MSGID = command;
|
||||
mr.FunctionList[mr.num_direct_callbacks].callback = callback;
|
||||
mr.num_direct_callbacks++;
|
||||
return;
|
||||
}
|
||||
|
||||
void ESP_RegisterTask(CommandPages command, ESP_RegisterTaskCallback callback) {
|
||||
mr.TaskList[mr.num_task_callbacks].MSGID = command;
|
||||
mr.TaskList[mr.num_task_callbacks].task = callback;
|
||||
mr.num_task_callbacks++;
|
||||
}
|
||||
|
||||
void ESP_MessageBrokerTask(void *param) {
|
||||
ESPNOW_MessageInfo received_msg;
|
||||
ESP_MessageBrokerTaskParams_t *task_params =
|
||||
(ESP_MessageBrokerTaskParams_t *)param;
|
||||
|
||||
// Extrahiere die einzelnen Parameter
|
||||
QueueHandle_t msg_queue = task_params->message_queue;
|
||||
|
||||
if (msg_queue == NULL) {
|
||||
ESP_LOGE(TAG, "Message queue not initialized. Terminating task.");
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Message broker task started.");
|
||||
|
||||
while (1) {
|
||||
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
|
||||
|
||||
ESP_LOGI(TAG, "Broker got message trying to relay it now");
|
||||
const BaseMessage *message = (const BaseMessage *)received_msg.data;
|
||||
ESP_LOGI(TAG, "Broker searching for command page %d",
|
||||
message->commandPage);
|
||||
for (int i = 0; i < mr.num_direct_callbacks;
|
||||
i++) { // TODO: there should not be a loop needed here
|
||||
if (mr.FunctionList[i].MSGID == message->commandPage) {
|
||||
mr.FunctionList[i].callback(&received_msg.esp_now_info,
|
||||
received_msg.data, received_msg.data_len);
|
||||
ESP_LOGI(TAG, "Broker found matching msgid %d",
|
||||
mr.FunctionList[i].MSGID);
|
||||
free_ESPNOW_MessageInfo(&received_msg);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < mr.num_direct_callbacks; i++) {
|
||||
// if (mr.FunctionList[i].MSGID == received_msg.msgid) {
|
||||
// TODO: Not yet implemented
|
||||
// Only send data to task, task should be created beforhead and wait
|
||||
// for new data in the queue.
|
||||
//}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QueueHandle_t messageQueue = NULL; // Warteschlange für empfangene Nachrichten
|
||||
bool hasMaster = false;
|
||||
static bool hasMaster = false;
|
||||
static ClientList *esp_client_list;
|
||||
static uint8_t channelNumber = 0;
|
||||
|
||||
#define MAC_STRING_BUFFER_SIZE 18
|
||||
|
||||
void init_com(ClientList *clients) {
|
||||
int init_com(ClientList *clients, uint8_t wifi_channel) {
|
||||
// Initialisiere die Kommunikations-Warteschlange
|
||||
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(BaseMessage));
|
||||
messageQueue = xQueueCreate(MESSAGE_QUEUE_SIZE, sizeof(ESPNOW_MessageInfo));
|
||||
if (messageQueue == NULL) {
|
||||
ESP_LOGE(TAG, "Message queue creation failed");
|
||||
return -1;
|
||||
}
|
||||
|
||||
esp_client_list = clients;
|
||||
hasMaster = false;
|
||||
channelNumber = wifi_channel;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void add_peer(uint8_t *macAddr) {
|
||||
int add_peer(uint8_t *macAddr) {
|
||||
esp_now_peer_info_t peerInfo = {
|
||||
.channel =
|
||||
0, // Standardkanal, sollte uit den anderen Geräten übereinstimmen
|
||||
.channel = channelNumber,
|
||||
.ifidx = ESP_IF_WIFI_STA,
|
||||
.encrypt = false, // Keine Verschlüsselung (kann geändert werden)
|
||||
.encrypt = false, // Keine Verschlüsselung // TODO: should be changed
|
||||
};
|
||||
memcpy(peerInfo.peer_addr, macAddr, ESP_NOW_ETH_ALEN);
|
||||
|
||||
@@ -47,6 +139,7 @@ void add_peer(uint8_t *macAddr) {
|
||||
ESP_LOGE(TAG, "Client could not be added to client handler, removing "
|
||||
"it from esp now client list!");
|
||||
esp_now_del_peer(peerInfo.peer_addr);
|
||||
return -1;
|
||||
}
|
||||
ESP_LOGI(TAG, "New client added.");
|
||||
}
|
||||
@@ -59,20 +152,20 @@ void add_peer(uint8_t *macAddr) {
|
||||
}
|
||||
} else {
|
||||
ESP_LOGE(TAG, "Failed to add peer: %s", esp_err_to_name(result));
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
BaseMessage MessageBuilder(CommandPages commandPage, PayloadUnion payload,
|
||||
size_t payload_size) {
|
||||
BaseMessage message;
|
||||
|
||||
// Initialisierung der BaseMessage
|
||||
message.commandPage = commandPage;
|
||||
message.version = 1;
|
||||
message.length = (uint16_t)payload_size;
|
||||
|
||||
// Kopieren des Payloads in die Union
|
||||
memset(&message.payload, 0, sizeof(message.payload)); // Sicherheitsmaßnahme
|
||||
memset(&message.payload, 0, sizeof(message.payload));
|
||||
memcpy(&message.payload, &payload, payload_size);
|
||||
|
||||
return message;
|
||||
@@ -87,21 +180,21 @@ void master_broadcast_task(void *param) {
|
||||
|
||||
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
||||
sizeof(BaseMessage)));
|
||||
ESP_LOGI(TAG, "Broadcast Message sent");
|
||||
|
||||
// ESP_LOGI(TAG, "Broadcast Message sent");
|
||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||
}
|
||||
}
|
||||
|
||||
void master_broadcast_ping(void *param) {
|
||||
while (1) {
|
||||
// BroadCastPayload payload = {};
|
||||
PingPayload payload = {};
|
||||
payload.timestamp = esp_timer_get_time();
|
||||
BaseMessage message =
|
||||
MessageBuilder(PingPage, *(PayloadUnion *)&payload, sizeof(payload));
|
||||
ESP_ERROR_CHECK(esp_now_send(broadcast_address, (uint8_t *)&message,
|
||||
sizeof(BaseMessage)));
|
||||
ESP_LOGI(TAG, "Broadcast PING Message sent");
|
||||
// ESP_LOGI(TAG, "Broadcast PING Message sent");
|
||||
vTaskDelay(pdMS_TO_TICKS(2500));
|
||||
}
|
||||
}
|
||||
@@ -125,38 +218,25 @@ void master_ping_task(void *param) {
|
||||
}
|
||||
}
|
||||
|
||||
void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
void master_StatusCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
|
||||
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
switch (message->commandPage) {
|
||||
case StatusPage:
|
||||
ESP_LOGI(TAG, "GOT STATUS MESSAGE");
|
||||
break;
|
||||
case PingPage:
|
||||
ESP_LOGI(TAG, "GOT PING MESSAGE");
|
||||
uint32_t currentTime = esp_timer_get_time();
|
||||
uint32_t diff = currentTime - message->payload.ping_payload.timestamp;
|
||||
|
||||
ESP_LOGI(TAG, "Start: %lu, End: %lu, Diff: %lu, Ping: %lu",
|
||||
message->payload.ping_payload.timestamp, currentTime, diff,
|
||||
diff / 1000); // ping in ms
|
||||
ESP_LOGI(TAG, "SRC " MACSTR, MAC2STR(esp_now_info->src_addr));
|
||||
ESP_LOGI(TAG,
|
||||
"Status Message Received: status: %d, runningPartition: %d, uptime: "
|
||||
"%d, version: %d",
|
||||
message->payload.status_payload.status,
|
||||
message->payload.status_payload.runningPartition,
|
||||
message->payload.status_payload.uptime,
|
||||
message->payload.status_payload.version);
|
||||
}
|
||||
|
||||
void master_RegisterCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
BaseMessage replyMessage = {};
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
|
||||
int id = get_client_id(esp_client_list, esp_now_info->src_addr);
|
||||
if (id >= 0) {
|
||||
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
|
||||
esp_client_list->Clients[id].lastPing = (diff / 1000);
|
||||
ESP_LOGI(TAG, "Updated client %d: " MACSTR " last ping time to %lu", id,
|
||||
MAC2STR(esp_now_info->src_addr),
|
||||
esp_client_list->Clients[id].lastSuccessfullPing);
|
||||
}
|
||||
break;
|
||||
case BroadCastPage:
|
||||
ESP_LOGI(TAG, "MASTER SHOULD NOT GET BROADCAST MESSAGE, is there another "
|
||||
"master calling?");
|
||||
break;
|
||||
case RegisterPage:
|
||||
ESP_LOGI(TAG, "WILL REGISTER DEVICE");
|
||||
esp_now_peer_info_t checkPeerInfo;
|
||||
esp_err_t checkPeer =
|
||||
@@ -177,45 +257,76 @@ void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
ESP_LOGI(TAG, "ESP ERR ESPNOW_ARG");
|
||||
break;
|
||||
case (ESP_ERR_ESPNOW_NOT_FOUND):
|
||||
ESP_LOGI(TAG, "CLIENT WIRD IN DIE LISTE AUFGENOMMEN");
|
||||
add_peer(esp_now_info->src_addr);
|
||||
ESP_LOGI(TAG, "CLIENT WIRD IN DIE LISTE AUFGENOMMEN " MACSTR,
|
||||
MAC2STR(esp_now_info->src_addr));
|
||||
int peer_err = add_peer(esp_now_info->src_addr);
|
||||
if (peer_err < 0) {
|
||||
ESP_LOGE(TAG, "Could not add ESP TO ClientList %d", peer_err);
|
||||
}
|
||||
ESP_LOGI(TAG, "FRAGE CLIENT STATUS AN");
|
||||
|
||||
GetStatusPayload payload = {};
|
||||
replyMessage = MessageBuilder(GetStatusPage, *(PayloadUnion *)&payload,
|
||||
sizeof(payload));
|
||||
esp_err_t err = esp_now_send(esp_now_info->src_addr,
|
||||
(uint8_t *)&replyMessage, sizeof(BaseMessage));
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Could not send Message Error %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
ESP_LOGI(TAG, "Unknown Message %i", checkPeer);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
ESP_LOGI(TAG, "Unknown CommandPage %i", message->commandPage);
|
||||
break;
|
||||
}
|
||||
|
||||
void master_pingCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
BaseMessage replyMessage = {};
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
|
||||
ESP_LOGI(TAG, "GOT PING MESSAGE");
|
||||
uint32_t currentTime = esp_timer_get_time();
|
||||
uint32_t diff = currentTime - message->payload.ping_payload.timestamp;
|
||||
|
||||
ESP_LOGI(TAG, "Start: %lu, End: %lu, Diff: %lu, Ping: %lu",
|
||||
message->payload.ping_payload.timestamp, currentTime, diff,
|
||||
diff / 1000); // ping in ms
|
||||
|
||||
int id = get_client_id(esp_client_list, esp_now_info->src_addr);
|
||||
if (id >= 0) {
|
||||
esp_client_list->Clients[id].lastSuccessfullPing = xTaskGetTickCount();
|
||||
esp_client_list->Clients[id].lastPing = (diff / 1000);
|
||||
ESP_LOGI(TAG, "Updated client %d: " MACSTR " last ping time to %lu", id,
|
||||
MAC2STR(esp_now_info->src_addr),
|
||||
esp_client_list->Clients[id].lastSuccessfullPing);
|
||||
}
|
||||
}
|
||||
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
|
||||
void master_broadcastCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
|
||||
ESP_LOGI(TAG, "Received message from: " MACSTR,
|
||||
ESP_LOGI(TAG,
|
||||
"Master should not recieve Broadcast is there another master "
|
||||
"Calling got message from " MACSTR,
|
||||
MAC2STR(esp_now_info->src_addr));
|
||||
ESP_LOGI(TAG, "Message: %.*s", data_len, data);
|
||||
}
|
||||
|
||||
void ESPNOW_RegisterMasterCallbacks() {
|
||||
ESP_RegisterFunction(StatusPage, master_StatusCallback);
|
||||
ESP_RegisterFunction(RegisterPage, master_RegisterCallback);
|
||||
ESP_RegisterFunction(PingPage, master_pingCallback);
|
||||
ESP_RegisterFunction(BroadCastPage, master_broadcastCallback);
|
||||
}
|
||||
|
||||
void slave_broadcastCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
BaseMessage replyMessage = {};
|
||||
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
switch (message->commandPage) {
|
||||
case StatusPage:
|
||||
ESP_LOGI(TAG, "GOT STATUS MESSAGE");
|
||||
break;
|
||||
case PingPage:
|
||||
ESP_LOGI(TAG, "GOT PING MESSAGE");
|
||||
replyMessage = MessageBuilder(PingPage, *(PayloadUnion *)&message->payload,
|
||||
sizeof(message->payload));
|
||||
ESP_ERROR_CHECK(esp_now_send(
|
||||
esp_now_info->src_addr, (uint8_t *)&replyMessage, sizeof(BaseMessage)));
|
||||
break;
|
||||
case BroadCastPage:
|
||||
|
||||
ESP_LOGI(TAG, "GOT BROADCAST MESSAGE");
|
||||
if (!hasMaster) {
|
||||
if (IS_BROADCAST_ADDR(esp_now_info->des_addr)) {
|
||||
ESP_LOGI(TAG,
|
||||
"GOT BROADCAST MESSAGE ATTEMPTING TO REGISTER TO MASTER!");
|
||||
ESP_LOGI(TAG, "GOT BROADCAST MESSAGE ATTEMPTING TO REGISTER TO MASTER!");
|
||||
add_peer(esp_now_info->src_addr);
|
||||
replyMessage =
|
||||
MessageBuilder(RegisterPage, *(PayloadUnion *)&message->payload,
|
||||
@@ -225,31 +336,130 @@ void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
sizeof(BaseMessage)));
|
||||
hasMaster = true;
|
||||
}
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Already have master wont register by the new one");
|
||||
}
|
||||
break;
|
||||
case RegisterPage:
|
||||
break;
|
||||
default:
|
||||
ESP_LOGI(TAG, "GOT UNKONW MESSAGE");
|
||||
break;
|
||||
}
|
||||
void slave_getstatusCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
BaseMessage replyMessage = {};
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
|
||||
StatusPayload payload = {
|
||||
.status = 1,
|
||||
.runningPartition = 1,
|
||||
.uptime = 100,
|
||||
.version = 0x0002,
|
||||
|
||||
};
|
||||
replyMessage =
|
||||
MessageBuilder(StatusPage, *(PayloadUnion *)&payload, sizeof(payload));
|
||||
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr, (uint8_t *)&replyMessage,
|
||||
sizeof(BaseMessage)));
|
||||
}
|
||||
void slave_pingCallback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
if (!hasMaster)
|
||||
return;
|
||||
|
||||
BaseMessage replyMessage = {};
|
||||
const BaseMessage *message = (const BaseMessage *)data;
|
||||
|
||||
ESP_LOGI(TAG, "GOT PING MESSAGE");
|
||||
replyMessage = MessageBuilder(PingPage, *(PayloadUnion *)&message->payload,
|
||||
sizeof(message->payload));
|
||||
ESP_ERROR_CHECK(esp_now_send(esp_now_info->src_addr, (uint8_t *)&replyMessage,
|
||||
sizeof(BaseMessage)));
|
||||
}
|
||||
|
||||
void ESPNOW_RegisterSlaveCallbacks() {
|
||||
ESP_RegisterFunction(BroadCastPage, slave_broadcastCallback);
|
||||
ESP_RegisterFunction(GetStatusPage, slave_getstatusCallback);
|
||||
ESP_RegisterFunction(PingPage, slave_pingCallback);
|
||||
}
|
||||
|
||||
void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
ESP_LOGI(TAG, "MASTER GOT MESSAGE");
|
||||
|
||||
// Allokiere Speicher für die Daten und kopiere sie
|
||||
uint8_t *copied_data = (uint8_t *)malloc(data_len);
|
||||
if (copied_data == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
|
||||
return;
|
||||
}
|
||||
memcpy(copied_data, data, data_len);
|
||||
|
||||
// Fülle die neue Struktur mit kopierten Daten
|
||||
ESPNOW_MessageInfo msg_info;
|
||||
msg_info.esp_now_info.src_addr = malloc(6);
|
||||
if (msg_info.esp_now_info.src_addr) {
|
||||
memcpy(msg_info.esp_now_info.src_addr, esp_now_info->src_addr, 6);
|
||||
}
|
||||
|
||||
// Speicher für des_addr kopieren
|
||||
msg_info.esp_now_info.des_addr = malloc(6);
|
||||
if (msg_info.esp_now_info.des_addr) {
|
||||
memcpy(msg_info.esp_now_info.des_addr, esp_now_info->des_addr, 6);
|
||||
}
|
||||
|
||||
// rx_ctrl Struktur kopieren
|
||||
msg_info.esp_now_info.rx_ctrl = malloc(sizeof(wifi_pkt_rx_ctrl_t));
|
||||
if (msg_info.esp_now_info.rx_ctrl) {
|
||||
memcpy(msg_info.esp_now_info.rx_ctrl, esp_now_info->rx_ctrl,
|
||||
sizeof(wifi_pkt_rx_ctrl_t));
|
||||
}
|
||||
|
||||
msg_info.data = copied_data;
|
||||
msg_info.data_len = data_len;
|
||||
|
||||
if (xQueueSend(ESP_recieved_message_queue, &msg_info, portMAX_DELAY) !=
|
||||
pdPASS) {
|
||||
// Fehlerbehandlung: Queue voll oder Senden fehlgeschlagen
|
||||
ESP_LOGE(TAG, "Failed to send parsed message to queue.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len) {
|
||||
ESP_LOGI(TAG, "SLAVE GOT MESSAGE");
|
||||
ESP_LOGI(TAG, "Received message from: " MACSTR,
|
||||
MAC2STR(esp_now_info->src_addr));
|
||||
|
||||
uint8_t *copied_data = (uint8_t *)malloc(data_len);
|
||||
if (copied_data == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to allocate memory for message data.");
|
||||
return;
|
||||
}
|
||||
memcpy(copied_data, data, data_len);
|
||||
|
||||
// Fülle die neue Struktur mit kopierten Daten
|
||||
ESPNOW_MessageInfo msg_info;
|
||||
memcpy(&msg_info.esp_now_info, esp_now_info, sizeof(esp_now_recv_info_t));
|
||||
msg_info.data = copied_data;
|
||||
msg_info.data_len = data_len;
|
||||
|
||||
if (xQueueSend(ESP_recieved_message_queue, &msg_info, portMAX_DELAY) !=
|
||||
pdPASS) {
|
||||
// Fehlerbehandlung: Queue voll oder Senden fehlgeschlagen
|
||||
ESP_LOGE(TAG, "Failed to send parsed message to queue.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void client_data_sending_task(void *param) {
|
||||
while (1) {
|
||||
const char *dataToSend = "DATA:42";
|
||||
ESP_LOGI(TAG, "SEND DATA");
|
||||
esp_now_send(NULL, (uint8_t *)dataToSend,
|
||||
strlen(dataToSend));
|
||||
esp_now_send(NULL, (uint8_t *)dataToSend, strlen(dataToSend));
|
||||
vTaskDelay(pdMS_TO_TICKS(5000));
|
||||
}
|
||||
}
|
||||
|
||||
void client_monitor_task(void *pvParameters) {
|
||||
TickType_t timeout_ticks =
|
||||
pdMS_TO_TICKS(CLIENT_TIMEOUT_MS);
|
||||
TickType_t interval_ticks =
|
||||
pdMS_TO_TICKS(CHECK_INTERVAL_MS);
|
||||
TickType_t timeout_ticks = pdMS_TO_TICKS(CLIENT_TIMEOUT_MS);
|
||||
TickType_t interval_ticks = pdMS_TO_TICKS(CHECK_INTERVAL_MS);
|
||||
|
||||
while (1) {
|
||||
TickType_t now = xTaskGetTickCount();
|
||||
|
||||
+103
-11
@@ -11,6 +11,7 @@
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#define BROADCAST_INTERVAL_MS 500
|
||||
|
||||
@@ -27,37 +28,86 @@ static uint8_t broadcast_address[ESP_NOW_ETH_ALEN] = {0xFF, 0xFF, 0xFF,
|
||||
#define MESSAGE_QUEUE_SIZE 10
|
||||
|
||||
typedef enum {
|
||||
BroadCastPage,
|
||||
OTA_PREP_UPGRADE,
|
||||
OTA_SEND_PAYLOAD,
|
||||
OTA_WRITE_UPDATE_BUFFER,
|
||||
OTA_SEND_MISSING,
|
||||
OTA_UPDATE_INFO,
|
||||
OTA_END_UPGRADE,
|
||||
StatusPage,
|
||||
GetStatusPage,
|
||||
ConfigPage,
|
||||
PingPage,
|
||||
BroadCastPage,
|
||||
RegisterPage,
|
||||
} CommandPages;
|
||||
|
||||
typedef struct {
|
||||
uint32_t uptime;
|
||||
typedef struct __attribute__((packed)) {
|
||||
|
||||
} OTA_PREP_UPGRADE_Payload;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
} OTA_SEND_PAYLOAD_Payload;
|
||||
typedef struct __attribute__((packed)) {
|
||||
} OTA_WRITE_UPDATE_BUFFER_Payload;
|
||||
typedef struct __attribute__((packed)) {
|
||||
} OTA_SEND_MISSING_Payload;
|
||||
typedef struct __attribute__((packed)) {
|
||||
} OTA_UPDATE_INFO_Payload;
|
||||
typedef struct __attribute__((packed)) {
|
||||
} OTA_END_UPGRADE_Payload;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint16_t version; // software version
|
||||
uint8_t runningPartition;
|
||||
uint8_t status;
|
||||
uint32_t uptime;
|
||||
} StatusPayload;
|
||||
|
||||
typedef struct {
|
||||
typedef struct __attribute__((packed)) {
|
||||
} GetStatusPayload;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t timeslot;
|
||||
} ConfigPayload;
|
||||
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint32_t timestamp;
|
||||
} PingPayload;
|
||||
|
||||
typedef struct {
|
||||
typedef struct __attribute__((packed)) {
|
||||
} BroadCastPayload;
|
||||
|
||||
typedef struct {
|
||||
typedef struct __attribute__((packed)) {
|
||||
bool familierClient;
|
||||
} RegisterPayload;
|
||||
|
||||
typedef union {
|
||||
// TODO: Check checksum fields
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint16_t length; // length of complete firmware
|
||||
uint8_t checksum; // checksum of firmware
|
||||
} FirmwarePrepPayload;
|
||||
|
||||
// TODO: Check checksum fields
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint8_t length;
|
||||
uint8_t checksum;
|
||||
uint32_t address;
|
||||
uint8_t payload[240]; // TODO: need a way to figure out a safe value for this
|
||||
} FirmwarePayload;
|
||||
|
||||
typedef union __attribute__((packed)) {
|
||||
StatusPayload status_payload;
|
||||
ConfigPayload config_payload;
|
||||
PingPayload ping_payload;
|
||||
BroadCastPayload broadcast_payload;
|
||||
RegisterPayload register_payload;
|
||||
FirmwarePrepPayload firmware_prep_payload;
|
||||
FirmwarePayload firmware_payload;
|
||||
} PayloadUnion;
|
||||
|
||||
typedef struct {
|
||||
uint16_t version;
|
||||
typedef struct __attribute__((packed)) {
|
||||
uint16_t version; // protcol version
|
||||
CommandPages commandPage;
|
||||
uint16_t length;
|
||||
PayloadUnion payload;
|
||||
@@ -66,9 +116,50 @@ typedef struct {
|
||||
static_assert(sizeof(BaseMessage) <= 255,
|
||||
"BaseMessage darf nicht größer als 255 sein");
|
||||
|
||||
void init_com(ClientList *clients);
|
||||
typedef void (*ESP_RegisterFunctionCallback)(
|
||||
const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len);
|
||||
typedef void (*ESP_RegisterTaskCallback)(
|
||||
const esp_now_recv_info_t *esp_now_info, const uint8_t *data, int data_len);
|
||||
|
||||
struct ESP_RegisterdFunction {
|
||||
CommandPages MSGID;
|
||||
ESP_RegisterFunctionCallback callback;
|
||||
};
|
||||
|
||||
struct ESP_RegisterdTask {
|
||||
CommandPages MSGID;
|
||||
ESP_RegisterTaskCallback task;
|
||||
};
|
||||
|
||||
struct ESP_MessageBroker {
|
||||
struct ESP_RegisterdFunction FunctionList[64];
|
||||
uint8_t num_direct_callbacks;
|
||||
struct ESP_RegisterdTask TaskList[64];
|
||||
uint8_t num_task_callbacks;
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
QueueHandle_t message_queue;
|
||||
} ESP_MessageBrokerTaskParams_t;
|
||||
|
||||
typedef struct {
|
||||
esp_now_recv_info_t esp_now_info;
|
||||
uint8_t *data;
|
||||
int data_len;
|
||||
} ESPNOW_MessageInfo;
|
||||
|
||||
void ESP_InitMessageBroker(QueueHandle_t msg_queue_handle);
|
||||
void ESP_RegisterFunction(CommandPages command,
|
||||
ESP_RegisterFunctionCallback callback);
|
||||
void ESP_RegisterTask(CommandPages command, ESP_RegisterTaskCallback callback);
|
||||
void ESP_MessageBrokerTask(void *param);
|
||||
|
||||
void ESPNOW_RegisterMasterCallbacks();
|
||||
void ESPNOW_RegisterSlaveCallbacks();
|
||||
|
||||
int init_com(ClientList *clients, uint8_t wifi_channel);
|
||||
int getNextFreeClientId();
|
||||
void add_peer(uint8_t *macAddr);
|
||||
int add_peer(uint8_t *macAddr);
|
||||
BaseMessage MessageBuilder(CommandPages commandPage, PayloadUnion payload,
|
||||
size_t payload_size);
|
||||
|
||||
@@ -81,6 +172,7 @@ void master_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
void client_receive_callback(const esp_now_recv_info_t *esp_now_info,
|
||||
const uint8_t *data, int data_len);
|
||||
void client_data_sending_task(void *param);
|
||||
void client_send_random_data_task(void *param);
|
||||
void client_monitor_task(void *pvParameters);
|
||||
|
||||
#endif
|
||||
|
||||
+100
-12
@@ -1,7 +1,11 @@
|
||||
#include "client_handler.h"
|
||||
#include "driver/gpio.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_log_buffer.h"
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_phy_init.h"
|
||||
#include "esp_rom_gpio.h"
|
||||
#include "esp_timer.h"
|
||||
@@ -10,10 +14,12 @@
|
||||
#include "hal/uart_types.h"
|
||||
#include "message_handler.h"
|
||||
#include "message_parser.h"
|
||||
#include "nvs.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
#include "communication_handler.h"
|
||||
#include "main.h"
|
||||
#include "ota_update.h"
|
||||
#include "uart_handler.h"
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
@@ -22,13 +28,15 @@
|
||||
#include <sys/types.h>
|
||||
|
||||
#include "message_builder.h"
|
||||
#include "uart_msg_ids.h"
|
||||
|
||||
static const char *TAG = "ALOX - MAIN";
|
||||
static const uint16_t version = 0x0001;
|
||||
static uint8_t send_message_buffer[1024];
|
||||
static uint8_t send_message_payload_buffer[512 - 4];
|
||||
static uint8_t send_message_payload_buffer[512];
|
||||
|
||||
static MessageBrokerTaskParams_t broker_task_params;
|
||||
static ESP_MessageBrokerTaskParams_t esp_broker_task_params;
|
||||
|
||||
ClientList clientList = {.Clients = {{0}}, .ClientCount = 0};
|
||||
|
||||
@@ -36,8 +44,8 @@ void echoCallback(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||
uint8_t *send_payload_buffer, size_t send_payload_buffer_size,
|
||||
uint8_t *send_buffer, size_t send_buffer_size) {
|
||||
ESP_LOGI(TAG, "Echo command 0x01...");
|
||||
int len =
|
||||
build_message(0x01, payload, payload_len, send_buffer, send_buffer_size);
|
||||
int len = build_message(UART_ECHO, payload, payload_len, send_buffer,
|
||||
send_buffer_size);
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||
@@ -67,7 +75,7 @@ void versionCallback(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||
send_payload_buffer[1] = (uint8_t)((version >> 8) & 0xFF);
|
||||
memcpy(&send_payload_buffer[2], &BUILD_GIT_HASH, git_build_hash_len);
|
||||
|
||||
int len = build_message(0x02, send_payload_buffer, needed_buffer_size,
|
||||
int len = build_message(UART_VERSION, send_payload_buffer, needed_buffer_size,
|
||||
send_buffer, send_buffer_size);
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
@@ -84,7 +92,7 @@ void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
|
||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||
size_t send_buffer_size) {
|
||||
ESP_LOGI(TAG, "Client Info Command 0x03...");
|
||||
static uint8_t entryLength = 17;
|
||||
static uint8_t entryLength = 19;
|
||||
uint8_t needed_buffer_size = 1 + entryLength * clientList.ClientCount;
|
||||
|
||||
if (send_payload_buffer_size < needed_buffer_size) {
|
||||
@@ -126,11 +134,16 @@ void clientInfoCallback(uint8_t msgid, const uint8_t *payload,
|
||||
4);
|
||||
memcpy(&send_payload_buffer[offset + 13],
|
||||
&clientList.Clients[i].lastSuccessfullPing, 4);
|
||||
memcpy(&send_payload_buffer[offset + 17],
|
||||
&clientList.Clients[i].clientVersion, 2);
|
||||
}
|
||||
}
|
||||
|
||||
int len = build_message(0x04, send_payload_buffer, needed_buffer_size,
|
||||
send_buffer, send_buffer_size);
|
||||
int len = build_message(UART_CLIENT_INFO, send_payload_buffer,
|
||||
needed_buffer_size, send_buffer, send_buffer_size);
|
||||
|
||||
// ESP_LOG_BUFFER_HEX("SEND BUFFER: ", send_buffer, send_buffer_size);
|
||||
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||
@@ -166,8 +179,7 @@ void app_main(void) {
|
||||
wifi_config_t wifi_config = {
|
||||
.sta =
|
||||
{
|
||||
.channel = 1, // Kanal 1, stelle sicher, dass alle Geräte
|
||||
// denselben Kanal verwenden
|
||||
.channel = 1,
|
||||
},
|
||||
};
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
@@ -181,11 +193,84 @@ void app_main(void) {
|
||||
ESP_ERROR_CHECK(esp_now_register_recv_cb(client_receive_callback));
|
||||
}
|
||||
|
||||
init_com(&clientList);
|
||||
ret = init_com(&clientList, 1);
|
||||
if (ret < 0) {
|
||||
ESP_LOGE(TAG, "Could not Init ESP NOW Communication!");
|
||||
}
|
||||
|
||||
esp_partition_iterator_t partition_iter = esp_partition_find(
|
||||
ESP_PARTITION_TYPE_ANY, ESP_PARTITION_SUBTYPE_ANY, NULL);
|
||||
|
||||
while (partition_iter != NULL) {
|
||||
const esp_partition_t *part1 = esp_partition_get(partition_iter);
|
||||
ESP_LOGI(TAG, "Partition: %s, Address: %d, Size %d", part1->label,
|
||||
part1->address, part1->size);
|
||||
partition_iter = esp_partition_next(partition_iter);
|
||||
}
|
||||
|
||||
const esp_partition_t *running = esp_ota_get_running_partition();
|
||||
ESP_LOGI(TAG, "OTA: Running Partition: %s", running->label);
|
||||
uint8_t ota_part_count = esp_ota_get_app_partition_count();
|
||||
ESP_LOGI(TAG, "OTA: Got %d OTA Partitions", ota_part_count);
|
||||
|
||||
esp_ota_img_states_t ota_state;
|
||||
if (esp_ota_get_state_partition(running, &ota_state) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "OTA: Partition State : %d", ota_state);
|
||||
if (ota_state == ESP_OTA_IMG_PENDING_VERIFY) {
|
||||
// run diagnostic function ...
|
||||
bool diagnostic_is_ok = true; // TODO: a real function that checks if
|
||||
// everything is running properly
|
||||
if (diagnostic_is_ok) {
|
||||
ESP_LOGI(
|
||||
TAG,
|
||||
"Diagnostics completed successfully! Continuing execution ...");
|
||||
// esp_ota_mark_app_valid_cancel_rollback();
|
||||
} else {
|
||||
ESP_LOGE(
|
||||
TAG,
|
||||
"Diagnostics failed! Start rollback to the previous version ...");
|
||||
// esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const char nvs_part_name[] = "nvs_data";
|
||||
const char nvs_namespace_name[] = "saved_clients";
|
||||
ret = nvs_flash_init_partition(nvs_part_name);
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES ||
|
||||
ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase_partition(nvs_part_name));
|
||||
ret = nvs_flash_init_partition(nvs_part_name);
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
nvs_handle_t nt;
|
||||
ESP_ERROR_CHECK(nvs_open_from_partition(nvs_part_name, nvs_namespace_name,
|
||||
NVS_READWRITE, &nt));
|
||||
|
||||
int32_t outval;
|
||||
ret = nvs_get_i32(nt, "test_entry", &outval);
|
||||
if (ret == ESP_ERR_NVS_NOT_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_set_i32(nt, "test_entry", 6969));
|
||||
ESP_ERROR_CHECK(nvs_commit(nt));
|
||||
ESP_LOGE(TAG, "Nichts im Flash gefunden hab was dahin geschrieben");
|
||||
} else if (ret == ESP_OK) {
|
||||
ESP_LOGE(TAG, "DAS WAR IM FLASH %d", outval);
|
||||
}
|
||||
nvs_close(nt);
|
||||
|
||||
QueueHandle_t espnow_message_queue =
|
||||
xQueueCreate(10, sizeof(ESPNOW_MessageInfo));
|
||||
ESP_InitMessageBroker(espnow_message_queue);
|
||||
|
||||
esp_broker_task_params.message_queue = espnow_message_queue;
|
||||
xTaskCreate(ESP_MessageBrokerTask, "espnow_message_broker_task", 4096,
|
||||
(void *)&esp_broker_task_params, 4, NULL);
|
||||
|
||||
// Tasks starten basierend auf Master/Client
|
||||
if (isMaster) {
|
||||
ESP_LOGI(TAG, "Started in Mastermode");
|
||||
ESPNOW_RegisterMasterCallbacks();
|
||||
|
||||
add_peer(broadcast_address);
|
||||
xTaskCreate(master_broadcast_task, "MasterBroadcast", 4096, NULL, 1, NULL);
|
||||
// xTaskCreate(master_ping_task, "MasterPing", 4096, NULL, 1, NULL);
|
||||
@@ -214,12 +299,15 @@ void app_main(void) {
|
||||
RegisterCallback(0x02, versionCallback);
|
||||
RegisterCallback(0x03, clientInfoCallback);
|
||||
|
||||
init_ota();
|
||||
|
||||
// xTaskCreate(uart_status_task, "MasterUartStatusTask", 4096, NULL, 1,
|
||||
// NULL); xTaskCreate(SendClientInfoTask, "SendCientInfo", 4096, NULL, 1,
|
||||
// NULL);
|
||||
} else {
|
||||
ESP_LOGI(TAG, "Started in Slavemode");
|
||||
xTaskCreate(client_data_sending_task, "ClientDataSending", 4096, NULL, 1,
|
||||
NULL);
|
||||
ESPNOW_RegisterSlaveCallbacks();
|
||||
// xTaskCreate(client_data_sending_task, "ClientDataSending", 4096, NULL, 1,
|
||||
// NULL);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ bool add_byte_with_length_check(uint8_t byte, size_t write_index, uint8_t *data,
|
||||
int build_message(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||
uint8_t *msg_buffer, size_t msg_buffer_size) {
|
||||
|
||||
ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
|
||||
msg_buffer_size);
|
||||
//ESP_LOGE("BM", "payload_len %d, msg_buffer_size %d", payload_len + 4,
|
||||
// msg_buffer_size);
|
||||
if (payload_len + 4 > msg_buffer_size) {
|
||||
return PayloadBiggerThenBuffer;
|
||||
}
|
||||
@@ -75,6 +75,5 @@ int build_message(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||
msg_buffer[write_index++] = checksum;
|
||||
msg_buffer[write_index++] = EndByte;
|
||||
|
||||
ESP_LOGE("BM", "MESSAGE FERTIG GEBAUT");
|
||||
return write_index;
|
||||
}
|
||||
|
||||
@@ -46,8 +46,8 @@ void MessageBrokerTask(void *param) {
|
||||
|
||||
while (1) {
|
||||
if (xQueueReceive(msg_queue, &received_msg, portMAX_DELAY)) {
|
||||
ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
|
||||
received_msg.msgid, received_msg.payload_len);
|
||||
//ESP_LOGI(TAG, "Received message from queue: MSGID=0x%02X, Length=%u",
|
||||
// received_msg.msgid, received_msg.payload_len);
|
||||
|
||||
for (int i = 0; i < mr.num_direct_callbacks; i++) {
|
||||
if (mr.FunctionList[i].MSGID == received_msg.msgid) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define MAX_MESSAGE_PAYLOAD_LENGTH 128
|
||||
#define MAX_MESSAGE_PAYLOAD_LENGTH 512
|
||||
#define MAX_TOTAL_CONTENT_LENGTH (MAX_MESSAGE_PAYLOAD_LENGTH + 1)
|
||||
|
||||
enum ParserState {
|
||||
@@ -33,7 +33,7 @@ struct MessageReceive {
|
||||
enum ParserError error;
|
||||
uint8_t messageid;
|
||||
uint8_t message[MAX_MESSAGE_PAYLOAD_LENGTH];
|
||||
uint8_t index;
|
||||
uint16_t index;
|
||||
uint8_t checksum;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
#include "ota_update.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_system.h"
|
||||
#include "message_builder.h"
|
||||
#include "message_handler.h"
|
||||
#include "uart_handler.h"
|
||||
#include "uart_msg_ids.h"
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX(a, b) ((a) > (b) ? (a) : (b))
|
||||
#define MIN(a, b) ((a) < (b) ? (a) : (b))
|
||||
|
||||
static uint8_t update_buffer[UPDATE_BUFFER_SIZE];
|
||||
static uint16_t update_buffer_write_index;
|
||||
static uint32_t update_size;
|
||||
static uint16_t sequenz_counter; // how often the update buffer gets written
|
||||
static const char *TAG = "ALOX - OTA";
|
||||
static esp_ota_handle_t update_handle;
|
||||
|
||||
int prepare_ota_update() {
|
||||
const esp_partition_t *running = esp_ota_get_running_partition();
|
||||
ESP_LOGI(TAG, "OTA: Running Partition: %s", running->label);
|
||||
int part = 0;
|
||||
|
||||
char partition_to_update[] = "ota_0";
|
||||
if (strcmp(running->label, "ota_0") == 0) {
|
||||
strcpy(partition_to_update, "ota_1");
|
||||
part = 1;
|
||||
}
|
||||
|
||||
const esp_partition_t *update_partition = esp_partition_find_first(
|
||||
ESP_PARTITION_TYPE_APP, ESP_PARTITION_SUBTYPE_ANY, partition_to_update);
|
||||
|
||||
// Check if the partition was found
|
||||
if (update_partition == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to find OTA partition: %s", partition_to_update);
|
||||
return -1; // Or handle the error appropriately
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Gonna write OTA Update in Partition: %s",
|
||||
update_partition->label);
|
||||
|
||||
esp_err_t err =
|
||||
esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
|
||||
esp_ota_abort(update_handle);
|
||||
return -2;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "OTA update started successfully.");
|
||||
return part;
|
||||
}
|
||||
|
||||
void start_uart_update(uint8_t msgid, const uint8_t *payload,
|
||||
size_t payload_len, uint8_t *send_payload_buffer,
|
||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||
size_t send_buffer_size) {
|
||||
ESP_LOGI(TAG, "OTA Update Start Uart Command");
|
||||
|
||||
vTaskPrioritySet(NULL, 2);
|
||||
|
||||
update_size = 0;
|
||||
|
||||
int part = prepare_ota_update();
|
||||
|
||||
// Message:
|
||||
// byte partition
|
||||
// byte error
|
||||
|
||||
if (part < 0) {
|
||||
send_payload_buffer[1] = (part * -1) & 0xff;
|
||||
} else {
|
||||
send_payload_buffer[0] = part & 0xff;
|
||||
}
|
||||
|
||||
int send_payload_len = 2;
|
||||
int len = build_message(UART_OTA_START, send_payload_buffer, send_payload_len,
|
||||
send_buffer, send_buffer_size);
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||
"%d, mes_len(error): %d",
|
||||
payload_len, send_buffer_size, len);
|
||||
return;
|
||||
}
|
||||
|
||||
uart_write_bytes(MASTER_UART, send_buffer, len);
|
||||
}
|
||||
|
||||
esp_err_t write_ota_update(uint32_t write_len, const uint8_t *payload) {
|
||||
if (update_buffer_write_index > UPDATE_BUFFER_SIZE - write_len) {
|
||||
// ESP_LOGI(TAG, "Writing Data to Update BUffer Sequence %d, writing Data
|
||||
// %d",
|
||||
// sequenz_counter, write_len);
|
||||
// write to ota
|
||||
esp_err_t err =
|
||||
esp_ota_write(update_handle, update_buffer, update_buffer_write_index);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
|
||||
update_buffer_write_index = 0;
|
||||
sequenz_counter++;
|
||||
return err;
|
||||
}
|
||||
|
||||
memcpy(&update_buffer[update_buffer_write_index], payload, write_len);
|
||||
update_buffer_write_index += write_len;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void payload_uart_update(uint8_t msgid, const uint8_t *payload,
|
||||
size_t payload_len, uint8_t *send_payload_buffer,
|
||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||
size_t send_buffer_size) {
|
||||
// ESP_LOGI(TAG, "OTA Update Payload Uart Command");
|
||||
|
||||
uint32_t write_len = MIN(UPDATE_PAYLOAD_SIZE, payload_len);
|
||||
update_size += write_len;
|
||||
|
||||
esp_err_t err = write_ota_update(write_len, payload);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
|
||||
}
|
||||
|
||||
size_t send_payload_len = 4;
|
||||
memcpy(send_payload_buffer, &sequenz_counter, 2);
|
||||
memcpy(&send_payload_buffer[2], &update_buffer_write_index, 2);
|
||||
send_payload_buffer[4] = 0x00; // error
|
||||
|
||||
int len = build_message(UART_OTA_PAYLOAD, send_payload_buffer,
|
||||
send_payload_len, send_buffer, send_buffer_size);
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||
"%d, mes_len(error): %d",
|
||||
payload_len, send_buffer_size, len);
|
||||
return;
|
||||
}
|
||||
|
||||
uart_write_bytes(MASTER_UART, send_buffer, len);
|
||||
}
|
||||
|
||||
esp_err_t end_ota_update() {
|
||||
esp_err_t err =
|
||||
esp_ota_write(update_handle, update_buffer, update_buffer_write_index);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
|
||||
}
|
||||
|
||||
err = esp_ota_end(update_handle);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "GOT ESP ERROR WRITE OTA %d", err);
|
||||
}
|
||||
|
||||
ESP_LOGE(TAG, "UPDATE ENDE UPDATGE SIZE SIND %d BYTES", update_size);
|
||||
|
||||
// Hol dir die zuletzt geschriebene Partition
|
||||
const esp_partition_t *partition = esp_ota_get_next_update_partition(NULL);
|
||||
if (partition == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to get updated partition");
|
||||
err = ESP_FAIL;
|
||||
}
|
||||
|
||||
// Setze sie als Boot-Partition
|
||||
ESP_LOGE(TAG, "Setzte nächste Partition auf %s", partition->label);
|
||||
err = esp_ota_set_boot_partition(partition);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ota_set_boot_partition failed: %s",
|
||||
esp_err_to_name(err));
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
void end_uart_update(uint8_t msgid, const uint8_t *payload, size_t payload_len,
|
||||
uint8_t *send_payload_buffer,
|
||||
size_t send_payload_buffer_size, uint8_t *send_buffer,
|
||||
size_t send_buffer_size) {
|
||||
ESP_LOGI(TAG, "OTA Update End Uart Command");
|
||||
|
||||
esp_err_t err = end_ota_update();
|
||||
|
||||
// message ret esp_err_t
|
||||
int send_payload_len = 1;
|
||||
send_payload_buffer[0] = err & 0xff;
|
||||
int len = build_message(UART_OTA_END, send_payload_buffer, send_payload_len,
|
||||
send_buffer, send_buffer_size);
|
||||
if (len < 0) {
|
||||
ESP_LOGE(TAG,
|
||||
"Error Building UART Message: payload_len, %d, sendbuffer_size: "
|
||||
"%d, mes_len(error): %d",
|
||||
payload_len, send_buffer_size, len);
|
||||
return;
|
||||
}
|
||||
|
||||
uart_write_bytes(MASTER_UART, send_buffer, len);
|
||||
|
||||
vTaskPrioritySet(NULL, 1);
|
||||
}
|
||||
|
||||
void write_ota_update_from_uart_task(void *param) {}
|
||||
|
||||
void init_ota() {
|
||||
RegisterCallback(UART_OTA_START, start_uart_update);
|
||||
RegisterCallback(UART_OTA_PAYLOAD, payload_uart_update);
|
||||
RegisterCallback(UART_OTA_END, end_uart_update);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef OTA_UPDATE_H
|
||||
#define OTA_UPDATE_H
|
||||
|
||||
#include "esp_err.h"
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
#define UPDATE_BUFFER_SIZE 4000
|
||||
#define UPDATE_PAYLOAD_SIZE 200
|
||||
#define UPDATE_MAX_SEQUENZES (UPDATE_BUFFER_SIZE / UPDATE_PAYLOAD_SIZE)
|
||||
|
||||
void init_ota();
|
||||
|
||||
enum OTA_UPDATE_STATES {
|
||||
IDEL,
|
||||
START_REQUESTED,
|
||||
WAITING_FOR_PAYLOAD,
|
||||
WRITING_OTA_TO_PARTITION,
|
||||
|
||||
};
|
||||
|
||||
int prepare_ota_update();
|
||||
esp_err_t write_ota_update(uint32_t write_len, const uint8_t *payload);
|
||||
esp_err_t end_ota_update();
|
||||
|
||||
#endif
|
||||
+3
-3
@@ -18,7 +18,7 @@ static const char *TAG = "ALOX - UART";
|
||||
static QueueHandle_t parsed_message_queue;
|
||||
|
||||
void init_uart(QueueHandle_t msg_queue_handle) {
|
||||
uart_config_t uart_config = {.baud_rate = 115200,
|
||||
uart_config_t uart_config = {.baud_rate = 921600, // 921600, 115200
|
||||
.data_bits = UART_DATA_8_BITS,
|
||||
.parity = UART_PARITY_DISABLE,
|
||||
.stop_bits = UART_STOP_BITS_1,
|
||||
@@ -61,9 +61,9 @@ void send_message_hook(const uint8_t *buffer, size_t length) {
|
||||
|
||||
void HandleMessageReceivedCallback(uint8_t msgid, const uint8_t *payload,
|
||||
size_t payload_len) {
|
||||
ESP_LOGI(TAG, "GOT UART MESSAGE MSGID: %02X, Len: %u bytes \nMSG: ", msgid,
|
||||
/*ESP_LOGI(TAG, "GOT UART MESSAGE MSGID: %02X, Len: %u bytes \nMSG: ", msgid,
|
||||
payload_len, payload);
|
||||
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);
|
||||
ESP_LOG_BUFFER_HEX(TAG, payload, payload_len);*/
|
||||
|
||||
ParsedMessage_t msg_to_send;
|
||||
msg_to_send.msgid = msgid;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#ifndef UART_MSG_IDS_H
|
||||
#define UART_MSG_IDS_H
|
||||
|
||||
enum UART_MSG_IDS {
|
||||
// MISC
|
||||
UART_ECHO = 0x01,
|
||||
UART_VERSION = 0x02,
|
||||
UART_CLIENT_INFO = 0x03,
|
||||
|
||||
// OTA
|
||||
UART_OTA_START = 0x10,
|
||||
UART_OTA_PAYLOAD = 0x11,
|
||||
UART_OTA_END = 0x12,
|
||||
UART_OTA_STATUS = 0x13,
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -2,54 +2,123 @@
|
||||
|
||||
## Struktur einer Nachricht
|
||||
|
||||
0xAA = Startbyte
|
||||
checksum = XOR über alle Bytes (ohne Startbyte und Checksum-Byte)
|
||||
- Control Bytes:
|
||||
- 0xAA = Startbyte
|
||||
- 0xBB = EscapeByte
|
||||
- 0xCC = EndByte
|
||||
|
||||
## Nachrichtenaufbau (Message Frame)
|
||||
checksum = XOR über alle Bytes (ohne Control Bytes und Checksum-Byte)
|
||||
|
||||
[ Startbyte ] [ Length ] [ CommandPage ] [ Payload (variabel) ] [ Checksum ]
|
||||
Command, Payload und Checksum werden Escaped sollten sie einem Control Byte ensteprechend
|
||||
| Startbyte | Command | Payload (variable) | Checksum | Endbyte |
|
||||
|-----------|---------|--------------------|----------|---------|
|
||||
|
||||
### Felder im Detail:
|
||||
|
||||
- **Length** (`uint8_t`):
|
||||
Gibt die Gesamtlänge der Nachricht **ab `CommandPage` bis einschließlich `Payload`** an.
|
||||
|
||||
- **CommandPage** (`uint8_t`):
|
||||
Gibt an, welcher Nachrichtentyp oder Befehl gesendet wird.
|
||||
- **Command** (`uint8_t`):
|
||||
Gibt an, welcher Nachrichtentyp gesendet wird.
|
||||
|
||||
- **Payload** (`variabel`):
|
||||
Datenfeld mit variabler Länge, abhängig vom `CommandPage`.
|
||||
Datenfeld mit variabler Länge, abhängig vom `Command`.
|
||||
|
||||
- **Checksum** (`uint8_t`):
|
||||
XOR über alle Bytes ab `Length` bis einschließlich `Payload`.
|
||||
|
||||
### Nachrichten von PC zu ESP:
|
||||
|
||||
clientid: 0x00 für master, 0xFF für broadcast, ansonsten 0xA0-0xB3 // 19 Clients
|
||||
|
||||
### RequestPing 0xE1
|
||||
Payload: byte: clientid
|
||||
### RequestInfo 0xE2
|
||||
Payload: byte: clientid
|
||||
### RequestRestart 0xE3
|
||||
Payload: byte: clientid
|
||||
### PrepareFirmwareUpdate 0xF1
|
||||
Payload: none
|
||||
### FirmwareUpdateLine 0xF2
|
||||
Payload: firmware line 240Bytes MAX
|
||||
### ExecuteFirmwareUpdate 0xF3
|
||||
Payload: none
|
||||
|
||||
### Nachrichten von ESP zu PC:
|
||||
XOR über aller Bytes von `Command` und `Payload`.
|
||||
|
||||
|
||||
### Messages
|
||||
|
||||
---
|
||||
Command:
|
||||
- UART_ECHO = 0x01
|
||||
- UART_VERSION = 0x02
|
||||
- UART_CLIENT_INFO = 0x03
|
||||
|
||||
# Roadmap
|
||||
- [ ] SEND STATUS OF DEVICE OVER UART
|
||||
- [ ] CONFIGURE PEERS OVER MASTER
|
||||
- [ ] SAVE PIN CONFIG ON PEERS
|
||||
Grundlegend sind alle Zahlenwerte im LittleEndian format!
|
||||
|
||||
#### UART_ECHO:
|
||||
|
||||
- Send Message: AA 01 01 CC
|
||||
- Message Received: AA 01 01 CC
|
||||
|
||||
Sendet zurück was geschickt wird.
|
||||
|
||||
#### UART_VERSION:
|
||||
|
||||
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|
||||
|--------|---------------|-------------|------------------|
|
||||
| 0 | 2 | Version | Software Version |
|
||||
| 2 | 7 | BuildHash | Git Hash |
|
||||
|
||||
|
||||
- Send Message: AA 02 02 CC
|
||||
- Message Received: AA 02 01 00 33 62 35 36 30 37 39 6F CC
|
||||
|
||||
| Version | Buildhash |
|
||||
|---------|-----------|
|
||||
| 1 | 3b56078 |
|
||||
|
||||
|
||||
Sendet die Version und den Buildhash vom Master zurück.
|
||||
|
||||
#### UART_CLIENT_INFO:
|
||||
|
||||
Das erste Datenbyte nach dem Commando gibt an wie viele Client Infos in dieser Nachricht vorhanden sind.
|
||||
|
||||
Danach teilt sich ein Eintrag wie Folgt auf:
|
||||
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|
||||
|--------|---------------|----------------------------|---------------------------------------------------------------|
|
||||
| 0 | 1 | Client ID | Eindeutige ID des Clients. |
|
||||
| 1 | 1 | Ist verfügbar | Boolean-Wert (0 = nein, 1 = ja), ob der Client verfügbar ist. |
|
||||
| 2 | 1 | Slot genutzt | Boolean-Wert (0 = nein, 1 = ja), ob der Slot belegt ist. |
|
||||
| 3 | 6 | MAC-Adresse | Die Hardware-Adresse des Clients. |
|
||||
| 9 | 4 | Letzter Ping | Zeit in Millisekunden seit dem letzten Ping. |
|
||||
| 13 | 4 | Letzter erfolgreicher Ping | Zeit in Millisekunden seit dem letzten erfolgreichen Ping. |
|
||||
| 17 | 2 | Version | Versionsnummer des Clients. |
|
||||
|
||||
##### Ein Client
|
||||
|
||||
- Send Message: AA 03 03 CC
|
||||
- Message Received: AA 03 01 00 01 01 50 78 7D 18 89 F8 34 00 00 00 61 1F 00 00 02 00 76 CC
|
||||
|
||||
| Client ID | Verfügbar | Genutzt | MAC-Adresse | Last Ping | Last Successful Ping | Version |
|
||||
|-----------|-----------|---------|-------------------|-----------|----------------------|---------|
|
||||
| 0 | 1 | 1 | 50:78:7D:18:89:F8 | 52 | 8033 | 2 |
|
||||
|
||||
##### Zwei Clients
|
||||
|
||||
- Send Message: AA 03 03 CC
|
||||
- Message Received: AA 03 02 00 01 01 50 78 7D 18 89 F8 22 00 00 00 F4 2A 01 00 02 00 01 01 01 50 78 7D 18 0C B4 10 00 00 00 F1 2A 01 00 02 00 FE CC
|
||||
|
||||
| Client ID | Verfügbar | Genutzt | MAC-Adresse | Last Ping | Last Successful Ping | Version |
|
||||
|-----------|-----------|---------|-------------------|-----------|----------------------|---------|
|
||||
| 0 | 1 | 1 | 50:78:7D:18:89:F8 | 34 | 76532 | 2 |
|
||||
| 1 | 1 | 1 | 50:78:7D:18:C:B4 | 16 | 76529 | 2 |
|
||||
|
||||
#### UART_CLIENT_INPUT:
|
||||
|
||||
Die Identifizierung wird hier anhand der vorher gesendeten ClientID gemacht also muss einmal vorher `UART_CLIENT_INFO` aufgerufen werden.
|
||||
|
||||
Das erste Datenbyte nach dem Commando gibt an wie viele Client Infos in dieser Nachricht vorhanden sind.
|
||||
|
||||
Danach teilt sich ein Eintrag wie Folgt auf:
|
||||
| Offset | Länge (Bytes) | Bezeichnung | Beschreibung |
|
||||
|--------|---------------|-------------|----------------------------------------------------------------------------------|
|
||||
| 0 | 1 | Client ID | Eindeutige ID des Clients. |
|
||||
| 1 | 4 | LageX | Float Wert von der X Lage. |
|
||||
| 5 | 4 | LageY | Float Wert von der Y Lage. |
|
||||
| 9 | 4 | InputMaske | Int32 Wert der als Bitmaske genutzt wird um bis zu 32 Boolische Werte anzugeben. |
|
||||
|
||||
Inputmaske:
|
||||
Taster1, Taster2, IOError1, IOErro2, AkkuStand1, AkkuStand2 (2 Bit kodiert für 25%,50%,75%,100%), rest unbelegt, default 0
|
||||
|
||||
| Bit1 | Bit2 | Akkustand |
|
||||
|------|------|-----------|
|
||||
| 0 | 0 | 25% |
|
||||
| 0 | 1 | 50% |
|
||||
| 1 | 0 | 75% |
|
||||
| 1 | 1 | 100% |
|
||||
|
||||
|
||||
<div style="page-break-after: always;"></div>
|
||||
|
||||
# Machbarkeits-Studie
|
||||
|
||||
@@ -177,3 +246,55 @@ techn. Anforderungen hinreichend gut umsetzen lassen.
|
||||
und ob diese den ursprünglichen Anforderungen entsprechen.
|
||||
|
||||
|
||||
|
||||
## OTA-Update Technische Umsetzung:
|
||||
|
||||
### Vorrausetzung:
|
||||
- Update File steht bereit und ist unter 2MB groß.
|
||||
- UART Verbindung steht
|
||||
- ESP Funktioniert einwandfrei
|
||||
- ESP Läuft auf Partition A, Partition B soll geupdated werden
|
||||
|
||||
### Erste Schritt:
|
||||
- Update in 200Byte stücke zerhacken und stück für stück per UART an den Master schicken
|
||||
- Uart Protokol hat schon eine fehlercheck für die Übertragung drinnen
|
||||
- Firmware wird in Partition B geschrieben
|
||||
- OTA API Validiert Firmware am ende
|
||||
|
||||
#### Hier könnte man schon einen Neustart machen und Validieren ob die Firmware für den Master läuft!
|
||||
#### Denn angeblich kann man beim ESP die aktuell laufende Partition auslesen
|
||||
|
||||
### Zweiter Schritt:
|
||||
- Master liest in 200Byte stücken die Firmware aus seiner Partition B aus
|
||||
- Und schickt per Broadcast die ersten 20 Packete an die Clients
|
||||
- Die clients haben 4KB Buffer vorgesehen wo sie die 20 Packete unterbringen können
|
||||
- Master Forder Ack Bitmaske an zur Validierung das alle 20 Packete da sind
|
||||
- Sollten in der Bitmaske zeilen fehlen gibt der Master per unicast die fehlenden Zeilen an die Entsprechend Clients erneut
|
||||
- ESP NOW kümmert sich hier um die Datenintigrität
|
||||
- Wenn alle ihre ersten 20 packete haben gibt der master das go und alle schreiben die ersten 20 packete weg.
|
||||
- Der master aktuallisiert den fortschritt für alle clients -> dann kann man das auch abfragen per uart und hat eine Fortschrittsanzeige
|
||||
- Alle melden sich zurück wenn sie fertig sind mit dem schreiben per ota und der buffer leer ist.
|
||||
- Repeat bis alle Daten da sind
|
||||
|
||||
Hier hab ich mal grob gerechnet:
|
||||
2MB in 200Byte Schritten -> 10.000 Packete
|
||||
10.000 Packete in 20er Schritten -> 500 Sequencen
|
||||
Retries und Acks mal aussen vor hab ich leider keinen richtigen anhaltspunkt wie lang das dauern kann.
|
||||
Aber 500* ca 300ms => ist schonmal 150sekunden nur für das acken das die Packete da sind. Annahme hier das die maximal latenz beim Ping mit 16 Clients ca 300ms sind.
|
||||
Entsprechend mit Daten und retries... ja kp, Gemini schätzt max 10min. Wird sich zeigen. Da addiert sich zu viel auf.
|
||||
|
||||
- Alle Clients validieren ihren firmware
|
||||
- Sollte das bei einem nicht klappen muss man hier nochmal gucken ob man den ganzen process nochmal von vorne anstößt nur mit dem fehlenden client...
|
||||
|
||||
### Dritter Schritt:
|
||||
- Alle Clients rebooten
|
||||
- Clients geben rückmeldung ob das Update funktioniert
|
||||
|
||||
#### Hier müssten war noch entscheiden was passiert wenn das Update bei nur ein paar funktionert hat?
|
||||
#### Was passiert wenn das Update garnicht funktioniert hat, behält der master dann auch seinen stand?
|
||||
#### Entsprechend hätte man ihn vorher auch nicht neustarten dürfen
|
||||
|
||||
- Sollten alle Clients ihr go geben startet der Master auch neu
|
||||
#### Wenn das Master Update jetzt fehlschlägt sagt er den clients bescheid und die booten auch wieder um?
|
||||
|
||||
Gibt halt noch ein zwar sachen die man sich überlegen muss aber ich denke den rest hab ich soweit ausgearbeitet
|
||||
|
||||
+2098
File diff suppressed because it is too large
Load Diff
+2357
File diff suppressed because it is too large
Load Diff
-248
@@ -1,248 +0,0 @@
|
||||
import queue # Zum sicheren Datenaustausch zwischen Threads
|
||||
import serial
|
||||
import time
|
||||
import threading
|
||||
import sys
|
||||
from parser import UartMessageParser, ParserError
|
||||
from message_builder import MessageBuilder, MessageBuilderError, PayloadTooLargeError, BufferOverflowError
|
||||
import payload_parser
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
|
||||
SERIAL_PORT = "/dev/ttyUSB0"
|
||||
BAUDRATE = 115200
|
||||
WRITE_TIMEOUT = 1.5
|
||||
READ_TIMEOUT = 2.0
|
||||
|
||||
payload_parser = payload_parser.PayloadParser()
|
||||
|
||||
|
||||
def on_message_received_from_uart(parsed_message):
|
||||
print(f"[CALLBACK] Nachricht empfangen: MSGID=0x{
|
||||
parsed_message.msgid:02X}, Length={parsed_message.payload_len}")
|
||||
received_message_queue.put(parsed_message)
|
||||
|
||||
|
||||
def on_message_fail_from_uart(error_message):
|
||||
print(f"[CALLBACK] Fehler beim Parsen: {error_message}")
|
||||
|
||||
|
||||
class ParsedMessage:
|
||||
def __init__(self, msgid, payload_len):
|
||||
self.msgid = msgid
|
||||
self.payload_len = payload_len
|
||||
|
||||
|
||||
received_message_queue = queue.Queue()
|
||||
|
||||
|
||||
class SerialReader(threading.Thread):
|
||||
# Ändere den Konstruktor, um eine bereits geöffnete serielle Instanz zu akzeptieren
|
||||
def __init__(self, ser_instance, read_timeout, parser):
|
||||
super().__init__()
|
||||
# Speichere die übergebene serielle Instanz
|
||||
self.ser = ser_instance
|
||||
self.read_timeout = read_timeout
|
||||
self.parser = parser
|
||||
self.running = False
|
||||
self.daemon = True # Thread beendet sich mit dem Hauptprogramm
|
||||
|
||||
def run(self):
|
||||
# Überprüfe, ob die serielle Schnittstelle wirklich offen ist, bevor du beginnst
|
||||
if not self.ser or not self.ser.is_open:
|
||||
print(
|
||||
f"[{self.name}] Fehler: Serielle Schnittstelle ist nicht geöffnet.")
|
||||
return
|
||||
|
||||
print(f"[{self.name}] Lese-Thread gestartet. Überwache {self.ser.port}...")
|
||||
self.ser.timeout = self.read_timeout # Setze den Timeout für byteweises Lesen
|
||||
self.running = True
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
byte = self.ser.read(1)
|
||||
if byte:
|
||||
self.parser.parse_byte(byte[0])
|
||||
else:
|
||||
pass # Timeout, kein Byte verfügbar, Thread läuft weiter
|
||||
except serial.SerialException as e:
|
||||
print(f"[{self.name}] Lesefehler: {e}")
|
||||
self.running = False
|
||||
except Exception as e:
|
||||
print(f"[{self.name}] Unerwarteter Fehler im Lese-Thread: {e}")
|
||||
self.running = False
|
||||
|
||||
# Der Thread schließt den Port NICHT mehr, das ist Aufgabe des Hauptprogramms.
|
||||
print(f"[{self.name}] Lese-Thread beendet.")
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
print(f"[{self.name}] Lese-Thread wird beendet...")
|
||||
|
||||
|
||||
def on_message_received_from_uart(message_id: int, payload: bytes, payload_length: int):
|
||||
"""
|
||||
Callback-Funktion, die aufgerufen wird, wenn der Parser eine vollständige,
|
||||
gültige Nachricht empfangen hat.
|
||||
"""
|
||||
print(f"\n[MAIN] Nachricht erfolgreich empfangen! ID: 0x{
|
||||
message_id:02X}")
|
||||
print(f"[MAIN] Payload ({payload_length} Bytes): {
|
||||
payload[:payload_length].hex().upper()}")
|
||||
|
||||
parsed_object = payload_parser.parse_payload(
|
||||
message_id, payload[:payload_length])
|
||||
|
||||
if message_id == 0x04:
|
||||
print(parsed_object)
|
||||
table = Table(title="Clients")
|
||||
columns = ["ClientId", "IsAvailable",
|
||||
"IsSlotUsed", "MAC", "LastPing", "LastSuccesfullPing"]
|
||||
|
||||
rows = []
|
||||
for x in parsed_object.clients:
|
||||
mac_string = ':'.join(f'{byte:02x}' for byte in x.mac_address)
|
||||
rows.append([str(x.client_id), str(x.is_available), str(x.is_slot_used), mac_string,
|
||||
str(x.last_ping), str(x.last_successfull_ping)])
|
||||
|
||||
for column in columns:
|
||||
table.add_column(column)
|
||||
|
||||
for row in rows:
|
||||
table.add_row(*row, style='bright_green')
|
||||
|
||||
console = Console()
|
||||
console.print(table)
|
||||
|
||||
|
||||
def on_message_fail_from_uart(message_id: int, current_message_buffer: bytes,
|
||||
current_index: int, error_type: ParserError):
|
||||
"""
|
||||
Callback-Funktion, die aufgerufen wird, wenn der Parser einen Fehler
|
||||
beim Empfang einer Nachricht feststellt.
|
||||
"""
|
||||
print(f"\n[MAIN] Fehler beim Parsen der Nachricht! ID: 0x{
|
||||
message_id:02X}")
|
||||
print(f"[MAIN] Fehler: {error_type.name}")
|
||||
print(f"[MAIN] Bisheriger Puffer ({current_index} Bytes): {
|
||||
current_message_buffer[:current_index].hex().upper()}")
|
||||
|
||||
|
||||
def run_uart_test():
|
||||
"""
|
||||
Führt den UART-Test durch: Sendet eine Nachricht und liest alle Antworten.
|
||||
"""
|
||||
ser = None
|
||||
|
||||
parser = UartMessageParser(
|
||||
on_message_received_callback=on_message_received_from_uart,
|
||||
on_message_fail_callback=on_message_fail_from_uart
|
||||
)
|
||||
message_builder = MessageBuilder()
|
||||
|
||||
try:
|
||||
ser = serial.Serial(
|
||||
port=SERIAL_PORT,
|
||||
baudrate=BAUDRATE,
|
||||
timeout=READ_TIMEOUT,
|
||||
write_timeout=WRITE_TIMEOUT
|
||||
)
|
||||
print(f"Serielle Schnittstelle {
|
||||
SERIAL_PORT} mit Baudrate {BAUDRATE} geöffnet.")
|
||||
|
||||
reader_thread = SerialReader(
|
||||
ser_instance=ser,
|
||||
read_timeout=10,
|
||||
parser=parser
|
||||
)
|
||||
reader_thread.start() # Starte den Lese-Thread
|
||||
|
||||
while not reader_thread.running:
|
||||
time.sleep(0.1)
|
||||
|
||||
print("\n--- UART Testkonsole ---")
|
||||
print("Gib eine Zahl (1-10) ein, um eine Nachricht zu senden.")
|
||||
print("Gib 'q' oder 'exit' ein, um das Programm zu beenden.")
|
||||
|
||||
while True:
|
||||
# Warte auf Benutzereingabe
|
||||
user_input = sys.stdin.readline().strip().lower()
|
||||
|
||||
if user_input in ('q', 'exit'):
|
||||
break
|
||||
|
||||
try:
|
||||
choice = int(user_input)
|
||||
if choice in MESSAGES:
|
||||
msg_info = MESSAGES[choice]
|
||||
print(f"\n[MAIN] Sende Nachricht für Option {
|
||||
choice} (MSGID: 0x{msg_info['msg_id']:02X})...")
|
||||
try:
|
||||
message_to_send = message_builder.build_message(
|
||||
msg_info["msg_id"],
|
||||
msg_info["payload"],
|
||||
255 # Max Payload Length
|
||||
)
|
||||
print(f"[MAIN] Gebaute Nachricht zum Senden: {
|
||||
message_to_send.hex().upper()}")
|
||||
bytes_written = ser.write(message_to_send)
|
||||
print(f"[MAIN] {bytes_written} Bytes gesendet.")
|
||||
except (PayloadTooLargeError, BufferOverflowError) as e:
|
||||
print(f"[MAIN] Fehler beim Bauen der Nachricht: {e}")
|
||||
except Exception as e:
|
||||
print(
|
||||
f"[MAIN] Ein unerwarteter Fehler beim Senden der Nachricht ist aufgetreten: {e}")
|
||||
else:
|
||||
print(
|
||||
"Ungültige Option. Bitte gib eine Zahl zwischen 1 und 10 ein.")
|
||||
except ValueError:
|
||||
print("Ungültige Eingabe. Bitte gib eine Zahl oder 'q' ein.")
|
||||
except Exception as e:
|
||||
print(
|
||||
f"[MAIN] Ein unerwarteter Fehler bei der Eingabeverarbeitung ist aufgetreten: {e}")
|
||||
|
||||
# Verarbeite empfangene Nachrichten, die sich in der Queue angesammelt haben
|
||||
while not received_message_queue.empty():
|
||||
msg = received_message_queue.get()
|
||||
print(
|
||||
f" > [MAIN-Loop] Verarbeitet: MSGID=0x{msg.msgid:02X}, Length={msg.payload_len}")
|
||||
received_message_queue.task_done()
|
||||
|
||||
except serial.SerialException as e:
|
||||
print(f"Fehler beim Zugriff auf die serielle Schnittstelle: {e}")
|
||||
print(f"Stelle sicher, dass '{
|
||||
SERIAL_PORT}' der korrekte Port ist und nicht von einer anderen Anwendung verwendet wird.")
|
||||
except KeyboardInterrupt:
|
||||
print("\n[MAIN] Test durch Benutzer abgebrochen (Ctrl+C).")
|
||||
except Exception as e:
|
||||
print(f"Ein unerwarteter Fehler im Hauptprogramm ist aufgetreten: {e}")
|
||||
finally:
|
||||
if 'reader_thread' in locals() and reader_thread.is_alive():
|
||||
reader_thread.stop()
|
||||
reader_thread.join(timeout=5)
|
||||
if reader_thread.is_alive():
|
||||
print(
|
||||
"[MAIN] Warnung: Lese-Thread konnte nicht sauber beendet werden.")
|
||||
if ser and ser.is_open:
|
||||
ser.close()
|
||||
print("Serielle Schnittstelle geschlossen.")
|
||||
print("[MAIN] Programm beendet.")
|
||||
|
||||
|
||||
# Nachrichten-Mapping
|
||||
MESSAGES = {
|
||||
1: {"msg_id": 0x01, "payload": b"Echo Message 1"},
|
||||
2: {"msg_id": 0x02, "payload": b"Version Request"},
|
||||
3: {"msg_id": 0x03, "payload": b"Client Info Request"},
|
||||
4: {"msg_id": 0x04, "payload": b"Custom Data 4"},
|
||||
5: {"msg_id": 0x05, "payload": b"Custom Data 5"},
|
||||
6: {"msg_id": 0x06, "payload": b"Custom Data 6"},
|
||||
7: {"msg_id": 0x07, "payload": b"Custom Data 7"},
|
||||
8: {"msg_id": 0x08, "payload": b"Custom Data 8"},
|
||||
9: {"msg_id": 0x09, "payload": b"Custom Data 9"},
|
||||
10: {"msg_id": 0x0A, "payload": b"Custom Data 10 - Last One!"},
|
||||
}
|
||||
|
||||
# Führe den Test aus
|
||||
if __name__ == "__main__":
|
||||
run_uart_test()
|
||||
@@ -1,115 +0,0 @@
|
||||
import enum
|
||||
|
||||
START_BYTE = 0xAA
|
||||
ESCAPE_BYTE = 0xBB
|
||||
END_BYTE = 0xCC
|
||||
|
||||
|
||||
class MessageBuilderError(Exception):
|
||||
"""Basisklasse für Fehler des Message Builders."""
|
||||
pass
|
||||
|
||||
|
||||
class PayloadTooLargeError(MessageBuilderError):
|
||||
"""Ausnahme, wenn der Payload zu groß für den Puffer ist."""
|
||||
|
||||
def __init__(self, required_size, buffer_size):
|
||||
super().__init__(f"Payload ({
|
||||
required_size} bytes) ist größer als der verfügbare Puffer ({buffer_size} bytes).")
|
||||
self.required_size = required_size
|
||||
self.buffer_size = buffer_size
|
||||
|
||||
|
||||
class BufferOverflowError(MessageBuilderError):
|
||||
"""Ausnahme, wenn der Puffer während des Bauens überläuft."""
|
||||
|
||||
def __init__(self, current_size, max_size, byte_to_add=None):
|
||||
msg = f"Pufferüberlauf: Aktuelle Größe {
|
||||
current_size}, Max. Größe {max_size}."
|
||||
if byte_to_add is not None:
|
||||
msg += f" Versuch, Byte 0x{byte_to_add:02X} hinzuzufügen."
|
||||
super().__init__(msg)
|
||||
self.current_size = current_size
|
||||
self.max_size = max_size
|
||||
self.byte_to_add = byte_to_add
|
||||
|
||||
|
||||
class MessageBuilder:
|
||||
"""
|
||||
Klasse zum Aufbau von UART-Nachrichten gemäß dem definierten Protokoll,
|
||||
inklusive Stuffing und Checksummenberechnung.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def _needs_stuffing_byte(self, byte: int) -> bool:
|
||||
"""
|
||||
Prüft, ob ein Byte ein Stuffing-Byte benötigt (d.h. ob es ein Steuerbyte ist).
|
||||
"""
|
||||
return (byte == START_BYTE or byte == ESCAPE_BYTE or byte == END_BYTE)
|
||||
|
||||
def _add_byte_with_length_check(self, byte: int, buffer: bytearray, max_length: int):
|
||||
"""
|
||||
Fügt ein Byte zum Puffer hinzu und prüft auf Pufferüberlauf.
|
||||
Löst BufferOverflowError aus, wenn der Puffer voll ist.
|
||||
"""
|
||||
if len(buffer) >= max_length:
|
||||
raise BufferOverflowError(len(buffer), max_length, byte)
|
||||
buffer.append(byte)
|
||||
|
||||
def build_message(self, msgid: int, payload: bytes, msg_buffer_size: int) -> bytes:
|
||||
"""
|
||||
Baut eine vollständige UART-Nachricht.
|
||||
|
||||
Args:
|
||||
msgid (int): Die Message ID (0-255).
|
||||
payload (bytes): Die Nutzdaten der Nachricht als Byte-Objekt.
|
||||
msg_buffer_size (int): Die maximale Größe des Ausgabepuffers.
|
||||
Dies ist die maximale Länge der *fertigen* Nachricht.
|
||||
|
||||
Returns:
|
||||
bytes: Die fertig aufgebaute Nachricht als Byte-Objekt.
|
||||
|
||||
Raises:
|
||||
PayloadTooLargeError: Wenn der Payload (mit Overhead) den Puffer überschreiten würde.
|
||||
BufferOverflowError: Wenn während des Bauens ein Pufferüberlauf auftritt.
|
||||
"""
|
||||
|
||||
if len(payload) + 4 > msg_buffer_size:
|
||||
raise PayloadTooLargeError(len(payload) + 4, msg_buffer_size)
|
||||
|
||||
checksum = 0
|
||||
msg_buffer = bytearray()
|
||||
|
||||
# 1. StartByte hinzufügen
|
||||
self._add_byte_with_length_check(
|
||||
START_BYTE, msg_buffer, msg_buffer_size)
|
||||
|
||||
# 2. Message ID hinzufügen (mit Stuffing)
|
||||
if self._needs_stuffing_byte(msgid):
|
||||
self._add_byte_with_length_check(
|
||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
||||
self._add_byte_with_length_check(msgid, msg_buffer, msg_buffer_size)
|
||||
checksum ^= msgid
|
||||
|
||||
# 3. Payload-Bytes hinzufügen (mit Stuffing)
|
||||
for byte_val in payload:
|
||||
if self._needs_stuffing_byte(byte_val):
|
||||
self._add_byte_with_length_check(
|
||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
||||
self._add_byte_with_length_check(
|
||||
byte_val, msg_buffer, msg_buffer_size)
|
||||
checksum ^= byte_val
|
||||
|
||||
# 4. Checksumme hinzufügen (mit Stuffing)
|
||||
if self._needs_stuffing_byte(checksum):
|
||||
self._add_byte_with_length_check(
|
||||
ESCAPE_BYTE, msg_buffer, msg_buffer_size)
|
||||
self._add_byte_with_length_check(checksum, msg_buffer, msg_buffer_size)
|
||||
|
||||
# 5. EndByte hinzufügen
|
||||
self._add_byte_with_length_check(END_BYTE, msg_buffer, msg_buffer_size)
|
||||
|
||||
# Konvertiere bytearray zu unveränderlichem bytes-Objekt
|
||||
return bytes(msg_buffer)
|
||||
-170
@@ -1,170 +0,0 @@
|
||||
import enum
|
||||
|
||||
# --- Konstanten für das UART-Protokoll ---
|
||||
# Diese Werte müssen mit denen auf deinem Embedded-System übereinstimmen
|
||||
START_BYTE = 0xAA
|
||||
END_BYTE = 0xCC
|
||||
ESCAPE_BYTE = 0x7D # Beispielwert, bitte an dein Protokoll anpassen
|
||||
|
||||
MAX_PAYLOAD_LENGTH = 255 # Maximale Länge des Nachrichten-Payloads (ohne Message ID und Checksumme)
|
||||
# MAX_TOTAL_CONTENT_LENGTH in C beinhaltet Message ID, Payload und Checksumme.
|
||||
# Hier definieren wir MAX_PAYLOAD_LENGTH, da der Parser den Payload sammelt.
|
||||
# Die Gesamtgröße des empfangenen Puffers (message + checksum) darf MAX_PAYLOAD_LENGTH + 1 nicht überschreiten,
|
||||
# da die Checksumme als letztes Byte des Payloads behandelt wird.
|
||||
|
||||
# --- Enumerationen für Parser-Zustände und Fehler ---
|
||||
class ParserState(enum.Enum):
|
||||
WAITING_FOR_START_BYTE = 0
|
||||
GET_MESSAGE_TYPE = 1
|
||||
ESCAPED_MESSAGE_TYPE = 2
|
||||
IN_PAYLOAD = 3
|
||||
ESCAPE_PAYLOAD_BYTE = 4
|
||||
|
||||
class ParserError(enum.Enum):
|
||||
NO_ERROR = 0
|
||||
UNEXPECTED_COMMAND_BYTE = 1
|
||||
WRONG_CHECKSUM = 2
|
||||
MESSAGE_TOO_LONG = 3
|
||||
|
||||
class UartMessageParser:
|
||||
"""
|
||||
Ein State-Machine-Parser für UART-Nachrichten basierend auf der bereitgestellten C-Logik.
|
||||
|
||||
Nachrichtenformat (angenommen):
|
||||
[START_BYTE] [MESSAGE_ID] [PAYLOAD_BYTES...] [CHECKSUM_BYTE] [END_BYTE]
|
||||
|
||||
Escape-Sequenzen:
|
||||
Wenn START_BYTE, END_BYTE oder ESCAPE_BYTE im MESSAGE_ID oder PAYLOAD vorkommen,
|
||||
werden sie durch ESCAPE_BYTE gefolgt vom ursprünglichen Byte (nicht XORed) ersetzt.
|
||||
Die Checksumme wird über die unescaped Bytes berechnet.
|
||||
"""
|
||||
|
||||
def __init__(self, on_message_received_callback=None, on_message_fail_callback=None):
|
||||
"""
|
||||
Initialisiert den UART-Nachrichten-Parser.
|
||||
|
||||
Args:
|
||||
on_message_received_callback (callable, optional): Eine Funktion, die aufgerufen wird,
|
||||
wenn eine gültige Nachricht empfangen wurde.
|
||||
Signatur: on_message_received(message_id: int, payload: bytes, payload_length: int)
|
||||
on_message_fail_callback (callable, optional): Eine Funktion, die aufgerufen wird,
|
||||
wenn ein Nachrichtenfehler auftritt.
|
||||
Signatur: on_message_fail(message_id: int, current_message_buffer: bytes,
|
||||
current_index: int, error_type: ParserError)
|
||||
"""
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.index = 0
|
||||
self.checksum = 0
|
||||
self.message_id = 0
|
||||
self.message_buffer = bytearray(MAX_PAYLOAD_LENGTH + 1) # +1 für Checksummen-Byte
|
||||
self.error = ParserError.NO_ERROR
|
||||
|
||||
# Callbacks für die Anwendung. Standardmäßig None oder einfache Print-Funktionen.
|
||||
self.on_message_received = on_message_received_callback if on_message_received_callback else self._default_on_message_received
|
||||
self.on_message_fail = on_message_fail_callback if on_message_fail_callback else self._default_on_message_fail
|
||||
|
||||
def _default_on_message_received(self, message_id, payload, payload_length):
|
||||
"""Standard-Callback für empfangene Nachrichten, falls keiner angegeben ist."""
|
||||
print(f"Parser: Nachricht empfangen! ID: 0x{message_id:02X}, "
|
||||
f"Payload ({payload_length} Bytes): {payload[:payload_length].hex().upper()}")
|
||||
|
||||
def _default_on_message_fail(self, message_id, current_message_buffer, current_index, error_type):
|
||||
"""Standard-Callback für Nachrichtenfehler, falls keiner angegeben ist."""
|
||||
print(f"Parser: Fehler bei Nachricht! ID: 0x{message_id:02X}, "
|
||||
f"Fehler: {error_type.name}, "
|
||||
f"Bisheriger Puffer ({current_index} Bytes): {current_message_buffer[:current_index].hex().upper()}")
|
||||
|
||||
def parse_byte(self, pbyte: int):
|
||||
"""
|
||||
Verarbeitet ein einzelnes empfangenes Byte.
|
||||
|
||||
Args:
|
||||
pbyte (int): Das empfangene Byte (0-255).
|
||||
"""
|
||||
# Sicherstellen, dass pbyte ein Integer im Bereich 0-255 ist
|
||||
if not isinstance(pbyte, int) or not (0 <= pbyte <= 255):
|
||||
print(f"Parser: Ungültiges Byte empfangen: {pbyte}. Muss ein Integer von 0-255 sein.")
|
||||
return
|
||||
|
||||
current_state = self.state # Für bessere Lesbarkeit
|
||||
|
||||
if current_state == ParserState.WAITING_FOR_START_BYTE:
|
||||
if pbyte == START_BYTE:
|
||||
self.index = 0
|
||||
self.checksum = 0
|
||||
self.message_id = 0 # Reset message_id
|
||||
self.error = ParserError.NO_ERROR # Reset error
|
||||
self.state = ParserState.GET_MESSAGE_TYPE
|
||||
# Andernfalls ignorieren wir Bytes, bis ein Start-Byte gefunden wird
|
||||
|
||||
elif current_state == ParserState.ESCAPED_MESSAGE_TYPE:
|
||||
self.message_id = pbyte
|
||||
self.checksum ^= pbyte
|
||||
self.state = ParserState.IN_PAYLOAD
|
||||
|
||||
elif current_state == ParserState.GET_MESSAGE_TYPE:
|
||||
if pbyte == ESCAPE_BYTE:
|
||||
self.state = ParserState.ESCAPED_MESSAGE_TYPE
|
||||
return # Dieses Byte wurde als Escape-Sequenz verarbeitet, nicht zum Payload hinzufügen
|
||||
if pbyte == START_BYTE or pbyte == END_BYTE:
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.error = ParserError.UNEXPECTED_COMMAND_BYTE
|
||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
||||
return
|
||||
self.message_id = pbyte
|
||||
self.checksum ^= pbyte
|
||||
self.state = ParserState.IN_PAYLOAD
|
||||
|
||||
elif current_state == ParserState.ESCAPE_PAYLOAD_BYTE:
|
||||
# Das escapte Byte ist Teil des Payloads
|
||||
if self.index < MAX_PAYLOAD_LENGTH + 1: # +1 für Checksummen-Byte
|
||||
self.message_buffer[self.index] = pbyte
|
||||
self.index += 1
|
||||
self.checksum ^= pbyte
|
||||
self.state = ParserState.IN_PAYLOAD
|
||||
else:
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.error = ParserError.MESSAGE_TOO_LONG
|
||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
||||
return
|
||||
|
||||
elif current_state == ParserState.IN_PAYLOAD:
|
||||
if pbyte == ESCAPE_BYTE:
|
||||
self.state = ParserState.ESCAPE_PAYLOAD_BYTE
|
||||
return # Dieses Byte wurde als Escape-Sequenz verarbeitet
|
||||
if pbyte == START_BYTE:
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.error = ParserError.UNEXPECTED_COMMAND_BYTE
|
||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
||||
return
|
||||
if pbyte == END_BYTE:
|
||||
if self.checksum != 0x00:
|
||||
# Checksummenfehler: Die Checksumme wurde bis zum End-Byte XORed.
|
||||
# Wenn die empfangene Checksumme korrekt war, sollte das Ergebnis 0 sein.
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.error = ParserError.WRONG_CHECKSUM
|
||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
||||
return
|
||||
|
||||
# Erfolgreich empfangen! Die Checksumme ist das letzte Byte im Puffer.
|
||||
# Die Länge des Payloads ist index - 1 (da das letzte Byte die Checksumme war).
|
||||
payload_length = self.index - 1
|
||||
if payload_length < 0: # Falls nur Message ID und Checksumme, aber kein Payload
|
||||
payload_length = 0
|
||||
|
||||
self.on_message_received(self.message_id, self.message_buffer, payload_length)
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
return # EndByte wurde verarbeitet, nicht zum Payload hinzufügen
|
||||
|
||||
# Normales Payload-Byte
|
||||
if self.index < MAX_PAYLOAD_LENGTH + 1: # +1 für Checksummen-Byte
|
||||
self.message_buffer[self.index] = pbyte
|
||||
self.index += 1
|
||||
self.checksum ^= pbyte
|
||||
else:
|
||||
# Nachricht zu lang
|
||||
self.state = ParserState.WAITING_FOR_START_BYTE
|
||||
self.error = ParserError.MESSAGE_TOO_LONG
|
||||
self.on_message_fail(self.message_id, self.message_buffer, self.index, self.error)
|
||||
return
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import dataclasses
|
||||
import struct
|
||||
from typing import Optional, Union, List
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class StatusMessage:
|
||||
"""
|
||||
Repräsentiert eine Status-Nachricht (z.B. Message ID 0x01).
|
||||
Payload-Format: [status_code: uint8], [battery_level: uint8], [uptime_seconds: uint16]
|
||||
"""
|
||||
status_code: int
|
||||
battery_level: int # 0-100%
|
||||
uptime_seconds: int
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class SensorDataMessage:
|
||||
"""
|
||||
Repräsentiert eine Sensor-Daten-Nachricht (z.B. Message ID 0x02).
|
||||
Payload-Format: [temperature_celsius: int16], [humidity_percent: uint16]
|
||||
"""
|
||||
temperature_celsius: int # signed short
|
||||
humidity_percent: int # unsigned short
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ClientEntry:
|
||||
"""
|
||||
Repräsentiert die Informationen für einen einzelnen Client innerhalb der ClientInfoMessage.
|
||||
Payload-Format:
|
||||
[client_id: uint8]
|
||||
[is_available: uint8] (0=false, >0=true)
|
||||
[is_slot_used: uint8] (0=false, >0=true)
|
||||
[mac_address: bytes (6)]
|
||||
[unoccupied_value_1: uint32]
|
||||
[unoccupied_value_2: uint32]
|
||||
Gesamt: 1 + 1 + 1 + 6 + 4 + 4 = 17 Bytes pro Eintrag.
|
||||
"""
|
||||
client_id: int
|
||||
is_available: bool
|
||||
is_slot_used: bool
|
||||
mac_address: bytes # 6 Bytes MAC-Adresse
|
||||
last_ping: int # 4 Bytes, unbelegt
|
||||
last_successfull_ping: int # 4 Bytes, unbelegt
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ClientInfoMessage:
|
||||
"""
|
||||
Repräsentiert eine Nachricht mit Client-Informationen (Message ID 0x03).
|
||||
Payload-Format:
|
||||
[num_clients: uint8]
|
||||
[client_entry_1: ClientEntry]
|
||||
[client_entry_2: ClientEntry]
|
||||
...
|
||||
"""
|
||||
num_clients: int
|
||||
clients: List[ClientEntry]
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class UnknownMessage:
|
||||
"""
|
||||
Repräsentiert eine Nachricht mit unbekannter ID oder fehlerhaftem Payload.
|
||||
"""
|
||||
message_id: int
|
||||
raw_payload: bytes
|
||||
error_message: str
|
||||
|
||||
# --- Payload Parser Klasse ---
|
||||
|
||||
|
||||
class PayloadParser:
|
||||
"""
|
||||
Interpretiert den Payload einer UART-Nachricht basierend auf ihrer Message ID
|
||||
und wandelt ihn in ein strukturiertes Python-Objekt (dataclass) um.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Ein Dictionary, das Message IDs auf ihre entsprechenden Parsing-Funktionen abbildet.
|
||||
self._parser_map = {
|
||||
0x01: self._parse_status_message,
|
||||
0x02: self._parse_sensor_data_message,
|
||||
# Aktualisiert für die neue 0x03 Struktur
|
||||
0x03: self._parse_client_info_message,
|
||||
0x04: self._parse_client_info_message,
|
||||
# Füge hier weitere Message IDs und ihre Parsing-Funktionen hinzu
|
||||
}
|
||||
|
||||
def _parse_status_message(self, payload: bytes) -> Union[StatusMessage, UnknownMessage]:
|
||||
"""Parsen des Payloads für Message ID 0x01 (StatusMessage)."""
|
||||
# Erwartetes Format: 1 Byte Status, 1 Byte Battery, 2 Bytes Uptime (Little-Endian)
|
||||
if len(payload) != 4:
|
||||
return UnknownMessage(0x01, payload, f"Falsche Payload-Länge für StatusMessage: Erwartet 4, Got {len(payload)}")
|
||||
try:
|
||||
# '<BBH' bedeutet: Little-Endian, Byte (unsigned char), Byte (unsigned char), Half-word (unsigned short)
|
||||
status_code, battery_level, uptime_seconds = struct.unpack(
|
||||
'<BBH', payload)
|
||||
return StatusMessage(status_code, battery_level, uptime_seconds)
|
||||
except struct.error as e:
|
||||
return UnknownMessage(0x01, payload, f"Fehler beim Entpacken der StatusMessage: {e}")
|
||||
|
||||
def _parse_sensor_data_message(self, payload: bytes) -> Union[SensorDataMessage, UnknownMessage]:
|
||||
"""Parsen des Payloads für Message ID 0x02 (SensorDataMessage)."""
|
||||
# Erwartetes Format: 2 Bytes Temperatur (signed short), 2 Bytes Feuchtigkeit (unsigned short) (Little-Endian)
|
||||
if len(payload) != 4:
|
||||
return UnknownMessage(0x02, payload, f"Falsche Payload-Länge für SensorDataMessage: Erwartet 4, Got {len(payload)}")
|
||||
try:
|
||||
# '<hH' bedeutet: Little-Endian, short (signed), unsigned short
|
||||
temperature_celsius, humidity_percent = struct.unpack(
|
||||
'<hH', payload)
|
||||
return SensorDataMessage(temperature_celsius, humidity_percent)
|
||||
except struct.error as e:
|
||||
return UnknownMessage(0x02, payload, f"Fehler beim Entpacken der SensorDataMessage: {e}")
|
||||
|
||||
def _parse_client_info_message(self, payload: bytes) -> Union[ClientInfoMessage, UnknownMessage]:
|
||||
"""Parsen des Payloads für Message ID 0x03 (ClientInfoMessage)."""
|
||||
if not payload:
|
||||
# Wenn der Payload leer ist, aber num_clients erwartet wird, ist das ein Fehler
|
||||
return UnknownMessage(0x03, payload, "Payload für ClientInfoMessage ist leer, aber num_clients erwartet.")
|
||||
|
||||
try:
|
||||
# Das erste Byte ist die Anzahl der Clients
|
||||
num_clients = payload[0]
|
||||
# Die restlichen Bytes sind die Client-Einträge
|
||||
client_data_bytes = payload[1:]
|
||||
|
||||
# 1 (ID) + 1 (Avail) + 1 (Used) + 6 (MAC) + 4 (Val1) + 4 (Val2)
|
||||
EXPECTED_CLIENT_ENTRY_SIZE = 17
|
||||
|
||||
if len(client_data_bytes) != num_clients * EXPECTED_CLIENT_ENTRY_SIZE:
|
||||
return UnknownMessage(0x03, payload,
|
||||
f"Falsche Payload-Länge für Client-Einträge: Erwartet {
|
||||
num_clients * EXPECTED_CLIENT_ENTRY_SIZE}, "
|
||||
f"Got {len(client_data_bytes)} nach num_clients.")
|
||||
|
||||
clients_list: List[ClientEntry] = []
|
||||
# Formatstring für einen Client-Eintrag:
|
||||
# < : Little-Endian
|
||||
# B : uint8 (client_id, is_available, is_slot_used)
|
||||
# 6s: 6 Bytes (mac_address)
|
||||
# I : uint32 (unoccupied_value_1, unoccupied_value_2)
|
||||
CLIENT_ENTRY_FORMAT = '<BBB6sII'
|
||||
|
||||
for i in range(num_clients):
|
||||
start_index = i * EXPECTED_CLIENT_ENTRY_SIZE
|
||||
end_index = start_index + EXPECTED_CLIENT_ENTRY_SIZE
|
||||
entry_bytes = client_data_bytes[start_index:end_index]
|
||||
|
||||
# Entpacke die Daten für einen Client-Eintrag
|
||||
client_id, is_available_byte, is_slot_used_byte, mac_address, val1, val2 = \
|
||||
struct.unpack(CLIENT_ENTRY_FORMAT, entry_bytes)
|
||||
|
||||
# Konvertiere 0/1 Bytes zu boolschen Werten
|
||||
is_available = bool(is_available_byte)
|
||||
is_slot_used = bool(is_slot_used_byte)
|
||||
|
||||
clients_list.append(ClientEntry(
|
||||
client_id=client_id,
|
||||
is_available=is_available,
|
||||
is_slot_used=is_slot_used,
|
||||
mac_address=mac_address,
|
||||
last_ping=val1,
|
||||
last_successfull_ping=val2
|
||||
))
|
||||
|
||||
return ClientInfoMessage(num_clients=num_clients, clients=clients_list)
|
||||
|
||||
except struct.error as e:
|
||||
return UnknownMessage(0x03, payload, f"Fehler beim Entpacken der ClientInfoMessage-Einträge: {e}")
|
||||
except Exception as e:
|
||||
return UnknownMessage(0x03, payload, f"Unerwarteter Fehler beim Parsen der ClientInfoMessage: {e}")
|
||||
|
||||
def parse_payload(self, message_id: int, payload: bytes) -> Union[StatusMessage, SensorDataMessage, ClientInfoMessage, UnknownMessage]:
|
||||
"""
|
||||
Interpretiert den gegebenen Payload basierend auf der Message ID.
|
||||
|
||||
Args:
|
||||
message_id (int): Die ID der Nachricht.
|
||||
payload (bytes): Die rohen Nutzdaten der Nachricht.
|
||||
|
||||
Returns:
|
||||
Union[StatusMessage, SensorDataMessage, ClientInfoMessage, UnknownMessage]:
|
||||
Ein dataclass-Objekt, das die dekodierten Daten repräsentiert,
|
||||
oder ein UnknownMessage-Objekt bei unbekannter ID oder Parsing-Fehler.
|
||||
"""
|
||||
parser_func = self._parser_map.get(message_id)
|
||||
if parser_func:
|
||||
return parser_func(payload)
|
||||
else:
|
||||
return UnknownMessage(message_id, payload, "Unbekannte Message ID.")
|
||||
Reference in New Issue
Block a user