use std::sync::Arc;
use std::time::Duration as StdDuration;
use super::{Meter, VenError, VenRuntime, Waker};
use crate::client::{Client, VirtualEndNode};
use crate::model::{MqttAuthentication, ObjectId};
use crate::mqtt::{BrokerAddress, Connection, ConnectionConfig, Incoming, QoS};
#[derive(Debug, Clone)]
pub struct MqttPushConfig {
pub client_id: Option<String>,
pub keep_alive: StdDuration,
pub max_backoff: StdDuration,
pub watch_programs: bool,
pub watch_own_objects: bool,
}
impl Default for MqttPushConfig {
fn default() -> Self {
Self {
client_id: None,
keep_alive: StdDuration::from_secs(30),
max_backoff: StdDuration::from_secs(30),
watch_programs: true,
watch_own_objects: true,
}
}
}
#[derive(Debug)]
pub struct MqttPush {
topics: Vec<String>,
broker: String,
task: tokio::task::JoinHandle<()>,
}
impl Drop for MqttPush {
fn drop(&mut self) {
self.task.abort();
}
}
impl MqttPush {
pub async fn connect<M: Meter>(
ven: &VenRuntime<M>,
config: MqttPushConfig,
) -> Result<Option<Self>, VenError> {
let ven_id = ven.ven_id().ok_or(VenError::NotRegistered)?;
Self::start(ven.client(), &ven_id, ven.waker(), config).await
}
pub async fn start(
client: &Client<VirtualEndNode>,
ven_id: &ObjectId,
waker: Waker,
config: MqttPushConfig,
) -> Result<Option<Self>, VenError> {
let notifiers = client.notifiers().await?;
let Some(binding) = notifiers.mqtt else {
tracing::info!("this VTN offers no MQTT notifier; the VEN will poll");
return Ok(None);
};
let broker = binding
.uris
.first()
.cloned()
.ok_or_else(|| VenError::Protocol("the MQTT binding names no broker URI".into()))?;
let topics = Self::discover(client, ven_id, &config).await?;
if topics.is_empty() {
return Err(VenError::Protocol(
"the VTN named no topics this VEN may subscribe to".into(),
));
}
let client_id = config
.client_id
.clone()
.unwrap_or_else(|| format!("openadr-ven-{ven_id}"));
let address =
BrokerAddress::parse(&broker).map_err(|e| VenError::Protocol(e.to_string()))?;
let (username, password) = if matches!(
binding.authentication,
MqttAuthentication::Oauth2BearerToken { .. }
) {
let token = client.access_token().await?.ok_or_else(|| {
VenError::Protocol(
"the broker wants the access token as its password, and this client has \
neither credentials nor a pre-shared token"
.into(),
)
})?;
let username = binding
.authentication
.resolve_username(client.client_id())
.ok_or_else(|| {
VenError::Protocol(
"the broker wants this VEN's clientID as its MQTT username, and a \
pre-shared bearer token does not say what that is — configure client \
credentials, or a fixed username in the VTN's binding"
.into(),
)
})?
.to_string();
(Some(username), Some(token))
} else {
(None, None)
};
let filters: Vec<(String, QoS)> = topics
.iter()
.map(|t| (t.clone(), QoS::AtLeastOnce))
.collect();
let (events, incoming) = tokio::sync::mpsc::channel(32);
let connection = Connection::open(
address,
ConnectionConfig {
client_id,
username,
password,
keep_alive: config.keep_alive,
max_backoff: config.max_backoff,
..Default::default()
},
filters,
events,
);
let task = tokio::spawn(run(incoming, waker, connection));
tracing::info!(broker = %broker, topics = topics.len(), "subscribed to VTN notifications");
Ok(Some(Self {
topics,
broker,
task,
}))
}
pub fn topics(&self) -> &[String] {
&self.topics
}
pub fn broker(&self) -> &str {
&self.broker
}
async fn discover(
client: &Client<VirtualEndNode>,
ven_id: &ObjectId,
config: &MqttPushConfig,
) -> Result<Vec<String>, VenError> {
let mut paths = vec![format!("vens/{ven_id}/events")];
if config.watch_programs {
paths.push(format!("vens/{ven_id}/programs"));
}
if config.watch_own_objects {
paths.push(format!("vens/{ven_id}"));
paths.push(format!("vens/{ven_id}/resources"));
}
let mut topics = Vec::new();
for path in paths {
let response = match client.mqtt_topics(&path).await {
Ok(response) => response,
Err(e) if e.status() == Some(404) => {
tracing::debug!(path, "this VTN does not offer that topic endpoint");
continue;
}
Err(e) => return Err(e.into()),
};
let t = response.topics;
match t.all {
Some(all) => topics.push(all),
None => {
topics.extend(t.create);
topics.push(t.update);
topics.push(t.delete);
}
}
}
topics.sort();
topics.dedup();
Ok(topics)
}
}
async fn run(
mut incoming: tokio::sync::mpsc::Receiver<Incoming>,
waker: Waker,
connection: Arc<Connection>,
) {
let _connection = connection;
while let Some(event) = incoming.recv().await {
match event {
Incoming::Message { topic, .. } => {
tracing::debug!(%topic, "notification received; syncing early");
waker.wake();
}
Incoming::Connected(ack) => {
tracing::info!(
session_present = ack.session_present,
"connected to the MQTT broker"
);
waker.wake();
}
Incoming::Disconnected(why) => {
tracing::warn!(reason = %why, "MQTT connection lost; reconnecting")
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wildcard_replaces_three_subscriptions_and_a_binding_without_one_does_not() {
use crate::model::{NotifierTopics, TopicsResponse};
let wildcard = TopicsResponse::under("events/vens/ven-1").topics;
assert_eq!(wildcard.all.as_deref(), Some("events/vens/ven-1/+"));
let plain = NotifierTopics {
create: Some("a/create".into()),
update: "a/update".into(),
delete: "a/delete".into(),
all: None,
};
let mut expanded: Vec<String> = Vec::new();
expanded.extend(plain.create.clone());
expanded.push(plain.update.clone());
expanded.push(plain.delete.clone());
assert_eq!(expanded, ["a/create", "a/update", "a/delete"]);
}
#[test]
fn the_default_client_id_is_per_ven_not_per_process() {
let config = MqttPushConfig::default();
assert!(config.client_id.is_none());
assert!(config.watch_programs && config.watch_own_objects);
}
}