Initial — Node.js IoT Dashboard with Chart.js
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
const express = require("express");
|
||||
const { createClient } = require("redis");
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const REDIS_HOST = process.env.REDIS_HOST || "127.0.0.1";
|
||||
const REDIS_PORT = parseInt(process.env.REDIS_PORT || "6379");
|
||||
const REDIS_PASSWORD = process.env.REDIS_PASSWORD || undefined;
|
||||
|
||||
const app = express();
|
||||
app.use(express.static("public"));
|
||||
|
||||
const redis = createClient({
|
||||
socket: { host: REDIS_HOST, port: REDIS_PORT },
|
||||
password: REDIS_PASSWORD,
|
||||
});
|
||||
|
||||
redis.on("error", (err) => console.error("Redis error:", err.message));
|
||||
|
||||
async function start() {
|
||||
await redis.connect();
|
||||
console.log("Redis connected");
|
||||
|
||||
// API: latest sensor values
|
||||
app.get("/api/latest", async (req, res) => {
|
||||
try {
|
||||
const data = await redis.hGetAll("iot:latest");
|
||||
const items = Object.entries(data).map(([id, json]) => ({
|
||||
sensor_id: id,
|
||||
...JSON.parse(json),
|
||||
}));
|
||||
res.json(items);
|
||||
} catch (e) {
|
||||
res.json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// API: counters by device type
|
||||
app.get("/api/counters", async (req, res) => {
|
||||
try {
|
||||
const data = await redis.hGetAll("iot:counters");
|
||||
res.json(data);
|
||||
} catch (e) {
|
||||
res.json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// API: recent events
|
||||
app.get("/api/recent", async (req, res) => {
|
||||
try {
|
||||
const items = await redis.zRange("iot:recent", 0, 49, { REV: true });
|
||||
res.json(items.map(JSON.parse));
|
||||
} catch (e) {
|
||||
res.json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get("/", (req, res) => {
|
||||
res.send("IoT Dashboard OK");
|
||||
});
|
||||
|
||||
app.listen(PORT, () => console.log(`Dashboard on port ${PORT}`));
|
||||
}
|
||||
|
||||
start();
|
||||
Reference in New Issue
Block a user