# NivaloLink SPI v1

NivaloLink is the local protocol between an ESP32 running `NivaloDevice` and a secondary application MCU running `nivalo-mcu`.

## Frame

Each SPI exchange transfers one fixed-size frame.

| Field | Offset | Size | Notes |
| --- | ---: | ---: | --- |
| magic | 0 | 2 | ASCII `ML`, retained for wire compatibility |
| version | 2 | 1 | `1` |
| type | 3 | 1 | Frame type |
| flags | 4 | 1 | Reserved |
| headerLength | 5 | 1 | `24` |
| sequence | 6 | 2 | Little-endian |
| ack | 8 | 2 | Little-endian |
| payloadLength | 10 | 2 | Little-endian |
| reserved16 | 12 | 2 | Reserved |
| crc32 | 16 | 4 | Little-endian, calculated with this field zeroed |
| reserved | 20 | 4 | Reserved |
| payload | 24 | up to 1000 | JSON payload |

Current frame size is `1024` bytes and current max payload is `1000` bytes.

## Frame Types

| Type | Value | Direction | Purpose |
| --- | ---: | --- | --- |
| `idle` | `0x00` | both | No work queued |
| `hello` | `0x01` | both | Link startup and metadata |
| `poll` | `0x02` | ESP32 to MCU | Request next queued frame |
| `command` | `0x10` | ESP32 to MCU | Forward cloud command |
| `command_status` | `0x11` | MCU to ESP32 | Report command state |
| `telemetry` | `0x20` | MCU to ESP32 | Publish variable value |
| `event` | `0x21` | MCU to ESP32 | Publish event |
| `definition` | `0x22` | MCU to ESP32 | Publish variable/function definition chunk |
| `definitions_begin` | `0x23` | MCU to ESP32 | Begin definitions transfer |
| `definitions_end` | `0x24` | MCU to ESP32 | End definitions transfer |
| `heartbeat` | `0x30` | both | Link health |
| `error` | `0x7f` | both | Protocol or runtime error |

## Command Payload

```json
{
  "commandId": "7e391300-6d7d-475d-b21d-0fe2988d8b0d",
  "command": "readVariable",
  "requestedBy": "user@example.com",
  "payload": {
    "name": "Temp"
  }
}
```

`requestedBy` is optional. When it was present in the cloud command, the ESP32
bridge preserves it unchanged. It is attribution only and MUST NOT be treated
as an authorization credential by the secondary MCU.

## Command Status Payload

```json
{
  "commandId": "7e391300-6d7d-475d-b21d-0fe2988d8b0d",
  "status": "succeeded",
  "message": "Temp published"
}
```
