Merge remote-tracking branch 'upstream/master' into feature-ptz-preset

This commit is contained in:
Andrew committed 2023-05-25 17:44:56 +01:00
commit b8dafbb92e
12 files changed
+427 -69

No files matched your search

+4
View File
@@ -57,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 =
+53
View File
@@ -76,6 +76,12 @@ 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>,
@@ -88,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 {
@@ -328,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 {
@@ -650,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",
})
}
}
}