Windows pyboard serial_number from python?

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
User avatar
FraggaMuffin
Posts: 9
Joined: Sat Nov 11, 2017 1:10 am
Location: Melbourne, Australia
Contact:

Windows pyboard serial_number from python?

Post by FraggaMuffin » Mon Jul 16, 2018 2:16 am

I'm trying to uniquely identify a pyboard's COM port from the OS.

So essentially comport_of_pyboard('3976346C3436') returns 'COM3' (or None, if the requested pyboard is not connected)

I can get what I need on Linux with:

>>> from serial.tools.list_ports import comports
>>> ports = comports()
>>> ports
[<serial.tools.list_ports_common.ListPortInfo at 0x26cfac9f080>]
>>> com = ports[0]
>>> com.device
'/dev/ttyACM0'
>>> com.serial_number
'3976346C3436'

But the same code on Windows 10:

>>> from serial.tools.list_ports import comports
>>> ports = comports()
>>> ports
[<serial.tools.list_ports_common.ListPortInfo at 0x26cfad57518>]
>>> com = ports[0]
>>> com.device
'COM3'
>>> com.serial_number
'6'

If I manually browse the Device Manager:
<computer> > Ports (COM & LPT) > USB Serial Device (COM3) [double-click]
Details [tab] > Property: Parent
has the value: USB\VID_F055&PID_9800\3976346C3436

So Windows has the same information Linux has, just in a different format (no surprise there)
I think there's a way to do it through the registry (I'll post what I find), but has anyone got a more elegant solution?

User avatar
FraggaMuffin
Posts: 9
Joined: Sat Nov 11, 2017 1:10 am
Location: Melbourne, Australia
Contact:

Re: Windows pyboard serial_number from python?

Post by FraggaMuffin » Mon Jul 16, 2018 5:09 am

Yep... windows registry solution is as follows:

>>> import re
>>> from serial.tools.list_ports import comports

>>> c = comports()[0]

>>> id_regex = re.compile(r'VID:PID=(?P<VID>\w+?):(?P<PID>\w+)')
>>> match = id_regex.search(c.usb_info())

>>> import winreg
>>> key = winreg.OpenKey(
... winreg.HKEY_LOCAL_MACHINE,
... r'SYSTEM\ControlSet001\Enum\USB\VID_{VID}&PID_{PID}'.format(**match.groupdict())
... )
>>> serial_number = winreg.EnumKey(key, 0)
>>> serial_number
'3976346C3436'

I only have one pyboard at the moment, so I haven't tested this with multiple boards connected.
I'm still interested to know if anybody has a more elegant solution.

Post Reply