├── .Dockerfile ├── .env.default ├── .gitignore ├── AVAILABLE_ENV.md ├── LICENSE ├── README.md ├── dev.Dockerfile ├── scripts ├── build.sh ├── dev.sh └── run.sh └── sources ├── main.py └── requirements.txt /.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:alpine 2 | 3 | COPY sources/requirements.txt /opt/app/ 4 | WORKDIR /opt/app 5 | 6 | RUN adduser -D worker && pip install -r requirements.txt 7 | USER worker 8 | 9 | COPY sources/ /opt/app/ 10 | 11 | CMD ["python", "main.py"] 12 | -------------------------------------------------------------------------------- /.env.default: -------------------------------------------------------------------------------- 1 | TYDOM_MAC_ADDRESS=xxxxxxxxxx 2 | TYDOM_PASSWORD=xxxxxxxxxxx 3 | MQTT_HOST=localhost 4 | MQTT_SSL=0 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Local dir 2 | .local/ 3 | 4 | # Local Docker files 5 | .env 6 | 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | *.egg-info/ 30 | .installed.cfg 31 | *.egg 32 | MANIFEST 33 | 34 | # PyInstaller 35 | # Usually these files are written by a python script from a template 36 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 37 | *.manifest 38 | *.spec 39 | 40 | # Installer logs 41 | pip-log.txt 42 | pip-delete-this-directory.txt 43 | 44 | # Unit test / coverage reports 45 | htmlcov/ 46 | .tox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | .hypothesis/ 54 | .pytest_cache/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # pyenv 82 | .python-version 83 | 84 | # celery beat schedule file 85 | celerybeat-schedule 86 | 87 | # SageMath parsed files 88 | *.sage.py 89 | 90 | # Environments 91 | .env 92 | .venv 93 | env/ 94 | venv/ 95 | ENV/ 96 | env.bak/ 97 | venv.bak/ 98 | 99 | # Spyder project settings 100 | .spyderproject 101 | .spyproject 102 | 103 | # Rope project settings 104 | .ropeproject 105 | 106 | # mkdocs documentation 107 | /site 108 | 109 | # mypy 110 | .mypy_cache/ -------------------------------------------------------------------------------- /AVAILABLE_ENV.md: -------------------------------------------------------------------------------- 1 | LOGFILE 2 | REMOTE_HTTP_TYDOM 3 | TYDOM_MAC_ADDRESS 4 | TYDOM_IP 5 | TYDOM_USERNAME 6 | TYDOM_PASSWORD 7 | MQTT_HOST 8 | MQTT_PORT 9 | MQTT_USER 10 | MQTT_PASSWORD 11 | MQTT_SSL -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tydom_python 2 | 3 | Example of Python Code (Python >= 3.5) to manage Tydom (Delta Dore) devices 4 | Need Tydom Gateway (I've used a Tydom 1.0) 5 | Code Reversed Engineered with help of Eli (creator of JeeDore plugin for Jeedom) 6 | 7 | *Modules required :* 8 | 9 | pip install websockets requests 10 | 11 | ## Run with Docker: 12 | Configure env: 13 | ``` 14 | cp .env.default .env 15 | ``` 16 | 17 | Build docker image: 18 | ``` 19 | ./scripts/build.sh 20 | ``` 21 | 22 | Run: 23 | ``` 24 | ./scripts/run.sh 25 | ``` 26 | 27 | ## Run without Docker: 28 | Configure env: 29 | ``` 30 | cp .env.default .env 31 | ``` 32 | 33 | Run: 34 | ``` 35 | pip install -r requirements.txt 36 | python sources/main.py 37 | ``` 38 | 39 | Following commands are implemented : 40 | 41 | **get_info** 42 | Get some information on tydom (version ...) 43 | **get_ping** 44 | Just Send a ping message to the Tydom. Not useful 45 | **get_devices_meta** 46 | Get some metadata on the devices 47 | **get_devices_data** 48 | Get the data on the devices 49 | **get_configs_file** 50 | This one get the list of device declared on your tydom 51 | **put_devices_data** 52 | Give order to Tydom endpoint 53 | 54 | ## Sources: 55 | - https://github.com/cth35/tydom_python 56 | - https://github.com/WiwiWillou/tydom_python 57 | - https://github.com/largotef/tydom_python 58 | - https://github.com/mgcrea/node-tydom-client 59 | - https://community.home-assistant.io/t/tydom2mqtt-make-delta-dore-devices-home-assistant-compatible/154439 60 | 61 | -------------------------------------------------------------------------------- /dev.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:alpine 2 | 3 | COPY sources/requirements.txt /opt/app/ 4 | WORKDIR /opt/app 5 | 6 | RUN adduser -D worker && pip install -r requirements.txt 7 | 8 | CMD ["sh"] 9 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Make docker image 4 | docker build --tag=tydom2mqtt --file=.Dockerfile . 5 | -------------------------------------------------------------------------------- /scripts/dev.sh: -------------------------------------------------------------------------------- 1 | 2 | #!/bin/sh 3 | 4 | # We could see the env-file syntax [here](https://docs.docker.com/compose/env-file) 5 | 6 | # Execute docker with .env file 7 | docker build --tag=tydom2mqtt/dev --file=dev.Dockerfile . 8 | docker run --rm -it --network="host" --env-file=.env -v $(pwd):/opt/app/ tydom2mqtt/dev 9 | -------------------------------------------------------------------------------- /scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # We could see the env-file syntax [here](https://docs.docker.com/compose/env-file) 4 | 5 | # Execute docker with .env file 6 | docker run --rm -it -u 0 --network="host" --env-file=.env tydom2mqtt python main.py "$@" 7 | 8 | -------------------------------------------------------------------------------- /sources/main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import asyncio 3 | from datetime import datetime 4 | import websockets 5 | import sys 6 | import logging 7 | import urllib3 8 | import json 9 | import os 10 | import base64 11 | import time 12 | import ssl 13 | import socket 14 | import subprocess, platform 15 | 16 | from requests.auth import HTTPDigestAuth 17 | import http.client 18 | from http.client import HTTPResponse 19 | from http.server import BaseHTTPRequestHandler 20 | from io import BytesIO 21 | 22 | from gmqtt.mqtt.constants import MQTTv311 23 | from gmqtt import Client as MQTTClient 24 | 25 | from tendo import singleton 26 | 27 | enable_MQTT = True #Disable MQTT if you want 28 | hassio = None 29 | tydom = None 30 | me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running 31 | 32 | def pingOk(sHost): 33 | try: 34 | output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True) 35 | except Exception as e: 36 | return False 37 | return True 38 | 39 | ####### SETTINGS 40 | logfile = os.environ.get('LOGFILE', "tydom2mqtt.log") 41 | remote_adress = os.environ.get('REMOTE_HTTP_TYDOM', "mediation.tydom.com") 42 | ####### TYDOM CREDENTIALS 43 | mac = os.environ.get('TYDOM_MAC_ADDRESS', "xxxxxxxxx") #MAC Address of Tydom Box 44 | tydom_ip = os.environ.get('TYDOM_IP', remote_adress) # Local ip address or mediation.tydom.com for remote connexion 45 | login = os.environ.get('TYDOM_USERNAME', mac) 46 | password = os.environ.get('TYDOM_PASSWORD', "") #Tydom password 47 | ####### MQTT CREDENTIALS 48 | mqtt_client_id = "client-id" 49 | mqtt_host = os.environ.get('MQTT_HOST', "xxxxxxxxx") 50 | mqtt_port = os.environ.get('MQTT_PORT', 1883) 51 | mqtt_user = os.environ.get('MQTT_USER') 52 | mqtt_pass = os.environ.get('MQTT_PASSWORD') 53 | mqtt_ssl = os.environ.get('MQTT_SSL', 1) == 1 54 | 55 | # Local use ? 56 | local = tydom_ip != remote_adress 57 | host = tydom_ip 58 | 59 | if (local): 60 | print('Local Execution Detected') 61 | else: 62 | print('Remote Execution Detected') 63 | 64 | ####### TEST IF REMOTE IP CAN WORK 65 | if pingOk(tydom_ip): 66 | print(f"'{tydom_ip}' is reachable.") 67 | else: 68 | print(f"'{tydom_ip}' is unreachable.") 69 | exit(1) 70 | 71 | # Set Host, ssl context and prefix for remote or local connection 72 | if local == False: 73 | ssl_context = None 74 | cmd_prefix = "\x02" 75 | else: 76 | ssl_context = ssl._create_unverified_context() 77 | cmd_prefix = "" 78 | 79 | deviceAlarmKeywords = ['alarmMode','alarmState','alarmSOS','zone1State','zone2State','zone3State','zone4State','zone5State','zone6State','zone7State','zone8State','gsmLevel','inactiveProduct','zone1State','liveCheckRunning','networkDefect','unitAutoProtect','unitBatteryDefect','unackedEvent','alarmTechnical','systAutoProtect','sysBatteryDefect','zsystSupervisionDefect','systOpenIssue','systTechnicalDefect','videoLinkDefect'] 80 | # Device dict for parsing 81 | device_dict = dict() 82 | 83 | # Globals 84 | ####################################### MQTT 85 | qos_pub=1 86 | 87 | tydom_topic = "homeassistant/+/tydom/#" 88 | 89 | cover_config_topic = "homeassistant/cover/tydom/{id}/config" 90 | cover_config = "homeassistant/cover/tydom/{id}/config" 91 | cover_position_topic = "homeassistant/cover/tydom/{id}/current_position" 92 | cover_set_postion_topic = "homeassistant/cover/tydom/{id}/set_position" 93 | cover_attributes_topic = "homeassistant/cover/tydom/{id}/attributes" 94 | 95 | 96 | alarm_topic = "homeassistant/alarm_control_panel/tydom/#" 97 | alarm_config = "homeassistant/alarm_control_panel/tydom/{id}/config" 98 | alarm_state_topic = "homeassistant/alarm_control_panel/tydom/{id}/state" 99 | alarm_command_topic = "homeassistant/alarm_control_panel/tydom/{id}/set" 100 | alarm_sos_topic = "homeassistant/binary_sensor/tydom/{id}/sos" 101 | alarm_attributes_topic = "homeassistant/alarm_control_panel/tydom/{id}/attributes" 102 | 103 | refresh_topic = "homeassistant/requests/tydom/refresh" 104 | 105 | #MQTT 106 | STOP = asyncio.Event() 107 | 108 | def on_error(client, err): 109 | print('Error', err) 110 | 111 | def on_connect(client, flags, rc, properties): 112 | print("##################################") 113 | try: 114 | print("Subscribing to : ", tydom_topic) 115 | # client.subscribe('homeassistant/#', qos=qos_pub) 116 | client.subscribe(tydom_topic, qos=qos_pub) 117 | except Exception as e: 118 | print("Error : ", e) 119 | 120 | async def on_message(client, topic, payload, qos, properties): 121 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 122 | # print('MQTT incoming : ', topic, payload) 123 | if tydom: 124 | if (topic == "homeassistant/requests/tydom/update"): 125 | print('Incoming MQTT update request : ', topic, payload) 126 | await get_data(tydom) 127 | if (topic == "homeassistant/requests/tydom/refresh"): 128 | print('Incoming MQTT refresh request : ', topic, payload) 129 | await post_refresh(tydom) 130 | if (topic == "homeassistant/requests/tydom/scenarii"): 131 | print('Incoming MQTT scenarii request : ', topic, payload) 132 | await get_scenarii(tydom) 133 | if ('set_scenario' in str(topic)): 134 | print('Incoming MQTT set_scenario request : ', topic, payload) 135 | get_id = (topic.split("/"))[3] #extract id from mqtt 136 | # print(tydom, str(get_id), 'position', json.loads(payload)) 137 | await put_devices_data(tydom, str(get_id), 'position', str(json.loads(payload))) 138 | 139 | if ('set_position' in str(topic)): 140 | print('Incoming MQTT set_position request : ', topic, payload) 141 | get_id = (topic.split("/"))[3] #extract id from mqtt 142 | # print(tydom, str(get_id), 'position', json.loads(payload)) 143 | await put_devices_data(tydom, str(get_id), 'position', str(json.loads(payload))) 144 | 145 | else: 146 | return 0 147 | else: 148 | print("No websocket connection yet !") 149 | 150 | async def on_disconnect(client, packet, exc=None): 151 | print('MQTT Disconnected') 152 | print("##################################") 153 | await mqttconnection(mqtt_host, mqtt_user, mqtt_pass) 154 | 155 | def on_subscribe(client, mid, qos): 156 | print("MQTT is connected and suscribed ! =)", client) 157 | pyld = 'Started !',str(datetime.fromtimestamp(time.time())) 158 | hassio.publish('homeassistant/sensor/tydom/last_clean_startup', pyld, qos=1, retain=True) 159 | 160 | def ask_exit(*args): 161 | STOP.set() 162 | 163 | async def mqttconnection(mqtt_client_id, broker_host, user, password): 164 | try: 165 | global hassio 166 | if (hassio == None): 167 | print('Attempting MQTT connection...') 168 | client = MQTTClient(mqtt_client_id) 169 | 170 | client.on_connect = on_connect 171 | client.on_disconnect = on_disconnect 172 | client.on_subscribe = on_subscribe 173 | client.on_message = on_message 174 | 175 | if user is not None and password is not None: 176 | client.set_auth_credentials(user, password) 177 | 178 | await client.connect(broker_host, port=mqtt_port, ssl=mqtt_ssl) 179 | hassio = client 180 | 181 | except Exception as err: 182 | print(f"Error : {err}") 183 | print('MQTT error, restarting in 8s...') 184 | await asyncio.sleep(8) 185 | await mqttconnection(mqtt_client_id, mqtt_host, mqtt_user, mqtt_pass) 186 | 187 | # client.publish('TEST/TIME', str(time.time()), qos=1) 188 | 189 | # await STOP.wait() 190 | # await client.disconnect() 191 | 192 | 193 | #######" END MQTT" 194 | 195 | 196 | class Cover: 197 | def __init__(self, id, name, current_position=None, set_position=None, attributes=None): 198 | 199 | self.id = id 200 | self.name = name 201 | self.current_position = current_position 202 | self.set_position = set_position 203 | self.attributes = attributes 204 | 205 | def id(self): 206 | return self.id 207 | 208 | def name(self): 209 | return self.name 210 | 211 | def current_position(self): 212 | return self.current_position 213 | 214 | def set_position(self): 215 | return self.set_position 216 | 217 | def attributes(self): 218 | return self.attributes 219 | 220 | # cover_config_topic = "homeassistant/cover/tydom/{id}/config" 221 | # cover_position_topic = "homeassistant/cover/tydom/{id}/current_position" 222 | # cover_set_postion_topic = "homeassistant/cover/tydom/{id}/set_position" 223 | # cover_attributes_topic = "homeassistant/cover/tydom/{id}/attributes" 224 | 225 | def setup(self): 226 | self.device = {} 227 | self.device['manufacturer'] = 'Delta Dore' 228 | self.device['model'] = 'Volet' 229 | self.device['name'] = self.name 230 | self.device['identifiers'] = id=self.id 231 | self.config_topic = cover_config_topic.format(id=self.id) 232 | self.config = {} 233 | self.config['name'] = self.name 234 | self.config['unique_id'] = self.id 235 | # self.config['attributes'] = self.attributes 236 | self.config['command_topic'] = cover_set_postion_topic.format(id=self.id) 237 | self.config['set_position_topic'] = cover_set_postion_topic.format(id=self.id) 238 | self.config['position_topic'] = cover_position_topic.format(id=self.id) 239 | self.config['payload_open'] = 100 240 | self.config['payload_close'] = 0 241 | self.config['retain'] = 'false' 242 | self.config['device'] = self.device 243 | 244 | # print(self.config) 245 | hassio.publish(self.config_topic, json.dumps(self.config), qos=qos_pub) 246 | 247 | def update(self): 248 | self.setup() 249 | self.position_topic = cover_position_topic.format(id=self.id, current_position=self.current_position) 250 | hassio.publish(self.position_topic, self.current_position, qos=qos_pub, retain=True) 251 | 252 | # self.attributes_topic = cover_attributes_topic.format(id=self.id, attributes=self.attributes) 253 | # hassio.publish(self.attributes_topic, self.attributes, qos=qos_pub) 254 | 255 | class Alarm: 256 | def __init__(self, id, name, current_state=None, attributes=None): 257 | self.id = id 258 | self.name = name 259 | self.current_state = current_state 260 | self.attributes = attributes 261 | 262 | # def id(self): 263 | # return id 264 | 265 | # def name(self): 266 | # return name 267 | 268 | # def current_state(self): 269 | # return current_state 270 | 271 | # def attributes(self): 272 | # return attributes 273 | 274 | def setup(self): 275 | self.device = {} 276 | self.device['manufacturer'] = 'Delta Dore' 277 | self.device['model'] = 'Tyxal' 278 | self.device['name'] = self.name 279 | self.device['identifiers'] = id=self.id 280 | self.config_alarm = alarm_config.format(id=self.id) 281 | self.config = {} 282 | self.config['name'] = self.name 283 | self.config['unique_id'] = self.id 284 | self.config['device'] = self.device 285 | # self.config['attributes'] = self.attributes 286 | self.config['command_topic'] = alarm_command_topic.format(id=self.id) 287 | self.config['state_topic'] = alarm_state_topic.format(id=self.id) 288 | 289 | 290 | # print(self.config) 291 | hassio.publish(self.config_alarm, json.dumps(self.config), qos=qos_pub) 292 | 293 | def update(self): 294 | self.setup() 295 | self.state_topic = alarm_state_topic.format(id=self.id, state=self.current_state) 296 | hassio.publish(self.state_topic, self.current_state, qos=qos_pub, retain=True) 297 | 298 | # self.attributes_topic = alarm_attributes_topic.format(id=self.id, attributes=self.attributes) 299 | # hassio.publish(self.attributes_topic, self.attributes, qos=qos_pub) 300 | 301 | class BytesIOSocket: 302 | def __init__(self, content): 303 | self.handle = BytesIO(content) 304 | 305 | def makefile(self, mode): 306 | return self.handle 307 | 308 | class HTTPRequest(BaseHTTPRequestHandler): 309 | def __init__(self, request_text): 310 | #self.rfile = StringIO(request_text) 311 | self.raw_requestline = request_text 312 | self.error_code = self.error_message = None 313 | self.parse_request() 314 | 315 | def send_error(self, code, message): 316 | self.error_code = code 317 | self.error_message = message 318 | 319 | def response_from_bytes(data): 320 | sock = BytesIOSocket(data) 321 | response = HTTPResponse(sock) 322 | response.begin() 323 | return urllib3.HTTPResponse.from_httplib(response) 324 | 325 | def put_response_from_bytes(data): 326 | request = HTTPRequest(data) 327 | return request 328 | 329 | # Get pretty name for a device id 330 | def get_name_from_id(id): 331 | name = "" 332 | if len(device_dict) != 0: 333 | name = device_dict[id] 334 | return(name) 335 | 336 | # Generate 16 bytes random key for Sec-WebSocket-Keyand convert it to base64 337 | def generate_random_key(): 338 | return base64.b64encode(os.urandom(16)) 339 | 340 | # Build the headers of Digest Authentication 341 | def build_digest_headers(nonce): 342 | digestAuth = HTTPDigestAuth(login, password) 343 | chal = dict() 344 | chal["nonce"] = nonce[2].split('=', 1)[1].split('"')[1] 345 | chal["realm"] = "ServiceMedia" if local is False else "protected area" 346 | chal["qop"] = "auth" 347 | digestAuth._thread_local.chal = chal 348 | digestAuth._thread_local.last_nonce = nonce 349 | digestAuth._thread_local.nonce_count = 1 350 | return digestAuth.build_digest_header('GET', "https://{}:443/mediation/client?mac={}&appli=1".format(host, mac)) 351 | 352 | # Send Generic GET message 353 | async def send_message(websocket, msg): 354 | str = cmd_prefix + "GET " + msg +" HTTP/1.1\r\nContent-Length: 0\r\nContent-Type: application/json; charset=UTF-8\r\nTransac-Id: 0\r\n\r\n" 355 | a_bytes = bytes(str, "ascii") 356 | await websocket.send(a_bytes) 357 | return 0 358 | # return await websocket.recv() #disable if handler 359 | 360 | # Send Generic POST message 361 | async def send_post_message(websocket, msg): 362 | str = cmd_prefix + "POST " + msg +" HTTP/1.1\r\nContent-Length: 0\r\nContent-Type: application/json; charset=UTF-8\r\nTransac-Id: 0\r\n\r\n" 363 | a_bytes = bytes(str, "ascii") 364 | await websocket.send(a_bytes) 365 | return 0 366 | # return await websocket.recv() 367 | 368 | 369 | ############################################################### 370 | # Commands # 371 | ############################################################### 372 | 373 | # Get some information on Tydom 374 | async def get_info(websocket): 375 | msg_type = '/info' 376 | await send_message(websocket, msg_type) 377 | 378 | # Refresh (all) 379 | async def post_refresh(websocket): 380 | if (websocket == None): 381 | print('Websocket not opened, reconnect...') 382 | await websocket_connection() 383 | else: 384 | print("Refresh....") 385 | msg_type = '/refresh/all' 386 | await send_post_message(websocket, msg_type) 387 | 388 | # Get the moments (programs) 389 | async def get_moments(websocket): 390 | msg_type = '/moments/file' 391 | await send_message(websocket, msg_type) 392 | 393 | # Get the scenarios 394 | async def get_scenarii(websocket): 395 | msg_type = '/scenarios/file' 396 | await send_message(websocket, msg_type) 397 | 398 | # Get a ping (pong should be returned) 399 | async def get_ping(websocket): 400 | msg_type = 'ping' 401 | await send_message(websocket, msg_type) 402 | 403 | # Get all devices metadata 404 | async def get_devices_meta(websocket): 405 | msg_type = '/devices/meta' 406 | await send_message(websocket, msg_type) 407 | 408 | # Get all devices data 409 | async def get_devices_data(websocket): 410 | msg_type = '/devices/data' 411 | await send_message(websocket, msg_type) 412 | 413 | # List the device to get the endpoint id 414 | async def get_configs_file(websocket): 415 | msg_type = '/configs/file' 416 | await send_message(websocket, msg_type) 417 | 418 | 419 | async def get_data(websocket): 420 | if (websocket_connection == None): 421 | print('Websocket not opened, reconnect...') 422 | await websocket_connection() 423 | 424 | else: 425 | await get_configs_file(websocket) 426 | await asyncio.sleep(2) 427 | await get_devices_data(websocket) 428 | 429 | # Give order (name + value) to endpoint 430 | async def put_devices_data(websocket, endpoint_id, name, value): 431 | if (websocket_connection == None): 432 | print('Websocket not opened, reconnect...') 433 | await websocket_connection() 434 | 435 | else: 436 | # For shutter, value is the percentage of closing 437 | body="[{\"name\":\"" + name + "\",\"value\":\""+ value + "\"}]" 438 | # endpoint_id is the endpoint = the device (shutter in this case) to open. 439 | str_request = cmd_prefix + "PUT /devices/{}/endpoints/{}/data HTTP/1.1\r\nContent-Length: ".format(str(endpoint_id),str(endpoint_id))+str(len(body))+"\r\nContent-Type: application/json; charset=UTF-8\r\nTransac-Id: 0\r\n\r\n"+body+"\r\n\r\n" 440 | a_bytes = bytes(str_request, "ascii") 441 | await websocket.send(a_bytes) 442 | 443 | # Run scenario 444 | async def put_scenarios(websocket, scenario_id): 445 | body="" 446 | # scenario_id is the id of scenario got from the get_scenarios command 447 | str_request = cmd_prefix + "PUT /scenarios/{} HTTP/1.1\r\nContent-Length: ".format(str(scenario_id))+str(len(body))+"\r\nContent-Type: application/json; charset=UTF-8\r\nTransac-Id: 0\r\n\r\n"+body+"\r\n\r\n" 448 | a_bytes = bytes(str_request, "ascii") 449 | await websocket.send(a_bytes) 450 | # name = await websocket.recv() 451 | # parse_response(name) 452 | 453 | # Give order to endpoint 454 | async def get_device_data(websocket, id): 455 | # 10 here is the endpoint = the device (shutter in this case) to open. 456 | str_request = cmd_prefix + "GET /devices/{}/endpoints/{}/data HTTP/1.1\r\nContent-Length: 0\r\nContent-Type: application/json; charset=UTF-8\r\nTransac-Id: 0\r\n\r\n".format(str(id),str(id)) 457 | a_bytes = bytes(str_request, "ascii") 458 | await websocket.send(a_bytes) 459 | # name = await websocket.recv() 460 | # parse_response(name) 461 | 462 | 463 | 464 | # Basic response parsing. Typically GET responses 465 | async def parse_response(incoming): 466 | data = incoming 467 | msg_type = None 468 | first = str(data[:20]) 469 | 470 | # Detect type of incoming data 471 | if (data != ''): 472 | if ("id" in first): 473 | print('Incoming message type : data detected') 474 | msg_type = 'msg_data' 475 | elif ("date" in first): 476 | print('Incoming message type : config detected') 477 | msg_type = 'msg_config' 478 | elif ("doctype" in first): 479 | print('Incoming message type : html detected (probable 404)') 480 | msg_type = 'msg_html' 481 | print(data) 482 | elif ("productName" in first): 483 | print('Incoming message type : Info detected') 484 | msg_type = 'msg_info' 485 | print(data) 486 | else: 487 | print('Incoming message type : no type detected') 488 | print(first) 489 | 490 | if not (msg_type == None): 491 | try: 492 | parsed = json.loads(data) 493 | # print(parsed) 494 | if (msg_type == 'msg_config'): 495 | for i in parsed["endpoints"]: 496 | # Get list of shutter 497 | if i["last_usage"] == 'shutter': 498 | # print('{} {}'.format(i["id_endpoint"],i["name"])) 499 | device_dict[i["id_endpoint"]] = i["name"] 500 | 501 | # TODO get other device type 502 | if i["last_usage"] == 'alarm': 503 | # print('{} {}'.format(i["id_endpoint"], i["name"])) 504 | device_dict[i["id_endpoint"]] = "Tyxal Alarm" 505 | print('Configuration updated') 506 | elif (msg_type == 'msg_data'): 507 | for i in parsed: 508 | attr = {} 509 | if i["endpoints"][0]["error"] == 0: 510 | for elem in i["endpoints"][0]["data"]: 511 | # Get full name of this id 512 | endpoint_id = i["endpoints"][0]["id"] 513 | # Element name 514 | elementName = elem["name"] 515 | # Element value 516 | elementValue = elem["value"] 517 | 518 | # Get last known position (for shutter) 519 | if elementName == 'position': 520 | name_of_id = get_name_from_id(endpoint_id) 521 | if len(name_of_id) != 0: 522 | print_id = name_of_id 523 | else: 524 | print_id = endpoint_id 525 | # print('{} : {}'.format(print_id, elementValue)) 526 | new_cover = "cover_tydom_"+str(endpoint_id) 527 | print("Cover created / updated : "+new_cover) 528 | new_cover = Cover(id=endpoint_id,name=print_id, current_position=elementValue, attributes=i) 529 | new_cover.update() 530 | 531 | # Get last known position (for alarm) 532 | if elementName in deviceAlarmKeywords: 533 | alarm_data = '{} : {}'.format(elementName, elementValue) 534 | # print(alarm_data) 535 | # alarmMode : ON or ZONE or OFF 536 | # alarmState : ON = Triggered 537 | # alarmSOS : true = SOS triggered 538 | state = None 539 | sos = False 540 | 541 | if alarm_data == "alarmMode : ON": 542 | state = "armed_away" 543 | elif alarm_data == "alarmMode : ZONE": 544 | state = "armed_home" 545 | elif alarm_data == "alarmMode : OFF": 546 | state = "disarmed" 547 | elif alarm_data == "alarmState : ON": 548 | state = "triggered" 549 | elif alarm_data == "alarmSOS : true": 550 | sos = True 551 | else: 552 | attr[elementName] = [elementValue] 553 | # attr[alarm_data] 554 | # print(attr) 555 | #device_dict[i["id_endpoint"]] = i["name"] 556 | if (sos == True): 557 | print("SOS !") 558 | if not (state == None): 559 | # print(state) 560 | alarm = "alarm_tydom_"+str(endpoint_id) 561 | print("Alarm created / updated : "+alarm) 562 | alarm = Alarm(id=endpoint_id,name="Tyxal Alarm", current_state=state, attributes=attr) 563 | alarm.update() 564 | elif (msg_type == 'msg_html'): 565 | print("pong") 566 | else: 567 | # Default json dump 568 | print() 569 | print(json.dumps(parsed, sort_keys=True, indent=4, separators=(',', ': '))) 570 | except Exception as e: 571 | print('Cannot parse response !') 572 | # print('Response :') 573 | # print(data) 574 | if (e != 'Expecting value: line 1 column 1 (char 0)'): 575 | print("Error : ", e) 576 | 577 | 578 | # PUT response DIRTY parsing 579 | def parse_put_response(bytes_str): 580 | # TODO : Find a cooler way to parse nicely the PUT HTTP response 581 | resp = bytes_str[len(cmd_prefix):].decode("utf-8") 582 | fields = resp.split("\r\n") 583 | fields = fields[6:] # ignore the PUT / HTTP/1.1 584 | end_parsing = False 585 | i = 0 586 | output = str() 587 | while not end_parsing: 588 | field = fields[i] 589 | if len(field) == 0 or field == '0': 590 | end_parsing = True 591 | else: 592 | output += field 593 | i = i + 2 594 | parsed = json.loads(output) 595 | return json.dumps(parsed) 596 | # print(json.dumps(parsed, sort_keys=True, indent=4, separators=(',', ': '))) 597 | 598 | ######## Messages Logic 599 | async def consumer_handler(websocket): 600 | while True : 601 | try: 602 | await consumer(websocket) 603 | except Exception as e: 604 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 605 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 606 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 607 | print('Consumer handler task has crashed !') 608 | print("Error : ", e) 609 | error = "Webconnection consumer_handler error ! {}".format(e) 610 | if (hassio != None): 611 | hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 612 | print('Webconnection consumer_handler error, retrying in 8 seconds...') 613 | tydom = None 614 | await asyncio.sleep(8) 615 | await websocket_connection() 616 | 617 | async def consumer(websocket): 618 | # Receiver 619 | # while True: 620 | bytes_str = await websocket.recv() 621 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 622 | # print(bytes_str) 623 | first = str(bytes_str[:40]) # Scanning 1st characters 624 | try: 625 | if ("refresh" in first): 626 | print('OK refresh message detected !') 627 | try: 628 | hassio.publish('homeassistant/sensor/tydom/last_update', str(datetime.fromtimestamp(time.time())), qos=1, retain=True) 629 | except: 630 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 631 | print('RAW INCOMING :') 632 | print(bytes_str) 633 | print('END RAW') 634 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 635 | if ("PUT /devices/data" in first): 636 | print('PUT /devices/data message detected !') 637 | try: 638 | incoming = parse_put_response(bytes_str) 639 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 640 | await parse_response(incoming) 641 | print('PUT message processed !') 642 | print("##################################") 643 | hassio.publish('homeassistant/sensor/tydom/last_update', str(datetime.fromtimestamp(time.time())), qos=1, retain=True) 644 | except: 645 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 646 | print('RAW INCOMING :') 647 | print(bytes_str) 648 | print('END RAW') 649 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 650 | elif ("scn" in first): 651 | try: 652 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 653 | incoming = get(bytes_str) 654 | await parse_response(incoming) 655 | print('Scenarii message processed !') 656 | print("##################################") 657 | except: 658 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 659 | print('RAW INCOMING :') 660 | print(bytes_str) 661 | print('END RAW') 662 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 663 | elif ("POST" in first): 664 | try: 665 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 666 | incoming = parse_put_response(bytes_str) 667 | await parse_response(incoming) 668 | print('POST message processed !') 669 | print("##################################") 670 | except: 671 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 672 | print('RAW INCOMING :') 673 | print(bytes_str) 674 | print('END RAW') 675 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 676 | elif ("HTTP/1.1" in first): #(bytes_str != 0) and 677 | response = response_from_bytes(bytes_str[len(cmd_prefix):]) 678 | incoming = response.data.decode("utf-8") 679 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 680 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 681 | # print(incoming) 682 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 683 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 684 | try: 685 | # print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 686 | await parse_response(incoming) 687 | print('Common / GET response message processed !') 688 | print("##################################") 689 | hassio.publish('homeassistant/sensor/tydom/last_update', str(datetime.fromtimestamp(time.time())), qos=1, retain=True) 690 | except: 691 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 692 | print('RAW INCOMING :') 693 | print(bytes_str) 694 | print('END RAW') 695 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 696 | # await parse_put_response(incoming) 697 | else: 698 | print("Didn't detect incoming type, here it is :") 699 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 700 | print('RAW INCOMING :') 701 | print(bytes_str) 702 | print('END RAW') 703 | print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") 704 | except Exception as e: 705 | print('Consumer task has crashed !') 706 | print("Error : ", e) 707 | error = "Consumer crashed ! {}".format(e) 708 | if (hassio != None): 709 | hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 710 | print('Webconnection consumer error, retrying in 8 seconds...') 711 | tydom = None 712 | await asyncio.sleep(8) 713 | await websocket_connection() 714 | 715 | 716 | 717 | async def producer_handler(websocket): 718 | while True : 719 | await producer(websocket) 720 | 721 | async def producer(websocket): 722 | if (tydom != None): 723 | await asyncio.sleep(48) 724 | try: 725 | 726 | # await get_ping(websocket) 727 | await post_refresh(tydom) 728 | # await get_data(tydom) 729 | print("Websocket refreshed at ", str(datetime.fromtimestamp(time.time()))) 730 | except Exception as e: 731 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 732 | error = "Producer error ! {}".format(e) 733 | print(error) 734 | # if (hassio != None): 735 | # hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 736 | print('Producer error, retrying in 8 seconds...') 737 | else: pass 738 | ######## HANDLER 739 | async def handler(websocket): 740 | try: 741 | # print("Starting handlers...") 742 | consumer_task = asyncio.ensure_future( 743 | consumer_handler(websocket)) 744 | producer_task = asyncio.ensure_future( 745 | producer_handler(websocket)) 746 | # mqtt_task = asyncio.ensure_future( 747 | # mqttconnection(mqtt_host, mqtt_user, mqtt_pass)) 748 | done, pending = await asyncio.wait( 749 | [consumer_task, producer_task], 750 | return_when=asyncio.FIRST_COMPLETED, 751 | ) 752 | for task in pending: 753 | task.cancel() 754 | 755 | except Exception as e: 756 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 757 | error = "Webconnection handler error ! {}".format(e) 758 | print(error) 759 | if (hassio != None): 760 | hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 761 | print('Webconnection handler error, retrying in 8 seconds...') 762 | tydom = None 763 | await asyncio.sleep(8) 764 | await main_task() 765 | 766 | 767 | 768 | async def websocket_connection(): 769 | global tydom 770 | httpHeaders = {"Connection": "Upgrade", 771 | "Upgrade": "websocket", 772 | "Host": host + ":443", 773 | "Accept": "*/*", 774 | "Sec-WebSocket-Key": generate_random_key(), 775 | "Sec-WebSocket-Version": "13" 776 | } 777 | 778 | conn = http.client.HTTPSConnection(host, 443, context=ssl_context) 779 | # Get first handshake 780 | conn.request("GET", "/mediation/client?mac={}&appli=1".format(mac), None, httpHeaders) 781 | res = conn.getresponse() 782 | # Get authentication 783 | nonce = res.headers["WWW-Authenticate"].split(',', 3) 784 | # read response 785 | res.read() 786 | # Close HTTPS Connection 787 | conn.close() 788 | # Build websocket headers 789 | websocketHeaders = {'Authorization': build_digest_headers(nonce)} 790 | if ssl_context is not None: 791 | websocket_ssl_context = ssl_context 792 | else: 793 | websocket_ssl_context = True # Verify certificate 794 | try: 795 | print('"Attempting websocket connection..."') 796 | ########## CONNECTION 797 | websocket = await websockets.client.connect('wss://{}:443/mediation/client?mac={}&appli=1'.format(host, mac), 798 | extra_headers=websocketHeaders, ssl=websocket_ssl_context) 799 | 800 | # async with websockets.client.connect('wss://{}:443/mediation/client?mac={}&appli=1'.format(host, mac), 801 | # extra_headers=websocketHeaders, ssl=websocket_ssl_context) as websocket: 802 | 803 | 804 | tydom = websocket 805 | print("Tydom Websocket is Connected !", tydom) 806 | print("##################################") 807 | await get_info(tydom) 808 | print('Requesting 1st data...') 809 | await post_refresh(tydom) 810 | await get_data(tydom) 811 | 812 | while True: 813 | # await consumer(tydom) # Only receiving from socket in real time 814 | await handler(tydom) # If you want to send periodically something, disable await consumer(tydom) 815 | 816 | except Exception as e: 817 | print('Webconnection main error, retrying in 8 seconds...') 818 | 819 | error = "Websocket main connexion error ! {}".format(e) 820 | print(error) 821 | if (hassio != None): 822 | hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 823 | await asyncio.sleep(8) 824 | await websocket_connection() 825 | 826 | # Main async task 827 | async def main_task(): 828 | print(str(datetime.fromtimestamp(time.time()))) 829 | try: 830 | if (tydom == None) or not tydom.open or (hassio == None): 831 | print("##################################") 832 | start = time.time() 833 | if (enable_MQTT == True): 834 | print('MQTT is enabled') 835 | await mqttconnection(mqtt_client_id, mqtt_host, mqtt_user, mqtt_pass) 836 | hassio.publish('homeassistant/sensor/tydom/last_crash', '', qos=1, retain=True) 837 | 838 | else: 839 | print('MQTT is disabled') 840 | await websocket_connection() 841 | print('Connection total time :') 842 | end = time.time() 843 | print(end - start) 844 | 845 | else: 846 | print('Websocket is still opened ! requesting data...') 847 | await post_refresh(tydom) 848 | except Exception as e: 849 | 850 | print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") 851 | print('Connection total time :') 852 | end = time.time() 853 | print(end - start) 854 | print(str(datetime.fromtimestamp(time.time()))) 855 | error = "Main task crashed ! {}".format(e) 856 | print(error) 857 | if (hassio != None): 858 | 859 | hassio.publish('homeassistant/sensor/tydom/last_crash', str(error), qos=1, retain=True) 860 | print('Main task crashed !, reconnecting in 8 s...') 861 | await asyncio.sleep(8) 862 | await main_task() 863 | 864 | def start_loop(): 865 | loop = asyncio.get_event_loop() 866 | loop.run_until_complete(main_task()) 867 | loop.run_forever() 868 | 869 | if __name__ == '__main__': 870 | while True: 871 | try: 872 | start_loop() 873 | except Exception as e: 874 | print('FATAL ERROR !') 875 | 876 | error = "FATAL ERROR ! {}".format(e) 877 | print(error) 878 | try: 879 | error = "FATAL ERROR ! {}".format(e) 880 | hassio.publish('homeassistant/sensor/tydom/last_crash', error, qos=1, retain=True) 881 | except: 882 | print("Error : ", e) 883 | os.excel("tydom2mqtt_restarter.sh","") 884 | sys.exit(-1) -------------------------------------------------------------------------------- /sources/requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2019.11.28 2 | chardet==3.0.4 3 | gmqtt==0.5.3 4 | idna==2.8 5 | pbr==5.4.4 6 | requests==2.22.0 7 | six==1.13.0 8 | tendo==0.2.15 9 | urllib3==1.25.7 10 | websockets==8.1 --------------------------------------------------------------------------------