import serial

def read_frame(ser):
    frame = []
    in_frame = False

    while True:
        byte = ser.read()
        if not byte:
            continue
        b = byte[0]
        if not in_frame:
            if b == 0x02:
                frame = [b]
                in_frame = True
        else:
            frame.append(b)
            if len(frame) >= 2 and frame[-2] == 0x1B and frame[-1] == 0x03:
                return frame

def interpret_frame(frame):
    if len(frame) < 4 or frame[0] != 0x02 or frame[-2:] != [0x1B, 0x03]:
        return "Trame invalide"

    op_code = frame[1]
    if op_code == 0x00:
        return f"[Erreur] Code: {hex(frame[2])}"
    elif op_code == 0x01:
        state = frame[2]
        return f"[Wi-Fi] {'UP' if state == 1 else 'DOWN'}"
    elif op_code == 0x02:
        status = 'Connecté' if frame[2] == 0x01 else 'Déconnecté'
        mac = ':'.join(f"{b:02X}" for b in frame[3:9])
        return f"[Connexion] {status} - {mac}"
    elif op_code == 0x03:
        return "[Demande appareils connectés]"
    elif op_code == 0x04:
        mac = ':'.join(f"{b:02X}" for b in frame[2:8])
        length = frame[8]
        msg = bytes(frame[9:9+length]).decode(errors='ignore')
        return f"[Message] à {mac} : {msg}"
    else:
        return f"[OpCode inconnu] {hex(op_code)}"

def main():
    with serial.Serial('COM5', 115200, timeout=1) as ser:
        print("Lecture des trames...")
        while True:
            frame = read_frame(ser)
            info = interpret_frame(frame)
            print(info)

if __name__ == "__main__":
    main()
