diff --git a/wii-pair/daemon.py b/wii-pair/daemon.py index f538089..990e275 100755 --- a/wii-pair/daemon.py +++ b/wii-pair/daemon.py @@ -4,6 +4,7 @@ import os, math, random import time import socket import struct +import select from threading import Thread import bluetooth import wiiboard @@ -169,15 +170,23 @@ s.bind(('', 4711)) s.listen(1) try: + conns = [] while True: - conn, addr = s.accept() - - while True: - m = conn.recv(1) - - if len(m) == 0: - conn.close() - break + rlist, wlist, xlist = select.select([s]+conns, [], conns) + if s in rlist: + conn, addr = s.accept() + conns.append(conn) + rlist.remove(s) + + for sock in xlist: + conns.remove(sock) + + for sock in rlist: + try: + m = sock.recv(1) + except Exception: + conns.remove(sock) + continue r = b'' for w in wiis: @@ -192,7 +201,12 @@ try: v = int(round(w.pos_y*100)) r += struct.pack('b', v) - conn.send(r) + try: + sock.send(r) + except Exception: + conns.remove(sock) + continue + except (KeyboardInterrupt, SystemExit): t1.stop = True t2.stop = True diff --git a/wii-pair/wiiboard.py b/wii-pair/wiiboard.py index 7be6711..6e3997d 100644 --- a/wii-pair/wiiboard.py +++ b/wii-pair/wiiboard.py @@ -70,9 +70,7 @@ class Wiiboard: try: self.datasocket = bluetooth.BluetoothSocket(bluetooth.L2CAP) - self.datasocket.settimeout(2) self.controlsocket = bluetooth.BluetoothSocket(bluetooth.L2CAP) - self.controlsocket.settimeout(2) except ValueError: raise Exception("Error: Bluetooth not found") @@ -88,7 +86,9 @@ class Wiiboard: print("Non existant address") return self.datasocket.connect((address, 0x13)) + self.datasocket.settimeout(2) self.controlsocket.connect((address, 0x11)) + self.controlsocket.settimeout(2) if self.datasocket and self.controlsocket: print("Connected to Wiiboard at address " + address) self.status = "Connected" @@ -181,7 +181,7 @@ class Wiiboard: # Thread that listens for incoming data def receivethread(self): while self.status == "Connected": - if True: + try: data = self.datasocket.recv(25) intype = data[1] if intype == INPUT_STATUS: @@ -202,6 +202,9 @@ class Wiiboard: else: print("ACK to data write received") + except bluetooth.btcommon.BluetoothError: + print('Error! Disconnecting') + self.disconnect() self.status = "Disconnected" self.disconnect()