Commit 35fca230 authored by Antoine Lima's avatar Antoine Lima

[WIP] Input and threads

parent b27bc7ac
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 18 18:34:40 2018
@author: Antoine Lima, Leo Reynaert, Domitille Jehenne
"""
import logging
import autopy
import serial
from os.path import dirname, abspath, join, isfile as exists
from autopy.key import tap as PressKey, Code as KeyCode
from threading import Thread
from player import Side
class InputThread(Thread):
keyButtonBindings = [KeyCode.ESCAPE, KeyCode.UP_ARROW, KeyCode.LEFT_ARROW, KeyCode.RIGHT_ARROW, KeyCode.DOWN_ARROW, KeyCode.RETURN]
def __init__(self, dispatcher, side):
Thread.__init__(self)
self.side = side
self.dispatcher = dispatcher
self.continueRunning = True
self.path = '/dev/ttyUSB0' if self.side==Side.Left else '/dev/ttyUSB1'
if exists(self.path):
self.arduino = serial.Serial(self.path, 9600, timeout=1)
else:
raise RuntimeError('No arduino connected on the {} side'.format(self.side.name.lower()))
def run(self):
while self.arduino.isOpen():
msg = self.arduino.readline()[:-1]
if msg:
parsedMessage = self.parseMsg(msg)
if 'butn' in parsedMessage:
self.sendKeyStroke(parsedMessage)
else:
self.dispatcher.dispatchMessage(parsedMessage)
else:
logging.warn('No message read on Arduino {}'.format(self.side.name))
def stop(self):
self.continueRunning = False
self.arduino.close()
def sendKeyStroke(self, msg):
if 'butn' in msg:
button = int(msg['butn'])
print({button: ['ESCAPE', 'UP_ARROW', 'LEFT_ARROW', 'RIGHT_ARROW', 'DOWN_ARROW', 'RETURN'][button]})
key = InputThread.keyButtonBindings[button]
PressKey(key, [])
def parseMsg(self, msg):
parts = msg.split(':')
return {parts[0]: parts[1], 'source': self.side}
......@@ -8,6 +8,7 @@ Created on Wed Apr 18 18:34:40 2018
import sys
import logging
import threading
from os.path import dirname, abspath, join
from PyQt5 import QtWidgets
......@@ -16,6 +17,8 @@ from PyQt5.QtCore import QTime, Qt
from ui.main_ui import Ui_MainWindow
from modules import *
from player import Side
from com import InputThread
class MainWin(QtWidgets.QMainWindow):
def __init__(self, parent=None):
......@@ -58,6 +61,15 @@ class MainWin(QtWidgets.QMainWindow):
def displaySystemTime(self):
self.ui.lcdTime.display(QTime.currentTime().toString("hh:mm:ss"))
def findMod(self, type):
mod_idx = [i for i, x in enumerate(self.modules) if isinstance(x, type)]
return -1 if len(mod_idx)==0 else mod_idx[0]
def dispatchMessage(self, msg, toAll=False):
modulesIdx = self.modules if toAll else [self.findMod(type(self.ui.panels.currentWidget()))]
for modIdx in modulesIdx:
self.modules[modIdx].other(**msg)
@staticmethod
def getContent(path):
......@@ -73,11 +85,27 @@ class MainWin(QtWidgets.QMainWindow):
else:
self.showNormal()
QApplication.setOverrideCursor(Qt.ArrowCursor);
if __name__=='__main__':
app = QtWidgets.QApplication(sys.argv)
from settings import Settings
#logging.basicConfig(filename='babyfoot.log', level=logging.DEBUG)
logging.basicConfig(level=logging.DEBUG)
app = QtWidgets.QApplication(sys.argv)
myapp = MainWin()
if Settings['app.mode']!='dev':
threadArduinoLeft = InputThread(myapp, Side.Left)
#threadArduinoRight = InputThread(myapp, Side.Right)
threadArduinoLeft.start()
#threadArduinoRight.start()
myapp.show()
app.exec_()
if Settings['app.mode']!='dev':
threadArduinoLeft.stop()
#threadArduinoRight.stop()
threadArduinoLeft.join()
#threadArduinoRight.join()
......@@ -15,20 +15,16 @@ from PyQt5.QtWidgets import QTableWidgetItem, QComboBox, QApplication
from modules import *
class Module(QtWidgets.QWidget):
def __init__(self, parent=None, widget=None):
def __init__(self, parent, widget):
# UI Setup
QtWidgets.QWidget.__init__(self, parent)
self.mainwin = parent
self.ui = widget
self.ui.setupUi(self)
def find(self, type):
mod_idx = [i for i, x in enumerate(self.mainwin.modules) if isinstance(x, type)]
return -1 if len(mod_idx)==0 else mod_idx[0]
def switchModule(self, new_type):
curmod_idx = self.find(type(self))
newmod_idx = self.find(new_type)
curmod_idx = self.mainwin.findMod(type(self))
newmod_idx = self.mainwin.findMod(new_type)
if curmod_idx<0:
logging.error('Unknown panel {}'.format(type(self)))
......@@ -51,7 +47,7 @@ class Module(QtWidgets.QWidget):
self.mainwin.modules[newmod_idx].grabKeyboard()
def send(self, to, **kwargs):
mod_idx = self.find(to)
mod_idx = self.mainwin.findMod(to)
if mod_idx<0:
logging.error('Unknown panel {}'.format(to))
......
......@@ -7,7 +7,7 @@ Created on Wed Apr 18 18:34:40 2018
"""
import json
from main import MainWin
import main
class Setting(object):
TypeName = ''
......@@ -106,4 +106,4 @@ class SettingsHolder(object):
getattr(self, cat)[name] = setting
Settings = SettingsHolder(MainWin.getContent('settings.json'))
Settings = SettingsHolder(main.MainWin.getContent('settings.json'))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment