Skip to content

Instantly share code, notes, and snippets.

@unaiur
Last active May 13, 2020 13:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save unaiur/b354f986f874a8ca7ad80153d7b37440 to your computer and use it in GitHub Desktop.
Save unaiur/b354f986f874a8ca7ad80153d7b37440 to your computer and use it in GitHub Desktop.
Simpler and faster version of Haaska AWS Lambda in https://github.com/mike-grant/haaska
#!/usr/bin/env python3.7
# coding: utf-8
# Copyright (c) 2019 Unai Uribarri <unaiur@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import json
import logging
import ssl
from http.client import HTTPSConnection, RemoteDisconnected
HOST = os.environ['HOST']
PORT = int(os.environ.get('PORT', default='443'))
BEARER_TOKEN = os.environ['BEARER_TOKEN']
AWS_REGION = os.environ.get("AWS_DEFAULT_REGION")
LOGGER = logging.getLogger()
if os.environ.get('DEBUG'):
LOGGER.setLevel(logging.DEBUG)
SSL_CONTEXT = ssl.create_default_context()
if os.environ.get('SSL_VERIFY', default = True):
SSL_CONTEXT.verify_mode = ssl.CERT_REQUIRED
SSL_CONTEXT.check_hostname = True
else:
SSL_CONTEXT.check_hostname = False
SSL_CONTEXT.verify_mode = ssl.CERT_NONE
CONNECTION = HTTPSConnection(HOST, PORT, context = SSL_CONTEXT)
HEADERS = {
'Authorization': f'Bearer {BEARER_TOKEN}',
'content-type': 'application/json',
'User-Agent': f"HAASKA-Lite in {AWS_REGION}"
}
URL = '/api/alexa/smart_home'
def handle_event(event, num_attempt = 1):
try:
LOGGER.debug(f'Received event: {event}')
CONNECTION.request('POST', URL,
body = json.dumps(event).encode('utf8'),
headers = HEADERS)
response = CONNECTION.getresponse()
if response.status != 200:
LOGGER.error(f'HomeAssistant error {response.status} {response.reason}')
return None
return json.loads(response.read())
except RemoteDisconnected:
LOGGER.info("HomeAssistant closed the connection.")
CONNECTION.close()
if num_attempt >= 3:
return None
LOGGER.debug(f"Attemp {num_attempt} failed. Retrying...")
return handle_event(event, num_attempt + 1)
def event_handler(event, context):
try:
return handle_event(event)
except Exception:
# Allow response timeouts after request was sent
LOGGER.exception('Internal error calling HomeAssistant')
CONNECTION.close()
return None
@mammuth
Copy link

mammuth commented Nov 1, 2019

Works great, thanks for sharing! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment