Migrating from ZHA to Zigbee2MQTT without re-pairing
Contents
Introduction#
My Home Assistant Zigbee network ran on ZHA. Since 20 October 2026, Zigbee2MQTT has owned the coordinator instead, and all 73 devices came across without me re-pairing a single one. That is what this post is about: a reproducible path from ZHA to Zigbee2MQTT on the same coordinator, without touching the devices. I run Zigbee2MQTT on K3s, but the migration itself doesn’t care where the container runs. Plain Podman or Docker Compose works just as well.
Tested with Zigbee2MQTT 2.14.2 (official container image), Home Assistant 2026.10, an SMLIGHT SLZB-06Mg24U network coordinator with EmberZNet 8.0.2 (EZSP 14).
Why Zigbee2MQTT#
I migrated to Zigbee2MQTT because it supports a wider ecosystem of Zigbee devices, especially new ones, without needing a bunch of quirks running in the Home Assistant code until a device gets proper support. A lot of devices also expose many more options through Zigbee2MQTT. And I was tired of battery devices going “unavailable” in ZHA. With Zigbee2MQTT and MQTT, that is fixed.
A side effect I like: the Zigbee stack no longer runs inside the Home Assistant process. Zigbee2MQTT can be restarted, upgraded and backed up on its own.
What has to carry over#
A Zigbee network is defined by its channel, PAN ID, extended PAN ID and network key. If Zigbee2MQTT drives the coordinator with exactly these values, the devices don’t notice that different software is in charge. If one of them is wrong, every device has to be paired again.
Two more things matter:
- The frame counter. Devices drop frames whose counter is lower than one they have already seen. It only matters if the network has to be re-formed from a backup, which happened in my migration (see the frame counter margin).
- The device database. Zigbee2MQTT only processes messages from devices that are in its own
database.db. Traffic from anything else is logged as coming from an unknown device and skipped. ZHA’s device list has to be converted too, or the network comes up and every device is effectively invisible.
The Zigbee2MQTT FAQ is cautious about adapter migrations: switching adapters normally requires re-pairing, and the exceptions are “not officially supported”. This case is simpler, though. The adapter stays the same and only the software in front of it changes.
Prerequisites#
- A Silicon Labs coordinator with EmberZNet firmware, used with Zigbee2MQTT’s
emberdriver. The Zigbee2MQTT docs list EmberZNet 7.4.x to 9.1.x as supported, andemberonly accepts backups from EZSP 12 or newer. - ZHA running on that coordinator through bellows (the EZSP radio type), so its backups contain the EmberZNet-specific parts Zigbee2MQTT needs.
- An MQTT broker that Home Assistant and Zigbee2MQTT both use, with MQTT discovery enabled in Home Assistant.
My coordinator is an SMLIGHT SLZB-06Mg24U on wired Ethernet. It exposes the radio as a serial port over TCP on port 6638. Zigbee2MQTT advises against running such adapters over Wi-Fi or other high-latency links.
The migration, step by step#
1. Take a fresh ZHA backup and stop ZHA#
ZHA takes automatic network backups, and manual ones can be created under Network Settings on the ZHA configuration page. Create one right before the switch, so the backup is as close as possible to the live state.
Then disable the ZHA integration in Home Assistant. Don’t delete it: it is your rollback. Only one program may use the coordinator at a time, and the Home Assistant docs say the same about ZHA: the coordinator “cannot already be connected or used by any other application”.
Now copy zigbee.db out of the Home Assistant configuration directory. It holds both ZHA’s device database and its network backups. With ZHA disabled, nothing writes to it any more. sqlite3 gives you a consistent single-file copy:
sqlite3 /config/zigbee.db ".backup /tmp/zigbee-copy.db"
2. Convert ZHA’s data#
The conversion produces three files from zigbee.db:
coordinator_backup.jsonfrom ZHA’s newest network backup,database.dbfrom ZHA’s device tables,network.yamlwith the values for Zigbee2MQTT’s configuration.
The original conversion was done by an AI agent working with me. The script below is a condensed version of the same mapping, cross-checked against the zigpy and zigbee-herdsman source code. It only needs zigpy:
python3 -m venv venv
./venv/bin/pip install zigpy
./venv/bin/python zha2z2m.py /tmp/zigbee-copy.db ./out
python zha2z2m.py
#!/usr/bin/env python3
"""Convert ZHA's zigbee.db into Zigbee2MQTT's coordinator_backup.json and database.db.
Usage: zha2z2m.py zigbee.db OUTDIR (needs: pip install zigpy)
"""
import json, os, re, sqlite3, sys
from zigpy.backups import NetworkBackup
FRAME_COUNTER_MARGIN = 2_000_000
TYPES = {0: "Coordinator", 1: "Router", 2: "EndDevice"}
POWER = {0: "Unknown", 1: "Mains (single phase)", 2: "Mains (3 phase)", 3: "Battery",
4: "DC Source", 5: "Emergency mains constantly powered",
6: "Emergency mains and transfer switch"}
BASIC = {0: "zclVersion", 1: "appVersion", 2: "stackVersion", 3: "hwVersion",
4: "manufName", 5: "modelId", 6: "dateCode", 7: "powerSource", 0x4000: "swBuildId"}
src, out = sys.argv[1], sys.argv[2]
db = sqlite3.connect(f"file:{src}?mode=ro", uri=True)
tables = [n for (n,) in db.execute("SELECT name FROM sqlite_master WHERE type='table'")]
v = max(int(m.group(1)) for n in tables if (m := re.fullmatch(r"devices_v(\d+)", n)))
q = lambda sql, *a: db.execute(sql.replace("{v}", str(v)), a).fetchall()
os.makedirs(out, exist_ok=True)
os.umask(0o077)
# 1. Coordinator backup: newest ZHA network backup, as open coordinator backup JSON.
(raw,) = q("SELECT backup_json FROM network_backups_v{v} ORDER BY id DESC LIMIT 1")[0]
ocb = NetworkBackup.from_dict(json.loads(raw)).as_open_coordinator_json()
assert ocb["metadata"]["internal"].get("ezspVersion", 0) >= 12, "ember needs an EZSP >= 12 backup"
# ember expects the extended PAN ID in coordinator byte order (see step 3)
ext_pan = bytes.fromhex(ocb["extended_pan_id"])[::-1]
ocb["extended_pan_id"] = ext_pan.hex()
# same byte order as the backups Zigbee2MQTT writes itself
ocb["coordinator_ieee"] = bytes.fromhex(ocb["coordinator_ieee"])[::-1].hex()
ocb["network_key"]["frame_counter"] += FRAME_COUNTER_MARGIN
with open(f"{out}/coordinator_backup.json", "w") as f:
json.dump(ocb, f, indent=2)
# 2. Values for configuration.yaml (advanced) and secret.yaml (network_key).
with open(f"{out}/network.yaml", "w") as f:
f.write(f"pan_id: {int(ocb['pan_id'], 16)}\n"
f"ext_pan_id: {list(ext_pan)}\n"
f"channel: {ocb['channel']}\n"
f"network_key: {list(bytes.fromhex(ocb['network_key']['key']))}\n")
# 3. Device database: one JSON object per line.
def value(raw):
if isinstance(raw, bytes):
raw = raw.decode("utf-8", "replace")
return raw.strip("\x00 ") if isinstance(raw, str) else raw
lines, next_id = [], 2
for ieee, nwk, last_seen in q("SELECT ieee, nwk, last_seen FROM devices_v{v} ORDER BY ieee"):
nd = q("SELECT logical_type, manufacturer_code, mac_capability_flags"
" FROM node_descriptors_v{v} WHERE ieee = ?", ieee)
logical, manuf_code, mac_flags = nd[0] if nd else (None, None, 0)
if logical == 0:
continue # Zigbee2MQTT adds the coordinator itself
entry = {"id": next_id, "type": TYPES.get(logical, "Unknown"),
"ieeeAddr": "0x" + ieee.replace(":", "").lower(), "nwkAddr": nwk,
"manufId": manuf_code, "epList": [], "endpoints": {},
"lastSeen": int(last_seen * 1000) if last_seen else None, "meta": {}}
# Mains power bit of the MAC capability flags; the Basic cluster overrides it below.
entry["powerSource"] = POWER[1] if mac_flags & 0x04 else POWER[3]
for ep, profile, dev_type in q("SELECT endpoint_id, profile_id, device_type FROM endpoints_v{v}"
" WHERE ieee = ? AND endpoint_id != 0 ORDER BY endpoint_id", ieee):
clusters = q("SELECT cluster_type, cluster_id FROM clusters_v{v}"
" WHERE ieee = ? AND endpoint_id = ? ORDER BY cluster_id", ieee, ep)
entry["epList"].append(ep)
entry["endpoints"][str(ep)] = {
"profId": profile, "epId": ep, "devId": dev_type,
"inClusterList": [c for t, c in clusters if t == 0],
"outClusterList": [c for t, c in clusters if t == 1],
"clusters": {}, "binds": [], "configuredReportings": [], "meta": {}}
for attr, raw in q("SELECT attr_id, value FROM attributes_cache_v{v} WHERE ieee = ? AND cluster_id = 0"
" AND cluster_type = 0 AND manufacturer_code IS NULL AND IFNULL(status, 0) = 0"
" AND value IS NOT NULL ORDER BY endpoint_id DESC", ieee):
if attr in BASIC:
entry[BASIC[attr]] = value(raw)
if isinstance(entry["powerSource"], int):
entry["powerSource"] = POWER.get(entry["powerSource"] & 0x7F, "Unknown")
ok = bool(entry.get("modelId")) and bool(entry["epList"])
entry["interviewCompleted"] = ok
entry["interviewState"] = "SUCCESSFUL" if ok else "FAILED"
lines.append(json.dumps(entry))
next_id += 1
with open(f"{out}/database.db", "w") as f:
f.write("\n".join(lines) + "\n")
print(f"{len(lines)} devices, schema v{v}, frame counter +{FRAME_COUNTER_MARGIN}")The output files contain the network key. Treat them like a password, and delete the out directory once Zigbee2MQTT runs.
The coordinator backup#
ZHA stores its network backups in zigpy’s own JSON format. zigpy can export that as an Open Coordinator Backup, the format Zigbee2MQTT reads from coordinator_backup.json. bellows already adds the two EmberZNet-specific fields Zigbee2MQTT needs: stack_specific.ezsp.hashed_tclk and metadata.internal.ezspVersion.
The script also reverses the extended PAN ID (see step 3) and adds a margin to the frame counter.
The device database#
database.db is a text file with one JSON object per device. The script fills it from ZHA’s devices, node_descriptors, endpoints, clusters and attributes_cache tables. Their _vNN suffix is zigpy’s schema version (15 or 16 at the moment); the script picks the newest.
The coordinator itself is left out: Zigbee2MQTT creates its entry on first start. Binds, reporting configuration and the per-device meta stay empty. Zigbee2MQTT then treats each device as not yet configured and runs its configure step: routers right after startup, ten seconds apart, and the other devices the next time they report in.
The model ID is what Zigbee2MQTT uses to find a device definition, so it decides whether a device works straight away. In my case, all 73 devices had one.
The frame counter margin#
A backup is a snapshot. The coordinator keeps sending frames after it was taken, so its live frame counter is always ahead of the one in the file.
On the normal path, this doesn’t matter: Zigbee2MQTT finds the existing network on the coordinator, which keeps its own counter, and the backup file isn’t used. It matters once Zigbee2MQTT re-forms the network from coordinator_backup.json: the ember driver writes the counter from the file to the coordinator as it is. Without a margin, the coordinator would start below what the devices have already seen from it, and they would drop its frames until the counter caught up.
That is what happened to me. The first two attempts wiped the network, and it came back from the backup with the margin added.
zigpy’s own restore_backup() adds 10,000 by default. 2,000,000 is much larger, but the counter is 32 bits wide, so that costs nothing.
3. Write the configuration#
The network values from network.yaml go into the advanced section of configuration.yaml. The network key goes into a separate secret.yaml, which Zigbee2MQTT resolves through '!secret.yaml …' references (the quotes are required).
All values below are examples:
# configuration.yaml
version: 5
mqtt:
server: '!secret.yaml mqtt_server'
user: '!secret.yaml mqtt_user'
password: '!secret.yaml mqtt_password'
base_topic: zigbee2mqtt
serial:
port: tcp://coordinator.example.lan:6638
adapter: ember
baudrate: 115200
advanced:
network_key: '!secret.yaml network_key'
pan_id: 4660
ext_pan_id: [136, 119, 102, 85, 68, 51, 34, 17]
channel: 25
homeassistant:
enabled: true
legacy_action_sensor: false
availability:
enabled: true
frontend:
enabled: true
port: 8080
permit_join: false
# secret.yaml
mqtt_server: mqtts://mqtt.example.lan:8883
mqtt_user: zigbee2mqtt
mqtt_password: <password>
network_key: [<16 decimal bytes from network.yaml>]
The byte order is where it is easiest to go wrong. ZHA shows the extended PAN ID in reverse of the order it writes to the coordinator:
ZHA shows: 11:22:33:44:55:66:77:88
stored on the radio: 88 77 66 55 44 33 22 11
ext_pan_id: [136, 119, 102, 85, 68, 51, 34, 17]
ext_pan_id takes the stored order, as a list of eight bytes. The network key is not reversed: network_key is a list of 16 bytes in the order ZHA shows them. The PAN ID is a plain number; YAML accepts it as decimal (4660) or hex (0x1234).
availability is off by default. With it on, Zigbee2MQTT marks mains devices offline after 10 minutes without contact and a failed ping, and battery devices after 25 hours of silence.
4. Put the files in place and start Zigbee2MQTT#
The data directory needs configuration.yaml, secret.yaml, coordinator_backup.json and database.db before the first start. If Zigbee2MQTT has ever started against this data directory, remove the old coordinator_backup.json, database.db and state.json first. Stale state from an earlier attempt is exactly what you don’t want here.
With Podman or Docker Compose, a network coordinator needs no device mapping:
# compose.yaml
services:
zigbee2mqtt:
image: ghcr.io/koenkk/zigbee2mqtt:2.14.2
restart: unless-stopped
volumes:
- ./data:/app/data
ports:
- 8080:8080
environment:
- TZ=Europe/Berlin
cp out/coordinator_backup.json out/database.db data/
podman compose up -d # or: docker compose up -d
podman compose logs -f zigbee2mqtt
On K3s, the same files go onto the data volume before the Deployment is scaled up. See Running it on K3s.
5. Check the startup log#
These are the lines you want to see:
zh:ember: [INIT TC] Adapter network matches config.
z2m: zigbee-herdsman started (resumed)
z2m: Currently 73 devices are joined.
z2m: Connected to MQTT server
“resumed” means Zigbee2MQTT took over the existing network. If the log says Adapter network does not match config. Leaving network... instead, at least one of PAN ID, extended PAN ID or network key doesn’t match. Zigbee2MQTT then leaves the network on the coordinator and forms a new one: from coordinator_backup.json if that matches the configuration (“restored”), otherwise from the configuration alone (“reset”). “reset” means a new network with a frame counter of zero, so stop Zigbee2MQTT and roll back.
After that, check the frontend. Mains devices should show up within minutes. Sleeping battery devices appear when they next report; pressing a button or triggering a sensor speeds that up.
6. Clean up Home Assistant#
After the switch, Home Assistant has every device twice: the old ZHA entities, now unavailable, and new MQTT entities whose IDs come from Zigbee2MQTT’s friendly names. Automations, scripts, scenes and dashboards still point at the old entity IDs, and automations that used ZHA device triggers or zha_event need new triggers.
It helps to give devices their final friendly names in Zigbee2MQTT first, so the generated entity IDs are usable. I let an AI agent do the rest, through ha-mcp, a Home Assistant MCP server installed from HACS. It exposes a lot more of Home Assistant than the built-in MCP integration, so the agent could fix the entity IDs and the automations that referenced them.
Rolling back to ZHA#
ZHA stays installed but disabled in Home Assistant. Both programs know the same network: same channel, PAN ID, extended PAN ID and key. So the rollback is:
- Stop Zigbee2MQTT and make sure it stays stopped.
- Re-enable the ZHA integration in Home Assistant.
If Zigbee2MQTT left the network and formed a new one (anything other than “resumed”), the original network on the coordinator is gone. Then restore ZHA’s latest automatic network backup to the coordinator from ZHA’s network settings, so that ZHA gets its network back. I had to do that twice.
Running it on K3s#
I run Zigbee2MQTT on K3s, managed by Argo CD. The cut-over was a single commit that changed replicas: 0 to replicas: 1. Two things matter on any orchestrator:
- Never run two instances. Only one process may talk to the coordinator, so use
strategy: Recreate. A rolling update would briefly run the old and the new pod side by side. - Seed the configuration, don’t mount it. Zigbee2MQTT rewrites its own
configuration.yaml(schema migrations, frontend settings, renames), so aConfigMapcan’t be the live file. An init container copies the seed only if no file exists yet and sets mode0600. TheConfigMapis mounted read-only andcpkeeps that mode, so without it Zigbee2MQTT fails withEACCES. If the init container also pins values, it has to handle both YAML list styles: Zigbee2MQTT rewrote myext_pan_id: [a, b, …]as a block list, my patch left the old items behind, and the pod crash-looped after a reboot.
secret.yaml stays out of that file and is mounted from a Kubernetes Secret.
What went wrong on the way#
It took three attempts on the same afternoon. Both problems are handled in the steps above, but this is what they looked like.
The extended PAN ID was reversed#
I had copied the extended PAN ID in the order ZHA displays it. On startup, Zigbee2MQTT found a network on the adapter that didn’t match its configuration, left it and formed a new one. That happened on both of the first two attempts. Each time, I scaled Zigbee2MQTT back to zero and gave the coordinator back to ZHA. With the stored byte order, the third attempt logged “resumed”.
Zigbee2MQTT ignored every device#
On the second attempt, coordinator_backup.json came from ZHA’s backup, and the network came up with ZHA’s key and frame counter. But database.db didn’t exist yet, so Zigbee2MQTT skipped the traffic from all 73 devices as unknown. Converting zigbee.db to database.db fixed that.
Result#
Zigbee2MQTT has run the network since the third attempt on 20 October 2026, and all 73 devices came across without re-pairing.
Sources#
- Zigbee2MQTT, EmberZNet adapters (
emberdriver, supported firmware, EZSP 12+ backups, latency warning) - Zigbee2MQTT, Adapter settings (
serial,tcp://ports,baudrate) - Zigbee2MQTT, Zigbee network (
network_key,pan_id,ext_pan_id,channel) - Zigbee2MQTT, MQTT (
!secret.yamlreferences for MQTT credentials andnetwork_key) - Zigbee2MQTT, Device availability
- Zigbee2MQTT, FAQ (adapter migration and what requires re-pairing)
- zigbee-herdsman,
emberadapter (network init, backup restore) - zigpy, network backups (
restore_backup()counter increment, Open Coordinator Backup export) - zigpy, Open Coordinator Backup format
- Home Assistant, Zigbee Home Automation (network backups, single-application coordinator)
- SMLIGHT, SLZB-06 series manual (network coordinator, TCP port 6638)
- ha-mcp, Home Assistant MCP server