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