Add Netatmo data handler (#35571)
* Fix webhook registration * Only load camera platform with valid scope * Add initial data handler and netatmo base class * Update camera to use data handler * Update init * Parallelize API calls * Remove cruft * Minor tweaks * Refactor data handler * Update climate to use data handler * Fix pylint error * Fix climate update not getting fresh data * Update climate data * update to pyatmo 4.0.0 * Refactor for pyatmo 4.0.0 * Exclude from coverage until tests are written * Fix typo * Reduce parallel calls * Add heating request attr * Async get_entities * Undo parallel updates * Fix camera issue * Introduce individual scan interval per device class * Some cleanup * Add basic webhook support for climate to improve responsiveness * Replace ClimateDevice by ClimateEntity * Add support for turning camera on/off * Update camera state upon webhook events * Guard data class registration with lock * Capture errors * Add light platform * Add dis-/connect handling * Fix set schedule service * Remove extra calls * Add service to set person(s) home/away * Add service descriptions * Improve service descriptions * Use LightEntity instead of Light * Add guard if no data is retrieved * Make services entity based * Only raise platform not ready if there is a NOC * Register webhook even during runtime * Fix turning off event * Fix linter error * Fix linter error * Exclude light platform from coverage * Change log level * Refactor public weather sensor to use data handler * Prevent too short coordinates * Ignore modules without _id * Code cleanup * Fix test * Exit early if no home data is retrieved * Prevent discovery if already active * Add services to (un-)register webhook * Fix tests * Not actually a coroutine * Move methods to base class * Address pylint comment * Address pylint complaints * Address comments * Address more comments * Add docstring * Use single instance allowed * Extract method * Remove cruft * Write state directly * Fix test * Add file to coverage * Move nested function * Move nested function * Update docstring * Clean up code * Fix webhook bug * Clean up listeners * Use deque * Clean up prints * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update homeassistant/components/netatmo/camera.py Co-authored-by: J. Nick Koston <nick@koston.org> * Rename data_class variable * Break when match * Extract method * Extract methods * Rename variable * Improve comment * Some refinements * Extra * Extract method * Simplify code * Improve reability * Code simplification * Simplify code * Simplify code * Code cleanup * Fix import * Clean up * Clean up magic strings * Replace data_class_name with CAMERA_DATA_CLASS_NAME * Replace data_class_name with CAMERA_DATA_CLASS_NAME * Replace data_class_name with HOMEDATA_DATA_CLASS_NAME * Replace data_class_name in public weather sensor * Clean up * Remove deprecated config options * Schedule immediate update on camera reconnect * Use UUID to clearly identify public weather areas * Use subscription mode * Move clean up of temporary data classes * Delay data class removal * Fix linter complaints * Adjust test * Only setup lights if webhook are registered * Prevent crash with old config entries * Don't cache home ids * Remove stale code * Fix coordinates if entered mixed up by the user * Move nested function * Add test case for swapped coordinates * Only wait for discovery entries * Only use what I need * Bring stuff closer to where it's used * Auto clean up setup data classes * Code cleanup * Remove unneccessary lock * Update homeassistant/components/netatmo/sensor.py Co-authored-by: J. Nick Koston <nick@koston.org> * Update tests/components/netatmo/test_config_flow.py Co-authored-by: J. Nick Koston <nick@koston.org> * Clean up dead code * Fix formating * Extend coverage * Extend coverage Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
1 parent
0780650015
commit
31dbdff3c4
19 files changed
+1422
-846
No files matched your search
@@ -10,59 +10,113 @@ from homeassistant.components.camera import (
|
||||
SUPPORT_STREAM,
|
||||
Camera,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.util import Throttle
|
||||
from homeassistant.const import ATTR_ENTITY_ID
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import config_validation as cv, entity_platform
|
||||
|
||||
from .const import (
|
||||
ATTR_PERSON,
|
||||
ATTR_PERSONS,
|
||||
ATTR_PSEUDO,
|
||||
AUTH,
|
||||
DATA_HANDLER,
|
||||
DATA_PERSONS,
|
||||
DOMAIN,
|
||||
MANUFACTURER,
|
||||
MIN_TIME_BETWEEN_EVENT_UPDATES,
|
||||
MIN_TIME_BETWEEN_UPDATES,
|
||||
MODELS,
|
||||
SERVICE_SETPERSONAWAY,
|
||||
SERVICE_SETPERSONSHOME,
|
||||
SIGNAL_NAME,
|
||||
)
|
||||
from .data_handler import CAMERA_DATA_CLASS_NAME
|
||||
from .netatmo_entity_base import NetatmoBase
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_HOME = "home"
|
||||
CONF_CAMERAS = "cameras"
|
||||
CONF_QUALITY = "quality"
|
||||
|
||||
DEFAULT_QUALITY = "high"
|
||||
|
||||
VALID_QUALITIES = ["high", "medium", "low", "poor"]
|
||||
SCHEMA_SERVICE_SETPERSONSHOME = vol.Schema(
|
||||
{
|
||||
vol.Required(ATTR_ENTITY_ID): cv.entity_domain(CAMERA_DOMAIN),
|
||||
vol.Required(ATTR_PERSONS): vol.All(cv.ensure_list, [cv.string]),
|
||||
}
|
||||
)
|
||||
|
||||
_BOOL_TO_STATE = {True: STATE_ON, False: STATE_OFF}
|
||||
|
||||
SCHEMA_SERVICE_SETLIGHTAUTO = vol.Schema(
|
||||
{vol.Optional(ATTR_ENTITY_ID): cv.entity_domain(CAMERA_DOMAIN)}
|
||||
SCHEMA_SERVICE_SETPERSONAWAY = vol.Schema(
|
||||
{
|
||||
vol.Required(ATTR_ENTITY_ID): cv.entity_domain(CAMERA_DOMAIN),
|
||||
vol.Optional(ATTR_PERSON): cv.string,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
"""Set up the Netatmo camera platform."""
|
||||
if "access_camera" not in entry.data["token"]["scope"]:
|
||||
_LOGGER.info(
|
||||
"Cameras are currently not supported with this authentication method"
|
||||
)
|
||||
return
|
||||
|
||||
def get_entities():
|
||||
data_handler = hass.data[DOMAIN][entry.entry_id][DATA_HANDLER]
|
||||
|
||||
async def get_entities():
|
||||
"""Retrieve Netatmo entities."""
|
||||
await data_handler.register_data_class(
|
||||
CAMERA_DATA_CLASS_NAME, CAMERA_DATA_CLASS_NAME, None
|
||||
)
|
||||
|
||||
data = data_handler.data
|
||||
|
||||
if not data.get(CAMERA_DATA_CLASS_NAME):
|
||||
return []
|
||||
|
||||
data_class = data_handler.data[CAMERA_DATA_CLASS_NAME]
|
||||
|
||||
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"])
|
||||
all_cameras = []
|
||||
for home in data_class.cameras.values():
|
||||
for camera in home.values():
|
||||
all_cameras.append(camera)
|
||||
|
||||
for camera in all_cameras:
|
||||
_LOGGER.debug("Adding camera %s %s", camera["id"], camera["name"])
|
||||
entities.append(
|
||||
NetatmoCamera(
|
||||
camera_data, camera["id"], camera["type"], True, DEFAULT_QUALITY
|
||||
data_handler,
|
||||
camera["id"],
|
||||
camera["type"],
|
||||
camera["home_id"],
|
||||
DEFAULT_QUALITY,
|
||||
)
|
||||
)
|
||||
camera_data.update_persons()
|
||||
|
||||
for person_id, person_data in data_handler.data[
|
||||
CAMERA_DATA_CLASS_NAME
|
||||
].persons.items():
|
||||
hass.data[DOMAIN][DATA_PERSONS][person_id] = person_data.get(
|
||||
ATTR_PSEUDO
|
||||
)
|
||||
except pyatmo.NoDevice:
|
||||
_LOGGER.debug("No cameras found")
|
||||
|
||||
return entities
|
||||
|
||||
async_add_entities(await hass.async_add_executor_job(get_entities), True)
|
||||
async_add_entities(await get_entities(), True)
|
||||
|
||||
platform = entity_platform.current_platform.get()
|
||||
|
||||
if data_handler.data[CAMERA_DATA_CLASS_NAME] is not None:
|
||||
platform.async_register_entity_service(
|
||||
SERVICE_SETPERSONSHOME,
|
||||
SCHEMA_SERVICE_SETPERSONSHOME,
|
||||
"_service_setpersonshome",
|
||||
)
|
||||
platform.async_register_entity_service(
|
||||
SERVICE_SETPERSONAWAY,
|
||||
SCHEMA_SERVICE_SETPERSONAWAY,
|
||||
"_service_setpersonaway",
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
|
||||
@@ -70,19 +124,26 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
|
||||
return
|
||||
|
||||
|
||||
class NetatmoCamera(Camera):
|
||||
class NetatmoCamera(NetatmoBase, Camera):
|
||||
"""Representation of a Netatmo camera."""
|
||||
|
||||
def __init__(self, data, camera_id, camera_type, verify_ssl, quality):
|
||||
def __init__(
|
||||
self, data_handler, camera_id, camera_type, home_id, quality,
|
||||
):
|
||||
"""Set up for access to the Netatmo camera images."""
|
||||
super().__init__()
|
||||
self._data = data
|
||||
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
|
||||
Camera.__init__(self)
|
||||
super().__init__(data_handler)
|
||||
|
||||
self._data_classes.append(
|
||||
{"name": CAMERA_DATA_CLASS_NAME, SIGNAL_NAME: CAMERA_DATA_CLASS_NAME}
|
||||
)
|
||||
|
||||
self._id = camera_id
|
||||
self._home_id = home_id
|
||||
self._device_name = self._data.get_camera(camera_id=camera_id).get("name")
|
||||
self._name = f"{MANUFACTURER} {self._device_name}"
|
||||
self._model = camera_type
|
||||
self._unique_id = f"{self._id}-{self._model}"
|
||||
self._quality = quality
|
||||
self._vpnurl = None
|
||||
self._localurl = None
|
||||
@@ -91,6 +152,35 @@ class NetatmoCamera(Camera):
|
||||
self._alim_status = None
|
||||
self._is_local = None
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Entity created."""
|
||||
await super().async_added_to_hass()
|
||||
|
||||
self._listeners.append(
|
||||
self.hass.bus.async_listen("netatmo_event", self.handle_event)
|
||||
)
|
||||
|
||||
async def handle_event(self, event):
|
||||
"""Handle webhook events."""
|
||||
data = event.data["data"]
|
||||
|
||||
if not data.get("event_type"):
|
||||
return
|
||||
|
||||
if not data.get("camera_id"):
|
||||
return
|
||||
|
||||
if data["home_id"] == self._home_id and data["camera_id"] == self._id:
|
||||
if data["push_type"] in ["NACamera-off", "NACamera-disconnection"]:
|
||||
self.is_streaming = False
|
||||
self._status = "off"
|
||||
elif data["push_type"] in ["NACamera-on", "NACamera-connection"]:
|
||||
self.is_streaming = True
|
||||
self._status = "on"
|
||||
|
||||
self.async_write_ha_state()
|
||||
return
|
||||
|
||||
def camera_image(self):
|
||||
"""Return a still image response from the camera."""
|
||||
try:
|
||||
@@ -100,77 +190,46 @@ class NetatmoCamera(Camera):
|
||||
)
|
||||
elif self._vpnurl:
|
||||
response = requests.get(
|
||||
f"{self._vpnurl}/live/snapshot_720.jpg",
|
||||
timeout=10,
|
||||
verify=self._verify_ssl,
|
||||
f"{self._vpnurl}/live/snapshot_720.jpg", timeout=10, verify=True,
|
||||
)
|
||||
else:
|
||||
_LOGGER.error("Welcome/Presence VPN URL is None")
|
||||
self._data.update()
|
||||
(self._vpnurl, self._localurl) = self._data.camera_data.camera_urls(
|
||||
cid=self._camera_id
|
||||
(self._vpnurl, self._localurl) = self._data.camera_urls(
|
||||
camera_id=self._id
|
||||
)
|
||||
return None
|
||||
|
||||
except requests.exceptions.RequestException as error:
|
||||
_LOGGER.info("Welcome/Presence URL changed: %s", error)
|
||||
self._data.update()
|
||||
(self._vpnurl, self._localurl) = self._data.camera_data.camera_urls(
|
||||
cid=self._camera_id
|
||||
)
|
||||
self._data.update_camera_urls(camera_id=self._id)
|
||||
(self._vpnurl, self._localurl) = self._data.camera_urls(camera_id=self._id)
|
||||
return None
|
||||
|
||||
return response.content
|
||||
|
||||
@property
|
||||
def should_poll(self) -> bool:
|
||||
"""Return True if entity has to be polled for state.
|
||||
|
||||
False if entity pushes its state to HA.
|
||||
"""
|
||||
return True
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""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": MODELS[self._camera_type],
|
||||
}
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the Netatmo-specific camera state attributes."""
|
||||
attr = {}
|
||||
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._vpnurl
|
||||
|
||||
return attr
|
||||
return {
|
||||
"id": self._id,
|
||||
"status": self._status,
|
||||
"sd_status": self._sd_status,
|
||||
"alim_status": self._alim_status,
|
||||
"is_local": self._is_local,
|
||||
"vpn_url": self._vpnurl,
|
||||
"local_url": self._localurl,
|
||||
}
|
||||
|
||||
@property
|
||||
def available(self):
|
||||
"""Return True if entity is available."""
|
||||
return bool(self._alim_status == "on")
|
||||
return bool(self._alim_status == "on" or self._status == "disconnected")
|
||||
|
||||
@property
|
||||
def supported_features(self):
|
||||
"""Return supported features."""
|
||||
return SUPPORT_STREAM
|
||||
|
||||
@property
|
||||
def is_recording(self):
|
||||
"""Return true if the device is recording."""
|
||||
return bool(self._status == "on")
|
||||
|
||||
@property
|
||||
def brand(self):
|
||||
"""Return the camera brand."""
|
||||
@@ -186,6 +245,16 @@ class NetatmoCamera(Camera):
|
||||
"""Return true if on."""
|
||||
return self.is_streaming
|
||||
|
||||
def turn_off(self):
|
||||
"""Turn off camera."""
|
||||
self._data.set_state(
|
||||
home_id=self._home_id, camera_id=self._id, monitoring="off"
|
||||
)
|
||||
|
||||
def turn_on(self):
|
||||
"""Turn on camera."""
|
||||
self._data.set_state(home_id=self._home_id, camera_id=self._id, monitoring="on")
|
||||
|
||||
async def stream_source(self):
|
||||
"""Return the stream source."""
|
||||
url = "{0}/live/files/{1}/index.m3u8"
|
||||
@@ -196,72 +265,48 @@ class NetatmoCamera(Camera):
|
||||
@property
|
||||
def model(self):
|
||||
"""Return the camera model."""
|
||||
if self._camera_type == "NOC":
|
||||
return "Presence"
|
||||
if self._camera_type == "NACamera":
|
||||
return "Welcome"
|
||||
return None
|
||||
return MODELS[self._model]
|
||||
|
||||
@property
|
||||
def unique_id(self):
|
||||
"""Return the unique ID for this sensor."""
|
||||
return self._unique_id
|
||||
|
||||
def update(self):
|
||||
"""Update entity status."""
|
||||
self._data.update()
|
||||
|
||||
camera = self._data.camera_data.get_camera(cid=self._camera_id)
|
||||
|
||||
self._vpnurl, self._localurl = self._data.camera_data.camera_urls(
|
||||
cid=self._camera_id
|
||||
)
|
||||
@callback
|
||||
def async_update_callback(self):
|
||||
"""Update the entity's state."""
|
||||
camera = self._data.get_camera(self._id)
|
||||
self._vpnurl, self._localurl = self._data.camera_urls(self._id)
|
||||
self._status = camera.get("status")
|
||||
self._sd_status = camera.get("sd_status")
|
||||
self._alim_status = camera.get("alim_status")
|
||||
self._is_local = camera.get("is_local")
|
||||
self.is_streaming = self._alim_status == "on"
|
||||
self.is_streaming = bool(self._status == "on")
|
||||
|
||||
def _service_setpersonshome(self, **kwargs):
|
||||
"""Service to change current home schedule."""
|
||||
persons = kwargs.get(ATTR_PERSONS)
|
||||
person_ids = []
|
||||
for person in persons:
|
||||
for pid, data in self._data.persons.items():
|
||||
if data.get("pseudo") == person:
|
||||
person_ids.append(pid)
|
||||
|
||||
class CameraData:
|
||||
"""Get the latest data from Netatmo."""
|
||||
self._data.set_persons_home(person_ids=person_ids, home_id=self._home_id)
|
||||
_LOGGER.info("Set %s as at home", persons)
|
||||
|
||||
def __init__(self, hass, auth):
|
||||
"""Initialize the data object."""
|
||||
self._hass = hass
|
||||
self.auth = auth
|
||||
self.camera_data = None
|
||||
def _service_setpersonaway(self, **kwargs):
|
||||
"""Service to mark a person as away or set the home as empty."""
|
||||
person = kwargs.get(ATTR_PERSON)
|
||||
person_id = None
|
||||
if person:
|
||||
for pid, data in self._data.persons.items():
|
||||
if data.get("pseudo") == person:
|
||||
person_id = pid
|
||||
|
||||
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 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
|
||||
if person_id is not None:
|
||||
self._data.set_persons_away(
|
||||
person_id=person_id, home_id=self._home_id,
|
||||
)
|
||||
_LOGGER.info("Set %s as away", person)
|
||||
|
||||
@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()
|
||||
|
||||
@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)
|
||||
else:
|
||||
self._data.set_persons_away(
|
||||
person_id=person_id, home_id=self._home_id,
|
||||
)
|
||||
_LOGGER.info("Set home as empty")
|
||||
Reference in new issue
Block a user