# espresense/espresense-companion architecture

> Architecture diagram of the GitHub repository espresense/espresense-companion, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-03-30). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/espresense/espresense-companion
- Repository: https://github.com/espresense/espresense-companion

## Overview

##### Main Components
- Backend Application (ASP.NET Core):
– Contains several C# Controllers (DeviceController, FirmwareController, HistoryController, NodeController, StateController) that expose REST endpoints.
– Includes a layered set of business logic components: services (ConfigLoader, DeviceTracker, MappingService, TelemetryService, etc.), models representing entities (Device, Node, Calibration, etc.), event dispatchers, and extension classes for various common tasks.
- Trilateration & Optimization Engine:
– Comprised of multiple “Locators” (e.g., BfgsMultilateralizer, GaussNewtonMultilateralizer, etc.) and “Optimizers” (e.g., CombinedOptimizer, TwoStageRxAdjAbsorptionOptimizer) that process the received distance data.
- MQTT Coordination & OTA Management:
– The system includes a MQTT Coordinator (in Services/MqttCoordinator.cs) to both intake MQTT messages from ESPresense nodes and output notifications or commands (like firmware updates or configuration changes).
– The OTA update functionality (via ESPOta in src/Network and related firmware scripts) enables seamless node firmware management.
- Web-Based Frontend (Svelte UI):
– Located inside the src/ui folder with a clear separation of concerns using routes, components (e.g., DeviceMarker, Map, CalibrationSpot), and utilities. This is the primary dashboard for visualization and interaction.
- Integration with Home Assistant:
– The system sends room-presence updates and receives configuration triggers via MQTT, making integration with Home Assistant a key element.
- Docker & Deployment:
– Dockerfile and GitHub workflows indicate containerization and CI/CD pipelines for robust deployment.

##### Relationships and Interactions
- Data Flow:
– ESPresense nodes publish raw distance readings and telemetry to an MQTT broker.
– The MQTT Coordinator service ingests these messages.
– Once ingested, the system’s event pipeline (via several Event classes) triggers the trilateration/optimization engine to calculate positions.
– The processed location data is stored, and appropriate notifications (e.g., device room status) are published back to Home Assistant via MQTT.
- REST API & Frontend Interactions:
– The API Controllers expose endpoints to the Svelte front-end.
– The front-end queries device statuses, calibration info, and node details, while also triggering operations (e.g., firmware updates) through the API.
- Administrative & Configuration Flow:
– The companion manages node configurations from configuration files (supported by the “bruno” directory for node, device, and firmware-specific scripts) as well as from UI inputs.
– Firmware updates and OTA operations provide a loop that keeps the nodes up-to-date.

##### Architectural Patterns and Key Technologies
- Layered Architecture: Separation between the API (Controllers), Business Logic (Services, Events), and Data/Configuration (Models, Stores).
- Event-Driven Programming: The design leverages event dispatchers and event arguments to handle asynchronous updates and processing.
- Micro–Frontend/SPA: The Svelte-based UI and its routing architecture clearly separate the presentation layer.
- Containerization & CI/CD: Use of Dockerfile and GitHub workflows for continuous integration/deployment.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% External Systems
    subgraph "External Systems"
        MQTTBroker["MQTT Broker"]:::external
        HomeAssistant["Home Assistant"]:::external
    end

    %% Companion Backend
    subgraph "Companion Backend"
        API["API Controllers"]:::backend
        Services["Business Logic Services"]:::backend
        EventDisp["Event Dispatchers"]:::backend
        DataModels["Data Models/Configuration Store"]:::backend
        subgraph "Trilateration & Optimization Engine"
            Locators["Locators"]:::backend
            Optimizers["Optimizers"]:::backend
        end
        MQTTCoord["MQTT Coordinator"]:::backend
        OTA["OTA Firmware Manager"]:::backend
        ConfigScripts["Configuration Scripts"]:::backend
    end

    %% Frontend
    subgraph "Web UI (Svelte)"
        SvelteUI["Svelte UI"]:::frontend
    end

    %% Deployment
    subgraph "Deployment"
        DeploymentNode["Docker & CI/CD Deployment"]:::deployment
    end

    %% Data and Control Flows
    MQTTBroker -->|"IncomingMQTTData"| MQTTCoord
    MQTTCoord -->|"TriggersEvents"| Services
    Services -->|"DispatchesEvent"| EventDisp
    Services -->|"InvokesTrilateration"| Locators
    Services -->|"InvokesOptimization"| Optimizers
    Services -->|"PublishesUpdates"| MQTTBroker
    API -->|"Reads/WritesConfig"| DataModels
    SvelteUI -->|"RestAPICalls"| API
    API -->|"RestAPIResponse"| SvelteUI
    OTA -->|"ExecutesFirmwareUpdate"| MQTTBroker
    MQTTCoord ---|"IntegratesWith"| OTA
    MQTTBroker -->|"PresenceUpdates"| HomeAssistant
    ConfigScripts -->|"ProvidesConfig"| DataModels

    %% Click Events
    click API "https://github.com/espresense/espresense-companion/tree/main/src/Controllers"
    click Services "https://github.com/espresense/espresense-companion/tree/main/src/Services"
    click EventDisp "https://github.com/espresense/espresense-companion/tree/main/src/Events"
    click DataModels "https://github.com/espresense/espresense-companion/tree/main/src/Models"
    click Locators "https://github.com/espresense/espresense-companion/tree/main/src/Locators"
    click Optimizers "https://github.com/espresense/espresense-companion/tree/main/src/Optimizers"
    click MQTTCoord "https://github.com/espresense/espresense-companion/blob/main/src/Services/MqttCoordinator.cs"
    click OTA "https://github.com/espresense/espresense-companion/blob/main/src/Network/ESPOta.cs"
    click SvelteUI "https://github.com/espresense/espresense-companion/tree/main/src/ui"
    click ConfigScripts "https://github.com/espresense/espresense-companion/tree/main/bruno"
    click DeploymentNode "https://github.com/espresense/espresense-companion/tree/main/Dockerfile"

    %% Styles
    classDef external fill:#fde2e4,stroke:#333,stroke-width:2px;
    classDef backend fill:#d0e6a5,stroke:#333,stroke-width:2px;
    classDef frontend fill:#a5d8e6,stroke:#333,stroke-width:2px;
    classDef deployment fill:#f8e1f4,stroke:#333,stroke-width:2px;
```
