共计 1130 个字符,预计需要花费 3 分钟才能阅读完成。
` // const MQTT_URL = “ws://192.168.50.221:8083/mqtt”;
// const MQTT_PORT = 8083;
const MQTT_TIMEOUT = 4000;
// const MQTT_TOPIC = "device/field/update/CR-7iA/WS01_PL04_01/INP_CURRENT";
try {if(item.url?.length){let url = new URL(item.url);
let port = url.port;
if(port?.length){let c = mqtt.connect(`${item.url}`, {port: `${port}`,
connectTimeout: MQTT_TIMEOUT,
keepalive: 5,
clientId: "mqtt_t_sub" + new Date().valueOf()
});
c.on("connect", e => {console.info("========= SUBSCRIBER CONNECTED");
c.subscribe(`${item.topicUrl}`, {}, (err, granted) => {// console.info(err, granted);
if (granted) {c.on("message", (topic, payload, packet) => {// console.info(">>" + payload.toString());
let stringData = payload.toString(),objData;
if(stringData.includes('{') || stringData.includes('[')){objData = JSON.parse(stringData);
}
else if(payload.buffer){objData = new Int32Array(new Uint8Array(payload).buffer);
}
// console.info(">>JSON.parse(stringData)", objData);
_this.callbackFun(item, objData);
});
}
});
});
c.on("disconnect", e=>{console.info("========= DISCONNECTED", e);
})
c.on("error", e=>{console.info("========= SUBSCRIBER ERROR...", e);
})
}
}
}
catch (e) {console.log(e);
}
`
先上代码
MQTT(websocket) 类型
入门教程【http://blog.itpub.net/6995813…】
正文完