Compare commits

...
12 Commits
Author SHA1 Message Date
QuantumEntangledAndy b9fd2f75ff v0.5.10 2023-05-14 12:33:57 +07:00
Andrew 61f65ed42a Merge remote-tracking branch 'origin/master' 2023-05-14 12:31:34 +07:00
Andrew King 634bff08af Merge pull request #72 from AdrianosBates/fix/ptz-stop
Fix/ptz stop
2023-05-14 12:23:39 +07:00
QuantumEntangledAndy 2d1ccf518a Clippy fixes 2023-05-14 10:45:34 +07:00
QuantumEntangledAndy d9600d0607 Filter out OK/FAIL replies 2023-05-14 10:40:46 +07:00
QuantumEntangledAndy 72cf358b0c Make mqtt messgae handler cleaner 2023-05-14 08:46:22 +07:00
QuantumEntangledAndy a819248556 Rework MQTT to allow async message handelling 2023-05-13 20:03:08 +07:00
QuantumEntangledAndy 6e334392da Merge branch 'master' of https://github.com/QuantumEntangledAndy/neolink into fix/ptz-stop 2023-05-13 16:52:40 +07:00
Adrian Bates 03a7e1473a Fixed mistake in new error message 2023-04-25 16:14:55 -04:00
Adrian Bates 5ccdc27d37 In mod.rs:
Removed the ability to send "stop" PTZ command with MQTT
	Changed the signature of PTZ MQTT commands to (direction amount seconds), where seconds is currently checked and limited to the range 0.0 - 10.0
In event_cam.rs:
	stop has been removed from event_cam.Direction, and directions now take an additional f32 seconds parameter
	in Message::PTZ if the intial send_ptz is successful, will sleep for designated seconds and then issue a stop command
2023-04-25 15:49:08 -04:00
Adrian Bates 29b47aa44e Changed Unrecognized PTZ Direction error to include unrecognized command 2023-04-22 11:41:45 -04:00
Adrian Bates 427046239c Added stop command to PTZ 2023-04-22 11:13:59 -04:00
8 changed files with 274 additions and 186 deletions

No files matched your search

Generated
+2 -2
View File
@@ -1402,7 +1402,7 @@ dependencies = [
[[package]]
name = "neolink"
version = "0.5.9"
version = "0.5.10"
dependencies = [
"anyhow",
"byte-slice-cast",
@@ -1432,7 +1432,7 @@ dependencies = [
[[package]]
name = "neolink_core"
version = "0.5.9"
version = "0.5.10"
dependencies = [
"aes",
"assert_matches",
+2 -2
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink"
description = "A standards-compliant bridge to Reolink IP cameras"
version = "0.5.9"
version = "0.5.10"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
@@ -25,7 +25,7 @@ gstreamer-rtsp = "0.20.0"
gstreamer-rtsp-server = { version = "0.20.3", features = ["v1_16"] }
lazy_static = "1.4.0"
log = { version = "0.4.17", features = [ "release_max_level_debug" ] }
neolink_core = { path = "crates/core", version = "0.5.9" }
neolink_core = { path = "crates/core", version = "0.5.10" }
regex = "1.7.3"
rumqttc = "0.20.0"
serde = { version = "1.0.160", features = ["derive"] }
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "neolink_core"
description = "Core services and structure for Reolink IP cameras"
version = "0.5.9"
version = "0.5.10"
authors = ["George Hilliard <thirtythreeforty@gmail.com>", "Andrew King <sheepchaan@gmail.com>"]
edition = "2018"
license = "AGPL-3.0-or-later"
@@ -296,7 +296,7 @@ impl Stream for UdpPayloadSource {
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let camera_addr = self.inner.addr;
let mut this = self.get_mut();
let this = self.get_mut();
match this.state {
State::Normal => {
// this.state = State::YieldNow;
@@ -417,7 +417,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
}
}
fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> std::result::Result<(), Self::Error> {
let mut this = self.get_mut();
let this = self.get_mut();
for chunk in item.chunks(MTU - UDPDATA_HEADER_SIZE) {
let udp_data = UdpData {
connection_id: this.camera_id,
@@ -487,7 +487,7 @@ impl Sink<Vec<u8>> for UdpPayloadSource {
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<std::result::Result<(), Self::Error>> {
let mut this = self.get_mut();
let this = self.get_mut();
if let State::Closed = this.state {
return Poll::Ready(Ok(()));
}
+3
View File
@@ -15,6 +15,8 @@ pub enum Direction {
In,
/// To zoom the camera Out (may be done with cropping depending on camera model)
Out,
/// To stop currently active PTZ command
Stop,
}
impl BcCamera {
@@ -36,6 +38,7 @@ impl BcCamera {
Direction::Out => {
todo!()
}
Direction::Stop => "stop",
}
.to_string();
let send = Bc {
+40 -14
View File
@@ -9,8 +9,11 @@ use std::sync::Arc;
use tokio::{
sync::mpsc::{channel, Receiver, Sender},
task::JoinSet,
time::sleep,
};
use core::time::Duration;
#[derive(Debug, Copy, Clone)]
pub(crate) enum Messages {
Login,
@@ -31,12 +34,12 @@ pub(crate) enum Messages {
#[derive(Debug, Copy, Clone)]
pub(crate) enum Direction {
Up(f32),
Down(f32),
Left(f32),
Right(f32),
In(f32),
Out(f32),
Up(f32, f32),
Down(f32, f32),
Left(f32, f32),
Right(f32, f32),
In(f32, f32),
Out(f32, f32),
}
#[derive(Debug)]
@@ -408,19 +411,42 @@ impl<'a> MessageHandler<'a> {
}
}
Messages::Ptz(direction) => {
let (bc_direction, amount) = match direction {
Direction::Up(amount) => (BcDirection::Up, amount),
Direction::Down(amount) => (BcDirection::Down, amount),
Direction::Left(amount) => (BcDirection::Left, amount),
Direction::Right(amount) => (BcDirection::Right, amount),
Direction::In(amount) => (BcDirection::In, amount),
Direction::Out(amount) => (BcDirection::Out, amount),
let (bc_direction, amount, seconds) = match direction {
Direction::Up(amount, seconds) => {
(BcDirection::Up, amount, seconds)
}
Direction::Down(amount, seconds) => {
(BcDirection::Down, amount, seconds)
}
Direction::Left(amount, seconds) => {
(BcDirection::Left, amount, seconds)
}
Direction::Right(amount, seconds) => {
(BcDirection::Right, amount, seconds)
}
Direction::In(amount, seconds) => {
(BcDirection::In, amount, seconds)
}
Direction::Out(amount, seconds) => {
(BcDirection::Out, amount, seconds)
}
};
if let Err(e) = self.camera.send_ptz(bc_direction, amount).await {
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
// sleep for the designated seconds
sleep(Duration::from_secs_f32(seconds)).await;
// note that amount is not used in the stop command
if let Err(e) =
self.camera.send_ptz(BcDirection::Stop, amount).await
{
error = Some(format!("Failed to send PTZ: {:?}", e));
"FAIL".to_string()
} else {
"OK".to_string()
}
}
}
_ => "UNKNOWN COMMAND".to_string(),
+222 -164
View File
@@ -67,6 +67,11 @@ pub(crate) use event_cam::{Direction, Messages};
use log::*;
use mqttc::{Mqtt, MqttReplyRef};
use self::{
event_cam::EventCamSender,
mqttc::{MqttReply, MqttSender},
};
/// Entry point for the mqtt subcommand
///
/// Opt is the command line options
@@ -118,175 +123,36 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
// Listen on mqtt messages and post on camera
let camera_name = cam_config.name.clone();
// When one error is recieved we pass it up async
let (error_send, mut error_recv) = tokio::sync::mpsc::channel::<Error>(1);
let mqtt_to_cam = async {
while let Ok(msg) = mqtt.poll().await {
tokio::task::yield_now().await;
let mut reply = None;
let mut reply_topic = None;
match msg.as_ref() {
MqttReplyRef {
topic: "control/led",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::StatusLedOn)
.await
.with_context(|| "Failed to set camera status light on")?,
);
}
MqttReplyRef {
topic: "control/led",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::StatusLedOff)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedOn)
.await
.with_context(|| "Failed to set camera status light on")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedOff)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "auto",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedAuto)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/reboot",
..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Reboot)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ptz",
message,
} => {
let lowercase_message = message.to_lowercase();
let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() {
let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() {
let direction = match direction_txt {
"up" => Direction::Up(amount),
"down" => Direction::Down(amount),
"left" => Direction::Left(amount),
"right" => Direction::Right(amount),
"in" => Direction::In(amount),
"out" => Direction::Out(amount),
_ => {
error!("Unrecongnized PTZ direction");
continue;
}
};
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Ptz(direction))
.await
.with_context(|| "Failed to send PTZ")?,
);
} else {
error!("No PTZ direction speed was not a valid number");
// Select to wait on an error (via the channel) or normal poll ops
tokio::select! {
v = async {
// Normal poll operations
while let Ok(msg) = mqtt.poll().await {
tokio::task::yield_now().await;
// Put the reply on it's own async thread so we can safely sleep
// and wait for it to reply in it's own time
let event_cam_sender = event_cam_sender.clone();
let mqtt_sender_mqtt = mqtt_sender_mqtt.clone();
let error_send = error_send.clone();
tokio::task::spawn(async move {
// Handle the message and wait for ok/error on this thread
let result: Result<()> = handle_mqtt_message(&msg, event_cam_sender, mqtt_sender_mqtt).await;
// If there is an error we pass it to the channel
// this allows for async error handelling
if let Err(e) = result {
let _ = error_send.try_send(e);
}
} else {
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
}
});
}
MqttReplyRef {
topic: "control/pir",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIROn)
.await
.with_context(|| "Failed to set pir on")?,
);
}
MqttReplyRef {
topic: "control/pir",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIROff)
.await
.with_context(|| "Failed to set pir off")?,
);
}
MqttReplyRef {
topic: "query/battery",
..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Battery)
.await
.with_context(|| "Failed to get battery status")?,
);
reply_topic = Some("status/battery");
}
MqttReplyRef {
topic: "query/pir", ..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIRQuery)
.await
.with_context(|| "Failed to get pir status")?,
);
reply_topic = Some("status/pir");
}
_ => {}
}
if let Some(reply) = reply {
if let Some(topic) = reply_topic {
mqtt_sender_mqtt
.send_message(topic, &reply, false)
.await
.with_context(|| "Failed to send Camera reply to Mqtt")?;
} else {
mqtt_sender_mqtt
.send_message(&msg.topic, &reply, false)
.await
.with_context(|| "Failed to send Camera reply to Mqtt")?;
}
}
Ok(())
} => v,
// Wait on any error from any of the error channels and if we get it we abort
v = error_recv.recv() => v.map(Err).unwrap_or_else(|| Err(anyhow!("Listen on camera error channel closed"))),
}
Result::<(), Error>::Ok(())
};
let cam_to_mqtt = async {
@@ -329,3 +195,195 @@ async fn listen_on_camera(cam_config: Arc<CameraConfig>, mqtt_config: &MqttConfi
Ok(())
}
async fn handle_mqtt_message(
msg: &MqttReply,
event_cam_sender: EventCamSender,
mqtt_sender_mqtt: MqttSender,
) -> Result<()> {
let mut reply = None;
let mut reply_topic = None;
match msg.as_ref() {
MqttReplyRef {
topic: _,
message: "OK",
}
| MqttReplyRef {
topic: _,
message: "FAIL",
} => {
// Do nothing for the success/fail replies
}
MqttReplyRef {
topic: "control/led",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::StatusLedOn)
.await
.with_context(|| "Failed to set camera status light on")?,
);
}
MqttReplyRef {
topic: "control/led",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::StatusLedOff)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedOn)
.await
.with_context(|| "Failed to set camera status light on")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedOff)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ir",
message: "auto",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::IRLedAuto)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/reboot",
..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Reboot)
.await
.with_context(|| "Failed to set camera status light off")?,
);
}
MqttReplyRef {
topic: "control/ptz",
message,
} => {
let lowercase_message = message.to_lowercase();
let mut words = lowercase_message.split_whitespace();
if let Some(direction_txt) = words.next() {
// Target amount to move
let amount = words.next().unwrap_or("32.0");
if let Ok(amount) = amount.parse::<f32>() {
let seconds = amount / 32f32;
// range checking on seconds so that you can't sleep for 3.4E+38 seconds
match seconds {
x if (0.0..10.0).contains(&x) => seconds,
_ => {
error!("seconds was not a valid number (out of range)");
return Ok(());
}
};
let direction = match direction_txt {
"up" => Direction::Up(amount, seconds),
"down" => Direction::Down(amount, seconds),
"left" => Direction::Left(amount, seconds),
"right" => Direction::Right(amount, seconds),
"in" => Direction::In(amount, seconds),
"out" => Direction::Out(amount, seconds),
_ => {
error!("Unrecognized PTZ direction \"{}\"", direction_txt);
return Ok(());
}
};
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Ptz(direction))
.await
.with_context(|| "Failed to send PTZ")?,
);
} else {
error!("No PTZ direction speed was not a valid number");
}
} else {
error!("No PTZ Direction given. Please add up/down/left/right/in/out");
}
}
MqttReplyRef {
topic: "control/pir",
message: "on",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIROn)
.await
.with_context(|| "Failed to set pir on")?,
);
}
MqttReplyRef {
topic: "control/pir",
message: "off",
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIROff)
.await
.with_context(|| "Failed to set pir off")?,
);
}
MqttReplyRef {
topic: "query/battery",
..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::Battery)
.await
.with_context(|| "Failed to get battery status")?,
);
reply_topic = Some("status/battery");
}
MqttReplyRef {
topic: "query/pir", ..
} => {
reply = Some(
event_cam_sender
.send_message_with_reply(Messages::PIRQuery)
.await
.with_context(|| "Failed to get pir status")?,
);
reply_topic = Some("status/pir");
}
_ => {}
}
if let Some(reply) = reply {
if let Some(topic) = reply_topic {
mqtt_sender_mqtt
.send_message(topic, &reply, false)
.await
.with_context(|| "Failed to send Camera reply to Mqtt")?;
} else {
mqtt_sender_mqtt
.send_message(&msg.topic, &reply, false)
.await
.with_context(|| "Failed to send Camera reply to Mqtt")?;
}
}
Ok(())
}
+1
View File
@@ -43,6 +43,7 @@ struct MqttReciever {
name: String,
}
#[derive(Clone)]
pub(crate) struct MqttSender {
client: Arc<AsyncClient>,
name: String,