Moved some stuff from main into the libary

This commit is contained in:
2022-12-28 04:17:23 +01:00
parent 2b4ddf82b6
commit 3b6a5e4c07
3 changed files with 59 additions and 47 deletions

View File

@@ -1,20 +1,23 @@
use std::sync::{Weak, RwLock};
use log::error;
use log::{error, debug};
use rumqttc::{Publish, Event, Incoming, EventLoop};
use log::trace;
use tokio::task::JoinHandle;
pub trait Listener {
fn notify(&mut self, message: &Publish);
}
// @TODO Maybe rename this to make it clear it has to do with mqtt
pub struct Notifier {
listeners: Vec<Weak<RwLock<dyn Listener + Sync + Send>>>,
eventloop: EventLoop,
}
impl Notifier {
pub fn new() -> Self {
return Self { listeners: Vec::new() }
pub fn new(eventloop: EventLoop) -> Self {
return Self { listeners: Vec::new(), eventloop }
}
fn notify(&mut self, message: Publish) {
@@ -32,20 +35,25 @@ impl Notifier {
self.listeners.push(listener);
}
pub async fn start(&mut self, mut eventloop: EventLoop) {
loop {
let notification = eventloop.poll().await;
match notification {
Ok(Event::Incoming(Incoming::Publish(p))) => {
trace!("{:?}", p);
self.notify(p);
},
Ok(..) => continue,
Err(err) => {
error!("{}", err);
break
},
pub fn start(mut self) -> JoinHandle<()> {
tokio::spawn(async move {
debug!("Listening for MQTT events");
loop {
let notification = self.eventloop.poll().await;
match notification {
Ok(Event::Incoming(Incoming::Publish(p))) => {
trace!("{:?}", p);
self.notify(p);
},
Ok(..) => continue,
Err(err) => {
error!("{}", err);
break
},
}
}
}
todo!("Error in MQTT (most likely lost connection to mqtt server), we need to handle these errors!");
})
}
}