|
|
@@ -0,0 +1,37 @@
|
|
|
+const mqtt = require('mqtt');
|
|
|
+const client = mqtt.connect('mqtt://broker.emqx.io'); // 使用公共MQTT broker作为示例
|
|
|
+
|
|
|
+const DEVICE_TOPIC = 'device/info';
|
|
|
+const PERSON_TOPIC = 'person/info';
|
|
|
+
|
|
|
+client.on('connect', () => {
|
|
|
+ console.log('Connected to MQTT broker');
|
|
|
+ client.subscribe(DEVICE_TOPIC, (err) => {
|
|
|
+ if (!err) {
|
|
|
+ console.log(`Subscribed to ${DEVICE_TOPIC}`);
|
|
|
+ }
|
|
|
+ });
|
|
|
+});
|
|
|
+
|
|
|
+client.on('message', (topic, message) => {
|
|
|
+ if (topic === DEVICE_TOPIC) {
|
|
|
+ console.log('Received device info:', message.toString());
|
|
|
+ // 这里处理接收到的设备信息
|
|
|
+ // 例如: 保存到数据库或触发其他操作
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+function publishPersonInfo(personInfo) {
|
|
|
+ const message = JSON.stringify(personInfo);
|
|
|
+ client.publish(PERSON_TOPIC, message, { qos: 1 }, (err) => {
|
|
|
+ if (!err) {
|
|
|
+ console.log('Person info published successfully');
|
|
|
+ } else {
|
|
|
+ console.error('Failed to publish person info:', err);
|
|
|
+ }
|
|
|
+ });
|
|
|
+}
|
|
|
+
|
|
|
+module.exports = {
|
|
|
+ publishPersonInfo
|
|
|
+};
|