-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathnode_helper.js
More file actions
executable file
·75 lines (66 loc) · 1.78 KB
/
node_helper.js
File metadata and controls
executable file
·75 lines (66 loc) · 1.78 KB
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
/* Magic Mirror
* Module: MMM-DHT-Sensor
*
* By Ricardo Gonzalez http://www.github.com/ryck/MMM-DHT-Sensor
* MIT Licensed.
*/
const NodeHelper = require("node_helper");
let sensor;
try {
sensor = require("node-dht-sensor");
} catch (error) {
console.error("MMM-DHT-Sensor: Failed to load node-dht-sensor", error);
}
module.exports = NodeHelper.create({
start: function () {
this.sensorAvailable = Boolean(sensor);
console.log("MMM-DHT-Sensor helper started ...");
if (!this.sensorAvailable) {
console.warn(
"MMM-DHT-Sensor: node-dht-sensor module unavailable; sending null readings.",
);
}
},
/**
* readSensor()
* Requests sensor data.
*/
readSensor: function (sensorPin, sensorType) {
if (!this.sensorAvailable) {
this.sendSensorData(null, null);
return;
}
if (typeof sensorPin !== "number" || typeof sensorType !== "number") {
console.warn("MMM-DHT-Sensor: Invalid sensor configuration", {
sensorPin,
sensorType,
});
this.sendSensorData(null, null);
return;
}
sensor.read(sensorType, sensorPin, (err, temperature, humidity) => {
if (err) {
console.error("MMM-DHT-Sensor: Sensor read failed", err);
this.sendSensorData(null, null);
return;
}
this.sendSensorData(temperature, humidity);
});
},
sendSensorData: function (temperature, humidity) {
const format = (value) =>
typeof value === "number" && Number.isFinite(value)
? value.toFixed(2)
: null;
this.sendSocketNotification("SENSOR_DATA", {
temperature: format(temperature),
humidity: format(humidity),
});
},
//Subclass socketNotificationReceived received.
socketNotificationReceived: function (notification, payload) {
if (notification === "GET_SENSOR_DATA") {
this.readSensor(payload.sensorPin, payload.sensorType);
}
},
});