# Driver message builder (`espnow_message`)

This utility builds **v1** JSON payloads for LED drivers (serial/ESP-NOW bridge and Wi-Fi TCP). See **`docs/API.md`** for the full wire format.

## Usage

### Basic Message Building

```python
from util.espnow_message import build_message, build_preset_dict, build_select_dict

# Build a message with presets and select
presets = {
    "red_blink": build_preset_dict({
        "pattern": "blink",
        "colors": ["#FF0000"],
        "delay": 200,
        "brightness": 255,
        "auto": True
    })
}

select = build_select_dict({
    "device1": "red_blink"
})

message = build_message(presets=presets, select=select)
# Result: {"v": "1", "presets": {...}, "select": {...}}
```

### Building Select Messages with Step Synchronization

```python
from util.espnow_message import build_message, build_select_dict

# Select with step for synchronization
select = build_select_dict(
    {"device1": "rainbow_preset", "device2": "rainbow_preset"},
    step_mapping={"device1": 10, "device2": 10}
)

message = build_message(select=select)
# Result: {"v": "1", "select": {"device1": ["rainbow_preset", 10], "device2": ["rainbow_preset", 10]}}
```

### Converting Presets

```python
from util.espnow_message import build_preset_dict, build_presets_dict

# Single preset
preset = build_preset_dict({
    "name": "my_preset",
    "pattern": "rainbow",
    "colors": ["#FF0000", "#00FF00"],  # Can be hex strings or RGB tuples
    "delay": 100,
    "brightness": 127,
    "auto": False,
    "n1": 2
})

# Multiple presets
presets_data = {
    "preset1": {"pattern": "on", "colors": ["#FF0000"]},
    "preset2": {"pattern": "blink", "colors": ["#00FF00"]}
}
presets = build_presets_dict(presets_data)
```

## API Specification

See **`docs/API.md`** for REST routes, session scoping, and the compact preset keys on the wire.

## Key Features

- **Version Field**: All messages include `"v": "1"` for version tracking
- **Preset Format**: Presets use hex colour strings (`#RRGGBB`), not RGB tuples
- **Select Format**: Select values are always lists: `["preset_name"]` or `["preset_name", step]`
- **Colour Conversion**: Automatically converts RGB tuples to hex strings
- **Default Values**: Provides sensible defaults for missing fields
