Flutter MQTT通信插件mqtt_client的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter MQTT通信插件mqtt_client的使用

简介

mqtt_client 是一个用于Dart的MQTT客户端库,支持服务器和浏览器端。它实现了MQTT v3(3.1 和 3.1.1)协议,并且可以处理订阅、发布消息的所有QOS级别、保持连接活跃以及同步连接。该客户端旨在尽可能多地处理MQTT协议的工作,使得用户能够专注于发布和订阅操作,而无需深入了解MQTT协议的具体细节。

此客户端已成功与多个主要云提供商的IoT/MQTT平台(如Google IOT Core、Amazon AWS、Microsoft Azure和IBM)以及公共可用的代理(如Mosquitto)和专有代理一起使用。

安装

iOS

如果你在Flutter环境中使用此客户端于Android或iOS设备上,则需要设置以下设备权限:

ios/Runner/Info.plist 文件中添加如下键值:

<key>NSLocalNetworkUsageDescription</key>
<string>Looking for local tcp Bonjour service</string>
<key>NSBonjourServices</key>
<array>
  <string>_mqtt._tcp</string>
</array>

Android

android/app/src/main/AndroidManifest.xml 文件中添加如下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

示例代码

下面是一个简单的示例,展示了如何配置一个基本的服务器端MQTT客户端。此示例基于官方提供的 mqtt_server_client.dart 示例改编而来。

完整的示例Demo

添加依赖

首先,在你的pubspec.yaml文件中添加mqtt_client依赖:

dependencies:
  mqtt_client: ^9.0.0

创建MQTT客户端并连接到代理

创建一个新的Dart文件,例如main.dart,并在其中编写以下代码:

import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MQTT Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MqttHomePage(),
    );
  }
}

class MqttHomePage extends StatefulWidget {
  @override
  _MqttHomePageState createState() => _MqttHomePageState();
}

class _MqttHomePageState extends State<MqttHomePage> {
  final MqttServerClient client = MqttServerClient('broker.hivemq.com', '');
  String receivedMessage = '';

  @override
  void initState() {
    super.initState();
    connect();
  }

  void connect() async {
    client.port = 1883;

    /// 设置连接丢失后的回调函数
    client.onDisconnected = onDisconnected;
    
    /// 设置连接成功的回调函数
    client.onConnected = onConnected;
    
    /// 设置收到消息的回调函数
    client.onSubscribed = onSubscribed;

    final connMess = MqttConnectMessage()
        .withClientIdentifier('flutter_mqtt_client')
        .startClean(); // 清除会话
    print('EXAMPLE::Mosquitto client connecting....');
    client.connectionMessage = connMess;

    try {
      await client.connect();
    } catch (e) {
      print('EXAMPLE::client exception - $e');
      client.disconnect();
    }

    if (client.connectionStatus!.state == MqttConnectionState.connected) {
      print('EXAMPLE::Mosquitto client connected');
    } else {
      print(
          'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${client.connectionStatus}');
      client.disconnect();
    }
  }

  void onSubscribed(String topic) {
    print('EXAMPLE::Subscription confirmed for topic $topic');
  }

  void onDisconnected() {
    print('EXAMPLE::OnDisconnected client callback - Client disconnection');
    if (client.connectionStatus!.disconnectionOrigin ==
        MqttDisconnectionOrigin.solicited) {
      print('EXAMPLE::OnDisconnected callback is solicited, client state is');
    } else {
      print('EXAMPLE::OnDisconnected callback is unsolicited or none, client state is');
    }
  }

  void onConnected() {
    print('EXAMPLE::OnConnected client callback - Client connection was sucessful');

    /// 订阅主题
    const topic = 'flutter/test'; // 替换为你要订阅的主题
    client.subscribe(topic, MqttQos.atMostOnce);

    /// 发布消息
    final builder = MqttClientPayloadBuilder();
    builder.addString('Hello from Flutter MQTT client');

    client.publishMessage(topic, MqttQos.exactlyOnce, builder.payload!);

    /// 监听消息
    client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      final recMess = c![0].payload as MqttPublishMessage;
      final pt =
          MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
      print(
          'EXAMPLE::Change notification:: topic is <${c[0].topic}>, payload is <-- $pt -->');
      setState(() {
        receivedMessage = 'Received message: $pt';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MQTT Demo'),
      ),
      body: Center(
        child: Text(receivedMessage),
      ),
    );
  }
}

这个例子展示了如何建立一个MQTT客户端,连接到一个MQTT代理(在这个例子中是HiveMQ的公共测试代理),订阅一个主题,并监听来自该主题的消息。同时,它也展示了如何向特定主题发布消息。

请根据实际需求修改代理地址、端口、主题名称等参数。

通过以上步骤,你应该能够在Flutter应用中成功地集成和使用mqtt_client插件进行MQTT通信了。


更多关于Flutter MQTT通信插件mqtt_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter MQTT通信插件mqtt_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个使用Flutter的mqtt_client插件进行MQTT通信的示例代码。这个示例展示了如何连接到MQTT代理、订阅主题以及发布消息。

首先,确保你已经在pubspec.yaml文件中添加了mqtt_client依赖:

dependencies:
  flutter:
    sdk: flutter
  mqtt_client: ^x.y.z  # 请替换为最新版本号

然后,你可以创建一个Flutter应用,并在其中使用mqtt_client进行MQTT通信。以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('MQTT Client Demo'),
        ),
        body: MqttClientDemo(),
      ),
    );
  }
}

class MqttClientDemo extends StatefulWidget {
  @override
  _MqttClientDemoState createState() => _MqttClientDemoState();
}

class _MqttClientDemoState extends State<MqttClientDemo> {
  MqttServerClient? _client;
  String _message = 'Connecting...';

  @override
  void initState() {
    super.initState();
    connectToMqtt();
  }

  Future<void> connectToMqtt() async {
    const String broker = 'mqtt.eclipse.org';
    const int port = 1883;
    const String clientId = 'FlutterMqttDemoClient';

    _client = MqttServerClient(broker, clientId);
    _client!.port = port;
    _client!.keepAlivePeriod = 20;
    _client!.protocolLevel = MqttProtocolLevel.v311;

    final MqttConnectOptions connOpts = MqttConnectOptions.builder()
        .setClientId(clientId)
        .setCleanSession()
        .setKeepAliveInterval(20)
        .setWillTopic('will/topic')
        .setWillMessage('My Will Message')
        .setWillQos(MqttQos.atLeastOnce)
        .setResumeSubs(true)
        .setAutomaticReconnect()
        .setUsername('your-username') // 如果需要用户名
        .setPassword('your-password'); // 如果需要密码

    try {
      await _client!.connect(connOpts).then((_) {
        if (_client!.connectionStatus.state == MqttConnectionState.connected) {
          setState(() {
            _message = 'Connected to broker: $broker';
          });
          // 订阅主题
          _client!.subscribe('test/topic', MqttQos.atMostOnce);
          // 发布消息
          _client!.publishMessage(
              'test/topic',
              MqttMessageBuilder().payload('Hello MQTT').qos(MqttQos.atLeastOnce).build(),
          );
        } else {
          setState(() {
            _message = 'Failed to connect, state is ${_client!.connectionStatus.state}';
          });
        }
      });

      _client!.updates!.listen((List<MqttReceivedMessage<MqttMessage>> c) {
        final MqttPublishMessage recMsg = c[0].payload as MqttPublishMessage;
        final String pt =
            MqttPublishPayload.bytesToStringAsString(recMsg.payload.message!);
        setState(() {
          _message += '\n\nTopic: ${c[0].topic} Message: $pt';
        });
      });

    } catch (e) {
      setState(() {
        _message = 'Exception: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(_message),
    );
  }

  @override
  void dispose() {
    if (_client!.isConnected) {
      _client!.disconnect();
    }
    super.dispose();
  }
}

代码说明:

  1. 依赖项:确保在pubspec.yaml中添加了mqtt_client依赖。
  2. 主函数main函数创建一个Flutter应用。
  3. UI组件MqttClientDemo是一个有状态的组件,它持有MQTT客户端的实例,并在UI中显示连接状态和接收到的消息。
  4. 连接MQTTconnectToMqtt方法用于连接到MQTT代理,设置连接选项,并订阅主题。它还发布了一条测试消息。
  5. 监听消息:通过监听_client!.updates!流来接收和处理订阅的主题消息。
  6. 清理资源:在dispose方法中,如果客户端已连接,则断开连接。

这个示例展示了如何使用mqtt_client插件在Flutter应用中实现MQTT通信。你可以根据需要进一步扩展和修改这个示例。

回到顶部