- vite@^4.5.0
- vue@^3.3.6
- mqtt@^4.3.7
import * as mqtt from 'mqtt/dist/mqtt.min';
let client = null;
export const MQTTSWebSocket = () => {
const connectUrl = `ws://192.168.1.56:8083/mqtt`;
const storeMqtt = useMqttStore();
client = mqtt.connect(connectUrl, {
clean: true,
connectTimeout: 8000,
reconnectPeriod: 1000,
username: 'admin',
password: 'public',
});
const topic = 'RCT/State/#';
client.on('connect', () => {
console.info('订阅成功');
client.subscribe(topic);
client.on('message', function (topic, message) {
let data = JSON.parse(message.toString());
console.info('返回的数据:', message, data);
});
});
client.on('close', function () {
console.info('已断开连接');
});
client.on('reconnect', (error) => {
console.info('正在重连:', error);
});
client.on('error', (error) => {
console.info('连接失败:', error);
});
};
export const mqttDisconnect = () => {
if (client) {
client.end(() => {
console.info('手动断开连接');
});
}
};