Update mqtt to use asyncio

This commit is contained in:
QuantumEntangledAndy committed 2023-04-18 20:27:53 +07:00
1 parent 3f4bc510a7
commit 45fec7cfc2
10 files changed
+217 -166

No files matched your search

@@ -101,6 +101,7 @@ impl Discoverer {
let thread_subscriber = subsribers.clone();
set.spawn(async move {
loop {
tokio::task::yield_now().await;
match reader.next().await {
Some(Ok((BcUdp::Discovery(bcudp), addr))) => {
let mut tid = bcudp.tid;
@@ -852,6 +853,7 @@ impl Discoverer {
let mut interval = interval(Duration::from_secs(1));
self.handle.write().await.spawn(async move {
loop {
tokio::task::yield_now().await;
interval.tick().await;
let msg = BcUdp::Discovery(UdpDiscovery {
tid,
@@ -880,6 +882,7 @@ impl Discoverer {
let mut interval = interval(Duration::from_secs(1));
self.handle.write().await.spawn(async move {
loop {
tokio::task::yield_now().await;
interval.tick().await;
let msg = BcUdp::Discovery(UdpDiscovery {
tid,
+1
View File
@@ -216,6 +216,7 @@ impl BcCamera {
let mut sub = connection.subscribe(msg_num).await?;
loop {
tokio::task::yield_now().await;
let msg = sub.recv().await;
let status = match msg {
Ok(motion_msg) => {
+1
View File
@@ -105,6 +105,7 @@ impl BcCamera {
let channel_id = self.channel_id;
let handle = task::spawn(async move {
tokio::task::yield_now().await;
let mut sub_video = connection.subscribe(msg_num).await?;
// On an E1 and swann cameras:
+1
View File
@@ -65,6 +65,7 @@ async fn output(pipeline: Pipeline) -> Result<GstSender> {
let mut set = JoinSet::new();
set.spawn(async move {
while let Some(control) = reciever.recv().await {
tokio::task::yield_now().await;
match control {
GstControl::Data(buf) => {
let mut gst_buf = gstreamer::Buffer::with_size(buf.len()).unwrap();
+1
View File
@@ -130,6 +130,7 @@ impl EventCam {
while self.app.running(&self.config.name) {
// Ignore errors and just loop
tokio::task::yield_now().await;
let _ = Self::cam_run(
&loop_config,
loop_tx.clone(),
+32 -17
View File
@@ -93,6 +93,7 @@ pub(crate) async fn main(_: Opt, config: Config) -> Result<()> {
info!("{}: Setting up mqtt", camera_config.name);
set.spawn(async move {
while loop_arc_app.running("app") {
tokio::task::yield_now().await;
let _ =
listen_on_camera(camera_config.clone(), &mqtt_config, loop_arc_app.clone())
.await;
@@ -115,7 +116,7 @@ async fn listen_on_camera(
) -> Result<()> {
// Camera thread
let arc_event_cam = Arc::new(EventCam::new(cam_config.clone(), arc_app.clone()));
let arc_mqtt = Mqtt::new(mqtt_config, &cam_config.name, arc_app.clone());
let mut mqtt = Mqtt::new(mqtt_config, &cam_config.name, arc_app.clone()).await;
let mut set = tokio::task::JoinSet::new();
// Start listening to camera events
let event_cam = arc_event_cam.clone();
@@ -124,35 +125,40 @@ async fn listen_on_camera(
event_cam.abort(); // Just to ensure everything aborts
});
// Start listening to mqtt events
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
set.spawn(async move {
let _ = mqtt.start().is_err();
event_cam.abort();
});
// Listen on camera messages and post on mqtt
let camera_name = cam_config.name.clone();
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
let app = arc_app.clone();
let mqtt_sender = mqtt.get_sender();
set.spawn(async move {
while app.running(&format!("app: {}", camera_name)) {
tokio::task::yield_now().await;
if let Ok(msg) = event_cam.poll().await {
match msg {
Messages::Login => {
if mqtt.send_message("status", "connected", true).is_err() {
if mqtt_sender
.send_message("status", "connected", true)
.await
.is_err()
{
error!("Failed to post connect over MQTT for {}", camera_name);
}
}
Messages::MotionStop => {
if mqtt.send_message("status/motion", "off", true).is_err() {
if mqtt_sender
.send_message("status/motion", "off", true)
.await
.is_err()
{
error!("Failed to publish motion stop for {}", camera_name);
}
}
Messages::MotionStart => {
if mqtt.send_message("status/motion", "on", true).is_err() {
if mqtt_sender
.send_message("status/motion", "on", true)
.await
.is_err()
{
error!("Failed to publish motion start for {}", camera_name);
}
}
@@ -164,12 +170,13 @@ async fn listen_on_camera(
// Listen on mqtt messages and post on camera
let event_cam = arc_event_cam.clone();
let mqtt = arc_mqtt.clone();
let app = arc_app.clone();
let camera_name = cam_config.name.clone();
let mqtt_sender = mqtt.get_sender();
set.spawn(async move {
while app.running(&format!("app: {}", camera_name)) {
if let Ok(msg) = mqtt.poll() {
tokio::task::yield_now().await;
if let Ok(msg) = mqtt.poll().await {
match msg.as_ref() {
MqttReplyRef {
topic: "control/led",
@@ -279,7 +286,11 @@ async fn listen_on_camera(
..
} => match event_cam.send_message_with_reply(Messages::Battery).await {
Ok(reply) => {
if mqtt.send_message("status/battery", &reply, false).is_err() {
if mqtt_sender
.send_message("status/battery", &reply, false)
.await
.is_err()
{
error!("Failed to send battery status reply");
}
}
@@ -289,7 +300,11 @@ async fn listen_on_camera(
topic: "query/pir", ..
} => match event_cam.send_message_with_reply(Messages::PIRQuery).await {
Ok(reply) => {
if mqtt.send_message("status/pir", &reply, false).is_err() {
if mqtt_sender
.send_message("status/pir", &reply, false)
.await
.is_err()
{
error!("Failed to send pir status reply");
}
}
+175 -149
View File
@@ -1,23 +1,21 @@
use super::App;
use crate::config::MqttConfig;
use anyhow::{Context, Result};
use crossbeam_channel::{unbounded, Receiver, RecvError, Sender};
use log::*;
use rumqttc::{
Client, ClientError, ConnectReturnCode, Connection, Event, Incoming, Key, LastWill,
AsyncClient, ClientError, ConnectReturnCode, Event, EventLoop, Incoming, Key, LastWill,
MqttOptions, Publish, QoS, TlsConfiguration, Transport,
};
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::task::JoinSet;
pub(crate) struct Mqtt {
app: Arc<App>,
client: Mutex<Client>,
connection: Mutex<Connection>,
client: Arc<AsyncClient>,
name: String,
incoming: (Sender<Publish>, Receiver<Publish>),
msg_channel: (Sender<MqttReply>, Receiver<MqttReply>),
drop_message: Mutex<Option<MqttReply>>,
incoming: Receiver<MqttReply>,
drop_message: Option<MqttReply>,
}
pub(crate) struct MqttReply {
@@ -39,10 +37,121 @@ pub(crate) struct MqttReplyRef<'a> {
pub(crate) message: &'a str,
}
struct MqttReciever {
app: Arc<App>,
client: MqttSender,
incoming_tx: Sender<MqttReply>,
name: String,
}
pub(crate) struct MqttSender {
client: Arc<AsyncClient>,
name: String,
}
impl MqttSender {
pub async fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
self.client
.publish(
format!("neolink/{}/{}", self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.await?;
Ok(())
}
async fn subscribe(&self) -> Result<(), ClientError> {
self.client
.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)
.await?;
Ok(())
}
async fn update_status(&self) -> Result<()> {
self.send_message("status", "disconnected", true).await?;
Ok(())
}
pub fn try_send_message(&self, sub_topic: &str, message: &str, retain: bool) -> Result<()> {
self.client
.try_publish(
format!("neolink/{}/{}", self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)
.map_err(|e| e.into())
}
}
impl MqttReciever {
async fn run(&mut self, connection: &mut EventLoop) -> Result<()> {
// This acts as an event loop
let name = self.name.clone();
info!("Starting MQTT Client for {}", name);
while self.app.running(&format!("app:{}", name)) {
if let Ok(notification) = connection.poll().await {
// if let Ok(notification) = notification {
match notification {
Event::Incoming(Incoming::ConnAck(connected)) => {
if ConnectReturnCode::Success == connected.code {
self.client
.update_status()
.await
.context("Failed to update status")?;
// We succesfully logged in. Now ask for the cameras subscription.
self.client
.subscribe()
.await
.context("Failed to subscribe")?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
if self.handle_message(published_message).await.is_err() {
error!("Failed to forward messages in mqtt");
}
}
_ => {}
}
// }
}
}
Ok(())
}
async fn handle_message(&mut self, published_message: Publish) -> Result<()> {
if let Some(sub_topic) = published_message
.topic
.strip_prefix(&format!("neolink/{}/", &self.name))
{
if self
.incoming_tx
.send(MqttReply {
topic: sub_topic.to_string(),
message: String::from_utf8_lossy(published_message.payload.as_ref())
.into_owned(),
})
.await
.is_err()
{
error!("Failed to send messages up the mqtt msg channel");
}
}
Ok(())
}
}
impl Mqtt {
pub(crate) fn new(config: &MqttConfig, name: &str, app: Arc<App>) -> Arc<Self> {
let incoming = unbounded::<Publish>();
let msg_channel = unbounded::<MqttReply>();
pub(crate) async fn new(config: &MqttConfig, name: &str, app: Arc<App>) -> Self {
let (incoming_tx, incoming) = channel::<MqttReply>(100);
let mut mqttoptions = MqttOptions::new(
format!("Neolink-{}", name),
&config.broker_addr,
@@ -91,158 +200,75 @@ impl Mqtt {
true,
));
let (client, connection) = Client::new(mqttoptions, 10);
let (client, mut connection) = AsyncClient::new(mqttoptions, 10);
let me = Self {
app: app.clone(),
client: Mutex::new(client),
connection: Mutex::new(connection),
name: name.to_string(),
incoming,
msg_channel,
// Send the drop message on clean disconnect
drop_message: Mutex::new(Some(MqttReply {
topic: "status".to_string(),
message: "offline".to_string(),
})),
};
let arc_me = Arc::new(me);
let client = Arc::new(client);
// Start the mqtt server
let mqtt_running = arc_me.clone();
let mqtt_app = app.clone();
let mqtt_name = name.to_string();
std::thread::spawn(move || {
let _ = (*mqtt_running).start();
mqtt_app.abort(&mqtt_name)
});
let mut set = JoinSet::<Result<()>>::new();
// Start polling messages
info!("{}: Starting listening to mqtt", name);
let mqtt_read_app = app;
let mqtt_reading = arc_me.clone();
let mqtt_read_name = name.to_string();
std::thread::spawn(move || {
while mqtt_read_app.running(&format!("app:{}", mqtt_read_name)) {
if (*mqtt_reading).handle_message().is_err() {
error!(
"Failed to get messages from mqtt client {}",
(mqtt_read_name)
);
}
}
});
let mut reciever = MqttReciever {
app: app.clone(),
incoming_tx,
name: name.to_string(),
client: MqttSender {
client: client.clone(),
name: name.to_string(),
},
};
set.spawn(async move { reciever.run(&mut connection).await });
arc_me
}
#[allow(unused)]
pub(crate) fn set_drop_message(&mut self, topic: &str, message: &str) {
self.drop_message.lock().unwrap().replace(MqttReply {
topic: topic.to_string(),
message: message.to_string(),
});
}
fn subscribe(&self) -> Result<(), ClientError> {
let mut client = self.client.lock().unwrap();
client.subscribe(format!("neolink/{}/#", self.name), QoS::AtMostOnce)?;
Ok(())
}
fn update_status(&self) -> Result<(), ClientError> {
self.send_message("status", "disconnected", true)?;
Ok(())
}
pub fn send_message(
&self,
sub_topic: &str,
message: &str,
retain: bool,
) -> Result<(), ClientError> {
let mut client = self.client.lock().unwrap();
client.publish(
format!("neolink/{}/{}", self.name, sub_topic),
QoS::AtLeastOnce,
retain,
message,
)?;
Ok(())
}
fn handle_message(&self) -> Result<(), RecvError> {
let (_, receiver) = &self.incoming;
let published_message = receiver.recv()?;
if let Some(sub_topic) = published_message
.topic
.strip_prefix(&format!("neolink/{}/", &self.name))
{
if self
.msg_channel
.0
.send(MqttReply {
topic: sub_topic.to_string(),
message: String::from_utf8_lossy(published_message.payload.as_ref())
.into_owned(),
})
.is_err()
{
error!("Failed to send messages up the mqtt msg channel");
}
}
Ok(())
}
pub fn get_message_listener(&self) -> Receiver<MqttReply> {
self.msg_channel.1.clone()
}
pub(crate) fn poll(&self) -> Result<MqttReply> {
self.get_message_listener()
.recv()
.context("Mqtt Polling error")
}
pub(crate) fn start(&self) -> Result<()> {
// This acts as an event loop
let mut connection = self.connection.lock().unwrap();
let (sender, _) = &self.incoming;
info!("Starting MQTT Client for {}", self.name);
while self.app.running(&format!("app:{}", self.name)) {
for (_i, notification) in connection.iter().enumerate() {
if let Ok(notification) = notification {
match notification {
Event::Incoming(Incoming::ConnAck(connected)) => {
if ConnectReturnCode::Success == connected.code {
self.update_status().context("Failed to update status")?;
// We succesfully logged in. Now ask for the cameras subscription.
self.subscribe().context("Failed to subscribe")?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
if sender.send(published_message).is_err() {
error!("Failed to publish motion message on mqtt");
}
}
_ => {}
let join_app = app;
let join_name = name.to_string();
tokio::task::spawn(async move {
while let Some(joined) = set.join_next().await {
tokio::task::yield_now().await;
match joined {
Err(e) => {
error!("MQTT reciever panicked: {:?}", e);
join_app.abort(&join_name);
}
Ok(Err(e)) => {
error!("MQTT stopped with error: {:?}", e);
join_app.abort(&join_name);
}
Ok(Ok(())) => {
info!("Normal shutdown of MQTT");
}
}
}
});
Self {
client,
name: name.to_string(),
incoming,
// Send the drop message on clean disconnect
drop_message: Some(MqttReply {
topic: "status".to_string(),
message: "offline".to_string(),
}),
}
Ok(())
}
pub fn get_sender(&self) -> MqttSender {
MqttSender {
client: self.client.clone(),
name: self.name.to_string(),
}
}
pub(crate) async fn poll(&mut self) -> Result<MqttReply> {
self.incoming.recv().await.context("Mqtt Polling error")
}
}
impl Drop for Mqtt {
fn drop(&mut self) {
let drop_message = self.drop_message.lock().unwrap();
if let Some(drop_message) = drop_message.as_ref() {
if let Some(drop_message) = self.drop_message.as_ref() {
if self
.send_message(&drop_message.topic, &drop_message.message, true)
.get_sender()
.try_send_message(&drop_message.topic, &drop_message.message, true)
.is_err()
{
error!("Failed to send offline message to mqtt");
+1
View File
@@ -141,6 +141,7 @@ impl Default for NeoMediaFactoryImpl {
};
threads.spawn(async move {
loop {
tokio::task::yield_now().await;
match sender.run().await {
Err(e) => {
warn!("Media send thead failed... restarting. Cause: {:?}", e);
+1
View File
@@ -97,6 +97,7 @@ pub(crate) async fn main(_opt: Opt, mut config: Config) -> Result<()> {
let name = camera.get_name();
let mut backoff = Duration::from_micros(125);
loop {
tokio::task::yield_now().await;
let failure = camera_main(camera).await;
match failure {
Err(CameraFailureKind::Fatal(e)) => {
+1
View File
@@ -52,6 +52,7 @@ impl Camera<Streaming> {
.await?;
set.spawn(async move {
loop {
tokio::task::yield_now().await;
// debug!("Straming: Get");
let data = timeout(Duration::from_secs(15), stream_data.get_data()).await??;
// debug!("Straming: Got");