const express = require("express"); const http = require("http"); const mqtt = require("mqtt"); const mysql = require("mysql"); const path = require("node:path"); const app = express(); app.use(express.json()); const client = mqtt.connect("mqtt://mqtt/", { port: 1883, protocol: "mqtt", clientId: "unidite_traitement", username: "student", password: "ensibs" }); client.once("error", (err) => { console.error("MQTT connection error:", err); }); http.get("http://192.168.4.1/", (cameraRes) => { app.get("/api/video", (req, res) => { res.writeHead(200, { "Content-Type": "multipart/x-mixed-replace; boundary=123456789000000000000987654321" }); cameraRes.on("data", (chunk) => { var string = chunk.toString(); res.write(chunk); }); cameraRes.on("end", () => res.end()); }); }); app.post("/api/alert", (req, res) => { const { sensor_id, level, text } = req.body; const connection = mysql.createConnection({ host: "mysql", user: "root", password: "IloveSachAwAmama69", database: "sachamama" }); connection.connect((err) => { if (err) { console.error("Error connecting to MySQL:", err); return res.status(500).json({ error: "Database connection failed" }); } }); const query = "INSERT INTO alerts (sensor_id, time, level, text) VALUES (?, ?, ?, ?)"; const values = [ sensor_id, new Date().toISOString().slice(0, 19).replace("T", " "), level, text ]; connection.query(query, values, (err, results) => { if (err) { console.error("Error inserting alert into database:", err); return res.status(500).json({ error: "Database insertion failed" }); } }); client.publish("alert", "alert", { qos: 1 }, (err) => { if (err) { console.error("Error publishing alert:", err); return res.status(500).json({ error: "Failed to send alert" }); } }); res.status(200).json({ message: "Alert sent successfully" }); }); app.use(express.static("public")); app.listen(3000, () => console.log("Server running on http://localhost:3000"));