From edfb60773e41fe4679902929445bf2bcab9598b9 Mon Sep 17 00:00:00 2001 From: Christian Mayer Date: Wed, 6 Jan 2021 14:01:53 +0100 Subject: [PATCH] HA API support SSL --- README.md | 6 ++++++ core/connectors/homeassistant.py | 14 +++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fa9169f..45d2ab5 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,12 @@ python3 -m pip install Twisted python3 -m pip install autobahn[twisted] ``` +### Install optional dependencies +For connecting via SSL +``` +python3 -m pip install pyOpenSSL +``` + ### Configure Kivy Edit file `/home/pi/.kivy/config.ini` diff --git a/core/connectors/homeassistant.py b/core/connectors/homeassistant.py index 8537fb1..1522833 100644 --- a/core/connectors/homeassistant.py +++ b/core/connectors/homeassistant.py @@ -1,10 +1,12 @@ # -*- coding: utf-8 -*- import json +import time from kivy.support import install_twisted_reactor install_twisted_reactor() from autobahn.twisted.websocket import WebSocketClientProtocol, \ - WebSocketClientFactory + WebSocketClientFactory, \ + connectWS from twisted.internet import reactor @@ -43,7 +45,8 @@ class HAClientFactory(WebSocketClientFactory): protocol = HAClientProtocol def __init__(self, config, handler): - url = 'ws://' + config['host'] + ':' + str(config['port']) + '/api/websocket' + use_ssl = config.get('use_ssl', False) + url = ('wss://' if use_ssl else 'ws://') + config['host'] + ':' + str(config['port']) + '/api/websocket' WebSocketClientFactory.__init__(self, url) self.handler = handler @@ -61,7 +64,12 @@ def __init__(self, app, config): def connect_to_server(self): self._factory = HAClientFactory(self.config, self) - reactor.connectTCP(self.config['host'], self.config['port'], self._factory) + ctxFactory = None + if self._factory.isSecure: + from twisted.internet import ssl + ctxFactory = ssl.ClientContextFactory() + + connectWS(self._factory, ctxFactory) def send_message(self, msg): proto = self._factory._proto