// 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}`); });