|
@@ -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)
|
|
|
|
|
+ })
|
|
|
|
|
+}
|