yskang

threejs-viewer-38

Apr 20th, 2022 (edited)
476
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mqtt = require('mqtt');
  2. const cron = require('node-cron');
  3.  
  4. const config = require('../config');
  5. const { generateRandomValues } = require('./iot.mocked.js');
  6.  
  7. class DeviceGateway {
  8.     constructor() {
  9.         this.client = null;
  10.         this.db = null;
  11.         this.task = null;
  12.     }
  13.  
  14.     doTask() {
  15.         if (!this.db) throw 'Invalid DB';
  16.  
  17.         const sensors = this.db.get('sensors').value();
  18.  
  19.         this.task = cron.schedule('*/10 * * * * *', () => {
  20.             console.log('Mocking sensor data every 10 seconds');
  21.              for (const sensor of sensors) {
  22.                  const topic = `${config.features.mqtt.topic}/${sensor.code}`;
  23.                  const resolution = 32;
  24.                  const values = generateRandomValues(18.0, 30.0, resolution, 1.0);
  25.                  const data = { code: sensor.code, value: values[0] };
  26.  
  27.                  const message = JSON.stringify(data);
  28.                  console.log('-- Sending mqtt message ', topic, message);
  29.  
  30.                  this.client.publish(topic, message, { qos: 2 }, () => {
  31.                      console.log('---- Mqtt message sent', topic, message);
  32.                  });
  33.              }
  34.          });
  35.     }
  36.  
  37.     start(db) {
  38.         this.db = db;
  39.         if (!this.client) {
  40.             this.client = mqtt.connect({
  41.                 host: config.features.mqtt.broker.host,
  42.                 port: config.features.mqtt.broker.port
  43.             });
  44.  
  45.             this.client.on('connect', () => {
  46.                 console.log('MQTT broker connected');
  47.                 this.doTask();
  48.             });
  49.          }
  50.     }
  51.  
  52.     reset() {
  53.         console.log('Invalidating old task and creating a new one');
  54.         if (this.task)
  55.             this.task.stop();
  56.             this.doTask();
  57.     }
  58. }
  59.  
  60. module.exports = new DeviceGateway();
  61.  
  62.  
  63.  
  64. // vvvv Add lines below to server.js vvvv
  65.  
  66. const deviceGateway = require('./services/DeviceGateway');
  67. deviceGateway.start(router.db);
  68.  
Add Comment
Please, Sign In to add comment