Skip to content

Commit

Permalink
changes to use pysecuritas api
Browse files Browse the repository at this point in the history
  • Loading branch information
nragon committed Dec 6, 2020
1 parent 83be2cf commit 312ec25
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 319 deletions.
57 changes: 32 additions & 25 deletions custom_components/securitas_direct/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Support for Securitas Direct alarms."""
import logging
import threading
from datetime import timedelta

import voluptuous as vol
Expand All @@ -15,15 +14,17 @@
from homeassistant.helpers import discovery
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv


from . import securitas
from pysecuritas.core.session import Session
from pysecuritas.api.installation import Installation
from pysecuritas.api.alarm import Alarm

_LOGGER = logging.getLogger(__name__)

CONF_ALARM = "alarm"
CONF_CODE_DIGITS = "code_digits"
CONF_COUNTRY = "country"
CONF_LANG = "lang"
CONF_INSTALLATION = "installation"

DOMAIN = "securitas_direct"

Expand All @@ -38,7 +39,9 @@
{
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Optional(CONF_COUNTRY,default="ES"): cv.string,
vol.Required(CONF_INSTALLATION): cv.positive_int,
vol.Optional(CONF_COUNTRY, default="ES"): cv.string,
vol.Optional(CONF_LANG, default="es"): cv.string,
vol.Optional(CONF_ALARM, default=True): cv.boolean,
vol.Optional(CONF_CODE_DIGITS, default=4): cv.positive_int,
vol.Optional(CONF_CODE, default=""): cv.string,
Expand All @@ -51,6 +54,7 @@
extra=vol.ALLOW_EXTRA,
)


def setup(hass, config):
"""Set up the Securitas component."""
global HUB
Expand All @@ -76,33 +80,36 @@ def __init__(self, domain_config):
"""Initialize the Securitas hub."""
self.overview = {}
self.config = domain_config
self._lock = threading.Lock()
country = domain_config[CONF_COUNTRY].upper()
lang = country.lower() if country != 'UK' else 'en'
self.session = securitas.SecuritasAPIClient(
domain_config[CONF_USERNAME],
domain_config[CONF_PASSWORD],
country=country, lang=lang
)
self.session = Session(domain_config[CONF_USERNAME], domain_config[CONF_PASSWORD],
domain_config[CONF_INSTALLATION],
domain_config[CONF_COUNTRY].upper(), domain_config[CONF_LANG].lower())
self.installation = Installation(self.session)
self.alarm = Alarm(self.session)

def login(self):
"""Login to Securitas."""
ret = self.session.login()
_LOGGER.debug("Log in Securitas: %s", ret)
if not ret:
_LOGGER.error("Could not log in to Securitas: %s", ret)
return False
ret = self.session.get_ins()
return True
self.session.connect()

return self.session.is_connected()

def logout(self):
"""Logout from Securitas."""
ret = self.session.logout()
if not ret:
_LOGGER.error("Could not log out from Securitas: %s", ret)
return False
self.session.close()

return True

def update_overview(self):
"""Update the overview."""
self.overview = self.session.last_state()

filter = ('1', '2', '31', '32', '46', '202', '311', '13', '24')
res = self.installation.get_activity_log()
_LOGGER.debug(res)
try:
regs = res['LIST']['REG']
for reg in regs:
if filter is None or reg['@type'] in filter:
self.overview = reg

return
except (KeyError, TypeError):
pass
78 changes: 24 additions & 54 deletions custom_components/securitas_direct/alarm_control_panel.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
"""Support for Securitas Direct (AKA Verisure EU) alarm control panels."""

import logging, datetime
from time import sleep
import datetime
import logging

import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
SUPPORT_ALARM_ARM_NIGHT,
)
from homeassistant.const import (
CONF_CODE,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_DISARMED,
STATE_ALARM_ARMED_NIGHT,
STATE_ALARM_ARMED_CUSTOM_BYPASS,
STATE_ALARM_PENDING,
STATE_ALARM_TRIGGERED,
STATE_ALARM_ARMING,
STATE_ALARM_DISARMING,
# STATE_UNAVAILABLE,
# STATE_UNKNOWN,
# STATE_UNAVAILABLE,
# STATE_UNKNOWN,
STATE_ALARM_PENDING,
)

from homeassistant.components.alarm_control_panel.const import (
SUPPORT_ALARM_ARM_AWAY,
SUPPORT_ALARM_ARM_HOME,
SUPPORT_ALARM_ARM_NIGHT,
)
from . import CONF_ALARM, CONF_CODE_DIGITS, HUB as hub

from . import CONF_ALARM, CONF_CODE_DIGITS, CONF_COUNTRY, HUB as hub
# from securitas import SecuritasAPIClient

_LOGGER = logging.getLogger(__name__)

Expand All @@ -51,14 +49,6 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
add_entities(alarms)


def set_arm_state(state, code=None):
"""Send set arm state command."""
# hub.session.api_call(state)
_LOGGER.error("Securitas: esternal set arm state %s", state)
# sleep(2)
# hub.update_overview(no_throttle=True)


class SecuritasAlarm(alarm.AlarmControlPanelEntity):
"""Representation of a Securitas alarm status."""

Expand All @@ -75,35 +65,11 @@ def __force_state(self, state):
self._state = state
self.hass.states.set(self.entity_id, state)

def __arm_state(self, state):
res = hub.session.api_call(state)
_LOGGER.debug("Securitas: setting arm state: %s\nres=%s", state, res)
return res

def get_arm_state(self):
res = self.__arm_state('EST')
if hub.session._is_ok(res):
for k, v in SECURITAS_STATUS.items():
if res['PET']['STATUS'] in v[0]:
return k

def set_arm_state(self, state, attempts=3):
"""Send set arm state command."""
for i in range(attempts):
res = self.__arm_state(state)
if hub.session._is_ok(res):
break
else:
_LOGGER.warning("Securitas: disarming (res=%s)", res)
self.__arm_state('DARM')
sleep(i*2+1)
sleep(2)
hub.update_overview(no_throttle=True)

@property
def name(self):
"""Return the name of the device."""
return "securitas_{}".format(hub.session._params['numinst'])
res = hub.alarm.get_status()
for k, v in SECURITAS_STATUS.items():
if res["STATUS"] in v[0]:
return k

@property
def state(self):
Expand Down Expand Up @@ -154,35 +120,39 @@ def device_state_attributes(self):
return {'device': self._device,
'time': self._time,
'message': self._message,
'alias': hub.session.alias
}

def alarm_disarm(self, code=None):
"""Send disarm command."""
if (hub.config.get(CONF_CODE, "") == "" or
hub.config.get(CONF_CODE, "") == code):
self.__force_state(STATE_ALARM_DISARMING)
self.set_arm_state("DARM")
hub.alarm.disconnect()
hub.update_overview(no_throttle=True)

def alarm_arm_home(self, code=None):
"""Send arm home command."""
self.__force_state(STATE_ALARM_ARMING)
self.set_arm_state("ARMDAY")
hub.alarm.activate_day_mode()
hub.update_overview(no_throttle=True)

def alarm_arm_away(self, code=None):
"""Send arm away command."""
self.__force_state(STATE_ALARM_ARMING)
self.set_arm_state("ARM")
hub.alarm.activate_total_mode()
hub.update_overview(no_throttle=True)

def alarm_arm_night(self, code=None):
"""Send arm home command."""
self.__force_state(STATE_ALARM_ARMING)
self.set_arm_state("ARMNIGHT")
hub.alarm.activate_night_mode()
hub.update_overview(no_throttle=True)

def alarm_arm_custom_bypass(self, code=None):
"""Send arm perimeter command."""
self.__force_state(STATE_ALARM_ARMING)
self.set_arm_state("PERI")
hub.alarm.activate_perimeter_mode()
hub.update_overview(no_throttle=True)

@property
def supported_features(self) -> int:
Expand Down
4 changes: 3 additions & 1 deletion custom_components/securitas_direct/example_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
securitas_direct:
username: your_securitas_username
password: your_securitas_password
installation: your_securitas_installation
code: 1234
country: ES

lang: es

# remove '#' to enable debug for this component (to see logs: 'tail -f homeassistant.log')
#logger:
# logs:
Expand Down
6 changes: 2 additions & 4 deletions custom_components/securitas_direct/manifest.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
{
"domain": "securitas_direct",
"name": "Securitas Direct",
"documentation": "https://github.com/segalion/securitasdirect",
"issue_tracker": "https://github.com/segalion/securitasdirect/issues",
"documentation": "https://www.home-assistant.io/integrations/securitas_direct",
"requirements": [
"xml2dict"
"pysecuritas==0.1.3"
],
"dependencies": [],
"codeowners": [
"@segalion",
"@Cebeerre"
Expand Down
Loading

0 comments on commit 312ec25

Please sign in to comment.