import serial
import time

START_BYTE = 0x02
END_BYTES = [0x1B, 0x03]

def build_command(opcode, payload=b''):
    frame = bytearray()
    frame.append(START_BYTE)
    frame.append(opcode)
    frame.extend(payload)
    frame.extend(END_BYTES)
    return frame

def send_command(ser, opcode, payload=b''):
    frame = build_command(opcode, payload)
    print(f"Envoi : {[hex(b) for b in frame]}")
    ser.write(frame)

def main():
    port = 'COM5' 
    baud = 115200

    try:
        with serial.Serial(port, baud, timeout=2) as ser:
            while True:
                print("\nCommandes disponibles :")
                print("1. État du Wi-Fi")
                print("2. Liste des clients connectés")
                print("3. Envoyer un message")
                print("4. Quitter")

                choix = input("Choix (1-4) : ")

                if choix == "1":
                    send_command(ser, 0x01)
                elif choix == "2":
                    send_command(ser, 0x03)
                elif choix == "3":
                    msg = input("Message à envoyer : ")
                    msg_bytes = msg.encode('utf-8')
                    send_command(ser, 0x05, msg_bytes)
                elif choix == "4":
                    print("Fermeture.")
                    break
                else:
                    print("Choix invalide.")

                time.sleep(0.5)

                print("Réponse reçue :")
                while ser.in_waiting:
                    byte = ser.read(1)
                    print(f"Reçu : 0x{byte[0]:02X}")

    except serial.SerialException as e:
        print(f"Erreur de port série : {e}")

if __name__ == "__main__":
    main()
