Browse Source

优化mqtt

caner 1 year ago
parent
commit
4c46efe120
1 changed files with 11 additions and 8 deletions
  1. 11 8
      src/services/mqtt.service.ts

+ 11 - 8
src/services/mqtt.service.ts

@@ -10,12 +10,14 @@ import useStore from '@/store'
  */
  */
 @injectable
 @injectable
 export default class MqttService extends Service {
 export default class MqttService extends Service {
-  private client_id = 'contrller'
+  private mqtt_id = 'contrller'
 
 
   private client_channel = ''
   private client_channel = ''
 
 
   private store = useStore()
   private store = useStore()
 
 
+  private client_id = ''
+
   constructor() {
   constructor() {
     super()
     super()
     this.onListen()
     this.onListen()
@@ -31,9 +33,10 @@ export default class MqttService extends Service {
   async connect(url: string, room: string, name: string) {
   async connect(url: string, room: string, name: string) {
     if (!url || !name || !room) return null
     if (!url || !name || !room) return null
     const newUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
     const newUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
-    const mqttUrl = `${newUrl}?client_id=${name}-${new Date().getTime()}`
-    if (mqttUrl.startsWith('mqtt://')) return await connect(this.client_id, mqttUrl)
-    return await connect(this.client_id, mqttUrl, { skipVerification: true })
+    this.client_id = `${name}-${new Date().getTime()}`
+    const mqttUrl = `${newUrl}?client_id=${this.client_id}`
+    if (mqttUrl.startsWith('mqtt://')) return await connect(this.mqtt_id, mqttUrl)
+    return await connect(this.mqtt_id, mqttUrl, { skipVerification: true })
   }
   }
 
 
   /**
   /**
@@ -43,9 +46,9 @@ export default class MqttService extends Service {
    * @returns
    * @returns
    */
    */
   async send(params: string, qos = 0) {
   async send(params: string, qos = 0) {
-    console.log('发送', this.client_channel, this.client_id)
-    if (!this.client_channel || !this.client_id) return null
-    return await publish(this.client_id, this.client_channel, qos, false, params)
+    console.log('发送', this.client_channel, this.mqtt_id)
+    if (!this.client_channel || !this.mqtt_id) return null
+    return await publish(this.mqtt_id, this.client_channel, qos, false, params)
   }
   }
 
 
   /**
   /**
@@ -53,7 +56,7 @@ export default class MqttService extends Service {
    */
    */
   async disconnect() {
   async disconnect() {
     this.client_channel = ''
     this.client_channel = ''
-    await disconnect(this.client_id)
+    await disconnect(this.mqtt_id)
   }
   }
 
 
   /**
   /**