Compare commits

..
1205 Commits
Author SHA1 Message Date
Andrew King 6e05e7844b Merge pull request #345 from ecksun/feature/users
Add support for managing users
2025-01-30 14:00:08 +07:00
Andrew King 43b62090c8 Rust fmt 2025-01-30 11:24:17 +07:00
Andrew King 7a66473ab9 Skip seser on the pass field
Skip deser the pass field for camera's that try to sent it in the user list
2025-01-30 11:21:08 +07:00
Linus a30f403dc4 Add support for managing users
Support includes:
- Listing users
- Creating users
- Deleting users
- Changing the password of users
2025-01-29 22:31:22 +01:00
Linus 76833e6242 dissector: Document Message ID 59 <UserList>
It is used to manage users
2025-01-29 22:31:22 +01:00
Linus 1518ab24bb dissector: Deindent ConfigFileInfo
It seemed to be a child of AbilitySupport, which is not the case
2025-01-27 23:12:47 +01:00
Andrew King c3353591ae Merge pull request #312 from QuantumEntangledAndy/fix/windowsBuild 2024-10-26 17:17:41 +07:00
QuantumEntangledAndy 18c4d56826 Don't forget the two includes 2024-10-26 16:53:28 +07:00
QuantumEntangledAndy e9e66b1a44 Rustc 1.82.0 2024-10-26 16:41:58 +07:00
QuantumEntangledAndy 1499503789 Single point of control on rust version 2024-10-26 15:16:07 +07:00
QuantumEntangledAndy fb9df1d586 Use explicit rust version for proper control in scripts 2024-10-26 15:14:15 +07:00
QuantumEntangledAndy 1517077564 More fixes to features 2024-10-26 15:13:48 +07:00
QuantumEntangledAndy e6c6f5ca62 Try and fix the gstreamer only cfg 2024-10-26 14:39:30 +07:00
QuantumEntangledAndy ed4a5ea001 Style fixes 2024-10-26 14:33:19 +07:00
QuantumEntangledAndy 4f8fb6c7b5 Remove the extra path var in windows build 2024-10-25 15:30:46 +07:00
QuantumEntangledAndy fb956c399e Bump gstreamer for windows build 2024-10-25 15:29:44 +07:00
QuantumEntangledAndy 81f77f461c Fix quotes 2024-10-25 13:59:46 +07:00
QuantumEntangledAndy 5279a34bcb More investigation of windows build error on the runner 2024-10-25 13:57:36 +07:00
QuantumEntangledAndy d09874eca5 Test the windows path on the runner 2024-10-25 13:45:18 +07:00
QuantumEntangledAndy 13081f745f Remove push notifications for now 2024-10-24 11:49:17 +07:00
QuantumEntangledAndy a14336fe3c Restore lost extra setting 2024-10-21 07:29:06 +07:00
QuantumEntangledAndy 1afb8c4a62 Some additions to the github workflows 2024-10-20 17:11:17 +07:00
QuantumEntangledAndy f78be4dd18 Mail protocol testing 2024-10-18 08:22:02 +07:00
QuantumEntangledAndy a82c2e28bc Format messages md 2024-10-18 08:15:00 +07:00
QuantumEntangledAndy 69a2d5c41f Implement motion pause on the new method 2024-08-08 14:41:51 +07:00
QuantumEntangledAndy efaea4ff91 Simplify the video send 2024-08-08 09:28:22 +07:00
QuantumEntangledAndy f15fdaefbc Don't sleep the thread in async 2024-08-04 13:04:23 +07:00
QuantumEntangledAndy 5fc9bc200a Attempt skipping passwords in mqtt config 2024-08-03 15:42:35 +07:00
QuantumEntangledAndy 7158943fc8 Style check error codes 2024-08-02 20:05:49 +07:00
QuantumEntangledAndy 8f19d12b8c Differenetiate the different DroppedConnection 2024-08-02 20:01:41 +07:00
QuantumEntangledAndy b0e009ba4d Notice from upstream 2024-08-02 14:25:38 +07:00
QuantumEntangledAndy 99146a8dce Merge remote-tracking branch 'upstream/master' 2024-08-02 14:19:40 +07:00
QuantumEntangledAndy 3349486750 Make gstreamer and pushnotificaitions build time dependencies 2024-08-02 14:15:37 +07:00
QuantumEntangledAndy 204c92cb4e deps updates 2024-08-02 10:10:53 +07:00
QuantumEntangledAndy d16cd4398c Bump deps 2024-08-01 10:28:36 +07:00
QuantumEntangledAndy 56d343e69f Make setting the camera time a soft error 2024-08-01 10:18:42 +07:00
QuantumEntangledAndy f8bb04fb8b Clippy issues 2024-07-31 13:13:34 +07:00
QuantumEntangledAndy 813eb25343 Update dissector to handle multiple cameras at once with AES 2024-07-31 12:44:46 +07:00
QuantumEntangledAndy f86cefc2fd Merge branch 'master' of github.com:QuantumEntangledAndy/neolink 2024-07-31 12:13:47 +07:00
Andrew King a04077e2c1 Merge pull request #284 from M-U-16/fixing-broken-links 2024-07-30 09:44:51 +07:00
Andrew King 1c797dffb5 Merge pull request #285 from kevin-david/fix-flood 2024-07-30 09:43:47 +07:00
Kevin David 9ace435f5f Make resolution optional in DeviceInfo
`resolution` is not specified for devices without cameras (i.e. the floodlight).

Without this change, an error like

```
[2024-07-21T19:26:18Z ERROR neolink_core::bc::de] e: Custom("missing field `resolution`")
[2024-07-21T19:26:18Z WARN  neolink::common::camthread] backyard_floodlight: Connection Lost: Nom Parsing error: Nom Error: VerboseError { errors: [([], Nom(MapRes)), ([], Context("Unable to parse Payload XML"))] }
```

occurs on startup/connection.
2024-07-21 15:49:41 -04:00
M-U-16 684e1a9015 fixing broken 404 links in dissector markdown 2024-07-20 14:31:11 +02:00
Andrew King 23bf14119f Merge pull request #281 from byteit101/patch-1 2024-07-08 08:08:19 +07:00
Patrick Plenefisch 77eeea224c Fix Wireshark dissector install comand 2024-07-07 14:25:12 -04:00
Andrew King b37b3ee4b7 Merge pull request #264 from zfouts/security_patch_upstream_containers
Support upgrading base upstream image.
2024-06-24 13:36:15 +07:00
Andrew King 3f7a231ff6 Merge pull request #263 from schredder/jemalloc-largepage 2024-06-11 17:58:22 +07:00
QuantumEntangledAndy 108adb13a5 Change how pinging reports errors 2024-06-10 10:41:32 +07:00
QuantumEntangledAndy b561b643c5 Ensure buffer length, and ensure audio is not longer then video buffer 2024-06-10 10:40:42 +07:00
QuantumEntangledAndy afd71a7cd2 Restructure how gst pipelines are made 2024-06-10 10:28:32 +07:00
Zachary Fouts 6572577859 Support upgrading base upstream image.
This will ensure latest available security patches are applied on each build.
Some upstream images take months to be updated.
2024-06-07 14:37:07 +00:00
schredder cc8a6e7e18 Add JEMALLOC_SYS_WITH_LG_PAGE to native build job 2024-06-06 00:06:50 -07:00
schredder 2e24b1e476 Set JEMALLOC_SYS_WITH_LG_PAGE=16 at build
Support large page sizes becoming more common on arm64 systems. This is compatible with systems that use smaller page sizes
2024-06-05 22:33:33 -07:00
QuantumEntangledAndy 82524a12b2 Handle empty vec such as FloodlightStatusList 2024-05-14 10:01:47 +07:00
QuantumEntangledAndy ae6e0fd928 Add a pass alias for the camera password to match that in rtsp credentials 2024-05-08 09:57:14 +07:00
QuantumEntangledAndy ab947b895c Use a Uuid for the mqtt client ID 2024-05-05 11:08:58 +07:00
QuantumEntangledAndy e53b0f09d2 Use pausing at the rtsp pipeline 2024-05-05 10:18:14 +07:00
QuantumEntangledAndy 0f53185d01 Log cleanup 2024-05-03 11:48:01 +07:00
QuantumEntangledAndy 1b6011b4eb Bump ulimit in the docker 2024-05-03 11:44:20 +07:00
QuantumEntangledAndy bae36ef40a Use hashset/hashmap for pushnoti 2024-05-03 11:44:06 +07:00
QuantumEntangledAndy 32937c1f61 Use path not config on deperation 2024-05-03 11:37:08 +07:00
QuantumEntangledAndy 308a454c74 Add buffer_duration to config 2024-05-03 11:36:43 +07:00
QuantumEntangledAndy daf20e192a Fix on client disconnect not working without on motion 2024-05-02 11:26:53 +07:00
QuantumEntangledAndy 8f043a3ce2 Create push notificaiton token dir 2024-05-02 10:57:00 +07:00
QuantumEntangledAndy 0d5fbd30f1 Log cleanup 2024-05-02 10:56:40 +07:00
QuantumEntangledAndy a6ebdfe713 Reduce discovery logs 2024-05-02 08:56:22 +07:00
George Hilliard 186d580462 README: Development has moved
See #370 for background.
2024-04-30 21:13:30 -05:00
QuantumEntangledAndy e6321f36d7 Mode debug prints for error code 400 2024-04-28 11:38:39 +07:00
QuantumEntangledAndy 366c2a4b69 More log clean up 2024-04-27 15:17:07 +07:00
QuantumEntangledAndy e8aca0ee10 Log cleanup 2024-04-26 16:52:39 +07:00
QuantumEntangledAndy 96e994512e Build release 2024-04-26 14:46:34 +07:00
QuantumEntangledAndy a8b93a4ef2 Quote the CMD var 2024-04-26 14:44:33 +07:00
QuantumEntangledAndy 9d68338774 Fix the dockerfile issue 2024-04-26 14:43:38 +07:00
QuantumEntangledAndy bd2adf8924 Merge branch 'master' of github.com:QuantumEntangledAndy/neolink 2024-04-26 11:26:47 +07:00
QuantumEntangledAndy 7e407c4456 Add a print to the entrypoint command 2024-04-26 11:26:20 +07:00
Andrew King d96f637c84 Merge pull request #243 from si458/patch-1
fix timed out waiting for camera ping
2024-04-26 11:18:32 +07:00
QuantumEntangledAndy 67508c1f17 Fix the test_enc3_extension test 2024-04-26 11:16:07 +07:00
QuantumEntangledAndy e85e8f4780 Make check value i32 2024-04-26 11:05:58 +07:00
QuantumEntangledAndy 175c33b131 Merge branch 'test/valgrind' into fix/argus3_disc 2024-04-26 11:05:21 +07:00
Simon Smith 556e051edc fix timed out waiting for camera ping 2024-04-25 12:16:28 +01:00
QuantumEntangledAndy 3bfd273528 Remove valgrind from docker 2024-04-21 18:01:45 +07:00
QuantumEntangledAndy bfa76009b9 One more print 2024-04-20 21:08:46 +07:00
QuantumEntangledAndy c59b44c83e Deeper discovery prints 2024-04-18 22:08:26 +07:00
QuantumEntangledAndy e146f9593b Reduce history buffer duration 2024-04-18 18:57:39 +07:00
QuantumEntangledAndy 5d05504ec8 Add a discovery udpxml test 2024-04-18 18:57:39 +07:00
QuantumEntangledAndy 88a2ec7a11 Fix the build yml 2024-04-18 18:56:41 +07:00
QuantumEntangledAndy 3b0a510ccf Debug print on discovery 2024-04-18 18:55:36 +07:00
QuantumEntangledAndy 2d49df07db Reduce history buffer duration 2024-04-18 18:50:20 +07:00
QuantumEntangledAndy 4d441d89fd Add a discovery udpxml test 2024-04-18 18:49:32 +07:00
QuantumEntangledAndy 31fb8f31db Add m1 macos 2024-04-18 18:48:42 +07:00
QuantumEntangledAndy 616e2e5223 Option time_r in test 2024-04-16 15:43:31 +07:00
QuantumEntangledAndy 08f917279c Make time_r optional in D2C_CFM 2024-04-16 15:23:17 +07:00
QuantumEntangledAndy df0f494702 In Extension::try_parse try to give use ful error message 2024-04-16 15:09:12 +07:00
QuantumEntangledAndy 4bfc73cce5 Merge branch 'test/valgrind' of github.com:QuantumEntangledAndy/neolink into test/valgrind 2024-04-16 10:15:02 +07:00
QuantumEntangledAndy a19a5f3919 Add a maximum length to history buffer too 2024-04-16 10:14:34 +07:00
QuantumEntangledAndy d0db861c10 Add a maximum length to history buffer too 2024-04-16 10:14:22 +07:00
QuantumEntangledAndy 9480dd8605 Increase timeout on rtsp session 2024-04-16 10:13:24 +07:00
QuantumEntangledAndy 2b827d9542 Use constant fps based time and fix history buffers 2024-04-16 10:12:33 +07:00
QuantumEntangledAndy c85a7641cb Insert fillers when no stream 2024-04-16 10:11:06 +07:00
QuantumEntangledAndy e74e12268a Don't use shared pipeline 2024-04-16 10:10:26 +07:00
QuantumEntangledAndy 6572be1d95 Change latency and queue buffers 2024-04-16 10:09:43 +07:00
QuantumEntangledAndy b46e5db5d8 Add message to udp buffers 2024-04-16 10:08:59 +07:00
QuantumEntangledAndy b8a22f4663 Change time units 2024-04-16 10:08:41 +07:00
QuantumEntangledAndy aa8bb6a5db Update push notification IDs between restarts 2024-04-14 14:59:59 +07:00
George Hilliard 4ef6fb59f0 Merge pull request #378 from thirtythreeforty/dependabot/cargo/bumpalo-3.16.0
Bump bumpalo from 3.11.0 to 3.16.0
2024-04-14 00:50:49 -05:00
dependabot[bot] 4b801884ef Bump bumpalo from 3.11.0 to 3.16.0
Bumps [bumpalo](https://github.com/fitzgen/bumpalo) from 3.11.0 to 3.16.0.
- [Changelog](https://github.com/fitzgen/bumpalo/blob/main/CHANGELOG.md)
- [Commits](https://github.com/fitzgen/bumpalo/compare/3.11.0...3.16.0)

---
updated-dependencies:
- dependency-name: bumpalo
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-04-14 02:49:40 +00:00
George Hilliard 26fa7ee161 Merge pull request #377 from thirtythreeforty/Fix-CI-Macos
Fix CI
2024-04-13 21:42:46 -05:00
QuantumEntangledAndy c92e289fb7 Buffer fill prints 2024-04-13 11:31:51 +07:00
QuantumEntangledAndy 350fc7d28c Add some debug prints 2024-04-13 11:27:57 +07:00
QuantumEntangledAndy e6f8aa1e64 Addressing streaming issues 2024-04-12 19:00:00 +07:00
QuantumEntangledAndy 60cdf914a5 Bits to bytes 2024-04-12 14:58:44 +07:00
QuantumEntangledAndy be8ec85175 Reduce buffer sizes 2024-04-12 14:36:15 +07:00
QuantumEntangledAndy d94b24d86d Remove max pool size 2024-04-12 14:14:09 +07:00
QuantumEntangledAndy d6d47039ba Report byte levels 2024-04-12 11:02:24 +07:00
QuantumEntangledAndy 72c486353b Update github runners to node20 2024-04-12 10:50:55 +07:00
QuantumEntangledAndy 8c186f3f56 Run blocking stream code on a seperate thread 2024-04-12 10:28:03 +07:00
QuantumEntangledAndy 87e5bcb931 Logs on the pause 2024-04-12 09:42:34 +07:00
QuantumEntangledAndy cb27c11ed8 Debug logging cleanup 2024-04-12 09:40:42 +07:00
QuantumEntangledAndy ebf607b1a9 Disable PN if no cameras have it enabled 2024-04-11 14:57:13 +07:00
QuantumEntangledAndy 358e62601e Changes to buffer max sizes 2024-04-11 14:03:27 +07:00
QuantumEntangledAndy 0eddab0b2e Use aptitude over apt for resolving conflicts 2024-04-11 10:20:26 +07:00
QuantumEntangledAndy e7268f2481 Swapping to newer config format 2024-04-11 10:12:59 +07:00
QuantumEntangledAndy f31d948671 Cargo fmt 2024-04-11 10:01:39 +07:00
Andrew King 7a920fb09a Update build.rs 2024-04-11 09:51:40 +07:00
Andrew King 2deac96af4 Update to windows too 2024-04-11 09:50:42 +07:00
Andrew King 1e620d15df Update build.yml 2024-04-11 09:45:21 +07:00
QuantumEntangledAndy 7f8ccc6806 Avoid recreating the AES key 2024-04-11 09:33:50 +07:00
QuantumEntangledAndy 8f8d9e6f78 Avoid a needless copy in de 2024-04-10 17:07:35 +07:00
QuantumEntangledAndy ea1b21b7f8 Use pools and padded data 2024-04-10 16:24:04 +07:00
QuantumEntangledAndy 47a89c0c76 Debug build again 2024-04-10 16:20:09 +07:00
QuantumEntangledAndy f07b8e4a8c Test on release 2024-04-10 09:06:24 +07:00
QuantumEntangledAndy b7eb6cefdc Add a timeout so that it stops on its own (and generated a massif.out) 2024-04-09 13:02:05 +07:00
QuantumEntangledAndy 2fc5c24834 Without the --debug 2024-04-09 11:31:19 +07:00
QuantumEntangledAndy d6d4ea522e Less zealous find and replace 2024-04-09 11:28:13 +07:00
QuantumEntangledAndy 31048ed075 Basic valgrind massif docker 2024-04-09 11:26:15 +07:00
Andrew King d354b90976 Merge pull request #231 from QuantumEntangledAndy/feature/port_control 2024-04-08 10:47:32 +07:00
QuantumEntangledAndy 54f7665414 Add command for camera service port controls (not on old camera) 2024-04-05 19:06:02 +07:00
QuantumEntangledAndy 9187694889 Update to udp discovery xml 2024-04-05 18:47:32 +07:00
Andrew King c0a6123740 Merge pull request #230 from QuantumEntangledAndy/feature/shared_gst
Update deps
2024-04-05 15:15:05 +07:00
QuantumEntangledAndy 04595b6aff Windows build script woes 2024-04-05 14:55:21 +07:00
QuantumEntangledAndy 1ba899840f Merge branch 'master' into feature/shared_gst 2024-04-05 14:39:43 +07:00
QuantumEntangledAndy 919d8fffba Changes to serde 2024-04-05 13:42:28 +07:00
QuantumEntangledAndy c3ed0b41ab Test passing, clippy fixes 2024-04-05 11:29:25 +07:00
QuantumEntangledAndy 4c17fa9f2b Deps and logs
Use quick_xml instead of yaserde

Use thiserror instead of err_derive

Update deps to latest (except fcm), fcm will need to wait for reolink to update their fcm apis first in their app
2024-04-04 12:47:36 +07:00
Andrew King df0642e0f8 Merge pull request #199 from Frans-Willem/feature/fix-talk-stability 2024-03-31 10:52:15 +07:00
Andrew King cfd7ac6778 Merge pull request #184 from vfdev-5/typos 2024-03-31 10:49:43 +07:00
Andrew King 6b9731168d Merge pull request #194 from iam-TJ/doc-dissector 2024-03-31 10:49:00 +07:00
Andrew King 14f867c728 Merge pull request #200 from Cian911/ciang/support-k8s 2024-03-31 10:47:45 +07:00
Andrew King fbd19fd5c6 Merge pull request #205 from developersteve/master 2024-03-31 10:46:10 +07:00
Andrew King fde7a08405 Merge pull request #220 from rexxars/fix/typos 2024-03-31 10:44:46 +07:00
Espen Hovlandsdal 37f560cf66 Fix typos in comments and code 2024-03-14 10:24:16 -07:00
developersteve fcc559885a Update README.md with env var changes
added README information about the added `NEO_LINK_MODE` and `NEO_LINK_PORT` variables
2024-01-18 17:40:57 +11:00
developersteve 8205b652d3 Update Dockerfile with env vars 2024-01-18 17:36:31 +11:00
developersteve 1a020e5788 Update Dockerfile to include a NEO_LINK_MODE
This enables the ability to change the neolink mode type using an env var so that it's not locked to RTSP but will default to RTSP if the env var is not set.
2024-01-17 14:01:06 +11:00
Cian Gallagher b13db1227d feat: add support for running neolink in k8s. add related documentation. 2023-12-03 12:37:22 +00:00
Frans-Willem Hardijzer 261e458947 Stop making assumptions around buffer size, just use expected message duration instead. 2023-12-01 15:02:47 +01:00
Frans-Willem Hardijzer afabd05cef No need to time sending the blocks, the response message will be delayed if the buffer on the device is full. 2023-12-01 14:48:33 +01:00
Frans-Willem Hardijzer ce4e4f2f5d Move payload_bytes into loop, instead of constantly re-setting it. 2023-12-01 14:47:57 +01:00
Frans-Willem Hardijzer b6c7cff6a7 Better timing of sending chunks, works well for files, might not for streams (e.g. microphone) 2023-12-01 13:44:22 +01:00
Frans-Willem Hardijzer 9cd5551156 Properly handle response of TALK command, such that receive buffer doesn't fill up.
If receive buffer fills up, neolink will never exit as the response to TALK_STOP will not get handled correctly.
2023-12-01 13:40:45 +01:00
Tj 311b8b03d8 dissector: add instructions on building and using 2023-11-19 11:04:20 +00:00
vfdev 606c978a86 Fixed typos 2023-11-06 00:06:13 +01:00
QuantumEntangledAndy acae5f95ee Larger buffer for the appsrc 2023-10-31 08:09:07 +07:00
QuantumEntangledAndy 76e804ea6a Set missed tick to skip 2023-10-30 12:08:50 +07:00
QuantumEntangledAndy 18a69b9d1e Add a frame reorder 2023-10-30 09:44:34 +07:00
QuantumEntangledAndy 159cb4b716 Frame time changes 2023-10-30 07:44:37 +07:00
QuantumEntangledAndy 6c64cf663a Use shared factory pipeline 2023-10-29 17:29:40 +07:00
QuantumEntangledAndy 5cec02e3c2 Use a central UID system for push notifications 2023-10-29 17:24:21 +07:00
QuantumEntangledAndy 4a94a2ddb2 README.md 2023-10-28 12:20:11 +07:00
QuantumEntangledAndy 459c9255ad v0.6.3-rc.1 2023-10-28 12:17:23 +07:00
QuantumEntangledAndy 07636a407b Disable keyframe repeat again 2023-10-28 10:07:58 +07:00
QuantumEntangledAndy 5ede452a12 Use bell for siren not restart 2023-10-28 07:57:32 +07:00
QuantumEntangledAndy dc4b5505b0 Change how keyframe resume is printed 2023-10-27 19:06:09 +07:00
QuantumEntangledAndy 7f047efaef Further CPU optiations 2023-10-27 16:13:11 +07:00
QuantumEntangledAndy a6c8665a98 Retry send errors in passive task 2023-10-26 13:34:03 +07:00
QuantumEntangledAndy 71dc655673 Retry send errors in passive task 2023-10-26 13:33:01 +07:00
QuantumEntangledAndy 4cbf8d22dd Try with repeat iframes again 2023-10-26 12:17:33 +07:00
QuantumEntangledAndy a7d2574e88 Try with repeat iframes again 2023-10-26 12:17:17 +07:00
QuantumEntangledAndy a023138a8d Remove good doggo message 2023-10-26 12:14:20 +07:00
QuantumEntangledAndy f56346194e Add siren discovery and update readme 2023-10-26 11:46:07 +07:00
QuantumEntangledAndy a634639778 Increase broadcast size to something more realist for large streams 2023-10-26 11:35:27 +07:00
QuantumEntangledAndy 45151203e2 Add the siren.rs 2023-10-26 11:31:22 +07:00
QuantumEntangledAndy 44ffdcc2e8 Add filter for unknown messages in dissector 2023-10-26 10:49:00 +07:00
QuantumEntangledAndy 31c825f228 Make dissector extract the nonce itself 2023-10-26 10:34:57 +07:00
QuantumEntangledAndy 6653fc43ac Add discovery and status into mqtt for floodlight tasks 2023-10-26 09:35:25 +07:00
QuantumEntangledAndy 484d16c262 Hnadle flushing error in appsrc as non fatal 2023-10-24 15:39:47 +07:00
QuantumEntangledAndy 5527f0281e More adjustments to connection timeouts 2023-10-24 12:40:54 +07:00
QuantumEntangledAndy f532d83bb3 More inner udp source timeout locations 2023-10-24 12:28:43 +07:00
QuantumEntangledAndy 9518a566a4 Fix control/zoom mqtt command name 2023-10-24 11:18:28 +07:00
QuantumEntangledAndy d069b47972 Fix naming of get and set zoom 2023-10-24 11:03:05 +07:00
QuantumEntangledAndy 61a5073adb Add methods to get current zoom and its limits 2023-10-24 10:39:30 +07:00
QuantumEntangledAndy 9dd8c2ea99 Add basic zoom functalilty 2023-10-24 08:55:50 +07:00
QuantumEntangledAndy db98926e6c Disable keyframe repeat 2023-10-23 10:00:26 +07:00
QuantumEntangledAndy 9ae537fb38 Add control/floodlight_tasks 2023-10-23 09:57:33 +07:00
QuantumEntangledAndy 7d5782d2a3 Reconnect fcm every 5 mins 2023-10-23 09:35:37 +07:00
QuantumEntangledAndy 446387a3a0 Fix action parsing 2023-10-23 08:58:06 +07:00
QuantumEntangledAndy a9540d0c26 Add floodlight task xml 2023-10-20 17:05:16 +07:00
QuantumEntangledAndy ab87f0325d Make fallback switch for audio optional 2023-10-19 14:32:37 +07:00
QuantumEntangledAndy 06b9482501 Appropiate cancels in the stream main 2023-10-19 13:55:58 +07:00
QuantumEntangledAndy b3a524823f Rework how the pause works 2023-10-19 12:49:16 +07:00
QuantumEntangledAndy b1ad94ca03 Add info of profile api 2023-10-19 12:18:48 +07:00
QuantumEntangledAndy 362c764d08 Small rework to ping error handle 2023-10-19 11:50:48 +07:00
QuantumEntangledAndy 3cdd75b244 More debug print for stream restarts 2023-10-19 11:22:20 +07:00
QuantumEntangledAndy b1305c3fc8 Assume that no ping 5x means unsupported 2023-10-19 10:39:49 +07:00
QuantumEntangledAndy 6ec0600445 Print name in camthread messages 2023-10-19 10:21:43 +07:00
QuantumEntangledAndy 93bf955a37 Rework how the wakecommand works 2023-10-19 09:41:10 +07:00
QuantumEntangledAndy 7809f6db78 Remove extra use, and some more fixes 2023-10-19 09:35:22 +07:00
QuantumEntangledAndy ccd39c5e65 Remove extra use, and some more fixes 2023-10-19 09:35:11 +07:00
QuantumEntangledAndy 7e9b3d5fb7 Fixes 2023-10-19 09:32:36 +07:00
QuantumEntangledAndy 6027d6f643 More debug on push notifications 2023-10-19 09:30:20 +07:00
QuantumEntangledAndy c05168bec8 Make control/wakeup wait for connect before starting the countdown 2023-10-19 09:11:56 +07:00
QuantumEntangledAndy 63df8b3d9b More debug when registering a camera for push notifiations 2023-10-18 12:24:42 +07:00
QuantumEntangledAndy 15545a7db2 Reregister push notifications when needed 2023-10-18 08:32:10 +07:00
QuantumEntangledAndy 0702110f1f Unbreak OK filter on mqtt 2023-10-17 19:43:57 +07:00
QuantumEntangledAndy 6f24056ad1 Debug int parse issue 2023-10-17 19:41:39 +07:00
QuantumEntangledAndy 6501b82379 pattern not patter 2023-10-17 12:49:02 +07:00
QuantumEntangledAndy 86456335f0 Add splash_pattern config 2023-10-17 12:47:23 +07:00
QuantumEntangledAndy 0cf5b1e8f2 Add a mqtt command for waking up from idle
The command is `control/wakeup (mins)`
2023-10-17 12:13:50 +07:00
QuantumEntangledAndy 561b7f094d Add audio silence during skip too 2023-10-17 11:47:05 +07:00
QuantumEntangledAndy c8f8f2bd9d Change the fps of the repeat iframes 2023-10-17 10:42:13 +07:00
QuantumEntangledAndy 5871d0566d Wait longer for frame repeat 2023-10-12 14:21:41 +07:00
QuantumEntangledAndy aeab451bbc Don't dump historical buffer 2023-10-12 14:18:53 +07:00
QuantumEntangledAndy b10ee03f22 More changes to session cleanup 2023-10-12 14:15:38 +07:00
QuantumEntangledAndy ed0909a797 Teardown 2023-10-12 10:16:15 +07:00
QuantumEntangledAndy d550f08d88 Print more session info 2023-10-12 09:39:59 +07:00
QuantumEntangledAndy f4a0cb3abc Small pause after a connection 2023-10-12 06:12:46 +07:00
QuantumEntangledAndy 0aa9b347cc Add periodic session cleanup 2023-10-12 06:09:50 +07:00
QuantumEntangledAndy e362ff1b0a Add periodic session cleanup 2023-10-11 20:32:49 +07:00
QuantumEntangledAndy d011a37731 Print on non keyrepeat frame 2023-10-11 16:54:56 +07:00
QuantumEntangledAndy 9d47021aa7 Allow for some missed pings (UDP ness) 2023-10-11 09:44:53 +07:00
QuantumEntangledAndy f3587bafe4 Full debug logs on tasks error messages 2023-10-11 09:42:40 +07:00
QuantumEntangledAndy 70e8da0702 Without keyframe repeat 2023-10-10 12:40:49 +07:00
QuantumEntangledAndy 8067ffc30d || 2023-10-10 12:31:39 +07:00
QuantumEntangledAndy 6824d52db7 Make failing to build media a soft error 2023-10-10 11:53:33 +07:00
QuantumEntangledAndy 6058d95b3a Rework error retries in the tasks 2023-10-10 11:28:43 +07:00
QuantumEntangledAndy 6e8c744025 More debug prints on the mqtt disconnect points 2023-10-09 21:14:56 +07:00
QuantumEntangledAndy 4d3c3ec610 Fix tightloop in push notficaiton 2023-10-08 20:38:17 +07:00
QuantumEntangledAndy 1195087d4b Add more retryable IO errors 2023-10-08 18:01:48 +07:00
QuantumEntangledAndy acaa4703df More checks for live appsrc 2023-10-08 17:54:24 +07:00
QuantumEntangledAndy 33e51a7c13 Log cleanup 2023-10-08 17:34:08 +07:00
QuantumEntangledAndy 894f2e3644 Refractor stream handlleing 2023-10-08 17:13:04 +07:00
QuantumEntangledAndy 0d9d6b97c9 Move async handle into closure 2023-10-06 15:15:18 +07:00
QuantumEntangledAndy beb9fed919 Experimental skip frames 2023-10-06 15:02:46 +07:00
QuantumEntangledAndy 6daf1f5b3d More adjustments to timestamping 2023-10-05 11:21:30 +07:00
QuantumEntangledAndy bd17c8e5e0 Cancel certain async callback on disconnect 2023-10-05 09:32:38 +07:00
QuantumEntangledAndy ca823a1894 Fix blocking send on need and enough callbacks 2023-10-04 07:33:42 +07:00
QuantumEntangledAndy fa4ebc436f Dep bump 2023-10-03 18:15:23 +07:00
QuantumEntangledAndy c09bc13598 Settup EOS shutdowns, fix frame order 2023-10-03 11:55:03 +07:00
QuantumEntangledAndy 47e9b8ffe0 Some more windows setup 2023-10-03 08:48:31 +07:00
QuantumEntangledAndy 44fc744dcd Variable openssl path for windows 2023-10-03 08:46:41 +07:00
QuantumEntangledAndy 26f82f0395 Check windows drives early 2023-10-02 12:51:19 +07:00
QuantumEntangledAndy 095bd889ef Unwrap io errors if its a bcerror 2023-10-02 12:42:06 +07:00
QuantumEntangledAndy 3d0f8b794e More ways to generate an IO::Disconnect error 2023-10-02 12:15:57 +07:00
QuantumEntangledAndy f13887a369 Check the inner IO errors 2023-10-02 08:55:10 +07:00
QuantumEntangledAndy 8bdb8ef1bd Add a counter for the number of clients 2023-09-28 13:00:37 +07:00
QuantumEntangledAndy daf44fe1c2 More changes to keep threads alive over reconnect 2023-09-28 12:21:11 +07:00
QuantumEntangledAndy c14cdcccc2 Track more error types for connect restarts 2023-09-28 12:12:32 +07:00
QuantumEntangledAndy 969bcb8956 Base buffer size on bitrate 2023-09-28 06:49:21 +07:00
QuantumEntangledAndy a8cee8d294 Fix some stary bugs in md pause and enable_preview 2023-09-27 15:40:38 +07:00
QuantumEntangledAndy 6bea9a805e CLippy and build fixes 2023-09-27 13:26:48 +07:00
QuantumEntangledAndy 393e127d89 Hook push notifications into the motion pause system 2023-09-27 12:31:52 +07:00
QuantumEntangledAndy 52008e351f More docker changes 2023-09-27 11:35:52 +07:00
QuantumEntangledAndy 8ae76a8dc3 Retry push notifications on registration failure 2023-09-27 11:24:43 +07:00
QuantumEntangledAndy 53891f256a Disable push notificaiton on certain errors 2023-09-27 10:09:30 +07:00
QuantumEntangledAndy 40f9f2c795 Include ssl and cacerts in docker 2023-09-27 09:00:28 +07:00
QuantumEntangledAndy 0fc0455111 Add debug message for push server fails 2023-09-26 21:14:30 +07:00
QuantumEntangledAndy 4a010b5095 Openssl in windows might give issues 2023-09-26 20:28:09 +07:00
QuantumEntangledAndy cd189fc61d More windows openssl fun 2023-09-26 19:57:42 +07:00
QuantumEntangledAndy 240ebab622 Openssl in windows might give issues 2023-09-26 19:34:47 +07:00
QuantumEntangledAndy 48b81ff1d3 The other dependencies too 2023-09-26 19:07:49 +07:00
QuantumEntangledAndy f52aad3b48 Try installing via usual methods 2023-09-26 19:01:51 +07:00
QuantumEntangledAndy 28457510e2 Add dependencies into github action 2023-09-26 18:53:43 +07:00
QuantumEntangledAndy 3f95aafe99 Handle restart of push notification client 2023-09-26 18:30:14 +07:00
QuantumEntangledAndy f4b852f1e6 Handle additional last will clients 2023-09-26 15:34:13 +07:00
QuantumEntangledAndy 0f28154fdb Push notifications and disconnect on idle 2023-09-26 14:44:59 +07:00
Andrew 061cba4f6d Merge branch 'feature/push_notification' into feature/push_mqtt 2023-09-26 10:13:19 +07:00
QuantumEntangledAndy 776c63a1bf channel alias 2023-09-26 10:08:06 +07:00
QuantumEntangledAndy 30fd27bfcf A few more memory optimisations 2023-09-26 10:06:42 +07:00
QuantumEntangledAndy e47a0d5734 v0.6.2 2023-09-25 16:29:03 +07:00
QuantumEntangledAndy 2ba75e7df7 v0.6.2 2023-09-25 16:28:51 +07:00
QuantumEntangledAndy 67c545a483 Bring back use_splash 2023-09-25 16:27:52 +07:00
QuantumEntangledAndy b63fc743d9 Don't instantly remove the user name 2023-09-25 15:55:17 +07:00
QuantumEntangledAndy da66b1b2ff Rework thread creation to reduce memory stress 2023-09-25 15:30:31 +07:00
QuantumEntangledAndy d9c8caeff8 Remove jitterbuffer on h265 2023-09-24 15:53:11 +07:00
QuantumEntangledAndy 8735ab7664 Add the mqtt command query/preview 2023-09-24 14:47:30 +07:00
QuantumEntangledAndy 0f91c06d0b v0.6.1 2023-09-24 13:47:45 +07:00
QuantumEntangledAndy 21ffcf3809 Fix MQTT issues 2023-09-24 13:46:17 +07:00
QuantumEntangledAndy 31d6c1ef62 Seperate tasks into passive and active 2023-09-24 09:14:08 +07:00
QuantumEntangledAndy b00bc20c81 Use connected over online for mqtt message 2023-09-23 12:07:13 +07:00
QuantumEntangledAndy eb994dc65d Fix [[mqtt]] in readme 2023-09-23 09:05:43 +07:00
QuantumEntangledAndy 87e32f571a Cancel threads in stream witha drop guard 2023-09-21 11:23:20 +07:00
QuantumEntangledAndy 9f02f6dead Merge branch 'master' of github.com:QuantumEntangledAndy/neolink 2023-09-21 09:36:46 +07:00
QuantumEntangledAndy 66c5202caf Skip frames before first iframe 2023-09-21 09:34:26 +07:00
Andrew King 1288e92517 Merge pull request #149 from dgriswo/patch-1 2023-09-21 08:36:35 +07:00
QuantumEntangledAndy c7ad6c9ea2 Use queue2 2023-09-20 13:05:52 +07:00
QuantumEntangledAndy 23524c6422 Try not to implement stream 2023-09-20 12:37:44 +07:00
dgriswo b067f6b1f9 Update README.md 2023-09-19 22:11:29 -04:00
dgriswo 3b0e1faf5c mqtt server was replaced by broker_addr 2023-09-19 22:08:06 -04:00
QuantumEntangledAndy e41668df53 Adjust pts to jitter buffer 2023-09-20 08:04:23 +07:00
QuantumEntangledAndy 2b5f9b718b Even earlier stream start BI woes... 2023-09-19 19:14:51 +07:00
QuantumEntangledAndy 1134d50492 Try to make all threads close on drop 2023-09-19 12:27:05 +07:00
QuantumEntangledAndy 08df28633f Create a dummy factory sooner 2023-09-19 09:26:02 +07:00
QuantumEntangledAndy e5008abe56 v0.6.0 2023-09-18 09:25:37 +07:00
QuantumEntangledAndy 40742fd850 Update the readme 2023-09-18 09:21:24 +07:00
QuantumEntangledAndy 7d4001eb39 Shorten watcgdog to 2s 2023-09-16 10:42:29 +07:00
QuantumEntangledAndy dc6ca3532b Add a watchdog to the stream 2023-09-16 10:41:42 +07:00
QuantumEntangledAndy e894b7cb4a Imporve the mqtt poll loop 2023-09-15 17:05:20 +07:00
QuantumEntangledAndy e7268e0e04 Use mqtt to update active streams 2023-09-15 12:48:13 +07:00
QuantumEntangledAndy d9541766dc Use reactor for all commands 2023-09-15 08:37:14 +07:00
QuantumEntangledAndy cc9c35400f Update the config via mqtt 2023-09-15 08:08:09 +07:00
QuantumEntangledAndy 3391666598 Saturating subs 2023-09-15 07:23:33 +07:00
QuantumEntangledAndy 5561236323 Immediatly send a Hb packet on reconnect 2023-09-14 13:28:56 +07:00
QuantumEntangledAndy 5c73615f90 First try reconnect on the same port 2023-09-14 13:20:06 +07:00
QuantumEntangledAndy 1f5db9f0b1 Add a low level socket reconnect 2023-09-14 12:30:12 +07:00
QuantumEntangledAndy e996279e8a Avoid the split sink 2023-09-13 15:59:31 +07:00
QuantumEntangledAndy 93c1b28a60 Make high/low stream fill in highest/lowest in the config 2023-09-12 17:05:31 +07:00
QuantumEntangledAndy 101f2ffaa9 WIP Mqtt using reactor 2023-09-12 16:41:45 +07:00
QuantumEntangledAndy 2a10236f91 Add motion pause to rtsp 2023-09-06 11:56:13 +07:00
QuantumEntangledAndy 573db1a193 Add motion pause to rtsp 2023-09-06 11:52:52 +07:00
QuantumEntangledAndy fe63e35584 Make stream instances provide an activation handle 2023-09-06 03:02:33 +07:00
QuantumEntangledAndy 86c6de3bd8 Fix stream thread activation 2023-09-06 02:21:43 +07:00
QuantumEntangledAndy a8845c48a9 Handle stream vid/aud seperation globally 2023-09-05 11:20:41 +07:00
QuantumEntangledAndy cf6d266508 Allow config alterations to change the avaliable rtsp streams 2023-09-03 23:49:57 +07:00
QuantumEntangledAndy 71e9830643 Use reactor for rtsp 2023-09-03 09:57:19 +07:00
Andrew 1da4472ca8 Merge branch 'master' into refractor/neo_reactor 2023-08-31 07:10:24 +07:00
QuantumEntangledAndy ff2591e544 Changes to discovery
- Timeout is longer
- Number of retries configurable with max_retries in config
- Longer wait between resend
- Don't send multiple to same reg sever
2023-08-30 23:54:53 +07:00
QuantumEntangledAndy 23f5f11b27 WIP Reactor 2023-08-30 23:20:07 +07:00
QuantumEntangledAndy 746d449639 Imporve error recognition in stream 2023-08-27 18:04:01 +07:00
QuantumEntangledAndy 210e6690ce Imporve stream restart logic 2023-08-27 16:08:35 +07:00
QuantumEntangledAndy d068eeefc7 Breakout reactor code to modules 2023-08-27 15:25:35 +07:00
QuantumEntangledAndy 1e64192da5 Use reactor for image command 2023-08-27 14:34:04 +07:00
QuantumEntangledAndy 66637998a6 Use reactor with simple commands 2023-08-25 12:19:29 +07:00
Andrew b200288b38 Start Neoreactor
This is centralised reconnect managment that allows async retries over reconnects of the camera
2023-08-25 09:54:20 +07:00
QuantumEntangledAndy 0768bcf959 Send pings regardless of state 2023-08-21 19:10:46 +07:00
QuantumEntangledAndy 48892344b8 Add pings to the camera while paused 2023-08-21 11:00:45 +07:00
QuantumEntangledAndy cc275ed02e Remove the stop on error 2023-08-21 09:34:42 +07:00
QuantumEntangledAndy 9786953e5f Change some timeouts and send ack less often 2023-08-21 09:32:02 +07:00
QuantumEntangledAndy bdc6fad818 Use send over send_all 2023-08-19 10:40:32 +07:00
QuantumEntangledAndy ff569dc15b Low level ack and send on their own threads 2023-08-18 12:36:06 +07:00
QuantumEntangledAndy ea2cad06ea Fix motion paues flag tracking 2023-08-16 19:13:02 +07:00
QuantumEntangledAndy 4030f4a9cd Don't unwrap in production 2023-08-16 19:00:53 +07:00
QuantumEntangledAndy 13c06afc67 Log cleanup 2023-08-16 18:54:00 +07:00
QuantumEntangledAndy d64dbdb027 Default false should return false 2023-08-16 18:34:02 +07:00
QuantumEntangledAndy 8f21ace578 Abort the inner udp handle on drop 2023-08-16 11:56:34 +07:00
QuantumEntangledAndy e08bb66891 v0.5.18 2023-08-15 19:02:06 +07:00
Andrew 173c994530 Merge branch 'fix/snap' 2023-08-15 19:00:18 +07:00
Andrew 95ce97c85e Merge branch 'refractor/udp_layer' 2023-08-15 19:00:09 +07:00
Andrew 9087169873 Merge branch 'feature/motion_ai' 2023-08-15 18:59:49 +07:00
QuantumEntangledAndy d08a5fe4aa Add Pref to luacheck globals 2023-08-15 18:50:29 +07:00
QuantumEntangledAndy 6a4468c8f6 Name wireshark reassembly 2023-08-15 18:14:19 +07:00
QuantumEntangledAndy d084a13eb0 Add AES decryption to dissector. REQUIRES luagcrypt 2023-08-15 18:01:42 +07:00
QuantumEntangledAndy 1cde5ec3e5 Cleanup old subscribers 2023-08-14 18:42:15 +07:00
QuantumEntangledAndy 97703bdb38 Fix for Snap on older cameras 2023-08-14 17:12:07 +07:00
QuantumEntangledAndy d0c85419eb Low level UDP timeout 2023-08-14 13:05:21 +07:00
QuantumEntangledAndy a8a306301b Rework low level UDP layer 2023-08-14 11:52:18 +07:00
QuantumEntangledAndy f23f28c12e Log cleanup 2023-08-12 11:11:01 +07:00
QuantumEntangledAndy 623fcb3fd1 Optimisation of the UDP acknoledgment flushing 2023-08-12 11:06:28 +07:00
QuantumEntangledAndy e093151db6 Add a debug option to the camera config 2023-08-10 15:17:12 +07:00
QuantumEntangledAndy eefe3dfa71 Make listen on motion as fire on AIType 2023-08-08 16:26:04 +07:00
QuantumEntangledAndy 6e8fc3ee5b Add battery sub command 2023-08-07 19:03:31 +07:00
QuantumEntangledAndy 17e8ab0f37 Add gracefull shutdown to sub commands 2023-08-07 19:03:06 +07:00
QuantumEntangledAndy 0d2f0c3e6f Also bump man cargo version number 2023-08-07 17:22:14 +07:00
QuantumEntangledAndy 0661aa8853 v0.5.17 2023-08-07 16:35:38 +07:00
Andrew King a380212662 Merge pull request #127 from QuantumEntangledAndy/fix/sim_sub_disc
Fix login on new firmware
2023-08-07 16:33:12 +07:00
QuantumEntangledAndy a45bcf8761 Added enable config option 2023-08-07 10:52:16 +07:00
QuantumEntangledAndy c198f21c92 Add a latency field to the ack packet 2023-08-07 09:01:13 +07:00
QuantumEntangledAndy 5109dbba9e Only decrypt bcmecia packets where encrypt len is set 2023-08-06 19:05:04 +07:00
QuantumEntangledAndy b90d6d7eed Try AES on binary payloads 2023-08-06 17:31:08 +07:00
QuantumEntangledAndy 971c1cddf8 Match on 0x12 inside de.rs too 2023-08-05 10:10:22 +07:00
QuantumEntangledAndy 816797a32b Match both 0x02, 0x12 as the basic AES 2023-08-04 22:27:28 +07:00
QuantumEntangledAndy c3921cbb6c Try with a 0x12 for the login kind 2023-08-04 21:46:03 +07:00
QuantumEntangledAndy e93dc2fe9a Don't send -1 ack packets again 2023-08-04 21:09:56 +07:00
QuantumEntangledAndy af899d3cfd Empty legacy packet 2023-08-04 19:53:02 +07:00
QuantumEntangledAndy 6b60ee6bcc Don't send -1 ack packets 2023-08-04 18:59:14 +07:00
QuantumEntangledAndy 810dd3cdc7 Fix early exit on discovery 2023-08-04 18:53:08 +07:00
Andrew 374b399631 Fix simultaneous discovery subscription 2023-08-04 16:33:39 +07:00
QuantumEntangledAndy 2484b8753b v0.5.16 2023-08-04 08:33:02 +07:00
Andrew King 9730114172 Merge pull request #125 from QuantumEntangledAndy/fix/non_zero_port 2023-08-03 20:16:52 +07:00
QuantumEntangledAndy c45a5033b9 fmt 2023-08-03 18:59:59 +07:00
QuantumEntangledAndy b2e43c605e Loop registration, until timeout 2023-08-03 18:55:45 +07:00
QuantumEntangledAndy e3b057f915 Ensure port is non zero in discovery 2023-08-03 18:08:34 +07:00
Andrew 2f557f777d Handle graceful shutdown in image command 2023-08-03 18:07:42 +07:00
QuantumEntangledAndy 42ee790512 v0.5.15 2023-08-03 13:35:42 +07:00
Andrew ae9d204718 Merge branch 'feature/noSplash' 2023-08-03 13:33:49 +07:00
Andrew King 5c7de6181c Merge pull request #123 from QuantumEntangledAndy/fix/async_lookup_and_register
Fix/async lookup and register
2023-08-03 13:33:25 +07:00
Andrew King 268303a0a2 Update README.md 2023-08-03 10:48:43 +07:00
QuantumEntangledAndy acc063e325 Readme updates 2023-08-03 10:47:19 +07:00
QuantumEntangledAndy e384fb6153 Single registration discovery 2023-08-03 09:19:31 +07:00
Andrew f6085cff1f Fix Lookup 2023-08-03 09:19:31 +07:00
Andrew King 94ffc54325 Add note about --use-stream to the README 2023-07-18 19:00:37 +07:00
Andrew ce89a6dfbc Merge branch 'maintenance/readMe' 2023-07-18 18:47:43 +07:00
QuantumEntangledAndy 6925736030 Funding yml 2023-07-18 18:47:01 +07:00
Andrew King edfacc7eba Update README.md 2023-07-18 18:45:03 +07:00
QuantumEntangledAndy 786218a114 Make Stream Not Ready splash optional 2023-07-18 14:51:14 +07:00
QuantumEntangledAndy 52ad743bea v0.5.14 2023-07-18 09:16:53 +07:00
Andrew King 0331945730 Merge pull request #116 from QuantumEntangledAndy/fix/streamPrep
Fix Gstreamer Issues with Memory
2023-07-18 09:15:48 +07:00
QuantumEntangledAndy 790807c016 Update deps 2023-07-18 09:10:48 +07:00
QuantumEntangledAndy 45e08e6d7d Trying new buffer push 2023-07-17 09:20:13 +07:00
QuantumEntangledAndy 5b3f845c83 Try process buffers sequentially 2023-07-16 18:30:28 +07:00
QuantumEntangledAndy 4d6d5c5ac5 Single queue 2023-07-16 15:27:06 +07:00
QuantumEntangledAndy 5583ea0f9a Wrapping appsrc in an Arc 2023-07-16 12:27:24 +07:00
Andrew King 4286e75ca6 Merge pull request #106 from QuantumEntangledAndy/feature/image_snap
Use snap command to make jpeg images
2023-07-15 19:09:08 +07:00
QuantumEntangledAndy 15880d1b84 Update image doc 2023-06-19 10:17:48 +07:00
QuantumEntangledAndy 0aee461156 Use tokio file 2023-06-19 10:14:46 +07:00
QuantumEntangledAndy b9969ce9ad Use snap command to make jpeg images 2023-06-15 14:09:15 +07:00
QuantumEntangledAndy 254a310fe9 v0.5.13 2023-06-15 13:53:21 +07:00
Andrew King 679cd60ce0 Merge pull request #95 from kevin-david/discovery
Feature/optional MQTT discovery
2023-06-15 13:48:21 +07:00
QuantumEntangledAndy f73dbacd26 fmt 2023-06-08 16:42:41 +07:00
QuantumEntangledAndy c6505952d5 Add config options for mqtt threads 2023-06-08 16:42:20 +07:00
QuantumEntangledAndy 4f0169ef8f fmt 2023-06-08 13:40:58 +07:00
Andrew 15bf7cfa49 Merge remote-tracking branch 'upstream/master' into discovery 2023-06-08 13:36:29 +07:00
Andrew King 6df5091246 Merge pull request #102 from QuantumEntangledAndy/feature-ptz-preset
Seperate set and assign presets. Also add queury messages to mqtt
2023-06-08 13:25:36 +07:00
QuantumEntangledAndy fbbfddaa37 Handle closing and upgrade message numbers and IDs more cleanly 2023-06-08 13:22:54 +07:00
QuantumEntangledAndy f7b5e89ba8 Handle messages and IDs to better replicate offical messaging system 2023-06-08 12:52:53 +07:00
QuantumEntangledAndy c7bd565049 Handle off byte endian and handle ServieUnavalible in mqtt 2023-06-08 10:13:42 +07:00
QuantumEntangledAndy 83dc6cc90b Add battery sensor to discovery README 2023-06-07 20:58:46 +07:00
QuantumEntangledAndy a449666a8c Add battery sensor to discovery 2023-06-07 20:57:29 +07:00
QuantumEntangledAndy 56476bc162 Add simple battery level 2023-06-07 18:43:39 +07:00
QuantumEntangledAndy c30725bc09 Update readme 2023-06-07 17:56:22 +07:00
QuantumEntangledAndy 3467951c5c Handle message that don't reply on success 2023-06-07 17:36:42 +07:00
QuantumEntangledAndy 9eb892ae27 fmt 2023-06-07 15:59:31 +07:00
QuantumEntangledAndy 00f30b8972 Use enum for config 2023-06-07 15:57:07 +07:00
QuantumEntangledAndy dba2f24364 Add all the mqtt controls to auto discovery 2023-06-07 15:41:10 +07:00
QuantumEntangledAndy 04d15537e4 Update the ptz mod.rs readme 2023-06-07 13:41:01 +07:00
QuantumEntangledAndy b5ae5f2fb5 fmt 2023-06-07 13:39:16 +07:00
Andrew 9267de44c7 Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-06-07 13:35:15 +07:00
QuantumEntangledAndy 2b3ae0e522 Add snap.rs 2023-06-07 13:08:38 +07:00
QuantumEntangledAndy c2e613d68b fmt 2023-06-07 13:06:01 +07:00
QuantumEntangledAndy b221fe6961 Actually add the new .rs 2023-06-07 13:04:34 +07:00
QuantumEntangledAndy 10956e8c8e Add camera preview into mqtt via snap shot command 2023-06-07 13:03:58 +07:00
QuantumEntangledAndy 48f385e73a Add camera preview auto discovery 2023-06-06 15:55:04 +07:00
QuantumEntangledAndy 5c3cae597f Merge branch 'master' of https://github.com/QuantumEntangledAndy/neolink into discovery 2023-06-06 13:25:30 +07:00
Andrew King 4c028bd6de Merge pull request #101 from QuantumEntangledAndy/refractor/buffer
Refractor/buffer
2023-06-06 07:23:01 +01:00
Andrew 1390fa0cf9 Merge branch 'master' into refractor/buffer 2023-06-06 11:47:40 +07:00
QuantumEntangledAndy de0528b1b8 Set pts and dts 2023-06-06 11:39:03 +07:00
QuantumEntangledAndy dee305710c Not on a cron 2023-06-06 11:23:01 +07:00
Andrew 77a33ac86a Merge remote-tracking branch 'upstream/master' 2023-06-06 11:22:18 +07:00
QuantumEntangledAndy a08019bc09 Ensure some buffer for pause before we declare ready 2023-06-06 11:07:43 +07:00
QuantumEntangledAndy 60638441aa Reduce default buffer size 2023-06-06 10:57:39 +07:00
QuantumEntangledAndy 9e981df990 Fixes for zero buffer config 2023-06-06 10:52:45 +07:00
QuantumEntangledAndy 73e828f940 Restore stream timestamp stitching for the pause 2023-06-06 10:45:58 +07:00
Andrew King 017b9cb493 Merge pull request #90 from QuantumEntangledAndy/feature/single_quality_pause
Feature/single quality pause
2023-06-06 04:07:13 +01:00
QuantumEntangledAndy a165377d7a Not smoothing when no buffer 2023-06-05 07:58:16 +07:00
QuantumEntangledAndy f7c16bf5a3 Allow zero buffer and remove buffer refill 2023-06-05 07:53:25 +07:00
Kevin David b5136ed913 Document MQTT Discovery in README.md 2023-06-04 12:53:16 -04:00
Kevin David 2d37807401 Don't get clever trying to reuse device/availability 2023-06-04 12:44:20 -04:00
Kevin David fd3fffc0a1 Attempting to reduce .clone() usage 2023-06-03 12:55:01 -04:00
Kevin David fc8adf2a5c Feature/optional MQTT discovery
Adds config options to enable MQTT Discovery as documented here: https://www.home-assistant.io/integrations/mqtt/#mqtt-discovery

As discussed in https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1561076262

Unfortinuately, the floodlight/spotlight doesn't show up in the `<AbilityInfo>` returned by the camera: https://github.com/QuantumEntangledAndy/neolink/pull/14#issuecomment-1563728970

Open to other suggestions on how to detect or enable these options.
2023-06-03 12:55:01 -04:00
Andrew King cf67a05dd1 Merge pull request #96 from kevin-david/docker_username
Allow DockerHub username to be specified via `DOCKER_USERNAME` var
2023-06-01 15:20:00 +01:00
Andrew King d961bf36f7 Merge pull request #92 from danielkaiser/feature-ptz-preset 2023-05-29 17:59:03 +01:00
Kevin David a59dafab00 Switch back to distinct DOCKER_PRUNE_TOKEN 2023-05-28 16:41:30 -04:00
Kevin David cf07304bae Allow docker username to be specified, only use one token 2023-05-27 17:04:08 -04:00
QuantumEntangledAndy 9524a1a9f7 Seperate set and assign presets. Also add queury messages to mqtt 2023-05-26 15:09:54 +07:00
QuantumEntangledAndy 4628946514 Use same amount model as in mqtt and add optional speed 2023-05-26 00:55:11 +07:00
QuantumEntangledAndy da3afe228e Use async sleep 2023-05-25 23:55:47 +07:00
Andrew b8dafbb92e Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-05-25 17:44:56 +01:00
Andrew King fdff244f15 Merge pull request #14 from kevin-david/flood_mqtt 2023-05-25 14:59:27 +01:00
Daniel Kaiser 27dc4c2bca Add control/preset command to mqtt 2023-05-24 19:12:24 +02:00
Daniel Kaiser aee14bb411 Add PTZ presets and PTZ command line 2023-05-24 15:19:46 +02:00
Kevin David 5f96b2e7f8 Fix XML deserialization of FloodlightStatusList
The children are `FloodlightStatus`, so that's what we should `yaserde(rename)` to
2023-05-24 08:25:47 -04:00
QuantumEntangledAndy f9975520ab Fmt 2023-05-24 12:33:38 +07:00
QuantumEntangledAndy 864f58d20e Async handle_msg closures 2023-05-24 12:26:27 +07:00
QuantumEntangledAndy f42191973a Seperate quality stream pausing 2023-05-22 13:32:15 +07:00
Kevin David d90f0b1002 Improve MQTT error message 2023-05-19 23:48:10 -04:00
QuantumEntangledAndy 4afa457eff Rework pause to be per stream 2023-05-20 10:31:38 +07:00
QuantumEntangledAndy e7a244a1ab Add protobuf-compiler for clippy checks 2023-05-19 23:29:54 +07:00
QuantumEntangledAndy b978809a59 fmt 2023-05-19 23:20:18 +07:00
QuantumEntangledAndy 6b35db8fbe Cleanup of pushnoti README 2023-05-19 23:16:48 +07:00
QuantumEntangledAndy 384a0271bd v0.5.12 2023-05-19 22:58:45 +07:00
Andrew King 134ef9df0f Merge pull request #86 from QuantumEntangledAndy/feature/cellular
Feature/cellular
2023-05-19 22:55:02 +07:00
QuantumEntangledAndy c3f3ecdb83 Use the right method for fcm 2023-05-19 16:18:30 +07:00
QuantumEntangledAndy 1824e061f4 fmt 2023-05-19 13:17:04 +07:00
QuantumEntangledAndy be10aaeed5 Add floodlight status and keep alive pings 2023-05-19 13:15:31 +07:00
Andrew ff9e100ac2 Merge remote-tracking branch 'QuantumEntangledAndy/master' into flood_mqtt 2023-05-19 11:26:14 +07:00
QuantumEntangledAndy 9133f20e64 Seeking withoffset again 2023-05-19 10:37:40 +07:00
QuantumEntangledAndy 2b0a0edf77 Add the cellular discovery option 2023-05-19 10:30:38 +07:00
QuantumEntangledAndy 5e22a019e5 Rework discovery to allow cellular 2023-05-19 10:19:38 +07:00
QuantumEntangledAndy 2a8c713ee0 Readme updates 2023-05-19 09:34:49 +07:00
QuantumEntangledAndy f99df6e5e7 Add fcm test project 2023-05-19 09:18:01 +07:00
Andrew King 4a95740f96 Merge pull request #83 from PrplHaz4/patch-1 2023-05-18 20:12:48 +07:00
PrplHaz4 5eee60ee17 change log level from trace to debug 2023-05-18 08:37:23 -04:00
QuantumEntangledAndy e09d9d30dc More messages and further details on APNS 2023-05-18 14:43:56 +07:00
QuantumEntangledAndy c2f0b5b2d9 Add snap to messages 2023-05-18 14:17:33 +07:00
QuantumEntangledAndy 472eda9f06 RE push noti message 2023-05-18 08:38:30 +07:00
QuantumEntangledAndy c831d07573 v0.5.11 2023-05-18 08:32:23 +07:00
QuantumEntangledAndy 90b51b7e46 v0.5.11 2023-05-18 08:26:26 +07:00
Andrew King cdc8a9cb8e Merge pull request #82 from QuantumEntangledAndy/fix/pause_buffers
Fix pause buffers
2023-05-18 08:06:25 +07:00
QuantumEntangledAndy 790eb655a3 Put a message about max bitrate in the log when buffer is exhausted 2023-05-17 15:01:58 +07:00
QuantumEntangledAndy 99584ce813 Slightly increase the MTU 2023-05-17 11:16:18 +07:00
QuantumEntangledAndy c2a5798905 Change buffer over and undeful size 2023-05-16 18:31:09 +07:00
QuantumEntangledAndy 951a822973 Make buffer size configurable 2023-05-16 18:25:39 +07:00
QuantumEntangledAndy f5ac615b3c Renable time smoothing 2023-05-16 15:52:32 +07:00
QuantumEntangledAndy 3b677f9156 Refilling debug print correction 2023-05-16 15:45:07 +07:00
QuantumEntangledAndy 9473a8ad5d Correct buffer sorting, and reinit 2023-05-16 15:21:00 +07:00
QuantumEntangledAndy 56ef79ff45 Yet another alteration to seek 2023-05-16 12:42:30 +07:00
QuantumEntangledAndy d61e48ce79 Full grouping for frames of the same time 2023-05-16 12:25:49 +07:00
QuantumEntangledAndy 86f15f9eb1 Handle jump to live even for a one frame buffer 2023-05-16 11:37:20 +07:00
QuantumEntangledAndy 84e10530a5 Minimum stamp buffer size 2023-05-16 11:28:58 +07:00
QuantumEntangledAndy 2f74a720f5 Sign correction 2023-05-16 09:00:24 +07:00
QuantumEntangledAndy 511e50fe52 Update the start time on restamp too 2023-05-16 08:58:23 +07:00
QuantumEntangledAndy 78da59fc71 Change the way buffer time stamps are handled 2023-05-16 08:36:47 +07:00
QuantumEntangledAndy 36f70c3222 No smooth and extra debug 2023-05-15 19:44:07 +07:00
PrplHaz4 8f1c86a8c8 Add docker run instructions to README
Add docker run instructions to README, use host networking to avoid explicitly mapping a bunch of ports, and trace logging to document for any users that need to troubleshoot.
2023-05-15 08:32:28 -04:00
QuantumEntangledAndy 279c1c5bf1 Do target live calculation for abstract buffer 2023-05-15 18:32:25 +07:00
QuantumEntangledAndy f5ba6e244f Imporve handoff between preprocess and live 2023-05-15 10:05:31 +07:00
Andrew 6a980b47ae Reduce target buffer size 2023-05-15 09:45:11 +07:00
QuantumEntangledAndy 3a783bf50c Use only unique timestamps to calculate live 2023-05-15 09:32:35 +07:00
Andrew 9dabb43a9c Address pausing of buffers 2023-05-15 08:52:55 +07:00
QuantumEntangledAndy b9fd2f75ff v0.5.10 2023-05-14 12:33:57 +07:00
Andrew 61f65ed42a Merge remote-tracking branch 'origin/master' 2023-05-14 12:31:34 +07:00
Andrew King 634bff08af Merge pull request #72 from AdrianosBates/fix/ptz-stop
Fix/ptz stop
2023-05-14 12:23:39 +07:00
QuantumEntangledAndy 2d1ccf518a Clippy fixes 2023-05-14 10:45:34 +07:00
QuantumEntangledAndy d9600d0607 Filter out OK/FAIL replies 2023-05-14 10:40:46 +07:00
QuantumEntangledAndy 72cf358b0c Make mqtt messgae handler cleaner 2023-05-14 08:46:22 +07:00
QuantumEntangledAndy a819248556 Rework MQTT to allow async message handelling 2023-05-13 20:03:08 +07:00
QuantumEntangledAndy 6e334392da Merge branch 'master' of https://github.com/QuantumEntangledAndy/neolink into fix/ptz-stop 2023-05-13 16:52:40 +07:00
QuantumEntangledAndy eed2aeb1be v0.5.9 2023-05-12 12:13:27 +07:00
QuantumEntangledAndy 84163dcd2a v0.5.9 2023-05-12 09:26:31 +07:00
Andrew King 30573c7ba3 Merge pull request #68 from QuantumEntangledAndy/fix/vlc_seek
Improve VLC support

Should also improve frigate
2023-05-12 09:21:51 +07:00
QuantumEntangledAndy c3c58b3f67 Put back in smoothing and bump up the buffer size 2023-05-11 13:28:21 +07:00
QuantumEntangledAndy bc3f9b65a0 Add messages about buffer size 2023-05-10 20:43:53 +07:00
QuantumEntangledAndy 5513fce18f Disable time smoothing 2023-05-10 20:37:06 +07:00
QuantumEntangledAndy df3462875b Add timeout to p2p address resolution 2023-05-10 13:54:39 +07:00
QuantumEntangledAndy e2d5eb061f Add time out to map discovery 2023-05-10 13:25:51 +07:00
QuantumEntangledAndy 2921ede080 Reinit client buffers when master is restamped 2023-05-10 13:11:56 +07:00
QuantumEntangledAndy 004405e868 Correct delta on buffer schedule 2023-05-10 11:47:18 +07:00
QuantumEntangledAndy d411e9c25b Restamp over clear buffer during reconnect 2023-05-10 11:38:13 +07:00
QuantumEntangledAndy e712e3b47c Dedicated thread for the BC connection layer 2023-05-10 10:26:53 +07:00
QuantumEntangledAndy b09a590fb6 Cleanup logs 2023-05-10 09:39:59 +07:00
QuantumEntangledAndy f9407d8d8d Seek within buffer, not RANDOM_ACCESS 2023-05-10 09:31:13 +07:00
QuantumEntangledAndy eec01faa0a 250ms Latency 2023-05-09 18:25:07 +07:00
QuantumEntangledAndy d2daad0bf2 Just seek to live 2023-05-09 15:47:06 +07:00
QuantumEntangledAndy 55d357ecf8 Async sender code 2023-05-09 15:22:51 +07:00
QuantumEntangledAndy 15f9993c12 Manual seeking 2023-05-09 14:35:01 +07:00
QuantumEntangledAndy 52840348bf Send frames async 2023-05-09 11:23:23 +07:00
QuantumEntangledAndy d5cb12dc3c Improve clearing of 'Stream not ready' streams 2023-05-09 08:56:58 +07:00
QuantumEntangledAndy 9f1cda3c60 Group audio playback
Also use buffer lists
2023-05-08 19:21:00 +07:00
QuantumEntangledAndy 5e81d6a369 Update for pausing 2023-05-08 15:24:00 +07:00
QuantumEntangledAndy 7a50d3e42f Try another method 2023-05-08 13:59:02 +07:00
QuantumEntangledAndy 587c8bf334 Fix client pause 2023-05-07 15:57:13 +07:00
QuantumEntangledAndy dbf21d9c90 Change how frames are popped from buffer. Change how target time is updated 2023-05-07 09:29:47 +07:00
George Hilliard 8c6776607b Autobuild every couple of months if no other activity
Builds expire after 90 days
2023-05-06 07:39:51 -05:00
QuantumEntangledAndy 60e4b994ab Some changes to how we poll buffer processing 2023-05-05 20:16:01 +07:00
QuantumEntangledAndy 8c061efc1e Added drifting start_time 2023-05-05 11:01:20 +07:00
QuantumEntangledAndy 262d2b2ed4 Lockless subscription 2023-05-05 08:09:35 +07:00
QuantumEntangledAndy b07aa2ddfe Jump to live if more than 15s difference 2023-05-04 09:10:52 +07:00
QuantumEntangledAndy 386fec4220 Allow decode Bc frame over packet boundary 2023-05-03 20:26:13 +07:00
QuantumEntangledAndy e2602b5c17 Add tokio console to the config 2023-05-03 18:17:05 +07:00
QuantumEntangledAndy 26d894222a Build this way 2023-05-03 16:00:25 +07:00
QuantumEntangledAndy c20b944411 Sh it's sh 2023-05-03 15:31:28 +07:00
QuantumEntangledAndy f60de36bae Source /.cargo/env 2023-05-03 15:27:57 +07:00
QuantumEntangledAndy 929dac374b Nightly 2023-05-03 15:21:49 +07:00
QuantumEntangledAndy fd3282efe2 Add rustflag directly 2023-05-03 15:15:37 +07:00
QuantumEntangledAndy 359597131e Tokio console 2023-05-03 14:43:26 +07:00
QuantumEntangledAndy 0b922aeeb5 Always timed polls 2023-05-03 13:29:47 +07:00
QuantumEntangledAndy 29b6ff8c24 Timed polling 2023-05-03 13:19:59 +07:00
QuantumEntangledAndy ae3f9365b1 Skip printing of pkg_config join tags in array 2023-05-03 11:51:05 +07:00
QuantumEntangledAndy c666a4c3bd Add skip build to style checks too 2023-05-03 11:30:20 +07:00
QuantumEntangledAndy e4bcf9bd23 Fixes to docker build tagging 2023-05-03 11:27:36 +07:00
QuantumEntangledAndy 8a0d4a8f03 Changes to github action to reduce reruns 2023-05-03 11:24:34 +07:00
QuantumEntangledAndy a6e11af084 Use mt tokio 2023-05-03 10:37:18 +07:00
QuantumEntangledAndy 2403ee2b27 Close client on buffers prepared
Don't prepare buffers more than once across restarts

Use time limited queues

Don't cache dummy sender
2023-05-03 10:15:35 +07:00
QuantumEntangledAndy 9d57b2dafd Change how queues work 2023-05-03 08:46:27 +07:00
QuantumEntangledAndy 86f6ea55ec Without jump to lives 2023-05-03 08:15:40 +07:00
QuantumEntangledAndy 2ff1ee474e Handle error in appsrc push during init 2023-05-02 15:49:10 +07:00
QuantumEntangledAndy ccd5778f57 Display stream not ready if connecing before buffers prepared 2023-05-02 15:25:40 +07:00
QuantumEntangledAndy af9f181ff5 Increase minimum buffer amount 2023-05-02 15:19:01 +07:00
QuantumEntangledAndy d50fa87baf Rework the type of the time 2023-05-02 14:40:56 +07:00
QuantumEntangledAndy f2b609f12c Allow negative start times 2023-05-02 13:53:20 +07:00
QuantumEntangledAndy c53b0955f8 Bullseye docker 2023-05-02 13:15:22 +07:00
QuantumEntangledAndy dc6860378d Drop whole session 2023-05-02 10:57:41 +07:00
QuantumEntangledAndy 84bf5ef05c Fix the jump to live process 2023-05-02 10:20:24 +07:00
QuantumEntangledAndy 31ac6e4707 Reconnect streams when media type changes 2023-05-01 18:37:57 +07:00
QuantumEntangledAndy 048af92808 Saturating subs all around 2023-05-01 15:40:14 +07:00
QuantumEntangledAndy 4a08b8148b Use the bin (faster) method for sending the prebuffer 2023-05-01 14:19:32 +07:00
QuantumEntangledAndy cce519de6d Use queue2 2023-05-01 12:34:31 +07:00
QuantumEntangledAndy d24a4d12e2 More adjustments to how the pre-buffer is sent 2023-05-01 12:26:00 +07:00
QuantumEntangledAndy 8cea9e79e5 Use time to trim the buffer 2023-04-30 13:56:03 +07:00
QuantumEntangledAndy a222a2d053 New live buffer method 2023-04-30 09:31:03 +07:00
QuantumEntangledAndy 093a1b1af9 Close brace 2023-04-28 21:15:22 +07:00
QuantumEntangledAndy c30e6293f6 Rework how buffers are sent to always be 2023-04-28 19:59:06 +07:00
Adrian Bates 03a7e1473a Fixed mistake in new error message 2023-04-25 16:14:55 -04:00
Adrian Bates 5ccdc27d37 In mod.rs:
Removed the ability to send "stop" PTZ command with MQTT
	Changed the signature of PTZ MQTT commands to (direction amount seconds), where seconds is currently checked and limited to the range 0.0 - 10.0
In event_cam.rs:
	stop has been removed from event_cam.Direction, and directions now take an additional f32 seconds parameter
	in Message::PTZ if the intial send_ptz is successful, will sleep for designated seconds and then issue a stop command
2023-04-25 15:49:08 -04:00
QuantumEntangledAndy 107902ef3a Complete rework of buffer time 2023-04-25 14:28:35 +07:00
Adrian Bates 29b47aa44e Changed Unrecognized PTZ Direction error to include unrecognized command 2023-04-22 11:41:45 -04:00
Adrian Bates 427046239c Added stop command to PTZ 2023-04-22 11:13:59 -04:00
Andrew c4c35d1bde Implement fake seek for VLC 2023-04-20 15:40:58 +07:00
Andrew King 81a573ba6d Merge pull request #66 from QuantumEntangledAndy/fix/mqtt_asyncio
Update mqtt to use tokio
2023-04-20 15:39:40 +07:00
Andrew 7d771fc94b Log current discovery method 2023-04-20 15:24:31 +07:00
QuantumEntangledAndy 4f50a962e6 Pass fail/OK messages back to mqtt 2023-04-20 07:32:30 +07:00
QuantumEntangledAndy 7468d77178 Pass error up from mqtt, add more detailed error messages 2023-04-20 07:13:54 +07:00
Andrew 19a468ac2e Squash more blocking in async on mqttt 2023-04-19 11:51:50 +07:00
Andrew a46192d47c Do discovery sequentially 2023-04-19 11:47:30 +07:00
QuantumEntangledAndy 45fec7cfc2 Update mqtt to use asyncio 2023-04-18 20:27:53 +07:00
QuantumEntangledAndy 3f4bc510a7 Don't prune version tagged dockerimages 2023-04-18 11:05:16 +07:00
QuantumEntangledAndy 42ff221b07 v0.5.8 2023-04-18 09:54:20 +07:00
QuantumEntangledAndy 9a153cda80 v0.5.8 2023-04-18 09:29:10 +07:00
QuantumEntangledAndy 1f37e699b2 v0.5.8 2023-04-18 08:55:15 +07:00
Andrew King 45789d44d6 Merge pull request #63 from QuantumEntangledAndy/fix/bytes_remaining
Fix/bytes remaining and blocking
2023-04-18 08:44:28 +07:00
QuantumEntangledAndy c1445ea1e1 Remove debug print 2023-04-18 08:17:52 +07:00
QuantumEntangledAndy 74274ae30e Add restarts to the send thread 2023-04-18 08:15:31 +07:00
QuantumEntangledAndy 233a73e1dc Backoff on retries 2023-04-17 19:49:50 +07:00
QuantumEntangledAndy f8b48544f8 Switch too non-locking, fail skipping, signal reading 2023-04-17 19:45:54 +07:00
QuantumEntangledAndy 5e9783fed3 Dockerprune script token 2023-04-16 16:23:42 +07:00
QuantumEntangledAndy 78186a2725 Debug dockerprune 2023-04-16 16:13:00 +07:00
QuantumEntangledAndy 824206faaa Reducing blocking on gstraemer pushes 2023-04-16 16:08:44 +07:00
Andrew f61fef9b32 Allow decode across EOF 2023-04-16 16:08:44 +07:00
Andrew 37049f7ca4 Fix bytes remaining on stream 2023-04-16 16:08:44 +07:00
Andrew King 8db2fd4a91 Merge pull request #60 from QuantumEntangledAndy/refractor/dep_update01
Updates of all packages
2023-04-15 14:26:36 +07:00
Andrew 3a2db7aaa8 Clippy 2023-04-15 09:44:05 +07:00
QuantumEntangledAndy 78375b220d Updates of all packages 2023-04-15 08:05:58 +07:00
QuantumEntangledAndy 1ea8f182fa Add dockerprune script 2023-04-14 10:18:16 +07:00
QuantumEntangledAndy 8380227f8f Added needed packages to docker 2023-04-14 09:20:21 +07:00
QuantumEntangledAndy a424fa55c0 0.5.7 2023-04-13 15:02:11 +07:00
Andrew King cd582b90c8 Merge pull request #57 from QuantumEntangledAndy/refractor/gts_rework
Refractor/gts rework
2023-04-13 14:59:39 +07:00
QuantumEntangledAndy 2348c1e442 README updates 2023-04-13 14:51:12 +07:00
QuantumEntangledAndy 7ae5e14c2d README update 2023-04-13 13:35:05 +07:00
QuantumEntangledAndy 7faddb3b50 Add plugin base to docker 2023-04-12 15:57:44 +07:00
QuantumEntangledAndy 50126a3833 Remove do retransmission 2023-04-11 19:50:36 +07:00
QuantumEntangledAndy 0a9aa284ae Dependency cleanup 2023-04-11 19:28:51 +07:00
QuantumEntangledAndy 7f8cf76a8c Removed unused deps 2023-04-11 16:47:52 +07:00
QuantumEntangledAndy cdec5b0958 Fmt 2023-04-11 16:12:36 +07:00
QuantumEntangledAndy 4235d9dc85 Fix motion based pausing 2023-04-11 16:08:13 +07:00
QuantumEntangledAndy 27e0ddc888 Add new client pause method 2023-04-10 21:15:26 +07:00
QuantumEntangledAndy 78f0a87528 Fix PTS 2023-04-10 13:31:25 +07:00
QuantumEntangledAndy 31723e9469 Don't forget to login 2023-04-10 06:49:39 +07:00
QuantumEntangledAndy 2ae25a1e58 Refractor pause state model 2023-04-09 16:42:37 +07:00
QuantumEntangledAndy 8a11f6e867 Add Adpcm audio 2023-04-06 10:50:55 +07:00
QuantumEntangledAndy 8c6f5be1bd WIP changes 2023-04-05 18:19:29 +07:00
QuantumEntangledAndy b728ba14c7 Added AAC 2023-04-05 18:19:29 +07:00
QuantumEntangledAndy ceff4c2495 Video streams using new method 2023-04-05 18:19:29 +07:00
QuantumEntangledAndy 8b825cc5fa Implement own gstremer media and server 2023-04-05 18:19:13 +07:00
Andrew King b45aee252f Merge pull request #46 from QuantumEntangledAndy/feature/UidAddr
Permit connect with UID at an Addr
2023-04-05 18:09:58 +07:00
QuantumEntangledAndy 0b9a7c17e9 Readme updates 2023-04-05 17:48:48 +07:00
QuantumEntangledAndy 2291f778da fmt 2023-04-05 17:09:02 +07:00
QuantumEntangledAndy 6fafb67c45 Fixes to port logic 2023-04-05 17:04:33 +07:00
QuantumEntangledAndy 1d3336ece5 Fix merge issues 2023-04-05 17:01:40 +07:00
QuantumEntangledAndy 1892278633 Revert "Fix to port logic"
This reverts commit afe6346e74.
2023-04-05 16:55:31 +07:00
QuantumEntangledAndy afe6346e74 Fix to port logic 2023-04-05 16:21:48 +07:00
QuantumEntangledAndy c8d08d22b2 Timeout on tcp 2023-04-05 16:18:48 +07:00
QuantumEntangledAndy ad26b55730 fmt 2023-04-05 16:18:48 +07:00
QuantumEntangledAndy 6c87d81a81 Do discovery of TCP if possible and order UDP disc
This allows either UDP or TCP if both an address
and a UID are given. They are resolved with this
preference: TCP, Local, Remote, Map, Relay
2023-04-05 16:18:48 +07:00
QuantumEntangledAndy 3771098c2f Change config validation 2023-04-05 16:16:06 +07:00
Andrew 94805c881e Permit connect with UID at an Addr 2023-04-05 16:16:06 +07:00
QuantumEntangledAndy 5734321633 v0.5.6 2023-04-05 16:14:55 +07:00
Andrew King fb4f929109 Merge pull request #53 from QuantumEntangledAndy/feature/pir
Rework PIR data and fetch status
2023-04-05 16:12:36 +07:00
QuantumEntangledAndy 16022c8b28 Cliipy 2023-04-05 15:41:31 +07:00
QuantumEntangledAndy 17f3695ca7 Slight pirstate refractor 2023-04-05 15:30:54 +07:00
QuantumEntangledAndy 000f756420 Fmt 2023-04-05 15:27:32 +07:00
QuantumEntangledAndy 6a1415913b Add retry if PIR state returns error code 400 2023-04-05 11:48:43 +07:00
QuantumEntangledAndy 3014be9008 Add abilityinfo.rs 2023-04-04 18:49:04 +07:00
QuantumEntangledAndy 618aafef2c Added an ability support check to functions 2023-04-04 16:45:16 +07:00
Andrew ca5de6445d Set rfId instead of channelId
Missing `:`

Missing `None`
2023-04-03 17:15:00 +07:00
QuantumEntangledAndy 82a39a2fa1 Add PIR to mqtt 2023-04-03 15:06:05 +07:00
QuantumEntangledAndy 77be9483b0 Rework PIR data and fetch status 2023-04-02 18:39:36 +07:00
QuantumEntangledAndy 4fcaf4d538 0.5.5 2023-03-03 08:19:04 +07:00
Andrew King 70e62170a9 Merge pull request #42 from QuantumEntangledAndy/battery
Battery message and requests
2023-03-03 08:11:33 +07:00
QuantumEntangledAndy 92447b63b8 Add configurable battery printing 2023-03-02 15:55:15 +07:00
QuantumEntangledAndy 1bcf1cfe85 Print battery status to stdout 2023-03-02 14:45:29 +07:00
QuantumEntangledAndy aef898c471 Negative temperatures and such 2023-03-02 14:44:23 +07:00
QuantumEntangledAndy 0bbd334a78 Updated readme 2023-03-01 14:28:02 +07:00
QuantumEntangledAndy 80e705bd60 Add battery status to the MQTT 2023-03-01 14:28:02 +07:00
QuantumEntangledAndy 19c2031691 Added default-run 2023-03-01 14:28:02 +07:00
QuantumEntangledAndy 52c4515e62 Revert "Added default-run"
This reverts commit c54f62d79c56f30c0b18d290171c7b8864774af1.
2023-03-01 14:28:02 +07:00
QuantumEntangledAndy 8d3c0af7af Added default-run 2023-03-01 14:28:02 +07:00
QuantumEntangledAndy f4d7bebbf1 Added battery info commands 2023-03-01 14:28:02 +07:00
Andrew King e04c2a10f0 Merge pull request #44 from thirtythreeforty/master
Add some copyright notices at the entry points of programs
2023-03-01 14:14:26 +07:00
George Hilliard 1dc25da8f2 Add some copyright notices at the entry points of programs
The existing readme is clear about the license applying to the whole
project, however to clarify a little further, and to make sure the
notice conveys with copy/pasted portions (especially the dissector), add
a notice to the head of each executable.  Also, make the neolink help
print the license and source code link.

See #341.
2023-03-01 14:11:25 +07:00
QuantumEntangledAndy df3b36954c Added docuementation for discovery 2023-03-01 13:58:35 +07:00
QuantumEntangledAndy d12d17c052 Add an AES decoder tool 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy c0d0f396b0 Comment and discussion update 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy 7fccda4aa7 Configurable strict BCMedia 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy 17846c7bfc Some debug 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy 8adae665fb Add debug for discovery. Slow resend interval 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy a5a3cf9715 Restructure discovery 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy ac0703dbfd Add simple timeouts 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy fa155df974 Pass errors from deser down to the recievers 2023-02-28 12:41:04 +07:00
QuantumEntangledAndy e7b9aee122 Minor log level changes 2023-02-27 11:50:58 +07:00
QuantumEntangledAndy 4f2a010e33 0.5.3rc 2023-02-27 09:21:09 +07:00
QuantumEntangledAndy f1c35a1809 Prepare for merge 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy a2bec57251 fmt 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 8ead7ad2fc Keep sending data until jpeg is made 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy bd2a3b4ebc Add the file too 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy c37cedf183 Added the unhandler 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 1fe1ce5046 Setup a mechanism to respond to camera message, and use it for keepalive 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 7ebe73b226 Added encryption configuration and handle empty ack packets 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 7dae880bb2 Rework rensend wait logic in discovery 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 438d2a71e1 Retry send super bump 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 0f76622b17 Fix merge issues 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 9945b02fd9 Macos store file cleanup 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy f514733706 Log cleanup 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy bd9da2620b Added still image command 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy 6d0d290644 Swap invalid chatacter in dockerhub step 2023-02-27 09:14:07 +07:00
QuantumEntangledAndy a3aa3c4556 Handle aes encrypt during deser too 2023-02-24 07:25:37 +07:00
QuantumEntangledAndy f253100ea7 Rmove DS_Store 2023-02-24 07:25:37 +07:00
QuantumEntangledAndy ad5d09045c Fix issue with BcPayloadStream not waking for next poll 2023-02-23 21:01:27 +07:00
George Hilliard 8bd560b04e Add some copyright notices at the entry points of programs
The existing readme is clear about the license applying to the whole
project, however to clarify a little further, and to make sure the
notice conveys with copy/pasted portions (especially the dissector), add
a notice to the head of each executable.  Also, make the neolink help
print the license and source code link.

See #341.
2023-02-22 08:34:59 -06:00
QuantumEntangledAndy bf9cfc7178 Added missing ) 2023-02-22 09:59:37 +07:00
QuantumEntangledAndy a8ee89b6c0 v0.5.2rc 2023-02-22 09:58:01 +07:00
QuantumEntangledAndy e46c00e45a Added rc to build scripts 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy a064fa7d3e Fmt 2023-02-22 09:55:28 +07:00
QEAndy 575da98dc9 Ensure pkg-config on macos 2023-02-22 09:55:28 +07:00
QEAndy ede2c58d46 whitespace 2023-02-22 09:55:28 +07:00
QEAndy f4456456f8 macos Debug 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy 612684339c Debug macbuild 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy 5785b0ffb3 Debug macbuild 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy b49ce87f32 Added config option to control discovery 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy 3949dca1af Relay connection works 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy c2212b9038 Log cleanup 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy e4016a8d97 More error tracing
Signed-off-by: QuantumEntangledAndy <sheepchaan@gmail.com>
2023-02-22 09:55:28 +07:00
QuantumEntangledAndy c8be843ebc More changes to run in tokio 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy 25bd29f2a7 Work on remote/relay connections
Signed-off-by: QuantumEntangledAndy <sheepchaan@gmail.com>
2023-02-22 09:55:28 +07:00
QuantumEntangledAndy 52a4c5a120 Core Async connections 2023-02-22 09:55:28 +07:00
QuantumEntangledAndy c52ae2b1c0 Start of async TCP 2023-02-22 09:55:28 +07:00
Kevin David 355cd4846a Remove incorrect code for now 2023-01-25 22:52:45 -05:00
Kevin David 6be7ac2d14 Remove .vscode, improve logging 2023-01-24 23:46:40 -05:00
Kevin David 8cbaf06cde Satisify rustfmt 2023-01-24 23:14:11 -05:00
Kevin David 1f8296dd01 WIP: Add support for floodlight control over MQTT 2023-01-24 22:38:00 -05:00
QuantumEntangledAndy 2e6f9c7190 Use verbose error on all deser 2023-01-21 14:57:30 +07:00
QuantumEntangledAndy ec88f5c312 Bump the version number 2023-01-19 15:34:06 +07:00
QuantumEntangledAndy 44675f25b4 build.yml fixes 2023-01-19 15:01:22 +07:00
QuantumEntangledAndy eaded82874 Add lower case factory paths 2023-01-19 14:35:31 +07:00
QuantumEntangledAndy c293bf7790 Don't push to docker on tagged 2023-01-09 17:47:15 +07:00
QuantumEntangledAndy 766139f2cd Add docker into README 2023-01-09 15:55:26 +07:00
QuantumEntangledAndy 3db62214ee Merge branch 'master' of github.com:thirtythreeforty/neolink 2023-01-09 15:51:08 +07:00
QuantumEntangledAndy 916f52f56a Typos and formatting 2023-01-09 15:49:21 +07:00
QuantumEntangledAndy 3a1793f43f Release 0.5.0 2023-01-09 15:43:50 +07:00
QuantumEntangledAndy e905d47b8e Remove prune for now 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 7e9474050e Enable tag contition on realse 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 52eaf1a0fd Add a repository prune 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy babd654d88 Build amd64 in buster 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy e941744fbb In the run version please 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy f8e4333274 Add a version print in the build 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 9bdea03bd9 Use path context 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 391e3956b5 Extra debug prints 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy aead6ccbff Rework dockerfile to reduce uneeded builds if not compiling 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy e5583e697a Update target platform 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy e045aaf876 Update windows platform_cfg 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy d8147b1fdc Check env variables 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 7508a956f9 Use add content over redirection in powershell 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 0bc9f61d2f Some windows prints and checks 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 0ab6bfa1c3 Only one colon 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy e2ced4d76e Try to set windows gstreamer drive via the SYSTEMDRIVE variable 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 3e6c14f7cb Make docker pull prebuilts for multiple archs 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 5dbf61620d Remember to install clippy in the toolchain 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 29d2218ff8 * the chmod 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 8dd1c27784 Add rustup target 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 9d40b8e315 Try to fix when windows installs to D 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 0b453b0e0d Install rustup in the container 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy e122ff2c05 Remove other action-rs 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 5f25f99f91 Cargo-rs is unmaintained swapping for raw cargo 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 17aa3accce Add a chmod +x to the neolink binary 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy 5bd5703885 Upgrade deperataed github actions 2023-01-09 15:02:57 +07:00
QuantumEntangledAndy cd1407bcbf Test release 2023-01-09 15:02:57 +07:00
George Hilliard 7087b348c4 Merge branch 'motion' 2023-01-08 21:33:57 -06:00
QuantumEntangledAndy 40f198a516 Check with aptitude 2022-12-28 14:59:20 +07:00
QuantumEntangledAndy baef43ce8d Bump github runner 2022-12-28 14:59:20 +07:00
QuantumEntangledAndy fbf33e6393 Try to work out where gstreamer is 2022-12-28 14:13:33 +07:00
QuantumEntangledAndy 182ec7b1c1 Debian based image 2022-12-28 14:13:33 +07:00
QuantumEntangledAndy 6b5380e56e Merge branch 'master' of github.com:QuantumEntangledAndy/neolink 2022-12-22 09:17:14 +07:00
QuantumEntangledAndy 0898b40f3e Merge branch 'master' of github.com:thirtythreeforty/neolink 2022-12-22 09:16:48 +07:00
QuantumEntangledAndy 600a864ffd Add battrylist xml to messages 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 627a10f0ac Add mqtt messages to the docs 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 90e21e9916 Add example configurations in the doc 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 10eecf416c Added PTZ controls 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 9f3c482f51 Added optional amount to ptz controls 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 9a524afa84 Start work on new commands 2022-12-22 09:16:15 +07:00
QuantumEntangledAndy 2d7b3e765e Change how we check for missing mqtt settings 2022-12-22 09:16:15 +07:00
George Hilliard f73527b933 Fix CI build links
GitHub changed the default runner, and the builds didn't break but the
release names did.  We should stabilize the artifact names.  For now,
just get the downloads flowing again.
2022-12-21 11:01:21 -06:00
QuantumEntangledAndy 1c9be03fd3 Move H265 and H264 parsing and rtp into required 2022-12-16 15:47:44 +07:00
QuantumEntangledAndy f710f5385b Better prompt on what needs to be done 2022-12-16 15:47:44 +07:00
QuantumEntangledAndy cc2c6ffc3b Add check for gstreamer plugins 2022-12-16 15:47:44 +07:00
QuantumEntangledAndy 06edd88696 Update gstreamer path for windows 2022-12-14 09:59:57 +07:00
QuantumEntangledAndy 124771b143 Build script fixes 2022-12-14 09:59:57 +07:00
QuantumEntangledAndy 6fac0097dd Major changes to streaming protocol 2022-12-14 09:59:57 +07:00
Kevin David 2a0c2a2b46 Floodlight: Start filling in messages.md
This isn't as complete as the other entries, but figured it'd be a good start.
2022-12-12 15:13:38 +07:00
Kevin David 000fa4e297 Try ubuntu-20.04 instead of 22 2022-12-12 15:13:38 +07:00
Kevin David db0cc39b4b Upgrade Actions build OSs to latest versions
Avoid all these depreciations: 
- https://github.com/actions/runner-images/issues/5583
- https://github.com/actions/runner-images/issues/6002
- Windows hasn't been announced yet but was moved to latest recently: https://github.com/actions/runner-images/issues/4856
2022-12-12 15:13:38 +07:00
Kevin David 063855f720 Satisfy Rustfmt requirements 2022-12-12 12:18:58 +07:00
Kevin David 9c0eed7a11 Move Clippy & Rust-fmt back to ubuntu-20.04
Get these working again, the issue causing their breakage on 22.04 can be diagnosed later.
2022-12-12 12:18:58 +07:00
Kevin David 12e145b5ea Remove launch.json 2022-12-11 13:07:23 +07:00
Kevin David c19bba9235 Improve MQTT documentation, example config
Also print an error message when the configuration isn't present but the `mqtt` subcommand is used. Without this, the program just exits without any messsages.
2022-12-11 13:07:23 +07:00
Andrew King 7ae61604b8 Merge pull request #327 from kevin-david/floodlight-messages
Floodlight: Start filling in `messages.md`
2022-12-05 10:00:27 +07:00
Andrew King 185419ce19 Merge pull request #323 from kevin-david/actions-os
Upgrade Actions build OSs to newer versions
2022-12-04 12:10:22 +07:00
Kevin David 19b60aa192 Floodlight: Start filling in messages.md
This isn't as complete as the other entries, but figured it'd be a good start.
2022-12-03 23:46:32 -05:00
QuantumEntangledAndy b80144492e Use newer config for mqtt 2022-11-28 19:35:10 +07:00
QuantumEntangledAndy edf89dc993 Merge and clippy fixes 2022-11-28 15:22:48 +07:00
Kevin David 6c33c0a3ae Try ubuntu-20.04 instead of 22 2022-11-27 23:33:19 -05:00
QuantumEntangledAndy 2114af085d Merge branch 'motion_stream' 2022-11-28 10:17:08 +07:00
QuantumEntangledAndy 6a2ed051d3 Merge branch 'mqtt_cmd' 2022-11-28 10:12:35 +07:00
QuantumEntangledAndy 561f978635 Merge branch 'motion'
Conflicts:
	crates/core/src/bc_protocol.rs
	crates/core/src/bc_protocol/stream.rs
	src/rtsp/mod.rs
2022-11-28 10:04:41 +07:00
Andrew 61eb3c3cb7 Merge branch 'single_login_streams' 2022-11-28 09:51:27 +07:00
Kevin David 5503bb8c10 Upgrade Actions build OSs to latest versions
Avoid all these depreciations: 
- https://github.com/actions/runner-images/issues/5583
- https://github.com/actions/runner-images/issues/6002
- Windows hasn't been announced yet but was moved to latest recently: https://github.com/actions/runner-images/issues/4856
2022-11-27 11:25:21 -05:00
George Hilliard b6dd2e6c0d Update Crossbeam 2022-09-16 11:16:05 -05:00
George Hilliard d75e416c96 Merge pull request #307 from thirtythreeforty/dep-update
Update dependencies
2022-09-15 18:21:33 -05:00
George Hilliard 0cc5bbdca9 Update dependencies 2022-09-15 17:34:59 -05:00
George Hilliard 5f4085f925 Fix incorrect comparison in dissector 2022-09-15 17:30:24 -05:00
George Hilliard 58e74fc3ee Add workflow_dispatch trigger for rerunning build
Artifacts expire on GitHub, so make it so we can rebuild them if needed.
2022-09-15 17:26:57 -05:00
QuantumEntangledAndy a75e12deca Clippy 2022-06-25 07:18:00 +07:00
QuantumEntangledAndy 1923bb8439 Explicit return type in closure 2022-06-25 07:12:08 +07:00
QuantumEntangledAndy 9ef394ff1d Abort all camera streams when one fails 2022-06-21 11:15:54 +07:00
QuantumEntangledAndy 4bfb9738cb Add stream stop message 2022-06-21 11:04:27 +07:00
QuantumEntangledAndy 83ea1b4edd Handle multiple streams on the same login 2022-06-21 10:55:51 +07:00
QuantumEntangledAndy 11a4ec921d Apply clippy lints 2022-06-21 10:29:06 +07:00
QuantumEntangledAndy f375d1b14d Handle non 200 response codes 2022-06-21 10:16:09 +07:00
QuantumEntangledAndy 87bd7d7287 Subscribe on message number 2022-06-21 10:08:49 +07:00
Andrew King cab43d0b09 Merge pull request #271 from jbremond/master 2022-06-13 11:52:28 +07:00
Joris Bremond a49a9d248f Format code 2022-06-12 14:24:37 +02:00
jbremond 63e9026191 Merge branch 'thirtythreeforty:master' into master 2022-06-12 14:23:10 +02:00
George Hilliard cf55029594 Merge pull request #282 from cincodenada/patch-1
Fix typo in help for talk command
2022-06-01 11:25:35 -05:00
Joel Bradshaw a594018762 Fix typo in help for talk command
It reference changing lights, rather than talking
2022-05-29 17:20:25 -07:00
Joris Bremond 2b56705172 Rename command from motion to pir 2022-05-14 14:23:01 +02:00
Joris Bremond 9f1bcd6f55 Add new motion command to set PIR sensor ON or OFF on battery powered camera
tested on reolink argus pro
2022-05-09 22:38:28 +02:00
Andrew King a8aa52aec7 Merge pull request #262 from sebix/add-510a 2022-03-27 18:00:59 +07:00
Andrew King a48cec8bcb Merge pull request #261 from sebix/fix-command-rtsp 2022-03-27 17:59:47 +07:00
Sebastian Wagner b22e3ca4cd docs: add 510A to supported cameras
I can confirm this camera works
2022-03-26 19:21:12 +01:00
Sebastian Wagner 04e44b3703 use new command 'neolink rtsp' in docs
on some places in the docs the old command 'neolink ...' was used.
that raises a warning, so refer to 'neolink rtsp' where apropriate
2022-03-26 19:15:58 +01:00
George Hilliard 23a4790b8d Merge pull request #247 from QuantumEntangledAndy/argus2_media
Newer iframe and pframe format
2022-03-01 21:38:54 -06:00
QuantumEntangledAndy 50b12bd124 Condense unknowns in iframe deser 2022-02-26 15:22:27 +07:00
George Hilliard 6747edf2c7 Merge pull request #233 from QuantumEntangledAndy/readme_update
Update readme to signify that debian can run the ubuntu x86_64
2022-02-24 14:01:22 -06:00
QuantumEntangledAndy a33897ec2c Bug and clippy lint squashing 2022-01-17 21:02:48 +07:00
QuantumEntangledAndy e436b27e63 Merge branch 'master' of github.com:thirtythreeforty/neolink into mqtt_cmd 2022-01-17 15:59:11 +07:00
George Hilliard 57c55e4121 Merge pull request #232 from QuantumEntangledAndy/keep_alive
Limit UDP keep alive
2021-12-12 14:40:25 -06:00
QuantumEntangledAndy ff76e4d2d7 Handle (optional) larger iframe headers in bcmedia 2021-12-03 16:57:16 +07:00
QuantumEntangledAndy 0f7598e9fc Merge branch 'master' of github.com:thirtythreeforty/neolink into motion_stream 2021-11-29 10:00:12 +07:00
QuantumEntangledAndy 624fd72939 Handle (optional) larger pframe headers in bcmedia
Including samples for test
2021-11-27 13:34:29 +07:00
QuantumEntangledAndy 0f40722e33 Use nom's verbose error in deser so we can add context 2021-11-27 13:32:09 +07:00
QuantumEntangledAndy 04a779ad14 Update readme to signify that debian can run the ubuntu x86_64 2021-11-25 10:59:03 +07:00
QuantumEntangledAndy 0145983198 Only enable keep alive during UDP connection 2021-11-25 10:36:56 +07:00
QuantumEntangledAndy 9021acf6d6 Stop sending keep alive messages if the camera responses with an error code to them 2021-11-24 17:12:02 +07:00
QuantumEntangledAndy 039edfc18e Limit sending keep alive packets 2021-11-02 13:40:43 +07:00
George Hilliard 324d14e3f2 Merge pull request #217 from thirtythreeforty/unify-structs
Re-unify single-camera command structs and code
2021-11-01 10:04:08 -05:00
George Hilliard 81b148f6cd Allow --config anywhere in CLI
Since clap doesn't support required + global, do our own insisting.
2021-10-29 01:24:02 -05:00
George Hilliard fdd50f9dc0 Refactor: move single-camera boilerplate to utils.rs 2021-10-29 01:09:09 -05:00
George Hilliard de39e7ed2a Re-unify configuration files
Unfortunately the grammar of the --config parameter is a bit of a
football right now; previously you were allowed to specify it anywhere
because there wasn't much in the way of a CLI, then when subcommands
were added it became required to specify it after the subcommand.

This change makes it so that it must be specified *before* the
subcommand.  Ideally it would just be required *somewhere* in the
command line but clap doesn't support "global" for required arguments
(and it is indeed required).

On the whole, I'm okay with the change - the net win of having a unified
config struct makes up for the ergonomics hit in my opinion, and it
unlocks some further refactoring I will do next.
2021-10-29 00:25:54 -05:00
Andrew King f10f9f9706 Merge pull request #199 from QuantumEntangledAndy/udp_proto 2021-10-29 09:41:23 +07:00
George Hilliard e194d8dc02 Merge pull request #198 from QuantumEntangledAndy/newer_enc
Disable Support for 03 Encryption
2021-10-27 10:56:00 -05:00
QuantumEntangledAndy 1c218b3587 Add some notes to the paused inputs 2021-10-08 10:46:19 +07:00
QuantumEntangledAndy dea3cbdb39 Make paused sources more customisable
Add audio paused source
2021-10-07 17:35:16 +07:00
QuantumEntangledAndy f1baaf7458 Add a still mode to paused streams 2021-10-07 15:16:42 +07:00
QuantumEntangledAndy 35c53fba90 Handle case of invalid active-pad 2021-10-06 16:08:10 +07:00
QuantumEntangledAndy 880c06bce9 Limit keep alive messages 2021-10-06 16:07:53 +07:00
QuantumEntangledAndy 8aa8345d87 Use input select for when stream is paused 2021-10-03 14:50:45 +07:00
QuantumEntangledAndy 80d28440b3 Remove unused error enum 2021-10-03 14:50:27 +07:00
QuantumEntangledAndy 7ec17c0cc5 Ensure camera accepts stream start command 2021-10-03 14:50:13 +07:00
QuantumEntangledAndy 982d7aa199 Using a sharable struct to track stream state 2021-10-02 14:35:00 +07:00
QuantumEntangledAndy 13690d723f Added a timeout to the motion based stream 2021-09-16 12:32:40 +07:00
QuantumEntangledAndy 62a694fbe4 Added basic motion based streaming 2021-09-16 11:45:09 +07:00
Andrew 02bd3fb606 Merge branch 'motion' into motion_stream 2021-09-14 14:04:17 +07:00
QuantumEntangledAndy f70a93ac56 Register the default ip address during the remote discovery 2021-09-08 17:02:19 +07:00
Andrew King a301944298 Apply suggestions from code review 2021-09-08 16:29:03 +07:00
QuantumEntangledAndy 79e012647a Read me updates 2021-09-08 15:19:42 +07:00
QuantumEntangledAndy ad0b79eec5 Add comments to the udp crc 2021-09-08 11:50:53 +07:00
QuantumEntangledAndy 9b23d8dbfc Add Uid as a seperate field into the config 2021-09-08 11:45:37 +07:00
QuantumEntangledAndy 8327a8348b Reference battery before udp in the readme 2021-09-06 20:31:55 +07:00
QuantumEntangledAndy 7d95663d90 Remove ping every 2021-09-06 20:30:52 +07:00
QuantumEntangledAndy 8b85042fe8 Removed unneeded code in the udp description 2021-09-06 20:26:01 +07:00
QuantumEntangledAndy 6c69acf0cb Use fastcrc crate for udp crc 2021-09-06 18:31:40 +07:00
Andrew KingandGeorge Hilliard f07d3ce318 Update sample_config.toml
Co-authored-by: George Hilliard <thirtythreeforty@gmail.com>
2021-09-04 09:23:34 +07:00
Andrew KingandGeorge Hilliard 162bdf85cc Update crates/core/src/bcudp/model.rs
Co-authored-by: George Hilliard <thirtythreeforty@gmail.com>
2021-09-04 09:20:07 +07:00
Andrew KingandGeorge Hilliard 3516af13ba Typo in BcUdp
Co-authored-by: George Hilliard <thirtythreeforty@gmail.com>
2021-09-04 09:19:39 +07:00
Andrew King cf54129b5c Merge pull request #206 from troyrollo/swann-channel-fix
Fix IFrame and PFrame identification for Swann DVRs
2021-09-03 12:52:57 +07:00
Troy Rollo 1094cdf713 Fix IFrame and PFrame identification for Swann DVRs 2021-09-01 22:30:14 +10:00
QuantumEntangledAndy 6848a793ca Clean up duplication merge issue 2021-08-31 21:28:40 +07:00
QuantumEntangledAndy 2dcb807b74 Update lock file 2021-08-31 20:56:50 +07:00
QuantumEntangledAndy a036c38b1b Merge branch 'master' of github.com:thirtythreeforty/neolink into udp_proto 2021-08-31 20:56:29 +07:00
QuantumEntangledAndy 7ab46e4273 Clean up files 2021-08-31 20:55:12 +07:00
QuantumEntangledAndy af1e52b850 Send UDP disconnect when UDP is finished 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 08d174a89d Fix to the more complex udp ack 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 0fbde1f5f9 Attempt to handle more complex udp acknoledgements 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 1d841714c1 Use correct body size on dissector 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy f2a6349203 Adjust how neoliknk handles udp resend 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy dae1fd3761 Update udp doc 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy b8cab8f68d Make dissector add the ports table upon detection for udp too 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 4b8d16d028 Add luacheck and make dissector compilent 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy ea4de74e8d Readded Bc<->Bc messages to dissector
Also added them to the heurestic check
2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 73204acf52 Added payload to udpack in dissector 2021-08-31 20:47:34 +07:00
QuantumEntangledAndy 33a227420a Udp Layer rewrite
Using a keep alive message

Restructed udp into modules

Using all interfaces broadcast address (ipv4)

Using remote discovery if local fails
2021-08-31 20:47:34 +07:00
QuantumEntangledAndy d432f7862d Update to the udp dissector 2021-08-31 20:47:23 +07:00
QuantumEntangledAndy 884b7c600d Handle camera hang up on udp 2021-08-31 20:47:23 +07:00
QuantumEntangledAndy 7a5def551d Use ports 2015 and 2018 for UDP discovery
Also add remote discovery but it is disabled for now
2021-08-31 20:47:23 +07:00
QuantumEntangledAndy 643953845a Doc update to include battery cameras and doc fixes 2021-08-31 20:46:47 +07:00
QuantumEntangledAndy 8aee6e8e8d Add a better timeout handling to UDP and Media 2021-08-31 20:46:47 +07:00
QuantumEntangledAndy c0e1a817d2 Removed redundant field in udp dissector 2021-08-31 20:46:47 +07:00
QuantumEntangledAndy b70a88451d Added UDP based connection 2021-08-31 20:46:47 +07:00
QuantumEntangledAndy c3f0a8c0c5 Serde UDP packets 2021-08-31 20:45:14 +07:00
QuantumEntangledAndy 996e55a3dd Add UDP dissector
Using udp code from jdillenkofer
2021-08-31 20:45:14 +07:00
QuantumEntangledAndy 999bb3315e Merge branch 'master' of github.com:thirtythreeforty/neolink into motion 2021-08-31 20:39:02 +07:00
QuantumEntangledAndy 1883e5362e Merge branch 'master' of github.com:thirtythreeforty/neolink into motion 2021-08-31 20:37:13 +07:00
QuantumEntangledAndy 10642b18d1 Remove uneeded mutablility in ledstate 2021-08-31 20:26:59 +07:00
QuantumEntangledAndy 5bf46f170e Make streams abortable like motion 2021-08-31 20:26:30 +07:00
QuantumEntangledAndy cdb86848da Add motion to neolink_core 2021-08-31 20:25:40 +07:00
QuantumEntangledAndy 58b1e3145a Fixes to documentation 2021-08-31 20:25:13 +07:00
QuantumEntangledAndy 09d16deb8c Disable support for unknown 03 encryption 2021-08-29 14:57:03 +07:00
QuantumEntangledAndy 5fc92f0bf4 Further notes in stream about the numbers 2021-08-27 10:55:50 -05:00
QuantumEntangledAndy d471072fc3 Add further notes and tests about B800 differences 2021-08-27 10:55:50 -05:00
QuantumEntangledAndy 6bf11047b8 Fixed typo in stream display name 2021-08-27 10:55:50 -05:00
QuantumEntangledAndy 38b40fd989 Use an enum for selecting stream quality 2021-08-27 10:55:50 -05:00
QuantumEntangledAndy ffd869091b Added externStream as an option 2021-08-27 10:55:50 -05:00
George Hilliard 1d824b80b0 Add missing code block close 2021-08-26 10:22:13 -05:00
George HilliardandAndrew King df8c02cd7b Reorganize readme (#201)
* Reorganize readme

Remove obsolete note about format, and move usage info to the top.

* Add the bash tag in the readme

Co-authored-by: Andrew King <sheepchaan@gmail.com>
2021-08-26 12:25:28 +07:00
George Hilliard 2e5cbdce6a Merge pull request #185 from QuantumEntangledAndy/refractor
Refractor code into workspaces and sub commands
2021-08-25 23:16:46 -05:00
Andrew King ebb6e874c8 Update BI doc image (#200) 2021-08-26 11:12:07 +07:00
Morphy99andAndrew King deece56488 Update README.md (#193)
* Update README.md

* Update README.md

Co-authored-by: Andrew King <sheepchaan@gmail.com>

* Update README.md

Co-authored-by: Andrew King <sheepchaan@gmail.com>

* More update to the readme

* Correct the indentation in the readme

Co-authored-by: Andrew King <sheepchaan@gmail.com>
2021-08-19 10:09:48 +07:00
Andrew King 5d2dad36c2 Merge pull request #169 from mpfl/master
Add example docker-compose config
2021-08-19 10:03:50 +07:00
QuantumEntangledAndy 8f1c3ece9d Use anyhow for application level error 2021-08-19 10:00:12 +07:00
QuantumEntangledAndy 0dd2eb744d Allow missing subcommand line specification 2021-08-18 16:37:43 +07:00
QuantumEntangledAndy b7b36bb525 Updates to protocol and message documentation 2021-08-18 00:17:22 -05:00
QuantumEntangledAndy 81e7fd8ecf Bug fix to event loop 2021-08-15 16:14:39 +07:00
QuantumEntangledAndy cc517588fe Make the loops in mqtt abort cleanly 2021-08-10 14:53:35 +07:00
QuantumEntangledAndy 20601b897e Added mqtt command 2021-08-10 11:25:01 +07:00
QuantumEntangledAndy a17a826f3c Added motion to core and made streams abortable via their callback 2021-08-10 11:24:43 +07:00
QuantumEntangledAndy cc4e0dadbd Merge branch 'talk' 2021-08-07 16:13:04 +07:00
QuantumEntangledAndy 561f893d2a Rust fmt 2021-08-07 16:05:58 +07:00
QuantumEntangledAndy a83ec69663 Add tests for deserialising adpcm, infov1, iframe and pframe BcMedia 2021-08-07 16:05:32 +07:00
Andrew King 5ca8eae8f4 Unify mic and file input source in talk
Update talk sources to use new input format
Quick fix to input sources
2021-08-07 16:05:32 +07:00
Robin Westerlundh 8b6cc4be7a Allow custom mic inputs 2021-08-06 15:24:27 +02:00
QuantumEntangledAndy 9d0e6516b5 Doc update 2021-08-06 14:03:14 +07:00
QuantumEntangledAndy cbbf3992a4 Add tests for deserialising adpcm, infov1, iframe and pframe BcMedia 2021-08-05 17:45:37 +07:00
QuantumEntangledAndy 340f3f924b Fix adpcm and add a test for swann cameras 2021-08-05 17:45:37 +07:00
QuantumEntangledAndy d738843fd9 Add talk command to neolink
Bug fix to TalkConfig

Bug fix to adpcm serde

Slow talk to sample rate

Update gstreamer-rs

Also remove gio and glib in favor of gstreamer::{glib, gio} to ensure 
always using comapt version

Add TalkAbility protocol and update talk to use it. Also add a `talk_stream` method

Use `talk_stream` and gstreamer to play other types of audio

Add microphone and volume to talk command

Don't decode adpcm

Debug print the error when camera fails to stream

Use correct adpcm block size

Allow retries during read in deserlisation

Use TalkReset messages after talk finishes
2021-08-05 17:45:37 +07:00
QuantumEntangledAndy f4bcde6ffc Actually implement reboot 2021-08-05 17:45:37 +07:00
QuantumEntangledAndy a86565f68b Add talk to neolink_core 2021-08-05 17:45:37 +07:00
QuantumEntangledAndy 373a3478ea Use nom to deserialise BcMedia
Split bc and bcmedia into seperate modules

Add bcmedia serialisation and remove redundent data from the bcmedia model
2021-08-05 17:45:37 +07:00
QuantumEntangledAndy a0dcbbfd51 Added reboot to neolink-core
Added a reboot command to neolink
2021-08-05 17:45:37 +07:00
QuantumEntangledAndy 9d03821c54 Fix adpcm and add a test for swann cameras 2021-08-05 17:14:59 +07:00
QuantumEntangledAndy ce1b410f74 Use TalkReset messages after talk finishes 2021-08-05 07:46:03 +07:00
QuantumEntangledAndy 921be53ef0 Allow retries during read in deserlisation 2021-08-05 07:45:33 +07:00
QuantumEntangledAndy 3a960141b1 Use correct adpcm block size 2021-08-04 20:01:39 +07:00
QuantumEntangledAndy eea7f8505b Debug print the error when camera fails to stream 2021-08-04 17:43:20 +07:00
QuantumEntangledAndy 8acf004ad0 Don't decode adpcm 2021-08-04 17:22:41 +07:00
QuantumEntangledAndy 3404345410 Add microphone and volume to talk command 2021-08-04 16:13:06 +07:00
QuantumEntangledAndy 892bbc1cd1 Use talk_stream and gstreamer to play other types of audio 2021-08-04 15:28:45 +07:00
QuantumEntangledAndy e5bbd631eb Add TalkAbility protocol and update talk to use it. Also add a talk_stream method 2021-08-04 15:28:15 +07:00
QuantumEntangledAndy 4bf399f171 Update gstreamer-rs
Also remove gio and glib in favor of gstreamer::{glib, gio} to ensure 
always using comapt version
2021-08-04 15:27:15 +07:00
QuantumEntangledAndy a2e184d42f Slow talk to sample rate 2021-08-04 10:52:29 +07:00
QuantumEntangledAndy 1440cd62e8 Bug fix to adpcm serde 2021-08-04 10:23:24 +07:00
QuantumEntangledAndy c2365c1e64 Bug fix to TalkConfig 2021-08-04 07:46:36 +07:00
QuantumEntangledAndy 988c782eac Add talk command to neolink 2021-08-03 18:29:29 +07:00
QuantumEntangledAndy 4de0185fc2 Actually implement reboot 2021-08-03 18:29:15 +07:00
QuantumEntangledAndy e3ac3089aa Add talk to neolink_core 2021-08-03 18:28:55 +07:00
QuantumEntangledAndy 692b7429c7 Add bcmedia serialisation and remove redundent data from the bcmedia model 2021-08-03 17:07:08 +07:00
QuantumEntangledAndy 4ecb2a1ae4 Split bc and bcmedia into seperate modules 2021-08-03 15:53:25 +07:00
QuantumEntangledAndy 9ba2a59eda Use nom to deserialise BcMedia 2021-08-03 14:58:26 +07:00
QuantumEntangledAndy bc6c6adccd Added a reboot command to neolink 2021-08-02 15:20:31 +07:00
QuantumEntangledAndy 5d4488ad33 Added reboot to neolink-core 2021-08-02 15:20:20 +07:00
QuantumEntangledAndy 4680ec4c2b Some imporved documentation for the subcommand modules 2021-08-02 13:41:40 +07:00
QuantumEntangledAndy ae908e914b Add links to documentation 2021-08-02 11:10:26 +07:00
QuantumEntangledAndy 8c25de15cf Small adjustment to statusled info stdout 2021-08-02 09:57:18 +07:00
QuantumEntangledAndy babc2fa81a Fix bug in serialisation of extension 2021-08-02 09:56:24 +07:00
QuantumEntangledAndy ffdbdb6777 Gracefully stop polling
Polling would error on a normal disconnect before. This fixes that
2021-08-02 09:56:08 +07:00
QuantumEntangledAndy 4897dc80eb Bug fix in logout sequences 2021-08-02 09:01:42 +07:00
QuantumEntangledAndy ddee51dcd8 Updates to the readme 2021-08-02 07:59:48 +07:00
QuantumEntangledAndy 98c360162e Updates to docker 2021-08-02 07:59:41 +07:00
QuantumEntangledAndy 629004d98f Add neolink command for the status-light 2021-08-02 07:50:26 +07:00
QuantumEntangledAndy e12ac6c7b4 Add LED light controls to core 2021-08-01 13:38:34 +07:00
QuantumEntangledAndy d93534a1c2 Rust fmt 2021-08-01 08:47:27 +07:00
QuantumEntangledAndy 6e325f8b9a Add logout model and use it during disconnect 2021-08-01 08:41:29 +07:00
QuantumEntangledAndy 1c07973c37 Restuructured bc_protocol to increase modulaitry 2021-08-01 07:53:21 +07:00
QuantumEntangledAndy 9efedd660a More clippy suggestions 2021-08-01 07:22:30 +07:00
QuantumEntangledAndy 9a69de6dcd Restucture of rtsp crate into module 2021-07-31 20:49:51 +07:00
QuantumEntangledAndy 165e07fa8a Make the cargo fmt check all workspaces 2021-07-31 19:49:17 +07:00
QuantumEntangledAndy 13792fe014 Include docs for neolink_rtsp and neolink 2021-07-31 18:57:55 +07:00
QuantumEntangledAndy 4a773886ae Removed unessecary public from the rtsp module 2021-07-31 18:35:17 +07:00
QuantumEntangledAndy ca5a598274 Add documentation to neolink_core 2021-07-31 18:31:52 +07:00
QuantumEntangledAndy fccb54af8f Remove redundent dependencies 2021-07-31 15:38:50 +07:00
QuantumEntangledAndy 0510d35910 Apply clippy changes 2021-07-31 15:18:35 +07:00
QuantumEntangledAndy 5e6f1eabfd Basic setup of subcommands 2021-07-31 12:30:32 +07:00
QuantumEntangledAndy 0afc0d8154 Initial move to workspaces 2021-07-30 20:11:03 +07:00
Andrew King f5fd552f25 And missing comma in dissector 2021-07-29 12:18:41 -05:00
Robin Westerlundh b72d47e26c Add missing variable f_bin_offset 2021-07-26 17:23:44 -05:00
Matthias Liffers e89aca4a31 Add yml syntax highlight to docker-compose example
Signed-off-by: Matthias Liffers <m@tthi.as>
2021-06-21 09:02:23 +08:00
Matthias Liffers e82f70405e Add example docker-compose config 2021-06-20 11:40:56 +08:00
Gleb Sinyavskiy fc6573e91c Add Arch Linux installation instructions
Hello,

Thanks for a great project!
I've been using neolink for a while and decided to publish it to AUR to let other Arch Linux user install neolink using more or less traditional for arch tools.

The PR simply adds a link to the AUR page of the project.
2021-06-17 11:52:57 -05:00
George Hilliard 5a62bb1df1 Merge pull request #83 from QuantumEntangledAndy/protocol_updates
Protocol Updates
2021-04-17 22:34:23 -05:00
QuantumEntangledAndy 9692aa82da Update tests to the new protocol model 2021-04-18 09:10:57 +07:00
QuantumEntangledAndy 05cb032d3c Bump nom version 2021-04-18 08:13:01 +07:00
George Hilliard 6ac4b70ff3 cargo fmt 2021-04-17 16:04:25 -05:00
George Hilliard 949192b620 Use pure Rust AES implementation 2021-04-17 15:53:18 -05:00
QuantumEntangledAndy 4721d364f1 Use context to keep track of binary 2021-04-17 21:30:12 +07:00
QuantumEntangledAndy 0dc25690f4 Removed docs for prototype mqtt 2021-04-17 21:29:56 +07:00
QuantumEntangledAndy ce9f3e7a1b Removed extra init method for context 2021-04-17 21:29:14 +07:00
QuantumEntangledAndy eda598c40f Restore timeout duration 2021-04-17 17:09:05 +07:00
QuantumEntangledAndy f4630f4d07 Treat AES encrypt and decrypt differently 2021-04-17 17:07:40 +07:00
QuantumEntangledAndy 30fad08706 Bug fixes and making serde respect the status code to send 2021-04-17 17:03:29 +07:00
George Hilliard 1227ff1e96 Refactor AesKey to only contain key bytes 2021-04-17 01:49:29 -05:00
QuantumEntangledAndy 02f4cab6ba Added AES encryption 2021-04-17 12:35:55 +07:00
QuantumEntangledAndy f479c8282a Added firmware update to messages.md 2021-04-15 09:23:13 +07:00
QuantumEntangledAndy a2ca630bdd Merge branch 'master' of github.com:thirtythreeforty/neolink into protocol_updates 2021-04-15 08:04:30 +07:00
QuantumEntangledAndy 772ba86156 Bug fix and preperation for new encryption protocol 2021-04-14 17:17:43 +07:00
twistedddx 5c83472fae Update documentation for status code and additional encryption offset data 2021-01-26 18:03:21 -06:00
twistedddx a7202fa9e1 config sample for tls_client_auth, stream, channel_id
remove deprecated format
2021-01-26 18:00:42 -06:00
George Hilliard 055d731fec Merge pull request #111 from kevans91/fwver
Report firmware version after login
2020-12-20 20:18:38 -06:00
George Hilliard ae86407483 Don't unwrap while checking camera version 2020-12-20 19:56:49 -06:00
George Hilliard a91979d2b6 Allow older version of Rust to build adpcm 2020-12-20 19:37:49 -06:00
George Hilliard 64af3dce1a Docker: also install testing packages in release container
Actually closes #104 on GitHub
2020-12-20 19:14:47 -06:00
Kyle Evans 6a432b30ad main: report camera firmware version 2020-12-20 10:27:45 -06:00
Kyle Evans ce8c2d3648 BcCamera: add a version() function for VersionInfo 2020-12-20 01:19:42 -06:00
Kyle Evans e00ed786ac bc: add VersionInfo 2020-12-20 01:16:18 -06:00
George Hilliard bdd270d3ca build.rs: Add GITHUB_SHA detection 2020-12-15 16:19:43 +00:00
George Hilliard 5ccfd6a0d8 Fix clippy lints 2020-12-14 22:40:28 -06:00
George Hilliard f4612b8f8d Fix use of deprecated time::OffsetDateTime::now_local() 2020-12-14 22:37:15 -06:00
George Hilliard b8118dadc9 Remove usage of deprecated env_logger::from_env() 2020-12-14 22:26:28 -06:00
George Hilliard c342434848 Refactor: move camera management into new function 2020-12-14 22:26:15 -06:00
George Hilliard d01f5684b4 Fix Docker build: pull gst-rtsp-server from Alpine testing
Closes #104 on GitHub.
2020-12-14 22:12:35 -06:00
George Hilliard 2b0f465c25 readme: Fix typos in download links 2020-12-11 09:22:35 -06:00
George Hilliard ea4f4130ce readme: Add direct download links to latest CI builds 2020-12-11 09:20:45 -06:00
George Hilliard c581ad43f4 Actions: Rename *.yaml to *.yml
The app https://nightly.link/ requires .yml extensions due to a bug:

oprypin/nightly.link#3

Easy enough to change extensions.
2020-12-11 08:30:20 -06:00
George Hilliard ea0c91ee83 Add list of prebuilts and artifact download instructions 2020-12-10 19:26:46 +00:00
George Hilliard e07f97bc12 Merge pull request #103 from thirtythreeforty/cross-builds-rebased
Implement more CI builds: for macOS and ARM Linux
2020-12-10 13:08:03 -06:00
George Hilliard 17c293b3fd macOS: Do not cache build artifacts
The GitHub-managed cache is missing crates when we cache the build.
Disable this on macOS.
2020-12-10 12:55:49 -06:00
George Hilliard 61e9baab53 Unify cross-build workflows using a matrix 2020-12-10 12:49:38 -06:00
QuantumEntangledAndyandtwistedddx 2e04405550 Format error cause nicely
Co-Authored-By: twistedddx <bits@live.com>
2020-12-09 15:44:33 +07:00
QuantumEntangledAndy afdb0f495c Make armhf use matrix and add more Debian architectures 2020-12-09 01:07:35 -06:00
QuantumEntangledAndy 9b59888b08 Add macos build 2020-12-09 01:07:35 -06:00
d7e84891f6 Bump minimum glib version and update dependencies
Co-Authored-By: twistedddx <bits@live.com>
Co-Authored-By: George Hilliard <thirtythreeforty@gmail.com>
2020-12-09 01:07:17 -06:00
George Hilliard f88b1a6ce6 Merge pull request #99 from kevans91/dns
config: allow hostnames for camera addresses
2020-12-08 10:29:17 -06:00
Kyle Evans 2e8126cd73 config: allow hostnames for camera addresses
This offers more flexibility, as a camera system admin only
needs a DNS assignment rather than DHCP. The syntax is still
as expected:

address = "cameras.example.com:9000"

This is especially handy in more complex topologies, where one
or more specified "camera" may actually be pointed at a system
providing a tunnel through to multiple cameras; names make it
easier to identify said gateway machine.

All IPs that the given name resolves to are tried so that we
correctly handle, e.g., a name with both AAAA and A records.

Note that addresses are no longer validated up front, but instead
simply get resolved when the connection attempt is made.

Name resolution will be aborted after ~60s of failure.
2020-12-07 20:15:47 -06:00
George Hilliard 32400971a5 Merge pull request #87 from QuantumEntangledAndy/error_updates
More detailed error messages on deser fail and timeout
2020-11-30 23:35:26 -06:00
twistedddxandtwistedddx 80a75b20a6 Dissector - Add BC to BC magic 0x0fedcba0
Co-authored-by: twistedddx <bits@live.com>
2020-11-30 23:33:09 -06:00
Andrew 882d34de5a Merge branch 'error_updates' into protocol_updates 2020-11-29 13:51:58 +07:00
QuantumEntangledAndyandtwistedddx cecb29b46f Less naked while loop to print error on deser fail
Co-Authored-By: twistedddx <bits@live.com>
2020-11-28 14:09:44 +07:00
QuantumEntangledAndyandtwistedddx 6396883a26 Merge branch 'master'
Co-Authored-By: twistedddx <bits@live.com>
Conflicts:
	src/bc_protocol.rs
	src/bc_protocol/media_packet.rs
2020-11-28 14:07:52 +07:00
George Hilliard efa4a1d7a7 Merge pull request #90 from QuantumEntangledAndy/bugfix-Lumus-Audio
Transcode audio to PCM for all even for AAC
2020-11-27 18:09:59 -06:00
QuantumEntangledAndyandtwistedddx a961829c63 Bug fixes from merges
Using u8 for channel id throughtout
Using simpler map_err

Co-Authored-By: twistedddx <bits@live.com>
2020-11-26 17:11:22 +07:00
QuantumEntangledAndyandtwistedddx 9604ecb29f Merge branch 'error_updates'
Co-Authored-By: twistedddx <bits@live.com>
2020-11-26 17:03:46 +07:00
QuantumEntangledAndyandtwistedddx 21030072cc Merge branch 'master'
Co-Authored-By: twistedddx <bits@live.com>
Conflicts:
	dissector/baichuan.lua
	src/bc_protocol.rs
	src/bc_protocol/media_packet.rs
2020-11-26 17:01:58 +07:00
QuantumEntangledAndyandtwistedddx dda603a9a4 Add message handle and status codes and handel encryption correctly
Co-Authored-By: twistedddx <bits@live.com>
2020-11-26 16:43:31 +07:00
QuantumEntangledAndyandtwistedddx a8a727a248 Use powershell syntax for setting envs for new github api methods
Co-Authored-By: twistedddx <bits@live.com>
2020-11-26 13:17:15 +07:00
QuantumEntangledAndy 25b561c976 More chances to confrom to new protocol 2020-11-26 13:07:27 +07:00
QuantumEntangledAndy a598ddd2a4 Using new github set path and env 2020-11-17 10:37:13 +07:00
QuantumEntangledAndy bbc176e9f7 Convert to raw then send as raw over rtsp 2020-11-17 10:14:17 +07:00
QuantumEntangledAndy 7a6a2ca2e7 Always decode and reencode aac audio
This is so that we can accept mpeg1 and mpeg2 audio in addition to mpeg4
2020-11-16 09:37:49 +07:00
QuantumEntangledAndy 6e1cf2f020 Work on switching encoffset with channelid and msg_mum 2020-11-16 09:23:44 +07:00
twistedddx 428a6f767a Dissector - more message_types 2020-11-13 12:07:57 -06:00
Andrew King f7f12c76a1 Audio and Format auto detect (#68)
* Add queues to the gstreamer launch

* Add audio to the stream

* Removing format option in prep for auto detect

* Adding format detect from headers

* Set format in gstreamer launch depending on video magic bytes

* Rename MaybeAppSrcs to reflect new role of managing gst outputs

* Auto detect format

* Remove all setting of stream format

* Re-add missing media_format caused by rebase

* Add audio format auto detect too

* Use more appropiate adpcm in gst

* Combined gst and media_packet format enums into a single enum StreamFormat

* Reduce adpcm header size

* Disable adpcm output

* Add oki adpcm native rust support

* Maintain state between packets for adpcm

* Use bytes in adpcm stream to determine adpcm decoding state

* Clean up adpcm code

* Use raw rtp payload for the adpcm stream

* Bug fix to treat adpcm and aac seperatly in the match

* Remove redundent second clamp of the step index in adpcm.

* ADPCM format changes.

This is a squashed commit of changes made during live testing of ADPCM 
format.

Summary: Using DVI4 for the ADPCM, with our own decoder written in rust.

* Changes to comments and IMA max range in the adpcm decoder

* ADPCM magic contains block size use it for chunking the adpcm data

* Use error logs rather than asserts in adpcm decode

* Rustfmt and clippy styling

* Use static slice for adpcm step and changes arrays

* Bounds and error checks in ADPCM

* Use i/u32 in adpcm

* Rust fmted
2020-11-13 08:45:40 -06:00
QuantumEntangledAndy 782a9f7c4c Handle timeout and dissconnect error differently 2020-10-29 13:11:21 +07:00
QuantumEntangledAndy 3803bc02ab Add error messages when deser fails 2020-10-29 12:57:39 +07:00
QuantumEntangledAndy 71de7da506 Base encryption solely off legacy login reply 2020-10-29 12:52:04 +07:00
QuantumEntangledAndy d92cb38ec9 Rust fmted 2020-10-15 11:16:06 +07:00
QuantumEntangledAndy edf2f25952 Fixes from rebase 2020-10-15 11:15:38 +07:00
QuantumEntangledAndy d0f760ea7b Refractor to apply ext xml before payload_offset 2020-10-15 11:03:19 +07:00
QuantumEntangledAndy 31aefdbc74 Rename bin_offset to payload_offset 2020-10-15 11:02:32 +07:00
QuantumEntangledAndy 4ff53b73af Refractored bc connection to treat binary as a generic payload 2020-10-15 11:02:32 +07:00
QuantumEntangledAndy 3acd0b4a3c Updates to the readme 2020-10-15 10:59:22 +07:00
QuantumEntangledAndy 5baacbeeed Implement bc make ext xml 2020-10-15 10:59:22 +07:00
Andrew Kingandtwistedddx b5312edb90 Dissector update and some notes about BC message (#80)
Co-authored-by: twistedddx <bits@live.com>
2020-10-12 16:34:26 -05:00
George Hilliard affc0d9b94 Merge pull request #75 from QuantumEntangledAndy/Clippy-fix
Fix clippy style check action
2020-09-18 09:46:54 -05:00
QuantumEntangledAndy 5c9a196333 Only install minimum build requirements in apt CI building 2020-09-18 09:44:18 +07:00
QuantumEntangledAndy da3b0d77c1 Install dependencies before clippy 2020-09-18 09:37:26 +07:00
QuantumEntangledAndy fc5e8e039f Rust fmted 2020-09-17 09:38:27 -05:00
QuantumEntangledAndy e2c2ce26c3 Apply clippy to master
Only change was (clippy::redundant_field_names) on channel_id
2020-09-17 09:38:27 -05:00
QuantumEntangledAndy 59d7600cdb Apply rustfmt to media_packet 2020-09-17 09:38:27 -05:00
QuantumEntangledAndy b0eee39f13 Add clippy and fmt checks and conform to clippy style 2020-09-17 09:38:27 -05:00
Andrew King fab6a11820 Use management bool to set the clock
See #69 on GitHub.
2020-09-16 08:35:42 -05:00
George Hilliard 6d7b07d07b Fix Windows build: use choco package for gst-devel 2020-09-16 08:14:42 -05:00
George Hilliard 28830d55d0 Merge pull request #71 from m1k1o/patch-1
add tzdata to Dockerfile
2020-09-14 10:54:06 -05:00
George Hilliard fb83321d70 Merge pull request #70 from twistedddx/channel_id
Allow setting channel_id
2020-09-13 01:40:14 -05:00
Miroslav Šedivý 0f1c30fe00 add tzdata to Dockerfile 2020-08-15 10:33:26 +02:00
twistedddx e4f67ef3c2 -allow setting channel_id 2020-08-14 23:26:42 +09:30
George Hilliard 9f3181e2cd Merge pull request #50 from QuantumEntangledAndy/magic_headers
Filter data sent to gsteamer using magic bytes
2020-08-11 21:33:46 -05:00
QuantumEntangledAndy 9ca38b1e8b Add warning when hitting unexpected data in the stream 2020-08-12 09:29:58 +07:00
QuantumEntangledAndy d44b1dcdb0 Rename MAGIC_LEN to MAGIC_SIZE 2020-08-12 09:20:12 +07:00
QuantumEntangledAndy efd79ba00c Use simple magic header checks and remove Invalid Media Packet 2020-08-12 05:58:16 +07:00
QuantumEntangledAndy d69f1cc557 Remove dead code and vars from media_packet 2020-08-11 16:55:51 +07:00
QuantumEntangledAndy b0378e08b1 Clippy linting 2020-08-11 16:50:47 +07:00
QuantumEntangledAndy 11396dfe68 Using bytes instead of string for header checks 2020-08-11 16:46:07 +07:00
QuantumEntangledAndy e5f579860c Removed uneeded pup from media_packet 2020-08-11 16:40:48 +07:00
QuantumEntangledAndy 018c70a054 Remove continue packet type 2020-08-11 16:29:55 +07:00
QuantumEntangledAndy 7ad7706341 Use const to explain the pad_size 2020-08-11 16:28:35 +07:00
QuantumEntangledAndy 4dd4ffee7a Removed unused expected_num_packets 2020-08-11 16:21:15 +07:00
QuantumEntangledAndy 07257ede2d Remove uneeded function from media_packet.rs 2020-08-09 15:23:14 +07:00
QuantumEntangledAndy 024659ee45 Rustfmt-ed 2020-08-05 12:07:07 +07:00
QuantumEntangledAndy 00e46783b6 String formatting for docker publish 2020-08-05 10:57:39 +07:00
QuantumEntangledAndy f6dd3b718b Move media packet to bc_protocol module and implement adv header checks 2020-08-05 10:47:34 +07:00
QuantumEntangledAndy e580985951 Make docker hub usernames etc based on repo names 2020-08-05 09:09:59 +07:00
QuantumEntangledAndy 25ba342a16 Merge branch 'master' into magic_headers 2020-08-05 07:41:49 +07:00
QuantumEntangledAndy 66fbd99f37 Using own dockerhub 2020-08-05 07:41:01 +07:00
QuantumEntangledAndy eb3abb4fb0 Seperate MediaData logic into its own module 2020-08-03 14:46:32 +07:00
QuantumEntangledAndy b5584bb851 Clean up to continuation code 2020-08-03 14:08:01 +07:00
QuantumEntangledAndy 832907f574 Rust fmt-ed 2020-08-03 13:29:33 +07:00
Andrew King e973b1eced Merge branch 'master' into magic_headers 2020-08-03 13:26:59 +07:00
QuantumEntangledAndy 963e4799c6 Use a deque and process media packets as a substream 2020-08-03 13:25:45 +07:00
QuantumEntangledAndy 8ee375fda1 Merge branch 'master' into magic_headers 2020-08-03 09:39:35 +07:00
George Hilliard 534b8df829 Fix another typo in Docker conditional push 2020-08-02 13:02:21 -05:00
George Hilliard d665b633df Fix Docker auto-publish 2020-08-02 12:57:40 -05:00
George Hilliard 71d1808525 Merge pull request #54 from thirtythreeforty/set-time
Automatically check/set the time on cameras, and bump timeout
2020-08-02 12:49:50 -05:00
George Hilliard 3f96dc1996 Merge remote-tracking branch 'origin/master' into set-time 2020-08-02 12:34:06 -05:00
George Hilliard 8ab4ba3b33 Add possible reason for failure to set time 2020-08-02 12:31:47 -05:00
George Hilliard 74f11769a0 Merge pull request #56 from thirtythreeforty/gst16
Update to gstreamer bindings v0.16
2020-08-02 12:22:18 -05:00
George Hilliard 80757c170b Merge pull request #60 from QuantumEntangledAndy/doc_typos
Typos and Doc Updates
2020-08-02 11:50:36 -05:00
George Hilliard 9cc3ca856f Update to gstreamer bindings v0.16 2020-08-02 11:48:40 -05:00
QuantumEntangledAndy 8e2aa426a5 Typos and doc updates 2020-08-02 19:51:20 +07:00
QuantumEntangledAndy c5948f3850 Rustfmt-ed 2020-08-02 13:22:08 +07:00
QuantumEntangledAndy cf7efca44d Refractor continuation logic to seperate subscription getter 2020-08-02 11:45:58 +07:00
QuantumEntangledAndy 9d4ebe0bf8 Hashmaps in the contiuation model 2020-07-31 14:45:24 +07:00
George Hilliard 7de269d1b3 Merge pull request #40 from QuantumEntangledAndy/cross-compile-armhf
Add a build action for armhf
2020-07-31 02:22:14 -05:00
QuantumEntangledAndy 1f98cf517b Ok bug fixes to my continuation model and rustfmt again 2020-07-31 13:54:46 +07:00
QuantumEntangledAndy 011a639356 A basic continuation model using contex, also rustfmt-ed 2020-07-31 13:47:17 +07:00
George Hilliard 051887a7c3 Bump timeout to 5 seconds and remove config option
This, combined with auto time set, should completely fix #14.
2020-07-31 00:46:07 -05:00
George Hilliard e603699e45 Implement get/set time during camera connect 2020-07-31 00:35:51 -05:00
QuantumEntangledAndy 9a3b8317c4 Refractor assuming extra binary bytes are junk and use single BinaryData 2020-07-31 11:22:14 +07:00
George Hilliard 0e68b2bc53 Merge pull request #43 from thirtythreeforty/BI-Setup-Guide-Modified
Add Task Scheduling Guide and Add Section for 400 Series Cams
2020-07-30 17:30:26 -05:00
Andrew King 1416ee678c Add more documentation for linux (#52)
* Add a documentation for creating a service on linux

* Added a bit about the groups into the linux service doc

* Started unix setup doc

* Added more information to the unix_setup doc

* Copy pasta in unix_setup doc title correction

* More typo fixes in the docs
2020-07-30 09:53:12 -05:00
QuantumEntangledAndy 7ecd089bc5 Use little endian and some bug fixes 2020-07-30 14:47:57 +07:00
QuantumEntangledAndy 152282a2d8 Attempt to keep track of chunked video frames 2020-07-30 14:00:16 +07:00
QuantumEntangledAndy 3ee6cdd575 Using getters for the VideoI and PFrames 2020-07-30 13:34:07 +07:00
QuantumEntangledAndy 317f4cd6a6 Adding more structure to the deserialised video frames 2020-07-30 11:45:57 +07:00
Andrew 60fb3c0200 Add armhf github action 2020-07-29 16:23:42 +07:00
QuantumEntangledAndy 67f42feabd Refractor video magic bytes into BinaryData 2020-07-29 16:06:22 +07:00
QuantumEntangledAndy 1acb893305 Include whole frame even the magick header 2020-07-28 17:04:30 +07:00
QuantumEntangledAndy 266fd67aad Use magick headers for deciding what to do with the data 2020-07-28 16:51:14 +07:00
hh1209 e7a87ed3ee Fix the screenshots 2020-07-20 08:26:36 -05:00
hh1209 fc29372e04 Add camera type and E1 note for format changing 2020-07-19 13:58:21 -05:00
hh1209 ac6062f705 Add Task Scheduling Guide and Add section for 400 series cams 2020-07-18 19:29:48 -05:00
George Hilliard 5935d331b3 Add warning about plaintext users/passwords 2020-07-18 15:12:26 -05:00
George Hilliard c9a3561088 In sample config, don't enable RTSPS by default 2020-07-18 15:12:26 -05:00
George Hilliard cbf03fca5b gst: don't accept StreamFormat by reference 2020-07-18 15:12:26 -05:00
George Hilliard bae4182bf5 Refactor users to use &str as main type 2020-07-18 15:12:26 -05:00
George Hilliard 3d866a482e config: remove unneeded defaults 2020-07-18 15:12:26 -05:00
George Hilliard 6731086e85 Merge branch 'auth' 2020-07-18 14:58:33 -05:00
George Hilliard 5ffde81f2e Make CI link more specific 2020-07-18 13:57:19 -05:00
George Hilliard fdf33b42e5 Update README.md 2020-07-18 09:33:53 -05:00
hh1209andGeorge Hilliard 98539c823a Setting up Neolink with Blue Iris.md (#32)
This PR introduces a guide for users to setup their Reolink Cameras and Neolink to use with Blue Iris.

Co-authored-by: George Hilliard <thirtythreeforty@gmail.com>
2020-07-18 09:24:47 -05:00
George Hilliard 2887cd34e3 Merge pull request #39 from QuantumEntangledAndy/conditonal-docker
Conditional docker publish
2020-07-18 07:22:21 -07:00
QuantumEntangledAndy 39e2391efd Add conditions to docker publish 2020-07-14 12:18:23 +07:00
QuantumEntangledAndy 5bd4c5aff4 Correct messages of validate of the client tls in the config 2020-07-14 10:00:53 +07:00
QuantumEntangledAndy 5d30e1a8b1 No printing of secrets even at debug level 2020-07-14 09:59:55 +07:00
QuantumEntangledAndy 419c9561d2 Using hashmap for permitted users throughout 2020-07-14 09:57:55 +07:00
QuantumEntangledAndy 4e16ae912d Added more info in the sample_config 2020-07-13 15:31:25 +07:00
QuantumEntangledAndy b86f5abf6c Chaning the default of permitted_users to depend on [[users]] 2020-07-13 14:33:31 +07:00
QuantumEntangledAndy 60810fc0f7 Rustfmt cleanup 2020-07-13 12:12:17 +07:00
QuantumEntangledAndy c1151acecb More readme updates to explain the default permitted_users 2020-07-13 12:02:13 +07:00
QuantumEntangledAndy 0d39cbaeff Updates to the readme 2020-07-13 11:51:29 +07:00
QuantumEntangledAndy 143390d6f4 using valdator to check for reserved names 2020-07-13 10:11:58 +07:00
QuantumEntangledAndy 4b53e426cf Using anonymous for default permitted users 2020-07-13 09:20:09 +07:00
QuantumEntangledAndy 6811f15aba Using hashmap to do the deduplicating 2020-07-13 09:18:11 +07:00
QuantumEntangledAndy 65748bd117 Using a slice for the permitted users 2020-07-13 09:17:50 +07:00
QuantumEntangledAndy 0fa62698a7 Updates to the readme 2020-07-12 18:49:51 +07:00
QuantumEntangledAndy 4723435a45 Clean up of redundent code in TLS and Basic auth 2020-07-11 09:11:11 +07:00
George Hilliard 87ca90528a Merge pull request #33 from m1k1o/patch-1
Dockerfile missing gst dependencies
2020-07-10 08:05:43 -07:00
QuantumEntangledAndy ad1b34239c But fix and update to the warning given during user/password checking 2020-07-10 17:36:36 +07:00
Andrew King 7cf0bfc24b Merge branch 'master' into srtp 2020-07-10 17:15:15 +07:00
Miroslav Šedivý cd842ae4d4 Dockerfile gst dependencies 2020-07-10 09:37:19 +02:00
QuantumEntangledAndy 18880ae1d2 Adding more info messages, and reserving special user names 2020-07-08 07:15:19 +07:00
QuantumEntangledAndy 1a5ce73b6d Ensure anonymous has access to check the URL if not play it 2020-07-07 22:02:12 +07:00
George Hilliard 8f82bb7fbc Use a few Rust idioms 2020-07-04 12:35:46 -05:00
George Hilliard fc86e04861 Format RTSP paths exclusively in one place 2020-07-04 12:26:06 -05:00
George Hilliard 085c59d355 Dissector: Put message info in Info column 2020-07-04 12:03:45 -05:00
George Hilliard 7d337c86cb dissector: add common message types for easier following of data stream 2020-07-04 11:51:19 -05:00
George Hilliard e69ea587f4 Revert "Docker: only publish on tagged releases"
This reverts commit b49cb5078f.
2020-07-03 17:26:06 -05:00
George Hilliard b49cb5078f Docker: only publish on tagged releases 2020-07-03 17:24:30 -05:00
George Hilliard 89982a8097 Release v0.3.0 2020-07-03 17:20:27 -05:00
George Hilliard 2c66120b99 Cargo: bump package versions 2020-07-03 17:18:54 -05:00
George Hilliard 9846eb99c6 Autoformat 2020-07-03 17:14:16 -05:00
George Hilliard 94be9e603c Fix stream paths 2020-07-03 17:12:58 -05:00
George Hilliard d0552d5618 Merge branch 'docker' 2020-07-03 14:07:28 -05:00
George Hilliard 10f1e584a8 README: mention Docker 2020-07-03 14:07:20 -05:00
George Hilliard 8e293a4f1b Docker: Remove pre-build of dependencies 2020-07-03 13:55:51 -05:00
George Hilliard 0f5c6ece93 Implement Docker image based on Alpine 2020-07-03 13:51:17 -05:00
QuantumEntangledAndy f3b3684f00 Add default no users 2020-07-03 14:57:34 +07:00
QuantumEntangledAndy 1fbe7e6122 Merge branch 'MultipleUsers' back into srtp 2020-07-03 14:26:46 +07:00
QuantumEntangledAndy f6ab54a09c Readme and comment updates 2020-07-03 14:23:09 +07:00
QuantumEntangledAndy 80e416d01d Merging changes from PR 2020-07-03 13:49:43 +07:00
QuantumEntangledAndy fc802c873a Seperate reading and parsing cert files for better error handlling 2020-07-03 13:25:32 +07:00
QuantumEntangledAndy 9a6d8572b4 Changed handelling of getting user path 2020-07-03 12:58:13 +07:00
QuantumEntangledAndy 5ff211747e Using option when setting up TLS 2020-07-03 12:38:09 +07:00
QuantumEntangledAndy 1b68d73399 Using Options for basic auth 2020-07-03 12:21:54 +07:00
QuantumEntangledAndy 0317137616 Use unreachable for the client tls 2020-07-03 11:52:55 +07:00
QuantumEntangledAndy 418f8a0fa8 Use new from file when loading the pem 2020-07-03 11:49:23 +07:00
QuantumEntangledAndy 7eed4a037a Print using TLS only on debug level 2020-07-03 11:48:33 +07:00
QuantumEntangledAndy 3a71c7e651 Use .unwrap_or_else with getting the auth from gst 2020-07-03 11:46:52 +07:00
QuantumEntangledAndy 02642c2638 Print username only in debug mode 2020-07-03 11:44:01 +07:00
QuantumEntangledAndy 296c281f15 Added more control over authourised users. 2020-07-03 11:42:56 +07:00
Andrew King a4012f258e Merge branch 'master' into srtp 2020-07-03 08:39:36 +07:00
QuantumEntangledAndy b5e8cb8ff7 Updated readme to include TLS and basic auth. 2020-07-03 08:29:05 +07:00
QuantumEntangledAndy a9a0048d78 Added basic user auth 2020-07-03 07:49:41 +07:00
George Hilliard 22e2dfbed3 Hooray, E1 is officially tested, and VLC is happy 2020-07-02 08:55:50 -05:00
George Hilliard 98a0d3cd5d Merge branch 'h264' 2020-07-02 08:49:10 -05:00
George Hilliard a562dcdba2 Reword readme 2020-07-02 08:49:00 -05:00
George Hilliard 5583313394 Refactor creating multiple-path streams
This way, we don't stream from the Reolink camera more than once, and
simply create multiple Gstreamer mountpoints for the underlying factory.
2020-07-02 08:44:03 -05:00
QuantumEntangledAndy 5fde4c6800 Add TLS 2020-07-02 15:57:18 +07:00
QuantumEntangledAndy 55555333ff Do subvalidation on the config 2020-07-02 10:02:13 +07:00
QuantumEntangledAndy 698fc0841f Updates to the readme 2020-07-02 09:41:18 +07:00
QuantumEntangledAndy 8d13f14bea Add appropiate submounts 2020-07-01 12:40:27 +07:00
QuantumEntangledAndy 84b4c0659a Added port specification 2020-07-01 11:56:25 +07:00
QuantumEntangledAndy 3ba10ace5d Moved gst launch str to gst and using enums 2020-07-01 11:34:58 +07:00
QuantumEntangledAndy c4e3745d27 Added validation to the config file 2020-07-01 11:34:19 +07:00
QuantumEntangledAndy 7ab104a4ac Renaming and type changes in sub stream selection 2020-07-01 11:32:33 +07:00
George Hilliard 227d04549e Also execute build on pull requests 2020-06-30 22:33:53 -05:00
QuantumEntangledAndy 73536b5f55 Add timestamps to the stream 2020-06-30 21:16:33 +07:00
QuantumEntangledAndy 83e25c86b2 Info message when connecting to stream tells you which stream it is 2020-06-30 21:15:46 +07:00
QuantumEntangledAndy 0548b422da Updated README with changes h264 and subStream instructions. 2020-06-30 11:48:58 +07:00
QuantumEntangledAndy 4ea20f0542 Allow stream specification in config 2020-06-30 11:41:19 +07:00
QuantumEntangledAndy 826814abd7 Allowing custom gst-launches and specification of format in the camera 2020-06-30 11:30:24 +07:00
George Hilliard 63875d1175 Update README, mention buffer sizes 2020-06-26 11:40:26 -05:00
George Hilliard 9a0eb567dd Mention opening issue with other cameras 2020-06-19 14:48:07 -05:00
George Hilliard c836c956f8 MaybeAppSrc: Don't require "success" from EOS push
Gstreamer's definition of success is too narrow, and we panic on a
"flushing" result.

Addresses #13 on GitHub.
2020-06-18 14:42:34 -05:00
George Hilliard fa44f7077f Update issue templates 2020-06-18 14:02:36 -05:00
George Hilliard 3d94f30145 Notify Gstreamer of end-of-stream on hangup from camera
This may help resolve #13 on GitHub.
2020-06-18 13:46:23 -05:00
George Hilliard bfb84807e8 Banish println, use all logging 2020-06-13 18:17:34 -05:00
George Hilliard 728e2fde05 Raise level of "uninteresting message" to DEBUG 2020-06-13 18:17:34 -05:00
George Hilliard 86b0fb091e Raise default verbosity to INFO 2020-06-13 18:17:34 -05:00
George Hilliard 01d60b336e Delay marking camera as connected until we've logged in
The reason for this change is that a "not responding" camera proxy such
as a ^Z'd `socat` instance will connect just fine, but never send any
data. In such a case, we retry in a 1-second loop, which is not the
intent of the retry loop.
2020-06-13 18:17:34 -05:00
George Hilliard bfa1fdf3b3 Add read timeout to Baichuan socket
This might help with #13, although I remain unable to reproduce it
exactly as described.
2020-06-13 18:17:34 -05:00
242 changed files with 35613 additions and 2529 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+15
View File
@@ -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"]
+3
View File
@@ -0,0 +1,3 @@
target/
Dockerfile
.dockerignore
+13
View File
@@ -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']
+25
View File
@@ -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:
+14
View File
@@ -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.
-52
View File
@@ -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*"
+433
View File
@@ -0,0 +1,433 @@
name: CI
on:
push:
pull_request:
workflow_dispatch:
env:
rust_version: "1.82.0"
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 linux 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 libssl-dev
- if: runner.os == 'Windows'
name: Install Windows deps
run: |
# Gstreamer
choco install -y --no-progress gstreamer --version=1.24.2
choco install -y --no-progress gstreamer-devel --version=1.24.2
$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 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"
# One last check on directories
dir "$env:GSTREAMER_1_0_ROOT_MSVC_X86_64"
dir "$env:OPENSSL_DIR"
- if: runner.os == 'macOS'
name: Install macOS deps
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-bookworm-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
- 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 "${{ env.rust_version }}"
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
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 rust
run: |
rustup default "${{ env.rust_version }}"
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 rust
run: |
rustup default "${{ env.rust_version }}"
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') }}
+147
View File
@@ -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 }}
+73
View File
@@ -0,0 +1,73 @@
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: |
echo "All Features"
cargo +nightly clippy --workspace --all-targets --all-features || exit 1
echo "No Features"
cargo +nightly clippy --workspace --all-targets --no-default-features || exit 1
echo "Gstreamer Only"
cargo +nightly clippy --workspace --all-targets --no-default-features --features=gstreamer || exit 1
echo "Pushnoti Only"
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
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
MD013:
code_blocks: false
+20
View File
@@ -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
+3169 -518
View File
File diff suppressed because it is too large. Load diff
+56 -23
View File
@@ -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"]
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
View File
@@ -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}
+577 -78
View File
@@ -1,122 +1,621 @@
# Neolink
![CI](https://github.com/thirtythreeforty/neolink/workflows/CI/badge.svg)
![CI](https://github.com/QuantumEntangledAndy/neolink/workflows/CI/badge.svg)
[![dependency status](https://deps.rs/repo/github/QuantumEntangledAndy/neolink/status.svg)](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
### Extra Camera Settings
Listed below are extra camera settings:
```toml
[[cameras]]
name = "Camera01"
username = "admin"
password = "password"
uid = "ABCDEF0123456789"
debug = false # Displays Debug XML messages from camera
enabled = true # Enable or Disable the camera
update_time = false # When camera connects, force the setting of the camera date/time to now. The default is false
print_format = "None" # Type of format that logs are displayed in (None, Human, Xml). The default is None
```
- **Debug:** Will dump the various XMLs from the camera as they are recieved
and decrypted. Leave this off unless asked for it to fix an issue.
- **Enabled:** Useful if you want to remove a camera from rtsp without deleting
it from the config
- **update_time:** Used to FORCE an update on the camera time. Usually it checks
if it is needed but this
will force it regardless. (Mostly this was introduced to address a specific
ssue a user had)
- **print_format:** Used for adjusting printing of some values mostly, battery
messages
### 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
[Because google remove the api for the push notifications we cannot
reliably use push notifications to wake up, so motion won't wake
up neolink anymore]
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~
[Google removed the apis we were using for push notifications]
### 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.
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/G2G5HOYIZ)
+42 -10
View File
@@ -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() {}
+36
View File
@@ -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"
+152
View File
@@ -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))
}
}
+122
View File
@@ -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[..]);
}
+580
View File
@@ -0,0 +1,580 @@
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))
}
// If missing payload_offset treat all as payload
let ext_len = header.payload_offset.unwrap_or_default();
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())
);
}
}
+44
View File
@@ -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;
+368
View File
@@ -0,0 +1,368 @@
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;
/// Get users and general system info
pub const MSG_ID_GET_ABILITY_SUPPORT: u32 = 58;
/// Update, create and remove users
pub const MSG_ID_UPDATE_USER_LIST: u32 = 59;
/// 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,
}
#[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.
Binary file not shown.
Binary file not shown.
+212
View File
@@ -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
+469
View File
@@ -0,0 +1,469 @@
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 users;
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, &reg_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(&reg_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(&reg_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"
);
}
+115
View File
@@ -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(())
}
}
+131
View File
@@ -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 Unpin for BcStream<'_> {}
impl Stream for BcStream<'_> {
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()
}
}
+264
View File
@@ -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
}
}
+297
View File
@@ -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),
}
}
}
+215
View File
@@ -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)
}
}
+32
View File
@@ -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(())
}
}
+149
View File
@@ -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,
}
+53
View File
@@ -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",
})
}
}
}
+170
View File
@@ -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)
}
}
+43
View File
@@ -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(())
}
}
+296
View File
@@ -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");
});
}
}
+33
View File
@@ -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(())
}
}
+153
View File
@@ -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,
}
+343
View File
@@ -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",
})
}
}
}
+75
View File
@@ -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(())
}
}
+41
View File
@@ -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",
})
}
}
}
+234
View File
@@ -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 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<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()
}
}
+423
View File
@@ -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",
})
}
}
}
+50
View File
@@ -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(())
}
}
+160
View File
@@ -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",
})
}
}
}
+350
View File
@@ -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",
})
}
}
}
+51
View File
@@ -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",
})
}
}
}
+482
View File
@@ -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;
}
}
+184
View File
@@ -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))
}
+55
View File
@@ -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)
}
}
+179
View File
@@ -0,0 +1,179 @@
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Returns all users configured in the camera
pub async fn get_users(&self) -> Result<UserList> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection
.subscribe(MSG_ID_GET_ABILITY_SUPPORT, msg_num)
.await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_ABILITY_SUPPORT,
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("admin".to_owned()),
..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,
});
}
// Valid message with response_code == 200
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
user_list: Some(user_list),
..
})),
..
}) = msg.body
{
Ok(user_list)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected ModernMsg payload with a user_list but it was not recieved",
})
}
}
/// Add a new user
///
/// This function does not check if the user exist and the API will likely throw an error if
/// that is the case
pub async fn add_user(
&self,
user_name: String,
password: String,
user_level: u8,
) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if users.iter().any(|user| user.user_name == user_name) {
return Err(Error::Other("User already exists"));
}
users.push(User {
user_set_state: "add".to_owned(),
user_name,
password: Some(password),
user_level,
user_id: None,
login_state: None,
});
self.set_users(users).await
}
/// Modify a user. It seems the only property of a user that is modifiable is the password.
pub async fn modify_user(&self, user_name: String, password: String) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
user.user_set_state = "modify".to_owned();
user.password = Some(password.clone());
} else {
return Err(Error::Other("User not found"));
}
self.set_users(users).await
}
/// Remove a user. This does not check for the existence of that user and will likely return an
/// error if the user doesn't exist.
pub async fn delete_user(&self, user_name: String) -> Result<()> {
let users = self.get_users().await;
let mut users = users?.user_list.unwrap_or(Vec::new());
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
user.user_set_state = "delete".to_owned();
} else {
return Err(Error::Other("User not found"));
}
self.set_users(users).await
}
/// Helper method to send a UserList and wait for its success/failure.
async fn set_users(&self, users: Vec<User>) -> Result<()> {
let bcxml = BcXml {
user_list: Some(UserList {
version: "1.1".to_owned(),
user_list: Some(users),
}),
..Default::default()
};
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection
.subscribe(MSG_ID_UPDATE_USER_LIST, msg_num)
.await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_UPDATE_USER_LIST,
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(())
}
}
}
+57
View File
@@ -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)
}
}
+87
View File
@@ -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;
}
}
}
}
}
}
+547
View File
@@ -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!();
}
}
}
+7
View File
@@ -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;
+294
View File
@@ -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.
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff. Show more