# Example 21: IR Remote Control

## Experiment Overview

Receive infrared remote signals through a module such as VS1838B, decode them and trigger device actions. The driver supports NEC, RC5, SONY and other common formats when `irRemote` is compiled and active.

IR remote control uses a **universal learning (pairing)** approach. Configuration takes two steps:

1. **Learn**: open the Web **IR Management** panel, start a time-limited learning window, press a remote key, then save the captured code under a **key name** (e.g., `power`, `key1`). The key library is persisted to `/config/ir_keys.json`
2. **Bind**: in a peripheral execution rule, set the trigger to the **IR Code Received** event (`ir_code_received`) and pick a learned key from the **IR Key** dropdown

Rules reference **key names** instead of hard-coded codes. So when you switch to any other remote, just re-learn the keys using the same key names — every rule keeps working, with no rule changes required.

After configuring an **IR Receiver (type 53)** peripheral, each received key code dispatches an `ir_code_received` event with the following data:

```json
{"protocol":"NEC","code":"0x00FF6897","bits":32,"key":"power"}
```

> The `key` field appears only when the received code matches an entry in the key library. Un-learned keys carry only `protocol` / `code` / `bits`.

> **Note**: `FASTBEE_ENABLE_IR_REMOTE=1` is required. `esp32s3-F8R8` excludes IR/RF because of an RMT/library conflict; check `/api/features/status` on other environments.
>
> **ESP32-S3 RMT Driver Configuration**: ESP32-S3's RMT driver has legacy vs. new version conflicts. If enabling IR in custom S3 firmware, both configurations must be handled:
>
> ```ini
> -DCONFIG_RMT_ENABLE=0
> -DIR_USE_GPIO=1
> ```
>
> If using other environments and need IR, ensure the above compile flags are added.

## Hardware Wiring

| Board Label | GPIO Pin | Connected Device |
|-------------|----------|-----------------|
| IR\_RX | GPIO35 | VS1838B IR receiver (OUT pin) |

> VS1838B wiring: VCC→3.3V, GND→GND, OUT→GPIO35. The receiver has a push-pull output, no external pull-up needed; input-only pins (GPIO35/36/39) are recommended, other free GPIOs also work.

## JSON Configuration Example

```json
{
  "peripherals": [
    {
      "id": "ir_recv",
      "name": "IR Receiver",
      "type": 53,
      "enabled": true,
      "pins": [35],
      "pinCount": 1,
      "params": {}
    }
  ]
}
```

> Type `53` is the IR receiver. When creating the peripheral in the Web UI, just select **IR Receiver** from the type dropdown; no extra parameters required.

## IR Learning (Pairing Keys)

### Web Steps

1. Turn on **Developer Mode** at the top-right of the page (learning, deleting a key and clearing all keys are write operations and require it; opening the panel itself is read-only)
2. Go to the **Peripheral Configuration** page and click the **IR Management** button on the "IR Receiver" row
3. In the **Learn (Pair Key)** section, set **Learn Timeout (seconds)** (default 10s, allowed 3-60s) and click **Start Learning**
4. Aim the remote at the receiver and press the key you want to record; on success the page shows the captured code and protocol
5. Type a name in the **Key Name** field (e.g., `power`, `vol_up`, `key1`) and click **Save Key**
6. Repeat steps 3-5 for the remaining keys. Saved keys are listed in the **Key Library** table below, where you can delete them individually or click **Clear All**

> If the panel shows "IR receiver is not initialized", the peripheral is disabled or failed to initialize — enable it in peripheral management first.

### Learning States

| State | Meaning | Page behavior |
|-------|---------|---------------|
| `idle` | Idle | Not in a learning window |
| `learning` | Learning | Shows remaining countdown, waiting for a key |
| `captured` | Captured | Shows code and protocol, ready to name and save |
| `timeout` | Timed out | No valid code received within the window; click **Start Learning** again |

> **No `ir_code_received` event is dispatched while the learning window is open**, so pairing never fires your existing rules by accident.

### Key Library Rules

| Item | Description |
|------|-------------|
| Key name | Letters, digits, underscore and hyphen only, 1-32 characters |
| Maximum count | Up to 40 keys; delete one before adding a new key once full |
| Overwrite | Saving an existing name overwrites its code — this is the recommended way to **switch remotes** |
| Persistence | `/config/ir_keys.json`, structured as `{"keys":[{"name","code","protocol"}]}` |
| Migration | The file is on the config import/export allowlist, so it can be migrated to other devices via **Device Config → Advanced → Export/Import Config** |

## Peripheral Execution Linkage

### Scenario 1: Any Remote Key Controls LED (Event Trigger)

**Function**: Toggle LED state on any IR key press

#### Web Interface Configuration Steps

**Step 1: Ensure LED peripheral is configured**

* Peripheral ID: `led_d1`
* Type: GPIO Output

**Step 2: Create Rule**

1. Click **Peripheral Execution** in the left menu
2. Click **<i class="fas fa-plus"></i> New Rule** button
3. Fill in basic configuration:
   * **Rule Name**: `IR Control LED`
   * **Report Data**: ✅ Enable
   * **Enabled**: ✅ Enable

**Step 3: Configure Trigger (Event Trigger)**

1. Click **Add Trigger** button
2. Fill in trigger configuration:

   | Field | Value | Description |
   |-------|-------|-------------|
   | **Trigger Type** | Select **Event Trigger** | Respond to IR events |
   | **Event** | Select **IR Code Received** | i.e., `ir_code_received` |
   | **IR Key** | Keep `-- Any IR Key --` | Empty means any received IR code triggers the rule |

**Step 4: Configure Action**

1. Click **Add Action** button

2. Fill in:
   * **Action Type**: Select **Toggle Level**
   * **Target Peripheral**: Select `led_d1`

3. Click **Save** button

***

### Scenario 2: Different Keys Perform Different Actions (by Key Name)

**Function**: `key1` turns the light on, `key2` turns it off

**Prerequisite**: `key1` and `key2` already exist in the key library (see IR Learning above).

Once the **IR Code Received** event is selected, an **IR Key** dropdown appears and is populated from the key library (options are shown as "key name (code)"). Create two rules:

1. Rule `IR Key1 Light On`:
   * Trigger: **Event Trigger** → Event **IR Code Received** → IR Key `key1`
   * Action: **Set Level**, target peripheral `led_d1`, value `0` (active-low LED)
2. Rule `IR Key2 Light Off`:
   * Trigger: **Event Trigger** → Event **IR Code Received** → IR Key `key2`
   * Action: **Set Level**, target peripheral `led_d1`, value `1`

### Three Formats for Compare Value

Selecting from the dropdown stores a `compareValue` such as `key:key1`. The firmware also still matches by code, which is handy when editing JSON directly or keeping legacy rules:

| Format | Example | Description |
|--------|---------|-------------|
| `key:<name>` | `key:key1` | **Recommended**. Matches a learned key name (case-insensitive); switching remotes needs no rule change |
| `<protocol>:<code>` | `NEC:0x00FF30CF` | Protocol + code, for legacy rules |
| `<code>` | `0x00FF30CF` or `00FF30CF` | Any protocol + code; the `0x` prefix is optional and matching is case-insensitive |
| Empty | — | Any IR code triggers the rule |

> The Web form only offers "select a learned key". The latter two formats are meant for imported JSON configs or historical rules, and are still matched correctly at runtime.

## API Reference

The IR management panel talks to the firmware through the following endpoints (all require login; write operations additionally require Developer Mode):

| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/ir/status` | Init state, learning state, key count, last received code |
| POST | `/api/ir/learn/start` | Start learning, parameter `timeoutMs` (default 10000) |
| GET | `/api/ir/learn/status` | Learning state, remaining ms, captured code and protocol |
| POST | `/api/ir/learn/stop` | Cancel learning |
| GET | `/api/ir/keys` | List the key library |
| POST | `/api/ir/keys` | Save/overwrite a key, parameters `name`, `code`, `protocol` (optional) |
| POST | `/api/ir/keys/delete` | Delete one key, parameter `name` |
| POST | `/api/ir/keys/clear` | Clear all keys |

## Common Remote Key Values (NEC Protocol) — Reference

Learning makes manual code entry unnecessary; the table below is only for troubleshooting reference (typical small NEC remotes):

| Button | Key Value (short) | 32-bit Full Code |
|--------|-----------|-------------|
| 1 | 0xFF30CF | `0x00FF30CF` |
| 2 | 0xFF18E7 | `0x00FF18E7` |
| 3 | 0xFF7A85 | `0x00FF7A85` |
| OK | 0xFF02FD | `0x00FF02FD` |
| ▲ | 0xFF629D | `0x00FF629D` |
| ▼ | 0xFFA857 | `0x00FFA857` |

> 💡 **Tip**: Different brands use different key values — there is no need to look them up, just pair the keys in the **IR Management** panel. You can also check **System Logs** for the raw decode result (e.g., `[IR] Received: NEC value=0x00FF30CF bits=32`) to confirm the hardware path works.

## Notes

1. **Firmware State**: Confirm `irRemote` is compiled and active; do not use `esp32s3-F8R8` for this example
2. **RMT Driver Compatibility**: ESP32-S3's RMT new driver (driver\_ng) and legacy driver cannot coexist, must verify startup and decode stability before custom enabling
3. **Developer Mode required for pairing**: learning, saving, deleting and clearing keys are write operations and are rejected unless Developer Mode is on
4. **Switching remotes**: just re-learn using the same key names; rules stay untouched. Key-name matching also works when the new remote uses a different protocol (e.g., NEC → SONY)
5. **No code captured**: verify wiring (OUT→GPIO35, VCC→3.3V — reversing them yields no output), remote battery, and press briefly within 20cm facing the receiver; click **Start Learning** again after a timeout
6. **Receiving Distance**: VS1838B typical receiving distance 8-10m, needs to aim at receiver
7. **Ambient Light Interference**: Strong sunlight or fluorescent lights may interfere with IR reception
8. **Protocol Support**: Auto-detects NEC, RC5, RC6, SONY, Samsung and other protocols; the `protocol` field in the event is the protocol name, `code` is the hex code
9. **Repeat Code & Debounce**: NEC repeat codes from long presses are filtered automatically, with a built-in 150ms debounce; peripheral execution additionally enforces a 1-second minimum repeat interval per trigger, so holding a key does not fire repeatedly
10. **No IR transmit**: only receiving/decoding is supported today; sending IR codes is not
