mqtt.service.ts 899 B

12345678910111213141516171819202122232425262728293031
  1. import { connect, disconnect, listen, publish } from '@kuyoonjo/tauri-plugin-mqtt'
  2. import { injectable, Service } from './service'
  3. import useStore from '@/store/index'
  4. /**
  5. * MQTT服务
  6. */
  7. @injectable
  8. export default class MqttService extends Service {
  9. private store = useStore()
  10. async connect(url: string, name: string, room: string) {
  11. const mqttUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
  12. await connect(this.store.mqtt_client_id, mqttUrl)
  13. }
  14. async send(params: string) {
  15. await publish(this.store.mqtt_client_id, this.store.mqtt_channel, 1, false, params)
  16. }
  17. async disconnect() {
  18. await disconnect(this.store.mqtt_client_id)
  19. }
  20. async listen(callback: (data: any) => void) {
  21. await listen(client => {
  22. // if(client.payload)
  23. // 如果断开连接,如果有订阅需要取消订阅,然后重新连接
  24. callback(client.payload)
  25. })
  26. }
  27. }