Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const mqtt = require('mqtt');
- const cron = require('node-cron');
- const config = require('../config');
- const { generateRandomValues } = require('./iot.mocked.js');
- class DeviceGateway {
- constructor() {
- this.client = null;
- this.db = null;
- this.task = null;
- }
- doTask() {
- if (!this.db) throw 'Invalid DB';
- const sensors = this.db.get('sensors').value();
- this.task = cron.schedule('*/10 * * * * *', () => {
- console.log('Mocking sensor data every 10 seconds');
- for (const sensor of sensors) {
- const topic = `${config.features.mqtt.topic}/${sensor.code}`;
- const resolution = 32;
- const values = generateRandomValues(18.0, 30.0, resolution, 1.0);
- const data = { code: sensor.code, value: values[0] };
- const message = JSON.stringify(data);
- console.log('-- Sending mqtt message ', topic, message);
- this.client.publish(topic, message, { qos: 2 }, () => {
- console.log('---- Mqtt message sent', topic, message);
- });
- }
- });
- }
- start(db) {
- this.db = db;
- if (!this.client) {
- this.client = mqtt.connect({
- host: config.features.mqtt.broker.host,
- port: config.features.mqtt.broker.port
- });
- this.client.on('connect', () => {
- console.log('MQTT broker connected');
- this.doTask();
- });
- }
- }
- reset() {
- console.log('Invalidating old task and creating a new one');
- if (this.task)
- this.task.stop();
- this.doTask();
- }
- }
- module.exports = new DeviceGateway();
- // vvvv Add lines below to server.js vvvv
- const deviceGateway = require('./services/DeviceGateway');
- deviceGateway.start(router.db);
Add Comment
Please, Sign In to add comment