Browse Source

mqtt修改

huhao@jgai.com 6 ngày trước cách đây
mục cha
commit
698fc528f1

+ 3 - 5
product/phone/src/main/ets/common/constants/CommonConstants.ets

@@ -66,14 +66,12 @@ export default class CommonConstants {
   ]
 
   static readonly ipPrefix: string = '192.168.1.'
-  static readonly mqttSubscribeTopic1: string = 'station11/data/devices';
+  static 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';
+  static mqttSubscribePublish: string = 'station11/cmd/devices';
+  static readonly mqttUrl: string = 'tcp://192.168.1.3:1883';
   // 默认随机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 = '';
   // 电烙铁允许最大、最小温度

+ 4 - 2
product/phone/src/main/ets/common/util/Mqtt.ets

@@ -189,7 +189,9 @@ class MqttManager {
           AppStorage.setOrCreate<AntiWristStrap>('AntiWristStrap', device4);
           AppStorage.setOrCreate<CardReader>('CardReader', device5);
           AppStorage.setOrCreate<Lighting>('Lighting', device6)
-          AppStorage.setOrCreate<TempHumiditySensor>('TempHumiditySensor', device7)
+          if (CommonConstants.mqttSubscribeTopic1 === CommonConstants.mqttSubscribeTopic2) {
+            AppStorage.setOrCreate<TempHumiditySensor>('TempHumiditySensor', device7)
+          }
           AppStorage.setOrCreate<number>('onlineDeviceNum', onlineDeviceNum)
         }
       } else if (CommonConstants.mqttSubscribeTopic2 == topic) {
@@ -229,7 +231,7 @@ class MqttManager {
       console.error(TAG, `Connect failed: ${res.message}`);
       return false;
     } catch (err) {
-      console.error(TAG, `Connect error: ${err.message}`);
+      console.error(TAG, `Connect error: ` + JSON.stringify(err));
       return false;
     }
   }

+ 3 - 3
product/phone/src/main/ets/model/ElectricScrewdriverPresetModel.ets

@@ -41,14 +41,14 @@ class ElectricScrewdriverPresetModel {
     // 3.获取rdb
     relationalStore.getRdbStore(context, config, (err, rdbStore) => {
       if(err){
-        console.log('testTag', '获取rdbStore失败!')
+        console.log('hhtest', '获取rdbStore失败!')
         return
       }
       // 执行Sql
       rdbStore.executeSql(sql).then(()=>{
-        console.log('testTag', '创建电动螺丝刀预设表成功!')
+        console.log('hhtest', '创建电动螺丝刀预设表成功!')
       }).catch((err: object)=>{
-        console.log('testTag', '创建失败')
+        console.log('hhtest', '创建失败')
       })
       // 保存rdbStore
       this.rdbStore = rdbStore

+ 3 - 3
product/phone/src/main/ets/model/ElectricSolderingIronPresetModel.ets

@@ -35,14 +35,14 @@ class ElectricSolderingIronPresetModel {
     // 3.获取rdb
     relationalStore.getRdbStore(context, config, (err, rdbStore) => {
       if(err){
-        console.log('testTag', '获取rdbStore失败!')
+        console.log('hhtest', '获取rdbStore失败!')
         return
       }
       // 执行Sql
       rdbStore.executeSql(sql).then(()=>{
-        console.log('testTag', '创建电烙铁预设表成功!')
+        console.log('hhtest', '创建电烙铁预设表成功!')
       }).catch((err: object)=>{
-        console.log('testTag', '创建失败')
+        console.log('hhtest', '创建失败')
       })
       // 保存rdbStore
       this.rdbStore = rdbStore

+ 87 - 1
product/phone/src/main/ets/pages/EntryView.ets

@@ -40,6 +40,22 @@ import { DeviceView } from '../view/DeviceView';
 
 import common from '@ohos.app.ability.common';
 import { WorkshopView } from '../view/WorkshopView';
+import CommonConstants2 from '../common/constants/CommonConstants'
+import {
+  MqttAsync,
+  MqttConnectOptions,
+  MqttSubscribeOptions,
+  MqttPublishOptions,
+  MqttResponse,
+  MqttMessage,
+  MqttClient,
+  MqttClientOptions,
+} from '@ohos/mqtt';
+import MqttManager from '../common/util/mqtt';
+import MqttUploadData from '../viewmodel/mqtt/MqttUploadData'
+import ElectricScrewdriverPresetModel from '../model/ElectricScrewdriverPresetModel';
+import ElectricSolderingIronPresetModel from '../model/ElectricSolderingIronPresetModel';
+import connection from '@ohos.net.connection';
 
 const TAG = "EntryView";
 
@@ -69,6 +85,10 @@ struct EntryView {
 
   @State selectNavbar: number = 1
 
+  // mqtt是否连接
+  @State isConnected: boolean = false
+  @Provide('stationIp') stationIp: string = ''
+
   onPageShow(): void {
     Log.showInfo(TAG, 'onPageShow');
   }
@@ -79,7 +99,7 @@ struct EntryView {
     Log.showInfo(TAG, 'onPageHide');
   }
 
-  aboutToAppear(): void {
+  async aboutToAppear() {
     Log.showInfo(TAG, 'aboutToAppear');
     this.mStage.onCreate();
     this.navigationBarStatus = SettingsModel.getInstance().getValue();
@@ -89,6 +109,38 @@ struct EntryView {
     this.registerPageDesktopNavigatorStatusChangeEvent(this.mLocalEventListener);
     //register orientation listener
     this.mOrientationListener.on('change', this.onPortrait);
+
+    ElectricScrewdriverPresetModel.initTaskDB(getContext())
+    ElectricSolderingIronPresetModel.initTaskDB(getContext())
+    // 获取工位ip
+    this.stationIp = CommonConstants2.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
+            console.log('hhtest', 'stationIp---------------' + this.stationIp );
+            if (address.address.address.startsWith(CommonConstants2.ipPrefix)) {
+              CommonConstants2.mqttSubscribeTopic1 = 'station' + address.address.address.replace(CommonConstants2.ipPrefix, '') + '/data/devices'
+              CommonConstants2.mqttSubscribePublish = 'station' + address.address.address.replace(CommonConstants2.ipPrefix, '') + '/cmd/devices'
+            }
+          })
+        }
+      }
+    } catch (err) {
+      console.log('hhtest', err);
+    }
+    // 创建mqtt连接和usb设备连接(每两秒检测是否连接成功)
+    const checkInterval = setInterval(() => {
+      console.log('hhtest', 'isConnected:------' + this.isConnected)
+      if (this.isConnected) {
+        clearInterval(checkInterval); // 停止轮询
+        return
+      }
+      this.connectMQTT()
+    }, 1000);
   }
 
   registerPageDesktopNavigatorStatusChangeEvent(listener: LocalEventListener): void {
@@ -119,6 +171,40 @@ struct EntryView {
     }
   };
 
+
+  connectMQTT = async ()=> {
+    const clientOptions: MqttClientOptions = {
+      url: CommonConstants2.mqttUrl,   // 替换实际IP
+      clientId: `station_${Date.now()}`,
+      persistenceType: 1,              // 使用英文逗号       // 建议开启自动重连
+    };
+    // MQTT连接配置
+    const connectOptions: MqttConnectOptions = {
+      cleanSession: true,
+      connectTimeout: 30,
+      keepAliveInterval: 60,
+      userName: CommonConstants2.mqttUserName,
+      password: CommonConstants2.mqttPassword
+    };
+    try {
+      MqttManager.init(clientOptions);
+      this.isConnected = await MqttManager.connect(connectOptions);
+      console.log('hhtest', 'isConnected:------' + this.isConnected)
+      if (this.isConnected) {
+        console.info('hhtest', 'MQTT connected successfully');
+        await MqttManager.subscribe(CommonConstants2.mqttSubscribeTopic1);
+        if (CommonConstants2.mqttSubscribeTopic1 != CommonConstants2.mqttSubscribeTopic2) {
+          await MqttManager.subscribe(CommonConstants2.mqttSubscribeTopic2);
+        }
+      } else {
+        console.error('hhtest', 'MQTT connection failed');
+      }
+    } catch (err) {
+      console.error('hhtest', `MQTT error: ${JSON.stringify(err)}`);
+    }
+  }
+
+
   aboutToDisappear(): void {
     this.mOrientationListener.off('change', this.onPortrait);
     this.mStage.onDestroy();

+ 0 - 59
product/phone/src/main/ets/view/HomeView.ets

@@ -27,77 +27,18 @@ export struct HomeView {
   @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())
-    // 获取工位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)
     this.vehicleStatistics = await MesAioRequest.post("/api/v1/test/vehicleStatistics", {} as RequestParamModel)
     this.processStatistics = await MesAioRequest.post("/api/v1/test/productProcessStatistics", {} as RequestParamModel)
-
   }
 
   build() {