Python Snippet: Automatically Connect to Notecard over Serial (Linux, Mac, Windows)

Hi Blues Forum,

I was recently working on an internal Python script and noticed a useful snippet for OS-agnostically detecting Notecards (automatically) over Serial.

Below is an example of a quick and simple function you can use in your projects / products. It works by listing available Serial ports and then using a grep function to filter by the Notecard USB VID.

from sys import platform, exit
from serial import Serial
from serial.tools import list_ports
from notecard import OpenSerial

NOTECARD_VENDOR_ID = "30A4"

def getNotecard() -> str:
    """
    Detect and return the appropriate serial port for Notecard connection.
    
    Returns:
        str: Serial port path/identifier
    
    Raises:
        RuntimeError: If platform is unsupported
    """
    defaultPortLookup = {
        "linux": "/dev/serial0",
        "linux2": "/dev/serial0",
        "darwin": "/dev/tty.usbmodemNOTE1",
        "win32": "COM4"
    }

    # Get Notecard serial port from USB VID
    iterator = sorted(list_ports.grep(NOTECARD_VENDOR_ID))
    portIds = [p for (p,_,_) in iterator]
        
    if len(portIds) > 1:
        print("Warning: Multiple Notecards detected. Using first one.")
        return portIds[0]
    
    # If no Notecards are detected, use the default port for the current platform
    if len(portIds) == 0:
        if platform not in defaultPortLookup:
            raise RuntimeError(f"Unsupported platform: {platform}")
        print(f"Serial port not detected. Using {platform} default: {defaultPortLookup[platform]}. You may need to manually specify the port.")
        return defaultPortLookup[platform]
    
    return portIds[0]

if __name__ == "__main__":
    try:
        port = getNotecard()
        with Serial(port=port, timeout=5) as serial_port:
            card = OpenSerial(serial_port)

            # Your Notecard request here, e.g. {"req": "card.version"}
            req = {"req": "card.version"}
            response = card.Transaction(req)
            print(response)

    except Exception as e:
        print(f"Error: {e.__class__.__name__}: {e}")
        exit(1)

You’ll need to download the dependencies for serial and notecard. You can also find this snippet in a GitHub Gist.

Let me know if this is useful and/or if there’s any helpful scripts you use for Notecard/Notehub development!

2 Likes