import esptool
import sys






def read_esp32_mac(port):
    """Reads the MAC address from an ESP32/ESP8266 device via a specified serial port."""
    try:
        # Create an ESPLoader instance

        print("readmac top")
        esp = esptool.ESPLoader(
            serial_port=port,
            baud=115200,
            # Pass other necessary arguments if needed
        )
        print("got esp loader")
        # Connect to the chip (this automatically puts the chip into download mode)
        esp.connect()

        # Read the MAC address using the library function
        mac_address = esp.read_mac()
        
        # Format the MAC address as a string
        mac_str = ":".join(f"{b:02x}" for b in mac_address)

        print(f"Successfully read MAC address: {mac_str}")
        return mac_str

    except Exception as e:
        print(f"Error reading MAC address: {e}")
        return None
    finally:
        # Ensure the serial port is closed
        if 'esp' in locals() and esp.serial is not None:
            esp.serial.close()








def get_usb_vendor_ids():
    ports = serial.tools.list_ports.comports()
    
    if not ports:
        print("No serial ports found.")
        return

    #print(f"{'Device Name':<20} | {'Vendor ID (VID)':<15}")
    #print("-" * 40)

    for port in ports:
        # The 'hwid' attribute contains a technical description
        # which includes VID and PID for USB devices
        # The 'vid' attribute directly provides the USB Vendor ID as an integer (or None)
        if port.vid is not None:
            # Print the device name and the vendor ID in hexadecimal format
            #print(f"{port.device:<20} | 0x{port.vid:04X} ({port.vid})")
            #print(f"{port.device:<20} | 0x{port.vid:04X} -- {port.description}")
            #print(f"{port.device:<20} | vid 0x{port.vid:04X}  pid 0x{port.pid:04X} -- {port.description}")
            #print(port.pid)
            print(port.device)

            #chipId = getEspChipId(port.device)
            #print(f"Chip ID: {chipId}") 
            read_esp32_mac(port.device)


            if port.vid == 0x1A86:
                print("ch343")    


            if port.vid == 0x10c4:
                print("cp210x")

if __name__ == "__main__":
    get_usb_vendor_ids()

