Securitas Direct (Verisure EU) Custom Component [TESTERS WANTED]

It is a known issue. I asked to Securitas Direct about that. The log that our component use is based on the activity of the remote controllers when they are told to be tracked. It does not ask the alarm unit as it is very costly in terms of performance and process. The panel actions are not tracked and therefore the HA component does not know about any action it had done. It can be solved by asking Securitas Direct to change your panel configuration forcing you to confirm the action panel by passing the remote control on every action. This why when you leave you house and arm the alarm from the panel the HA component does not know it is armed. It does not happen when you enter at home as you sweep the remote in the panel.

I personally left the panel to activate the alarm without sweeping the remote. A potential improvement to the HA component could be a periodical check to the alarm unit at least once per hour. But, I understand it could cause undesirable colateral problems.

Hola

Few things hereā€¦ I was testing latest versions, and getting failures on loginā€¦ on troubleshooting it seems it was due to not supporting multiple installations per Securitas account (I have 2 alarms in different locations)

Afer some fiddling around, I wrote some changes to add multiple site supportā€¦ this is the original error, (same traceback from hassio or from CLI tool)

JACONTRE-M-54DP:securitas_direct jacontre$ python3 securitas.py 3658041 Nolose2341+
Traceback (most recent call last):
File ā€œsecuritas.pyā€, line 124, in
out = client.last_state()
File ā€œsecuritas.pyā€, line 109, in last_state
res = self._api_requests(ā€˜ACT_V2ā€™,timefilter=2,activityfilter=0)
File ā€œsecuritas.pyā€, line 55, in _api_requests
res = self.login()
File ā€œsecuritas.pyā€, line 96, in login
self._params.update({ā€˜numinstā€™:inst[ā€˜NUMINSTā€™], ā€˜panelā€™:inst[ā€˜PANELā€™]})
TypeError: list indices must be integers or slices, not str

I added:

  1. Support for installid, to select which of the sites you want to monitor in login function
  2. Changed how the CLI tool handles parameters, to add support for it (tried to keep things working the same, but needed to add some named args)
  3. Added support in the hassio side , to optionally specify the installID

I donā€™t have access to single site alarm accountā€¦ so donā€™t know if there are any side effects. Please check :slight_smile:

I got it working nowā€¦ but still testing on my side

Code changes:

diff --git a/custom_components/securitas_direct/__init__.py b/custom_components/securitas_direct/__init__.py
index bc34f85..4591df9 100644
--- a/custom_components/securitas_direct/__init__.py
+++ b/custom_components/securitas_direct/__init__.py
@@ -24,6 +24,7 @@ _LOGGER = logging.getLogger(__name__)
 CONF_ALARM = "alarm"
 CONF_CODE_DIGITS = "code_digits"
 CONF_COUNTRY = "country"
+CONF_INSTALLID = "installid"

 DOMAIN = "securitas_direct"

@@ -42,6 +43,7 @@ CONFIG_SCHEMA = vol.Schema(
                 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,
+                vol.Optional(CONF_INSTALLID, default=""): cv.string,
                 vol.Optional(CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL): (
                     vol.All(cv.time_period, vol.Clamp(min=MIN_SCAN_INTERVAL))
                 ),
@@ -79,10 +81,12 @@ class SecuritasHub:
         self._lock = threading.Lock()
         country = domain_config[CONF_COUNTRY].upper()
         lang = country.lower() if country != 'UK' else 'en'
+        installid=domain_config[CONF_INSTALLID]
         self.session = securitas.SecuritasAPIClient(
             domain_config[CONF_USERNAME],
             domain_config[CONF_PASSWORD],
-            country=country, lang=lang
+            country=country, lang=lang,
+            installid=installid
         )

     def login(self):
diff --git a/custom_components/securitas_direct/securitas.py b/custom_components/securitas_direct/securitas.py
index 78b5a85..98743c7 100644
--- a/custom_components/securitas_direct/securitas.py
+++ b/custom_components/securitas_direct/securitas.py
@@ -6,6 +6,7 @@
 # (by segalion at gmail, 20/10/2019)

 import time, datetime, requests, json, xmltodict, sys
+import argparse

 # All actions based on post:
 # https://community.home-assistant.io/t/securitas-direct-verisure-spain/70239/15
@@ -40,11 +41,12 @@ class SecuritasAPIClient():
     BASE_URL='https://mob2217.securitasdirect.es:12010/WebService/ws.do'
     requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'

-    def __init__(self, user, pwd, country="ES", lang="es" ):
+    def __init__(self, user, pwd, country="ES", lang="es", installid=0 ):
         self._params = {'Country':country, 'user':user, 'pwd':pwd, 'lang':lang
-                        ,'request':"", 'ID':""}
+                        ,'request':"", 'ID':"", 'installid':installid}
         self.alias = ""

+
     def _set_id(self):
         self._params['ID'] = ('IPH_________________________'
                 + self._params['user']
@@ -92,7 +94,15 @@ class SecuritasAPIClient():
                 self._params.update({'hash': res['PET']['HASH']})
                 res = self._api_requests('INS')
                 if self._is_ok(res):
-                    inst = res['PET']['INSTALATIONS']['INSTALATION']
+                    if len(res['PET']['INSTALATIONS']['INSTALATION'])>1:
+                        if self._params['installid'] !='':
+                            for instalation in res['PET']['INSTALATIONS']['INSTALATION']:
+                                if instalation['NUMINST']==self._params['installid']:
+                                    inst=instalation
+                        else:
+                            print("More than one installation detected, please provide installation ID")
+                    else:
+                        inst = res['PET']['INSTALATIONS']['INSTALATION']
                     self._params.update({'numinst':inst['NUMINST'], 'panel':inst['PANEL']})
                     self.alias = inst['ALIAS']
             return res
@@ -115,11 +125,27 @@ class SecuritasAPIClient():
                     return reg

 if __name__ == '__main__':
+
+    client = argparse.ArgumentParser(description="Securitas Direct CLI client")
+    client.add_argument("user")
+    client.add_argument("password")
+    client.add_argument("action", default="", nargs='?')
+
+    client.add_argument("-c", "--country",default="ES",
+                        help="Optional, country code'")
+    client.add_argument("-l", "--lang", default="es",
+                        help="Optional, language code'")
+    client.add_argument("-i", "--installid", default="",
+                        help="Optional, Install ID'")
+    '''
     args=sys.argv[1:]
     if len(args) < 2:
         sys.exit(sys.argv[0] + ' User Pass [ACTION] [Country] [Lang]')
     action = args.pop(2) if len(args)>2 else ""
-    client = SecuritasAPIClient(*args)
+    '''
+    options = client.parse_args()
+    action = options.action
+    client = SecuritasAPIClient(options.user, options.password, options.country, options.lang, options.installid)
     if action == '':
         out = client.last_state()
     elif action == 'ACT_V2':

Use the official compomponent if you are in sweden, works fine.

Thanks, I am actually using the official Verisure component for my Yale locks. This works fine with help of the free subscription that Verisure offers. However, my alarm is from Securitas Direct and not from Verisure. Think they are owned by the same company, but use completely different login pages and mobile apps. I have managed to connect my alarm with help of a python shell script and Selenium. Guess this can be put into a custom_component but I am not familiar with how that works.

Hi,

I cannot find the Securitas Direct custom component in the HACS community store


Would be great to access it from there

Regards,

M

Hi,
Iā€™m now getting this error after a reboot. Any clue what it could be?

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 174, in _async_setup_component
    component.setup, hass, processed_config  # type: ignore
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/securitas_direct/__init__.py", line 64, in setup
    HUB.update_overview()
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 240, in wrapper
    result = method(*args, **kwargs)
  File "/config/custom_components/securitas_direct/__init__.py", line 107, in update_overview
    self.overview = self.session.last_state()
  File "/config/custom_components/securitas_direct/securitas.py", line 111, in last_state
    regs= res['PET']['LIST']['REG']
KeyError: 'REG'

Pedro, how were you able to get it working again? I deleted the component and re-installed again with the latest code and just cant get it to work againā€¦ same error as youā€¦
It was working earlierā€¦

IĀ“m on HA version 0.104.3
Thanks!
R

Hi !

As thereā€™s people working in different integrations (Hass.io, HomeKit, Alexa ā€¦), Iā€™ve shared my notes on the Verisure API in GitHub so itā€™s available for everybody.

Hope that helps you guys in getting more features in your integrations:

https://github.com/Cebeerre/VerisureEUAPI

BR !

Iā€™m getting some timeouts in the last days.

During handling of the above exception, another exception occurred:



Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/requests/adapters.py", line 449, in send
    timeout=timeout
  File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 720, in urlopen
    method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "/usr/local/lib/python3.7/site-packages/urllib3/util/retry.py", line 400, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/usr/local/lib/python3.7/site-packages/urllib3/packages/six.py", line 735, in reraise
    raise value
  File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 672, in urlopen
    chunked=chunked,
  File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 423, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py", line 331, in _raise_timeout
    self, url, "Read timed out. (read timeout=%s)" % timeout_value
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='mob2217.securitasdirect.es', port=12010): Read timed out. (read timeout=5)

Also trying to disarm I get this error:

Securitas: disarming (res=OrderedDict([('PET', OrderedDict([('RES', 'ERROR'), ('ERR', '60067'), ('MSG', 'Hemos tenido problemas para identificarle, por favor, cierre la sesiĆ³n y vuelva a iniciarla.'), ('BLOQ', OrderedDict([('@remotereqactive', '1'), ('#text', 'Estamos mejorando nuestros servicios. Por favor intentelo de nuevo mas tarde. Gracias por confiar en Securitas Direct')]))]))]))

__

iPhone App is working as normal.

It seems something must have changed on the Securitasā€™ web side because right now Iā€™m getting errors at boot up from the component:

Error during setup of component securitas_direct
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 174, in _async_setup_component
    component.setup, hass, processed_config  # type: ignore
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/config/custom_components/securitas_direct/__init__.py", line 64, in setup
    HUB.update_overview()
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 240, in wrapper
    result = method(*args, **kwargs)
  File "/config/custom_components/securitas_direct/__init__.py", line 107, in update_overview
    self.overview = self.session.last_state()
  File "/config/custom_components/securitas_direct/securitas.py", line 111, in last_state
    regs= res['PET']['LIST']['REG']
KeyError: 'REG'

Got the same. No clarity why and user I use works for sure ā€¦

Iā€™m getting this error

ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 390, in _async_add_entity
    suggested_object_id or entity.name or DEVICE_DEFAULT_NAME
  File "/config/custom_components/securitas_direct/alarm_control_panel.py", line 100, in name
    return "securitas_{}".format(hub.session._params['numinst'])
KeyError: 'numinst'

I have downloaded the last cistom component from github, configured yaml, but alarm_control_panel.securitas_direct not found. Iā€™m an italian user. Configuration

securitas_direct:
  username: ++++++++
  password: ++++++++
  code: 0123
  country: IT

Thanks a lot

Solved. It was a problem with the new user created ad hoc. I needed to access the first time with the new user.

Now i have another question, is it possible toview the state of a single sensor? For example when i open port iā€™d like to trigger something.

Thank you

what is the BASE_URL for the UK?

You donā€™t need to change the BASE_URL, but in the UK, this will only work if youā€™ve the alarm kit in the left:

https://www.verisure.co.uk/alarms/customer-area.html

In the country code, you should use GB.

BR

I do have the system on the left but it does not seemed to work.

Invalid config

The following integrations and platforms could not be set up:

  • securitas_direct

Please check your config.

Control configuration.yaml.

securitas_direct:
username: [email protected]
password: xxxxxxx
code: xxx
country: GB

Hi,

In username I donā€™t think the ā€œ@ā€ character is accepted.
Also in my config file code line comes last (but that shouldnā€™t have any incidence)

Regards,

M