|
|
@@ -47,16 +47,20 @@ export default {
|
|
|
handler(newTopics) {
|
|
|
if (!this.client || !this.isConnected) return;
|
|
|
|
|
|
+ const newTopicNames = newTopics.map((t) =>
|
|
|
+ typeof t === "string" ? t : t.topic
|
|
|
+ );
|
|
|
// 取消订阅已经移除的 topic
|
|
|
this.subscribedTopics.forEach((t) => {
|
|
|
- if (!newTopics.includes(t)) {
|
|
|
+ if (!newTopicNames.includes(t)) {
|
|
|
this.unsubscribeTopic(t);
|
|
|
}
|
|
|
});
|
|
|
|
|
|
// 订阅新增 topic
|
|
|
newTopics.forEach((t) => {
|
|
|
- if (!this.subscribedTopics.includes(t)) {
|
|
|
+ const topic = typeof t === "string" ? t : t.topic;
|
|
|
+ if (!this.subscribedTopics.includes(topic)) {
|
|
|
this.subscribeTopic(t);
|
|
|
}
|
|
|
});
|
|
|
@@ -111,25 +115,32 @@ export default {
|
|
|
},
|
|
|
|
|
|
// 订阅单个 topic
|
|
|
- subscribeTopic(topic) {
|
|
|
+ subscribeTopic(t) {
|
|
|
if (!this.client || !this.isConnected) {
|
|
|
- console.warn("MQTT 未连接,无法订阅:", topic);
|
|
|
+ console.warn("MQTT 未连接,无法订阅:", t);
|
|
|
return;
|
|
|
}
|
|
|
+
|
|
|
+ // 兼容字符串和对象
|
|
|
+ const topic = typeof t === "string" ? t : t.topic;
|
|
|
+ const qos = typeof t === "string" ? 0 : (t.qos || 0);
|
|
|
+
|
|
|
if (!topic || this.subscribedTopics.includes(topic)) return;
|
|
|
|
|
|
- this.client.subscribe(topic, (err) => {
|
|
|
+ this.client.subscribe(topic, { qos }, (err) => {
|
|
|
if (!err) {
|
|
|
- console.log("订阅成功:", topic);
|
|
|
+ console.log(`订阅成功: ${topic}, QoS=${qos}`);
|
|
|
this.subscribedTopics.push(topic);
|
|
|
- this.$emit("topic-subscribed", topic);
|
|
|
+ this.$emit("topic-subscribed", { topic, qos });
|
|
|
}
|
|
|
});
|
|
|
},
|
|
|
|
|
|
// 取消订阅单个 topic
|
|
|
- unsubscribeTopic(topic) {
|
|
|
+ unsubscribeTopic(t) {
|
|
|
if (!this.client || !this.isConnected) return;
|
|
|
+ // 兼容字符串和对象
|
|
|
+ const topic = typeof t === "string" ? t : t.topic;
|
|
|
if (!topic || !this.subscribedTopics.includes(topic)) return;
|
|
|
|
|
|
this.client.unsubscribe(topic, (err) => {
|
|
|
@@ -142,15 +153,18 @@ export default {
|
|
|
},
|
|
|
|
|
|
// 发布消息
|
|
|
- publish(topic, message) {
|
|
|
+ publish(topic, message, qos = 0, retain = false) {
|
|
|
if (!this.client || !this.isConnected) {
|
|
|
console.warn("MQTT 未连接,消息未发送:", topic);
|
|
|
return;
|
|
|
}
|
|
|
- console.log("sdfdsf",typeof message === "object");
|
|
|
|
|
|
const payload = typeof message === "object" ? JSON.stringify(message) : String(message);
|
|
|
- this.client.publish(topic, payload);
|
|
|
+ this.client.publish(topic, payload, { qos, retain }, (err) => {
|
|
|
+ if (!err) {
|
|
|
+ console.log(`消息已发布: ${topic}, QoS=${qos}, Retain=${retain}`);
|
|
|
+ }
|
|
|
+ });
|
|
|
},
|
|
|
|
|
|
// 断开连接,取消所有订阅
|