-
Notifications
You must be signed in to change notification settings - Fork 5
/
wrapper.js
495 lines (403 loc) · 15.4 KB
/
wrapper.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
const SerialPort = require('serialport');
const EventEmitter = require('events');
const SensorState = require("./core/sensor-state.js");
const SensorCommand = require("./core/sensor-command.js");
const addChecksumToCommandArray = require("./core/packet-utils.js").addChecksumToCommandArray;
const verifyPacket = require("./core/packet-utils.js").verifyPacket;
const PacketHandlers = require("./core/packet-handlers.js");
const ALLOWED_RETRIES = 10; // Number of retries allowed for single command request.
const COMMAND_RETRY_INTERVAL = 150; // Time between sequential retries.
class SDS011Wrapper extends EventEmitter {
/**
* Open sensor.
*
* @param {string} portPath - Serial port path
*/
constructor(portPath) {
super();
this._port = new SerialPort(portPath, { baudRate: 9600 });
this._state = new SensorState();
this._commandQueue = [];
this._isCurrentlyProcessing = false;
this._retryCount = 0;
this._port.on('error', function (err) {
console.log('Error: ', err.message);
});
this._port.on('close', () => {
console.log('SDS011Wrapper port closed');
this.close();
});
/**
* Listen for incoming data and react: change internal state so queued commands know that they were completed or emit data.
*/
this._port.on('data', (data) => {
if (verifyPacket(data)) {
var type = data.readUIntBE(1, 1); // Byte offset 1 is command type
switch (type) {
case 0xC0:
PacketHandlers.handle0xC0(data, this._state);
if (this._state.mode == 'active')
this.emit('measure', { 'PM2.5': this._state.pm2p5, 'PM10': this._state.pm10 });
break;
case 0xC5:
PacketHandlers.handle0xC5(data, this._state);
break;
default:
throw new Error('Unknown packet type: ' + type);
}
}
});
// Queue first command to "warm-up" the connection and command queue
this.query().catch( ex => { console.error('SDS011Wrapper error: ' + ex); } );
}
/**
* Close open connection and cleanup.
*/
close() {
if (this._state.closed) {
console.log('Sensor connection is already closed.');
return;
}
this._port.close();
this._state.closed = true;
this._commandQueue.length = 0;
this.emit('close', {});
this.removeAllListeners();
}
/**
* Query sensor for it's latest reading.
*
* @returns {Promise<object>} Resolved with PM2.5 and PM10 readings. May be rejected if sensor fails to respond after a number of internal retries.
*/
query() {
return this._enqueueQueryCommand(this._port, this._state);
}
_enqueueQueryCommand(port, state) {
function prepare() {
this.state.pm2p5 = undefined;
this.state.pm10 = undefined;
}
const prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command));
}
const executeContext = {
port: port
};
function isFullfilled() {
return (this.state.pm2p5 !== undefined) && (this.state.pm10 !== undefined);
}
const isFullfilledContext = {
state: state
};
return new Promise((resolve, reject, onCancel) => {
function resolveWithReadings() {
resolve({
'PM2.5': this.state.pm2p5,
'PM10': this.state.pm10
});
}
const resolveContext = {
state: state
};
const command = new SensorCommand(port, resolveWithReadings.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Set reporting mode. This setting is still effective after power off.
*
* @param {('active'|'query')} mode - active: data will be emitted as "data" event, query: new data has to requested manually @see query
*
* @returns {Promise} Resolved when mode was set successfully. May be rejected if sensor fails to respond after a number of internal retries.
*/
setReportingMode(mode) {
return this._enqueueSetModeCommand(this._port, this._state, mode);
}
_enqueueSetModeCommand(port, state, mode) {
if (mode !== 'active' && mode !== 'query')
throw new Error('Invalid mode');
function prepare() {
this.state.mode = undefined;
}
const prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 2, 1, this.mode === 'active' ? 0 : 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command));
}
const executeContext = {
port: port,
mode: mode
};
function isFullfilled() {
return this.state.mode === this.setMode;
}
const isFullfilledContext = {
state: this._state,
setMode: mode
};
return new Promise((resolve, reject, onCancel) => {
const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Get reporting mode.
*
* @returns {Promise} Resolved with either 'active' or 'query'. May be rejected if sensor fails to respond after a number of internal retries.
*/
getReportingMode() {
return this._enqueueGetModeCommand(this._port, this._state);
}
_enqueueGetModeCommand(port, state) {
function prepare() {
this.state.mode = undefined;
}
const prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command));
}
const executeContext = {
port: port
};
function isFullfilled() {
return this.state.mode != undefined;
}
const isFullfilledContext = {
state: this._state
};
return new Promise((resolve, reject, onCancel) => {
function resolveWithMode() {
resolve(this.state.mode);
}
const resolveContext = {
state: state
};
const command = new SensorCommand(port, resolveWithMode.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Switch to sleep mode and back. Fan and laser will be turned off while in sleep mode. Any command will wake the device.
*
* @param {boolean} shouldSleep - whether device should sleep or not
*
* @returns {Promise} Resolved when operation completed successfully. May be rejected if sensor fails to respond after a number of internal retries.
*/
setSleepSetting(shouldSleep) {
return this._enqueueSetSleepCommand(this._port, this._state, shouldSleep);
}
_enqueueSetSleepCommand(port, state, shouldSleep) {
function prepare() {
this.state.isSleeping = undefined;
}
const prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 6, 1, shouldSleep ? 0 : 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command));
}
const executeContext = {
port: port,
shouldSleep: shouldSleep
};
function isFullfilled() {
return this.state.isSleeping === this.shouldSleep;
}
const isFullfilledContext = {
state: this._state,
shouldSleep: shouldSleep
};
return new Promise((resolve, reject, onCancel) => {
const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Read software version. It will be presented in "year-month-day" format.
*
* @returns {Promise<string>} - Resolved with sensor firmware version. May be rejected if sensor fails to respond after a number of internal retries.
*/
getVersion() {
return this._enqueueGetVersionCommand(this._port, this._state);
}
_enqueueGetVersionCommand(port, state) {
function prepare() {
this.state.firmware = undefined;
}
const prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command));
}
const executeContext = {
port: port
};
function isFullfilled() {
return this.state.firmware !== undefined;
}
const isFullfilledContext = {
state: this._state
};
return new Promise((resolve, reject, onCancel) => {
function resolveWithFirmwareVersion() {
resolve(this.state.firmware);
}
const resolveContext = {
state: state
};
const command = new SensorCommand(port, resolveWithFirmwareVersion.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Set working period of the sensor. This setting is still effective after power off.
*
* @param {number} time - Working time (0 - 30 minutes). Sensor will work continuously when set to 0.
*
* @returns {Promise} Resolved when period was changed successfully. May be rejected if sensor fails to respond after a number of internal retries.
*/
setWorkingPeriod(time) {
if (time < 0 || time > 30)
throw new Error('Invalid argument.');
return this._enqueueSetWorkingPeriodCommand(this._port, this._state, time);
}
_enqueueSetWorkingPeriodCommand(port, state, time) {
function prepare() {
this.state.workingPeriod = undefined;
}
var prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 8, 1, this.time, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command)); // Send the command to the sensor
}
var executeContext = {
port: port,
time: time
};
function isFullfilled() {
return this.state.workingPeriod === this.setPeriod;
}
var isFullfilledContext = {
state: this._state,
setPeriod: time
};
return new Promise((resolve, reject, onCancel) => {
const command = new SensorCommand(port, resolve, reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
/**
* Get current working period.
*
* @returns {Promise<Number>} Resolved with current period setting. May be rejected if sensor fails to respond after a number of internal retries.
*/
getWorkingPeriod() {
return this._enqueueGetWorkingPeriodCommand(this._port, this._state);
}
_enqueueGetWorkingPeriodCommand(port, state) {
function prepare() {
this.state.workingPeriod = undefined;
}
var prepareContext = {
state: state
};
function execute() {
var command = [
0xAA, 0xB4, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0xAB
];
addChecksumToCommandArray(command);
this.port.write(Buffer.from(command)); // Send the command to the sensor
}
var executeContext = {
port: port
};
function isFullfilled() {
return this.state.workingPeriod !== undefined;
}
var isFullfilledContext = {
state: this._state
};
return new Promise((resolve, reject, onCancel) => {
function resolveWithTime() {
resolve(this.state.workingPeriod);
}
const resolveContext = {
state: state
};
const command = new SensorCommand(port, resolveWithTime.bind(resolveContext), reject, prepare.bind(prepareContext), execute.bind(executeContext), isFullfilled.bind(isFullfilledContext))
this._enqueueCommand(command);
});
}
_enqueueCommand(command) {
if (command.constructor.name !== 'SensorCommand')
throw new Error('Argument of type "SensorCommand" is required.');
this._commandQueue.push(command);
if (!this._isCurrentlyProcessing) {
this._processCommands();
}
}
_processCommands() {
this._isCurrentlyProcessing = true;
const cmd = this._commandQueue[0];
// Run prepare command for the first execution of new command
if (this._retryCount == 0 && cmd !== undefined)
cmd.prepare();
// Reject command if it failed after defined number of retries
if (++this._retryCount > ALLOWED_RETRIES) {
const faultyCommand = this._commandQueue.shift();
faultyCommand.failureCallback(); // Let the world know
this._retryCount = 0;
this._processCommands(); // Move to the next command
return;
}
if (this._commandQueue.length > 0) {
if (cmd.isFullfilled()) {
this._commandQueue.shift(); // Fully processed, remove from the queue.
this._retryCount = 0;
cmd.successCallback();
this._processCommands(); // Move to the next command
} else {
// Command completion condition was not met. Run command and run check after some time.
cmd.execute();
setTimeout(this._processCommands.bind(this), COMMAND_RETRY_INTERVAL);
}
} else {
// Processed all pending commands.
this._isCurrentlyProcessing = false;
this._retryCount = 0;
}
}
}
module.exports = SDS011Wrapper;