# MangoLink Protocol 1 — TLS and explicit local TCP

Status: implementation version 0.2.0. The JSON protocol remains version 1. This specification is mirrored in MangoLink and
MangoLinkSimulator. Changes to either implementation must update both copies.

## Transport and framing

- TLS over TCP (default port 8766) or explicitly selected unencrypted TCP (8765). Both ports are configurable. The server listener uses exactly one selected mode; there is no STARTTLS upgrade, protocol sniffing, or automatic fallback.
- Each frame is one UTF-8 JSON object followed by LF (`0x0A`). No pretty printing.
- Maximum payload is 8192 bytes, excluding LF. JSON string newlines must be escaped.
- TCP reads/writes do not correspond to frame boundaries. Buffer until LF.
- Every message has integer `v: 1` and string `type`.
- Truncated, malformed, oversized and unsupported-version frames terminate the session.
- TLS requires 1.2 or newer. The client verifies the server before sending the
  authentication frame. TLS failures never trigger a plaintext retry.
- With an empty fingerprint, Android validates the normal trusted certificate
  chain and certificate DNS/IP identity. With a SHA-256 fingerprint obtained
  from a trusted desktop or USB console, the exact leaf certificate is the
  device identity; its validity and server-auth usage are checked. This pinned
  mode does not require that the device's current LAN IP appear in the certificate.
- No accept-all trust manager, first-use network trust or automatic pin replacement.
  When a certificate changes, deliberately verify and enter its new fingerprint.
- In explicitly selected TCP mode all data, including the token, is plaintext.
  Use it only on a trusted lab network; do not publicly expose the debug endpoint.
- TLS protects transport, not the contents of exported files or the safety of
  commands implemented by the firmware. Mutual TLS and device authorization
  beyond the session token are outside this milestone.

## Handshake

Client must send authentication within five seconds:

```json
{"v":1,"type":"auth","token":"mangolink-demo"}
```

Server either sends an error and closes, or sends:

```json
{"v":1,"type":"hello","device":"MangoLink Simulator","firmware":"0.2.0","boot":1,"capabilities":["logs","commands","telemetry"]}
```

No logs or telemetry are sent before successful authentication. The client must
wait for hello before sending commands. A second hello on one session is invalid.
Simulator sends periodic data at least every second. The Android client closes
after 15 seconds without readable data; quiet firmware must emit heartbeat
telemetry within that interval. There is no automatic reconnect in 0.2.0.

## Device to client

```json
{"v":1,"type":"log","seq":12,"boot":1,"uptime_ms":12345,"level":"WARN","tag":"MOTOR","text":"Current above target"}
{"v":1,"type":"telemetry","uptime_s":12.3,"temperature_c":35.2,"voltage_v":3.31,"led":false,"boot":1}
{"v":1,"type":"response","id":"request-123","ok":true,"text":"LED ON"}
{"v":1,"type":"error","text":"Authentication failed"}
```

- `seq` increments per device log, and resets after reboot. The client flags
  discontinuities but cannot recover missing records in this version.
- `uptime_ms` is device time since boot; the client separately records local
  receipt time. No synchronized wall-clock claim is made.
- Telemetry keys other than `v`/`type` are displayed as values; named units belong
  in keys for this first protocol (`temperature_c`, `voltage_v`).
- Responses echo the complete request ID. `ok` reflects the command handler's
  result. A response accepting reboot does not prove boot completed.
- `error` is a fatal protocol/authentication error; client disconnects.

## Client to device

```json
{"v":1,"type":"command","id":"request-123","command":"led on"}
```

IDs are strings of 1–64 characters (Android uses UUIDs). Commands contain
1–256 characters. Supported simulator commands:

| Command | Result |
| --- | --- |
| `help` | List supported commands |
| `status` / `sensors` | Current device values in response text |
| `led on` / `led off` | Set simulated LED state |
| `warn` / `error` | Broadcast a test log event |
| `disconnect` | Acknowledge, then close requesting client |
| `reboot` | Acknowledge, increment boot counter, reset uptime/LED, disconnect all clients |

Unknown commands get `ok: false`. Structurally invalid commands get a fatal error.
Simulator UI/CLI generates a random session token by default. The demonstration
token in this document is only an example. The server must not publish a shared
production credential. Android tracks up to 32 unanswered commands and a 10-second response deadline.
An unanswered command has an **unknown execution outcome**. The app never
automatically retries or replays commands. This version does not guarantee
exactly-once execution or persist request deduplication across sessions.

## Resource limits and future ESP32 implementation

Android retains only 2,000 rows in memory and reports discarded older rows.
It bounds outgoing and pending UI queues. Export saves the current buffer;
it is not a complete durable recording of arbitrarily long sessions.

The simulator closes slow clients when a write drain times out. Its GUI queue and
display are bounded. It is a development fixture, not a hardened public server.
Generated TLS private keys remain on the PC and are excluded from Git. The GUI
displays a public certificate fingerprint for pairing. Certificate generation
uses the optional cryptography dependency; serving existing certificates uses
Python SSL. The CLI prints a random session token for the developer to enter
on the phone; protect terminal output and any redirected copies.

ESP32 integration should enqueue logs without blocking the control task, transmit
from a network task, report overflow counts, and keep the network debug endpoint
independent from time-critical control. Early boot/panic logs may be unavailable
when networking is down. Device-side persistent history is a later milestone.
