98 lines
2.8 KiB
JavaScript
98 lines
2.8 KiB
JavaScript
/**
|
|
* MQTT 管理 Mixin
|
|
*/
|
|
export default {
|
|
computed: {
|
|
isConnected() {
|
|
return this.$store ? this.$store.state.mqtt.isConnected : false;
|
|
},
|
|
mqttStatus() {
|
|
return this.$store ? this.$store.state.mqtt.mqttStatus : '未连接';
|
|
}
|
|
},
|
|
methods: {
|
|
// MQTT 连接已由主进程自动处理,客户端不再需要手动连接
|
|
// 只保留状态查询方法
|
|
async checkMQTTStatus() {
|
|
try {
|
|
|
|
if (!window.electronAPI) {
|
|
return;
|
|
}
|
|
|
|
const statusResult = await window.electronAPI.invoke('mqtt:status');
|
|
if (statusResult && typeof statusResult.isConnected !== 'undefined') {
|
|
if (this.$store) {
|
|
this.$store.dispatch('mqtt/setConnected', statusResult.isConnected);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.warn('查询MQTT状态失败:', error);
|
|
}
|
|
},
|
|
|
|
async disconnectMQTT() {
|
|
try {
|
|
if (!window.electronAPI) {
|
|
return;
|
|
}
|
|
|
|
await window.electronAPI.invoke('mqtt:disconnect');
|
|
if (this.addLog) {
|
|
this.addLog('info', '服务断开连接指令已发送');
|
|
}
|
|
} catch (error) {
|
|
if (this.addLog) {
|
|
this.addLog('error', `断开服务连接异常: ${error.message}`);
|
|
}
|
|
}
|
|
},
|
|
|
|
onMQTTConnected(data) {
|
|
console.log('[MQTT] onMQTTConnected 被调用,数据:', data);
|
|
if (this.$store) {
|
|
this.$store.dispatch('mqtt/setConnected', true);
|
|
console.log('[MQTT] 状态已更新为已连接');
|
|
}
|
|
if (this.addLog) {
|
|
this.addLog('success', 'MQTT 服务已连接');
|
|
}
|
|
},
|
|
|
|
onMQTTDisconnected(data) {
|
|
if (this.$store) {
|
|
this.$store.dispatch('mqtt/setConnected', false);
|
|
}
|
|
if (this.addLog) {
|
|
this.addLog('warn', `服务连接断开: ${data.reason || '未知原因'}`);
|
|
}
|
|
},
|
|
|
|
onMQTTMessage(data) {
|
|
const action = data.payload?.action || 'unknown';
|
|
if (this.addLog) {
|
|
this.addLog('info', `收到远程指令: ${action}`);
|
|
}
|
|
},
|
|
|
|
onMQTTStatusChange(data) {
|
|
console.log('[MQTT] onMQTTStatusChange 被调用,数据:', data);
|
|
// 根据状态数据更新连接状态
|
|
if (data && typeof data.isConnected !== 'undefined') {
|
|
if (this.$store) {
|
|
this.$store.dispatch('mqtt/setConnected', data.isConnected);
|
|
console.log('[MQTT] 通过 isConnected 更新状态:', data.isConnected);
|
|
}
|
|
} else if (data && data.status) {
|
|
// 如果数据中有 status 字段,根据状态字符串判断
|
|
const isConnected = data.status === 'connected' || data.status === '已连接';
|
|
if (this.$store) {
|
|
this.$store.dispatch('mqtt/setConnected', isConnected);
|
|
console.log('[MQTT] 通过 status 更新状态:', isConnected);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|