Improve typing hints MQTT __init__ (#80674)

* Improve typing __init__

* Follow up suggestions
This commit is contained in:
Jan Bouwhuis 2022-10-21 12:25:21 +02:00 committed by GitHub
parent 78f71c46da
commit 5f27e2fe01
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio import asyncio
from collections.abc import Callable from collections.abc import Callable
from datetime import datetime
import logging import logging
from typing import Any, cast from typing import Any, cast
@ -236,7 +237,7 @@ def _merge_basic_config(
hass.config_entries.async_update_entry(entry, data=entry_config) hass.config_entries.async_update_entry(entry, data=entry_config)
def _merge_extended_config(entry, conf): def _merge_extended_config(entry: ConfigEntry, conf: ConfigType) -> dict[str, Any]:
"""Merge advanced options in configuration.yaml config with config entry.""" """Merge advanced options in configuration.yaml config with config entry."""
# Add default values # Add default values
conf = {**DEFAULT_VALUES, **conf} conf = {**DEFAULT_VALUES, **conf}
@ -251,7 +252,9 @@ async def _async_config_entry_updated(hass: HomeAssistant, entry: ConfigEntry) -
await hass.config_entries.async_reload(entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
async def async_fetch_config(hass: HomeAssistant, entry: ConfigEntry) -> dict | None: async def async_fetch_config(
hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any] | None:
"""Fetch fresh MQTT yaml config from the hass config when (re)loading the entry.""" """Fetch fresh MQTT yaml config from the hass config when (re)loading the entry."""
mqtt_data = get_mqtt_data(hass) mqtt_data = get_mqtt_data(hass)
if mqtt_data.reload_entry: if mqtt_data.reload_entry:
@ -366,20 +369,20 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def async_dump_service(call: ServiceCall) -> None: async def async_dump_service(call: ServiceCall) -> None:
"""Handle MQTT dump service calls.""" """Handle MQTT dump service calls."""
messages = [] messages: list[tuple[str, str]] = []
@callback @callback
def collect_msg(msg): def collect_msg(msg: ReceiveMessage) -> None:
messages.append((msg.topic, msg.payload.replace("\n", ""))) messages.append((msg.topic, str(msg.payload).replace("\n", "")))
unsub = await async_subscribe(hass, call.data["topic"], collect_msg) unsub = await async_subscribe(hass, call.data["topic"], collect_msg)
def write_dump(): def write_dump() -> None:
with open(hass.config.path("mqtt_dump.txt"), "w", encoding="utf8") as fp: with open(hass.config.path("mqtt_dump.txt"), "w", encoding="utf8") as fp:
for msg in messages: for msg in messages:
fp.write(",".join(msg) + "\n") fp.write(",".join(msg) + "\n")
async def finish_dump(_): async def finish_dump(_: datetime) -> None:
"""Write dump to file.""" """Write dump to file."""
unsub() unsub()
await hass.async_add_executor_job(write_dump) await hass.async_add_executor_job(write_dump)
@ -439,7 +442,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, _reload_config) async_register_admin_service(hass, DOMAIN, SERVICE_RELOAD, _reload_config)
async def async_forward_entry_setup_and_setup_discovery(config_entry): async def async_forward_entry_setup_and_setup_discovery(
config_entry: ConfigEntry,
conf: ConfigType,
) -> None:
"""Forward the config entry setup to the platforms and set up discovery.""" """Forward the config entry setup to the platforms and set up discovery."""
reload_manual_setup: bool = False reload_manual_setup: bool = False
# Local import to avoid circular dependencies # Local import to avoid circular dependencies
@ -477,7 +483,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if reload_manual_setup: if reload_manual_setup:
await async_reload_manual_mqtt_items(hass) await async_reload_manual_mqtt_items(hass)
await async_forward_entry_setup_and_setup_discovery(entry) await async_forward_entry_setup_and_setup_discovery(entry, conf)
return True return True
@ -497,9 +503,7 @@ async def async_reload_manual_mqtt_items(hass: HomeAssistant) -> None:
) )
@callback @callback
def websocket_mqtt_info( def websocket_mqtt_info(
hass: HomeAssistant, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None: ) -> None:
"""Get MQTT debug info for device.""" """Get MQTT debug info for device."""
device_id = msg["device_id"] device_id = msg["device_id"]
@ -516,15 +520,13 @@ def websocket_mqtt_info(
) )
@websocket_api.async_response @websocket_api.async_response
async def websocket_subscribe( async def websocket_subscribe(
hass: HomeAssistant, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None: ) -> None:
"""Subscribe to a MQTT topic.""" """Subscribe to a MQTT topic."""
if not connection.user.is_admin: if not connection.user.is_admin:
raise Unauthorized raise Unauthorized
async def forward_messages(mqttmsg: ReceiveMessage): async def forward_messages(mqttmsg: ReceiveMessage) -> None:
"""Forward events to websocket.""" """Forward events to websocket."""
try: try:
payload = cast(bytes, mqttmsg.payload).decode( payload = cast(bytes, mqttmsg.payload).decode(