Refactor Netatmo integration (#29851)

* Refactor to use ids in data class

* Use station_id

* Refactor Netatmo to use oauth

* Remove old code

* Clean up

* Clean up

* Clean up

* Refactor binary sensor

* Add initial light implementation

* Add discovery

* Add set schedule service back in

* Add discovery via homekit

* More work on the light

* Fix set schedule service

* Clean up

* Remove unnecessary code

* Add support for multiple entities/accounts

* Fix MANUFACTURER typo

* Remove multiline inline if statement

* Only add tags when camera type is welcome

* Remove on/off as it's currently broken

* Fix camera turn_on/off

* Fix debug message

* Refactor some camera code

* Refactor camera methods

* Remove old code

* Rename method

* Update persons regularly

* Remove unused code

* Refactor method

* Fix isort

* Add english strings

* Catch NoDevice exception

* Fix unique id and only add sensors for tags if present

* Address comments

* Remove ToDo comment

* Add set_light_auto back in

* Add debug info

* Fix multiple camera issue

* Move camera light service to camera

* Only allow camera entities

* Make test pass

* Upgrade pyatmo module to 3.2.0

* Update requirements

* Remove list comprehension

* Remove guideline violating code

* Remove stale code

* Rename devices to entities

* Remove light platform

* Remove commented code

* Exclude files from coverage

* Remove unused code

* Fix unique id

* Address comments

* Fix comments

* Exclude sensor as well

* Add another test

* Use core interfaces
This commit is contained in:
cgtobi authored and Martin Hjelmare committed 2020-01-11 12:20:00 +01:00
1 parent 5ffbf55170
commit e793ed9ab0
19 files changed
+762 -927

No files matched your search

+119 -246
View File
@@ -1,25 +1,28 @@
"""Support for the Netatmo cameras."""
import logging
from pyatmo import NoDevice
import pyatmo
import requests
import voluptuous as vol
from homeassistant.components.camera import (
CAMERA_SERVICE_SCHEMA,
PLATFORM_SCHEMA,
DOMAIN as CAMERA_DOMAIN,
SUPPORT_STREAM,
Camera,
)
from homeassistant.const import CONF_VERIFY_SSL, STATE_OFF, STATE_ON
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
import homeassistant.helpers.config_validation as cv
from homeassistant.util import Throttle
from . import CameraData
from .const import DATA_NETATMO_AUTH, DOMAIN
from .const import (
ATTR_PSEUDO,
AUTH,
DATA_PERSONS,
DOMAIN,
MANUFACTURER,
MIN_TIME_BETWEEN_EVENT_UPDATES,
MIN_TIME_BETWEEN_UPDATES,
)
_LOGGER = logging.getLogger(__name__)
@@ -31,96 +34,61 @@ DEFAULT_QUALITY = "high"
VALID_QUALITIES = ["high", "medium", "low", "poor"]
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
vol.Optional(CONF_HOME): cv.string,
vol.Optional(CONF_CAMERAS, default=[]): vol.All(cv.ensure_list, [cv.string]),
vol.Optional(CONF_QUALITY, default=DEFAULT_QUALITY): vol.All(
cv.string, vol.In(VALID_QUALITIES)
),
}
)
_BOOL_TO_STATE = {True: STATE_ON, False: STATE_OFF}
SCHEMA_SERVICE_SETLIGHTAUTO = vol.Schema(
{vol.Optional(ATTR_ENTITY_ID): cv.entity_domain(CAMERA_DOMAIN)}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up access to Netatmo cameras."""
home = config.get(CONF_HOME)
verify_ssl = config.get(CONF_VERIFY_SSL, True)
quality = config.get(CONF_QUALITY, DEFAULT_QUALITY)
auth = hass.data[DATA_NETATMO_AUTH]
async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Netatmo camera platform."""
try:
data = CameraData(hass, auth, home)
for camera_name in data.get_camera_names():
camera_type = data.get_camera_type(camera=camera_name, home=home)
if CONF_CAMERAS in config:
if (
config[CONF_CAMERAS] != []
and camera_name not in config[CONF_CAMERAS]
):
continue
add_entities(
[
def get_entities():
"""Retrieve Netatmo entities."""
entities = []
try:
camera_data = CameraData(hass, hass.data[DOMAIN][entry.entry_id][AUTH])
for camera in camera_data.get_all_cameras():
_LOGGER.debug("Setting up camera %s %s", camera["id"], camera["name"])
entities.append(
NetatmoCamera(
data, camera_name, home, camera_type, verify_ssl, quality
camera_data, camera["id"], camera["type"], True, DEFAULT_QUALITY
)
]
)
data.get_persons()
except NoDevice:
return None
)
camera_data.update_persons()
except pyatmo.NoDevice:
_LOGGER.debug("No cameras found")
return entities
async def async_service_handler(call):
"""Handle service call."""
_LOGGER.debug(
"Service handler invoked with service=%s and data=%s",
call.service,
call.data,
)
service = call.service
entity_id = call.data["entity_id"][0]
async_dispatcher_send(hass, f"{service}_{entity_id}")
async_add_entities(await hass.async_add_executor_job(get_entities), True)
hass.services.async_register(
DOMAIN, "set_light_auto", async_service_handler, CAMERA_SERVICE_SCHEMA
)
hass.services.async_register(
DOMAIN, "set_light_on", async_service_handler, CAMERA_SERVICE_SCHEMA
)
hass.services.async_register(
DOMAIN, "set_light_off", async_service_handler, CAMERA_SERVICE_SCHEMA
)
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Netatmo camera platform."""
return
class NetatmoCamera(Camera):
"""Representation of the images published from a Netatmo camera."""
"""Representation of a Netatmo camera."""
def __init__(self, data, camera_name, home, camera_type, verify_ssl, quality):
def __init__(self, data, camera_id, camera_type, verify_ssl, quality):
"""Set up for access to the Netatmo camera images."""
super().__init__()
self._data = data
self._camera_name = camera_name
self._home = home
if home:
self._name = f"{home} / {camera_name}"
else:
self._name = camera_name
self._cameratype = camera_type
self._camera_id = camera_id
self._camera_name = self._data.camera_data.get_camera(cid=camera_id).get("name")
self._name = f"{MANUFACTURER} {self._camera_name}"
self._camera_type = camera_type
self._unique_id = f"{self._camera_id}-{self._camera_type}"
self._verify_ssl = verify_ssl
self._quality = quality
# URLs.
# URLs
self._vpnurl = None
self._localurl = None
# Identifier
self._id = None
# Monitoring status.
# Monitoring status
self._status = None
# SD Card status
@@ -132,12 +100,6 @@ class NetatmoCamera(Camera):
# Is local
self._is_local = None
# VPN URL
self._vpn_url = None
# Light mode status
self._light_mode_status = None
def camera_image(self):
"""Return a still image response from the camera."""
try:
@@ -152,23 +114,21 @@ class NetatmoCamera(Camera):
verify=self._verify_ssl,
)
else:
_LOGGER.error("Welcome VPN URL is None")
_LOGGER.error("Welcome/Presence VPN URL is None")
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
(self._vpnurl, self._localurl) = self._data.camera_data.camera_urls(
cid=self._camera_id
)
return None
except requests.exceptions.RequestException as error:
_LOGGER.error("Welcome URL changed: %s", error)
_LOGGER.info("Welcome/Presence URL changed: %s", error)
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
(self._vpnurl, self._localurl) = self._data.camera_data.camera_urls(
cid=self._camera_id
)
return None
return response.content
# Entity property overrides
@property
def should_poll(self) -> bool:
"""Return True if entity has to be polled for state.
@@ -182,24 +142,26 @@ class NetatmoCamera(Camera):
"""Return the name of this Netatmo camera device."""
return self._name
@property
def device_info(self):
"""Return the device info for the sensor."""
return {
"identifiers": {(DOMAIN, self._camera_id)},
"name": self._camera_name,
"manufacturer": MANUFACTURER,
"model": self._camera_type,
}
@property
def device_state_attributes(self):
"""Return the Netatmo-specific camera state attributes."""
_LOGGER.debug("Getting new attributes from camera netatmo '%s'", self._name)
attr = {}
attr["id"] = self._id
attr["id"] = self._camera_id
attr["status"] = self._status
attr["sd_status"] = self._sd_status
attr["alim_status"] = self._alim_status
attr["is_local"] = self._is_local
attr["vpn_url"] = self._vpn_url
if self.model == "Presence":
attr["light_mode_status"] = self._light_mode_status
_LOGGER.debug("Attributes of '%s' = %s", self._name, attr)
attr["vpn_url"] = self._vpnurl
return attr
@@ -221,7 +183,7 @@ class NetatmoCamera(Camera):
@property
def brand(self):
"""Return the camera brand."""
return "Netatmo"
return MANUFACTURER
@property
def motion_detection_enabled(self):
@@ -243,173 +205,84 @@ class NetatmoCamera(Camera):
@property
def model(self):
"""Return the camera model."""
if self._cameratype == "NOC":
if self._camera_type == "NOC":
return "Presence"
if self._cameratype == "NACamera":
if self._camera_type == "NACamera":
return "Welcome"
return None
# Other Entity method overrides
async def async_added_to_hass(self):
"""Subscribe to signals and add camera to list."""
_LOGGER.debug("Registering services for entity_id=%s", self.entity_id)
async_dispatcher_connect(
self.hass, f"set_light_auto_{self.entity_id}", self.set_light_auto
)
async_dispatcher_connect(
self.hass, f"set_light_on_{self.entity_id}", self.set_light_on
)
async_dispatcher_connect(
self.hass, f"set_light_off_{self.entity_id}", self.set_light_off
)
@property
def unique_id(self):
"""Return the unique ID for this sensor."""
return self._unique_id
def update(self):
"""Update entity status."""
_LOGGER.debug("Updating camera netatmo '%s'", self._name)
# Refresh camera data.
# Refresh camera data
self._data.update()
# URLs.
self._vpnurl, self._localurl = self._data.camera_data.cameraUrls(
camera=self._camera_name
camera = self._data.camera_data.get_camera(cid=self._camera_id)
# URLs
self._vpnurl, self._localurl = self._data.camera_data.camera_urls(
cid=self._camera_id
)
# Identifier
self._id = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["id"]
# Monitoring status.
self._status = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["status"]
_LOGGER.debug("Status of '%s' = %s", self._name, self._status)
# Monitoring status
self._status = camera.get("status")
# SD Card status
self._sd_status = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["sd_status"]
self._sd_status = camera.get("sd_status")
# Power status
self._alim_status = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["alim_status"]
self._alim_status = camera.get("alim_status")
# Is local
self._is_local = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["is_local"]
# VPN URL
self._vpn_url = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["vpn_url"]
self._is_local = camera.get("is_local")
self.is_streaming = self._alim_status == "on"
if self.model == "Presence":
# Light mode status
self._light_mode_status = self._data.camera_data.cameraByName(
camera=self._camera_name, home=self._home
)["light_mode_status"]
# Camera method overrides
class CameraData:
"""Get the latest data from Netatmo."""
def enable_motion_detection(self):
"""Enable motion detection in the camera."""
_LOGGER.debug("Enable motion detection of the camera '%s'", self._name)
self._enable_motion_detection(True)
def __init__(self, hass, auth):
"""Initialize the data object."""
self._hass = hass
self.auth = auth
self.camera_data = None
def disable_motion_detection(self):
"""Disable motion detection in camera."""
_LOGGER.debug("Disable motion detection of the camera '%s'", self._name)
self._enable_motion_detection(False)
def get_all_cameras(self):
"""Return all camera available on the API as a list."""
self.update()
cameras = []
for camera in self.camera_data.cameras.values():
cameras.extend(camera.values())
return cameras
def _enable_motion_detection(self, enable):
"""Enable or disable motion detection."""
try:
if self._localurl:
requests.get(
f"{self._localurl}/command/changestatus?status={_BOOL_TO_STATE.get(enable)}",
timeout=10,
)
elif self._vpnurl:
requests.get(
f"{self._vpnurl}/command/changestatus?status={_BOOL_TO_STATE.get(enable)}",
timeout=10,
verify=self._verify_ssl,
)
else:
_LOGGER.error("Welcome/Presence VPN URL is None")
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
)
return None
except requests.exceptions.RequestException as error:
_LOGGER.error("Welcome/Presence URL changed: %s", error)
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
def get_modules(self, camera_id):
"""Return all modules for a given camera."""
return self.camera_data.get_camera(camera_id).get("modules", [])
def get_camera_type(self, camera_id):
"""Return camera type for a camera, cid has preference over camera."""
return self.camera_data.cameraType(cid=camera_id)
def update_persons(self):
"""Gather person data for webhooks."""
for person_id, person_data in self.camera_data.persons.items():
self._hass.data[DOMAIN][DATA_PERSONS][person_id] = person_data.get(
ATTR_PSEUDO
)
return None
else:
self.async_schedule_update_ha_state(True)
# Netatmo Presence specific camera method.
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Call the Netatmo API to update the data."""
self.camera_data = pyatmo.CameraData(self.auth, size=100)
self.update_persons()
def set_light_auto(self):
"""Set flood light in automatic mode."""
_LOGGER.debug(
"Set the flood light in automatic mode for the camera '%s'", self._name
)
self._set_light_mode("auto")
def set_light_on(self):
"""Set flood light on."""
_LOGGER.debug("Set the flood light on for the camera '%s'", self._name)
self._set_light_mode("on")
def set_light_off(self):
"""Set flood light off."""
_LOGGER.debug("Set the flood light off for the camera '%s'", self._name)
self._set_light_mode("off")
def _set_light_mode(self, mode):
"""Set light mode ('auto', 'on', 'off')."""
if self.model == "Presence":
try:
config = f'{{"mode":"{mode}"}}'
if self._localurl:
requests.get(
f"{self._localurl}/command/floodlight_set_config?config={config}",
timeout=10,
)
elif self._vpnurl:
requests.get(
f"{self._vpnurl}/command/floodlight_set_config?config={config}",
timeout=10,
verify=self._verify_ssl,
)
else:
_LOGGER.error("Presence VPN URL is None")
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
)
return None
except requests.exceptions.RequestException as error:
_LOGGER.error("Presence URL changed: %s", error)
self._data.update()
(self._vpnurl, self._localurl) = self._data.camera_data.cameraUrls(
camera=self._camera_name
)
return None
else:
self.async_schedule_update_ha_state(True)
else:
_LOGGER.error("Unsupported camera model for light mode")
@Throttle(MIN_TIME_BETWEEN_EVENT_UPDATES)
def update_event(self, camera_type):
"""Call the Netatmo API to update the events."""
self.camera_data.updateEvent(devicetype=camera_type)