/
sensors.js
115 lines (100 loc) · 2.81 KB
/
sensors.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
const interval = 5000;
const host = 'i5-4590-LIN';
const eventReport = 'sensor-report';
const eventAlarm = 'sensor-alarm';
const port = 3000;
const gasThreshold = 1000;
const tempThreshold = 40;
const alarmWaitMs = 5000;
const pins = {
movement: photon.pin.D0,
flame: photon.pin.D1,
humidity: photon.pin.D2,
gas: photon.pin.A0
}
Object.keys(pins).forEach(k => {
photon.pin.mode(pins[k], 'INPUT');
});
photon.pin.mode(pins.humidity, 'INPUT_PULLDOWN');
function readSensors() {
const dht = dht11.read(pins.humidity);
return {
movement: photon.pin(pins.movement),
flame: !photon.pin(pins.flame),
humidity: dht.humidity,
temperature: dht.temperature,
gas: photon.pin(pins.gas)
};
}
function checkData(data) {
return data.movement ||
data.flame ||
(data.gas > gasThreshold) ||
(data.temperature > tempThreshold);
}
function sendData(data) {
const client = photon.TCPClient();
client.connect(host, port);
if(!client.connected()) {
photon.log.error(`Could not connect to ${host}, discarding data.`);
return;
}
client.write(JSON.stringify(data) + '\n');
client.stop();
}
function sendEvent(event, data) {
try {
const datastr = JSON.stringify(data);
photon.log.trace(`Sending event ${event}, data: ${datastr}`);
photon.publish(event, datastr);
} catch(e) {
photon.log.error(`Could not publish event: ${e.toString()}`);
}
}
let data = {};
let timeSinceAlarmMs = 0;
const intervals = [];
export function startReports() {
// Check sensors as fast as possible for
// values outside the normal thresholds
intervals.push(
setInterval(() => {
timeSinceAlarmMs += 500;
try {
data = readSensors();
if(checkData(data)) {
photon.pin(photon.pin.D7, true);
if(timeSinceAlarmMs >= alarmWaitMs) {
sendEvent(eventAlarm, data);
sendData(data);
timeSinceAlarmMs = 0;
}
} else {
photon.pin(photon.pin.D7, false);
}
} catch(e) {
photon.log.error(e.toString());
}
}, 500)
);
// Send a snapshot every interval milliseconds
intervals.push(
setInterval(() => {
try {
sendEvent(eventReport, data);
sendData(data);
} catch(e) {
photon.log.error(e.toString());
}
}, interval)
);
}
export function stopReports() {
intervals.forEach(clearInterval);
}
export function getLastReport() {
return {
data: data,
timeSinceLastAlarmMs: timeSinceAlarmMs
};
}