# Rules Engine

The Rules Engine allows for on-device automation. You can configure rules to trigger actions based on the state of Modbus inputs (e.g., Turn on a valve when a temperature sensor exceeds a value).

## Web Interface

Access the Rules configuration via the web interface at:
`http://<device-ip>/rules`

## API Endpoints

### Get Rules

Retrieve all configured rules.

```
GET /api/rules
```

**Response:**

```json
[
  {
    "id": "rule_123456",
    "enabled": true,
    "name": "Freezer Protection",
    "ifNodeId": 1,
    "ifChannel": 0,
    "operatorType": ">",
    "ifValue": -10.5,
    "actions": [
      {
        "nodeId": 2,
        "channel": 0,
        "value": 1
      },
      {
        "nodeId": 2,
        "channel": 1,
        "value": 1
      }
    ]
  }
]
```

### Save Rules

Overwrite the entire rules list.

```
POST /api/rules
Content-Type: application/json
```

**Request Body:**

Array of Rule objects (same format as GET response).

## Rule Object Structure

| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Unique identifier for the rule |
| `enabled` | boolean | Whether the rule is active |
| `name` | string | Human-readable name |
| `ifNodeId` | integer | Modbus address of the input node |
| `ifChannel` | integer | Register/Channel index to monitor |
| `operatorType` | string | Comparison operator (see below) |
| `ifValue` | float | Threshold value to compare against |
| `actions` | array | List of actions to perform when triggered |

### Operators

| Operator | Description |
|----------|-------------|
| `>` | Greater than |
| `<` | Less than |
| `>=` | Greater than or equal to |
| `<=` | Less than or equal to |
| `==` | Equal to |
| `!=` | Not equal to |

### Actions

The `actions` array contains objects defining what to do when the rule triggers.

| Field | Type | Description |
|-------|------|-------------|
| `nodeId` | integer | Modbus address of the target device |
| `channel` | integer | Register/Channel index to write to |
| `value` | float | Value to write (Use `1` for ON, `0` for OFF) |

## Logic

- Rules are evaluated every time the device polls its Modbus nodes (typically every few seconds).
- If the condition is met (`currentValue operator ifValue`), **ALL** defined actions are executed.
- Providing multiple actions allows you to control multiple devices or channels from a single trigger event.
