Przeglądaj źródła

Signed-off-by: zhaobao <528046418@qq.com>

zhaobao 3 lat temu
rodzic
commit
d5a37e4c43
2 zmienionych plików z 70 dodań i 0 usunięć
  1. 19 0
      src/store/modules/mqtt.ts
  2. 51 0
      src/utils/mqtt.ts

+ 19 - 0
src/store/modules/mqtt.ts

@@ -0,0 +1,19 @@
+const useMqttStore = defineStore(
+  // 唯一ID
+  'mqtt',
+  () => {
+    // 消息
+    const message = ref()
+    // 获取mqtt消息
+    function setMqttMessage(topic: any, messageInfo: any) {
+      message.value[topic] = messageInfo
+    }
+
+    return {
+      message,
+      setMqttMessage,
+    }
+  },
+)
+
+export default useMqttStore

+ 51 - 0
src/utils/mqtt.ts

@@ -0,0 +1,51 @@
+import * as mqtt from 'mqtt/dist/mqtt.min'
+import type { App } from 'vue'
+import mqttUseStore from '@/store/modules/mqtt'
+const mqttStore = mqttUseStore()
+export function initMqtt(app: App<Element>) {
+  const options = {
+    clean: true,
+    connectTimeout: 4000,
+    clientId: new Date().getTime(),
+    username: 'admin',
+    password: 'houyaf1!',
+  }
+  const client = mqtt.connect('ws://1.15.92.205:8083/mqtt', options)
+  client.on('connect', () => {
+    client.subscribe('topic/goaf/waring/person', (err: any) => {
+      if (!err) {
+        client.publish('topic/goaf/waring/person', 'Hello mqtt')
+      }
+      else {
+        client.publish('topic/goaf/waring/person', 'Hello mqtt err')
+      }
+    })
+    client.subscribe('topic/goaf/waring/sensor', (err: any) => {
+      if (!err) {
+        client.publish('topic/goaf/waring/sensor', 'Hello mqtt')
+      }
+      else {
+        client.publish('topic/goaf/waring/sensor', 'Hello mqtt err')
+      }
+    })
+  })
+  client.on('message', (topic: any, message: any) => {
+    const messageInfo = {
+      message,
+      time: new Date().getTime(),
+    }
+    mqttStore.setMqttMessage(topic, messageInfo)
+  })
+  if (app) {
+    app.config.globalProperties.$mqtt = client
+  }
+}
+
+export function mqttWatch(topic: string | number, callback: (arg0: any) => void) {
+  if (!topic) {
+    return
+  }
+  watch(() => mqttStore.message.value[topic], (val) => {
+    callback(val)
+  })
+}