Clean up accessing dispatcher helpers via hass (#72014)

Clean up accessing ditpatcher helpers via hass
pull/72016/head
Franck Nijhof 2022-05-17 18:41:36 +02:00 committed by GitHub
parent 0b09376360
commit c8f700c803
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 64 additions and 68 deletions

View File

@ -15,6 +15,7 @@ from homeassistant.const import (
Platform, Platform,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .const import ( from .const import (
@ -81,23 +82,23 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
def handle_message(sender, message): def handle_message(sender, message):
"""Handle message from AlarmDecoder.""" """Handle message from AlarmDecoder."""
hass.helpers.dispatcher.dispatcher_send(SIGNAL_PANEL_MESSAGE, message) dispatcher_send(hass, SIGNAL_PANEL_MESSAGE, message)
def handle_rfx_message(sender, message): def handle_rfx_message(sender, message):
"""Handle RFX message from AlarmDecoder.""" """Handle RFX message from AlarmDecoder."""
hass.helpers.dispatcher.dispatcher_send(SIGNAL_RFX_MESSAGE, message) dispatcher_send(hass, SIGNAL_RFX_MESSAGE, message)
def zone_fault_callback(sender, zone): def zone_fault_callback(sender, zone):
"""Handle zone fault from AlarmDecoder.""" """Handle zone fault from AlarmDecoder."""
hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_FAULT, zone) dispatcher_send(hass, SIGNAL_ZONE_FAULT, zone)
def zone_restore_callback(sender, zone): def zone_restore_callback(sender, zone):
"""Handle zone restore from AlarmDecoder.""" """Handle zone restore from AlarmDecoder."""
hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_RESTORE, zone) dispatcher_send(hass, SIGNAL_ZONE_RESTORE, zone)
def handle_rel_message(sender, message): def handle_rel_message(sender, message):
"""Handle relay or zone expander message from AlarmDecoder.""" """Handle relay or zone expander message from AlarmDecoder."""
hass.helpers.dispatcher.dispatcher_send(SIGNAL_REL_MESSAGE, message) dispatcher_send(hass, SIGNAL_REL_MESSAGE, message)
baud = ad_connection.get(CONF_DEVICE_BAUD) baud = ad_connection.get(CONF_DEVICE_BAUD)
if protocol == PROTOCOL_SOCKET: if protocol == PROTOCOL_SOCKET:

View File

@ -15,6 +15,7 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -70,7 +71,7 @@ class AquaLogicProcessor(threading.Thread):
def data_changed(self, panel): def data_changed(self, panel):
"""Aqualogic data changed callback.""" """Aqualogic data changed callback."""
self._hass.helpers.dispatcher.dispatcher_send(UPDATE_TOPIC) dispatcher_send(self._hass, UPDATE_TOPIC)
def run(self): def run(self):
"""Event thread.""" """Event thread."""

View File

@ -11,6 +11,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP, Platform
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
from .const import ( from .const import (
@ -81,7 +82,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def _run_client(hass, client, interval): async def _run_client(hass, client, interval):
def _listen(_): def _listen(_):
hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_CLIENT_DATA, client.host) async_dispatcher_send(hass, SIGNAL_CLIENT_DATA, client.host)
while True: while True:
try: try:
@ -89,9 +90,7 @@ async def _run_client(hass, client, interval):
await client.start() await client.start()
_LOGGER.debug("Client connected %s", client.host) _LOGGER.debug("Client connected %s", client.host)
hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(hass, SIGNAL_CLIENT_STARTED, client.host)
SIGNAL_CLIENT_STARTED, client.host
)
try: try:
with client.listen(_listen): with client.listen(_listen):
@ -100,9 +99,7 @@ async def _run_client(hass, client, interval):
await client.stop() await client.stop()
_LOGGER.debug("Client disconnected %s", client.host) _LOGGER.debug("Client disconnected %s", client.host)
hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(hass, SIGNAL_CLIENT_STOPPED, client.host)
SIGNAL_CLIENT_STOPPED, client.host
)
except ConnectionFailed: except ConnectionFailed:
await asyncio.sleep(interval) await asyncio.sleep(interval)

View File

@ -18,6 +18,7 @@ from homeassistant.components.media_player.errors import BrowseError
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
@ -127,21 +128,15 @@ class ArcamFmj(MediaPlayerEntity):
self.async_schedule_update_ha_state(force_refresh=True) self.async_schedule_update_ha_state(force_refresh=True)
self.async_on_remove( self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect( async_dispatcher_connect(self.hass, SIGNAL_CLIENT_DATA, _data)
SIGNAL_CLIENT_DATA, _data
)
) )
self.async_on_remove( self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect( async_dispatcher_connect(self.hass, SIGNAL_CLIENT_STARTED, _started)
SIGNAL_CLIENT_STARTED, _started
)
) )
self.async_on_remove( self.async_on_remove(
self.hass.helpers.dispatcher.async_dispatcher_connect( async_dispatcher_connect(self.hass, SIGNAL_CLIENT_STOPPED, _stopped)
SIGNAL_CLIENT_STOPPED, _stopped
)
) )
async def async_update(self): async def async_update(self):

View File

@ -2,7 +2,7 @@
from enocean.protocol.packet import Packet from enocean.protocol.packet import Packet
from enocean.utils import combine_hex from enocean.utils import combine_hex
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from .const import SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE from .const import SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE
@ -37,4 +37,4 @@ class EnOceanEntity(Entity):
"""Send a command via the EnOcean dongle.""" """Send a command via the EnOcean dongle."""
packet = Packet(packet_type, data=data, optional=optional) packet = Packet(packet_type, data=data, optional=optional)
self.hass.helpers.dispatcher.dispatcher_send(SIGNAL_SEND_MESSAGE, packet) dispatcher_send(self.hass, SIGNAL_SEND_MESSAGE, packet)

View File

@ -7,7 +7,7 @@ from enocean.communicators import SerialCommunicator
from enocean.protocol.packet import RadioPacket from enocean.protocol.packet import RadioPacket
import serial import serial
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from .const import SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE from .const import SIGNAL_RECEIVE_MESSAGE, SIGNAL_SEND_MESSAGE
@ -58,7 +58,7 @@ class EnOceanDongle:
if isinstance(packet, RadioPacket): if isinstance(packet, RadioPacket):
_LOGGER.debug("Received radio packet: %s", packet) _LOGGER.debug("Received radio packet: %s", packet)
self.hass.helpers.dispatcher.dispatcher_send(SIGNAL_RECEIVE_MESSAGE, packet) dispatcher_send(self.hass, SIGNAL_RECEIVE_MESSAGE, packet)
def detect(): def detect():

View File

@ -19,6 +19,7 @@ from aiohomekit.model.services import Service
from homeassistant.const import ATTR_VIA_DEVICE from homeassistant.const import ATTR_VIA_DEVICE
from homeassistant.core import CALLBACK_TYPE, callback from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.helpers import device_registry as dr from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
@ -162,7 +163,7 @@ class HKDevice:
if self.available == available: if self.available == available:
return return
self.available = available self.available = available
self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated) async_dispatcher_send(self.hass, self.signal_state_updated)
async def async_setup(self) -> bool: async def async_setup(self) -> bool:
"""Prepare to use a paired HomeKit device in Home Assistant.""" """Prepare to use a paired HomeKit device in Home Assistant."""
@ -568,7 +569,7 @@ class HKDevice:
# For now we update both # For now we update both
self.entity_map.process_changes(new_values_dict) self.entity_map.process_changes(new_values_dict)
self.hass.helpers.dispatcher.async_dispatcher_send(self.signal_state_updated) async_dispatcher_send(self.hass, self.signal_state_updated)
async def get_characteristics(self, *args, **kwargs) -> dict[str, Any]: async def get_characteristics(self, *args, **kwargs) -> dict[str, Any]:
"""Read latest state from homekit accessory.""" """Read latest state from homekit accessory."""

View File

@ -353,8 +353,8 @@ async def webhook_render_template(hass, config_entry, data):
) )
async def webhook_update_location(hass, config_entry, data): async def webhook_update_location(hass, config_entry, data):
"""Handle an update location webhook.""" """Handle an update location webhook."""
hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(
SIGNAL_LOCATION_UPDATE.format(config_entry.entry_id), data hass, SIGNAL_LOCATION_UPDATE.format(config_entry.entry_id), data
) )
return empty_okay_response() return empty_okay_response()

View File

@ -18,7 +18,10 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_when_setup from homeassistant.setup import async_when_setup
@ -140,7 +143,7 @@ async def async_connect_mqtt(hass, component):
return return
message["topic"] = msg.topic message["topic"] = msg.topic
hass.helpers.dispatcher.async_dispatcher_send(DOMAIN, hass, context, message) async_dispatcher_send(hass, DOMAIN, hass, context, message)
await mqtt.async_subscribe(hass, context.mqtt_topic, async_handle_mqtt_message, 1) await mqtt.async_subscribe(hass, context.mqtt_topic, async_handle_mqtt_message, 1)
@ -179,7 +182,7 @@ async def handle_webhook(hass, webhook_id, request):
# Keep it as a 200 response so the incorrect packet is discarded # Keep it as a 200 response so the incorrect packet is discarded
return json_response([]) return json_response([])
hass.helpers.dispatcher.async_dispatcher_send(DOMAIN, hass, context, message) async_dispatcher_send(hass, DOMAIN, hass, context, message)
response = [] response = []

View File

@ -21,7 +21,10 @@ from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.discovery import load_platform from homeassistant.helpers.discovery import load_platform
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
@ -150,7 +153,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
def callback_value_changed(_qsd, qsid, _val): def callback_value_changed(_qsd, qsid, _val):
"""Update entity values based on device change.""" """Update entity values based on device change."""
_LOGGER.debug("Dispatch %s (update from devices)", qsid) _LOGGER.debug("Dispatch %s (update from devices)", qsid)
hass.helpers.dispatcher.async_dispatcher_send(qsid, None) async_dispatcher_send(hass, qsid, None)
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
qsusb = QSUsb( qsusb = QSUsb(
@ -221,7 +224,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
if qspacket[QS_ID] in sensor_ids: if qspacket[QS_ID] in sensor_ids:
_LOGGER.debug("Dispatch %s ((%s))", qspacket[QS_ID], qspacket) _LOGGER.debug("Dispatch %s ((%s))", qspacket[QS_ID], qspacket)
hass.helpers.dispatcher.async_dispatcher_send(qspacket[QS_ID], qspacket) async_dispatcher_send(hass, qspacket[QS_ID], qspacket)
# Update all ha_objects # Update all ha_objects
hass.async_add_job(qsusb.update_from_devices) hass.async_add_job(qsusb.update_from_devices)

View File

@ -30,7 +30,10 @@ from homeassistant.helpers.device_registry import (
DeviceEntry, DeviceEntry,
DeviceRegistry, DeviceRegistry,
) )
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import DeviceInfo, Entity from homeassistant.helpers.entity import DeviceInfo, Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.restore_state import RestoreEntity
@ -214,7 +217,7 @@ async def async_setup_internal(hass, entry: ConfigEntry):
event_data[ATTR_DEVICE_ID] = device_entry.id event_data[ATTR_DEVICE_ID] = device_entry.id
# Callback to HA registered components. # Callback to HA registered components.
hass.helpers.dispatcher.async_dispatcher_send(SIGNAL_EVENT, event, device_id) async_dispatcher_send(hass, SIGNAL_EVENT, event, device_id)
# Signal event to any other listeners # Signal event to any other listeners
hass.bus.async_fire(EVENT_RFXTRX_EVENT, event_data) hass.bus.async_fire(EVENT_RFXTRX_EVENT, event_data)

View File

@ -17,7 +17,10 @@ from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import discovery from homeassistant.helpers import discovery
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
@ -147,8 +150,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
@callback @callback
def async_handle_callback(tellcore_id, tellcore_command, tellcore_data, cid): def async_handle_callback(tellcore_id, tellcore_command, tellcore_data, cid):
"""Handle the actual callback from Tellcore.""" """Handle the actual callback from Tellcore."""
hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(
SIGNAL_TELLCORE_CALLBACK, tellcore_id, tellcore_command, tellcore_data hass, SIGNAL_TELLCORE_CALLBACK, tellcore_id, tellcore_command, tellcore_data
) )
# Register callback # Register callback

View File

@ -16,6 +16,7 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, discovery from homeassistant.helpers import config_validation as cv, discovery
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.typing import ConfigType from homeassistant.helpers.typing import ConfigType
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -156,5 +157,5 @@ class WaterFurnaceData(threading.Thread):
self._reconnect() self._reconnect()
else: else:
self.hass.helpers.dispatcher.dispatcher_send(UPDATE_TOPIC) dispatcher_send(self.hass, UPDATE_TOPIC)
time.sleep(SCAN_INTERVAL.total_seconds()) time.sleep(SCAN_INTERVAL.total_seconds())

View File

@ -14,6 +14,7 @@ import async_timeout
from homeassistant.components.http import HomeAssistantView from homeassistant.components.http import HomeAssistantView
from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant, callback from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later from homeassistant.helpers.event import async_call_later
from .auth import AuthPhase, auth_required_message from .auth import AuthPhase, auth_required_message
@ -203,9 +204,7 @@ class WebSocketHandler:
self.hass.data[DATA_CONNECTIONS] = ( self.hass.data[DATA_CONNECTIONS] = (
self.hass.data.get(DATA_CONNECTIONS, 0) + 1 self.hass.data.get(DATA_CONNECTIONS, 0) + 1
) )
self.hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(self.hass, SIGNAL_WEBSOCKET_CONNECTED)
SIGNAL_WEBSOCKET_CONNECTED
)
# Command phase # Command phase
while not wsock.closed: while not wsock.closed:
@ -258,8 +257,6 @@ class WebSocketHandler:
if connection is not None: if connection is not None:
self.hass.data[DATA_CONNECTIONS] -= 1 self.hass.data[DATA_CONNECTIONS] -= 1
self.hass.helpers.dispatcher.async_dispatcher_send( async_dispatcher_send(self.hass, SIGNAL_WEBSOCKET_DISCONNECTED)
SIGNAL_WEBSOCKET_DISCONNECTED
)
return wsock return wsock

View File

@ -1,6 +1,6 @@
"""Tests for arcam fmj receivers.""" """Tests for arcam fmj receivers."""
from math import isclose from math import isclose
from unittest.mock import ANY, MagicMock, PropertyMock, patch from unittest.mock import ANY, PropertyMock, patch
from arcam.fmj import DecodeMode2CH, DecodeModeMCH, SourceCodes from arcam.fmj import DecodeMode2CH, DecodeModeMCH, SourceCodes
import pytest import pytest
@ -303,22 +303,12 @@ async def test_added_to_hass(player, state):
SIGNAL_CLIENT_STOPPED, SIGNAL_CLIENT_STOPPED,
) )
connectors = {} with patch(
"homeassistant.components.arcam_fmj.media_player.async_dispatcher_connect"
) as connect:
await player.async_added_to_hass()
def _connect(signal, fun):
connectors[signal] = fun
player.hass = MagicMock()
player.hass.helpers.dispatcher.async_dispatcher_connect.side_effects = _connect
await player.async_added_to_hass()
state.start.assert_called_with() state.start.assert_called_with()
player.hass.helpers.dispatcher.async_dispatcher_connect.assert_any_call( connect.assert_any_call(player.hass, SIGNAL_CLIENT_DATA, ANY)
SIGNAL_CLIENT_DATA, ANY connect.assert_any_call(player.hass, SIGNAL_CLIENT_STARTED, ANY)
) connect.assert_any_call(player.hass, SIGNAL_CLIENT_STOPPED, ANY)
player.hass.helpers.dispatcher.async_dispatcher_connect.assert_any_call(
SIGNAL_CLIENT_STARTED, ANY
)
player.hass.helpers.dispatcher.async_dispatcher_connect.assert_any_call(
SIGNAL_CLIENT_STOPPED, ANY
)

View File

@ -2,6 +2,7 @@
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from homeassistant.components.cloud.const import DISPATCHER_REMOTE_UPDATE from homeassistant.components.cloud.const import DISPATCHER_REMOTE_UPDATE
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
@ -29,14 +30,14 @@ async def test_remote_connection_sensor(hass):
with patch("homeassistant.components.cloud.binary_sensor.WAIT_UNTIL_CHANGE", 0): with patch("homeassistant.components.cloud.binary_sensor.WAIT_UNTIL_CHANGE", 0):
cloud.remote.is_connected = False cloud.remote.is_connected = False
cloud.remote.certificate = object() cloud.remote.certificate = object()
hass.helpers.dispatcher.async_dispatcher_send(DISPATCHER_REMOTE_UPDATE, {}) async_dispatcher_send(hass, DISPATCHER_REMOTE_UPDATE, {})
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("binary_sensor.remote_ui") state = hass.states.get("binary_sensor.remote_ui")
assert state.state == "off" assert state.state == "off"
cloud.remote.is_connected = True cloud.remote.is_connected = True
hass.helpers.dispatcher.async_dispatcher_send(DISPATCHER_REMOTE_UPDATE, {}) async_dispatcher_send(hass, DISPATCHER_REMOTE_UPDATE, {})
await hass.async_block_till_done() await hass.async_block_till_done()
state = hass.states.get("binary_sensor.remote_ui") state = hass.states.get("binary_sensor.remote_ui")