# Devices API

Read device states and write commands to connected Modbus devices.

## Get Device Information

Retrieve device info and current Modbus states.

```
GET /api/devices
```

**Response:**
```json
{
  "AABBCCDDEEFF": {
    "id": "AABBCCDDEEFF",
    "firmware": "1.0.3",
    "model": "SwychTemp MD1",
    "states": {
      "1": {
        "0": "2150",
        "1": "1875"
      },
      "2": {
        "0": "1",
        "1": "0"
      }
    },
    "lastUpdated": "2026-02-01T06:30:00Z"
  }
}
```

### States Structure

States are organized by Modbus address, then by channel:
- First level key: Modbus node address (string)
- Second level key: Channel/register number (string)
- Value: Register value as string

## Get Linked Devices

Get only the Modbus node configuration (without WiFi/MQTT settings):

```
GET /api/linkeddevices
```

## Write Commands

Send write commands to Modbus devices.

```
POST /write
Content-Type: application/json
```

### Write Single Register

```json
{
  "id": "AABBCCDDEEFF",
  "mdWrite": true,
  "address": 1,
  "channel": 0,
  "payload": "256"
}
```

### Write Single Coil (On/Off)

```json
{
  "id": "AABBCCDDEEFF",
  "mdWrite": true,
  "address": 1,
  "channel": 0,
  "type": "COIL_STATUS",
  "payload": "1"
}
```

| Payload Value | Effect |
|---------------|--------|
| `"1"` or `"ON"` | Turn coil ON |
| `"0"` or `"OFF"` | Turn coil OFF |

### Write Multiple Channels

To write multiple channels in one request, use a JSON payload:

```json
{
  "id": "AABBCCDDEEFF",
  "mdWrite": true,
  "address": 1,
  "channel": 0,
  "type": "COIL_STATUS",
  "payload": "{\"1\": {\"0\": \"1\", \"1\": \"0\", \"2\": \"1\"}}"
}
```

This writes:
- Channel 0 → ON
- Channel 1 → OFF
- Channel 2 → ON

### Response

```json
{
  "status": "SUCCESS",
  "message": "Command processed"
}
```

### Error Response

```json
{
  "status": "ERROR",
  "message": "Invalid JSON"
}
```

## Read Commands (via LoRa)

For reading specific registers via the write endpoint:

```json
{
  "id": "AABBCCDDEEFF",
  "md1Read": true,
  "address": 1,
  "readRange": [0, 4]
}
```

This triggers a read of registers 0-4 from Modbus address 1 and broadcasts the response over LoRa.

## Write Types

| Type | Use Case |
|------|----------|
| `HOLDING_REGISTER` | Write numeric values (default) |
| `COIL_STATUS` | Write ON/OFF states |

## Examples

### Turn on valve 3 on address 1

```bash
curl -X POST http://swychmd1-XXXXXX.local/write \
  -H "Content-Type: application/json" \
  -d '{
    "id": "AABBCCDDEEFF",
    "mdWrite": true,
    "address": 1,
    "channel": 3,
    "type": "COIL_STATUS",
    "payload": "1"
  }'
```

### Set temperature setpoint to 2500 (25.00°C)

```bash
curl -X POST http://swychmd1-XXXXXX.local/write \
  -H "Content-Type: application/json" \
  -d '{
    "id": "AABBCCDDEEFF",
    "mdWrite": true,
    "address": 1,
    "channel": 0,
    "payload": "2500"
  }'
```
