Files
2026-10-14 01:05:36 -07:00

59 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// server.js – minimal Express + Socket.io + Redis subscriber
const http = require('http');
const express = require('express');
const { Server } = require('socket.io');
const { createClient } = require('redis');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
// ---------- 1. Settings ----------
const REDIS_URL = 'redis://0.0.0.0:6379'; // adjust if needed
const REDIS_CHANNEL = 'temp_hum'; // channel you subscribed to
// ---------- 2. Serve static files ----------
app.use(express.static('public')); // public contains index.php, src/… etc.
// ---------- 3. Redis subscriber ----------
const redisClient = createClient({ url: REDIS_URL });
redisClient.on('error', err => console.error('Redis error:', err));
async function startRedis() {
await redisClient.connect();
const sub = redisClient.duplicate();
await sub.connect();
// Helper: forward a Redis message to all Socket.io clients
const forward = (msg) => {
try {
const payload = JSON.parse(msg);
io.emit('temp_hum', payload); // event name matches the JS listener
} catch (e) {
console.error('Failed to parse Redis message:', e);
}
};
await sub.subscribe(REDIS_CHANNEL, forward);
console.log(`Subscribed to Redis channel "${REDIS_CHANNEL}"`);
}
startRedis().catch(console.error);
// ---------- 4. Socket.io ----------
io.on('connection', socket => {
console.log('Socket.io client connected:', socket.id);
// Optionally send the most recent snapshot
// (If you keep a cache, emit it here)
socket.on('disconnect', () => {
console.log('Socket.io client disconnected:', socket.id);
});
});
// ---------- 5. Start HTTP server ----------
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Dashboard server listening on http://localhost:${PORT}`);
});