Merge remote-tracking branch 'upstream/master' into discovery

This commit is contained in:
Andrew committed 2023-06-08 13:36:29 +07:00
commit 15bf7cfa49
7 files changed
+170 -34

No files matched your search

+6 -2
View File
@@ -190,9 +190,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/preset [id]` Move to PTZ preset `id`
- `/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:
@@ -206,11 +207,14 @@ Status Messages:
- `/status/pir` Sent in reply to a `/query/pir` an XML encoded version of the
pir status
- `/status/motion` Contains the motion detection alarm status. `on` for motion and `off` for still
- `/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
#### MQTT Discovery
+3 -3
View File
@@ -586,7 +586,7 @@ pub struct PtzPreset {
pub channel_id: u8,
/// List of presets
#[yaserde(rename = "presetList")]
pub preset_list: Option<PresetList>,
pub preset_list: PresetList,
}
/// A preset list
@@ -600,11 +600,11 @@ pub struct PresetList {
#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)]
pub struct Preset {
/// The ID of the preset
pub id: i8,
pub id: u8,
/// The preset name
pub name: Option<String>,
/// Command: Known values: `"toPos"` and `"setPos"`
pub command: Option<String>,
pub command: String,
}
/// A list of battery infos. This message is sent from the camera as
+67 -12
View File
@@ -129,10 +129,10 @@ impl BcCamera {
}
}
/// Set a PTZ preset. If a [name] is given the current position will be saved as a preset
/// with the given [preset_id] and [name], otherwise the camera will attempt to move to the
/// preset with the given ID.
pub async fn set_ptz_preset(&self, preset_id: i8, name: Option<String>) -> Result<()> {
/// 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();
@@ -140,7 +140,11 @@ impl BcCamera {
.subscribe(MSG_ID_PTZ_CONTROL_PRESET, msg_num)
.await?;
let command = if name.is_some() { "setPos" } else { "toPos" };
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,
@@ -158,13 +162,64 @@ impl BcCamera {
}),
payload: Some(BcPayloads::BcXml(BcXml {
ptz_preset: Some(PtzPreset {
preset_list: Some(PresetList {
preset: vec![Preset {
id: preset_id,
name,
command: Some(command.to_string()),
}],
}),
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_ID_PTZ_CONTROL_PRESET, 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()
+38 -2
View File
@@ -31,9 +31,11 @@ pub(crate) enum Messages {
PIROff,
PIRQuery,
Ptz(Direction),
Preset(i8),
Snap(Vec<u8>),
BatteryLevel(u32),
Preset(u8),
PresetAssign(u8, String),
PresetQuery,
}
#[derive(Debug, Copy, Clone)]
@@ -647,13 +649,47 @@ impl<'a> MessageHandler<'a> {
}
}
Messages::Preset(id) => {
if let Err(e) = self.camera.set_ptz_preset(id, None).await {
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 {
+39 -3
View File
@@ -16,7 +16,8 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
/// - `/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/preset` [id] Move the camera to a known preset
/// - `/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:
///
@@ -24,11 +25,13 @@ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
/// `/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
@@ -400,10 +403,10 @@ async fn handle_mqtt_message(
}
}
MqttReplyRef {
topic: "control/preset",
topic: "control/ptz/preset",
message,
} => {
if let Ok(id) = message.parse::<i8>() {
if let Ok(id) = message.parse::<u8>() {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Preset(id))
@@ -414,6 +417,27 @@ async fn handle_mqtt_message(
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",
@@ -459,6 +483,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 {
+4 -6
View File
@@ -23,12 +23,10 @@ pub struct Opt {
#[derive(Parser, Debug)]
pub enum PtzCommand {
/// Gets the available presets on the camera, moves the camera to a given preset ID or saves
/// the current position as a preset with name and ID.
Preset {
preset_id: Option<i8>,
name: Option<String>,
},
/// 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
+13 -6
View File
@@ -15,7 +15,7 @@
/// # 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 preset 0 PresetName
/// neolink ptz --config=config.toml CameraName assign 0 PresetName
/// ```
///
use anyhow::{Context, Result};
@@ -37,10 +37,10 @@ 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, name } => {
if preset_id.is_some() {
PtzCommand::Preset { preset_id } => {
if let Some(preset_id) = preset_id {
camera
.set_ptz_preset(preset_id.unwrap(), name)
.moveto_ptz_preset(preset_id)
.await
.context("Unable to set PTZ preset")
.expect("TODO: panic message");
@@ -50,11 +50,18 @@ pub(crate) async fn main(opt: Opt, config: Config) -> Result<()> {
.await
.context("Unable to get PTZ presets")?;
println!("Available presets:\nID Name");
for preset in preset_list.preset_list.unwrap().preset {
println!("{:<2} {}", preset.id, preset.name.unwrap());
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,