再开过程中我们经常使用到MQTT 进行 订阅,来进行 消息的发送、接受等操作。
下面就是我对Flutter MQTT 的简单实用并,这里为方便大家使用 ,我封装了一个MQTT管理类,代码如下,功能介绍也写在 代码注释中。
注意:Flutter 开发环境为 2.8.0,如果版本 存在差别,要略微 修改。
插件:
mqtt_client: ^9.6.8
import 'dart:async';
import 'package:amazingbox/util/LoggerUtil.dart';//日志打印类,可忽略
import 'package:mqtt_client/mqtt_client.dart'; // Mqtt插件
import 'package:mqtt_client/mqtt_server_client.dart'; // Mqtt插件
import 'package:typed_data/typed_buffers.dart';
typedef ConnectedCallback = void Function();
class MqttUtil {
MqttQos qos = MqttQos.atLeastOnce;
late MqttServerClient mqttClient;
static MqttUtil? _instance;
static MqttUtil? getInstance() {
_instance ??= MqttUtil();
return _instance;
}
/*
* 链接服务器
* */
Future connect(String server, int port,
String clientIdentifier, String username, String password,
{bool isSsl = false}) {
mqttClient = MqttServerClient.withPort(server, clientIdentifier, port);
mqttClient.onConnected = onConnected;
mqttClient.onSubscribed = _onSubscribed;
mqttClient.onSubscribeFail = _onSubscribeFail;
mqttClient.onUnsubscribed = _onUnSubscribed;
mqttClient.pongCallback = pong; //收到 PING 响应回调
mqttClient.setProtocolV311();
mqttClient.logging(on: false);
if (isSsl) {
mqttClient.secure = true;
mqttClient.onBadCertificate = (dynamic a) => true;
}
_log("_正在连接中...");
return mqttClient.connect(username, password);
}
/*
* 发送数据
* */
int publishMessage(String pTopic, String msg) {
_log("_发送数据-topic:$pTopic,playLoad:$msg");
Uint8Buffer uint8buffer = Uint8Buffer();
var codeUnits = msg.codeUnits;
uint8buffer.addAll(codeUnits);
return mqttClient.publishMessage(pTopic, qos, uint8buffer, retain: false);
}
/*
*发送数据
* */
int publishRawMessage(String pTopic, List list) {
_log("_发送数据-topic:$pTopic,playLoad:$list");
Uint8Buffer uint8buffer = Uint8Buffer();
// var codeUnits = msg.codeUnits;
uint8buffer.addAll(list);
return mqttClient.publishMessage(pTopic, qos, uint8buffer, retain: false);
}
// TODO: 订阅主题
Subscription? subscribeMessage(String subtopic) {
return mqttClient.subscribe(subtopic, qos);
}
// TODO: 取消订阅
void unsubscribeMessage(String? unSubtopic) {
mqttClient.unsubscribe(unSubtopic!);
}
// TODO: MQTT状态获取
MqttClientConnectionStatus? getMqttStatus() {
return mqttClient.connectionStatus;
}
// TODO: 监听MQTT接到的消息
Stream>>? updates() {
_log("_监听成功!");
return mqttClient.updates;
}
// TODO: 链接成功
onConnected() {
// mqttClient.onConnected = callback;
_log("链接成功");
}
// TODO: 断开链接
disconnect() {
mqttClient.disconnect();
_log("断开链接");
}
// TODO: 连接断开回调
onDisConnected(ConnectedCallback callback) {
mqttClient.onDisconnected = callback;
}
// TODO: _订阅主题成功
_onSubscribed(String topic) {
_log("_订阅主题成功---topic:$topic");
}
// TODO: _取消订阅主题成功
_onUnSubscribed(String? topic) {
_log("_取消订阅主题成功---topic:$topic");
}
// TODO: 订阅失败
_onSubscribeFail(String topic) {
_log("_onSubscribeFail");
}
// TODO: 收到 PING 响应
void pong() {
print('收到 PING 响应');
}
_log(String msg) {
LogD("MQTT-->$msg");
}
}
以上就是MQTT工具类的封装,每个方法都有对应的注释,具体都什么作用就不做过多介绍,下面着重介绍一下使用。代码如下:
连接
//连接
MqttUtil.getInstance()?.connect("链接地址", "端口号", "设备唯一标识", "账号", "密码");
订阅
MqttUtil.getInstance()?.subscribeMessage("订阅topic");
消息监听
MqttUtil.getInstance()?.updates()!.listen((List> mqttMessageList) {
print('----------------------mqqt 消息监听------------------------');
print(mqttMessageList);
// final MqttPublishMessage message = mqttMessageList[0].payload;
// final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);
// print('消息:$payload,主题: <${mqttMessageList[0].topic}>');
});
取消连接
MqttUtil.getInstance()?.disconnect();
取消订阅
MqttUtil.getInstance()?.unsubscribeMessage("取消订阅的Topic");
发动消息
MqttUtil.getInstance()?.publishMessage("要发送的topic", "消息内容");
// 发送的消息内容为列表
MqttUtil.getInstance()?.publishRawMessage("发送的topic", []);
获取MQTT状态
MqttUtil.getInstance()?.getMqttStatus();
到此就完成了MQTT封装和使用,希望对大家有所帮助