# Communication Protocol

This document defines the communication contracts between the **Frontend**, **Backend Engine**, and the **Physical Device**.

## 1. System Communication Overview

The system operates on three layers of communication:
1.  **Frontend <-> Backend (IPC)**: High-level command and event exchange via Python queues.
2.  **Backend <-> Device (UART)**: Serial communication using strings, JSON-RPC, or CSV data.
3.  **Low-Level Tools (Subprocess)**: Temporary takeover of the port by tools like `esptool`.

---

## 2. Frontend <-> Backend IPC

The `esp_viewer` uses a standard `Packet` object to pass data across thread boundaries.

### 2.1 Packet Structure

```python
class Packet:
    def __init__(self, type, payload=None):
        self.type = type        # Enum (EventType or CommandType)
        self.payload = payload  # Dictionary containing packet data
```

### 2.2 Sequence: Control Flow

Commands are sent from the UI to the Engine, which then delegates to the `DeviceService`.

```mermaid
sequenceDiagram
    participant FE as Frontend (UI)
    participant E as Engine (Backend)
    participant DS as DeviceService (Worker)
    participant D as Physical Device

    FE->>E: Send Command (CommandType.SET_PARAM, {id: "v", val: 10})
    E->>E: Queue Command
    E->>DS: Process Command
    DS->>D: Write to Serial ("SET_V 10\n")
    D-->>DS: ACK / Response
    DS->>E: Push Event (EventType.LOG_MSG, "Value set")
    E->>FE: Update UI State
```

### 2.3 Command & Event Types
- **CommandType (FE -> BE)**: `CONNECT`, `DISCONNECT`, `SET_PARAM`, `GET_CHIP_INFO`.
- **EventType (BE -> FE)**: `STREAM_DATA`, `LOG_MSG`, `IO_DATA`, `CHIP_INFO_RECEIVED`.

---

## 3. Backend <-> Device Protocol

The framework supports a **Hybrid Approach** for serial interaction.

### 3.1 Data Flow (Telemetry)
High-frequency data is typically sent in a compact format (CSV or Delimited) to minimize overhead.

```mermaid
graph LR
    D[Device] -- "DATA,1.2,3.4\n" --> DS[DeviceService]
    DS -- Regex/Header Match --> P[Stream Parser]
    P -- StreamPacket --> E[Engine]
    E -- EventType.STREAM_DATA --> FE[UI Plots]
```

### 3.2 Control Flow (Commands)
Commands are typically human-readable strings defined by the `set_template` in the profile.

- **Request**: `SET_LED 1\n`
- **Response**: `+OK\n` (Optional, usually logged but not required for simple open-loop control).

---

## 4. Diagnostics & Tooling Takeover

When performing hardware diagnostics (e.g., `esptool`), the `DeviceService` must suspend its serial monitoring to allow sub-processes to access the port.

```mermaid
sequenceDiagram
    participant FE as Frontend
    participant E as Engine
    participant DS as DeviceService
    participant ET as esptool (Subprocess)

    FE->>E: CommandType.GET_CHIP_INFO
    E->>DS: Suspend Monitoring
    DS->>DS: Close Serial Port
    E->>ET: Launch Subprocess (esptool --port ... chip_id)
    ET-->>E: Pipe Terminal Output
    E->>FE: EventType.LOG_MSG (Real-time logs)
    ET->>E: JSON Result
    E->>FE: EventType.CHIP_INFO_RECEIVED
    E->>DS: Resume Monitoring
    DS->>DS: Re-open Serial Port
```
