# ESP Viewer Architecture & Module Design

## 1. Project Philosophy & Structure

The framework is designed as a generic, profile-driven visualization tool.

### 🏠 Directory Structure
- **`esp_viewer/`**: The Core Framework.
    - **`core/`**: Backend logic (`backend.py`, `protocol.py`).
    - **`web/`**: Web Frontend (Vue 3 + Vite).
    - **`ui/`**: Native Desktop logic (PySide6).

### 🔑 Key Concepts
1.  **Profiles (`.json`)**: The "Brain" of the UI. Defines connection settings, data streams, UI parameter widgets, and layout. Changing `.json` files is the primary way to modify the UI/Protocol without touching code.
2.  **Mock Device (`core/mock_device.py`)**: Simulates hardware behavior, responding to `set_config` commands and generating interference patterns (EMS simulation).

---

## 2. High-Level Architecture

The **ESP Viewer Framework** adopts a decoupled **Frontend-Backend** architecture driven by a **Profile Configuration**.

### 2.1 Key Components
*   **Profile (JSON)**: Defines connection parameters, UI controls, command templates, and parsing rules.
*   **Core Engine (EspViewerEngine)**: Central broker managing `DeviceService` and threading queues. Fans out events to adapters.
*   **Backend (DeviceService)**: Separate thread handling Serial I/O, Data Parsing, and Command formatting.
*   **Adapter (FrontendAdapter)**: Interface bridging Core Engine and representation layer (PySide, Web).
*   **Frontend (GenericWindow / Vue Web)**: The GUI. "Dumb" rendering based solely on Profile and data streams.

### 2.2 Architecture Diagram

```mermaid
sequenceDiagram
    participant UI as GenericWindow (PySide6/Web)
    participant Adp as FrontendAdapter
    participant Eng as EspViewerEngine
    participant Svc as DeviceService
    participant Dev as DeviceInterface (Serial/Mock)

    %% Command Flow
    UI->>Adp: send_command()
    Adp->>Eng: send_command(CommandType, payload)
    Eng->>Svc: (via cmd_queue)
    Svc->>Svc: _handle_command()
    Svc->>Dev: write(JSON/String)
    
    %% Data Flow
    loop Read Loop
        Dev-->>Svc: readline()
        alt is JSON (Control)
            Svc->>Svc: _handle_json_message()
        else is Stream (Data)
            Svc->>Svc: _parse_stream_line()
        end
        Svc->>Eng: Put Packet(EventType) (via event_queue)
    end
    
    %% UI Update
    Eng->>Adp: on_event_received(packet)
    Adp-->>UI: Event/Signal Emitted
```

---

## 3. Module Design

### 3.1 Core Modules (`esp_viewer/core/`)
*   **`engine.py` (EspViewerEngine)**: Hub for starting/stopping service and dispatching events.
*   **`backend.py` (DeviceService)**: Service orchestrator. Handles I/O, dynamic parsing via `streams` definition, and command processing.
*   **`drivers.py`**: Defines standard `read()`, `write()`, `open()`, `close()` interface for `SerialDriver` and `MockDriver`.
*   **`protocol.py`**: Def contrats for `Packet`, `CommandType`, and `EventType`.

### 3.2 UI Adapters (`esp_viewer/ui/` & `esp_viewer/web/`)
*   **`pyside_adapter.py`**: Bridges threads into Qt signals via `QTimer`.
*   **`web_adapter.py`**: FastAPI server managing WebSocket connections for browser-based UIs.

---

## 4. Data Flow

### 4.1 Streaming Data (Device -> UI)
1.  **Driver**: Reads raw line from UART.
2.  **Backend (Parser)**: Matches Regex or Delimiter from Profile `streams`. Extracts fields.
3.  **Backend (IPC)**: Puts `STREAM_DATA` packet into `event_queue`.
4.  **Frontend**: Drains queue and routes payload to plotting/monitor logic.

### 4.2 Command Data (UI -> Device)
1.  **User**: Interacts with a Widget.
2.  **Frontend Adapter**: Calls `engine.send_command(SET_PARAM, ...)`.
3.  **Backend**: Reads queue, constructs string based on `set_template`, and calls `driver.write()`.

---

## 5. Key Features
*   **Mock Simulation**: Built-in `MockDevice` for development without hardware.
*   **Multi-Channel Sync**: Synchronized visualization of multiple data channels.
*   **Event Markers**: Real-time vertical markers for transient events (e.g., "Touch").
