Clean up Netatmo integration (#50904)

This commit is contained in:
Tobias Sauerwein 2021-05-20 19:28:21 +02:00 committed by GitHub
parent 19d25cd901
commit 0623648309
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 50 additions and 17 deletions

View File

@ -44,6 +44,10 @@ from .const import (
DOMAIN, DOMAIN,
OAUTH2_AUTHORIZE, OAUTH2_AUTHORIZE,
OAUTH2_TOKEN, OAUTH2_TOKEN,
PLATFORMS,
WEBHOOK_ACTIVATION,
WEBHOOK_DEACTIVATION,
WEBHOOK_PUSH_TYPE,
) )
from .data_handler import NetatmoDataHandler from .data_handler import NetatmoDataHandler
from .webhook import async_handle_webhook from .webhook import async_handle_webhook
@ -62,8 +66,6 @@ CONFIG_SCHEMA = vol.Schema(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
PLATFORMS = ["camera", "climate", "light", "sensor"]
async def async_setup(hass: HomeAssistant, config: dict): async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the Netatmo component.""" """Set up the Netatmo component."""
@ -126,7 +128,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
async_dispatcher_send( async_dispatcher_send(
hass, hass,
f"signal-{DOMAIN}-webhook-None", f"signal-{DOMAIN}-webhook-None",
{"type": "None", "data": {"push_type": "webhook_deactivation"}}, {"type": "None", "data": {WEBHOOK_PUSH_TYPE: WEBHOOK_DEACTIVATION}},
) )
webhook_unregister(hass, entry.data[CONF_WEBHOOK_ID]) webhook_unregister(hass, entry.data[CONF_WEBHOOK_ID])
await hass.data[DOMAIN][entry.entry_id][AUTH].async_dropwebhook() await hass.data[DOMAIN][entry.entry_id][AUTH].async_dropwebhook()
@ -150,9 +152,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
entry.data[CONF_WEBHOOK_ID] entry.data[CONF_WEBHOOK_ID]
) )
if entry.data["auth_implementation"] == "cloud" and not webhook_url.startswith( if entry.data[
"https://" "auth_implementation"
): ] == cloud.DOMAIN and not webhook_url.startswith("https://"):
_LOGGER.warning( _LOGGER.warning(
"Webhook not registered - " "Webhook not registered - "
"https and port 443 is required to register the webhook" "https and port 443 is required to register the webhook"
@ -170,7 +172,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
async def handle_event(event): async def handle_event(event):
"""Handle webhook events.""" """Handle webhook events."""
if event["data"]["push_type"] == "webhook_activation": if event["data"][WEBHOOK_PUSH_TYPE] == WEBHOOK_ACTIVATION:
if activation_listener is not None: if activation_listener is not None:
activation_listener() activation_listener()

View File

@ -31,6 +31,9 @@ from .const import (
SERVICE_SET_PERSON_AWAY, SERVICE_SET_PERSON_AWAY,
SERVICE_SET_PERSONS_HOME, SERVICE_SET_PERSONS_HOME,
SIGNAL_NAME, SIGNAL_NAME,
WEBHOOK_LIGHT_MODE,
WEBHOOK_NACAMERA_CONNECTION,
WEBHOOK_PUSH_TYPE,
) )
from .data_handler import CAMERA_DATA_CLASS_NAME from .data_handler import CAMERA_DATA_CLASS_NAME
from .netatmo_entity_base import NetatmoBase from .netatmo_entity_base import NetatmoBase
@ -158,13 +161,16 @@ class NetatmoCamera(NetatmoBase, Camera):
return return
if data["home_id"] == self._home_id and data["camera_id"] == self._id: if data["home_id"] == self._home_id and data["camera_id"] == self._id:
if data["push_type"] in ["NACamera-off", "NACamera-disconnection"]: if data[WEBHOOK_PUSH_TYPE] in ["NACamera-off", "NACamera-disconnection"]:
self.is_streaming = False self.is_streaming = False
self._status = "off" self._status = "off"
elif data["push_type"] in ["NACamera-on", "NACamera-connection"]: elif data[WEBHOOK_PUSH_TYPE] in [
"NACamera-on",
WEBHOOK_NACAMERA_CONNECTION,
]:
self.is_streaming = True self.is_streaming = True
self._status = "on" self._status = "on"
elif data["push_type"] == "NOC-light_mode": elif data[WEBHOOK_PUSH_TYPE] == WEBHOOK_LIGHT_MODE:
self._light_state = data["sub_type"] self._light_state = data["sub_type"]
self.async_write_ha_state() self.async_write_ha_state()
@ -176,8 +182,10 @@ class NetatmoCamera(NetatmoBase, Camera):
return await self._data.async_get_live_snapshot(camera_id=self._id) return await self._data.async_get_live_snapshot(camera_id=self._id)
except ( except (
aiohttp.ClientPayloadError, aiohttp.ClientPayloadError,
pyatmo.exceptions.ApiError,
aiohttp.ContentTypeError, aiohttp.ContentTypeError,
aiohttp.ServerDisconnectedError,
aiohttp.ClientConnectorError,
pyatmo.exceptions.ApiError,
) as err: ) as err:
_LOGGER.debug("Could not fetch live camera image (%s)", err) _LOGGER.debug("Could not fetch live camera image (%s)", err)
return None return None

View File

@ -1,9 +1,16 @@
"""Constants used by the Netatmo component.""" """Constants used by the Netatmo component."""
from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
API = "api" API = "api"
DOMAIN = "netatmo" DOMAIN = "netatmo"
MANUFACTURER = "Netatmo" MANUFACTURER = "Netatmo"
PLATFORMS = [CAMERA_DOMAIN, CLIMATE_DOMAIN, LIGHT_DOMAIN, SENSOR_DOMAIN]
MODEL_NAPLUG = "Relay" MODEL_NAPLUG = "Relay"
MODEL_NATHERM1 = "Smart Thermostat" MODEL_NATHERM1 = "Smart Thermostat"
MODEL_NRV = "Smart Radiator Valves" MODEL_NRV = "Smart Radiator Valves"
@ -156,3 +163,9 @@ MODE_LIGHT_ON = "on"
MODE_LIGHT_OFF = "off" MODE_LIGHT_OFF = "off"
MODE_LIGHT_AUTO = "auto" MODE_LIGHT_AUTO = "auto"
CAMERA_LIGHT_MODES = [MODE_LIGHT_ON, MODE_LIGHT_OFF, MODE_LIGHT_AUTO] CAMERA_LIGHT_MODES = [MODE_LIGHT_ON, MODE_LIGHT_OFF, MODE_LIGHT_AUTO]
WEBHOOK_ACTIVATION = "webhook_activation"
WEBHOOK_DEACTIVATION = "webhook_deactivation"
WEBHOOK_NACAMERA_CONNECTION = "NACamera-connection"
WEBHOOK_PUSH_TYPE = "push_type"
WEBHOOK_LIGHT_MODE = "NOC-light_mode"

View File

@ -15,7 +15,15 @@ from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
from .const import AUTH, DOMAIN, MANUFACTURER from .const import (
AUTH,
DOMAIN,
MANUFACTURER,
WEBHOOK_ACTIVATION,
WEBHOOK_DEACTIVATION,
WEBHOOK_NACAMERA_CONNECTION,
WEBHOOK_PUSH_TYPE,
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -108,15 +116,15 @@ class NetatmoDataHandler:
async def handle_event(self, event): async def handle_event(self, event):
"""Handle webhook events.""" """Handle webhook events."""
if event["data"]["push_type"] == "webhook_activation": if event["data"][WEBHOOK_PUSH_TYPE] == WEBHOOK_ACTIVATION:
_LOGGER.info("%s webhook successfully registered", MANUFACTURER) _LOGGER.info("%s webhook successfully registered", MANUFACTURER)
self._webhook = True self._webhook = True
elif event["data"]["push_type"] == "webhook_deactivation": elif event["data"][WEBHOOK_PUSH_TYPE] == WEBHOOK_DEACTIVATION:
_LOGGER.info("%s webhook unregistered", MANUFACTURER) _LOGGER.info("%s webhook unregistered", MANUFACTURER)
self._webhook = False self._webhook = False
elif event["data"]["push_type"] == "NACamera-connection": elif event["data"][WEBHOOK_PUSH_TYPE] == WEBHOOK_NACAMERA_CONNECTION:
_LOGGER.debug("%s camera reconnected", MANUFACTURER) _LOGGER.debug("%s camera reconnected", MANUFACTURER)
self.async_force_update(CAMERA_DATA_CLASS_NAME) self.async_force_update(CAMERA_DATA_CLASS_NAME)

View File

@ -12,6 +12,8 @@ from .const import (
EVENT_TYPE_LIGHT_MODE, EVENT_TYPE_LIGHT_MODE,
MANUFACTURER, MANUFACTURER,
SIGNAL_NAME, SIGNAL_NAME,
WEBHOOK_LIGHT_MODE,
WEBHOOK_PUSH_TYPE,
) )
from .data_handler import CAMERA_DATA_CLASS_NAME, NetatmoDataHandler from .data_handler import CAMERA_DATA_CLASS_NAME, NetatmoDataHandler
from .netatmo_entity_base import NetatmoBase from .netatmo_entity_base import NetatmoBase
@ -105,7 +107,7 @@ class NetatmoLight(NetatmoBase, LightEntity):
if ( if (
data["home_id"] == self._home_id data["home_id"] == self._home_id
and data["camera_id"] == self._id and data["camera_id"] == self._id
and data["push_type"] == "NOC-light_mode" and data[WEBHOOK_PUSH_TYPE] == WEBHOOK_LIGHT_MODE
): ):
self._is_on = bool(data["sub_type"] == "on") self._is_on = bool(data["sub_type"] == "on")

View File

@ -159,7 +159,7 @@ def async_parse_identifier(
item: MediaSourceItem, item: MediaSourceItem,
) -> tuple[str, str, int | None]: ) -> tuple[str, str, int | None]:
"""Parse identifier.""" """Parse identifier."""
if "/" not in item.identifier: if not item.identifier or "/" not in item.identifier:
return "events", "", None return "events", "", None
source, path = item.identifier.lstrip("/").split("/", 1) source, path = item.identifier.lstrip("/").split("/", 1)