-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
100 lines (76 loc) · 2.38 KB
/
Copy pathserver.js
File metadata and controls
100 lines (76 loc) · 2.38 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
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
import express from "express";
import http from "http";
import { Server } from "socket.io";
import Bme280 from "bme280";
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// change port here
const PORT = process.env.PORT || 3000;
const DAY_MS = 24 * 60 * 60 * 1000;
const HALF_DAY_MS = 12 * 60 * 60 * 1000;
app.use(express.static("public"));
// store history in memory
let history = [];
let latestData = {
temperature: null,
humidity: null,
pressure: null,
updated_at: null,
stats12h: null,
stats24h: null
};
app.get("/json", (req, res) => {
res.json(latestData);
});
function getStats(data) {
return {
tempHigh: data.length ? Math.max(...data.map(x => x.temperature)) : null,
tempLow: data.length ? Math.min(...data.map(x => x.temperature)) : null,
humHigh: data.length ? Math.max(...data.map(x => x.humidity)) : null,
humLow: data.length ? Math.min(...data.map(x => x.humidity)) : null,
pressHigh: data.length ? Math.max(...data.map(x => x.pressure)) : null,
pressLow: data.length ? Math.min(...data.map(x => x.pressure)) : null
};
}
(async () => {
try {
const bme280 = await Bme280.open({
i2cBusNumber: 1,
i2cAddress: 0x76
});
console.log("BME280 initialised");
setInterval(async () => {
try {
const reading = await bme280.read();
const now = Date.now();
const sample = {
temperature: Number(reading.temperature.toFixed(2)),
humidity: Number(reading.humidity.toFixed(2)),
pressure: Number(reading.pressure.toFixed(2)),
timestamp: now
};
history.push(sample);
history = history.filter(x => now - x.timestamp < DAY_MS);
const history12 = history.filter(x => now - x.timestamp < HALF_DAY_MS);
const history24 = history;
latestData = {
temperature: sample.temperature,
humidity: sample.humidity,
pressure: sample.pressure,
updated_at: now,
stats12h: getStats(history12),
stats24h: getStats(history24)
};
io.emit("sensorData", latestData);
} catch (err) {
console.error("Sensor read failed:", err);
}
}, 1000);
} catch (err) {
console.error("BME280 init failed:", err);
}
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
})();