Fix MQTT issues

This commit is contained in:
QuantumEntangledAndy committed 2023-09-24 13:46:17 +07:00
1 parent 31d6c1ef62
commit 21ffcf3809
5 files changed
+245 -96

No files matched your search

+45
View File
@@ -227,4 +227,49 @@ impl NeoInstance {
.await?;
Ok(instance_rx.await?)
}
pub(crate) fn drop_command<F>(self, task: F, timeout: tokio::time::Duration) -> DropRunTask<F>
where
F: for<'a> Fn(
&'a BcCamera,
)
-> std::pin::Pin<Box<dyn futures::Future<Output = Result<()>> + Send + 'a>>,
{
DropRunTask {
instance: self,
command: Some(Box::new(task)),
timeout,
}
}
}
// A task that is run on a camera when the structure is dropped
pub(crate) struct DropRunTask<F>
where
F: for<'a> Fn(
&'a BcCamera,
) -> std::pin::Pin<Box<dyn futures::Future<Output = Result<()>> + Send + 'a>>,
{
instance: NeoInstance,
command: Option<Box<F>>,
timeout: tokio::time::Duration,
}
impl<F> Drop for DropRunTask<F>
where
F: for<'a> Fn(
&'a BcCamera,
) -> std::pin::Pin<Box<dyn futures::Future<Output = Result<()>> + Send + 'a>>,
{
fn drop(&mut self) {
if let Some(command) = self.command.take() {
tokio::task::block_in_place(move || {
let _ = tokio::runtime::Handle::current().block_on(async move {
tokio::time::timeout(self.timeout, self.instance.run_passive_task(*command))
.await??;
crate::AnyResult::Ok(())
});
});
}
}
}
+20
View File
@@ -250,6 +250,26 @@ impl NeoCam {
// This thread will apply battery saving by disconnecting the camera on certain events (like no motion)
// and reconnecting on other events like push notifications
let connect_instance = instance.subscribe().await?;
let connect_cancel = me.cancel.clone();
let connect_name = config.name.clone();
me.set.spawn(async move {
tokio::select! {
_ = connect_cancel.cancelled() => {
AnyResult::Ok(())
},
v = async {
let mut permit = connect_instance.permit().await?;
permit.deactivate().await?; // Watching only from here
loop {
permit.aquired_users().await?;
log::debug!("{connect_name}: InUse");
permit.dropped_users().await?;
log::debug!("{connect_name}: Idle");
}
} => v,
}
});
Ok(me)
}
+1 -1
View File
@@ -319,7 +319,7 @@ impl StreamData {
let (aud_history, _) = watch::<VecDeque<StampedData>>(VecDeque::new());
let aud_history = Arc::new(aud_history);
let resolution = instance
.run_task(|cam| {
.run_passive_task(|cam| {
Box::pin(async move {
let infos = cam
.get_stream_info()
+137 -92
View File
@@ -136,16 +136,27 @@ pub(crate) async fn main(_: Opt, reactor: NeoReactor) -> Result<()> {
.build()
.unwrap();
runtime.block_on(async move {
let camera = thread_reactor2.get(&name).await?;
tokio::select!(
_ = thread_global_cancel.cancelled() => {
AnyResult::Ok(())
},
_ = local_cancel.cancelled() => {
AnyResult::Ok(())
},
v = listen_on_camera(camera, mqtt_instance) => v,
)
loop {
let camera = thread_reactor2.get(&name).await?;
let mqtt_instance = mqtt_instance.resubscribe().await?;
let r = tokio::select!{
_ = thread_global_cancel.cancelled() => {
AnyResult::Ok(())
},
_ = local_cancel.cancelled() => {
AnyResult::Ok(())
},
v = listen_on_camera(camera, mqtt_instance) => {
v
},
};
if let Ok(()) = &r {
break r
} else {
log::debug!("listen_on_camera stopped: {:?}", r);
continue;
}
}
})
}) ;
}
@@ -264,10 +275,12 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
.send_message("status", "disconnected", true)
.await
.with_context(|| format!("Failed to publish status for {}", camera_name))?;
let _drop_message = mqtt_instance.drop_guard_message("status", "disconnected").await?;
mqtt_instance
.send_message("status/motion", "unknown", true)
.await
.with_context(|| format!("Failed to publish motion unknown for {}", camera_name))?;
let _drop_message2 = mqtt_instance.drop_guard_message("status/motion", "unknown").await?;
if let Some(discovery_config) = config.discovery.as_ref() {
enable_discovery(discovery_config, &mqtt_instance, &camera).await?;
@@ -300,6 +313,7 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
let (tx, mut rx) = mpsc(1);
tokio::select! {
v = async {
log::debug!("Listening to message on {}", mqtt_msg.get_name());
while let Ok(msg) = mqtt_msg.recv().await {
let mqtt_msg = mqtt_msg.resubscribe().await?;
let camera_msg = camera_msg.clone();
@@ -309,6 +323,7 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
tokio::select!{
_ = cancel_msg.cancelled() => AnyResult::Ok(()),
v = async {
// log::debug!("Got message: {msg:?}");
let res = handle_mqtt_message(msg, &mqtt_msg, &camera_msg).await;
if res.is_err() {
tx.send(res).await?;
@@ -318,6 +333,7 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
}
});
}
log::debug!("Listening to message on {}", mqtt_msg.get_name());
AnyResult::Ok(())
} => v,
v = rx.recv() => {
@@ -347,7 +363,7 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
// Handle the floodlight
v = async {
let (tx, mut rx) = mpsc(100);
tokio::select! {
let v = tokio::select! {
v = camera_floodlight.run_passive_task(|cam| {
let tx = tx.clone();
Box::pin(
@@ -376,6 +392,12 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
}
AnyResult::Ok(())
} => v,
};
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),
}?;
AnyResult::Ok(())
} => v,
@@ -383,18 +405,27 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
v = async {
let mut md = camera_motion.motion().await?;
loop {
md.wait_for(|state| matches!(state, MdState::Start(_))).await.with_context(|| {
format!("{}: MdStart Watch Dropped", camera_name)
})?;
mqtt_motion.send_message("status/motion", "on", true).await.with_context(|| {
format!("{}: Failed to publish motion start", camera_name)
})?;
md.wait_for(|state| matches!(state, MdState::Stop(_))).await.with_context(|| {
format!("{}: MdStop Watch Dropped", camera_name)
})?;
mqtt_motion.send_message("status/motion", "off", true).await.with_context(|| {
format!("{}: Failed to publish motion stop", camera_name)
})?;
let v = async {
md.wait_for(|state| matches!(state, MdState::Start(_))).await.with_context(|| {
format!("{}: MdStart Watch Dropped", camera_name)
})?;
mqtt_motion.send_message("status/motion", "on", true).await.with_context(|| {
format!("{}: Failed to publish motion start", camera_name)
})?;
md.wait_for(|state| matches!(state, MdState::Stop(_))).await.with_context(|| {
format!("{}: MdStop Watch Dropped", camera_name)
})?;
mqtt_motion.send_message("status/motion", "off", true).await.with_context(|| {
format!("{}: Failed to publish motion stop", 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),
}?;
}
} => v,
// Handle the SNAP (image preview)
@@ -404,31 +435,40 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
i.set_missed_tick_behavior(MissedTickBehavior::Skip);
i
});
while wait.next().await.is_some() {
let image = camera_snap.run_passive_task(|cam| {
Box::pin(async move {
let image = cam.get_snapshot().await?;
AnyResult::Ok(image)
})
}).await;
let image = match image {
Err(e) => match e.downcast::<neolink_core::Error>() {
Ok(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Image not supported");
futures::future::pending().await
},
Ok(e) => Err(e.into()),
Err(e) => Err(e),
}
n => n,
}?;
mqtt_snap
.send_message("status/preview", BASE64.encode(image).as_str(), true)
.await
.with_context(|| {
format!("{}: Failed to publish preview", camera_name)
})?;
}
let v = async {
while wait.next().await.is_some() {
let image = camera_snap.run_passive_task(|cam| {
Box::pin(async move {
let image = cam.get_snapshot().await?;
AnyResult::Ok(image)
})
}).await;
let image = match image {
Err(e) => match e.downcast::<neolink_core::Error>() {
Ok(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Image not supported");
futures::future::pending().await
},
Ok(e) => Err(e.into()),
Err(e) => Err(e),
}
n => n,
}?;
mqtt_snap
.send_message("status/preview", BASE64.encode(image).as_str(), true)
.await
.with_context(|| {
format!("{}: Failed to publish preview", 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),
}?;
AnyResult::Ok(())
} => v,
// Handle the battery publish
@@ -438,31 +478,41 @@ async fn listen_on_camera(camera: NeoInstance, mqtt_instance: MqttInstance) -> R
i.set_missed_tick_behavior(MissedTickBehavior::Skip);
i
});
while wait.next().await.is_some() {
let xml = camera_battery.run_passive_task(|cam| {
Box::pin(async move {
let xml = cam.battery_info().await?;
AnyResult::Ok(xml)
})
}).await;
let xml = match xml {
Err(e) => match e.downcast::<neolink_core::Error>() {
Ok(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Battery not supported");
futures::future::pending().await
},
Ok(e) => Err(e.into()),
Err(e) => Err(e),
}
n => n,
}?;
mqtt_battery
.send_message("status/battery_level", format!("{}", xml.battery_percent).as_str(), true)
.await
.with_context(|| {
format!("{}: Failed to publish battery", camera_name)
})?;
}
let v = async {
while wait.next().await.is_some() {
let xml = camera_battery.run_passive_task(|cam| {
Box::pin(async move {
let xml = cam.battery_info().await?;
AnyResult::Ok(xml)
})
}).await;
let xml = match xml {
Err(e) => match e.downcast::<neolink_core::Error>() {
Ok(neolink_core::Error::CameraServiceUnavaliable) => {
log::debug!("Battery not supported");
futures::future::pending().await
},
Ok(e) => Err(e.into()),
Err(e) => Err(e),
}
n => n,
}?;
mqtt_battery
.send_message("status/battery_level", format!("{}", xml.battery_percent).as_str(), true)
.await
.with_context(|| {
format!("{}: Failed to publish battery", 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),
}?;
AnyResult::Ok(())
} => v
}?;
@@ -712,10 +762,22 @@ async fn handle_mqtt_message(
};
if let (Some(seconds), Some(bc_direction)) = (seconds, bc_direction) {
// On drop send the stop command again just to make sure it stops
let _drop_command = camera.clone().drop_command(
|cam| {
Box::pin(async move {
cam.send_ptz(BcDirection::Stop, speed).await?;
AnyResult::Ok(())
})
},
Duration::from_millis(100),
);
if let Err(e) = camera
.run_task(|cam| {
Box::pin(async move {
cam.send_ptz(bc_direction, speed).await?;
sleep(Duration::from_secs_f32(seconds)).await;
cam.send_ptz(BcDirection::Stop, speed).await?;
AnyResult::Ok(())
})
})
@@ -724,24 +786,7 @@ async fn handle_mqtt_message(
error!("Failed to send PTZ: {:?}", e);
"FAIL"
} else {
// 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) = camera
.run_task(|cam| {
Box::pin(async move {
cam.send_ptz(bc_direction, speed).await?;
AnyResult::Ok(())
})
})
.await
{
error!("Failed to send PTZ: {:?}", e);
"FAIL"
} else {
"OK"
}
"OK"
}
} else {
"FAIL"
@@ -946,7 +991,7 @@ async fn handle_mqtt_message(
"OK"
}
Err(_) => {
error!("Failed to encode pur status");
error!("Failed to encode pir status");
"FAIL"
}
},
+42 -3
View File
@@ -328,6 +328,10 @@ pub(crate) struct MqttInstance {
}
impl MqttInstance {
pub(crate) fn get_name(&self) -> &str {
&self.name
}
pub async fn subscribe<T: Into<String>>(&self, name: T) -> AnyResult<Self> {
let (tx, rx) = oneshot();
self.outgoing_tx
@@ -405,27 +409,44 @@ impl MqttInstance {
.incomming_rx
.next()
.await
.ok_or(anyhow!("End or client data"))?
.with_context(|| "Clinet stream is too far behind")?;
.ok_or(anyhow!("End of client data"))?
.with_context(|| "Client stream is too far behind")?;
// log::debug!("Got MQTT: {msg:?}");
// log::debug!("self.name: {:?}", self.name);
if self.name.is_empty() {
break msg;
} else {
let mut topics = msg.topic.split('/');
let sub_topic = topics.next();
// log::debug!("topics: {:?}", msg.topic);
// log::debug!("sub_topic: {sub_topic:?}");
if sub_topic
.map(|subtopic| *subtopic == self.name)
.unwrap_or(false)
{
msg.topic = topics.collect::<Vec<_>>().join("/");
// log::debug!("new topics: {:?}", msg.topic);
break msg;
}
}
})
}
pub(crate) async fn drop_guard_message(
&self,
topic: &str,
message: &str,
) -> AnyResult<DropSender> {
Ok(DropSender {
instance: self.resubscribe().await?,
topic: topic.to_string(),
message: message.to_string(),
})
}
}
#[derive(Clone)]
#[derive(Clone, Debug)]
pub(crate) struct MqttReply {
pub(crate) topic: String,
pub(crate) message: String,
@@ -451,3 +472,21 @@ enum MqttRequest {
HangUp(OneshotSender<()>),
Subscribe(String, OneshotSender<Result<MqttInstance>>),
}
pub(crate) struct DropSender {
instance: MqttInstance,
topic: String,
message: String,
}
impl Drop for DropSender {
fn drop(&mut self) {
tokio::task::block_in_place(move || {
let _ = tokio::runtime::Handle::current().block_on(async move {
self.instance
.send_message(&self.topic, &self.message, true)
.await
});
});
}
}