const http = require('http'); const fs = require('fs'); const { MongoClient } = require('mongodb'); const path = require('path'); const PORT = 3002; const MONGO_URI = 'mongodb://localhost:27017'; let db; async function connectDB() { const client = new MongoClient(MONGO_URI); await client.connect(); db = client.db('oktopus'); console.log('Connected to MongoDB'); } const server = http.createServer(async (req, res) => { if (req.url === '/api/monitor/devices') { try { const devices = await db.collection('devices').find({}).toArray(); res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(devices)); } catch (e) { res.writeHead(500); res.end(JSON.stringify({ error: e.message })); } } else { // Serve static files let filePath = req.url === '/' ? '/index.html' : req.url; filePath = path.join(__dirname, filePath); try { const content = fs.readFileSync(filePath); const ext = path.extname(filePath); const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'application/javascript' }; res.writeHead(200, { 'Content-Type': types[ext] || 'text/plain' }); res.end(content); } catch { res.writeHead(404); res.end('Not found'); } } }); connectDB().then(() => { server.listen(PORT, () => console.log(`Device Monitor: http://localhost:${PORT}`)); });