Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e05e7844b | ||
|
|
43b62090c8 | ||
|
|
7a66473ab9 | ||
|
|
a30f403dc4 | ||
|
|
76833e6242 | ||
|
|
1518ab24bb |
No files matched your search
@@ -31,7 +31,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-22.04, windows-2022, macos-13, macos-14] # macos-14+ is arm64
|
||||
os: [ubuntu-22.04, windows-2022, macos-12, macos-14] # macos-14+ is arm64
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
name: Checkout onto ${{ runner.os }}
|
||||
@@ -86,7 +86,7 @@ jobs:
|
||||
- if: runner.os == 'macOS'
|
||||
name: Install macOS deps
|
||||
run: |
|
||||
curl -L 'https://gstreamer.freedesktop.org/data/pkg/osx/1.24.11/gstreamer-1.0-devel-1.24.11-universal.pkg' -o "$(pwd)/gstreamer-devel.pkg"
|
||||
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"
|
||||
@@ -366,7 +366,7 @@ jobs:
|
||||
- name: Download Macos
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: release-macos-13
|
||||
name: release-macos-12
|
||||
path: neolink_macos_intel
|
||||
- name: Download Macos arm64
|
||||
uses: actions/download-artifact@v4
|
||||
|
||||
@@ -243,20 +243,6 @@ Status Messages:
|
||||
pir status
|
||||
- `/status/motion` Contains the motion detection alarm status. `on` for motion
|
||||
and `off` for still, only published when `enable_moton` is true in the config
|
||||
- `/status/visitor` Contains the visitor detection status, which occurs when a
|
||||
doorbell is pressed.
|
||||
- `/status/ai` Contains the ai detection status, which occurs when a
|
||||
the camera's internal ai detects something. The value is `person/car/other`
|
||||
- `/status/ai/person` Contains the ai detection status of the last person,
|
||||
which occurs when a the camera's internal ai detects a person.
|
||||
- `/status/ai/car` Contains the ai detection status of the last car, which
|
||||
occurs when a the camera's internal ai detects a car.
|
||||
- `/status/ai/other` Contains the ai detection status from the camera, which
|
||||
occurs when a the camera's internal ai detects something.
|
||||
|
||||
(This is a placeholder until I can fiquire out everything that the camera
|
||||
can detect. If you have list for me please open an issue with it, I don't
|
||||
have a cam with AI to check myself)
|
||||
- `/status/ptz/preset` Sent in reply to a `/query/ptz/preset` an XML encoded
|
||||
version of the PTZ presets
|
||||
- `/status/preview` a base64 encoded camera image updated every 2s. Not
|
||||
@@ -339,14 +325,6 @@ enable_motion = false # motion detection
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
#
|
||||
enable_visitor = false # visitor press for doorbell camera
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
#
|
||||
enable_ai = false # report detected ai by the camera
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
#
|
||||
enable_light = false # flood lights only available on some camera
|
||||
# (limited battery drain since it
|
||||
# is a passive listening connection)
|
||||
|
||||
@@ -40,6 +40,10 @@ pub const MSG_ID_GET_SERVICE_PORTS: u32 = 37;
|
||||
pub const MSG_ID_GET_EMAIL: u32 = 42;
|
||||
/// Set email settings
|
||||
pub const MSG_ID_SET_EMAIL: u32 = 43;
|
||||
/// Get users and general system info
|
||||
pub const MSG_ID_GET_ABILITY_SUPPORT: u32 = 58;
|
||||
/// Update, create and remove users
|
||||
pub const MSG_ID_UPDATE_USER_LIST: u32 = 59;
|
||||
/// Version messages have this ID
|
||||
pub const MSG_ID_VERSION: u32 = 80;
|
||||
/// Ping messages have this ID
|
||||
|
||||
+52
-14
@@ -138,6 +138,9 @@ pub struct BcXml {
|
||||
/// EmailTask for turning the email notifications on/off
|
||||
#[serde(rename = "EmailTask", skip_serializing_if = "Option::is_none")]
|
||||
pub email_task: Option<EmailTask>,
|
||||
/// Read and write users
|
||||
#[serde(rename = "UserList", skip_serializing_if = "Option::is_none")]
|
||||
pub user_list: Option<UserList>,
|
||||
}
|
||||
|
||||
impl BcXml {
|
||||
@@ -633,15 +636,11 @@ pub struct AlarmEvent {
|
||||
/// The channel the event occured on. Usually zero unless from an NVR
|
||||
#[serde(rename = "channelId")]
|
||||
pub channel_id: u8,
|
||||
/// Motion status. Known values are `"MD"` or `"none"` or `"visitor"`
|
||||
/// Motion status. Known values are `"MD"` or `"none"`
|
||||
pub status: String,
|
||||
/// AI status. Known values are `"people"` or `"none"`
|
||||
#[serde(
|
||||
rename = "AItype",
|
||||
default = "ai_type_default",
|
||||
skip_serializing_if = "ai_type_skip"
|
||||
)]
|
||||
pub ai_type: String,
|
||||
#[serde(rename = "AItype", skip_serializing_if = "Option::is_none")]
|
||||
pub ai_type: Option<String>,
|
||||
/// The recording status. Known values `0` or `1`
|
||||
pub recording: i32,
|
||||
/// The timestamp associated with the recording. `0` if not recording
|
||||
@@ -649,13 +648,6 @@ pub struct AlarmEvent {
|
||||
pub timeStamp: i32,
|
||||
}
|
||||
|
||||
fn ai_type_default() -> String {
|
||||
"none".to_string()
|
||||
}
|
||||
fn ai_type_skip(value: &String) -> bool {
|
||||
value == "none"
|
||||
}
|
||||
|
||||
/// The Ptz messages used to move the camera
|
||||
#[derive(PartialEq, Default, Debug, Deserialize, Serialize)]
|
||||
pub struct PtzControl {
|
||||
@@ -1577,6 +1569,52 @@ pub struct Schedule {
|
||||
pub time_block_list: TimeBlockList,
|
||||
}
|
||||
|
||||
/// List of users
|
||||
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)]
|
||||
pub struct UserList {
|
||||
/// XML Version
|
||||
#[serde(rename = "@version")]
|
||||
pub version: String,
|
||||
/// The actual user-list
|
||||
#[serde(rename = "User", skip_serializing_if = "Option::is_none")]
|
||||
pub user_list: Option<Vec<User>>,
|
||||
}
|
||||
|
||||
/// A struct for reading and writing camera user records
|
||||
#[derive(PartialEq, Eq, Default, Debug, Deserialize, Serialize)]
|
||||
pub struct User {
|
||||
/// The user_name is used to identify the user in the API
|
||||
#[serde(rename = "userName")]
|
||||
pub user_name: String,
|
||||
/// The password seems to only be included when creating or modifying a user
|
||||
#[serde(
|
||||
rename = "password",
|
||||
skip_serializing_if = "Option::is_none",
|
||||
skip_deserializing
|
||||
)]
|
||||
pub password: Option<String>,
|
||||
/// The user_id does not seem to have a purpose. It is not included when creating a user.
|
||||
#[serde(rename = "userId", skip_serializing_if = "Option::is_none")]
|
||||
pub user_id: Option<u32>,
|
||||
/// User type, 0 is User and 1 is Administrator
|
||||
#[serde(rename = "userLevel")]
|
||||
pub user_level: u8,
|
||||
/// Unknown, seems to be 1 for the current API user
|
||||
#[serde(rename = "loginState", skip_serializing_if = "Option::is_none")]
|
||||
pub login_state: Option<u8>,
|
||||
/// The user_set_state states what will happen with a user-record. 4 different values have been
|
||||
/// observed: none | add | delete | modify
|
||||
///
|
||||
/// | Value | Description |
|
||||
/// | --- | --- |
|
||||
/// | none | This is the state set when reading Users. When writing this seems to indicate that the user should not be modified |
|
||||
/// | add | Indicates that a new User should be created |
|
||||
/// | delete | Indicates that the user should be removed |
|
||||
/// | modify | Indicates that the user should be modified. It seems like only the password can be changed. |
|
||||
#[serde(rename = "userSetState")]
|
||||
pub user_set_state: String,
|
||||
}
|
||||
|
||||
/// Convience function to return the xml version used throughout the library
|
||||
pub fn xml_ver() -> String {
|
||||
"1.1".to_string()
|
||||
|
||||
@@ -40,6 +40,7 @@ mod support;
|
||||
mod talk;
|
||||
mod time;
|
||||
mod uid;
|
||||
mod users;
|
||||
mod version;
|
||||
|
||||
pub(crate) use connection::*;
|
||||
@@ -47,7 +48,7 @@ pub use credentials::*;
|
||||
pub use errors::Error;
|
||||
pub use ledstate::LightState;
|
||||
pub use login::MaxEncryption;
|
||||
pub use motion::{AiKind, MotionData, MotionEvents};
|
||||
pub use motion::{MotionData, MotionStatus};
|
||||
pub use pirstate::PirState;
|
||||
pub use ptz::Direction;
|
||||
pub use pushinfo::PhoneType;
|
||||
|
||||
@@ -5,46 +5,25 @@ use tokio::sync::mpsc::{channel, error::TryRecvError, Receiver};
|
||||
use tokio::task::JoinSet;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// Motion Events that the callback can send
|
||||
/// Motion Status that the callback can send
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum MotionEvents {
|
||||
pub enum MotionStatus {
|
||||
/// Sent when motion is first detected
|
||||
Start(Instant),
|
||||
/// Sent when motion stops
|
||||
Stop(Instant),
|
||||
/// Sent when a doorbell is pressed
|
||||
Vistor(Instant),
|
||||
/// Sent when an AI is recieved
|
||||
Ai(Instant, AiKind),
|
||||
/// Sent when an Alarm about something other than motion was received
|
||||
NoChange(Instant),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
/// The kinds of objects the AI can detect
|
||||
pub enum AiKind {
|
||||
/// A person
|
||||
Person,
|
||||
/// A car
|
||||
Car,
|
||||
/// Something else, open a PR to fix with actual thing
|
||||
Other,
|
||||
}
|
||||
|
||||
/// A handle on current motion related events comming from the camera
|
||||
///
|
||||
/// When this object is dropped the motion events are stopped
|
||||
pub struct MotionData {
|
||||
handle: JoinSet<Result<()>>,
|
||||
cancel: CancellationToken,
|
||||
rx: Receiver<Result<MotionEvents>>,
|
||||
history: MotionHistory,
|
||||
}
|
||||
|
||||
pub struct MotionHistory {
|
||||
motion: MotionEvents,
|
||||
visitor: MotionEvents,
|
||||
ai: MotionEvents,
|
||||
rx: Receiver<Result<MotionStatus>>,
|
||||
last_update: MotionStatus,
|
||||
}
|
||||
|
||||
impl MotionData {
|
||||
@@ -54,10 +33,10 @@ impl MotionData {
|
||||
/// 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.history.motion {
|
||||
MotionEvents::Start(_) => Some(true),
|
||||
MotionEvents::Stop(_) => Some(false),
|
||||
_ => None,
|
||||
Ok(match &self.last_update {
|
||||
MotionStatus::Start(_) => Some(true),
|
||||
MotionStatus::Stop(_) => Some(false),
|
||||
MotionStatus::NoChange(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -67,64 +46,44 @@ impl MotionData {
|
||||
/// 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.history.motion {
|
||||
MotionEvents::Start(_) => Some(true),
|
||||
MotionEvents::Stop(time) => Some((Instant::now() - *time) < duration),
|
||||
_ => None,
|
||||
Ok(match &self.last_update {
|
||||
MotionStatus::Start(_) => Some(true),
|
||||
MotionStatus::Stop(time) => Some((Instant::now() - *time) < duration),
|
||||
MotionStatus::NoChange(_) => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Consume all the motion events on the queue and update the history
|
||||
/// 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<()> {
|
||||
while self.try_recv()?.is_some() {
|
||||
// Tight loop....
|
||||
// Should not be many of such messages in the queue though
|
||||
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)),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_history(&mut self, latest_event: &MotionEvents) {
|
||||
match latest_event {
|
||||
MotionEvents::Start(_) => {
|
||||
self.history.motion = *latest_event;
|
||||
}
|
||||
MotionEvents::Stop(_) => {
|
||||
self.history.motion = *latest_event;
|
||||
}
|
||||
MotionEvents::Vistor(_) => {
|
||||
self.history.visitor = *latest_event;
|
||||
}
|
||||
MotionEvents::Ai(_, _) => {
|
||||
self.history.ai = *latest_event;
|
||||
}
|
||||
MotionEvents::NoChange(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to recv a new motion event on the pipeline
|
||||
pub fn try_recv(&mut self) -> Result<Option<MotionEvents>> {
|
||||
match self.rx.try_recv() {
|
||||
Ok(motion) => {
|
||||
let motion = motion?;
|
||||
self.update_history(&motion);
|
||||
Ok(Some(motion))
|
||||
}
|
||||
Err(TryRecvError::Empty) => Ok(None),
|
||||
Err(e) => Err(Error::from(e)),
|
||||
if let Some(last) = results.last() {
|
||||
self.last_update = *last;
|
||||
}
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// Await a new motion event
|
||||
pub async fn recv(&mut self) -> Result<Option<MotionEvents>> {
|
||||
match self.rx.recv().await {
|
||||
Some(motion) => {
|
||||
let motion = motion?;
|
||||
self.update_history(&motion);
|
||||
Ok(Some(motion))
|
||||
}
|
||||
None => Ok(None),
|
||||
///
|
||||
///
|
||||
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"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,10 +91,10 @@ impl MotionData {
|
||||
///
|
||||
/// It must be stopped for at least the given duration
|
||||
pub async fn await_stop(&mut self, duration: Duration) -> Result<()> {
|
||||
self.consume_motion_events()?;
|
||||
let mut last_motion = self.history.motion;
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let MotionEvents::Stop(time) = last_motion {
|
||||
if let Some(MotionStatus::Stop(time)) = last_motion {
|
||||
// In stop state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
@@ -146,37 +105,22 @@ impl MotionData {
|
||||
_ = tokio::time::sleep(remaining_sleep) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.recv().await {
|
||||
n @ Ok(Some(MotionEvents::Start(_))) => {return n;},
|
||||
n @ Ok(None) => {return n;} // End of data
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Start(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
match result {
|
||||
Some(Ok(None)) => {
|
||||
// Camera has dropped motion
|
||||
return Ok(());
|
||||
}
|
||||
Some(Ok(Some(_))) => {
|
||||
// continue to next data
|
||||
}
|
||||
Some(Err(e)) => return Err(e),
|
||||
None => {
|
||||
// Timeout occured motion stopped
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(next_motion) = self.recv().await? {
|
||||
last_motion = next_motion;
|
||||
} else {
|
||||
// Camera had dropped motion
|
||||
return Ok(());
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,10 +128,10 @@ impl MotionData {
|
||||
///
|
||||
/// The motion must have a minimum duration as given
|
||||
pub async fn await_start(&mut self, duration: Duration) -> Result<()> {
|
||||
self.consume_motion_events()?;
|
||||
let mut last_motion = self.history.motion;
|
||||
let motions = self.consume_motion_events()?;
|
||||
let mut last_motion = motions.last().copied();
|
||||
loop {
|
||||
if let MotionEvents::Start(time) = last_motion {
|
||||
if let Some(MotionStatus::Start(time)) = last_motion {
|
||||
// In start state
|
||||
if duration.is_zero() || (Instant::now() - time) > duration {
|
||||
return Ok(());
|
||||
@@ -197,37 +141,22 @@ impl MotionData {
|
||||
_ = tokio::time::sleep(duration - (Instant::now() - time)) => {None},
|
||||
v = async {
|
||||
loop {
|
||||
match self.recv().await {
|
||||
n @ Ok(Some(MotionEvents::Stop(_))) => {return n;},
|
||||
n @ Ok(None) => {return n;} // End of data
|
||||
match self.next_motion().await {
|
||||
n @ Ok(MotionStatus::Stop(_)) => {return n;},
|
||||
n @ Err(_) => {return n;},
|
||||
_ => {continue;}
|
||||
}
|
||||
}
|
||||
} => {Some(v)}
|
||||
};
|
||||
match result {
|
||||
Some(Ok(None)) => {
|
||||
// Camera has dropped motion
|
||||
return Ok(());
|
||||
}
|
||||
Some(Ok(Some(_))) => {
|
||||
// conitnue to next data
|
||||
}
|
||||
Some(Err(e)) => return Err(e),
|
||||
None => {
|
||||
// Timeout occured motion started
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = result {
|
||||
v?;
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(next_motion) = self.recv().await? {
|
||||
last_motion = next_motion;
|
||||
} else {
|
||||
// Camera had dropped motion
|
||||
return Ok(());
|
||||
}
|
||||
last_motion = Some(self.next_motion().await?);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -296,7 +225,7 @@ impl BcCamera {
|
||||
loop {
|
||||
tokio::task::yield_now().await;
|
||||
let msg = sub.recv().await;
|
||||
let status_list = match msg {
|
||||
let status = match msg {
|
||||
Ok(motion_msg) => {
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
@@ -307,51 +236,36 @@ impl BcCamera {
|
||||
..
|
||||
}) = motion_msg.body
|
||||
{
|
||||
let mut result = vec![];
|
||||
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 == "visitor" {
|
||||
result.push(MotionEvents::Vistor(Instant::now()));
|
||||
} else if alarm_event.status == "MD" {
|
||||
result.push(MotionEvents::Start(Instant::now()));
|
||||
} else if alarm_event.ai_type != "none" {
|
||||
result.push(MotionEvents::Ai(Instant::now(),
|
||||
match alarm_event.ai_type.as_ref() {
|
||||
"person" | "people" | "human" => AiKind::Person,
|
||||
"car" | "vehicle" => AiKind::Car,
|
||||
_ => AiKind::Other,
|
||||
}
|
||||
));
|
||||
if alarm_event.status != "none"
|
||||
|| alarm_event
|
||||
.ai_type
|
||||
.as_ref()
|
||||
.map(|ai_type| ai_type != "none")
|
||||
.unwrap_or(false)
|
||||
{
|
||||
result = MotionStatus::Start(Instant::now());
|
||||
break;
|
||||
} else {
|
||||
result.push(MotionEvents::Stop(Instant::now()));
|
||||
result = MotionStatus::Stop(Instant::now());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
} else {
|
||||
Ok(vec![])
|
||||
Ok(MotionStatus::NoChange(Instant::now()))
|
||||
}
|
||||
}
|
||||
// On connection drop we stop
|
||||
Err(e) => Err(e),
|
||||
};
|
||||
|
||||
match status_list {
|
||||
Ok(mut status_list) => {
|
||||
for status in status_list.drain(..) {
|
||||
if tx.send(Ok(status)).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
break;
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
// Err from camera
|
||||
if tx.send(Err(e)).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
}
|
||||
break;
|
||||
}
|
||||
if tx.send(status).await.is_err() {
|
||||
// Motion reciever has been dropped
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -363,11 +277,7 @@ impl BcCamera {
|
||||
handle: set,
|
||||
cancel,
|
||||
rx,
|
||||
history: MotionHistory {
|
||||
motion: MotionEvents::NoChange(Instant::now()),
|
||||
visitor: MotionEvents::NoChange(Instant::now()),
|
||||
ai: MotionEvents::NoChange(Instant::now()),
|
||||
},
|
||||
last_update: MotionStatus::NoChange(Instant::now()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
use super::{BcCamera, Error, Result};
|
||||
use crate::bc::{model::*, xml::*};
|
||||
|
||||
impl BcCamera {
|
||||
/// Returns all users configured in the camera
|
||||
pub async fn get_users(&self) -> Result<UserList> {
|
||||
let connection = self.get_connection();
|
||||
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_get = connection
|
||||
.subscribe(MSG_ID_GET_ABILITY_SUPPORT, msg_num)
|
||||
.await?;
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_GET_ABILITY_SUPPORT,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: Some(Extension {
|
||||
user_name: Some("admin".to_owned()),
|
||||
..Default::default()
|
||||
}),
|
||||
payload: None,
|
||||
}),
|
||||
};
|
||||
|
||||
sub_get.send(get).await?;
|
||||
let msg = sub_get.recv().await?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
// Valid message with response_code == 200
|
||||
if let BcBody::ModernMsg(ModernMsg {
|
||||
payload:
|
||||
Some(BcPayloads::BcXml(BcXml {
|
||||
user_list: Some(user_list),
|
||||
..
|
||||
})),
|
||||
..
|
||||
}) = msg.body
|
||||
{
|
||||
Ok(user_list)
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "Expected ModernMsg payload with a user_list but it was not recieved",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a new user
|
||||
///
|
||||
/// This function does not check if the user exist and the API will likely throw an error if
|
||||
/// that is the case
|
||||
pub async fn add_user(
|
||||
&self,
|
||||
user_name: String,
|
||||
password: String,
|
||||
user_level: u8,
|
||||
) -> Result<()> {
|
||||
let users = self.get_users().await;
|
||||
|
||||
let mut users = users?.user_list.unwrap_or(Vec::new());
|
||||
if users.iter().any(|user| user.user_name == user_name) {
|
||||
return Err(Error::Other("User already exists"));
|
||||
}
|
||||
|
||||
users.push(User {
|
||||
user_set_state: "add".to_owned(),
|
||||
user_name,
|
||||
password: Some(password),
|
||||
user_level,
|
||||
user_id: None,
|
||||
login_state: None,
|
||||
});
|
||||
|
||||
self.set_users(users).await
|
||||
}
|
||||
|
||||
/// Modify a user. It seems the only property of a user that is modifiable is the password.
|
||||
pub async fn modify_user(&self, user_name: String, password: String) -> Result<()> {
|
||||
let users = self.get_users().await;
|
||||
|
||||
let mut users = users?.user_list.unwrap_or(Vec::new());
|
||||
|
||||
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
|
||||
user.user_set_state = "modify".to_owned();
|
||||
user.password = Some(password.clone());
|
||||
} else {
|
||||
return Err(Error::Other("User not found"));
|
||||
}
|
||||
|
||||
self.set_users(users).await
|
||||
}
|
||||
|
||||
/// Remove a user. This does not check for the existence of that user and will likely return an
|
||||
/// error if the user doesn't exist.
|
||||
pub async fn delete_user(&self, user_name: String) -> Result<()> {
|
||||
let users = self.get_users().await;
|
||||
|
||||
let mut users = users?.user_list.unwrap_or(Vec::new());
|
||||
|
||||
if let Some(user) = users.iter_mut().find(|user| user.user_name == user_name) {
|
||||
user.user_set_state = "delete".to_owned();
|
||||
} else {
|
||||
return Err(Error::Other("User not found"));
|
||||
}
|
||||
|
||||
self.set_users(users).await
|
||||
}
|
||||
|
||||
/// Helper method to send a UserList and wait for its success/failure.
|
||||
async fn set_users(&self, users: Vec<User>) -> Result<()> {
|
||||
let bcxml = BcXml {
|
||||
user_list: Some(UserList {
|
||||
version: "1.1".to_owned(),
|
||||
user_list: Some(users),
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let connection = self.get_connection();
|
||||
let msg_num = self.new_message_num();
|
||||
let mut sub_set = connection
|
||||
.subscribe(MSG_ID_UPDATE_USER_LIST, msg_num)
|
||||
.await?;
|
||||
|
||||
let get = Bc {
|
||||
meta: BcMeta {
|
||||
msg_id: MSG_ID_UPDATE_USER_LIST,
|
||||
channel_id: self.channel_id,
|
||||
msg_num,
|
||||
response_code: 0,
|
||||
stream_type: 0,
|
||||
class: 0x6414,
|
||||
},
|
||||
body: BcBody::ModernMsg(ModernMsg {
|
||||
extension: None,
|
||||
payload: Some(BcPayloads::BcXml(bcxml)),
|
||||
}),
|
||||
};
|
||||
|
||||
sub_set.send(get).await?;
|
||||
if let Ok(reply) =
|
||||
tokio::time::timeout(tokio::time::Duration::from_millis(500), sub_set.recv()).await
|
||||
{
|
||||
let msg = reply?;
|
||||
if msg.meta.response_code != 200 {
|
||||
return Err(Error::CameraServiceUnavailable {
|
||||
id: msg.meta.msg_id,
|
||||
code: msg.meta.response_code,
|
||||
});
|
||||
}
|
||||
|
||||
if let BcMeta {
|
||||
response_code: 200, ..
|
||||
} = msg.meta
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::UnintelligibleReply {
|
||||
reply: std::sync::Arc::new(Box::new(msg)),
|
||||
why: "The camera did not except the BcXmp with service data",
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Some cameras seem to just not send a reply on success, so after 500ms we return Ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
+146
-50
@@ -1267,77 +1267,173 @@ Message have zero to two payloads.
|
||||
```
|
||||
|
||||
- **Notes:** The passwords are not sent in some models of cameras namely
|
||||
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710) in these cases the passwords
|
||||
are blank. In some older cameras that do not use encryption at all these
|
||||
passwords are completely visible to any network sniffers. Even the "encrypted"
|
||||
cameras only have weak encryption that is easily broken since the
|
||||
decryption key is fixed and well-known.
|
||||
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710), RLC-811A in these cases the
|
||||
passwords are blank. In some older cameras that do not use encryption at
|
||||
all these passwords are completely visible to any network sniffers. Even
|
||||
the "encrypted" cameras only have weak encryption that is easily broken
|
||||
since the decryption key is fixed and well-known.
|
||||
|
||||
- 67: `<ConfigFileInfo> (FW Upgrade)`
|
||||
- 59: `<UserList>`
|
||||
|
||||
- Client
|
||||
- Client
|
||||
|
||||
- Header
|
||||
- Header: Standard header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 01 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
|
||||
- Extension
|
||||
|
||||
- Extension
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<userName>admin</userName>
|
||||
</Extension>
|
||||
```
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<ConfigFileInfo version="1.1">
|
||||
<fileName>FIRMWAREFILE.pak</fileName>
|
||||
<fileSize>SIZE_IN_BYTES</fileSize>
|
||||
<updateParameter>0</updateParameter>
|
||||
</ConfigFileInfo>
|
||||
</body>
|
||||
```
|
||||
- Camera
|
||||
|
||||
- **Notes:** updateParameter refers to updating the settings. If 1 it will restore factory settings. If 0 it will keep current.
|
||||
- Header: Standard header
|
||||
|
||||
- Camera
|
||||
- Payload — Changing the password of testUser
|
||||
|
||||
- Header
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<UserList version="1.1">
|
||||
<User>
|
||||
<userName>admin</userName>
|
||||
<password>password12</password>
|
||||
<userLevel>1</userLevel>
|
||||
<userSetState>none</userSetState>
|
||||
</User>
|
||||
<User>
|
||||
<userName>testUser</userName>
|
||||
<password>newPass</password>
|
||||
<userLevel>0</userLevel>
|
||||
<userSetState>modify</userSetState>
|
||||
</User>
|
||||
</UserList>
|
||||
</body>
|
||||
```
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
- Payload — creating a user
|
||||
|
||||
- Client
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<UserList version="1.1">
|
||||
<User>
|
||||
<userName>admin</userName>
|
||||
<password>password12</password>
|
||||
<userLevel>1</userLevel>
|
||||
<userSetState>none</userSetState>
|
||||
</User>
|
||||
<User>
|
||||
<userName>testUser</userName>
|
||||
<password>testPass</password>
|
||||
<userLevel>0</userLevel>
|
||||
<userSetState>add</userSetState>
|
||||
</User>
|
||||
</UserList>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Header
|
||||
- Payload — deleting a user
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 94 58 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 6a |
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<UserList version="1.1">
|
||||
<User>
|
||||
<userName>admin</userName>
|
||||
<password>password12</password>
|
||||
<userLevel>1</userLevel>
|
||||
<userSetState>none</userSetState>
|
||||
</User>
|
||||
<User>
|
||||
<userName>testUser</userName>
|
||||
<password>newPass</password>
|
||||
<userLevel>0</userLevel>
|
||||
<userSetState>delete</userSetState>
|
||||
</User>
|
||||
</UserList>
|
||||
</body>
|
||||
```
|
||||
|
||||
- Extension
|
||||
- **Notes:** The passwords are not sent in some models of cameras namely
|
||||
RLC-410 4mp, RLC-410 5mp, RLC-520 (fw 200710), RLC-811A in these cases the
|
||||
passwords are blank. In some older cameras that do not use encryption at
|
||||
all these passwords are completely visible to any network sniffers. Even
|
||||
the "encrypted" cameras only have weak encryption that is easily broken
|
||||
since the decryption key is fixed and well-known.
|
||||
- **Notes:** The password field seems to only be needed when creating a user
|
||||
or changing a users password.
|
||||
- **Notes:** It does not appear like userLevel is modifiable (at least on
|
||||
RLC-811A)
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<binaryData>1</binaryData>
|
||||
</Extension>
|
||||
```
|
||||
- 67: `<ConfigFileInfo> (FW Upgrade)`
|
||||
|
||||
- Payload
|
||||
- Client
|
||||
|
||||
This contains binary data of the file but stops once the message size reaches
|
||||
38000 bytes and continues in another packet. There does not appear to
|
||||
be a checksum or hash and this part contains only the raw bytes of the file.
|
||||
- Header
|
||||
|
||||
- Camera
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 01 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 |
|
||||
|
||||
- Header
|
||||
- Extension
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<body>
|
||||
<ConfigFileInfo version="1.1">
|
||||
<fileName>FIRMWAREFILE.pak</fileName>
|
||||
<fileSize>SIZE_IN_BYTES</fileSize>
|
||||
<updateParameter>0</updateParameter>
|
||||
</ConfigFileInfo>
|
||||
</body>
|
||||
```
|
||||
|
||||
- **Notes:** Last two messages repeat until all data is sent
|
||||
- **Notes:** updateParameter refers to updating the settings. If 1 it will restore factory settings. If 0 it will keep current.
|
||||
|
||||
- Camera
|
||||
|
||||
- Header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
|
||||
- Client
|
||||
|
||||
- Header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 94 58 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 6a |
|
||||
|
||||
- Extension
|
||||
|
||||
```xml
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Extension version="1.1">
|
||||
<binaryData>1</binaryData>
|
||||
</Extension>
|
||||
```
|
||||
|
||||
- Payload
|
||||
|
||||
This contains binary data of the file but stops once the message size reaches
|
||||
38000 bytes and continues in another packet. There does not appear to
|
||||
be a checksum or hash and this part contains only the raw bytes of the file.
|
||||
|
||||
- Camera
|
||||
|
||||
- Header
|
||||
|
||||
| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset |
|
||||
| ----------- | ----------- | -------------- | ----------------- | ----------- | ------------- | -------------- |
|
||||
| 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 |
|
||||
|
||||
- **Notes:** Last two messages repeat until all data is sent
|
||||
|
||||
- 76: `<Ip>`
|
||||
|
||||
|
||||
@@ -32,4 +32,5 @@ pub enum Command {
|
||||
Image(super::image::Opt),
|
||||
Battery(super::battery::Opt),
|
||||
Services(super::services::Opt),
|
||||
Users(super::users::Opt),
|
||||
}
|
||||
+2
-17
@@ -15,9 +15,10 @@ use tokio::{
|
||||
};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{AiState, MdState, NeoCamCommand, NeoCamThreadState, Permit, VisitorState};
|
||||
use super::{MdState, NeoCamCommand, NeoCamThreadState, Permit};
|
||||
use crate::{config::CameraConfig, AnyResult, Result};
|
||||
use neolink_core::bc_protocol::BcCamera;
|
||||
|
||||
#[cfg(feature = "gstreamer")]
|
||||
mod gst;
|
||||
|
||||
@@ -237,22 +238,6 @@ impl NeoInstance {
|
||||
Ok(instance_rx.await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn visitor(&self) -> Result<WatchReceiver<VisitorState>> {
|
||||
let (instance_tx, instance_rx) = oneshot();
|
||||
self.camera_control
|
||||
.send(NeoCamCommand::Visitor(instance_tx))
|
||||
.await?;
|
||||
Ok(instance_rx.await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn ai(&self) -> Result<WatchReceiver<AiState>> {
|
||||
let (instance_tx, instance_rx) = oneshot();
|
||||
self.camera_control
|
||||
.send(NeoCamCommand::Ai(instance_tx))
|
||||
.await?;
|
||||
Ok(instance_rx.await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn config(&self) -> Result<WatchReceiver<CameraConfig>> {
|
||||
let (instance_tx, instance_rx) = oneshot();
|
||||
self.camera_control
|
||||
|
||||
+8
-76
@@ -15,7 +15,7 @@ use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::NeoInstance;
|
||||
use crate::{AnyResult, Result};
|
||||
use neolink_core::bc_protocol::{AiKind, MotionEvents};
|
||||
use neolink_core::bc_protocol::MotionStatus;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
@@ -25,26 +25,8 @@ pub(crate) enum MdState {
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) enum VisitorState {
|
||||
Visted(Instant),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub(crate) enum AiState {
|
||||
Person(Instant),
|
||||
Car(Instant),
|
||||
Other(Instant),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
pub(crate) struct NeoCamMdThread {
|
||||
md_watcher: Arc<WatchSender<MdState>>,
|
||||
visitor_watcher: Arc<WatchSender<VisitorState>>,
|
||||
ai_watcher: Arc<WatchSender<AiState>>,
|
||||
md_request_rx: MpscReceiver<MdRequest>,
|
||||
cancel: CancellationToken,
|
||||
instance: NeoInstance,
|
||||
@@ -57,17 +39,8 @@ impl NeoCamMdThread {
|
||||
) -> Result<Self> {
|
||||
let (md_watcher, _) = watch(MdState::Unknown);
|
||||
let md_watcher = Arc::new(md_watcher);
|
||||
|
||||
let (visitor_watcher, _) = watch(VisitorState::Unknown);
|
||||
let visitor_watcher = Arc::new(visitor_watcher);
|
||||
|
||||
let (ai_watcher, _) = watch(AiState::Unknown);
|
||||
let ai_watcher = Arc::new(ai_watcher);
|
||||
|
||||
Ok(Self {
|
||||
md_watcher,
|
||||
visitor_watcher,
|
||||
ai_watcher,
|
||||
md_request_rx,
|
||||
cancel: CancellationToken::new(),
|
||||
instance,
|
||||
@@ -77,8 +50,6 @@ impl NeoCamMdThread {
|
||||
pub(crate) async fn run(&mut self) -> Result<()> {
|
||||
let thread_cancel = self.cancel.clone();
|
||||
let watcher = self.md_watcher.clone();
|
||||
let visitor_watcher = self.visitor_watcher.clone();
|
||||
let ai_watcher = self.ai_watcher.clone();
|
||||
let md_instance = self.instance.clone();
|
||||
tokio::select! {
|
||||
_ = thread_cancel.cancelled() => {
|
||||
@@ -87,21 +58,11 @@ impl NeoCamMdThread {
|
||||
v = async {
|
||||
while let Some(request) = self.md_request_rx.recv().await {
|
||||
match request {
|
||||
MdRequest::Md {
|
||||
MdRequest::Get {
|
||||
sender
|
||||
} => {
|
||||
let _ = sender.send(self.md_watcher.subscribe());
|
||||
},
|
||||
MdRequest::Visitor {
|
||||
sender
|
||||
} => {
|
||||
let _ = sender.send(self.visitor_watcher.subscribe());
|
||||
},
|
||||
MdRequest::Ai {
|
||||
sender
|
||||
} => {
|
||||
let _ = sender.send(self.ai_watcher.subscribe());
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -110,46 +71,23 @@ impl NeoCamMdThread {
|
||||
loop {
|
||||
let r: AnyResult<()> = md_instance.run_passive_task(|cam| {
|
||||
let watcher = watcher.clone();
|
||||
let visitor_watcher = visitor_watcher.clone();
|
||||
let ai_watcher = ai_watcher.clone();
|
||||
Box::pin(
|
||||
async move {
|
||||
let mut md = cam.listen_on_motion().await.with_context(|| "Error in getting MD listen_on_motion")?;
|
||||
loop {
|
||||
let event = md.recv().await.with_context(|| "Error in getting MD next_motion")?.ok_or(anyhow::anyhow!("MD connection was dropped"))?;
|
||||
let event = md.next_motion().await.with_context(|| "Error in getting MD next_motion")?;
|
||||
match event {
|
||||
MotionEvents::Start(at) => {
|
||||
MotionStatus::Start(at) => {
|
||||
watcher.send_replace(
|
||||
MdState::Start(at.into())
|
||||
);
|
||||
}
|
||||
MotionEvents::Stop(at) => {
|
||||
MotionStatus::Stop(at) => {
|
||||
watcher.send_replace(
|
||||
MdState::Stop(at.into())
|
||||
);
|
||||
},
|
||||
MotionEvents::Vistor(at) => {
|
||||
visitor_watcher.send_replace(
|
||||
VisitorState::Visted(at.into())
|
||||
);
|
||||
},
|
||||
MotionEvents::Ai(at, kind) => {
|
||||
ai_watcher.send_replace(
|
||||
match kind {
|
||||
AiKind::Person => {
|
||||
AiState::Person(at.into())
|
||||
}
|
||||
AiKind::Car => {
|
||||
AiState::Car(at.into())
|
||||
}
|
||||
AiKind::Other => {
|
||||
AiState::Other(at.into())
|
||||
}
|
||||
}
|
||||
|
||||
);
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
MotionStatus::NoChange(_) => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -172,13 +110,7 @@ impl Drop for NeoCamMdThread {
|
||||
|
||||
/// Used to pass messages to the MdThread
|
||||
pub(crate) enum MdRequest {
|
||||
Md {
|
||||
Get {
|
||||
sender: OneshotSender<WatchReceiver<MdState>>,
|
||||
},
|
||||
Visitor {
|
||||
sender: OneshotSender<WatchReceiver<VisitorState>>,
|
||||
},
|
||||
Ai {
|
||||
sender: OneshotSender<WatchReceiver<AiState>>,
|
||||
},
|
||||
}
|
||||
+3
-19
@@ -20,8 +20,8 @@ use tokio_stream::wrappers::ReceiverStream;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{
|
||||
AiState, MdRequest, MdState, NeoCamMdThread, NeoCamThread, NeoCamThreadState, NeoInstance,
|
||||
Permit, UseCounter, VisitorState,
|
||||
MdRequest, MdState, NeoCamMdThread, NeoCamThread, NeoCamThreadState, NeoInstance, Permit,
|
||||
UseCounter,
|
||||
};
|
||||
#[cfg(feature = "pushnoti")]
|
||||
use super::{PnRequest, PushNoti};
|
||||
@@ -33,8 +33,6 @@ pub(crate) enum NeoCamCommand {
|
||||
HangUp,
|
||||
Instance(OneshotSender<Result<NeoInstance>>),
|
||||
Motion(OneshotSender<WatchReceiver<MdState>>),
|
||||
Visitor(OneshotSender<WatchReceiver<VisitorState>>),
|
||||
Ai(OneshotSender<WatchReceiver<AiState>>),
|
||||
Config(OneshotSender<WatchReceiver<CameraConfig>>),
|
||||
Disconnect(OneshotSender<()>),
|
||||
Connect(OneshotSender<()>),
|
||||
@@ -111,21 +109,7 @@ impl NeoCam {
|
||||
}
|
||||
NeoCamCommand::Motion(sender) => {
|
||||
md_request_tx.send(
|
||||
MdRequest::Md {
|
||||
sender,
|
||||
}
|
||||
).await?;
|
||||
},
|
||||
NeoCamCommand::Visitor(sender) => {
|
||||
md_request_tx.send(
|
||||
MdRequest::Visitor {
|
||||
sender,
|
||||
}
|
||||
).await?;
|
||||
},
|
||||
NeoCamCommand::Ai(sender) => {
|
||||
md_request_tx.send(
|
||||
MdRequest::Ai {
|
||||
MdRequest::Get {
|
||||
sender,
|
||||
}
|
||||
).await?;
|
||||
|
||||
@@ -235,10 +235,6 @@ pub(crate) struct MqttConfig {
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_motion: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_visitor: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_ai: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_light: bool,
|
||||
#[serde(default = "default_true")]
|
||||
pub(crate) enable_battery: bool,
|
||||
@@ -307,8 +303,6 @@ const fn default_false() -> bool {
|
||||
fn default_mqtt() -> MqttConfig {
|
||||
MqttConfig {
|
||||
enable_motion: true,
|
||||
enable_visitor: true,
|
||||
enable_ai: true,
|
||||
enable_light: true,
|
||||
enable_battery: true,
|
||||
battery_update: 2000,
|
||||
|
||||
@@ -52,6 +52,7 @@ mod services;
|
||||
mod statusled;
|
||||
#[cfg(feature = "gstreamer")]
|
||||
mod talk;
|
||||
mod users;
|
||||
mod utils;
|
||||
|
||||
use cmdline::{Command, Opt};
|
||||
@@ -143,6 +144,9 @@ async fn main() -> Result<()> {
|
||||
Some(Command::Services(opts)) => {
|
||||
services::main(opts, neo_reactor.clone()).await?;
|
||||
}
|
||||
Some(Command::Users(opts)) => {
|
||||
users::main(opts, neo_reactor.clone()).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+9
-75
@@ -77,7 +77,7 @@ mod discovery;
|
||||
mod mqttc;
|
||||
|
||||
use crate::{
|
||||
common::{AiState, MdState, NeoInstance, NeoReactor, VisitorState},
|
||||
common::{MdState, NeoInstance, NeoReactor},
|
||||
config::Config,
|
||||
AnyResult,
|
||||
};
|
||||
@@ -303,14 +303,14 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
|
||||
.await
|
||||
.with_context(|| format!("Failed to publish status for {}", camera_name))?;
|
||||
let _drop_message = mqtt_instance.last_will("status", "disconnected").await?;
|
||||
// mqtt_instance
|
||||
// .send_message("status/motion", "unknown", true)
|
||||
// .await
|
||||
// .with_context(|| format!("Failed to publish motion unknown for {}", camera_name))?;
|
||||
// mqtt_instance
|
||||
// .send_message("status/notification", "unknown", true)
|
||||
// .await
|
||||
// .with_context(|| format!("Failed to publish push notification unknown for {}", camera_name))?;
|
||||
mqtt_instance
|
||||
.send_message("status/motion", "unknown", true)
|
||||
.await
|
||||
.with_context(|| format!("Failed to publish motion unknown for {}", camera_name))?;
|
||||
mqtt_instance
|
||||
.send_message("status/notification", "unknown", true)
|
||||
.await
|
||||
.with_context(|| format!("Failed to publish push notification unknown for {}", camera_name))?;
|
||||
let _drop_message2 = mqtt_instance.last_will("status/motion", "unknown").await?;
|
||||
|
||||
if let Some(discovery_config) = config.discovery.as_ref() {
|
||||
@@ -331,12 +331,6 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
|
||||
let camera_motion = camera.clone();
|
||||
let mqtt_motion = mqtt_instance.resubscribe().await?;
|
||||
|
||||
let camera_visitor = camera.clone();
|
||||
let mqtt_visitor = mqtt_instance.resubscribe().await?;
|
||||
|
||||
let camera_ai = camera.clone();
|
||||
let mqtt_ai = mqtt_instance.resubscribe().await?;
|
||||
|
||||
#[cfg(feature = "pushnoti")]
|
||||
let camera_pn = camera.clone();
|
||||
#[cfg(feature = "pushnoti")]
|
||||
@@ -482,66 +476,6 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
|
||||
}?;
|
||||
}
|
||||
}, if config.enable_motion => v,
|
||||
// Handle the visitor messages
|
||||
v = async {
|
||||
let mut vis = camera_visitor.visitor().await?;
|
||||
loop {
|
||||
let v = async {
|
||||
vis.changed().await.with_context(|| {
|
||||
format!("{}: ViaStart Watch Dropped", camera_name)
|
||||
})?;
|
||||
vis.wait_for(|state| matches!(state, VisitorState::Visted(_))).await.with_context(|| {
|
||||
format!("{}: ViaStart Watch Dropped", camera_name)
|
||||
})?;
|
||||
mqtt_visitor.send_message("status/visitor", "visitor", true).await.with_context(|| {
|
||||
format!("{}: Failed to publish visitor", camera_name)
|
||||
})?;
|
||||
AnyResult::Ok(())
|
||||
}.await;
|
||||
match v.map_err(|e| e.downcast::<neolink_core::Error>()) {
|
||||
Err(Ok(neolink_core::Error::UnintelligibleReply{..})) => futures::future::pending().await,
|
||||
Ok(()) => AnyResult::Ok(()),
|
||||
Err(Ok(e)) => Err(e.into()),
|
||||
Err(Err(e)) => Err(e),
|
||||
}?;
|
||||
}
|
||||
}, if config.enable_visitor => v,
|
||||
// Handle the ai messages
|
||||
v = async {
|
||||
let mut ai = camera_ai.ai().await?;
|
||||
loop {
|
||||
let v = async {
|
||||
let ai_kind = {
|
||||
ai.changed().await.with_context(|| {
|
||||
format!("{}: AiStart Watch Dropped", camera_name)
|
||||
})?;
|
||||
let ai_state = ai.wait_for(|state| !matches!(state, AiState::Unknown)).await.with_context(|| {
|
||||
format!("{}: AiStart Watch Dropped", camera_name)
|
||||
})?;
|
||||
match &*ai_state {
|
||||
AiState::Person(_) => "person",
|
||||
AiState::Car(_) => "car",
|
||||
AiState::Other(_) => "other",
|
||||
AiState::Unknown => unreachable!(),
|
||||
}
|
||||
};
|
||||
|
||||
mqtt_ai.send_message("status/ai", ai_kind, true).await.with_context(|| {
|
||||
format!("{}: Failed to publish ai msg", camera_name)
|
||||
})?;
|
||||
mqtt_ai.send_message(&format!("status/ai/{}", ai_kind), ai_kind, true).await.with_context(|| {
|
||||
format!("{}: Failed to publish ai sub msg", camera_name)
|
||||
})?;
|
||||
AnyResult::Ok(())
|
||||
}.await;
|
||||
match v.map_err(|e| e.downcast::<neolink_core::Error>()) {
|
||||
Err(Ok(neolink_core::Error::UnintelligibleReply{..})) => futures::future::pending().await,
|
||||
Ok(()) => AnyResult::Ok(()),
|
||||
Err(Ok(e)) => Err(e.into()),
|
||||
Err(Err(e)) => Err(e),
|
||||
}?;
|
||||
}
|
||||
}, if config.enable_ai => v,
|
||||
// Handle the SNAP (image preview)
|
||||
v = async {
|
||||
let mut wait = IntervalStream::new({
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ struct MqttBackend<'a> {
|
||||
cancel: CancellationToken,
|
||||
}
|
||||
|
||||
impl MqttBackend<'_> {
|
||||
impl<'a> MqttBackend<'a> {
|
||||
async fn run(&mut self) -> AnyResult<()> {
|
||||
log::trace!("Run MQTT Server");
|
||||
let mut mqttoptions = MqttOptions::new(
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
use clap::{Parser, ValueEnum};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub struct Opt {
|
||||
/// The name of the camera. Must be a name in the config
|
||||
pub camera: String,
|
||||
/// The action to perform
|
||||
#[command(subcommand)]
|
||||
pub cmd: UserAction,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
pub enum UserAction {
|
||||
/// List users
|
||||
List,
|
||||
/// Create a new user
|
||||
Add {
|
||||
/// The username of the new user
|
||||
user_name: String,
|
||||
/// The password of the new user
|
||||
password: String,
|
||||
/// User type
|
||||
user_type: UserType,
|
||||
},
|
||||
Password {
|
||||
/// The username of the new user
|
||||
user_name: String,
|
||||
/// The password of the new user
|
||||
password: String,
|
||||
},
|
||||
Delete {
|
||||
/// The username of the user to delete
|
||||
user_name: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug, Clone, ValueEnum)]
|
||||
pub enum UserType {
|
||||
/// user_level = 0
|
||||
User,
|
||||
/// user_level = 1
|
||||
Administrator,
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
///
|
||||
/// # Neolink Users
|
||||
///
|
||||
/// This modules handles users
|
||||
///
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```bash
|
||||
/// # To list users
|
||||
/// neolink --config=config.toml users CameraName list
|
||||
/// # To create a a new administrator
|
||||
/// neolink --config=config.toml users CameraName add newuser hunter2 administrator
|
||||
/// # To delete a user
|
||||
/// neolink --config=config.toml users CameraName delete newuser
|
||||
/// ```
|
||||
///
|
||||
/// There are two types of users:
|
||||
/// - administrator — Can access the device and change device settings
|
||||
/// - user — Can access the device but not change device settings
|
||||
///
|
||||
use anyhow::{anyhow, Context, Result};
|
||||
|
||||
mod cmdline;
|
||||
|
||||
use crate::common::NeoReactor;
|
||||
pub(crate) use cmdline::*;
|
||||
use neolink_core::bc::xml::UserList;
|
||||
|
||||
/// Entry point for the users subcommand
|
||||
///
|
||||
/// Opt is the command line options
|
||||
pub(crate) async fn main(opt: Opt, reactor: NeoReactor) -> Result<()> {
|
||||
let camera = reactor.get(&opt.camera).await?;
|
||||
|
||||
match opt.cmd {
|
||||
UserAction::List => {
|
||||
let user_list = camera
|
||||
.run_task(|cam| {
|
||||
Box::pin(
|
||||
async move { cam.get_users().await.context("Unable to list camera users") },
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
match user_list {
|
||||
UserList {
|
||||
user_list: Some(users),
|
||||
..
|
||||
} => {
|
||||
println!("{:<12} {:>4} {:>16}", "Username", "ID", "User type");
|
||||
for user in users {
|
||||
println!(
|
||||
"{:<12} {:>4} {:>16}",
|
||||
user.user_name,
|
||||
user.user_id
|
||||
.expect("user_id should exist when reading users"),
|
||||
match user.user_level {
|
||||
0 => "User".to_owned(),
|
||||
1 => "Administrator".to_owned(),
|
||||
n => format!("Unknown ({})", n),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
eprintln!("No users were included in response");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
UserAction::Add {
|
||||
user_name,
|
||||
password,
|
||||
user_type,
|
||||
} => {
|
||||
camera
|
||||
.run_task(|cam| {
|
||||
Box::pin({
|
||||
let user_name = user_name.clone();
|
||||
let password = password.clone();
|
||||
let user_type = user_type.clone();
|
||||
async move {
|
||||
let user_list = cam
|
||||
.get_users()
|
||||
.await
|
||||
.context("Failed to list current users")?;
|
||||
let user_exists = match user_list.user_list {
|
||||
Some(users) => users.iter().any(|user| user.user_name == user_name),
|
||||
_ => false,
|
||||
};
|
||||
if user_exists {
|
||||
return Err(anyhow!("The user '{}' already exists.", user_name));
|
||||
}
|
||||
|
||||
cam.add_user(
|
||||
user_name,
|
||||
password,
|
||||
match user_type {
|
||||
UserType::User => 0,
|
||||
UserType::Administrator => 1,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.context("Unable to create user")
|
||||
}
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
println!("Successfully created user '{}'", user_name);
|
||||
}
|
||||
UserAction::Password {
|
||||
user_name,
|
||||
password,
|
||||
} => {
|
||||
camera
|
||||
.run_task(|cam| {
|
||||
Box::pin({
|
||||
let user_name = user_name.clone();
|
||||
let password = password.clone();
|
||||
async move {
|
||||
let user_list = cam
|
||||
.get_users()
|
||||
.await
|
||||
.context("Failed to list current users")?;
|
||||
let user_exists = match user_list.user_list {
|
||||
Some(users) => users.iter().any(|user| user.user_name == user_name),
|
||||
_ => false,
|
||||
};
|
||||
if !user_exists {
|
||||
return Err(anyhow!("The user '{}' does not exist.", user_name));
|
||||
}
|
||||
|
||||
cam.modify_user(user_name, password)
|
||||
.await
|
||||
.context("Unable to create user")
|
||||
}
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
println!("Successfully changed the password of '{}'", user_name);
|
||||
}
|
||||
UserAction::Delete { user_name } => {
|
||||
camera
|
||||
.run_task(|cam| {
|
||||
Box::pin({
|
||||
let user_name = user_name.clone();
|
||||
async move {
|
||||
let user_list = cam
|
||||
.get_users()
|
||||
.await
|
||||
.context("Failed to list current users")?;
|
||||
let user_exists = match user_list.user_list {
|
||||
Some(users) => users.iter().any(|user| user.user_name == user_name),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
if !user_exists {
|
||||
return Err(anyhow!("The user '{}' does not exist.", user_name));
|
||||
}
|
||||
|
||||
cam.delete_user(user_name)
|
||||
.await
|
||||
.context("Unable to delete user")
|
||||
}
|
||||
})
|
||||
})
|
||||
.await?;
|
||||
println!("Successfully removed user '{}'", user_name);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user