import serial
from serial import SerialException
import logging
import time
import binascii

SerialPort = "COM1"
BaudRate = 19200
PackageByTime = 0.1
PackageByLenght = 256
BufferMax = 2000
LogFileName = "megasport_new_4.log"

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename=LogFileName,
                    filemode="w")

ser = serial.Serial()
ser.port = SerialPort
ser.baudrate = BaudRate
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.timeout = PackageByTime
ser.xonxoff = False
ser.rtscts = False
ser.dsrdtr = False
ser.write_timeout = 2

start = b"\xe0\xe0\xe8\xe8\xe4\xe4\xf8"
finish = b"\r"
while True:
    try:
        print("Initializing")
        ser.close()
        ser.open()
        if ser.is_open:
            try:
                RequestCount = 0
                print("Port Opening")
                RetryCount = 0
                remainder_hex = b""
                while True:
                    response = ser.read(PackageByLenght)
                    print(response)
                        
                    logging.debug(response)
                    if len(response) > 0:
                        
                        StarterTime = time.time() * 1000
                        response_hex = response.replace(b" ", b"")
                        try:
                            int(response_hex,16)
                        except ValueError:
                            response_hex = binascii.hexlify(response)
                            response_hex = response_hex.upper()
                        
                        response_hex = remainder_hex + response_hex
                        print(response_hex)
                            
            except Exception as e1:
                logging.error("error communicating...: " + str(e1))
        else:
            print("Port Opening Failed... trying again in 5 seconds")
            time.sleep(5)
            ser.close()
    except SerialException:
        print("No port connected... trying again in 5 seconds")
        time.sleep(5)
