102 lines
2.4 KiB
TypeScript
102 lines
2.4 KiB
TypeScript
import mqtt from 'mqtt'
|
|
|
|
// MQTT 配置
|
|
const defaultOptions: any = {
|
|
clean: true,
|
|
connectTimeout: 4000,
|
|
clientId: 'vue3-client-' + Math.random().toString(16).substr(2, 8),
|
|
username: 'zbjk',
|
|
password: 'zbjk@123456',
|
|
// 移除 port 配置
|
|
// port: 8083,
|
|
reconnectPeriod: 1000, // 添加重连间隔
|
|
}
|
|
|
|
// MQTT 代理地址(示例使用公共测试服务器)
|
|
const brokerUrl = 'wss://www.tuxixi.net/mqtt'
|
|
|
|
export default class MQTTClient {
|
|
private client: any | null = null
|
|
private url: string
|
|
private options: any
|
|
|
|
constructor(url: string, options = {} as any) {
|
|
this.client = null
|
|
this.url = url || brokerUrl
|
|
this.options = { ...defaultOptions, ...options }
|
|
}
|
|
|
|
connect(): void {
|
|
this.client = mqtt.connect(this.url, this.options)
|
|
|
|
// 连接成功
|
|
this.client.on('connect', () => {
|
|
console.log('MQTT Connected successfully')
|
|
})
|
|
|
|
// 连接关闭
|
|
this.client.on('close', () => {
|
|
console.log('MQTT Connection closed')
|
|
})
|
|
|
|
// 重连
|
|
this.client.on('reconnect', () => {
|
|
console.log('MQTT Attempting to reconnect...')
|
|
})
|
|
|
|
// 错误处理
|
|
this.client.on('error', (error: Error) => {
|
|
console.error('MQTT Error:', error)
|
|
console.error('Error details:', {
|
|
message: error.message,
|
|
stack: error.stack,
|
|
url: this.url,
|
|
options: this.options,
|
|
})
|
|
})
|
|
|
|
// 连接结束
|
|
this.client.on('end', () => {
|
|
console.log('MQTT Connection ended')
|
|
})
|
|
}
|
|
|
|
subscribe(topic: string): void {
|
|
if (!this.client) return
|
|
|
|
this.client.subscribe(topic, { qos: 0 }, (err?: any) => {
|
|
if (!err) console.log(`Subscribed to ${topic}`)
|
|
})
|
|
}
|
|
|
|
unsubscribe(topic: string): void {
|
|
if (!this.client) return
|
|
|
|
this.client.unsubscribe(topic, (err?: any) => {
|
|
if (!err) console.log(`Unsubscribed from ${topic}`)
|
|
})
|
|
}
|
|
|
|
// 接收消息处理
|
|
onMessage(callback: (topic: string, message: string) => void): void {
|
|
if (!this.client) return
|
|
|
|
this.client.on('message', (topic: string, message: Buffer) => {
|
|
console.log('接收消息---------', topic, message.toString())
|
|
callback(topic, message.toString())
|
|
})
|
|
}
|
|
|
|
// 发送消息
|
|
publish(topic: string, message: string): void {
|
|
if (!this.client) return
|
|
|
|
console.log('发送消息---------', topic, message)
|
|
this.client.publish(topic, message, { qos: 0 })
|
|
}
|
|
|
|
disconnect(): void {
|
|
this.client?.end()
|
|
}
|
|
}
|