HomeSpan Visual BuilderUser Guide

RU EN

1. Smart home and Apple Home

Apple Home (or simply "Home") is an app on iPhone, iPad, Mac, and Apple Watch that controls smart devices in your home: lights, outlets, thermostats, sensors, locks. You open the app, tap a lamp — it turns on. Or say to Siri: "Turn off the living room light" — and she does.

Smart devices come from many manufacturers: Philips Hue bulbs, Eve outlets, Ecobee thermostats, Aqara sensors. They all work in Apple Home because they support HomeKit — a set of rules developed by Apple. If a device works with HomeKit, it appears in Home and obeys Siri.

The problem: off-the-shelf devices cost money and only do what the manufacturer programmed. For example, you can't make a commercial smart bulb turn on when your custom motion sensor triggers.

HomeSpan Visual Builder solves this: you assemble your own device from accessible parts — an ESP32 and any modules (relays, sensors, buttons) — program it through a visual interface, and it becomes a full HomeKit device.

2. What is an accessory

In HomeKit, an accessory is a separate device. A bulb is an accessory. An outlet is an accessory. A thermometer is an accessory. A motion sensor is an accessory.

Every accessory has a name — how it appears in Home ("Bedroom lamp", "Kitchen sensor"). One ESP32 can control several accessories — say, a relay and a sensor at the same time. In Home they appear as two separate devices.

The type of an accessory defines what it can do. A thermometer shows temperature. A lamp turns on and off. A lock opens and closes. In our editor, the accessory type is called a service: LightBulb, TemperatureSensor, Doorbell, Switch, MotionSensor, and so on. There are about 40 of them. The full list is in the service ribbon at the top of the editor.

3. What are characteristics

A characteristic is a property of an accessory.

A lamp has a characteristic On ("is it on?"). The answer is yes or no. A lamp may also have Brightness (0–100%), Hue (0–360°), Saturation (0–100%). These are optional characteristics.

A thermometer has CurrentTemperature — the current temperature. A lock has LockCurrentState and LockTargetState. A motion sensor has MotionDetected (bool).

When you pick a service, some characteristics are required (a lamp must have On), others are optional (Brightness can be added or skipped).

In the editor you can do three things with each characteristic:

  • Set a default value — for example, the lamp is off at startup.
  • Enable persist — keep the value across ESP32 reboots (not always needed — e.g., not for "current temperature").
  • Read and write it in your rules: "if On becomes true — turn on the relay".

4. What is a bridge

HomeKit has a limit: no more than 100 accessories per device. If you have 10 ESP32s, each with its own device, that's 10 separate pairings in Home. If a single ESP32 controls 50 relays — it gets unwieldy.

A bridge is a container device. In Home you pair only the bridge (one pairing code entry). All accessories "behind" the bridge appear automatically and don't count against the 100-accessory limit.

In the editor:

  • Normal mode (Bridge mode off) — accessories at the top level. Good for one or two devices. Simple.
  • Bridge mode (Bridge mode on) — the first accessory card automatically becomes the bridge itself (empty accessory), and the rest become its children. You pair once — all devices appear at once.

What to choose:

  • One accessory — normal mode, simpler.
  • Two or more — bridge, easier to extend.
  • Planning 10+ accessories on one ESP32 — definitely bridge.

5. ESP32 and GPIO pins

ESP32 is a microcontroller with Wi-Fi and Bluetooth. About the size of a fingernail, costs a few dollars. Programmed via Arduino IDE. Can control hardware: turn on relays, read sensors, blink LEDs.

There are different ESP32 models: classic ESP32, ESP32-S3, ESP32-C3, ESP32-C6, and others. Each has a different set of pins, frequencies, and memory. We support all ESP32 models that have Wi-Fi (required for HomeKit).

A GPIO pin is a physical leg on the ESP32 board where external devices are connected. Each pin has a number: GPIO 0, GPIO 1, ... GPIO 48 (not all numbers exist on all boards).

What you can do with a pin:

  • Digital input. Read — voltage present or not. For example, is a button pressed. The answer is HIGH (yes) or LOW (no).
  • Digital output. Output voltage or not. For example, turn on a relay. HIGH = on, LOW = off.
  • Analog input. Read a voltage level from 0 to 4095 (12-bit ADC). Needed for light sensors, potentiometers.
  • Analog output / PWM. Rapidly toggle HIGH/LOW — producing a pseudo-analog signal. Used for LED brightness, motor speed.
  • Interrupt. ESP32 watches the pin in the background and calls a function when the state changes. Useful for buttons: no need to poll, ESP32 will notify itself.

Two special pins. In device settings you configure:

  • Control pin — the control button pin (for entering pairing mode with a long press).
  • Status pin — the status LED pin (blinking shows the ESP32 is running and ready for pairing).

HomeSpan manages these pins itself; your logic doesn't need to touch them.

Important Some ESP32 pins have special functions (for example, GPIO 0 is the boot pin, GPIO 2 is often wired to the on-board LED). Avoid them for critical tasks unless you know what you're doing.

6. What is HomeSpan

HomeSpan is an open-source C++ library for ESP32 that implements HomeKit. It handles all the difficult parts: network protocols, TLS encryption, Apple pairing, data exchange. The programmer only needs to describe services and logic.

Our builder generates code for HomeSpan. The downloaded .ino is opened in Arduino IDE, you install the HomeSpan library (via Library Manager), compile, and flash it to the ESP32.

The main convenience: HomeSpan configures Wi-Fi on first launch itself. The user connects to a temporary access point (Captive Portal), opens the web interface, enters their network credentials. Wi-Fi passwords never go into the firmware — this is secure.

Pairing works the same way: on first launch the device waits for the pairing code from the Home app. No hard-coded codes.

7. Quick start: smart lamp

Let's build a simple device — a smart lamp with a relay on pin 10.

Step 1. Create a project

On the main page click + New Project. Enter a name, e.g. My Lamp. Choose the board — ESP32-C3.

Step 2. Configure the device

Click Device in the toolbar. Fill in:

  • Device name — My Lamp (how it appears in Home).
  • Category — Lighting.
  • Pairing code — 8 digits, e.g. 12345678.
  • Control pin = 9, Status pin = 8.

Click Apply.

Step 3. Add the relay pin

Left panel, tab Pins → Add pin:

  • Name: RELAY_PIN
  • GPIO: 10
  • Role: Output, Mode: Digital
  • Init When: Before HomeSpan

Step 4. Add an accessory

Top, in the service ribbon, pick the Lights & Power category → click Light Bulb. The accessory appears on the canvas. Click it → properties open on the right. Rename it to Lamp.

Step 5. Add logic

On the accessory card click +changed. This creates a "When characteristic changes" rule. It appears below the card in the LOGIC section.

Click the rule → switch to the Body tab on the right → + Add action:

  • Pick Set Pin State.
  • Pin: RELAY_PIN.
  • Value: Source = Characteristic → On.

Step 6. Initial relay state

Routines → Setup tab → Setup before HomeSpan card → click + Add. Switch to the Body tab of this rule → + Add action:

  • Set Pin State, Pin = RELAY_PIN, Value = Named constant → LOW.

Step 7. Save and download

Click Save → Preview. You see the sketch. Close Preview, click Save → Download .ino.

Step 8. Flash

Open the file in Arduino IDE. Install the HomeSpan library via Sketch → Include Library → Manage Libraries. Select ESP32C3 Dev Module. Upload.

Step 9. Pair

In the Home app → + → Add Accessory → More options… → enter the pairing code. The device appears in your home.

8. What happened under the hood

The builder generated approximately this sketch:

#include <HomeSpan.h>

#define CONTROL_PIN    GPIO_NUM_9
#define STATUS_LED_PIN GPIO_NUM_8
#define RELAY_PIN      GPIO_NUM_10

class LampService : public Service::LightBulb
{
public:
    SpanCharacteristic* m_On;

    LampService() : Service::LightBulb()
    {
        m_On = new Characteristic::On(false);
    }

    boolean update()
    {
        digitalWrite(RELAY_PIN, m_On->getNewVal() ? HIGH : LOW);
        return true;
    }
};

LampService* g_Lamp = nullptr;

void setup()
{
    Serial.begin(115200);
    pinMode(RELAY_PIN, OUTPUT);
    digitalWrite(RELAY_PIN, LOW);

    homeSpan.setControlPin(CONTROL_PIN);
    homeSpan.setStatusPin(STATUS_LED_PIN);
    homeSpan.setPairingCode("12345678");
    homeSpan.begin(Category::Lighting, "My Lamp");

    new SpanAccessory();
    new Service::AccessoryInformation();
    new Characteristic::Identify();
    g_Lamp = new LampService();
}

void loop()
{
    homeSpan.poll();
}

Let's break down the key parts.

#define is a "nickname" for a pin number. RELAY_PIN becomes GPIO_NUM_10.

class LampService : public Service::LightBulb — our own accessory class. It inherits from the standard Service::LightBulb provided by HomeSpan.

Inside the class there's the characteristic m_On — created in the constructor with the value false (off by default).

The update() method is called by HomeSpan every time Home sends a "turn on" or "turn off" command. We read the new value (getNewVal()) and write it to the relay pin.

In setup():

  • Open Serial for debugging.
  • Configure the relay pin as output and immediately set it to LOW — relay off.
  • Configure HomeSpan: control pin, status pin, pairing code, category, name.
  • Create one SpanAccessory with our service.

In loop() — only homeSpan.poll(). HomeSpan handles the network itself. If you need something periodic (sensor polling, logic updates), put it before or after homeSpan.poll().

Note The real generated code will differ slightly (fields like Manufacturer, Model, SerialNumber will be added, plus a Sn for the serial number). These are details — they don't affect logic.

9. Top toolbar

Left to right:

  • Project name and version (v3, v4, ...).
  • Device — opens device settings (name, category, pairing code, control/status pin).
  • IDE — Arduino IDE settings: board, frequency, flash size. Used as a hint for the generated sketch header.
  • History — project version history. Each save creates a new version.
  • Preview — preview of the generated .ino.
  • Save — save the project (creates a new version).
  • Back — return to the project list.
  • Help — this guide.

10. Service ribbon

Below the toolbar — the service ribbon. It replaces the old palette that used to live in the left panel.

How to use:

  1. At the top — category tabs: Doors & Locks, HVAC, Lights & Power, Security, Sensors, Water.
  2. Click a category — the icon row below changes.
  3. Click a service icon — the accessory appears on the canvas in the Devices section.

The full service name appears in the tooltip (hover). The icon shows a short name (Battery instead of BatteryService, Prog. Switch instead of StatelessProgrammableSwitch).

About 40 services: LightBulb, Switch, Outlet, Doorbell, TemperatureSensor, HumiditySensor, MotionSensor, Thermostat, Fan, TV, Door, GarageDoorOpener, LockMechanism, SecuritySystem, Valve, and others. The list comes from the official HomeSpan documentation.

11. Left panel

Four tabs — all global project resources:

  • Pins — all GPIO pins you will use.
  • Vars — global variables (shared across the whole program).
  • Const — named constants (e.g. MAX_PRESSES = 5).
  • Events — events for task/ISR synchronization.

Why on the left? Because these are global entities. They are available everywhere in the project. The right panel, on the other hand, shows local properties of the selected object.

Panel width is adjustable: drag the border between the panel and the canvas. The size is saved in the browser.

12. Canvas

The central area is the canvas. It shows project state in three sections:

  • DEVICES — accessory cards. Click a card — the accessory becomes selected, properties appear on the right.
  • LOGIC — rules of the selected accessory. Appears when you click an accessory.
  • ROUTINES — five tabs:
    • Setup — what happens in setup() before and after HomeSpan init.
    • Loop — what happens in loop() before and after homeSpan.poll().
    • User functions — your own functions.
    • Tasks — FreeRTOS tasks (parallel threads).
    • Interrupts — pin interrupt handlers.

13. Right panel

Shows properties of the selected object: accessory, rule, function, task, or ISR.

Four tabs:

  • Props — general properties (name, characteristics, parameters).
  • Vars — local variables of this entity (created when entering a function, discarded when leaving).
  • Body — list of actions (body of the rule / function / task / ISR).
  • Events — not used in the current version (Events moved to the left panel).

Smart behavior:

  • If a Setup / Loop rule is selected — there's no Props tab (nothing to configure), Body opens immediately.
  • If an On Change rule is selected — Props opens (trigger and Apply change settings).
  • If an existing object is selected (rule, task) — Body opens.
  • Inapplicable tabs become grayed out.

14. Device settings

The Device modal contains general parameters:

  • Device name — the name in HomeKit.
  • Category — the category (Lighting, Switches, Sensors, Bridges, …). Affects how the device appears in Home.
  • Pairing code — 8 digits. Entered when pairing.
  • Manufacturer / Model / Firmware — metadata, visible in Home under "Accessory".
  • Control pin / Status pin — the control button pin and the status LED pin. HomeSpan manages them itself.
  • Bridge mode — if enabled, the device becomes a bridge (can hold more than 100 accessories). In this mode the first accessory in the sketch is the bridge itself, and your devices follow as normal accessories.

15. Accessories

An accessory is a unit visible in HomeKit. For example: "Living room light", "Balcony temperature sensor".

Add an accessory: in the top service ribbon, pick the desired service. The accessory appears on the canvas with the default set of required characteristics.

What you can configure on an accessory:

  • Name — used in UI and code.
  • Characteristics — list of characteristics. Required ones can't be removed, optional ones can.
  • Fields — custom field variables at the C++ service level (rarely needed).

Three trigger buttons on the accessory card

  • +changed — create a "When characteristic changes" rule.
  • +loop — create an "Every accessory loop() iteration" rule.
  • +create — create an "On service creation" rule (runs once in the constructor).

Each rule type can exist only once per accessory. Once a rule is created, the corresponding button becomes grayed out.

Delete an accessory: the × in the top-right corner of the card.

16. Pins

Pins are a global resource: visible to all accessories and rules. Each pin corresponds to a #define NAME GPIO_NUM_N in the generated sketch.

Pin fields

  • Name — the name that goes into #define.
  • GPIO — pin number.
  • Role:
    • Input — for reading (buttons, sensors).
    • Output — for writing (relays, LEDs).
  • Mode:
    • Input: Plain, Pullup, Pulldown.
    • Output: Digital, Analog (PWM).
  • Interrupt mode (Input) — None, Change, Rising, Falling. If anything other than None is selected, the pin automatically gets an interrupt handler (see "Interrupts").
  • Auto-interrupt — if enabled, attachInterrupt() is called automatically at the end of setup(). If disabled, you must call the Enable Interrupt action manually.
  • Init When — when to initialize the pin: Urgent (before Serial.begin), Before HomeSpan, After HomeSpan, None.
  • Init Delay — delay after pinMode in milliseconds.
  • Owner — optional label indicating which accessory the pin belongs to. Used only for filtering in the UI.

What is generated: #define, pinMode(), attachInterrupt(), the function void IRAM_ATTR <PIN>_isr() (if interrupt is set), plus any actions you add to its body.

17. Variables and constants

Global variables (Vars tab on the left)

  • Name, Type (bool, int, uint8_t, uint32_t, float, String, char, event), Initial value.
  • Declared at the top of the sketch.
  • Variables used in an ISR (in any way — read or written) are automatically marked volatile.

Type event is special. A variable of this type stores which event fired (in C++ it's EventBits_t). Used together with the Wait event action (see "Actions"). No default value.

Named constants (Const tab on the left)

  • Generated as constexpr <type> <NAME> = <value>;.
  • Used where you want a named value: BELL_SIGNAL_DURATION = 250.
  • Available in the UI through the Named constant value source. Built-in Arduino constants HIGH and LOW are also there.

Local variables

Every entity (rule, function, task, ISR) has its own locals. Edited on the Vars tab of the right panel when that entity is selected.

18. Events

Events are a global resource. They are used to synchronize between tasks and interrupts.

A typical scenario: a button is pressed → the interrupt sets a `BUTTON_PRESSED` event → a task waits for that event and does something.

How to create an event: the Events tab in the left panel → + Add event. Give it a meaningful name (`BUTTON_PRESSED`, `MOTION_DETECTED`, etc.).

Limits: no more than 8 events per project. This is a FreeRTOS constraint (one event group has 24 usable bits, but we cap at 8 for UI simplicity).

What happens under the hood: if you have at least one event, the sketch creates a single global event group (g_eventGroup). Each event gets its own bit (#define EV_BUTTON_PRESSED (1 << 0)). The group is created at the very beginning of setup() — before everything else, because it may be used by ISRs and service constructors.

You don't need to think about bits and groups. Just create an event with a name and use it in the Signal, Clear, Wait actions and in the Event / Timeout / Is event set? value sources.

19. Rules — trigger and actions

Logic in a project is described by rules. A rule = trigger + list of actions.

  • Trigger answers "when does it fire".
  • Actions — what to do.

Every rule has a Body (list of actions) on the right panel, Body tab.

Actions run sequentially, top to bottom. You can nest conditions (`If`), loops (`Repeat`, `While`, `Do-While`) — they create nested lists.

20. Accessory triggers

Three kinds of accessory rules.

characteristic_update (button +changed)

Fires when HomeKit changed a characteristic. Generated inside boolean update() of the service class. Here you can return a value to accept or reject the change (see "Apply change?" in the rule properties).

loop_tick (button +loop)

Fires in void loop() of the service on every iteration. Usually used for polling sensors.

accessory_init (button +create)

Fires in the service constructor, once at startup. Useful for reading an initial characteristic value (SoundEnabled = m_On->getVal()) and initializing fields.

21. Setup and Loop

Global sections, analogous to Arduino's setup() and loop().

  • Setup before HomeSpan — runs before homeSpan.begin(). Put digitalWrite, initial pin states, variable initialization here.
  • Setup after HomeSpan — after homeSpan.begin(). Put attachInterrupt (if auto is off), xTaskCreate, event group creation here.
  • Loop before poll() — at the start of loop(), before homeSpan.poll().
  • Loop after poll() — at the end of loop(), after homeSpan.poll().

You can create a rule right from the card: if the rule already exists, the card expands; if not, a + Add button is shown.

22. User functions

Your own C++ functions. Generated as void <name>(<params>) { ... }.

What you can configure

  • Name — function name.
  • Parameters — name, type, direction (in, out, in/out). Direction only affects the signature (for C++ readability); there's no actual pass-by-reference.
  • Locals — local variables (declared at the top of the function).
  • Body — actions.

Call a function from another rule — action Call function.

23. Tasks

FreeRTOS tasks. Generated as xTaskCreate() + a loop function while (true) { ... }.

Task fields

  • Name — name.
  • Priority — Background / Normal / Realtime.
  • Stack size — stack size in bytes (usually 2048–4096).
  • Auto-start — if enabled, the task starts in setup(). Otherwise it must be started manually from a Create Task action.
  • Locals — task-level variables (declared before while(true), not re-created on each iteration).
  • Body — actions. Executed in a loop.
Important Inside a task you must not use blocking calls without vTaskDelay or delay() — otherwise the task will hog the CPU.

A task can use Wait event — a blocking wait for an event with a timeout. This is the main way to synchronize tasks with ISRs.

24. Interrupts

If a pin has Interrupt mode != None, it automatically gets an interrupt handler (ISR). All ISRs are collected on the Interrupts tab in Routines.

What you can configure

  • Pin — fixed. To change or remove the interrupt, edit the pin on the Pins tab.
  • Body — body of the ISR.
  • Locals — variables at ISR function level (created on each call; they're ordinary locals and don't persist between calls).

What is not allowed in an ISR

The frontend will not show these actions in the menu, and the backend will reject saving:

  • Delay
  • Print
  • Return
  • Create Task / Delete Task / End Task
  • Wait Event, Wait (wait_notification)
  • Enable Interrupt / Disable Interrupt

Reason: an ISR must run as fast as possible and not block the system. For long operations, use events (Signal event in the ISR, Wait event in a task) or flags processed in loop().

If auto-interrupt is enabled (usually yes), attachInterrupt() is called at the very end of setup() — after all accessories are created. This is needed so the ISR can safely access g_AccName->m_Char and global variables.

25. Actions reference

All available actions are grouped by category.

Values & Data

  • Set variable — assign a value to a variable.
  • Toggle variable — invert a bool variable.
  • Set characteristic — set a characteristic value on an accessory. Works both for "own" accessories and for others.
  • Call function — call a user function.

Pins & Signals

  • Set Pin State — digitalWrite(PIN, HIGH/LOW).
  • Write Pin — analogWrite(PIN, value) (PWM).
  • Enable Interrupt — attachInterrupt(PIN, ISR, MODE).
  • Disable Interrupt — detachInterrupt(PIN).

Flow Control

  • If — branching. Condition can be simple or compound (with AND / OR groups). The operator is binary (==, !=, >, <, >=, <=) or unary for bool (yes, no).
  • Repeat N times — for loop.
  • While — while loop.
  • Do-While — do { } while loop.
  • Break — break out of a loop.
  • Return — return from a function.
  • End Task — end the current task (task context only).

Tasks

  • Create Task — xTaskCreate (void context only).
  • Delete Task — delete a task.

Timing

  • Delay — delay(ms). The value can be any source: constant, variable, named constant, expression.

Debug

  • Print (Serial) — Serial.print with terminator choice (None, CR, LF, CRLF, LFCR).

Notifications & Events

  • Notify — notify a task (xTaskNotify).
  • Wait — wait for a notification (task only).
  • Signal — set an event (xEventGroupSetBits; in ISR — the FromISR version).
  • Clear — clear an event (xEventGroupClearBits; in ISR — the FromISR version).
  • Wait Event — wait for an event with a timeout, the result is saved into a variable of type event. Task only.

26. Value sources

Wherever a value is needed, these sources are available:

  • Constant — literal value (number, string, true/false).
  • Named constant — a named constant from the Const tab. Plus built-in HIGH / LOW.
  • Variable — global or local variable.
  • Characteristic — value of an accessory characteristic.
  • Get Pin State — digitalRead(PIN) (bool).
  • Read Pin — analogRead(PIN) (number).
  • Milliseconds / Microseconds — millis() / micros().
  • Event — a specific event as a value (to compare with a variable of type event).
  • Timeout — the constant 0. Used to check a timeout after Wait Event.
  • Is event set? — true if the event is currently set (no blocking, no clearing).
  • Expression — arithmetic or logic expression (Math: + − * / % & | ^ << >>, Logic: == != > < >= <=). Operators are grouped in the select. Expressions nest inside each other.
Filtering rule The set of available sources is limited by the target field type. For example, if the variable is bool, you can't put a number or string into it — the select will only show bool-compatible sources.

27. Conditions

A condition is a tree:

  • Comparison — <source> <op> <source> (binary) or <bool source> yes/no (unary).
  • AND group — all items true.
  • OR group — at least one item true.

Groups nest arbitrarily. The buttons + Add condition and + Add group add items and nested groups.

Left-hand side

Can be: variable, characteristic, `Get Pin State`, `Read Pin`. Constants and expressions are not allowed on the left — this is for logic readability.

Right-hand side

Depends on the type of the left:

  • Left = bool → Right: Constant (true/false), Variable (bool), Characteristic (bool), Get Pin State, Is event set?
  • Left = int / float → Right: Constant, Named constant, Variable, Characteristic, Read Pin
  • Left = string / char → Right: Constant, Variable, Characteristic
  • Left = event → Right: Event, Timeout, Variable (event)

Operators

  • For bool: yes, no, ==, !=. If you pick yes or no — the right side is hidden.
  • For int / float: ==, !=, >, <, >=, <=.
  • For string / char / event: ==, !=.

28. Code preview

The Preview button in the toolbar opens a modal with the generated .ino. The code is rebuilt from your schema. If the schema is invalid, errors are shown.

The Copy button copies the code to the clipboard.

29. IDE settings

The IDE button opens a modal with settings that end up as comments at the top of the generated sketch:

  • Board — board type.
  • CPU Frequency, Flash Mode, Flash Size, Partition Scheme, Upload Speed, and others.

You should set these values in Arduino IDE as well when compiling. We include them as a hint.

30. Version history

Every save creates a new project version. In History you see the list of versions with time and a short description.

Next to each version:

  • Restore — restore the project to that state.
  • Pencil — rename the version description.
  • Trash — delete one version. The current version cannot be deleted.

At the top there are checkboxes for bulk selection and a Delete selected button — delete several versions at once.

31. Compile and flash

  1. Save → Download .ino.
  2. In Arduino IDE: Sketch → Include Library → Manage Libraries → HomeSpan. Install it.
  3. Tools → Board → choose your board (e.g. ESP32C3 Dev Module).
  4. Tools → Port → choose the port the ESP32 is connected to.
  5. Upload.
  6. After flashing: Tools → Serial Monitor → speed 115200. You will see logs and the pairing code.
  7. In the Home app → + → Add Accessory → More options… → enter the pairing code.

32. Example: RF switching lamp

A device that:

  • Listens to an RF button on pin 10 via interrupt.
  • Drives a relay on pin 3.
  • Synchronizes state with HomeKit.

What to create

Pins

  • SWITCH_SIGNAL_PIN — GPIO 10, Input, Plain, interrupt Change, auto ON, init Before.
  • SWITCH_CONTROL_PIN — GPIO 3, Output, Digital, init Before.

Variables

  • LampState — bool, false.
  • CurrentLampState — bool, false.

Accessory

Lamp — LightBulb.

Rules

  • On Lamp, create +changed:
    • Set variable LampState = Characteristic On
    • Set variable CurrentLampState = Variable LampState
    • Set Pin State SWITCH_CONTROL_PIN = Variable LampState
  • ISR (Routines → Interrupts → SWITCH_SIGNAL_PIN):
    • Toggle variable LampState
  • Loop before poll():
    • If (CurrentLampState != LampState):
      • Set variable CurrentLampState = Variable LampState
      • Set characteristic Lamp.On = Variable CurrentLampState
      • Set Pin State SWITCH_CONTROL_PIN = Variable LampState
  • Setup before HomeSpan:
    • Set Pin State SWITCH_CONTROL_PIN = Named constant LOW

Result: RF button pressed → ISR toggles LampState → in loop() we see the states diverged → update HomeKit and the relay. HomeKit changes On → update() updates LampState and the relay.