pax_global_header00006660000000000000000000000064142625527110014517gustar00rootroot0000000000000052 comment=24bfb08e8ec1c86fc1f50c2ed9fc8ebc0d357da3 RyuzakiKK-pyialarm-24bfb08/000077500000000000000000000000001426255271100156305ustar00rootroot00000000000000RyuzakiKK-pyialarm-24bfb08/.gitignore000066400000000000000000000022261426255271100176220ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ # PyCharm .idea/RyuzakiKK-pyialarm-24bfb08/LICENSE000066400000000000000000000261351426255271100166440ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. RyuzakiKK-pyialarm-24bfb08/README.md000066400000000000000000000006261426255271100171130ustar00rootroot00000000000000# pyialarm Python library to interface with [iAlarm systems](https://www.antifurtocasa365.it/). It has also been confirmed to work with the alarm systems brands Meian and Emooluxr. From the version 1.0 this library switched from webscraping the local configuration webpage to using the API that Android and iOS app use. Thanks to https://github.com/wildstray/meian-client for writing down the API specs. RyuzakiKK-pyialarm-24bfb08/pyialarm/000077500000000000000000000000001426255271100174465ustar00rootroot00000000000000RyuzakiKK-pyialarm-24bfb08/pyialarm/__init__.py000066400000000000000000000000351426255271100215550ustar00rootroot00000000000000from .pyialarm import IAlarm RyuzakiKK-pyialarm-24bfb08/pyialarm/pyialarm.py000066400000000000000000000230511426255271100216370ustar00rootroot00000000000000import logging import time import re import socket from collections import OrderedDict import dicttoxml2 import xmltodict log = logging.getLogger(__name__) # dicttoxml is very verbose at INFO level logging.getLogger("dicttoxml").setLevel(logging.CRITICAL) class IAlarm(object): """ Interface the iAlarm security systems. """ ARMED_AWAY = 0 DISARMED = 1 ARMED_STAY = 2 CANCEL = 3 TRIGGERED = 4 ZONE_NOT_USED = 0 ZONE_IN_USE = (1 << 0) ZONE_ALARM = (1 << 1) ZONE_BYPASS = (1 << 2) ZONE_FAULT = (1 << 3) ZONE_LOW_BATTERY = (1 << 4) ZONE_LOSS = (1 << 5) def __init__(self, host, port=18034): """ :param host: host of the iAlarm security system (e.g. its IP address) :param port: port of the iAlarm security system (should be '18034') """ self.host = host self.port = port self.seq = 0 self.sock = None def ensure_connection_is_open(self) -> None: if self.sock is None or self.sock.fileno() == -1: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.settimeout(5) else: return self.seq = 0 try: self.sock.connect((self.host, self.port)) except (socket.timeout, OSError, ConnectionRefusedError) as err: self.sock.close() raise ConnectionError('Connection to the alarm system failed') from err def _close_connection(self) -> None: if self.sock and self.sock.fileno() != 1: self.sock.close() def _send_request_list(self, xpath, command, offset=0, partial_list=None): if offset > 0: command['Offset'] = 'S32,0,0|%d' % offset response = self._send_request_raw(xpath, command) if partial_list is None: partial_list = [] total = self._clean_response_dict(response, '%s/Total' % xpath) ln = self._clean_response_dict(response, '%s/Ln' % xpath) for i in list(range(ln)): partial_list.append( self._clean_response_dict(response, '%s/L%d' % (xpath, i))) offset += ln if total > offset: # Continue getting elements increasing the offset self._send_request_list(xpath, command, offset, partial_list) return partial_list def _send_request_raw(self, xpath, command) -> dict: root_dict = self._create_root_dict(xpath, command) try: self._send_dict(root_dict) response = self._receive() except ConnectionError as err: log.debug("Failed to send request, retrying with a new connection: %s", err) self._close_connection() # The alarm can start to drop responses if we send multiple requests back-to-back time.sleep(1) self._send_dict(root_dict) response = self._receive() return response def _send_request(self, xpath, command) -> dict: response = self._send_request_raw(xpath, command) return self._clean_response_dict(response, xpath) def get_mac(self) -> str: mac = "" command = OrderedDict() command['Mac'] = None command['Name'] = None command['Ip'] = None command['Gate'] = None command['Subnet'] = None command['Dns1'] = None command['Dns2'] = None command['Err'] = None network_info = self._send_request('/Root/Host/GetNet', command) if network_info is not None: mac = network_info.get("Mac", "") if mac: return mac else: raise ConnectionError('An error occurred trying to connect to the alarm ' 'system or received an unexpected reply') def get_status(self, include_memory_feature=False) -> int: """ :param include_memory_feature: .. deprecated:: 1.9.5 Memory feature is always enabled, this parameter has no effect :return: The current alarm status :raises ConnectionError: """ command = OrderedDict() command['DevStatus'] = None command['Err'] = None alarm_status = self._send_request('/Root/Host/GetAlarmStatus', command) if alarm_status is None: raise ConnectionError('An error occurred trying to connect to the alarm ' 'system') status = int(alarm_status.get("DevStatus", -1)) if status == -1: raise ConnectionError('Received an unexpected reply from the alarm') if status != self.ARMED_AWAY and status != self.ARMED_STAY: # If the status is not "armed", there is no point in checking for "triggered" return status # The alarm can start to drop responses if we send multiple different requests back-to-back time.sleep(1) command = OrderedDict() command['Total'] = None command['Offset'] = 'S32,0,0|0' command['Ln'] = None command['Err'] = None zone_status = self._send_request_list('/Root/Host/GetByWay', command) self._close_connection() if zone_status is None: raise ConnectionError('An error occurred trying to connect to the alarm ' 'system') for zone in zone_status: if zone & self.ZONE_ALARM: status = self.TRIGGERED return status def arm_away(self) -> None: command = OrderedDict() command['DevStatus'] = 'TYP,ARM|0' command['Err'] = None self._send_request('/Root/Host/SetAlarmStatus', command) def arm_stay(self) -> None: command = OrderedDict() command['DevStatus'] = 'TYP,STAY|2' command['Err'] = None self._send_request('/Root/Host/SetAlarmStatus', command) def disarm(self) -> None: command = OrderedDict() command['DevStatus'] = 'TYP,DISARM|1' command['Err'] = None self._send_request('/Root/Host/SetAlarmStatus', command) def cancel_alarm(self) -> None: command = OrderedDict() command['DevStatus'] = 'TYP,CLEAR|3' command['Err'] = None self._send_request('/Root/Host/SetAlarmStatus', command) def _send_dict(self, root_dict) -> None: xml = dicttoxml2.dicttoxml(root_dict, attr_type=False, root=False) self.ensure_connection_is_open() self.seq += 1 msg = b'@ieM%04d%04d0000%s%04d' % (len(xml), self.seq, self._xor(xml), self.seq) self.sock.send(msg) def _receive(self): try: data = self.sock.recv(1024) except (socket.timeout, OSError, ConnectionRefusedError) as err: self.sock.close() raise ConnectionError("Connection error") from err if not data: self.sock.close() raise ConnectionError("Connection error, received no reply") # It might happen to receive the err tag before the root, we just # remove it because it's not necessary decoded = self._xor(data[16:-4]).decode().replace("ERR|00", "") if not decoded: self.sock.close() raise ConnectionError("Connection error, received an unexpected reply") return xmltodict.parse(decoded, xml_attribs=False, dict_constructor=dict, postprocessor=self._xmlread) @staticmethod def _xmlread(_path, key, value): if value is None or not isinstance(value, str): return key, value err_re = re.compile(r'ERR\|(\d{2})') mac_re = re.compile(r'MAC,(\d+)\|(([0-9A-F]{2}[:-]){5}([0-9A-F]{2}))') s32_re = re.compile(r'S32,(\d+),(\d+)\|(\d*)') str_re = re.compile(r'STR,(\d+)\|(.*)') typ_re = re.compile(r'TYP,(\w+)\|(\d+)') if err_re.match(value): value = int(err_re.search(value).groups()[0]) elif mac_re.match(value): value = str(mac_re.search(value).groups()[1]) elif s32_re.match(value): value = int(s32_re.search(value).groups()[2]) elif str_re.match(value): value = str(str_re.search(value).groups()[1]) elif typ_re.match(value): value = int(typ_re.search(value).groups()[1]) # Else: we are not interested in this value, just keep it as is return key, value @staticmethod def _create_root_dict(path, my_dict=None): if my_dict is None: my_dict = {} root = {} elem = root plist = path.strip('/').split('/') k = len(plist) - 1 for i, j in enumerate(plist): elem[j] = {} if i == k: elem[j] = my_dict elem = elem.get(j) return root @staticmethod def _clean_response_dict(response, path): for i in path.strip('/').split('/'): try: i = int(i) response = response[i] except ValueError: response = response.get(i) return response @staticmethod def _xor(xml): sz = bytearray.fromhex('0c384e4e62382d620e384e4e44382d300f382b382b0c5a6234384e304e4c372b10535a0c20432d171142444e58422c421157322a204036172056446262382b5f0c384e4e62382d620e385858082e232c0f382b382b0c5a62343830304e2e362b10545a0c3e432e1711384e625824371c1157324220402c17204c444e624c2e12') buf = bytearray(xml) for i in range(len(xml)): ki = i & 0x7f buf[i] = buf[i] ^ sz[ki] return buf RyuzakiKK-pyialarm-24bfb08/setup.py000066400000000000000000000014001426255271100173350ustar00rootroot00000000000000from setuptools import setup __version__ = '2.1.5' setup( name='pyialarm', py_modules=["pyialarm"], version=__version__, description='A simple library to interface with iAlarm systems, built for use with Home-Assistant', author='Ludovico de Nittis', author_email='aasonykk+pyialarm@gmail.com', url='https://github.com/RyuzakiKK/pyialarm', download_url='https://github.com/RyuzakiKK/pyialarm', license='Apache 2.0', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Programming Language :: Python :: 3', ], keywords=['ialarm', 'antifurtocasa365', 'alarm'], packages=['pyialarm'], include_package_data=True, install_requires=['dicttoxml2', 'xmltodict'], )