# rahad0islam/iot_preli architecture

> Architecture diagram of the GitHub repository rahad0islam/iot_preli, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-04). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/rahad0islam/iot_preli
- Repository: https://github.com/rahad0islam/iot_preli

## Overview

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: [`back-end/src/app.ts`](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/app.ts) (App), [`back-end/src/modules/alerts/alert.service.ts`](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/alerts/alert.service.ts) (Alerts), [`back-end/src/database/database.service.ts`](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/database/database.service.ts) (LowDB), [`front-end/src/api/http.ts`](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/api/http.ts) (API Clients)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_backend["Backend"]
  node_server["Server<br/>app bootstrap<br/>[server.ts]"]
  node_app["App<br/>[app.ts]"]
  node_config["Config<br/>[config.ts]"]
  node_db[("LowDB<br/>json store")]
  node_socket(("Socket.IO<br/>realtime hub<br/>[socket.service.ts]"))
  node_devices["Devices<br/>feature module<br/>[device.service.ts]"]
  node_usage["Usage<br/>feature module<br/>[usage.service.ts]"]
  node_alerts["Alerts<br/>feature module<br/>[alert.service.ts]"]
  node_office["Office<br/>feature module<br/>[office.service.ts]"]
  node_simulator{{"Simulator<br/>synthetic source"}}
  node_discord["Discord Bot<br/>integration<br/>[discord.service.ts]"]
  node_gemini["Gemini<br/>llm fallback<br/>[gemini.service.ts]"]
  node_verify["Alert Check<br/>ops script<br/>[verify-alerts.ts]"]
end

subgraph group_frontend["Frontend"]
  node_client["React App<br/>spa shell<br/>[App.tsx]"]
  node_socketctx(("Socket Context<br/>client realtime<br/>[SocketContext.tsx]"))
  node_apis["API Clients<br/>client data layer<br/>[http.ts]"]
  node_hooks["Query Hooks<br/>client state<br/>[useDevices.ts]"]
  node_views["Views<br/>presentation<br/>[DashboardPage.tsx]"]
end

node_server -->|"bootstraps"| node_app
node_app -->|"reads"| node_config
node_app -->|"uses"| node_db
node_app -->|"publishes"| node_socket
node_app -->|"routes"| node_devices
node_app -->|"routes"| node_usage
node_app -->|"routes"| node_alerts
node_app -->|"routes"| node_office
node_devices -->|"writes"| node_db
node_usage -->|"reads"| node_db
node_alerts -->|"reads/writes"| node_db
node_alerts -->|"emits"| node_socket
node_simulator -->|"drives"| node_devices
node_simulator -->|"updates"| node_db
node_discord -->|"snapshots"| node_db
node_discord -->|"falls back to"| node_gemini
node_discord -->|"notifies"| node_alerts
node_verify -->|"checks"| node_alerts
node_client -->|"uses"| node_socketctx
node_client -->|"loads data"| node_apis
node_client -->|"renders via"| node_hooks
node_socketctx -->|"connects to"| node_socket
node_apis -->|"requests"| node_devices
node_apis -->|"requests"| node_usage
node_apis -->|"requests"| node_alerts
node_hooks -->|"subscribes"| node_socketctx
node_views -->|"consumes"| node_hooks

click node_server "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/server.ts"
click node_app "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/app.ts"
click node_config "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/config/config.ts"
click node_db "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/database/database.service.ts"
click node_socket "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/socket/socket.service.ts"
click node_devices "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/devices/device.service.ts"
click node_usage "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/usage/usage.service.ts"
click node_alerts "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/alerts/alert.service.ts"
click node_office "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/office/office.service.ts"
click node_simulator "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/simulator/simulator.service.ts"
click node_discord "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/discord/discord.service.ts"
click node_gemini "https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/discord/gemini.service.ts"
click node_verify "https://github.com/rahad0islam/iot_preli/blob/main/back-end/scripts/verify-alerts.ts"
click node_client "https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/App.tsx"
click node_socketctx "https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/contexts/SocketContext.tsx"
click node_apis "https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/api/http.ts"
click node_hooks "https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/hooks/useDevices.ts"
click node_views "https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/pages/DashboardPage.tsx"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_server,node_app,node_config,node_db,node_socket,node_devices,node_usage,node_alerts,node_office,node_simulator,node_discord,node_gemini,node_verify toneBlue
class node_client,node_socketctx,node_apis,node_hooks,node_views toneAmber
```

## Components

### Backend

Node.js/TypeScript server, persistence, realtime, and feature modules.

- [Server](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/server.ts): app bootstrap · Starts the HTTP API, middleware, routes, and realtime wiring. · `back-end/src/server.ts`
- [App](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/app.ts): express app · Composes middleware, routes, static assets, and error handling. · `back-end/src/app.ts`
- [Config](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/config/config.ts): runtime config · Loads environment-driven settings for persistence, alerts, Discord, simulator, and CORS. · `back-end/src/config/config.ts`
- [LowDB](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/database/database.service.ts): json store · Single source of truth for devices, alerts, office state, and derived snapshots. · `back-end/src/database/database.service.ts`
- [Socket.IO](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/socket/socket.service.ts): realtime hub · Broadcasts device, usage, and alert events to connected clients. · `back-end/src/socket/socket.service.ts`
- [Devices](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/devices/device.service.ts): feature module · Reads and mutates device state, toggles, grouping, and validation. · `back-end/src/modules/devices/device.service.ts`
- [Usage](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/usage/usage.service.ts): feature module · Derives total and per-room power plus usage history from device state. · `back-end/src/modules/usage/usage.service.ts`
- [Alerts](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/alerts/alert.service.ts): feature module · Evaluates rule violations, persists alert records, and manages alert lifecycle. · `back-end/src/modules/alerts/alert.service.ts`
- [Office](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/office/office.service.ts): feature module · Exposes office-hours configuration and related office state. · `back-end/src/modules/office/office.service.ts`
- [Simulator](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/simulator/simulator.service.ts): synthetic source · Generates periodic device toggles for demo and development flows. · `back-end/src/modules/simulator/simulator.service.ts`
- [Discord Bot](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/discord/discord.service.ts): integration · Answers commands from Discord and posts alert notifications. · `back-end/src/modules/discord/discord.service.ts`
- [Gemini](https://github.com/rahad0islam/iot_preli/blob/main/back-end/src/modules/discord/gemini.service.ts): llm fallback · Generates optional conversational responses for Discord commands. · `back-end/src/modules/discord/gemini.service.ts`
- [Alert Check](https://github.com/rahad0islam/iot_preli/blob/main/back-end/scripts/verify-alerts.ts): ops script · 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](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/App.tsx): spa shell · Client-side dashboard shell and route composition. · `front-end/src/App.tsx`
- [Socket Context](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/contexts/SocketContext.tsx): client realtime · Maintains the single Socket.IO connection for live updates. · `front-end/src/contexts/SocketContext.tsx`
- [API Clients](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/api/http.ts): client data layer · HTTP clients for devices, alerts, and usage endpoints. · `front-end/src/api/http.ts`
- [Query Hooks](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/hooks/useDevices.ts): client state · Resource loading and mutations for dashboard interactions. · `front-end/src/hooks/useDevices.ts`
- [Views](https://github.com/rahad0islam/iot_preli/blob/main/front-end/src/pages/DashboardPage.tsx): presentation · Dashboard, room, alerts, and about pages plus visual widgets. · `front-end/src/pages/DashboardPage.tsx`

## Connections

- 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.
