allow connecting with existing mqttoptions

This commit is contained in:
Robin Appelman 2024-10-30 19:27:02 +01:00
commit 78f89a491f
2 changed files with 8 additions and 3 deletions

View file

@ -67,7 +67,12 @@ impl TasmotaClient {
if let Some((username, password)) = credentials { if let Some((username, password)) = credentials {
mqtt_opts.set_credentials(username, password); mqtt_opts.set_credentials(username, password);
} }
let mqtt = MqttHelper::connect(mqtt_opts)?; Self::from_mqtt_options(mqtt_opts).await
}
/// Connect to an MQTT server using an existing [`MqttOptions`].
pub async fn from_mqtt_options(options: MqttOptions) -> Result<Self> {
let mqtt = MqttHelper::connect(options);
let mut lwt = mqtt.subscribe("tele/+/LWT".into()).await?; let mut lwt = mqtt.subscribe("tele/+/LWT".into()).await?;

View file

@ -17,7 +17,7 @@ pub struct MqttHelper {
} }
impl MqttHelper { impl MqttHelper {
pub fn connect(opts: MqttOptions) -> Result<Self> { pub fn connect(opts: MqttOptions) -> Self {
let (client, event_loop) = AsyncClient::new(opts, 10); let (client, event_loop) = AsyncClient::new(opts, 10);
let listeners = Arc::<Mutex<Vec<(String, Sender<_>)>>>::default(); let listeners = Arc::<Mutex<Vec<(String, Sender<_>)>>>::default();
@ -55,7 +55,7 @@ impl MqttHelper {
} }
}); });
Ok(Self { client, listeners }) Self { client, listeners }
} }
pub async fn send<B: Serialize>(&self, topic: &str, body: &B) -> Result<()> { pub async fn send<B: Serialize>(&self, topic: &str, body: &B) -> Result<()> {