Update the config via mqtt

This commit is contained in:
QuantumEntangledAndy committed 2023-09-15 08:08:09 +07:00
1 parent 3391666598
commit cc9c35400f
4 files changed
+56 -18

No files matched your search

+14
View File
@@ -19,6 +19,7 @@ use crate::{config::Config, Result};
enum NeoReactorCommand {
HangUp,
Config(OneshotSender<WatchReceiver<Config>>),
UpdateConfig(Config, OneshotSender<Result<()>>),
Get(String, OneshotSender<Result<Option<NeoInstance>>>),
}
@@ -92,6 +93,10 @@ impl NeoReactor {
log::debug!("Got instance from reactor");
let _ = sender.send(new);
},
NeoReactorCommand::UpdateConfig(new_conf, reply) => {
let _ = config_tx.send_replace(new_conf);
let _ = reply.send(Ok(()));
}
}
}
Ok(())
@@ -125,6 +130,15 @@ impl NeoReactor {
Ok(sender_rx.await?)
}
pub(crate) async fn update_config(&self, new_config: Config) -> Result<()> {
let (sender_tx, sender_rx) = oneshot();
self.commander
.send(NeoReactorCommand::UpdateConfig(new_config, sender_tx))
.await?;
sender_rx.await?
}
pub(crate) async fn shutdown(&self) {
let _ = self.commander.send(NeoReactorCommand::HangUp).await;
self.cancel.cancelled().await;
+35 -10
View File
@@ -66,6 +66,7 @@ use tokio::{
};
use tokio_stream::{wrappers::IntervalStream, StreamExt};
use tokio_util::sync::CancellationToken;
use validator::Validate;
use neolink_core::bc_protocol::{Direction as BcDirection, LightState};
@@ -75,6 +76,7 @@ mod mqttc;
use crate::{
common::{MdState, NeoInstance, NeoReactor},
config::Config,
AnyResult,
};
use anyhow::{anyhow, Context, Result};
@@ -177,20 +179,43 @@ pub(crate) async fn main(_: Opt, reactor: NeoReactor) -> Result<()> {
});
// This threads checks for config changes on the mqtt
let mut thread_config = config.clone();
let thread_config = config.clone();
let mut thread_instance = mqtt.subscribe("").await?;
let thread_reactor = reactor.clone();
set.spawn(async move {
while let Ok(msg) = {
log::info!("Trying to pull msg");
let v = thread_instance.recv().await;
if let Err(e) = &v {
log::info!("{:?}", e);
while let Ok(msg) = thread_instance.recv().await {
if msg.topic == "config" {
let config: Result<Config> = toml::from_str(&msg.message).with_context(|| {
format!("Failed to parse the MQTT {:?} config file", msg.topic)
});
if let Err(e) = config {
thread_instance
.send_message("config/status", &format!("{:?}", e), false)
.await?;
continue;
}
let config = config?;
let validate = config.validate().with_context(|| {
format!("Failed to validate the MQTT {:?} config file", msg.topic)
});
if let Err(e) = validate {
thread_instance
.send_message("config/status", &format!("{:?}", e), false)
.await?;
continue;
}
if (*thread_config.borrow()) == config {
continue;
}
let result = thread_reactor.update_config(config).await;
thread_instance
.send_message("config/status", &format!("{:?}", result), false)
.await?;
}
v
} {
log::info!("{}", msg.topic);
}
log::info!("Shuting down MQTT Config Updater");
AnyResult::Ok(())
});
+6 -7
View File
@@ -211,17 +211,15 @@ async fn run_mqtt_server(
.await?;
// We succesfully logged in. Now ask for the cameras subscription.
client
.subscribe("neolink/".to_string(), QoS::AtMostOnce)
.subscribe("neolink/#".to_string(), QoS::AtMostOnce)
.await?;
}
}
Event::Incoming(Incoming::Publish(published_message)) => {
log::info!("Got MQTT message: {:?}", published_message);
if let Some(sub_topic) = published_message
.topic
.strip_prefix("neolink/")
{
let _ = incomming_tx
.send(MqttReply {
topic: sub_topic.to_string(),
@@ -332,7 +330,7 @@ impl MqttInstance {
pub(crate) async fn recv(&mut self) -> AnyResult<MqttReply> {
Ok(loop {
let msg = self
let mut msg = self
.incomming_rx
.next()
.await
@@ -342,12 +340,13 @@ impl MqttInstance {
if self.name.is_empty() {
break msg;
} else {
let topics = msg.topic.split('/').collect::<Vec<_>>();
if topics
.get(2)
let mut topics = msg.topic.split('/');
let sub_topic = topics.next();
if sub_topic
.map(|subtopic| *subtopic == self.name)
.unwrap_or(false)
{
msg.topic = topics.collect::<Vec<_>>().join("/");
break msg;
}
}
+1 -1
View File
@@ -902,7 +902,7 @@ fn get_runtime(app: &AppSrc) -> Option<Duration> {
if let Some(clock) = app.clock() {
if let Some(time) = clock.time() {
if let Some(base_time) = app.base_time() {
let runtime = timesaturating_sub(base_time);
let runtime = time.saturating_sub(base_time);
return Some(Duration::from_micros(runtime.useconds()));
}
}