leinwand/leinwand.py

107 lines
3.4 KiB
Python

#!/bin/env python
import BaseHTTPServer
import SocketServer
import re
import threading
import enum
import pifaceio
PORT = 8080
BIND_ADDRESS = '127.0.0.1'
WAITING_TIME = 10
# commands
UP_COMMAND = 0b00000000
DOWN_COMMAND = 0b00000000
STOP_COMMAND = 0b00000000
class ScreenStates(enum.Enum):
stop = 'stop'
moving_up = 'moving_up'
up = 'up'
moving_down = 'moving_down'
down = 'down'
class LeinwandRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
current_state = ScreenStates.stop
stop_timer = None
pf = pifaceio.PiFace()
lock = threading.Semaphore()
def handle_screen_up(self):
print('moving up...')
LeinwandRequestHandler.pf.write(UP_COMMAND)
LeinwandRequestHandler.current_state = ScreenStates.moving_up
LeinwandRequestHandler.stop_timer = threading.Timer(WAITING_TIME, self.screen_stop)
LeinwandRequestHandler.stop_timer.start()
self.send_response(200)
print(self.current_state)
def handle_screen_down(self):
print('moving down...')
LeinwandRequestHandler.pf.write(DOWN_COMMAND)
LeinwandRequestHandler.current_state = ScreenStates.moving_down
LeinwandRequestHandler.stop_timer = threading.Timer(WAITING_TIME, self.screen_stop)
LeinwandRequestHandler.stop_timer.start()
self.send_response(200)
def return_screen_state(self):
print('state: %s' % self.current_state)
self.send_response(200)
self.send_header('content-type', 'text/plain')
self.wfile.write('\n')
self.wfile.write('{status: "' + LeinwandRequestHandler.current_state + '"}')
def screen_stop(self):
if LeinwandRequestHandler.current_state == ScreenStates.moving_down:
LeinwandRequestHandler.current_state = ScreenStates.down
elif LeinwandRequestHandler.current_state == ScreenStates.moving_up:
LeinwandRequestHandler.current_state = ScreenStates.up
print('stop')
LeinwandRequestHandler.pf.write(STOP_COMMAND)
def do_GET(self):
# output just for debugging...
print('Request from ' + self.client_address[0])
print(self.path)
path_match = re.match('^/(screen)/(up|down|state)$', self.path)
# return simple command documentation on error
if path_match == None:
self.send_response(404)
self.send_header('content-type', 'text/plain')
self.wfile.write('\n')
self.wfile.write('Unknown command. \n\nValid commands are: \n')
self.wfile.write('/screen/up \t move screen up\n')
self.wfile.write('/screen/down \t move screen down\n')
self.wfile.write('/screen/state \t get the current screen state\n')
return
if path_match.group(1) == 'screen':
if path_match.group(2) == 'up':
self.handle_screen_up()
return
elif path_match.group(2) == 'down':
self.handle_screen_down()
return
elif path_match.group(2) == 'state':
self.return_screen_state()
return
class ThreadedBaseHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
pass
if __name__ == '__main__':
handler = LeinwandRequestHandler
httpd = ThreadedBaseHTTPServer((BIND_ADDRESS, PORT), handler)
httpd.serve_forever()