5252
5353_DEBOUNCE_DEFAULT_S = 60.0
5454
55+ # How long to wait for a plug to answer when its records are not cached.
56+ # 5 seconds is enough to cover network latency and plug response time.
57+ _REQUEST_TIMEOUT_MS = 5000
58+
5559
5660try :
5761 import zeroconf as _zc
58- from zeroconf .asyncio import AsyncServiceBrowser
62+ from zeroconf .asyncio import AsyncServiceBrowser , AsyncServiceInfo
5963
6064 class PowersensorZeroconfDevices (_PowersensorDevicesBase ):
6165 """Discovers and manages Powersensor plugs via continuous mDNS browsing.
@@ -237,42 +241,23 @@ def cleanup(task: Task[None]) -> None:
237241
238242
239243 class _Listener (_zc .ServiceListener ):
240- """Zeroconf ServiceListener that forwards events to PowersensorZeroconfDevices."""
244+ """Zeroconf ServiceListener that forwards events to PowersensorZeroconfDevices.
245+
246+ Its callbacks must never raise as Zeroconf does not catch exceptions from
247+ browser callbacks. In Home Assistant, the instance is shared with other
248+ integration, so this would disrupt their discovery too. Anything that can
249+ fail is therefore either handled here or run in a task.
250+ """
241251
242252 def __init__ (self , owner : PowersensorZeroconfDevices ) -> None :
243253 self ._owner = owner
244254 self ._name_to_mac : dict [str , str ] = {}
245255
246- def _extract (self , zc : Any , type_ : str , name : str ) -> tuple [str , str , int ] | None :
247- """Return (mac, ip, port) from the zeroconf cache, or None.
248-
249- Uses ServiceInfo.load_from_cache() rather than
250- Zeroconf.get_service_info() for two reasons:
251-
252- 1. On zeroconf >= 0.32 (including HA's 0.149.x), ServiceBrowser
253- callbacks run inside the asyncio event loop. Calling
254- get_service_info() from there blocks waiting for a DNS reply
255- that can never be processed because the event loop is occupied —
256- it deadlocks, times out after 3 s, and silently returns None,
257- causing the device to be dropped.
258-
259- 2. load_from_cache() is synchronous, non-blocking, and explicitly
260- documented as threadsafe. The ServiceBrowser guarantees the
261- cache is populated before firing add_service / update_service,
262- so the record is always present when this method is called.
263- """
264- info = _zc .ServiceInfo (type_ , name )
265- if not info .load_from_cache (zc ):
266- self ._owner ._maybe_log (
267- _LogLevel .WARNING ,
268- "No cache entry for %s — device will appear on next mDNS announcement" ,
269- name ,
270- )
271- return None
272-
256+ def _parse (self , info : AsyncServiceInfo , name : str ) -> tuple [str , str , int ] | None :
257+ """Return (mac, ip, port) from a resolved service record, or None."""
273258 addresses = info .parsed_addresses ()
274259 if not addresses :
275- self ._owner ._maybe_log (_LogLevel .WARNING , "No addresses in zeroconf cache record for %s" , name )
260+ self ._owner ._maybe_log (_LogLevel .WARNING , "No addresses in zeroconf record for %s" , name )
276261 return None
277262
278263 try :
@@ -289,35 +274,69 @@ def _extract(self, zc: Any, type_: str, name: str) -> tuple[str, str, int] | Non
289274 self ._owner ._maybe_log (_LogLevel .ERROR , "No port in zeroconf record for %s" , name )
290275 return None
291276
292- return raw_id .decode ('utf-8' ), addresses [0 ], info .port
277+ # This runs inside the browser callback, so a bad id from any
278+ # device advertising this service type must not raise.
279+ try :
280+ mac = raw_id .decode ('utf-8' )
281+ except UnicodeDecodeError :
282+ self ._owner ._maybe_log (_LogLevel .ERROR , "'id' property in zeroconf record for %s is not valid UTF-8" , name )
283+ return None
293284
294- def add_service (self , zc : Any , type_ : str , name : str ) -> None :
295- result = self ._extract (zc , type_ , name )
296- if result is None :
297- self ._owner ._maybe_log (
298- _LogLevel .WARNING ,
299- "add_service: no info available for %s — will retry on next announcement" ,
300- name ,
301- )
302- return
303- mac , ip , port = result
304285 self ._name_to_mac [name ] = mac
305- self . _owner . _internal_callback ( self . _owner . _on_zc_add ( mac , ip , port ))
286+ return mac , addresses [ 0 ], info . port
306287
307- def update_service (self , zc : Any , type_ : str , name : str ) -> None :
308- result = self ._extract (zc , type_ , name )
309- if result is None :
310- self ._owner ._maybe_log (
311- _LogLevel .WARNING ,
312- "update_service: no info available for %s — will retry on next announcement" ,
313- name ,
314- )
288+ def _resolve (
289+ self ,
290+ zc : _zc .Zeroconf ,
291+ type_ : str ,
292+ name : str ,
293+ on_resolved : Callable [[str , str , int ], _InternalCallback ],
294+ ) -> None :
295+ """Resolve a plug's address and port, then schedule on_resolved.
296+
297+ The records are usually already in the zeroconf cache but they are
298+ not guaranteed to be. A browser started on a shared zeroconf
299+ instance (as in Home Assistant when a config entry is reloaded) is
300+ seeded from cached PTR records, and the plug's SRV and A records
301+ have much shorter lifetimes, so they may have expired. Waiting for
302+ the plug to announce itself again can take a long time, so ask it
303+ directly instead, as Home Assistant's own zeroconf discovery does.
304+ """
305+ # If a device advertises an invalid DNS name, the constructor will
306+ # reject it. This runs inside the browser callback, so ignore
307+ # invalid names rather than raise.
308+ try :
309+ info = AsyncServiceInfo (type_ , name )
310+ except _zc .BadTypeInNameException :
311+ self ._owner ._maybe_log (_LogLevel .DEBUG , "Ignoring %s: not a valid service name" , name )
315312 return
316- mac , ip , port = result
317- self ._name_to_mac [name ] = mac
318- self ._owner ._internal_callback (self ._owner ._on_zc_update (mac , ip , port ))
319313
320- def remove_service (self , zc : Any , type_ : str , name : str ) -> None :
314+ if info .load_from_cache (zc ):
315+ if (result := self ._parse (info , name )) is not None :
316+ self ._owner ._internal_callback (on_resolved (* result ))
317+ return
318+
319+ async def request () -> None :
320+ if not await info .async_request (zc , _REQUEST_TIMEOUT_MS ):
321+ self ._owner ._maybe_log (
322+ _LogLevel .WARNING ,
323+ "No response from %s — device will appear on next mDNS announcement" ,
324+ name ,
325+ )
326+ return
327+ if (result := self ._parse (info , name )) is not None :
328+ await on_resolved (* result )
329+
330+ self ._owner ._maybe_log (_LogLevel .DEBUG , "No cache entry for %s, requesting it" , name )
331+ self ._owner ._internal_callback (request ())
332+
333+ def add_service (self , zc : _zc .Zeroconf , type_ : str , name : str ) -> None :
334+ self ._resolve (zc , type_ , name , self ._owner ._on_zc_add )
335+
336+ def update_service (self , zc : _zc .Zeroconf , type_ : str , name : str ) -> None :
337+ self ._resolve (zc , type_ , name , self ._owner ._on_zc_update )
338+
339+ def remove_service (self , zc : _zc .Zeroconf , type_ : str , name : str ) -> None :
321340 mac = self ._name_to_mac .pop (name , None )
322341 if mac is None :
323342 self ._owner ._maybe_log (
0 commit comments