Flutter之MQTT使用

news/2024/2/29 2:45:47

1.添加依赖:

首先,需要在Flutter项目的​​pubspec.yaml​​​文件中添加​​mqtt_client​​依赖。

dependencies:#https://pub.dev/packages/mqtt_clientmqtt_client: ^10.0.02.创建MQTT客户端并连接到MQTT服务器:

2.创建一个MQTT客户端实例来进行连接和通信

Future<MqttServerClient> connect(String cid) async {print('mqtt connect host = $host cid = $cid ');MqttServerClient client =MqttServerClient.withPort(host, cid, port);client.logging(on: true);client.onConnected = onConnected;client.onDisconnected = onDisconnected;client.onUnsubscribed = onUnsubscribed;client.onSubscribed = onSubscribed;client.onSubscribeFail = onSubscribeFail;client.pongCallback = pong;final connMessage = MqttConnectMessage().authenticateAs(user, pwd).keepAliveFor(60)// 保持连接时间,单位为秒.withWillTopic('willtopic').withWillMessage('Will message').startClean()// 清理会话.withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMessage;try {await client.connect();} catch (e) {print('Exception: $e');client.disconnect();}return client;}

其中host 是主机名,port是端口号,cid是客户端ID,你可以根据需要为其分配一个唯一的标识。

3.订阅主题:

一旦连接到MQTT服务器,你可以订阅感兴趣的主题以接收消息。以下是订阅主题的示例代码:
//用于监听已订阅主题的消息到达。

    client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);// 解码包含中文字符的字符串final String decodedString = utf8.decode(pt.codeUnits);LogI('Received message: $decodedString from topic: ${c[0].topic}');});

通过​​client.subscribe​​​方法订阅一个主题,并使用​​client.updates​​流来监听接收到的消息。

4.发布消息:

使用MQTT客户端来发布消息到特定的主题。以下是发布消息的示例代码:

final MqttClientPayloadBuilder builder = MqttClientPayloadBuilder();
builder.addString('Hello from Flutter');client.publishMessage('your_topic', MqttQos.exactlyOnce, builder.payload);

在上面的代码中,使用​​MqttClientPayloadBuilder​​​来构建消息的有效载荷,然后使用​​client.publishMessage​​方法来发布消息到指定的主题。

5.断开连接:

当你不再需要与MQTT服务器通信时,记得断开连接以释放资源:

client.disconnect();

完整代码:

class XMqttClient {static final XMqttClient _instance = XMqttClient._();static XMqttClient get instance => _instance;static const host = '139.196.xx.xx';//替换成你自己的主机static const port = 1883;//端口号static const user = 'admin';//用户static const pwd = 'public';//密码List<String> topics = [];MqttClient? client;XMqttClient._() {_initMqtt();}_initMqtt() async {//clientld 确保唯一性,否则如果两台机器的clientld 相同 则会连上立刻断开连接!!!String clientId = '${DateTime.now().millisecondsSinceEpoch}asc';client = await connect(clientId);}Future<MqttServerClient> connect(String cid) async {print('mqtt connect host = $host cid = $cid ');MqttServerClient client =MqttServerClient.withPort(host, cid, port);client.logging(on: true);client.onConnected = onConnected;client.onDisconnected = onDisconnected;client.onUnsubscribed = onUnsubscribed;client.onSubscribed = onSubscribed;client.onSubscribeFail = onSubscribeFail;client.pongCallback = pong;final connMessage = MqttConnectMessage().authenticateAs(user, pwd).keepAliveFor(60)// 保持连接时间,单位为秒.withWillTopic('willtopic').withWillMessage('Will message').startClean()// 清理会话.withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMessage;try {await client.connect();} catch (e) {print('Exception: $e');client.disconnect();}//用于监听已订阅主题的消息到达。client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {final MqttPublishMessage recMess = c[0].payload as MqttPublishMessage;final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);// 解码包含中文字符的字符串final String decodedString = utf8.decode(pt.codeUnits);LogI('Received message: $decodedString from topic: ${c[0].topic}');});return client;}///订阅一个主题_subscribe(String topic) {client?.subscribe(topic, MqttQos.atLeastOnce);}///订阅多个主题topicSubscribe(List<String> topics) async {this.topics.addAll(topics);if (client?.connectionStatus?.state == MqttConnectionState.connected) {topics.forEach((topic) {_subscribe(topic);});} else {//未连接成功 每隔3s重新订阅Future.delayed(const Duration(seconds: 3), () {topicSubscribe(topics);});}}///取消订阅_unsubscribe() {client?.unsubscribe('topic/test');}///断开连接_disconnect() {client?.disconnect();}// 连接成功void onConnected() {print('连接成功');}// 连接断开void onDisconnected() {print('连接断开');}// 订阅主题成功void onSubscribed(String topic) {print('订阅主题成功: $topic');}// 订阅主题失败void onSubscribeFail(String topic) {print('订阅主题失败 $topic');}// 成功取消订阅void onUnsubscribed(String? topic) {print('成功取消订阅: $topic');}// 收到 PING 响应void pong() {print('收到 PING 响应 Ping response client callback invoked');}}

https://www.xjx100.cn/news/3119035.html

相关文章

NoSql非关系型数据库

前言&#xff1a;Nosql not only sql&#xff0c;意即“不仅仅是sql”&#xff0c;泛指非关系型数据库。这些类型的数据存储不需要固定的模式&#xff08;当然也有固定的模式&#xff09;&#xff0c;无需多余的操作就可以横向扩展。NoSql数据库中的数据是使用聚合模型来进行处…

Linux-hid

/kernel/drivers/hid/hid-core.c hid总线驱动/kernel/drivers/hid/hid-generic.c hid通用驱动/kernel/drivers/hid/hid-multitouch.c 多点触控面板驱动/kernel/drivers/hid/hid-quirks.c hid-quirks.c 是 Linux 内核中的一个文件&#xff0c;用于实现 HID&#xff08;Human…

LangChain 15根据问题自动路由Router Chain确定用户的意图

LangChain系列文章 LangChain 实现给动物取名字&#xff0c;LangChain 2模块化prompt template并用streamlit生成网站 实现给动物取名字LangChain 3使用Agent访问Wikipedia和llm-math计算狗的平均年龄LangChain 4用向量数据库Faiss存储&#xff0c;读取YouTube的视频文本搜索I…

推荐一款好用的BMP转PNG工具BMP2PNG

推荐一款好用的BMP转PNG工具BMP2PNG 自己写的一个BMP转PNG工具BMP2PNG 写这个工具是因为要使用传奇的部分素材在COCOS2DX使用&#xff0c; 但是COCOS2DX不支持BMP 如果直接将BMP转换到PNG的话&#xff0c;网上找到的工具都不支持透明色转换。难道要用PS一个一个抠图吗&#xf…

普中STM32 单片机资料

普中科技–各型号开发板资料下载链接: ①普中-精灵1开发板: 百度网盘链接:https://pan.baidu.com/s/1Pa8Ep1xmg6uoq17O6Nwyyw?pwd=1234 提取码:1234 ②普中-ESP32开发板: 百度网盘链接:https://pan.baidu.com/s/16VthcbW27oEWp162H3bi6Q?pwd=1234 提取码:1234 一…

LVS+Keepalived实验

实验前准备 主DR服务器&#xff1a;(ens33)192.168.188.11 ipvsadm、keepalived (ens33:0)192.168.188.188 备DR服务器&#xff1a;(ens33)192.168.188.12 ipvsadm、keepalived (ens33:0)192.168.188.188 Wbe服务器1&#xff1a;(ens33)192.168.188.13 (lo:0)192.168.188.188 W…

MySQL中的JOIN与IN:性能对比与最佳实践

文章目录 JOIN与IN的基本介绍JOININ JOIN与IN性能对比使用JOIN的查询使用IN的查询 何时使用JOIN何时使用IN性能优化的其他考虑因素总结 &#x1f389;MySQL中的JOIN与IN&#xff1a;性能对比与最佳实践 ☆* o(≧▽≦)o *☆嗨~我是IT陈寒&#x1f379;✨博客主页&#xff1a;IT陈…

HTML中使用JavaScript实现一个简单的鼠标悬停特效。

代码中&#xff0c;我们首先在CSS中定义了一个红色的方块&#xff0c;然后使用:hover伪类定义了鼠标悬停时的样式。接着&#xff0c;在JavaScript中定义了一个函数showMessage()&#xff0c;用于在控制台输出一条消息。最后&#xff0c;在HTML中使用<div>标签定义了一个i…