diff --git a/README.md b/README.md index 8cde7cf..ca6485a 100644 --- a/README.md +++ b/README.md @@ -188,9 +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/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: @@ -202,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 diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 3cda05c..618e055 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -583,7 +583,7 @@ pub struct PtzPreset { pub channel_id: u8, /// List of presets #[yaserde(rename = "presetList")] - pub preset_list: Option, + pub preset_list: PresetList, } /// A preset list @@ -597,11 +597,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, /// Command: Known values: `"toPos"` and `"setPos"` - pub command: Option, + pub command: String, } /// A list of battery infos. This message is sent from the camera as diff --git a/crates/core/src/bc_protocol/ptz.rs b/crates/core/src/bc_protocol/ptz.rs index 0e08843..4cc2411 100644 --- a/crates/core/src/bc_protocol/ptz.rs +++ b/crates/core/src/bc_protocol/ptz.rs @@ -129,21 +129,19 @@ 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) -> 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(); let mut sub_set = connection.subscribe(msg_num).await?; - let command = if name.is_some() { "setPos" } else { "toPos" }; let preset = Preset { id: preset_id, - name, - command: Some(command.to_string()), - ..Default::default() + name: Some(name), + command: "setPos".to_owned(), }; let send = Bc { meta: BcMeta { @@ -162,9 +160,64 @@ impl BcCamera { }), payload: Some(BcPayloads::BcXml(BcXml { ptz_preset: Some(PtzPreset { - preset_list: Some(PresetList { + 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() diff --git a/src/mqtt/event_cam.rs b/src/mqtt/event_cam.rs index 6fc652b..76a4c0d 100644 --- a/src/mqtt/event_cam.rs +++ b/src/mqtt/event_cam.rs @@ -13,7 +13,7 @@ use tokio::{ time::{interval, sleep, Duration}, }; -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Clone)] pub(crate) enum Messages { Login, MotionStop, @@ -31,7 +31,9 @@ pub(crate) enum Messages { PIROff, PIRQuery, Ptz(Direction), - Preset(i8), + Preset(u8), + PresetAssign(u8, String), + PresetQuery, } #[derive(Debug, Copy, Clone)] @@ -544,13 +546,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 { diff --git a/src/mqtt/mod.rs b/src/mqtt/mod.rs index d0b0056..8abb219 100644 --- a/src/mqtt/mod.rs +++ b/src/mqtt/mod.rs @@ -14,7 +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/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: /// @@ -22,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 @@ -372,10 +375,10 @@ async fn handle_mqtt_message( } } MqttReplyRef { - topic: "control/preset", + topic: "control/ptz/preset", message, } => { - if let Ok(id) = message.parse::() { + if let Ok(id) = message.parse::() { reply = Some( event_cam_sender .send_message_with_reply(Messages::Preset(id)) @@ -386,6 +389,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::()), 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::()), name) { + error!("PTZ preset was not a valid number"); + } else if let (_, None) = (id.map(|id| id.parse::()), name) { + error!("PTZ preset was not given a name"); + } + } MqttReplyRef { topic: "control/pir", message: "on", @@ -431,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 { diff --git a/src/ptz/cmdline.rs b/src/ptz/cmdline.rs index 6e54a6d..66d474e 100644 --- a/src/ptz/cmdline.rs +++ b/src/ptz/cmdline.rs @@ -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, - name: Option, - }, + /// Move to a stored preset + Preset { preset_id: Option }, + /// 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 diff --git a/src/ptz/mod.rs b/src/ptz/mod.rs index 58fe4ad..acdd392 100644 --- a/src/ptz/mod.rs +++ b/src/ptz/mod.rs @@ -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,