-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmcp9808-temperature-sensor.js
442 lines (371 loc) · 12.6 KB
/
mcp9808-temperature-sensor.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
'use strict';
const EventEmitter = require('events');
const Gpio = require('onoff').Gpio;
const i2c = require('i2c-bus');
const mutexify = require('mutexify');
const DEFAULT_I2C_BUS = 1;
const DEFAULT_I2C_ADDRESS = 0x18;
const MANUFACTURER_ID = 0x54;
const DEVICE_ID = 0x04;
const CONFIGURATION_REG = 0x01;
const UPPER_ALERT_TEMP_REG = 0x02;
const LOWER_ALERT_TEMP_REG = 0x03;
const CRITICAL_TEMP_REG = 0x04;
const TEMP_REG = 0x05;
const MANUFACTURER_ID_REG = 0x06;
const DEVICE_ID_REVISION_REG = 0x07;
const RESOLUTION_REG = 0x08;
const MIN_TEMPERATURE = -256;
const MAX_TEMPERATURE = 0xffc / 16; // 255.75
const MIN_RESOLUTION = 0;
const MAX_RESOLUTION = 3;
const MIN_HYSTERESIS = 0;
const MAX_HYSTERESIS = 3;
const CONFIGURATION_BITS = 0x7ff;
const HYSTERESIS_BITS = 0x0600;
const SHUTDOWN_BIT = 0x0100;
const INTERRUPT_CLEAR_BIT = 0x0020;
const ALERT_ENABLED_BIT = 0x0008;
const ALERT_MODE_BIT = 0x0001;
const configRegLock = mutexify();
const validateOpenOptions = options => {
if (typeof options !== 'object') {
return 'Expected options to be of type object.' +
' Got type ' + typeof options + '.';
}
if (options.i2cBusNumber !== undefined &&
(!Number.isSafeInteger(options.i2cBusNumber) ||
options.i2cBusNumber < 0
)
) {
return 'Expected i2cBusNumber to be a non-negative integer.' +
' Got "' + options.i2cBusNumber + '".';
}
if (options.i2cAddress !== undefined &&
(!Number.isSafeInteger(options.i2cAddress) ||
options.i2cAddress < 0 ||
options.i2cAddress > 0x7f
)
) {
return 'Expected i2cAddress to be an integer' +
' >= 0 and <= 0x7f. Got "' + options.i2cAddress + '".';
}
if (options.alertGpioNumber !== undefined &&
(!Number.isSafeInteger(options.alertGpioNumber) ||
options.alertGpioNumber < 0
)
) {
return 'Expected alertGpioNumber to be a non-negative integer. ' +
'Got "' + options.alertGpioNumber + '".';
}
if (options.lowerAlertTemperature !== undefined &&
(typeof options.lowerAlertTemperature !== 'number' ||
options.lowerAlertTemperature < MIN_TEMPERATURE ||
options.lowerAlertTemperature > MAX_TEMPERATURE
)
) {
return 'Expected lowerAlertTemperature to be a number >= ' +
MIN_TEMPERATURE + ' and <= ' + MAX_TEMPERATURE +
'. Got "' + options.lowerAlertTemperature + '".';
}
if (options.upperAlertTemperature !== undefined &&
(typeof options.upperAlertTemperature !== 'number' ||
options.upperAlertTemperature < MIN_TEMPERATURE ||
options.upperAlertTemperature > MAX_TEMPERATURE
)
) {
return 'Expected upperAlertTemperature to be a number >= ' +
MIN_TEMPERATURE + ' and <= ' + MAX_TEMPERATURE +
'. Got "' + options.upperAlertTemperature + '".';
}
if (options.criticalTemperature !== undefined &&
(typeof options.criticalTemperature !== 'number' ||
options.criticalTemperature < MIN_TEMPERATURE ||
options.criticalTemperature > MAX_TEMPERATURE
)
) {
return 'Expected criticalTemperature to be a number >= ' +
MIN_TEMPERATURE + ' and <= ' + MAX_TEMPERATURE +
'. Got "' + options.criticalTemperature + '".';
}
if (options.criticalTemperature !== undefined &&
(typeof options.criticalTemperature !== 'number' ||
options.criticalTemperature < MIN_TEMPERATURE ||
options.criticalTemperature > MAX_TEMPERATURE
)
) {
return 'Expected criticalTemperature to be a number >= ' +
MIN_TEMPERATURE + ' and <= ' + MAX_TEMPERATURE +
'. Got "' + options.criticalTemperature + '".';
}
if (options.resolution !== undefined &&
(!Number.isSafeInteger(options.resolution) ||
options.resolution < MIN_RESOLUTION ||
options.resolution > MAX_RESOLUTION
)
) {
return 'Expected resolution to be an integer >= ' +
MIN_RESOLUTION + ' and <= ' + MAX_RESOLUTION +
'. Got "' + options.resolution + '".';
}
if (options.hysteresis !== undefined &&
(!Number.isSafeInteger(options.hysteresis) ||
options.hysteresis < MIN_HYSTERESIS ||
options.hysteresis > MAX_HYSTERESIS
)
) {
return 'Expected hysteresis to be an integer >= ' +
MIN_HYSTERESIS + ' and <= ' + MAX_HYSTERESIS +
'. Got "' + options.hysteresis + '".';
}
if (options.lowerAlertTemperature !== undefined ||
options.upperAlertTemperature !== undefined ||
options.criticalTemperature !== undefined) {
if (options.lowerAlertTemperature === undefined ||
options.upperAlertTemperature === undefined ||
options.criticalTemperature === undefined) {
return 'Expected all alert temperatures' +
' or no alert temperatures to be specified.';
}
let lowerAlertTemperature =
Math.round(options.lowerAlertTemperature * 4) / 4;
let upperAlertTemperature =
Math.round(options.upperAlertTemperature * 4) / 4;
let criticalTemperature =
Math.round(options.criticalTemperature * 4) / 4;
if (lowerAlertTemperature >= upperAlertTemperature) {
return 'Expected lowerAlertTemperature to be < upperAlertTemperature.';
}
if (upperAlertTemperature >= criticalTemperature) {
return 'Expected upperAlertTemperature to be < criticalTemperature.';
}
}
return null;
};
const watchAlertGpio = (alertGpio, tempSensor, i2cMcp9808) => {
let lastAlertWasCritical = false;
alertGpio.watch((err, value) => {
if (err) {
tempSensor.emit('error', err);
return;
}
let fallingEdge = (value === 0);
tempSensor.temperature().then(temperature => {
if (fallingEdge || lastAlertWasCritical) {
tempSensor.emit('alert', temperature);
}
lastAlertWasCritical = temperature.critical;
if (fallingEdge && !temperature.critical) {
return i2cMcp9808.configuration(INTERRUPT_CLEAR_BIT, 0);
}
}).catch(err => tempSensor.emit('error', err));
});
};
class I2cMcp9808 {
constructor(i2cBus, i2cAddress) {
this._i2cBus = i2cBus;
this._i2cAddress = i2cAddress;
}
close() {
return this._i2cBus.close();
}
writeByte(register, byte) {
return this._i2cBus.writeByte(this._i2cAddress, register, byte);
}
readWord(register) {
return this._i2cBus.readWord(this._i2cAddress, register).
then(word => (word >> 8) + ((word & 0xff) << 8));
}
writeWord(register, word) {
return this._i2cBus.writeWord(
this._i2cAddress, register, (word >> 8) + ((word & 0xff) << 8)
);
}
softReset() {
return this.configuration(0, SHUTDOWN_BIT).
then(_ => this.configuration(0, ALERT_ENABLED_BIT)).
then(_ => this.configuration(0, ALERT_MODE_BIT)). // TODO - can this be removed?
then(_ => this.lowerAlertTemperature(0)).
then(_ => this.upperAlertTemperature(0)).
then(_ => this.criticalTemperature(0)).
then(_ => this.resolution(Mcp9808.RESOLUTION_1_16)).
then(_ =>
this.configuration(
INTERRUPT_CLEAR_BIT, CONFIGURATION_BITS ^ INTERRUPT_CLEAR_BIT
)
);
}
configuration(bitsToSet, bitsToReset) {
let releaseConfigRegLock = null;
// To modify bits in the configuration register it's necessary to read
// the register, modify the required bits and write back to the
// register. In order to prevent parallel asynchronous operations that
// are modifying the configuration register from stepping on each other
// here a mutex is needed.
return new Promise((resolve, reject) => {
configRegLock(release => {
releaseConfigRegLock = release;
resolve();
});
}).
then(_ => this.readWord(CONFIGURATION_REG)).
then(config => {
config |= bitsToSet;
config &= (~bitsToReset & 0xffff);
return this.writeWord(CONFIGURATION_REG, config);
}).
then(_ => releaseConfigRegLock()).
catch(err => {
if (releaseConfigRegLock !== null) {
releaseConfigRegLock();
}
return Promise.reject(err);
});
}
writeTemperature(tempRegister, temp) {
return Promise.resolve().then(_ => {
let rawTemp = temp < 0 ? temp + 256 : temp;
rawTemp = (Math.round(rawTemp * 4) << 2);
if (temp < 0) {
rawTemp |= 0x1000;
}
return this.writeWord(tempRegister, rawTemp);
});
}
temperature() {
return this.readWord(TEMP_REG).then(rawTemp => {
let temp = (rawTemp & 0x0fff) / 16;
if (rawTemp & 0x1000) {
temp -= 256;
}
return {
celsius: temp,
belowLowerLimit: !!(rawTemp & 0x2000),
aboveUpperLimit: !!(rawTemp & 0x4000),
critical: !!(rawTemp & 0x8000),
rawTemp: rawTemp
};
});
}
lowerAlertTemperature(temp) {
return this.writeTemperature(LOWER_ALERT_TEMP_REG, temp);
}
upperAlertTemperature(temp) {
return this.writeTemperature(UPPER_ALERT_TEMP_REG, temp);
}
criticalTemperature(temp) {
return this.writeTemperature(CRITICAL_TEMP_REG, temp);
}
manufacturerId() {
return this.readWord(MANUFACTURER_ID_REG);
}
deviceId() {
return this.readWord(DEVICE_ID_REVISION_REG).then(word => word >> 8);
}
resolution(val) {
return this.writeByte(RESOLUTION_REG, val);
}
hysteresis(val) {
return this.configuration(
(val << 9) & HYSTERESIS_BITS, (~val << 9) & HYSTERESIS_BITS
);
}
enableAlerts() {
// Don't set alertEnabled and alertMode at the same time. If done, there
// will be no interrupt if the application is started and the current
// temperature is > upperAlertTemperature and < criticalTemperature.
return this.configuration(ALERT_ENABLED_BIT, 0).
then(_ => this.configuration(ALERT_MODE_BIT, 0));
}
}
class Mcp9808 extends EventEmitter {
static get RESOLUTION_1_2() {return 0;}
static get RESOLUTION_1_4() {return 1;}
static get RESOLUTION_1_8() {return 2;}
static get RESOLUTION_1_16() {return 3;}
static get HYSTERESIS_0() {return 0;}
static get HYSTERESIS_1_5() {return 1;}
static get HYSTERESIS_3() {return 2;}
static get HYSTERESIS_6() {return 3;}
constructor(i2cMcp9808, alertGpio) {
super();
this._i2cMcp9808 = i2cMcp9808;
this._alertGpio = alertGpio;
}
static open(options) {
let i2cMcp9808;
let tempSensor;
return Promise.resolve().then(_ => {
options = options || {};
let errMsg = validateOpenOptions(options);
if (errMsg) {
return Promise.reject(new Error(errMsg));
}
return i2c.openPromisified(options.i2cBusNumber === undefined ?
DEFAULT_I2C_BUS : options.i2cBusNumber);
}).then(i2cBus => {
const i2cAddress = options.i2cAddress === undefined ?
DEFAULT_I2C_ADDRESS : options.i2cAddress;
i2cMcp9808 = new I2cMcp9808(i2cBus, i2cAddress);
let alertGpio = null;
if (options.alertGpioNumber !== undefined) {
alertGpio = new Gpio(options.alertGpioNumber, 'in', 'both');
}
tempSensor = new Mcp9808(i2cMcp9808, alertGpio);
if (alertGpio !== null) {
watchAlertGpio(alertGpio, tempSensor, i2cMcp9808);
}
}).then(_ =>
i2cMcp9808.manufacturerId()
).then(manufacturerId => {
if (manufacturerId !== MANUFACTURER_ID) {
return Promise.reject(new Error(
'Expected manufacturer ID to be 0x' + MANUFACTURER_ID.toString(16) +
'. Got 0x' + manufacturerId.toString(16) +
'. MCP9808 sensor not found.'
));
}
return i2cMcp9808.deviceId();
}).then(deviceId => {
if (deviceId !== DEVICE_ID) {
return Promise.reject(new Error(
'Expected device ID to be 0x' + DEVICE_ID.toString(16) +
'. Got 0x' + deviceId.toString(16) +
'. MCP9808 sensor not found.'
));
}
return i2cMcp9808.softReset();
}).then(_ => {
if (options.lowerAlertTemperature !== undefined) {
return Promise.all([
i2cMcp9808.lowerAlertTemperature(options.lowerAlertTemperature),
i2cMcp9808.upperAlertTemperature(options.upperAlertTemperature),
i2cMcp9808.criticalTemperature(options.criticalTemperature)
]);
}
}).then(_ => {
if (options.hysteresis !== undefined) {
return i2cMcp9808.hysteresis(options.hysteresis);
}
}).then(_ => {
if (options.resolution !== undefined) {
return i2cMcp9808.resolution(options.resolution);
}
}).then(_ => tempSensor);
}
close() {
return Promise.resolve().then(_ => {
if (this._alertGpio !== null) {
this._alertGpio.unexport();
}
return this._i2cMcp9808.close();
});
}
enableAlerts() {
return this._i2cMcp9808.enableAlerts();
}
temperature() {
return this._i2cMcp9808.temperature();
}
}
module.exports = Mcp9808;