diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index ac29671667f0404a11ff68ff639413a6c399561f..bcb0d60902bd8ef550f5e105f0dcbb9c78b574dc 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -6,40 +6,40 @@ https://home-assistant.io/components/mqtt/ """ import asyncio from itertools import groupby -from typing import Optional, Any, Union, Callable, List, cast # noqa: F401 -from operator import attrgetter import logging +from operator import attrgetter import os import socket -import time import ssl -import requests.certs -import attr +import time +from typing import Any, Callable, List, Optional, Union, cast # noqa: F401 +import attr +import requests.certs import voluptuous as vol from homeassistant import config_entries -from homeassistant.helpers.typing import HomeAssistantType, ConfigType, \ - ServiceDataType -from homeassistant.core import callback, Event, ServiceCall -from homeassistant.setup import async_prepare_setup_platform +from homeassistant.const import ( + CONF_PASSWORD, CONF_PAYLOAD, CONF_PORT, CONF_PROTOCOL, CONF_USERNAME, + CONF_VALUE_TEMPLATE, EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP) +from homeassistant.core import Event, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError -from homeassistant.loader import bind_hass -from homeassistant.helpers import template, config_validation as cv +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import template from homeassistant.helpers.entity import Entity +from homeassistant.helpers.typing import ( + ConfigType, HomeAssistantType, ServiceDataType) +from homeassistant.loader import bind_hass +from homeassistant.setup import async_prepare_setup_platform from homeassistant.util.async_ import ( - run_coroutine_threadsafe, run_callback_threadsafe) -from homeassistant.const import ( - EVENT_HOMEASSISTANT_STOP, CONF_VALUE_TEMPLATE, CONF_USERNAME, - CONF_PASSWORD, CONF_PORT, CONF_PROTOCOL, CONF_PAYLOAD, - EVENT_HOMEASSISTANT_START) + run_callback_threadsafe, run_coroutine_threadsafe) # Loading the config flow file will register the flow from . import config_flow # noqa # pylint: disable=unused-import from .const import CONF_BROKER from .server import HBMQTT_CONFIG_SCHEMA -REQUIREMENTS = ['paho-mqtt==1.3.1'] +REQUIREMENTS = ['paho-mqtt==1.4.0'] _LOGGER = logging.getLogger(__name__) @@ -296,8 +296,7 @@ def subscribe(hass: HomeAssistantType, topic: str, return remove -async def _async_setup_server(hass: HomeAssistantType, - config: ConfigType): +async def _async_setup_server(hass: HomeAssistantType, config: ConfigType): """Try to start embedded MQTT broker. This method is a coroutine. @@ -366,7 +365,7 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: broker_config = await _async_setup_server(hass, config) if broker_config is None: - _LOGGER.error('Unable to start embedded MQTT broker') + _LOGGER.error("Unable to start embedded MQTT broker") return False conf.update({ @@ -418,8 +417,8 @@ async def async_setup_entry(hass, entry): })[DOMAIN] elif any(key in conf for key in entry.data): _LOGGER.warning( - 'Data in your config entry is going to override your ' - 'configuration.yaml: %s', entry.data) + "Data in your config entry is going to override your " + "configuration.yaml: %s", entry.data) conf.update(entry.data) @@ -438,8 +437,8 @@ async def async_setup_entry(hass, entry): if (conf.get(CONF_CERTIFICATE) is None and 19999 < conf[CONF_PORT] < 30000 and conf[CONF_BROKER].endswith('.cloudmqtt.com')): - certificate = os.path.join(os.path.dirname(__file__), - 'addtrustexternalcaroot.crt') + certificate = os.path.join( + os.path.dirname(__file__), 'addtrustexternalcaroot.crt') # When the certificate is set to auto, use bundled certs from requests elif conf.get(CONF_CERTIFICATE) == 'auto': @@ -623,12 +622,12 @@ class MQTT: result = await self.hass.async_add_job( self._mqttc.connect, self.broker, self.port, self.keepalive) except OSError as err: - _LOGGER.error('Failed to connect due to exception: %s', err) + _LOGGER.error("Failed to connect due to exception: %s", err) return False if result != 0: import paho.mqtt.client as mqtt - _LOGGER.error('Failed to connect: %s', mqtt.error_string(result)) + _LOGGER.error("Failed to connect: %s", mqtt.error_string(result)) return False self._mqttc.loop_start() @@ -655,7 +654,7 @@ class MQTT: This method is a coroutine. """ if not isinstance(topic, str): - raise HomeAssistantError("topic needs to be a string!") + raise HomeAssistantError("Topic needs to be a string!") subscription = Subscription(topic, msg_callback, qos, encoding) self.subscriptions.append(subscription) @@ -697,8 +696,8 @@ class MQTT: self._mqttc.subscribe, topic, qos) _raise_on_error(result) - def _mqtt_on_connect(self, _mqttc, _userdata, _flags, - result_code: int) -> None: + def _mqtt_on_connect( + self, _mqttc, _userdata, _flags, result_code: int) -> None: """On connect callback. Resubscribe to all topics we were subscribed to and publish birth @@ -707,7 +706,7 @@ class MQTT: import paho.mqtt.client as mqtt if result_code != mqtt.CONNACK_ACCEPTED: - _LOGGER.error('Unable to connect to the MQTT broker: %s', + _LOGGER.error("Unable to connect to the MQTT broker: %s", mqtt.connack_string(result_code)) self._mqttc.disconnect() return @@ -741,14 +740,13 @@ class MQTT: try: payload = msg.payload.decode(subscription.encoding) except (AttributeError, UnicodeDecodeError): - _LOGGER.warning("Can't decode payload %s on %s " - "with encoding %s", - msg.payload, msg.topic, - subscription.encoding) + _LOGGER.warning( + "Can't decode payload %s on %s with encoding %s", + msg.payload, msg.topic, subscription.encoding) continue - self.hass.async_run_job(subscription.callback, - msg.topic, payload, msg.qos) + self.hass.async_run_job( + subscription.callback, msg.topic, payload, msg.qos) def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None: """Disconnected callback.""" @@ -810,7 +808,7 @@ class MqttAvailability(Entity): self._payload_not_available = payload_not_available async def async_added_to_hass(self) -> None: - """Subscribe mqtt events. + """Subscribe MQTT events. This method must be run in the event loop and returns a coroutine. """ diff --git a/homeassistant/components/mqtt/config_flow.py b/homeassistant/components/mqtt/config_flow.py index 82b6f35056b5faf9416c58b7f393bdbeeae656fd..a8987a19742e9aceff944b9898b78229229b73ba 100644 --- a/homeassistant/components/mqtt/config_flow.py +++ b/homeassistant/components/mqtt/config_flow.py @@ -5,7 +5,7 @@ import queue import voluptuous as vol from homeassistant import config_entries -from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_PORT +from homeassistant.const import CONF_PASSWORD, CONF_PORT, CONF_USERNAME from .const import CONF_BROKER @@ -20,14 +20,12 @@ class FlowHandler(config_entries.ConfigFlow): async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if self._async_current_entries(): - return self.async_abort( - reason='single_instance_allowed' - ) + return self.async_abort(reason='single_instance_allowed') return await self.async_step_broker() async def async_step_broker(self, user_input=None): - """Confirm setup.""" + """Confirm the setup.""" errors = {} if user_input is not None: @@ -37,9 +35,7 @@ class FlowHandler(config_entries.ConfigFlow): if can_connect: return self.async_create_entry( - title=user_input[CONF_BROKER], - data=user_input - ) + title=user_input[CONF_BROKER], data=user_input) errors['base'] = 'cannot_connect' @@ -50,10 +46,7 @@ class FlowHandler(config_entries.ConfigFlow): fields[vol.Optional(CONF_PASSWORD)] = str return self.async_show_form( - step_id='broker', - data_schema=vol.Schema(fields), - errors=errors, - ) + step_id='broker', data_schema=vol.Schema(fields), errors=errors) async def async_step_import(self, user_input): """Import a config entry. @@ -62,14 +55,9 @@ class FlowHandler(config_entries.ConfigFlow): Instead, we're going to rely on the values that are in config file. """ if self._async_current_entries(): - return self.async_abort( - reason='single_instance_allowed' - ) - - return self.async_create_entry( - title='configuration.yaml', - data={} - ) + return self.async_abort(reason='single_instance_allowed') + + return self.async_create_entry(title='configuration.yaml', data={}) def try_connection(broker, port, username, password): diff --git a/homeassistant/components/mqtt/discovery.py b/homeassistant/components/mqtt/discovery.py index 128c45f1311adeb77e91b4d0ea292c2f7f127549..689515f64c81e9649357a4e971fb95288ca162c9 100644 --- a/homeassistant/components/mqtt/discovery.py +++ b/homeassistant/components/mqtt/discovery.py @@ -9,9 +9,9 @@ import logging import re from homeassistant.components import mqtt -from homeassistant.helpers.discovery import async_load_platform -from homeassistant.const import CONF_PLATFORM from homeassistant.components.mqtt import CONF_STATE_TOPIC +from homeassistant.const import CONF_PLATFORM +from homeassistant.helpers.discovery import async_load_platform _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/mqtt/server.py b/homeassistant/components/mqtt/server.py index 45529411ed52e6a8fe2cdb8273809ad3070819e2..dda2214ce46d1053ee9185f10655e58a1721be16 100644 --- a/homeassistant/components/mqtt/server.py +++ b/homeassistant/components/mqtt/server.py @@ -14,6 +14,9 @@ from homeassistant.const import EVENT_HOMEASSISTANT_STOP import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['hbmqtt==0.9.4'] + +_LOGGER = logging.getLogger(__name__) + DEPENDENCIES = ['http'] # None allows custom config to be created through generate_config @@ -27,8 +30,6 @@ HBMQTT_CONFIG_SCHEMA = vol.Any(None, vol.Schema({ }) }, extra=vol.ALLOW_EXTRA)) -_LOGGER = logging.getLogger(__name__) - @asyncio.coroutine def async_start(hass, password, server_config): diff --git a/homeassistant/components/shiftr.py b/homeassistant/components/shiftr.py index 67baa045b182cfc29984acdf810635ac9997b277..17a46be47344cc3e450c7d4391c60fe013bc5fd1 100644 --- a/homeassistant/components/shiftr.py +++ b/homeassistant/components/shiftr.py @@ -14,7 +14,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP) from homeassistant.helpers import state as state_helper -REQUIREMENTS = ['paho-mqtt==1.3.1'] +REQUIREMENTS = ['paho-mqtt==1.4.0'] _LOGGER = logging.getLogger(__name__) diff --git a/requirements_all.txt b/requirements_all.txt index 96e5ed0b1e3555a371ff6f38bbbc0621877c0a59..ff438baecd1a360ad729e3534eaed13885ad66e9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -660,7 +660,7 @@ orvibo==1.1.1 # homeassistant.components.mqtt # homeassistant.components.shiftr -paho-mqtt==1.3.1 +paho-mqtt==1.4.0 # homeassistant.components.media_player.panasonic_viera panasonic_viera==0.3.1 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 42561336ff95edee45a03c869c2ac479ed70fd9d..6990c4da5438f619f4d43329da15cf36397333b8 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -112,7 +112,7 @@ numpy==1.15.1 # homeassistant.components.mqtt # homeassistant.components.shiftr -paho-mqtt==1.3.1 +paho-mqtt==1.4.0 # homeassistant.components.device_tracker.aruba # homeassistant.components.device_tracker.asuswrt