caner 1 year ago
parent
commit
d4823a33e9
4 changed files with 87 additions and 24 deletions
  1. 1 0
      package.json
  2. 8 10
      src/pages/login/index.vue
  3. 69 12
      src/services/mqtt.service.ts
  4. 9 2
      src/store/index.ts

+ 1 - 0
package.json

@@ -14,6 +14,7 @@
   "dependencies": {
   "dependencies": {
     "@kuyoonjo/tauri-plugin-mqtt": "^0.1.0",
     "@kuyoonjo/tauri-plugin-mqtt": "^0.1.0",
     "@tauri-apps/api": "^2",
     "@tauri-apps/api": "^2",
+    "buffer": "^6.0.3",
     "naive-ui": "^2.40.1",
     "naive-ui": "^2.40.1",
     "pinia": "^2.2.6",
     "pinia": "^2.2.6",
     "pinia-plugin-persist": "^1.0.0",
     "pinia-plugin-persist": "^1.0.0",

+ 8 - 10
src/pages/login/index.vue

@@ -57,10 +57,12 @@
   </div>
   </div>
 </template>
 </template>
 <script setup lang="ts">
 <script setup lang="ts">
-import { computed, onUnmounted, ref } from 'vue'
-import { connect, disconnect, listen } from '@kuyoonjo/tauri-plugin-mqtt'
+import {
+  computed, onUnmounted, ref, watch
+} from 'vue'
 import topBar from '@/components/topBar.vue'
 import topBar from '@/components/topBar.vue'
 import useStore from '@/store/index'
 import useStore from '@/store/index'
+import MqttService from '@/services/mqtt.service'
 
 
 const err = ref('')
 const err = ref('')
 const name = ref('test123')
 const name = ref('test123')
@@ -68,20 +70,16 @@ const room = ref('test')
 const url = ref('mqtts://caner.top:49659')
 const url = ref('mqtts://caner.top:49659')
 const disabled = computed(() => !name.value || !room.value || !url.value || !url.value.startsWith('mqtts:'))
 const disabled = computed(() => !name.value || !room.value || !url.value || !url.value.startsWith('mqtts:'))
 const store = useStore()
 const store = useStore()
+const mqtt = new MqttService()
 
 
 async function login() {
 async function login() {
   if (disabled.value) return
   if (disabled.value) return
-  const mqttUrl = url.value.replace(/(\/\/)/, `$1${room.value}:${name.value}@`)
-  console.log(123, mqttUrl)
-  const a = await connect(store.mqtt_client_id, mqttUrl, { skipVerification: true })
-  console.log(456, a)
+  await mqtt.connect(url.value, room.value, name.value)
 }
 }
 
 
-listen((client) => {
-  console.log(6666, client.payload, client.payload.event)
+watch(() => store.mqtt_message, (val) => {
+  console.log('监听', val)
 })
 })
-
-onUnmounted(() => disconnect(store.mqtt_client_id))
 </script>
 </script>
 <style scoped lang="scss">
 <style scoped lang="scss">
 .login {
 .login {

+ 69 - 12
src/services/mqtt.service.ts

@@ -1,31 +1,88 @@
-import { connect, disconnect, listen, publish } from '@kuyoonjo/tauri-plugin-mqtt'
+import {
+  connect, disconnect, listen, publish
+} from '@kuyoonjo/tauri-plugin-mqtt'
+import { Buffer } from 'buffer'
 import { injectable, Service } from './service'
 import { injectable, Service } from './service'
-import useStore from '@/store/index'
+import useStore from '@/store'
+
 /**
 /**
  * MQTT服务
  * MQTT服务
  */
  */
 @injectable
 @injectable
 export default class MqttService extends Service {
 export default class MqttService extends Service {
+  private client_id = 'contrller'
+
+  private client_channel = ''
+
   private store = useStore()
   private store = useStore()
 
 
-  async connect(url: string, name: string, room: string) {
+  constructor() {
+    super()
+    this.onListen()
+  }
+
+  /**
+   * 链接mqtt
+   * @param url string
+   * @param name string
+   * @param room string
+   * @returns
+   */
+  async connect(url: string, room: string, name: string) {
+    if (!url || !name || !room) return null
     const mqttUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
     const mqttUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
-    await connect(this.store.mqtt_client_id, mqttUrl)
+    return await connect(this.client_id, mqttUrl, { skipVerification: true })
   }
   }
 
 
-  async send(params: string) {
-    await publish(this.store.mqtt_client_id, this.store.mqtt_channel, 1, false, params)
+  /**
+   * 发送消息
+   * @param params string
+   * @param qos number  0 | 1 | 2
+   * @returns
+   */
+  async send(params: string, qos = 0) {
+    if (!this.client_channel || !this.client_id) return null
+    return await publish(this.client_id, this.client_channel, qos, false, params)
   }
   }
 
 
+  /**
+   * 断开连接
+   */
   async disconnect() {
   async disconnect() {
-    await disconnect(this.store.mqtt_client_id)
+    this.client_channel = ''
+    await disconnect(this.client_id)
   }
   }
 
 
-  async listen(callback: (data: any) => void) {
-    await listen(client => {
-      // if(client.payload)
-      // 如果断开连接,如果有订阅需要取消订阅,然后重新连接
-      callback(client.payload)
+  /**
+   * 监听mqtt消息
+   */
+  private onListen() {
+    listen((client) => {
+      const { event } = client.payload
+      // 连接成功
+      if (event.connect) {
+        console.log('已连接服务器')
+        this.store.setMqttMessage({ type: 'connect' })
+      }
+
+      // 断开连接
+      if (event.disconnect) {
+        console.log('已断开服务器,插件未自动断开已提is')
+        this.store.setMqttMessage({ type: 'disconnect' })
+      }
+
+      // 收到消息
+      if (event.message) {
+        console.log('收到消息', event.message)
+        try {
+          const { payload, topic } = event.message
+          this.client_channel = topic
+          const data = JSON.parse(Buffer.from(payload).toString())
+          this.store.setMqttMessage({ ...data })
+        } catch (error) {
+          this.throw('mqtt消息解析失败')
+        }
+      }
     })
     })
   }
   }
 }
 }

+ 9 - 2
src/store/index.ts

@@ -6,6 +6,11 @@ export interface UserInfo {
   room: string
   room: string
 }
 }
 
 
+export interface MqttMessage {
+  type: string;
+  [key: string]: any
+}
+
 // id必填,且需要唯一
 // id必填,且需要唯一
 const useStore = defineStore('index', {
 const useStore = defineStore('index', {
   state: () => ({
   state: () => ({
@@ -14,12 +19,14 @@ const useStore = defineStore('index', {
       name: '',
       name: '',
       room: ''
       room: ''
     },
     },
-    mqtt_client_id: 'contrller',
-    mqtt_channel: ''
+    mqtt_message: { type: '' }
   }),
   }),
   actions: {
   actions: {
     setUserInfo(data: UserInfo) {
     setUserInfo(data: UserInfo) {
       this.userInfro = data
       this.userInfro = data
+    },
+    setMqttMessage(data: MqttMessage) {
+      this.mqtt_message = data
     }
     }
   },
   },
   persist: {
   persist: {