import time
import serial
import argparse

#======Serial Variable=======
# SERIAL_PATH = "/dev/serial/by-path/pci-0000:00:14.0-usb-0:2:1.0-port0"
SERIAL_PATH = "/dev/ttyUSB1"
BAUD_RATE = 19200
PARITY='N'
STOP_BITS=1
BYTE_SIZE=8
TIMEOUT=1
#============================

ser = serial.Serial(port=SERIAL_PATH, baudrate=BAUD_RATE, parity=PARITY, stopbits=STOP_BITS, bytesize=BYTE_SIZE, timeout=TIMEOUT)


def light_control(args, ch_num:int):
    global ser

    ch_list=[0, 16, 17, 18, 19]
    bright = int(args.brightness)

    if(ch_num == 0):
        print("Channel range : 1~4 // not 0 ")
    try:
        START=(5 & 0xFF).to_bytes(1, byteorder='big')
        CH_NUM=(ch_list[ch_num] & 0xFF).to_bytes(1, byteorder='big')
        BLIGHT=(bright & 0xFF).to_bytes(1, byteorder='big')
        CHK_SUM=(ch_list[ch_num] + bright & 0xFF).to_bytes(1, byteorder='big')
        
        ser.write(START)
        ser.write(CH_NUM)
        ser.write(BLIGHT)
        ser.write(CHK_SUM)      

    except Exception as e:
        print(e)

    return True


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--brightness', help='adjustment led brightness', required=True)
    
    args = parser.parse_args()

    light_control(args, 1)


# print(light_control(ser,1,30))
# time.sleep(1)
# print(light_control(ser,1,0))
# time.sleep(1)
# print(light_control(ser,1,100))
# time.sleep(1)
# print(light_control(ser,1,0))
# time.sleep(1)
# print(light_control(ser,1,240))
# 
# 
# #for i in range(500):
# while True:
#     for i in range(0,50):
#         light_control(ser,1,i*5)
#         time.sleep(0.02)
#    
#     for i in range(0,50):
#         light_control(ser,1,255-i*5)
#         time.sleep(0.02)
#     print(i)



# turn_on = [b"\x05", b"\x10", b'\xF0', b'\x00']
# turn_off = [b'\x05', b'\x10', b'\x00', b'\x10']
# 
# rqt_status = [b'\x05', b'\x14', b'\x00', b'\x14']
# remote_on = [b'\x05', b'\x29', b'\x01', b'\x2A']
# 
# try:
#     result = ser.write(b''.join(turn_off))
#     print(result)
#     time.sleep(2)
#     result = ser.write(b''.join(turn_on))
#     print(result)
# except Exception as e:
#     print(f"Error {e}")
#     port.close()

