seopardy/buttonreader.py

80 lines
2.2 KiB
Python
Raw Normal View History

2013-11-06 20:42:00 +01:00
# write a thread that reads buttoninput from fifo or pyserial or something
# https://gist.github.com/elshaka/2999082
# and make this configureable
from __future__ import print_function
2013-12-07 20:42:08 +01:00
import os
import serial
2013-11-06 20:42:00 +01:00
from PySide import QtCore
2013-12-07 20:42:08 +01:00
from player import ButtonEvent
_inputs = {}
def _add_input(inputType, inputClass):
global _inputs
_inputs[inputType] = inputClass
def get_input(inputType, args, app):
global _inputs
if inputType not in _inputs:
raise ValueError("'%s' is an unknown input type" % inputType)
return _inputs[inputType](app, *args)
class BaseInput(QtCore.QThread):
def __init__(self, app, parent=None):
super(BaseInput, self).__init__(parent)
self._app = app
def _sendButtonEvent(self, btn):
if self._app.activeWindow():
QtCore.QCoreApplication.postEvent(self._app.activeWindow(), ButtonEvent(int(btn)))
2013-11-06 20:42:00 +01:00
class SerialThread(QtCore.QThread):
dataReady = QtCore.Signal(str)
2013-12-07 20:42:08 +01:00
class SerialInput(BaseInput):
def __init__(self, app, device, baudrate=9600, bytesize=8, parity='N', stopbits=1):
super(SerialInput, self).__init__(app)
try:
self._serial = serial.Serial(device, baudrate, bytesize, parity, stopbits)
except serial.SerialException as e:
raise InputException("Error: %s" % e)
print(" >> serial %s initialized with rate %s %s%s%s" % (device, baudrate, bytesize, parity, stopbits))
def run(self):
while True:
c = self._serial.read(1)
if len(c) == 1 and ord(c) > ord('0') and ord(c) <= ord('9'):
self._sendButtonEvent(c)
_add_input("Serial", SerialInput)
class FifoInput(BaseInput):
def __init__(self, app, fifoPath, debug=False):
super(FifoInput, self).__init__(app)
self._path = fifoPath
self._debug = debug
if not os.path.exists(self._path):
try:
os.mkfifo(self._path)
except OSError as e:
raise InputException("Could not create fifo '%s': %s" % (self._path, e))
if os.path.isfile(self._path) or os.path.isdir(self._path):
raise InputException("Fifo '%s' is not a fifo" % self._path)
print(" >> Fifo initialized, using '%s'" % self._path)
def run(self):
fifo = open(self._path)
while True:
c = fifo.read(1)
if len(c) == 1 and ord(c) > ord('0') and ord(c) <= ord('9'):
self._sendButtonEvent(c)
_add_input("Fifo", FifoInput)
class InputException(Exception):
pass