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"\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)
                            
                            
            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)
