Devices that left the network are re-initialized on every availability check, reading attributes from a device that is gone

Aperta Adatta ai principianti
#1,105 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@zigpy-review-bot ci sta già lavorando.

Dal 28/11/2026.

  • #1106 di @zigpy-review-bot — aperta

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
88/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
embedded-iot

Direzione di ricerca

Inizia con BaseDevice._update_available e ZigbeeDevice._check_available in zha/zigbee/device.py, quindi esamina come Gateway.device_left modifica on_network in zha/application/gateway.py. Riproduci il comportamento usando il test fornito per un dispositivo alimentato dalla rete che esce dopo il suo ultimo messaggio. Il risultato è completo quando controlli ripetuti della disponibilità non reiniziano il dispositivo andato via e non leggono i suoi attributi di cluster, mentre un dispositivo che torna alla rete viene comunque reinizializzato una sola volta.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bot: code audit
Problem

Severity: medium (the audit's estimate)

When a device leaves the network (it was factory reset to be paired again, or it sent a Leave on its own), ZHA keeps the device, marks it as not on the network and makes it unavailable. Its last message is still recent, though. Until that message is older than the "consider unavailable" time (2 hours for mains powered devices, 6 hours for battery powered ones by default), every pass of the availability checker, every 30 to 45 seconds, finds the device "seen recently" and re-initializes it: its entities are discovered again and their attributes are read from the device, which is no longer there to answer. The device stays unavailable the whole time, so Home Assistant shows nothing unusual, but the debug log shows "Device availability changed and device became available, reinitializing cluster handlers" for the device on every check, and the coordinator keeps sending it requests that can only time out.

The cause is in BaseDevice._update_available (https://github.com/zigpy/zha/blob/4d8e640c877c998e66b74ad2059c9e1ed1b07510/zha/zigbee/device.py#L780-L804). It compares the requested availability with the device's availability before the call, was_available, which includes on_network. When the device has left, Gateway.device_left sets on_network = False (https://github.com/zigpy/zha/blob/4d8e640c877c998e66b74ad2059c9e1ed1b07510/zha/application/gateway.py#L653-L657), and ZigbeeDevice._check_available still calls update_available(True) while the last message is recent (https://github.com/zigpy/zha/blob/4d8e640c877c998e66b74ad2059c9e1ed1b07510/zha/zigbee/device.py#L1475-L1482). was_available is False and the requested value is True, so every call takes the "became available" branch and starts _async_became_available, which runs async_initialize(False) (https://github.com/zigpy/zha/blob/4d8e640c877c998e66b74ad2059c9e1ed1b07510/zha/zigbee/device.py#L826-L828), although the device's availability doesn't change: available is still False afterwards, as on_network is.

Evidence

A test that lets a mains powered switch leave the network right after its last message, then runs three availability checks. It fails at 4d8e640c877c998e66b74ad2059c9e1ed1b07510: the three checks re-initialized the device three times and read attributes from its OnOff cluster six times.

Test and output
async def test_check_available_does_not_reinitialize_device_off_network(
    zha_gateway: Gateway,
) -> None:
    """Test a device that left the network isn't re-initialized by every check."""
    zigpy_dev = zigpy_device_mains(zha_gateway, with_basic_cluster=True)
    zha_device = await join_zigpy_device(zha_gateway, zigpy_dev)
    on_off_cluster = zigpy_dev.endpoints[3].on_off

    # we want to test the device availability handling alone
    zha_gateway.global_updater.stop()

    # The device leaves the network right after it was last seen
    zigpy_dev.last_seen = time.time()
    zha_gateway.device_left(zigpy_dev)
    await zha_gateway.async_block_till_done()
    assert zha_device.available is False

    on_off_cluster.read_attributes.reset_mock()

    with patch.object(
        zha_device, "async_initialize", wraps=zha_device.async_initialize
    ) as async_initialize:
        # Its last message is still recent for the next availability checks
        for _ in range(3):
            await zha_device._check_available()
            await zha_gateway.async_block_till_done()

        # It stays unavailable, and is not re-initialized while it is gone
        assert zha_device.available is False
        assert on_off_cluster.read_attributes.await_count == 0
        assert async_initialize.await_count == 0
        ...
>           assert on_off_cluster.read_attributes.await_count == 0
E           AssertionError: assert 6 == 0
E            +  where 6 = <AsyncMock id='135438639022496'>.await_count
E            +    where <AsyncMock id='135438639022496'> = <zigpy.zcl.clusters.general.OnOff object at 0x7b2e448e34d0>.read_attributes

With the reads assertion left out, the next one shows assert 3 == 0 for async_initialize.await_count.

Proposed fix

Set the new availability first and compare the resulting available, which includes on_network, with was_available. A device that left then stays unavailable without being re-initialized, and a device coming back on the network (a message from it sets on_network again) is still re-initialized once.

Lingua principale
Python
Stelle
96
Fork
84
Merge medio
2g 4h
PR unite (30g)
30

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di zigpy/zha

Tutte le issue di zigpy/zha

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.