Skip to content

Commit

Permalink
Merge pull request #119 from bieniu/import-top-level
Browse files Browse the repository at this point in the history
Move imports to top level to avoid blocking call in event loop
  • Loading branch information
mrk-its authored Sep 14, 2024
2 parents c181812 + f614586 commit 4f16582
Showing 1 changed file with 2 additions and 20 deletions.
22 changes: 2 additions & 20 deletions custom_components/blitzortung/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from typing import Callable, List, Optional, Union

import attr
import paho.mqtt.client as mqtt
from paho.mqtt.matcher import MQTTMatcher

from homeassistant.core import callback, HomeAssistant
from homeassistant.exceptions import HomeAssistantError
Expand All @@ -28,9 +30,6 @@

def _raise_on_error(result_code: int) -> None:
"""Raise error if error result."""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt

if result_code != 0:
raise HomeAssistantError(
f"Error talking to MQTT: {mqtt.error_string(result_code)}"
Expand All @@ -39,9 +38,6 @@ def _raise_on_error(result_code: int) -> None:

def _match_topic(subscription: str, topic: str) -> bool:
"""Test if topic matches subscription."""
# pylint: disable=import-outside-toplevel
from paho.mqtt.matcher import MQTTMatcher

matcher = MQTTMatcher()
matcher[subscription] = True
try:
Expand Down Expand Up @@ -93,10 +89,6 @@ def __init__(
keepalive=DEFAULT_KEEPALIVE,
) -> None:
"""Initialize Home Assistant MQTT client."""
# We don't import on the top because some integrations
# should be able to optionally rely on MQTT.
import paho.mqtt.client as mqtt # pylint: disable=import-outside-toplevel

self.hass = hass
self.host = host
self.port = port
Expand All @@ -110,10 +102,6 @@ def __init__(

def init_client(self):
"""Initialize paho client."""
# We don't import on the top because some integrations
# should be able to optionally rely on MQTT.
import paho.mqtt.client as mqtt # pylint: disable=import-outside-toplevel

proto = mqtt.MQTTv311
self._mqttc = mqtt.Client(protocol=proto)

Expand All @@ -133,9 +121,6 @@ async def async_publish(

async def async_connect(self) -> str:
"""Connect to the host. Does not process messages yet."""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt

result: int = None
try:
result = await self.hass.async_add_executor_job(
Expand Down Expand Up @@ -225,9 +210,6 @@ def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code: int) -> None:
Resubscribe to all topics we were subscribed to and publish birth
message.
"""
# pylint: disable=import-outside-toplevel
import paho.mqtt.client as mqtt

if result_code != mqtt.CONNACK_ACCEPTED:
_LOGGER.error(
"Unable to connect to the MQTT broker: %s",
Expand Down

0 comments on commit 4f16582

Please sign in to comment.