# alfredodompablo/monica architecture

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

- Interactive diagram: https://gitdiagram.com/alfredodompablo/monica
- Repository: https://github.com/alfredodompablo/monica

## Overview

1. **System boundary**
   MONICA is split into four main execution domains: a Next.js web application, a Python AI inference service, a PostgreSQL-backed data layer, and several PlatformIO-based firmware targets for IoT devices. The web app is the orchestration layer; the embedded devices and AI service are separate runtime boundaries.

2. **Web application core**
   The main product lives under `src/` and is built with Next.js App Router. It serves the public site, the dashboard, and the admin area. UI composition is mostly React components in `src/components`, with dashboard-specific pages under `src/app/dashboard` and admin login/settings screens under `src/app/admin`.

3. **API layer inside Next.js**
   Instead of a separate Node backend, the application exposes backend functionality through Next.js route handlers in `src/app/api/**`. These endpoints cover authentication, users, nodes, readings, sensor-readings, network logs/commands, and waste detections. This means the web app is both frontend and primary application server.

4. **Authentication and admin boundary**
   Authentication is handled by NextAuth through `src/app/api/auth/[...nextauth]/route.ts` and helper logic in `src/lib/auth.ts`. Admin-focused routes and components suggest RBAC-style separation between regular dashboard users and privileged operators. The `src/proxy.ts` file likely enforces request routing or auth checks at the app boundary.

5. **Data persistence layer**
   PostgreSQL is the system of record, accessed through Prisma (`src/lib/prisma.ts`, `src/prisma/schema.prisma`). The schema is migrated and seeded from `src/prisma/migrations`, `seed.ts`, and `seed_csv.ts`. Historical sensor data is preloaded from `src/prisma/datos_Cuauhtemoc.csv`, which means the app supports both live telemetry and backfilled datasets.

6. **IoT telemetry flow**
   Sensor and network data appear to originate from the firmware projects, then enter the web app through API endpoints such as `/api/sensor-readings`, `/api/nodes`, `/api/readings`, and network command/log routes. The presence of `lora_protocol.h` in the firmware folders indicates LoRa-based device communication, with a concentrator bridging field nodes to the application backend.

7. **Firmware subsystems**
   There are four separate embedded targets: `firmware`, `firmware_cam`, `firmware_cam_light`, and `firmware_concentrator`. This suggests distinct hardware roles: environmental sensing nodes, camera-enabled nodes, a lighter camera variant, and a concentrator/gateway. Shared protocol definitions live in `include/lora_protocol.h`, while secret placeholders indicate device-specific credentials are injected per build.

8. **AI inference pipeline**
   The AI service is isolated in `ai_service/` and runs as a Python FastAPI microservice. It ships with a trained model artifact at `ai_service/model/best.pt`, implying local inference rather than a remote model API. The README describes a YOLOv11-seg workflow for waste segmentation, so this service is responsible for processing images and returning detection results.

9. **Waste detection storage flow**
   Waste detection endpoints in the Next.js app connect the AI service and object storage. The documented flow is: client submits an image to `/api/waste-detections`, the app calls the AI service, and image artifacts are stored in MinIO/S3 via helpers in `src/lib/s3.ts`. Metadata stays in PostgreSQL, while the actual images are retrieved later through `/api/waste-detections/[id]/image`.

10. **Object storage boundary**
    MinIO is used as the S3-compatible object store for original images and derived assets. This keeps binary media out of PostgreSQL and allows the UI to fetch galleries and detection images independently from the metadata queries. The bucket name and endpoint are externalized through environment variables.

11. **UI and state management**
    The dashboard is organized around reusable domain components such as maps, charts, node tables, reading modals, gallery sections, and network managers. `src/contexts/NodeContext.tsx` and `src/components/Providers.tsx` indicate shared client-side state, especially for selected nodes and map-driven interactions. This is a presentation layer on top of the API and database.

12. **Operational scripts and support tooling**
    The repo includes seed/reset scripts, key generation utilities, and a small `scratch/monitor_nodes.py` helper for node monitoring. There is also an `openapi.json` in `public/`, which suggests the API is documented and probably consumed externally. Docker Compose is used for local infrastructure bootstrapping, while PM2 is used to run both the Python service and the Next.js app in production-style deployments.

13. **Architectural summary**
    The clearest diagram is: field devices and cameras feed telemetry and images into the system; the Next.js app exposes APIs and the operator UI; PostgreSQL stores relational state and history; MinIO stores binary media; the Python AI microservice processes images; and authentication gates admin and operational actions. The main integration points are HTTP between the web app and AI service, S3 between the web app and object storage, and LoRa/device protocols between firmware and the concentrator.

Main entry points: [`src/app/api`](https://github.com/alfredodompablo/monica/tree/main/src/app/api) (API routes), [`firmware_concentrator/src/main.cpp`](https://github.com/alfredodompablo/monica/blob/main/firmware_concentrator/src/main.cpp) (Concentrator), [`src/app`](https://github.com/alfredodompablo/monica/tree/main/src/app) (Web app), [`firmware/include/lora_protocol.h`](https://github.com/alfredodompablo/monica/blob/main/firmware/include/lora_protocol.h) (LoRa protocol)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_web["Next.js app"]
  node_next_app["Web app<br/>Next.js App Router"]
  node_dashboard_ui["Dashboard UI<br/>React views"]
  node_admin_ui["Admin UI<br/>operator screens"]
  node_api_routes["API routes<br/>HTTP handlers"]
  node_auth_layer["Auth layer<br/>NextAuth RBAC<br/>[auth.ts]"]
  node_shared_ui["UI components<br/>React components"]
  node_client_state["Node state<br/>React context<br/>[NodeContext.tsx]"]
end

subgraph group_data["Persistence"]
  node_db_layer[("Database layer<br/>Prisma/Postgres<br/>[prisma.ts]")]
  node_schema["Schema<br/>[schema.prisma]"]
  node_seed_pipeline["Seeds<br/>DB bootstrap<br/>[seed.ts]"]
  node_object_store[("Object storage<br/>S3/MinIO<br/>[s3.ts]")]
end

subgraph group_edge["IoT edge"]
  node_edge_firmware["Field firmware<br/>PlatformIO target<br/>[main.cpp]"]
  node_camera_firmware["Camera firmware<br/>PlatformIO target<br/>[main.cpp]"]
  node_light_camera_firmware["Light camera<br/>PlatformIO target<br/>[main.cpp]"]
  node_concentrator["Concentrator<br/>LoRa gateway<br/>[main.cpp]"]
  node_lora_proto["LoRa protocol<br/>shared headers<br/>[lora_protocol.h]"]
end

subgraph group_ai["AI service"]
  node_ai_service["AI service<br/>FastAPI inference<br/>[main.py]"]
  node_model_artifact["YOLO model<br/>weights artifact<br/>[best.pt]"]
end

subgraph group_ops["Operations"]
  node_ops_scripts["Ops scripts<br/>utilities<br/>[reset-and-seed.ts]"]
  node_compose["Compose stack<br/>local deploy<br/>[docker-compose.yml]"]
end

node_next_app -->|"renders"| node_dashboard_ui
node_next_app -->|"renders"| node_admin_ui
node_next_app -->|"hosts"| node_api_routes
node_dashboard_ui -->|"uses"| node_shared_ui
node_admin_ui -->|"uses"| node_shared_ui
node_shared_ui -->|"reads state"| node_client_state
node_api_routes -->|"guards"| node_auth_layer
node_api_routes -->|"queries"| node_db_layer
node_db_layer -->|"implements"| node_schema
node_seed_pipeline -->|"loads"| node_db_layer
node_api_routes -->|"stores media"| node_object_store
node_api_routes -->|"invokes"| node_ai_service
node_ai_service -->|"runs"| node_model_artifact
node_concentrator -->|"speaks"| node_lora_proto
node_edge_firmware -->|"speaks"| node_lora_proto
node_camera_firmware -->|"speaks"| node_lora_proto
node_light_camera_firmware -->|"speaks"| node_lora_proto
node_concentrator -->|"uploads telemetry"| node_api_routes
node_edge_firmware -->|"reports"| node_concentrator
node_camera_firmware -->|"reports"| node_concentrator
node_light_camera_firmware -->|"reports"| node_concentrator
node_ops_scripts -->|"runs"| node_seed_pipeline
node_compose -->|"starts"| node_next_app
node_compose -->|"starts"| node_ai_service

click node_next_app "https://github.com/alfredodompablo/monica/tree/main/src/app"
click node_dashboard_ui "https://github.com/alfredodompablo/monica/tree/main/src/app/dashboard"
click node_admin_ui "https://github.com/alfredodompablo/monica/tree/main/src/app/admin"
click node_api_routes "https://github.com/alfredodompablo/monica/tree/main/src/app/api"
click node_auth_layer "https://github.com/alfredodompablo/monica/blob/main/src/lib/auth.ts"
click node_shared_ui "https://github.com/alfredodompablo/monica/tree/main/src/components"
click node_client_state "https://github.com/alfredodompablo/monica/blob/main/src/contexts/NodeContext.tsx"
click node_db_layer "https://github.com/alfredodompablo/monica/blob/main/src/lib/prisma.ts"
click node_schema "https://github.com/alfredodompablo/monica/blob/main/src/prisma/schema.prisma"
click node_seed_pipeline "https://github.com/alfredodompablo/monica/blob/main/src/prisma/seed.ts"
click node_object_store "https://github.com/alfredodompablo/monica/blob/main/src/lib/s3.ts"
click node_edge_firmware "https://github.com/alfredodompablo/monica/blob/main/firmware/src/main.cpp"
click node_camera_firmware "https://github.com/alfredodompablo/monica/blob/main/firmware_cam/src/main.cpp"
click node_light_camera_firmware "https://github.com/alfredodompablo/monica/blob/main/firmware_cam_light/src/main.cpp"
click node_concentrator "https://github.com/alfredodompablo/monica/blob/main/firmware_concentrator/src/main.cpp"
click node_lora_proto "https://github.com/alfredodompablo/monica/blob/main/firmware/include/lora_protocol.h"
click node_ai_service "https://github.com/alfredodompablo/monica/blob/main/ai_service/main.py"
click node_model_artifact "https://github.com/alfredodompablo/monica/blob/main/ai_service/model/best.pt"
click node_ops_scripts "https://github.com/alfredodompablo/monica/blob/main/src/scripts/reset-and-seed.ts"
click node_compose "https://github.com/alfredodompablo/monica/blob/main/docker-compose.yml"

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_next_app,node_dashboard_ui,node_admin_ui,node_api_routes,node_auth_layer,node_shared_ui,node_client_state toneBlue
class node_db_layer,node_schema,node_seed_pipeline,node_object_store toneAmber
class node_edge_firmware,node_camera_firmware,node_light_camera_firmware,node_concentrator,node_lora_proto toneMint
class node_ai_service,node_model_artifact toneRose
class node_ops_scripts,node_compose toneIndigo
```

## Components

### Next.js app

Public site, dashboard, admin UI, and API routes

- [Web app](https://github.com/alfredodompablo/monica/tree/main/src/app): Next.js App Router · Main orchestration layer for UI and backend routes · `src/app`
- [Dashboard UI](https://github.com/alfredodompablo/monica/tree/main/src/app/dashboard): React views · Dashboard pages and shared presentation components · `src/app/dashboard`
- [Admin UI](https://github.com/alfredodompablo/monica/tree/main/src/app/admin): operator screens · Admin login and settings screens · `src/app/admin`
- [API routes](https://github.com/alfredodompablo/monica/tree/main/src/app/api): HTTP handlers · Application server endpoints for users, nodes, readings, network, and waste detections · `src/app/api`
- [Auth layer](https://github.com/alfredodompablo/monica/blob/main/src/lib/auth.ts): NextAuth RBAC · Authentication and request boundary helpers · `src/lib/auth.ts`
- [UI components](https://github.com/alfredodompablo/monica/tree/main/src/components): React components · Reusable dashboard, map, gallery, and network components · `src/components`
- [Node state](https://github.com/alfredodompablo/monica/blob/main/src/contexts/NodeContext.tsx): React context · Shared selection and interaction state for the dashboard · `src/contexts/NodeContext.tsx`

### Persistence

Relational data and object storage

- [Database layer](https://github.com/alfredodompablo/monica/blob/main/src/lib/prisma.ts): Prisma/Postgres · PostgreSQL access and schema management · `src/lib/prisma.ts`
- [Schema](https://github.com/alfredodompablo/monica/blob/main/src/prisma/schema.prisma): Prisma schema · Relational model for users, nodes, readings, and detections · `src/prisma/schema.prisma`
- [Seeds](https://github.com/alfredodompablo/monica/blob/main/src/prisma/seed.ts): DB bootstrap · Migration, seed, and backfill scripts for the database · `src/prisma/seed.ts`
- [Object storage](https://github.com/alfredodompablo/monica/blob/main/src/lib/s3.ts): S3/MinIO · Binary media store for images and derived assets · `src/lib/s3.ts`

### IoT edge

Firmware targets and LoRa protocol layer

- [Field firmware](https://github.com/alfredodompablo/monica/blob/main/firmware/src/main.cpp): PlatformIO target · Environmental sensing node firmware · `firmware/src/main.cpp`
- [Camera firmware](https://github.com/alfredodompablo/monica/blob/main/firmware_cam/src/main.cpp): PlatformIO target · Camera-enabled device firmware · `firmware_cam/src/main.cpp`
- [Light camera](https://github.com/alfredodompablo/monica/blob/main/firmware_cam_light/src/main.cpp): PlatformIO target · Lighter camera variant firmware · `firmware_cam_light/src/main.cpp`
- [Concentrator](https://github.com/alfredodompablo/monica/blob/main/firmware_concentrator/src/main.cpp): LoRa gateway · Gateway firmware bridging field devices to the web app · `firmware_concentrator/src/main.cpp`
- [LoRa protocol](https://github.com/alfredodompablo/monica/blob/main/firmware/include/lora_protocol.h): shared headers · Common device protocol definitions · `firmware/include/lora_protocol.h`

### AI service

Python inference boundary

- [AI service](https://github.com/alfredodompablo/monica/blob/main/ai_service/main.py): FastAPI inference · Python image inference microservice · `ai_service/main.py`
- [YOLO model](https://github.com/alfredodompablo/monica/blob/main/ai_service/model/best.pt): weights artifact · Trained segmentation model used for waste detection · `ai_service/model/best.pt`

### Operations

Scripts and deployment support

- [Ops scripts](https://github.com/alfredodompablo/monica/blob/main/src/scripts/reset-and-seed.ts): utilities · Reset, seed, inference, and node-monitoring helpers · `src/scripts/reset-and-seed.ts`
- [Compose stack](https://github.com/alfredodompablo/monica/blob/main/docker-compose.yml): local deploy · Container bootstrap for running the system locally · `docker-compose.yml`

## Connections

- Web app → Dashboard UI: renders · App Router serves dashboard pages
- Web app → Admin UI: renders · App Router serves admin screens
- Web app → API routes: hosts · Next.js route handlers provide backend APIs
- Dashboard UI → UI components: uses · Dashboard screens compose reusable components
- Admin UI → UI components: uses · Admin screens reuse shared UI building blocks
- UI components → Node state: reads state · Interactive components rely on shared node context
- API routes → Auth layer: guards · Endpoints enforce authentication and role checks
- API routes → Database layer: queries · API handlers persist and read relational data
- Database layer → Schema: implements · Prisma client is generated from schema
- Seeds → Database layer: loads · Seed and migration scripts initialize PostgreSQL
- API routes → Object storage: stores media · Waste detections and images are saved in object storage
- API routes → AI service: invokes · Waste detection flow calls the inference service
- AI service → YOLO model: runs · Service uses the bundled model weights
- Concentrator → LoRa protocol: speaks · Gateway and nodes share the LoRa protocol
- Field firmware → LoRa protocol: speaks · Field nodes use shared protocol definitions
- Camera firmware → LoRa protocol: speaks · Camera nodes use shared protocol definitions
- Light camera → LoRa protocol: speaks · Light camera nodes use shared protocol definitions
- Concentrator → API routes: uploads telemetry · Gateway bridges device data into the application APIs
- Field firmware → Concentrator: reports · Sensor data flows from field devices through the gateway
- Camera firmware → Concentrator: reports · Images or events flow through the gateway
- Light camera → Concentrator: reports · Light camera data flows through the gateway
- Ops scripts → Seeds: runs · Operational scripts reset and seed the database
- Compose stack → Web app: starts · Compose bootstraps the web application runtime
- Compose stack → AI service: starts · Compose bootstraps the Python inference service
