Skip to content

Instantly share code, notes, and snippets.

@archite
Last active March 17, 2025 04:15
Show Gist options
  • Save archite/1930050f3c5ac032b418f83313d8d5dc to your computer and use it in GitHub Desktop.
Save archite/1930050f3c5ac032b418f83313d8d5dc to your computer and use it in GitHub Desktop.
Use pyscript to generate z2m config from zha
import homeassistant.helpers.template as template
from box import Box, BoxList
class ZHADevice:
def __init__(self, dev_info) -> None:
dev_info = Box(dev_info.zha_device_info)
self.db_data = Box(
ieeeAddr=f"0x{dev_info.ieee.replace(':', '')}",
manufId=dev_info.manufacturer_code,
nwkAddr=dev_info.nwk.real,
type=dev_info.device_type,
)
self.config_data = Box(
box_dots=True,
default_box=True,
)
if ugn := getattr(dev_info, "user_given_name"):
self.config_data.friendly_name = ugn
if aid := getattr(dev_info, "area_id"):
self.config_data.homeassistant.device.suggested_area = template.area_name(
hass, aid
)
class Z2MConfig:
def __init__(self):
zgp = hass.data["zha"].gateway_proxy
zdp = zgp.device_proxies
zg = zgp.gateway
nwk_info = zg.state.network_info
self.config_data = Box(
default_box=True,
)
self.db_data = BoxList()
self.config_data.advanced = Box(
channel=int(nwk_info.channel),
ext_pan_id=[int(i) for i in reversed(nwk_info.extended_pan_id)],
network_key=[int(i) for i in nwk_info.network_key.key],
pan_id=int(nwk_info.pan_id),
)
for i, d in enumerate(zdp.values(), start=1):
zd = ZHADevice(d)
self.config_data.devices[zd.db_data.ieeeAddr] = zd.config_data
if zd.db_data.type != "Coordinator":
self.db_data.append(Box(id=i, **zd.db_data))
@pyscript_compile
def save(self, config_file="zha2z2m.yaml", db_file="zha2z2m.json"):
self.config_data.to_yaml(filename=f"/config/{config_file}")
self.db_data.to_json(filename=f"/config/{db_file}", indent=2)
@service
def zha2z2m(config_file, db_file):
"""yaml
name: ZHA to Z2M Generator
description: Creates Z2M configuration data based on ZHA data.
fields:
config_file:
name: Configuration File Name
description: Configuration file name to create in `/config/`
default: zha2z2m.yaml
example: zha2z2m.yaml
required: true
selector:
text:
db_file:
name: Database File Name
description: Database file name to create in `/config/`
default: zha2z2m.json
example: zha2z2m.json
required: true
selector:
text:
"""
z2mc = Z2MConfig()
z2mc.save(config_file, db_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment