44 lines
1.4 KiB
Rust
44 lines
1.4 KiB
Rust
use crate::light::{Command, Status};
|
|
use crate::mqtt_commands::MqttCommands;
|
|
use crate::mqtt_updates::MqttUpdates;
|
|
use rumqtt;
|
|
use rumqtt::{ConnectionMethod, LastWill, MqttClient, MqttOptions, QoS, ReconnectOptions};
|
|
|
|
pub fn mqtt_connect(
|
|
host: &str,
|
|
port: u16,
|
|
commands: crossbeam_channel::Sender<Command>,
|
|
updates: crossbeam_channel::Receiver<Status>,
|
|
) -> Result<(MqttCommands, MqttUpdates), String> {
|
|
let last_will = LastWill {
|
|
topic: format!("{}/status", crate::MQTT_ID),
|
|
message: "disconnected".to_string(),
|
|
qos: QoS::AtLeastOnce,
|
|
retain: true,
|
|
};
|
|
let options = MqttOptions::new(crate::MQTT_ID, host, port);
|
|
let options = options
|
|
.set_connection_method(ConnectionMethod::Tcp)
|
|
.set_keep_alive(10)
|
|
.set_last_will(last_will)
|
|
.set_reconnect_opts(ReconnectOptions::Always(20));
|
|
|
|
match MqttClient::start(options) {
|
|
Ok((mut client, notifications)) => {
|
|
match client.publish(
|
|
format!("{}/status", crate::MQTT_ID),
|
|
QoS::AtLeastOnce,
|
|
true,
|
|
"connected",
|
|
) {
|
|
Ok(()) => Ok((
|
|
MqttCommands::new(notifications, commands),
|
|
MqttUpdates::new(client, updates),
|
|
)),
|
|
Err(conn_err) => Err(conn_err.to_string()),
|
|
}
|
|
}
|
|
Err(conn_err) => Err(conn_err.to_string()),
|
|
}
|
|
}
|