# -*- coding: utf-8 -*-
#
# Form implementation generated from reading ui file 'resource/terminal.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5.QtCore import (Qt, QDate, QTime, QDateTime, QThread, pyqtSignal)
import serial



class WorkThread(QThread):
    # Singleton pattern
    '''
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(WorkThread, cls).__new__(cls)    

        return cls.__instance
    '''

    threadSignal = pyqtSignal(str)
    # 0 - stoped
    # 1 - working
    th_state = 0;
    count_msg = 0
    close = 0
    baudrate = 115200
    port = "COM5"   

    def __init__(self):
        super().__init__()
    
    def close_thread(self):
        self.close = 1

    def get_count_msg(self):
        return self.count_msg
    
    def get_port(self):
        return self.port

    def set_port(self, port):
        self.port = port

    def get_baudrate(self):
        return self.baudrate

    def set_baudrate(self, baudrate):
        self.baudrate = baudrate 

    def set_state(self, th_state):
        self.th_state = th_state

    def get_state(self):
        return self.th_state

    def run(self):
        #    if(serialPort.in_waiting > 0):
        #        serialString = serialPort.readline()
        #        self.richEdit.appendPlainText(serialString.decode('Ascii'));
        try:
            
            self.serialPort = serial.Serial(port = self.get_port(), baudrate = self.get_baudrate(), bytesize = 8, timeout = 2, stopbits = serial.STOPBITS_ONE)
            self.set_state(1)
            print("start thread")
        except Exception:
            print('Error: dont create serial module')
            return
        serialString = ""

        self.count_msg = 0
        self.close = 0
        #print(f'ports: {self.serial_ports}')
        while(1):
            '''
            while self.serialPort.canReadLine():
                text = self.serialPort.readLine().data().decode()
                text = text.rstrip('\r\n')
                print(text)
            '''
            if self.close == 1:
                self.serialPort.close();
                self.set_state(0)
                print("end thread")
                break
            if(self.serialPort.in_waiting > 0):
                # выводит по символьно
                #serialString = serialPort.read()
                serialString = self.serialPort.readline()
                date = QDate.currentDate()
                time = QTime.currentTime()
                text = f'N:{self.get_count_msg()} ({date.toString(Qt.ISODate)} : {time.toString(Qt.DefaultLocaleLongDate)}) >  {serialString.decode("Ascii")}, {serialString}'
                self.count_msg += 1
                self.threadSignal.emit(text)
                print(text)
                #self.msleep(2000)
            

    def serial_ports(self):
        ports = ['COM%s' % (i + 1) for i in range(256)]

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        return result