Added an ability support check to functions

This commit is contained in:
QuantumEntangledAndy committed 2023-04-04 16:45:16 +07:00
1 parent ca5de6445d
commit 618aafef2c
14 files changed
+144 -2

No files matched your search

+2
View File
@@ -31,6 +31,8 @@ pub const MSG_ID_VERSION: u32 = 80;
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;
/// Will send the talk config for talk back data to follow this msg
+53
View File
@@ -82,6 +82,9 @@ pub struct BcXml {
/// 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>,
}
impl BcXml {
@@ -561,6 +564,56 @@ pub struct BatteryInfo {
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,
}
/// Convience function to return the xml version used throughout the library
pub fn xml_ver() -> String {
"1.1".to_string()
+54 -2
View File
@@ -3,10 +3,15 @@ use futures::stream::StreamExt;
use log::*;
use serde::{Deserialize, Serialize};
use std::net::ToSocketAddrs;
use std::sync::atomic::{AtomicBool, AtomicU16, Ordering};
use std::{
collections::HashMap,
sync::atomic::{AtomicBool, AtomicU16, Ordering},
};
use tokio::sync::RwLock;
use Md5Trunc::*;
mod abilityinfo;
mod battery;
mod connection;
mod credentials;
@@ -40,6 +45,13 @@ 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
///
@@ -50,6 +62,7 @@ pub struct BcCamera {
message_num: AtomicU16,
// Certain commands such as logout require the username/pass in plain text.... why....???
credentials: Credentials,
abilities: RwLock<HashMap<String, ReadKind>>,
}
/// Used to choode the print format of various status messages like battery levels
@@ -334,9 +347,12 @@ impl BcCamera {
channel_id,
logged_in: AtomicBool::new(false),
credentials: Credentials::new(username, passwd),
abilities: Default::default(),
};
me.keepalive().await?;
me.monitor_battery(aux_info_format).await?;
if let Err(e) = me.monitor_battery(aux_info_format).await {
warn!("Could not monitor battery: {:?}", e);
}
Ok(me)
}
@@ -355,6 +371,42 @@ impl BcCamera {
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(),
}),
}
}
}
/// The Baichuan library has a very peculiar behavior where it always zeros the last byte. I
+16
View File
@@ -143,6 +143,22 @@ pub enum Error {
#[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,
},
/// A generic catch all error
#[error(display = "Other error: {}", _0)]
Other(&'static str),
+2
View File
@@ -4,6 +4,7 @@ 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?;
@@ -51,6 +52,7 @@ impl BcCamera {
/// 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();
+3
View File
@@ -164,6 +164,9 @@ impl BcCamera {
}
}
}
// Populate the list of abilities this user has with the camera
self.polulate_abilities().await?;
Ok(device_info)
}
}
+1
View File
@@ -86,6 +86,7 @@ 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();
+2
View File
@@ -4,6 +4,7 @@ use crate::bc::{model::*, xml::*};
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 msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?;
@@ -51,6 +52,7 @@ impl BcCamera {
/// 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?;
+1
View File
@@ -20,6 +20,7 @@ pub enum Direction {
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?;
+1
View File
@@ -4,6 +4,7 @@ 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?;
+2
View File
@@ -74,6 +74,7 @@ impl BcCamera {
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();
@@ -208,6 +209,7 @@ impl BcCamera {
/// 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?;
+4
View File
@@ -14,6 +14,7 @@ impl BcCamera {
/// It is also sent when the request for talk config returns status code 422
///
pub async fn talk_stop(&self) -> Result<()> {
self.has_ability_rw("talk").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
@@ -58,6 +59,7 @@ impl BcCamera {
/// Requests the [`TalkAbility`] xml
///
pub async fn talk_ability(&self) -> Result<TalkAbility> {
self.has_ability_ro("talk").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
let mut sub_get = connection.subscribe(msg_num).await?;
@@ -117,6 +119,7 @@ impl BcCamera {
///
///
pub async fn talk(&self, adpcm: &[u8], talk_config: TalkConfig) -> Result<()> {
self.has_ability_rw("talk").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
@@ -258,6 +261,7 @@ impl BcCamera {
///
///
pub async fn talk_stream(&self, rx: Receiver<Vec<u8>>, talk_config: TalkConfig) -> Result<()> {
self.has_ability_rw("talk").await?;
let connection = self.get_connection();
let msg_num = self.new_message_num();
+2
View File
@@ -11,6 +11,7 @@ impl BcCamera {
/// 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?;
@@ -95,6 +96,7 @@ impl BcCamera {
/// 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?;
+1
View File
@@ -4,6 +4,7 @@ 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?;