Kaynağa Gözat

修改mqtt;

hh 2 hafta önce
ebeveyn
işleme
fcce1ba888

+ 1 - 5
entry/src/main/ets/common/constants/BusinessConstant.ets

@@ -1,13 +1,9 @@
-import HashMap from '@ohos.util.HashMap';
-
-export default class BusinessConstant {
+export default class CommonConstants {
 
   static readonly  mqttSubscribeTopic: string = 'station100/data/devices';
   static readonly  mqttSubscribeTopic2: string = 'station11/data/devices';
   static readonly  mqttPublishTopic: string = 'station100/cmd/devices';
   static readonly  mqttUrl: string = 'tcp://192.168.1.3';
-  // 每个clientId不重复
-  static readonly  mqttClientId: string = 'station100' + Date.now().toString(36);
   static readonly  mqttUserName: string = '';
   static readonly  mqttPassword: string = '';
 

+ 378 - 0
entry/src/main/ets/common/util/Mqtt.ets

@@ -0,0 +1,378 @@
+import { MqttAsync, MqttClient, MqttClientOptions, MqttConnectOptions,MqttQos, MqttMessage, MqttPublishOptions } from '@ohos/mqtt';
+import TempHumiditySensor from '../../viewmodel/device/TempHumiditySensor';
+import RobotInfo from '../../viewmodel/RobotInfo';
+import StationControl from '../../viewmodel/StationControl';
+import CommonConstants, { DeviceType } from '../constants/CommonConstants';
+
+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();
+  // 工位控制
+  stationArray: StationControl[] = [
+    {stationName: "装调工位1",
+      onlineStatus: 0,
+      stationType: 1,
+      controlPowerStatus: 1,
+      devicePowerStatus: 1
+    },
+    {stationName: "装调工位2",
+      onlineStatus: 0,
+      stationType: 1,
+      controlPowerStatus: 1,
+      devicePowerStatus: 1
+    },
+    {stationName: "出入库工位",
+      onlineStatus: 0,
+      stationType: 1,
+      controlPowerStatus: 1,
+      devicePowerStatus: 1
+    },
+    {stationName: "检验工位",
+      onlineStatus: 0,
+      stationType: 1,
+      controlPowerStatus: 1,
+      devicePowerStatus: 1
+    },
+    {stationName: "包装工位",
+      onlineStatus: 0,
+      stationType: 1,
+      controlPowerStatus: 1,
+      devicePowerStatus: 1
+    },
+    {stationName: "仓储充电位1",
+      onlineStatus: 0,
+      stationType: 2,
+      controlPowerStatus: 0,
+      devicePowerStatus: 1
+    },
+    {stationName: "仓储充电位2",
+      onlineStatus: 0,
+      stationType: 2,
+      controlPowerStatus: 0,
+      devicePowerStatus: 1
+    }
+  ]
+
+  robotArray: RobotInfo[] = [
+    {robotName: 'rgv1'},
+  ]
+  lightControlArray: number[] = [1, 1, 1]
+
+  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 async handleMessage(message: MqttMessage): Promise<void> {
+    const topic = message.topic;
+    let payload = message.payload.toString();
+    const topicCallbacks = this.callbacks.get(topic) || [];
+    topicCallbacks.forEach(cb => cb(topic, payload));
+    try {
+      let index = payload.lastIndexOf(',"ts"');
+      if (index >= 0) {
+        payload = payload.slice(0, index) + '}';
+      }
+      let updateData: MQTTReceiveData = JSON.parse(payload);
+      if (!updateData || !updateData.d || updateData.d.length <= 0) {
+        console.info('hhtest', "updateData没有解析成功" + JSON.stringify(updateData));
+        return
+      }
+      let updateStationFlag: boolean = false
+      if (topic === CommonConstants.mqttSubscribeTopic) {
+        updateStationFlag = true
+      }
+
+      let device0: TempHumiditySensor =  { Temperature: 0, Humidity: 0, OnlineStatus: 0 };
+      let device1: StationControl = JSON.parse(JSON.stringify(this.stationArray[0]));
+      let device2: StationControl = JSON.parse(JSON.stringify(this.stationArray[1]));
+      let device3: StationControl = JSON.parse(JSON.stringify(this.stationArray[2]));
+      let device4: StationControl = JSON.parse(JSON.stringify(this.stationArray[3]));
+      let device5: StationControl = JSON.parse(JSON.stringify(this.stationArray[4]));
+      let device6: StationControl = JSON.parse(JSON.stringify(this.stationArray[5]));
+      let device7: StationControl = JSON.parse(JSON.stringify(this.stationArray[6]));
+      let device8: RobotInfo = JSON.parse(JSON.stringify(this.robotArray[0]));
+      device0.OnlineStatus = 0
+      device1.onlineStatus = 0
+      device2.onlineStatus = 0
+      device3.onlineStatus = 0
+      device4.onlineStatus = 0
+      device5.onlineStatus = 0
+      device6.onlineStatus = 0
+      device7.onlineStatus = 0
+      device8.onlineStatus = 0
+      let onlineNum: number = 0
+      for (const element of updateData.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;
+            case DeviceType.PlcControl:
+              if (element.tag! === 'LED1Control') {
+                this.lightControlArray[0] = element.value!
+              } else if (element.tag! === 'LED2Control') {
+                this.lightControlArray[1] = element.value!
+              } else if (element.tag! === 'LED3Control') {
+                this.lightControlArray[2] = element.value!
+              } else if (CommonConstants.stationLightMap.get('装调工位1')?.indexOf(element.tag!)! >= 0) {
+                device1.onlineStatus = 1
+                if (element.tag! === CommonConstants.stationLightMap.get('装调工位1')![0]) {
+                  device1.controlPowerStatus = element.value
+                } else {
+                  device1.devicePowerStatus = element.value
+                }
+                onlineNum++
+              } else if (CommonConstants.stationLightMap.get('装调工位2')?.indexOf(element.tag!)! >= 0) {
+                device2.onlineStatus = 1
+                if (element.tag! === CommonConstants.stationLightMap.get('装调工位2')![0]) {
+                  device2.controlPowerStatus = element.value
+                } else {
+                  device2.devicePowerStatus = element.value
+                }
+                onlineNum++
+              } else if (CommonConstants.stationLightMap.get('出入库工位')?.indexOf(element.tag!)! >= 0) {
+                device3.onlineStatus = 1
+                if (element.tag! === CommonConstants.stationLightMap.get('出入库工位')![0]) {
+                  device3.controlPowerStatus = element.value
+                } else {
+                  device3.devicePowerStatus = element.value
+                }
+                onlineNum++
+              } else if (CommonConstants.stationLightMap.get('检验工位')?.indexOf(element.tag!)! >= 0) {
+                device4.onlineStatus = 1
+                if (element.tag! === CommonConstants.stationLightMap.get('检验工位')![0]) {
+                  device4.controlPowerStatus = element.value
+                } else {
+                  device4.devicePowerStatus = element.value
+                }
+                onlineNum++
+              } else if (CommonConstants.stationLightMap.get('包装工位')?.indexOf(element.tag!)! >= 0) {
+                device5.onlineStatus = 1
+                if (element.tag! === CommonConstants.stationLightMap.get('包装工位')![0]) {
+                  device5.controlPowerStatus = element.value
+                } else {
+                  device5.devicePowerStatus = element.value
+                }
+                onlineNum++
+              } else if (element.tag! === 'Charging1Set') {
+                device6.onlineStatus = 1
+                device6.controlPowerStatus = element.value
+                onlineNum++
+              } else if (element.tag! === 'Charging2Set') {
+                device7.onlineStatus = 1
+                device7.controlPowerStatus = element.value
+                onlineNum++
+              }
+              break;
+            case DeviceType.RGV1:
+              if (element.tag! === 'Rgv1CurrBatlevel') {
+                device8.batteryLevel = element.value
+              } else if (element.tag! === 'Rgv1CurrStatus') {
+                device8.onlineStatus = (element.value === 6 || element.value === 7) ? 0 : 1
+              }
+              break;
+          }
+        }
+      }
+
+      if (updateStationFlag) {
+        AppStorage.setOrCreate<StationControl[]>('stationArray', [device1, device2, device3, device4, device5, device6, device7]);
+        AppStorage.setOrCreate<RobotInfo[]>('robotArray', [device8]);
+        AppStorage.setOrCreate<number[]>('lightControlArray', this.lightControlArray);
+        AppStorage.setOrCreate<number>('onlineNum', onlineNum);
+        AppStorage.setOrCreate<number>('offlineNum', this.stationArray.length! - onlineNum > 0 ? this.stationArray.length - onlineNum : 0);
+      } else {
+        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('');
+}

+ 1 - 1
entry/src/main/ets/entryability/EntryAbility.ets

@@ -40,7 +40,7 @@ export default class EntryAbility extends UIAbility {
       windowClass.setWindowLayoutFullScreen(true)
     })
 
-    windowStage.loadContent('pages/Index', (err) => {
+    windowStage.loadContent('pages/WorkshopPage', (err) => {
       if (err.code) {
         hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
         return;

+ 64 - 475
entry/src/main/ets/pages/Index.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 {
   MqttAsync,
   MqttConnectOptions,
@@ -8,36 +8,24 @@ import {
   MqttResponse,
   MqttMessage,
   MqttClient,
+  MqttClientOptions,
 } from '@ohos/mqtt';
 import TimeUtil from '../common/util/TimeUtil'
 import TempHumiditySensor from '../viewmodel/device/TempHumiditySensor';
 import MqttDataItem from '../viewmodel/mqtt/MqttDataItem';
 import MqttCmdData from '../viewmodel/mqtt/MqttCmdData';
 import MqttUploadData from '../viewmodel/mqtt/MqttUploadData';
-import { deepCopy } from '@mcui/mccharts/src/main/ets/utils';
+import RobotInfo from '../viewmodel/RobotInfo';
+import StationControl from '../viewmodel/StationControl';
+import MqttManager from '../common/util/mqtt';
 
 @Entry
 @Component
 struct WorkshopPage {
-
-  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 tempHumiditySensor: TempHumiditySensor = {}
+  @StorageProp('tempHumiditySensor') tempHumiditySensor: TempHumiditySensor = {}
 
   // 工位控制
-  @State stationArray: StationControl[] = [
+  @StorageProp('stationArray') stationArray: StationControl[] = [
     {stationName: "装调工位1",
       onlineStatus: 0,
       stationType: 1,
@@ -82,17 +70,19 @@ struct WorkshopPage {
     }
   ]
   // 机器人信息
-  @State robotArray: RobotInfo[] = [
+  @StorageProp('robotArray') robotArray: RobotInfo[] = [
     {robotName: 'rgv1'},
   ]
   // 在线数
-  @State onlineNum:number = 0
+  @StorageProp('onlineNum') onlineNum: number = 0
   // 离线数
-  @State offlineNum:number = 0
+  @StorageProp('offlineNum') offlineNum: number = 0
   // 工作状态(1:开工 0:停工)
   // @State workStatus:number = 1
   // 三个区域的灯光控制(1关 2开)
-  @State lightControlArray: number[] = [1, 1, 1]
+  @StorageProp('lightControlArray') lightControlArray: number[] = [1, 1, 1]
+
+  @State isConnected: boolean = false
 
   @State defOption: Options = new Options({
     legend: {
@@ -133,26 +123,53 @@ struct WorkshopPage {
   // 切换类型(1:电源控制 2:设备控制)
   toggleType: number = 1
 
+  connectMQTT = async ()=> {
+    const clientOptions: MqttClientOptions = {
+      url: CommonConstants.mqttUrl,   // 替换实际IP
+      clientId: `station_${Date.now()}`,
+      persistenceType: 1,              // 使用英文逗号       // 建议开启自动重连
+    };
+    // MQTT连接配置
+    const connectOptions: MqttConnectOptions = {
+      cleanSession: true,
+      connectTimeout: 30,
+      keepAliveInterval: 60,
+      userName: CommonConstants.mqttUserName,
+      password: CommonConstants.mqttPassword
+    };
+    try {
+      MqttManager.init(clientOptions);
+      this.isConnected = await MqttManager.connect(connectOptions);
+      if (this.isConnected ) {
+        console.info('hhtest', 'MQTT connected successfully');
+        await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic);
+        await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic2);
+      } else {
+        console.error('hhtest', 'MQTT connection failed');
+      }
+    } catch (err) {
+      console.error('hhtest', `MQTT error: ${JSON.stringify(err)}`);
+    }
+  }
+
   async onPageShow() {
     this.onlineNum = 0;
     this.offlineNum = this.stationArray.length;
-    try {
-      setTimeout(async ()=>{
-        await this.createClient();
-        await this.connect();
-        await this.subscribe();
-      }, 20000);
-    } catch (e) {
-      console.log('hhtest', '创建mqtt失败' + e);
-    }
-    try {
-      setTimeout(async ()=>{
-        this.issueControlCommand('Charging1Set', 1)
-        this.issueControlCommand('Charging2Set', 1)
-      }, 30000);
-    } catch (e) {
-      console.log('hhtest', '创建mqtt失败' + e);
-    }
+    const checkInterval = setInterval(() => {
+      if (this.isConnected) {
+        clearInterval(checkInterval); // 停止轮询
+        return
+      }
+      this.connectMQTT()
+      try {
+        setTimeout(async ()=>{
+          this.issueControlCommand('Charging1Set', 1)
+          this.issueControlCommand('Charging2Set', 1)
+        }, 1000);
+      } catch (e) {
+        console.log('hhtest', '创建mqtt失败' + e);
+      }
+    }, 2000);
   }
 
   // 照明控制弹窗控制器
@@ -223,7 +240,7 @@ struct WorkshopPage {
       confirm: ()=> {
         // this.workStatus = 0
         let times = 0
-        BusinessConstant.stationLightMap.forEach((value, key) => {
+        CommonConstants.stationLightMap.forEach((value, key) => {
           if (value && value.length === 2) {
             setTimeout(()=>{
               this.issueControlCommand(value[0], 1)
@@ -272,7 +289,7 @@ struct WorkshopPage {
           this.issueControlCommand('LED3Control', 0)
         }, times * 1000);
         times++;
-        BusinessConstant.stationLightMap.forEach((value, key) => {
+        CommonConstants.stationLightMap.forEach((value, key) => {
           if (value && value.length === 2) {
             setTimeout(()=>{
               this.issueControlCommand(value[0], 0)
@@ -303,7 +320,7 @@ struct WorkshopPage {
       confirm: ()=> {
         console.log('hhtest', JSON.stringify(this.clickStation))
         console.log('hhtest', JSON.stringify(this.toggleType))
-        let controlStr = BusinessConstant.stationLightMap.get(this.clickStation.stationName!);
+        let controlStr = CommonConstants.stationLightMap.get(this.clickStation.stationName!);
         if (this.toggleType === 1) {
           if (controlStr && controlStr.length > 0) {
             this.issueControlCommand(controlStr[0], this.clickStation.controlPowerStatus! === 1 ? 0 : 1);
@@ -321,7 +338,6 @@ struct WorkshopPage {
     customStyle: true,
   })
 
-
   build() {
     Column() {
       // 顶部状态栏
@@ -698,412 +714,6 @@ struct WorkshopPage {
     .backgroundColor($r('app.color.000000'))
   }
 
-  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);
-    console.log("hhtest", '创建成功::' + this.mqttAsyncClient);
-    // 创建第二个mqtt
-    // this.mqttAsyncClient2 = MqttAsync.createMqtt({
-    //   url: this.url,
-    //   clientId: this.clientId,
-    //   persistenceType: 1,
-    // });
-    // num = 0
-    // while (num < 5) {
-    //   if (!this.mqttAsyncClient) {
-    //     this.mqttAsyncClient2 = 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);
-
-  }
-
-  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
-    }
-    let subscribeOption2: MqttSubscribeOptions = {
-      topic: this.subscribeTopic2,
-      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));
-        })
-        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(subscribeOption, (err: Error, data: MqttResponse) => {
-          if (!err) {
-            console.info('hhtest', "subscribe result:" + JSON.stringify(data));
-          } else {
-            console.info('hhtest', "subscribe error:" + JSON.stringify(err));
-          }
-        });
-        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));
-        })
-      }
-    }
-  }
-
-  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);
-        let payload = data.payload;
-        let index = payload.lastIndexOf(',"ts"');
-        if (index >= 0) {
-          payload = payload.slice(0, index) + '}';
-        }
-        // console.log('hhtest', 'messageArrived: ' + payload);
-        let updateData: MqttUploadData = JSON.parse(payload) as MqttUploadData;
-        if (!updateData || !updateData.d || updateData.d.length <= 0) {
-          console.info('hhtest', "updateData没有解析成功" + JSON.stringify(updateData));
-          return
-        }
-        let updateStationFlag: boolean = false
-        if (dataStr.indexOf(this.subscribeTopic) >= 0) {
-          updateStationFlag = true
-        }
-
-        let device0: TempHumiditySensor = JSON.parse(JSON.stringify(this.tempHumiditySensor));
-        let device1: StationControl = JSON.parse(JSON.stringify(this.stationArray[0]));
-        let device2: StationControl = JSON.parse(JSON.stringify(this.stationArray[1]));
-        let device3: StationControl = JSON.parse(JSON.stringify(this.stationArray[2]));
-        let device4: StationControl = JSON.parse(JSON.stringify(this.stationArray[3]));
-        let device5: StationControl = JSON.parse(JSON.stringify(this.stationArray[4]));
-        let device6: StationControl = JSON.parse(JSON.stringify(this.stationArray[5]));
-        let device7: StationControl = JSON.parse(JSON.stringify(this.stationArray[6]));
-        let device8: RobotInfo = JSON.parse(JSON.stringify(this.robotArray[0]));
-        device0.OnlineStatus = 0
-        device1.onlineStatus = 0
-        device2.onlineStatus = 0
-        device3.onlineStatus = 0
-        device4.onlineStatus = 0
-        device5.onlineStatus = 0
-        device6.onlineStatus = 0
-        device7.onlineStatus = 0
-        device8.onlineStatus = 0
-        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:
-                if (element.tag! === 'Temperature') {
-                  device0.Temperature = element.value
-                } else if (element.tag! === 'Humidity') {
-                  device0.Humidity = element.value
-                }
-                device0.OnlineStatus = 1
-                break;
-              case DeviceType.PlcControl:
-                if (element.tag! === 'LED1Control') {
-                  this.lightControlArray[0] = element.value!
-                } else if (element.tag! === 'LED2Control') {
-                  this.lightControlArray[1] = element.value!
-                } else if (element.tag! === 'LED3Control') {
-                  this.lightControlArray[2] = element.value!
-                } else if (BusinessConstant.stationLightMap.get('装调工位1')?.indexOf(element.tag!)! >= 0) {
-                  device1.onlineStatus = 1
-                  if (element.tag! === BusinessConstant.stationLightMap.get('装调工位1')![0]) {
-                    device1.controlPowerStatus = element.value
-                  } else {
-                    device1.devicePowerStatus = element.value
-                  }
-                } else if (BusinessConstant.stationLightMap.get('装调工位2')?.indexOf(element.tag!)! >= 0) {
-                  device2.onlineStatus = 1
-                  if (element.tag! === BusinessConstant.stationLightMap.get('装调工位2')![0]) {
-                    device2.controlPowerStatus = element.value
-                  } else {
-                    device2.devicePowerStatus = element.value
-                  }
-                } else if (BusinessConstant.stationLightMap.get('出入库工位')?.indexOf(element.tag!)! >= 0) {
-                  device3.onlineStatus = 1
-                  if (element.tag! === BusinessConstant.stationLightMap.get('出入库工位')![0]) {
-                    device3.controlPowerStatus = element.value
-                  } else {
-                    device3.devicePowerStatus = element.value
-                  }
-                } else if (BusinessConstant.stationLightMap.get('检验工位')?.indexOf(element.tag!)! >= 0) {
-                  device4.onlineStatus = 1
-                  if (element.tag! === BusinessConstant.stationLightMap.get('检验工位')![0]) {
-                    device4.controlPowerStatus = element.value
-                  } else {
-                    device4.devicePowerStatus = element.value
-                  }
-                } else if (BusinessConstant.stationLightMap.get('包装工位')?.indexOf(element.tag!)! >= 0) {
-                  device5.onlineStatus = 1
-                  if (element.tag! === BusinessConstant.stationLightMap.get('包装工位')![0]) {
-                    device5.controlPowerStatus = element.value
-                  } else {
-                    device5.devicePowerStatus = element.value
-                  }
-                } else if (element.tag! === 'Charging1Set') {
-                  device6.onlineStatus = 1
-                  device6.controlPowerStatus = element.value
-                } else if (element.tag! === 'Charging2Set') {
-                  device7.onlineStatus = 1
-                  device7.controlPowerStatus = element.value
-                }
-                break;
-              case DeviceType.RGV1:
-                if (element.tag! === 'Rgv1CurrBatlevel') {
-                  device8.batteryLevel = element.value
-                } else if (element.tag! === 'Rgv1CurrStatus') {
-                  device8.onlineStatus = (element.value === 6 || element.value === 7) ? 0 : 1
-                }
-                break;
-            }
-          }
-        }
-
-        this.tempHumiditySensor = device0;
-        if (updateStationFlag) {
-          this.stationArray[0] = device1;
-          this.stationArray[1] = device2;
-          this.stationArray[2] = device3;
-          this.stationArray[3] = device4;
-          this.stationArray[4] = device5;
-          this.stationArray[5] = device6;
-          this.stationArray[6] = device7;
-          this.robotArray[0] = device8
-        }
-      } 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;
-    });
-  }
-
   private issueControlCommand(tag: string, value: number) {
     let item: MqttDataItem = {
       tag: tag,
@@ -1112,9 +722,8 @@ struct WorkshopPage {
     let mqttData: MqttCmdData = {
       w: [item]
     };
-    this.payload = JSON.stringify(mqttData);
-    console.log('hhtest', TimeUtil.getCurrentTime() + '------' + JSON.stringify(this.payload))
-    this.publish();
+    console.log('hhtest', TimeUtil.getCurrentTime() + '------' + JSON.stringify(mqttData))
+    MqttManager.publish(CommonConstants.mqttPublishTopic, JSON.stringify(mqttData));
   }
 }
 
@@ -1519,26 +1128,6 @@ struct confirmDialog {
   }
 }
 
-// 工位控制
-class StationControl {
-  // 设备名称
-  stationName?: string
-  // 在线状态(1:在线 0:离线)
-  onlineStatus?: number
-  // 1双路控制 2单路控制
-  stationType?: number
-  // 控制电源状态(0:开 1:关)
-  controlPowerStatus?: number
-  // 设备电源状态(0:开 1:关)
-  devicePowerStatus?: number
-}
 
-// 机器人信息
-class RobotInfo {
-  // 机器人名称
-  robotName?: string
-  // 电量(百分比)
-  batteryLevel?: number
-  // 在线状态(1:在线 0:离线)
-  onlineStatus?: number
-}
+
+

+ 9 - 0
entry/src/main/ets/viewmodel/RobotInfo.ets

@@ -0,0 +1,9 @@
+// 机器人信息
+export default class RobotInfo {
+  // 机器人名称
+  robotName?: string
+  // 电量(百分比)
+  batteryLevel?: number
+  // 在线状态(1:在线 0:离线)
+  onlineStatus?: number
+}

+ 13 - 0
entry/src/main/ets/viewmodel/StationControl.ets

@@ -0,0 +1,13 @@
+// 工位控制
+export default class StationControl {
+  // 设备名称
+  stationName?: string
+  // 在线状态(1:在线 0:离线)
+  onlineStatus?: number
+  // 1双路控制 2单路控制
+  stationType?: number
+  // 控制电源状态(0:开 1:关)
+  controlPowerStatus?: number
+  // 设备电源状态(0:开 1:关)
+  devicePowerStatus?: number
+}

+ 1 - 1
entry/src/main/resources/base/profile/main_pages.json

@@ -1,5 +1,5 @@
 {
   "src": [
-    "pages/Index"
+    "pages/WorkshopPage"
   ]
 }