How rahad0islam/iot_preli works
1. High-level shape
This repo is a single-tenant office IoT monitor split into two deployable apps: a Node.js/TypeScript backend and a Vite/React frontend. The backend is the system of record; the frontend is a live dashboard that mirrors backend state over HTTP plus Socket.IO.
2. Backend as the source of truth
All device, alert, and office-state data lives in a LowDB JSON file under back-end/src/database. The backend owns state mutations, calculates derived usage values, and emits realtime events after writes. No other subsystem writes directly to persistence.
3. Core backend boundaries
The backend is organized by feature modules under src/modules:
- devices manages list/toggle/grouping of the 15 devices
- usage computes total and per-room power plus history
- alerts scans for rule violations and stores alerts
- office exposes office-hours configuration
- simulator generates synthetic device toggles
- discord connects to Discord and replies to commands
These modules are wired together through shared database and socket services, not through the frontend.
4. Realtime update path
The main live data flow is: device state changes in the backend → backend updates LowDB → backend emits Socket.IO events (device_updated, usage_updated, alert_triggered) → frontend subscribers update their cached query state and rerender. This is the key boundary that keeps the dashboard live without refresh.
5. Frontend architecture
The frontend is a client-only React app with routes for dashboard, room view, alerts, and about. Data access is split into api/ clients, hooks/ for resource loading and mutations, and contexts/SocketContext.tsx for the single Socket.IO connection. Components such as device cards, room cards, charts, and summary panels are presentation-only and consume backend-derived state.
6. HTTP API boundary
The frontend and external callers use the Express REST API for initial loads and explicit actions. Main endpoints are grouped by resource: /api/devices, /api/rooms, /api/usage, /api/alerts, and /api/office. The backend also exposes /health and serves a static landing page from src/public/index.html.
7. Alert subsystem
The alert engine is backend-only and runs on a timer. It checks every device against two independent rules: after-hours ON and continuous runtime beyond a threshold. Alerts are deduplicated per device using flags stored with each device record, then persisted and broadcast over Socket.IO. Clearing or toggling a device OFF resets those flags so the alert can fire again later.
8. Simulator and event source
In development and local demo mode, simulator.service.ts acts as the synthetic device source. It flips 1–2 devices every 10–15 seconds, simulating what real hardware might do. That simulator exercises the same device-update path as manual REST toggles, so it drives usage recomputation, alerts, and websocket fan-out exactly like a real source.
9. Discord integration
The backend also embeds a Discord bot. It listens for !status, !room <name>, and !usage, builds a snapshot from the database, and attempts a Gemini-generated reply first. If Gemini is unavailable or unconfigured, it falls back to deterministic rule-based text. The same bot also posts proactive alert notifications to a configured alert channel.
10. Derived data flow
Usage is not stored as a primary input; it is derived from device state. The usage module aggregates wattage by room and office-wide totals, then emits updated usage snapshots. The frontend charts and power widgets depend on these derived values rather than recomputing independently.
11. Configuration and deployment surface
Runtime behavior is controlled almost entirely by environment variables. Backend config covers office hours, simulator cadence, alert thresholds, persistence file location, Discord credentials, Gemini credentials, logging, and CORS. Frontend config only points the browser at the backend API and Socket.IO endpoint. This makes the backend the main operational boundary.
12. Important architectural constraint
There is no auth layer in the repo. The system is intentionally local-first, so any client that can reach the backend can read state, toggle devices, and clear alerts. For diagrams, this should be treated as a deliberate trust-boundary decision rather than an omission in one subsystem.
13. Operational tooling
The repo includes a standalone backend script, scripts/verify-alerts.ts, used to validate alert behavior without running the full app. That makes the alert engine a testable unit separate from the HTTP server and Discord bot, which is useful when diagramming subsystem responsibilities.
14. What to emphasize in a diagram
The most important boxes are: LowDB persistence, Devices/Usage/Alerts backend services, Socket.IO realtime channel, React dashboard, Discord bot, and Simulator. The critical arrows are: simulator or UI toggle into backend state, backend state into LowDB, backend events out to frontend, and backend snapshots out to Discord/Gemini.
Main entry points: app.ts App · alert.service.ts Alerts · database.service.ts LowDB · http.ts API Clients
Components 18
Backend
Node.js/TypeScript server, persistence, realtime, and feature modules.
- Server · Starts the HTTP API, middleware, routes, and realtime wiring.
back-end/src/server.ts - App · Composes middleware, routes, static assets, and error handling.
back-end/src/app.ts - Config · Loads environment-driven settings for persistence, alerts, Discord, simulator, and CORS.
back-end/src/config/config.ts - LowDB · Single source of truth for devices, alerts, office state, and derived snapshots.
back-end/src/database/database.service.ts - Socket.IO · Broadcasts device, usage, and alert events to connected clients.
back-end/src/socket/socket.service.ts - Devices · Reads and mutates device state, toggles, grouping, and validation.
back-end/src/modules/devices/device.service.ts - Usage · Derives total and per-room power plus usage history from device state.
back-end/src/modules/usage/usage.service.ts - Alerts · Evaluates rule violations, persists alert records, and manages alert lifecycle.
back-end/src/modules/alerts/alert.service.ts - Office · Exposes office-hours configuration and related office state.
back-end/src/modules/office/office.service.ts - Simulator · Generates periodic device toggles for demo and development flows.
back-end/src/modules/simulator/simulator.service.ts - Discord Bot · Answers commands from Discord and posts alert notifications.
back-end/src/modules/discord/discord.service.ts - Gemini · Generates optional conversational responses for Discord commands.
back-end/src/modules/discord/gemini.service.ts - Alert Check · Standalone script for validating alert behavior without the full app.
back-end/scripts/verify-alerts.ts
Frontend
Vite/React client dashboard and its data-access layer.
- React App · Client-side dashboard shell and route composition.
front-end/src/App.tsx - Socket Context · Maintains the single Socket.IO connection for live updates.
front-end/src/contexts/SocketContext.tsx - API Clients · HTTP clients for devices, alerts, and usage endpoints.
front-end/src/api/http.ts - Query Hooks · Resource loading and mutations for dashboard interactions.
front-end/src/hooks/useDevices.ts - Views · Dashboard, room, alerts, and about pages plus visual widgets.
front-end/src/pages/DashboardPage.tsx
Connections 27
- Server → App: bootstraps · Main entry initializes the Express application.
- App → Config: reads · App wiring depends on runtime configuration.
- App → LowDB: uses · Routes and services persist through the shared database service.
- App → Socket.IO: publishes · HTTP mutations fan out to realtime subscribers.
- App → Devices: routes · Device endpoints are mounted through the feature module.
- App → Usage: routes · Usage endpoints expose derived power snapshots.
- App → Alerts: routes · Alert endpoints expose and manage alert state.
- App → Office: routes · Office configuration endpoints are mounted here.
- Devices → LowDB: writes · Device toggles and grouping changes update the source of truth.
- Usage → LowDB: reads · Usage is computed from persisted device state.
- Alerts → LowDB: reads/writes · Alert scans read device state and persist alert records.
- Alerts → Socket.IO: emits · Triggered alerts are broadcast to clients and integrations.
- Simulator → Devices: drives · Synthetic toggles enter the same device-update path as manual actions.
- Simulator → LowDB: updates · Generated device changes are persisted through backend state flow.
- Discord Bot → LowDB: snapshots · Command replies are built from the current database snapshot.
- Discord Bot → Gemini: falls back to · LLM responses are attempted first, then deterministic output is used.
- Discord Bot → Alerts: notifies · Proactive alert messages are posted to Discord channels.
- Alert Check → Alerts: checks · Standalone script exercises alert behavior outside the server.
- React App → Socket Context: uses · The SPA consumes one shared realtime connection.
- React App → API Clients: loads data · Pages and hooks fetch initial state and perform mutations over HTTP.
- React App → Query Hooks: renders via · UI state is driven through resource hooks.
- Socket Context → Socket.IO: connects to · Frontend subscribes to backend realtime events.
- API Clients → Devices: requests · Device list and toggle actions go through REST endpoints.
- API Clients → Usage: requests · Power summaries and history are fetched from the backend.
- API Clients → Alerts: requests · Alert lists and clear actions use REST endpoints.
- Query Hooks → Socket Context: subscribes · Hooks refresh cached state when realtime events arrive.
- Views → Query Hooks: consumes · Pages and widgets render derived data from hooks.