Skip to content

Commit 8c5c42f

Browse files
tomer-wCopilot
andcommitted
Add on_new_device support and parent device via_device linking
Register devices in HA device registry via on_new_device callback, which fires before on_new_metric in topological order. Sub-devices (like SwitchableOutputs) are linked to their parent via via_device. Changes: - _on_new_device: registers devices in HA device registry proactively - _map_device_info: uses device.parent_device for via_device instead of hardcoding system_0 - DeviceType check for system device instead of unique_id comparison Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 0582a09 commit 8c5c42f

1 file changed

Lines changed: 22 additions & 2 deletions

File tree

  • custom_components/victron_mqtt

custom_components/victron_mqtt/hub.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
)
2525
from homeassistant.core import HomeAssistant
2626
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
27+
from homeassistant.helpers import device_registry as dr
2728
from homeassistant.helpers.device_registry import DeviceInfo
2829
from homeassistant.helpers.redact import async_redact_data
2930

@@ -106,6 +107,8 @@ def __init__(self, hass: HomeAssistant, entry: VictronGxConfigEntry) -> None:
106107
),
107108
)
108109
self._hub.on_new_metric = self._on_new_metric
110+
self._hub.on_new_device = self._on_new_device
111+
self._config_entry_id = entry.entry_id
109112
self.new_metric_callbacks: dict[MetricKind, NewMetricCallback] = {}
110113

111114
async def start(self) -> None:
@@ -127,6 +130,21 @@ async def stop(self) -> None:
127130
_LOGGER.info("Stopping hub")
128131
await self._hub.disconnect()
129132

133+
def _on_new_device(
134+
self,
135+
hub: VictronVenusHub,
136+
device: VictronVenusDevice,
137+
) -> None:
138+
"""Register a new device in the HA device registry."""
139+
_LOGGER.info("New device received. Device: %s", device)
140+
assert hub.installation_id is not None
141+
device_info = Hub._map_device_info(device, hub.installation_id)
142+
device_registry = dr.async_get(self.hass)
143+
device_registry.async_get_or_create(
144+
config_entry_id=self._config_entry_id,
145+
**device_info,
146+
)
147+
130148
def _on_new_metric(
131149
self,
132150
hub: VictronVenusHub,
@@ -155,8 +173,10 @@ def _map_device_info(
155173
model=device.model,
156174
serial_number=device.serial_number,
157175
)
158-
# Don't set via_device for the GX device itself
159-
if device.unique_id != "system_0":
176+
# Set via_device based on parent_device relationship
177+
if device.parent_device is not None:
178+
device_info["via_device"] = (DOMAIN, f"{installation_id}_{device.parent_device.unique_id}")
179+
elif device.device_type != DeviceType.SYSTEM:
160180
device_info["via_device"] = (DOMAIN, f"{installation_id}_system_0")
161181
return device_info
162182

0 commit comments

Comments
 (0)