Compare commits
1188
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8623cdcd0 | ||
|
|
9b633e5966 | ||
|
|
7a9fa12c3b | ||
|
|
ae26ad9b51 | ||
|
|
1afb8c4a62 | ||
|
|
f78be4dd18 | ||
|
|
a82c2e28bc | ||
|
|
69a2d5c41f | ||
|
|
efaea4ff91 | ||
|
|
f15fdaefbc | ||
|
|
5fc9bc200a | ||
|
|
7158943fc8 | ||
|
|
8f19d12b8c | ||
|
|
b0e009ba4d | ||
|
|
99146a8dce | ||
|
|
3349486750 | ||
|
|
204c92cb4e | ||
|
|
d16cd4398c | ||
|
|
56d343e69f | ||
|
|
f8bb04fb8b | ||
|
|
813eb25343 | ||
|
|
f86cefc2fd | ||
|
|
a04077e2c1 | ||
|
|
1c797dffb5 | ||
|
|
9ace435f5f | ||
|
|
684e1a9015 | ||
|
|
23bf14119f | ||
|
|
77eeea224c | ||
|
|
b37b3ee4b7 | ||
|
|
3f7a231ff6 | ||
|
|
108adb13a5 | ||
|
|
b561b643c5 | ||
|
|
afd71a7cd2 | ||
|
|
6572577859 | ||
|
|
cc8a6e7e18 | ||
|
|
2e24b1e476 | ||
|
|
82524a12b2 | ||
|
|
ae6e0fd928 | ||
|
|
ab947b895c | ||
|
|
e53b0f09d2 | ||
|
|
0f53185d01 | ||
|
|
1b6011b4eb | ||
|
|
bae36ef40a | ||
|
|
32937c1f61 | ||
|
|
308a454c74 | ||
|
|
daf20e192a | ||
|
|
8f043a3ce2 | ||
|
|
0d5fbd30f1 | ||
|
|
a6ebdfe713 | ||
|
|
186d580462 | ||
|
|
e6321f36d7 | ||
|
|
366c2a4b69 | ||
|
|
e8aca0ee10 | ||
|
|
96e994512e | ||
|
|
a8b93a4ef2 | ||
|
|
9d68338774 | ||
|
|
bd2adf8924 | ||
|
|
7e407c4456 | ||
|
|
d96f637c84 | ||
|
|
67508c1f17 | ||
|
|
e85e8f4780 | ||
|
|
175c33b131 | ||
|
|
556e051edc | ||
|
|
3bfd273528 | ||
|
|
bfa76009b9 | ||
|
|
c59b44c83e | ||
|
|
e146f9593b | ||
|
|
5d05504ec8 | ||
|
|
88a2ec7a11 | ||
|
|
3b0a510ccf | ||
|
|
2d49df07db | ||
|
|
4d441d89fd | ||
|
|
31fb8f31db | ||
|
|
616e2e5223 | ||
|
|
08f917279c | ||
|
|
df0f494702 | ||
|
|
4bfc73cce5 | ||
|
|
a19a5f3919 | ||
|
|
d0db861c10 | ||
|
|
9480dd8605 | ||
|
|
2b827d9542 | ||
|
|
c85a7641cb | ||
|
|
e74e12268a | ||
|
|
6572be1d95 | ||
|
|
b46e5db5d8 | ||
|
|
b8a22f4663 | ||
|
|
aa8bb6a5db | ||
|
|
4ef6fb59f0 | ||
|
|
4b801884ef | ||
|
|
26fa7ee161 | ||
|
|
c92e289fb7 | ||
|
|
350fc7d28c | ||
|
|
e6f8aa1e64 | ||
|
|
60cdf914a5 | ||
|
|
be8ec85175 | ||
|
|
d94b24d86d | ||
|
|
d6d47039ba | ||
|
|
72c486353b | ||
|
|
8c186f3f56 | ||
|
|
87e5bcb931 | ||
|
|
cb27c11ed8 | ||
|
|
ebf607b1a9 | ||
|
|
358e62601e | ||
|
|
0eddab0b2e | ||
|
|
e7268f2481 | ||
|
|
f31d948671 | ||
|
|
7a920fb09a | ||
|
|
2deac96af4 | ||
|
|
1e620d15df | ||
|
|
7f8ccc6806 | ||
|
|
8f8d9e6f78 | ||
|
|
ea1b21b7f8 | ||
|
|
47a89c0c76 | ||
|
|
f07b8e4a8c | ||
|
|
b7eb6cefdc | ||
|
|
2fc5c24834 | ||
|
|
d6d4ea522e | ||
|
|
31048ed075 | ||
|
|
d354b90976 | ||
|
|
54f7665414 | ||
|
|
9187694889 | ||
|
|
c0a6123740 | ||
|
|
04595b6aff | ||
|
|
1ba899840f | ||
|
|
919d8fffba | ||
|
|
c3ed0b41ab | ||
|
|
4c17fa9f2b | ||
|
|
df0642e0f8 | ||
|
|
cfd7ac6778 | ||
|
|
6b9731168d | ||
|
|
14f867c728 | ||
|
|
fbd19fd5c6 | ||
|
|
fde7a08405 | ||
|
|
37f560cf66 | ||
|
|
fcc559885a | ||
|
|
8205b652d3 | ||
|
|
1a020e5788 | ||
|
|
b13db1227d | ||
|
|
261e458947 | ||
|
|
afabd05cef | ||
|
|
ce4e4f2f5d | ||
|
|
b6c7cff6a7 | ||
|
|
9cd5551156 | ||
|
|
311b8b03d8 | ||
|
|
606c978a86 | ||
|
|
acae5f95ee | ||
|
|
76e804ea6a | ||
|
|
18a69b9d1e | ||
|
|
159cb4b716 | ||
|
|
6c64cf663a | ||
|
|
5cec02e3c2 | ||
|
|
4a94a2ddb2 | ||
|
|
459c9255ad | ||
|
|
07636a407b | ||
|
|
5ede452a12 | ||
|
|
dc4b5505b0 | ||
|
|
7f047efaef | ||
|
|
a6c8665a98 | ||
|
|
71dc655673 | ||
|
|
4cbf8d22dd | ||
|
|
a7d2574e88 | ||
|
|
a023138a8d | ||
|
|
f56346194e | ||
|
|
a634639778 | ||
|
|
45151203e2 | ||
|
|
44ffdcc2e8 | ||
|
|
31c825f228 | ||
|
|
6653fc43ac | ||
|
|
484d16c262 | ||
|
|
5527f0281e | ||
|
|
f532d83bb3 | ||
|
|
9518a566a4 | ||
|
|
d069b47972 | ||
|
|
61a5073adb | ||
|
|
9dd8c2ea99 | ||
|
|
db98926e6c | ||
|
|
9ae537fb38 | ||
|
|
7d5782d2a3 | ||
|
|
446387a3a0 | ||
|
|
a9540d0c26 | ||
|
|
ab87f0325d | ||
|
|
06b9482501 | ||
|
|
b3a524823f | ||
|
|
b1ad94ca03 | ||
|
|
362c764d08 | ||
|
|
3cdd75b244 | ||
|
|
b1305c3fc8 | ||
|
|
6ec0600445 | ||
|
|
93bf955a37 | ||
|
|
7809f6db78 | ||
|
|
ccd39c5e65 | ||
|
|
7e9b3d5fb7 | ||
|
|
6027d6f643 | ||
|
|
c05168bec8 | ||
|
|
63df8b3d9b | ||
|
|
15545a7db2 | ||
|
|
0702110f1f | ||
|
|
6f24056ad1 | ||
|
|
6501b82379 | ||
|
|
86456335f0 | ||
|
|
0cf5b1e8f2 | ||
|
|
561b7f094d | ||
|
|
c8f8f2bd9d | ||
|
|
5871d0566d | ||
|
|
aeab451bbc | ||
|
|
b10ee03f22 | ||
|
|
ed0909a797 | ||
|
|
d550f08d88 | ||
|
|
f4a0cb3abc | ||
|
|
0aa9b347cc | ||
|
|
e362ff1b0a | ||
|
|
d011a37731 | ||
|
|
9d47021aa7 | ||
|
|
f3587bafe4 | ||
|
|
70e8da0702 | ||
|
|
8067ffc30d | ||
|
|
6824d52db7 | ||
|
|
6058d95b3a | ||
|
|
6e8c744025 | ||
|
|
4d3c3ec610 | ||
|
|
1195087d4b | ||
|
|
acaa4703df | ||
|
|
33e51a7c13 | ||
|
|
894f2e3644 | ||
|
|
0d9d6b97c9 | ||
|
|
beb9fed919 | ||
|
|
6daf1f5b3d | ||
|
|
bd17c8e5e0 | ||
|
|
ca823a1894 | ||
|
|
fa4ebc436f | ||
|
|
c09bc13598 | ||
|
|
47e9b8ffe0 | ||
|
|
44fc744dcd | ||
|
|
26f82f0395 | ||
|
|
095bd889ef | ||
|
|
3d0f8b794e | ||
|
|
f13887a369 | ||
|
|
8bdb8ef1bd | ||
|
|
daf44fe1c2 | ||
|
|
c14cdcccc2 | ||
|
|
969bcb8956 | ||
|
|
a8cee8d294 | ||
|
|
6bea9a805e | ||
|
|
393e127d89 | ||
|
|
52008e351f | ||
|
|
8ae76a8dc3 | ||
|
|
53891f256a | ||
|
|
40f9f2c795 | ||
|
|
0fc0455111 | ||
|
|
4a010b5095 | ||
|
|
cd189fc61d | ||
|
|
240ebab622 | ||
|
|
48b81ff1d3 | ||
|
|
f52aad3b48 | ||
|
|
28457510e2 | ||
|
|
3f95aafe99 | ||
|
|
f4b852f1e6 | ||
|
|
0f28154fdb | ||
|
|
061cba4f6d | ||
|
|
776c63a1bf | ||
|
|
30fd27bfcf | ||
|
|
e47a0d5734 | ||
|
|
2ba75e7df7 | ||
|
|
67c545a483 | ||
|
|
b63fc743d9 | ||
|
|
da66b1b2ff | ||
|
|
d9c8caeff8 | ||
|
|
8735ab7664 | ||
|
|
0f91c06d0b | ||
|
|
21ffcf3809 | ||
|
|
31d6c1ef62 | ||
|
|
b00bc20c81 | ||
|
|
eb994dc65d | ||
|
|
87e32f571a | ||
|
|
9f02f6dead | ||
|
|
66c5202caf | ||
|
|
1288e92517 | ||
|
|
c7ad6c9ea2 | ||
|
|
23524c6422 | ||
|
|
b067f6b1f9 | ||
|
|
3b0e1faf5c | ||
|
|
e41668df53 | ||
|
|
2b5f9b718b | ||
|
|
1134d50492 | ||
|
|
08df28633f | ||
|
|
e5008abe56 | ||
|
|
40742fd850 | ||
|
|
7d4001eb39 | ||
|
|
dc6ca3532b | ||
|
|
e894b7cb4a | ||
|
|
e7268e0e04 | ||
|
|
d9541766dc | ||
|
|
cc9c35400f | ||
|
|
3391666598 | ||
|
|
5561236323 | ||
|
|
5c73615f90 | ||
|
|
1f5db9f0b1 | ||
|
|
e996279e8a | ||
|
|
93c1b28a60 | ||
|
|
101f2ffaa9 | ||
|
|
2a10236f91 | ||
|
|
573db1a193 | ||
|
|
fe63e35584 | ||
|
|
86c6de3bd8 | ||
|
|
a8845c48a9 | ||
|
|
cf6d266508 | ||
|
|
71e9830643 | ||
|
|
1da4472ca8 | ||
|
|
ff2591e544 | ||
|
|
23f5f11b27 | ||
|
|
746d449639 | ||
|
|
210e6690ce | ||
|
|
d068eeefc7 | ||
|
|
1e64192da5 | ||
|
|
66637998a6 | ||
|
|
b200288b38 | ||
|
|
0768bcf959 | ||
|
|
48892344b8 | ||
|
|
cc275ed02e | ||
|
|
9786953e5f | ||
|
|
bdc6fad818 | ||
|
|
ff569dc15b | ||
|
|
ea2cad06ea | ||
|
|
4030f4a9cd | ||
|
|
13c06afc67 | ||
|
|
d64dbdb027 | ||
|
|
8f21ace578 | ||
|
|
e08bb66891 | ||
|
|
173c994530 | ||
|
|
95ce97c85e | ||
|
|
9087169873 | ||
|
|
d08a5fe4aa | ||
|
|
6a4468c8f6 | ||
|
|
d084a13eb0 | ||
|
|
1cde5ec3e5 | ||
|
|
97703bdb38 | ||
|
|
d0c85419eb | ||
|
|
a8a306301b | ||
|
|
f23f28c12e | ||
|
|
623fcb3fd1 | ||
|
|
e093151db6 | ||
|
|
eefe3dfa71 | ||
|
|
6e8fc3ee5b | ||
|
|
17e8ab0f37 | ||
|
|
0d2f0c3e6f | ||
|
|
0661aa8853 | ||
|
|
a380212662 | ||
|
|
a45bcf8761 | ||
|
|
c198f21c92 | ||
|
|
5109dbba9e | ||
|
|
b90d6d7eed | ||
|
|
971c1cddf8 | ||
|
|
816797a32b | ||
|
|
c3921cbb6c | ||
|
|
e93dc2fe9a | ||
|
|
af899d3cfd | ||
|
|
6b60ee6bcc | ||
|
|
810dd3cdc7 | ||
|
|
374b399631 | ||
|
|
2484b8753b | ||
|
|
9730114172 | ||
|
|
c45a5033b9 | ||
|
|
b2e43c605e | ||
|
|
e3b057f915 | ||
|
|
2f557f777d | ||
|
|
42ee790512 | ||
|
|
ae9d204718 | ||
|
|
5c7de6181c | ||
|
|
268303a0a2 | ||
|
|
acc063e325 | ||
|
|
e384fb6153 | ||
|
|
f6085cff1f | ||
|
|
94ffc54325 | ||
|
|
ce89a6dfbc | ||
|
|
6925736030 | ||
|
|
edfacc7eba | ||
|
|
786218a114 | ||
|
|
52ad743bea | ||
|
|
0331945730 | ||
|
|
790807c016 | ||
|
|
45e08e6d7d | ||
|
|
5b3f845c83 | ||
|
|
4d6d5c5ac5 | ||
|
|
5583ea0f9a | ||
|
|
4286e75ca6 | ||
|
|
15880d1b84 | ||
|
|
0aee461156 | ||
|
|
b9969ce9ad | ||
|
|
254a310fe9 | ||
|
|
679cd60ce0 | ||
|
|
f73dbacd26 | ||
|
|
c6505952d5 | ||
|
|
4f0169ef8f | ||
|
|
15bf7cfa49 | ||
|
|
6df5091246 | ||
|
|
fbbfddaa37 | ||
|
|
f7b5e89ba8 | ||
|
|
c7bd565049 | ||
|
|
83dc6cc90b | ||
|
|
a449666a8c | ||
|
|
56476bc162 | ||
|
|
c30725bc09 | ||
|
|
3467951c5c | ||
|
|
9eb892ae27 | ||
|
|
00f30b8972 | ||
|
|
dba2f24364 | ||
|
|
04d15537e4 | ||
|
|
b5ae5f2fb5 | ||
|
|
9267de44c7 | ||
|
|
2b3ae0e522 | ||
|
|
c2e613d68b | ||
|
|
b221fe6961 | ||
|
|
10956e8c8e | ||
|
|
48f385e73a | ||
|
|
5c3cae597f | ||
|
|
4c028bd6de | ||
|
|
1390fa0cf9 | ||
|
|
de0528b1b8 | ||
|
|
dee305710c | ||
|
|
77a33ac86a | ||
|
|
a08019bc09 | ||
|
|
60638441aa | ||
|
|
9e981df990 | ||
|
|
73e828f940 | ||
|
|
017b9cb493 | ||
|
|
a165377d7a | ||
|
|
f7c16bf5a3 | ||
|
|
b5136ed913 | ||
|
|
2d37807401 | ||
|
|
fd3fffc0a1 | ||
|
|
fc8adf2a5c | ||
|
|
cf67a05dd1 | ||
|
|
d961bf36f7 | ||
|
|
a59dafab00 | ||
|
|
cf07304bae | ||
|
|
9524a1a9f7 | ||
|
|
4628946514 | ||
|
|
da3afe228e | ||
|
|
b8dafbb92e | ||
|
|
fdff244f15 | ||
|
|
27dc4c2bca | ||
|
|
aee14bb411 | ||
|
|
5f96b2e7f8 | ||
|
|
f9975520ab | ||
|
|
864f58d20e | ||
|
|
f42191973a | ||
|
|
d90f0b1002 | ||
|
|
4afa457eff | ||
|
|
e7a244a1ab | ||
|
|
b978809a59 | ||
|
|
6b35db8fbe | ||
|
|
384a0271bd | ||
|
|
134ef9df0f | ||
|
|
c3f3ecdb83 | ||
|
|
1824e061f4 | ||
|
|
be10aaeed5 | ||
|
|
ff9e100ac2 | ||
|
|
9133f20e64 | ||
|
|
2b0a0edf77 | ||
|
|
5e22a019e5 | ||
|
|
2a8c713ee0 | ||
|
|
f99df6e5e7 | ||
|
|
4a95740f96 | ||
|
|
5eee60ee17 | ||
|
|
e09d9d30dc | ||
|
|
c2f0b5b2d9 | ||
|
|
472eda9f06 | ||
|
|
c831d07573 | ||
|
|
90b51b7e46 | ||
|
|
cdc8a9cb8e | ||
|
|
790eb655a3 | ||
|
|
99584ce813 | ||
|
|
c2a5798905 | ||
|
|
951a822973 | ||
|
|
f5ac615b3c | ||
|
|
3b677f9156 | ||
|
|
9473a8ad5d | ||
|
|
56ef79ff45 | ||
|
|
d61e48ce79 | ||
|
|
86f15f9eb1 | ||
|
|
84e10530a5 | ||
|
|
2f74a720f5 | ||
|
|
511e50fe52 | ||
|
|
78da59fc71 | ||
|
|
36f70c3222 | ||
|
|
8f1c86a8c8 | ||
|
|
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 | ||
|
|
8c6776607b | ||
|
|
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 | ||
|
|
355cd4846a | ||
|
|
6be7ac2d14 | ||
|
|
8cbaf06cde | ||
|
|
1f8296dd01 | ||
|
|
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
@@ -1,2 +0,0 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
@@ -0,0 +1,15 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
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,13 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: qesoul
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -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,442 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to force the cross build on'
|
||||
required: false
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
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, macos-14] # macos-14+ is arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
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 protobuf-compiler libssl-dev
|
||||
- if: runner.os == 'Windows'
|
||||
name: Install Gstreamer
|
||||
run: |
|
||||
# Gstreamer
|
||||
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\'
|
||||
# Github runners work on both C or D drive and figuring out which was used is difficult
|
||||
if (-not (Test-Path -Path "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64" -PathType Container)) {
|
||||
$env:GSTREAMER_1_0_ROOT_MSVC_X86_64='D:\\gstreamer\1.0\msvc_x86_64\'
|
||||
}
|
||||
echo "GSTREAMER_1_0_ROOT_MSVC_X86_64=$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
||||
|
||||
# Proto buffers
|
||||
choco install -y --no-progress protoc --version=24.2.0
|
||||
|
||||
# Open SSL
|
||||
choco install -y --no-progress openssl --version=1.1.1.2100
|
||||
$env:OPENSSL_DIR=$env:SYSTEMDRIVE + '\Program Files\OpenSSL-Win64\'
|
||||
|
||||
# Alternative openssl location (depends on version that gets installed by choco)
|
||||
if (-not (Test-Path -Path "$env:OPENSSL_DIR" -PathType Container)) {
|
||||
$env:OPENSSL_DIR=$env:SYSTEMDRIVE + '\Program Files\OpenSSL\'
|
||||
}
|
||||
# Github runners work on both C or D drive and figuring out which was used is difficult
|
||||
if (-not (Test-Path -Path "$env:OPENSSL_DIR" -PathType Container)) {
|
||||
$env:OPENSSL_DIR='D:\\Program Files\OpenSSL-Win64\'
|
||||
}
|
||||
# Or course we could be on alternative location and drive....
|
||||
if (-not (Test-Path -Path "$env:OPENSSL_DIR" -PathType Container)) {
|
||||
$env:OPENSSL_DIR='D:\\Program Files\OpenSSL\'
|
||||
}
|
||||
|
||||
# Set up pkgconfig for gstreamer
|
||||
$env:PKG_CONFIG_PATH += ';' + $env:GSTREAMER_1_0_ROOT_MSVC_X86_64 + '\lib\pkgconfig'
|
||||
|
||||
# Set github vars
|
||||
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"
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "OPENSSL_DIR=$env:OPENSSL_DIR"
|
||||
Add-Content -Path $env:GITHUB_ENV -Value "PKG_CONFIG_PATH=$env:PKG_CONFIG_PATH"
|
||||
|
||||
# One last check on directories
|
||||
dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
|
||||
dir "$env:OPENSSL_DIR"
|
||||
- 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 protobuf openssl@1.1
|
||||
echo "OPENSSL_INCLUDE_DIR=$(brew --prefix openssl@1.1)/include/" >> "${GITHUB_ENV}"
|
||||
echo "OPENSSL_LIB_DIR=$(brew --prefix openssl@1.1)/lib/" >> "${GITHUB_ENV}"
|
||||
- name: Cache cargo registry
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cargo/registry
|
||||
key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
|
||||
- name: Cache cargo index
|
||||
uses: actions/cache@v4
|
||||
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@v4
|
||||
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
|
||||
export JEMALLOC_SYS_WITH_LG_PAGE=16
|
||||
cargo build --release --all-features
|
||||
- uses: actions/upload-artifact@v4
|
||||
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@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.tag }}
|
||||
- name: Install basic tools
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install --assume-yes --no-install-recommends curl ca-certificates protobuf-compiler
|
||||
- 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 }} \
|
||||
libssl-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 default 1.79.0
|
||||
rustup target add ${TARGET}
|
||||
env:
|
||||
TARGET: ${{ matrix.target }}
|
||||
- name: Build
|
||||
run: |
|
||||
cargo build --release --verbose --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 }}
|
||||
JEMALLOC_SYS_WITH_LG_PAGE: 16
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: release-${{ matrix.arch }}-bookworm
|
||||
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@v4
|
||||
with:
|
||||
ref: ${{ github.event.inputs.tag }}
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
- name: Convert username to lower case for docker
|
||||
id: string_user
|
||||
uses: ASzc/change-string-case-action@v6
|
||||
with:
|
||||
string: ${{ github.repository_owner }}
|
||||
- name: Convert repo to lower case for docker
|
||||
id: string_repo
|
||||
uses: ASzc/change-string-case-action@v6
|
||||
with:
|
||||
string: ${{ github.repository }}
|
||||
- name: Set up QEMU
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Set up Docker Buildx
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Login to Docker Hub
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: docker.io
|
||||
username: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
- name: Set Docker name with owner (package name) depending on if DOCKER_USERNAME is set
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
id: docker_repo
|
||||
shell: bash
|
||||
run: |
|
||||
if [ -z $DOCKER_USERNAME ]; then
|
||||
echo "DOCKER_NWO=${GITHUB_NWO}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
IFS='/' read -ra NWO_SPLIT <<< "$GITHUB_NWO"
|
||||
REPO_NAME=${NWO_SPLIT[1]}
|
||||
echo "DOCKER_NWO=${DOCKER_USERNAME}/${REPO_NAME}" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
env:
|
||||
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
|
||||
GITHUB_NWO: ${{ steps.string_repo.outputs.lowercase }}
|
||||
- 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.docker_repo.outputs.DOCKER_NWO }}
|
||||
- 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@v4
|
||||
with:
|
||||
name: release-amd64-bookworm
|
||||
path: linux/amd64
|
||||
- name: Download Linux armv7
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-armhf-bookworm
|
||||
path: linux/arm/v7
|
||||
- name: Download Linux arm64
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-arm64-bookworm
|
||||
path: linux/arm64
|
||||
- name: Download Linux i386
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-i386-bookworm
|
||||
path: linux/386
|
||||
- name: Push to Docker Hub
|
||||
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
|
||||
uses: docker/build-push-action@v5
|
||||
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=${{ vars.DOCKER_USERNAME || 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@v4
|
||||
- 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@v4
|
||||
with:
|
||||
name: release-windows-2022
|
||||
path: neolink_windows
|
||||
- name: Download Macos
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-macos-12
|
||||
path: neolink_macos_intel
|
||||
- name: Download Macos arm64
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-macos-14
|
||||
path: neolink_macos_m1
|
||||
- name: Download Linux x86_64
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-ubuntu-22.04
|
||||
path: neolink_linux_x86_64_ubuntu
|
||||
- name: Download Linux x86_64
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-amd64-bookworm
|
||||
path: neolink_linux_x86_64_bookworm
|
||||
- name: Download Linux armhf
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-armhf-bookworm
|
||||
path: neolink_linux_armhf
|
||||
- name: Download Linux arm64
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-arm64-bookworm
|
||||
path: neolink_linux_arm64
|
||||
- name: Download Linux i386
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-i386-bookworm
|
||||
path: neolink_linux_i386
|
||||
- name: Prepare releases
|
||||
run: |
|
||||
dirs=(
|
||||
neolink_windows
|
||||
neolink_macos_intel
|
||||
neolink_macos_m1
|
||||
neolink_linux_x86_64_ubuntu
|
||||
neolink_linux_x86_64_bookworm
|
||||
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_intel.zip
|
||||
neolink_macos_m1.zip
|
||||
neolink_linux_x86_64_ubuntu.zip
|
||||
neolink_linux_x86_64_bookworm.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@v6
|
||||
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@v6
|
||||
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}" =~ ^[v]?[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: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
|
||||
TOKEN: ${{ secrets.DOCKER_PRUNE_TOKEN }}
|
||||
@@ -0,0 +1,69 @@
|
||||
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@v4
|
||||
- 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 || exit 1
|
||||
cargo +nightly clippy --workspace --all-targets --no-default-features || exit 1
|
||||
cargo +nightly clippy --workspace --all-targets --no-default-features --features=gstreamer || exit 1
|
||||
cargo +nightly clippy --workspace --all-targets --no-default-features --features=pushnoti || exit 1
|
||||
|
||||
check_fmt:
|
||||
needs: pre_job
|
||||
if: needs.pre_job.outputs.should_skip != 'true'
|
||||
name: Rust-fmt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- 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@v4
|
||||
- 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 Pref
|
||||
+14
@@ -14,3 +14,17 @@
|
||||
|
||||
# Committing IntelliJ project files is a violation of intergalactic law
|
||||
.idea/
|
||||
|
||||
# We prefer to keep .vscode files outside the repo
|
||||
.vscode/
|
||||
# MacOS
|
||||
.DS_Store
|
||||
._.DS_Store
|
||||
**/.DS_Store
|
||||
**/._.DS_Store
|
||||
|
||||
# The token file for the FCM tests
|
||||
token.toml
|
||||
|
||||
# Debug FCM build
|
||||
./crates/fcm-push-listener/
|
||||
@@ -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
+3188
-518
File diff suppressed because it is too large.
Load diff
+56
-23
@@ -1,30 +1,63 @@
|
||||
[package]
|
||||
name = "neolink"
|
||||
description = "A standards-compliant bridge to Reolink IP cameras"
|
||||
version = "0.2.0"
|
||||
authors = ["George Hilliard <thirtythreeforty@gmail.com>"]
|
||||
version = "0.6.3-rc.3"
|
||||
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"
|
||||
base64 = "0.22.0"
|
||||
byte-slice-cast = {version = "1.2.2", optional = true}
|
||||
bytes = "1.6.0"
|
||||
clap = { version = "4.2.2", features = ["derive", "cargo"] }
|
||||
crossbeam-channel = {version = "0.5.8", optional = true}
|
||||
dirs = {version = "5.0.1", optional = true}
|
||||
env_logger = "0.11.3"
|
||||
fcm-push-listener = {version = "2.0.3", optional = true}
|
||||
futures = "0.3.28"
|
||||
gstreamer = {version = "0.23.0", optional = true}
|
||||
gstreamer-app = { version = "0.23.0", features = ["v1_20"], optional = true }
|
||||
gstreamer-rtsp = { version = "0.23.0", features = ["v1_20"], optional = true }
|
||||
gstreamer-rtsp-server = { version = "0.23.0", features = ["v1_20"], optional = true }
|
||||
heck = "0.5.0"
|
||||
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
|
||||
md5 = {version = "0.7.0", optional = true}
|
||||
neolink_core = { path = "crates/core", version = "0.6.3-rc.3" }
|
||||
once_cell = "1.19.0"
|
||||
quick-xml = { version = "0.36.1", features = ["serialize"] }
|
||||
regex = "1.7.3"
|
||||
rumqttc = "0.24.0"
|
||||
serde = { version = "1.0.160", features = ["derive"] }
|
||||
serde_json = "1.0.96"
|
||||
tokio = { version = "1.27.0", features = ["rt-multi-thread", "macros", "io-util", "tracing"] }
|
||||
tokio-stream = "0.1.12"
|
||||
tokio-util = { version = "0.7.7", features = ["full", "tracing"] }
|
||||
toml = "0.8.2"
|
||||
uuid = { version = "1.8.0", features = ["v4"] }
|
||||
validator = {version="0.18.1", features = ["derive"] }
|
||||
|
||||
[target.'cfg(not(target_env = "msvc"))'.dependencies]
|
||||
tikv-jemallocator = "0.5"
|
||||
|
||||
[features]
|
||||
default = ["gstreamer", "pushnoti"]
|
||||
gstreamer = [
|
||||
"dep:gstreamer",
|
||||
"dep:gstreamer-app",
|
||||
"dep:gstreamer-rtsp",
|
||||
"dep:gstreamer-rtsp-server",
|
||||
"dep:byte-slice-cast",
|
||||
"dep:crossbeam-channel"
|
||||
]
|
||||
pushnoti = [
|
||||
"dep:fcm-push-listener",
|
||||
"dep:dirs",
|
||||
"dep:md5"
|
||||
]
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
# 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-bookworm 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
|
||||
#
|
||||
# We prefer copying from artifact to reduce
|
||||
# build time on the github runners
|
||||
#
|
||||
# Because of this though, during normal
|
||||
# github runner ops we are not testing the
|
||||
# docker to see if it will build from scratch
|
||||
# so if it is failing please make a PR
|
||||
#
|
||||
# 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 upgrade -y && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
openssl \
|
||||
libssl-dev \
|
||||
ca-certificates \
|
||||
libgstrtspserver-1.0-dev \
|
||||
libgstreamer1.0-dev \
|
||||
libgtk2.0-dev \
|
||||
protobuf-compiler \
|
||||
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:bookworm-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 upgrade -y && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
openssl \
|
||||
dnsutils \
|
||||
iputils-ping \
|
||||
ca-certificates \
|
||||
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 \
|
||||
gstreamer1.0-libav && \
|
||||
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 && \
|
||||
mkdir -m 0700 /root/.config/
|
||||
|
||||
ENV NEO_LINK_MODE="rtsp" NEO_LINK_PORT=8554
|
||||
|
||||
CMD /usr/local/bin/neolink "${NEO_LINK_MODE}" --config /etc/neolink.toml
|
||||
ENTRYPOINT ["/entrypoint.sh"]
|
||||
EXPOSE ${NEO_LINK_PORT}
|
||||
|
||||
@@ -1,122 +1,585 @@
|
||||
# Neolink
|
||||
|
||||

|
||||

|
||||
[](https://deps.rs/repo/github/QuantumEntangledAndy/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 missing gstreamer plugins
|
||||
- Protocol more closely follows official 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 official 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 \
|
||||
libssl
|
||||
```
|
||||
|
||||
Note that if you use Chocolatey to install Gstreamer, it does this automatically.
|
||||
- **Windows**: You may also need to
|
||||
[install openssl](https://wiki.openssl.org/index.php/Binaries)
|
||||
- **Macos**: You may also need to
|
||||
[install openssl](https://wiki.openssl.org/index.php/Binaries) or
|
||||
`brew install openssl@1.1`
|
||||
- **Ubuntu/Debian**: Install the `libssl` package
|
||||
|
||||
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:
|
||||
Make a config file see below.
|
||||
|
||||
```
|
||||
neolink --config my_config.toml
|
||||
## Config/Usage
|
||||
|
||||
### 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 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 we 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 reolink.
|
||||
|
||||
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/recieves a connect
|
||||
request from the reolink servers the camera will initiate a connection
|
||||
to neolink. This requires that our IP and reolink are reachable 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.
|
||||
#### Cellular
|
||||
|
||||
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.
|
||||
Cellular cameras should select `"cellular"` which only enables `map` and
|
||||
`relay` since `local` and `remote` will always fail
|
||||
|
||||
## Development
|
||||
|
||||
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
|
||||
```toml
|
||||
discovery = "cellular"
|
||||
```
|
||||
|
||||
from this top directory.
|
||||
See the sample config file for more details.
|
||||
|
||||
### Baichuan Protocol
|
||||
### MQTT
|
||||
|
||||
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.
|
||||
To use mqtt you will need to adjust your config file as such:
|
||||
|
||||
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.
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
### Baichuan dissector
|
||||
[mqtt]
|
||||
broker_addr = "127.0.0.1" # Address of the mqtt server
|
||||
port = 1883 # mqtt servers port
|
||||
credentials = ["username", "password"] # mqtt server login details
|
||||
|
||||
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.
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
```
|
||||
|
||||
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.
|
||||
Then to start the mqtt+rtsp connection run the following:
|
||||
|
||||
```bash
|
||||
./neolink mqtt-rtsp --config=neolink.toml
|
||||
```
|
||||
|
||||
OR for only mqtt
|
||||
|
||||
```bash
|
||||
./neolink mqtt --config=neolink.toml
|
||||
```
|
||||
|
||||
Neolink will publish these messages:
|
||||
|
||||
Messages that are prefixed with `neolink/`
|
||||
|
||||
- `/status` Tracks the connection of neolink, `connected` for ready `offline`
|
||||
for not ready this is a LastWill message
|
||||
- `/config` The configuration file used to start neolink, you can publish to
|
||||
this to **temporarily** alter the live configuration
|
||||
- `/config/status` If you publish to `/config` then any errors from your
|
||||
publish config will show here, or `Ok(())` if no errors and finished loading
|
||||
|
||||
Messages that are prefixed with `neolink/{CAMERANAME}`
|
||||
|
||||
Control messages:
|
||||
|
||||
- `/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/ptz/preset [id]` Move the camera to a PTZ preset
|
||||
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID
|
||||
and name
|
||||
- `/control/zoom (amount)` Zoom the camera to the specified amount. Example: 1.0
|
||||
for normal and 3.5 for 3.5x zoom factor. This only works on cameras that support
|
||||
zoom
|
||||
- `/control/pir [on|off]`
|
||||
- `/control/floodlight [on|off]` Turns floodlight (if equipped) on/off
|
||||
- `/control/floodlight_tasks [on|off]` Turns floodlight (if equipped) tasks on/off
|
||||
This is the automatic tasks such as on motion and night triggers
|
||||
- `/control/wakeup (mins)` For cameras that are using `idle_disconnect` this will
|
||||
force a wakeup for at least the given minutes
|
||||
- `/control/siren on` Signal the siren, the message is always "on" as there is no
|
||||
"off" signal for the siren
|
||||
|
||||
Status Messages:
|
||||
|
||||
- `/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/battery_level` A simple % value of current battery level, only
|
||||
published when `enable_battery` is true in the config
|
||||
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
|
||||
pir status
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion
|
||||
and `off` for still, only published when `enable_moton` is true in the config
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded
|
||||
version of the PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 2s. Not
|
||||
every camera supports the snapshot command needed for this. In such cases
|
||||
there will be no `/status/preview` message. Only published when
|
||||
`enable_preview` is true in the config
|
||||
- `/status/floodlight_tasks` The current status of the floodlight tasks
|
||||
used updated every 2s by default
|
||||
|
||||
Query Messages:
|
||||
|
||||
- `/query/battery` Request that the camera reports its battery level
|
||||
- `/query/pir` Request that the camera reports its pir status
|
||||
- `/query/ptz/preset` Request that the camera reports its PTZ presets
|
||||
- `/query/preview` Request that the camera post a base64 encoded jpeg
|
||||
of the stream to `/status/preview` now, ignoring the timer
|
||||
|
||||
### Controlling RTSP from MQTT
|
||||
|
||||
If neolink is started with `mqtt-rtsp` then the `/neolink/config` can be used
|
||||
to control the RTSP
|
||||
|
||||
Changes made to the config by publishing to `/neolink/config` should be
|
||||
reflected in the rtsp
|
||||
|
||||
These include changing the:
|
||||
|
||||
- Available users
|
||||
|
||||
```toml
|
||||
[[users]]
|
||||
name = "me"
|
||||
pass = "mepass"
|
||||
```
|
||||
|
||||
- Permitted users on a camera
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
permitted_users = [ "me" ]
|
||||
```
|
||||
|
||||
- Available streams
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
stream = "Main"
|
||||
```
|
||||
|
||||
Setting a value of `None` will disable the stream
|
||||
|
||||
- Disable the entire camera (mqtt updates and all)
|
||||
|
||||
```toml
|
||||
[[cameras]]
|
||||
enabled = false
|
||||
```
|
||||
|
||||
### MQTT Disable Features
|
||||
|
||||
Certain features like preview and motion detection may not be desired
|
||||
you can disable them with the following config options.
|
||||
Disabling these may help to conserve battery
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
[mqtt]
|
||||
broker_addr = "127.0.0.1" # Address of the mqtt server
|
||||
port = 1883 # mqtt servers port
|
||||
credentials = ["username", "password"] # mqtt server login details
|
||||
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
[cameras.mqtt]
|
||||
enable_motion = false # motion detection
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
#
|
||||
enable_light = false # flood lights only available on some camera
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
#
|
||||
enable_battery = false # battery updates in `/status/battery_level`
|
||||
#
|
||||
enable_preview = false # preview image in `/status/preview`
|
||||
#
|
||||
enable_floodlight = false # preview image in `/status/floodlight_tasks`
|
||||
#
|
||||
battery_update = 2000 # Number of ms between `/status/battery_level` updates
|
||||
#
|
||||
preview_update = 2000 # Number of ms between `/status/preview` updates
|
||||
#
|
||||
floodlight_update = 2000 # Number of ms between `/status/floodlight_tasks` updates
|
||||
```
|
||||
|
||||
#### MQTT Discovery
|
||||
|
||||
[MQTT Discovery](https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery)
|
||||
is partially supported. Currently, discovery is opt-in and camera features
|
||||
must be manually specified.
|
||||
|
||||
```toml
|
||||
[cameras.mqtt]
|
||||
# <see above>
|
||||
[cameras.mqtt.discovery]
|
||||
topic = "homeassistant"
|
||||
features = ["floodlight"]
|
||||
```
|
||||
|
||||
Available features are:
|
||||
|
||||
- `floodlight`: This adds a light control to home assistant
|
||||
- `camera`: This adds a camera preview to home assistant. It is only updated
|
||||
every 0.5s and cannot be much more than that since it is updated over mqtt
|
||||
not over RTSP. Not every camera supports the snapshot command needed for
|
||||
this. In such cases there will be no `/status/preview` message.
|
||||
- `led`: This adds a switch to chage the LED status light on/off to home
|
||||
assistant
|
||||
- `ir`: This adds a selection switch to chage the IR light on/off/auto to home
|
||||
assistant
|
||||
- `motion`: This adds a motion detection binary sensor to home assistant
|
||||
- `reboot`: This adds a reboot button to home assistant
|
||||
- `pt`: This adds a selection of buttons to control the pan and tilt of the
|
||||
camera
|
||||
- `battery`: This adds a battery level sensor to home assistant
|
||||
- `siren`: Adds a siren button to home assistant
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### Idle Disconnects
|
||||
|
||||
To really save battery we need to disconnect the camera when it is idle.
|
||||
|
||||
To acheieve this you can add `idle_disconnect = true` to the `[[cameras]]`
|
||||
section
|
||||
|
||||
```toml
|
||||
bind = "0.0.0.0"
|
||||
|
||||
[[cameras]]
|
||||
name = "Camera01"
|
||||
username = "admin"
|
||||
password = "password"
|
||||
uid = "ABCDEF0123456789"
|
||||
idle_disconnect = true
|
||||
[cameras.pause]
|
||||
on_client = true # Should pause when no rtsp client
|
||||
timeout = 2.1 # How long to wait after motion stops before pausing
|
||||
```
|
||||
|
||||
When `idle_disconnect = true` neolink will disconnect from the camera 30s
|
||||
after it stops being used.
|
||||
|
||||
Neolink considers it as being used if there is an active stream running, or
|
||||
if there is motion being detected or an mqtt command being run
|
||||
|
||||
You can make neolink stop active streams when there are no rtsp clients using
|
||||
|
||||
```toml
|
||||
[cameras.pause]
|
||||
on_client = true # Should pause when no rtsp client
|
||||
```
|
||||
|
||||
Once in the disconnected state. Neolink will stay disconnected until there is a
|
||||
new requested activation such as a client connecting or an mqtt command
|
||||
|
||||
Neolink will also wake up on push notifications from the camera. These are usually
|
||||
sent by the camera on motion or PIR alarms. To disable this you can set
|
||||
`push_notifications = false` in the `[[cameras]]` config
|
||||
|
||||
### 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
|
||||
|
||||
# Add `-e "RUST_LOG=debug"` to run with debug logs
|
||||
#
|
||||
# --network host is only needed if you require to connect
|
||||
# via local broadcasts. If you can connect via any other
|
||||
# method then normal bridge mode should work fine
|
||||
# and you can ommit this option. Not all OSes support
|
||||
# network=host, notably macos lacks this option.
|
||||
docker run --network host --volume=$PWD/config.toml:/etc/neolink.toml quantumentangledandy/neolink
|
||||
```
|
||||
|
||||
#### Environmental Variables
|
||||
|
||||
There are currently 2 environmental variables available as part of the container:
|
||||
|
||||
- `NEO_LINK_MODE`: defaults to `"rtsp"` if not set, other options are "mqtt" or "mqtt-rtsp".
|
||||
- `NEO_LINK_PORT`: defaults to `8554`, set this to your required port value.
|
||||
|
||||
### 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 of
|
||||
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.
|
||||
|
||||
Some cameras do not support the SNAP command that is used to generate the image
|
||||
on the camera. If this is the case with your camera you can try the
|
||||
`--use-stream` option which will instead create a jpeg by transcoding the video
|
||||
stream.
|
||||
|
||||
### Battery Levels
|
||||
|
||||
You can get the battery level and status using
|
||||
|
||||
```bash
|
||||
neolink battery --config=config.toml CameraName
|
||||
```
|
||||
|
||||
This will produce an xml formatted battery status on stdout for processing
|
||||
|
||||
### PIR
|
||||
|
||||
You can control pir using
|
||||
|
||||
```bash
|
||||
neolink pir --config=config.toml CameraName [on|off]
|
||||
```
|
||||
|
||||
This will turn the PIR on or off
|
||||
|
||||
### Reboot
|
||||
|
||||
You can reboot a camera using
|
||||
|
||||
```bash
|
||||
neolink reboot --config=config.toml CameraName
|
||||
```
|
||||
|
||||
### Status LED
|
||||
|
||||
You can control the status LED using
|
||||
|
||||
```bash
|
||||
neolink status-light --config=config.toml CameraName [on|off]
|
||||
```
|
||||
|
||||
### Talk
|
||||
|
||||
You can talk over the camera using
|
||||
|
||||
```bash
|
||||
neolink talk --config=config.toml --adpcm-file=data.adpc\
|
||||
--sample-rate=16000 --block-size=512 CameraName
|
||||
```
|
||||
|
||||
Where the sounds is ADPCM encoded
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
neolink talk --config=config.toml --microphone CameraName
|
||||
```
|
||||
|
||||
Which uses the default microphone which depends on
|
||||
[gstreamer](https://gstreamer.freedesktop.org/documentation/autodetect/autoaudiosrc.html?gi-language=c#autoaudiosrc-page)
|
||||
|
||||
### PTZ
|
||||
|
||||
You can control the PTZ using
|
||||
|
||||
```bash
|
||||
neolink ptz --config=config.toml CameraName control 32 [left|right|up|down|in|out]
|
||||
```
|
||||
|
||||
Where 32 is the speed. Not all cameras support speed
|
||||
|
||||
Some cameras also support preset positions
|
||||
|
||||
```bash
|
||||
# Print the list of preset positions
|
||||
neolink ptz --config=config.toml CameraName preset
|
||||
# Move the camera to preset ID 0
|
||||
neolink ptz --config=config.toml CameraName preset 0
|
||||
# Save the current position as preset ID 0 with name PresetName
|
||||
neolink ptz --config=config.toml CameraName assign 0 PresetName
|
||||
```
|
||||
|
||||
To change the zoom level use the following:
|
||||
|
||||
```bash
|
||||
# Zoom the camera to 2.5x
|
||||
neolink ptz --config=config.toml CameraName zoom 2.5
|
||||
```
|
||||
|
||||
With 1.0 being normal and 2.5 being 2.5x zoom
|
||||
|
||||
## 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.
|
||||
|
||||
## Donations
|
||||
|
||||
If you find this code helpful please consider supporting development.
|
||||
|
||||
[](https://ko-fi.com/G2G5HOYIZ)
|
||||
@@ -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,46 @@ 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());
|
||||
let openssl_dir = env::var_os("OPENSSL_1_1_ROOT_MACOSX")
|
||||
.and_then(|x| x.into_string().ok())
|
||||
.unwrap_or_else(|| r"/usr/local/opt/openssl@1.1".to_string());
|
||||
|
||||
println!(
|
||||
r"cargo:rustc-link-search=native={}/lib;{}/lib",
|
||||
gstreamer_dir, openssl_dir
|
||||
);
|
||||
println!(
|
||||
r"cargo:rustc-link-arg=-Wl,-rpath,{}/lib;{}/lib/",
|
||||
gstreamer_dir, openssl_dir
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
|
||||
fn platform_cfg() {}
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "neolink_core"
|
||||
description = "Core services and structure for Reolink IP cameras"
|
||||
version = "0.6.3-rc.3"
|
||||
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.12.0"
|
||||
futures = "0.3.28"
|
||||
get_if_addrs = "0.5.3"
|
||||
lazy_static = "1.4.0"
|
||||
log = "0.4.17"
|
||||
md5 = "0.7.0"
|
||||
nom = { version = "7.1.3", features = ["alloc"] }
|
||||
quick-xml = { version = "0.36.0", features = ["serialize"] }
|
||||
rand = "0.8.5"
|
||||
regex = "1.7.3"
|
||||
serde = { version = "1.0.106", features = ["derive"] }
|
||||
thiserror = "1.0.58"
|
||||
time = { version = "0.3.36" , 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"] }
|
||||
|
||||
[dev-dependencies]
|
||||
assert_matches = "1.5.0"
|
||||
env_logger = "*"
|
||||
indoc = "2.0.1"
|
||||
@@ -0,0 +1,152 @@
|
||||
//! 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_with_debug(credentials: Credentials) -> Self {
|
||||
let mut context = BcContext::new(credentials);
|
||||
|
||||
context.debug_on();
|
||||
Self { context }
|
||||
}
|
||||
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();
|
||||
const BC_ENCRYPTED: EncryptionProtocol = EncryptionProtocol::BCEncrypt;
|
||||
let buf: Vec<u8> = Default::default();
|
||||
let enc_protocol: &EncryptionProtocol = match self.context.get_encrypted() {
|
||||
EncryptionProtocol::Aes { .. } | EncryptionProtocol::FullAes { .. }
|
||||
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)
|
||||
&BC_ENCRYPTED
|
||||
}
|
||||
n => n,
|
||||
};
|
||||
let buf = item.serialize(buf, enc_protocol)?;
|
||||
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),
|
||||
)),
|
||||
0x12 => self.context.set_encrypted(EncryptionProtocol::full_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,122 @@
|
||||
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";
|
||||
|
||||
/// These are the encyption modes supported by the camera
|
||||
///
|
||||
/// The mode is negotiated during login
|
||||
#[derive(Debug, Clone)]
|
||||
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 {
|
||||
/// The encryptor
|
||||
enc: Aes128CfbEnc,
|
||||
/// The decryptor
|
||||
dec: Aes128CfbDec,
|
||||
},
|
||||
/// Same as Aes but the media stream is also encrypted and not just
|
||||
/// the control commands
|
||||
FullAes {
|
||||
/// The encryptor
|
||||
enc: Aes128CfbEnc,
|
||||
/// The decryptor
|
||||
dec: Aes128CfbDec,
|
||||
},
|
||||
}
|
||||
|
||||
impl EncryptionProtocol {
|
||||
/// Helper to make unencrypted
|
||||
pub fn unencrypted() -> Self {
|
||||
EncryptionProtocol::Unencrypted
|
||||
}
|
||||
/// Helper to make bcencrypted
|
||||
pub fn bcencrypt() -> Self {
|
||||
EncryptionProtocol::BCEncrypt
|
||||
}
|
||||
/// Helper to make aes
|
||||
pub fn aes(key: [u8; 16]) -> Self {
|
||||
EncryptionProtocol::Aes {
|
||||
enc: Aes128CfbEnc::new(key.as_slice().into(), IV.into()),
|
||||
dec: Aes128CfbDec::new(key.as_slice().into(), IV.into()),
|
||||
}
|
||||
}
|
||||
/// Helper to make full aes
|
||||
pub fn full_aes(key: [u8; 16]) -> Self {
|
||||
EncryptionProtocol::FullAes {
|
||||
enc: Aes128CfbEnc::new(key.as_slice().into(), IV.into()),
|
||||
dec: Aes128CfbDec::new(key.as_slice().into(), IV.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrypt the data, offset comes from the header of the packet
|
||||
pub fn decrypt(&self, offset: u32, buf: &[u8]) -> Vec<u8> {
|
||||
match self {
|
||||
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 { dec, .. } | EncryptionProtocol::FullAes { dec, .. } => {
|
||||
// AES decryption
|
||||
|
||||
let mut decrypted = buf.to_vec();
|
||||
dec.clone().decrypt(&mut decrypted);
|
||||
decrypted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encrypt the data, offset comes from the header of the packet
|
||||
pub fn encrypt(&self, offset: u32, buf: &[u8]) -> Vec<u8> {
|
||||
match self {
|
||||
EncryptionProtocol::Unencrypted => {
|
||||
// Encrypt is the same as decrypt
|
||||
self.decrypt(offset, buf)
|
||||
}
|
||||
EncryptionProtocol::BCEncrypt => {
|
||||
// Encrypt is the same as decrypt
|
||||
self.decrypt(offset, buf)
|
||||
}
|
||||
EncryptionProtocol::Aes { enc, .. } | EncryptionProtocol::FullAes { enc, .. } => {
|
||||
// AES encryption
|
||||
let mut encrypted = buf.to_vec();
|
||||
enc.clone().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 = EncryptionProtocol::BCEncrypt.decrypt(0, &sample[..]);
|
||||
assert_eq!(decrypted, &should_be[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xml_crypto_roundtrip() {
|
||||
let zeros: [u8; 256] = [0; 256];
|
||||
|
||||
let decrypted = EncryptionProtocol::BCEncrypt.encrypt(0, &zeros[..]);
|
||||
let encrypted = EncryptionProtocol::BCEncrypt.decrypt(0, &decrypted[..]);
|
||||
assert_eq!(encrypted, &zeros[..]);
|
||||
}
|
||||
@@ -0,0 +1,582 @@
|
||||
use super::model::*;
|
||||
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> {
|
||||
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);
|
||||
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>(input: I, ctx: &'static str, kind: ErrorKind) -> E
|
||||
where
|
||||
I: std::marker::Copy,
|
||||
E: ParseError<I> + 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 = encryption_protocol.decrypt(header.channel_id as u32, ext_buf);
|
||||
&decrypted
|
||||
}
|
||||
};
|
||||
|
||||
let mut in_binary = false;
|
||||
let mut encrypted_len = None;
|
||||
// Now we'll take the buffer that Nom gave a ref to and parse it.
|
||||
let extension = if ext_len > 0 {
|
||||
if context.debug {
|
||||
println!(
|
||||
"Extension Txt: {:?}",
|
||||
String::from_utf8(processed_ext_buf.to_vec()).unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
// 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(|_| {
|
||||
log::error!("Extension buffer: {:?}", processed_ext_buf);
|
||||
Err::Error(make_error(
|
||||
buf,
|
||||
"Unable to parse Extension XML",
|
||||
ErrorKind::MapRes,
|
||||
))
|
||||
})?;
|
||||
if let Extension {
|
||||
binary_data: Some(1),
|
||||
encrypt_len,
|
||||
..
|
||||
} = parsed
|
||||
{
|
||||
// In binary so tell the current context that we need to treat the payload as binary
|
||||
in_binary = true;
|
||||
encrypted_len = encrypt_len;
|
||||
}
|
||||
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
|
||||
const UNENCRYPTED: EncryptionProtocol = EncryptionProtocol::Unencrypted;
|
||||
const BC_ENCRYPTED: EncryptionProtocol = EncryptionProtocol::BCEncrypt;
|
||||
let encryption_protocol = match header {
|
||||
BcHeader {
|
||||
msg_id: 1,
|
||||
response_code,
|
||||
..
|
||||
} if (response_code >> 8) & 0xff == 0xdd => {
|
||||
// 0xdd means we are setting the encryption method
|
||||
// Durig login, the max encryption is BcEncrypt since
|
||||
// the nonce has not been exchanged yet
|
||||
match response_code & 0xff {
|
||||
0x00 => &UNENCRYPTED,
|
||||
_ => &BC_ENCRYPTED,
|
||||
}
|
||||
}
|
||||
BcHeader { msg_id: 1, .. } => {
|
||||
match &context.get_encrypted() {
|
||||
EncryptionProtocol::Aes { .. } | EncryptionProtocol::FullAes { .. } => {
|
||||
// During login max is BcEncrypt
|
||||
&BC_ENCRYPTED
|
||||
}
|
||||
n => *n,
|
||||
}
|
||||
}
|
||||
_ => context.get_encrypted(),
|
||||
};
|
||||
|
||||
let processed_payload_buf =
|
||||
encryption_protocol.decrypt(header.channel_id as u32, payload_buf);
|
||||
if context.in_bin_mode.contains(&(header.msg_num)) || in_binary {
|
||||
payload = match (context.get_encrypted(), encrypted_len) {
|
||||
(EncryptionProtocol::FullAes { .. }, Some(encrypted_len)) => {
|
||||
// if if context.debug {
|
||||
// log::trace!("Binary: {:X?}", &processed_payload_buf[0..30]);
|
||||
// }
|
||||
Some(BcPayloads::Binary(
|
||||
processed_payload_buf[0..(encrypted_len as usize)].to_vec(),
|
||||
))
|
||||
}
|
||||
_ => Some(BcPayloads::Binary(payload_buf.to_vec())),
|
||||
};
|
||||
} else {
|
||||
if context.debug {
|
||||
println!(
|
||||
"Payload Txt: {:?}",
|
||||
String::from_utf8(processed_payload_buf.to_vec())
|
||||
.unwrap_or("Not Text".to_string())
|
||||
);
|
||||
}
|
||||
let xml = BcXml::try_parse(processed_payload_buf.as_slice()).map_err(|e| {
|
||||
error!("header.msg_id: {}", header.msg_id);
|
||||
error!(
|
||||
"processed_payload_buf: {:X?}::{:?}",
|
||||
processed_payload_buf,
|
||||
std::str::from_utf8(&processed_payload_buf)
|
||||
);
|
||||
log::error!("e: {:?}", e);
|
||||
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 || *x == MAGIC_HEADER_REV),
|
||||
)(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;
|
||||
use env_logger::Env;
|
||||
|
||||
fn init() {
|
||||
let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info"))
|
||||
.is_test(true)
|
||||
.try_init();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bc_modern_login() {
|
||||
init();
|
||||
|
||||
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
|
||||
fn test_03_enc_login() {
|
||||
init();
|
||||
|
||||
let sample = include_bytes!("samples/battery_enc.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, 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() {
|
||||
init();
|
||||
|
||||
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() {
|
||||
init();
|
||||
|
||||
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() {
|
||||
init();
|
||||
|
||||
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() {
|
||||
init();
|
||||
|
||||
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 official clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_externstream() {
|
||||
init();
|
||||
|
||||
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 official clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_substream() {
|
||||
init();
|
||||
|
||||
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 official clients
|
||||
//
|
||||
// They also have extra streams
|
||||
fn test_bc_b800_mainstream() {
|
||||
init();
|
||||
|
||||
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,44 @@
|
||||
//! 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;
|
||||
|
||||
/// Contains the encryption protocols
|
||||
pub mod crypto;
|
||||
|
||||
pub(crate) mod codex;
|
||||
@@ -0,0 +1,369 @@
|
||||
use crate::Credentials;
|
||||
|
||||
pub use super::crypto::EncryptionProtocol;
|
||||
pub use super::xml::{BcPayloads, BcXml, Extension};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const MAGIC_HEADER: u32 = 0x0abcdef0;
|
||||
/// Sometimes will get the BE magic header even though all other numbers are LE?
|
||||
/// Seems to happens with certain messages like snap that produce jpegs, so perhaps it
|
||||
/// it is meant to be a hint as to the endianess of the binary payload
|
||||
pub(super) const MAGIC_HEADER_REV: u32 = 0x0fedcba0;
|
||||
|
||||
/// 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;
|
||||
/// PTZ goto preset position
|
||||
pub const MSG_ID_PTZ_CONTROL_PRESET: u32 = 19;
|
||||
/// 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;
|
||||
/// Set service ports
|
||||
pub const MSG_ID_SET_SERVICE_PORTS: u32 = 36;
|
||||
/// Get service ports
|
||||
pub const MSG_ID_GET_SERVICE_PORTS: u32 = 37;
|
||||
/// Get Email setting
|
||||
pub const MSG_ID_GET_EMAIL: u32 = 42;
|
||||
/// Set email settings
|
||||
pub const MSG_ID_SET_EMAIL: u32 = 43;
|
||||
/// 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;
|
||||
/// Setting general system info (clock mostly) messages have this ID
|
||||
pub const MSG_ID_SET_GENERAL: u32 = 105;
|
||||
/// Snapshot to get a jpeg image
|
||||
pub const MSG_ID_SNAP: u32 = 109;
|
||||
/// Used to grab the UID
|
||||
pub const MSG_ID_UID: u32 = 114;
|
||||
/// Used to pass the token and client ID for push notifications
|
||||
pub const MSG_ID_PUSH_INFO: u32 = 124;
|
||||
/// Send a test email configuration
|
||||
pub const MSG_ID_TEST_EMAIL: u32 = 141;
|
||||
/// StreamInfoList messages have this ID
|
||||
pub const MSG_ID_STREAM_INFO_LIST: u32 = 146;
|
||||
/// Used to get the abilities of a user
|
||||
pub const MSG_ID_ABILITY_INFO: u32 = 151;
|
||||
/// Get the available PTZ position presets
|
||||
pub const MSG_ID_GET_PTZ_PRESET: u32 = 190;
|
||||
/// Get the support details (ptz, talk et)
|
||||
pub const MSG_ID_GET_SUPPORT: u32 = 199;
|
||||
/// 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;
|
||||
/// Set Email Task
|
||||
pub const MSG_ID_SET_EMAIL_TASK: u32 = 216;
|
||||
/// Get Email Task
|
||||
pub const MSG_ID_GET_EMAIL_TASK: u32 = 217;
|
||||
/// 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;
|
||||
/// Used for to play sounds like the siren
|
||||
pub const MSG_ID_PLAY_AUDIO: u32 = 263;
|
||||
/// Manual Floodlight Control
|
||||
pub const MSG_ID_FLOODLIGHT_MANUAL: u32 = 288;
|
||||
/// Set Floodlight tasks xml
|
||||
pub const MSG_ID_FLOODLIGHT_TASKS_WRITE: u32 = 290;
|
||||
/// Floodlight status report from the camera
|
||||
pub const MSG_ID_FLOODLIGHT_STATUS_LIST: u32 = 291;
|
||||
/// Used for camera Zoom read
|
||||
pub const MSG_ID_GET_ZOOM_FOCUS: u32 = 294;
|
||||
/// Used for camera Zoom write
|
||||
pub const MSG_ID_SET_ZOOM_FOCUS: u32 = 295;
|
||||
/// Get the floodlight task xml
|
||||
pub const MSG_ID_FLOODLIGHT_TASKS_READ: u32 = 438;
|
||||
|
||||
/// 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,
|
||||
},
|
||||
/// Sent to upgrade to modern and not exposed the MD5 username/password
|
||||
LoginUpgrade,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct BcContext {
|
||||
pub(crate) credentials: Credentials,
|
||||
pub(crate) in_bin_mode: HashSet<u16>,
|
||||
pub(crate) encryption_protocol: EncryptionProtocol,
|
||||
pub(crate) debug: bool,
|
||||
}
|
||||
|
||||
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,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
debug: false,
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
pub(crate) fn debug_on(&mut self) {
|
||||
self.debug = true;
|
||||
}
|
||||
}
|
||||
|
||||
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.
@@ -0,0 +1,212 @@
|
||||
use super::model::*;
|
||||
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;
|
||||
|
||||
impl Bc {
|
||||
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 payload_offset;
|
||||
|
||||
match &self.body {
|
||||
BcBody::ModernMsg(ref modern) => {
|
||||
// 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![],
|
||||
)?;
|
||||
|
||||
// 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.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![]).map_err(|e| {
|
||||
error!("Send error: {}", e);
|
||||
e
|
||||
})?;
|
||||
body_buf = buf;
|
||||
payload_offset = None;
|
||||
}
|
||||
};
|
||||
|
||||
// Now have enough info to create the header
|
||||
let header = BcHeader::from_meta(&self.meta, body_buf.len() as u32, payload_offset);
|
||||
|
||||
let (buf, _n) = gen(tuple((bc_header(&header), slice(body_buf))), buf)?;
|
||||
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
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 = encryption_protocol.encrypt(enc_offset, &xml_bytes);
|
||||
slice(enc_bytes)
|
||||
}
|
||||
|
||||
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();
|
||||
// log::debug!(
|
||||
// "Seialised as: {:?}",
|
||||
// std::str::from_utf8(xml_bytes.as_ref())
|
||||
// );
|
||||
encryption_protocol.encrypt(enc_offset, &xml_bytes)
|
||||
}
|
||||
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_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.payload_offset, le_u32),
|
||||
))
|
||||
}
|
||||
|
||||
fn bc_legacy<W: Write>(legacy: &'_ LegacyMsg) -> impl SerializeFn<W> + '_ {
|
||||
move |out: WriteContext<W>| {
|
||||
use LegacyMsg::*;
|
||||
match legacy {
|
||||
LoginMsg { username, password } => {
|
||||
if username.len() != 32 || password.len() != 32 {
|
||||
// Error handling could be improved here...
|
||||
return Err(GenError::CustomError(0));
|
||||
}
|
||||
tuple((
|
||||
slice(username),
|
||||
slice(password),
|
||||
// Login messages are 1836 bytes total, username/password
|
||||
// take up 32 chars each, 1772 zeros follow
|
||||
slice(&[0u8; 1772][..]),
|
||||
))(out)
|
||||
}
|
||||
LoginUpgrade => {
|
||||
// Write nothing as it is header only
|
||||
slice(&[])(out)
|
||||
}
|
||||
UnknownMsg => {
|
||||
panic!("Cannot serialize an unknown message!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the supplied serializer with the Option's interior data if present
|
||||
fn opt<W, T, F>(opt: Option<T>, ser: impl Fn(T) -> F) -> impl SerializeFn<W>
|
||||
where
|
||||
F: SerializeFn<W>,
|
||||
T: Copy,
|
||||
W: Write,
|
||||
{
|
||||
move |buf: WriteContext<W>| {
|
||||
if let Some(val) = opt {
|
||||
ser(val)(buf)
|
||||
} else {
|
||||
do_nothing()(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn opt_ref<'a, W, T, F, S>(opt: &'a Option<T>, ser: S) -> impl SerializeFn<W> + 'a
|
||||
where
|
||||
F: SerializeFn<W>,
|
||||
W: Write,
|
||||
S: Fn(&'a T) -> F + 'a,
|
||||
{
|
||||
move |buf: WriteContext<W>| {
|
||||
if let Some(ref val) = opt {
|
||||
ser(val)(buf)
|
||||
} else {
|
||||
do_nothing()(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A serializer combinator that does nothing with its input
|
||||
fn do_nothing<W>() -> impl SerializeFn<W> {
|
||||
Ok
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_legacy_login_roundtrip() {
|
||||
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(&context, &mut bytes::BytesMut::from(&sample[..])).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 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(&context, &mut bytes::BytesMut::from(&sample[..])).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);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,468 @@
|
||||
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 tokio_util::sync::CancellationToken;
|
||||
|
||||
use Md5Trunc::*;
|
||||
|
||||
mod abilityinfo;
|
||||
mod battery;
|
||||
mod connection;
|
||||
mod credentials;
|
||||
mod email;
|
||||
mod errors;
|
||||
mod floodlight;
|
||||
mod keepalive;
|
||||
mod ledstate;
|
||||
mod link;
|
||||
mod login;
|
||||
mod logout;
|
||||
mod motion;
|
||||
mod ping;
|
||||
mod pirstate;
|
||||
mod ptz;
|
||||
mod pushinfo;
|
||||
mod reboot;
|
||||
mod resolution;
|
||||
mod services;
|
||||
mod siren;
|
||||
mod snap;
|
||||
mod stream;
|
||||
mod stream_info;
|
||||
mod support;
|
||||
mod talk;
|
||||
mod time;
|
||||
mod uid;
|
||||
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>>,
|
||||
#[allow(dead_code)]
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// Maximum number of retries for discovery
|
||||
pub max_discovery_retries: usize,
|
||||
/// Credentials for login
|
||||
pub credentials: Credentials,
|
||||
/// Toggle debug print of underlying data
|
||||
pub debug: bool,
|
||||
}
|
||||
|
||||
/// 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, PartialEq, Eq)]
|
||||
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> {
|
||||
let discovery = Discovery::new().await?;
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sockets.is_empty() {
|
||||
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::Cellular => (false, false, true, true),
|
||||
DiscoveryMethods::Debug => (false, false, true, false),
|
||||
};
|
||||
|
||||
let res = tokio::select! {
|
||||
Ok(v) = async {
|
||||
let uid_local = uid.clone();
|
||||
info!("{}: Trying local discovery", options.name);
|
||||
let result = discovery.local(&uid_local, Some(sockets)).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Local discovery success {} at {}",
|
||||
options.name,
|
||||
uid_local,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e)
|
||||
}
|
||||
}, if allow_local => Ok(v),
|
||||
Ok(v) = async {
|
||||
let mut discovery = Discovery::new().await?;
|
||||
let reg_result;
|
||||
// Registration is looped as it seems that reolink
|
||||
// only updates the registration lazily when someone attempts
|
||||
// to connect. The first few connects fails until the server data
|
||||
// is updated
|
||||
//
|
||||
// We loop infinitly and allow the caller to timeout at the
|
||||
// interval they desire
|
||||
let mut retry = 0;
|
||||
let max_retry: usize = options.max_discovery_retries;
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
if let Ok(result) = discovery.get_registration(uid).await {
|
||||
reg_result = result;
|
||||
break;
|
||||
}
|
||||
if retry >= max_retry && max_retry > 0 {
|
||||
return Err(Error::DiscoveryTimeout);
|
||||
}
|
||||
log::info!("{}: Registration with reolink servers failed. Retrying: {}/{}", options.name, retry + 1, if max_retry > 0 {format!("{}", max_retry)} else {"infinite".to_string()});
|
||||
retry += 1;
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
|
||||
// New discovery to get new client IDs
|
||||
discovery = Discovery::new().await?;
|
||||
};
|
||||
tokio::select! {
|
||||
Ok(v) = async {
|
||||
let uid_remote = uid.clone();
|
||||
info!("{}: Trying remote discovery", options.name);
|
||||
let result = discovery
|
||||
.remote(&uid_remote, ®_result)
|
||||
.await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Remote discovery success {} at {}",
|
||||
options.name,
|
||||
uid_remote,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e)
|
||||
}
|
||||
}, if allow_remote => Ok(v),
|
||||
Ok(v) = async {
|
||||
let uid_map = uid.clone();
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(250)).await;
|
||||
info!("{}: Trying map discovery", options.name);
|
||||
let result = discovery.map(®_result).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Map success {} at {}",
|
||||
options.name,
|
||||
uid_map,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}, if allow_map => Ok(v),
|
||||
Ok(v) = async {
|
||||
let uid_relay = uid.clone();
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(500)).await;
|
||||
info!("{}: Trying relay discovery", options.name);
|
||||
let result = discovery.relay(®_result).await;
|
||||
match result {
|
||||
Ok(disc) => {
|
||||
info!(
|
||||
"{}: Relay success {} at {}",
|
||||
options.name,
|
||||
uid_relay,
|
||||
disc.get_addr()
|
||||
);
|
||||
Ok(CameraLocation::Udp(disc))
|
||||
},
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}, if allow_relay => Ok(v),
|
||||
else => Err(Error::DiscoveryTimeout),
|
||||
}
|
||||
}, if allow_remote || allow_map || allow_relay => Ok(v),
|
||||
else => Err(Error::DiscoveryTimeout),
|
||||
}?;
|
||||
|
||||
return Ok(res);
|
||||
}
|
||||
|
||||
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(), options.debug)
|
||||
.await?
|
||||
.split();
|
||||
(Box::new(x), Box::new(r))
|
||||
}
|
||||
CameraLocation::Udp(discovery) => {
|
||||
let (x, r) = UdpSource::new_from_discovery(
|
||||
discovery,
|
||||
&username,
|
||||
passwd.as_ref(),
|
||||
options.debug,
|
||||
)
|
||||
.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(),
|
||||
cancel: CancellationToken::new(),
|
||||
};
|
||||
me.keepalive().await?;
|
||||
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
|
||||
}
|
||||
|
||||
/// Disconnect from the camera. This is done by sending cancel to
|
||||
/// all threads then waiting for the join
|
||||
pub async fn shutdown(&self) -> Result<()> {
|
||||
self.connection.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,115 @@
|
||||
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_ID_ABILITY_INFO, 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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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 mut ser_buf = bytes::BytesMut::new();
|
||||
let info_res = quick_xml::se::to_writer(&mut ser_buf, &info).map(|_| ser_buf);
|
||||
if let Ok(Ok(info_str)) = info_res.map(|b| std::str::from_utf8(&b).map(|a| a.to_owned())) {
|
||||
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,131 @@
|
||||
//! 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| {
|
||||
Box::pin(async move {
|
||||
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({
|
||||
let mut ser_buf = bytes::BytesMut::new();
|
||||
let parsed =
|
||||
quick_xml::se::to_writer(&mut ser_buf, &battery)
|
||||
.map(|_| ser_buf);
|
||||
parsed.expect("Could not serialise data").to_vec()
|
||||
})
|
||||
.expect("Should be UTF8");
|
||||
println!("{}", bat_ser);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Option::<Bc>::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_ID_BATTERY_INFO, 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,405 @@
|
||||
use super::BcSubscription;
|
||||
use crate::{bc::model::*, Error, Result};
|
||||
use futures::future::BoxFuture;
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use futures::stream::{Stream, StreamExt};
|
||||
use log::*;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::{channel, Sender};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use tokio::{sync::RwLock, task::JoinSet};
|
||||
|
||||
type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Subscriber {
|
||||
/// Subscribers based on their ID and their num
|
||||
/// First filtered by ID then number
|
||||
/// If num is None it will be upgraded to a Some based on the number the
|
||||
/// camera assigns
|
||||
num: BTreeMap<u32, BTreeMap<Option<u16>, Sender<Result<Bc>>>>,
|
||||
/// Subscribers based on their ID
|
||||
id: BTreeMap<u32, Arc<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<()>>>,
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl BcConnection {
|
||||
pub async fn new(mut sink: BcConnSink, mut source: BcConnSource) -> Result<BcConnection> {
|
||||
let (sinker, sinker_rx) = channel::<Result<Bc>>(100);
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
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 thread_cancel = cancel.clone();
|
||||
rx_thread.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => {
|
||||
Result::Ok(())
|
||||
},
|
||||
v = async {
|
||||
let sender = thread_poll_commander;
|
||||
while let Some(bc) = source.next().await {
|
||||
sender.send(PollCommand::Bc(Box::new(bc))).await?;
|
||||
}
|
||||
Result::Ok(())
|
||||
} => v
|
||||
}
|
||||
});
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
rx_thread.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
let mut stream = ReceiverStream::new(sinker_rx);
|
||||
while let Some(packet) = stream.next().await {
|
||||
sink.send(packet?).await?;
|
||||
}
|
||||
Ok(())
|
||||
} => v
|
||||
}
|
||||
});
|
||||
|
||||
let thread_cancel = cancel.clone();
|
||||
rx_thread.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
loop {
|
||||
if let n @ Err(_) = poller.run().await {
|
||||
trace!("Polling has ended");
|
||||
return n;
|
||||
}
|
||||
}
|
||||
}=> v
|
||||
}
|
||||
});
|
||||
|
||||
Ok(BcConnection {
|
||||
sink: sinker,
|
||||
poll_commander,
|
||||
rx_thread: RwLock::new(rx_thread),
|
||||
cancel,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn send(&self, bc: Bc) -> crate::Result<()> {
|
||||
self.sink.send(Ok(bc)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn subscribe(&self, msg_id: u32, msg_num: u16) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, Some(msg_num), tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, Some(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: 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>,
|
||||
{
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddHandler(msg_id, Arc::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(())
|
||||
}
|
||||
|
||||
/// Some times we want to wait for a reply on a new message ID
|
||||
/// to do this we wait for the next packet with a certain ID
|
||||
/// grab it's message ID and then subscribe to that ID
|
||||
///
|
||||
/// The command Snap that grabs a jpeg payload is an example of this
|
||||
///
|
||||
/// This function creates a temporary handle to grab this single message
|
||||
pub async fn subscribe_to_id(&self, msg_id: u32) -> Result<BcSubscription> {
|
||||
let (tx, rx) = channel(100);
|
||||
self.poll_commander
|
||||
.send(PollCommand::AddSubscriber(msg_id, None, tx))
|
||||
.await?;
|
||||
Ok(BcSubscription::new(rx, None, self))
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
pub async fn shutdown(&self) -> Result<()> {
|
||||
let _ = self.poll_commander.send(PollCommand::Disconnect).await;
|
||||
self.cancel.cancel();
|
||||
let mut locked_threads = self.rx_thread.write().await;
|
||||
while locked_threads.join_next().await.is_some() {}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BcConnection {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop BcConnection");
|
||||
self.cancel.cancel();
|
||||
|
||||
let poll_commander = self.poll_commander.clone();
|
||||
let _gt = tokio::runtime::Handle::current().enter();
|
||||
let mut threads = std::mem::take(&mut self.rx_thread);
|
||||
tokio::task::spawn(async move {
|
||||
let _ = poll_commander.send(PollCommand::Disconnect).await;
|
||||
let locked_threads = threads.get_mut();
|
||||
while locked_threads.join_next().await.is_some() {}
|
||||
log::trace!("Dropped BcConnection");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
enum PollCommand {
|
||||
Bc(Box<Result<Bc>>),
|
||||
AddHandler(u32, Arc<MsgHandler>),
|
||||
RemoveHandler(u32),
|
||||
AddSubscriber(u32, Option<u16>, Sender<Result<Bc>>),
|
||||
Disconnect,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for PollCommand {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PollCommand::Bc(_) => f.write_str("PollCommand::Bc"),
|
||||
PollCommand::AddHandler(_, _) => f.write_str("PollCommand::AddHandler"),
|
||||
PollCommand::RemoveHandler(_) => f.write_str("PollCommand::RemoveHandler"),
|
||||
PollCommand::AddSubscriber(_, _, _) => f.write_str("PollCommand::AddSubscriber"),
|
||||
PollCommand::Disconnect => f.write_str("PollCommand::Disconnect"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Poller {
|
||||
subscribers: Subscriber,
|
||||
sink: Sender<Result<Bc>>,
|
||||
reciever: ReceiverStream<PollCommand>,
|
||||
}
|
||||
|
||||
impl Poller {
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let cancel = CancellationToken::new();
|
||||
let _dropguard = cancel.clone().drop_guard();
|
||||
while let Some(command) = self.reciever.next().await {
|
||||
// Clean Up subscribers
|
||||
self.subscribers
|
||||
.num
|
||||
.iter_mut()
|
||||
.for_each(|(_, channels)| channels.retain(|_, channel| !channel.is_closed()));
|
||||
self.subscribers
|
||||
.num
|
||||
.retain(|_, channels| !channels.is_empty());
|
||||
// Handle the command
|
||||
match command {
|
||||
PollCommand::Bc(boxed_response) => {
|
||||
match *boxed_response {
|
||||
Ok(response) => {
|
||||
let msg_id = response.meta.msg_id;
|
||||
let msg_num = response.meta.msg_num;
|
||||
log::trace!(
|
||||
"Looking for ID: {} with num: {}, in {:?} and {:?}",
|
||||
msg_id,
|
||||
msg_num,
|
||||
self.subscribers.id.keys().to_owned(),
|
||||
self.subscribers
|
||||
.num
|
||||
.iter()
|
||||
.map(|(k, v)| (k, v.keys()))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
match (
|
||||
self.subscribers.id.get(&msg_id),
|
||||
self.subscribers.num.get_mut(&msg_id), // Both filter first on ID
|
||||
) {
|
||||
(Some(occ), _) => {
|
||||
log::trace!("Calling ID callback");
|
||||
let occ = occ.clone();
|
||||
let sink = self.sink.clone();
|
||||
// Move this on another thread coz I have NO idea
|
||||
// how long the callback will run for
|
||||
// and we must NOT hang
|
||||
let cancel = cancel.clone();
|
||||
tokio::task::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = cancel.cancelled() => Result::Ok(()),
|
||||
v = occ(&response) => {
|
||||
if let Some(reply) = v {
|
||||
assert!(reply.meta.msg_num == response.meta.msg_num);
|
||||
sink.send(Ok(reply)).await?;
|
||||
}
|
||||
Result::Ok(())
|
||||
}
|
||||
}
|
||||
});
|
||||
log::trace!("Called ID callback");
|
||||
}
|
||||
(None, Some(occ)) => {
|
||||
let sender = if let Some(sender) =
|
||||
occ.get(&Some(msg_num)).filter(|a| !a.is_closed()).cloned()
|
||||
{
|
||||
// Connection with id exists and is not closed
|
||||
Some(sender)
|
||||
} else if let Some(sender) = occ.get(&None).cloned() {
|
||||
// Upgrade a None to a known MsgID
|
||||
occ.remove(&None);
|
||||
occ.insert(Some(msg_num), sender.clone());
|
||||
Some(sender)
|
||||
} else if occ
|
||||
.get(&Some(msg_num))
|
||||
.map(|a| a.is_closed())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
// Connection is closed and there is no None to replace it
|
||||
// Remove it for cleanup and report no sender
|
||||
occ.remove(&Some(msg_num));
|
||||
None
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(sender) = sender {
|
||||
if sender.capacity() == 0 {
|
||||
warn!("Reaching limit of channel");
|
||||
warn!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
} else {
|
||||
trace!(
|
||||
"Remaining: {} of {} message space for {} (ID: {})",
|
||||
sender.capacity(),
|
||||
sender.max_capacity(),
|
||||
&msg_num,
|
||||
&msg_id
|
||||
);
|
||||
}
|
||||
let _ = sender.send(Ok(response)).await;
|
||||
} else {
|
||||
trace!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id,
|
||||
msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
(None, None) => {
|
||||
trace!(
|
||||
"Ignoring uninteresting message id {} (number: {})",
|
||||
msg_id,
|
||||
msg_num
|
||||
);
|
||||
trace!("Contents: {:?}", response);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
for sub in self.subscribers.num.values() {
|
||||
for sender in sub.values() {
|
||||
let _ = sender.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_id, msg_num, tx) => {
|
||||
match self
|
||||
.subscribers
|
||||
.num
|
||||
.entry(msg_id)
|
||||
.or_default()
|
||||
.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 {
|
||||
// log::error!("Failed to subscribe in bcconn to {:?} for {:?}", msg_num, msg_id);
|
||||
let _ = tx
|
||||
.send(Err(Error::SimultaneousSubscription { msg_num }))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
PollCommand::Disconnect => {
|
||||
return Err(Error::ConnectionShutdown);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::BcConnection;
|
||||
use crate::bcmedia::codex::BcMediaCodex;
|
||||
use crate::{bc::model::*, bcmedia::model::*, Error, Result};
|
||||
use futures::stream::{Stream, 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, StreamExt};
|
||||
use tokio_util::codec::FramedRead;
|
||||
use tokio_util::compat::FuturesAsyncReadCompatExt;
|
||||
|
||||
pub struct BcSubscription<'a> {
|
||||
rx: ReceiverStream<Result<Bc>>,
|
||||
msg_num: Option<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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> BcSubscription<'a> {
|
||||
pub fn new(
|
||||
rx: Receiver<Result<Bc>>,
|
||||
msg_num: Option<u32>,
|
||||
conn: &'a BcConnection,
|
||||
) -> BcSubscription<'a> {
|
||||
BcSubscription {
|
||||
rx: ReceiverStream::new(rx),
|
||||
msg_num,
|
||||
conn,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send(&self, bc: Bc) -> Result<()> {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
log::debug!("Sending message before msg_num has been aquired");
|
||||
}
|
||||
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 {
|
||||
if let Some(msg_num) = self.msg_num {
|
||||
assert!(bc.meta.msg_num as u32 == msg_num);
|
||||
} else {
|
||||
// Leaning number now
|
||||
self.msg_num = Some(bc.meta.msg_num as u32);
|
||||
}
|
||||
}
|
||||
bc
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn bc_stream(&'_ mut self) -> BcStream<'_> {
|
||||
BcStream { rx: &mut self.rx }
|
||||
}
|
||||
|
||||
pub fn payload_stream(&'_ mut self) -> impl Stream<Item = IoResult<Vec<u8>>> + '_ {
|
||||
(&mut self.rx).filter_map(|x| match x {
|
||||
Ok(Bc {
|
||||
meta: BcMeta { .. },
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
..
|
||||
}),
|
||||
}) => Some(Ok(data)),
|
||||
Ok(_) => None,
|
||||
Err(e) => Some(Err(IoError::new(ErrorKind::Other, e))),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bcmedia_stream(&'_ mut self, strict: bool) -> impl Stream<Item = Result<BcMedia>> + '_ {
|
||||
let async_read = self
|
||||
.payload_stream()
|
||||
.map(|frame| frame)
|
||||
.into_async_read()
|
||||
.compat();
|
||||
FramedRead::new(async_read, BcMediaCodex::new(strict)).map(|frame| frame)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,34 @@
|
||||
//! 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;
|
||||
|
||||
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,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
}
|
||||
|
||||
impl DiscoveryResult {
|
||||
/// Get the address discovered
|
||||
pub(crate) fn get_addr(&self) -> &SocketAddr {
|
||||
&self.addr
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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>,
|
||||
debug: bool,
|
||||
) -> Result<TcpSource> {
|
||||
let stream = connect_to(addr).await?;
|
||||
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
Ok(Self {
|
||||
inner: Framed::new(stream, codex),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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,796 @@
|
||||
use super::DiscoveryResult;
|
||||
use crate::bc::codex::BcCodex;
|
||||
use crate::bc::model::*;
|
||||
use crate::bc_protocol::errors::BcUdpDropReciverKind;
|
||||
use crate::bcudp::codex::BcUdpCodex;
|
||||
use crate::bcudp::{model::*, xml::*};
|
||||
use crate::{Credentials, Error, Result};
|
||||
use delegate::delegate;
|
||||
use futures::{
|
||||
sink::{Sink, SinkExt},
|
||||
stream::{IntoAsyncRead, Stream, StreamExt, TryStreamExt},
|
||||
};
|
||||
use rand::{seq::SliceRandom, thread_rng, Rng};
|
||||
use std::collections::BTreeMap;
|
||||
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,
|
||||
sync::{
|
||||
mpsc::channel,
|
||||
watch::{channel as watch, Sender as WatchSender},
|
||||
},
|
||||
task::JoinSet,
|
||||
time::{interval, sleep, Duration, Instant, Interval},
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::compat::{Compat, FuturesAsyncReadCompatExt};
|
||||
use tokio_util::sync::{CancellationToken, PollSender};
|
||||
use tokio_util::{
|
||||
codec::{Decoder, Encoder, Framed},
|
||||
udp::UdpFramed,
|
||||
};
|
||||
|
||||
const MTU: usize = 1350;
|
||||
const UDPDATA_HEADER_SIZE: usize = 20;
|
||||
|
||||
pub(crate) type InnerFramed = Framed<Compat<IntoAsyncRead<UdpPayloadSource>>, BcCodex>;
|
||||
pub(crate) struct UdpSource {
|
||||
inner: Pin<Box<InnerFramed>>,
|
||||
}
|
||||
|
||||
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>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let stream = Arc::new(connect().await?);
|
||||
|
||||
Self::new_from_socket(
|
||||
stream, addr, client_id, camera_id, username, password, debug,
|
||||
)
|
||||
.await
|
||||
}
|
||||
pub(crate) async fn new_from_discovery<T: Into<String>, U: Into<String>>(
|
||||
discovery: DiscoveryResult,
|
||||
username: T,
|
||||
password: Option<U>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
// Ensure that the discovery keep alive are all stopped here
|
||||
// We now handle all coms in UdpSource
|
||||
discovery.socket.set_broadcast(false)?;
|
||||
Self::new_from_socket(
|
||||
discovery.socket,
|
||||
discovery.addr,
|
||||
discovery.client_id,
|
||||
discovery.camera_id,
|
||||
username,
|
||||
password,
|
||||
debug,
|
||||
)
|
||||
.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>,
|
||||
debug: bool,
|
||||
) -> Result<Self> {
|
||||
let bcudp_source = BcUdpSource::new_from_socket(stream, addr).await?;
|
||||
let payload_source = bcudp_source.into_payload_source(client_id, camera_id).await;
|
||||
let async_read = payload_source.into_async_read().compat();
|
||||
let codex = if debug {
|
||||
BcCodex::new_with_debug(Credentials::new(username, password))
|
||||
} else {
|
||||
BcCodex::new(Credentials::new(username, password))
|
||||
};
|
||||
let framed = Framed::new(async_read, codex);
|
||||
|
||||
Ok(Self {
|
||||
inner: Box::pin(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 self.inner.as_mut() {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner.as_ref().get_ref() {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<Bc> for UdpSource {
|
||||
type Error = <BcCodex as Encoder<Bc>>::Error;
|
||||
|
||||
delegate! {
|
||||
to self.inner.as_mut() {
|
||||
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: Pin<Box<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: Box::pin(UdpFramed::new(stream, BcUdpCodex::new())),
|
||||
addr,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn into_payload_source(
|
||||
self,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> UdpPayloadSource {
|
||||
UdpPayloadSource::new(self, client_id, camera_id).await
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for BcUdpSource {
|
||||
type Item = Result<(BcUdp, SocketAddr)>;
|
||||
|
||||
delegate! {
|
||||
to self.inner.as_mut() {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner.as_ref().get_ref() {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink<(BcUdp, SocketAddr)> for BcUdpSource {
|
||||
type Error = Error;
|
||||
|
||||
delegate! {
|
||||
to self.inner.as_mut() {
|
||||
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)]
|
||||
#[derive(Debug)]
|
||||
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
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct AckLatency {
|
||||
current_values: Vec<u32>,
|
||||
last_recieve_time: Option<Instant>,
|
||||
display_value: u32,
|
||||
last_display_time: Option<Instant>,
|
||||
}
|
||||
|
||||
impl AckLatency {
|
||||
/// Used to get the current latency, in thd way that the official
|
||||
/// client does. This is a value that seems to be updated only every second
|
||||
/// Observed values are `0`, `54785`, `55062`, `2528`,
|
||||
fn get_value(&self) -> u32 {
|
||||
self.display_value
|
||||
}
|
||||
|
||||
/// Used to updaet the average latency calculation
|
||||
fn feed_ack(&mut self) {
|
||||
// Update the last recieve time
|
||||
let now = Instant::now();
|
||||
if let Some(last_recieve_time) = self.last_recieve_time {
|
||||
let diff = (now - last_recieve_time).as_micros();
|
||||
self.current_values.push(diff as u32);
|
||||
self.last_recieve_time = Some(now);
|
||||
} else {
|
||||
self.last_recieve_time = Some(now);
|
||||
}
|
||||
|
||||
// Update the display_value
|
||||
// this is done only ever 1s
|
||||
if let Some(last_display_time) = self.last_display_time {
|
||||
if now - last_display_time > Duration::from_secs(1) {
|
||||
// A second has passed update this
|
||||
self.last_display_time = Some(now);
|
||||
let current_values_count = self.current_values.len() as u32;
|
||||
let current_value = self
|
||||
.current_values
|
||||
.iter()
|
||||
.fold(0u32, |acc, value| acc + *value / current_values_count);
|
||||
self.current_values = vec![]; // Reset the average vec
|
||||
|
||||
self.display_value = current_value;
|
||||
}
|
||||
} else {
|
||||
// First 1s is a zero value
|
||||
self.last_display_time = Some(now);
|
||||
self.display_value = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct UdpPayloadSource {
|
||||
inner_stream: Pin<Box<ReceiverStream<IoResult<Vec<u8>>>>>,
|
||||
inner_sink: PollSender<Vec<u8>>,
|
||||
set: JoinSet<Result<()>>,
|
||||
cancel_token: CancellationToken,
|
||||
}
|
||||
|
||||
impl Drop for UdpPayloadSource {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop UdpPayloadSource");
|
||||
self.cancel_token.cancel();
|
||||
let _gt = tokio::runtime::Handle::current().enter();
|
||||
let mut set = std::mem::take(&mut self.set);
|
||||
tokio::task::spawn(async move {
|
||||
while set.join_next().await.is_some() {}
|
||||
log::trace!("Dropped UdpPayloadSource");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpPayloadInner {
|
||||
camera_addr: SocketAddr,
|
||||
ack_tx: WatchSender<UdpAck>,
|
||||
socket_in: PollSender<BcUdp>,
|
||||
socket_out: ReceiverStream<(BcUdp, SocketAddr)>,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
packets_sent: u32,
|
||||
packets_want: u32,
|
||||
sent: BTreeMap<u32, UdpData>,
|
||||
recieved: BTreeMap<u32, Vec<u8>>,
|
||||
/// 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
|
||||
/// Offical Client does resend every 500ms
|
||||
/// This `resend_interval` controls how ofen we do this
|
||||
resend_interval: Interval,
|
||||
ack_latency: AckLatency,
|
||||
cancel: CancellationToken,
|
||||
set: JoinSet<Result<()>>,
|
||||
}
|
||||
impl UdpPayloadInner {
|
||||
fn new(
|
||||
mut inner: BcUdpSource,
|
||||
thread_stream: PollSender<IoResult<Vec<u8>>>,
|
||||
thread_sink: ReceiverStream<Vec<u8>>,
|
||||
client_id: i32,
|
||||
camera_id: i32,
|
||||
) -> Self {
|
||||
let mut set = JoinSet::new();
|
||||
let camera_addr = inner.addr;
|
||||
let cancel = CancellationToken::new();
|
||||
// Data in this needs to be passed into the socket regularly
|
||||
// especially the ACK packets on UDP. The thread must not lock
|
||||
// and MUST send ACK packets or else be dropped by the camera.
|
||||
// In order to achieve this we use dedicated threads for ACK
|
||||
// and the socket
|
||||
|
||||
let (socket_in_tx, socket_in_rx) = channel::<BcUdp>(500);
|
||||
let (socket_out_tx, socket_out_rx) = channel::<(BcUdp, SocketAddr)>(500);
|
||||
// let (mut socket_tx, mut socket_rx) = inner.split();
|
||||
|
||||
// Send/Recv on the socket
|
||||
let send_cancel = cancel.clone();
|
||||
let mut socket_in_rx = ReceiverStream::new(socket_in_rx);
|
||||
let thread_camera_addr = camera_addr;
|
||||
let socket_out_tx = socket_out_tx.clone();
|
||||
let thread_client_id = client_id;
|
||||
let thread_camera_id = camera_id;
|
||||
const TIME_OUT: u64 = 10;
|
||||
let mut recv_timeout = Box::pin(sleep(Duration::from_secs(TIME_OUT)));
|
||||
set.spawn(async move {
|
||||
let result = tokio::select! {
|
||||
_ = send_cancel.cancelled() => {
|
||||
Result::Ok(())
|
||||
},
|
||||
v = async {
|
||||
loop {
|
||||
break tokio::select!{
|
||||
_ = recv_timeout.as_mut() => {
|
||||
Err(Error::BcUdpTimeout)
|
||||
}
|
||||
packet = inner.next() => {
|
||||
log::trace!("Cam->App");
|
||||
let packet = packet.ok_or(Error::BcUdpDropReciver(BcUdpDropReciverKind::NoneRecieved))??;
|
||||
recv_timeout.as_mut().reset(Instant::now() + Duration::from_secs(TIME_OUT));
|
||||
// let packet = socket_rx.next().await.ok_or(Error::BcUdpDropReciver)??;
|
||||
socket_out_tx.try_send(packet).map_err(|e| Error::BcUdpDropReciver(BcUdpDropReciverKind::SendFailed(format!("{e:?}"))))?;
|
||||
continue;
|
||||
},
|
||||
packet = socket_in_rx.next() => {
|
||||
let packet = packet.ok_or(Error::BcUdpDropSender)?;
|
||||
match tokio::time::timeout(tokio::time::Duration::from_millis(250), inner.send((packet, thread_camera_addr))).await {
|
||||
Ok(written) => {
|
||||
written?;
|
||||
}
|
||||
Err(_) => {
|
||||
log::trace!("Socket Error, attempting reconnect over a new one");
|
||||
// Socket is (maybe) broken
|
||||
// Seems to happen with network reconnects like over
|
||||
// a lossy cellular network
|
||||
let stream = Arc::new(tokio::time::timeout(tokio::time::Duration::from_millis(250), connect_try_port(inner.inner.get_ref().local_addr()?.port())).await.map_err(|_| Error::BcUdpReconnectTimeout)??);
|
||||
inner = tokio::time::timeout(tokio::time::Duration::from_millis(250), BcUdpSource::new_from_socket(stream, inner.addr)).await.map_err(|_| Error::BcUdpReconnectTimeout)??;
|
||||
|
||||
// Inform the camera that we are the same client
|
||||
//
|
||||
// At least I think that is what this is for.
|
||||
// Might also have to do this for the relay but not sure
|
||||
let msg = BcUdp::Discovery(UdpDiscovery {
|
||||
tid: {
|
||||
let mut rng = thread_rng();
|
||||
(rng.gen::<u8>()) as u32
|
||||
},
|
||||
payload: UdpXml::C2dHb(C2dHb {
|
||||
cid: thread_client_id,
|
||||
did: thread_camera_id,
|
||||
}),
|
||||
});
|
||||
let _ = tokio::time::timeout(tokio::time::Duration::from_millis(250), inner.send((msg, thread_camera_addr))).await;
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("Send Packet");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}?;
|
||||
Ok(())
|
||||
} => v,
|
||||
};
|
||||
send_cancel.cancel();
|
||||
result
|
||||
});
|
||||
|
||||
// Queue up ack packets
|
||||
let ack_cancel = cancel.clone();
|
||||
let mut ack_interval = interval(Duration::from_millis(10)); // Offical Client does ack every 10ms
|
||||
ack_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let (ack_tx, ack_rx) = watch(UdpAck::empty(camera_id));
|
||||
let ack_socket_in_tx = socket_in_tx.clone();
|
||||
set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = ack_cancel.cancelled() => {
|
||||
Result::Ok(())
|
||||
},
|
||||
v = async {
|
||||
loop {
|
||||
ack_interval.tick().await;
|
||||
// Send an ack packet
|
||||
log::trace!("send ack");
|
||||
let ack_packet = BcUdp::Ack(ack_rx.borrow().clone());
|
||||
ack_socket_in_tx.send(ack_packet).await?;
|
||||
}
|
||||
} => v,
|
||||
}
|
||||
});
|
||||
|
||||
// Queue up Hb packets
|
||||
let thread_client_id = client_id;
|
||||
let thread_camera_id = camera_id;
|
||||
let thread_sender = socket_in_tx.clone();
|
||||
let mut thread_interval = interval(Duration::from_secs(1));
|
||||
let thread_cancel = cancel.clone();
|
||||
set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
loop {
|
||||
thread_interval.tick().await;
|
||||
let msg = BcUdp::Discovery(UdpDiscovery {
|
||||
tid: {
|
||||
let mut rng = thread_rng();
|
||||
(rng.gen::<u8>()) as u32
|
||||
},
|
||||
payload: UdpXml::C2dHb(C2dHb {
|
||||
cid: thread_client_id,
|
||||
did: thread_camera_id,
|
||||
}),
|
||||
});
|
||||
if thread_sender.send(msg).await.is_err() {
|
||||
break Result::Ok(());
|
||||
}
|
||||
}
|
||||
} => v,
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
camera_addr,
|
||||
ack_tx,
|
||||
socket_in: PollSender::new(socket_in_tx),
|
||||
socket_out: ReceiverStream::new(socket_out_rx),
|
||||
thread_stream,
|
||||
thread_sink,
|
||||
client_id,
|
||||
camera_id,
|
||||
packets_sent: 0,
|
||||
packets_want: 0,
|
||||
sent: Default::default(),
|
||||
recieved: Default::default(),
|
||||
resend_interval: interval(Duration::from_millis(500)), // Offical Client does resend every 500ms
|
||||
ack_latency: Default::default(),
|
||||
cancel,
|
||||
set,
|
||||
}
|
||||
}
|
||||
async fn run(&mut self) -> Result<()> {
|
||||
let camera_addr = self.camera_addr;
|
||||
tokio::select! {
|
||||
_ = self.resend_interval.tick() => {
|
||||
log::trace!("Resend Tick");
|
||||
for (_, resend) in self.sent.iter() {
|
||||
self.socket_in.feed(BcUdp::Data(resend.clone())).await?;
|
||||
}
|
||||
self.ack_tx.send_replace(self.build_send_ack()); // Ensure we update the ack packet sometimes too
|
||||
Result::Ok(())
|
||||
},
|
||||
v = self.thread_sink.next() => {
|
||||
log::trace!("App->Camera");
|
||||
// Incomming from application
|
||||
// Outgoing on socket
|
||||
let item = v.ok_or(Error::BcUdpDropSender)?;
|
||||
|
||||
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
|
||||
let udp_data = UdpData {
|
||||
connection_id: self.camera_id,
|
||||
packet_id: self.packets_sent,
|
||||
payload: chunk.to_vec(),
|
||||
};
|
||||
self.packets_sent += 1;
|
||||
self.sent.insert(udp_data.packet_id, udp_data.clone());
|
||||
self.socket_in.feed(BcUdp::Data(udp_data)).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
v = self.socket_out.next() => {
|
||||
log::trace!("Camera->App");
|
||||
// Incomming from socket
|
||||
// Outgoing to application
|
||||
let (item, addr) = v.ok_or(Error::BcUdpDropReciver(BcUdpDropReciverKind::NoneRecieved))?;
|
||||
if addr == camera_addr {
|
||||
match item {
|
||||
BcUdp::Discovery(UdpDiscovery{
|
||||
payload: UdpXml::D2cHb(D2cHb {
|
||||
cid,
|
||||
did,
|
||||
}),
|
||||
..
|
||||
}) => {
|
||||
if cid != self.client_id {
|
||||
log::info!("Camera sent different client ID in HB");
|
||||
}
|
||||
if did != self.camera_id {
|
||||
log::info!("Camera sent different device ID in HB");
|
||||
}
|
||||
},
|
||||
BcUdp::Discovery(_disc) => {},
|
||||
BcUdp::Ack(ack) => {
|
||||
if ack.connection_id == self.client_id {
|
||||
self.handle_ack(ack);
|
||||
}
|
||||
},
|
||||
BcUdp::Data(data) => {
|
||||
if data.connection_id == self.client_id {
|
||||
let packet_id = data.packet_id;
|
||||
if packet_id >= self.packets_want {
|
||||
// error!("packets_want: {}", this.packets_want);
|
||||
self.recieved.insert(packet_id, data.payload);
|
||||
self.ack_tx.send_replace(self.build_send_ack());
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
log::trace!("Got packet");
|
||||
Ok(())
|
||||
},
|
||||
}?;
|
||||
log::trace!("Send");
|
||||
while let Some(payload) = self.recieved.remove(&self.packets_want) {
|
||||
log::trace!(" + {}", self.packets_want);
|
||||
self.packets_want += 1;
|
||||
self.thread_stream.feed(Ok(payload)).await?;
|
||||
}
|
||||
log::trace!("recieved: {}", self.recieved.len());
|
||||
log::trace!("Flush");
|
||||
self.socket_in.flush().await?;
|
||||
self.thread_stream.flush().await?;
|
||||
log::trace!("Flushed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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,
|
||||
maybe_latency: self.ack_latency.get_value(),
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.ack_latency.feed_ack();
|
||||
log::trace!("sent: {}", self.sent.len());
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for UdpPayloadInner {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop UdpPayloadInner");
|
||||
self.cancel.cancel();
|
||||
let _gt = tokio::runtime::Handle::current().enter();
|
||||
let mut set = std::mem::take(&mut self.set);
|
||||
tokio::task::spawn(async move {
|
||||
while set.join_next().await.is_some() {}
|
||||
log::trace!("Dropped UdpPayloadInner");
|
||||
});
|
||||
}
|
||||
}
|
||||
impl UdpPayloadSource {
|
||||
async fn new(inner: BcUdpSource, client_id: i32, camera_id: i32) -> Self {
|
||||
let (inner_sink, thread_sink) = channel(100);
|
||||
let (thread_stream, inner_stream) = channel(100);
|
||||
|
||||
let mut payload_inner = UdpPayloadInner::new(
|
||||
inner,
|
||||
PollSender::new(thread_stream),
|
||||
ReceiverStream::new(thread_sink),
|
||||
client_id,
|
||||
camera_id,
|
||||
);
|
||||
let cancel_token = tokio_util::sync::CancellationToken::new();
|
||||
|
||||
let thread_cancel_token = cancel_token.clone();
|
||||
let mut set = JoinSet::new();
|
||||
set.spawn(async move {
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
if payload_inner.thread_stream.is_closed() {
|
||||
log::trace!("payload_inner.thread_stream.is_closed");
|
||||
payload_inner.thread_sink.close();
|
||||
return Err(Error::BcUdpPayloadDroppedInner);
|
||||
}
|
||||
log::trace!("Calling inner");
|
||||
let res = payload_inner.run().await;
|
||||
log::trace!("Called inner: {:?}", res);
|
||||
match res {
|
||||
Ok(()) => {}
|
||||
Err(e) => {
|
||||
log::trace!("UDP Error. Connection will Drop: {:?}", e);
|
||||
// Pass error up
|
||||
let _ = payload_inner
|
||||
.thread_stream
|
||||
.send(Err(IoError::new(ErrorKind::Other, e.clone())))
|
||||
.await;
|
||||
return Result::<()>::Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} => v,
|
||||
_ = thread_cancel_token.cancelled() => Ok(()),
|
||||
}
|
||||
});
|
||||
|
||||
UdpPayloadSource {
|
||||
inner_stream: Box::pin(ReceiverStream::new(inner_stream)),
|
||||
inner_sink: PollSender::new(inner_sink),
|
||||
set,
|
||||
cancel_token,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Stream for UdpPayloadSource {
|
||||
type Item = IoResult<Vec<u8>>;
|
||||
|
||||
delegate! {
|
||||
to self.inner_stream.as_mut() {
|
||||
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>;
|
||||
}
|
||||
}
|
||||
|
||||
delegate! {
|
||||
to self.inner_stream.as_ref().get_ref() {
|
||||
fn size_hint(&self) -> (usize, Option<usize>);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_ready_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.start_send_unpin(item)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
fn poll_flush(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_flush_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
|
||||
fn poll_close(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
self.get_mut()
|
||||
.inner_sink
|
||||
.poll_close_unpin(cx)
|
||||
.map_err(|e| IoError::new(ErrorKind::Other, e))
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
drop(rng); // Do not hold RNG over an await
|
||||
}
|
||||
|
||||
let addrs: Vec<_> = ports
|
||||
.iter()
|
||||
.map(|&port| SocketAddr::from(([0, 0, 0, 0], port)))
|
||||
.collect();
|
||||
let socket = UdpSocket::bind(&addrs[..]).await?;
|
||||
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
async fn connect_try_port(port: u16) -> Result<UdpSocket> {
|
||||
let mut ports: Vec<u16> = (53500..54000).collect();
|
||||
{
|
||||
let mut rng = thread_rng();
|
||||
ports.shuffle(&mut rng);
|
||||
drop(rng); // Do not hold RNG over an await
|
||||
}
|
||||
|
||||
let addrs: Vec<_> = [port]
|
||||
.iter()
|
||||
.chain(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 omitted
|
||||
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,264 @@
|
||||
//! Email controlling methods
|
||||
//!
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the current Email XML
|
||||
pub async fn get_email(&self) -> Result<Email> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_EMAIL, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_EMAIL,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
email: Some(email), ..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(email)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Email xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the Email XML
|
||||
pub async fn set_email(&self, email: Email) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_SET_EMAIL, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SET_EMAIL,
|
||||
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 {
|
||||
email: Some(email),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Test the Email with this XML
|
||||
pub async fn test_email(&self, email: Email) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_TEST_EMAIL, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_TEST_EMAIL,
|
||||
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 {
|
||||
email: Some(email),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get the current EmailTask XML
|
||||
pub async fn get_email_task(&self) -> Result<EmailTask> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_EMAIL_TASK, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_EMAIL_TASK,
|
||||
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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
email_task: Some(email_task),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(email_task)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected EmailTask xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Setup the Email Task
|
||||
pub async fn set_email_task(&self, email_task: EmailTask) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_SET_EMAIL_TASK, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SET_EMAIL_TASK,
|
||||
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 {
|
||||
email_task: Some(email_task),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Turn on Email notifications
|
||||
pub async fn email_on(&self) -> Result<()> {
|
||||
self.set_email_task(EmailTask {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
enable: 1,
|
||||
schedule_list: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Turn off Email notifications
|
||||
pub async fn email_off(&self) -> Result<()> {
|
||||
self.set_email_task(EmailTask {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
enable: 0,
|
||||
schedule_list: None,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Turn on Email notifications all the time
|
||||
pub async fn email_on_always(&self) -> Result<()> {
|
||||
const DOW: [&str; 7] = [
|
||||
"Sunday",
|
||||
"Monday",
|
||||
"Tuesday",
|
||||
"Wednesday",
|
||||
"Thursday",
|
||||
"Friday",
|
||||
"Saturday",
|
||||
];
|
||||
self.set_email_task(EmailTask {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
enable: 1,
|
||||
schedule_list: Some(ScheduleList {
|
||||
schedule: Schedule {
|
||||
alarm_type: "MD".to_owned(),
|
||||
time_block_list: TimeBlockList {
|
||||
time_block: DOW
|
||||
.iter()
|
||||
.map(|d| TimeBlock {
|
||||
enable: 1,
|
||||
week_day: d.to_string(),
|
||||
begin_hour: 0,
|
||||
end_hour: 23,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
use super::bc::model::{Bc, BcXml};
|
||||
use crate::NomErrorType;
|
||||
use thiserror::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("IO Error: {:?}", _0)]
|
||||
Io(#[from] std::sync::Arc<std::io::Error>),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error("Error in time coversion: {:?}", _0)]
|
||||
TimeRange(#[from] time::error::ComponentRange),
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error("Error in time parsing")]
|
||||
TimeParse,
|
||||
|
||||
/// Raised when fails to parse time from the camera
|
||||
#[error("Error in try from NonZeroInt")]
|
||||
TryFromInt(#[from] std::num::TryFromIntError),
|
||||
|
||||
/// /// Raised when fails to parse time from the camera
|
||||
#[error("Error in time conversion")]
|
||||
TimeTryFrom(#[from] time::error::TryFromParsed),
|
||||
|
||||
/// Raised when a Bc reply was not understood
|
||||
#[error("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 a BcXml reply was not understood
|
||||
#[error("Communication error")]
|
||||
UnintelligibleXml {
|
||||
/// The Bc packet that was not understood
|
||||
reply: std::sync::Arc<Box<BcXml>>,
|
||||
/// The message attached to the error
|
||||
why: &'static str,
|
||||
},
|
||||
|
||||
/// Raised when the camera responds with a status code over than OK
|
||||
#[error("Camera responded with Service Unavaliable: Msg of type {id} returned code {code}")]
|
||||
CameraServiceUnavailable {
|
||||
/// The message ID
|
||||
id: u32,
|
||||
/// The return code this is usually
|
||||
/// 200 for OK
|
||||
/// 400 for not yet ready
|
||||
/// 500 for camera cannot comply or understand
|
||||
code: u16,
|
||||
},
|
||||
|
||||
/// Raised when the camera responds with a status code over than OK during login
|
||||
#[error("Camera responded with Err during login")]
|
||||
CameraLoginFail,
|
||||
|
||||
/// Raised when a connection is dropped.
|
||||
#[error("Dropped connection")]
|
||||
DroppedConnection,
|
||||
|
||||
/// Raised when a connection is dropped during a tokio mpsc TryRecv event
|
||||
#[error("Dropped connection (TryRecv)")]
|
||||
DroppedConnectionTry(#[from] tokio::sync::mpsc::error::TryRecvError),
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error("Dropped connection (Broadcast TryRecv)")]
|
||||
BroadcastDroppedConnectionTry(#[from] tokio::sync::broadcast::error::TryRecvError),
|
||||
|
||||
/// Raised when a stream thread has finished
|
||||
#[error("End of Stream")]
|
||||
StreamFinished,
|
||||
|
||||
/// Raised when a connection requests shutdown
|
||||
#[error("Connection shuting down")]
|
||||
ConnectionShutdown,
|
||||
|
||||
/// Raised when a discovery attempt fails to get a reply
|
||||
#[error("No reply to discovery packet")]
|
||||
DiscoveryIgnored,
|
||||
|
||||
/// Raised when there is no reply to a UDP packet
|
||||
#[error("BcUDP packet timeout")]
|
||||
BcUdpTimeout,
|
||||
|
||||
/// Raised when a BcUdp incomming connection is dropped
|
||||
#[error("BcUDP reciver dropped: {0:?}")]
|
||||
BcUdpDropReciver(BcUdpDropReciverKind),
|
||||
|
||||
/// Raised when a BcUdp outgoing connection is dropped
|
||||
#[error("BcUDP sender dropped")]
|
||||
BcUdpDropSender,
|
||||
|
||||
/// Raised when a BcUdp outgoing connection is dropped
|
||||
#[error("BcUDPPayload inner protocol was dropped")]
|
||||
BcUdpPayloadDroppedInner,
|
||||
|
||||
/// Raised when BcUdp sender fails to reconnect in time
|
||||
#[error("BcUDP reconnect timeout")]
|
||||
BcUdpReconnectTimeout,
|
||||
|
||||
/// Raised when a connection is dropped during a TryRecv event
|
||||
#[error("Send Error")]
|
||||
TokioBcSendError,
|
||||
|
||||
/// Raised when the TIMEOUT is reach
|
||||
#[error("Timeout")]
|
||||
Timeout(#[from] std::sync::Arc<tokio::time::error::Elapsed>),
|
||||
|
||||
/// Raised when a timeout fails in a non standard way such as timeout during shutdown
|
||||
#[error("TimeoutError")]
|
||||
TimeoutError(#[from] tokio::time::error::Error),
|
||||
|
||||
/// Raised when connection is dropped because the timeout is reach
|
||||
#[error("Dropped connection (Timeout)")]
|
||||
TimeoutDisconnected,
|
||||
|
||||
/// Raised when a camera cannot be connected to ay any of the given addresses
|
||||
#[error("Cannot contact camera at given address")]
|
||||
CannotInitCamera,
|
||||
|
||||
/// Raised when failed to login to the camera
|
||||
#[error("Credential error")]
|
||||
AuthFailed,
|
||||
|
||||
/// Raised when the given camera url could not be resolved
|
||||
#[error("Failed to translate camera address")]
|
||||
AddrResolutionError,
|
||||
|
||||
/// Raised non adpcm data is sent to the talk command
|
||||
#[error("Talk data is not ADPCM")]
|
||||
UnknownTalkEncoding,
|
||||
|
||||
/// Raised when dicovery times out waiting for a reply
|
||||
#[error("Timed out while waiting for camera reply")]
|
||||
DiscoveryTimeout,
|
||||
|
||||
/// Raised during a (de)seralisation error
|
||||
#[error("Cookie GenError")]
|
||||
GenError(#[from] std::sync::Arc<cookie_factory::GenError>),
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_num
|
||||
#[error("Simultaneous subscription, {msg_num:?}")]
|
||||
SimultaneousSubscription {
|
||||
/// The message number that was subscribed to
|
||||
msg_num: Option<u16>,
|
||||
},
|
||||
|
||||
/// Raised when a connection is subscrbed to more than once for msg_id
|
||||
#[error("Simultaneous subscription, {msg_id}")]
|
||||
SimultaneousSubscriptionId {
|
||||
/// The message number that was subscribed to
|
||||
msg_id: u32,
|
||||
},
|
||||
|
||||
/// Raised when a new encyrption byte is observed
|
||||
#[error("Unknown encryption: {0:x?}")]
|
||||
UnknownEncryption(usize),
|
||||
|
||||
/// Raised when the camera cannot be found
|
||||
#[error("Camera Not Findable")]
|
||||
ConnectionUnavailable,
|
||||
|
||||
/// Raised when the subscription id dropped too soon
|
||||
#[error("Dropped Subscriber")]
|
||||
DroppedSubscriber,
|
||||
|
||||
/// Raised when a unknown connection ID attempts to connect with us over UDP
|
||||
#[error("Connection with unknown connectionID: {0:?}")]
|
||||
UnknownConnectionId(i32),
|
||||
|
||||
/// Raised when a unknown SocketAddr attempts to connect with us over UDP
|
||||
#[error("Connection from unknown source: {0:?}")]
|
||||
UnknownSource(std::net::SocketAddr),
|
||||
|
||||
/// Raised when the IP/Hostname cannot be understood
|
||||
#[error("Could not parse as IP")]
|
||||
AddrParseError(#[from] std::net::AddrParseError),
|
||||
|
||||
/// Raised when a relay connection is not possible
|
||||
/// usually happens if the camera has not contacted reolink yet
|
||||
#[error("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("Cannot perform lookup with this camera against reolink servers")]
|
||||
NoDev,
|
||||
|
||||
/// Raised when a discovery fails to be accepted by the register
|
||||
#[error("Register refuses to accept us")]
|
||||
RegisterError,
|
||||
|
||||
/// Raised when a the relay terminates the connection by sending a R2C_DISC
|
||||
#[error("Relay terminated the connection")]
|
||||
RelayTerminate,
|
||||
|
||||
/// Raised when a the camera terminates the connection by sending a D2C_DISC
|
||||
#[error("Camera terminated the connection")]
|
||||
CameraTerminate,
|
||||
|
||||
/// Raised when the stream is not enough to complete a message
|
||||
#[error("Nom Parsing incomplete: {0}")]
|
||||
NomIncomplete(usize),
|
||||
|
||||
/// Raised when a stream cannot be decoded
|
||||
#[error("Nom Parsing error: {0}")]
|
||||
NomError(String),
|
||||
|
||||
/// Raised when a camera/user lacks an ability
|
||||
#[error("Missing ability: {name} with {requested} permission has only {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("Thread panicked")]
|
||||
JoinError(#[from] std::sync::Arc<tokio::task::JoinError>),
|
||||
|
||||
/// A generic catch all error
|
||||
#[error("Other error: {0}")]
|
||||
Other(&'static str),
|
||||
|
||||
/// A generic catch all error
|
||||
#[error("Other error: {0}")]
|
||||
OtherString(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BcUdpDropReciverKind {
|
||||
NoneRecieved,
|
||||
SendFailed(String),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for Error {
|
||||
fn from(k: std::io::Error) -> Self {
|
||||
// Check for other error that is already an Error of this type
|
||||
if k.get_ref()
|
||||
.is_some_and(|e| e.downcast_ref::<Error>().is_some())
|
||||
{
|
||||
*k.into_inner().unwrap().downcast::<Error>().unwrap()
|
||||
} else {
|
||||
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<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,215 @@
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Listen on the flood light update messages and return their XMLs
|
||||
pub async fn listen_on_flightlight(&self) -> Result<Receiver<FloodlightStatusList>> {
|
||||
let (tx, rx) = channel(3);
|
||||
let connection = self.get_connection();
|
||||
connection
|
||||
.handle_msg(MSG_ID_FLOODLIGHT_STATUS_LIST, move |bc| {
|
||||
let tx = tx.clone();
|
||||
Box::pin(async move {
|
||||
if let Bc {
|
||||
meta:
|
||||
BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST,
|
||||
..
|
||||
},
|
||||
body:
|
||||
BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
floodlight_status_list: Some(list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}),
|
||||
} = bc
|
||||
{
|
||||
let send_this: FloodlightStatusList = list.clone();
|
||||
let _ = tx.send(send_this).await;
|
||||
}
|
||||
None
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(rx)
|
||||
}
|
||||
|
||||
/// Set the floodlight status using the [FloodlightManual] xml
|
||||
pub async fn set_floodlight_manual(&self, state: bool, duration: u16) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_MANUAL, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_MANUAL,
|
||||
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 {
|
||||
floodlight_manual: Some(FloodlightManual {
|
||||
version: "1".to_string(),
|
||||
channel_id: self.channel_id,
|
||||
status: match state {
|
||||
true => 1,
|
||||
false => 0,
|
||||
},
|
||||
duration,
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
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 Floodlight manual state",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the Flood Light tasks XML
|
||||
pub async fn get_flightlight_tasks(&self) -> Result<FloodlightTask> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_TASKS_READ, msg_num)
|
||||
.await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_TASKS_READ,
|
||||
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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
floodlight_task: Some(xml),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected FloodlightTask xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the Flood Light tasks XML
|
||||
pub async fn set_flightlight_tasks(&self, new_xml: FloodlightTask) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection
|
||||
.subscribe(MSG_ID_FLOODLIGHT_TASKS_WRITE, msg_num)
|
||||
.await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_FLOODLIGHT_TASKS_WRITE,
|
||||
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 {
|
||||
floodlight_task: Some(new_xml),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convience function: Activate the Flood Light night mode
|
||||
pub async fn flightlight_tasks_enable(&self, state: bool) -> Result<()> {
|
||||
// println!("{:?}", pir_state);
|
||||
if self.is_flightlight_tasks_enabled().await? != state {
|
||||
let mut curr_state = self.get_flightlight_tasks().await?;
|
||||
curr_state.enable = match state {
|
||||
true => 1,
|
||||
false => 0,
|
||||
};
|
||||
self.set_flightlight_tasks(curr_state).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convience function: Check if Flood Light tasks are enbabled
|
||||
pub async fn is_flightlight_tasks_enabled(&self) -> Result<bool> {
|
||||
let curr_state = self.get_flightlight_tasks().await?;
|
||||
Ok(curr_state.enable == 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
use super::{BcCamera, Result};
|
||||
use crate::bc::model::*;
|
||||
|
||||
impl BcCamera {
|
||||
/// Create a handler 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| {
|
||||
Box::pin(async move {
|
||||
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,149 @@
|
||||
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_ID_GET_LED_STATUS, 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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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_ID_SET_LED_STATUS, 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?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
|
||||
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",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,53 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [LinkType] xml which contains the connection status of the camera
|
||||
///
|
||||
/// This is the same as `ping()` but with the return type
|
||||
pub async fn get_linktype(&self) -> Result<LinkType> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_PING, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PING,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
link_type: Some(link_type),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(link_type)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected LinkType xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
use super::{md5_string, BcCamera, Error, Result, Truncate};
|
||||
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_ID_LOGIN, 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 => 0xdc12,
|
||||
};
|
||||
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::LoginUpgrade),
|
||||
};
|
||||
|
||||
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_ID_LOGOUT, 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,296 @@
|
||||
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;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// 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<()>>,
|
||||
cancel: CancellationToken,
|
||||
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_ID_MOTION_REQUEST, 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> {
|
||||
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;
|
||||
let cancel = CancellationToken::new();
|
||||
let thread_cancel = cancel.clone();
|
||||
set.spawn(async move {
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => Result::Ok(()),
|
||||
v = async {
|
||||
let mut sub = connection.subscribe_to_id(MSG_ID_MOTION).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 != "none"
|
||||
|| alarm_event
|
||||
.ai_type
|
||||
.as_ref()
|
||||
.map(|ai_type| ai_type != "none")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else {
|
||||
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(())
|
||||
} => v,
|
||||
}
|
||||
});
|
||||
|
||||
Ok(MotionData {
|
||||
handle: set,
|
||||
cancel,
|
||||
rx,
|
||||
last_update: MotionStatus::NoChange(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MotionData {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop MotionData");
|
||||
self.cancel.cancel();
|
||||
let mut handle = std::mem::take(&mut self.handle);
|
||||
let _gt = tokio::runtime::Handle::current().enter();
|
||||
tokio::task::spawn(async move {
|
||||
while handle.join_next().await.is_some() {}
|
||||
log::trace!("Dropped MotionData");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
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_ID_PING, 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?;
|
||||
|
||||
log::trace!("Ping complete");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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_ID_GET_PIR_ALARM, 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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
} else if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
} 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_ID_START_PIR_ALARM, 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?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,343 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
/// Directions used for Ptz
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
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 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_ID_PTZ_CONTROL, msg_num).await?;
|
||||
|
||||
let direction_str = match direction {
|
||||
Direction::Up => "up",
|
||||
Direction::Down => "down",
|
||||
Direction::Left => "left",
|
||||
Direction::Right => "right",
|
||||
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",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [PtzPreset] XML which contains the list of the preset positions known to the camera
|
||||
pub async fn get_ptz_preset(&self) -> Result<PtzPreset> {
|
||||
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_ID_GET_PTZ_PRESET, msg_num).await?;
|
||||
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_PTZ_PRESET,
|
||||
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_set.send(send).await?;
|
||||
let msg = sub_set.recv().await?;
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_preset: Some(ptz_preset),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(ptz_preset)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not return a valid PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a PTZ preset.
|
||||
///
|
||||
/// The current position will be saved as a preset with the given [preset_id] and [name]
|
||||
pub async fn set_ptz_preset(&self, preset_id: u8, name: String) -> 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_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
name: Some(name),
|
||||
command: "setPos".to_owned(),
|
||||
};
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
|
||||
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_preset: Some(PtzPreset {
|
||||
preset_list: PresetList {
|
||||
preset: vec![preset],
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..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 PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera will attempt to move to the preset with the given ID.
|
||||
pub async fn moveto_ptz_preset(&self, preset_id: u8) -> 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_ID_PTZ_CONTROL_PRESET, msg_num)
|
||||
.await?;
|
||||
|
||||
let preset = Preset {
|
||||
id: preset_id,
|
||||
name: None,
|
||||
command: "toPos".to_owned(),
|
||||
};
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
|
||||
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_preset: Some(PtzPreset {
|
||||
preset_list: PresetList {
|
||||
preset: vec![preset],
|
||||
},
|
||||
..Default::default()
|
||||
}),
|
||||
..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 PtzPreset xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The camera will zoom to a given zoom amount.
|
||||
/// Not sure what the units for this are, seems to be 1000 is 1x and 2000 is 2x
|
||||
pub async fn zoom_to(&self, zoom_pos: u32) -> Result<()> {
|
||||
let current = self.get_zoom().await?;
|
||||
let zoom_pos = zoom_pos.clamp(current.zoom.min_pos, current.zoom.max_pos);
|
||||
|
||||
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_ID_SET_ZOOM_FOCUS, msg_num).await?;
|
||||
let send = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SET_ZOOM_FOCUS,
|
||||
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 {
|
||||
start_zoom_focus: Some(StartZoomFocus {
|
||||
version: xml_ver(),
|
||||
channel_id: self.channel_id,
|
||||
command: "zoomPos".to_string(),
|
||||
move_pos: zoom_pos,
|
||||
}),
|
||||
..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 StartZoomFocus xml",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the zoom xml, that has current min and max zoom values
|
||||
pub async fn get_zoom(&self) -> Result<PtzZoomFocus> {
|
||||
self.has_ability_ro("control").await?;
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_ZOOM_FOCUS, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_ZOOM_FOCUS,
|
||||
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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
ptz_zoom_focus: Some(xml),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected PtzZoomFocus xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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_ID_PUSH_INFO, 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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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_ID_REBOOT, 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,234 @@
|
||||
//! This is a helper module to resolve either to a UID or a SockerAddr
|
||||
|
||||
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, PartialEq, Eq)]
|
||||
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,
|
||||
/// Cellular camera only support relay and map, by choosing this option
|
||||
/// only those are tried
|
||||
#[serde(alias = "cellular")]
|
||||
Cellular,
|
||||
#[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) => {
|
||||
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 {
|
||||
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) => {
|
||||
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 {
|
||||
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,423 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
use tokio::time::{interval, Duration};
|
||||
|
||||
impl BcCamera {
|
||||
/// Helper to set the service state since they all share the same code
|
||||
/// No checks are made to ensure the xml is valid service xml
|
||||
/// hence private method
|
||||
async fn set_services(&self, bcxml: BcXml) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_SET_SERVICE_PORTS, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SET_SERVICE_PORTS,
|
||||
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)),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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 BcXmp with service data",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper since they all send the same message
|
||||
/// No checks are made to ensure the xml is valid service xml
|
||||
/// hence private method
|
||||
async fn get_services(&self) -> Result<BcXml> {
|
||||
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_ID_GET_SERVICE_PORTS, msg_num)
|
||||
.await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_SERVICE_PORTS,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
} else if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
} else {
|
||||
// Valid message with response_code == 200
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload: Some(BcPayloads::BcXml(xml)),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
return Ok(xml);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected ModernMsg payload but it was not recieved",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`ServerPort`] XML
|
||||
pub async fn get_serverport(&self) -> Result<ServerPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
server_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected ServerPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the server port
|
||||
pub async fn set_serverport(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
server_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
server_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected ServerPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`HttpPort`] XML
|
||||
pub async fn get_http(&self) -> Result<HttpPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
http_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected HttpPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the http port
|
||||
pub async fn set_http(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
http_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
http_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected HttpPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`HttpPort`] XML
|
||||
pub async fn get_https(&self) -> Result<HttpsPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
https_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected HttpsPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the https port
|
||||
pub async fn set_https(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
https_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
https_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected HttpsPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`RtspPort`] XML
|
||||
pub async fn get_rtsp(&self) -> Result<RtspPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
rtsp_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected RtspPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the http port
|
||||
pub async fn set_rtsp(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
rtsp_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
rtsp_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected RtspPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`RtmpPort`] XML
|
||||
pub async fn get_rtmp(&self) -> Result<RtmpPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
rtmp_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected RtmpPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the rtmp port
|
||||
pub async fn set_rtmp(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
rtmp_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
rtmp_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected RtmpPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the [`OnvifPort`] XML
|
||||
pub async fn get_onvif(&self) -> Result<OnvifPort> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
onvif_port: Some(xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected OnvifPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the onvif port
|
||||
pub async fn set_onvif(&self, set_on: Option<bool>, set_port: Option<u32>) -> Result<()> {
|
||||
let bcxml = self.get_services().await?;
|
||||
if let BcXml {
|
||||
onvif_port: Some(mut xml),
|
||||
..
|
||||
} = bcxml
|
||||
{
|
||||
if let Some(enabled) = set_on {
|
||||
xml.enable = Some({
|
||||
if enabled {
|
||||
1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(port) = set_port {
|
||||
xml.port = port;
|
||||
}
|
||||
self.set_services(BcXml {
|
||||
onvif_port: Some(xml),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
} else {
|
||||
Err(Error::UnintelligibleXml {
|
||||
reply: std::sync::Arc::new(Box::new(bcxml)),
|
||||
why: "Expected OnvifPort xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Trigger for the siren
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Trigger the siren
|
||||
pub async fn siren(&self) -> Result<()> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_PLAY_AUDIO, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_PLAY_AUDIO,
|
||||
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 {
|
||||
audio_play_info: Some(AudioPlayInfo {
|
||||
channel_id: self.channel_id,
|
||||
play_mode: 0,
|
||||
play_duration: 0,
|
||||
play_times: 1,
|
||||
on_off: 0,
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// use futures::{StreamExt, TryStreamExt};
|
||||
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the snapshot image
|
||||
pub async fn get_snapshot(&self) -> Result<Vec<u8>> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_SNAP, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_SNAP,
|
||||
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 {
|
||||
snap: Some(Snap {
|
||||
version: "1.1".to_string(),
|
||||
channel_id: self.channel_id,
|
||||
logic_channel: Some(self.channel_id),
|
||||
time: 0,
|
||||
full_frame: Some(0),
|
||||
stream_type: Some("main".to_string()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
})),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
snap:
|
||||
Some(Snap {
|
||||
file_name: Some(filename),
|
||||
picture_size: Some(expected_size),
|
||||
..
|
||||
}),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
drop(sub_get); // Ensure that we are NOT listening on that msgnum as the reply can come on ANY msgnum
|
||||
log::trace!("Got snap XML {} with size {}", filename, expected_size);
|
||||
// Messages are now sent on ID 109 but not with the same message ID
|
||||
// preumably because the camera considers it to be a new message rather
|
||||
// than a reply
|
||||
//
|
||||
// This means we need to listen for the next 109 grab the message num and
|
||||
// subscribe to it. This is what `subscribe_to_next` is for
|
||||
let mut sub_get = connection.subscribe_to_id(MSG_ID_SNAP).await?;
|
||||
let expected_size = expected_size as usize;
|
||||
|
||||
let mut result: Vec<_> = vec![];
|
||||
log::trace!("Waiting for packets on {}", msg_num);
|
||||
let mut msg = sub_get.recv().await?;
|
||||
|
||||
while msg.meta.response_code == 200 {
|
||||
// sends 200 while more is to come
|
||||
// 201 when finished
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload: Some(BcPayloads::Binary(data)),
|
||||
}) = msg.body
|
||||
{
|
||||
result.extend_from_slice(&data);
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
log::trace!(
|
||||
"Got packet size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
msg = sub_get.recv().await?;
|
||||
}
|
||||
|
||||
if msg.meta.response_code == 201 {
|
||||
// 201 means all binary data sent
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
extension:
|
||||
Some(Extension {
|
||||
binary_data: Some(1),
|
||||
..
|
||||
}),
|
||||
payload,
|
||||
}) = msg.body
|
||||
{
|
||||
if let Some(BcPayloads::Binary(data)) = payload {
|
||||
// Add last data if present (may be zero if preveious packet contained it)
|
||||
result.extend_from_slice(&data);
|
||||
}
|
||||
log::trace!(
|
||||
"Got all packets size is now {} of {}",
|
||||
result.len(),
|
||||
expected_size
|
||||
);
|
||||
if result.len() != expected_size {
|
||||
log::debug!("Snap did not recieve expected number of bytes");
|
||||
}
|
||||
} else {
|
||||
return Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected binary data but got something else",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// anything else is an error
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
// let binary_stream = sub_get.payload_stream();
|
||||
// let result: Vec<_>= binary_stream
|
||||
// .map_ok(|i| tokio_stream::iter(i).map(Result::Ok))
|
||||
// .try_flatten()
|
||||
// .take(expected_size)
|
||||
// .try_collect()
|
||||
// .await?;
|
||||
log::trace!("Snapshot recieved: {} of {}", result.len(), expected_size);
|
||||
Ok(result)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Snap xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::{
|
||||
bc::{model::*, xml::*},
|
||||
bcmedia::model::*,
|
||||
};
|
||||
use futures::stream::StreamExt;
|
||||
use tokio::sync::mpsc::{channel, Receiver};
|
||||
use tokio::task::{self, JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// 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 available on some camera. If the camera doesn't
|
||||
/// support it the stream will be the same as the SD stream
|
||||
Extern,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StreamKind {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
match self {
|
||||
StreamKind::Main => write!(f, "mainStream"),
|
||||
StreamKind::Sub => write!(f, "subStream"),
|
||||
StreamKind::Extern => write!(f, "externStream"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: CancellationToken,
|
||||
}
|
||||
|
||||
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.cancel();
|
||||
handle.await??;
|
||||
return Err(Error::StreamFinished);
|
||||
}
|
||||
} else {
|
||||
self.abort_handle.cancel();
|
||||
return Err(Error::StreamFinished);
|
||||
}
|
||||
match self.rx.recv().await {
|
||||
Some(data) => Ok(data),
|
||||
None => {
|
||||
self.abort_handle.cancel();
|
||||
Err(Error::StreamFinished)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to gracefully shutdown this will cancel the background task and send
|
||||
/// the Stop command to the camera
|
||||
pub async fn shutdown(&mut self) -> Result<()> {
|
||||
self.abort_handle.cancel();
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _ = handle.await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StreamData {
|
||||
fn drop(&mut self) {
|
||||
log::trace!("Drop StreamData");
|
||||
self.abort_handle.cancel();
|
||||
if let Some(handle) = self.handle.take() {
|
||||
let _gt = tokio::runtime::Handle::current().enter();
|
||||
tokio::task::spawn(async move {
|
||||
let _ = handle.await;
|
||||
});
|
||||
}
|
||||
log::trace!("Dropped MotionData");
|
||||
}
|
||||
}
|
||||
|
||||
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> {
|
||||
if let Err(e) = self.has_ability_rw("preview").await {
|
||||
if self.has_ability_ro("streamTable").await.is_err() {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
|
||||
let abort_handle = CancellationToken::new();
|
||||
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 {
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO, 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 official 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);
|
||||
|
||||
tokio::select! {
|
||||
_ = abort_handle_thread.cancelled() => {},
|
||||
_ = async {
|
||||
while let Some(bc_media) = media_sub.next().await {
|
||||
// We now have a complete interesting packet. Send it to on the callback
|
||||
if tx.send(bc_media).await.is_err() {
|
||||
break; // Connection dropped
|
||||
}
|
||||
}
|
||||
} => {}
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
},
|
||||
);
|
||||
let mut sub_stop = connection.subscribe(MSG_ID_VIDEO_STOP, msg_num).await?;
|
||||
sub_stop.send(stop_video).await?;
|
||||
|
||||
tokio::select! {
|
||||
v = async {
|
||||
loop {
|
||||
let msg = sub_stop.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::CameraServiceUnavailable{
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
}
|
||||
} => 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<()> {
|
||||
if let Err(e) = self.has_ability_rw("preview").await {
|
||||
if self.has_ability_ro("streamTable").await.is_err() {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_video = connection.subscribe(MSG_ID_VIDEO_STOP, 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 official 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(Error::CameraServiceUnavailable {
|
||||
id: reply.meta.msg_id,
|
||||
code: reply.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [StreamInfoList] xml which contains the supported camera streams
|
||||
pub async fn get_stream_info(&self) -> Result<StreamInfoList> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection
|
||||
.subscribe(MSG_ID_STREAM_INFO_LIST, msg_num)
|
||||
.await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_STREAM_INFO_LIST,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
stream_info_list: Some(data),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(data)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected StreamInfoList xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [Support] xml which contains the ptz/talk support
|
||||
///
|
||||
pub async fn get_support(&self) -> Result<Support> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_GET_SUPPORT, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_SUPPORT,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
support: Some(xml), ..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Support xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
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_ID_TALKRESET, 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_ID_TALKABILITY, 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_ID_TALKCONFIG, 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_ID_TALK, 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_ID_TALKCONFIG, 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 mut sub = connection.subscribe(MSG_ID_TALK, 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 end_of_stream = false;
|
||||
let mut expected_stream_end = std::time::Instant::now();
|
||||
while !end_of_stream {
|
||||
let mut payload_bytes = vec![];
|
||||
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;
|
||||
};
|
||||
|
||||
// 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)),
|
||||
}),
|
||||
};
|
||||
|
||||
let time_sent = std::time::Instant::now();
|
||||
sub.send(msg).await?;
|
||||
let play_length = std::time::Duration::from_secs_f32(play_length);
|
||||
if time_sent > expected_stream_end {
|
||||
expected_stream_end = time_sent + play_length;
|
||||
} else {
|
||||
expected_stream_end += play_length;
|
||||
}
|
||||
let _ = sub.recv().await?;
|
||||
}
|
||||
|
||||
// Chunks are still being played, while talk_stop will interrupt them. Wait until we expect
|
||||
// the stream to end (+ and extra 100ms) before issuing talk_stop.
|
||||
let remaining_stream_duration = expected_stream_end - std::time::Instant::now();
|
||||
tokio::time::sleep(remaining_stream_duration + std::time::Duration::from_secs_f32(0.1))
|
||||
.await;
|
||||
|
||||
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,184 @@
|
||||
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_ID_GET_GENERAL, 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::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
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_ID_SET_GENERAL, 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,55 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Get the [Uid] xml which contains the uid of the camera
|
||||
pub async fn get_uid(&self) -> Result<Uid> {
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection.subscribe(MSG_ID_UID, msg_num).await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UID,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
uid: Some(uid_xml), ..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(uid_xml)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected Uid xml but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the UID
|
||||
pub async fn uid(&self) -> Result<String> {
|
||||
Ok(self.get_uid().await?.uid)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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_ID_VERSION, 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::CameraServiceUnavailable {
|
||||
id: modern_reply.meta.msg_id,
|
||||
code: modern_reply.meta.response_code,
|
||||
});
|
||||
}
|
||||
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,87 @@
|
||||
//! 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.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 doesn'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 {
|
||||
trace!("Amount skipped to restore stream: {}", self.amount_skipped);
|
||||
self.amount_skipped = 0;
|
||||
}
|
||||
return Ok(Some(bc));
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) => {
|
||||
if self.amount_skipped > 0 {
|
||||
trace!("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,547 @@
|
||||
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> {
|
||||
let (result, len) = match consumed(bcmedia)(buf) {
|
||||
Ok((_, (parsed_buff, result))) => Ok((result, parsed_buff.len())),
|
||||
Err(e) => Err(e),
|
||||
}?;
|
||||
buf.advance(len);
|
||||
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();
|
||||
|
||||
let mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) if buf.is_empty() => {
|
||||
// EOF still (but parser looking for next magic)
|
||||
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();
|
||||
|
||||
let mut buf = BytesMut::from(&sample[..]);
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) if buf.is_empty() => {
|
||||
// EOF still (but parser looking for next magic)
|
||||
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();
|
||||
|
||||
let mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
// Should derealise all of this
|
||||
loop {
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
match e {
|
||||
Err(Error::Io(e)) if e.kind() == ErrorKind::UnexpectedEof => {
|
||||
// Reach end of files
|
||||
break;
|
||||
}
|
||||
Err(Error::NomIncomplete(_)) if buf.is_empty() => {
|
||||
// EOF still (but parser looking for next magic)
|
||||
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 mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
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 mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
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 mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
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 mut buf = BytesMut::from(&sample[..]);
|
||||
|
||||
let e = BcMedia::deserialize(&mut buf);
|
||||
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,294 @@
|
||||
/// 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, Copy)]
|
||||
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>,
|
||||
}
|
||||
|
||||
impl BcMediaAac {
|
||||
/// Read the ADTS header to learn the duration in micro secs
|
||||
pub fn duration(&self) -> Option<u32> {
|
||||
if self.data.len() < 8 {
|
||||
// Too small for the header
|
||||
return None;
|
||||
}
|
||||
if self.data[0] != 0b11111111 {
|
||||
// Syncword incorrect
|
||||
return None;
|
||||
}
|
||||
if (self.data[1] & 0b11110000) != 0b11110000 {
|
||||
// Syncword incorrect
|
||||
return None;
|
||||
}
|
||||
let frequency_index = (self.data[2] & 0b00111100) >> 2;
|
||||
let sample_frequency = match frequency_index {
|
||||
0 => Some(96000u32),
|
||||
1 => Some(88200u32),
|
||||
2 => Some(64000u32),
|
||||
3 => Some(48000u32),
|
||||
4 => Some(44100u32),
|
||||
5 => Some(32000u32),
|
||||
6 => Some(24000u32),
|
||||
7 => Some(22050u32),
|
||||
8 => Some(16000u32),
|
||||
9 => Some(12000u32),
|
||||
10 => Some(11025u32),
|
||||
11 => Some(8000u32),
|
||||
12 => Some(7350u32),
|
||||
_ => None,
|
||||
}?;
|
||||
log::trace!("sample_frequency: {sample_frequency}");
|
||||
|
||||
let frames = (self.data[6] & 0b00000011) + 1;
|
||||
log::trace!("frames: {frames}");
|
||||
let samples = frames as u32 * 1024;
|
||||
log::trace!("samples: {samples}");
|
||||
const MICROSECONDS: u32 = 1000000;
|
||||
let duration = samples * MICROSECONDS / sample_frequency;
|
||||
Some(duration)
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
}
|
||||
|
||||
impl BcMediaAdpcm {
|
||||
/// The block size, this is bytes without the block header
|
||||
pub fn block_size(&self) -> u32 {
|
||||
self.data.len() as u32 - 4
|
||||
}
|
||||
|
||||
/// Returns duration in micro seconds;
|
||||
pub fn duration(&self) -> Option<u32> {
|
||||
let samples = self.block_size() * 2;
|
||||
// Always 8000Hz for ADPCM
|
||||
const SAMPLE_FREQUENCY: u32 = 8000;
|
||||
const MICROSECONDS: u32 = 1000000;
|
||||
let duration = samples * MICROSECONDS / SAMPLE_FREQUENCY;
|
||||
Some(duration)
|
||||
}
|
||||
}
|
||||
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 237 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user