Compare commits

..
Author SHA1 Message Date
QuantumEntangledAndy 78a6401b16 Begin documenting SD reading 2023-06-09 12:49:05 +07:00
Andrew King 6df5091246 Merge pull request #102 from QuantumEntangledAndy/feature-ptz-preset
Seperate set and assign presets. Also add queury messages to mqtt
2023-06-08 13:25:36 +07:00
QuantumEntangledAndy 04d15537e4 Update the ptz mod.rs readme 2023-06-07 13:41:01 +07:00
QuantumEntangledAndy b5ae5f2fb5 fmt 2023-06-07 13:39:16 +07:00
Andrew 9267de44c7 Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-06-07 13:35:15 +07:00
Andrew King 4c028bd6de Merge pull request #101 from QuantumEntangledAndy/refractor/buffer
Refractor/buffer
2023-06-06 07:23:01 +01:00
Andrew 1390fa0cf9 Merge branch 'master' into refractor/buffer 2023-06-06 11:47:40 +07:00
QuantumEntangledAndy de0528b1b8 Set pts and dts 2023-06-06 11:39:03 +07:00
QuantumEntangledAndy dee305710c Not on a cron 2023-06-06 11:23:01 +07:00
Andrew 77a33ac86a Merge remote-tracking branch 'upstream/master' 2023-06-06 11:22:18 +07:00
QuantumEntangledAndy a08019bc09 Ensure some buffer for pause before we declare ready 2023-06-06 11:07:43 +07:00
QuantumEntangledAndy 60638441aa Reduce default buffer size 2023-06-06 10:57:39 +07:00
QuantumEntangledAndy 9e981df990 Fixes for zero buffer config 2023-06-06 10:52:45 +07:00
QuantumEntangledAndy 73e828f940 Restore stream timestamp stitching for the pause 2023-06-06 10:45:58 +07:00
Andrew King 017b9cb493 Merge pull request #90 from QuantumEntangledAndy/feature/single_quality_pause
Feature/single quality pause
2023-06-06 04:07:13 +01:00
QuantumEntangledAndy a165377d7a Not smoothing when no buffer 2023-06-05 07:58:16 +07:00
QuantumEntangledAndy f7c16bf5a3 Allow zero buffer and remove buffer refill 2023-06-05 07:53:25 +07:00
Andrew King cf67a05dd1 Merge pull request #96 from kevin-david/docker_username
Allow DockerHub username to be specified via `DOCKER_USERNAME` var
2023-06-01 15:20:00 +01:00
Andrew King d961bf36f7 Merge pull request #92 from danielkaiser/feature-ptz-preset 2023-05-29 17:59:03 +01:00
Kevin David a59dafab00 Switch back to distinct DOCKER_PRUNE_TOKEN 2023-05-28 16:41:30 -04:00
Kevin David cf07304bae Allow docker username to be specified, only use one token 2023-05-27 17:04:08 -04:00
QuantumEntangledAndy 9524a1a9f7 Seperate set and assign presets. Also add queury messages to mqtt 2023-05-26 15:09:54 +07:00
QuantumEntangledAndy 4628946514 Use same amount model as in mqtt and add optional speed 2023-05-26 00:55:11 +07:00
QuantumEntangledAndy da3afe228e Use async sleep 2023-05-25 23:55:47 +07:00
Andrew b8dafbb92e Merge remote-tracking branch 'upstream/master' into feature-ptz-preset 2023-05-25 17:44:56 +01:00
Andrew King fdff244f15 Merge pull request #14 from kevin-david/flood_mqtt 2023-05-25 14:59:27 +01:00
Daniel Kaiser 27dc4c2bca Add control/preset command to mqtt 2023-05-24 19:12:24 +02:00
Daniel Kaiser aee14bb411 Add PTZ presets and PTZ command line 2023-05-24 15:19:46 +02:00
Kevin David 5f96b2e7f8 Fix XML deserialization of FloodlightStatusList
The children are `FloodlightStatus`, so that's what we should `yaserde(rename)` to
2023-05-24 08:25:47 -04:00
QuantumEntangledAndy f9975520ab Fmt 2023-05-24 12:33:38 +07:00
QuantumEntangledAndy 864f58d20e Async handle_msg closures 2023-05-24 12:26:27 +07:00
QuantumEntangledAndy f42191973a Seperate quality stream pausing 2023-05-22 13:32:15 +07:00
Kevin David d90f0b1002 Improve MQTT error message 2023-05-19 23:48:10 -04:00
QuantumEntangledAndy 4afa457eff Rework pause to be per stream 2023-05-20 10:31:38 +07:00
QuantumEntangledAndy 1824e061f4 fmt 2023-05-19 13:17:04 +07:00
QuantumEntangledAndy be10aaeed5 Add floodlight status and keep alive pings 2023-05-19 13:15:31 +07:00
Andrew ff9e100ac2 Merge remote-tracking branch 'QuantumEntangledAndy/master' into flood_mqtt 2023-05-19 11:26:14 +07:00
George Hilliard 8c6776607b Autobuild every couple of months if no other activity
Builds expire after 90 days
2023-05-06 07:39:51 -05:00
Kevin David 355cd4846a Remove incorrect code for now 2023-01-25 22:52:45 -05:00
Kevin David 6be7ac2d14 Remove .vscode, improve logging 2023-01-24 23:46:40 -05:00
Kevin David 8cbaf06cde Satisify rustfmt 2023-01-24 23:14:11 -05:00
Kevin David 1f8296dd01 WIP: Add support for floodlight control over MQTT 2023-01-24 22:38:00 -05:00
29 changed files with 1309 additions and 391 deletions

No files matched your search

+22 -4
View File
@@ -1,6 +1,9 @@
name: CI
on: [push, pull_request, workflow_dispatch]
on:
push:
pull_request:
workflow_dispatch:
jobs:
pre_job:
@@ -195,8 +198,23 @@ jobs:
uses: docker/login-action@v2
with:
registry: docker.io
username: ${{ steps.string_user.outputs.lowercase }}
username: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
password: ${{ secrets.DOCKER_TOKEN }}
- name: Set Docker name with owner (package name) depending on if DOCKER_USERNAME is set
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
id: docker_repo
shell: bash
run: |
if [ -z $DOCKER_USERNAME ]; then
echo "DOCKER_NWO=${GITHUB_NWO}" >> $GITHUB_OUTPUT
else
IFS='/' read -ra NWO_SPLIT <<< "$GITHUB_NWO"
REPO_NAME=${NWO_SPLIT[1]}
echo "DOCKER_NWO=${DOCKER_USERNAME}/${REPO_NAME}" >> $GITHUB_OUTPUT
fi
env:
DOCKER_USERNAME: ${{ vars.DOCKER_USERNAME }}
GITHUB_NWO: ${{ steps.string_repo.outputs.lowercase }}
- name: Get tag name
if: ${{ steps.vars.outputs.HAS_SECRET_TOKEN }}
id: tags
@@ -226,7 +244,7 @@ jobs:
echo "TAGS=${tagstr}"
echo "TAGS=${tagstr}" >> "${GITHUB_OUTPUT}"
env:
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
REPO_NAME: ${{ steps.docker_repo.outputs.DOCKER_NWO }}
- name: Install latest rust
run: |
rustup toolchain install stable
@@ -272,7 +290,7 @@ jobs:
push: true
file: Dockerfile
tags: ${{ steps.tags.outputs.TAGS }}
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ github.repository_owner }}
build-args: VERSION=${{ steps.toml.outputs.version }}, REPO=${{ github.repository }}, OWNER=${{ vars.DOCKER_USERNAME || github.repository_owner }}
env:
DOCKER_BUILDKIT: 1
+2 -2
View File
@@ -143,5 +143,5 @@ jobs:
env:
DAYS: "100"
REPO_NAME: ${{ steps.string_repo.outputs.lowercase }}
OWNER: ${{ steps.string_user.outputs.lowercase }}
TOKEN: ${{ secrets.DOCKER_PRUNE__TOKEN }}
OWNER: ${{ vars.DOCKER_USERNAME || steps.string_user.outputs.lowercase }}
TOKEN: ${{ secrets.DOCKER_PRUNE_TOKEN }}
+2
View File
@@ -15,6 +15,8 @@
# Committing IntelliJ project files is a violation of intergalactic law
.idea/
# We prefer to keep .vscode files outside the repo
.vscode/
# MacOS
.DS_Store
._.DS_Store
+6 -1
View File
@@ -188,8 +188,10 @@ Control messages:
- `/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
- `/control/ptz [up|down|left|right|in|out] (amount)` Control the PTZ
movements, amount defaults to 32.0
- `/control/ptz/preset [id]` Move the camera to a PTZ preset
- `/control/ptz/assign [id] [name]` Set the current PTZ position to a preset ID and name
- `/control/pir [on|off]`
Status Messages:
@@ -201,11 +203,14 @@ Status Messages:
of the battery status
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
pir status
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded version of the
PTZ presets
Query Messages:
- `/query/battery` Request that the camera reports its battery level
- `/query/pir` Request that the camera reports its pir status
- `/query/ptz/preset` Request that the camera reports its PTZ presets
### Pause
+8
View File
@@ -19,6 +19,8 @@ pub const MSG_ID_TALKABILITY: u32 = 10;
pub const MSG_ID_TALKRESET: u32 = 11;
/// PtzControl messages have this ID
pub const MSG_ID_PTZ_CONTROL: u32 = 18;
/// PTZ goto preset position
pub const MSG_ID_PTZ_CONTROL_PRESET: u32 = 19;
/// Reboot messages have this ID
pub const MSG_ID_REBOOT: u32 = 23;
/// Request motion detection messages
@@ -35,6 +37,8 @@ pub const MSG_ID_GET_GENERAL: u32 = 104;
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;
/// Get the available PTZ position presets
pub const MSG_ID_GET_PTZ_PRESET: u32 = 190;
/// 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
@@ -53,6 +57,10 @@ pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234;
pub const MSG_ID_BATTERY_INFO_LIST: u32 = 252;
/// Battery message initiaed by the client
pub const MSG_ID_BATTERY_INFO: u32 = 253;
/// Manual Floodlight Control
pub const MSG_ID_FLOODLIGHT_MANUAL: u32 = 288;
/// Floodlight status report from the camera
pub const MSG_ID_FLOODLIGHT_STATUS_LIST: u32 = 291;
/// An empty password in legacy format
pub const EMPTY_LEGACY_PASSWORD: &str =
+90 -1
View File
@@ -76,6 +76,15 @@ pub struct BcXml {
/// Sent to move the camera
#[yaserde(rename = "PtzControl")]
pub ptz_control: Option<PtzControl>,
/// Sent to manually control the floodlight
#[yaserde(rename = "FloodlightManual")]
pub floodlight_manual: Option<FloodlightManual>,
/// Received when the floodlight status is updated
#[yaserde(rename = "FloodlightStatusList")]
pub floodlight_status_list: Option<FloodlightStatusList>,
/// Sent or received for the PTZ preset functionality
#[yaserde(rename = "PtzPreset")]
pub ptz_preset: Option<PtzPreset>,
/// Recieved on login/low battery events
#[yaserde(rename = "BatteryList")]
pub battery_list: Option<BatteryList>,
@@ -85,6 +94,9 @@ pub struct BcXml {
/// Recieved on request for a users persmissions/capabilitoes
#[yaserde(rename = "AbilityInfo")]
pub ability_info: Option<AbilityInfo>,
/// Recieved on request for a link type
#[yaserde(rename = "LinkType")]
pub link_type: Option<LinkType>,
}
impl BcXml {
@@ -325,6 +337,42 @@ pub struct LedState {
pub light_state: String,
}
/// FloodlightStatus xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct FloodlightStatus {
/// Channel ID of floodlight
#[yaserde(rename = "channel")]
pub channel_id: u8,
/// On or off
pub status: u8,
}
/// FloodlightStatusList xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize, Clone)]
pub struct FloodlightStatusList {
/// XML Version
#[yaserde(attribute)]
pub version: String,
/// List of events
#[yaserde(rename = "FloodlightStatus")]
pub floodlight_status_list: Vec<FloodlightStatus>,
}
/// FloodlightManual xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct FloodlightManual {
/// XML Version
#[yaserde(attribute)]
pub version: String,
/// Channel ID of floodlight
#[yaserde(rename = "channelId")]
pub channel_id: u8,
/// On or off
pub status: u8,
/// How long the manual control should apply for
pub duration: u16,
}
/// rfAlarmCfg xml
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct RfAlarmCfg {
@@ -519,7 +567,40 @@ pub struct PtzControl {
pub channel_id: u8,
/// The amount of movement to perform
pub speed: f32,
/// The direction to transverse. Known directions: "right"
/// The direction to transverse. Known values are `"left"`, `"right"`, `"up"`, `"down"`,
/// `"leftUp"`, `"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"`
pub command: String,
}
/// An XML that describes a list of available PTZ presets
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct PtzPreset {
/// XML Version
#[yaserde(attribute)]
pub version: String,
/// The channel ID. Usually zero unless from an NVR
#[yaserde(rename = "channelId")]
pub channel_id: u8,
/// List of presets
#[yaserde(rename = "presetList")]
pub preset_list: PresetList,
}
/// A preset list
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct PresetList {
/// List of Presets
pub preset: Vec<Preset>,
}
/// A preset. Either contains the ID and the name or the ID and the command
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct Preset {
/// The ID of the preset
pub id: u8,
/// The preset name
pub name: Option<String>,
/// Command: Known values: `"toPos"` and `"setPos"`
pub command: String,
}
@@ -614,6 +695,14 @@ pub struct AbilityInfoSubModule {
pub ability_value: String,
}
/// The Link Type contains the type of connection present
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct LinkType {
#[yaserde(rename = "type")]
/// Type of connection known values `"LAN"`
link_type: String,
}
/// Convience function to return the xml version used throughout the library
pub fn xml_ver() -> String {
"1.1".to_string()
+1
View File
@@ -16,6 +16,7 @@ mod battery;
mod connection;
mod credentials;
mod errors;
mod floodlight_status;
mod keepalive;
mod ledstate;
mod login;
+44 -42
View File
@@ -19,58 +19,60 @@ impl BcCamera {
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\
Box::pin(async move {
if let Bc {
body:
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
battery_list: Some(battery_list),
..
})),
..
}),
..
} = bc
{
for battery in battery_list.battery_info.iter() {
match format {
PrintFormat::None => {}
PrintFormat::Human => {
println!(
"==Battery==\n\
Charge: {}%,\n\
Temperature: {}°C,\n\
LowPower: {},\n\
Adapter: {},\n\
ChargeStatus: {},\n\
",
battery.battery_percent,
battery.temperature,
if battery.low_power == 1 {
"true"
} else {
"false"
},
battery.adapter_status,
battery.charge_status,
);
}
PrintFormat::Xml => {
let bat_ser = String::from_utf8(
yaserde::ser::serialize_with_writer(
battery,
vec![],
&Default::default(),
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 Ser the struct"),
)
.expect("Should be UTF8");
println!("{}", bat_ser);
.expect("Should be UTF8");
println!("{}", bat_ser);
}
}
}
}
}
None
Option::<Bc>::None
})
})
.await?;
Ok(())
@@ -1,10 +1,12 @@
use super::BcSubscription;
use crate::{bc::model::*, Error, Result};
use futures::future::BoxFuture;
use futures::sink::{Sink, SinkExt};
use futures::stream::{Stream, StreamExt};
use log::*;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::sync::Arc;
use tokio::sync::mpsc::{channel, Sender};
use tokio::task::yield_now;
use tokio_stream::wrappers::ReceiverStream;
@@ -12,13 +14,14 @@ use tokio_util::sync::PollSender;
use tokio::{sync::RwLock, task::JoinSet};
type MsgHandler = Box<dyn Fn(&Bc) -> Option<Bc> + Send + Sync>;
type MsgHandler = dyn 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>;
#[derive(Default)]
struct Subscriber {
/// Subscribers based on their Num
num: BTreeMap<u16, Sender<Result<Bc>>>,
/// Subscribers based on their ID
id: BTreeMap<u32, MsgHandler>,
id: BTreeMap<u32, Arc<MsgHandler>>,
}
pub(crate) type BcConnSink = Box<dyn Sink<Bc, Error = Error> + Send + Sync + Unpin>;
@@ -95,10 +98,10 @@ impl BcConnection {
/// 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,
T: 'static + Send + Sync + for<'a> Fn(&'a Bc) -> BoxFuture<'a, Option<Bc>>,
{
self.poll_commander
.send(PollCommand::AddHandler(msg_id, Box::new(handler)))
.send(PollCommand::AddHandler(msg_id, Arc::new(handler)))
.await?;
Ok(())
}
@@ -133,7 +136,7 @@ impl BcConnection {
enum PollCommand {
Bc(Box<Result<Bc>>),
AddHandler(u32, MsgHandler),
AddHandler(u32, Arc<MsgHandler>),
RemoveHandler(u32),
AddSubscriber(u16, Sender<Result<Bc>>),
}
@@ -160,7 +163,7 @@ impl Poller {
self.subscribers.num.get(&msg_num),
) {
(Some(occ), _) => {
if let Some(reply) = occ(&response) {
if let Some(reply) = occ(&response).await {
assert!(reply.meta.msg_num == response.meta.msg_num);
self.sink.send(Ok(reply)).await?;
}
@@ -0,0 +1,94 @@
use tokio::sync::mpsc::{channel, Receiver};
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Listen on the flood light update messages and return their XMLs
pub async fn listen_on_flightlight(&self) -> Result<Receiver<FloodlightStatusList>> {
let (tx, rx) = channel(3);
let connection = self.get_connection();
connection
.handle_msg(MSG_ID_FLOODLIGHT_STATUS_LIST, move |bc| {
let tx = tx.clone();
Box::pin(async move {
if let Bc {
meta:
BcMeta {
msg_id: MSG_ID_FLOODLIGHT_STATUS_LIST,
..
},
body:
BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
floodlight_status_list: Some(list),
..
})),
..
}),
} = bc
{
let send_this: FloodlightStatusList = list.clone();
let _ = tx.send(send_this).await;
}
None
})
})
.await?;
Ok(rx)
}
/// Set the floodlight status using the [FloodlightManual] xml
pub async fn set_floodlight_manual(&self, state: bool, duration: u16) -> Result<()> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_FLOODLIGHT_MANUAL,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: Some(BcPayloads::BcXml(BcXml {
floodlight_manual: Some(FloodlightManual {
version: "1".to_string(),
channel_id: self.channel_id,
status: match state {
true => 1,
false => 0,
},
duration,
}),
..Default::default()
})),
}),
};
sub_set.send(get).await?;
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 Floodlight manual state",
})
}
}
}
+14 -12
View File
@@ -10,18 +10,20 @@ impl BcCamera {
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()
}),
Box::pin(async move {
Some(Bc {
meta: BcMeta {
msg_id: MSG_ID_UDP_KEEP_ALIVE,
channel_id: bc.meta.channel_id,
msg_num: bc.meta.msg_num,
stream_type: bc.meta.stream_type,
response_code: 200,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
..Default::default()
}),
})
})
})
.await?;
+50
View File
@@ -0,0 +1,50 @@
use super::{BcCamera, Error, Result};
use crate::bc::{model::*, xml::*};
impl BcCamera {
/// Get the [LinkType] xml which contains the connection status of the camera
///
/// This is the same as `ping()` but with the return type
pub async fn get_linktype(&self) -> Result<LinkType> {
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?;
let get = Bc {
meta: BcMeta {
msg_id: MSG_ID_PING,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: None,
payload: None,
}),
};
sub_get.send(get).await?;
let msg = sub_get.recv().await?;
if msg.meta.response_code != 200 {
return Err(Error::CameraServiceUnavaliable);
}
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
link_type: Some(link_type),
..
})),
..
}) = msg.body
{
Ok(link_type)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "Expected LinkType xml but it was not recieved",
})
}
}
}
+158
View File
@@ -82,4 +82,162 @@ impl BcCamera {
})
}
}
/// Get the [PtzPreset] XML which contains the list of the preset positions known to the camera
pub async fn get_ptz_preset(&self) -> Result<PtzPreset> {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?;
let send = Bc {
meta: BcMeta {
msg_id: MSG_ID_GET_PTZ_PRESET,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: None,
}),
};
sub_set.send(send).await?;
let msg = sub_set.recv().await?;
if let BcBody::ModernMsg(ModernMsg {
payload:
Some(BcPayloads::BcXml(BcXml {
ptz_preset: Some(ptz_preset),
..
})),
..
}) = msg.body
{
Ok(ptz_preset)
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not return a valid PtzPreset xml",
})
}
}
/// Set a PTZ preset.
///
/// The current position will be saved as a preset with the given [preset_id] and [name]
pub async fn set_ptz_preset(&self, preset_id: u8, name: String) -> Result<()> {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?;
let preset = Preset {
id: preset_id,
name: Some(name),
command: "setPos".to_owned(),
};
let send = Bc {
meta: BcMeta {
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: Some(BcPayloads::BcXml(BcXml {
ptz_preset: Some(PtzPreset {
preset_list: PresetList {
preset: vec![preset],
},
..Default::default()
}),
..Default::default()
})),
}),
};
sub_set.send(send).await?;
let msg = sub_set.recv().await?;
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not accept the PtzPreset xml",
})
}
}
/// The camera will attempt to move to the preset with the given ID.
pub async fn moveto_ptz_preset(&self, preset_id: u8) -> Result<()> {
self.has_ability_rw("control").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_set = connection.subscribe(msg_num).await?;
let preset = Preset {
id: preset_id,
name: None,
command: "toPos".to_owned(),
};
let send = Bc {
meta: BcMeta {
msg_id: MSG_ID_PTZ_CONTROL_PRESET,
channel_id: self.channel_id,
msg_num,
response_code: 0,
stream_type: 0,
class: 0x6414,
},
body: BcBody::ModernMsg(ModernMsg {
extension: Some(Extension {
channel_id: Some(self.channel_id),
..Default::default()
}),
payload: Some(BcPayloads::BcXml(BcXml {
ptz_preset: Some(PtzPreset {
preset_list: PresetList {
preset: vec![preset],
},
..Default::default()
}),
..Default::default()
})),
}),
};
sub_set.send(send).await?;
let msg = sub_set.recv().await?;
if let BcMeta {
response_code: 200, ..
} = msg.meta
{
Ok(())
} else {
Err(Error::UnintelligibleReply {
reply: std::sync::Arc::new(Box::new(msg)),
why: "The camera did not accept the PtzPreset xml",
})
}
}
}
+1
View File
@@ -88,6 +88,7 @@ local message_types = {
[15]="<FileInfoList>",
[16]="<FileInfoList>",
[18]="<PtzControl>",
[19]="<PtzPreset>",
[23]="Reboot",
[25]="<VideoInput> (write)",
[26]="<VideoInput>", -- <InputAdvanceCfg>
+69 -1
View File
@@ -355,6 +355,10 @@ Message have zero to two payloads.
</body>
```
- **Notes** : The known movement commands are `"left"`, `"right"`, `"up"`, `"down"`, `"leftUp"`,
`"leftDown"`, `"rightUp"`, `"rightDown"` and `"stop"` although the diagonal movement
does not seem to work.
- Camera
- Header
@@ -363,6 +367,45 @@ Message have zero to two payloads.
|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------|
| 0a bc de f0 | 00 00 00 12 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
- 19: `<PtzPreset>`
- Client
- Header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|--------------|-------------|----------------|-------------------|-------------------|---------------|---------------|
| 0a bc de f0 | 00 00 00 13 | 00 00 01 44 | 1e 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
- Payload
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<PtzPreset version="1.1">
<channelId>0</channelId>
<presetList>
<preset>
<id>0</id>
<command>setPos</command>
<name>Test</name>
</preset>
</presetList>
</PtzPreset>
</body>
```
- **Notes** : The known values for command are `"setPos"` and `"toPos"`
- Camera
- Header
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|--------------|-------------|----------------|-------------------|-------------------|---------------|---------------|
| 0a bc de f0 | 00 00 00 13 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
- 23: `Reboot`
- Client
@@ -1612,6 +1655,8 @@ Message have zero to two payloads.
- Payload
If no SD Card:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
@@ -1619,6 +1664,24 @@ Message have zero to two payloads.
</body>
```
If there is a SD Card
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<body>
<HddInfoList version="1.1">
<HddInfo>
<number>0</number>
<capacity>30</capacity>
<format>1</format>
<mount>1</mount>
<remainSize>29</remainSize>
<remainSizeM>551</remainSizeM>
</HddInfo>
</HddInfoList>
</body>
```
- 104: `<SystemGeneral>`
- Client
@@ -1987,7 +2050,12 @@ Message have zero to two payloads.
<body>
<PtzPreset version="1.1">
<channelId>0</channelId>
<presetList />
<presetList>
<preset>
<id>0</id>
<name>Test</name>
</preset>
</presetList>
</PtzPreset>
</body>
```
+1
View File
@@ -21,6 +21,7 @@ pub enum Command {
StatusLight(super::statusled::Opt),
Reboot(super::reboot::Opt),
Pir(super::pir::Opt),
Ptz(super::ptz::Opt),
Talk(super::talk::Opt),
Mqtt(super::mqtt::Opt),
Image(super::image::Opt),
+2 -2
View File
@@ -104,7 +104,7 @@ pub(crate) struct CameraConfig {
pub(crate) update_time: bool,
#[validate(range(
min = 10,
min = 0,
max = 500,
message = "Invalid buffer size",
code = "buffer_size"
@@ -260,7 +260,7 @@ fn default_smoothing() -> bool {
}
fn default_buffer_size() -> usize {
100
25
}
pub(crate) static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
+4
View File
@@ -34,6 +34,7 @@ mod config;
mod image;
mod mqtt;
mod pir;
mod ptz;
mod reboot;
mod rtsp;
mod statusled;
@@ -102,6 +103,9 @@ async fn main() -> Result<()> {
Some(Command::Pir(opts)) => {
pir::main(opts, config).await?;
}
Some(Command::Ptz(opts)) => {
ptz::main(opts, config).await?;
}
Some(Command::Talk(opts)) => {
talk::main(opts, config).await?;
}
+161 -23
View File
@@ -1,6 +1,7 @@
use crate::config::CameraConfig;
use crate::utils::AddressOrUid;
use anyhow::{anyhow, Context, Result};
use futures::stream::StreamExt;
use log::*;
use neolink_core::bc_protocol::{
BcCamera, Direction as BcDirection, Error as BcError, LightState, MaxEncryption, MotionStatus,
@@ -9,17 +10,17 @@ use std::sync::Arc;
use tokio::{
sync::mpsc::{channel, Receiver, Sender},
task::JoinSet,
time::sleep,
time::{interval, sleep, Duration},
};
use core::time::Duration;
#[derive(Debug, Copy, Clone)]
#[derive(Debug, Clone)]
pub(crate) enum Messages {
Login,
MotionStop,
MotionStart,
Reboot,
FloodlightOn,
FloodlightOff,
StatusLedOn,
StatusLedOff,
IRLedOn,
@@ -30,6 +31,9 @@ pub(crate) enum Messages {
PIROff,
PIRQuery,
Ptz(Direction),
Preset(u8),
PresetAssign(u8, String),
PresetQuery,
}
#[derive(Debug, Copy, Clone)]
@@ -203,6 +207,15 @@ impl EventCamThread {
camera: arc_cam.clone(),
};
let mut flight_thread = FloodlightThread {
tx: self.tx.clone(),
camera: arc_cam.clone(),
};
let mut keepalive_thread = KeepaliveThread {
camera: arc_cam.clone(),
};
let mut message_handler = MessageHandler {
rx: &mut self.rx,
camera: arc_cam,
@@ -221,6 +234,30 @@ impl EventCamThread {
Ok(())
}
},
val = async {
debug!("{}: Starting Pings", camera_config.name);
keepalive_thread.run().await
} => {
if let Err(e) = val {
debug!("Ping thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on Ping thread");
Ok(())
}
},
val = async {
info!("{}: Listening to FloodLight Status", camera_config.name);
flight_thread.run().await
} => {
if let Err(e) = val {
error!("FloodLight thread aborted: {:?}", e);
Err(e)
} else {
debug!("Normal finish on FloodLight thread");
Ok(())
}
},
val = async {
info!("{}: Setting up camera actions", camera_config.name);
message_handler.listen().await
@@ -272,6 +309,47 @@ impl MotionThread {
}
}
struct FloodlightThread {
tx: Sender<Messages>,
camera: Arc<BcCamera>,
}
impl FloodlightThread {
async fn run(&mut self) -> Result<()> {
let mut reciever =
tokio_stream::wrappers::ReceiverStream::new(self.camera.listen_on_flightlight().await?);
while let Some(flights) = reciever.next().await {
for flight in flights.floodlight_status_list.iter() {
if flight.status == 0 {
self.tx.send(Messages::FloodlightOff).await?;
} else {
self.tx.send(Messages::FloodlightOn).await?;
}
}
}
Ok(())
}
}
struct KeepaliveThread {
camera: Arc<BcCamera>,
}
impl KeepaliveThread {
async fn run(&mut self) -> Result<()> {
let mut interval =
tokio_stream::wrappers::IntervalStream::new(interval(Duration::from_secs(5)));
while let Some(_update) = interval.next().await {
if self.camera.ping().await.is_err() {
break;
}
}
futures::pending!(); // Never actually finish, has to be aborted
Ok(())
}
}
struct MessageHandler<'a> {
rx: &'a mut Receiver<ToCamera>,
camera: Arc<BcCamera>,
@@ -297,6 +375,30 @@ impl<'a> MessageHandler<'a> {
"OK".to_string()
}
}
Messages::FloodlightOn => {
let res = self.camera.set_floodlight_manual(true, 180).await;
if res.is_err() {
error = Some(format!(
"Failed to turn on the floodlight light: {:?}",
res.err()
));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::FloodlightOff => {
let res = self.camera.set_floodlight_manual(false, 180).await;
if res.is_err() {
error = Some(format!(
"Failed to turn off the floodlight light: {:?}",
res.err()
));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::StatusLedOn => {
if let Err(e) = self.camera.led_light_set(true).await {
error =
@@ -411,27 +513,23 @@ impl<'a> MessageHandler<'a> {
}
}
Messages::Ptz(direction) => {
let (bc_direction, amount, seconds) = match direction {
Direction::Up(amount, seconds) => {
(BcDirection::Up, amount, seconds)
let (bc_direction, speed, seconds) = match direction {
Direction::Up(speed, seconds) => (BcDirection::Up, speed, seconds),
Direction::Down(speed, seconds) => {
(BcDirection::Down, speed, seconds)
}
Direction::Down(amount, seconds) => {
(BcDirection::Down, amount, seconds)
Direction::Left(speed, seconds) => {
(BcDirection::Left, speed, seconds)
}
Direction::Left(amount, seconds) => {
(BcDirection::Left, amount, seconds)
Direction::Right(speed, seconds) => {
(BcDirection::Right, speed, seconds)
}
Direction::Right(amount, seconds) => {
(BcDirection::Right, amount, seconds)
}
Direction::In(amount, seconds) => {
(BcDirection::In, amount, seconds)
}
Direction::Out(amount, seconds) => {
(BcDirection::Out, amount, seconds)
Direction::In(speed, seconds) => (BcDirection::In, speed, seconds),
Direction::Out(speed, seconds) => {
(BcDirection::Out, speed, seconds)
}
};
if let Err(e) = self.camera.send_ptz(bc_direction, amount).await {
if let Err(e) = self.camera.send_ptz(bc_direction, speed).await {
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
@@ -439,9 +537,7 @@ impl<'a> MessageHandler<'a> {
sleep(Duration::from_secs_f32(seconds)).await;
// note that amount is not used in the stop command
if let Err(e) =
self.camera.send_ptz(BcDirection::Stop, amount).await
{
if let Err(e) = self.camera.send_ptz(BcDirection::Stop, 0.0).await {
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
@@ -449,6 +545,48 @@ impl<'a> MessageHandler<'a> {
}
}
}
Messages::Preset(id) => {
if let Err(e) = self.camera.moveto_ptz_preset(id).await {
error = Some(format!("Failed to send PTZ preset: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::PresetAssign(id, name) => {
if let Err(e) = self.camera.set_ptz_preset(id, name).await {
error = Some(format!("Failed to send PTZ preset: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
Messages::PresetQuery => match self.camera.get_ptz_preset().await {
Err(e) => {
error!("Failed to get PTZ preset status: {:?}", e);
"FAIL".to_string()
}
Ok(ptz_info) => {
let bytes_res = yaserde::ser::serialize_with_writer(
&ptz_info,
vec![],
&Default::default(),
);
match bytes_res {
Ok(bytes) => match String::from_utf8(bytes) {
Ok(str) => str,
Err(_) => {
error!("Failed to encode PTZ preset status");
"FAIL".to_string()
}
},
Err(_) => {
error!("Failed to serialise PTZ preset status");
"FAIL".to_string()
}
}
}
},
_ => "UNKNOWN COMMAND".to_string(),
};
if let Some(replier) = replier {
+104 -7
View File
@@ -14,6 +14,8 @@
/// - `/control/ir [on|off|auto]` Turn IR lights on/off or automatically via light detection
/// - `/control/reboot` Reboot the camera
/// - `/control/ptz` [up|down|left|right|in|out] (amount) Control the PTZ movements, amount defaults to 32.0
/// - `/control/ptz/preset` [id] Move the camera to a known preset
/// - `/control/ptz/assign` [id] [name] Assign the current ptz position to an ID and name
///
/// Status Messages:
///
@@ -21,11 +23,13 @@
/// `/status disconnected` Sent when the camera goes offline
/// `/status/battery` Sent in reply to a `/query/battery`
/// `/status/pir` Sent in reply to a `/query/pir`
/// `/status/ptz/preset` Sent in reply to a `/query/ptz/preset`
///
/// Query Messages:
///
/// `/query/battery` Request that the camera reports its battery level
/// `/query/pir` Request that the camera reports its pir status
/// `/query/ptz/preset` Request that the camera reports the PTZ presets
///
///
/// # Usage
@@ -167,6 +171,28 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
format!("Failed to post connect over MQTT for {}", camera_name)
})?;
}
Messages::FloodlightOn => {
mqtt_sender_cam
.send_message("status/floodlight", "on", true)
.await
.with_context(|| {
format!(
"Failed to publish gloodlight on over MQTT for {}",
camera_name
)
})?;
}
Messages::FloodlightOff => {
mqtt_sender_cam
.send_message("status/floodlight", "off", true)
.await
.with_context(|| {
format!(
"Failed to publish gloodlight off over MQTT for {}",
camera_name
)
})?;
}
Messages::MotionStop => {
mqtt_sender_cam
.send_message("status/motion", "off", true)
@@ -214,6 +240,28 @@ async fn handle_mqtt_message(
} => {
// Do nothing for the success/fail replies
}
MqttReplyRef {
topic: "control/floodlight",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::FloodlightOn)
.await
.with_context(|| "Failed to set camera status light on")?,
);
}
MqttReplyRef {
topic: "control/floodlight",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::FloodlightOff)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/led",
message: "on",
@@ -288,9 +336,10 @@ async fn handle_mqtt_message(
let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() {
// Target amount to move
let speed = 32f32;
let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() {
let seconds = amount / 32f32;
let seconds = amount / speed;
// range checking on seconds so that you can't sleep for 3.4E+38 seconds
match seconds {
x if (0.0..10.0).contains(&x) => seconds,
@@ -301,12 +350,12 @@ async fn handle_mqtt_message(
};
let direction = match direction_txt {
"up" => Direction::Up(amount, seconds),
"down" => Direction::Down(amount, seconds),
"left" => Direction::Left(amount, seconds),
"right" => Direction::Right(amount, seconds),
"in" => Direction::In(amount, seconds),
"out" => Direction::Out(amount, seconds),
"up" => Direction::Up(speed, seconds),
"down" => Direction::Down(speed, seconds),
"left" => Direction::Left(speed, seconds),
"right" => Direction::Right(speed, seconds),
"in" => Direction::In(speed, seconds),
"out" => Direction::Out(speed, seconds),
_ => {
error!("Unrecognized PTZ direction \"{}\"", direction_txt);
return Ok(());
@@ -325,6 +374,42 @@ async fn handle_mqtt_message(
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
}
}
MqttReplyRef {
topic: "control/ptz/preset",
message,
} => {
if let Ok(id) = message.parse::<u8>() {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Preset(id))
.await
.with_context(|| "Failed to send PTZ preset")?,
);
} else {
error!("PTZ preset was not a valid number");
}
}
MqttReplyRef {
topic: "control/ptz/assign",
message,
} => {
let mut words = message.split_whitespace();
let id = words.next();
let name = words.next();
if let (Some(Ok(id)), Some(name)) = (id.map(|id| id.parse::<u8>()), name) {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PresetAssign(id, name.to_owned()))
.await
.with_context(|| "Failed to send PTZ preset assign")?,
);
} else if let (Some(Err(_)), _) = (id.map(|id| id.parse::<u8>()), name) {
error!("PTZ preset was not a valid number");
} else if let (_, None) = (id.map(|id| id.parse::<u8>()), name) {
error!("PTZ preset was not given a name");
}
}
MqttReplyRef {
topic: "control/pir",
message: "on",
@@ -370,6 +455,18 @@ async fn handle_mqtt_message(
);
reply_topic = Some("status/pir");
}
MqttReplyRef {
topic: "query/ptz/preset",
..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PresetQuery)
.await
.with_context(|| "Failed to get prz preset status")?,
);
reply_topic = Some("status/ptz/preset");
}
_ => {}
}
if let Some(reply) = reply {
+10 -6
View File
@@ -264,12 +264,16 @@ impl Mqtt {
impl Drop for Mqtt {
fn drop(&mut self) {
if let Some(drop_message) = self.drop_message.as_ref() {
if self
.get_sender()
.try_send_message(&drop_message.topic, &drop_message.message, true)
.is_err()
{
error!("Failed to send offline message to mqtt");
let res = self.get_sender().try_send_message(
&drop_message.topic,
&drop_message.message,
true,
);
if res.is_err() {
error!(
"Failed to send offline message to mqtt: {:?}. Is the MQTT topic name valid?",
res.err().unwrap()
);
}
}
self.set.abort_all();
+40
View File
@@ -0,0 +1,40 @@
use clap::Parser;
#[derive(clap::ValueEnum, Clone, Debug)]
pub enum CmdDirection {
Left,
Right,
Up,
Down,
In,
Out,
Stop,
}
/// The ptz command will control the positioning of the camera
#[derive(Parser, Debug)]
pub struct Opt {
/// The name of the camera to change the lights of. Must be a name in the config
pub camera: String,
#[command(subcommand)]
pub cmd: PtzCommand,
}
#[derive(Parser, Debug)]
pub enum PtzCommand {
/// Move to a stored preset
Preset { preset_id: Option<u8> },
/// Assign the current position to a preset with a given name
Assign { preset_id: u8, name: String },
/// Performs a movement in the given direction
Control {
/// The amount to move
amount: u32,
/// The direction command
#[clap(value_enum)]
command: CmdDirection,
/// The speed to move at
speed: Option<u32>,
},
}
+94
View File
@@ -0,0 +1,94 @@
///
/// # Neolink PTZ Control
///
/// This module handles the controls of the PTZ commands
///
/// # Usage
///
/// ```bash
/// # Rotate left by 32
/// neolink ptz --config=config.toml CameraName control 32 left
/// # Rotate left by 32 at speed 10 (speed not supported on most camera)
/// neolink ptz --config=config.toml CameraName control 32 left 10
/// # Print the list of preset positions
/// neolink ptz --config=config.toml CameraName preset
/// # Move the camera to preset ID 0
/// neolink ptz --config=config.toml CameraName preset 0
/// # Save the current position as preset ID 0 with name PresetName
/// neolink ptz --config=config.toml CameraName assign 0 PresetName
/// ```
///
use anyhow::{Context, Result};
use tokio::time::{sleep, Duration};
mod cmdline;
use super::config::Config;
use crate::ptz::cmdline::CmdDirection;
use crate::ptz::cmdline::PtzCommand;
use crate::utils::find_and_connect;
pub(crate) use cmdline::Opt;
use neolink_core::bc_protocol::Direction;
/// Entry point for the ptz subcommand
///
/// Opt is the command line options
pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
let camera = find_and_connect(&config, &opt.camera).await?;
match opt.cmd {
PtzCommand::Preset { preset_id } => {
if let Some(preset_id) = preset_id {
camera
.moveto_ptz_preset(preset_id)
.await
.context("Unable to set PTZ preset")
.expect("TODO: panic message");
} else {
let preset_list = camera
.get_ptz_preset()
.await
.context("Unable to get PTZ presets")?;
println!("Available presets:\nID Name");
for preset in preset_list.preset_list.preset {
println!("{:<2} {:?}", preset.id, preset.name);
}
}
}
PtzCommand::Assign { preset_id, name } => {
camera
.set_ptz_preset(preset_id, name)
.await
.context("Unable to set PTZ preset")
.expect("TODO: panic message");
}
PtzCommand::Control {
amount,
command,
speed,
} => {
let direction = match command {
CmdDirection::Left => Direction::Left,
CmdDirection::Right => Direction::Right,
CmdDirection::Up => Direction::Up,
CmdDirection::Down => Direction::Down,
CmdDirection::In => Direction::In,
CmdDirection::Out => Direction::Out,
CmdDirection::Stop => Direction::Stop,
};
let speed = speed.unwrap_or(32) as f32;
let seconds = amount as f32 / speed;
let duration = Duration::from_secs_f32(seconds);
camera
.send_ptz(direction, speed)
.await
.context("Unable to execute PTZ move command")?;
sleep(duration).await;
camera
.send_ptz(Direction::Stop, 0_f32)
.await
.context("Unable to execute PTZ move command")?;
}
};
Ok(())
}
+48 -130
View File
@@ -43,6 +43,12 @@ struct NeoBuffer {
max_size: usize,
}
/// The historical buffer is how much we keep extra after live.
///
/// This represents the upper limit we keep in storage after live
/// while waiting for the time to play arrives
const HISTORICAL_BUFFER_SIZE: usize = 100;
impl NeoBuffer {
fn new(max_size: usize) -> Self {
Self {
@@ -98,65 +104,21 @@ impl NeoBuffer {
last.data.push(media);
}
while self.buf.len() > self.max_size {
while self.buf.len() > self.max_size + HISTORICAL_BUFFER_SIZE {
if self.buf.pop_front().is_none() {
break;
}
}
}
fn prep_size(&self) -> usize {
self.max_size * 2 / 3
}
fn live_size(&self) -> usize {
self.max_size / 3
self.max_size
}
pub(crate) fn ready(&self) -> bool {
self.buf.len() > self.prep_size()
self.buf.len() >= self.live_size() + HISTORICAL_BUFFER_SIZE / 2
}
pub(crate) fn ready_play(&self) -> bool {
self.buf.len() > self.live_size()
}
// fn last_iframe_time(&self) -> Option<FrameTime> {
// let (fronts, backs) = self.buf.as_slices();
// backs
// .iter()
// .rev()
// .chain(&mut fronts.iter().rev())
// .flat_map(|frame| match frame {
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
// _ => None,
// })
// .next()
// .map(|i| i as FrameTime)
// }
// fn first_iframe_time(&self) -> Option<FrameTime> {
// let (fronts, backs) = self.buf.as_slices();
// fronts
// .iter()
// .chain(&mut backs.iter())
// .flat_map(|frame| match frame {
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
// _ => None,
// })
// .next()
// .map(|i| i as FrameTime)
// }
// fn start_time(&self) -> Option<FrameTime> {
// let (fronts, backs) = self.buf.as_slices();
// fronts
// .iter()
// .chain(&mut backs.iter())
// .map(|frame| frame.time)
// .next()
// }
fn end_time(&self) -> Option<FrameTime> {
let (fronts, backs) = self.buf.as_slices();
backs
@@ -166,35 +128,6 @@ impl NeoBuffer {
.map(|frame| frame.time)
.next()
}
// fn min_time(&self) -> Option<FrameTime> {
// let (fronts, backs) = self.buf.as_slices();
// fronts
// .iter()
// .chain(&mut backs.iter())
// .flat_map(|frame| match Arc::as_ref(frame) {
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
// BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => Some(*microseconds),
// _ => None,
// })
// .min()
// .map(|i| i as FrameTime)
// }
// fn max_time(&self) -> Option<FrameTime> {
// let (fronts, backs) = self.buf.as_slices();
// backs
// .iter()
// .rev()
// .chain(&mut fronts.iter().rev())
// .flat_map(|frame| match Arc::as_ref(frame) {
// BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => Some(*microseconds),
// BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => Some(*microseconds),
// _ => None,
// })
// .max()
// .map(|i| i as FrameTime)
// }
}
pub(super) struct NeoMediaSenders {
@@ -288,24 +221,30 @@ impl NeoMediaSenders {
async fn handle_new_data(&mut self, data: BcMedia) -> AnyResult<()> {
// trace!("Handle new data");
self.update_mediatypes(&data).await;
let time = match &data {
BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => *microseconds as FrameTime,
BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => *microseconds as FrameTime,
_ => self.buffer.end_time().unwrap_or(0),
};
let data = Arc::new(data);
let end_time = self.buffer.end_time();
let frame_time = time;
// Ocassionally the camera will make a jump in timestamps of about 15s (on sub 9s on main)
// This could mean that it runs on some fixed sized buffer
let frame_time = match data.as_ref() {
BcMedia::Iframe(BcMediaIframe { microseconds, .. }) => *microseconds as FrameTime,
BcMedia::Pframe(BcMediaPframe { microseconds, .. }) => *microseconds as FrameTime,
_ => self.buffer.end_time().unwrap_or(0),
};
// If there is a jump in the time stamps for any reason
// (including a resume from a pause)
// Then we stitch the old and new frames together without
// waiting for the time to elapse
if let Some(end_time) = end_time {
// An approximate fps
let delta_frame = (self.buffer.buf.back().unwrap().time
- self.buffer.buf.front().unwrap().time)
/ self.buffer.buf.len() as i64;
// Shift current frames backwards from the new start - approx fps
let delta_time = frame_time - end_time - delta_frame;
let delta_duration = Duration::from_micros(delta_time.unsigned_abs());
// If that shift >1s then we stitch it together
if delta_duration > Duration::from_secs(1) {
trace!(
"Reschedule buffer due to jump: {:?}, Prev: {}, New: {}",
@@ -329,6 +268,8 @@ impl NeoMediaSenders {
for frame in client.buffer.buf.iter_mut() {
frame.time = frame.time.saturating_add(delta_time);
}
// We also move the start time up so that the new frames will play
// with the stiching
client.start_time.mod_value(delta_time as f64);
}
}
@@ -465,9 +406,6 @@ impl NeoMediaSenders {
},
FactoryCommand::JumpToLive => {
for client in self.client_data.values_mut() {
// Set them into the non init state
// This will make them wait for the
// buffer to be enough then jump to live
let _ = client.jump_to_live().await;
}
},
@@ -512,7 +450,6 @@ pub(super) struct NeoMediaSender {
command_sender: Sender<NeoMediaSenderCommand>,
inited: bool,
playing: bool,
refilling: bool,
use_smoothing: bool,
}
@@ -529,8 +466,7 @@ impl NeoMediaSender {
command_sender: tx,
inited: false,
playing: true,
refilling: false,
use_smoothing,
use_smoothing: use_smoothing && buffer_size > 0,
}
}
@@ -553,6 +489,10 @@ impl NeoMediaSender {
fn target_live_for(buffer: &NeoBuffer) -> Option<FrameTime> {
let target_idx = buffer.live_size();
if target_idx == 0 {
// No buffer needed grab the last
return buffer.buf.back().map(|item| item.time);
}
let stamps = buffer.buf.iter().map(|item| item.time).collect::<Vec<_>>();
if stamps.len() >= target_idx {
@@ -568,12 +508,7 @@ impl NeoMediaSender {
}
} else {
trace!("Not enough timestamps for target live: {:?}", stamps);
if let Some(st) = stamps.first() {
trace!("Setting to 1s behind first frame in buffer");
Some(st - Duration::from_secs(1).as_micros() as FrameTime)
} else {
None
}
None
}
}
@@ -687,13 +622,13 @@ impl NeoMediaSender {
self.start_time.reset_to(target_time as f64);
// Send preprocess now
self.send_buffers(preprocess.as_slice()).await?;
trace!("Preprocessed");
self.send_buffers(preprocess.as_slice(), true).await?;
trace!("Preprocessed: {}", preprocess.len());
// Send these later
for frame in buffer.drain(..) {
self.buffer.buf.push_back(frame);
}
trace!("Buffer filled");
trace!("Buffer filled: {}", self.buffer.buf.len());
self.jump_to_live().await?;
} else {
@@ -737,22 +672,9 @@ impl NeoMediaSender {
}
async fn update(&mut self) -> AnyResult<()> {
if self.buffer.buf.len() >= self.buffer.max_size * 9 / 10 {
debug!("Buffer overfull");
self.jump_to_live().await?;
}
if self.refilling && self.buffer.ready_play() {
self.refilling = false;
self.jump_to_live().await?;
} else if self.refilling {
trace!(
"Refilling: {}/{} ({:.2}%)",
self.buffer.buf.len(),
self.buffer.live_size(),
self.buffer.buf.len() as f32 / (self.buffer.live_size()) as f32 * 100.0
);
} else if !self.refilling && self.inited && self.playing {
if self.inited && self.playing {
self.update_starttime().await?;
let ignore_stamps = self.buffer.live_size() == 0;
// Check app src is live
if !self
.vid
@@ -763,17 +685,6 @@ impl NeoMediaSender {
return Err(anyhow!("Vid src is closed"));
}
// Check if buffers are ok
if self.buffer.buf.len() <= self.buffer.max_size / 10 {
warn!(
"Buffer exhausted. Not enough data from Camera. Pausing RTSP until refilled."
);
info!("Try reducing your Max Bitrate using the offical app");
self.refilling = true;
} else {
trace!("Buffer size: {}", self.buffer.buf.len());
}
// Send buffers
let mut buffers = vec![];
if let Some(buftime) = self.get_buftime() {
@@ -785,7 +696,6 @@ impl NeoMediaSender {
.map(|data| data.time <= buftime)
.unwrap_or(false)
{
tokio::task::yield_now().await;
match self.buffer.buf.pop_front() {
Some(frame) => {
buffers.push(frame);
@@ -797,13 +707,13 @@ impl NeoMediaSender {
tokio::task::yield_now().await;
// collect certain frames
self.send_buffers(&buffers).await?;
self.send_buffers(&buffers, ignore_stamps).await?;
}
Ok(())
}
async fn send_buffers(&mut self, medias: &[Stamped]) -> AnyResult<()> {
async fn send_buffers(&mut self, medias: &[Stamped], ignore_stamps: bool) -> AnyResult<()> {
if medias.is_empty() {
return Ok(());
}
@@ -852,7 +762,10 @@ impl NeoMediaSender {
let buffers_ref = buffers.get_mut().unwrap();
for (time, buf) in vid_buffers.drain(..) {
tokio::task::yield_now().await;
let runtime = self.buftime_to_runtime(time);
let runtime = match (self.get_runtime(), ignore_stamps) {
(None, _) | (_, false) => self.buftime_to_runtime(time),
(Some(runtime), true) => runtime,
};
trace!(
" - Sending vid frame at time {} ({:?} Expect: {:?})",
time,
@@ -870,6 +783,7 @@ impl NeoMediaSender {
runtime.try_into().unwrap(),
);
gst_buf_mut.set_dts(time);
gst_buf_mut.set_pts(time);
let mut gst_buf_data =
gst_buf_mut.map_writable().unwrap();
gst_buf_data.copy_from_slice(buf.as_slice());
@@ -913,7 +827,10 @@ impl NeoMediaSender {
let buffers_ref = buffers.get_mut().unwrap();
for (time, buf) in aud_buffers.drain(..) {
tokio::task::yield_now().await;
let runtime = self.buftime_to_runtime(time);
let runtime = match (self.get_runtime(), ignore_stamps) {
(None, _) | (_, false) => self.buftime_to_runtime(time),
(Some(runtime), true) => runtime,
};
let gst_buf = {
let mut gst_buf =
@@ -925,6 +842,7 @@ impl NeoMediaSender {
runtime.try_into().unwrap(),
);
gst_buf_mut.set_dts(time);
gst_buf_mut.set_pts(time);
let mut gst_buf_data =
gst_buf_mut.map_writable().unwrap();
gst_buf_data.copy_from_slice(buf.as_slice());
+167 -87
View File
@@ -55,6 +55,8 @@
use anyhow::{anyhow, Context, Result};
use futures::stream::FuturesUnordered;
use log::*;
use neolink_core::bc_protocol::{BcCamera, StreamKind};
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use tokio_stream::StreamExt;
@@ -242,23 +244,153 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
.await;
log::info!("{}: Buffers prepared", name);
let mut active_tags = streaming.shared.get_streams().clone();
let mut motion_pause = false;
loop {
// Wait for error or reason to pause
tokio::select! {
let change = tokio::select! {
v = async {
// Wait for error
streaming.join().await
} => {
info!("Join Pause");
v
// Wait for error
streaming.join().await
}, if ! active_tags.is_empty() => {
info!("{}: Join Pause", name);
Ok(StreamChange::StreamError(v))
},
v = await_change(
streaming.get_camera(),
&streaming.shared,
&rtsp_thread,
&active_tags,
motion_pause,
&name,
), if streaming.shared.get_config().pause.on_motion || streaming.shared.get_config().pause.on_disconnect => {
v.with_context(|| format!("{}: Error updating pause state", name))
.map_err(CameraFailureKind::Retry)
}
}?;
match change {
StreamChange::StreamError(res) => {
res.map_err(CameraFailureKind::Retry)?;
}
StreamChange::MotionStart => {
motion_pause = false;
let inactive_streams = streaming
.shared
.get_streams()
.iter()
.filter(|i| !active_tags.contains(i))
.copied()
.collect::<Vec<_>>();
if streaming.shared.get_config().pause.on_disconnect {
// Pause on client is also on
//
// Only resume clients with active connections
for stream in inactive_streams.iter() {
if rtsp_thread
.get_number_of_clients(streaming.shared.get_tag_for_stream(stream))
.await
.map(|n| n > 0)
.unwrap_or(false)
{
streaming
.start_stream(*stream)
.await
.map_err(CameraFailureKind::Retry)?;
active_tags.insert(*stream);
rtsp_thread
.resume(streaming.shared.get_tag_for_stream(stream))
.await
.map_err(CameraFailureKind::Retry)?;
}
}
} else {
// Pause on client is not on
//
// Resume all
for stream in inactive_streams.iter() {
streaming
.start_stream(*stream)
.await
.map_err(CameraFailureKind::Retry)?;
active_tags.insert(*stream);
rtsp_thread
.resume(streaming.shared.get_tag_for_stream(stream))
.await
.map_err(CameraFailureKind::Retry)?;
}
}
}
StreamChange::MotionStop => {
motion_pause = true;
// Clear all streams
for stream in active_tags.drain() {
rtsp_thread
.pause(streaming.shared.get_tag_for_stream(&stream))
.await
.map_err(CameraFailureKind::Retry)?;
streaming
.stop_stream(stream)
.await
.map_err(CameraFailureKind::Retry)?;
}
}
StreamChange::ClientStart(stream) => {
if !streaming.shared.get_config().pause.on_motion || !motion_pause {
streaming
.start_stream(stream)
.await
.map_err(CameraFailureKind::Retry)?;
active_tags.insert(stream);
rtsp_thread
.resume(streaming.shared.get_tag_for_stream(&stream))
.await
.map_err(CameraFailureKind::Retry)?;
}
}
StreamChange::ClientStop(stream) => {
if !streaming.shared.get_config().pause.on_motion || !motion_pause {
rtsp_thread
.pause(streaming.shared.get_tag_for_stream(&stream))
.await
.map_err(CameraFailureKind::Retry)?;
streaming
.stop_stream(stream)
.await
.map_err(CameraFailureKind::Retry)?;
active_tags.remove(&stream);
}
}
}
}
// Ok(())
}
enum StreamChange {
StreamError(Result<()>),
MotionStart,
MotionStop,
ClientStart(StreamKind),
ClientStop(StreamKind),
}
async fn await_change(
camera: &BcCamera,
shared: &Shared,
rtsp_thread: &NeoRtspServer,
active_tags: &HashSet<StreamKind>,
motion_pause: bool,
name: &str,
) -> Result<StreamChange> {
tokio::select! {
v = async {
// Wait for motion stop
let mut motion = streaming.get_camera().listen_on_motion().await?;
motion.await_stop(Duration::from_secs_f64(streaming.get_config().pause.motion_timeout)).await
}, if streaming.get_config().pause.on_motion => {
info!("Motion Pause");
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))
let mut motion = camera.listen_on_motion().await?;
motion.await_stop(Duration::from_secs_f64(shared.get_config().pause.motion_timeout)).await
}, if motion_pause && shared.get_config().pause.on_motion => {
info!("{}: Motion Pause", name);
v.map_err(|e| anyhow!("Error while processing motion messages: {:?}", e))?;
Ok(StreamChange::MotionStop)
},
v = async {
// Wait for client to disconnect
@@ -266,97 +398,45 @@ async fn camera_main(camera: Camera<Disconnected>) -> Result<(), CameraFailureKi
loop {
inter.tick().await;
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
// info!("Num clients: {}", total_clients);
if total_clients == 0 {
return Ok(())
for tag in active_tags.iter() {
if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n == 0).unwrap_or(true) {
return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStop(*tag))
}
}
}
}, if streaming.get_config().pause.on_disconnect => {
info!("Client Pause");
}, if shared.get_config().pause.on_disconnect => {
if let Ok(StreamChange::ClientStop(tag)) = v.as_ref() {
info!("{}: Client Pause:: {:?}", name, tag);
}
v
},
}.with_context(|| format!("{}: Error while streaming", name))
.map_err(CameraFailureKind::Retry)?;
tags.iter()
.map(|tag| rtsp_thread.pause(tag))
.collect::<FuturesUnordered<_>>()
.collect::<Vec<_>>()
.await;
let paused = streaming
.stop()
.await
.with_context(|| format!("{}: Could not stop stream", name))
.map_err(CameraFailureKind::Retry)?;
// Wait for reason to restart
tokio::select! {
v = async {
// Wait for motion start and client for start
let mut motion = paused.get_camera().listen_on_motion().await?;
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
loop {
motion.await_start(Duration::ZERO).await?;
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
if total_clients > 0 {
return Result::<()>::Ok(());
}
inter.tick().await;
}
}, if paused.get_config().pause.on_motion && paused.get_config().pause.on_disconnect => {
info!("Motion and Client Resume");
v.with_context(|| "Error while processing motion/client messages")
},
v = async {
// Wait for motion start
let mut motion = paused.get_camera().listen_on_motion().await?;
let mut motion = camera.listen_on_motion().await?;
motion.await_start(Duration::ZERO).await
}, if paused.get_config().pause.on_motion && !paused.get_config().pause.on_disconnect => {
info!("Motion Resume");
v.with_context(|| "Error while processing motion messages")
}, if ! motion_pause && shared.get_config().pause.on_motion => {
info!("{}: Motion Resume", name);
v.with_context(|| "Error while processing motion messages")?;
Ok(StreamChange::MotionStart)
},
v = async {
// Wait for client to connect
let mut inter = tokio::time::interval(tokio::time::Duration::from_secs_f32(0.01));
let inactive_tags = shared.get_streams().iter().filter(|i| !active_tags.contains(i)).collect::<Vec<_>>();
trace!("inactive_tags: {:?}", inactive_tags);
loop {
inter.tick().await;
let total_clients = tags.iter().map(|tag| rtsp_thread.get_number_of_clients(tag)).collect::<FuturesUnordered<_>>().fold(0usize, |acc, f| acc + f.unwrap_or(0usize)).await;
if total_clients > 0 {
return Ok(())
for tag in inactive_tags.iter() {
if rtsp_thread.get_number_of_clients(shared.get_tag_for_stream(tag)).await.map(|n| n > 0).unwrap_or(false) {
return Result::<_,anyhow::Error>::Ok(StreamChange::ClientStart(**tag))
}
}
}
}, if paused.get_config().pause.on_disconnect && !paused.get_config().pause.on_motion => {
info!("Client Resume");
}, if shared.get_config().pause.on_disconnect => {
if let Ok(StreamChange::ClientStart(tag)) = v.as_ref() {
info!("{}: Client Resume:: {:?}", name, tag);
}
v
},
else => {
// No pause. This means that the stream stopped for some reason
// but not because of an error
info!("Generic Resume");
Ok(())
}
}
.with_context(|| format!("{}: Error while paused", name))
.map_err(CameraFailureKind::Retry)?;
tags.iter()
.map(|tag| rtsp_thread.jump_to_live(tag))
.collect::<FuturesUnordered<_>>()
.collect::<Vec<_>>()
.await;
streaming = paused
.stream()
.await
.with_context(|| format!("{}: Could not start stream", name))
.map_err(CameraFailureKind::Retry)?;
tags.iter()
.map(|tag| rtsp_thread.resume(tag))
.collect::<FuturesUnordered<_>>()
.collect::<Vec<_>>()
.await;
}
}.with_context(|| format!("{}: Error while streaming", name))
}
+1
View File
@@ -15,6 +15,7 @@ impl<T> Camera<T> {
self.shared.config.name.clone()
}
#[allow(dead_code)]
pub(crate) fn get_config(&self) -> &CameraConfig {
&self.shared.config
}
+1
View File
@@ -93,6 +93,7 @@ impl Camera<LoggedIn> {
Ok(())
}
#[allow(dead_code)]
pub(crate) fn get_camera(&self) -> &BcCamera {
&self.state.camera
}
+6
View File
@@ -102,6 +102,12 @@ impl Shared {
.map(|k| self.get_tag_for_stream(k))
.collect()
}
pub(crate) fn get_streams(&self) -> &HashSet<Stream> {
&self.streams
}
pub(crate) fn get_config(&self) -> &CameraConfig {
&self.config
}
pub(crate) fn get_tag_for_stream(&self, stream: &Stream) -> String {
format!("{}::{:?}", self.config.name, stream)
}
+100 -67
View File
@@ -2,11 +2,16 @@
//
// Data is streamed into a gstreamer source
use std::collections::HashMap;
use futures::stream::{FuturesUnordered, StreamExt};
use anyhow::{anyhow, Context, Error, Result};
use log::*;
use neolink_core::bcmedia::model::BcMedia;
use tokio::sync::RwLock;
use tokio::task::JoinHandle;
use tokio::time::{timeout, Duration};
use tokio::{sync::RwLock, task::JoinSet};
use neolink_core::bc_protocol::{BcCamera, StreamKind as Stream};
@@ -15,7 +20,7 @@ use crate::rtsp::gst::FactoryCommand;
pub(crate) struct Streaming {
pub(crate) camera: BcCamera,
set: RwLock<JoinSet<Result<()>>>,
stream_handles: RwLock<HashMap<Stream, JoinHandle<Result<()>>>>,
}
impl Camera<Streaming> {
@@ -23,74 +28,98 @@ impl Camera<Streaming> {
// Create new gst outputs
//
// Otherwise use those already present
let mut set: JoinSet<Result<()>> = Default::default();
for stream in loggedin.shared.streams.iter() {
let tag = loggedin.shared.get_tag_for_stream(stream);
let sender = loggedin
.shared
.rtsp
.get_sender(&tag)
.await
.ok_or_else(|| anyhow!("Stream has not been created"))?;
let stream_display_name = match stream {
Stream::Main => "Main Stream (Clear)",
Stream::Sub => "Sub Stream (Fluent)",
Stream::Extern => "Extern Stream (Balanced)",
};
info!(
"{}: Starting video stream {}",
&loggedin.shared.config.name, stream_display_name
);
let stream_thead = *stream;
let strict_thread = loggedin.shared.config.strict;
let tag_thread = tag.clone();
let mut stream_data = loggedin
.state
.camera
.start_video(stream_thead, 0, strict_thread)
.await?;
set.spawn(async move {
loop {
tokio::task::yield_now().await;
// debug!("Straming: Get");
let data = timeout(Duration::from_secs(15), stream_data.get_data())
.await
.with_context(|| "Timed out waiting for new Media Frame")??;
// debug!("Straming: Got");
match &data {
Ok(BcMedia::InfoV1(_)) => trace!("{}: - InfoV1", &tag_thread),
Ok(BcMedia::InfoV2(_)) => trace!("{}: - InfoV2", &tag_thread),
Ok(BcMedia::Iframe(_)) => trace!("{}: - Iframe", &tag_thread),
Ok(BcMedia::Pframe(_)) => trace!("{}: - Pframe", &tag_thread),
Ok(BcMedia::Aac(_)) => trace!("{}: - Aac", &tag_thread),
Ok(BcMedia::Adpcm(_)) => trace!("{}: - Adpcm", &tag_thread),
Err(_) => trace!(" - Error"),
}
// debug!("Straming: Send");
timeout(
Duration::from_secs(15),
sender.send(FactoryCommand::BcMedia(data?)),
)
.await
.with_context(|| "Timed out waiting to send Media Frame")??;
// debug!("Straming: Sent");
}
});
}
Ok(Camera {
let mut me = Camera {
shared: loggedin.shared,
state: Streaming {
camera: loggedin.state.camera,
set: RwLock::new(set),
stream_handles: Default::default(),
},
})
};
for stream in me.shared.streams.iter().copied().collect::<Vec<_>>() {
me.start_stream(stream).await?;
}
Ok(me)
}
pub(crate) async fn start_stream(&mut self, stream: Stream) -> Result<()> {
if let Some(handle) = self.state.stream_handles.get_mut().get(&stream) {
if !handle.is_finished() {
return Ok(());
}
}
let tag = self.shared.get_tag_for_stream(&stream);
let sender = self
.shared
.rtsp
.get_sender(&tag)
.await
.ok_or_else(|| anyhow!("Stream has not been created"))?;
let stream_display_name = match stream {
Stream::Main => "Main Stream (Clear)",
Stream::Sub => "Sub Stream (Fluent)",
Stream::Extern => "Extern Stream (Balanced)",
};
info!(
"{}: Starting video stream {}",
&self.shared.config.name, stream_display_name
);
let stream_thead = stream;
let strict_thread = self.shared.config.strict;
let tag_thread = tag.clone();
let mut stream_data = self
.state
.camera
.start_video(stream_thead, 0, strict_thread)
.await?;
let handle = tokio::task::spawn(async move {
loop {
tokio::task::yield_now().await;
// debug!("Straming: Get");
let data = timeout(Duration::from_secs(15), stream_data.get_data())
.await
.with_context(|| "Timed out waiting for new Media Frame")??;
// debug!("Straming: Got");
match &data {
Ok(BcMedia::InfoV1(_)) => trace!("{}: - InfoV1", &tag_thread),
Ok(BcMedia::InfoV2(_)) => trace!("{}: - InfoV2", &tag_thread),
Ok(BcMedia::Iframe(_)) => trace!("{}: - Iframe", &tag_thread),
Ok(BcMedia::Pframe(_)) => trace!("{}: - Pframe", &tag_thread),
Ok(BcMedia::Aac(_)) => trace!("{}: - Aac", &tag_thread),
Ok(BcMedia::Adpcm(_)) => trace!("{}: - Adpcm", &tag_thread),
Err(_) => trace!(" - Error"),
}
// debug!("Straming: Send");
timeout(
Duration::from_secs(15),
sender.send(FactoryCommand::BcMedia(data?)),
)
.await
.with_context(|| "Timed out waiting to send Media Frame")??;
// debug!("Straming: Sent");
}
});
self.state.stream_handles.get_mut().insert(stream, handle);
Ok(())
}
pub(crate) async fn stop_stream(&mut self, stream: Stream) -> Result<()> {
if let Some(handle) = self.state.stream_handles.get_mut().remove(&stream) {
handle.abort();
}
Ok(())
}
#[allow(dead_code)]
pub(crate) async fn stop(self) -> Result<Camera<LoggedIn>> {
self.state.set.into_inner().abort_all();
self.state
.stream_handles
.into_inner()
.into_values()
.for_each(|h| h.abort());
Ok(Camera {
shared: self.shared,
state: LoggedIn {
@@ -102,15 +131,19 @@ impl Camera<Streaming> {
pub(crate) async fn join(&self) -> Result<()> {
tokio::select! {
v = async {
let mut locked_threads = self.state.set.write().await;
while let Some(res) = locked_threads.join_next().await {
let mut locked_threads = self.state.stream_handles.write().await;
let mut thread_joins = locked_threads.iter_mut().map(|(_, t)| t).collect::<FuturesUnordered::<_>>();
while let Some(res) = thread_joins.next().await {
match res {
Err(e) => {
locked_threads.abort_all();
drop(thread_joins);
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
return Err(e.into());
}
Ok(Err(e)) => {
locked_threads.abort_all();
drop(thread_joins);
locked_threads.iter_mut().for_each(|(_,h)| h.abort());
return Err(e);
}
Ok(Ok(())) => {}