forked from drone/command-center-dashboard

罗广辉
2025-04-21 2800fa4f32f3900509cb4d6eefaf2bfaf54efdd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import EventEmitter from 'eventemitter3'
import { OPTIONS } from './config'
import mqtt from 'mqtt'
 
export class UranusMqtt extends EventEmitter {
    constructor(url, options) {
        super()
        this._url = url || ''
        this._options = options
        this._client = null
        this._hasInit = false
    }
 
    initMqtt = () => {
        // 仅初始化一次
        if (this._hasInit) return
        // 建立连接
        this._client = mqtt.connect(this._url, {
            ...OPTIONS,
            ...this._options,
        })
        this._hasInit = true
        if (this._client) {
            this._client.on('reconnect', this._onReconnect)
 
            // 消息监听
            this._client.on('message', this._onMessage)
 
            // 连接关闭
            this._client.on('close', this._onClose)
 
            // 连接异常
            this._client.on('error', this._onError)
        }
    }
 
    // 发布
    publishMqtt = (topic, body, opts) => {
        if (!this._client?.connected) {
            this.initMqtt()
        }
        this._client?.publish(topic, body, opts || {}, (error, packet) => {
            if (error) {
                window.console.error('mqtt publish error,', error, packet)
            }
        })
    }
 
    // 订阅
    subscribeMqtt = topic => {
        if (!this._client?.connected) {
            this.initMqtt()
        }
        window.console.log('subscribeMqtt>>>>>', topic)
        this._client?.subscribe(topic, (error, granted) => {
            window.console.log('mqtt subscribe,', error, granted)
        })
    }
 
    // 取消订阅
    unsubscribeMqtt = topic => {
        window.console.log('mqtt unsubscribeMqtt,', topic)
        this._client?.unsubscribe(topic)
    }
 
    // 关闭 mqtt 客户端
    destroyed = () => {
        window.console.log('mqtt 销毁')
        this._client?.end()
    }
 
    _onReconnect = () => {
        if (this._client) {
            window.console.error('mqtt reconnect,')
        }
    }
 
    _onMessage = (topic, payload, packet) => {
        this.emit('onMessageMqtt', { topic, payload, packet })
    }
 
    _onClose = () => {
        // 连接异常关闭会自动重连
        window.console.error('mqtt close,')
        this.emit('onStatus', {
            status: 'close',
        })
    }
 
    _onError = error => {
        // 连接错误会自动重连
        window.console.error('mqtt error,', error)
        this.emit('onStatus', {
            status: 'error',
            data: error,
        })
    }
}