-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
26 lines (25 loc) · 930 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'use strict';
require('dotenv').config()
const SerialPort = require('serialport')
const mqtt = require('mqtt')
const Reading = require('./libs/Reading')
const mqttClient = mqtt.connect(process.env.MQTT_BROKER_HOST)
mqttClient.on('connect', () => {
mqttClient.subscribe(process.env.MQTT_TOPIC)
let port = new SerialPort('/dev/ttyUSB0', {dataBits: 7})
let readLine = SerialPort.parsers.ReadLine;
let parser = port.pipe(readLine({delimiter: '!'}))
parser.on('data', function(data) {
let reading = new Reading(data)
if (reading.valid()) {
let r = {
meterSerialnumber: reading.meterSerialnumber,
energyAMilliwattHour: reading.energyAMilliwattHour,
energyBMilliwattHour: reading.energyBMilliwattHour,
powerAMilliwatt: reading.powerAMilliwatt,
powerBMilliwatt: reading.powerBMilliwatt
}
mqttClient.publish(process.env.MQTT_TOPIC, JSON.stringify(r))
}
})
})