geekcowboy.neta florea.xyz revival

Home automation

X10 lights in Home Assistant, through an Arduino and MQTT

Home Assistant's X10 support needs a USB interface that is now sold out. If you have a TW523 or PSC05 and an Arduino, one small Python script puts every X10 module in Home Assistant as a light, and keeps it in step when someone uses an old X10 remote.

By florea.xyz ·

You have X10 modules that still work and a Home Assistant install that runs everything else. Home Assistant can talk to X10 through its Mochad integration, but that needs a CM15A or CM19A USB interface, and both were sold out at x10.com when this was written. If you have a TW523 or PSC05 instead, and an Arduino running the X10 bridge sketch, this script fills the gap:

  • every X10 unit you list appears in Home Assistant as a light, through MQTT discovery;
  • switching it in Home Assistant sends A1 ON to the bridge;
  • when someone presses a button on an X10 remote or a wall controller, the bridge hears it and the light’s state in Home Assistant follows.

What you need

  • The Arduino and TW523 or PSC05, wired and running x10_bridge.ino as in the bridge article.
  • A computer next to it that runs Python 3.10 or newer: the Home Assistant machine itself if it runs a full OS, or a Raspberry Pi. The script runs with uv, which fetches its two dependencies (pyserial and paho-mqtt) by itself.
  • An MQTT broker and Home Assistant’s MQTT integration. If you do not have one yet, the Mosquitto broker add-on is the usual choice.

The script

x10_mqtt.py

# /// script
# requires-python = ">=3.10"
# dependencies = ["pyserial==3.5", "paho-mqtt==2.1.0"]
# ///
"""x10_mqtt.py: X10 lights in Home Assistant, through an Arduino running x10_bridge.ino and MQTT.

    uv run x10_mqtt.py --serial /dev/ttyACM0 --mqtt localhost --unit A1 --unit A2 --unit B5
    uv run x10_mqtt.py --self-test

Each --unit appears in Home Assistant as a light (MQTT discovery). Switching it sends "A1 ON" to the bridge; codes
the bridge hears from remotes and controllers ("RX A1", "RX A ON") update the lights' state.
geekcowboy.net, 2026. MIT licence.
"""
import argparse
import json
import os
import queue
import re
import sys
import time

FUNCTIONS_OFF = {'OFF', 'ALLUNITSOFF', 'ALLLIGHTSOFF'}
UNIT = r'[A-P]([1-9]|1[0-6])'  # a house letter and a unit number, as the bridge prints them


class X10State:
    """X10 addressing: a module remembers that it was addressed until a function follows; the next address after a
    function starts a new selection. Plain modules never report, so this is all a listener can know."""

    def __init__(self, units):
        self.units = set(units)
        self.selected = {}         # house letter -> set of addressed units
        self.after_function = {}   # house letter -> the last code for that house was a function

    def feed(self, line):
        """One line from the bridge. Returns [(unit, 'ON' | 'OFF')] for configured units whose state changed."""
        m = re.fullmatch(f'RX ({UNIT})', line)
        if m:
            unit = m.group(1)
            house = unit[0]
            if self.after_function.get(house, True):
                self.selected[house] = set()
            self.selected[house].add(unit)
            self.after_function[house] = False
            return []
        m = re.fullmatch(r'RX ([A-P]) ([A-Z]+)', line)
        if not m:
            return []
        house, fn = m.groups()
        self.after_function[house] = True
        mine = sorted(u for u in self.units if u[0] == house)
        if fn in ('ALLUNITSOFF', 'ALLLIGHTSON', 'ALLLIGHTSOFF'):
            targets = mine  # shortcut: every configured unit is treated as a lamp module, which obeys these
        elif fn in ('ON', 'OFF'):
            targets = sorted(self.selected.get(house, set()) & self.units)
        else:
            return []  # DIM, BRIGHT, STATUS...: no on/off change a listener can be sure of
        state = 'OFF' if fn in FUNCTIONS_OFF else 'ON'
        return [(u, state) for u in targets]


def self_test():
    s = X10State(['A1', 'A2', 'A3', 'B5'])
    assert s.feed('RX A1') == [] and s.feed('RX A2') == []
    assert s.feed('RX A ON') == [('A1', 'ON'), ('A2', 'ON')]
    assert s.feed('RX A3') == []                      # a new selection after a function
    assert s.feed('RX A OFF') == [('A3', 'OFF')]
    assert s.feed('RX A DIM') == []
    assert s.feed('RX A ALLUNITSOFF') == [('A1', 'OFF'), ('A2', 'OFF'), ('A3', 'OFF')]
    assert s.feed('RX C7') == [] and s.feed('RX C ON') == []   # not configured
    assert s.feed('RX B5') == [] and s.feed('RX B ON') == [('B5', 'ON')]
    assert s.feed('RX B ON') == [('B5', 'ON')]        # repeated function, same selection
    for junk in ('', 'OK', 'ERR the unit is 1-16', 'RX Q1', 'RX A17', 'RX A on', 'x10_bridge ready: try A1 ON'):
        assert s.feed(junk) == [], junk
    for bad in ('Z1', 'A0', 'A17', 'AA', '1A', 'A1 '):
        assert not re.fullmatch(UNIT, bad), bad
    print('x10_mqtt: self-test passed')


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument('--serial', help='the Arduino, e.g. /dev/ttyACM0')
    ap.add_argument('--mqtt', default='localhost', help='MQTT broker host (default localhost)')
    ap.add_argument('--port', type=int, default=1883)
    ap.add_argument('--unit', action='append', default=[], help='an X10 unit to expose, e.g. A1 (repeat)')
    ap.add_argument('--self-test', action='store_true')
    args = ap.parse_args()
    if args.self_test:
        return self_test()
    units = [u.upper() for u in args.unit]
    bad = [u for u in units if not re.fullmatch(UNIT, u)]
    if not args.serial or not units or bad:
        ap.error(f'need --serial and at least one --unit like A1 (bad: {", ".join(bad)})' if bad
                 else 'need --serial and at least one --unit like A1')

    import serial
    import paho.mqtt.client as mqtt

    state = X10State(units)
    commands = queue.Queue()  # (unit, 'ON' | 'OFF') from Home Assistant, sent to the bridge one at a time
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=f'x10-mqtt-{os.getpid()}')
    if os.environ.get('MQTT_USER'):
        client.username_pw_set(os.environ['MQTT_USER'], os.environ.get('MQTT_PASSWORD'))
    client.will_set('x10/bridge/status', 'offline', retain=True)

    def on_connect(client, userdata, flags, reason_code, properties):
        if reason_code.is_failure:
            print(f'MQTT refused the connection: {reason_code}', file=sys.stderr)
            return
        for u in units:
            config = {'name': None, 'unique_id': f'x10_{u.lower()}',
                      'command_topic': f'x10/{u}/set', 'state_topic': f'x10/{u}/state',
                      'availability_topic': 'x10/bridge/status',
                      'device': {'identifiers': [f'x10_{u.lower()}'], 'name': f'X10 {u}', 'manufacturer': 'X10'}}
            client.publish(f'homeassistant/light/x10_{u.lower()}/config', json.dumps(config), retain=True)
        client.subscribe('x10/+/set')
        client.publish('x10/bridge/status', 'online', retain=True)

    def on_message(client, userdata, msg):
        unit, payload = msg.topic.split('/')[1], msg.payload.decode(errors='replace').upper()
        if unit in units and payload in ('ON', 'OFF'):
            commands.put((unit, payload))

    client.on_connect, client.on_message = on_connect, on_message
    port = serial.Serial(args.serial, 115200, timeout=0.1)
    deadline = time.monotonic() + 5  # opening the port resets most Arduinos: wait for the sketch to start
    while time.monotonic() < deadline and b'ready' not in port.readline():
        pass
    client.connect(args.mqtt, args.port)
    client.loop_start()

    def publish(changes):
        for unit, value in changes:
            client.publish(f'x10/{unit}/state', value, retain=True)

    try:
        while True:
            try:
                unit, value = commands.get_nowait()
            except queue.Empty:
                line = port.readline().decode(errors='replace').strip()
                if line:
                    publish(state.feed(line))
                continue
            port.write(f'{unit} {value}\n'.encode())
            deadline = time.monotonic() + 5  # a command takes about 0.8 s on the mains
            while time.monotonic() < deadline:
                line = port.readline().decode(errors='replace').strip()
                if line == 'OK':  # on the line; our own codes are not echoed back, so update the state here
                    publish(state.feed(f'RX {unit}') + state.feed(f'RX {unit[0]} {value}'))
                    break
                if line.startswith('ERR'):
                    print(f'{unit} {value}: {line}', file=sys.stderr)
                    break
                if line:
                    publish(state.feed(line))
            else:
                print(f'{unit} {value}: no answer from the bridge', file=sys.stderr)
    except KeyboardInterrupt:
        pass
    finally:
        client.publish('x10/bridge/status', 'offline', retain=True).wait_for_publish(2)
        client.loop_stop()
        client.disconnect()


if __name__ == '__main__':
    main()

Running it

Plug the Arduino in and find its serial port. The names under /dev/serial/by-id/ stay the same across reboots, unlike /dev/ttyACM0. Then:

export MQTT_USER=x10 MQTT_PASSWORD=...        # if your broker needs a login
uv run x10_mqtt.py --serial /dev/serial/by-id/usb-Arduino...-if00 --mqtt homeassistant.local --unit A1 --unit A2 --unit B5

The MQTT login is read from the environment rather than the command line, because other users on the machine can see command lines. Run it under systemd or in a tmux session so it survives logging out.

In Home Assistant, three lights appear: X10 A1, X10 A2 and X10 B5, each its own device. They become unavailable when the script stops, because the script registers a “last will” with the broker.

The topics, if you want to use them from something else:

Topic Who writes it What
homeassistant/light/x10_a1/config the script, retained discovery: the light and its topics
x10/A1/set Home Assistant ON or OFF
x10/A1/state the script, retained ON or OFF, as far as it knows
x10/bridge/status the script, and the broker’s last will online or offline

How it keeps track

X10 addressing has a quirk the script has to follow. A remote that switches A1 and A2 on together sends A1, A2, then A ON: each module remembers that it was addressed until a function arrives. The next address after a function starts a new selection. X10State does the same bookkeeping, so RX A1, RX A2, RX A ON turns both lights on in Home Assistant, and a later RX A3, RX A OFF turns off only A3.

Commands from Home Assistant go to the bridge one at a time through a queue, because each one occupies the mains for about 0.8 seconds. The bridge does not echo the codes it sends itself, so the script updates the state when the bridge answers OK.

What it cannot know

“As far as it knows” in the table above is meant literally. Plain X10 modules never report their state, so:

  • if someone switches a lamp at the module, or a code is lost to noise, Home Assistant shows the wrong state until the next command;
  • dimming is not tracked: DIM and BRIGHT are ignored;
  • “all lights on” and “all lights off” are applied to every unit you listed. Appliance modules actually ignore those two codes, so do not rely on the state of an appliance module after one.

That is X10, not the script. It is also why the security article says to keep anything important off it.

How it was tested

  • uv run x10_mqtt.py --self-test runs the addressing logic through selections, repeated functions, “all units off”, units that are not configured, and garbage lines.
  • An end-to-end test starts a real Mosquitto 2 broker in a container and a fake Arduino on a pseudo-terminal that answers OK like the sketch. A small MQTT client plays Home Assistant. It checks that the discovery messages are correct and retained, that switching A1 on sends exactly A1 ON to the serial port and sets the state, that a remote’s RX A2, RX A OFF changes A2 but not A1, and that junk payloads and unknown units never reach the serial port.

It has not been run against a real Home Assistant install or a real TW523 for this article. If you try it and something does not match, write in.