Browse Source

修改mqtt

hh 1 week ago
parent
commit
f426cbac36

+ 0 - 62
product/phone/src/main/ets/common/constants/BusinessConstant.ets

@@ -1,62 +0,0 @@
-import HashMap from '@ohos.util.HashMap';
-
-export default class BusinessConstant {
-
-  static readonly mqttSubscribeTopic: string = 'station13/data/devices';
-  static readonly mqttSubscribeTopic2: string = 'station11/data/devices';
-  static readonly mqttPublishTopic: string = 'station13/cmd/devices';
-  static readonly mqttUrl: string = 'tcp://192.168.1.3';
-  // 每个clientId不重复
-  static readonly mqttClientId: string = 'station13' + Date.now().toString(36);
-  static readonly mqttUserName: string = '';
-  static readonly mqttPassword: string = '';
-  // 电烙铁允许最大、最小温度
-  static readonly ironTempMin: number = 150
-  static readonly ironTempMax: number = 450
-  // 最大储位
-  static readonly maxStorageLocation: number = 23 * 7
-
-  static readonly stationName: string = '装配工位001'
-
-  static readonly attrMap: Map<string, string> = new Map([
-    ['LedRed', 'SSD'],
-    ['LedOrange', 'SSD'],
-    ['LedGreen', 'SSD'],
-    ['Buzzer', 'SSD'],
-    ['ExhaustFan', 'HYPYJ'],
-    ['SolderingCurrTemp', 'WKDLT'],
-    ['SolderingSetTemp', 'WKDLT'],
-
-    ['TightenTorqueMax', 'DDLSD'],
-    ['TightenResult', 'DDLSD'],
-    ['TightenTorqueTarget', 'DDLSD'],
-    ['TorqueHoldTime', 'DDLSD'],
-    ['TighteRotationDirection', 'DDLSD'],
-    ['TorqueUpperLimit', 'DDLSD'],
-    ['TorqueLowerLimit', 'DDLSD'],
-    ['SlipDetectionTurns', 'DDLSD'],
-    ['FloatDetectionTurns', 'DDLSD'],
-    ['EnableFloatSlipDetection', 'DDLSD'],
-    ['ScrewWarning', 'DDLSD'],
-
-    ['RingWearNormal', 'FJDJC'],
-    ['RingWearStandby', 'FJDJC'],
-    ['RingWearFault', 'FJDJC'],
-    ['RfidCardNum1', 'DKQ'],
-    ['RfidCardNum2', 'DKQ'],
-    ['lighting', 'ZM'],
-    ['Temperature', 'WSDCGQ'],
-    ['Humidity', 'WSDCGQ'],
-  ]);
-}
-
-export enum DeviceType {
-  ThreeColourLight = 'SSD',
-  WeldFumeExtractor = 'HYPYJ',
-  ElectricSolderingIron = 'WKDLT',
-  ElectricScrewdriver = 'DDLSD',
-  AntiWristStrap = 'FJDJC',
-  CardReader = 'DKQ',
-  Lighting = 'ZM',
-  TempHumiditySensor = 'WSDCGQ',
-}

+ 61 - 0
product/phone/src/main/ets/common/constants/CommonConstants.ets

@@ -64,4 +64,65 @@ export default class CommonConstants {
       lastSelfCheck: '2024/02/16 10:56:34'
     } as RobotInfo,
   ]
+
+  static readonly ipPrefix: string = '192.168.1.'
+  static readonly mqttSubscribeTopic1: string = 'station11/data/devices';
+  static readonly mqttSubscribeTopic2: string = 'station11/data/devices';
+  static readonly mqttSubscribePublish: string = 'station11/cmd/devices';
+  static readonly mqttUrl: string = 'tcp://192.168.1.3';
+  // 默认随机ip
+  static readonly STATION_DEFAULT_IP: string = '192.168.1.' + Math.floor(Math.random() * 90 + 10)
+  // 每个clientId不重复
+  static readonly mqttClientId: string = 'station11' + Date.now().toString(36);
+  static readonly mqttUserName: string = '';
+  static readonly mqttPassword: string = '';
+  // 电烙铁允许最大、最小温度
+  static readonly ironTempMin: number = 150
+  static readonly ironTempMax: number = 450
+  // 最大储位
+  static readonly maxStorageLocation: number = 23 * 7
+
+  static readonly stationName: string = '装配工位001'
+
+  static readonly attrMap: Map<string, string> = new Map([
+    ['LedRed', 'SSD'],
+    ['LedOrange', 'SSD'],
+    ['LedGreen', 'SSD'],
+    ['Buzzer', 'SSD'],
+    ['ExhaustFan', 'HYPYJ'],
+    ['SolderingCurrTemp', 'WKDLT'],
+    ['SolderingSetTemp', 'WKDLT'],
+
+    ['TightenTorqueMax', 'DDLSD'],
+    ['TightenResult', 'DDLSD'],
+    ['TightenTorqueTarget', 'DDLSD'],
+    ['TorqueHoldTime', 'DDLSD'],
+    ['TighteRotationDirection', 'DDLSD'],
+    ['TorqueUpperLimit', 'DDLSD'],
+    ['TorqueLowerLimit', 'DDLSD'],
+    ['SlipDetectionTurns', 'DDLSD'],
+    ['FloatDetectionTurns', 'DDLSD'],
+    ['EnableFloatSlipDetection', 'DDLSD'],
+    ['ScrewWarning', 'DDLSD'],
+
+    ['RingWearNormal', 'FJDJC'],
+    ['RingWearStandby', 'FJDJC'],
+    ['RingWearFault', 'FJDJC'],
+    ['RfidCardNum1', 'DKQ'],
+    ['RfidCardNum2', 'DKQ'],
+    ['lighting', 'ZM'],
+    ['Temperature', 'WSDCGQ'],
+    ['Humidity', 'WSDCGQ'],
+  ]);
 }
+
+export enum DeviceType {
+  ThreeColourLight = 'SSD',
+  WeldFumeExtractor = 'HYPYJ',
+  ElectricSolderingIron = 'WKDLT',
+  ElectricScrewdriver = 'DDLSD',
+  AntiWristStrap = 'FJDJC',
+  CardReader = 'DKQ',
+  Lighting = 'ZM',
+  TempHumiditySensor = 'WSDCGQ',
+}

+ 367 - 0
product/phone/src/main/ets/common/util/Mqtt.ets

@@ -0,0 +1,367 @@
+import { MqttAsync, MqttClient, MqttClientOptions, MqttConnectOptions,MqttQos, MqttMessage, MqttPublishOptions } from '@ohos/mqtt/index';
+import CommonConstants, { DeviceType } from '../../Common/constants/CommonConstants';
+import AntiWristStrap from '../../viewmodel/device/AntiWristStrap';
+import CardReader from '../../viewmodel/device/CardReader';
+import ElectricScrewdriver from '../../viewmodel/device/ElectricScrewdriver';
+import ElectricSolderingIron from '../../viewmodel/device/ElectricSolderingIron';
+import Lighting from '../../viewmodel/device/Lighting';
+import TempHumiditySensor from '../../viewmodel/device/TempHumiditySensor';
+import ThreeColourLight from '../../viewmodel/device/ThreeColourLight';
+import WeldFumeExtractor from '../../viewmodel/device/WeldFumeExtractor';
+
+const TAG = 'hhtest';
+
+type MessageCallback = (topic: string, payload: string) => void;
+
+
+
+interface TagValuePair {
+  tag: string;
+  value: number;
+}
+
+class MqttManager {
+  // static readonly MQTT_SERVICE = '192.168.1.10'
+  private static instance: MqttManager;
+  private client: MqttClient | null = null;
+  private callbacks: Map<string, MessageCallback[]> = new Map();
+
+  private constructor() {}
+
+  public static getInstance(): MqttManager {
+    if (!MqttManager.instance) {
+      MqttManager.instance = new MqttManager();
+    }
+    return MqttManager.instance;
+  }
+
+  public init(options: MqttClientOptions): void {
+    try {
+      this.client = MqttAsync.createMqtt(options);
+      this.registerCallbacks();
+      console.info(TAG, 'MQTT client initialized');
+    } catch (err) {
+      console.error(TAG, `Initialization failed: ${JSON.stringify(err)}`);
+    }
+  }
+
+  private registerCallbacks(): void {
+    if (!this.client) return;
+
+    this.client.messageArrived((err, message) => {
+      if (err) {
+        console.error(TAG, `Message error: ${err.message}`);
+        return;
+      }
+      this.handleMessage(message);
+    });
+
+    this.client.connectLost((err) => {
+      if (err) {
+        console.error(TAG, `Connection lost: ${err.message}`);
+      }
+      this.reconnect();
+    });
+  }
+
+  // 修改后的 handleMessage 方法片段
+  private handleMessage(message: MqttMessage): void {
+    const topic = message.topic;
+    const payload = message.payload.toString();
+    const topicCallbacks = this.callbacks.get(topic) || [];
+    topicCallbacks.forEach(cb => cb(topic, payload));
+    try {
+      const valueJson: MQTTReceiveData = JSON.parse(payload);
+      //订阅主题一的接收数据
+      if (CommonConstants.mqttSubscribeTopic1 == topic) {
+        let device0: ThreeColourLight = {
+          LedRed: 0,
+          LedOrange: 0,
+          LedGreen: 0,
+          Buzzer: 0,
+          OpenStatus: 0
+        }
+        let device1: WeldFumeExtractor = { ExhaustFan: 0, OnlineStatus: 0 }
+        let device2: ElectricSolderingIron = { SolderingCurrTemp: 0, OnlineStatus: 0 }
+        let device3: ElectricScrewdriver = {
+          TighteRotationDirection: 0,
+          TorqueHoldTime: 0,
+          TightenTorqueTarget: 0,
+          TorqueUpperLimit: 0,
+          TorqueLowerLimit: 0,
+          EnableFloatSlipDetection: 0,
+          FloatDetectionTurns: 0,
+          OnlineStatus: 0
+        }
+        let device4: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0, OnlineStatus: 0 }
+        let device5: CardReader = { RfidCardNum1: '', RfidCardNum2: '', OnlineStatus: 0 }
+        let device6: Lighting = { lighting: 0, OnlineStatus: 0 }
+        let device7: TempHumiditySensor = { Temperature: 0, Humidity: 0, OnlineStatus: 0 }
+        let onlineDeviceNum: number = 0
+        for (const element of valueJson.d) {
+          if (CommonConstants.attrMap.has(element.tag)) {
+            let deviceType: string = CommonConstants.attrMap.get(element.tag) ?? '';
+            switch (deviceType) {
+              case DeviceType.ThreeColourLight:
+                onlineDeviceNum++
+                if (element.tag! === 'LedRed') {
+                  device0.LedRed = element.value
+                } else if (element.tag! === 'LedOrange') {
+                  device0.LedOrange = element.value
+                } else if (element.tag! === 'LedGreen') {
+                  device0.LedGreen = element.value
+                } else if (element.tag! === 'Buzzer') {
+                  device0.Buzzer = element.value
+                }
+                if (device0.LedRed! === 1 || device0.LedOrange! === 1
+                  || device0.LedGreen! === 1 || device0.Buzzer! === 1) {
+                  device0.OpenStatus = 1
+                }
+                device0.OnlineStatus = 1
+                break;
+              case DeviceType.WeldFumeExtractor:
+                onlineDeviceNum++
+                if (element.tag! === 'ExhaustFan') {
+                  device1.ExhaustFan = element.value
+                }
+                device1.OnlineStatus = 1
+                break;
+              case DeviceType.ElectricSolderingIron:
+                onlineDeviceNum++
+                if (element.tag! === 'SolderingCurrTemp') {
+                  device2.SolderingCurrTemp = element.value
+                }
+                device2.OnlineStatus = 1
+                break;
+              case DeviceType.ElectricScrewdriver:
+                onlineDeviceNum++
+                if (element.tag! === 'TightenTorqueTarget') {
+                  device3.TightenTorqueTarget = element.value
+                } else if (element.tag! === 'TorqueHoldTime') {
+                  device3.TorqueHoldTime = element.value
+                }
+                device3.OnlineStatus = 1
+                break;
+              case DeviceType.AntiWristStrap:
+                onlineDeviceNum++
+                if (element.tag! === 'RingWearNormal') {
+                  device4.RingWearNormal = element.value
+                } else if (element.tag! === 'RingWearStandby') {
+                  device4.RingWearStandby = element.value
+                } else if (element.tag! === 'RingWearFault') {
+                  device4.RingWearFault = element.value
+                }
+                device4.OnlineStatus = 1
+                break;
+              case DeviceType.CardReader:
+                onlineDeviceNum++
+                if (element.tag! === 'RfidCardNum1') {
+                  let value = element.value?.toString(16)
+                  device5.RfidCardNum1 = value === '0' ? '' : value
+                } else if (element.tag! === 'RfidCardNum2') {
+                  let value = element.value?.toString(16)
+                  device5.RfidCardNum2 = value === '0' ? '' : value
+                }
+                device5.OnlineStatus = 1
+                break;
+              case DeviceType.Lighting:
+                onlineDeviceNum++
+                if (element.tag! === 'lighting') {
+                  device6.lighting = element.value
+                }
+                device6.OnlineStatus = 1
+                break;
+              case DeviceType.TempHumiditySensor:
+                onlineDeviceNum++
+                if (element.tag! === 'Temperature') {
+                  device7.Temperature = element.value
+                } else if (element.tag! === 'Humidity') {
+                  device7.Humidity = element.value
+                }
+                device7.OnlineStatus = 1
+                break;
+            }
+          }
+          AppStorage.setOrCreate<ThreeColourLight>('ThreeColourLight', device0);
+          AppStorage.setOrCreate<WeldFumeExtractor>('WeldFumeExtractor', device1);
+          AppStorage.setOrCreate<ElectricSolderingIron>('ElectricSolderingIron', device2);
+          AppStorage.setOrCreate<ElectricScrewdriver>('ElectricScrewdriver', device3);
+          AppStorage.setOrCreate<AntiWristStrap>('AntiWristStrap', device4);
+          AppStorage.setOrCreate<CardReader>('CardReader', device5);
+          AppStorage.setOrCreate<Lighting>('Lighting', device6)
+          AppStorage.setOrCreate<TempHumiditySensor>('TempHumiditySensor', device7)
+          AppStorage.setOrCreate<number>('onlineDeviceNum', onlineDeviceNum)
+        }
+      } else if (CommonConstants.mqttSubscribeTopic2 == topic) {
+        //订阅主题二的接收数据
+        let device0: TempHumiditySensor = { Temperature: 0, Humidity: 0, OnlineStatus: 0 }
+        for (const element of valueJson.d) {
+          if (CommonConstants.attrMap.has(element.tag)) {
+            let deviceType: string = CommonConstants.attrMap.get(element.tag) ?? '';
+            switch (deviceType) {
+              case DeviceType.TempHumiditySensor:
+                if (element.tag! === 'Temperature') {
+                  device0.Temperature = element.value
+                } else if (element.tag! === 'Humidity') {
+                  device0.Humidity = element.value
+                }
+                device0.OnlineStatus = 1
+                break;
+            }
+          }
+        }
+        AppStorage.setOrCreate<TempHumiditySensor>('TempHumiditySensor', device0);
+      }
+    } catch (e) {
+      console.error("MQTT消息处理异常:", e);
+    }
+  }
+
+  public async connect(options: MqttConnectOptions): Promise<boolean> {
+    if (!this.client) return false;
+
+    try {
+      const res = await this.client.connect(options);
+      if (res.code === 0) {
+        console.info(TAG, 'Connected to broker');
+        return true;
+      }
+      console.error(TAG, `Connect failed: ${res.message}`);
+      return false;
+    } catch (err) {
+      console.error(TAG, `Connect error: ${err.message}`);
+      return false;
+    }
+  }
+
+  public async subscribe(topic: string, callback?: MessageCallback): Promise<void> {
+    if (!this.client) return;
+    try {
+      const res = await this.client.subscribe({ topic, qos: 1 });
+      if (res.code === 0) {
+        console.info(TAG, `Subscribed to ${topic}`);
+        if (callback) {
+          this.addCallback(topic, callback);
+        }
+      }
+    } catch (err) {
+      console.error(TAG, `Subscribe error: ${err.message}`);
+    }
+  }
+
+  private addCallback(topic: string, callback: MessageCallback): void {
+    const callbacks = this.callbacks.get(topic) || [];
+    callbacks.push(callback);
+    this.callbacks.set(topic, callbacks);
+  }
+
+  private reconnect(): void {
+    setTimeout(() => {
+      this.client?.reconnect().then(success => {
+        if (success) {
+          console.info(TAG, 'Reconnected successfully');
+        }
+      });
+    }, 5000);
+  }
+
+  public async disconnect(): Promise<void> {
+    if (!this.client) return;
+
+    try {
+      await this.client.disconnect();
+      console.info(TAG, 'Disconnected');
+    } catch (err) {
+      console.error(TAG, `Disconnect error: ${err.message}`);
+    }
+  }
+  public async publish(
+    topic: string,
+    payload: string | object,
+    qos: MqttQos = 1,
+    retained: boolean = false
+  ): Promise<void> {
+    if (!this.client) {
+      console.error(TAG, 'MQTT客户端未初始化');
+      return;
+    }
+
+    try {
+      // 统一处理 payload 类型
+      const payloadStr = typeof payload === 'string' ? payload : JSON.stringify(payload);
+
+      const options: MqttPublishOptions  = {
+        topic: topic,
+        payload: payloadStr,
+        qos: qos,
+        retained: retained
+      };
+
+      const res = await this.client.publish(options);
+      if (res.code === 0) {
+        console.info(TAG, `消息发布成功: ${topic}`);
+      } else {
+        console.error(TAG, `发布失败: ${res.message}`);
+      }
+    } catch (err) {
+      console.error(TAG, `发布异常: ${JSON.stringify(err)}`);
+    }
+  }
+}
+
+
+export default MqttManager.getInstance();
+
+
+export interface MQTTPublishData {
+  w: TagValuePair[];
+}
+
+export interface MQTTReceiveData {
+  d: TagValuePair[];
+}
+
+
+function decodeRegister(regValue: number | undefined): string {
+  if (regValue === undefined || regValue === 0) return '';
+  //if (regValue === undefined) return ''; // 处理undefined
+
+  // 确保是16位无符号整数
+  const value = regValue & 0xFFFF;
+
+  // 提取高8位和低8位
+  const highByte = (value >> 8) & 0xFF;
+  const lowByte = value & 0xFF;
+
+  // 转换为ASCII字符
+  return String.fromCharCode(highByte) + String.fromCharCode(lowByte);
+}
+
+// 完整RFID解码函数
+function decodeRfidString(
+  rfidData1?: number,
+  rfidData2?: number,
+  rfidData3?: number,
+  rfidData4?: number
+): string {
+  return [
+    decodeRegister(rfidData1),
+    decodeRegister(rfidData2),
+    decodeRegister(rfidData3),
+    decodeRegister(rfidData4)
+  ].join('');
+}
+
+function decodeWeight(regValue: number | undefined): number {
+  if (regValue === undefined) return 0; // 处理undefined
+
+  // 确保是16位无符号整数
+  const value = regValue & 0xFFFF;
+
+  // 提取高8位和低8位
+  const highByte = (value >> 8) & 0xFF;
+  const lowByte = value & 0xFF;
+
+  // 转换为ASCII字符
+  return highByte+lowByte/100
+}

+ 25 - 294
product/phone/src/main/ets/pages/DeviceControllerPage.ets

@@ -1,14 +1,5 @@
 import router from '@ohos.router';
-import {
-  MqttAsync,
-  MqttConnectOptions,
-  MqttSubscribeOptions,
-  MqttPublishOptions,
-  MqttResponse,
-  MqttMessage,
-  MqttClient,
-} from '@ohos/mqtt';
-import BusinessConstant from '../Common/constants/BusinessConstant';
+import CommonConstants from '../Common/constants/CommonConstants';
 import ElectricScrewdriverPresetModel from '../model/ElectricScrewdriverPresetModel';
 import ElectricSolderingIronPresetModel from '../model/ElectricSolderingIronPresetModel';
 import AntiWristStrap from '../viewmodel/device/AntiWristStrap';
@@ -20,20 +11,12 @@ import ThreeColourLight from '../viewmodel/device/ThreeColourLight';
 import WeldFumeExtractor from '../viewmodel/device/WeldFumeExtractor';
 import MqttCmdData from '../viewmodel/mqtt/MqttCmdData';
 import MqttDataItem from '../viewmodel/mqtt/MqttDataItem';
-import MqttUploadData from '../viewmodel/mqtt/MqttUploadData';
 import { AddSubtractComp } from '../common/component/AddSubtractComp'
+import MqttManager from '../common/util/mqtt';
 
 // 声明接受参数的类型
 interface PARAMS {
   deviceType?: number,
-  // 在线状态(1:在线 0:离线)
-  onlineStatus?: number,
-  // 三色灯
-  threeColourLight?: ThreeColourLight,
-  // 电烙铁
-  solderingIron?: ElectricSolderingIron,
-  // 电烙铁
-  screwdriver?: ElectricScrewdriver,
 }
 
 const params = router.getParams() as PARAMS; // 获取传递过来的参数对象
@@ -41,19 +24,6 @@ const params = router.getParams() as PARAMS; // 获取传递过来的参数对
 @Component
 @Entry
 struct DeviceControllerPage {
-  //  Set Client Configuration
-  @State subscribeTopic: string = BusinessConstant.mqttSubscribeTopic;
-  @State publishTopic: string = BusinessConstant.mqttPublishTopic;
-  @State payload: string = '';
-  @State url: string = BusinessConstant.mqttUrl;
-  @State clientId: string = BusinessConstant.mqttClientId;
-  @State userName: string = BusinessConstant.mqttUserName;
-  @State password: string = BusinessConstant.mqttPassword;
-  @State connectedCount: number = 0;
-  // @State isConnect: boolean = false;
-  @State isPromise: boolean = false;
-  private mqttAsyncClient: MqttClient | null = null;
-
   /*
   * 业务参数
   * */
@@ -66,16 +36,18 @@ struct DeviceControllerPage {
   @State deviceType: number = 2
   // @State deviceType: number = 0
   @State onlineStatus: number = 0
+
   //三色灯
-  @State threeColourLight: ThreeColourLight = {}
+  @StorageProp('ThreeColourLight') threeColourLight: ThreeColourLight = {}
   //焊烟排烟机/空气净化器
-  @State weldFumeExtractor: WeldFumeExtractor = { ExhaustFan: 0}
+  @StorageProp('WeldFumeExtractor') weldFumeExtractor: WeldFumeExtractor = { ExhaustFan: 0}
   // 电烙铁
-  @State solderingIron: ElectricSolderingIron = { SolderingCurrTemp: 0}
-  // 防静电手环
-  @State wristStrap: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0, OnlineStatus: 0}
+  @StorageProp('ElectricSolderingIron') solderingIron: ElectricSolderingIron = { SolderingCurrTemp: 0}
   // 电动螺丝刀
-  @State screwdriver: ElectricScrewdriver = { TorqueHoldTime:0 }
+  @StorageProp('ElectricScrewdriver') screwdriver: ElectricScrewdriver = { TorqueHoldTime:0 }
+  // 防静电手环
+  @StorageProp('AntiWristStrap') wristStrap: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0, OnlineStatus: 0}
+
 
   // 电烙铁预设列表
   @State ironPresets: ElectricSolderingIronPreset[] = []
@@ -83,7 +55,7 @@ struct DeviceControllerPage {
   @State screwdriverPresets: ElectricScrewdriverPreset[] = []
 
   // 预设温度
-  @State presetTemp: number = BusinessConstant.ironTempMin
+  @State presetTemp: number = CommonConstants.ironTempMin
 
   // 选择预设
   @State selectPreset: number = -1
@@ -114,16 +86,21 @@ struct DeviceControllerPage {
     customStyle: true,
   })
 
+  private issueControlCommand(tag: string, value: number) {
+    let item: MqttDataItem = {
+      tag: tag,
+      value: value
+    };
+    let mqttData: MqttCmdData = {
+      w: [item]
+    };
+    // 发送控制命令
+    MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
+  }
+
   async aboutToAppear() {
     this.deviceType = ((params && params.deviceType != null) ? params.deviceType : 1000)
-    this.onlineStatus = ((params && params.onlineStatus != null) ? params.onlineStatus : 0)
-    this.threeColourLight = ((params && params.threeColourLight != null) ? params.threeColourLight : {})
-    this.solderingIron = ((params && params.solderingIron != null) ? params.solderingIron : {})
-    this.screwdriver = ((params && params.screwdriver != null) ? params.screwdriver : {})
-
-    await this.createClient();
-    await this.connect();
-    await this.subscribe();
+
     if (this.deviceType === 1) {
       this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList();
       this.presetTemp = this.solderingIron?.SolderingCurrTemp!;
@@ -763,7 +740,7 @@ struct DeviceControllerPage {
             .height('18.5%')
 
             Row() {
-              Slider({ style: SliderStyle.OutSet, value: this.presetTemp, min: BusinessConstant.ironTempMin, max: BusinessConstant.ironTempMax, step: 1})
+              Slider({ style: SliderStyle.OutSet, value: this.presetTemp, min: CommonConstants.ironTempMin, max: CommonConstants.ironTempMax, step: 1})
                 // .blockStyle({ type: SliderBlockType.IMAGE, image: $r('app.media.device_controller_temp'), })
                 .blockSize({width: $r('app.float.virtualSize_19_2'), height: $r('app.float.virtualSize_19_2')})
                 .selectedColor($r('app.color.0A84FF'))
@@ -1184,252 +1161,6 @@ struct DeviceControllerPage {
     .width(px2vp(292))
     .height(px2vp(160))
   }
-
-  private issueControlCommand(tag: string, value: number) {
-    let item: MqttDataItem = {
-      tag: tag,
-      value: value
-    };
-    let mqttData: MqttCmdData = {
-      w: [item]
-    };
-    this.payload = JSON.stringify(mqttData);
-    this.publish();
-  }
-
-  createClient(): undefined | void {
-    console.log("hhtest", '请求连接');
-    if (this.mqttAsyncClient) {
-      return;
-    }
-    this.mqttAsyncClient = MqttAsync.createMqtt({
-      url: this.url,
-      clientId: this.clientId,
-      persistenceType: 1,
-    });
-    let times = 0;
-    while (times < 5) {
-      if (!this.mqttAsyncClient) {
-        this.mqttAsyncClient = MqttAsync.createMqtt({
-          url: this.url,
-          clientId: this.clientId,
-          persistenceType: 1,
-        });
-      }
-      times++;
-    }
-    if (!this.mqttAsyncClient) {
-      console.log("hhtest", '创建失败');
-      return;
-    }
-    // this.messageArrived()
-    this.connectLost()
-    this.mqttAsyncClient.setMqttTrace(6);
-    // // this.showLog("create client success");
-  }
-
-  async connect(): Promise<undefined | void> {
-    console.info('hhtest', "connect");
-    // // this.showLog("connect");
-    let options: MqttConnectOptions = {
-      userName: this.userName,
-      password: this.password,
-      cleanSession:false,
-      connectTimeout: 300
-    };
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.connect(options).then((data: MqttResponse) => {
-          console.info('hhtest', "connect result:" + JSON.stringify(data));
-          this.connectedCount++;
-        }).catch((data: MqttResponse) => {
-          console.info('hhtest', "connect fail result:" + JSON.stringify(data));
-        })
-      } else {
-        this.mqttAsyncClient.connect(options, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "connect result:" + JSON.stringify(data));
-            if (data.message == "Connect Success") {
-              console.info('hhtest', "connect result connectedCount:");
-              this.connectedCount++;
-            }
-          } else {
-            console.info('hhtest', "connect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async publish(): Promise<undefined | void> {
-    console.info('hhtest', "publish");
-    let publishOption: MqttPublishOptions = {
-      topic: this.publishTopic,
-      qos: 1,
-      payload: this.payload
-    }
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.publish(publishOption).then((data: MqttResponse) => {
-          console.info('hhtest', "publish success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "publish fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.publish(publishOption, (err: Error, data: MqttResponse) => {
-          console.info('hhtest', "publish response:");
-          if (!err) {
-            console.info('hhtest', "publish result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "publish error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async subscribe(): Promise<undefined | void> {
-    console.info('hhtest', "subscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      console.info('hhtest', "client not created");
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.subscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "subscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "subscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.subscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async unsubscribe(): Promise<undefined | void> {
-    console.info('hhtest', "unsubscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.unsubscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "unsubscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "unsubscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.unsubscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "unsubscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "unsubscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async disconnect(): Promise<undefined | void> {
-    console.info('hhtest', "disconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.disconnect().then((data: MqttResponse) => {
-          console.info('hhtest', "disconnect success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "disconnect fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.disconnect((err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "disconnect result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "disconnect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async isConnected(): Promise<undefined | boolean> {
-    console.info('hhtest', "isConnected");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    return this.mqttAsyncClient.isConnected().then((data: boolean) => {
-      console.info('hhtest', "isConnected result:" + data);
-      if (!data) {
-      }
-      return data;
-    })
-  }
-
-  async reconnect(): Promise<undefined | void> {
-    console.info('hhtest', "reconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.connectedCount == 0) {
-        console.info('hhtest', "reconnect: client previously not connected");
-        return;
-      }
-      this.mqttAsyncClient.reconnect().then((data: boolean) => {
-        console.info('hhtest', "reConnected result:" + data);
-      });
-    }
-  }
-
-  connectLost(): undefined | void {
-    console.info('hhtest', "connectLost");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.connectLost((err: Error, data: MqttResponse) => {
-      if (!err) {
-        this.reconnect();
-        console.info('hhtest', "connect lost cause:" + JSON.stringify(data));
-      } else {
-        console.info('hhtest', "connect lost error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async destroy(): Promise<undefined | void> {
-    console.info('hhtest', "destroy");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.destroy().then((data: boolean) => {
-      console.info('hhtest', "destroy result:" + data);
-      this.mqttAsyncClient = null;
-      this.connectedCount = 0;
-    });
-  }
 }
 
 // 修改预设名称弹窗

+ 1 - 1
product/phone/src/main/ets/pages/warehouse/StationDevicesPage.ets

@@ -45,7 +45,7 @@ struct StationDevicesPage {
   @State private items: Array<HardwareModel> = [
   //   {
   //   name: '三色灯',
-  //   text: BusinessConstant.stationName,
+  //   text: CommonConstants.stationName,
   //   type: $r('app.media.sansedeng'),
   //   open: $r('app.media.open'),
   //   colse: $r('app.media.colse'),

+ 36 - 493
product/phone/src/main/ets/view/DeviceView.ets

@@ -1,25 +1,16 @@
 import TimeUtil from '../common/util/TimeUtil'
-import BusinessConstant, { DeviceType } from '../common//constants/BusinessConstant'
-import {
-  MqttAsync,
-  MqttConnectOptions,
-  MqttSubscribeOptions,
-  MqttPublishOptions,
-  MqttResponse,
-  MqttMessage,
-  MqttClient,
-} from '@ohos/mqtt';
+import CommonConstants from '../common//constants/CommonConstants'
 import Lighting from '../viewmodel/device/Lighting';
 import router from '@ohos.router';
 import AntiWristStrap from '../viewmodel/device/AntiWristStrap';
 import ThreeColourLight from '../viewmodel/device/ThreeColourLight';
 import ElectricSolderingIron from '../viewmodel/device/ElectricSolderingIron';
 import WeldFumeExtractor from '../viewmodel/device/WeldFumeExtractor';
-import MqttUploadData from '../viewmodel/mqtt/MqttUploadData';
 import MqttDataItem from '../viewmodel/mqtt/MqttDataItem';
 import MqttCmdData from '../viewmodel/mqtt/MqttCmdData';
 import CardReader from '../viewmodel/device/CardReader';
 import ElectricScrewdriver from '../viewmodel/device/ElectricScrewdriver';
+import MqttManager from '../common/util/mqtt';
 
 @Component
 export struct DeviceView {
@@ -29,47 +20,24 @@ export struct DeviceView {
   @State arr: string[] = [];
   scroller: Scroller = new Scroller();
 
-  private mqttAsyncClient: MqttClient | null = null;
-  //  Set Client Configuration
-  @State subscribeTopic: string = BusinessConstant.mqttSubscribeTopic;
-  @State publishTopic: string = BusinessConstant.mqttPublishTopic;
-  @State payload: string = '';
-  @State url: string = BusinessConstant.mqttUrl;
-  @State clientId: string = BusinessConstant.mqttClientId;
-  @State userName: string = BusinessConstant.mqttUserName;
-  @State password: string = BusinessConstant.mqttPassword;
-  @State connectedCount: number = 0;
-  // @State isConnect: boolean = false;
-  @State isPromise: boolean = false;
-
+  //照明
+  @StorageProp('Lighting') lighting: Lighting = {}
   //三色灯
-  @State threeColourLight: ThreeColourLight = { LedRed: 0, LedOrange: 0, LedGreen: 0, Buzzer: 0 }
+  @StorageProp('ThreeColourLight') threeColourLight: ThreeColourLight = {}
   //焊烟排烟机/空气净化器
-  @State weldFumeExtractor: WeldFumeExtractor = { ExhaustFan: 0}
+  @StorageProp('WeldFumeExtractor') weldFumeExtractor: WeldFumeExtractor = { ExhaustFan: 0}
   // 电烙铁
-  @State solderingIron: ElectricSolderingIron = { SolderingCurrTemp: 0}
+  @StorageProp('ElectricSolderingIron') solderingIron: ElectricSolderingIron = { SolderingCurrTemp: 0}
   // 电动螺丝刀
-  @State screwdriver: ElectricScrewdriver = { OnlineStatus: 0}
+  @StorageProp('ElectricScrewdriver') screwdriver: ElectricScrewdriver = { TorqueHoldTime:0 }
   // 防静电手环
-  @State wristStrap: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0,OnlineStatus: 0 }
+  @StorageProp('AntiWristStrap') wristStrap: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0, OnlineStatus: 0}
   // 读卡器
-  @State cardReader: CardReader = { RfidCardNum1: '', RfidCardNum2: '', OnlineStatus: 0}
-  // 照明
-  @State lighting: Lighting = { lighting: 0, OnlineStatus: 0 }
+  @StorageProp('CardReader') cardReader: CardReader = {}
 
 
   private swiperController: SwiperController = new SwiperController()
 
-  async aboutToAppear() {
-    await this.createClient();
-    await this.connect();
-    await this.subscribe();
-  }
-
-  // async aboutToDisappear() {
-  //   await this.disconnect();
-  //   await this.destroy()
-  // }
 
   build() {
     Column() {
@@ -249,7 +217,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor(this.weldFumeExtractor?.ExhaustFan! === 1 ? $r("app.color.99000000") : $r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -288,14 +256,14 @@ export struct DeviceView {
                 let mqttData: MqttCmdData = {
                   w: [item]
                 }
-                this.payload = JSON.stringify(mqttData)
-                this.publish()
-                if (this.weldFumeExtractor?.OnlineStatus! === 1) {
-                  this.weldFumeExtractor = {
-                    ExhaustFan: item.value,
-                    OnlineStatus: 1
-                  }
-                }
+                // 发送控制命令
+                MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
+                // if (this.weldFumeExtractor?.OnlineStatus! === 1) {
+                //   this.weldFumeExtractor = {
+                //     ExhaustFan: item.value,
+                //     OnlineStatus: 1
+                //   }
+                // }
               })
 
               // 照明
@@ -314,7 +282,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor(this.lighting?.lighting! === 1 ? $r("app.color.99000000") : $r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -353,14 +321,14 @@ export struct DeviceView {
                 let mqttData: MqttCmdData = {
                   w: [item]
                 }
-                this.payload = JSON.stringify(mqttData)
-                this.publish()
-                if (this.lighting?.OnlineStatus! === 1) {
-                  this.lighting = {
-                    lighting: item.value,
-                    OnlineStatus: 1
-                  }
-                }
+                // 发送控制命令
+                MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
+                // if (this.lighting?.OnlineStatus! === 1) {
+                //   this.lighting = {
+                //     lighting: item.value,
+                //     OnlineStatus: 1
+                //   }
+                // }
               })
 
               // 读卡器
@@ -384,7 +352,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -448,7 +416,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -508,7 +476,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r('app.color.FFFFFF'))
                     .fontWeight(FontWeight.Lighter)
@@ -566,7 +534,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -621,7 +589,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r('app.color.FFFFFF'))
                     .fontWeight(FontWeight.Lighter)
@@ -678,7 +646,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -759,7 +727,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r("app.color.60FFFFFF"))
                     .fontWeight(FontWeight.Lighter)
@@ -807,7 +775,7 @@ export struct DeviceView {
                 .width('100%')
                 .justifyContent(FlexAlign.Center)
                 Row() {
-                  Text(BusinessConstant.stationName)
+                  Text(CommonConstants.stationName)
                     .fontSize($r('app.float.fontSize_6_4'))
                     .fontColor($r('app.color.FFFFFF'))
                     .fontWeight(FontWeight.Lighter)
@@ -848,430 +816,5 @@ export struct DeviceView {
     .width('100%')
     .height('100%')
   }
-
-  createClient(): undefined | void {
-    console.log("hhtest", '请求连接');
-    if (this.mqttAsyncClient) {
-      return;
-    }
-    this.mqttAsyncClient = MqttAsync.createMqtt({
-      url: this.url,
-      clientId: this.clientId,
-      persistenceType: 1,
-    });
-    let num = 0
-    while (num < 5) {
-      if (!this.mqttAsyncClient) {
-        this.mqttAsyncClient = MqttAsync.createMqtt({
-          url: this.url,
-          clientId: this.clientId,
-          persistenceType: 1,
-        });
-      }
-      num++
-    }
-    if (!this.mqttAsyncClient) {
-      console.log("hhtest", '创建失败');
-      return;
-    }
-    this.messageArrived()
-    this.connectLost()
-    this.mqttAsyncClient.setMqttTrace(6);
-    // // this.showLog("create client success");
-  }
-
-  async connect(): Promise<undefined | void> {
-    console.info('hhtest', "connect");
-    // // this.showLog("connect");
-    let options: MqttConnectOptions = {
-      userName: this.userName,
-      password: this.password,
-      cleanSession:false,
-      connectTimeout: 300
-    };
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.connect(options).then((data: MqttResponse) => {
-          console.info('hhtest', "connect result:" + JSON.stringify(data));
-          this.connectedCount++;
-        }).catch((data: MqttResponse) => {
-          console.info('hhtest', "connect fail result:" + JSON.stringify(data));
-        })
-      } else {
-        this.mqttAsyncClient.connect(options, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "connect result:" + JSON.stringify(data));
-            if (data.message == "Connect Success") {
-              console.info('hhtest', "connect result connectedCount:");
-              this.connectedCount++;
-            }
-          } else {
-            console.info('hhtest', "connect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async publish(): Promise<undefined | void> {
-    console.info('hhtest', "publish");
-    let publishOption: MqttPublishOptions = {
-      topic: this.publishTopic,
-      qos: 1,
-      payload: this.payload
-    }
-    console.log('hhtest', 'publish msg:----------' + JSON.stringify(publishOption))
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.publish(publishOption).then((data: MqttResponse) => {
-          console.info('hhtest', "publish success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "publish fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.publish(publishOption, (err: Error, data: MqttResponse) => {
-          console.info('hhtest', "publish response:");
-          if (!err) {
-            console.info('hhtest', "publish result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "publish error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async subscribe(): Promise<undefined | void> {
-    console.info('hhtest', "subscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      console.info('hhtest', "client not created");
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.subscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "subscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "subscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.subscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  messageArrived(): undefined | void {
-    console.info('hhtest', "messageArrived");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.messageArrived((err: Error, data: MqttMessage) => {
-      if (!err) {
-        // this.showLog(msg);
-        let dataStr = JSON.stringify(data);
-        console.info('hhtest', "messageArrived message:" + dataStr);
-        if (dataStr.indexOf(this.subscribeTopic) === -1) {
-          return
-        }
-        let updateData: MqttUploadData = JSON.parse(data.payload) as MqttUploadData;
-        if (!updateData || !updateData.d || updateData.d.length <= 0) {
-          console.info('hhtest', "updateData没有解析成功" + JSON.stringify(updateData));
-          return
-        }
-
-        let device0: ThreeColourLight = { LedRed: 0, LedOrange: 0, LedGreen: 0, Buzzer: 0, OpenStatus: 0 }
-        let device1: WeldFumeExtractor = { ExhaustFan: 0, OnlineStatus: 0}
-        let device2: ElectricSolderingIron = { SolderingCurrTemp: 0, OnlineStatus: 0}
-        let device3: ElectricScrewdriver = { TighteRotationDirection: 0, TorqueHoldTime: 0, TightenTorqueTarget: 0,
-          TorqueUpperLimit: 0, TorqueLowerLimit: 0, EnableFloatSlipDetection: 0, FloatDetectionTurns: 0, OnlineStatus: 0}
-        let device4: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0,OnlineStatus: 0 }
-        let device5: CardReader = { RfidCardNum1: '', RfidCardNum2: '', OnlineStatus: 0}
-        let device6: Lighting = { lighting: 0, OnlineStatus: 0 }
-        let collectFlag: Array<boolean> = [false, false, false, false, false, false, false, false]
-        for (const element of updateData.d) {
-          if (BusinessConstant.attrMap.has(element.tag)) {
-            let deviceType: string = BusinessConstant.attrMap.get(element.tag) ?? '';
-            switch (deviceType) {
-              case DeviceType.ThreeColourLight:
-                collectFlag[0] = true
-                if (element.tag! === 'LedRed') {
-                  device0.LedRed = element.value
-                } else if (element.tag! === 'LedOrange') {
-                  device0.LedOrange = element.value
-                } else if (element.tag! === 'LedGreen') {
-                  device0.LedGreen = element.value
-                } else if (element.tag! === 'Buzzer') {
-                  device0.Buzzer = element.value
-                }
-                if (device0.LedRed! === 1 || device0.LedOrange! === 1
-                  || device0.LedGreen! === 1 || device0.Buzzer! === 1) {
-                  device0.OpenStatus = 1
-                }
-                device0.OnlineStatus = 1
-                break;
-              case DeviceType.WeldFumeExtractor:
-                collectFlag[1] = true
-                if (element.tag! === 'ExhaustFan') {
-                  device1.ExhaustFan = element.value
-                }
-                device1.OnlineStatus = 1
-                break;
-              case DeviceType.ElectricSolderingIron:
-                collectFlag[2] = true
-                if (element.tag! === 'SolderingCurrTemp') {
-                  device2.SolderingCurrTemp = element.value
-                }
-                device2.OnlineStatus = 1
-                break;
-              case DeviceType.ElectricScrewdriver:
-                collectFlag[3] = true
-                if (element.tag! === 'TightenTorqueTarget') {
-                  device3.TightenTorqueTarget = element.value
-                } else if (element.tag! === 'TorqueHoldTime') {
-                  device3.TorqueHoldTime = element.value
-                }
-                device3.OnlineStatus = 1
-                break;
-              case DeviceType.AntiWristStrap:
-                collectFlag[4] = true
-                if (element.tag! === 'RingWearNormal') {
-                  device4.RingWearNormal = element.value
-                } else if (element.tag! === 'RingWearStandby') {
-                  device4.RingWearStandby = element.value
-                } else if (element.tag! === 'RingWearFault') {
-                  device4.RingWearFault = element.value
-                }
-                device4.OnlineStatus = 1
-                break;
-              case DeviceType.CardReader:
-                collectFlag[5] = true
-                if (element.tag! === 'RfidCardNum1') {
-                  let value = element.value?.toString(16)
-                  device5.RfidCardNum1 = value === '0' ? '' : value
-                } else if (element.tag! === 'RfidCardNum2') {
-                  let value = element.value?.toString(16)
-                  device5.RfidCardNum2 = value === '0' ? '' : value
-                }
-                device5.OnlineStatus = 1
-                break;
-              case DeviceType.Lighting:
-                collectFlag[6] = true
-                if (element.tag! === 'lighting') {
-                  device6.lighting = element.value
-                }
-                device6.OnlineStatus = 1
-                break;
-            }
-          }
-        }
-        if (collectFlag[0]) {
-          this.threeColourLight = device0;
-        } else {
-          this.threeColourLight = {
-            LedRed: this.threeColourLight.LedRed,
-            LedGreen: this.threeColourLight.LedGreen,
-            LedOrange: this.threeColourLight.LedOrange,
-            Buzzer: this.threeColourLight.Buzzer,
-            OpenStatus: 0
-          }
-        }
-        if (collectFlag[1]) {
-          this.weldFumeExtractor = device1;
-        } else {
-          this.weldFumeExtractor.OnlineStatus = 0
-          this.weldFumeExtractor = {
-            ExhaustFan: this.weldFumeExtractor.ExhaustFan,
-            OnlineStatus: 0
-          }
-        }
-        if (collectFlag[2]) {
-          this.solderingIron = device2;
-        } else {
-          this.solderingIron.OnlineStatus = 0
-          this.solderingIron = {
-            SolderingCurrTemp: this.solderingIron.SolderingCurrTemp,
-            OnlineStatus: 0
-          }
-        }
-        if (collectFlag[3]) {
-          this.screwdriver = JSON.parse(JSON.stringify(device3)) as ElectricScrewdriver;
-        } else {
-          this.screwdriver = {
-            TightenTorqueTarget: this.screwdriver.TightenTorqueTarget,
-            TorqueHoldTime: this.screwdriver.TorqueHoldTime,
-            OnlineStatus: 0
-          }
-        }
-        if (collectFlag[4]) {
-          this.wristStrap = JSON.parse(JSON.stringify(device4)) as AntiWristStrap;
-        } else {
-          this.wristStrap = {
-            RingWearNormal: this.wristStrap.RingWearNormal,
-            RingWearStandby: this.wristStrap.RingWearStandby,
-            RingWearFault: this.wristStrap.RingWearFault,
-            OnlineStatus: 0
-          }
-        }
-        if (collectFlag[5]) {
-          this.cardReader = JSON.parse(JSON.stringify(device5)) as CardReader;
-        } else {
-          this.cardReader = {
-            RfidCardNum1: this.cardReader.RfidCardNum1,
-            RfidCardNum2: this.cardReader.RfidCardNum2,
-            OnlineStatus: 0
-          }
-        }
-        if (collectFlag[6]) {
-          this.lighting = JSON.parse(JSON.stringify(device6)) as Lighting;
-        } else {
-          this.lighting = {
-            lighting: this.lighting.lighting,
-            OnlineStatus: 0
-          }
-        }
-        console.info('hhtest', "this.threeColourLight" + JSON.stringify(this.threeColourLight));
-        console.info('hhtest', "this.weldFumeExtractor" + JSON.stringify(this.weldFumeExtractor));
-        console.info('hhtest', "this.solderingIron" + JSON.stringify(this.solderingIron));
-        console.info('hhtest', "this.wristStrap" + JSON.stringify(this.wristStrap));
-        console.info('hhtest', "this.cardReader" + JSON.stringify(this.cardReader));
-        console.info('hhtest', "this.lighting" + JSON.stringify(this.lighting));
-      } else {
-        console.info('hhtest', "messageArrived error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async unsubscribe(): Promise<undefined | void> {
-    console.info('hhtest', "unsubscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.unsubscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "unsubscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "unsubscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.unsubscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "unsubscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "unsubscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async disconnect(): Promise<undefined | void> {
-    console.info('hhtest', "disconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.disconnect().then((data: MqttResponse) => {
-          console.info('hhtest', "disconnect success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "disconnect fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.disconnect((err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "disconnect result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "disconnect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async isConnected(): Promise<undefined | boolean> {
-    console.info('hhtest', "isConnected");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    return this.mqttAsyncClient.isConnected().then((data: boolean) => {
-      console.info('hhtest', "isConnected result:" + data);
-      if (!data) {
-      }
-      return data;
-    })
-  }
-
-  async reconnect(): Promise<undefined | void> {
-    console.info('hhtest', "reconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.connectedCount == 0) {
-        console.info('hhtest', "reconnect: client previously not connected");
-        return;
-      }
-      this.mqttAsyncClient.reconnect().then((data: boolean) => {
-        console.info('hhtest', "reConnected result:" + data);
-      });
-    }
-  }
-
-  connectLost(): undefined | void {
-    console.info('hhtest', "connectLost");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.connectLost((err: Error, data: MqttResponse) => {
-      if (!err) {
-        this.reconnect();
-        console.info('hhtest', "connect lost cause:" + JSON.stringify(data));
-      } else {
-        console.info('hhtest', "connect lost error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async destroy(): Promise<undefined | void> {
-    console.info('hhtest', "destroy");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.destroy().then((data: boolean) => {
-      console.info('hhtest', "destroy result:" + data);
-      this.mqttAsyncClient = null;
-      this.connectedCount = 0;
-    });
-  }
-
-  clear(): void {
-    this.arr = [];
-  }
-
-  setIsPromise(isPromise: boolean): void {
-    this.isPromise = !isPromise
-    console.info('hhtest', "setIsPromise result:" + this.isPromise);
-  }
 }
 

+ 68 - 360
product/phone/src/main/ets/view/HomeView.ets

@@ -1,4 +1,4 @@
-import BusinessConstant, { DeviceType } from '../common/constants/BusinessConstant'
+import CommonConstants, { DeviceType } from '../common/constants/CommonConstants'
 import MesAioRequest from '../common/util/request/MesAioRequest'
 import TimeUtil from '../Common/util/TimeUtil'
 import RequestParamModel from '../viewmodel/warehouse/RequestParamModel'
@@ -10,49 +10,88 @@ import {
   MqttResponse,
   MqttMessage,
   MqttClient,
+  MqttClientOptions,
 } from '@ohos/mqtt';
+import MqttManager from '../common/util/mqtt';
 import MqttUploadData from '../viewmodel/mqtt/MqttUploadData'
 import TempHumiditySensor from '../viewmodel/device/TempHumiditySensor'
 import ElectricScrewdriverPresetModel from '../model/ElectricScrewdriverPresetModel';
 import ElectricSolderingIronPresetModel from '../model/ElectricSolderingIronPresetModel';
+import connection from '@ohos.net.connection';
 
 @Component
 export struct HomeView {
-
-  private mqttAsyncClient: MqttClient | null = null;
-  //  Set Client Configuration
-  @State subscribeTopic: string = BusinessConstant.mqttSubscribeTopic;
-  @State subscribeTopic2: string = BusinessConstant.mqttSubscribeTopic2;
-  @State publishTopic: string = BusinessConstant.mqttPublishTopic;
-  @State payload: string = '';
-  @State url: string = BusinessConstant.mqttUrl;
-  @State clientId: string = BusinessConstant.mqttClientId;
-  @State userName: string = BusinessConstant.mqttUserName;
-  @State password: string = BusinessConstant.mqttPassword;
-  @State connectedCount: number = 0;
-  // @State isConnect: boolean = false;
-  @State isPromise: boolean = false;
-
-
   @State numList: number[] = [1,2,3]
-
   @State planFinish: PlanFinish = {}
-
-  @State tempHumiditySensor: TempHumiditySensor = {OnlineStatus: 0}
-  @State onlineDeviceNum: number = 0
   @State userStatistics: UserStatistics = {}
   @State outsourceStatistics: OutsourceStatistics = {}
   @State vehicleStatistics: VehicleStatistics = {}
   @State processStatistics: ProductProcessStatistics = {}
-
+  @Provide('stationIp') stationIp:string = ''
+  // mqtt是否连接
+  @State isConnected: boolean = false
+  // 温湿度传感器
+  @StorageProp('TempHumiditySensor') tempHumiditySensor: TempHumiditySensor = {}
+  // 温湿度传感器
+  @StorageProp('onlineDeviceNum') onlineDeviceNum: number = 0
   private swiperController: SwiperController = new SwiperController()
 
+  connectMQTT = async ()=> {
+    const clientOptions: MqttClientOptions = {
+      url: 'mqtt://192.168.1.3:1883',   // 替换实际IP
+      clientId: `process_client_${Date.now()}`,
+      persistenceType: 1,              // 使用英文逗号       // 建议开启自动重连
+    };
+    // MQTT连接配置
+    const connectOptions: MqttConnectOptions = {
+      cleanSession: true,
+      connectTimeout: 30,
+      keepAliveInterval: 60,
+      userName: 'optional_username',
+      password: 'optional_password'
+    };
+    try {
+      MqttManager.init(clientOptions);
+      this.isConnected = await MqttManager.connect(connectOptions);
+      if (this.isConnected ) {
+        console.info('hhtest', 'MQTT connected successfully');
+        await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic1);
+        if (CommonConstants.mqttSubscribeTopic1 != CommonConstants.mqttSubscribeTopic2) {
+          await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic2);
+        }
+      } else {
+        console.error('hhtest', 'MQTT connection failed');
+      }
+    } catch (err) {
+      console.error('hhtest', `MQTT error: ${JSON.stringify(err)}`);
+    }
+  }
+
   async aboutToAppear() {
     ElectricScrewdriverPresetModel.initTaskDB(getContext())
     ElectricSolderingIronPresetModel.initTaskDB(getContext())
-    await this.createClient();
-    await this.connect();
-    await this.subscribe();
+    // 获取工位ip
+    this.stationIp = CommonConstants.STATION_DEFAULT_IP
+    try {
+      const netHandle = connection.getDefaultNetSync();
+      if (netHandle) {
+        let connectionProperties = await connection.getConnectionProperties(netHandle)
+        if (connectionProperties && connectionProperties.linkAddresses) {
+          connectionProperties.linkAddresses.forEach((address: connection.LinkAddress, index: number) => {
+            this.stationIp = address.address.address
+            if (address.address.address.startsWith(CommonConstants.ipPrefix)) {
+              // todo 部署时放开注释
+              // CommonConstants.mqttSubscribeTopic1 = 'station' + address.address.address.replace(CommonConstants.ipPrefix, '') + '/data/devices'
+              // CommonConstants.mqttSubscribePublish = 'station' + address.address.address.replace(CommonConstants.ipPrefix, '') + '/cmd/devices'
+            }
+          })
+        }
+      }
+    } catch (err) {
+      console.log('hhtest', err);
+    }
+    // 创建mqtt连接和usb设备连接
+    this.connectMQTT()
     this.planFinish = await MesAioRequest.post("/api/v1/process/census/task/count", {} as RequestParamModel)
     this.userStatistics = await MesAioRequest.post("/api/v1/test/userStatistics", {} as RequestParamModel)
     this.outsourceStatistics = await MesAioRequest.post("/api/v1/test/outsourceStatistics", {} as RequestParamModel)
@@ -163,7 +202,7 @@ export struct HomeView {
                 .alignItems(VerticalAlign.Bottom)
 
                 // Row() {
-                //   Text(BusinessConstant.stationName)
+                //   Text(CommonConstants.stationName)
                 //     .fontSize($r('app.float.fontSize_6_4'))
                 //     .fontColor($r('app.color.FFFFFF'))
                 //     .fontWeight(FontWeight.Lighter)
@@ -319,7 +358,7 @@ export struct HomeView {
                 .alignItems(VerticalAlign.Bottom)
                 .justifyContent(FlexAlign.Center)
                 // Row() {
-                //   Text(BusinessConstant.stationName)
+                //   Text(CommonConstants.stationName)
                 //     .fontSize($r('app.float.fontSize_6_4'))
                 //     .fontColor($r('app.color.FFFFFF'))
                 //     .fontWeight(FontWeight.Lighter)
@@ -631,7 +670,7 @@ export struct HomeView {
                 Row() {}.height('10%')
                 Row() {
                   Stack() {
-                    Progress({ value: (this.vehicleStatistics?.totalNum! ? this.vehicleStatistics.totalNum : 0), total: BusinessConstant.maxStorageLocation, type: ProgressType.Ring})
+                    Progress({ value: (this.vehicleStatistics?.totalNum! ? this.vehicleStatistics.totalNum : 0), total: CommonConstants.maxStorageLocation, type: ProgressType.Ring})
                       .width($r('app.float.virtualSize_58'))
                       .height($r('app.float.virtualSize_58'))
                       .style({strokeWidth: $r('app.float.virtualSize_6_4')})
@@ -640,7 +679,7 @@ export struct HomeView {
                       .backgroundColor($r('app.color.10FFFFFF'))
 
                     Row() {
-                      Text(this.vehicleStatistics?.totalNum! ? (this.vehicleStatistics.totalNum * 100 / BusinessConstant.maxStorageLocation).toFixed(1) : '0')
+                      Text(this.vehicleStatistics?.totalNum! ? (this.vehicleStatistics.totalNum * 100 / CommonConstants.maxStorageLocation).toFixed(1) : '0')
                         .fontSize($r('app.float.fontSize_15_2'))
                         .fontColor($r('app.color.FFFFFF'))
                         .fontWeight(FontWeight.Lighter)
@@ -986,337 +1025,6 @@ export struct HomeView {
     .width('100%')
     .height('100%')
   }
-
-  createClient(): undefined | void {
-    console.log("hhtest", '请求连接');
-    if (this.mqttAsyncClient) {
-      return;
-    }
-    this.mqttAsyncClient = MqttAsync.createMqtt({
-      url: this.url,
-      clientId: this.clientId,
-      persistenceType: 1,
-    });
-    let num = 0
-    while (num < 5) {
-      if (!this.mqttAsyncClient) {
-        this.mqttAsyncClient = MqttAsync.createMqtt({
-          url: this.url,
-          clientId: this.clientId,
-          persistenceType: 1,
-        });
-      }
-      num++
-    }
-    if (!this.mqttAsyncClient) {
-      console.log("hhtest", '创建失败');
-      return;
-    }
-    this.messageArrived()
-    this.connectLost()
-    this.mqttAsyncClient.setMqttTrace(6);
-    // // this.showLog("create client success");
-  }
-
-  async connect(): Promise<undefined | void> {
-    console.info('hhtest', "connect");
-    // // this.showLog("connect");
-    let options: MqttConnectOptions = {
-      userName: this.userName,
-      password: this.password,
-      cleanSession:false,
-      connectTimeout: 300
-    };
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.connect(options).then((data: MqttResponse) => {
-          console.info('hhtest', "connect result:" + JSON.stringify(data));
-          this.connectedCount++;
-        }).catch((data: MqttResponse) => {
-          console.info('hhtest', "connect fail result:" + JSON.stringify(data));
-        })
-      } else {
-        this.mqttAsyncClient.connect(options, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "connect result:" + JSON.stringify(data));
-            if (data.message == "Connect Success") {
-              console.info('hhtest', "connect result connectedCount:");
-              this.connectedCount++;
-            }
-          } else {
-            console.info('hhtest', "connect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async publish(): Promise<undefined | void> {
-    console.info('hhtest', "publish");
-    let publishOption: MqttPublishOptions = {
-      topic: this.publishTopic,
-      qos: 1,
-      payload: this.payload
-    }
-    console.log('hhtest', 'publish msg:----------' + JSON.stringify(this.payload))
-    console.log('hhtest', 'publish msg:----------' + JSON.stringify(publishOption))
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.publish(publishOption).then((data: MqttResponse) => {
-          console.info('hhtest', "publish success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "publish fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.publish(publishOption, (err: Error, data: MqttResponse) => {
-          console.info('hhtest', "publish response:");
-          if (!err) {
-            console.info('hhtest', "publish result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "publish error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async subscribe(): Promise<undefined | void> {
-    console.info('hhtest', "subscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      console.info('hhtest', "client not created");
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.subscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "subscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "subscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.subscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-    if (this.subscribeTopic === this.subscribeTopic2) {
-      return
-    }
-    let subscribeOption2: MqttSubscribeOptions = {
-      topic: this.subscribeTopic2,
-      qos: 2
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.subscribe(subscribeOption2).then((data: MqttResponse) => {
-          console.info('hhtest', "subscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "subscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.subscribe(subscribeOption2, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  messageArrived(): undefined | void {
-    console.info('hhtest', "messageArrived");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.messageArrived((err: Error, data: MqttMessage) => {
-      if (!err) {
-        // this.showLog(msg);
-        let dataStr = JSON.stringify(data);
-        console.info('hhtest', "messageArrived message:" + dataStr);
-        if (dataStr.indexOf(this.subscribeTopic2) === -1) {
-          return
-        }
-        let updateData: MqttUploadData = JSON.parse(data.payload) as MqttUploadData;
-        if (!updateData || !updateData.d || updateData.d.length <= 0) {
-          console.info('hhtest', "updateData没有解析成功" + JSON.stringify(updateData));
-          return
-        }
-
-        let device0: TempHumiditySensor = { Temperature: 0, Humidity: 0, OnlineStatus: 0 }
-        this.onlineDeviceNum = 0
-        let collectFlag: Array<boolean> = [false]
-        for (const element of updateData.d) {
-          if (BusinessConstant.attrMap.has(element.tag)) {
-            let deviceType: string = BusinessConstant.attrMap.get(element.tag) ?? '';
-            switch (deviceType) {
-              case DeviceType.TempHumiditySensor:
-                collectFlag[0] = true
-                if (element.tag! === 'Temperature') {
-                  device0.Temperature = element.value
-                } else if (element.tag! === 'Humidity') {
-                  device0.Humidity = element.value
-                }
-                device0.OnlineStatus = 1
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.WeldFumeExtractor:
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.ElectricSolderingIron:
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.ElectricScrewdriver:
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.AntiWristStrap:
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.CardReader:
-                this.onlineDeviceNum++
-                break;
-              case DeviceType.Lighting:
-                this.onlineDeviceNum++
-                break;
-            }
-          }
-        }
-        if (collectFlag[0]) {
-          this.tempHumiditySensor = device0;
-        } else {
-          this.tempHumiditySensor = {
-            OnlineStatus: 0
-          }
-        }
-        console.info('hhtest', "this.tempHumiditySensor" + JSON.stringify(this.tempHumiditySensor));
-      } else {
-        console.info('hhtest', "messageArrived error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async unsubscribe(): Promise<undefined | void> {
-    console.info('hhtest', "unsubscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.unsubscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "unsubscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "unsubscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.unsubscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "unsubscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "unsubscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async disconnect(): Promise<undefined | void> {
-    console.info('hhtest', "disconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.disconnect().then((data: MqttResponse) => {
-          console.info('hhtest', "disconnect success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "disconnect fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.disconnect((err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "disconnect result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "disconnect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async isConnected(): Promise<undefined | boolean> {
-    console.info('hhtest', "isConnected");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    return this.mqttAsyncClient.isConnected().then((data: boolean) => {
-      console.info('hhtest', "isConnected result:" + data);
-      if (!data) {
-      }
-      return data;
-    })
-  }
-
-  async reconnect(): Promise<undefined | void> {
-    console.info('hhtest', "reconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.connectedCount == 0) {
-        console.info('hhtest', "reconnect: client previously not connected");
-        return;
-      }
-      this.mqttAsyncClient.reconnect().then((data: boolean) => {
-        console.info('hhtest', "reConnected result:" + data);
-      });
-    }
-  }
-
-  connectLost(): undefined | void {
-    console.info('hhtest', "connectLost");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.connectLost((err: Error, data: MqttResponse) => {
-      if (!err) {
-        this.reconnect();
-        console.info('hhtest', "connect lost cause:" + JSON.stringify(data));
-      } else {
-        console.info('hhtest', "connect lost error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async destroy(): Promise<undefined | void> {
-    console.info('hhtest', "destroy");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.destroy().then((data: boolean) => {
-      console.info('hhtest', "destroy result:" + data);
-      this.mqttAsyncClient = null;
-      this.connectedCount = 0;
-    });
-  }
 }
 
 

+ 6 - 311
product/phone/src/main/ets/view/WorkshopView.ets

@@ -1,5 +1,5 @@
 import { McBarChart, McLineChart, Options } from '@mcui/mccharts'
-import BusinessConstant, { DeviceType } from '../common/constants/BusinessConstant'
+import CommonConstants, { DeviceType } from '../common/constants/CommonConstants'
 import MesAioRequest from '../common/util/request/MesAioRequest'
 import TimeUtil from '../Common/util/TimeUtil'
 import RequestParamModel from '../viewmodel/warehouse/RequestParamModel'
@@ -16,23 +16,10 @@ import MqttUploadData from '../viewmodel/mqtt/MqttUploadData'
 import TempHumiditySensor from '../viewmodel/device/TempHumiditySensor'
 import MqttDataItem from '../viewmodel/mqtt/MqttDataItem'
 import MqttCmdData from '../viewmodel/mqtt/MqttCmdData'
+import MqttManager from '../common/util/mqtt';
 
 @Component
 export struct WorkshopView {
-  private mqttAsyncClient: MqttClient | null = null;
-  //  Set Client Configuration
-  @State subscribeTopic: string = BusinessConstant.mqttSubscribeTopic;
-  @State publishTopic: string = BusinessConstant.mqttPublishTopic;
-  @State payload: string = '';
-  @State url: string = BusinessConstant.mqttUrl;
-  @State clientId: string = BusinessConstant.mqttClientId;
-  @State userName: string = BusinessConstant.mqttUserName;
-  @State password: string = BusinessConstant.mqttPassword;
-  @State connectedCount: number = 0;
-  // @State isConnect: boolean = false;
-  @State isPromise: boolean = false;
-
-
   @State stations: StationRelateInfo[] = []
 
   @State deviceArray: DeviceInfo[] = [
@@ -160,10 +147,6 @@ export struct WorkshopView {
         }
       }
     }
-    await this.createClient();
-    await this.connect();
-    await this.subscribe();
-
     this.stations = await MesAioRequest.post("/api/v1/test/queryStationRelateInfo", {} as RequestParamModel)
 
     if (this.stations && this.stations.length > 0) {
@@ -495,8 +478,8 @@ export struct WorkshopView {
             let mqttData: MqttCmdData = {
               w: [item]
             }
-            this.payload = JSON.stringify(mqttData)
-            this.publish()
+            // 发送控制命令
+            MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
             this.workStatus = 1
           })
           // 一键停工
@@ -530,8 +513,8 @@ export struct WorkshopView {
             let mqttData: MqttCmdData = {
               w: [item]
             }
-            this.payload = JSON.stringify(mqttData)
-            this.publish()
+            // 发送控制命令
+            MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
             this.workStatus = 0
           })
 
@@ -585,294 +568,6 @@ export struct WorkshopView {
     .width('100%')
     .height('100%')
   }
-
-  createClient(): undefined | void {
-    console.log("hhtest", '请求连接');
-    if (this.mqttAsyncClient) {
-      return;
-    }
-    this.mqttAsyncClient = MqttAsync.createMqtt({
-      url: this.url,
-      clientId: this.clientId,
-      persistenceType: 1,
-    });
-    let num = 0
-    while (num < 5) {
-      if (!this.mqttAsyncClient) {
-        this.mqttAsyncClient = MqttAsync.createMqtt({
-          url: this.url,
-          clientId: this.clientId,
-          persistenceType: 1,
-        });
-      }
-      num++
-    }
-    if (!this.mqttAsyncClient) {
-      console.log("hhtest", '创建失败');
-      return;
-    }
-    this.messageArrived()
-    this.connectLost()
-    this.mqttAsyncClient.setMqttTrace(6);
-    // // this.showLog("create client success");
-  }
-
-  async connect(): Promise<undefined | void> {
-    console.info('hhtest', "connect");
-    // // this.showLog("connect");
-    let options: MqttConnectOptions = {
-      userName: this.userName,
-      password: this.password,
-      cleanSession:false,
-      connectTimeout: 300
-    };
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.connect(options).then((data: MqttResponse) => {
-          console.info('hhtest', "connect result:" + JSON.stringify(data));
-          this.connectedCount++;
-        }).catch((data: MqttResponse) => {
-          console.info('hhtest', "connect fail result:" + JSON.stringify(data));
-        })
-      } else {
-        this.mqttAsyncClient.connect(options, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "connect result:" + JSON.stringify(data));
-            if (data.message == "Connect Success") {
-              console.info('hhtest', "connect result connectedCount:");
-              this.connectedCount++;
-            }
-          } else {
-            console.info('hhtest', "connect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async publish(): Promise<undefined | void> {
-    console.info('hhtest', "publish");
-    let publishOption: MqttPublishOptions = {
-      topic: this.publishTopic,
-      qos: 1,
-      payload: this.payload
-    }
-    console.log('hhtest', 'publish msg:----------' + JSON.stringify(this.payload))
-    console.log('hhtest', 'publish msg:----------' + JSON.stringify(publishOption))
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.publish(publishOption).then((data: MqttResponse) => {
-          console.info('hhtest', "publish success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "publish fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.publish(publishOption, (err: Error, data: MqttResponse) => {
-          console.info('hhtest', "publish response:");
-          if (!err) {
-            console.info('hhtest', "publish result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "publish error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async subscribe(): Promise<undefined | void> {
-    console.info('hhtest', "subscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      console.info('hhtest', "client not created");
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.subscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "subscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "subscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.subscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  messageArrived(): undefined | void {
-    console.info('hhtest', "messageArrived");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.messageArrived((err: Error, data: MqttMessage) => {
-      if (!err) {
-        // this.showLog(msg);
-        let dataStr = JSON.stringify(data);
-        console.info('hhtest', "messageArrived message:" + dataStr);
-        if (dataStr.indexOf('Assemble_500W') !== -1) {
-          return
-        }
-        let updateData: MqttUploadData = JSON.parse(data.payload) as MqttUploadData;
-        if (!updateData || !updateData.d || updateData.d.length <= 0) {
-          console.info('hhtest', "updateData没有解析成功" + JSON.stringify(updateData));
-          return
-        }
-
-        let device0: TempHumiditySensor = { Temperature: 0, Humidity: 0, OnlineStatus: 0 }
-        let collectFlag: Array<boolean> = [false]
-
-        for (const element of updateData.d) {
-          if (BusinessConstant.attrMap.has(element.tag)) {
-            let deviceType: string = BusinessConstant.attrMap.get(element.tag) ?? '';
-            switch (deviceType) {
-              case DeviceType.TempHumiditySensor:
-                collectFlag[0] = true
-                if (element.tag! === 'Temperature') {
-                  device0.Temperature = element.value
-                } else if (element.tag! === 'Humidity') {
-                  device0.Humidity = element.value
-                }
-                device0.OnlineStatus = 1
-                break;
-            }
-          }
-        }
-        if (collectFlag[0]) {
-          this.tempHumiditySensor = device0;
-        } else {
-          this.tempHumiditySensor = {
-            OnlineStatus: 0
-          }
-        }
-        console.info('hhtest', "this.tempHumiditySensor" + JSON.stringify(this.tempHumiditySensor));
-      } else {
-        console.info('hhtest', "messageArrived error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async unsubscribe(): Promise<undefined | void> {
-    console.info('hhtest', "unsubscribe");
-    let subscribeOption: MqttSubscribeOptions = {
-      topic: this.subscribeTopic,
-      qos: 2
-    }
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.unsubscribe(subscribeOption).then((data: MqttResponse) => {
-          console.info('hhtest', "unsubscribe success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "unsubscribe fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.unsubscribe(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "unsubscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "unsubscribe error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async disconnect(): Promise<undefined | void> {
-    console.info('hhtest', "disconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (await this.isConnected()) {
-      if (this.isPromise) {
-        this.mqttAsyncClient.disconnect().then((data: MqttResponse) => {
-          console.info('hhtest', "disconnect success result:" + JSON.stringify(data));
-        }).catch((err: MqttResponse) => {
-          console.info('hhtest', "disconnect fail result:" + JSON.stringify(err));
-        })
-      } else {
-        this.mqttAsyncClient.disconnect((err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "disconnect result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "disconnect error:" + JSON.stringify(err));
-          }
-        });
-      }
-    }
-  }
-
-  async isConnected(): Promise<undefined | boolean> {
-    console.info('hhtest', "isConnected");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    return this.mqttAsyncClient.isConnected().then((data: boolean) => {
-      console.info('hhtest', "isConnected result:" + data);
-      if (!data) {
-      }
-      return data;
-    })
-  }
-
-  async reconnect(): Promise<undefined | void> {
-    console.info('hhtest', "reconnect");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    if (!(await this.isConnected())) {
-      if (this.connectedCount == 0) {
-        console.info('hhtest', "reconnect: client previously not connected");
-        return;
-      }
-      this.mqttAsyncClient.reconnect().then((data: boolean) => {
-        console.info('hhtest', "reConnected result:" + data);
-      });
-    }
-  }
-
-  connectLost(): undefined | void {
-    console.info('hhtest', "connectLost");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.connectLost((err: Error, data: MqttResponse) => {
-      if (!err) {
-        this.reconnect();
-        console.info('hhtest', "connect lost cause:" + JSON.stringify(data));
-      } else {
-        console.info('hhtest', "connect lost error:" + JSON.stringify(err));
-      }
-    });
-  }
-
-  async destroy(): Promise<undefined | void> {
-    console.info('hhtest', "destroy");
-    if (this.mqttAsyncClient == null) {
-      return;
-    }
-    this.mqttAsyncClient.destroy().then((data: boolean) => {
-      console.info('hhtest', "destroy result:" + data);
-      this.mqttAsyncClient = null;
-      this.connectedCount = 0;
-    });
-  }
 }
 
 class DeviceInfo {