- 下载mqtt服务:npm install mqtt
-
const mqttConfig = { // 你的 MQTT 服务器配置 protocolId: 'MQTT', protocolVersion: 4, clean: true, clientId: 'xxxx', reconnectPeriod: 1000, connectTimeout: 60 * 1000, // will: { // topic: 'WillTopic', // payload: 'Connection Closed Unexpectedly!', // qos: 0, // retain: false // }, username: 'xxxx', // 如果需要 password: 'xxxxx', // 如果需要 // 其他配置... }; export function useMqtt() { const client = ref(null); const listeners = ref({}); // 连接到 MQTT 服务器 function connect() { console.log('2**********'); if (client.value) return; client.value = mqtt.connect('地址',mqttConfig); client.value.on('connect', () => { console.log('Connected to MQTT'); return true // 这里可以添加默认的订阅 // client.value.subscribe('xxxx') }); client.value.on('message', (topic, message) => { if (listeners.value[topic]) { listeners.value[topic].forEach(callback => callback(message.toString())) } }); // 处理错误和断开连接的情况 client.value.on('error', (error) => { console.error('MQTT error:', error); }); client.value.on('close', () => { console.log('MQTT connection closed'); client.value = null; // 断开连接后重置 client }); } // 断开 MQTT 连接 function disconnect() { if (client.value) { client.value.end(); client.value = null; } } // 订阅 MQTT 主题 function subscribe(topic, callback) { console.log(topic) if (client.value && client.value.connected) { client.value.subscribe(topic); if (!listeners.value[topic]) { listeners.value[topic] = []; } listeners.value[topic].push(callback); } } // 取消订阅 MQTT 主题 function unsubscribe(topic, callback) { if (client.value && client.value.connected && listeners.value[topic]) { const index = listeners.value[topic].indexOf(callback); if (index > -1) { listeners.value[topic].splice(index, 1); // 如果没有监听者了,可以取消订阅 if (listeners.value[topic].length === 0) { client.value.unsubscribe(topic); } } } } // 发布 MQTT 消息 function publish(topic, message) { if (client.value && client.value.connected) { client.value.publish(topic, message); } }