import serial
from serial import SerialException
import datetime
import binascii
import logging
import time
import json

import re

# Configuration Data (later to be put in Panel2Net.conf)
# SerialPort: Name of RPi serial port receiving the panel data
# SerialPort = "COM1"
SerialPort = "COM1"
# BaudRate: Serial port speed (Baud, Default will be adjusted later)
BaudRate = 19200
# PackageByTime: Time Duration until a package is closed
# and sent off (seconds)
PackageByTime = 0.1
# PackageByLength*	Length (in bytes) of data input
# until a package is closed and sent off
PackageByLength = 128
# PackageByLength = 256    #попробовать нужно !!!!!!!!!!!!!!!!!!!!
# PackageByLength = 256

# MaxBuffer before flushing (in order to avoid buffer overflow)
BufferMax = 2000


# LogFileName: Name of LogFile
current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
LogFileName = f"timer_megasport5_{current_time}.log"
# LogFileSize Maximum Size of LogFile (in Mbytes)
LogFileSize = 10
# LogLevel	Minimum Severity Level to be logged (see severity in Logs)
LogLevel = "E"

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

def hexspace(string, length):
    return ' '.join(string[i:i+length] for i in range(0,len(string),length))

ser = serial.Serial()
ser.port = SerialPort
ser.baudrate = BaudRate
ser.bytesize = serial.EIGHTBITS # number of bits per bytes
ser.parity = serial.PARITY_NONE         #  PARITY_NONE # set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE  # number of stop bits
ser.timeout = PackageByTime # non-block read
ser.xonxoff = False     # disable software flow control
ser.rtscts = False       # disable hardware (RTS/CTS) flow control
ser.dsrdtr = False      # disable hardware (DSR/DTR) flow control
ser.writeTimeout = 0    # timeout for write

while True:
    try:
        print("Initializing")
        ser.close()
        ser.open()
        if ser.is_open:
            try:
                ser.reset_input_buffer()
                # flush input buffer, discarding all its contents
                ser.reset_output_buffer()
                # flush output buffer, aborting current output
                # and discard all that is in buffer
                RequestCount = 0
                print("Port Opening")
                # Initialise RetryCounter
                RetryCount = 0
                # Initialise Variable to take remainder string
                remainder_hex = b""

                while True:
                    # Read from Serial Interface
                    response = ser.read(PackageByLength)
                    # print(response)
                    if len(response) > 0:
                        # In case there is something coming down the serial path
                        logging.debug(response)

                        if response != b"":
                            cdata = binascii.hexlify(response)
                            ddata = cdata.decode("utf-8").upper()
                            edata = hexspace(ddata, 2)
                            temp_data = edata.split()
                            temp_new = [int(t, 16) for t in temp_data]
                            timer = f"{temp_new[3]}:{temp_new[2]}"
                            seconds = temp_new[5]
                            # milliseconds = str(temp_new[6])[0]
                            print(len(temp_new), edata, temp_new, timer, seconds)

                        
                    else:
                        # In case nothing is coming down the serial interface
                        print(
                            "\rWaiting for serial input...",
                            end="          ",
                            flush=True,
                        )

            # in case that the Serial Read or HTTP request fails
            except Exception as e1:
                print("error communicating...: " + str(e1))
                logging.error("error communicating...: " + str(e1))

        else:
            print("Port Opening Failed... trying again in 5 seconds")
            time.sleep(0.1)
            ser.close()

    except SerialException:
        print("No port connected... trying again in 5 seconds")
        time.sleep(0.1)
