connectMqttServer method
Implementation
Future connectMqttServer(MqttClientWrapper wrapper) async {
try {
await client.connect(wrapper);
client.mqttClient?.onConnected = () {
log("Mqtt Server 连接成功");
};
client.mqttClient?.onDisconnected = () {
log("Mqtt Server 断开连接");
connected.value = false;
clientWrapper.value = null;
};
connected.value = true;
clientWrapper.value = wrapper;
clientWrapper.refresh();
// 订阅主题
client.subscribe(
'${deviceType.value}/${MessageAction.state}/${deviceId.value}');
client.subscribe(
'${deviceType.value}/${MessageAction.debug}/${deviceId.value}');
client.subscribe(
'${deviceType.value}/${MessageAction.command}/${deviceId.value}');
client.subscribe(
'${deviceType.value}/${MessageAction.rename}/${deviceId.value}');
client.listen((messages) {
if (messages.isEmpty) return;
var message = messages.first;
// log("[listen]: ${message.topic} ${message.payload}");
var topic = message.topic.split('/');
if (topic.length != 3) return;
handleMessage(message: message);
});
await registerStateMessage();
} catch (e, st) {
log("Mqtt Server 连接失败", error: e, stackTrace: st);
connected.value = false;
clientWrapper.value = null;
}
}