Skip to content
This repository has been archived by the owner on Dec 20, 2023. It is now read-only.

Commit

Permalink
Fix build errors
Browse files Browse the repository at this point in the history
  • Loading branch information
dgonano committed Dec 9, 2016
1 parent adaa49a commit c0665d2
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 88 deletions.
177 changes: 90 additions & 87 deletions src/alexapi/device_platforms/magicmirror.py
Original file line number Diff line number Diff line change
@@ -1,130 +1,132 @@
from __future__ import print_function
import time
import os
from abc import ABCMeta

from baseplatform import BasePlatform
import alexapi.bcolors as bcolors
import BaseHTTPServer
import threading
import urllib2
import urlparse

"""
Magic Mirror platform
-----------------------------------------------------------------------------------------------------------------
This device platform is made to integrate with the Magic Mirror project: https://github.com/MichMich/MagicMirror
Specifically, this communicates with the MMM-AlexaPi module: https://github.com/dgonano/MMM-AlexaPi
The two systems communicate over GET requests which,
- Update the Magic Mirror display with AlexaPi's status (No connection, idle, listening, processing, speaking)
- Allow the Magic Mirror to trigger a 'start listening' request
"""
from baseplatform import BasePlatform

# Magic Mirror platform
# -----------------------------------------------------------------------------------------------------------------
# This device platform is made to integrate with the Magic Mirror project: https://github.com/MichMich/MagicMirror
# Specifically, this communicates with the MMM-AlexaPi module: https://github.com/dgonano/MMM-AlexaPi
# The two systems communicate over GET requests which,
# - Update the Magic Mirror display with AlexaPi's status (No connection, idle, listening, processing, speaking)
# - Allow the Magic Mirror to trigger a 'start listening' request

class MagicmirrorPlatform(BasePlatform):
__metaclass__ = ABCMeta

def __init__(self, config):
if config['debug']:
print("Initialising Magic Mirro platorm")
self.shutdown = False

super(MagicmirrorPlatform, self).__init__(config, 'magicmirror')

self.host_name = self._pconfig['hostname']
self.port_number = self._pconfig['port']
self.mm_host = self._pconfig['mm_hostname']
self.mm_port = self._pconfig['mm_port']
self.hb_timer = self._pconfig['hb_timer']

self.shutdown = False
self.req_record = False
# get config
self.HOST_NAME = self._pconfig['hostname']
self.PORT_NUMBER = self._pconfig['port']
self.MM_HOST = self._pconfig['mm_hostname']
self.MM_PORT = self._pconfig['mm_port']
self.HB_TIMER = self._pconfig['hb_timer']
self.httpd = ""
self.serverthread = ""

def setup(self):
if self._config['debug']:
print("Setting up Magic Mirror platform")
print(time.asctime(), "Magic Mirror HTTP Server - %s:%s" % (self.host_name, self.port_number))

# Setup http server
self.httpd = CallbackHTTPServer((self.HOST_NAME, self.PORT_NUMBER), MMHTTPHandler)
self.httpd.set_callback(self.HTTPcallback)
print(time.asctime(), "Magic Mirror HTTP Server - %s:%s" % (self.HOST_NAME, self.PORT_NUMBER))
self.httpd = CallbackHTTPServer((self.host_name, self.port_number), MMHTTPHandler)
self.httpd.set_callback(self.http_callback)
self.serverthread = threading.Thread(target=self.httpd.serve_forever)
self.serverthread.daemon = True

def indicate_failure(self):
if self._config['debug']:
print("Indicating Failure")

self.update_mm("failure")

def indicate_success(self):
if self._config['debug']:
print("Indicating Success")

self.update_mm("success")

def after_setup(self):
# threaded detection of button press
if self._config['debug']:
print("Starting Magic Mirror platform HTTP Server")

self.serverthread.start()
# Start HB

if self._config['debug']:
print("Starting Magic Mirror heartbeat with " + str(self.HB_TIMER) + " second interval")
print("Starting Magic Mirror heartbeat with " + str(self.hb_timer) + " second interval")

self.mm_heartbeat()

def indicate_recording(self, state=True):
if state:
if self._config['debug']:
print("Indicate Start Recording")
self.update_mm("recording")
else:
if self._config['debug']:
print("Indicate Stop Recording")
self.update_mm("idle")
if self._config['debug']:
print("Indicate Start Recording" if state else "Indicate Stop Recording")

self.update_mm("recording" if state else "idle")

def indicate_playback(self, state=True):
if state:
if self._config['debug']:
print("Indicate Start Playing")
self.update_mm("playback")
else:
if self._config['debug']:
print("Indicate Stop Playing")
self.update_mm("idle")
if self._config['debug']:
print("Indicate Start Playing" if state else "Indicate Stop Playing")

self.update_mm("playback" if state else "idle")

def indicate_processing(self, state=True):
if state:
if self._config['debug']:
print("Indicate Start Processing")
self.update_mm("processing")
else:
if self._config['debug']:
print("Indicate Stop Processing")
self.update_mm("idle")
if self._config['debug']:
print("Indicate Start Processing" if state else "Indicate Stop Processing")

self.update_mm("processing" if state else "idle")

def should_record(self):
if self.req_record:
self.req_record = False
return True
return False
record = self.req_record
self.req_record = False
return record

def update_mm(self, status):
address = ("http://" + self.MM_HOST + ":" + self.MM_PORT + "/alexapi?action=AVSSTATUS&status=" + status)
try:
if self._config['debug']:
print("Calling URL: " + address)
response = urllib2.urlopen(address).read()
if self._config['debug']:
print("Response: " + response)
except Exception, e:
print(e)
address = ("http://" + self.mm_host + ":" + self.mm_port + "/alexapi?action=AVSSTATUS&status=" + status)

if self._config['debug']:
print("Calling URL: " + address)

try:
response = urllib2.urlopen(address).read()
except urllib2.URLError, err:
print("URLError: ", err.reason)
return

if self._config['debug']:
print("Response: " + response)

def mm_heartbeat(self):
if self.shutdown: return
threading.Timer(self.HB_TIMER, self.mm_heartbeat).start()
address = ("http://" + self.MM_HOST + ":" + self.MM_PORT + "/alexapi?action=AVSHB")
# Check if stop or set next timer
if self.shutdown:
return
threading.Timer(self.hb_timer, self.mm_heartbeat).start()

address = ("http://" + self.mm_host + ":" + self.mm_port + "/alexapi?action=AVSHB")

if self._config['debug']:
print("Sending MM Heatbeat")

try:
if self._config['debug']:
print("Sending MM Heatbeat")
response = urllib2.urlopen(address).read()
except Exception, e:
print(e)
except urllib2.URLError, err:
print("URLError: ", err.reason)
return

def HTTPcallback(self, query_dict):
if self._config['debug']:
print("Response: " + response)

def http_callback(self, query_dict):
if (query_dict['action'][0] == "requestrecord"):
self.req_record = True
return True
Expand All @@ -134,6 +136,7 @@ def HTTPcallback(self, query_dict):
def cleanup(self):
if self._config['debug']:
print("Cleaning up Magic Mirror platform")

self.httpd.shutdown()
self.shutdown = True

Expand All @@ -146,25 +149,25 @@ def set_callback(self, callback):
# Subclass Request Handler to use callback
class MMHTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
@classmethod
def set_callback(s, callback):
s.callback = callback
def set_callback(cls, callback):
cls.callback = callback

def do_HEAD(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
def do_HEAD(self): # pylint: disable=invalid-name
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()

def do_GET(s):
s.send_response(200)
s.end_headers()
def do_GET(self): # pylint: disable=invalid-name
self.send_response(200)
self.end_headers()

query = urlparse.urlsplit(s.path).query
query = urlparse.urlsplit(self.path).query
query_dict = urlparse.parse_qs(query)

if 'action' in query_dict.keys():
if (s.callback(query_dict)):
s.wfile.write("{\"status\":\"success\"}")
if (self.callback(query_dict)):
self.wfile.write('{"status":"success"}')
else:
s.wfile.write("{\"status\":\"error\", \"reason\":\"unknown_action\"}")
self.wfile.write('{"status":"error", "reason":"unknown_action"}')
else:
s.wfile.write("{\"status\":\"error\", \"reason\":\"unknown_command\"}")
self.wfile.write('{"status":"error", "reason":"unknown_command"}')
2 changes: 1 addition & 1 deletion src/scripts/inc/magicmirror.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/bash

function install_device {
echo "No GPIO to install"
:
}

function install_device_config {
Expand Down

0 comments on commit c0665d2

Please sign in to comment.