mqtt-handler.js 996 B

12345678910111213141516171819202122232425262728293031323334353637
  1. const mqtt = require('mqtt');
  2. const client = mqtt.connect('mqtt://broker.emqx.io'); // 使用公共MQTT broker作为示例
  3. const DEVICE_TOPIC = 'device/info';
  4. const PERSON_TOPIC = 'person/info';
  5. client.on('connect', () => {
  6. console.log('Connected to MQTT broker');
  7. client.subscribe(DEVICE_TOPIC, (err) => {
  8. if (!err) {
  9. console.log(`Subscribed to ${DEVICE_TOPIC}`);
  10. }
  11. });
  12. });
  13. client.on('message', (topic, message) => {
  14. if (topic === DEVICE_TOPIC) {
  15. console.log('Received device info:', message.toString());
  16. // 这里处理接收到的设备信息
  17. // 例如: 保存到数据库或触发其他操作
  18. }
  19. });
  20. function publishPersonInfo(personInfo) {
  21. const message = JSON.stringify(personInfo);
  22. client.publish(PERSON_TOPIC, message, { qos: 1 }, (err) => {
  23. if (!err) {
  24. console.log('Person info published successfully');
  25. } else {
  26. console.error('Failed to publish person info:', err);
  27. }
  28. });
  29. }
  30. module.exports = {
  31. publishPersonInfo
  32. };