Skip to content

Commit 1c79406

Browse files
Merge pull request #54 from GDSC-ZHCET/avyukt
changes
2 parents 246d259 + 739993a commit 1c79406

File tree

4 files changed

+45
-96
lines changed

4 files changed

+45
-96
lines changed

client/src/app/dashboard/page.tsx

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ export default function DashboardPage() {
286286
const [deviceStatus, setDeviceStatus] = useState<boolean>(false); // Device status (on/off)
287287
const [ws, setWs] = useState<WebSocket | null>(null); // WebSocket instance
288288
const [timeframe, setTimeframe] = useState("real-time"); // Default to real-time (last 10 readings)
289+
const [espID, setEspID] = useState("");
289290

290291
// Initialize the device document in Firestore if it doesn't exist
291292
useEffect(() => {
@@ -448,6 +449,8 @@ export default function DashboardPage() {
448449
ws.onmessage = (event) => {
449450
const newData = JSON.parse(event.data);
450451

452+
if (newData.device_id) setEspID(newData.device_id);
453+
451454
// Add timestamp to the data if not present
452455
newData.timestamp = newData.timestamp || new Date().toISOString();
453456

@@ -460,22 +463,28 @@ export default function DashboardPage() {
460463

461464
// Update total power consumed (only if power is valid)
462465
setTotalPowerConsumed((prevTotal) => {
463-
// Make sure we're adding a valid number
464466
const powerIncrement = newData.power / 1000 || 0;
465467
const newTotal = (prevTotal || 0) + powerIncrement;
466-
return isNaN(newTotal) ? 0 : newTotal; // Ensure we never return NaN
468+
return isNaN(newTotal) ? 0 : newTotal;
467469
});
468470

469-
// Update device status
471+
// Update device status from WebSocket (primary source of truth)
470472
if (newData.status !== undefined) {
471473
setDeviceStatus(newData.status);
474+
475+
// Sync Firestore with the WebSocket status
476+
const deviceDocRef = doc(db, "devices", "ESP32_TEST_DEVICE");
477+
updateDoc(deviceDocRef, {
478+
status: newData.status ? "on" : "off",
479+
last_updated: new Date().toISOString(),
480+
});
472481
}
473482

474-
// Update state for UI (keep only the last 10 readings)
483+
// Update sensor data
475484
setSensorData((prevData) => {
476485
const updatedData = [...prevData, newData];
477486
if (updatedData.length > maxDataPoints) {
478-
return updatedData.slice(-maxDataPoints); // Keep only the last 10 readings
487+
return updatedData.slice(-maxDataPoints);
479488
}
480489
return updatedData;
481490
});
@@ -498,22 +507,40 @@ export default function DashboardPage() {
498507
};
499508
}, []);
500509

501-
// Handle device status toggle
502510
const handleToggleDeviceStatus = async (checked: boolean) => {
503-
const deviceDocRef = doc(db, "devices", "ESP32_TEST_DEVICE"); // Replace with your device ID
504-
await updateDoc(deviceDocRef, {
505-
status: checked ? "on" : "off",
506-
last_updated: new Date().toISOString(),
507-
});
508-
509-
// Send WebSocket message to ESP32
510-
if (ws) {
511-
ws.send(
512-
JSON.stringify({ device_id: "ESP32_TEST_DEVICE", status: checked })
513-
);
511+
if (!ws) {
512+
console.error("WebSocket is not connected.");
513+
return;
514514
}
515515

516+
// Optimistically update the UI
516517
setDeviceStatus(checked);
518+
519+
// Send the toggle command via WebSocket
520+
try {
521+
const response = await fetch(
522+
`https://voltsense-server-110999938896.asia-south1.run.app/api/send-command`,
523+
{
524+
method: "POST",
525+
headers: {
526+
"Content-Type": "application/json",
527+
},
528+
body: JSON.stringify({
529+
device_id: espID,
530+
command: "toggle_relay",
531+
}),
532+
}
533+
);
534+
535+
if (!response.ok) {
536+
throw new Error("Failed to send command");
537+
}
538+
} catch (error) {
539+
console.error("Error toggling device:", error);
540+
541+
// Revert the UI state if the command fails
542+
setDeviceStatus(!checked);
543+
}
517544
};
518545

519546
// For the currentPower calculation

client/src/app/metrics/page.tsx

Lines changed: 0 additions & 40 deletions
This file was deleted.

client/src/components/sidebar.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ export function Sidebar({ className }: SidebarProps) {
7878
image?: string;
7979
} | null>(null);
8080

81-
const voltageThreshold = 235;
81+
const voltageThreshold = 300;
8282

8383
useEffect(() => {
8484
const auth = getAuth();

server/src/app.js

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -38,44 +38,6 @@ const server = http.createServer(expressApp);
3838
// Create a WebSocket server
3939
const wss = new WebSocket.Server({ server });
4040

41-
// WebSocket connection handler
42-
// wss.on("connection", (ws) => {
43-
// console.log("Client connected");
44-
45-
// ws.on("message", async (message) => {
46-
// console.log(`Received raw message: ${message}`);
47-
48-
// try {
49-
// // Parse the message as JSON
50-
// const newData = JSON.parse(message);
51-
52-
// // Add timestamp to the data
53-
// newData.timestamp = new Date().toISOString();
54-
55-
// // Store data in Firestore
56-
// try {
57-
// const docRef = await addDoc(collection(db, "sensorData"), newData);
58-
// console.log("Data stored in Firestore with ID:", docRef.id);
59-
// } catch (error) {
60-
// console.error("Error storing data in Firestore:", error);
61-
// }
62-
63-
// // Broadcast the message to all connected WebSocket clients
64-
// wss.clients.forEach((client) => {
65-
// if (client !== ws && client.readyState === WebSocket.OPEN) {
66-
// client.send(JSON.stringify(newData));
67-
// }
68-
// });
69-
// } catch (error) {
70-
// console.error("Invalid JSON received:", error);
71-
// }
72-
// });
73-
74-
// ws.on("close", () => {
75-
// console.log("Client disconnected");
76-
// });
77-
// });
78-
7941
wss.on("connection", (ws) => {
8042
console.log("Client connected via WebSocket");
8143

0 commit comments

Comments
 (0)