Python serial.tools.list_ports.comports() Examples

The following are 30 code examples of serial.tools.list_ports.comports(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module serial.tools.list_ports , or try the search function .
Example #1
Source File: ebb_serial.py    From plotink with MIT License 12 votes vote down vote up
def listEBBports():
    # Find and return a list of all EiBotBoard units
    # connected via USB port.
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        return None
    if comports:
        com_ports_list = list(comports())
        ebb_ports_list = []
        for port in com_ports_list:
            port_has_ebb = False
            if port[1].startswith("EiBotBoard"):
                port_has_ebb = True
            elif port[2].startswith("USB VID:PID=04D8:FD92"):
                port_has_ebb = True
            if port_has_ebb:
                ebb_ports_list.append(port)
        if ebb_ports_list:
            return ebb_ports_list 
Example #2
Source File: miniterm.py    From ddt4all with GNU General Public License v3.0 8 votes vote down vote up
def ask_for_port():
    """\
    Show a list of ports and ask the user for a choice. To make selection
    easier on systems with long device names, also allow the input of an
    index.
    """
    sys.stderr.write('\n--- Available ports:\n')
    ports = []
    for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
        sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc))
        ports.append(port)
    while True:
        port = raw_input('--- Enter port index or full name: ')
        try:
            index = int(port) - 1
            if not 0 <= index < len(ports):
                sys.stderr.write('--- Invalid index!\n')
                continue
        except ValueError:
            pass
        else:
            port = ports[index]
        return port 
Example #3
Source File: ebb_serial.py    From plotink with MIT License 7 votes vote down vote up
def findPort():
    # Find first available EiBotBoard by searching USB ports.
    # Return serial port object.
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        return None
    if comports:
        com_ports_list = list(comports())
        ebb_port = None
        for port in com_ports_list:
            if port[1].startswith("EiBotBoard"):
                ebb_port = port[0]  # Success; EBB found by name match.
                break  # stop searching-- we are done.
        if ebb_port is None:
            for port in com_ports_list:
                if port[2].startswith("USB VID:PID=04D8:FD92"):
                    ebb_port = port[0]  # Success; EBB found by VID/PID match.
                    break  # stop searching-- we are done.
        return ebb_port 
Example #4
Source File: optomotor.py    From ethoscope with GNU General Public License v3.0 7 votes vote down vote up
def _find_port(self):
        from serial.tools import list_ports
        import serial
        import os
        all_port_tuples = list_ports.comports()
        logging.info("listing serial ports")
        all_ports = set()
        for ap, _, _ in all_port_tuples:
            p = os.path.basename(ap)
            print(p)
            if p.startswith("ttyUSB") or p.startswith("ttyACM"):
                all_ports |= {ap}
                logging.info("\t%s", str(ap))

        if len(all_ports) == 0:
            logging.error("No valid port detected!. Possibly, device not plugged/detected.")
            raise NoValidPortError()

        elif len(all_ports) > 2:
            logging.info("Several port detected, using first one: %s", str(all_ports))
        return all_ports.pop() 
Example #5
Source File: ebb_serial.py    From axidraw with GNU General Public License v2.0 6 votes vote down vote up
def listEBBports():
    # Find and return a list of all EiBotBoard units
    # connected via USB port.
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        return None
    if comports:
        com_ports_list = list(comports())
        ebb_ports_list = []
        for port in com_ports_list:
            port_has_ebb = False
            if port[1].startswith("EiBotBoard"):
                port_has_ebb = True
            elif port[2].startswith("USB VID:PID=04D8:FD92"):
                port_has_ebb = True
            if port_has_ebb:
                ebb_ports_list.append(port)
        if ebb_ports_list:
            return ebb_ports_list 
Example #6
Source File: extcap_ot.py    From pyspinel with Apache License 2.0 6 votes vote down vote up
def extcap_interfaces():
    """List available interfaces to capture from"""

    log_file = open(
        os.path.join(tempfile.gettempdir(), 'extcap_ot_interfaces.log'), 'w')
    print(
        'extcap {version=1.0.0}{display=OpenThread Sniffer}{help=https://github.com/openthread/pyspinel}'
    )

    threads = []
    for interface in comports():
        th = threading.Thread(target=serialopen, args=(interface, log_file))
        threads.append(th)
        th.start()
    for th in threads:
        th.join() 
Example #7
Source File: ebb_serial.py    From axidraw with GNU General Public License v2.0 6 votes vote down vote up
def findPort():
    # Find first available EiBotBoard by searching USB ports.
    # Return serial port object.
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        return None
    if comports:
        com_ports_list = list(comports())
        ebb_port = None
        for port in com_ports_list:
            if port[1].startswith("EiBotBoard"):
                ebb_port = port[0]  # Success; EBB found by name match.
                break  # stop searching-- we are done.
        if ebb_port is None:
            for port in com_ports_list:
                if port[2].startswith("USB VID:PID=04D8:FD92"):
                    ebb_port = port[0]  # Success; EBB found by VID/PID match.
                    break  # stop searching-- we are done.
        return ebb_port 
Example #8
Source File: miniterm.py    From android_universal with MIT License 6 votes vote down vote up
def ask_for_port():
    """\
    Show a list of ports and ask the user for a choice. To make selection
    easier on systems with long device names, also allow the input of an
    index.
    """
    sys.stderr.write('\n--- Available ports:\n')
    ports = []
    for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
        sys.stderr.write('--- {:2}: {:20} {!r}\n'.format(n, port, desc))
        ports.append(port)
    while True:
        port = raw_input('--- Enter port index or full name: ')
        try:
            index = int(port) - 1
            if not 0 <= index < len(ports):
                sys.stderr.write('--- Invalid index!\n')
                continue
        except ValueError:
            pass
        else:
            port = ports[index]
        return port 
Example #9
Source File: serialutils.py    From nodemcu-uploader with MIT License 6 votes vote down vote up
def default_port(sysname=system(), detect=True):
    """This returns the default port used for different systems if SERIALPORT env variable is not set"""
    system_default = {
        'Windows': 'COM1',
        'Darwin': '/dev/tty.SLAB_USBtoUART'
    }.get(sysname, '/dev/ttyUSB0')
    # if SERIALPORT is set then don't even waste time detecting ports
    if 'SERIALPORT' not in environ and detect:
        try:
            ports = list_ports.comports(include_links=False)
            if len(ports) == 1:
                return ports[0].device
            else:
                # clever guessing, sort of
                # vid/pid
                # 4292/60000 adafruit huzzah
                for p in ports:
                    if p.vid == 4292 and p.pid == 60000:
                        return p.device
                # use last port as fallback
                return ports[-1].device
        except Exception:
            pass

    return environ.get('SERIALPORT', system_default) 
Example #10
Source File: link.py    From btlejack with MIT License 6 votes vote down vote up
def __init__(self, interface=None, baudrate=115200):
        self.lock = Lock()

        # Pick the first serial port that matches a Micro:Bit
        # if no interface is provided
        if interface is None:
            for port in comports():
                if type(port) is tuple:
                    if "VID:PID=0d28:0204" in port[-1]:
                        interface = port[0]
                        break
                elif port.vid == 0x0D28 and port.pid == 0x0204:
                    interface = port.device
                    break

        # If no interface found, we cannot do anything as we need at least
        # one Micro:bit device connected.
        if interface is None:
            raise DeviceError('No Micro:Bit connected')

        # If an interface was found, continue
        self.interface = Serial(interface, baudrate, timeout=0)
        self.rx_buffer = bytes() 
Example #11
Source File: tools.py    From Openroast with GNU General Public License v3.0 6 votes vote down vote up
def format_filename(s):
    """Take a string and return a valid filename constructed from the string.
    Uses a whitelist approach: any characters not present in valid_chars are
    removed. Also spaces are replaced with underscores."""
    valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
    filename = ''.join(c for c in s if c in valid_chars)
    filename = filename.replace(' ','_') # I don't like spaces in filenames.
    return filename


# def vid_pid_to_serial_url(vidpid):
#     #Get all com ports currently connected to the system
#     currentComPorts = list(list_ports.comports())
#     for port in currentComPorts:
#         if re.search(vidpid, port[2], flags=re.IGNORECASE):
#             return port[0]
#     raise LookupError('VID:PID Not found on system') 
Example #12
Source File: quality_control.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _find_port(self):
        all_port_tuples = list_ports.comports()
        logging.info("listing serial ports")

        all_ports = set()
        for ap, _, _  in all_port_tuples:
            all_ports |= {ap}
            logging.info("\t%s", str(ap))

        for ap in list(all_ports):
            logging.info("trying port %s", str(ap))

            try:
                #here we use a recursive strategy to find the good port (ap).
                SimpleLynxMotionConnection(ap)
                return ap
            except (WrongSleepDepPortError, serial.SerialException):
                warn_str = "Tried to use port %s. Failed." % ap
                logging.warning(warn_str)
                pass

        logging.error("No valid port detected!. Possibly, device not plugged/detected.")
        raise NoValidPortError() 
Example #13
Source File: lynx_basics.py    From ethoscope with GNU General Public License v3.0 6 votes vote down vote up
def _find_port(self):
        all_port_tuples = list_ports.comports()
        logging.info("listing serial ports")

        all_ports = set()
        for ap, _, _  in all_port_tuples:
            all_ports |= {ap}
            logging.info("\t%s", str(ap))

        for ap in list(all_ports):
            logging.info("trying port %s", str(ap))

            try:
                #here we use a recursive strategy to find the good port (ap).
                SimpleLynxMotionConnection(ap)
                return ap
            except (WrongSleepDepPortError, serial.SerialException):
                warn_str = "Tried to use port %s. Failed." % ap
                logging.warning(warn_str)
                pass

        logging.error("No valid port detected!. Possibly, device not plugged/detected.")
        raise NoValidPortError() 
Example #14
Source File: ebb.py    From axibot with GNU General Public License v2.0 5 votes vote down vote up
def list_ports(cls):
        ports = comports()
        for port in ports:
            if port[1].startswith('EiBotBoard'):
                yield port[0]
            elif port[2].upper().startswith('USB VID:PID=04D8:FD92'):
                yield port[0] 
Example #15
Source File: i2cgui.py    From i2cdriver with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def devices(self):
        if sys.platform in ('win32', 'cygwin'):
            return {pi.device: pi.device for pi in slp.comports()}
        elif sys.platform == 'darwin':
            devdir = "/dev/"
            pattern = "^cu.usbserial-(.*)"
        else:
            devdir = "/dev/serial/by-id/"
            pattern = "^usb-FTDI_FT230X_Basic_UART_(........)-"

        if not os.access(devdir, os.R_OK):
            return {}
        devs = os.listdir(devdir)
        def filter(d):
            m = re.match(pattern, d)
            if m:
                return (m.group(1), devdir + d)
        seldev = [filter(d) for d in devs]
        return dict([d for d in seldev if d]) 
Example #16
Source File: serial_board.py    From letsrobot with Apache License 2.0 5 votes vote down vote up
def fallbackSerial():
    for port in ports.comports():
        if not port.device == "/dev/ttyAMA0":
            yield port.device
        else:
            log.debug("Serial Fallback ignoring onboard bluetooth serial")
    log.debug("No more possible serial ports") 
Example #17
Source File: serial_board.py    From letsrobot with Apache License 2.0 5 votes vote down vote up
def searchSerial(name):
    for port in ports.comports():
        if name in port.description or \
           name in port.hwid or \
           name in port.manufacturer:
            return port.device
    return None 
Example #18
Source File: hue_ui.py    From hue-plus with GNU General Public License v3.0 5 votes vote down vote up
def get_port(self):
        ports = []
        for port in list_ports.comports():
            if 'MCP2200' in port[1] or 'USB Serial Device' in port[1] or 'USB Serial Port' in port[1]:
                ports.append(port[0])
        if ports:
            return ports[0]
        else:
            return None 
Example #19
Source File: plugin.py    From declaracad with GNU General Public License v3.0 5 votes vote down vote up
def get_connections(cls):
        return [Connection(name=str(port),
                           factory=cls(port=port)) for port in comports()] 
Example #20
Source File: myo_raw.py    From myo-raw with MIT License 5 votes vote down vote up
def detect_tty(self):
        for p in comports():
            if re.search(r'PID=2458:0*1', p[2]):
                print('using device:', p[0])
                return p[0]

        return None 
Example #21
Source File: pozyx_serial.py    From Pozyx-Python-library with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_serial_ports():
    """Returns the open serial ports"""
    return comports() 
Example #22
Source File: UART.py    From peniot with MIT License 5 votes vote down vote up
def list_serial_ports():
    # Scan for available ports.
    return list_ports.comports() 
Example #23
Source File: jobs.py    From btlejack with MIT License 5 votes vote down vote up
def __init__(self, max_number_sniffers=1, baudrate=115200, devices=None, v5=False):
        super().__init__(None)
        self.interfaces = []

        # Enumerate available interfaces
        self.devices = []
        if devices is None:
            for port in comports():
                if type(port) is tuple:
                    if "VID:PID=0d28:0204" in port[-1]:
                        self.devices.append(port[0])
                elif port.vid == 0x0D28 and port.pid == 0x0204:
                    self.devices.append(port.device)
        else:
            for device in devices:
                self.devices.append(device)

        # Cannot continue if no device is connected :/
        if len(self.devices) == 0:
            raise DeviceError("No compatible device found")

        #print('new sniffer, reset active link')
        self.active_link = None
        self.v5 = v5
        self.connect(max_number_sniffers, baudrate)
        self.reset() 
Example #24
Source File: microfs.py    From microfs with MIT License 5 votes vote down vote up
def find_microbit():
    """
    Returns a tuple representation of the port and serial number for a
    connected micro:bit device. If no device is connected the tuple will be
    (None, None).
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return (port[0], port.serial_number)
    return (None, None) 
Example #25
Source File: device.py    From axi with MIT License 5 votes vote down vote up
def find_port():
    for port in comports():
        if VID_PID in port[2]:
            return port[0]
    return None 
Example #26
Source File: list_ports.py    From xArm-Python-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_ports(is_dump=True):
    ports = []
    for i in list_ports.comports():
        # if i.pid is not None and '{:04x}:{:04x}'.format(i.vid, i.pid) == vidpid:
        if i.pid is not None:
            if is_dump:
                _dump_port(i)
            ports.append({
                'pid': '{:04x}'.format(i.pid),
                'vid': '{:04x}'.format(i.vid),
                'device': i.device,
                'serial_number': i.serial_number,
                'hwid': i.hwid,
                'name': i.name,
                'description': i.description,
                'interface': i.interface,
                'location': i.location,
                'manufacturer': i.manufacturer,
                'product': i.product
            })
    return ports 
Example #27
Source File: microfs.py    From mu with GNU General Public License v3.0 5 votes vote down vote up
def find_microbit():
    """
    Returns a tuple representation of the port and serial number for a
    connected micro:bit device. If no device is connected the tuple will be
    (None, None).
    """
    ports = list_serial_ports()
    for port in ports:
        if "VID:PID=0D28:0204" in port[2].upper():
            return (port[0], port.serial_number)
    return (None, None) 
Example #28
Source File: api.py    From dorna with MIT License 5 votes vote down vote up
def port_list(self):
		#result = json.dumps([str(p[0]) for p in list_ports.comports()])
		result = [str(p[0]) for p in list_ports.comports()]
		self._log_add(result, "port_list")
		return json.dumps(result) 
Example #29
Source File: serial_bus.py    From pqcom with MIT License 5 votes vote down vote up
def get_ports():
    ports = []
    for comport in list_ports.comports():
        port = comport[0]
        if (port.startswith('/dev/ttyACM') or port.startswith('/dev/ttyUSB') or
                port.startswith('COM') or
                port.startswith('/dev/cu.')):
            ports.append(port)

    ports.sort()

    return ports 
Example #30
Source File: tinyfpga-programmer-gui.py    From TinyFPGA-Programmer-Application with GNU General Public License v3.0 5 votes vote down vote up
def update_serial_port_list_task():
    global tinyfpga_ports
    global program_in_progress
    global tinyfpga_adapters
    
    if not program_in_progress:
        new_tinyfpga_adapters = dict((adapter.displayName(), adapter) for adapter in [getProgrammerHardwareAdapter(port) for port in comports()] if adapter is not None)
        new_tinyfpga_ports = [key for key, value in new_tinyfpga_adapters.iteritems()]
        
        if new_tinyfpga_ports != tinyfpga_ports:
            if com_port_sv.get() == "" and len(new_tinyfpga_ports) > 0:
                com_port_sv.set(new_tinyfpga_ports[0])
                update_button_state(new_serial_port_ready = True)

            update_button_state(new_serial_port_ready = com_port_sv.get() in new_tinyfpga_ports)

            menu = select_port_om["menu"]
            menu.delete(0, "end")
            for string in new_tinyfpga_ports:
                menu.add_command(
                    label=string, 
                    command=lambda value=string: com_port_sv.set(value))
            tinyfpga_ports = new_tinyfpga_ports
            tinyfpga_adapters = new_tinyfpga_adapters

    r.after(100, update_serial_port_list_task)