Skip to content

Instantly share code, notes, and snippets.

@karasu
Created December 14, 2018 19:08
Show Gist options
  • Save karasu/242ecf5a830783ff3a633551eeb6969f to your computer and use it in GitHub Desktop.
Save karasu/242ecf5a830783ff3a633551eeb6969f to your computer and use it in GitHub Desktop.
alexa firetv basic homeassistant
import json
import urllib3
import requests
def lambda_handler(event, context):
""" lambda handler function """
session = event['session']
request = event['request']
my_app_id = 'amzn1.ask.skill.dbd1327c-f056-465c-af2f-2581a1a05d92'
app_id = session['application']['applicationId']
print("event.session.application.applicationId=" + app_id)
if app_id != my_app_id:
raise ValueError("Invalid Application ID")
if session['new']:
on_session_started({'requestId': request['requestId']}, session)
if request['type'] == "LaunchRequest":
return on_launch(request, session)
elif request['type'] == "IntentRequest":
return on_intent(request, session)
elif request['type'] == "SessionEndedRequest":
return on_session_ended(request, session)
def on_session_started(request, session):
""" Called when the session starts """
print("on_session_started requestId=" + request['requestId'] + ", sessionId=" + session['sessionId'])
def on_launch(request, session):
""" Called when the user launches the skill
without specifying what they want """
print("on_launch requestId=" + request['requestId'] + ", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response()
def on_intent(request, session):
""" Called when the user specifies an intent for this skill """
intent = request['intent']
intent_name = request['intent']['name']
print("on_intent requestId=" + request['requestId'] +
", sessionId=" + session['sessionId'], ", intent_name=" + intent_name)
# Dispatch to your skill's intent handlers
if intent_name == "openIntent":
return set_app_in_session(intent, session)
elif intent_name == "playIntent":
raise ValueError("Not implemented")
elif intent_name == "AMAZON.FallbackIntent":
raise ValueError("Not implemented")
elif intent_name == "AMAZON.CancelIntent":
raise ValueError("Not implemented")
elif intent_name == "AMAZON.HelpIntent":
return get_welcome_response()
elif intent_name == "AMAZON.StopIntent":
raise ValueError("Not implemented")
elif intent_name == "AMAZON.NavigateHomeIntent":
raise ValueError("Not implemented")
else:
raise ValueError("Invalid intent")
def on_session_ended(request, session):
""" Called when the user ends the session.
Is not called when the skill returns should_end_session=true
"""
print("on_session_ended requestId=" + request['requestId'] + ", sessionId=" + session['sessionId'])
# add cleanup logic here
# --------------- Functions that control the skill's behavior ------------------
def get_welcome_response():
""" If we wanted to initialize the session to have some attributes we could
add those here """
session_attributes = {}
card_title = "Welcome"
speech_output = "Please tell me the application you want to open by saying, " \
"open application"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "Please tell me to open the application netflix by saying, " \
"open netflix in fire t.v."
speechlet = build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session=False)
return build_response(session_attributes, speechlet)
def set_app_in_session(intent, session):
""" Sets the application in the session and prepares the speech to reply to the user. """
card_title = intent['name']
session_attributes = {}
if 'app' in intent['slots']:
app = intent['slots']['app']['value']
session_attributes = create_app_attributes(app)
speech_output = "Opening " + app + " in fire t.v. basic"
reprompt_text = ""
should_end_session = True
run_homeassistant_script(app)
else:
speech_output = "I'm not sure what application do you want to open." \
"Please try again."
reprompt_text = "I'm not sure what application do you want to open." \
"You can tell me what application do you want to open by saying, " \
"open netflix in fire t.v."
should_end_session = False
speechlet = build_speechlet_response(
card_title, speech_output, reprompt_text, should_end_session)
return build_response(session_attributes, speechlet)
def create_app_attributes(app):
return {"app": app}
def run_homeassistant_script(app):
""" Comunicates with homeassistant """
app = app.lower()
# Already checked before (against slots)
known_apps = [
"netflix", "amazon prime", "prime", "prime video", "amazon prime video", "movistar"]
if app in known_apps:
response = None
url = 'https://myhost.duckdns.org:8123/api/services/script/{}'.format(app)
headers = {
'Authorization': 'Bearer HOMEASSISTANT_SECRET_TOKEN_HERE',
'content-type': 'application/json'
}
data = {
'application': app
}
try:
response = requests.post(
url,
headers=headers,
data=json.dumps(data),
timeout=(None, 0.01))
response.raise_for_status()
except requests.exceptions.ReadTimeout:
# Allow response timeouts after request was sent
print('request for {} sent without waiting for response'.format(url))
return response
else:
raise ValueError("Unknown application name {}".format(app))
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'type': 'Simple',
'title': 'SessionSpeechlet - ' + title,
'content': 'SessionSpeechlet - ' + output
},
'reprompt': {
'outputSpeech': {
'type': 'PlainText',
'text': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
#!/usr/bin/python
import subprocess
from flask import Flask
app = Flask(__name__)
def awake_me():
cmd = ['adb', 'shell', 'input', 'keyevent']
# KEYCODE_WAKEUP
subprocess.call(cmd + ['224'])
# UNLOCK SCREEN
subprocess.call(cmd + ['82'])
@app.route('/<application>')
def run_app(application):
""" Run app in firetv basic stick using android debugger """
apps = {
'netflix': 'com.netflix.ninja/.MainActivity'
}
connect_cmd = ['adb', 'connect', '192.168.1.X']
base_cmd = ['/usr/bin/adb', 'shell', 'am', 'start', '-n']
myapp = apps.get(application, None)
if myapp:
awake_me()
subprocess.call(connect_cmd)
subprocess.call(base_cmd + [myapp])
return "{} opened".format(application)
else:
return "Unknown application"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment