forked from ruudverheijden/node-p1-reader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.js
177 lines (142 loc) · 5.51 KB
/
main.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
const EventEmitter = require('events');
const util = require('util');
let serialPort = require('serialport');
let serialPortUsed = false;
let autodiscoverList = [];
let constructor;
let timer;
const parsePacket = require('./lib/parsePacket');
const debug = require('./lib/debug');
const config = require('./config/config.json');
function P1Reader(options) {
if (typeof options !== 'object') {
options = {};
}
debug.setDebugMode(options.debug);
if (options.emulator) {
serialPort = require('./lib/emulateSerialport');
serialPort.setEmulatorOverrides(options.emulatorOverrides);
}
constructor = this;
EventEmitter.call(this);
// Either force a specific port (with specific configuration) or automatically discover it
if (options && options.serialPort) {
autodiscoverList[0] = {
port: options.serialPort.port,
baudRate: options.serialPort.baudRate,
parity: options.serialPort.parity,
dataBits: options.serialPort.dataBits,
stopBits: options.serialPort.stopBits
};
_setupSerialConnection();
} else {
serialPort.list()
.then(ports => {
// Create the auto discovery list with each of the possible serialport configurations per port found
for (let i = 0; i < ports.length; i++) {
for (let j = 0; j < config.serialPort.length; j++) {
autodiscoverList.push({
port: ports[i].comName,
baudRate: config.serialPort[j].baudRate,
parity: config.serialPort[j].parity,
dataBits: config.serialPort[j].dataBits,
stopBits: config.serialPort[j].stopBits
});
}
}
debug.logAutodiscoverList(autodiscoverList);
_setupSerialConnection();
})
.catch(err => {
console.error('Serialports could not be listed: ' + err);
});
}
}
util.inherits(P1Reader, EventEmitter);
/**
* Retrieve the name of the serial port being used
*/
P1Reader.prototype.getSerialPort = function () {
return serialPortUsed;
};
module.exports = P1Reader;
/**
* Setup serial port connection
*/
function _setupSerialConnection() {
const currentPortConfig = autodiscoverList[0];
debug.log('Trying to connect to Smart Meter via port: ' + currentPortConfig.port
+ ' (BaudRate: ' + currentPortConfig.baudRate + ', Parity: ' + currentPortConfig.parity + ', Databits: '
+ currentPortConfig.dataBits + 'Stopbits: ' + currentPortConfig.stopBits + ')');
// Go to the next port if this one didn't respond within the timeout limit
timer = setTimeout(() => {
if (!serialPortUsed) {
_tryNextSerialPort();
}
}, config.connectionSetupTimeout);
// Open serial port connection
const sp = new serialPort(currentPortConfig.port, {
baudRate: currentPortConfig.baudRate,
parity: currentPortConfig.parity,
dataBits: currentPortConfig.dataBits,
stopBits: currentPortConfig.stopBits
});
let received = '';
sp.on('open', () => {
debug.log('Serial connection established');
sp.on('data', (data) => {
received += data.toString();
const startCharPos = received.indexOf(config.startCharacter);
const endCharPos = received.indexOf(config.stopCharacter);
// Package is complete if the start- and stop character are received
if (startCharPos >= 0 && endCharPos >= 0) {
const packet = received.substr(startCharPos, endCharPos - startCharPos);
const parsedPacket = parsePacket(packet);
received = '';
// Verify if connected to the correct serial port at initialization
if (!serialPortUsed) {
if (parsedPacket.timestamp !== null) {
debug.log('Connection with Smart Meter established');
serialPortUsed = currentPortConfig.port;
constructor.emit('connected', currentPortConfig);
} else {
_tryNextSerialPort();
}
}
debug.writeToLogFile(packet, parsedPacket);
constructor.emit('reading-raw', packet);
if (parsedPacket.timestamp !== null) {
constructor.emit('reading', parsedPacket);
} else {
constructor.emit('error', 'Invalid reading');
}
}
});
});
sp.on('error', (error) => {
// Reject this port if we haven't found the correct port yet
if (!serialPortUsed) {
_tryNextSerialPort();
} else {
// Only emit errors after we have established a connection with the Smart Meter
debug.log('Error emitted: ' + error);
constructor.emit('error', error);
}
});
sp.on('close', () => {
constructor.emit('close');
});
}
/**
* Try the next serial port if available
*/
function _tryNextSerialPort() {
clearTimeout(timer);
autodiscoverList.shift();
if (autodiscoverList.length > 0) {
debug.log('Smart Meter not found yet, trying another port / configuration...');
_setupSerialConnection();
} else {
console.error('Could not find a Smart Meter');
}
}