How normalsuperiordeldistritodebarranquilla/weather-station works
1. What this repository is
- M1K1U is an IoT monitoring platform for a weather station.
- It has three main runtime parts: an ESP32/Arduino telemetry source, a FastAPI backend, and a React frontend.
- The backend stores telemetry locally in SQLite by default, with PostgreSQL supported through DATABASE_URL.
2. Core system boundary
- The main architectural split is between telemetry ingestion and user-facing visualization.
- The ESP32 pushes readings into the backend through a protected REST endpoint.
- The frontend never talks to the device directly; it only consumes backend APIs.
3. Backend structure
- The backend is organized in classic layers:
- routers expose HTTP endpoints.
- services contain business logic for auth, sensor data, alerts, seeding, and diagnostics.
- models define persistence entities.
- schemas define API contracts.
- core holds config, security, and metric registry logic.
- main.py is the application entrypoint and database.py manages the SQLAlchemy connection/session.
4. Telemetry ingestion flow
- The ESP32 sends JSON readings to POST /api/sensor-data.
- This endpoint requires X-API-Key, making device ingestion separate from human authentication.
- Incoming payloads are normalized against the master metric contract, then persisted as sensor records.
- If the timestamp is missing, the backend generates it; if it arrives without timezone, it is normalized to UTC.
5. Telemetry read path
- The frontend reads from authenticated endpoints such as:
- latest reading
- historical series
- station statistics
- sensor detail views
- current alerts
- The public landing page uses a public endpoint that can return real data or an empty-state payload when no telemetry exists yet.
- This creates a clean split between public marketing-style views and authenticated monitoring views.
6. Authentication and session boundary
- User auth is handled with JWT stored in an HttpOnly cookie.
- Login, logout, and session introspection are exposed through /api/auth/*.
- Because the cookie is HttpOnly, the browser UI relies on backend session state rather than reading tokens directly.
- The default admin user is auto-seeded, which is why the repo can start without manual user setup.
7. Alerts and diagnostics
- Alert generation is a backend service that derives operational and environmental warnings from the latest telemetry plus recent history.
- Alerts include station silence, extreme temperature, freezing risk, pressure drops, strong wind, rain detection, and sensor flatline/missing-field conditions.
- A separate sensor diagnostics endpoint computes per-metric health/status, which supports the “detail by sensor” UI.
8. Persistence and schema management
- SQLite is the default embedded datastore and lives inside the backend project tree.
- PostgreSQL is supported for containerized deployment.
- Alembic is used for schema evolution, with migrations already present for the initial schema and later metric additions.
- The seed layer is intentionally small: it only creates the initial admin user, not sample telemetry.
9. Frontend structure
- The frontend is a Vite + React + TypeScript app styled with Tailwind CSS.
- It is organized around:
- pages for top-level screens
- components for reusable dashboard pieces
- services for API calls
- hooks for auth, alerts, and public landing state
- layouts for authenticated shell structure
- API calls use a shared HTTP client configured for cookie-based auth and the backend base URL.
10. Frontend UX boundaries
- Public pages cover landing, about/project information, technologies, and general presentation.
- Protected pages cover dashboard, console home, charts, history, live status, sensor detail, location, and alerts.
- ProtectedRoute and AuthRedirectRoute enforce navigation rules based on session state.
- The app shell components (Navbar, Sidebar, Footer, alert panels) frame the authenticated monitoring experience.
11. Shared metric contract
- A key repo-specific design choice is the master metric contract aligned with arduino.ino.
- The active fields are the same ones the backend and frontend understand: temperature, pressure, altitude, luminosity, rain analog/digital, and wind speed.
- Backend metric registry logic and frontend metric configuration keep the UI and API aligned with the ESP32 payload format.
- The aliases in the backend show that the system tolerates alternate field names from the device while normalizing to canonical keys.
12. Deployment model
- The project supports local development with separate frontend and backend processes.
- Docker Compose can bring up PostgreSQL plus the FastAPI backend together.
- CORS and VITE_API_URL are important integration boundaries because the frontend and backend are intentionally decoupled services even in local dev.
Main entry points: main.py App entry · App.tsx Routes · http.ts HTTP client · sensor_data_service.py Telemetry service
Components 34
ESP32 device
Telemetry source and shared metric contract
- Arduino sketch · ESP32 weather-station firmware and master metric contract
arduino.ino
FastAPI backend
Ingestion, auth, persistence, and alerting
- App entry · FastAPI application setup and router wiring
backend/app/main.py - Config · Environment, CORS, and database/runtime configuration
backend/app/core/config.py - Security · API key and JWT cookie security helpers
backend/app/core/security.py - Metric registry · Canonical sensor fields and alias normalization
backend/app/core/metrics.py - Database · Engine and session management for SQLite or PostgreSQL
backend/app/database.py - Models · User and sensor-data entities
backend/app/models - Schemas · Request and response shapes for auth, telemetry, alerts, and sensor detail
backend/app/schemas - Auth router · Login, logout, and session introspection endpoints
backend/app/routers/auth.py - Sensor router · Protected telemetry ingestion endpoint for the device
backend/app/routers/sensor_data.py - Alerts router · Current alerts and alert-derived views
backend/app/routers/alerts.py - Sensors router · Latest, history, statistics, and sensor-detail endpoints
backend/app/routers/sensors.py - Auth service · User authentication and JWT session handling
backend/app/services/auth_service.py - Telemetry service · Normalize, validate, and persist incoming readings
backend/app/services/sensor_data_service.py - Alert service · Derive operational and environmental warnings from telemetry
backend/app/services/alerts_service.py - Diagnostics · Per-sensor health and status computation
backend/app/services/sensor_diagnostics_service.py - Seed service · Creates the initial admin user
backend/app/services/seed_service.py
React frontend
Public site and authenticated monitoring UI
- React entry · Vite/React application entrypoint
frontend/src/main.tsx - Routes · Top-level route map and page composition
frontend/src/App.tsx - HTTP client · Shared backend client with cookie-based auth and base URL
frontend/src/services/http.ts - Auth API · Login and session calls
frontend/src/services/authService.ts - Sensor API · Telemetry, history, and sensor-detail calls
frontend/src/services/sensorDataService.ts - Alerts API · Alert-fetching calls
frontend/src/services/alertsService.ts - Auth hook · Browser session state and auth flow
frontend/src/hooks/useAuth.tsx - Landing hook · Public landing-page data and empty-state handling
frontend/src/hooks/usePublicLanding.ts - Alerts hook · Alert state for dashboard panels
frontend/src/hooks/useAlerts.ts - App shell · Navbar, sidebar, footer, and monitoring shell
frontend/src/layouts/AppShell.tsx - Protected route · Blocks unauthenticated monitoring pages
frontend/src/components/ProtectedRoute.tsx - Auth redirect · Redirects logged-in users away from auth pages
frontend/src/components/AuthRedirectRoute.tsx - Public pages · Home, about, project info, and technologies pages
frontend/src/pages/HomePage.tsx - Auth pages · Login and session-aware entry pages
frontend/src/pages/LoginPage.tsx - Dashboard pages · Dashboard, console, charts, history, live status, location, alerts, and sensor detail
frontend/src/pages/DashboardPage.tsx
Deployment
Local and container startup
- Compose stack · Runs backend with PostgreSQL for containerized deployment
docker-compose.yml - Start/stop scripts · Local process orchestration helpers
scripts/start_m1k1u.ps1
Connections 47
- Arduino sketch → Sensor router: POST readings · ESP32 sends telemetry JSON to the protected ingestion endpoint
- Arduino sketch → Metric registry: metric contract · Firmware and backend share canonical sensor fields and aliases
- App entry → Config: loads config · Application bootstrap reads runtime settings
- App entry → Database: initializes db · Startup wires SQLAlchemy session and engine
- App entry → Auth router: mounts · Registers auth endpoints
- App entry → Sensor router: mounts · Registers telemetry ingestion endpoints
- App entry → Alerts router: mounts · Registers alert endpoints
- App entry → Sensors router: mounts · Registers sensor read endpoints
- App entry → Seed service: seeds admin · Bootstraps the default admin user
- Auth router → Auth service: uses · Auth endpoints delegate to auth business logic
- Sensor router → Security: api key · Ingestion requires X-API-Key protection
- Sensor router → Telemetry service: uses · Telemetry endpoint delegates normalization and persistence
- Alerts router → Alert service: uses · Alert views are derived by alert service
- Sensors router → Telemetry service: reads telemetry · Read endpoints query latest, history, and statistics
- Sensors router → Diagnostics: computes health · Sensor detail views include per-metric diagnostics
- Auth service → Security: signs sessions · Auth service issues and verifies JWT cookie sessions
- Telemetry service → Metric registry: normalizes fields · Telemetry is mapped to the master metric contract
- Telemetry service → Models: persists · Normalized readings are stored as sensor records
- Telemetry service → Database: writes/queries · Uses the database session for telemetry storage
- Alert service → Database: reads history · Alert rules inspect recent telemetry and latest readings
- Diagnostics → Database: queries status · Diagnostics compute per-sensor health from stored data
- Auth service → Models: users · User records back authentication
- Models → Schemas: serialized as · Models are exposed through API contracts
- React entry → Routes: renders · Bootstraps the application route tree
- Routes → Protected route: guards · Protects authenticated monitoring pages
- Routes → Auth redirect: guards · Redirects signed-in users away from auth pages
- Routes → App shell: wraps · Authenticated views use the shared shell
- Routes → Public pages: public screens · Home and informational pages
- Routes → Auth pages: auth screens · Login and session-related pages
- Routes → Dashboard pages: monitoring screens · Dashboard and operational views
- HTTP client → Auth router: session calls · Frontend auth requests target backend auth endpoints
- HTTP client → Sensors router: telemetry reads · Dashboard pages consume backend sensor APIs
- HTTP client → Alerts router: alert reads · Alert panels consume backend alert APIs
- Auth API → HTTP client: uses · Auth API is built on the shared HTTP client
- Sensor API → HTTP client: uses · Sensor data API is built on the shared HTTP client
- Alerts API → HTTP client: uses · Alerts API is built on the shared HTTP client
- Auth hook → Auth API: drives · Browser session state is managed through auth API calls
- Landing hook → Sensor API: reads public data · Landing content can show real telemetry or empty state
- Alerts hook → Alerts API: reads alerts · Dashboard alert state comes from the alerts API
- Public pages → Landing hook: state · Public pages use landing data hook
- Auth pages → Auth hook: session state · Auth pages rely on browser session state
- Dashboard pages → Alerts hook: alert state · Monitoring pages surface live alerts
- Dashboard pages → Sensor API: telemetry views · Charts, history, status, and sensor detail use telemetry APIs
- Compose stack → App entry: runs backend · Container deployment launches the FastAPI service
- Compose stack → Database: postgres · Compose provides the PostgreSQL-backed persistence option
- Start/stop scripts → App entry: start/stop · Local scripts manage backend runtime lifecycle
- Start/stop scripts → React entry: start/stop · Local scripts manage frontend runtime lifecycle