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);
}
}