|
|
@@ -1,33 +1,31 @@
|
|
|
-import { EventCallback } from '@tauri-apps/api/event'
|
|
|
-import {
|
|
|
- connect, disconnect, publish, listen, Payload
|
|
|
-} from '@kuyoonjo/tauri-plugin-mqtt'
|
|
|
+import { connect, disconnect, listen, publish } from '@kuyoonjo/tauri-plugin-mqtt'
|
|
|
import { injectable, Service } from './service'
|
|
|
-
|
|
|
+import useStore from '@/store/index'
|
|
|
/**
|
|
|
* MQTT服务
|
|
|
*/
|
|
|
@injectable
|
|
|
export default class MqttService extends Service {
|
|
|
- private mqtt_client_id: string = 'mqtt_contrl_id'
|
|
|
-
|
|
|
- public mqtt_channel: string = ''
|
|
|
+ private store = useStore()
|
|
|
|
|
|
async connect(url: string, name: string, room: string) {
|
|
|
- const newUrl = `${url}?username=${room}&password=${name}`
|
|
|
- return await connect(this.mqtt_client_id, newUrl)
|
|
|
+ const mqttUrl = url.replace(/(\/\/)/, `$1${room}:${name}@`)
|
|
|
+ await connect(this.store.mqtt_client_id, mqttUrl)
|
|
|
}
|
|
|
|
|
|
- async disconnect() {
|
|
|
- await disconnect(this.mqtt_client_id)
|
|
|
+ async send(params: string) {
|
|
|
+ await publish(this.store.mqtt_client_id, this.store.mqtt_channel, 1, false, params)
|
|
|
}
|
|
|
|
|
|
- async publish(payload: string) {
|
|
|
- if (!this.mqtt_channel) return
|
|
|
- await publish(this.mqtt_client_id, this.mqtt_channel, 0, false, payload)
|
|
|
+ async disconnect() {
|
|
|
+ await disconnect(this.store.mqtt_client_id)
|
|
|
}
|
|
|
|
|
|
-// (callback: EventCallback<Payload>) {
|
|
|
-// listen(callback)
|
|
|
-// }
|
|
|
+ async listen(callback: (data: any) => void) {
|
|
|
+ await listen(client => {
|
|
|
+ // if(client.payload)
|
|
|
+ // 如果断开连接,如果有订阅需要取消订阅,然后重新连接
|
|
|
+ callback(client.payload)
|
|
|
+ })
|
|
|
+ }
|
|
|
}
|