# from wx.lib.pubsub import pub
from pubsub import pub
import serial
import threading
import queue
import time


class ComReaderThread(threading.Thread):
    ''' 
    Creates a thread that continously reads from the serial connection
    Puts result as a tuple (timestamp, data) in a queue
    '''

    def __init__(self, ser, error_que):
        threading.Thread.__init__(self)
        self.ser = ser
        self.error_que = error_que

        self.alive = threading.Event()
        self.alive.set()

    def run(self):
        while self.alive.isSet():
            try:
                if self.ser.in_waiting > 0:
                    timestamp = time.time()

                    data = self.ser.read(self.ser.in_waiting)

                    pub.sendMessage('serial.data', data=(timestamp, data))

            except serial.SerialException as e:
                reconnected = False
                print('Serial connection lost, trying to reconnect.')
                ts = time.time()
                self.error_que.put((ts, str(e)))
                while not reconnected and self.alive.isSet():
                    try:
                        # if ser still thinks it's open close it
                        if self.ser.is_open:
                            self.ser.close()

                        self.ser.open()

                    except Exception as e:
                        # if reconnection failed let some time pass
                        time.sleep(0.1)

                    else:
                        reconnected = True
                        print('Reconnected')

    def stop(self, timeout=0.5):
        self.alive.clear()
        threading.Thread.join(self, timeout)

[((16, 8, 16, 39), 'threading.Thread.__init__', 'threading.Thread.__init__', ({(16, 34, 16, 38): 'self'}, {}), '(self)', False, 'import threading\n'), ((20, 21, 20, 38), 'threading.Event', 'threading.Event', ({}, {}), '()', False, 'import threading\n'), ((56, 8, 56, 44), 'threading.Thread.join', 'threading.Thread.join', ({(56, 30, 56, 34): 'self', (56, 36, 56, 43): 'timeout'}, {}), '(self, timeout)', False, 'import threading\n'), ((27, 32, 27, 43), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((31, 20, 31, 74), 'pubsub.pub.sendMessage', 'pub.sendMessage', (), '', False, 'from pubsub import pub\n'), ((36, 21, 36, 32), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n'), ((48, 24, 48, 39), 'time.sleep', 'time.sleep', ({(48, 35, 48, 38): '(0.1)'}, {}), '(0.1)', False, 'import time\n')]