Procházet zdrojové kódy

AI: 添加MQTT功能

D8D AI před 1 rokem
rodič
revize
01c35f3e65
2 změnil soubory, kde provedl 40 přidání a 2 odebrání
  1. 3 2
      package.json
  2. 37 0
      server/mqtt-handler.js

+ 3 - 2
package.json

@@ -11,11 +11,12 @@
     "install-all": "npm install && cd client && npm install"
   },
   "dependencies": {
-    "express": "^4.17.1",
-    "mongoose": "^6.0.12",
     "cors": "^2.8.5",
     "dotenv": "^10.0.0",
     "exceljs": "^4.3.0",
+    "express": "^4.17.1",
+    "mongoose": "^6.0.12",
+    "mqtt": "^4.3.8",
     "pdfkit": "^0.13.0"
   },
   "devDependencies": {

+ 37 - 0
server/mqtt-handler.js

@@ -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
+};