Compare commits

...
Author SHA1 Message Date
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 c3f3ecdb83 Use the right method for fcm 2023-05-19 16:18:30 +07:00
QuantumEntangledAndy f99df6e5e7 Add fcm test project 2023-05-19 09:18:01 +07: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
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
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
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
210 changed files with 25755 additions and 2306 deletions

No files matched your search

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