Compare commits
723
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7a244a1ab | ||
|
|
b978809a59 | ||
|
|
6b35db8fbe | ||
|
|
c3f3ecdb83 | ||
|
|
f99df6e5e7 | ||
|
|
e09d9d30dc | ||
|
|
c2f0b5b2d9 | ||
|
|
472eda9f06 | ||
|
|
c831d07573 | ||
|
|
90b51b7e46 | ||
|
|
cdc8a9cb8e | ||
|
|
790eb655a3 | ||
|
|
99584ce813 | ||
|
|
c2a5798905 | ||
|
|
951a822973 | ||
|
|
f5ac615b3c | ||
|
|
3b677f9156 | ||
|
|
9473a8ad5d | ||
|
|
56ef79ff45 | ||
|
|
d61e48ce79 | ||
|
|
86f15f9eb1 | ||
|
|
84e10530a5 | ||
|
|
2f74a720f5 | ||
|
|
511e50fe52 | ||
|
|
78da59fc71 | ||
|
|
36f70c3222 | ||
|
|
279c1c5bf1 | ||
|
|
f5ba6e244f | ||
|
|
6a980b47ae | ||
|
|
3a783bf50c | ||
|
|
9dabb43a9c | ||
|
|
b9fd2f75ff | ||
|
|
61f65ed42a | ||
|
|
634bff08af | ||
|
|
2d1ccf518a | ||
|
|
d9600d0607 | ||
|
|
72cf358b0c | ||
|
|
a819248556 | ||
|
|
6e334392da | ||
|
|
eed2aeb1be | ||
|
|
84163dcd2a | ||
|
|
30573c7ba3 | ||
|
|
c3c58b3f67 | ||
|
|
bc3f9b65a0 | ||
|
|
5513fce18f | ||
|
|
df3462875b | ||
|
|
e2d5eb061f | ||
|
|
2921ede080 | ||
|
|
004405e868 | ||
|
|
d411e9c25b | ||
|
|
e712e3b47c | ||
|
|
b09a590fb6 | ||
|
|
f9407d8d8d | ||
|
|
eec01faa0a | ||
|
|
d2daad0bf2 | ||
|
|
55d357ecf8 | ||
|
|
15f9993c12 | ||
|
|
52840348bf | ||
|
|
d5cb12dc3c | ||
|
|
9f1cda3c60 | ||
|
|
5e81d6a369 | ||
|
|
7a50d3e42f | ||
|
|
587c8bf334 | ||
|
|
dbf21d9c90 | ||
|
|
60e4b994ab | ||
|
|
8c061efc1e | ||
|
|
262d2b2ed4 | ||
|
|
b07aa2ddfe | ||
|
|
386fec4220 | ||
|
|
e2602b5c17 | ||
|
|
26d894222a | ||
|
|
c20b944411 | ||
|
|
f60de36bae | ||
|
|
929dac374b | ||
|
|
fd3282efe2 | ||
|
|
359597131e | ||
|
|
0b922aeeb5 | ||
|
|
29b6ff8c24 | ||
|
|
ae3f9365b1 | ||
|
|
c666a4c3bd | ||
|
|
e4bcf9bd23 | ||
|
|
8a0d4a8f03 | ||
|
|
a6e11af084 | ||
|
|
2403ee2b27 | ||
|
|
9d57b2dafd | ||
|
|
86f6ea55ec | ||
|
|
2ff1ee474e | ||
|
|
ccd5778f57 | ||
|
|
af9f181ff5 | ||
|
|
d50fa87baf | ||
|
|
f2b609f12c | ||
|
|
c53b0955f8 | ||
|
|
dc6860378d | ||
|
|
84bf5ef05c | ||
|
|
31ac6e4707 | ||
|
|
048af92808 | ||
|
|
4a08b8148b | ||
|
|
cce519de6d | ||
|
|
d24a4d12e2 | ||
|
|
8cea9e79e5 | ||
|
|
a222a2d053 | ||
|
|
093a1b1af9 | ||
|
|
c30e6293f6 | ||
|
|
03a7e1473a | ||
|
|
5ccdc27d37 | ||
|
|
107902ef3a | ||
|
|
29b47aa44e | ||
|
|
427046239c | ||
|
|
c4c35d1bde | ||
|
|
81a573ba6d | ||
|
|
7d771fc94b | ||
|
|
4f50a962e6 | ||
|
|
7468d77178 | ||
|
|
19a468ac2e | ||
|
|
a46192d47c | ||
|
|
45fec7cfc2 | ||
|
|
3f4bc510a7 | ||
|
|
42ff221b07 | ||
|
|
9a153cda80 | ||
|
|
1f37e699b2 | ||
|
|
45789d44d6 | ||
|
|
c1445ea1e1 | ||
|
|
74274ae30e | ||
|
|
233a73e1dc | ||
|
|
f8b48544f8 | ||
|
|
5e9783fed3 | ||
|
|
78186a2725 | ||
|
|
824206faaa | ||
|
|
f61fef9b32 | ||
|
|
37049f7ca4 | ||
|
|
8db2fd4a91 | ||
|
|
3a2db7aaa8 | ||
|
|
78375b220d | ||
|
|
1ea8f182fa | ||
|
|
8380227f8f | ||
|
|
a424fa55c0 | ||
|
|
cd582b90c8 | ||
|
|
2348c1e442 | ||
|
|
7ae5e14c2d | ||
|
|
7faddb3b50 | ||
|
|
50126a3833 | ||
|
|
0a9aa284ae | ||
|
|
7f8cf76a8c | ||
|
|
cdec5b0958 | ||
|
|
4235d9dc85 | ||
|
|
27e0ddc888 | ||
|
|
78f0a87528 | ||
|
|
31723e9469 | ||
|
|
2ae25a1e58 | ||
|
|
8a11f6e867 | ||
|
|
8c6f5be1bd | ||
|
|
b728ba14c7 | ||
|
|
ceff4c2495 | ||
|
|
8b825cc5fa | ||
|
|
b45aee252f | ||
|
|
0b9a7c17e9 | ||
|
|
2291f778da | ||
|
|
6fafb67c45 | ||
|
|
1d3336ece5 | ||
|
|
1892278633 | ||
|
|
afe6346e74 | ||
|
|
c8d08d22b2 | ||
|
|
ad26b55730 | ||
|
|
6c87d81a81 | ||
|
|
3771098c2f | ||
|
|
94805c881e | ||
|
|
5734321633 | ||
|
|
fb4f929109 | ||
|
|
16022c8b28 | ||
|
|
17f3695ca7 | ||
|
|
000f756420 | ||
|
|
6a1415913b | ||
|
|
3014be9008 | ||
|
|
618aafef2c | ||
|
|
ca5de6445d | ||
|
|
82a39a2fa1 | ||
|
|
77be9483b0 | ||
|
|
4fcaf4d538 | ||
|
|
70e62170a9 | ||
|
|
92447b63b8 | ||
|
|
1bcf1cfe85 | ||
|
|
aef898c471 | ||
|
|
0bbd334a78 | ||
|
|
80e705bd60 | ||
|
|
19c2031691 | ||
|
|
52c4515e62 | ||
|
|
8d3c0af7af | ||
|
|
f4d7bebbf1 | ||
|
|
e04c2a10f0 | ||
|
|
1dc25da8f2 | ||
|
|
df3b36954c | ||
|
|
d12d17c052 | ||
|
|
c0d0f396b0 | ||
|
|
7fccda4aa7 | ||
|
|
17846c7bfc | ||
|
|
8adae665fb | ||
|
|
a5a3cf9715 | ||
|
|
ac0703dbfd | ||
|
|
fa155df974 | ||
|
|
e7b9aee122 | ||
|
|
4f2a010e33 | ||
|
|
f1c35a1809 | ||
|
|
a2bec57251 | ||
|
|
8ead7ad2fc | ||
|
|
bd2a3b4ebc | ||
|
|
c37cedf183 | ||
|
|
1fe1ce5046 | ||
|
|
7ebe73b226 | ||
|
|
7dae880bb2 | ||
|
|
438d2a71e1 | ||
|
|
0f76622b17 | ||
|
|
9945b02fd9 | ||
|
|
f514733706 | ||
|
|
bd9da2620b | ||
|
|
6d0d290644 | ||
|
|
a3aa3c4556 | ||
|
|
f253100ea7 | ||
|
|
ad5d09045c | ||
|
|
8bd560b04e | ||
|
|
bf9cfc7178 | ||
|
|
a8ee89b6c0 | ||
|
|
e46c00e45a | ||
|
|
a064fa7d3e | ||
|
|
575da98dc9 | ||
|
|
ede2c58d46 | ||
|
|
f4456456f8 | ||
|
|
612684339c | ||
|
|
5785b0ffb3 | ||
|
|
b49ce87f32 | ||
|
|
3949dca1af | ||
|
|
c2212b9038 | ||
|
|
e4016a8d97 | ||
|
|
c8be843ebc | ||
|
|
25bd29f2a7 | ||
|
|
52a4c5a120 | ||
|
|
c52ae2b1c0 | ||
|
|
2e6f9c7190 | ||
|
|
ec88f5c312 | ||
|
|
44675f25b4 | ||
|
|
eaded82874 | ||
|
|
c293bf7790 | ||
|
|
766139f2cd | ||
|
|
3db62214ee | ||
|
|
916f52f56a | ||
|
|
3a1793f43f | ||
|
|
e905d47b8e | ||
|
|
7e9474050e | ||
|
|
52eaf1a0fd | ||
|
|
babd654d88 | ||
|
|
e941744fbb | ||
|
|
f8e4333274 | ||
|
|
9bdea03bd9 | ||
|
|
391e3956b5 | ||
|
|
aead6ccbff | ||
|
|
e5583e697a | ||
|
|
e045aaf876 | ||
|
|
d8147b1fdc | ||
|
|
7508a956f9 | ||
|
|
0bc9f61d2f | ||
|
|
0ab6bfa1c3 | ||
|
|
e2ced4d76e | ||
|
|
3e6c14f7cb | ||
|
|
5dbf61620d | ||
|
|
29d2218ff8 | ||
|
|
8dd1c27784 | ||
|
|
9d40b8e315 | ||
|
|
0b453b0e0d | ||
|
|
e122ff2c05 | ||
|
|
5f25f99f91 | ||
|
|
17aa3accce | ||
|
|
5bd5703885 | ||
|
|
cd1407bcbf | ||
|
|
7087b348c4 | ||
|
|
40f198a516 | ||
|
|
baef43ce8d | ||
|
|
fbf33e6393 | ||
|
|
182ec7b1c1 | ||
|
|
6b5380e56e | ||
|
|
0898b40f3e | ||
|
|
600a864ffd | ||
|
|
627a10f0ac | ||
|
|
90e21e9916 | ||
|
|
10eecf416c | ||
|
|
9f3c482f51 | ||
|
|
9a524afa84 | ||
|
|
2d7b3e765e | ||
|
|
f73527b933 | ||
|
|
1c9be03fd3 | ||
|
|
f710f5385b | ||
|
|
cc2c6ffc3b | ||
|
|
06edd88696 | ||
|
|
124771b143 | ||
|
|
6fac0097dd | ||
|
|
2a0c2a2b46 | ||
|
|
000fa4e297 | ||
|
|
db0cc39b4b | ||
|
|
063855f720 | ||
|
|
9c0eed7a11 | ||
|
|
12e145b5ea | ||
|
|
c19bba9235 | ||
|
|
7ae61604b8 | ||
|
|
185419ce19 | ||
|
|
19b60aa192 | ||
|
|
b80144492e | ||
|
|
edf89dc993 | ||
|
|
6c33c0a3ae | ||
|
|
2114af085d | ||
|
|
6a2ed051d3 | ||
|
|
561f978635 | ||
|
|
61eb3c3cb7 | ||
|
|
5503bb8c10 | ||
|
|
b6dd2e6c0d | ||
|
|
d75e416c96 | ||
|
|
0cc5bbdca9 | ||
|
|
5f4085f925 | ||
|
|
58e74fc3ee | ||
|
|
a75e12deca | ||
|
|
1923bb8439 | ||
|
|
9ef394ff1d | ||
|
|
4bfb9738cb | ||
|
|
83ea1b4edd | ||
|
|
11a4ec921d | ||
|
|
f375d1b14d | ||
|
|
87bd7d7287 | ||
|
|
cab43d0b09 | ||
|
|
a49a9d248f | ||
|
|
63e9026191 | ||
|
|
cf55029594 | ||
|
|
a594018762 | ||
|
|
2b56705172 | ||
|
|
9f1bcd6f55 | ||
|
|
a8aa52aec7 | ||
|
|
a48cec8bcb | ||
|
|
b22e3ca4cd | ||
|
|
04e44b3703 | ||
|
|
23a4790b8d | ||
|
|
50b12bd124 | ||
|
|
6747edf2c7 | ||
|
|
a33897ec2c | ||
|
|
e436b27e63 | ||
|
|
57c55e4121 | ||
|
|
ff76e4d2d7 | ||
|
|
0f7598e9fc | ||
|
|
624fd72939 | ||
|
|
0f40722e33 | ||
|
|
04a779ad14 | ||
|
|
0145983198 | ||
|
|
9021acf6d6 | ||
|
|
039edfc18e | ||
|
|
324d14e3f2 | ||
|
|
81b148f6cd | ||
|
|
fdd50f9dc0 | ||
|
|
de39e7ed2a | ||
|
|
f10f9f9706 | ||
|
|
e194d8dc02 | ||
|
|
1c218b3587 | ||
|
|
dea3cbdb39 | ||
|
|
f1baaf7458 | ||
|
|
35c53fba90 | ||
|
|
880c06bce9 | ||
|
|
8aa8345d87 | ||
|
|
80d28440b3 | ||
|
|
7ec17c0cc5 | ||
|
|
982d7aa199 | ||
|
|
13690d723f | ||
|
|
62a694fbe4 | ||
|
|
02bd3fb606 | ||
|
|
f70a93ac56 | ||
|
|
a301944298 | ||
|
|
79e012647a | ||
|
|
ad0b79eec5 | ||
|
|
9b23d8dbfc | ||
|
|
8327a8348b | ||
|
|
7d95663d90 | ||
|
|
8b85042fe8 | ||
|
|
6c69acf0cb | ||
|
|
f07d3ce318 | ||
|
|
162bdf85cc | ||
|
|
3516af13ba | ||
|
|
cf54129b5c | ||
|
|
1094cdf713 | ||
|
|
6848a793ca | ||
|
|
2dcb807b74 | ||
|
|
a036c38b1b | ||
|
|
7ab46e4273 | ||
|
|
af1e52b850 | ||
|
|
08d174a89d | ||
|
|
0fbde1f5f9 | ||
|
|
1d841714c1 | ||
|
|
f2a6349203 | ||
|
|
dae1fd3761 | ||
|
|
b8cab8f68d | ||
|
|
4b8d16d028 | ||
|
|
ea4de74e8d | ||
|
|
73204acf52 | ||
|
|
33a227420a | ||
|
|
d432f7862d | ||
|
|
884b7c600d | ||
|
|
7a5def551d | ||
|
|
643953845a | ||
|
|
8aee6e8e8d | ||
|
|
c0e1a817d2 | ||
|
|
b70a88451d | ||
|
|
c3f0a8c0c5 | ||
|
|
996e55a3dd | ||
|
|
999bb3315e | ||
|
|
1883e5362e | ||
|
|
10642b18d1 | ||
|
|
5bf46f170e | ||
|
|
cdb86848da | ||
|
|
58b1e3145a | ||
|
|
09d16deb8c | ||
|
|
5fc92f0bf4 | ||
|
|
d471072fc3 | ||
|
|
6bf11047b8 | ||
|
|
38b40fd989 | ||
|
|
ffd869091b | ||
|
|
1d824b80b0 | ||
|
|
df8c02cd7b | ||
|
|
2e5cbdce6a | ||
|
|
ebb6e874c8 | ||
|
|
deece56488 | ||
|
|
5d2dad36c2 | ||
|
|
8f1c3ece9d | ||
|
|
0dd2eb744d | ||
|
|
b7b36bb525 | ||
|
|
81e7fd8ecf | ||
|
|
cc517588fe | ||
|
|
20601b897e | ||
|
|
a17a826f3c | ||
|
|
cc4e0dadbd | ||
|
|
561f893d2a | ||
|
|
a83ec69663 | ||
|
|
5ca8eae8f4 | ||
|
|
8b6cc4be7a | ||
|
|
9d0e6516b5 | ||
|
|
cbbf3992a4 | ||
|
|
340f3f924b | ||
|
|
d738843fd9 | ||
|
|
f4bcde6ffc | ||
|
|
a86565f68b | ||
|
|
373a3478ea | ||
|
|
a0dcbbfd51 | ||
|
|
9d03821c54 | ||
|
|
ce1b410f74 | ||
|
|
921be53ef0 | ||
|
|
3a960141b1 | ||
|
|
eea7f8505b | ||
|
|
8acf004ad0 | ||
|
|
3404345410 | ||
|
|
892bbc1cd1 | ||
|
|
e5bbd631eb | ||
|
|
4bf399f171 | ||
|
|
a2e184d42f | ||
|
|
1440cd62e8 | ||
|
|
c2365c1e64 | ||
|
|
988c782eac | ||
|
|
4de0185fc2 | ||
|
|
e3ac3089aa | ||
|
|
692b7429c7 | ||
|
|
4ecb2a1ae4 | ||
|
|
9ba2a59eda | ||
|
|
bc6c6adccd | ||
|
|
5d4488ad33 | ||
|
|
4680ec4c2b | ||
|
|
ae908e914b | ||
|
|
8c25de15cf | ||
|
|
babc2fa81a | ||
|
|
ffdbdb6777 | ||
|
|
4897dc80eb | ||
|
|
ddee51dcd8 | ||
|
|
98c360162e | ||
|
|
629004d98f | ||
|
|
e12ac6c7b4 | ||
|
|
d93534a1c2 | ||
|
|
6e325f8b9a | ||
|
|
1c07973c37 | ||
|
|
9efedd660a | ||
|
|
9a69de6dcd | ||
|
|
165e07fa8a | ||
|
|
13792fe014 | ||
|
|
4a773886ae | ||
|
|
ca5a598274 | ||
|
|
fccb54af8f | ||
|
|
0510d35910 | ||
|
|
5e6f1eabfd | ||
|
|
0afc0d8154 | ||
|
|
f5fd552f25 | ||
|
|
b72d47e26c | ||
|
|
e89aca4a31 | ||
|
|
e82f70405e | ||
|
|
fc6573e91c | ||
|
|
5a62bb1df1 | ||
|
|
9692aa82da | ||
|
|
05cb032d3c | ||
|
|
6ac4b70ff3 | ||
|
|
949192b620 | ||
|
|
4721d364f1 | ||
|
|
0dc25690f4 | ||
|
|
ce9f3e7a1b | ||
|
|
eda598c40f | ||
|
|
f4630f4d07 | ||
|
|
30fad08706 | ||
|
|
1227ff1e96 | ||
|
|
02f4cab6ba | ||
|
|
f479c8282a | ||
|
|
a2ca630bdd | ||
|
|
772ba86156 | ||
|
|
5c83472fae | ||
|
|
a7202fa9e1 | ||
|
|
055d731fec | ||
|
|
ae86407483 | ||
|
|
a91979d2b6 | ||
|
|
64af3dce1a | ||
|
|
6a432b30ad | ||
|
|
ce8c2d3648 | ||
|
|
e00ed786ac | ||
|
|
bdd270d3ca | ||
|
|
5ccfd6a0d8 | ||
|
|
f4612b8f8d | ||
|
|
b8118dadc9 | ||
|
|
c342434848 | ||
|
|
d01f5684b4 | ||
|
|
2b0f465c25 | ||
|
|
ea4f4130ce | ||
|
|
c581ad43f4 | ||
|
|
ea0c91ee83 | ||
|
|
e07f97bc12 | ||
|
|
17c293b3fd | ||
|
|
61e9baab53 | ||
|
|
2e04405550 | ||
|
|
afdb0f495c | ||
|
|
9b59888b08 | ||
|
|
d7e84891f6 | ||
|
|
f88b1a6ce6 | ||
|
|
2e8126cd73 | ||
|
|
32400971a5 | ||
|
|
80a75b20a6 | ||
|
|
882d34de5a | ||
|
|
cecb29b46f | ||
|
|
6396883a26 | ||
|
|
efa4a1d7a7 | ||
|
|
a961829c63 | ||
|
|
9604ecb29f | ||
|
|
21030072cc | ||
|
|
dda603a9a4 | ||
|
|
a8a727a248 | ||
|
|
25b561c976 | ||
|
|
a598ddd2a4 | ||
|
|
bbc176e9f7 | ||
|
|
7a6a2ca2e7 | ||
|
|
6e1cf2f020 | ||
|
|
428a6f767a | ||
|
|
f7f12c76a1 | ||
|
|
782a9f7c4c | ||
|
|
3803bc02ab | ||
|
|
71de7da506 | ||
|
|
d92cb38ec9 | ||
|
|
edf2f25952 | ||
|
|
d0f760ea7b | ||
|
|
31aefdbc74 | ||
|
|
4ff53b73af | ||
|
|
3acd0b4a3c | ||
|
|
5baacbeeed | ||
|
|
b5312edb90 | ||
|
|
affc0d9b94 | ||
|
|
5c9a196333 | ||
|
|
da3b0d77c1 | ||
|
|
fc5e8e039f | ||
|
|
e2c2ce26c3 | ||
|
|
59d7600cdb | ||
|
|
b0eee39f13 | ||
|
|
fab6a11820 | ||
|
|
6d7b07d07b | ||
|
|
28830d55d0 | ||
|
|
fb83321d70 | ||
|
|
0f1c30fe00 | ||
|
|
e4f67ef3c2 | ||
|
|
9f3181e2cd | ||
|
|
9ca38b1e8b | ||
|
|
d44b1dcdb0 | ||
|
|
efd79ba00c | ||
|
|
d69f1cc557 | ||
|
|
b0378e08b1 | ||
|
|
11396dfe68 | ||
|
|
e5f579860c | ||
|
|
018c70a054 | ||
|
|
7ad7706341 | ||
|
|
4dd4ffee7a | ||
|
|
07257ede2d | ||
|
|
024659ee45 | ||
|
|
00e46783b6 | ||
|
|
f6dd3b718b | ||
|
|
e580985951 | ||
|
|
25ba342a16 | ||
|
|
66fbd99f37 | ||
|
|
eb3abb4fb0 | ||
|
|
b5584bb851 | ||
|
|
832907f574 | ||
|
|
e973b1eced | ||
|
|
963e4799c6 | ||
|
|
8ee375fda1 | ||
|
|
534b8df829 | ||
|
|
d665b633df | ||
|
|
71d1808525 | ||
|
|
3f96dc1996 | ||
|
|
8ab4ba3b33 | ||
|
|
74f11769a0 | ||
|
|
80757c170b | ||
|
|
9cc3ca856f | ||
|
|
8e2aa426a5 | ||
|
|
c5948f3850 | ||
|
|
cf7efca44d | ||
|
|
9d4ebe0bf8 | ||
|
|
7de269d1b3 | ||
|
|
1f98cf517b | ||
|
|
011a639356 | ||
|
|
051887a7c3 | ||
|
|
e603699e45 | ||
|
|
9a3b8317c4 | ||
|
|
0e68b2bc53 | ||
|
|
1416ee678c | ||
|
|
7ecd089bc5 | ||
|
|
152282a2d8 | ||
|
|
3ee6cdd575 | ||
|
|
317f4cd6a6 | ||
|
|
60fb3c0200 | ||
|
|
67f42feabd | ||
|
|
1acb893305 | ||
|
|
266fd67aad | ||
|
|
e7a87ed3ee | ||
|
|
fc29372e04 | ||
|
|
ac6062f705 | ||
|
|
5935d331b3 | ||
|
|
c9a3561088 | ||
|
|
cbf03fca5b | ||
|
|
bae4182bf5 | ||
|
|
3d866a482e | ||
|
|
6731086e85 | ||
|
|
5ffde81f2e | ||
|
|
fdf33b42e5 | ||
|
|
98539c823a | ||
|
|
2887cd34e3 | ||
|
|
39e2391efd | ||
|
|
5bd4c5aff4 | ||
|
|
5d30e1a8b1 | ||
|
|
419c9561d2 | ||
|
|
4e16ae912d | ||
|
|
b86f5abf6c | ||
|
|
60810fc0f7 | ||
|
|
c1151acecb | ||
|
|
0d39cbaeff | ||
|
|
143390d6f4 | ||
|
|
4b53e426cf | ||
|
|
6811f15aba | ||
|
|
65748bd117 | ||
|
|
0fa62698a7 | ||
|
|
4723435a45 | ||
|
|
87ca90528a | ||
|
|
ad1b34239c | ||
|
|
7cf0bfc24b | ||
|
|
cd842ae4d4 | ||
|
|
18880ae1d2 | ||
|
|
1a5ce73b6d | ||
|
|
8f82bb7fbc | ||
|
|
fc86e04861 | ||
|
|
085c59d355 | ||
|
|
7d337c86cb | ||
|
|
e69ea587f4 | ||
|
|
b49cb5078f | ||
|
|
89982a8097 | ||
|
|
2c66120b99 | ||
|
|
9846eb99c6 | ||
|
|
94be9e603c | ||
|
|
d0552d5618 | ||
|
|
10f1e584a8 | ||
|
|
8e293a4f1b | ||
|
|
0f5c6ece93 | ||
|
|
f3b3684f00 | ||
|
|
1fbe7e6122 | ||
|
|
f6ab54a09c | ||
|
|
80e416d01d | ||
|
|
fc802c873a | ||
|
|
9a6d8572b4 | ||
|
|
5ff211747e | ||
|
|
1b68d73399 | ||
|
|
0317137616 | ||
|
|
418f8a0fa8 | ||
|
|
7eed4a037a | ||
|
|
3a71c7e651 | ||
|
|
02642c2638 | ||
|
|
296c281f15 | ||
|
|
a4012f258e | ||
|
|
b5e8cb8ff7 | ||
|
|
a9a0048d78 | ||
|
|
22e2dfbed3 | ||
|
|
98a0d3cd5d | ||
|
|
a562dcdba2 | ||
|
|
5583313394 | ||
|
|
5fde4c6800 | ||
|
|
55555333ff | ||
|
|
698fc0841f | ||
|
|
8d13f14bea | ||
|
|
84b4c0659a | ||
|
|
3ba10ace5d | ||
|
|
c4e3745d27 | ||
|
|
7ab104a4ac | ||
|
|
227d04549e | ||
|
|
73536b5f55 | ||
|
|
83e25c86b2 | ||
|
|
0548b422da | ||
|
|
4ea20f0542 | ||
|
|
826814abd7 | ||
|
|
63875d1175 | ||
|
|
9a0eb567dd | ||
|
|
c836c956f8 | ||
|
|
fa44f7077f | ||
|
|
3d94f30145 | ||
|
|
bfb84807e8 | ||
|
|
728e2fde05 | ||
|
|
86b0fb091e | ||
|
|
01d60b336e | ||
|
|
bfa1fdf3b3 |
No files matched your search
+14
-1
@@ -1,2 +1,15 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
rustflags = ["-C", "target-feature=+crt-static", "--cfg", "tokio_unstable"]
|
||||
|
||||
# TODO not good as a default
|
||||
[target.armv7-unknown-linux-gnueabihf]
|
||||
linker = "arm-linux-gnueabihf-gcc"
|
||||
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
linker = "aarch64-linux-gnu-gcc"
|
||||
|
||||
[target.i686-unknown-linux-gnu]
|
||||
linker = "i686-linux-gnu-gcc"
|
||||
|
||||
[build]
|
||||
rustflags = ["--cfg", "tokio_unstable"]
|
||||
@@ -0,0 +1,3 @@
|
||||
target/
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
@@ -0,0 +1,25 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something isn't working
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior. Example:
|
||||
1. Create this configuration file:
|
||||
2. Launch Neolink:
|
||||
3. Click on ... in Blue Iris
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Versions**
|
||||
NVR software:
|
||||
Neolink software:
|
||||
Reolink camera model and firmware:
|
||||
@@ -0,0 +1,14 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex: "I'm always frustrated when [...]"
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
@@ -1,52 +0,0 @@
|
||||
name: CI
|
||||
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
ubuntu:
|
||||
name: build
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-18.04, windows-2019]
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- if: runner.os == 'Linux'
|
||||
name: apt install gstreamer
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgstreamer-plugins-bad1.0-dev libgstreamer-plugins-good1.0-dev
|
||||
- if: runner.os == 'Windows'
|
||||
name: Install Gstreamer
|
||||
run: |
|
||||
$curlgst = Start-Job -ScriptBlock { curl.exe -fsSL "https://gstreamer.freedesktop.org/data/pkg/windows/1.16.2/gstreamer-1.0-devel-msvc-x86_64-1.16.2.msi" -o gstreamer-1.0-devel.msi }
|
||||
choco install -y --no-progress gstreamer
|
||||
echo "Installing gstreamer-1.0-devel"
|
||||
Wait-Job $curlgst
|
||||
msiexec /i gstreamer-1.0-devel.msi /qn /norestart
|
||||
echo "Updating Environment"
|
||||
echo "::add-path::C:\gstreamer\1.0\x86_64\bin"
|
||||
echo "::set-env name=GSTREAMER_1_0_ROOT_X86_64::C:\gstreamer\1.0\x86_64\"
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: ~/.cargo/registry
|
||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Cache cargo index
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: ~/.cargo/git
|
||||
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Cache cargo build
|
||||
uses: actions/cache@v1
|
||||
with:
|
||||
path: target
|
||||
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
command: build
|
||||
args: --release --all-features
|
||||
- uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: release-${{ matrix.os }}
|
||||
path: "target/release/neolink*"
|
||||
@@ -0,0 +1,365 @@
|
||||
name: CI
|
||||
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
|
||||
jobs:
|
||||
pre_job:
|
||||
# continue-on-error: true # Uncomment once integration is finished
|
||||
runs-on: ubuntu-latest
|
||||
# Map a step output to a job output
|
||||
outputs:
|
||||
should_skip: ${{ steps.skip_check.outputs.should_skip }} && ! (startsWith(github.ref, 'refs/tags/') && github.event_name == 'push')
|
||||
steps:
|
||||
- id: skip_check
|
||||
uses: fkirc/skip-duplicate-actions@v5
|
||||
with:
|
||||
# All of these options are optional, so you can remove them if you are happy with the defaults
|
||||
concurrent_skipping: 'same_content_newer'
|
||||
skip_after_successful_duplicate: 'false'
|
||||
|
||||
native:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: native
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-22.04, windows-2022, macos-12]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
name: Checkout onto ${{ runner.os }}
|
||||
- if: runner.os == 'Linux'
|
||||
name: apt install gstreamer
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y aptitude
|
||||
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev
|
||||
- if: runner.os == 'Windows'
|
||||
name: Install Gstreamer
|
||||
run: |
|
||||
choco install -y --no-progress gstreamer --version=1.20.0
|
||||
choco install -y --no-progress gstreamer-devel --version=1.20.0
|
||||
$env:GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:SYSTEMDRIVE + '\gstreamer\1.0\msvc_x86_64\'
|
||||
echo "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
||||
Add-Content -Path $env:GITHUB_PATH -Value "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64\bin"
|
||||
Add-Content -Path $env:GITHUB_PATH -Value "%GSTREAMER_1_0_ROOT_MSVC_X86_64%\bin"
|
||||
- if: runner.os == 'macOS'
|
||||
name: Install Gstreamer on macOS
|
||||
run: |
|
||||
curl -L 'https://gstreamer.freedesktop.org/data/pkg/osx/1.20.4/gstreamer-1.0-devel-1.20.4-universal.pkg' -o "$(pwd)/gstreamer-devel.pkg"
|
||||
sudo installer -verbose -pkg "$(pwd)/gstreamer-devel.pkg" -target /
|
||||
PKG_CONFIG_PATH="/Library/Frameworks/GStreamer.framework/Versions/1.0/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}"
|
||||
PKG_CONFIG_GSTREAMER_1_0_PREFIX="/Library/Frameworks/GStreamer.framework/Versions/1.0"
|
||||
echo "PKG_CONFIG_PATH=${PKG_CONFIG_PATH}" >> "${GITHUB_ENV}"
|
||||
echo "PKG_CONFIG_GSTREAMER_1_0_PREFIX=${PKG_CONFIG_GSTREAMER_1_0_PREFIX}" >> "${GITHUB_ENV}"
|
||||
echo "PKG_CONFIG_PATH=${PKG_CONFIG_PATH}"
|
||||
brew install pkg-config
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.cargo/registry
|
||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Cache cargo index
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ~/.cargo/git
|
||||
key: ${{ runner.os }}-cargo-index-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Cache cargo build
|
||||
if: runner.os != 'macOS' # Random missing crates on macOS, unclear why
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: target
|
||||
key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Build
|
||||
shell: bash
|
||||
run: |
|
||||
echo "PATH=${PATH}"
|
||||
echo "GSTREAMER_1_0_ROOT_MSVC_X86_64=${GSTREAMER_1_0_ROOT_MSVC_X86_64}"
|
||||
echo "PKG_CONFIG_PATH=${PKG_CONFIG_PATH}"
|
||||
# pkg-config --variable pc_path pkg-config
|
||||
cargo build --release --all-features
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: release-${{ matrix.os }}
|
||||
path: "target/release/neolink*"
|
||||
cross:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: cross
|
||||
runs-on: ubuntu-latest
|
||||
container: "node:current-bullseye-slim"
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# Everyone has a slightly different screwball naming scheme;
|
||||
# Rust uses the target triple, GCC generally targets a family
|
||||
# with a specific prefix, and dpkg's arch does its own thing
|
||||
include:
|
||||
- arch: amd64
|
||||
target: x86_64-unknown-linux-gnu
|
||||
gcc: x86-64-linux-gnu
|
||||
pkgconfig: x86_64-linux-gnu
|
||||
- arch: armhf
|
||||
target: armv7-unknown-linux-gnueabihf
|
||||
gcc: arm-linux-gnueabihf
|
||||
pkgconfig: arm-linux-gnueabihf
|
||||
- arch: arm64
|
||||
target: aarch64-unknown-linux-gnu
|
||||
gcc: aarch64-linux-gnu
|
||||
pkgconfig: aarch64-linux-gnu
|
||||
- arch: i386
|
||||
target: i686-unknown-linux-gnu
|
||||
gcc: i686-linux-gnu
|
||||
# on i686, the pkgconfig path doesn't match the prefix!
|
||||
pkgconfig: i386-linux-gnu
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install basic tools
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install --assume-yes --no-install-recommends curl ca-certificates
|
||||
- name: Install ${{ matrix.arch }} cross compiler and gstreamer
|
||||
id: setup
|
||||
run: |
|
||||
dpkg --add-architecture ${{ matrix.arch }}
|
||||
apt-get update
|
||||
apt-get install --assume-yes --no-install-recommends \
|
||||
build-essential \
|
||||
gcc-${{ matrix.gcc }} \
|
||||
g++-${{ matrix.gcc }} \
|
||||
libgstrtspserver-1.0-dev:${{ matrix.arch }} \
|
||||
libgstreamer1.0-dev:${{ matrix.arch }} \
|
||||
libgtk2.0-dev:${{ matrix.arch }} \
|
||||
libglib2.0-dev:${{ matrix.arch }}
|
||||
- name: Install rustup
|
||||
run: |
|
||||
curl https://sh.rustup.rs -sSf | sh -s -- --no-modify-path --quiet -y
|
||||
echo "${HOME}/.cargo/bin" >> "${GITHUB_PATH}"
|
||||
- name: Install ${{ matrix.arch }} Rust toolchain
|
||||
run: |
|
||||
rustup target add ${TARGET}
|
||||
env:
|
||||
TARGET: ${{ matrix.target }}
|
||||
- name: Build
|
||||
run: |
|
||||
cargo build --verbose --release --all-features --target=${TARGET}
|
||||
env:
|
||||
# Retarget pkg-config as described in https://www.freedesktop.org/wiki/Software/pkg-config/CrossCompileProposal/
|
||||
PKG_CONFIG_ALLOW_CROSS: 1
|
||||
PKG_CONFIG_LIBDIR: /usr/lib/${{ matrix.pkgconfig }}/pkgconfig
|
||||
TARGET: ${{ matrix.target }}
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: release-${{ matrix.arch }}-bullseye
|
||||
path: "target/${{ matrix.target }}/release/neolink*"
|
||||
|
||||
push_to_registry:
|
||||
name: Build Docker image
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- "cross"
|
||||
steps:
|
||||
- name: Check token is set
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
unset HAS_SECRET
|
||||
if [ -n $SECRET ]; then HAS_SECRET='true' ; fi
|
||||
echo "HAS_SECRET_TOKEN=${HAS_SECRET}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
SECRET: "${{ secrets.DOCKER_TOKEN }}"
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v3
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
- name: Convert username to lower case for docker
|
||||
id: string_user
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.repository_owner }}
|
||||
- name: Convert repo to lower case for docker
|
||||
id: string_repo
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.repository }}
|
||||
- name: Set up QEMU
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/setup-qemu-action@v2
|
||||
- name: Set up Docker Buildx
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/setup-buildx-action@v2
|
||||
- name: Login to Docker Hub
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ steps.string_user.outputs.lowercase }}
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
- name: Get tag name
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: tags
|
||||
shell: bash
|
||||
run: |
|
||||
tags=( )
|
||||
gittag="$(git tag --points-at HEAD)"
|
||||
branch="$(git rev-parse --abbrev-ref HEAD)"
|
||||
|
||||
if [[ -n "${gittag}" ]]; then
|
||||
tags=( "${tags[@]}" "${REPO_NAME}:${gittag}" )
|
||||
fi
|
||||
if [[ -n "${branch}" ]]; then
|
||||
branch="$(echo "${branch}" | sed -E 's|[/]|-|g')"
|
||||
tags=( "${tags[@]}" "${REPO_NAME}:${branch}" )
|
||||
if [ "${branch}" == "master" ]; then
|
||||
tags=( "${tags[@]}" "${tags},${REPO_NAME}:latest" )
|
||||
fi
|
||||
fi
|
||||
function join_by {
|
||||
local d=${1-} f=${2-}
|
||||
if shift 2; then
|
||||
printf %s "$f" "${@/#/$d}"
|
||||
fi
|
||||
}
|
||||
tagstr="$(join_by "," "${tags[@]}")"
|
||||
echo "TAGS=${tagstr}"
|
||||
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
|
||||
env:
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
- name: Install latest rust
|
||||
run: |
|
||||
rustup toolchain install stable
|
||||
- name: Install toml-cli
|
||||
run: |
|
||||
cargo install toml-cli
|
||||
- name: Get project version
|
||||
id: toml
|
||||
run: |
|
||||
NEOLINK_VERSION="$(toml get Cargo.toml package.version | sed 's|"||g')"
|
||||
echo "version=${NEOLINK_VERSION}" >> $GITHUB_OUTPUT
|
||||
- name: Prepare directory
|
||||
run: |
|
||||
mkdir linux
|
||||
mkdir linux/arm
|
||||
mkdir linux/arm64
|
||||
- name: Download Linux x86_64
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-amd64-bullseye
|
||||
path: linux/amd64
|
||||
- name: Download Linux armv7
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-armhf-bullseye
|
||||
path: linux/arm/v7
|
||||
- name: Download Linux arm64
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-arm64-bullseye
|
||||
path: linux/arm64
|
||||
- name: Download Linux i386
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-i386-bullseye
|
||||
path: linux/386
|
||||
- name: Push to Docker Hub
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/386
|
||||
context: .
|
||||
push: true
|
||||
file: Dockerfile
|
||||
tags: ${{ steps.tags.outputs.TAGS }}
|
||||
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ github.repository_owner }}
|
||||
env:
|
||||
DOCKER_BUILDKIT: 1
|
||||
|
||||
create_release:
|
||||
name: Create Release
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/') && github.event_name == 'push' # Ensure this only runs on a tag or expect issues
|
||||
needs:
|
||||
- "cross"
|
||||
- "native"
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v3
|
||||
- name: Install latest rust
|
||||
run: |
|
||||
rustup toolchain install stable
|
||||
- name: Install toml-cli
|
||||
run: |
|
||||
cargo install toml-cli
|
||||
- name: Get project version
|
||||
id: toml
|
||||
run: |
|
||||
NEOLINK_VERSION="$(toml get Cargo.toml package.version | sed 's|"||g')"
|
||||
echo "version=${NEOLINK_VERSION}" >> $GITHUB_OUTPUT
|
||||
- name: Download Windows
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-windows-2022
|
||||
path: neolink_windows
|
||||
- name: Download Macos
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-macos-12
|
||||
path: neolink_macos
|
||||
- name: Download Linux x86_64
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-ubuntu-22.04
|
||||
path: neolink_linux_x86_64_ubuntu
|
||||
- name: Download Linux x86_64
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-amd64-bullseye
|
||||
path: neolink_linux_x86_64_bullseye
|
||||
- name: Download Linux armhf
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-armhf-bullseye
|
||||
path: neolink_linux_armhf
|
||||
- name: Download Linux arm64
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-arm64-bullseye
|
||||
path: neolink_linux_arm64
|
||||
- name: Download Linux i386
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: release-i386-bullseye
|
||||
path: neolink_linux_i386
|
||||
- name: Prepare Releases
|
||||
run: |
|
||||
dirs=(
|
||||
neolink_windows
|
||||
neolink_macos
|
||||
neolink_linux_x86_64_ubuntu
|
||||
neolink_linux_x86_64_bullseye
|
||||
neolink_linux_armhf
|
||||
neolink_linux_arm64
|
||||
neolink_linux_i386
|
||||
)
|
||||
for d in "${dirs[@]}"; do
|
||||
chmod +x "${d}/neolink"*
|
||||
zip -r "${d}.zip" "${d}"
|
||||
done
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
name: Neolink ${{steps.toml.outputs.version}}
|
||||
files: |
|
||||
neolink_windows.zip
|
||||
neolink_macos.zip
|
||||
neolink_linux_x86_64_ubuntu.zip
|
||||
neolink_linux_x86_64_bullseye.zip
|
||||
neolink_linux_armhf.zip
|
||||
neolink_linux_arm64.zip
|
||||
neolink_linux_i386.zip
|
||||
body: |
|
||||
Neolink Release ${{steps.toml.outputs.version}}
|
||||
draft: true
|
||||
prerelease: ${{ contains(github.ref_name, 'rc') }}
|
||||
@@ -0,0 +1,147 @@
|
||||
name: DockerHub
|
||||
|
||||
on: [push, pull_request, workflow_dispatch]
|
||||
|
||||
jobs:
|
||||
pre_job:
|
||||
# continue-on-error: true # Uncomment once integration is finished
|
||||
runs-on: ubuntu-latest
|
||||
# Map a step output to a job output
|
||||
outputs:
|
||||
should_skip: ${{ steps.skip_check.outputs.should_skip }}
|
||||
steps:
|
||||
- id: skip_check
|
||||
uses: fkirc/skip-duplicate-actions@v5
|
||||
with:
|
||||
# All of these options are optional, so you can remove them if you are happy with the defaults
|
||||
concurrent_skipping: 'same_content_newer'
|
||||
skip_after_successful_duplicate: 'false'
|
||||
|
||||
native:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: native
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check token is set
|
||||
id: vars
|
||||
shell: bash
|
||||
run: |
|
||||
unset HAS_SECRET
|
||||
if [ -n $SECRET ]; then HAS_SECRET='true' ; fi
|
||||
echo "HAS_SECRET_TOKEN=${HAS_SECRET}" >> $GITHUB_OUTPUT
|
||||
env:
|
||||
SECRET: "${{ secrets.DOCKER_PRUNE_TOKEN }}"
|
||||
- name: Convert username to lower case for docker
|
||||
id: string_user
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.repository_owner }}
|
||||
- name: Convert repo to lower case for docker
|
||||
id: string_repo
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: ASzc/change-string-case-action@v5
|
||||
with:
|
||||
string: ${{ github.event.repository.name }}
|
||||
- name: Run Clean Script
|
||||
shell: bash
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
run: |
|
||||
#!/bin/bash
|
||||
|
||||
#Script will delete all images in all repositories of your docker hub account which are older than x days
|
||||
|
||||
set -e
|
||||
|
||||
|
||||
# set username and password
|
||||
UNAME="${OWNER}"
|
||||
TOKEN="${TOKEN}"
|
||||
DAYS="${DAYS}"
|
||||
REPO_NAME="${REPO_NAME}"
|
||||
|
||||
# get list of namespaces accessible by user (not in use right now)
|
||||
#NAMESPACES=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/namespaces/ | jq -r '.namespaces|.[]')
|
||||
|
||||
#echo $TOKEN
|
||||
echo
|
||||
# get list of repos for that user account
|
||||
echo "List of Repositories in ${UNAME} Docker Hub account"
|
||||
REPO_LIST="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
echo "$REPO_LIST"
|
||||
echo
|
||||
# build a list of all images & tags
|
||||
for i in ${REPO_LIST}
|
||||
do
|
||||
# get tags for repo
|
||||
IMAGE_TAGS="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
|
||||
# build a list of images from tags
|
||||
for j in ${IMAGE_TAGS}
|
||||
do
|
||||
# add each tag to list
|
||||
FULL_IMAGE_LIST="${FULL_IMAGE_LIST} ${UNAME}/${i}:${j}"
|
||||
|
||||
done
|
||||
done
|
||||
|
||||
# output list of all docker images
|
||||
echo
|
||||
echo "List of all docker images in ${UNAME} Docker Hub account"
|
||||
for i in ${FULL_IMAGE_LIST}
|
||||
do
|
||||
echo "${i}"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "Identifying and deleting images which are older than ${DAYS} days in ${UNAME} docker hub account"
|
||||
# Note!!! Please un-comment below line if you wanna perform operation on all repositories of your Docker Hub account
|
||||
#for i in ${REPO_LIST}
|
||||
|
||||
repos=(
|
||||
"${REPO_NAME}"
|
||||
)
|
||||
|
||||
for i in "${repos[@]}"; do
|
||||
# get tags for repo
|
||||
echo
|
||||
echo "Looping Through $i repository in ${UNAME} account"
|
||||
IMAGE_TAGS="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/?page_size=10000" | jq -r '.results|.[]|.name')"
|
||||
|
||||
# build a list of images from tags
|
||||
for j in ${IMAGE_TAGS}
|
||||
do
|
||||
if [[ "${j}" =~ ^[0-9][.][0-9][.][0-9]$ ]]; then
|
||||
echo "Version tag (${j}) will not be deleted"
|
||||
continue
|
||||
fi
|
||||
echo
|
||||
# add last_updated_time
|
||||
updated_time="$(curl -s -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/${j}/?page_size=10000" | jq -r '.last_updated')"
|
||||
echo "$updated_time"
|
||||
datetime=$updated_time
|
||||
timeago="${DAYS} days ago"
|
||||
|
||||
dtSec=$(date --date "$datetime" +'%s')
|
||||
taSec=$(date --date "$timeago" +'%s')
|
||||
|
||||
echo "INFO: dtSec=$dtSec, taSec=$taSec"
|
||||
|
||||
if [ "$dtSec" -lt "$taSec" ]
|
||||
then
|
||||
echo "This image ${UNAME}/${i}:${j} is older than ${DAYS} days, deleting this image"
|
||||
## Please uncomment below line to delete docker hub images of docker hub repositories
|
||||
curl -s -X DELETE -H "Authorization: JWT ${TOKEN}" "https://hub.docker.com/v2/repositories/${UNAME}/${i}/tags/${j}/"
|
||||
else
|
||||
echo "This image ${UNAME}/${i}:${j} is within ${DAYS} days time range, keep this image"
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo "Script execution ends"
|
||||
env:
|
||||
DAYS: "100"
|
||||
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
|
||||
OWNER: ${{ steps.string_user.outputs.lowercase }}
|
||||
TOKEN: ${{ secrets.DOCKER_PRUNE__TOKEN }}
|
||||
@@ -0,0 +1,65 @@
|
||||
name: Style
|
||||
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
pre_job:
|
||||
# continue-on-error: true # Uncomment once integration is finished
|
||||
runs-on: ubuntu-latest
|
||||
# Map a step output to a job output
|
||||
outputs:
|
||||
should_skip: ${{ steps.skip_check.outputs.should_skip }}
|
||||
steps:
|
||||
- id: skip_check
|
||||
uses: fkirc/skip-duplicate-actions@v5
|
||||
with:
|
||||
# All of these options are optional, so you can remove them if you are happy with the defaults
|
||||
concurrent_skipping: 'same_content_newer'
|
||||
skip_after_successful_duplicate: 'false'
|
||||
|
||||
check_clippy:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: Clippy
|
||||
runs-on: ubuntu-22.04
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: apt install gstreamer and deps
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y aptitude
|
||||
sudo aptitude install -y libgstrtspserver-1.0-dev libgstreamer1.0-dev libgtk2.0-dev protobuf-compiler
|
||||
- name: Install nightly rust
|
||||
run: |
|
||||
rustup toolchain install nightly --component clippy
|
||||
rustup override set nightly
|
||||
- name: Run clippy manually
|
||||
run: cargo +nightly clippy --workspace --all-targets --all-features
|
||||
|
||||
check_fmt:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: Rust-fmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Install nightly rust
|
||||
run: |
|
||||
rustup toolchain install nightly --component rustfmt
|
||||
rustup override set nightly
|
||||
- name: rustfmt
|
||||
run: |
|
||||
cargo +nightly fmt --all -- --check
|
||||
|
||||
check_lua:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: Luacheck
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Run luacheck
|
||||
uses: nebularg/actions-luacheck@v1
|
||||
with:
|
||||
files: 'dissector/baichuan.lua'
|
||||
args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable
|
||||
@@ -14,3 +14,12 @@
|
||||
|
||||
# Committing IntelliJ project files is a violation of intergalactic law
|
||||
.idea/
|
||||
|
||||
# MacOS
|
||||
.DS_Store
|
||||
._.DS_Store
|
||||
**/.DS_Store
|
||||
**/._.DS_Store
|
||||
|
||||
# The token file for the FCM tests
|
||||
token.toml
|
||||
@@ -0,0 +1,2 @@
|
||||
MD013:
|
||||
code_blocks: false
|
||||
@@ -0,0 +1,20 @@
|
||||
repos:
|
||||
- repo: https://github.com/doublify/pre-commit-rust
|
||||
rev: eeee35a
|
||||
hooks:
|
||||
- id: fmt
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.4.0 # Use the ref you want to point at
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: check-case-conflict
|
||||
- id: check-merge-conflict
|
||||
- id: check-toml
|
||||
- id: mixed-line-ending
|
||||
- repo: https://github.com/igorshubovych/markdownlint-cli
|
||||
rev: v0.33.0
|
||||
hooks:
|
||||
- id: markdownlint-fix
|
||||
files: README.md
|
||||
args: [--disable, MD041, --]
|
||||
|
||||
Generated
+2785
-420
File diff suppressed because it is too large.
Load diff
+33
-23
@@ -1,30 +1,40 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.2.0"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>"]
|
||||
version = "0.5.11"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/*",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
cookie-factory = "0.3"
|
||||
crossbeam = "0.7"
|
||||
env_logger = "*"
|
||||
err-derive = "0.2"
|
||||
glib = "*"
|
||||
gstreamer = "0.15"
|
||||
gstreamer-app = "0.15"
|
||||
gstreamer-rtsp = "0.15"
|
||||
gstreamer-rtsp-server = "0.15"
|
||||
log = { version = "0.4" }
|
||||
indoc = "0.3"
|
||||
md5 = "0.7"
|
||||
nom = "5.1"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
socket2 = "0.3"
|
||||
structopt = "0.3"
|
||||
toml = "0.5"
|
||||
yaserde = "0.3.16"
|
||||
yaserde_derive = "0.3.16"
|
||||
xml-rs = "0.8"
|
||||
anyhow = "1.0.70"
|
||||
byte-slice-cast = "1.2.2"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
console-subscriber = "0.1.8"
|
||||
crossbeam-channel = "0.5.8"
|
||||
env_logger = "0.10.0"
|
||||
futures = "0.3.28"
|
||||
gstreamer = "0.20.3"
|
||||
gstreamer-app = "0.20.0"
|
||||
gstreamer-rtsp = "0.20.0"
|
||||
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
|
||||
is_sorted = "0.1.1"
|
||||
itertools = "0.10.5"
|
||||
lazy_static = "1.4.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
neolink_core = { path = "crates/core", version = "0.5.11" }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.20.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
time = "0.3.20"
|
||||
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
|
||||
tokio-stream = "0.1.12"
|
||||
toml = "0.7.3"
|
||||
validator = "0.16.0"
|
||||
validator_derive = "0.16.0"
|
||||
yaserde = "0.8.0"
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
# Neolink Docker image build scripts
|
||||
# Copyright (c) 2020 George Hilliard,
|
||||
# Andrew King,
|
||||
# Miroslav Šedivý
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
FROM docker.io/rust:slim-bullseye AS build
|
||||
ARG TARGETPLATFORM
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
|
||||
WORKDIR /usr/local/src/neolink
|
||||
COPY . /usr/local/src/neolink
|
||||
|
||||
# Build the main program or copy from artifact
|
||||
# hadolint ignore=DL3008
|
||||
RUN echo "TARGETPLATFORM: ${TARGETPLATFORM}"; \
|
||||
if [ -f "${TARGETPLATFORM}/neolink" ]; then \
|
||||
echo "Restoring from artifact"; \
|
||||
mkdir -p /usr/local/src/neolink/target/release/; \
|
||||
cp "${TARGETPLATFORM}/neolink" "/usr/local/src/neolink/target/release/neolink"; \
|
||||
else \
|
||||
echo "Building from scratch"; \
|
||||
apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
libgstrtspserver-1.0-dev \
|
||||
libgstreamer1.0-dev \
|
||||
libgtk2.0-dev \
|
||||
libglib2.0-dev && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/* ; \
|
||||
cargo build --release; \
|
||||
fi
|
||||
|
||||
# Create the release container. Match the base OS used to build
|
||||
FROM debian:bullseye-slim
|
||||
ARG TARGETPLATFORM
|
||||
ARG REPO
|
||||
ARG VERSION
|
||||
ARG OWNER
|
||||
|
||||
LABEL description="An image for the neolink program which is a reolink camera to rtsp translator"
|
||||
LABEL repository="$REPO"
|
||||
LABEL version="$VERSION"
|
||||
LABEL maintainer="$OWNER"
|
||||
|
||||
# hadolint ignore=DL3008
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
libgstrtspserver-1.0-0 \
|
||||
libgstreamer1.0-0 \
|
||||
gstreamer1.0-tools \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad && \
|
||||
apt-get clean -y && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=build \
|
||||
/usr/local/src/neolink/target/release/neolink \
|
||||
/usr/local/bin/neolink
|
||||
COPY docker/entrypoint.sh /entrypoint.sh
|
||||
|
||||
RUN gst-inspect-1.0; \
|
||||
chmod +x "/usr/local/bin/neolink" && \
|
||||
"/usr/local/bin/neolink" --version
|
||||
|
||||
CMD ["/usr/local/bin/neolink", "rtsp", "--config", "/etc/neolink.toml"]
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
EXPOSE 8554
|
||||
@@ -1,122 +1,271 @@
|
||||
# Neolink
|
||||
|
||||

|
||||

|
||||
|
||||
Neolink is a small program that acts as a proxy between Reolink IP cameras and normal RTSP clients.
|
||||
Certain cameras, such as the Reolink B800, do not implement ONVIF or RTSP, but instead use a proprietary "Baichuan" protocol only compatible with their apps and NVRs (any camera that uses "port 9000" will likely be using this protocol).
|
||||
|
||||
Neolink allows you to use NVR software such as Shinobi or Blue Iris to receive video from these cameras instead.
|
||||
Neolink is a small program that acts as a proxy between Reolink IP cameras and
|
||||
normal RTSP clients.
|
||||
Certain cameras, such as the Reolink B800, do not implement ONVIF or RTSP, but
|
||||
instead use a proprietary "Baichuan" protocol only compatible with their apps
|
||||
and NVRs (any camera that uses "port 9000" will likely be using this protocol).
|
||||
Neolink allows you to use NVR software such as Shinobi or Blue Iris to receive
|
||||
video from these cameras instead.
|
||||
The Reolink NVR is not required, and the cameras are unmodified.
|
||||
Your NVR software connects to Neolink, which forwards the video stream from the camera.
|
||||
Your NVR software connects to Neolink, which forwards the video stream from the
|
||||
camera.
|
||||
|
||||
The Neolink project is not affiliated with Reolink in any way; everything it does has been reverse engineered.
|
||||
The Neolink project is not affiliated with Reolink in any way; everything it
|
||||
does has been reverse engineered.
|
||||
|
||||
## Supported cameras
|
||||
## This Fork
|
||||
|
||||
Neolink intends to support all Reolink cameras that do not provide native RTSP.
|
||||
Currently it has been tested on the following cameras:
|
||||
This fork is an extension of
|
||||
[thirtythreeforty's](https://github.com/thirtythreeforty/neolink) with additional
|
||||
features not yet in upstream master.
|
||||
|
||||
- B800/D800
|
||||
**Major Features**:
|
||||
|
||||
It *should* support the following cameras, but this has not yet been tested.
|
||||
Please test and report if you have them:
|
||||
- MQTT
|
||||
- Motion Detection
|
||||
- Paused Streams (when no rtsp client or no motion detected)
|
||||
- Save a still image to disk
|
||||
|
||||
- B400/D400
|
||||
- E1
|
||||
- Lumus
|
||||
**Minor Features**:
|
||||
|
||||
Neolink does not support other cameras such as the RLC-420, since they already [provide native RTSP](https://support.reolink.com/hc/en-us/articles/360007010473-How-to-Live-View-Reolink-Cameras-via-VLC-Media-Player).
|
||||
- Improved error messages when your missing gstreamer plugins
|
||||
- Protocol more closely follows offical reolink format
|
||||
- Possibly can handle more simulatenous connections
|
||||
- More ways to connect to the camera. Including Relaying through reolink
|
||||
servers
|
||||
- Camera battery levels can be displayed in the log
|
||||
|
||||
## Installation
|
||||
|
||||
In the future Neolink will be much easier to install.
|
||||
For now, follow these steps.
|
||||
Download from the
|
||||
[release page](https://github.com/QuantumEntangledAndy/neolink/releases)
|
||||
|
||||
1. [Install Gstreamer][gstreamer] from the most recent MSI installer on Windows, or your package manager on Linux.
|
||||
2. If you are using Windows, add the following to your `PATH` environment variable:
|
||||
Extract the zip
|
||||
|
||||
```
|
||||
%GSTREAMER_1_0_ROOT_X86_64%\bin
|
||||
Install the latest [gstreamer](https://gstreamer.freedesktop.org/download/)
|
||||
(1.20.5 as of writing this).
|
||||
|
||||
- **Windows**: ensure you install `full` when prompted in the MSI options.
|
||||
- **Mac**: Install the dpkg version on the offical gstreamer website over
|
||||
the brew version
|
||||
- **Ubuntu/Debian**: These packages should work
|
||||
|
||||
```bash
|
||||
sudo apt install \
|
||||
libgstrtspserver-1.0-0 \
|
||||
libgstreamer1.0-0 \
|
||||
libgstreamer-plugins-bad1.0-0 \
|
||||
gstreamer1.0-x \
|
||||
gstreamer1.0-plugins-base \
|
||||
gstreamer1.0-plugins-good \
|
||||
gstreamer1.0-plugins-bad
|
||||
```
|
||||
|
||||
Note that if you use Chocolatey to install Gstreamer, it does this automatically.
|
||||
Make a config file see below.
|
||||
|
||||
3. Download and extract a [prebuilt binary from continuous integration][ci-download] (click on the topmost commit for the most recent build).
|
||||
4. Write a configuration file for your cameras. See the section below.
|
||||
5. Launch Neolink from a shell, passing your configuration file:
|
||||
## Config/Usage
|
||||
|
||||
```
|
||||
neolink --config my_config.toml
|
||||
### RTSP
|
||||
|
||||
To use `neolink` you need a config file.
|
||||
|
||||
There's a more complete example
|
||||
[here](https://github.com/QuantumEntangledAndy/neolink/blob/master/sample_config.toml),
|
||||
but the following should work as a minimal example.
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
|
||||
[[cameras]]
|
||||
name = "Camera02"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "BCDEF0123456789A"
|
||||
address = "192.168.1.10"
|
||||
```
|
||||
|
||||
6. Connect your NVR software to Neolink's RTSP server.
|
||||
The default URL is `rtsp://127.0.0.1:8554/your_camera_name` if you're running it on the same computer.
|
||||
If you run it on a different server, you may need to open firewall ports.
|
||||
Create a text file with called `neolink.toml` in the same folder as the
|
||||
neolink binary. With your config options.
|
||||
|
||||
[gstreamer]: https://gstreamer.freedesktop.org/documentation/installing/index.html
|
||||
[ci-download]: https://github.com/thirtythreeforty/neolink/actions?query=branch%3Amaster
|
||||
When ready start `neolink` with the following command
|
||||
using the terminal in the same folder the neolink binary is in.
|
||||
|
||||
## Configuration
|
||||
|
||||
Copy and modify the `sample_config.toml` to specify the address, username, and password for each camera (if there is no password, you can omit that line).
|
||||
Each `[[cameras]]` block creates a new camera; the `name` determines the RTSP path you should connect your client to.
|
||||
Currently Neolink cannot auto-detect cameras like the official clients do; you must specify their IP addresses directly.
|
||||
|
||||
By default Neolink serves on all IP addresses on port 8554.
|
||||
You can modify this by changing the `bind` parameter.
|
||||
|
||||
You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`:
|
||||
|
||||
```
|
||||
set RUST_LOG=debug
|
||||
```bash
|
||||
./neolink rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
On Linux:
|
||||
### Discovery
|
||||
|
||||
```
|
||||
export RUST_LOG=debug
|
||||
To connect to a camera using a UID we need to find the IP address of the camera
|
||||
with that UID
|
||||
|
||||
The IP is discovered with four methods
|
||||
|
||||
1. Local discovery: Here we send a broadcast on all visible networks asking
|
||||
the local network if there is a camera with this UID. This only works if
|
||||
the network supports broadcasts
|
||||
|
||||
If you know the ip address you can put it into the `address` field of the
|
||||
config and attempt a direct connection without broadcasts. This requires a
|
||||
route from neolink to the camera.
|
||||
|
||||
2. Remote discovery: Here a ask the reolink servers what the IP address is.
|
||||
This requires that we contact reolink and provide some basic information
|
||||
like the UID. Once we have this information we connect directly to the
|
||||
local IP address. This requires a route from neolink to the camera and
|
||||
for the camera to be able to contact the reolink IPs.
|
||||
|
||||
3. Map discovery: In this case we register our IP address with reolink and ask
|
||||
the camera to connect to us. Once the camera either polls/recives a connect
|
||||
request from the reolink servers the camera will then initiate a connect
|
||||
to neolink. This requires that our IP and the reolink IPs are reacable from
|
||||
the camera.
|
||||
|
||||
4. Relay: In this case we request that reolink relay our connection. Neolink
|
||||
nor the camera need to be able to direcly contact each other. But both
|
||||
neolink and the camera need to be able to contact reolink.
|
||||
|
||||
This can be controlled with the config
|
||||
|
||||
```toml
|
||||
discovery = "local"
|
||||
```
|
||||
|
||||
## Stability
|
||||
In the `[[cameras]]` section of the toml.
|
||||
|
||||
Neolink has had minimal testing, but it seems to be very reliable in multiple users' testing.
|
||||
Possible values are `local`, `remote`, `map`, `relay` later values implictly
|
||||
enable prior methods.
|
||||
|
||||
The formats of all configuration files and APIs is subject to change as required while it is pre-1.0.
|
||||
### MQTT
|
||||
|
||||
Note that some RTSP clients, especially VLC, have trouble handling the stream.
|
||||
Currently this seems to be related to receive buffer sizes but the exact cause remains unclear.
|
||||
Blue Iris is known to work well.
|
||||
To use mqtt you will to adjust your config file as such:
|
||||
|
||||
## Development
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
Neolink is written in Rust, and binds to Gstreamer to provide RTSP server functionality.
|
||||
To compile, ensure you have the Rust compiler, Gstreamer, and gst-rtsp-server installed.
|
||||
Then simply run:
|
||||
|
||||
```
|
||||
cargo build
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
[cameras.mqtt]
|
||||
server = "127.0.0.1" # Address of the mqtt server
|
||||
port = 1883 # mqtt servers port
|
||||
credentials = ["username", "password"] # mqtt server login details
|
||||
```
|
||||
|
||||
from this top directory.
|
||||
Then to start the mqtt connection run the following:
|
||||
|
||||
### Baichuan Protocol
|
||||
```bash
|
||||
./neolink mqtt --config=neolink.toml
|
||||
```
|
||||
|
||||
The "port 9000" protocol used by Reolink and some Swann cameras is internally referred to as the Baichuan protocol; this is the company based in China that is known internationally as Reolink.
|
||||
Neolink will publish these messages:
|
||||
|
||||
This protocol is a slightly convoluted header-data format, and appears to have been upgraded several times.
|
||||
The modern variant uses obfuscated XML commands and sends ordinary H.265 or H.264 video streams encapsulated in a custom header.
|
||||
More details about the on-the-wire protocol will come later.
|
||||
Messages are prefixed with `neolink/{CAMERANAME}`
|
||||
|
||||
### Baichuan dissector
|
||||
Control messages:
|
||||
|
||||
A Wireshark dissector is available for the BC wire protocol in the `dissector` directory.
|
||||
It dissects the BC header and also allows viewing the deobfuscated XML in command messages.
|
||||
To use it, copy or symlink it into your Wireshark plugin directory; typically this is `~/.local/lib/wireshark/plugins/` under Linux.
|
||||
- `/control/led [on|off]` Turns status LED on/off
|
||||
- `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light
|
||||
detection
|
||||
- `/control/reboot` Reboot the camera
|
||||
- `/control/ptz [up|down|left|right|in|out]` (amount) Control the PTZ
|
||||
movements, amount defaults to 32.0
|
||||
- `/control/pir [on|off]`
|
||||
|
||||
Currently the dissector does not attempt to decode the Baichuan "extension" messages except `binaryData`.
|
||||
This will change in the future as reverse engineering needs require.
|
||||
Status Messages:
|
||||
|
||||
- `/status offline` Sent when the neolink goes offline this is a LastWill
|
||||
message
|
||||
- `/status disconnected` Sent when the camera goes offline
|
||||
- `/status/battery` Sent in reply to a `/query/battery` an XML encoded version
|
||||
of the battery status
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
|
||||
Query Messages:
|
||||
|
||||
- `/query/battery` Request that the camera reports its battery level
|
||||
- `/query/pir` Request that the camera reports its pir status
|
||||
|
||||
### Pause
|
||||
|
||||
To use the pause feature you will need to adjust your config file as such:
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
[cameras.pause]
|
||||
on_motion = true # Should pause when no motion
|
||||
on_client = true # Should pause when no rtsp client
|
||||
timeout = 2.1 # How long to wait after motion stops before pausing
|
||||
```
|
||||
|
||||
Then start the rtsp server as usual:
|
||||
|
||||
```bash
|
||||
./neolink rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
### Battery Levels
|
||||
|
||||
If you have a battery camera and would like to see the battery messages in th
|
||||
log add the following to your config
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
# Usual camera options like uid etc
|
||||
print_format = "Human"
|
||||
```
|
||||
|
||||
You can also print into xml format with `print_format = "Xml"` which can then b
|
||||
passed by a script for processing.
|
||||
|
||||
### Docker
|
||||
|
||||
[Docker](https://hub.docker.com/r/quantumentangledandy/neolink) builds are also
|
||||
provided in multiple architectures. The latest tag tracks master while each
|
||||
|
||||
branch gets it's own tag.
|
||||
|
||||
```bash
|
||||
docker pull quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
### Image
|
||||
|
||||
You can write an image from the stream to disk using:
|
||||
|
||||
```bash
|
||||
neolink image --config=config.toml --file-path=filepath CameraName
|
||||
```
|
||||
|
||||
Where filepath is the path to save the image to and CameraName is the name o
|
||||
the camera from the config to save the image from.
|
||||
|
||||
File is always jpeg and the extension given in filepath will be added or changed
|
||||
|
||||
to reflect this.
|
||||
|
||||
## License
|
||||
|
||||
Neolink is free software, released under the GNU Affero General Public License v3.
|
||||
This means that if you incorporate it into a piece of software available over the network, you must offer that software's source code to your users.
|
||||
Neolink is free software, released under the GNU Affero General Public License
|
||||
v3.
|
||||
|
||||
This means that if you incorporate it into a piece of software available over
|
||||
the network, you must offer that software's source code to your users.
|
||||
@@ -18,14 +18,14 @@ fn build_ver() {
|
||||
}
|
||||
|
||||
fn git_ver() -> Option<String> {
|
||||
let mut git_cmd = Command::new("git");
|
||||
git_cmd.args(&["describe", "--tags"]);
|
||||
github_ver().or_else(git_cmd_ver)
|
||||
}
|
||||
|
||||
if let Some(true) = git_cmd
|
||||
.status()
|
||||
.ok()
|
||||
.map(|exit| exit.success())
|
||||
{
|
||||
fn git_cmd_ver() -> Option<String> {
|
||||
let mut git_cmd = Command::new("git");
|
||||
git_cmd.args(["describe", "--tags"]);
|
||||
|
||||
if let Some(true) = git_cmd.status().ok().map(|exit| exit.success()) {
|
||||
println!("cargo:rerun-if-changed=.git/HEAD");
|
||||
git_cmd
|
||||
.output()
|
||||
@@ -36,14 +36,37 @@ fn git_ver() -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn github_ver() -> Option<String> {
|
||||
if let Ok(sha1) = env::var("GITHUB_SHA") {
|
||||
println!("cargo:rerun-if-env-changed=GITHUB_SHA");
|
||||
Some(sha1)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn platform_cfg() {
|
||||
let gstreamer_dir = env::var_os("GSTREAMER_1_0_ROOT_X86_64")
|
||||
.and_then(|x| x.into_string().ok())
|
||||
.unwrap_or_else(|| r#"C:\gstreamer\1.0\x86_64\"#.to_string());
|
||||
.unwrap_or_else(|| {
|
||||
env::var_os("GSTREAMER_1_0_ROOT_MSVC_X86_64")
|
||||
.and_then(|x| x.into_string().ok())
|
||||
.unwrap_or_else(|| r#"C:\gstreamer\1.0\x86_64\"#.to_string())
|
||||
});
|
||||
|
||||
println!(r"cargo:rustc-link-search=native={}\lib", gstreamer_dir);
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
#[cfg(target_os = "macos")]
|
||||
fn platform_cfg() {
|
||||
let gstreamer_dir = env::var_os("GSTREAMER_1_0_ROOT_MACOSX")
|
||||
.and_then(|x| x.into_string().ok())
|
||||
.unwrap_or_else(|| r#"/Library/Frameworks/GStreamer.framework/Versions/1.0"#.to_string());
|
||||
|
||||
println!(r"cargo:rustc-link-search=native={}/lib", gstreamer_dir);
|
||||
println!(r"cargo:rustc-link-arg=-Wl,-rpath,{}/lib", gstreamer_dir);
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
|
||||
fn platform_cfg() {}
|
||||
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.5.11"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0-or-later"
|
||||
|
||||
[dependencies]
|
||||
aes = "0.8.2"
|
||||
bytes = "1.4.0"
|
||||
cfb-mode = "0.8.2"
|
||||
cookie-factory = "0.3.2"
|
||||
crc32fast = "1.3.2"
|
||||
crossbeam-channel = "0.5.8"
|
||||
delegate = "0.9.0"
|
||||
err-derive = "0.3.1"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
lazy_static = "1.4.0"
|
||||
local-ip-address = "0.5.1"
|
||||
log = "0.4.17"
|
||||
md5 = "0.7.0"
|
||||
nom = { version = "7.1.3", features = ["alloc"] }
|
||||
rand = "0.8.5"
|
||||
regex = "1.7.3"
|
||||
serde = { version = "1.0.106", features = ["derive"] }
|
||||
time = { version = "0.3.20" , features = [ "macros", "parsing", "local-offset" ]}
|
||||
tokio = { version = "1.27.0", features = ["full"] }
|
||||
tokio-stream = { version = "0.1.12", features = ["sync", "time", "net"] }
|
||||
tokio-util = { version = "0.7.7", features = ["full", "tracing"] }
|
||||
yaserde = "0.8.0"
|
||||
yaserde_derive = "0.8.0"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.5.0"
|
||||
env_logger = "*"
|
||||
indoc = "2.0.1"
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Create a tokio encoder/decoder for turning a AsyncRead/Write stream into
|
||||
//! a Bc packet
|
||||
//!
|
||||
//! BcCodex is used with a `[tokio_util::codec::Framed]` to form complete packets
|
||||
//!
|
||||
use crate::bc::model::*;
|
||||
use crate::bc::xml::*;
|
||||
use crate::{Credentials, Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use nom::AsBytes;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
pub(crate) struct BcCodex {
|
||||
context: BcContext,
|
||||
}
|
||||
|
||||
impl BcCodex {
|
||||
pub(crate) fn new(credentials: Credentials) -> Self {
|
||||
Self {
|
||||
context: BcContext::new(credentials),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoder<Bc> for BcCodex {
|
||||
type Error = Error;
|
||||
|
||||
fn encode(&mut self, item: Bc, dst: &mut BytesMut) -> Result<()> {
|
||||
// let context = self.context.read().unwrap();
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let enc_protocol: EncryptionProtocol = match self.context.get_encrypted() {
|
||||
EncryptionProtocol::Aes(_) if item.meta.msg_id == 1 => {
|
||||
// During login the encyption protocol cannot go higher than BCEncrypt
|
||||
// even if we support AES. (BUt it can go lower i.e. None)
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
n => *n,
|
||||
};
|
||||
let buf = item.serialize(buf, &enc_protocol)?;
|
||||
dst.reserve(buf.len());
|
||||
dst.extend_from_slice(buf.as_slice());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for BcCodex {
|
||||
type Item = Bc;
|
||||
type Error = Error;
|
||||
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
None => {
|
||||
if buf.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
log::debug!(
|
||||
"bytes remaining on BC stream: {:X?}",
|
||||
buf.as_bytes().chunks(25).next()
|
||||
);
|
||||
// Right after this we seem to get an issue with the camera dropping us
|
||||
// Needs probing
|
||||
// F0, DE, BC, A, 3, 0, 0, 0, 88, 6, 0, 0, 0, 1, 4, 0, C8, 0, 0, 0, 0, 0, 0, 0, 30, 31, 64, 63, 48,
|
||||
// 32, 36, 34, 6A, 6, 0, 0, 0, 0, 0, 0, D8, F5, C7, 86, 56, 0, 0, 0, 0, 0, 0, 1, 21, 9A, FC, 22, 7F, 6, AE, F6, 15, FF, E5, 71, 4, 2F, 24, 61, 15, 96, F0, BF, 83, DE, 10, BE, B4, 2E, 3
|
||||
// 9, 76, 56, 92, 7E, 48, 79, 20, 9A, DC, 1B, BB, AC, 22, 60, 5C, 72, B5, 3D, 8, E0, 34, 43, 3F, 2E, A7, 81, A8, 11, 75, 7F, 58, 3E, 8, 54, 91, 43, 21, EC, 6B, D6, 1A, D5, CB, D5, 6C,
|
||||
// 8C, 2E, 6E, A3, 51, C3, A4, F0, CF, 2B, 61, 81, D0, 1C, A1, 76, EE, BF, 7A, D5, D8, D1, C4, D, B0, 45, EE, 3E, 93, 9A, CE, 5F, AB, 75, 55, AC, 9D, 66, DE, 23, 6D, 5F, 25, 57, DA, F5
|
||||
//, E, 7F, 8D, 30, A7, 66, C4, 60, 76, 41, D0, 6A, 23, E, A9, C5, 51, EE, F6, DD, 19, E7, A8, 96, 9F, 2B, AF, 31, 90, 9D, FC, BE
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
// match self.decode(buf)? {
|
||||
// Some(frame) => Ok(Some(frame)),
|
||||
// None => Ok(None),
|
||||
// }
|
||||
}
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
// trace!("Decoding: {:X?}", src);
|
||||
let bc = Bc::deserialize(&self.context, src);
|
||||
// trace!("As: {:?}", bc);
|
||||
let bc = match bc {
|
||||
Ok(bc) => bc,
|
||||
Err(Error::NomIncomplete(_)) => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
// Update context
|
||||
if let Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
encryption: Some(Encryption { nonce, .. }),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = &bc
|
||||
{
|
||||
if response_code >> 8 == 0xdd {
|
||||
// Login reply has the encryption info
|
||||
// Set that the encryption type now
|
||||
let encryption_protocol_byte = (response_code & 0xff) as usize;
|
||||
match encryption_protocol_byte {
|
||||
0x00 => self.context.set_encrypted(EncryptionProtocol::Unencrypted),
|
||||
0x01 => self.context.set_encrypted(EncryptionProtocol::BCEncrypt),
|
||||
0x02 => self.context.set_encrypted(EncryptionProtocol::Aes(
|
||||
self.context.credentials.make_aeskey(nonce),
|
||||
)),
|
||||
_ => {
|
||||
return Err(Error::UnknownEncryption(encryption_protocol_byte));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(on_off),
|
||||
..
|
||||
}),
|
||||
..
|
||||
}) = bc.body
|
||||
{
|
||||
if on_off == 0 {
|
||||
self.context.binary_off(bc.meta.msg_num);
|
||||
} else {
|
||||
self.context.binary_on(bc.meta.msg_num);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(bc))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
use super::model::*;
|
||||
use super::xml::{BcPayloads, BcXml};
|
||||
use super::xml_crypto;
|
||||
use crate::Error;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use log::*;
|
||||
use nom::{
|
||||
bytes::streaming::take, combinator::*, error::context as error_context, number::streaming::*,
|
||||
sequence::*, Parser,
|
||||
};
|
||||
|
||||
type IResult<I, O, E = nom::error::VerboseError<I>> = Result<(I, O), nom::Err<E>>;
|
||||
|
||||
impl Bc {
|
||||
/// Returns Ok(deserialized data, the amount of data consumed)
|
||||
/// Can then use this as the amount that should be remove from a buffer
|
||||
pub(crate) fn deserialize(context: &BcContext, buf: &mut BytesMut) -> Result<Bc, Error> {
|
||||
const TYPICAL_HEADER: usize = 24;
|
||||
let parser = BcParser { context };
|
||||
let (result, amount) = match consumed(parser)(buf) {
|
||||
Ok((_, (parsed_buff, result))) => Ok((result, parsed_buff.len())),
|
||||
Err(e) => Err(Error::from(e)),
|
||||
}?;
|
||||
|
||||
buf.advance(amount);
|
||||
buf.reserve(amount + TYPICAL_HEADER); // Preallocate for future buffer calls
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
struct BcParser<'a> {
|
||||
context: &'a BcContext,
|
||||
}
|
||||
|
||||
impl<'a> Parser<&'a [u8], Bc, nom::error::VerboseError<&'a [u8]>> for BcParser<'a> {
|
||||
fn parse(&mut self, buf: &'a [u8]) -> IResult<&'a [u8], Bc> {
|
||||
bc_msg(self.context, buf)
|
||||
}
|
||||
}
|
||||
|
||||
fn bc_msg<'a>(context: &BcContext, buf: &'a [u8]) -> IResult<&'a [u8], Bc> {
|
||||
let (buf, header) = bc_header(buf)?;
|
||||
let (buf, body) = bc_body(context, &header, buf)?;
|
||||
|
||||
let bc = Bc {
|
||||
meta: header.to_meta(),
|
||||
body,
|
||||
};
|
||||
|
||||
Ok((buf, bc))
|
||||
}
|
||||
|
||||
fn bc_body<'a>(context: &BcContext, header: &BcHeader, buf: &'a [u8]) -> IResult<&'a [u8], BcBody> {
|
||||
if header.is_modern() {
|
||||
let (buf, body) = bc_modern_msg(context, header, buf)?;
|
||||
Ok((buf, BcBody::ModernMsg(body)))
|
||||
} else {
|
||||
let (buf, body) = match header.msg_id {
|
||||
MSG_ID_LOGIN => bc_legacy_login_msg(buf)?,
|
||||
_ => (buf, LegacyMsg::UnknownMsg),
|
||||
};
|
||||
Ok((buf, BcBody::LegacyMsg(body)))
|
||||
}
|
||||
}
|
||||
|
||||
fn hex32<'a>() -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], String> {
|
||||
map_res(take(32usize), |slice: &'a [u8]| {
|
||||
String::from_utf8(slice.to_vec())
|
||||
})
|
||||
}
|
||||
|
||||
fn bc_legacy_login_msg(buf: &'_ [u8]) -> IResult<&'_ [u8], LegacyMsg> {
|
||||
let (buf, username) = hex32()(buf)?;
|
||||
let (buf, password) = hex32()(buf)?;
|
||||
|
||||
Ok((buf, LegacyMsg::LoginMsg { username, password }))
|
||||
}
|
||||
|
||||
fn bc_modern_msg<'a>(
|
||||
context: &BcContext,
|
||||
header: &BcHeader,
|
||||
buf: &'a [u8],
|
||||
) -> IResult<&'a [u8], ModernMsg> {
|
||||
use nom::{
|
||||
error::{ContextError, ErrorKind, ParseError},
|
||||
Err,
|
||||
};
|
||||
|
||||
fn make_error<I, E: ParseError<I>>(input: I, ctx: &'static str, kind: ErrorKind) -> E
|
||||
where
|
||||
I: std::marker::Copy,
|
||||
E: ContextError<I>,
|
||||
{
|
||||
E::add_context(input, ctx, E::from_error_kind(input, kind))
|
||||
}
|
||||
|
||||
let ext_len = match header.payload_offset {
|
||||
Some(off) => off,
|
||||
_ => 0, // If missing payload_offset treat all as payload
|
||||
};
|
||||
|
||||
let (buf, ext_buf) = take(ext_len)(buf)?;
|
||||
let payload_len = header.body_len - ext_len;
|
||||
let (buf, payload_buf) = take(payload_len)(buf)?;
|
||||
|
||||
let decrypted;
|
||||
let processed_ext_buf = match context.get_encrypted() {
|
||||
EncryptionProtocol::Unencrypted => ext_buf,
|
||||
encryption_protocol => {
|
||||
decrypted = xml_crypto::decrypt(header.channel_id as u32, ext_buf, encryption_protocol);
|
||||
&decrypted
|
||||
}
|
||||
};
|
||||
|
||||
let mut in_binary = false;
|
||||
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||
let extension = if ext_len > 0 {
|
||||
// Apply the XML parse function, but throw away the reference to decrypted in the Ok and
|
||||
// Err case. This error-error-error thing is the same idiom Nom uses internally.
|
||||
let parsed = Extension::try_parse(processed_ext_buf).map_err(|_| {
|
||||
Err::Error(make_error(
|
||||
buf,
|
||||
"Unable to parse Extension XML",
|
||||
ErrorKind::MapRes,
|
||||
))
|
||||
})?;
|
||||
if let Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
} = parsed
|
||||
{
|
||||
// In binary so tell the current context that we need to treat the payload as binary
|
||||
in_binary = true;
|
||||
}
|
||||
Some(parsed)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Now to handle the payload block
|
||||
// This block can either be xml or binary depending on what the message expects.
|
||||
// For our purposes we use try_parse and if all xml based parsers fail we treat
|
||||
// As binary
|
||||
let payload;
|
||||
if payload_len > 0 {
|
||||
// Extract remainder of message as binary, if it exists
|
||||
let encryption_protocol = match header {
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x00 => EncryptionProtocol::Unencrypted,
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x01 => EncryptionProtocol::BCEncrypt,
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code & 0xff) == 0x02 => EncryptionProtocol::BCEncrypt, // This is AES but the first packet with the NONCE is BCEcrypt, since the NONCE in this packet is required to build the AES key
|
||||
BcHeader { msg_id: 1, .. }
|
||||
if matches!(context.get_encrypted(), EncryptionProtocol::Aes(_)) =>
|
||||
{
|
||||
// Maximum encryption level is BCEncrypt during login... Not sure why Reolink did it like that
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
_ => *context.get_encrypted(),
|
||||
};
|
||||
|
||||
let processed_payload_buf =
|
||||
xml_crypto::decrypt(header.channel_id as u32, payload_buf, &encryption_protocol);
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||
payload = Some(BcPayloads::Binary(payload_buf.to_vec()));
|
||||
} else {
|
||||
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|_| {
|
||||
error!("header.msg_id: {}", header.msg_id);
|
||||
error!(
|
||||
"processed_payload_buf: {:X?}::{:?}",
|
||||
processed_payload_buf,
|
||||
std::str::from_utf8(&processed_payload_buf)
|
||||
);
|
||||
Err::Error(make_error(
|
||||
buf,
|
||||
"Unable to parse Payload XML",
|
||||
ErrorKind::MapRes,
|
||||
))
|
||||
})?;
|
||||
payload = Some(BcPayloads::BcXml(xml));
|
||||
}
|
||||
} else {
|
||||
payload = None;
|
||||
}
|
||||
|
||||
Ok((buf, ModernMsg { extension, payload }))
|
||||
}
|
||||
|
||||
fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> {
|
||||
let (buf, _magic) =
|
||||
error_context("Magic invalid", verify(le_u32, |x| *x == MAGIC_HEADER))(buf)?;
|
||||
let (buf, msg_id) = error_context("MsgID missing", le_u32)(buf)?;
|
||||
let (buf, body_len) = error_context("BodyLen missing", le_u32)(buf)?;
|
||||
let (buf, channel_id) = error_context("ChannelID missing", le_u8)(buf)?;
|
||||
let (buf, stream_type) = error_context("StreamType missing", le_u8)(buf)?;
|
||||
let (buf, msg_num) = error_context("MsgNum missing", le_u16)(buf)?;
|
||||
let (buf, (response_code, class)) =
|
||||
error_context("ResponseCode missing", tuple((le_u16, le_u16)))(buf)?;
|
||||
|
||||
let (buf, payload_offset) = error_context(
|
||||
"Payload Offset is missing",
|
||||
cond(has_payload_offset(class), le_u32),
|
||||
)(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcHeader {
|
||||
body_len,
|
||||
msg_id,
|
||||
channel_id,
|
||||
stream_type,
|
||||
msg_num,
|
||||
response_code,
|
||||
class,
|
||||
payload_offset,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::bc::xml::*;
|
||||
use assert_matches::assert_matches;
|
||||
|
||||
#[test]
|
||||
fn test_bc_modern_login() {
|
||||
let sample = include_bytes!("samples/model_sample_modern_login.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
let (_, body) = bc_body(&context, &header, buf).unwrap();
|
||||
assert_eq!(header.msg_id, 1);
|
||||
assert_eq!(header.body_len, 145);
|
||||
assert_eq!(header.channel_id, 0);
|
||||
assert_eq!(header.stream_type, 0);
|
||||
assert_eq!(header.payload_offset, None);
|
||||
assert_eq!(header.response_code, 0xdd01);
|
||||
assert_eq!(header.class, 0x6614);
|
||||
match body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
encryption: Some(encryption),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"),
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This is an 0xdd03 encryption from an Argus 2
|
||||
//
|
||||
// It is currently unsupported
|
||||
fn test_03_enc_login() {
|
||||
let sample = include_bytes!("samples/battery_enc.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
assert!(bc_body(&context, &header, buf).is_err());
|
||||
// It should error because we don't support it
|
||||
//
|
||||
// The following would be its contents if we
|
||||
// did support it (maybe one day :) left it here
|
||||
// for then)
|
||||
//
|
||||
//
|
||||
// let (_, body) = bc_body(&mut context, &header, buf).unwrap();
|
||||
// assert_eq!(header.msg_id, 1);
|
||||
// assert_eq!(header.body_len, 175);
|
||||
// assert_eq!(header.channel_id, 0);
|
||||
// assert_eq!(header.stream_type, 0);
|
||||
// assert_eq!(header.payload_offset, None);
|
||||
// assert_eq!(header.response_code, 0xdd03);
|
||||
// assert_eq!(header.class, 0x6614);
|
||||
// match body {
|
||||
// BcBody::ModernMsg(ModernMsg {
|
||||
// payload:
|
||||
// Some(BcPayloads::BcXml(BcXml {
|
||||
// encryption: Some(encryption),
|
||||
// ..
|
||||
// })),
|
||||
// ..
|
||||
// }) => assert_eq!(encryption.nonce, "0-AhnEZyUg6eKrJFIWgXPF"),
|
||||
// _ => panic!(),
|
||||
// }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_legacy_login() {
|
||||
let sample = include_bytes!("samples/model_sample_legacy_login.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
let (_, body) = bc_body(&context, &header, buf).unwrap();
|
||||
assert_eq!(header.msg_id, 1);
|
||||
assert_eq!(header.body_len, 1836);
|
||||
assert_eq!(header.channel_id, 0);
|
||||
assert_eq!(header.stream_type, 0);
|
||||
assert_eq!(header.payload_offset, None);
|
||||
assert_eq!(header.response_code, 0xdc01);
|
||||
assert_eq!(header.class, 0x6514);
|
||||
match body {
|
||||
BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => {
|
||||
assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0");
|
||||
assert_eq!(password, EMPTY_LEGACY_PASSWORD);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_modern_login_failed() {
|
||||
let sample = include_bytes!("samples/modern_login_failed.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
let (_, body) = bc_body(&context, &header, buf).unwrap();
|
||||
assert_eq!(header.msg_id, 1);
|
||||
assert_eq!(header.body_len, 0);
|
||||
assert_eq!(header.channel_id, 0);
|
||||
assert_eq!(header.stream_type, 0);
|
||||
assert_eq!(header.payload_offset, Some(0x0));
|
||||
assert_eq!(header.response_code, 0x190); // 400
|
||||
assert_eq!(header.class, 0x0000);
|
||||
match body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}) => {}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_modern_login_success() {
|
||||
let sample = include_bytes!("samples/modern_login_success.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let (buf, header) = bc_header(&sample[..]).unwrap();
|
||||
let (_, body) = bc_body(&context, &header, buf).unwrap();
|
||||
assert_eq!(header.msg_id, 1);
|
||||
assert_eq!(header.body_len, 2949);
|
||||
assert_eq!(header.channel_id, 0);
|
||||
assert_eq!(header.stream_type, 0);
|
||||
assert_eq!(header.payload_offset, Some(0x0));
|
||||
assert_eq!(header.response_code, 0xc8); // 200
|
||||
assert_eq!(header.class, 0x0000);
|
||||
|
||||
// Previously, we were not handling payload_offset == 0 (no bin offset) correctly.
|
||||
// Test that we decoded XML and no binary.
|
||||
match body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: Some(_),
|
||||
}) => {}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_binary_mode() {
|
||||
let sample1 = include_bytes!("samples/modern_video_start1.bin");
|
||||
let sample2 = include_bytes!("samples/modern_video_start2.bin");
|
||||
|
||||
let mut context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let msg1 = Bc::deserialize(&context, &mut BytesMut::from(&sample1[..])).unwrap();
|
||||
match msg1.body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(bin)),
|
||||
}) => {
|
||||
assert_eq!(bin.len(), 32);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
|
||||
context.in_bin_mode.insert(msg1.meta.msg_num);
|
||||
let msg2 = Bc::deserialize(&context, &mut BytesMut::from(&sample2[..])).unwrap();
|
||||
match msg2.body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: Some(BcPayloads::Binary(bin)),
|
||||
}) => {
|
||||
assert_eq!(bin.len(), 30344);
|
||||
}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// B800 seems to have a different header to the E1 and swann cameras
|
||||
// the stream_type and message_num do not seem to set in the offical clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_externstream() {
|
||||
let sample = include_bytes!("samples/xml_externstream_b800.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let e = Bc::deserialize(&context, &mut BytesMut::from(&sample[..]));
|
||||
assert_matches!(
|
||||
e,
|
||||
Ok(Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: 3,
|
||||
channel_id: 0x8c,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
msg_num: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
preview:
|
||||
Some(Preview {
|
||||
version,
|
||||
channel_id: 0,
|
||||
handle: 1024,
|
||||
stream_type,
|
||||
}),
|
||||
..
|
||||
})),
|
||||
}),
|
||||
}) if version == "1.1" && stream_type == Some("externStream".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
// B800 seems to have a different header to the E1 and swann cameras
|
||||
// the stream_type and message_num do not seem to set in the offical clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_substream() {
|
||||
let sample = include_bytes!("samples/xml_substream_b800.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let e = Bc::deserialize(&context, &mut BytesMut::from(&sample[..]));
|
||||
assert_matches!(
|
||||
e,
|
||||
Ok(Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: 3,
|
||||
channel_id: 143,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
msg_num: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
preview:
|
||||
Some(Preview {
|
||||
version,
|
||||
channel_id: 0,
|
||||
handle: 256,
|
||||
stream_type,
|
||||
}),
|
||||
..
|
||||
})),
|
||||
}),
|
||||
}) if version == "1.1" && stream_type == Some("subStream".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
// B800 seems to have a different header to the E1 and swann cameras
|
||||
// the stream_type and message_num do not seem to set in the offical clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_mainstream() {
|
||||
let sample = include_bytes!("samples/xml_mainstream_b800.bin");
|
||||
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
let e = Bc::deserialize(&context, &mut BytesMut::from(&sample[..]));
|
||||
assert_matches!(
|
||||
e,
|
||||
Ok(Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: 3,
|
||||
channel_id: 138,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
msg_num: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
preview:
|
||||
Some(Preview {
|
||||
version,
|
||||
channel_id: 0,
|
||||
handle: 0,
|
||||
stream_type,
|
||||
}),
|
||||
..
|
||||
})),
|
||||
}),
|
||||
}) if version == "1.1" && stream_type == Some("mainStream".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! The Baichuan message format is a 20 byte header, the contents of which vary between legacy and
|
||||
//! modern messages:
|
||||
//!
|
||||
//!
|
||||
//!
|
||||
//! This header is followed by the message body. In legacy messages, the bodies are
|
||||
//! message-specific binary formats. Currently, we only attempt to interpret the legacy login
|
||||
//! message, as it is all that is needed to upgrade to the modern XML-based messages. Modern
|
||||
//! messages are either "encrypted" XML (the encryption is a simple XOR routine or AES)
|
||||
//! or binary data.
|
||||
//!
|
||||
//! ---
|
||||
//!
|
||||
//! # Payloads
|
||||
//! Messages contain one-two payloads seperated by the payload_offset in the header
|
||||
//!
|
||||
//! ## Extension Payload
|
||||
//! The first payload prior to the payload_offset is the extension xml
|
||||
//!
|
||||
//! This contains meta data on the following payload such as channel_id or content type
|
||||
//! (xml or binary)
|
||||
//!
|
||||
//! ## Payload
|
||||
//! The second payload which is the primary payload coming after the payload offset
|
||||
//! depends on the MsgID.
|
||||
//!
|
||||
//! It is usually XML except in the case of video and talk MsgIDs
|
||||
//! which are binary data in the bc media packet format
|
||||
//!
|
||||
|
||||
/// Contains the structure of the messages such as headers and payloads
|
||||
pub mod model;
|
||||
|
||||
/// Contains code related to the deserialisation of the bc packets
|
||||
pub mod de;
|
||||
/// `Contains code related to the serialisation of the bc packets
|
||||
pub mod ser;
|
||||
/// Contains the structs for the know xmls of payloads and extension
|
||||
pub mod xml;
|
||||
|
||||
mod xml_crypto;
|
||||
|
||||
pub(crate) mod codex;
|
||||
@@ -0,0 +1,329 @@
|
||||
use crate::Credentials;
|
||||
|
||||
pub use super::xml::{BcPayloads, BcXml, Extension};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const MAGIC_HEADER: u32 = 0xabcdef0;
|
||||
|
||||
/// Login messages have this ID
|
||||
pub const MSG_ID_LOGIN: u32 = 1;
|
||||
/// Logout messages have this ID
|
||||
pub const MSG_ID_LOGOUT: u32 = 2;
|
||||
/// Video and Audio Streams messages have this ID
|
||||
pub const MSG_ID_VIDEO: u32 = 3;
|
||||
/// ID used to stop the video stream
|
||||
pub const MSG_ID_VIDEO_STOP: u32 = 4;
|
||||
/// TalkAbility messages have this ID
|
||||
pub const MSG_ID_TALKABILITY: u32 = 10;
|
||||
/// TalkReset messages have this ID
|
||||
pub const MSG_ID_TALKRESET: u32 = 11;
|
||||
/// PtzControl messages have this ID
|
||||
pub const MSG_ID_PTZ_CONTROL: u32 = 18;
|
||||
/// Reboot messages have this ID
|
||||
pub const MSG_ID_REBOOT: u32 = 23;
|
||||
/// Request motion detection messages
|
||||
pub const MSG_ID_MOTION_REQUEST: u32 = 31;
|
||||
/// Motion detection messages
|
||||
pub const MSG_ID_MOTION: u32 = 33;
|
||||
/// Version messages have this ID
|
||||
pub const MSG_ID_VERSION: u32 = 80;
|
||||
/// Ping messages have this ID
|
||||
pub const MSG_ID_PING: u32 = 93;
|
||||
/// General system info messages have this ID
|
||||
pub const MSG_ID_GET_GENERAL: u32 = 104;
|
||||
/// Used to get the abilities of a user
|
||||
pub const MSG_ID_ABILITY_INFO: u32 = 151;
|
||||
/// Setting general system info (clock mostly) messages have this ID
|
||||
pub const MSG_ID_SET_GENERAL: u32 = 105;
|
||||
/// Used to pass the token and client ID for push notifications
|
||||
pub const MSG_ID_PUSH_INFO: u32 = 124;
|
||||
/// Will send the talk config for talk back data to follow this msg
|
||||
pub const MSG_ID_TALKCONFIG: u32 = 201;
|
||||
/// Used to send talk back binary data
|
||||
pub const MSG_ID_TALK: u32 = 202;
|
||||
/// Getting the LED status is done with this ID
|
||||
pub const MSG_ID_GET_LED_STATUS: u32 = 208;
|
||||
/// Setting the LED status is done with this ID
|
||||
pub const MSG_ID_SET_LED_STATUS: u32 = 209;
|
||||
/// Getting PIR status messages have this ID
|
||||
pub const MSG_ID_GET_PIR_ALARM: u32 = 212;
|
||||
/// Setting PIR status messages have this ID
|
||||
pub const MSG_ID_START_PIR_ALARM: u32 = 213;
|
||||
/// UDP Keep alive
|
||||
pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
|
||||
/// Battery message initiaed by the camera
|
||||
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
|
||||
/// Battery message initiaed by the client
|
||||
pub const MSG_ID_BATTERY_INFO: u32 = 253;
|
||||
|
||||
/// An empty password in legacy format
|
||||
pub const EMPTY_LEGACY_PASSWORD: &str =
|
||||
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
|
||||
|
||||
/// Top level bc message
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct Bc {
|
||||
/// header part of the message
|
||||
pub meta: BcMeta,
|
||||
/// body part of the message which can either be Legacy or Modern
|
||||
pub body: BcBody,
|
||||
}
|
||||
|
||||
///
|
||||
/// The body of a bc message is either legacy or modern
|
||||
///
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum BcBody {
|
||||
/// Legacy is unsupported except for login where it is used
|
||||
/// to negotiate the initial login and upgrade to modern
|
||||
LegacyMsg(LegacyMsg),
|
||||
/// Modern is the current reolink protocol it is mostly
|
||||
/// xml based
|
||||
ModernMsg(ModernMsg),
|
||||
}
|
||||
|
||||
/// Modern messages have two payloads split by the `payload_offset` in the header
|
||||
///
|
||||
/// The first payload is extension which describes the second payload. If the
|
||||
/// `payload_offset` is `0` then their is no `extension` (usually because it has
|
||||
/// already been negotiated in a previous message) and it is `None`
|
||||
///
|
||||
/// The second payload contains the actual data of interest and is all bytes after
|
||||
/// the `payload_offset` up to the `body_len`. If `payload_offset`
|
||||
/// equals `body_len` then there is not payload and it is `None`
|
||||
///
|
||||
/// If `payload_offset` is `0` and equal to `body_len` then there is neither
|
||||
/// `extension` or `payload` these are header only messages. This usually occurs to acknoledge receipt
|
||||
/// of a command. In such cases the header `response_code` should be checked.
|
||||
///
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct ModernMsg {
|
||||
/// Extension describes the following payload such as which channel id it is for
|
||||
pub extension: Option<Extension>,
|
||||
/// Primary payload which is dependant on MsgID
|
||||
pub payload: Option<BcPayloads>,
|
||||
}
|
||||
|
||||
/// Legacy login formats. Only login is supported
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum LegacyMsg {
|
||||
/// Legacy login data is constructed from username and password
|
||||
/// that will (usually but not always, depending on camera) be hashed
|
||||
LoginMsg {
|
||||
/// Username for a legacy login
|
||||
username: String,
|
||||
/// Password for a legacy login
|
||||
password: String,
|
||||
},
|
||||
/// Any other type of legacy message will be collected here
|
||||
UnknownMsg,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct BcHeader {
|
||||
pub body_len: u32,
|
||||
pub msg_id: u32,
|
||||
pub channel_id: u8,
|
||||
pub stream_type: u8,
|
||||
pub msg_num: u16,
|
||||
pub response_code: u16,
|
||||
pub class: u16,
|
||||
pub payload_offset: Option<u32>,
|
||||
}
|
||||
|
||||
/// The components of the Baichuan TLV header that are not
|
||||
/// descriptions of the Body (the application dictates these)
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct BcMeta {
|
||||
/// Message ID dictaes the major content of the message
|
||||
pub msg_id: u32,
|
||||
/// In most cases 0 but can be other values for NVRs
|
||||
pub channel_id: u8,
|
||||
/// In most cases this is unimportant but 0 means Clear Stream while 1 means Fluent stream
|
||||
/// This is only really used during `[MSG_ID_VIDEO]` streams when the SD `subStreams` are requested
|
||||
pub stream_type: u8,
|
||||
/// On modern messages this is the response code
|
||||
/// When sending a command it is set to `0`. The reply from the camera can be
|
||||
/// - `200` for OK
|
||||
/// - `400` for bad request
|
||||
/// A malformed packet will return a `400` code
|
||||
pub response_code: u16,
|
||||
/// A message ID is used to match replies with requests. The camera will parrot back
|
||||
/// this number in its reply
|
||||
///
|
||||
/// If there a message is too long to fit in one packet it will be split over multiple
|
||||
/// messages all with the same `msg_num` (this can happing in video streams, talk and when
|
||||
/// sending a firmware update)
|
||||
pub msg_num: u16,
|
||||
/// The class is mostly an unknown quanitiy but does dictate the size of the header
|
||||
/// know values are
|
||||
///
|
||||
/// - 0x6514: "legacy" 20 bytes
|
||||
/// - 0x6614: "modern" 20 bytes
|
||||
/// - 0x6414: "modern" 24 bytes
|
||||
/// - 0x0000: "modern" 24 bytes
|
||||
pub class: u16,
|
||||
}
|
||||
|
||||
/// The components of the Baichuan header that must be filled out after the body is serialized, or
|
||||
/// is needed for the deserialization of the body (strictly part of the wire format of the message)
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct BcSendInfo {
|
||||
pub body_len: u32,
|
||||
pub payload_offset: Option<u32>,
|
||||
}
|
||||
|
||||
/// These are the encyption modes supported by the camera
|
||||
///
|
||||
/// The mode is negotiated during login
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum EncryptionProtocol {
|
||||
/// Older camera use no encryption
|
||||
Unencrypted,
|
||||
/// Camera/Firmwares before 2021 use BCEncrypt which is a simple XOr
|
||||
BCEncrypt,
|
||||
/// Latest cameras/firmwares use Aes with the key derived from
|
||||
/// the camera's password and the negotiated NONCE
|
||||
Aes([u8; 16]),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct BcContext {
|
||||
pub(crate) credentials: Credentials,
|
||||
pub(crate) in_bin_mode: HashSet<u16>,
|
||||
pub(crate) encryption_protocol: EncryptionProtocol,
|
||||
}
|
||||
|
||||
impl Bc {
|
||||
/// Constructs a xml payload only Bc message
|
||||
pub fn new_from_xml(meta: BcMeta, xml: BcXml) -> Bc {
|
||||
Self::new(meta, None, Some(BcPayloads::BcXml(xml)))
|
||||
}
|
||||
|
||||
/// Constructs an Extension only Bc message
|
||||
pub fn new_from_ext(meta: BcMeta, ext: Extension) -> Bc {
|
||||
Self::new(meta, Some(ext), None)
|
||||
}
|
||||
|
||||
/// Constucts a header only Bc message
|
||||
pub fn new_from_meta(meta: BcMeta) -> Bc {
|
||||
Self::new(meta, None, None)
|
||||
}
|
||||
|
||||
/// Constructs a message with both extension and xml payload
|
||||
pub fn new_from_ext_xml(meta: BcMeta, ext: Extension, xml: BcXml) -> Bc {
|
||||
Self::new(meta, Some(ext), Some(BcPayloads::BcXml(xml)))
|
||||
}
|
||||
|
||||
/// General method to constructs a Bc message
|
||||
///
|
||||
/// Use this if your constructing a binary payload but otherwise the other constructors
|
||||
/// are better suited to the task
|
||||
pub fn new(meta: BcMeta, extension: Option<Extension>, payload: Option<BcPayloads>) -> Bc {
|
||||
Bc {
|
||||
meta,
|
||||
body: BcBody::ModernMsg(ModernMsg { extension, payload }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BcContext {
|
||||
pub(crate) fn new(credentials: Credentials) -> BcContext {
|
||||
BcContext {
|
||||
credentials,
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol: EncryptionProtocol::Unencrypted,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(unused)] // Used in tests
|
||||
pub(crate) fn new_with_encryption(encryption_protocol: EncryptionProtocol) -> BcContext {
|
||||
BcContext {
|
||||
credentials: Default::default(),
|
||||
in_bin_mode: HashSet::new(),
|
||||
encryption_protocol,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_encrypted(&mut self, encryption_protocol: EncryptionProtocol) {
|
||||
self.encryption_protocol = encryption_protocol;
|
||||
}
|
||||
|
||||
pub(crate) fn get_encrypted(&self) -> &EncryptionProtocol {
|
||||
&self.encryption_protocol
|
||||
}
|
||||
|
||||
pub(crate) fn binary_on(&mut self, msg_id: u16) {
|
||||
self.in_bin_mode.insert(msg_id);
|
||||
}
|
||||
|
||||
#[allow(unused)] // Used in tests
|
||||
pub(crate) fn binary_off(&mut self, msg_id: u16) {
|
||||
self.in_bin_mode.remove(&msg_id);
|
||||
}
|
||||
}
|
||||
|
||||
impl BcHeader {
|
||||
/// Check if this header corresponds to a known modern message class
|
||||
pub fn is_modern(&self) -> bool {
|
||||
// Most modern messages have an extra word at the end of the header; this
|
||||
// serves as the start offset of the appended payload data, if any.
|
||||
// A notable exception is the encrypted reply to the login message;
|
||||
// in this case the message is modern (with XML encryption etc), but there is
|
||||
// no extra word.
|
||||
// Here are the message classes:
|
||||
// 0x6514: legacy, no bin offset (initial login message, encrypted or not)
|
||||
// 0x6614: modern, no bin offset (reply to encrypted 0x6514 login)
|
||||
// 0x6414: modern, has bin offset, encrypted if supported (re-sent login message)
|
||||
// 0x0000, modern, has bin offset (most modern messages)
|
||||
self.class != 0x6514
|
||||
}
|
||||
|
||||
/// Converts a header into a `BcMeta` this mostly works by striping aspects that are
|
||||
/// not desciptions of the data such as `msg_len`
|
||||
pub fn to_meta(&self) -> BcMeta {
|
||||
BcMeta {
|
||||
msg_id: self.msg_id,
|
||||
msg_num: self.msg_num,
|
||||
channel_id: self.channel_id,
|
||||
response_code: self.response_code,
|
||||
stream_type: self.stream_type,
|
||||
class: self.class,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constuct a [`BcHeader`] from a [`BcMeta`]
|
||||
///
|
||||
/// This requires additional data such as the `body_len`
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `meta` - the [`BcMeta`] to convert
|
||||
///
|
||||
/// * `body_len` - The length of the body (extension and payload) in bytes
|
||||
///
|
||||
/// * `payload_offset` - The location in bytes where the payload starts and extension ends
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns the new `BcHeader`
|
||||
///
|
||||
pub fn from_meta(meta: &BcMeta, body_len: u32, payload_offset: Option<u32>) -> BcHeader {
|
||||
BcHeader {
|
||||
payload_offset,
|
||||
body_len,
|
||||
msg_id: meta.msg_id,
|
||||
channel_id: meta.channel_id,
|
||||
stream_type: meta.stream_type,
|
||||
response_code: meta.response_code,
|
||||
msg_num: meta.msg_num,
|
||||
class: meta.class,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_payload_offset(class: u16) -> bool {
|
||||
// See BcHeader::is_modern() for a description of which packets have the bin offset
|
||||
class == 0x6414 || class == 0x0000
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,90 +1,119 @@
|
||||
use super::model::*;
|
||||
use super::xml::BcXml;
|
||||
use super::xml::BcPayloads;
|
||||
use super::xml_crypto;
|
||||
use cookie_factory::bytes::*;
|
||||
use cookie_factory::sequence::tuple;
|
||||
use cookie_factory::{combinator::*, gen};
|
||||
use cookie_factory::{GenError, SerializeFn, WriteContext};
|
||||
use log::error;
|
||||
use std::io::Write;
|
||||
|
||||
pub type Error = GenError;
|
||||
|
||||
impl Bc {
|
||||
pub fn serialize<W: Write>(&self, buf: W) -> Result<W, GenError> {
|
||||
pub(crate) fn serialize<W: Write>(
|
||||
&self,
|
||||
buf: W,
|
||||
encryption_protocol: &EncryptionProtocol,
|
||||
) -> Result<W, GenError> {
|
||||
// Ideally this would be a combinator, but that would be hairy because we have to
|
||||
// serialize the XML to have the metadata to build the header
|
||||
let body_buf;
|
||||
let bin_offset;
|
||||
let payload_offset;
|
||||
|
||||
match &self.body {
|
||||
BcBody::ModernMsg(ref modern) => {
|
||||
let (buf, xml_len) = gen(
|
||||
opt_ref(&modern.xml, |xml| bc_xml(self.meta.client_idx, xml)),
|
||||
// First serialize ext
|
||||
let (temp_buf, ext_len) = gen(
|
||||
opt_ref(&modern.extension, |ext| {
|
||||
bc_ext(self.meta.channel_id as u32, ext, encryption_protocol)
|
||||
}),
|
||||
vec![],
|
||||
)?;
|
||||
body_buf = buf;
|
||||
bin_offset = if has_bin_offset(self.meta.class) {
|
||||
|
||||
// Now get the offset of the payload
|
||||
payload_offset = if has_payload_offset(self.meta.class) {
|
||||
// If we're required to put binary length, put 0 if we have no binary
|
||||
Some(if modern.binary.is_some() {
|
||||
xml_len as u32
|
||||
Some(if modern.extension.is_some() {
|
||||
ext_len as u32
|
||||
} else {
|
||||
0
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Now get the payload part of the body and add to ext_buf
|
||||
let (temp_buf, _) = gen(
|
||||
opt_ref(&modern.payload, |payload_offset| {
|
||||
bc_payload(
|
||||
self.meta.channel_id as u32,
|
||||
payload_offset,
|
||||
encryption_protocol,
|
||||
)
|
||||
}),
|
||||
temp_buf,
|
||||
)?;
|
||||
body_buf = temp_buf;
|
||||
}
|
||||
|
||||
BcBody::LegacyMsg(ref legacy) => {
|
||||
let (buf, _) = gen(bc_legacy(legacy), vec![])?;
|
||||
let (buf, _) = gen(bc_legacy(legacy), vec![]).map_err(|e| {
|
||||
error!("Send error: {}", e);
|
||||
e
|
||||
})?;
|
||||
body_buf = buf;
|
||||
bin_offset = None;
|
||||
payload_offset = None;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Now have enough info to create the header
|
||||
let header = BcHeader::from_meta(&self.meta, body_buf.len() as u32, bin_offset);
|
||||
let header = BcHeader::from_meta(&self.meta, body_buf.len() as u32, payload_offset);
|
||||
|
||||
let (mut buf, _n) = gen(tuple((bc_header(&header), slice(body_buf))), buf)?;
|
||||
|
||||
// Put the binary part of the body, TODO this is poorly written
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
binary: Some(ref binary),
|
||||
..
|
||||
}) = self.body
|
||||
{
|
||||
let (buf2, _) = gen(slice(binary), buf)?;
|
||||
buf = buf2
|
||||
}
|
||||
let (buf, _n) = gen(tuple((bc_header(&header), slice(body_buf))), buf)?;
|
||||
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
fn bc_xml<W: Write>(enc_offset: u32, xml: &BcXml) -> impl SerializeFn<W> {
|
||||
fn bc_ext<W: Write>(
|
||||
enc_offset: u32,
|
||||
xml: &Extension,
|
||||
encryption_protocol: &EncryptionProtocol,
|
||||
) -> impl SerializeFn<W> {
|
||||
let xml_bytes = xml.serialize(vec![]).unwrap();
|
||||
let enc_bytes = xml_crypto::crypt(enc_offset, &xml_bytes);
|
||||
let enc_bytes = xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol);
|
||||
slice(enc_bytes)
|
||||
}
|
||||
|
||||
fn bc_header<W: Write>(header: &BcHeader) -> impl SerializeFn<W> {
|
||||
// TODO this is actually a u16 "response code" in modern messages
|
||||
let (signaled_encryption, spare) = if header.class == 0x0000 {
|
||||
(0x00, 0x00)
|
||||
} else {
|
||||
(header.encrypted as u8, 0xdc)
|
||||
fn bc_payload<W: Write>(
|
||||
enc_offset: u32,
|
||||
payload: &BcPayloads,
|
||||
encryption_protocol: &EncryptionProtocol,
|
||||
) -> impl SerializeFn<W> {
|
||||
let payload_bytes = match payload {
|
||||
BcPayloads::BcXml(x) => {
|
||||
let xml_bytes = x.serialize(vec![]).unwrap();
|
||||
xml_crypto::encrypt(enc_offset, &xml_bytes, encryption_protocol)
|
||||
}
|
||||
BcPayloads::Binary(x) => x.to_owned(),
|
||||
};
|
||||
slice(payload_bytes)
|
||||
}
|
||||
|
||||
fn bc_header<W: Write>(header: &BcHeader) -> impl SerializeFn<W> {
|
||||
tuple((
|
||||
le_u32(MAGIC_HEADER),
|
||||
le_u32(header.msg_id),
|
||||
le_u32(header.body_len),
|
||||
le_u32(header.enc_offset),
|
||||
le_u8(signaled_encryption),
|
||||
le_u8(spare), // skipped byte
|
||||
le_u8(header.channel_id),
|
||||
le_u8(header.stream_type),
|
||||
le_u16(header.msg_num),
|
||||
le_u16(header.response_code),
|
||||
le_u16(header.class),
|
||||
opt(header.bin_offset, le_u32),
|
||||
opt(header.payload_offset, le_u32),
|
||||
))
|
||||
}
|
||||
|
||||
fn bc_legacy<'a, W: Write>(legacy: &'a LegacyMsg) -> impl SerializeFn<W> + 'a {
|
||||
fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
|
||||
move |out: WriteContext<W>| {
|
||||
use LegacyMsg::*;
|
||||
match legacy {
|
||||
@@ -132,7 +161,7 @@ where
|
||||
{
|
||||
move |buf: WriteContext<W>| {
|
||||
if let Some(ref val) = opt {
|
||||
ser(&*val)(buf)
|
||||
ser(val)(buf)
|
||||
} else {
|
||||
do_nothing()(buf)
|
||||
}
|
||||
@@ -141,33 +170,37 @@ where
|
||||
|
||||
/// A serializer combinator that does nothing with its input
|
||||
fn do_nothing<W>() -> impl SerializeFn<W> {
|
||||
move |out: WriteContext<W>| Ok(out)
|
||||
Ok
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_legacy_login_roundtrip() {
|
||||
let mut context = BcContext::new();
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
// I don't want to make up a sample message; just load it
|
||||
let sample = include_bytes!("samples/model_sample_legacy_login.bin");
|
||||
let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap();
|
||||
let msg = Bc::deserialize(&context, &mut bytes::BytesMut::from(&sample[..])).unwrap();
|
||||
|
||||
let ser_buf = msg.serialize(vec![]).unwrap();
|
||||
let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap();
|
||||
let ser_buf = msg
|
||||
.serialize(vec![], &EncryptionProtocol::BCEncrypt)
|
||||
.unwrap();
|
||||
let msg2 = Bc::deserialize(&context, &mut bytes::BytesMut::from(ser_buf.as_slice())).unwrap();
|
||||
assert_eq!(msg, msg2);
|
||||
assert_eq!(&sample[..], ser_buf.as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_modern_login_roundtrip() {
|
||||
let mut context = BcContext::new();
|
||||
let context = BcContext::new_with_encryption(EncryptionProtocol::BCEncrypt);
|
||||
|
||||
// I don't want to make up a sample message; just load it
|
||||
let sample = include_bytes!("samples/model_sample_modern_login.bin");
|
||||
|
||||
let msg = Bc::deserialize::<&[u8]>(&mut context, &sample[..]).unwrap();
|
||||
let msg = Bc::deserialize(&context, &mut bytes::BytesMut::from(&sample[..])).unwrap();
|
||||
|
||||
let ser_buf = msg.serialize(vec![]).unwrap();
|
||||
let msg2 = Bc::deserialize::<&[u8]>(&mut context, ser_buf.as_ref()).unwrap();
|
||||
let ser_buf = msg
|
||||
.serialize(vec![], &EncryptionProtocol::BCEncrypt)
|
||||
.unwrap();
|
||||
let msg2 = Bc::deserialize(&context, &mut bytes::BytesMut::from(ser_buf.as_slice())).unwrap();
|
||||
assert_eq!(msg, msg2);
|
||||
}
|
||||
@@ -0,0 +1,802 @@
|
||||
// YaSerde currently macro-expands names like __type__value from type_
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use std::io::{Read, Write};
|
||||
// YaSerde is currently naming the traits and the derive macros identically
|
||||
use yaserde::ser::Config;
|
||||
use yaserde_derive::{YaDeserialize, YaSerialize};
|
||||
|
||||
#[cfg(test)]
|
||||
use indoc::indoc;
|
||||
|
||||
/// There are two types of payloads xml and binary
|
||||
#[derive(PartialEq, Debug, YaDeserialize)]
|
||||
#[yaserde(flatten)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum BcPayloads {
|
||||
/// XML payloads are the more common ones and include payloads for camera controls
|
||||
#[yaserde(rename = "body")]
|
||||
BcXml(BcXml),
|
||||
/// Binary payloads are received from the camera for streams and sent to the camera
|
||||
/// for talk-back and firmware updates
|
||||
#[yaserde(flatten)]
|
||||
Binary(Vec<u8>),
|
||||
}
|
||||
|
||||
// Required for YaDeserialize
|
||||
impl Default for BcPayloads {
|
||||
fn default() -> Self {
|
||||
BcPayloads::Binary(Default::default())
|
||||
}
|
||||
}
|
||||
|
||||
/// The top level BC Xml
|
||||
#[derive(PartialEq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "body")]
|
||||
pub struct BcXml {
|
||||
/// Encryption xml is received during login and contain the NONCE
|
||||
#[yaserde(rename = "Encryption")]
|
||||
pub encryption: Option<Encryption>,
|
||||
/// LoginUser xml is used during modern login
|
||||
#[yaserde(rename = "LoginUser")]
|
||||
pub login_user: Option<LoginUser>,
|
||||
/// LoginNet xml is used during modern login
|
||||
#[yaserde(rename = "LoginNet")]
|
||||
pub login_net: Option<LoginNet>,
|
||||
/// The final part of a login sequence will return DeviceInfo xml
|
||||
#[yaserde(rename = "DeviceInfo")]
|
||||
pub device_info: Option<DeviceInfo>,
|
||||
/// The VersionInfo xml is recieved in reply to a version request
|
||||
#[yaserde(rename = "VersionInfo")]
|
||||
pub version_info: Option<VersionInfo>,
|
||||
/// Preview xml is used as part of the stream request to set the stream quality and channel
|
||||
#[yaserde(rename = "Preview")]
|
||||
pub preview: Option<Preview>,
|
||||
#[yaserde(rename = "SystemGeneral")]
|
||||
/// SystemGeneral xml is sent or recieved as part of the clock get/setting
|
||||
pub system_general: Option<SystemGeneral>,
|
||||
/// Received as part of the Genral system info request
|
||||
#[yaserde(rename = "Norm")]
|
||||
pub norm: Option<Norm>,
|
||||
/// Received as part of the LEDState info request
|
||||
#[yaserde(rename = "LedState")]
|
||||
pub led_state: Option<LedState>,
|
||||
/// Sent as part of the TalkConfig to prepare the camera for audio talk-back
|
||||
#[yaserde(rename = "TalkConfig")]
|
||||
pub talk_config: Option<TalkConfig>,
|
||||
/// rfAlarmCfg xml is sent or recieved as part of the PIR get/setting
|
||||
#[yaserde(rename = "rfAlarmCfg")]
|
||||
pub rf_alarm_cfg: Option<RfAlarmCfg>,
|
||||
/// Revieced as part of the TalkAbility request
|
||||
#[yaserde(rename = "TalkAbility")]
|
||||
pub talk_ability: Option<TalkAbility>,
|
||||
/// Received when motion is detected
|
||||
#[yaserde(rename = "AlarmEventList")]
|
||||
pub alarm_event_list: Option<AlarmEventList>,
|
||||
/// Sent to move the camera
|
||||
#[yaserde(rename = "PtzControl")]
|
||||
pub ptz_control: Option<PtzControl>,
|
||||
/// Recieved on login/low battery events
|
||||
#[yaserde(rename = "BatteryList")]
|
||||
pub battery_list: Option<BatteryList>,
|
||||
/// Recieved on request for battery info
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Option<BatteryInfo>,
|
||||
/// Recieved on request for a users persmissions/capabilitoes
|
||||
#[yaserde(rename = "AbilityInfo")]
|
||||
pub ability_info: Option<AbilityInfo>,
|
||||
/// Recieved on request for a users persmissions/capabilitoes
|
||||
#[yaserde(rename = "PushInfo")]
|
||||
pub push_info: Option<PushInfo>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
pub(crate) fn try_parse(s: impl Read) -> Result<Self, String> {
|
||||
yaserde::de::from_reader(s)
|
||||
}
|
||||
pub(crate) fn serialize<W: Write>(&self, w: W) -> Result<W, String> {
|
||||
yaserde::ser::serialize_with_writer(self, w, &Config::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Extension {
|
||||
pub(crate) fn try_parse(s: impl Read) -> Result<Self, String> {
|
||||
yaserde::de::from_reader(s)
|
||||
}
|
||||
pub(crate) fn serialize<W: Write>(&self, w: W) -> Result<W, String> {
|
||||
yaserde::ser::serialize_with_writer(self, w, &Config::default())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encryption xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Encryption {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
#[yaserde(rename = "type")]
|
||||
/// The hashing algorithm used. Only observed the value of "md5"
|
||||
pub type_: String,
|
||||
/// The nonce used to negotiate the login and to generate the AES key
|
||||
pub nonce: String,
|
||||
}
|
||||
|
||||
/// LoginUser xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct LoginUser {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Username to login as
|
||||
#[yaserde(rename = "userName")]
|
||||
pub user_name: String,
|
||||
/// Password for login in plain text
|
||||
pub password: String,
|
||||
/// Unknown always `1`
|
||||
#[yaserde(rename = "userVer")]
|
||||
pub user_ver: u32,
|
||||
}
|
||||
|
||||
/// LoginNet xml
|
||||
#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct LoginNet {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Type of connection usually LAN (even on wifi)
|
||||
#[yaserde(rename = "type")]
|
||||
pub type_: String,
|
||||
/// The port for the udp will be `0` for tcp
|
||||
#[yaserde(rename = "udpPort")]
|
||||
pub udp_port: u16,
|
||||
}
|
||||
|
||||
impl Default for LoginNet {
|
||||
fn default() -> Self {
|
||||
LoginNet {
|
||||
version: xml_ver(),
|
||||
type_: "LAN".to_string(),
|
||||
udp_port: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DeviceInfo xml
|
||||
///
|
||||
/// There is more to this xml but we don't deserialize it all
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct DeviceInfo {
|
||||
/// The resolution xml block
|
||||
pub resolution: Resolution,
|
||||
}
|
||||
|
||||
/// VersionInfo xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct VersionInfo {
|
||||
/// Name assigned to the camera
|
||||
pub name: String,
|
||||
/// Camera's serial number
|
||||
pub serialNumber: String,
|
||||
/// The camera build day e.g. `"build 19110800"`
|
||||
pub buildDay: String,
|
||||
/// The hardware version e.g. `"IPC_517SD5"`
|
||||
pub hardwareVersion: String,
|
||||
/// The config version e.g. `"v2.0.0.0"`
|
||||
pub cfgVersion: String,
|
||||
/// Firmware version usually a combination of config and build versions e.g.
|
||||
/// `"v2.0.0.587_19110800"`
|
||||
pub firmwareVersion: String,
|
||||
/// Unusure possibly a more detailed hardware version e.g. `"IPC_51716M110000000100000"`
|
||||
pub detail: String,
|
||||
}
|
||||
|
||||
/// Resolution xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Resolution {
|
||||
/// Resolution name is in the format "width*height" i.e. "2304*1296"
|
||||
#[yaserde(rename = "resolutionName")]
|
||||
pub name: String,
|
||||
/// Height of the stream in pixels
|
||||
pub width: u32,
|
||||
/// Width of the stream in pixels
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
/// Preview xml
|
||||
///
|
||||
/// This xml is used to request a stream to start
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Preview {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
|
||||
/// Channel id is usually zero unless using a NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Handle usually 0 for mainStream and 1 for subStream
|
||||
pub handle: u32,
|
||||
/// Either `"mainStream"` or `"subStream"`
|
||||
#[yaserde(rename = "streamType")]
|
||||
pub stream_type: Option<String>,
|
||||
}
|
||||
|
||||
/// Extension xml
|
||||
///
|
||||
/// This is used to describe the subsequent payload passed the `payload_offset`
|
||||
#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Extension {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// If the subsequent payload is binary this will be set to 1. Otherwise it is ommited
|
||||
#[yaserde(rename = "binaryData")]
|
||||
pub binary_data: Option<u32>,
|
||||
/// Certain requests such `AbilitySupport` require to know which user this
|
||||
/// ability support request is for (why camera dosen't know this based on who
|
||||
/// is logged in is unknown... Possible security hole)
|
||||
#[yaserde(rename = "userName")]
|
||||
pub user_name: Option<String>,
|
||||
/// Certain requests such as `AbilitySupport` require details such as what type of
|
||||
/// abilities are you intested in. This is a comma seperated list such as
|
||||
/// `"system, network, alarm, record, video, image"`
|
||||
pub token: Option<String>,
|
||||
/// The channel ID. This is usually `0` unless using an NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: Option<u8>,
|
||||
/// The rfID used in the PIR
|
||||
#[yaserde(rename = "rfId")]
|
||||
pub rf_id: Option<u8>,
|
||||
}
|
||||
|
||||
impl Default for Extension {
|
||||
fn default() -> Extension {
|
||||
Extension {
|
||||
version: xml_ver(),
|
||||
binary_data: None,
|
||||
user_name: None,
|
||||
token: None,
|
||||
channel_id: None,
|
||||
rf_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SystemGeneral xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct SystemGeneral {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
|
||||
/// Time zone is negative seconds offset from UTC. So +7:00 is -25200
|
||||
#[yaserde(rename = "timeZone")]
|
||||
pub time_zone: Option<i32>,
|
||||
/// Current year
|
||||
pub year: Option<i32>,
|
||||
/// Current month
|
||||
pub month: Option<u8>,
|
||||
/// Current day
|
||||
pub day: Option<u8>,
|
||||
/// Current hour
|
||||
pub hour: Option<u8>,
|
||||
/// Current minute
|
||||
pub minute: Option<u8>,
|
||||
/// Current second
|
||||
pub second: Option<u8>,
|
||||
|
||||
/// Format to use for On Screen Display usually `"DMY"`
|
||||
#[yaserde(rename = "osdFormat")]
|
||||
pub osd_format: Option<String>,
|
||||
/// Unknown usually `0`
|
||||
#[yaserde(rename = "timeFormat")]
|
||||
pub time_format: Option<u8>,
|
||||
|
||||
/// Language e.g. `English` will set the language on the reolink app
|
||||
pub language: Option<String>,
|
||||
/// Name assigned to the camera
|
||||
#[yaserde(rename = "deviceName")]
|
||||
pub device_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Norm xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct Norm {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
// This is usually just `"NTSC"`
|
||||
norm: String,
|
||||
}
|
||||
|
||||
/// LedState xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct LedState {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Channel ID of camera to get/set its LED state
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// LED Version, observed value is "2". Should be None when setting the LedState
|
||||
#[yaserde(rename = "ledVersion")]
|
||||
pub led_version: Option<u32>,
|
||||
/// State of the IR LEDs values are "auto", "open", "close"
|
||||
pub state: String,
|
||||
/// State of the LED status light (blue on light), values are "open", "close"
|
||||
#[yaserde(rename = "lightState")]
|
||||
pub light_state: String,
|
||||
}
|
||||
|
||||
/// rfAlarmCfg xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct RfAlarmCfg {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Rfid
|
||||
#[yaserde(rename = "rfID")]
|
||||
pub rf_id: u8,
|
||||
/// PIR status
|
||||
pub enable: u8,
|
||||
/// PIR sensitivity
|
||||
pub sensitivity: u8,
|
||||
/// PIR sensivalue
|
||||
pub sensiValue: u8,
|
||||
/// reduce False alarm boolean
|
||||
pub reduceFalseAlarm: u8,
|
||||
/// XML time block for all week days
|
||||
#[yaserde(rename = "timeBlockList")]
|
||||
pub time_block_list: TimeBlockList,
|
||||
/// The alarm handle to attach to this Rf
|
||||
#[yaserde(rename = "alarmHandle")]
|
||||
pub alarm_handle: AlarmHandle,
|
||||
}
|
||||
|
||||
/// TimeBlockList XML
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "timeBlockList")]
|
||||
pub struct TimeBlockList {
|
||||
/// List of time block entries which disable/enable the PIR at a time
|
||||
#[yaserde(rename = "timeBlock")]
|
||||
pub time_block: Vec<TimeBlock>,
|
||||
}
|
||||
|
||||
/// TimeBlock XML Used to set the time to enable/disable PIR dectection
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "timeBlock")]
|
||||
pub struct TimeBlock {
|
||||
/// Whether to enable or disable for this time block
|
||||
pub enable: u8,
|
||||
/// The day of the week for this block
|
||||
pub weekDay: String,
|
||||
/// Time to start this block
|
||||
#[yaserde(rename = "beginHour")]
|
||||
pub begin_hour: u8,
|
||||
/// Time to end this block
|
||||
#[yaserde(rename = "endHour")]
|
||||
pub end_hour: u8,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
/// AlarmHandle Xml
|
||||
pub struct AlarmHandle {
|
||||
/// Items in the alarm handle
|
||||
pub item: Vec<AlarmHandleItem>,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
/// An item in the alarm handle
|
||||
#[yaserde(rename = "item")]
|
||||
pub struct AlarmHandleItem {
|
||||
/// The channel ID
|
||||
pub channel: u8,
|
||||
/// The handle type: Known values, comma seperated list of snap,rec,push
|
||||
#[yaserde(rename = "handleType")]
|
||||
pub handle_type: String,
|
||||
}
|
||||
|
||||
/// TalkConfig xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct TalkConfig {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Channel ID of camera to set the TalkConfig
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Duplex known values `"FDX"`
|
||||
pub duplex: String,
|
||||
/// audioStreamMode known values `"followVideoStream"`
|
||||
#[yaserde(rename = "audioStreamMode")]
|
||||
pub audio_stream_mode: String,
|
||||
/// AudioConfig contans the details of the audio to follow
|
||||
#[yaserde(rename = "audioConfig")]
|
||||
pub audio_config: AudioConfig,
|
||||
}
|
||||
|
||||
/// audioConfig xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
|
||||
#[yaserde(rename = "audioConfig")]
|
||||
pub struct AudioConfig {
|
||||
/// Unknown only sent during TalkAbility request from the camera
|
||||
pub priority: Option<u32>,
|
||||
/// Audio type known values are `"adpcm"`
|
||||
///
|
||||
/// Do not expect camera to support anything else.
|
||||
#[yaserde(rename = "audioType")]
|
||||
pub audio_type: String,
|
||||
/// Audio sample rate known values are `16000`
|
||||
#[yaserde(rename = "sampleRate")]
|
||||
pub sample_rate: u16,
|
||||
/// Precision of data known vaues are `16` (i.e. 16bit)
|
||||
#[yaserde(rename = "samplePrecision")]
|
||||
pub sample_precision: u16,
|
||||
/// Number of audio samples this should be twice the block size for adpcm
|
||||
#[yaserde(rename = "lengthPerEncoder")]
|
||||
pub length_per_encoder: u16,
|
||||
/// Sound track is the number of tracks known values are `"mono"`
|
||||
///
|
||||
/// Do not expect camera to support anything else
|
||||
#[yaserde(rename = "soundTrack")]
|
||||
pub sound_track: String,
|
||||
}
|
||||
|
||||
/// TalkAbility xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct TalkAbility {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Duplexes known values `"FDX"`
|
||||
#[yaserde(rename = "duplexList")]
|
||||
pub duplex_list: Vec<DuplexList>,
|
||||
/// audioStreamModes known values `"followVideoStream"`
|
||||
#[yaserde(rename = "audioStreamModeList")]
|
||||
pub audio_stream_mode_list: Vec<AudioStreamModeList>,
|
||||
/// AudioConfigs contans the details of the audio to follow
|
||||
#[yaserde(rename = "audioConfigList")]
|
||||
pub audio_config_list: Vec<AudioConfigList>,
|
||||
}
|
||||
|
||||
/// duplexList xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct DuplexList {
|
||||
/// The supported duplex known values are "FBX"
|
||||
pub duplex: String,
|
||||
}
|
||||
|
||||
/// audioStreamModeList xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AudioStreamModeList {
|
||||
/// The supported audio stream mode
|
||||
#[yaserde(rename = "audioStreamMode")]
|
||||
pub audio_stream_mode: String,
|
||||
}
|
||||
|
||||
/// audioConfigList xml
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AudioConfigList {
|
||||
/// The supported audio configs
|
||||
#[yaserde(rename = "audioConfig")]
|
||||
pub audio_config: AudioConfig,
|
||||
}
|
||||
|
||||
/// An XML that desctibes a list of events such as motion detection
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AlarmEventList {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// List of events
|
||||
#[yaserde(rename = "AlarmEvent")]
|
||||
pub alarm_events: Vec<AlarmEvent>,
|
||||
}
|
||||
|
||||
/// An alarm event. Camera can send multiple per message as an array in AlarmEventList.
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AlarmEvent {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// The channel the event occured on. Usually zero unless from an NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Motion status. Known values are `"MD"` or `"none"`
|
||||
pub status: String,
|
||||
/// The recording status. Known values `0` or `1`
|
||||
pub recording: i32,
|
||||
/// The timestamp associated with the recording. `0` if not recording
|
||||
#[yaserde(rename = "timeStamp")]
|
||||
pub timeStamp: i32,
|
||||
}
|
||||
|
||||
/// The Ptz messages used to move the camera
|
||||
#[derive(PartialEq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct PtzControl {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// The channel the event occured on. Usually zero unless from an NVR
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// The amount of movement to perform
|
||||
pub speed: f32,
|
||||
/// The direction to transverse. Known directions: "right"
|
||||
pub command: String,
|
||||
}
|
||||
|
||||
/// A list of battery infos. This message is sent from the camera as
|
||||
/// an event
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryList {
|
||||
/// XML Version
|
||||
#[yaserde(attribute)]
|
||||
pub version: String,
|
||||
/// Battery info items
|
||||
#[yaserde(rename = "BatteryInfo")]
|
||||
pub battery_info: Vec<BatteryInfo>,
|
||||
}
|
||||
|
||||
/// The individual battery info
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct BatteryInfo {
|
||||
/// The channel the for the camera usually 0
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Charge status known values, "chargeComplete", "charging", "none",
|
||||
#[yaserde(rename = "chargeStatus")]
|
||||
pub charge_status: String,
|
||||
/// Status of charging port known values: "solarPanel"
|
||||
#[yaserde(rename = "adapterStatus")]
|
||||
pub adapter_status: String,
|
||||
/// Voltage
|
||||
pub voltage: i32,
|
||||
/// Current
|
||||
pub current: i32,
|
||||
/// Temperture
|
||||
pub temperature: i32,
|
||||
/// % charge from 0-100
|
||||
#[yaserde(rename = "batteryPercent")]
|
||||
pub battery_percent: u32,
|
||||
/// Low power flag. Known values 0, 1 (0=false)
|
||||
#[yaserde(rename = "lowPower")]
|
||||
pub low_power: u32,
|
||||
/// Battery version info: Known values 2
|
||||
#[yaserde(rename = "batteryVersion")]
|
||||
pub battery_version: u32,
|
||||
}
|
||||
|
||||
/// The ability battery info
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AbilityInfo {
|
||||
/// Username with this ability
|
||||
#[yaserde(rename = "userName")]
|
||||
pub username: String,
|
||||
/// System permissions
|
||||
pub system: Option<AbilityInfoToken>,
|
||||
/// Network permissions
|
||||
pub network: Option<AbilityInfoToken>,
|
||||
/// Alarm permissions
|
||||
pub alarm: Option<AbilityInfoToken>,
|
||||
/// Image permissions
|
||||
pub image: Option<AbilityInfoToken>,
|
||||
/// Video permissions
|
||||
pub video: Option<AbilityInfoToken>,
|
||||
/// Secutiry permissions
|
||||
pub security: Option<AbilityInfoToken>,
|
||||
/// Replay permissions
|
||||
pub replay: Option<AbilityInfoToken>,
|
||||
/// PTZ permissions
|
||||
#[yaserde(rename = "PTZ")]
|
||||
pub ptz: Option<AbilityInfoToken>,
|
||||
/// IO permissions
|
||||
#[yaserde(rename = "IO")]
|
||||
pub io: Option<AbilityInfoToken>,
|
||||
/// Streaming permissions
|
||||
pub streaming: Option<AbilityInfoToken>,
|
||||
}
|
||||
|
||||
/// Ability info for system token
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct AbilityInfoToken {
|
||||
/// Submodule for this ability info token
|
||||
#[yaserde(rename = "subModule")]
|
||||
pub sub_module: Vec<AbilityInfoSubModule>,
|
||||
}
|
||||
|
||||
/// Token submodule infomation
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
#[yaserde(rename = "subModule")]
|
||||
pub struct AbilityInfoSubModule {
|
||||
/// The channel the for the camera usually 0
|
||||
#[yaserde(rename = "channelId")]
|
||||
pub channel_id: Option<u8>,
|
||||
/// The comma seperated list of permissions like this: `general_rw, norm_rw, version_ro`
|
||||
#[yaserde(rename = "abilityValue")]
|
||||
pub ability_value: String,
|
||||
}
|
||||
|
||||
/// PushInfo XML
|
||||
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
|
||||
pub struct PushInfo {
|
||||
/// The token from FCM registration
|
||||
pub token: String,
|
||||
/// The phone type, known values: `reo_iphone`
|
||||
#[yaserde(rename = "phoneType")]
|
||||
pub phone_type: String,
|
||||
/// A client ID, seems to be an all CAPS MD5 hash of something
|
||||
#[yaserde(rename = "clientID")]
|
||||
pub client_id: String,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
pub fn xml_ver() -> String {
|
||||
"1.1".to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_encryption_deser() {
|
||||
let sample = indoc!(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<Encryption version="1.1">
|
||||
<type>md5</type>
|
||||
<nonce>9E6D1FCB9E69846D</nonce>
|
||||
</Encryption>
|
||||
</body>"#
|
||||
);
|
||||
let b: BcXml = yaserde::de::from_str(sample).unwrap();
|
||||
let enc = b.encryption.as_ref().unwrap();
|
||||
|
||||
assert_eq!(enc.version, "1.1");
|
||||
assert_eq!(enc.nonce, "9E6D1FCB9E69846D");
|
||||
assert_eq!(enc.type_, "md5");
|
||||
|
||||
let t = BcXml::try_parse(sample.as_bytes()).unwrap();
|
||||
match t {
|
||||
top_b if top_b == b => {}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_login_deser() {
|
||||
let sample = indoc!(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<LoginUser version="1.1">
|
||||
<userName>9F07915E819A076E2E14169830769D6</userName>
|
||||
<password>8EFECD610524A98390F118D2789BE3B</password>
|
||||
<userVer>1</userVer>
|
||||
</LoginUser>
|
||||
<LoginNet version="1.1">
|
||||
<type>LAN</type>
|
||||
<udpPort>0</udpPort>
|
||||
</LoginNet>
|
||||
</body>"#
|
||||
);
|
||||
let b: BcXml = yaserde::de::from_str(sample).unwrap();
|
||||
let login_user = b.login_user.unwrap();
|
||||
let login_net = b.login_net.unwrap();
|
||||
|
||||
assert_eq!(login_user.version, "1.1");
|
||||
assert_eq!(login_user.user_name, "9F07915E819A076E2E14169830769D6");
|
||||
assert_eq!(login_user.password, "8EFECD610524A98390F118D2789BE3B");
|
||||
assert_eq!(login_user.user_ver, 1);
|
||||
|
||||
assert_eq!(login_net.version, "1.1");
|
||||
assert_eq!(login_net.type_, "LAN");
|
||||
assert_eq!(login_net.udp_port, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_login_ser() {
|
||||
let sample = indoc!(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<LoginUser version="1.1">
|
||||
<userName>9F07915E819A076E2E14169830769D6</userName>
|
||||
<password>8EFECD610524A98390F118D2789BE3B</password>
|
||||
<userVer>1</userVer>
|
||||
</LoginUser>
|
||||
<LoginNet version="1.1">
|
||||
<type>LAN</type>
|
||||
<udpPort>0</udpPort>
|
||||
</LoginNet>
|
||||
</body>"#
|
||||
);
|
||||
|
||||
let b = BcXml {
|
||||
login_user: Some(LoginUser {
|
||||
version: "1.1".to_string(),
|
||||
user_name: "9F07915E819A076E2E14169830769D6".to_string(),
|
||||
password: "8EFECD610524A98390F118D2789BE3B".to_string(),
|
||||
user_ver: 1,
|
||||
}),
|
||||
login_net: Some(LoginNet {
|
||||
version: "1.1".to_string(),
|
||||
type_: "LAN".to_string(),
|
||||
udp_port: 0,
|
||||
}),
|
||||
..BcXml::default()
|
||||
};
|
||||
|
||||
let b2 = BcXml::try_parse(sample.as_bytes()).unwrap();
|
||||
let b3 = BcXml::try_parse(b.serialize(vec![]).unwrap().as_slice()).unwrap();
|
||||
|
||||
assert_eq!(b, b2);
|
||||
assert_eq!(b, b3);
|
||||
assert_eq!(b2, b3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deviceinfo_partial_deser() {
|
||||
let sample = indoc!(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<DeviceInfo version="1.1">
|
||||
<ipChannel>0</ipChannel>
|
||||
<analogChnNum>1</analogChnNum>
|
||||
<resolution>
|
||||
<resolutionName>3840*2160</resolutionName>
|
||||
<width>3840</width>
|
||||
<height>2160</height>
|
||||
</resolution>
|
||||
<language>English</language>
|
||||
<sdCard>0</sdCard>
|
||||
<ptzMode>none</ptzMode>
|
||||
<typeInfo>IPC</typeInfo>
|
||||
<softVer>33554880</softVer>
|
||||
<B485>0</B485>
|
||||
<supportAutoUpdate>0</supportAutoUpdate>
|
||||
<userVer>1</userVer>
|
||||
</DeviceInfo>
|
||||
</body>"#
|
||||
);
|
||||
|
||||
// Needs to ignore all the other crap that we don't care about
|
||||
let b = BcXml::try_parse(sample.as_bytes()).unwrap();
|
||||
match b {
|
||||
BcXml {
|
||||
device_info:
|
||||
Some(DeviceInfo {
|
||||
resolution:
|
||||
Resolution {
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
..
|
||||
},
|
||||
..
|
||||
}),
|
||||
..
|
||||
} => {}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_binary_deser() {
|
||||
let _ = env_logger::builder().is_test(true).try_init();
|
||||
|
||||
let sample = indoc!(
|
||||
r#"
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<binaryData>1</binaryData>
|
||||
</Extension>
|
||||
"#
|
||||
);
|
||||
let b = Extension::try_parse(sample.as_bytes()).unwrap();
|
||||
match b {
|
||||
Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
} => {}
|
||||
_ => panic!(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use super::model::EncryptionProtocol;
|
||||
use aes::{
|
||||
cipher::{AsyncStreamCipher, KeyIvInit},
|
||||
Aes128,
|
||||
};
|
||||
use cfb_mode::{Decryptor, Encryptor};
|
||||
|
||||
type Aes128CfbEnc = Encryptor<Aes128>;
|
||||
type Aes128CfbDec = Decryptor<Aes128>;
|
||||
|
||||
const XML_KEY: [u8; 8] = [0x1F, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78, 0xFF];
|
||||
const IV: &[u8] = b"0123456789abcdef";
|
||||
|
||||
pub fn decrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec<u8> {
|
||||
match encryption_protocol {
|
||||
EncryptionProtocol::Unencrypted => buf.to_vec(),
|
||||
EncryptionProtocol::BCEncrypt => {
|
||||
let key_iter = XML_KEY.iter().cycle().skip(offset as usize % 8);
|
||||
key_iter
|
||||
.zip(buf)
|
||||
.map(|(key, i)| *i ^ key ^ (offset as u8))
|
||||
.collect()
|
||||
}
|
||||
EncryptionProtocol::Aes(aeskey) => {
|
||||
// AES decryption
|
||||
|
||||
let mut decrypted = buf.to_vec();
|
||||
Aes128CfbDec::new(aeskey.into(), IV.into()).decrypt(&mut decrypted);
|
||||
decrypted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt(offset: u32, buf: &[u8], encryption_protocol: &EncryptionProtocol) -> Vec<u8> {
|
||||
match encryption_protocol {
|
||||
EncryptionProtocol::Unencrypted => {
|
||||
// Encrypt is the same as decrypt
|
||||
decrypt(offset, buf, encryption_protocol)
|
||||
}
|
||||
EncryptionProtocol::BCEncrypt => {
|
||||
// Encrypt is the same as decrypt
|
||||
decrypt(offset, buf, encryption_protocol)
|
||||
}
|
||||
EncryptionProtocol::Aes(aeskey) => {
|
||||
// AES encryption
|
||||
let mut encrypted = buf.to_vec();
|
||||
Aes128CfbEnc::new(aeskey.into(), IV.into()).encrypt(&mut encrypted);
|
||||
encrypted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xml_crypto() {
|
||||
let sample = include_bytes!("samples/xml_crypto_sample1.bin");
|
||||
let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin");
|
||||
|
||||
let decrypted = decrypt(0, &sample[..], &EncryptionProtocol::BCEncrypt);
|
||||
assert_eq!(decrypted, &should_be[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xml_crypto_roundtrip() {
|
||||
let zeros: [u8; 256] = [0; 256];
|
||||
|
||||
let decrypted = encrypt(0, &zeros[..], &EncryptionProtocol::BCEncrypt);
|
||||
let encrypted = decrypt(0, &decrypted[..], &EncryptionProtocol::BCEncrypt);
|
||||
assert_eq!(encrypted, &zeros[..]);
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
use crate::bc;
|
||||
use futures::stream::StreamExt;
|
||||
use log::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::atomic::{AtomicBool, AtomicU16, Ordering},
|
||||
};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use Md5Trunc::*;
|
||||
|
||||
mod abilityinfo;
|
||||
mod battery;
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod errors;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
mod login;
|
||||
mod logout;
|
||||
mod motion;
|
||||
mod ping;
|
||||
mod pirstate;
|
||||
mod ptz;
|
||||
mod pushinfo;
|
||||
mod reboot;
|
||||
mod resolution;
|
||||
mod stream;
|
||||
mod talk;
|
||||
mod time;
|
||||
mod version;
|
||||
|
||||
pub(crate) use connection::*;
|
||||
pub use credentials::*;
|
||||
pub use errors::Error;
|
||||
pub use ledstate::LightState;
|
||||
pub use login::MaxEncryption;
|
||||
pub use motion::{MotionData, MotionStatus};
|
||||
pub use pirstate::PirState;
|
||||
pub use ptz::Direction;
|
||||
pub use pushinfo::PhoneType;
|
||||
pub use resolution::*;
|
||||
use std::sync::Arc;
|
||||
pub use stream::{StreamData, StreamKind};
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ReadKind {
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
None,
|
||||
}
|
||||
|
||||
///
|
||||
/// This is the primary struct of this library when interacting with the camera
|
||||
///
|
||||
pub struct BcCamera {
|
||||
channel_id: u8,
|
||||
connection: Arc<BcConnection>,
|
||||
logged_in: AtomicBool,
|
||||
message_num: AtomicU16,
|
||||
// Certain commands such as logout require the username/pass in plain text.... why....???
|
||||
credentials: Credentials,
|
||||
abilities: RwLock<HashMap<String, ReadKind>>,
|
||||
}
|
||||
|
||||
/// Options used to construct a camera
|
||||
#[derive(Debug)]
|
||||
pub struct BcCameraOpt {
|
||||
/// Name, mostly used for message logs
|
||||
pub name: String,
|
||||
/// Channel the camera is on 0 unless using a NVR
|
||||
pub channel_id: u8,
|
||||
/// IPs of the camera
|
||||
pub addrs: Vec<IpAddr>,
|
||||
/// The UID of the camera
|
||||
pub uid: Option<String>,
|
||||
/// Port to try optional. When not given all known BC ports will be tried
|
||||
/// When given all known bc port AND the given port will be tried
|
||||
pub port: Option<u16>,
|
||||
/// Protocol decides if UDP/TCP are used for the camera
|
||||
pub protocol: ConnectionProtocol,
|
||||
/// Discovery method to allow
|
||||
pub discovery: DiscoveryMethods,
|
||||
/// Printing format for auxilaary data such as battery levels
|
||||
pub aux_printing: PrintFormat,
|
||||
/// Credentials for login
|
||||
pub credentials: Credentials,
|
||||
}
|
||||
|
||||
/// Used to choose the print format of various status messages like battery levels
|
||||
///
|
||||
/// Currently this is just the format of battery levels but if we ever got more status
|
||||
/// messages then they will also use this information
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub enum PrintFormat {
|
||||
/// None, don't print
|
||||
None,
|
||||
/// A human readable output
|
||||
Human,
|
||||
/// Xml formatted
|
||||
Xml,
|
||||
}
|
||||
|
||||
/// Type of connection to try
|
||||
#[derive(Default, Debug, Clone, Copy, Serialize, Deserialize)]
|
||||
pub enum ConnectionProtocol {
|
||||
/// TCP and UDP
|
||||
#[default]
|
||||
TcpUdp,
|
||||
/// TCP only
|
||||
Tcp,
|
||||
/// Udp only
|
||||
Udp,
|
||||
}
|
||||
|
||||
enum CameraLocation {
|
||||
Tcp(SocketAddr),
|
||||
Udp(DiscoveryResult),
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Try to connect to the camera via appropaite methods and return
|
||||
/// the location that should be used
|
||||
async fn find_camera(options: &BcCameraOpt) -> Result<CameraLocation> {
|
||||
if let ConnectionProtocol::Tcp | ConnectionProtocol::TcpUdp = options.protocol {
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
Some(9000) | None => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, 9000));
|
||||
}
|
||||
}
|
||||
Some(n) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, n));
|
||||
sockets.push(SocketAddr::new(*addr, 9000));
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("{}: Trying TCP discovery", options.name);
|
||||
for socket in sockets.drain(..) {
|
||||
let channel_id: u8 = options.channel_id;
|
||||
if let Ok(addr) = Discovery::check_tcp(socket, channel_id).await.map(|_| {
|
||||
info!("{}: TCP Discovery success at {:?}", options.name, &socket);
|
||||
socket
|
||||
}) {
|
||||
return Ok(CameraLocation::Tcp(addr));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(uid), ConnectionProtocol::Udp | ConnectionProtocol::TcpUdp) =
|
||||
(options.uid.as_ref(), options.protocol)
|
||||
{
|
||||
let mut sockets = vec![];
|
||||
match options.port {
|
||||
None | Some(2015) | Some(2018) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, 2018));
|
||||
sockets.push(SocketAddr::new(*addr, 2015));
|
||||
}
|
||||
}
|
||||
Some(n) => {
|
||||
for addr in options.addrs.iter() {
|
||||
sockets.push(SocketAddr::new(*addr, n));
|
||||
sockets.push(SocketAddr::new(*addr, 2015));
|
||||
sockets.push(SocketAddr::new(*addr, 2018));
|
||||
}
|
||||
}
|
||||
}
|
||||
let (allow_local, allow_remote, allow_map, allow_relay) = match options.discovery {
|
||||
DiscoveryMethods::None => (false, false, false, false),
|
||||
DiscoveryMethods::Local => (true, false, false, false),
|
||||
DiscoveryMethods::Remote => (true, true, false, false),
|
||||
DiscoveryMethods::Map => (true, true, true, false),
|
||||
DiscoveryMethods::Relay => (true, true, true, true),
|
||||
DiscoveryMethods::Debug => (false, false, false, true),
|
||||
};
|
||||
|
||||
if allow_local {
|
||||
let uid_local = uid.clone();
|
||||
info!("{}: Trying local discovery", options.name);
|
||||
let result = Discovery::local(&uid_local, Some(sockets)).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
options.name,
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_remote {
|
||||
let uid_remote = uid.clone();
|
||||
info!("{}: Trying remote discovery", options.name);
|
||||
let result = Discovery::remote(&uid_remote).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
options.name,
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_map {
|
||||
let uid_map = uid.clone();
|
||||
info!("{}: Trying map discovery", options.name);
|
||||
let result = Discovery::map(&uid_map).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Map success {} at {}",
|
||||
options.name,
|
||||
uid_map,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
if allow_relay {
|
||||
let uid_relay = uid.clone();
|
||||
info!("{}: Trying relay discovery", options.name);
|
||||
let result = Discovery::relay(&uid_relay).await;
|
||||
if let Ok(disc) = result {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
options.name,
|
||||
uid_relay,
|
||||
disc.get_addr()
|
||||
);
|
||||
return Ok(CameraLocation::Udp(disc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
info!("{}: Discovery failed", options.name);
|
||||
// Nothing works
|
||||
Err(Error::CannotInitCamera)
|
||||
}
|
||||
|
||||
///
|
||||
/// Create a new camera interface
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `options` - Camera information see [`BcCameraOpt]
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or the camera
|
||||
///
|
||||
pub async fn new(options: &BcCameraOpt) -> Result<Self> {
|
||||
let username: String = options.credentials.username.clone();
|
||||
let passwd: Option<String> = options.credentials.password.clone();
|
||||
|
||||
let (sink, source): (BcConnSink, BcConnSource) = {
|
||||
match BcCamera::find_camera(options).await? {
|
||||
CameraLocation::Tcp(addr) => {
|
||||
let (x, r) = TcpSource::new(addr, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
CameraLocation::Udp(discovery) => {
|
||||
let (x, r) =
|
||||
UdpSource::new_from_discovery(discovery, &username, passwd.as_ref())
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let conn = BcConnection::new(sink, source).await?;
|
||||
|
||||
trace!("Success");
|
||||
let me = Self {
|
||||
connection: Arc::new(conn),
|
||||
message_num: AtomicU16::new(0),
|
||||
channel_id: options.channel_id,
|
||||
logged_in: AtomicBool::new(false),
|
||||
credentials: Credentials::new(username, passwd),
|
||||
abilities: Default::default(),
|
||||
};
|
||||
me.keepalive().await?;
|
||||
if let Err(e) = me.monitor_battery(options.aux_printing).await {
|
||||
warn!("Could not monitor battery: {:?}", e);
|
||||
}
|
||||
Ok(me)
|
||||
}
|
||||
|
||||
/// This method will get a new message number and increment the message count atomically
|
||||
pub fn new_message_num(&self) -> u16 {
|
||||
self.message_num.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn get_connection(&self) -> Arc<BcConnection> {
|
||||
self.connection.clone()
|
||||
}
|
||||
|
||||
// Certains commands like logout need the username and password
|
||||
// this command will return
|
||||
// This will only work after login
|
||||
fn get_credentials(&self) -> &Credentials {
|
||||
&self.credentials
|
||||
}
|
||||
|
||||
async fn has_ability<T: Into<String>>(&self, name: T) -> ReadKind {
|
||||
let abilities = self.abilities.read().await;
|
||||
if let Some(kind) = abilities.get(&name.into()).copied() {
|
||||
kind
|
||||
} else {
|
||||
ReadKind::None
|
||||
}
|
||||
}
|
||||
async fn has_ability_ro<T: Into<String>>(&self, name: T) -> Result<()> {
|
||||
let s: String = name.into();
|
||||
match self.has_ability(&s).await {
|
||||
ReadKind::ReadWrite | ReadKind::ReadOnly => Ok(()),
|
||||
ReadKind::None => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "read".to_string(),
|
||||
actual: "none".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
async fn has_ability_rw<T: Into<String>>(&self, name: T) -> Result<()> {
|
||||
let s: String = name.into();
|
||||
match self.has_ability(&s).await {
|
||||
ReadKind::ReadWrite => Ok(()),
|
||||
ReadKind::ReadOnly => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "write".to_string(),
|
||||
actual: "read".to_string(),
|
||||
}),
|
||||
ReadKind::None => Err(Error::MissingAbility {
|
||||
name: s.clone(),
|
||||
requested: "write".to_string(),
|
||||
actual: "none".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for all thread to finish
|
||||
///
|
||||
/// If an error is returned in any thread it will return the first error
|
||||
pub async fn join(&self) -> Result<()> {
|
||||
self.connection.join().await
|
||||
}
|
||||
}
|
||||
|
||||
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
|
||||
/// believe this is because the MD5'ing of the user/password is a recent retrofit to the code and
|
||||
/// the original code wanted to prevent a buffer overflow with strcpy. The modern and legacy login
|
||||
/// messages have a slightly different behavior; the legacy message has a 32-byte buffer and the
|
||||
/// modern message uses XML. The legacy code copies all 32 bytes with memcpy, and the XML value is
|
||||
/// copied from a C-style string, so the appended null byte is dropped by the XML library - see the
|
||||
/// test below.
|
||||
/// Emulate this behavior by providing a configurable mangling of the last character.
|
||||
#[derive(PartialEq, Eq)]
|
||||
enum Md5Trunc {
|
||||
ZeroLast,
|
||||
Truncate,
|
||||
}
|
||||
|
||||
fn md5_string(input: &str, trunc: Md5Trunc) -> String {
|
||||
let mut md5 = format!("{:X}\0", md5::compute(input));
|
||||
md5.replace_range(31.., if trunc == Truncate { "" } else { "\0" });
|
||||
md5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_md5_string() {
|
||||
// Note that these literals are only 31 characters long - see explanation above.
|
||||
assert_eq!(
|
||||
md5_string("admin", Truncate),
|
||||
"21232F297A57A5A743894A0E4A801FC"
|
||||
);
|
||||
assert_eq!(
|
||||
md5_string("admin", ZeroLast),
|
||||
"21232F297A57A5A743894A0E4A801FC\0"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use log::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the ability info xml for the current user
|
||||
pub async fn get_abilityinfo(&self) -> Result<AbilityInfo> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_ABILITY_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
user_name: Some(self.get_credentials().username.clone()),
|
||||
token: Some("system, streaming, PTZ, IO, security, replay, disk, network, alarm, record, video, image".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
ability_info: Some(ability_info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(ability_info)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected AbilityInfo xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Populate ability list of the camera
|
||||
pub async fn polulate_abilities(&self) -> Result<()> {
|
||||
let info = self.get_abilityinfo().await?;
|
||||
let info_res = yaserde::ser::serialize_with_writer(&info, vec![], &Default::default());
|
||||
if let Ok(Ok(info_str)) = info_res.map(String::from_utf8) {
|
||||
debug!("Abilities: {}", info_str);
|
||||
}
|
||||
|
||||
let mut abilities: Vec<String> = vec![];
|
||||
|
||||
let mut tokens: Vec<Option<&AbilityInfoToken>> = vec![
|
||||
info.system.as_ref(),
|
||||
info.network.as_ref(),
|
||||
info.alarm.as_ref(),
|
||||
info.image.as_ref(),
|
||||
info.video.as_ref(),
|
||||
info.security.as_ref(),
|
||||
info.replay.as_ref(),
|
||||
info.ptz.as_ref(),
|
||||
info.io.as_ref(),
|
||||
info.streaming.as_ref(),
|
||||
];
|
||||
|
||||
for token in tokens.drain(..).flatten() {
|
||||
for sub_module in token.sub_module.iter() {
|
||||
abilities.extend(
|
||||
sub_module
|
||||
.ability_value
|
||||
.replace(' ', "")
|
||||
.split(',')
|
||||
.map(|s| s.to_string()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut locked_abilities = self.abilities.write().await;
|
||||
for ability in abilities.iter() {
|
||||
let mut abilities_ro = ability.split('_').map(|s| s.to_string());
|
||||
if let (Some(ability_name), Some(ability_kind)) =
|
||||
(abilities_ro.next(), abilities_ro.next())
|
||||
{
|
||||
match ability_kind.as_str() {
|
||||
"rw" => {
|
||||
locked_abilities.insert(ability_name, super::ReadKind::ReadWrite);
|
||||
}
|
||||
"ro" => {
|
||||
locked_abilities.insert(ability_name, super::ReadKind::ReadOnly);
|
||||
}
|
||||
_ => {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! Handles battery related messages
|
||||
//!
|
||||
//! There are primarily two messages:
|
||||
//! - BatteryInfoList which the camera sends as part of its login info
|
||||
//! - BatteryInfo which the client can request on demand
|
||||
//!
|
||||
|
||||
use super::{BcCamera, PrintFormat, Result};
|
||||
use crate::{
|
||||
bc::{model::*, xml::BatteryInfo},
|
||||
Error,
|
||||
};
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to battery messages
|
||||
/// These messages are sent by the camera on login and maybe
|
||||
/// also on low battery events
|
||||
pub async fn monitor_battery(&self, format: PrintFormat) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_BATTERY_INFO_LIST, move |bc| {
|
||||
if let Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_list: Some(battery_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
..
|
||||
} = bc
|
||||
{
|
||||
for battery in battery_list.battery_info.iter() {
|
||||
match format {
|
||||
PrintFormat::None => {}
|
||||
PrintFormat::Human => {
|
||||
println!(
|
||||
"==Battery==\n\
|
||||
Charge: {}%,\n\
|
||||
Temperature: {}°C,\n\
|
||||
LowPower: {},\n\
|
||||
Adapter: {},\n\
|
||||
ChargeStatus: {},\n\
|
||||
",
|
||||
battery.battery_percent,
|
||||
battery.temperature,
|
||||
if battery.low_power == 1 {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
},
|
||||
battery.adapter_status,
|
||||
battery.charge_status,
|
||||
);
|
||||
}
|
||||
PrintFormat::Xml => {
|
||||
let bat_ser = String::from_utf8(
|
||||
yaserde::ser::serialize_with_writer(
|
||||
battery,
|
||||
vec![],
|
||||
&Default::default(),
|
||||
)
|
||||
.expect("Should Ser the struct"),
|
||||
)
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Requests the current battery status of the camera
|
||||
pub async fn battery_info(&self) -> Result<BatteryInfo> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_BATTERY_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let Bc {
|
||||
meta: BcMeta {
|
||||
response_code: 200, ..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
battery_info: Some(battery_info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = msg
|
||||
{
|
||||
Ok(battery_info)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the battery info (maybe no battery) command.",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
use super::BcSubscription;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use log::*;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::BTreeMap;
|
||||
use tokio::sync::mpsc::{channel, Sender};
|
||||
use tokio::task::yield_now;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::PollSender;
|
||||
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their Num
|
||||
num: BTreeMap<u16, Sender<Result<Bc>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: BTreeMap<u32, MsgHandler>,
|
||||
}
|
||||
|
||||
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
|
||||
pub(crate) type BcConnSource = Box<dyn Stream<Item = Result<Bc>> + Send + Sync + Unpin>;
|
||||
|
||||
/// A shareable connection to a camera. Handles serialization of messages. To send/receive, call
|
||||
/// .[subscribe()] with a message number. You can use the BcSubscription to send or receive only
|
||||
/// messages with that number; each incoming message is routed to its appropriate subscriber.
|
||||
///
|
||||
/// There can be only one subscriber per kind of message at a time.
|
||||
pub struct BcConnection {
|
||||
sink: Sender<Result<Bc>>,
|
||||
poll_commander: Sender<PollCommand>,
|
||||
rx_thread: RwLock<JoinSet<Result<()>>>,
|
||||
}
|
||||
|
||||
impl BcConnection {
|
||||
pub async fn new(mut sink: BcConnSink, source: BcConnSource) -> Result<BcConnection> {
|
||||
let (sinker, sinker_rx) = channel::<Result<Bc>>(100);
|
||||
|
||||
let (poll_commander, poll_commanded) = channel(200);
|
||||
let mut poller = Poller {
|
||||
subscribers: Default::default(),
|
||||
sink: sinker.clone(),
|
||||
reciever: ReceiverStream::new(poll_commanded),
|
||||
};
|
||||
|
||||
let mut rx_thread = JoinSet::<Result<()>>::new();
|
||||
let thread_poll_commander = poll_commander.clone();
|
||||
let handle = tokio::task::spawn_blocking(move || {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(
|
||||
PollSender::new(thread_poll_commander)
|
||||
.send_all(&mut source.map(|bc| Ok(PollCommand::Bc(Box::new(bc))))),
|
||||
)
|
||||
});
|
||||
rx_thread.spawn(async move {
|
||||
handle.await??;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
rx_thread.spawn(async move { sink.send_all(&mut ReceiverStream::new(sinker_rx)).await });
|
||||
|
||||
rx_thread.spawn(async move {
|
||||
loop {
|
||||
poller.run().await?;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(BcConnection {
|
||||
sink: sinker,
|
||||
poll_commander,
|
||||
rx_thread: RwLock::new(rx_thread),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
self.sink.send(Ok(bc)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_num, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, msg_num as u32, self))
|
||||
}
|
||||
|
||||
/// Some messages are initiated by the camera. This creates a handler for them
|
||||
/// It requires a closure that will be used to handle the message
|
||||
/// and return either None or Some(Bc) reply
|
||||
pub async fn handle_msg<T>(&self, msg_id: u32, handler: T) -> Result<()>
|
||||
where
|
||||
T: Fn(&Bc) -> Option<Bc> + Send + Sync + 'static,
|
||||
{
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddHandler(msg_id, Box::new(handler)))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stop a message handler created using [`handle_msg`]
|
||||
#[allow(dead_code)] // Currently unused but added for future use
|
||||
pub async fn unhandle_msg(&self, msg_id: u32) -> Result<()> {
|
||||
self.poll_commander
|
||||
.send(PollCommand::RemoveHandler(msg_id))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn join(&self) -> Result<()> {
|
||||
let mut locked_threads = self.rx_thread.write().await;
|
||||
while let Some(res) = locked_threads.join_next().await {
|
||||
match res {
|
||||
Err(e) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e.into());
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
locked_threads.abort_all();
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
enum PollCommand {
|
||||
Bc(Box<Result<Bc>>),
|
||||
AddHandler(u32, MsgHandler),
|
||||
RemoveHandler(u32),
|
||||
AddSubscriber(u16, Sender<Result<Bc>>),
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
subscribers: Subscriber,
|
||||
sink: Sender<Result<Bc>>,
|
||||
reciever: ReceiverStream<PollCommand>,
|
||||
}
|
||||
|
||||
impl Poller {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
while let Some(command) = self.reciever.next().await {
|
||||
yield_now().await;
|
||||
match command {
|
||||
PollCommand::Bc(boxed_response) => match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_num = response.meta.msg_num;
|
||||
let msg_id = response.meta.msg_id;
|
||||
|
||||
let mut remove_it_num = false;
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get(&msg_num),
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
if let Some(reply) = occ(&response) {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
self.sink.send(Ok(reply)).await?;
|
||||
}
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
if occ.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
occ.capacity(),
|
||||
occ.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
if occ.send(Ok(response)).await.is_err() {
|
||||
remove_it_num = true;
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
debug!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id, msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
if remove_it_num {
|
||||
self.subscribers.num.remove(&msg_num);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
let _ = sub.send(Err(e.clone())).await;
|
||||
}
|
||||
self.subscribers.num.clear();
|
||||
self.subscribers.id.clear();
|
||||
return Err(e);
|
||||
}
|
||||
},
|
||||
PollCommand::AddHandler(msg_id, handler) => {
|
||||
match self.subscribers.id.entry(msg_id) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(handler);
|
||||
}
|
||||
Entry::Occupied(_) => {
|
||||
return Err(Error::SimultaneousSubscriptionId { msg_id });
|
||||
}
|
||||
};
|
||||
}
|
||||
PollCommand::RemoveHandler(msg_id) => {
|
||||
self.subscribers.id.remove(&msg_id);
|
||||
}
|
||||
PollCommand::AddSubscriber(msg_num, tx) => {
|
||||
match self.subscribers.num.entry(msg_num) {
|
||||
Entry::Vacant(vac_entry) => {
|
||||
vac_entry.insert(tx);
|
||||
}
|
||||
Entry::Occupied(mut occ_entry) => {
|
||||
if occ_entry.get().is_closed() {
|
||||
occ_entry.insert(tx);
|
||||
} else {
|
||||
let _ = tx
|
||||
.send(Err(Error::SimultaneousSubscription { msg_num }))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
use super::BcConnection;
|
||||
use crate::bcmedia::codex::BcMediaCodex;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use futures::stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt};
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::codec::FramedRead;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
}
|
||||
|
||||
pub struct BcStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcStream<'a> {}
|
||||
|
||||
impl<'a> Stream for BcStream<'a> {
|
||||
type Item = Result<Bc>;
|
||||
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Bc>>> {
|
||||
let mut this = self.as_mut();
|
||||
match Pin::new(&mut this.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(bc)) => Poll::Ready(Some(bc)),
|
||||
Poll::Ready(None) => Poll::Ready(None),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BcPayloadStream<'a> {
|
||||
rx: &'a mut ReceiverStream<Result<Bc>>,
|
||||
}
|
||||
|
||||
impl<'a> Unpin for BcPayloadStream<'a> {}
|
||||
|
||||
impl<'a> Stream for BcPayloadStream<'a> {
|
||||
type Item = IoResult<Vec<u8>>;
|
||||
|
||||
fn poll_next(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<IoResult<Vec<u8>>>> {
|
||||
// log::debug!("PayloadStream: Poll");
|
||||
match Pin::new(&mut self.rx).poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(Bc {
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
..
|
||||
}),
|
||||
..
|
||||
}))) => {
|
||||
// log::debug!("PayloadStream: Data");
|
||||
return Poll::Ready(Some(Ok(data)));
|
||||
}
|
||||
Poll::Ready(Some(Ok(_bc))) => {
|
||||
// trace!("Got other BC in payload stream");
|
||||
// log::debug!("PayloadStream: Other Data!");
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
// log::debug!("PayloadStream: Err");
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
// log::debug!("PayloadStream: None");
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
// log::debug!("PayloadStream: Pend");
|
||||
return Poll::Pending;
|
||||
}
|
||||
}
|
||||
// log::debug!("PayloadStream: Default Pend and Wake");
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
pub type BcMediaStream<'b> = FramedRead<Compat<IntoAsyncRead<BcPayloadStream<'b>>>, BcMediaCodex>;
|
||||
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: u32,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
rx: ReceiverStream::new(rx),
|
||||
msg_num,
|
||||
conn,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
self.conn.send(bc).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn recv(&mut self) -> Result<Bc> {
|
||||
let bc = self.rx.next().await.ok_or(Error::DroppedSubscriber)?;
|
||||
if let Ok(bc) = &bc {
|
||||
assert!(bc.meta.msg_num as u32 == self.msg_num);
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn bc_stream(&'_ mut self) -> BcStream<'_> {
|
||||
BcStream { rx: &mut self.rx }
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn payload_stream(&'_ mut self) -> BcPayloadStream<'_> {
|
||||
BcPayloadStream { rx: &mut self.rx }
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> BcMediaStream<'_> {
|
||||
let async_read = BcPayloadStream { rx: &mut self.rx }
|
||||
.into_async_read()
|
||||
.compat();
|
||||
FramedRead::new(async_read, BcMediaCodex::new(strict))
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,39 @@
|
||||
//! This module handles connections and subscribers
|
||||
//!
|
||||
//! This includes a tcp and udp connections. As well
|
||||
//! as subscribers to binary streams that are encoded
|
||||
//! in the bc packets.
|
||||
//!
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tokio::{net::UdpSocket, task::JoinSet};
|
||||
|
||||
mod bcconn;
|
||||
mod bcsub;
|
||||
mod discovery;
|
||||
mod tcpsource;
|
||||
mod udpsource;
|
||||
|
||||
pub(crate) use self::{
|
||||
bcconn::BcConnection, bcconn::*, bcsub::BcSubscription, discovery::Discovery,
|
||||
tcpsource::TcpSource, udpsource::UdpSource,
|
||||
};
|
||||
|
||||
pub(crate) struct DiscoveryResult {
|
||||
socket: Arc<UdpSocket>,
|
||||
addr: SocketAddr,
|
||||
keep_alive_tasks: JoinSet<()>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
}
|
||||
|
||||
impl DiscoveryResult {
|
||||
/// Stop all keep alive and any remaining tasks that the discover is managing
|
||||
pub(crate) async fn shutdown(&mut self) {
|
||||
self.keep_alive_tasks.shutdown().await;
|
||||
}
|
||||
/// Get the address discovered
|
||||
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
||||
&self.addr
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::bc::model::*;
|
||||
use crate::Result;
|
||||
use crate::{bc::codex::BcCodex, Credentials};
|
||||
use delegate::delegate;
|
||||
use futures::{sink::Sink, stream::Stream};
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::net::{TcpSocket, TcpStream};
|
||||
use tokio_util::codec::{Decoder, Encoder, Framed};
|
||||
|
||||
pub(crate) struct TcpSource {
|
||||
inner: Framed<TcpStream, BcCodex>,
|
||||
}
|
||||
|
||||
impl TcpSource {
|
||||
pub(crate) async fn new<T: Into<String>, U: Into<String>>(
|
||||
addr: SocketAddr,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<TcpSource> {
|
||||
let stream = connect_to(addr).await?;
|
||||
|
||||
Ok(Self {
|
||||
inner: Framed::new(stream, BcCodex::new(Credentials::new(username, password))),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for TcpSource {
|
||||
type Item = std::result::Result<<BcCodex as Decoder>::Item, <BcCodex as Decoder>::Error>;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Bc> for TcpSource {
|
||||
type Error = <BcCodex as Encoder<Bc>>::Error;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn start_send(mut self: Pin<&mut Self>, item: Bc) -> std::result::Result<(), Self::Error>;
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to create a TcpStream with a connect timeout
|
||||
async fn connect_to(addr: SocketAddr) -> Result<TcpStream> {
|
||||
let socket = match addr {
|
||||
SocketAddr::V4(_) => TcpSocket::new_v4()?,
|
||||
SocketAddr::V6(_) => TcpSocket::new_v6()?,
|
||||
};
|
||||
|
||||
Ok(socket.connect(addr).await?)
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
use super::DiscoveryResult;
|
||||
use crate::bc::codex::BcCodex;
|
||||
use crate::bc::model::*;
|
||||
use crate::bcudp::codex::BcUdpCodex;
|
||||
use crate::bcudp::model::*;
|
||||
use crate::{Credentials, Error, Result};
|
||||
use delegate::delegate;
|
||||
use futures::{
|
||||
sink::{Sink, SinkExt},
|
||||
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
||||
};
|
||||
use log::*;
|
||||
use rand::{seq::SliceRandom, thread_rng};
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{Error as IoError, ErrorKind, Result as IoResult};
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
use tokio::{
|
||||
net::UdpSocket,
|
||||
time::{interval, Duration, Interval},
|
||||
};
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
use tokio_util::{
|
||||
codec::{Decoder, Encoder, Framed},
|
||||
udp::UdpFramed,
|
||||
};
|
||||
|
||||
const MTU: usize = 1350;
|
||||
const UDPDATA_HEADER_SIZE: usize = 20;
|
||||
|
||||
pub(crate) struct UdpSource {
|
||||
inner: Framed<Compat<IntoAsyncRead<UdpPayloadSource>>, BcCodex>,
|
||||
}
|
||||
|
||||
impl UdpSource {
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn new<T: Into<String>, U: Into<String>>(
|
||||
addr: SocketAddr,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<Self> {
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(stream, addr, client_id, camera_id, username, password).await
|
||||
}
|
||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||
mut discovery: DiscoveryResult,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<Self> {
|
||||
// Ensure that the discovery keep alive are all stopped here
|
||||
// We now handle all coms in UdpSource
|
||||
discovery.shutdown().await;
|
||||
Self::new_from_socket(
|
||||
discovery.socket,
|
||||
discovery.addr,
|
||||
discovery.client_id,
|
||||
discovery.camera_id,
|
||||
username,
|
||||
password,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn new_from_socket<T: Into<String>, U: Into<String>>(
|
||||
stream: Arc<UdpSocket>,
|
||||
addr: SocketAddr,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
) -> Result<Self> {
|
||||
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id);
|
||||
let async_read = payload_source.into_async_read().compat();
|
||||
let framed = Framed::new(
|
||||
async_read,
|
||||
BcCodex::new(Credentials::new(username, password)),
|
||||
);
|
||||
|
||||
Ok(Self { inner: framed })
|
||||
}
|
||||
|
||||
// pub(crate) async fn send(&mut self, bc: Bc) -> Result<()> {
|
||||
// self.inner.send(bc).await
|
||||
// }
|
||||
// pub(crate) async fn recv(&mut self) -> Result<Bc> {
|
||||
// loop {
|
||||
// if let Some(result) = self.inner.next().await {
|
||||
// return result;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
impl Stream for UdpSource {
|
||||
type Item = std::result::Result<<BcCodex as Decoder>::Item, <BcCodex as Decoder>::Error>;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Bc> for UdpSource {
|
||||
type Error = <BcCodex as Encoder<Bc>>::Error;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn start_send(mut self: Pin<&mut Self>, item: Bc) -> std::result::Result<(), Self::Error>;
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct BcUdpSource {
|
||||
inner: UdpFramed<BcUdpCodex, Arc<UdpSocket>>,
|
||||
addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl BcUdpSource {
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn new(addr: SocketAddr) -> Result<Self> {
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(stream, addr).await
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub(crate) async fn new_from_discovery(discovery: DiscoveryResult) -> Result<Self> {
|
||||
Self::new_from_socket(discovery.socket, discovery.addr).await
|
||||
}
|
||||
|
||||
pub(crate) async fn new_from_socket(stream: Arc<UdpSocket>, addr: SocketAddr) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: UdpFramed::new(stream, BcUdpCodex::new()),
|
||||
addr,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn into_payload_source(self, client_id: i32, camera_id: i32) -> UdpPayloadSource {
|
||||
UdpPayloadSource {
|
||||
inner: self,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
state: State::Normal,
|
||||
send_buffer: Default::default(),
|
||||
ack_interval: interval(Duration::from_millis(10)), // Offical Client does ack every 10ms
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for BcUdpSource {
|
||||
type Item = Result<(BcUdp, SocketAddr)>;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
||||
type Error = Error;
|
||||
|
||||
delegate! {
|
||||
to Pin::new(&mut self.inner) {
|
||||
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn start_send(mut self: Pin<&mut Self>, item: (BcUdp, SocketAddr)) -> std::result::Result<(), Self::Error>;
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
enum State {
|
||||
Normal, // Normal recieve
|
||||
Flushing, // Used to send ack packets and things in the buffer
|
||||
Closed, // Used to shutdown
|
||||
YieldNow, // Used to ensure we rest between polling packets so as to not starve the runtime
|
||||
}
|
||||
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
inner: BcUdpSource,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
packets_sent: u32,
|
||||
packets_want: u32,
|
||||
sent: BTreeMap<u32, UdpData>,
|
||||
recieved: BTreeMap<u32, Vec<u8>>,
|
||||
state: State,
|
||||
send_buffer: VecDeque<BcUdp>,
|
||||
/// Offical Client does ack every 10ms if we don't also do this the camera
|
||||
/// seems to think we have a poor connection and will abort
|
||||
/// This `ack_interval` controls how ofen we do this
|
||||
ack_interval: Interval,
|
||||
/// Offical Client does resend every 500ms
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
}
|
||||
|
||||
impl UdpPayloadSource {
|
||||
fn build_send_ack(&self) -> UdpAck {
|
||||
if self.packets_want > 0 {
|
||||
let mut first_missing: u32 = self.packets_want;
|
||||
while self.recieved.contains_key(&first_missing) {
|
||||
// Happens if we have recieved but not consumed yet
|
||||
first_missing += 1;
|
||||
}
|
||||
let missing_ids = if let Some(end) = self.recieved.keys().max() {
|
||||
let mut vec = vec![];
|
||||
// From last contiguous packet to last recieved packet
|
||||
// create a payload of `00` (unreceived) and `01` (received)
|
||||
// that can be used to form the `UdpAck` packet
|
||||
for i in (first_missing)..(end + 1) {
|
||||
if self.recieved.contains_key(&i) {
|
||||
vec.push(1)
|
||||
} else {
|
||||
vec.push(0)
|
||||
}
|
||||
}
|
||||
vec
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
UdpAck {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: first_missing - 1, // Last we actually have is first_missing - 1
|
||||
group_id: 0,
|
||||
payload: missing_ids,
|
||||
}
|
||||
} else {
|
||||
UdpAck::empty(self.camera_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_ack(&mut self, ack: UdpAck) {
|
||||
let start = ack.packet_id;
|
||||
if start != 0xffffffff {
|
||||
// -1 means havent got anything yet
|
||||
self.sent.retain(|&k, _| k > start);
|
||||
|
||||
for (idx, &value) in ack.payload.iter().enumerate() {
|
||||
let packet_id = (start + 1) + idx as u32;
|
||||
if value > 0 {
|
||||
self.sent.remove(&packet_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn maintanence(&mut self, cx: &mut Context<'_>) {
|
||||
// Check for periodic resends
|
||||
if self.resend_interval.poll_tick(cx).is_ready() {
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.send_buffer.push_back(BcUdp::Data(resend.clone()));
|
||||
}
|
||||
}
|
||||
if self.ack_interval.poll_tick(cx).is_ready() {
|
||||
let ack = BcUdp::Ack(self.build_send_ack());
|
||||
self.send_buffer.push_back(ack);
|
||||
self.state = State::Flushing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for UdpPayloadSource {
|
||||
type Item = IoResult<Vec<u8>>;
|
||||
|
||||
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
|
||||
let camera_addr = self.inner.addr;
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal => {
|
||||
// this.state = State::YieldNow;
|
||||
// Handle resend events
|
||||
this.maintanence(cx);
|
||||
// Data ready to go
|
||||
if let Some(payload) = this.recieved.remove(&this.packets_want) {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
}
|
||||
// Normal behaviors
|
||||
match this.inner.poll_next_unpin(cx) {
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
payload,
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id >= this.packets_want =>
|
||||
{
|
||||
if packet_id == this.packets_want {
|
||||
this.packets_want += 1;
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
let ack = BcUdp::Ack(this.build_send_ack());
|
||||
this.send_buffer.push_back(ack);
|
||||
return Poll::Ready(Some(Ok(payload)));
|
||||
} else {
|
||||
this.recieved.insert(packet_id, payload);
|
||||
}
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Data(UdpData {
|
||||
connection_id,
|
||||
packet_id,
|
||||
..
|
||||
}),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id
|
||||
&& addr == camera_addr
|
||||
&& packet_id < this.packets_want =>
|
||||
{
|
||||
trace!("UdpPayloadSource.RecievedPacket: Old data: {}", packet_id);
|
||||
}
|
||||
Poll::Ready(Some(Ok((
|
||||
BcUdp::Ack(ack @ UdpAck { connection_id, .. }),
|
||||
addr,
|
||||
)))) if connection_id == this.client_id && addr == camera_addr => {
|
||||
this.handle_ack(ack);
|
||||
// Rather then immediatly flush wait for the next call
|
||||
// this.state = State::Flushing;
|
||||
}
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
return Poll::Ready(Some(Err(IoError::new(ErrorKind::Other, e))));
|
||||
}
|
||||
Poll::Ready(None) => {
|
||||
return Poll::Ready(None);
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
Poll::Ready(Some(Ok((bcudp, addr)))) => {
|
||||
trace!(
|
||||
"UdpPayloadSource.RecievedPacker: UnexpectedData {:?} from {}",
|
||||
bcudp,
|
||||
addr
|
||||
);
|
||||
} // _ => {
|
||||
// trace!("UDPSource.RecievedPacker: Other?");
|
||||
// // Repeat/unintersting packet
|
||||
// }
|
||||
}
|
||||
}
|
||||
State::Flushing => match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
Poll::Ready(Err(e)) => {
|
||||
return Poll::Ready(Some(Err(e)));
|
||||
}
|
||||
Poll::Pending => {
|
||||
return Poll::Pending;
|
||||
}
|
||||
},
|
||||
State::Closed => {
|
||||
return Poll::Ready(Some(Err(IoError::from(ErrorKind::ConnectionAborted))));
|
||||
}
|
||||
State::YieldNow => {
|
||||
this.state = State::Normal;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Vec<u8>> for UdpPayloadSource {
|
||||
type Error = IoError;
|
||||
|
||||
fn poll_ready(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
match this.state {
|
||||
State::Normal | State::YieldNow => this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Flushing => this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e)),
|
||||
State::Closed => Poll::Ready(Err(IoError::from(ErrorKind::ConnectionAborted))),
|
||||
}
|
||||
}
|
||||
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
|
||||
let this = self.get_mut();
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: this.camera_id,
|
||||
packet_id: this.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
this.packets_sent += 1;
|
||||
this.send_buffer.push_back(BcUdp::Data(udp_data));
|
||||
}
|
||||
if let Some(first) = this.send_buffer.pop_front() {
|
||||
if let BcUdp::Data(data) = &first {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((first, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
match this
|
||||
.inner
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let Some(next) = this.send_buffer.pop_front() {
|
||||
match this
|
||||
.inner
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
{
|
||||
Poll::Ready(Ok(())) => {
|
||||
if let BcUdp::Data(data) = &next {
|
||||
let id = data.packet_id;
|
||||
this.sent.insert(id, data.clone());
|
||||
}
|
||||
|
||||
let addr = this.inner.addr;
|
||||
Pin::new(&mut this.inner)
|
||||
.start_send((next, addr))
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))?;
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
}
|
||||
poll => {
|
||||
return poll;
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
let this = self.get_mut();
|
||||
if let State::Closed = this.state {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
|
||||
match this.poll_flush_unpin(cx) {
|
||||
Poll::Ready(Ok(())) => {
|
||||
this.state = State::Closed;
|
||||
this.inner
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
poll => poll,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl futures::AsyncWrite for UdpPayloadSource {
|
||||
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
|
||||
let mut this = self.get_mut();
|
||||
match Pin::new(&mut this).poll_ready(cx) {
|
||||
Poll::Ready(Ok(())) => match Pin::new(&mut this).start_send(buf.to_vec()) {
|
||||
Ok(()) => Poll::Ready(Ok(buf.len())),
|
||||
Err(e) => Poll::Ready(Err(e)),
|
||||
},
|
||||
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
|
||||
Sink::poll_flush(self, cx)
|
||||
}
|
||||
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> {
|
||||
Sink::poll_close(self, cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to create a UdpStream
|
||||
async fn connect() -> Result<UdpSocket> {
|
||||
let mut ports: Vec<u16> = (53500..54000).collect();
|
||||
let mut rng = thread_rng();
|
||||
ports.shuffle(&mut rng);
|
||||
|
||||
let addrs: Vec<_> = ports
|
||||
.iter()
|
||||
.map(|&port| SocketAddr::from(([0, 0, 0, 0], port)))
|
||||
.collect();
|
||||
let socket = UdpSocket::bind(&addrs[..]).await?;
|
||||
|
||||
Ok(socket)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Handles credentials for camera including default reolink password
|
||||
|
||||
use std::convert::TryInto;
|
||||
|
||||
/// Used for caching and supplying the credentials
|
||||
#[derive(Clone)]
|
||||
pub struct Credentials {
|
||||
/// The username to login to the camera with
|
||||
pub username: String,
|
||||
/// The password to use for login. Some camera allow this to be ommited
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Credentials {
|
||||
/// Default credentials for some reolink cameras
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
username: "admin".to_string(),
|
||||
password: Some("123456".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"username", &self.username)
|
||||
.entry(&"password", &"******")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
pub(crate) fn new<T: Into<String>, U: Into<String>>(username: T, password: Option<U>) -> Self {
|
||||
Self {
|
||||
username: username.into(),
|
||||
password: password.map(|t| t.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to make an AES key from the login password and the NONCE
|
||||
/// negotiated during login
|
||||
pub(crate) fn make_aeskey<T: AsRef<str>>(&self, nonce: T) -> [u8; 16] {
|
||||
let key_phrase = format!(
|
||||
"{}-{}",
|
||||
nonce.as_ref(),
|
||||
self.password.clone().unwrap_or_default()
|
||||
);
|
||||
let key_phrase_hash = format!("{:X}\0", md5::compute(key_phrase))
|
||||
.to_uppercase()
|
||||
.into_bytes();
|
||||
key_phrase_hash[0..16].try_into().unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
use super::bc::model::Bc;
|
||||
use crate::NomErrorType;
|
||||
use err_derive::Error;
|
||||
|
||||
/// This is the primary error type of the library
|
||||
#[derive(Debug, Error, Clone)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum Error {
|
||||
/// Underlying IO errors
|
||||
#[error(display = "IO Error: {:?}", _0)]
|
||||
Io(#[error(source)] std::sync::Arc<std::io::Error>),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time coversion: {:?}", _0)]
|
||||
TimeRange(#[error(source)] time::error::ComponentRange),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time parsing")]
|
||||
TimeParse,
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in try from NonZeroInt")]
|
||||
TryFromInt(#[error(source)] std::num::TryFromIntError),
|
||||
|
||||
/// /// Raised when fails to parse time from the camera
|
||||
#[error(display = "Error in time conversion")]
|
||||
TimeTryFrom(#[error(source)] time::error::TryFromParsed),
|
||||
|
||||
/// Raised when a Bc reply was not understood
|
||||
#[error(display = "Communication error")]
|
||||
UnintelligibleReply {
|
||||
/// The Bc packet that was not understood
|
||||
reply: std::sync::Arc<Box<Bc>>,
|
||||
/// The message attached to the error
|
||||
why: &'static str,
|
||||
},
|
||||
|
||||
/// Raised when the camera responds with a status code over than OK
|
||||
#[error(display = "Camera responded with Service Unavaliable")]
|
||||
CameraServiceUnavaliable,
|
||||
|
||||
/// Raised when the camera responds with a status code over than OK during login
|
||||
#[error(display = "Camera responded with Err during login")]
|
||||
CameraLoginFail,
|
||||
|
||||
/// Raised when a connection is dropped.
|
||||
#[error(display = "Dropped connection")]
|
||||
DroppedConnection,
|
||||
|
||||
/// Raised when a connection is dropped during a tokio mpsc TryRecv event
|
||||
#[error(display = "Dropped connection")]
|
||||
DroppedConnectionTry(#[error(source)] tokio::sync::mpsc::error::TryRecvError),
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error(display = "Dropped connection")]
|
||||
BroadcastDroppedConnectionTry(#[error(source)] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error(display = "Send Error")]
|
||||
TokioBcSendError,
|
||||
|
||||
/// Raised when the TIMEOUT is reach
|
||||
#[error(display = "Timeout")]
|
||||
Timeout(#[error(source)] std::sync::Arc<tokio::time::error::Elapsed>),
|
||||
|
||||
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
|
||||
#[error(display = "TimeoutError")]
|
||||
TimeoutError(#[error(source)] tokio::time::error::Error),
|
||||
|
||||
/// Raised when connection is dropped because the timeout is reach
|
||||
#[error(display = "Dropped connection")]
|
||||
TimeoutDisconnected,
|
||||
|
||||
/// Raised when a camera cannot be connected to ay any of the given addresses
|
||||
#[error(display = "Cannot contact camera at given address")]
|
||||
CannotInitCamera,
|
||||
|
||||
/// Raised when failed to login to the camera
|
||||
#[error(display = "Credential error")]
|
||||
AuthFailed,
|
||||
|
||||
/// Raised when the given camera url could not be resolved
|
||||
#[error(display = "Failed to translate camera address")]
|
||||
AddrResolutionError,
|
||||
|
||||
/// Raised non adpcm data is sent to the talk command
|
||||
#[error(display = "Talk data is not ADPCM")]
|
||||
UnknownTalkEncoding,
|
||||
|
||||
/// Raised when dicovery times out waiting for a reply
|
||||
#[error(display = "Timed out while waiting for camera reply")]
|
||||
DiscoveryTimeout,
|
||||
|
||||
/// Raised during a (de)seralisation error
|
||||
#[error(display = "Cookie GenError")]
|
||||
GenError(#[error(source)] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: u16,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
#[error(display = "Simultaneous subscription, {}", _0)]
|
||||
SimultaneousSubscriptionId {
|
||||
/// The message number that was subscribed to
|
||||
msg_id: u32,
|
||||
},
|
||||
|
||||
/// Raised when a new encyrption byte is observed
|
||||
#[error(display = "Unknown encryption: {:x?}", _0)]
|
||||
UnknownEncryption(usize),
|
||||
|
||||
/// Raised when the camera cannot be found
|
||||
#[error(display = "Camera Not Findable")]
|
||||
ConnectionUnavaliable,
|
||||
|
||||
/// Raised when the subscription id dropped too soon
|
||||
#[error(display = "Dropped Subscriber")]
|
||||
DroppedSubscriber,
|
||||
|
||||
/// Raised when a unknown connection ID attempts to connect with us over UDP
|
||||
#[error(display = "Connection with unknown connectionID: {:?}", _0)]
|
||||
UnknownConnectionId(i32),
|
||||
|
||||
/// Raised when a unknown SocketAddr attempts to connect with us over UDP
|
||||
#[error(display = "Connection from unknown source: {:?}", _0)]
|
||||
UnknownSource(std::net::SocketAddr),
|
||||
|
||||
/// Raised when the IP/Hostname cannot be understood
|
||||
#[error(display = "Could not parse as IP")]
|
||||
AddrParseError(#[error(source)] std::net::AddrParseError),
|
||||
|
||||
/// Raised when a relay connection is not possible
|
||||
/// usually happens if the camera has not contacted reolink yet
|
||||
#[error(display = "Cannot perform relay connection with this camera")]
|
||||
NoDmap,
|
||||
|
||||
/// Raised when a dev connection is not possible
|
||||
/// usually happens if the camera has not contacted reolink yet
|
||||
#[error(display = "Cannot perform lookup with this camera against reolink servers")]
|
||||
NoDev,
|
||||
|
||||
/// Raised when cannot determine local IP address
|
||||
#[error(display = "Local IP address is unknown: {}", _0)]
|
||||
LocalIpError(#[error(source)] std::sync::Arc<local_ip_address::Error>),
|
||||
|
||||
/// Raised when a discovery fails to be accepted by the register
|
||||
#[error(display = "Register refuses to accept us")]
|
||||
RegisterError,
|
||||
|
||||
/// Raised when a the relay terminates the connection by sending a R2C_DISC
|
||||
#[error(display = "Relay terminated the connection")]
|
||||
RelayTerminate,
|
||||
|
||||
/// Raised when a the camera terminates the connection by sending a D2C_DISC
|
||||
#[error(display = "Camera terminated the connection")]
|
||||
CameraTerminate,
|
||||
|
||||
/// Raised when the stream is not enough to complete a message
|
||||
#[error(display = "Nom Parsing incomplete: {}", _0)]
|
||||
NomIncomplete(usize),
|
||||
|
||||
/// Raised when a stream cannot be decoded
|
||||
#[error(display = "Nom Parsing error: {}", _0)]
|
||||
NomError(String),
|
||||
|
||||
/// Raised when a camera/user lacks an ability
|
||||
#[error(
|
||||
display = "Missing ability: {} with {} permission has only {}",
|
||||
name,
|
||||
requested,
|
||||
actual
|
||||
)]
|
||||
MissingAbility {
|
||||
/// Name of the ability
|
||||
name: String,
|
||||
/// Requested permission (read/write)
|
||||
requested: String,
|
||||
/// Actual permission (read/write/none)
|
||||
actual: String,
|
||||
},
|
||||
|
||||
/// Raised when a thread panics
|
||||
#[error(display = "Thread panicked")]
|
||||
JoinError(#[error(source)] std::sync::Arc<tokio::task::JoinError>),
|
||||
|
||||
/// A generic catch all error
|
||||
#[error(display = "Other error: {}", _0)]
|
||||
Other(&'static str),
|
||||
|
||||
/// A generic catch all error
|
||||
#[error(display = "Other error: {}", _0)]
|
||||
OtherString(String),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(k: std::io::Error) -> Self {
|
||||
Error::Io(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
|
||||
fn from(_: tokio::sync::mpsc::error::SendError<T>) -> Self {
|
||||
Error::TokioBcSendError
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<tokio_util::sync::PollSendError<T>> for Error {
|
||||
fn from(_: tokio_util::sync::PollSendError<T>) -> Self {
|
||||
Error::TokioBcSendError
|
||||
}
|
||||
}
|
||||
|
||||
impl From<cookie_factory::GenError> for Error {
|
||||
fn from(k: cookie_factory::GenError) -> Self {
|
||||
Error::GenError(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<local_ip_address::Error> for Error {
|
||||
fn from(k: local_ip_address::Error) -> Self {
|
||||
Error::LocalIpError(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::task::JoinError> for Error {
|
||||
fn from(k: tokio::task::JoinError) -> Self {
|
||||
Error::JoinError(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<tokio::time::error::Elapsed> for Error {
|
||||
fn from(k: tokio::time::error::Elapsed) -> Self {
|
||||
Error::Timeout(std::sync::Arc::new(k))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<nom::Err<NomErrorType<'a>>> for Error {
|
||||
fn from(k: nom::Err<NomErrorType<'a>>) -> Self {
|
||||
match k {
|
||||
nom::Err::Error(e) => Error::NomError(format!("Nom Error: {:X?}", e)),
|
||||
nom::Err::Failure(e) => Error::NomError(format!("Nom Error: {:X?}", e)),
|
||||
nom::Err::Incomplete(nom::Needed::Size(amount)) => Error::NomIncomplete(amount.get()),
|
||||
nom::Err::Incomplete(nom::Needed::Unknown) => Error::NomIncomplete(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handller to respond to keep alive messages
|
||||
/// These messages are sent by the camera so we listen to
|
||||
/// a message ID rather than setting a message number and
|
||||
/// responding to it
|
||||
pub async fn keepalive(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_UDP_KEEP_ALIVE, |bc| {
|
||||
Some(Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UDP_KEEP_ALIVE,
|
||||
channel_id: bc.meta.channel_id,
|
||||
msg_num: bc.meta.msg_num,
|
||||
stream_type: bc.meta.stream_type,
|
||||
response_code: 200,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [LedState] xml which contains the LED status of the camera
|
||||
pub async fn get_ledstate(&self) -> Result<LedState> {
|
||||
self.has_ability_ro("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_LED_STATUS,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
led_state: Some(ledstate),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(ledstate)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected LEDState xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the led lights using the [LedState] xml
|
||||
pub async fn set_ledstate(&self, mut led_state: LedState) -> Result<()> {
|
||||
self.has_ability_rw("ledState").await?;
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
// led_version is a field recieved from the camera but not sent
|
||||
// we set to None to ensure we don't send it to the camera
|
||||
led_state.led_version = None;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SET_LED_STATUS,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
led_state: Some(led_state),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the LEDState xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to control the IR LED lights
|
||||
///
|
||||
/// This is for the RED IR lights that can come on automaitcally
|
||||
/// during low light.
|
||||
pub async fn irled_light_set(&self, state: LightState) -> Result<()> {
|
||||
let mut led_state = self.get_ledstate().await?;
|
||||
led_state.state = match state {
|
||||
LightState::On => "open".to_string(),
|
||||
LightState::Off => "close".to_string(),
|
||||
LightState::Auto => "auto".to_string(),
|
||||
};
|
||||
self.set_ledstate(led_state).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This is a convience function to control the LED light
|
||||
/// True is on and false is off
|
||||
///
|
||||
/// This is for the little blue on light of some camera
|
||||
pub async fn led_light_set(&self, state: bool) -> Result<()> {
|
||||
let mut led_state = self.get_ledstate().await?;
|
||||
led_state.light_state = match state {
|
||||
true => "open".to_string(),
|
||||
false => "close".to_string(),
|
||||
};
|
||||
self.set_ledstate(led_state).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// This is pased to `irled_light_set` to turn it on, off or set it to light based auto
|
||||
pub enum LightState {
|
||||
/// Turn the light on
|
||||
On,
|
||||
/// Turn the light off
|
||||
Off,
|
||||
/// Set the light to light based auto
|
||||
Auto,
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::{md5_string, BcCamera, Error, Result, Truncate, ZeroLast};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
/// The requested encryption level to request
|
||||
/// to the camera
|
||||
///
|
||||
/// The camera may use a lower one depending on support
|
||||
///
|
||||
/// Note the reolink camera only encrypt the control messages
|
||||
/// the camera feed is always accessible
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum MaxEncryption {
|
||||
/// No encryption
|
||||
None,
|
||||
/// BCEncrypt is a simple XOR algortirhm with a fixed key
|
||||
/// used in many older models
|
||||
BcEncrypt,
|
||||
/// AES is used in newer model
|
||||
Aes,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login(&self) -> Result<DeviceInfo> {
|
||||
self.login_with_maxenc(MaxEncryption::Aes).await
|
||||
}
|
||||
/// Login to the camera.
|
||||
///
|
||||
/// This should be called before most other commands
|
||||
pub async fn login_with_maxenc(&self, max_encryption: MaxEncryption) -> Result<DeviceInfo> {
|
||||
let device_info;
|
||||
// This { is here due to the connection and set_credentials both requiring a mutable borrow
|
||||
{
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_login = connection.subscribe(msg_num).await?;
|
||||
|
||||
// Login flow is: Send legacy login message, expect back a modern message with Encryption
|
||||
// details. Then, re-send the login as a modern login message. Expect back a device info
|
||||
// congratulating us on logging in.
|
||||
|
||||
// In the legacy scheme, username/password are MD5'd if they are encrypted (which they need
|
||||
// to be to "upgrade" to the modern login flow), then the hex of the MD5 is sent.
|
||||
// Note: I suspect there may be a buffer overflow opportunity in the firmware since in the
|
||||
// Baichuan library, these strings are capped at 32 bytes with a null terminator. This
|
||||
// could also be a mistake in the library, the effect being it only compares 31 chars, not 32.
|
||||
let md5_username = md5_string(&credentials.username, ZeroLast);
|
||||
let md5_password = credentials
|
||||
.password
|
||||
.as_ref()
|
||||
.map(|p| md5_string(p, ZeroLast))
|
||||
.unwrap_or_else(|| EMPTY_LEGACY_PASSWORD.to_owned());
|
||||
|
||||
let enc_byte = match max_encryption {
|
||||
MaxEncryption::None => 0xdc00,
|
||||
MaxEncryption::BcEncrypt => 0xdc01,
|
||||
MaxEncryption::Aes => 0xdc02,
|
||||
};
|
||||
let legacy_login = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_LOGIN,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: enc_byte,
|
||||
class: 0x6514,
|
||||
},
|
||||
body: BcBody::LegacyMsg(LegacyMsg::LoginMsg {
|
||||
username: md5_username,
|
||||
password: md5_password,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_login.send(legacy_login).await?;
|
||||
|
||||
let legacy_reply = sub_login.recv().await?;
|
||||
|
||||
let nonce;
|
||||
match &legacy_reply.body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
encryption: Some(encryption),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) => {
|
||||
nonce = &encryption.nonce;
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(legacy_reply)),
|
||||
why: "Expected an Encryption message back",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// In the modern login flow, the username/password are concat'd with the server's nonce
|
||||
// string, then MD5'd, then the hex of this MD5 is sent as the password. This nonce
|
||||
// prevents replay attacks if the server were to require modern flow, but not rainbow table
|
||||
// attacks (since the plain user/password MD5s have already been sent). The upshot is that
|
||||
// you should use a very strong random password that is not found in a rainbow table and
|
||||
// not feasibly crackable with John the Ripper.
|
||||
|
||||
let modern_password = credentials.password.clone().unwrap_or_default();
|
||||
let concat_username = format!("{}{}", credentials.username, nonce);
|
||||
let concat_password = format!("{}{}", modern_password, nonce);
|
||||
let md5_username = md5_string(&concat_username, Truncate);
|
||||
let md5_password = md5_string(&concat_password, Truncate);
|
||||
|
||||
let modern_login = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_LOGIN,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
BcXml {
|
||||
login_user: Some(LoginUser {
|
||||
version: xml_ver(),
|
||||
user_name: md5_username,
|
||||
password: md5_password,
|
||||
user_ver: 1,
|
||||
}),
|
||||
login_net: Some(LoginNet::default()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
sub_login.send(modern_login).await?;
|
||||
let modern_reply = sub_login.recv().await?;
|
||||
if modern_reply.meta.response_code != 200 {
|
||||
return Err(Error::CameraLoginFail);
|
||||
}
|
||||
|
||||
match modern_reply.body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
device_info: Some(info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) => {
|
||||
// Login succeeded!
|
||||
self.logged_in.store(true, Ordering::Relaxed);
|
||||
device_info = info;
|
||||
}
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}) => return Err(Error::AuthFailed),
|
||||
_ => {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(legacy_reply)),
|
||||
why: "Expected a DeviceInfo message back from login",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Populate the list of abilities this user has with the camera
|
||||
log::debug!("Populating abilities");
|
||||
self.polulate_abilities().await?;
|
||||
Ok(device_info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
impl BcCamera {
|
||||
/// Logout from the camera
|
||||
pub async fn logout(&self) -> Result<()> {
|
||||
if self.logged_in.load(Ordering::Relaxed) {
|
||||
let credentials = self.get_credentials();
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let sub_logout = connection.subscribe(msg_num).await?;
|
||||
|
||||
let username = credentials.username.clone();
|
||||
let password = credentials.password.as_ref().cloned().unwrap_or_default();
|
||||
|
||||
let modern_logout = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_LOGOUT,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
BcXml {
|
||||
login_user: Some(LoginUser {
|
||||
version: xml_ver(),
|
||||
user_name: username,
|
||||
password,
|
||||
user_ver: 1,
|
||||
}),
|
||||
login_net: Some(LoginNet::default()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
sub_logout.send(modern_logout).await?;
|
||||
}
|
||||
self.logged_in.store(false, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc::{channel, error::TryRecvError, Receiver};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
/// Motion Status that the callback can send
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum MotionStatus {
|
||||
/// Sent when motion is first detected
|
||||
Start(Instant),
|
||||
/// Sent when motion stops
|
||||
Stop(Instant),
|
||||
/// Sent when an Alarm about something other than motion was received
|
||||
NoChange(Instant),
|
||||
}
|
||||
|
||||
/// A handle on current motion related events comming from the camera
|
||||
///
|
||||
/// When this object is dropped the motion events are stopped
|
||||
pub struct MotionData {
|
||||
handle: JoinSet<Result<()>>,
|
||||
rx: Receiver<Result<MotionStatus>>,
|
||||
last_update: MotionStatus,
|
||||
}
|
||||
|
||||
impl MotionData {
|
||||
/// Get if motion has been detected. Returns None if
|
||||
/// no motion data has yet been recieved from the camera
|
||||
///
|
||||
/// An error is raised if the motion connection to the camera is dropped
|
||||
pub fn motion_detected(&mut self) -> Result<Option<bool>> {
|
||||
self.consume_motion_events()?;
|
||||
Ok(match &self.last_update {
|
||||
MotionStatus::Start(_) => Some(true),
|
||||
MotionStatus::Stop(_) => Some(false),
|
||||
MotionStatus::NoChange(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Get if motion has been detected within given duration. Returns None if
|
||||
/// no motion data has yet been recieved from the camera
|
||||
///
|
||||
/// An error is raised if the motion connection to the camera is dropped
|
||||
pub fn motion_detected_within(&mut self, duration: Duration) -> Result<Option<bool>> {
|
||||
self.consume_motion_events()?;
|
||||
Ok(match &self.last_update {
|
||||
MotionStatus::Start(_) => Some(true),
|
||||
MotionStatus::Stop(time) => Some((Instant::now() - *time) < duration),
|
||||
MotionStatus::NoChange(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Consume the motion events diretly
|
||||
///
|
||||
/// An error is raised if the motion connection to the camera is dropped
|
||||
pub fn consume_motion_events(&mut self) -> Result<Vec<MotionStatus>> {
|
||||
let mut results: Vec<MotionStatus> = vec![];
|
||||
loop {
|
||||
match self.rx.try_recv() {
|
||||
Ok(motion) => results.push(motion?),
|
||||
Err(TryRecvError::Empty) => break,
|
||||
Err(e) => return Err(Error::from(e)),
|
||||
}
|
||||
}
|
||||
if let Some(last) = results.last() {
|
||||
self.last_update = *last;
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Await a new motion event
|
||||
///
|
||||
///
|
||||
pub async fn next_motion(&mut self) -> Result<MotionStatus> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
if let Some(last) = motions.last() {
|
||||
Ok(*last)
|
||||
} else if let Some(moition) = self.rx.recv().await {
|
||||
let moition = moition?;
|
||||
self.last_update = moition;
|
||||
Ok(moition)
|
||||
} else {
|
||||
Err(Error::Other("Motion dropped"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the motion to stop
|
||||
///
|
||||
/// It must be stopped for at least the given duration
|
||||
pub async fn await_stop(&mut self, duration: Duration) -> Result<()> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let Some(MotionStatus::Stop(time)) = last_motion {
|
||||
// In stop state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
} else {
|
||||
// Schedule a sleep or wait for motion to start
|
||||
let remaining_sleep = duration - (Instant::now() - time);
|
||||
let result = tokio::select! {
|
||||
_ = tokio::time::sleep(remaining_sleep) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Start(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the motion to start
|
||||
///
|
||||
/// The motion must have a minimum duration as given
|
||||
pub async fn await_start(&mut self, duration: Duration) -> Result<()> {
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let Some(MotionStatus::Start(time)) = last_motion {
|
||||
// In start state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
} else {
|
||||
// Schedule a sleep or wait for motion to stop
|
||||
let result = tokio::select! {
|
||||
_ = tokio::time::sleep(duration - (Instant::now() - time)) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Stop(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// This message tells the camera to send the motion events to us
|
||||
/// Which are the recieved on msgid 33
|
||||
async fn start_motion_query(&self) -> Result<u16> {
|
||||
self.has_ability_rw("motion").await?;
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_MOTION_REQUEST,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(msg_num)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the request to start motion",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This returns a data structure which can be used to
|
||||
/// query motion events
|
||||
pub async fn listen_on_motion(&self) -> Result<MotionData> {
|
||||
let msg_num = self.start_motion_query().await?;
|
||||
|
||||
let connection = self.get_connection();
|
||||
|
||||
// After start_motion_query (MSG_ID 31) the camera sends motion messages
|
||||
// when whenever motion is detected.
|
||||
let (tx, rx) = channel(20);
|
||||
|
||||
let mut set = JoinSet::new();
|
||||
let channel_id = self.channel_id;
|
||||
set.spawn(async move {
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
let msg = sub.recv().await;
|
||||
let status = match msg {
|
||||
Ok(motion_msg) => {
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
alarm_event_list: Some(alarm_event_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = motion_msg.body
|
||||
{
|
||||
let mut result = MotionStatus::NoChange(Instant::now());
|
||||
for alarm_event in &alarm_event_list.alarm_events {
|
||||
if alarm_event.channel_id == channel_id {
|
||||
if alarm_event.status == "MD" {
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else if alarm_event.status == "none" {
|
||||
result = MotionStatus::Stop(Instant::now());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Ok(MotionStatus::NoChange(Instant::now()))
|
||||
}
|
||||
}
|
||||
// On connection drop we stop
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
if tx.send(status).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Ok(MotionData {
|
||||
handle: set,
|
||||
rx,
|
||||
last_update: MotionStatus::NoChange(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MotionData {
|
||||
fn drop(&mut self) {
|
||||
self.handle.abort_all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Ping the camera will either return Ok(()) which means a sucess reply
|
||||
/// or error
|
||||
pub async fn ping(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_ping = connection.subscribe(msg_num).await?;
|
||||
|
||||
let ping = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PING,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
sub_ping.send(ping).await?;
|
||||
|
||||
sub_ping.recv().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use tokio::time::{interval, Duration};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [RfAlarmCfg] xml which contains the PIR status of the camera
|
||||
pub async fn get_pirstate(&self) -> Result<RfAlarmCfg> {
|
||||
self.has_ability_ro("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let mut reties: usize = 0;
|
||||
let mut retry_interval = interval(Duration::from_millis(500));
|
||||
loop {
|
||||
retry_interval.tick().await;
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PIR_ALARM,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
rf_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code == 400 {
|
||||
// Retryable
|
||||
if reties < 5 {
|
||||
reties += 1;
|
||||
continue;
|
||||
} else {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
} else if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
} else {
|
||||
// Valid message with response_code == 200
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
rf_alarm_cfg: Some(pirstate),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
return Ok(pirstate);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected PirSate xml but it was not recieved",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the PIR sensor using the [RfAlarmCfg] xml
|
||||
pub async fn set_pirstate(&self, rf_alarm_cfg: RfAlarmCfg) -> Result<()> {
|
||||
self.has_ability_rw("rfAlarm").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_START_PIR_ALARM,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
rf_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
rf_alarm_cfg: Some(rf_alarm_cfg),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the RfAlarmCfg xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// This is a convience function to control the PIR status
|
||||
/// True is on and false is off
|
||||
pub async fn pir_set(&self, state: bool) -> Result<()> {
|
||||
let mut pir_state = self.get_pirstate().await?;
|
||||
// println!("{:?}", pir_state);
|
||||
pir_state.enable = match state {
|
||||
true => 1,
|
||||
false => 0,
|
||||
};
|
||||
self.set_pirstate(pir_state).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn PIR ON or OFF
|
||||
pub enum PirState {
|
||||
/// Turn the PIR on
|
||||
On,
|
||||
/// Turn the PIR off
|
||||
Off,
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
/// Directions used for Ptz
|
||||
pub enum Direction {
|
||||
/// To move the camera Up
|
||||
Up,
|
||||
/// To move the camera Down
|
||||
Down,
|
||||
/// To move the camera Left
|
||||
Left,
|
||||
/// To move the camera Right
|
||||
Right,
|
||||
/// To zoom the camera In (may be done with cropping depending on camera model)
|
||||
In,
|
||||
/// To zoom the camera Out (may be done with cropping depending on camera model)
|
||||
Out,
|
||||
/// To stop currently active PTZ command
|
||||
Stop,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Send a PTZ message to the camera
|
||||
pub async fn send_ptz(&self, direction: Direction, amount: f32) -> Result<()> {
|
||||
self.has_ability_rw("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection.subscribe(msg_num).await?;
|
||||
|
||||
let direction_str = match direction {
|
||||
Direction::Up => "up",
|
||||
Direction::Down => "down",
|
||||
Direction::Left => "left",
|
||||
Direction::Right => "right",
|
||||
Direction::In => {
|
||||
todo!()
|
||||
}
|
||||
Direction::Out => {
|
||||
todo!()
|
||||
}
|
||||
Direction::Stop => "stop",
|
||||
}
|
||||
.to_string();
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PTZ_CONTROL,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_control: Some(PtzControl {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
speed: amount,
|
||||
command: direction_str,
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(send).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the PtzControl xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
/// Specifies the phone type for the push notification
|
||||
pub enum PhoneType {
|
||||
/// Specify that this is an ios push notfication
|
||||
///
|
||||
/// In this case the token must be the APNS
|
||||
Ios,
|
||||
/// Specify that this is an andriod push notfication
|
||||
///
|
||||
/// In this case the token must firebase cloud messaging token
|
||||
Android,
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
/// Convenience method for andriod of `[send_pushinfo]`
|
||||
pub async fn send_pushinfo_android(&self, token: &str, client_id: &str) -> Result<()> {
|
||||
self.send_pushinfo(token, client_id, PhoneType::Android)
|
||||
.await
|
||||
}
|
||||
/// Convenience method for andriod of `[send_pushinfo]`
|
||||
pub async fn send_pushinfo_ios(&self, token: &str, client_id: &str) -> Result<()> {
|
||||
self.send_pushinfo(token, client_id, PhoneType::Ios).await
|
||||
}
|
||||
/// Send the push info to regsiter for push notfications
|
||||
pub async fn send_pushinfo(
|
||||
&self,
|
||||
token: &str,
|
||||
client_id: &str,
|
||||
phone_type: PhoneType,
|
||||
) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let phone_type_str = match phone_type {
|
||||
PhoneType::Ios => "reo_iphone",
|
||||
PhoneType::Android => "reo_fcm",
|
||||
};
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PUSH_INFO,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
push_info: Some(PushInfo {
|
||||
token: token.to_owned(),
|
||||
phone_type: phone_type_str.to_owned(),
|
||||
client_id: client_id.to_owned(),
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Reboot the camera
|
||||
pub async fn reboot(&self) -> Result<()> {
|
||||
self.has_ability_rw("reboot").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_REBOOT,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the reboot command",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! This is a helper module to resolve either to a UID or a SockerAddr
|
||||
|
||||
use log::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
io::Error,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs},
|
||||
};
|
||||
|
||||
/// Select permitted discovery methods
|
||||
///
|
||||
/// This is used for UID lookup, it is unused with
|
||||
/// TPC/known ip address cameras
|
||||
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum DiscoveryMethods {
|
||||
/// Forbid all discovery methods. Only TCP connections with known addresses will work
|
||||
#[serde(alias = "none")]
|
||||
None,
|
||||
/// Allow local discovery on the local network using broadcasts
|
||||
/// This method does NOT contact reolink servers
|
||||
#[serde(alias = "local")]
|
||||
Local,
|
||||
/// Allow contact with the reolink servers to learn the ip address but DO NOT
|
||||
/// allow the camera/clinet to communicate through the reolink servers.
|
||||
///
|
||||
/// **This also enabled `Local` discovery**
|
||||
#[serde(alias = "remote")]
|
||||
Remote,
|
||||
/// Allow contact with the reolink servers to learn the ip address and map the connection
|
||||
/// from dev to client through those servers.
|
||||
///
|
||||
/// **This also enabled `Local` and `Remote` discovery**
|
||||
#[serde(alias = "map")]
|
||||
Map,
|
||||
/// Allow contact with the reolink servers to learn the ip address and relay the connection
|
||||
/// client to dev through those servers.
|
||||
///
|
||||
/// **This also enabled `Local`, `Map` and `Remote` discovery**
|
||||
#[serde(alias = "relay")]
|
||||
Relay,
|
||||
#[doc(hidden)]
|
||||
#[serde(alias = "debug")]
|
||||
/// Used for debugging it is set to whatever the dev is currently testing
|
||||
Debug,
|
||||
}
|
||||
|
||||
/// Used to return either the SocketAddr or the UID
|
||||
pub enum SocketAddrOrUid {
|
||||
/// When the result is a addr it will be this
|
||||
SocketAddr(SocketAddr),
|
||||
/// When the result is a UID
|
||||
Uid(String, Option<Vec<SocketAddr>>, DiscoveryMethods),
|
||||
}
|
||||
|
||||
/// An extension of ToSocketAddrs that will also resolve to a camera UID
|
||||
pub trait ToSocketAddrsOrUid: ToSocketAddrs {
|
||||
/// The return type of the function
|
||||
type UidIter: Iterator<Item = SocketAddrOrUid>;
|
||||
|
||||
/// This handles the actual resolution. It should first check the
|
||||
/// normal [.to_socket_addrs()] and if that fails it should check
|
||||
/// if it looks like a uid
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error>;
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for SocketAddr {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for str {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
match self.to_socket_addrs() {
|
||||
Ok(addrs) => Ok(addrs
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()),
|
||||
Err(e) => {
|
||||
debug!("Trying as uid");
|
||||
let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap();
|
||||
if re.is_match(self) {
|
||||
Ok(vec![SocketAddrOrUid::Uid(
|
||||
self.to_string(),
|
||||
None,
|
||||
DiscoveryMethods::Local,
|
||||
)]
|
||||
.into_iter())
|
||||
} else {
|
||||
debug!("Regex fails {:?} => {:?} ", re, self);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for String {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
match self.to_socket_addrs() {
|
||||
Ok(addrs) => Ok(addrs
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter()),
|
||||
Err(e) => {
|
||||
debug!("Trying as uid");
|
||||
let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap();
|
||||
if re.is_match(self) {
|
||||
Ok(vec![SocketAddrOrUid::Uid(
|
||||
self.to_string(),
|
||||
None,
|
||||
DiscoveryMethods::Local,
|
||||
)]
|
||||
.into_iter())
|
||||
} else {
|
||||
debug!("Regex fails {:?} => {:?} ", re, self);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for (&str, u16) {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for (IpAddr, u16) {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for (String, u16) {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for (Ipv4Addr, u16) {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for (Ipv6Addr, u16) {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for SocketAddrV4 {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToSocketAddrsOrUid for SocketAddrV6 {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] {
|
||||
type UidIter = std::vec::IntoIter<SocketAddrOrUid>;
|
||||
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
Ok(self
|
||||
.to_socket_addrs()?
|
||||
.map(SocketAddrOrUid::SocketAddr)
|
||||
.collect::<Vec<_>>()
|
||||
.into_iter())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ToSocketAddrsOrUid + ?Sized> ToSocketAddrsOrUid for &T {
|
||||
type UidIter = T::UidIter;
|
||||
fn to_socket_addrs_or_uid(&self) -> Result<Self::UidIter, Error> {
|
||||
(**self).to_socket_addrs_or_uid()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::{
|
||||
bc::{model::*, xml::*},
|
||||
bcmedia::model::*,
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
use tokio::task::{self, JoinHandle};
|
||||
|
||||
/// The stream names supported by BC
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum StreamKind {
|
||||
/// This is the HD stream
|
||||
Main,
|
||||
/// This is the SD stream
|
||||
Sub,
|
||||
/// This stream represents a balance between SD and HD
|
||||
///
|
||||
/// It is only avaliable on some camera. If the camera dosen't
|
||||
/// support it the stream will be the same as the SD stream
|
||||
Extern,
|
||||
}
|
||||
|
||||
/// A handle on currently streaming data
|
||||
///
|
||||
/// The data can be pulled using `get_data` which returns raw BcMedia packets
|
||||
///
|
||||
/// When this object is dropped the streaming is stopped
|
||||
pub struct StreamData {
|
||||
handle: Option<JoinHandle<Result<()>>>,
|
||||
rx: Receiver<Result<BcMedia>>,
|
||||
abort_handle: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl StreamData {
|
||||
/// Pull data from the camera's buffer
|
||||
/// This returns raw BcMedia packets
|
||||
pub async fn get_data(&mut self) -> Result<Result<BcMedia>> {
|
||||
if let Some(handle) = self.handle.as_mut() {
|
||||
if handle.is_finished() {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
handle.await??;
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
} else {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
return Err(Error::DroppedConnection);
|
||||
}
|
||||
// debug!("StreamData: Get");
|
||||
match self.rx.recv().await {
|
||||
Some(data) => {
|
||||
// debug!("StreamData: Got");
|
||||
Ok(data)
|
||||
}
|
||||
None => {
|
||||
// debug!("StreamData: Drop");
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
Err(Error::DroppedConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
self.abort_handle.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Starts the video stream
|
||||
///
|
||||
/// The returned object manages the data stream, when it is dropped
|
||||
/// the video stop signal is sent to the camera
|
||||
///
|
||||
/// To pull frames from the camera's buffer use `recv_data` on the returned object
|
||||
///
|
||||
/// The buffer_size represents number of compete messages so 1 would be one complete message
|
||||
/// which may be a single audio frame or a whole video key frame. If 0 a default of 100 is used
|
||||
///
|
||||
/// A value of scrict=true will mean that the stream will error if the underlying stream is not
|
||||
/// as expected
|
||||
pub async fn start_video(
|
||||
&self,
|
||||
stream: StreamKind,
|
||||
mut buffer_size: usize,
|
||||
strict: bool,
|
||||
) -> Result<StreamData> {
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
let abort_handle = Arc::new(AtomicBool::new(false));
|
||||
let abort_handle_thread = abort_handle.clone();
|
||||
|
||||
if buffer_size == 0 {
|
||||
buffer_size = 100;
|
||||
}
|
||||
let (tx, rx) = channel(buffer_size);
|
||||
let channel_id = self.channel_id;
|
||||
|
||||
let handle = task::spawn(async move {
|
||||
tokio::task::yield_now().await;
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
// - subStream always has a value of 1
|
||||
// - There is no externStram
|
||||
// On a B800:
|
||||
// - mainStream is 0
|
||||
// - subStream is 0
|
||||
// - externStream is 0
|
||||
let stream_code = match stream {
|
||||
StreamKind::Main => 0,
|
||||
StreamKind::Sub => 1,
|
||||
StreamKind::Extern => 0,
|
||||
};
|
||||
|
||||
// Theses are the numbers used with the offical client
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
// - subStream always has a value of 1
|
||||
// - There is no externStram
|
||||
// On a B800:
|
||||
// - mainStream is 0
|
||||
// - subStream is 256
|
||||
// - externStram is 1024
|
||||
let handle = match stream {
|
||||
StreamKind::Main => 0,
|
||||
StreamKind::Sub => 256,
|
||||
StreamKind::Extern => 1024,
|
||||
};
|
||||
|
||||
let stream_name = match stream {
|
||||
StreamKind::Main => "mainStream",
|
||||
StreamKind::Sub => "subStream",
|
||||
StreamKind::Extern => "externStream",
|
||||
}
|
||||
.to_string();
|
||||
|
||||
let start_video = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_VIDEO,
|
||||
channel_id,
|
||||
msg_num,
|
||||
stream_type: stream_code,
|
||||
response_code: 0,
|
||||
class: 0x6414, // IDK why
|
||||
},
|
||||
BcXml {
|
||||
preview: Some(Preview {
|
||||
version: xml_ver(),
|
||||
channel_id,
|
||||
handle,
|
||||
stream_type: Some(stream_name),
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
sub_video.send(start_video).await?;
|
||||
|
||||
let msg = sub_video.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the stream start command.",
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let mut media_sub = sub_video.bcmedia_stream(strict);
|
||||
|
||||
while !abort_handle_thread.load(Ordering::Relaxed) {
|
||||
// debug!("Stream: Get");
|
||||
if let Some(bc_media) = media_sub.next().await {
|
||||
// debug!("Stream: Got");
|
||||
// We now have a complete interesting packet. Send it to on the callback
|
||||
// debug!("Stream: Send");
|
||||
if tx.send(bc_media).await.is_err() {
|
||||
// debug!("Stream: Dropped");
|
||||
break; // Connection dropped
|
||||
}
|
||||
// debug!("Stream: Sent");
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// debug!("Stream: Stopping");
|
||||
let stop_video = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
channel_id,
|
||||
msg_num,
|
||||
stream_type: stream_code,
|
||||
response_code: 0,
|
||||
class: 0x6414, // IDK why
|
||||
},
|
||||
BcXml {
|
||||
preview: Some(Preview {
|
||||
version: xml_ver(),
|
||||
channel_id,
|
||||
handle,
|
||||
stream_type: None,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
// debug!("Stream: Send Stop");
|
||||
sub_video.send(stop_video).await?;
|
||||
// debug!("Stream: Sent Stop");
|
||||
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
let msg = sub_video.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200,
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
..
|
||||
} = msg.meta {
|
||||
return Ok(());
|
||||
}
|
||||
else if let BcMeta {
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
..
|
||||
} = msg.meta {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
}
|
||||
} => v,
|
||||
_ = tokio::time::sleep(tokio::time::Duration::from_secs(2)) => {Ok(())},
|
||||
}?;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
Ok(StreamData {
|
||||
handle: Some(handle),
|
||||
rx,
|
||||
abort_handle,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stop a camera from sending more stream data.
|
||||
pub async fn stop_video(&self, stream: StreamKind) -> Result<()> {
|
||||
self.has_ability_rw("preview").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(msg_num).await?;
|
||||
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
// - subStream always has a value of 1
|
||||
// - There is no externStram
|
||||
// On a B800:
|
||||
// - mainStream is 0
|
||||
// - subStream is 0
|
||||
// - externStream is 0
|
||||
let stream_code = match stream {
|
||||
StreamKind::Main => 0,
|
||||
StreamKind::Sub => 1,
|
||||
StreamKind::Extern => 0,
|
||||
};
|
||||
|
||||
// Theses are the numbers used with the offical client
|
||||
// On an E1 and swann cameras:
|
||||
// - mainStream always has a value of 0
|
||||
// - subStream always has a value of 1
|
||||
// - There is no externStram
|
||||
// On a B800:
|
||||
// - mainStream is 0
|
||||
// - subStream is 256
|
||||
// - externStram is 1024
|
||||
let handle = match stream {
|
||||
StreamKind::Main => 0,
|
||||
StreamKind::Sub => 256,
|
||||
StreamKind::Extern => 1024,
|
||||
};
|
||||
|
||||
let stop_video = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_VIDEO_STOP,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: stream_code,
|
||||
response_code: 0,
|
||||
class: 0x6414, // IDK why
|
||||
},
|
||||
BcXml {
|
||||
preview: Some(Preview {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
handle,
|
||||
stream_type: None,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
sub_video.send(stop_video).await?;
|
||||
|
||||
let reply = sub_video.recv().await?;
|
||||
if reply.meta.response_code != 200 {
|
||||
return Err(super::Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::{bc::model::*, bc::xml::*, bcmedia::model::*};
|
||||
use crossbeam_channel::Receiver;
|
||||
use std::io::{BufRead, Error as IoError, ErrorKind, Read};
|
||||
|
||||
type IoResult<T> = std::result::Result<T, IoError>;
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Finish Talk
|
||||
///
|
||||
/// The send the talk finish to the camera.
|
||||
///
|
||||
/// It is also sent when the request for talk config returns status code 422
|
||||
///
|
||||
pub async fn talk_stop(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKRESET,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let msg = sub.recv().await?;
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the talk stop command.",
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///
|
||||
/// Requests the [`TalkAbility`] xml
|
||||
///
|
||||
pub async fn talk_ability(&self) -> Result<TalkAbility> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKABILITY,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
talk_ability: Some(talk_ability),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(talk_ability)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected TalkAbility xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Send sound to the camera
|
||||
///
|
||||
/// The data should be in the format as described in `<TalkAbility>` xml
|
||||
/// This method assumes that you have set up the data in the desired format
|
||||
/// in the `<TalkAbility>` xml
|
||||
///
|
||||
/// It also checks that it is ADPCM as the code is written to accept only that
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `adpcm` - Data must be adpcm in DVI-4 format
|
||||
///
|
||||
/// * `talk_config` - The talk config that describes the adpcm data
|
||||
///
|
||||
///
|
||||
pub async fn talk(&self, adpcm: &[u8], talk_config: TalkConfig) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
}
|
||||
|
||||
let block_size = talk_config.audio_config.length_per_encoder / 2;
|
||||
let sample_rate = talk_config.audio_config.sample_rate;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKCONFIG,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
talk_config: Some(talk_config),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let mut msg = sub.recv().await?;
|
||||
|
||||
// If another client is already talking OR if we crashed before sending
|
||||
// msgid 11 the camera will reply 422
|
||||
//
|
||||
// The official client in this case just sends msgid 11 and retries so
|
||||
// we will do that too
|
||||
if let BcMeta {
|
||||
response_code: 422, ..
|
||||
} = msg.meta
|
||||
{
|
||||
self.talk_stop().await?;
|
||||
// Retry
|
||||
sub.send(msg).await?;
|
||||
msg = sub.recv().await?;
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why:
|
||||
"The camera did not accept the TalkConfig xml. Audio format is likely incorrect",
|
||||
});
|
||||
}
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 4;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
const SAMPLES_PER_BYTE: usize = 2;
|
||||
|
||||
for payload_bytes in adpcm.chunks(full_block_size as usize * BLOCK_PER_PAYLOAD) {
|
||||
let mut payload = vec![];
|
||||
for bytes in payload_bytes.chunks(full_block_size as usize) {
|
||||
let bcmedia_adpcm = BcMedia::Adpcm(BcMediaAdpcm {
|
||||
data: bytes.to_vec(),
|
||||
});
|
||||
payload = bcmedia_adpcm.serialize(payload)?;
|
||||
}
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALK,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
binary_data: Some(1),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(payload)),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
|
||||
let adpcm_len = payload_bytes.len();
|
||||
// There are two samples per byte
|
||||
//
|
||||
// To calculate the bytes we subtract the block headers from the len
|
||||
//
|
||||
// There is 1 initial sample stored in the block header so we add that in the end
|
||||
//
|
||||
let samples_sent = (adpcm_len - BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD)
|
||||
* SAMPLES_PER_BYTE
|
||||
+ BLOCK_PER_PAYLOAD;
|
||||
|
||||
// Time to play the sample in seconds
|
||||
let play_length = samples_sent as f32 / sample_rate as f32;
|
||||
std::thread::sleep(std::time::Duration::from_secs_f32(play_length));
|
||||
}
|
||||
|
||||
self.talk_stop().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
///
|
||||
/// Send sound to the camera through a channel
|
||||
///
|
||||
/// This is similar to [`talk`] except it uses a channel to receive data
|
||||
///
|
||||
/// The data should be in the format as described in `<TalkAbility>` xml
|
||||
/// This method assumes that you have set up the data in the desired format
|
||||
/// in the `<TalkAbility>` xml
|
||||
///
|
||||
/// It also checks that it is ADPCM as the code is written to accept only that
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `adpcm` - Data must be adpcm in DVI-4 format
|
||||
///
|
||||
/// * `talk_config` - The talk config that describes the adpcm data
|
||||
///
|
||||
///
|
||||
pub async fn talk_stream(&self, rx: Receiver<Vec<u8>>, talk_config: TalkConfig) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
if &talk_config.audio_config.audio_type != "adpcm" {
|
||||
return Err(Error::UnknownTalkEncoding);
|
||||
}
|
||||
|
||||
let block_size = talk_config.audio_config.length_per_encoder / 2;
|
||||
let sample_rate = talk_config.audio_config.sample_rate;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALKCONFIG,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::BcXml(BcXml {
|
||||
talk_config: Some(talk_config),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
let mut msg = sub.recv().await?;
|
||||
|
||||
// If another client is already talking OR if we crashed before sending
|
||||
// msgid 11 the camera will reply 422
|
||||
//
|
||||
// The official client in this case just sends msgid 11 and retries so
|
||||
// we will do that too
|
||||
if let BcMeta {
|
||||
response_code: 422, ..
|
||||
} = msg.meta
|
||||
{
|
||||
self.talk_stop().await?;
|
||||
// Retry
|
||||
sub.send(msg).await?;
|
||||
msg = sub.recv().await?;
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why:
|
||||
"The camera did not accept the TalkConfig xml. Audio format is likely incorrect",
|
||||
});
|
||||
}
|
||||
|
||||
let full_block_size = block_size + 4; // Block size + predictor state
|
||||
let msg_num = self.new_message_num();
|
||||
let sub = connection.subscribe(msg_num).await?;
|
||||
|
||||
const BLOCK_PER_PAYLOAD: usize = 1;
|
||||
const BLOCK_HEADER_SIZE: usize = 4;
|
||||
const SAMPLES_PER_BYTE: usize = 2;
|
||||
|
||||
let mut buffered_recv = BufferedStream::from_rx(rx);
|
||||
|
||||
let target_chunks = full_block_size as usize * BLOCK_PER_PAYLOAD;
|
||||
|
||||
let mut payload_bytes = vec![];
|
||||
let mut end_of_stream = false;
|
||||
while !end_of_stream {
|
||||
while payload_bytes.len() < target_chunks {
|
||||
let mut buffer = vec![255; target_chunks - payload_bytes.len()];
|
||||
if let Ok(read) = buffered_recv.read(&mut buffer) {
|
||||
payload_bytes.extend(&buffer[..read]);
|
||||
} else {
|
||||
// Error should occur if the channel is dropped
|
||||
// and all bytes are consumed
|
||||
end_of_stream = true;
|
||||
}
|
||||
if end_of_stream {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut payload = vec![];
|
||||
for block_bytes in payload_bytes.chunks(full_block_size as usize) {
|
||||
let bytes: Vec<u8> = block_bytes.to_vec();
|
||||
let bcmedia_adpcm = BcMedia::Adpcm(BcMediaAdpcm { data: bytes });
|
||||
payload = bcmedia_adpcm.serialize(payload)?;
|
||||
}
|
||||
|
||||
let adpcm_len = payload_bytes.len();
|
||||
|
||||
// There are two samples per byte
|
||||
//
|
||||
// To calculate the bytes we subtract the block headers from the len
|
||||
//
|
||||
// There is 1 initial sample stored in the block header so we add that in the end
|
||||
//
|
||||
let samples_sent = if adpcm_len >= BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD {
|
||||
(adpcm_len - BLOCK_HEADER_SIZE * BLOCK_PER_PAYLOAD) * SAMPLES_PER_BYTE
|
||||
+ BLOCK_PER_PAYLOAD
|
||||
} else {
|
||||
// Zero samples in this block
|
||||
break;
|
||||
};
|
||||
|
||||
payload_bytes = vec![];
|
||||
|
||||
// Time to play the sample in seconds
|
||||
let play_length = samples_sent as f32 / sample_rate as f32;
|
||||
|
||||
let msg = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TALK,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
channel_id: Some(self.channel_id),
|
||||
binary_data: Some(1),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(payload)),
|
||||
}),
|
||||
};
|
||||
|
||||
sub.send(msg).await?;
|
||||
|
||||
std::thread::sleep(std::time::Duration::from_secs_f32(play_length * 0.95));
|
||||
}
|
||||
|
||||
self.talk_stop().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct BufferedStream {
|
||||
rx: Receiver<Vec<u8>>,
|
||||
buffer: Vec<u8>,
|
||||
consumed: usize,
|
||||
}
|
||||
|
||||
impl BufferedStream {
|
||||
pub fn from_rx(rx: Receiver<Vec<u8>>) -> BufferedStream {
|
||||
BufferedStream {
|
||||
rx,
|
||||
buffer: vec![],
|
||||
consumed: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for BufferedStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
|
||||
let buffer = self.fill_buf()?;
|
||||
let amt = std::cmp::min(buf.len(), buffer.len());
|
||||
|
||||
// First check if the amount of bytes we want to read is small:
|
||||
// `copy_from_slice` will generally expand to a call to `memcpy`, and
|
||||
// for a single byte the overhead is significant.
|
||||
if amt == 1 {
|
||||
buf[0] = buffer[0];
|
||||
} else {
|
||||
buf[..amt].copy_from_slice(&buffer[..amt]);
|
||||
}
|
||||
|
||||
self.consume(amt);
|
||||
|
||||
Ok(amt)
|
||||
}
|
||||
}
|
||||
|
||||
impl BufRead for BufferedStream {
|
||||
fn fill_buf(&mut self) -> IoResult<&[u8]> {
|
||||
const CLEAR_CONSUMED_AT: usize = 1024;
|
||||
// This is a trade off between caching too much dead memory
|
||||
// and calling the drain method too often
|
||||
if self.consumed > CLEAR_CONSUMED_AT {
|
||||
let _ = self.buffer.drain(0..self.consumed).collect::<Vec<u8>>();
|
||||
self.consumed = 0;
|
||||
}
|
||||
while self.buffer.len() <= self.consumed {
|
||||
let data = self
|
||||
.rx
|
||||
.recv()
|
||||
.map_err(|err| IoError::new(ErrorKind::ConnectionReset, err))?;
|
||||
self.buffer.extend(data);
|
||||
}
|
||||
|
||||
Ok(&self.buffer.as_slice()[self.consumed..])
|
||||
}
|
||||
|
||||
fn consume(&mut self, amt: usize) {
|
||||
assert!(self.consumed + amt <= self.buffer.len());
|
||||
self.consumed += amt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use std::convert::{TryFrom, TryInto};
|
||||
use time::{
|
||||
macros::date, parsing::Parsed, Date, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset,
|
||||
};
|
||||
|
||||
impl BcCamera {
|
||||
///
|
||||
/// Get the time from the camera
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns either an error or an option with the offsetted date time
|
||||
///
|
||||
pub async fn get_time(&self) -> Result<Option<OffsetDateTime>> {
|
||||
self.has_ability_ro("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get_general = connection.subscribe(msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_GENERAL,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg::default()),
|
||||
};
|
||||
|
||||
sub_get_general.send(get).await?;
|
||||
let msg = sub_get_general.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
system_general:
|
||||
Some(SystemGeneral {
|
||||
time_zone: Some(time_zone),
|
||||
year: Some(year),
|
||||
month: Some(month),
|
||||
day: Some(day),
|
||||
hour: Some(hour),
|
||||
minute: Some(minute),
|
||||
second: Some(second),
|
||||
..
|
||||
}),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
let datetime =
|
||||
match try_build_timestamp(time_zone, year, month, day, hour, minute, second) {
|
||||
Ok(dt) => dt,
|
||||
Err(_) => {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Could not parse date",
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
// This code was written in 2020; I'm trying to catch all the possible epochs that
|
||||
// cameras might reset themselves to. My B800 resets to Jan 1, 1999, but I can't
|
||||
// guarantee that Reolink won't pick some newer date. Therefore, last year ought
|
||||
// to be new enough, yet still distant enough that it won't interfere with anything
|
||||
const BOUNDARY: Date = date!(2019 - 01 - 01);
|
||||
|
||||
// detect if no time is actually set, and return Ok(None): that is, operation
|
||||
// succeeded, and there is no time set
|
||||
if datetime.date() < BOUNDARY {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(datetime))
|
||||
}
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Reply did not contain SystemGeneral with all time fields filled out",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Sets the time of the camera
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// * `timestamp` - The time to set the camera to
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// returns Ok(()) or error
|
||||
///
|
||||
pub async fn set_time(&self, timestamp: OffsetDateTime) -> Result<()> {
|
||||
self.has_ability_rw("general").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set_general = connection.subscribe(msg_num).await?;
|
||||
let set = Bc::new_from_xml(
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_SET_GENERAL,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
BcXml {
|
||||
system_general: Some(SystemGeneral {
|
||||
version: xml_ver(),
|
||||
//osd_format: Some("MDY".to_string()),
|
||||
time_format: Some(0),
|
||||
// Reolink uses positive seconds to indicate a negative UTC offset:
|
||||
time_zone: Some(-timestamp.offset().whole_seconds()),
|
||||
year: Some(timestamp.year()),
|
||||
month: Some(timestamp.month().into()),
|
||||
day: Some(timestamp.day()),
|
||||
hour: Some(timestamp.hour()),
|
||||
minute: Some(timestamp.minute()),
|
||||
second: Some(timestamp.second()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
sub_set_general.send(set).await?;
|
||||
let msg = sub_set_general.recv().await?;
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not accept the set time command.",
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn try_build_timestamp(
|
||||
timezone: i32,
|
||||
year: i32,
|
||||
month: u8,
|
||||
day: u8,
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
second: u8,
|
||||
) -> std::result::Result<OffsetDateTime, crate::Error> {
|
||||
let date = Date::try_from(
|
||||
Parsed::new()
|
||||
.with_year(year)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_month(month.try_into()?)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_day(day.try_into()?)
|
||||
.ok_or(Error::TimeParse)?,
|
||||
)?;
|
||||
let time = Time::try_from(
|
||||
Parsed::new()
|
||||
.with_hour_24(hour)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_minute(minute)
|
||||
.ok_or(Error::TimeParse)?
|
||||
.with_second(second)
|
||||
.ok_or(Error::TimeParse)?,
|
||||
)?;
|
||||
let offset = UtcOffset::from_whole_seconds(timezone)?;
|
||||
|
||||
Ok(PrimitiveDateTime::new(date, time).assume_offset(offset))
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Request the [VersionInfo] xml
|
||||
pub async fn version(&self) -> Result<VersionInfo> {
|
||||
self.has_ability_ro("version").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_version = connection.subscribe(msg_num).await?;
|
||||
|
||||
let version = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_VERSION,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
stream_type: 0,
|
||||
response_code: 0,
|
||||
class: 0x6414, // IDK why
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
..Default::default()
|
||||
}),
|
||||
};
|
||||
|
||||
sub_version.send(version).await?;
|
||||
|
||||
let modern_reply = sub_version.recv().await?;
|
||||
if modern_reply.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavaliable);
|
||||
}
|
||||
let version_info;
|
||||
match modern_reply.body {
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
version_info: Some(info),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) => {
|
||||
version_info = info;
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(modern_reply)),
|
||||
why: "Expected a VersionInfo message",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Ok(version_info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Handles sending and recieving messages as packets
|
||||
//!
|
||||
//! BcMediaCodex is used with a `[tokio_util::codec::Framed]` to form complete packets
|
||||
//!
|
||||
use crate::bcmedia::model::*;
|
||||
use crate::{Error, Result};
|
||||
use bytes::BytesMut;
|
||||
use log::*;
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
pub struct BcMediaCodex {
|
||||
/// If true we will not search for the start of the next packet
|
||||
/// in the event that the stream appears to be corrupted
|
||||
strict: bool,
|
||||
amount_skipped: usize,
|
||||
}
|
||||
|
||||
impl BcMediaCodex {
|
||||
pub(crate) fn new(strict: bool) -> Self {
|
||||
Self {
|
||||
strict,
|
||||
amount_skipped: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoder<BcMedia> for BcMediaCodex {
|
||||
type Error = Error;
|
||||
|
||||
fn encode(&mut self, item: BcMedia, dst: &mut BytesMut) -> Result<()> {
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let buf = item.serialize(buf)?;
|
||||
dst.reserve(buf.len());
|
||||
dst.extend_from_slice(buf.as_slice());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for BcMediaCodex {
|
||||
type Item = BcMedia;
|
||||
type Error = Error;
|
||||
|
||||
/// Since frames can cross EOF boundaries we overload this so it dosen't error if
|
||||
/// there are bytes left on the stream
|
||||
fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
match self.decode(buf)? {
|
||||
Some(frame) => Ok(Some(frame)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>> {
|
||||
loop {
|
||||
match { BcMedia::deserialize(src) } {
|
||||
Ok(bc) => {
|
||||
if self.amount_skipped > 0 {
|
||||
debug!("Amount skipped to restore stream: {}", self.amount_skipped);
|
||||
self.amount_skipped = 0;
|
||||
}
|
||||
return Ok(Some(bc));
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) => {
|
||||
if self.amount_skipped > 0 {
|
||||
debug!("Amount skipped to restore stream: {}", self.amount_skipped);
|
||||
self.amount_skipped = 0;
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
Err(e) => {
|
||||
if self.strict {
|
||||
return Err(e);
|
||||
} else if src.is_empty() {
|
||||
return Ok(None);
|
||||
} else {
|
||||
if self.amount_skipped == 0 {
|
||||
debug!("Error in stream attempting to restore");
|
||||
trace!(" Stream Error: {:?}", e);
|
||||
}
|
||||
// Drop the whole packet and wait for a packet that starts with magic
|
||||
self.amount_skipped += src.len();
|
||||
src.clear();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
use super::model::BcMediaIframe;
|
||||
use super::model::*;
|
||||
use crate::Error;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use nom::{bytes::streaming::take, combinator::*, error::context, number::streaming::*};
|
||||
|
||||
type IResult<I, O, E = nom::error::VerboseError<I>> = Result<(I, O), nom::Err<E>>;
|
||||
|
||||
// PAD_SIZE: Media packets use 8 byte padding
|
||||
const PAD_SIZE: u32 = 8;
|
||||
|
||||
impl BcMedia {
|
||||
pub(crate) fn deserialize(buf: &mut BytesMut) -> Result<BcMedia, Error> {
|
||||
const TYPICAL_HEADER: usize = 25;
|
||||
let (result, len) = match consumed(bcmedia)(buf) {
|
||||
Ok((_, (parsed_buff, result))) => Ok((result, parsed_buff.len())),
|
||||
Err(e) => Err(e),
|
||||
}?;
|
||||
buf.advance(len);
|
||||
buf.reserve(len + TYPICAL_HEADER); // Preallocate for future buffer calls
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> {
|
||||
let (buf, magic) = context(
|
||||
"Failed to match any known bcmedia",
|
||||
verify(le_u32, |x| {
|
||||
matches!(
|
||||
*x,
|
||||
MAGIC_HEADER_BCMEDIA_INFO_V1
|
||||
| MAGIC_HEADER_BCMEDIA_INFO_V2
|
||||
| MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST
|
||||
| MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST
|
||||
| MAGIC_HEADER_BCMEDIA_AAC
|
||||
| MAGIC_HEADER_BCMEDIA_ADPCM
|
||||
)
|
||||
}),
|
||||
)(buf)?;
|
||||
|
||||
match magic {
|
||||
MAGIC_HEADER_BCMEDIA_INFO_V1 => {
|
||||
let (buf, payload) = bcmedia_info_v1(buf)?;
|
||||
Ok((buf, BcMedia::InfoV1(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_INFO_V2 => {
|
||||
let (buf, payload) = bcmedia_info_v2(buf)?;
|
||||
Ok((buf, BcMedia::InfoV2(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST => {
|
||||
let (buf, payload) = bcmedia_iframe(buf)?;
|
||||
Ok((buf, BcMedia::Iframe(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST => {
|
||||
let (buf, payload) = bcmedia_pframe(buf)?;
|
||||
Ok((buf, BcMedia::Pframe(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_AAC => {
|
||||
let (buf, payload) = bcmedia_aac(buf)?;
|
||||
Ok((buf, BcMedia::Aac(payload)))
|
||||
}
|
||||
MAGIC_HEADER_BCMEDIA_ADPCM => {
|
||||
let (buf, payload) = bcmedia_adpcm(buf)?;
|
||||
Ok((buf, BcMedia::Adpcm(payload)))
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bcmedia_info_v1(buf: &[u8]) -> IResult<&[u8], BcMediaInfoV1> {
|
||||
let (buf, _header_size) = context(
|
||||
"Header size mismatch in BCMedia InfoV1",
|
||||
verify(le_u32, |x| *x == 32),
|
||||
)(buf)?;
|
||||
let (buf, video_width) = le_u32(buf)?;
|
||||
let (buf, video_height) = le_u32(buf)?;
|
||||
let (buf, _unknown) = le_u8(buf)?;
|
||||
let (buf, fps) = le_u8(buf)?;
|
||||
let (buf, start_year) = le_u8(buf)?;
|
||||
let (buf, start_month) = le_u8(buf)?;
|
||||
let (buf, start_day) = le_u8(buf)?;
|
||||
let (buf, start_hour) = le_u8(buf)?;
|
||||
let (buf, start_min) = le_u8(buf)?;
|
||||
let (buf, start_seconds) = le_u8(buf)?;
|
||||
let (buf, end_year) = le_u8(buf)?;
|
||||
let (buf, end_month) = le_u8(buf)?;
|
||||
let (buf, end_day) = le_u8(buf)?;
|
||||
let (buf, end_hour) = le_u8(buf)?;
|
||||
let (buf, end_min) = le_u8(buf)?;
|
||||
let (buf, end_seconds) = le_u8(buf)?;
|
||||
let (buf, _unknown_b) = le_u16(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaInfoV1 {
|
||||
// header_size,
|
||||
video_width,
|
||||
video_height,
|
||||
fps,
|
||||
start_year,
|
||||
start_month,
|
||||
start_day,
|
||||
start_hour,
|
||||
start_min,
|
||||
start_seconds,
|
||||
end_year,
|
||||
end_month,
|
||||
end_day,
|
||||
end_hour,
|
||||
end_min,
|
||||
end_seconds,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn bcmedia_info_v2(buf: &[u8]) -> IResult<&[u8], BcMediaInfoV2> {
|
||||
let (buf, _header_size) = context(
|
||||
"Failed to match headersize in BCMedia Info V2",
|
||||
verify(le_u32, |x| *x == 32),
|
||||
)(buf)?;
|
||||
let (buf, video_width) = le_u32(buf)?;
|
||||
let (buf, video_height) = le_u32(buf)?;
|
||||
let (buf, _unknown) = le_u8(buf)?;
|
||||
let (buf, fps) = le_u8(buf)?;
|
||||
let (buf, start_year) = le_u8(buf)?;
|
||||
let (buf, start_month) = le_u8(buf)?;
|
||||
let (buf, start_day) = le_u8(buf)?;
|
||||
let (buf, start_hour) = le_u8(buf)?;
|
||||
let (buf, start_min) = le_u8(buf)?;
|
||||
let (buf, start_seconds) = le_u8(buf)?;
|
||||
let (buf, end_year) = le_u8(buf)?;
|
||||
let (buf, end_month) = le_u8(buf)?;
|
||||
let (buf, end_day) = le_u8(buf)?;
|
||||
let (buf, end_hour) = le_u8(buf)?;
|
||||
let (buf, end_min) = le_u8(buf)?;
|
||||
let (buf, end_seconds) = le_u8(buf)?;
|
||||
let (buf, _unknown_b) = le_u16(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaInfoV2 {
|
||||
// header_size,
|
||||
video_width,
|
||||
video_height,
|
||||
fps,
|
||||
start_year,
|
||||
start_month,
|
||||
start_day,
|
||||
start_hour,
|
||||
start_min,
|
||||
start_seconds,
|
||||
end_year,
|
||||
end_month,
|
||||
end_day,
|
||||
end_hour,
|
||||
end_min,
|
||||
end_seconds,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn take4(buf: &[u8]) -> IResult<&[u8], &str> {
|
||||
map_res(nom::bytes::streaming::take(4usize), |r| {
|
||||
std::str::from_utf8(r)
|
||||
})(buf)
|
||||
}
|
||||
|
||||
fn bcmedia_iframe(buf: &[u8]) -> IResult<&[u8], BcMediaIframe> {
|
||||
let (buf, video_type_str) = context(
|
||||
"Video Type is unrecognised in IFrame",
|
||||
verify(take4, |x| matches!(x, "H264" | "H265")),
|
||||
)(buf)?;
|
||||
let (buf, payload_size) = le_u32(buf)?;
|
||||
let (buf, additional_header_size) = le_u32(buf)?;
|
||||
let (buf, microseconds) = le_u32(buf)?;
|
||||
let (buf, _unknown_b) = le_u32(buf)?;
|
||||
let (buf, time) = if additional_header_size >= 4 {
|
||||
let (buf, time_value) = le_u32(buf)?;
|
||||
(buf, Some(time_value))
|
||||
} else {
|
||||
(buf, None)
|
||||
};
|
||||
let (buf, _unknown_remained) = if additional_header_size > 4 {
|
||||
let remainder = additional_header_size - 4;
|
||||
let (buf, unknown_remained) = take(remainder)(buf)?;
|
||||
(buf, Some(unknown_remained))
|
||||
} else {
|
||||
(buf, None)
|
||||
};
|
||||
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
assert_eq!(payload_size as usize, data_slice.len());
|
||||
|
||||
let video_type = match video_type_str {
|
||||
"H264" => VideoType::H264,
|
||||
"H265" => VideoType::H265,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaIframe {
|
||||
video_type,
|
||||
// payload_size,
|
||||
microseconds,
|
||||
time,
|
||||
data: data_slice.to_vec(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn bcmedia_pframe(buf: &[u8]) -> IResult<&[u8], BcMediaPframe> {
|
||||
let (buf, video_type_str) = context(
|
||||
"Video Type is unrecognised in PFrame",
|
||||
verify(take4, |x| matches!(x, "H264" | "H265")),
|
||||
)(buf)?;
|
||||
let (buf, payload_size) = le_u32(buf)?;
|
||||
let (buf, additional_header_size) = le_u32(buf)?;
|
||||
let (buf, microseconds) = le_u32(buf)?;
|
||||
let (buf, _unknown_b) = le_u32(buf)?;
|
||||
let (buf, _additional_header) = take(additional_header_size)(buf)?;
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
assert_eq!(payload_size as usize, data_slice.len());
|
||||
|
||||
let video_type = match video_type_str {
|
||||
"H264" => VideoType::H264,
|
||||
"H265" => VideoType::H265,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaPframe {
|
||||
video_type,
|
||||
// payload_size,
|
||||
microseconds,
|
||||
data: data_slice.to_vec(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn bcmedia_aac(buf: &[u8]) -> IResult<&[u8], BcMediaAac> {
|
||||
let (buf, payload_size) = le_u16(buf)?;
|
||||
let (buf, _payload_size_b) = le_u16(buf)?;
|
||||
let (buf, data_slice) = take(payload_size)(buf)?;
|
||||
let pad_size = match payload_size as u32 % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaAac {
|
||||
// payload_size,
|
||||
data: data_slice.to_vec(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> {
|
||||
const SUB_HEADER_SIZE: u16 = 4;
|
||||
|
||||
let (buf, payload_size) = le_u16(buf)?;
|
||||
let (buf, _payload_size_b) = le_u16(buf)?;
|
||||
let (buf, _magic) = context(
|
||||
"ADPCM data magic value is invalid",
|
||||
verify(le_u16, |x| *x == MAGIC_HEADER_BCMEDIA_ADPCM_DATA),
|
||||
)(buf)?;
|
||||
// On some camera this value is just 2
|
||||
// On other cameras is half the block size without the header
|
||||
let (buf, _half_block_size) = le_u16(buf)?;
|
||||
let block_size = payload_size - SUB_HEADER_SIZE;
|
||||
let (buf, data_slice) = take(block_size)(buf)?;
|
||||
let pad_size = match payload_size as u32 % PAD_SIZE {
|
||||
0 => 0,
|
||||
n => PAD_SIZE - n,
|
||||
};
|
||||
let (buf, _padding) = take(pad_size)(buf)?;
|
||||
|
||||
Ok((
|
||||
buf,
|
||||
BcMediaAdpcm {
|
||||
// payload_size,
|
||||
// block_size,
|
||||
data: data_slice.to_vec(),
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Error;
|
||||
use crate::bcmedia::model::*;
|
||||
use bytes::BytesMut;
|
||||
use env_logger::Env;
|
||||
use log::*;
|
||||
use std::io::ErrorKind;
|
||||
|
||||
fn init() {
|
||||
let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info"))
|
||||
.is_test(true)
|
||||
.try_init();
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This method will test the decoding on swann cameras output
|
||||
//
|
||||
// Crucially this contains adpcm
|
||||
fn test_swan_deser() {
|
||||
init();
|
||||
|
||||
let sample = [
|
||||
include_bytes!("samples/video_stream_swan_00.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_01.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_02.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_03.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_04.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_05.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_06.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_07.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_08.raw").as_ref(),
|
||||
include_bytes!("samples/video_stream_swan_09.raw").as_ref(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{:?}", e);
|
||||
panic!();
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This method will test the decoding of argus2 cameras output
|
||||
//
|
||||
// This packet has an extended iframe
|
||||
fn test_argus2_iframe_extended() {
|
||||
init();
|
||||
|
||||
let sample = [
|
||||
include_bytes!("samples/argus2_iframe_0.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_iframe_1.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_iframe_2.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_iframe_3.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_iframe_4.raw").as_ref(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{:?}", e);
|
||||
panic!();
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// This method will test the decoding of argus2 cameras output
|
||||
//
|
||||
// This packet has an extended pframe
|
||||
fn test_argus2_pframe_extended() {
|
||||
init();
|
||||
|
||||
let sample = [
|
||||
include_bytes!("samples/argus2_pframe_0.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_1.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_2.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_3.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_4.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_5.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_6.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_7.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_8.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_9.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_10.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_11.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_12.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_13.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_14.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_15.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_16.raw").as_ref(),
|
||||
include_bytes!("samples/argus2_pframe_17.raw").as_ref(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("{:?}", e);
|
||||
panic!();
|
||||
}
|
||||
Ok(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
// Tests the decoding of an info v1
|
||||
fn test_info_v1() {
|
||||
init();
|
||||
|
||||
let sample = include_bytes!("samples/info_v1.raw");
|
||||
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
assert!(matches!(
|
||||
e,
|
||||
Ok(BcMedia::InfoV1(BcMediaInfoV1 {
|
||||
video_width: 2560,
|
||||
video_height: 1440,
|
||||
fps: 30,
|
||||
start_year: 121,
|
||||
start_month: 8,
|
||||
start_day: 4,
|
||||
start_hour: 23,
|
||||
start_min: 23,
|
||||
start_seconds: 52,
|
||||
end_year: 121,
|
||||
end_month: 8,
|
||||
end_day: 4,
|
||||
end_hour: 23,
|
||||
end_min: 23,
|
||||
end_seconds: 52,
|
||||
}))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_iframe() {
|
||||
init();
|
||||
|
||||
let sample = [
|
||||
include_bytes!("samples/iframe_0.raw").as_ref(),
|
||||
include_bytes!("samples/iframe_1.raw").as_ref(),
|
||||
include_bytes!("samples/iframe_2.raw").as_ref(),
|
||||
include_bytes!("samples/iframe_3.raw").as_ref(),
|
||||
include_bytes!("samples/iframe_4.raw").as_ref(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
if let Ok(BcMedia::Iframe(BcMediaIframe {
|
||||
video_type: VideoType::H264,
|
||||
microseconds: 3557705112,
|
||||
time: Some(1628085232),
|
||||
data: d,
|
||||
})) = e
|
||||
{
|
||||
assert_eq!(d.len(), 192881);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pframe() {
|
||||
init();
|
||||
|
||||
let sample = [
|
||||
include_bytes!("samples/pframe_0.raw").as_ref(),
|
||||
include_bytes!("samples/pframe_1.raw").as_ref(),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
if let Ok(BcMedia::Pframe(BcMediaPframe {
|
||||
video_type: VideoType::H264,
|
||||
microseconds: 3557767112,
|
||||
data: d,
|
||||
})) = e
|
||||
{
|
||||
assert_eq!(d.len(), 45108);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_adpcm() {
|
||||
init();
|
||||
|
||||
let sample = include_bytes!("samples/adpcm_0.raw");
|
||||
|
||||
let e = BcMedia::deserialize(&mut BytesMut::from(&sample[..]));
|
||||
if let Ok(BcMedia::Adpcm(BcMediaAdpcm { data: d })) = e {
|
||||
assert_eq!(d.len(), 244);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub(crate) mod codex;
|
||||
/// Deserlizer for BCMedia
|
||||
pub mod de;
|
||||
/// Structure model for BCMedia
|
||||
pub mod model;
|
||||
/// Serlizer for BCMedia
|
||||
pub mod ser;
|
||||
@@ -0,0 +1,233 @@
|
||||
/// Video streams encapsulate a stream of BcMedia
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BcMedia {
|
||||
/// Holds info on the stream
|
||||
InfoV1(BcMediaInfoV1),
|
||||
/// Holds info on the stream
|
||||
InfoV2(BcMediaInfoV2),
|
||||
/// Holds an IFrame either H264 or H265
|
||||
Iframe(BcMediaIframe),
|
||||
/// Holds a PFrame either H264 or H265
|
||||
Pframe(BcMediaPframe),
|
||||
/// Holds AAC audio
|
||||
Aac(BcMediaAac),
|
||||
/// Holds ADPCM audio
|
||||
Adpcm(BcMediaAdpcm),
|
||||
}
|
||||
//
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V1: u32 = 0x31303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV1 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
// it's included
|
||||
// pub header_size: u32,
|
||||
/// Width of the video
|
||||
pub video_width: u32,
|
||||
/// Height of the video
|
||||
pub video_height: u32,
|
||||
// pub unknown: u8,
|
||||
/// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table
|
||||
pub fps: u8,
|
||||
/// Start year of the stream
|
||||
pub start_year: u8,
|
||||
/// Start month of the stream
|
||||
pub start_month: u8,
|
||||
/// Start day of the stream
|
||||
pub start_day: u8,
|
||||
/// Start hour of the stream
|
||||
pub start_hour: u8,
|
||||
/// Start minute of the stream
|
||||
pub start_min: u8,
|
||||
/// Start seconds of the stream
|
||||
pub start_seconds: u8,
|
||||
/// End year of the video probably only useful for the recorded files on the SD card
|
||||
pub end_year: u8,
|
||||
/// End month of the video probably only useful for the recorded files on the SD card
|
||||
pub end_month: u8,
|
||||
/// End day of the video probably only useful for the recorded files on the SD card
|
||||
pub end_day: u8,
|
||||
/// End hour of the video probably only useful for the recorded files on the SD card
|
||||
pub end_hour: u8,
|
||||
/// End min of the video probably only useful for the recorded files on the SD card
|
||||
pub end_min: u8,
|
||||
/// End seconds of the video probably only useful for the recorded files on the SD card
|
||||
pub end_seconds: u8,
|
||||
// unknown: u16
|
||||
}
|
||||
//
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_INFO_V2: u32 = 0x32303031;
|
||||
|
||||
/// The start of a BcMedia stream contains this message
|
||||
/// which describes the data to follow
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaInfoV2 {
|
||||
// This is the size of the header so it's actually a fixed value
|
||||
// The other messages have body size here so maybe that's why
|
||||
// it's included
|
||||
// pub header_size: u32,
|
||||
/// Width of the video
|
||||
pub video_width: u32,
|
||||
/// Height of the video
|
||||
pub video_height: u32,
|
||||
// pub unknown: u8,
|
||||
/// Frames per second. On older cameras this seems to be an index of the FPS on a lookup table
|
||||
pub fps: u8,
|
||||
/// Start year of the stream
|
||||
pub start_year: u8,
|
||||
/// Start month of the stream
|
||||
pub start_month: u8,
|
||||
/// Start day of the stream
|
||||
pub start_day: u8,
|
||||
/// Start hour of the stream
|
||||
pub start_hour: u8,
|
||||
/// Start minute of the stream
|
||||
pub start_min: u8,
|
||||
/// Start seconds of the stream
|
||||
pub start_seconds: u8,
|
||||
/// End year of the video probably only useful for the recorded files on the SD card
|
||||
pub end_year: u8,
|
||||
/// End month of the video probably only useful for the recorded files on the SD card
|
||||
pub end_month: u8,
|
||||
/// End day of the video probably only useful for the recorded files on the SD card
|
||||
pub end_day: u8,
|
||||
/// End hour of the video probably only useful for the recorded files on the SD card
|
||||
pub end_hour: u8,
|
||||
/// End min of the video probably only useful for the recorded files on the SD card
|
||||
pub end_min: u8,
|
||||
/// End seconds of the video probably only useful for the recorded files on the SD card
|
||||
pub end_seconds: u8,
|
||||
// unknown: u16
|
||||
}
|
||||
|
||||
// IFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039;
|
||||
|
||||
/// Video Types for I/PFrame
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum VideoType {
|
||||
/// H264 video data
|
||||
H264,
|
||||
/// H265 video data
|
||||
H265,
|
||||
}
|
||||
|
||||
/// This is a BcMedia video IFrame.
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaIframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u32,
|
||||
// unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00
|
||||
/// Timestamp in microseconds
|
||||
pub microseconds: u32,
|
||||
// unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00
|
||||
/// POSIX time (seconds since 00:00:00 Jan 1 1970)
|
||||
pub time: Option<u32>,
|
||||
//unknown: u32, // Known values 1-00/06/29 2-00/01 3-00/C3 4-00
|
||||
/// Raw IFrame data
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaIframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(&"time", &self.time)
|
||||
.entry(
|
||||
&"data[0..10]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-10..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// PFrame magics include the channel number in them
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130;
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139;
|
||||
|
||||
/// This is a BcMedia video PFrame.
|
||||
#[derive(Clone)]
|
||||
pub struct BcMediaPframe {
|
||||
/// "H264", or "H265"
|
||||
pub video_type: VideoType,
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u32,
|
||||
// unknown: u32, // NVR channel count? Known values 1-00/08 2-00 3-00 4-00
|
||||
/// Timestamp in microseconds
|
||||
pub microseconds: u32,
|
||||
// unknown: u32, // Known values 1-00/23/5A 2-00 3-00 4-00
|
||||
/// Raw PFrame data
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for BcMediaPframe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_map()
|
||||
.entry(&"video_type", &self.video_type)
|
||||
// .entry(&"payload_size", &self.payload_size)
|
||||
.entry(&"microseconds", &self.microseconds)
|
||||
.entry(
|
||||
&"data[0..20]",
|
||||
&self.data[0..std::cmp::min(20, self.data.len())].to_vec(),
|
||||
)
|
||||
.entry(
|
||||
&"data[-20..-1]",
|
||||
&self.data[std::cmp::max(0, self.data.len() - 20)..self.data.len()].to_vec(),
|
||||
)
|
||||
.entry(&"data.len()", &self.data.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_AAC: u32 = 0x62773530;
|
||||
|
||||
/// This contains BcMedia audio data in AAC format
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAac {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
// Size of payload after header in bytes exactly the same as before
|
||||
// pub payload_size_b: u16,
|
||||
/// Raw AAC data
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM: u32 = 0x62773130;
|
||||
|
||||
pub(super) const MAGIC_HEADER_BCMEDIA_ADPCM_DATA: u16 = 0x0100;
|
||||
|
||||
/// This contains BcMedia audio data in ADPCM format
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BcMediaAdpcm {
|
||||
// Size of payload after header in bytes
|
||||
// pub payload_size: u16,
|
||||
// Size of payload after header in bytes exactly the same as before
|
||||
// pub payload_size_b: u16,
|
||||
// more_magic: MAGIC_HEADER_BCMEDIA_ADPCM_DATA
|
||||
// Adpcm sample_block_size in bytes
|
||||
//
|
||||
// These bytes (and the MAGIC_HEADER_BCMEDIA_ADPCM_DATA) are included as
|
||||
// part of the payload_size. It may be more prudent to sealise them to
|
||||
// another structure.
|
||||
// pub sample_block_size: u16,
|
||||
/// The raw adpcm data in DVI-4 layout.
|
||||
///
|
||||
/// One `data` should contain 4 bytes of the adpcm predictor state then one block
|
||||
/// of adpcm samples
|
||||
///
|
||||
/// To calculate the block-align size simply remove 4 from the `len()`
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user