首页 > 其他分享 >flutter 通过网络控制设备 emqx mqtt_client

flutter 通过网络控制设备 emqx mqtt_client

时间:2024-12-20 17:31:57浏览次数:6  
标签:deviceConnectTypeWifiBlueGet String globalWiFiBluetooth mqtt client emqx null Ea

WiFi插件: mqtt_client: ^10.5.1
JWT加密: dart_jsonwebtoken: ^2.14.1

连接设备

class WifiConnectVoid {
  static void wifiConnectVoid(
      {String? deviceModelId,
      String? deviceActivatedAt,
      String? deviceId,
      String? name,
      String? modelName,
      String? sn,
      bool reConnect = false,
      Function? callback}) async {
    DeviceConnectTypeWifiBlueGet deviceConnectTypeWifiBlueGet =
        Get.put(DeviceConnectTypeWifiBlueGet());
    GlobalWiFiBluetooth globalWiFiBluetooth = Get.put(GlobalWiFiBluetooth());
    if (modelName == null || sn == null) {
      EasyLoading.showError("wifi_connect_error".tr);
      globalWiFiBluetooth.isHaveDeviceVoid(false);
      return;
    }


    if (deviceConnectTypeWifiBlueGet.client != null &&
        deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
            MqttConnectionState.connected &&
        globalWiFiBluetooth.addNewDeviceSn.value == sn) {
      if (!reConnect) {
        //ping机器
        WiFiPush.wifiPush(WriteBluetoothMsgPing.writeBluetoothMsgPing(flag: 1));
      } else {
        WiFiPush.wifiPush(WriteBluetoothMsgPing.writeBluetoothMsgPing());
      }
      if (callback != null) {
        callback();
      }
    } else {
      if (deviceConnectTypeWifiBlueGet.client != null &&
          deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
              MqttConnectionState.connected &&
          globalWiFiBluetooth.addNewDeviceSn.value != sn) {
        try {
          deviceConnectTypeWifiBlueGet.client!.disconnect();
        } catch (_) {
          deviceConnectTypeWifiBlueGet.client!.disconnect();
        }
      }
      SharedPreferences preferences = await SharedPreferences.getInstance();
      String email = preferences.getString("gen_ki_nno_email") ?? "";
      MqttServerClient client = MqttServerClient(
        '域名',
        email,
      );

      // 要编码的数据
      final jwt = JWT({
        "user_name": "yonghuming",
        "c": "",
        "manu": "",
        "s": ""
      });
      //JWTKet.secretKey为加密秘钥
      String token = jwt.sign(SecretKey(JWTKet.secretKey));
      // final property = MqttUserProperty();
      // property.pairName = email;
      // property.pairValue = token;
      String type = WiFiType.wifiType(modelName);
      String subTopic = '主题';
      String pUBTopic = '主题';

      deviceConnectTypeWifiBlueGet.clientDeviceVoid(client);
      deviceConnectTypeWifiBlueGet.wifiDeviceSNSubTopicVoid(subTopic);
      deviceConnectTypeWifiBlueGet.wifiDeviceSNPubTopicVoid(pUBTopic);
      globalWiFiBluetooth.blueModelIdVoid(deviceModelId!);
      if (globalWiFiBluetooth.activatedAt == "") {
        globalWiFiBluetooth.updateActivatedAt(deviceActivatedAt!);
      }
      globalWiFiBluetooth.updateDeviceId(deviceId!);
      globalWiFiBluetooth.updateDeviceName(name!);
      globalWiFiBluetooth.updateDeviceType(modelName);
      globalWiFiBluetooth.updateAddNewDeviceSn(sn);

      final connMess = MqttConnectMessage()
          .withClientIdentifier(email)
          .startClean() // 或者 startSession() 用于持久会话
          .authenticateAs(email, token);
      // 设置心跳保持时间
      deviceConnectTypeWifiBlueGet.client!.keepAlivePeriod = 20;
      deviceConnectTypeWifiBlueGet.client!.connectionMessage = connMess;
      deviceConnectTypeWifiBlueGet.client!.autoReconnect = true; //自动连接

      deviceConnectTypeWifiBlueGet.client!.onConnected = () {
        OnConnectVoid.onConnectVoid(
            deviceConnectTypeWifiBlueGet, globalWiFiBluetooth, subTopic, sn);
      };

      deviceConnectTypeWifiBlueGet.client!.onAutoReconnect = () {
        if (deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
            MqttConnectionState.connected) {
          OnConnectVoid.onConnectVoid(
              deviceConnectTypeWifiBlueGet, globalWiFiBluetooth, subTopic, sn);
        } else if (deviceConnectTypeWifiBlueGet
                .client!.connectionStatus!.state ==
            MqttConnectionState.connecting) {
          // print('正在连接到MQTT服务器...');
          // EasyLoading.showToast("正在重试连接");
        } else {
          // EasyLoading.showToast('未连接到MQTT服务器');
        }
      };

      try {
        await deviceConnectTypeWifiBlueGet.client!.connect().then((onValue) {
          /// 检查我们是否已连接。connectionStatus 总是给我们这个和其他信息。
          if (deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
              MqttConnectionState.connected) {
            deviceConnectTypeWifiBlueGet.wifiDeviceSNSubTopicVoid(subTopic);
            // deviceConnectTypeWifiBlueGet.wifiDeviceSNPubTopicVoid(pUBTopic);
            Future.delayed(const Duration(seconds: 10), () {
              if (globalWiFiBluetooth.wifiConnectSendPing.value == 0) {
                globalWiFiBluetooth.isHaveDeviceVoid(false);
                deviceConnectTypeWifiBlueGet.client!.disconnect();
                deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(false);
                EasyLoading.showError("robot_is_online".tr);
              } else {
                // EasyLoading.dismiss();
              }
              if (callback != null) {
                callback();
              }
              globalWiFiBluetooth.isChangeDeviceVoid(false);
            });
            if (!reConnect) {
              globalWiFiBluetooth.wifiConnectSendPingVoid(0);
              //ping机器
              WiFiPush.wifiPush(
                  WriteBluetoothMsgPing.writeBluetoothMsgPing(flag: 1));
            } else {
              WiFiPush.wifiPush(WriteBluetoothMsgPing.writeBluetoothMsgPing());
            }
            deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(true);
            if (callback != null) {
              callback();
            }
          } else {
            if (callback != null) {
              callback();
            }
            EasyLoading.showError("wifi_connect_error".tr);

            deviceConnectTypeWifiBlueGet.client!.disconnect();
            deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(false);
          }
        });
      } on NoConnectionException catch (_) {
        EasyLoading.dismiss();
        if (callback != null) {
          callback();
        }
        //连接失败断开和服务器的连接
        deviceConnectTypeWifiBlueGet.client!.disconnect();
        deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(false);
      }
    }
  }
}

重连后的回调执行的事件

class OnConnectVoid {
  static onConnectVoid(
      DeviceConnectTypeWifiBlueGet deviceConnectTypeWifiBlueGet,
      GlobalWiFiBluetooth globalWiFiBluetooth,
      String subTopic,
      String sn,

      ) {
    globalWiFiBluetooth.isChangeDeviceVoid(true);
    deviceConnectTypeWifiBlueGet.isListenerAddedVoid(false);
    // 重新订阅主题
    try {
      //自动连接
      // deviceConnectTypeWifiBlueGet.client!.doAutoReconnect(force: true);
      deviceConnectTypeWifiBlueGet.client!
          .subscribe(subTopic, MqttQos.atMostOnce);

      deviceConnectTypeWifiBlueGet.client!.subscribe(
          "\$SYS/brokers/掉线",
          MqttQos.atMostOnce);
      deviceConnectTypeWifiBlueGet.client!.subscribe(
          "\$SYS/brokers/重连",
          MqttQos.atMostOnce);
      WiFiPush.wifiPush(
          WriteBluetoothMsgPing.writeBluetoothMsgPing());
    } catch (e) {
      deviceConnectTypeWifiBlueGet.client!
          .subscribe(subTopic, MqttQos.atMostOnce);
      deviceConnectTypeWifiBlueGet.client!.subscribe(
          "\$SYS/brokers/掉线",
          MqttQos.atMostOnce);
      deviceConnectTypeWifiBlueGet.client!.subscribe(
          "\$SYS/brokers/重连",
          MqttQos.atMostOnce);
    }
  }
}

发布信息

class WiFiPush {
  static void wifiPush(List<int> byteData) {
    DeviceConnectTypeWifiBlueGet deviceConnectTypeWifiBlueGet =
        Get.put(DeviceConnectTypeWifiBlueGet());

    final builder = MqttClientPayloadBuilder();
    // List <int> byteData =  WriteBluetoothWeekly5c.writeBluetoothWeekly5c(status: 0);
//设置语言
//     List <int> byteData = WriteBluetoothSetVoiceParam.writeBluetoothSetVoiceParam(1);
    // 将 List<int> 转换为 Uint8List
    // Uint8List uint8List = Uint8List.fromList(byteData);
    /// 检查我们是否已连接。connectionStatus 总是给我们这个和其他信息。
    if (deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
        MqttConnectionState.connected){
      builder.addString(StringByte16.byteString(byteData));
// 主题订阅            // 主题发布
      deviceConnectTypeWifiBlueGet.client!.publishMessage(
          deviceConnectTypeWifiBlueGet.wifiDeviceSNPubTopic.value,
          MqttQos.atMostOnce,
          retain: false,
          builder.payload!);
    }else{
      if(deviceConnectTypeWifiBlueGet.client!= null){
        try {
          deviceConnectTypeWifiBlueGet.client!.connect();
        }catch (_){
          //
        }
      }
    }

  }
}

接收信息

class WiFiSub {
  static void wifiSub(DeviceConnectTypeWifiBlueGet deviceConnectTypeWifiBlueGet,
      GlobalWiFiBluetooth globalWiFiBluetooth) {


    // 监听消息
    deviceConnectTypeWifiBlueGet.client!.updates!
        .listen((List<MqttReceivedMessage<MqttMessage>> c) {
          ///蓝牙连接的状态下,wifi不接受信息
      if (globalWiFiBluetooth.device != null &&
          globalWiFiBluetooth.device!.isConnected &&
          globalWiFiBluetooth.characteristicWrite != null) {
        return;
      }

      // 获取第一个消息
      final recMess = c[0].payload as MqttPublishMessage;
      // 将 MQTT 消息的有效载荷(payload)从字节数组(bytes)转换成字符串
      // final pt = MqttUtilities.bytesToStringAsString(
      //     recMess.payload.message!);
      // 获取原始字节数据
      List<int> bytes = recMess.payload.message;
      // print("version:  1 object ${c[0].topic}");
      if (c[0].topic ==
          deviceConnectTypeWifiBlueGet.wifiDeviceSNSubTopic.value) {
        SharePreferences.sharePreferences("genkinno_flutter_blue_value_list",
            value: bytes);
      }
      /// 机器下线提醒
      if (c[0].topic ==
          "\$SYS/brokers/掉线") {
        EasyLoading.showToast("machine_offline".tr,duration: const Duration(milliseconds: 5000));
      }
      /// 机器上线提醒
      if (c[0].topic ==
          "\$SYS/brokers/重连") {
        EasyLoading.showToast("machine_online".tr,duration: const Duration(milliseconds: 5000));
      }
      // ParsingLastValueUtils.parsingLastValueUtils(bytes);
    });
  }
}

监听链接状态

      ///识别WiFi链接状态
      if (deviceConnectTypeWifiBlueGet.client != null &&
          deviceConnectTypeWifiBlueGet.client!.connectionStatus!.state ==
              MqttConnectionState.connected) {
        deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(true);
        globalWiFiBluetooth.wifiDisconnectVoid(1);
        // EasyLoading.showToast("status  555");
      } else {
        deviceConnectTypeWifiBlueGet.wifiConnectDeviceVoid(false);
        globalWiFiBluetooth.wifiDisconnectVoid(2);
        // EasyLoading.showToast("status6666");
      }

标签:deviceConnectTypeWifiBlueGet,String,globalWiFiBluetooth,mqtt,client,emqx,null,Ea
From: https://blog.csdn.net/python4_1/article/details/144614419

相关文章

  • IoTClient---基于C#开源的物联网设备通讯协议客户端
    https://github.com/zhaopeiym/IoTClientIoTClient是一个物联网设备通讯协议实现客户端,将包括主流PLC通信读取、ModBus协议、Bacnet协议等常用工业通讯协议。本组件基于.NETStandard2.0,可用于.Net的跨平台开发,如Windows、Linux甚至可运行于树莓派上。技术架构1. 编码语......
  • 踩坑之《FTPClient.listFiles()不能获取文件》
    在做一件什么事情当时做在做一个文件上传下载的功能,其中涉及到的是存储FTP服务器。这个系统是某司的内部系统,我们在七楼开发调试,完是到三楼部署。遇到了什么问题当时就遇到了一个很奇怪的问题。问题现象是获取列表的时候,返回数据为空,有时候还会提示链接断开。这个问题坑的我和......
  • 一款使用NET+MQTT+Arduino开发的智能浇花工具
    最近闲来无事,对硬件控制产生了兴趣。看到家里的盆栽,我突然萌生了制作一个自动浇水工具的想法。通过在淘宝搜索并查找相关资料,我了解了需要的硬件和通信协议。接下来,我们先看看需要做哪些准备工作(如安装Arduino、.NET、EMQX工具等,请自行搜索并完成安装)。准备工作硬件清单(淘......
  • 基于QT+MQTT的实时视频监控
    MQTT(MessageQueuingTelemetryTransport)是一种基于发布/订阅模式的轻量级通信协议,广泛应用于物联网领域。它允许设备通过极少的代码和有限的带宽实现实时可靠的消息服务。MQTT协议的核心在于其三部分组成的控制报文:固定报头、可变报头和有效载荷。mqtt中的一些名词解释:https:......
  • 云消息队列 MQTT 版
    云消息队列MQTT版是基于MQTT协议的云端消息队列服务,通常用于物联网(IoT)应用场景中。MQTT(MessageQueuingTelemetryTransport)是一种轻量级、基于发布/订阅模式的消息传输协议,专为低带宽、不稳定的网络和设备资源受限的环境设计。什么是MQTT协议?MQTT是一种简单的、开......
  • 微信小程序自定义组件boundingClientRect获取到的rect值为null
      解决办法: 在自定义组件内获取必须用SelectorQuery.in()Component({lifetimes:{ready(){constquery=wx.createSelectorQuery().in(this)constnum=Math.ceil(this.data.picList.length/LINE_LENGTH)query.select('.tab-content-i......
  • httpClient大文件下载
    在一直项目中使用文件下载,同事反应下载文件做进度条的时候没有正常显示进度条大致代码如下publicclassDowmloadModel{publicstringUrl{get;set;}publicstringLocalSaveFullPath{get;set;}publicboolIscontinue{get;set;}publicActio......
  • zenoh mqtt 简单说明
    zenohmqtt是一个zenoh插件,可以让zenoh提供mqtt的能力(目前支持v3以及v5协议)使用场景路由mqtt到边缘以及云对于mqtt系统进行桥接通过zenohrestapi进行mqtt消息的发布订阅mqttros2交互存储mqtt消息到zenoh支持的存储中(s3,fs,rocksdb)基于influxdb的mqtt消息回......
  • C#实现一个HttpClient集成通义千问-多轮对话功能实现
    多轮对话功能实现视频教程实现原理消息的类型功能开发消息类修改请求体修改发送请求函数修改用户消息输入多轮对话的token消息完整文档消息类型视频教程.Net+AI开发入门HttpClient实现通义千问集成-多轮对话功能实现实现原理一直保留更新messages现在设......
  • 利用ESP-01S中继实现STM32F103C8T6与MQTT服务器的串口双向通信
    最终现象未完待续实现流程STM32通过串口与ESP通信,ESP通过WiFi与MQTT服务器通信元件与接线STM32相关STM32F103C8T6开发板:STM32仿真器:烧录程序时,STM32F103C8T6与仿真器的接下如下:STM32ST-LINK3V33.3VGNDGNDSWDIOSWDIOSWCLKSWCLKUSB转TTL:未完待......