|
@@ -0,0 +1,75 @@
|
|
|
+import mqtt from './mqtt';
|
|
|
+
|
|
|
+export function createMqttClient() {
|
|
|
+ const params = {
|
|
|
+ keepalive: 6000,
|
|
|
+ clean: true,
|
|
|
+ connectTimeout: 30 * 1000,
|
|
|
+ clientId:
|
|
|
+ "xcx_mqtt_cmd1" +
|
|
|
+ uni.getStorageSync("userId") +
|
|
|
+ Math.random().toString(16).substring(2, 8),
|
|
|
+ username: "lnradar",
|
|
|
+ password: "lnradar",
|
|
|
+ wsOptions: {
|
|
|
+ WebSocket: function (url) {
|
|
|
+ return wx.connectSocket({
|
|
|
+ url: url,
|
|
|
+ header: {
|
|
|
+ "content-type": "application/json",
|
|
|
+ },
|
|
|
+ protocols: ["mqtt"],
|
|
|
+ });
|
|
|
+ },
|
|
|
+ },
|
|
|
+ };
|
|
|
+
|
|
|
+ let client = "";
|
|
|
+ // const selectedService = uni.getStorageSync("sercviceChoice");
|
|
|
+ // if (!selectedService || selectedService == "aloneServe") {
|
|
|
+ // if (__wxConfig.envVersion == "develop") {
|
|
|
+ // client = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params);
|
|
|
+ // }
|
|
|
+ // if (__wxConfig.envVersion == "trial") {
|
|
|
+ // client = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params);
|
|
|
+ // }
|
|
|
+ // client = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params);
|
|
|
+ // }
|
|
|
+ client = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params);
|
|
|
+
|
|
|
+ client.on("connect", () => {
|
|
|
+ console.log("MQTTCMD连接成功");
|
|
|
+ const userId = uni.getStorageSync("userId");
|
|
|
+ client.subscribe(`/mps/wx_${userId}/notice`, (err) => {
|
|
|
+ if (err) {
|
|
|
+ console.error("订阅失败", err);
|
|
|
+ } else {
|
|
|
+ console.log(`成功订阅设备主题: /mps/wx_${userId}/notice`);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ });
|
|
|
+
|
|
|
+ client.on("message", (topic, message) => {
|
|
|
+ console.log("topic", topic, message);
|
|
|
+ console.log("接收到消息:", JSON.parse(message.toString()));
|
|
|
+ const userId = uni.getStorageSync("userId");
|
|
|
+ const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
|
|
|
+ const match = topic.match(noticeMatch);
|
|
|
+ if (!match) return;
|
|
|
+ // 处理消息
|
|
|
+ });
|
|
|
+
|
|
|
+ client.on("error", (err) => {
|
|
|
+ console.error("MQTT连接错误:", err);
|
|
|
+ // 连接失败时重新尝试连接
|
|
|
+ setTimeout(() => {
|
|
|
+ createMqttClient(); // 重新连接
|
|
|
+ }, 1000);
|
|
|
+ });
|
|
|
+
|
|
|
+ client.on("disconnect", () => {
|
|
|
+ console.log("MQTT断开连接");
|
|
|
+ });
|
|
|
+
|
|
|
+ return client;
|
|
|
+}
|