WIP: Verisure app api (#7394)

update to verisure app api
This commit is contained in:
Per Sandström authored and GitHub committed 2017-06-26 22:30:25 +02:00
1 parent d73b695e73
commit 80c187f8ea
8 files changed
+299 -245

No files matched your search

+53 -107
View File
@@ -6,19 +6,19 @@ https://home-assistant.io/components/verisure/
"""
import logging
import threading
import time
import os.path
from datetime import timedelta
import voluptuous as vol
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import (CONF_PASSWORD, CONF_USERNAME,
EVENT_HOMEASSISTANT_STOP)
from homeassistant.helpers import discovery
from homeassistant.util import Throttle
import homeassistant.config as conf_util
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['vsure==0.11.1']
REQUIREMENTS = ['vsure==1.3.6', 'jsonpath==0.75']
_LOGGER = logging.getLogger(__name__)
@@ -26,6 +26,7 @@ ATTR_DEVICE_SERIAL = 'device_serial'
CONF_ALARM = 'alarm'
CONF_CODE_DIGITS = 'code_digits'
CONF_DOOR_WINDOW = 'door_window'
CONF_HYDROMETERS = 'hygrometers'
CONF_LOCKS = 'locks'
CONF_MOUSE = 'mouse'
@@ -45,6 +46,7 @@ CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_ALARM, default=True): cv.boolean,
vol.Optional(CONF_CODE_DIGITS, default=4): cv.positive_int,
vol.Optional(CONF_DOOR_WINDOW, default=True): cv.boolean,
vol.Optional(CONF_HYDROMETERS, default=True): cv.boolean,
vol.Optional(CONF_LOCKS, default=True): cv.boolean,
vol.Optional(CONF_MOUSE, default=True): cv.boolean,
@@ -66,9 +68,12 @@ def setup(hass, config):
HUB = VerisureHub(config[DOMAIN], verisure)
if not HUB.login():
return False
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP,
lambda event: HUB.logout())
HUB.update_overview()
for component in ('sensor', 'switch', 'alarm_control_panel', 'lock',
'camera'):
'camera', 'binary_sensor'):
discovery.load_platform(hass, component, DOMAIN, {}, config)
descriptions = conf_util.load_yaml_config_file(
@@ -93,132 +98,73 @@ class VerisureHub(object):
def __init__(self, domain_config, verisure):
"""Initialize the Verisure hub."""
self.alarm_status = {}
self.lock_status = {}
self.climate_status = {}
self.mouse_status = {}
self.smartplug_status = {}
self.smartcam_status = {}
self.smartcam_dict = {}
self.overview = {}
self.imageseries = {}
self.config = domain_config
self._verisure = verisure
self._lock = threading.Lock()
# When MyPages is brought up from maintenance it sometimes give us a
# "wrong password" message. We will continue to retry after maintenance
# regardless of that error.
self._disable_wrong_password_error = False
self._password_retries = 1
self._reconnect_timeout = time.time()
self.my_pages = verisure.MyPages(
self.session = verisure.Session(
domain_config[CONF_USERNAME],
domain_config[CONF_PASSWORD])
import jsonpath
self.jsonpath = jsonpath.jsonpath
def login(self):
"""Login to Verisure MyPages."""
"""Login to Verisure."""
try:
self.my_pages.login()
self.session.login()
except self._verisure.Error as ex:
_LOGGER.error("Could not log in to verisure mypages, %s", ex)
_LOGGER.error('Could not log in to verisure, %s', ex)
return False
return True
@Throttle(timedelta(seconds=1))
def update_alarms(self):
"""Update the status of the alarm."""
self.update_component(
self.my_pages.alarm.get,
self.alarm_status)
@Throttle(timedelta(seconds=1))
def update_locks(self):
"""Update the status of the locks."""
self.update_component(
self.my_pages.lock.get,
self.lock_status)
def logout(self):
"""Logout from Verisure."""
try:
self.session.logout()
except self._verisure.Error as ex:
_LOGGER.error('Could not log out from verisure, %s', ex)
return False
return True
@Throttle(timedelta(seconds=60))
def update_climate(self):
"""Update the status of the climate units."""
self.update_component(
self.my_pages.climate.get,
self.climate_status)
def update_overview(self):
"""Update the overview."""
try:
self.overview = self.session.get_overview()
except self._verisure.ResponseError as ex:
_LOGGER.error('Could not read overview, %s', ex)
if ex.status_code == 503: # Service unavailable
_LOGGER.info('Trying to log in again')
self.login()
else:
raise
@Throttle(timedelta(seconds=60))
def update_mousedetection(self):
"""Update the status of the mouse detectors."""
self.update_component(
self.my_pages.mousedetection.get,
self.mouse_status)
@Throttle(timedelta(seconds=1))
def update_smartplugs(self):
"""Update the status of the smartplugs."""
self.update_component(
self.my_pages.smartplug.get,
self.smartplug_status)
@Throttle(timedelta(seconds=30))
def update_smartcam(self):
"""Update the status of the smartcam."""
self.update_component(
self.my_pages.smartcam.get,
self.smartcam_status)
@Throttle(timedelta(seconds=30))
def update_smartcam_imagelist(self):
"""Update the imagelist for the camera."""
_LOGGER.debug("Running update imagelist")
self.smartcam_dict = self.my_pages.smartcam.get_imagelist()
_LOGGER.debug("New dict: %s", self.smartcam_dict)
def update_smartcam_imageseries(self):
"""Update the image series."""
self.imageseries = self.session.get_camera_imageseries()
@Throttle(timedelta(seconds=30))
def smartcam_capture(self, device_id):
"""Capture a new image from a smartcam."""
self.my_pages.smartcam.capture(device_id)
self.session.capture_image(device_id)
@property
def available(self):
"""Return True if hub is available."""
return self._password_retries >= 0
def get(self, jpath, *args):
"""Get values from the overview that matches the jsonpath."""
res = self.jsonpath(self.overview, jpath % args)
return res if res else []
def update_component(self, get_function, status):
"""Update the status of Verisure components."""
try:
for overview in get_function():
try:
status[overview.id] = overview
except AttributeError:
status[overview.deviceLabel] = overview
except self._verisure.Error as ex:
_LOGGER.info("Caught connection error %s, tries to reconnect", ex)
self.reconnect()
def get_first(self, jpath, *args):
"""Get first value from the overview that matches the jsonpath."""
res = self.get(jpath, *args)
return res[0] if res else None
def reconnect(self):
"""Reconnect to Verisure MyPages."""
if (self._reconnect_timeout > time.time() or
not self._lock.acquire(blocking=False) or
self._password_retries < 0):
return
try:
self.my_pages.login()
self._disable_wrong_password_error = False
self._password_retries = 1
except self._verisure.LoginError as ex:
_LOGGER.error("Wrong user name or password for Verisure MyPages")
if self._disable_wrong_password_error:
self._reconnect_timeout = time.time() + 60*60
else:
self._password_retries = self._password_retries - 1
except self._verisure.MaintenanceError:
self._disable_wrong_password_error = True
self._reconnect_timeout = time.time() + 60*60
_LOGGER.error("Verisure MyPages down for maintenance")
except self._verisure.Error as ex:
_LOGGER.error("Could not login to Verisure MyPages, %s", ex)
self._reconnect_timeout = time.time() + 60
finally:
self._lock.release()
def get_image_info(self, jpath, *args):
"""Get values from the imageseries that matches the jsonpath."""
res = self.jsonpath(self.imageseries, jpath % args)
return res if res else []