# LoRa Protocol

The MD1 uses LoRa radio for long-range, low-power communication with hub devices.

## Overview

- **Frequency**: Configured in firmware (region-specific)
- **Encryption**: Optional AES-256-CBC
- **Protocol**: JSON payloads

## Enabling LoRa

Include in your configuration:

```json
{
  "id": "AABBCCDDEEFF",
  "md1Config": true,
  "loraEnabled": true
}
```

## Encryption Setup

Enable AES-256-CBC encryption for secure communication:

```json
{
  "id": "AABBCCDDEEFF",
  "md1Config": true,
  "loraEnabled": true,
  "encryptionEnabled": true,
  "encryptionKey": "your-32-character-encryption-key"
}
```

> **Important:** The encryption key must be exactly 32 characters and must match on all devices in your network.

### Encryption Details

- **Algorithm**: AES-256-CBC
- **IV**: Random 16-byte IV prepended to each message
- **Padding**: PKCS#7

## Broadcast Messages

The MD1 broadcasts state updates every 5 seconds when LoRa is enabled:

```json
{
  "id": "AABBCCDDEEFF",
  "firmware": "1.0.2",
  "model": "SwychTemp MD1",
  "states": {
    "1": {
      "0": "2150"
    }
  },
  "ip_address": "192.168.1.100",
  "mac_address": "AA:BB:CC:DD:EE:FF",
  "wifi_ssid": "MyNetwork",
  "loraEnabled": true
}
```

## Write Commands via LoRa

Hub devices can send write commands over LoRa:

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

The `id` must match the target device's MAC address.

## Read Commands via LoRa

Request specific register values:

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

**Response (broadcast back):**
```json
{
  "md1ReadResponse": {
    "id": "AABBCCDDEEFF",
    "address": 1,
    "data": [2150, 1875, 0, 1, 256]
  },
  "id": "AABBCCDDEEFF",
  "model": "SwychTemp MD1",
  "firmware": "1.0.2"
}
```

## Configuration Commands via LoRa

Push configuration to a remote MD1:

```json
{
  "id": "AABBCCDDEEFF",
  "md1Config": true,
  "loraEnabled": true,
  "encryptionEnabled": true,
  "encryptionKey": "your-32-character-encryption-key",
  "modbusNodes": {
    "sensor1": {
      "address": 1,
      "channels": 4,
      "readRange": [0, 4],
      "readType": "INPUT_REGISTER"
    }
  }
}
```

The device saves the configuration and restarts.

## Integration with Hub

A typical hub device:
1. Listens for LoRa broadcasts from MD1 devices
2. Decrypts messages (if encryption enabled)
3. Parses JSON payload
4. Stores/forwards data to cloud or local database
5. Sends commands back to MD1 devices as needed
