def get_devices(include_links=False): if os.name == 'nt' or sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports if pyserial_34: ports = comports(include_links=include_links) else: ports = comports() return sorted(ports)
def enum_ports(): hits = 0 # get iteraror w/ or w/o filter iterator = sorted(comports()) for i in iterator: yield i[0]
def show_ports(): iterator = sorted(comports()) sys.stdout.write('Available ports: \n') for n, (port, desc, hwid) in enumerate(iterator, 1): sys.stdout.write('{:20}\n'.format(port)) sys.stdout.write(' desc: {}\n'.format(desc)) sys.stdout.write(' hwid: {}\n'.format(hwid))
def comports(): """Generator for comports found from list ports windows and comports found in the windows registry. See Also: list_ports_winreg.comports_list(), list_ports_winreg.winreg_comports(), list_ports_windows.comports() Note: This should include virtual comports. This method contains all list_ports_windows.comports() and winreg_comports() that were not found from list_ports_windows. Yields: comport (ListPortInfo): Comport details. Returns: comports (generator): Generator of ListPortInfo comports. """ existing = [] for comport in list_ports_windows.comports(): existing.append(comport) yield comport for li in winreg_comports(): if li not in existing: existing.append(li) yield li
def find_all_ports(self): '''Return a list of port names found. OS independent in nature. Unsupported OS raises OSError exception''' port_list=[] #List to return ports information #Find all ports for windows if sys.platform.startswith('win'): import serial.tools.list_ports_windows as sertoolswin ports = sertoolswin.comports() #Find all ports for Linux based OSes elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): import serial.tools.list_ports_linux as sertoolslin ports = sertoolslin.comports() #Find all ports for MacOSX elif sys.platform.startswith('darwin'): import serial.tools.list_ports_osx as sertoolsosx ports = sertoolsosx.comports() #Raise exception for unsupported OS else: raise OSError("Unsupported Platform/OS") #Fill the return list with information found print('Available ports are:') for port, desc, hwid in sorted(ports): port_list.append(port) print("{}: {} with id: {}".format(port, desc, hwid)) return port_list
def auto_detect_serial_win32(preferred_list=['*']): '''try to auto-detect serial ports on win32''' try: from serial.tools.list_ports_windows import comports list = sorted(comports()) except: return [] ret = [] others = [] for port, description, hwid in list: matches = False p = SerialPort(port, description=description, hwid=hwid) for preferred in preferred_list: if fnmatch.fnmatch(description, preferred) or fnmatch.fnmatch( hwid, preferred): matches = True if matches: ret.append(p) else: others.append(p) if len(ret) > 0: return ret # now the rest ret.extend(others) return ret
def getSerialPorts(cls) -> List[Optional[str]]: """Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if isWindows(): ports = [port.device for port in comports()] elif isLinux(): # this excludes your current terminal "/dev/tty" ports = glob.glob("/dev/tty[A-Za-z]*") elif isMacOS(): ports = glob.glob("/dev/tty.*") else: raise EnvironmentError("Unsupported platform") valid: List[str] = ports result: List[Optional[str]] = [] if len(valid) > 0: valid.sort() result.append(None) # Add the None option result.extend(valid) return result
def find_port(): logging.debug('Searching for port...') for port in comports(): device = port[0] if 'bluetooth' in device.lower(): continue if port.pid != 0xea60 and port.vid != 0x10c4: logging.debug(f'skipping: {port.hwid}') continue try: logging.debug('Trying %s', device) s = serial.Serial(device) except serial.SerialException: logging.debug('Port is busy, continuing...') continue else: s.close() logging.debug('Port is found! - %s', device) if (sys.version_info.major == 2): if isinstance(device, unicode): device = device.encode('utf-8') return device else: logging.debug('Port not found') return
def get_serialports(): if os.name == "nt": from serial.tools.list_ports_windows import comports elif os.name == "posix": from serial.tools.list_ports_posix import comports else: raise exception.GetSerialPortsError(os.name) return [{"port": p, "description": d, "hwid": h} for p, d, h in comports()]
def find_teensy(): """Returns a list of ports for all Teensy devices.""" result = [] for usb_dev in sorted(comports()): if usb_dev.vid == VendorID and usb_dev.pid == ProductID: result.append(usb_dev) return result
def devices(): '''Print available devices.''' if os.name == 'nt' or sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports for port in sorted(comports()): click.echo(port[0], err=True)
def getComPortsList(): log.debug(f"Update thread ID: {int(QThread.currentThreadId())}") log.debug("Fetching com ports...") newComPorts: List[ComPortInfo] = comports() log.debug( f"New com ports list: {', '.join(port.device for port in newComPorts)} ({len(newComPorts)} items)" ) return newComPorts
def ini_serial(): global SER_COM global ser for info in comports(False): if 'USB Serial Port' in info.description: SER_COM=info.device print(SER_COM) ser = serial.Serial(port=SER_COM, baudrate=921600,timeout=None, xonxoff=0, rtscts=1)#parity
def get_ports_list(): import argparse parser = argparse.ArgumentParser(description='Serial port enumeration') parser.add_argument('regexp', nargs='?', help='only show ports that match this regex') parser.add_argument('-v', '--verbose', action='store_true', help='show more messages') parser.add_argument('-q', '--quiet', action='store_true', help='suppress all messages') parser.add_argument('-n', type=int, help='only output the N-th entry') parser.add_argument( '-s', '--include-links', action='store_true', help='include entries that are symlinks to real devices') args = parser.parse_args() hits = 0 serial_results = [] # get iteraror w/ or w/o filter if args.regexp: if not args.quiet: sys.stderr.write("Filtered list with regexp: {!r}\n".format( args.regexp)) iterator = sorted(grep(args.regexp, include_links=args.include_links)) else: iterator = sorted(comports(include_links=args.include_links)) # list them for n, (port, desc, hwid) in enumerate(iterator, 1): if args.n is None or args.n == n: # sys.stdout.write("{:20}\n".format(port)) port_result = [port, desc, hwid] serial_results.append(port_result) if args.verbose: sys.stdout.write(" desc: {}\n".format(desc)) sys.stdout.write(" hwid: {}\n".format(hwid)) hits += 1 if not args.quiet: if hits: # sys.stderr.write("{} ports found\n".format(hits)) pass else: sys.stderr.write("no ports found\n") return serial_results
def findarduino(self): ports = list_ports_windows.comports() port_list = [] for x in ports: #print(x.__str__()) # TODO: bewonder dit lijstje if 'Arduino' in x.__str__(): # comport met arduino? port_list.append(x.__str__()[:5].strip( )) # sla de eerste 5 tekens op("COM##" of "COM# ") return port_list
def command_devices(verbose=False, include_links=False): if os.name == 'nt' or sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports if pyserial_34: ports = comports(include_links=include_links) else: ports = comports() sorted(ports) for port, desc, hwid in ports: sys.stdout.write("{:20}\n".format(port)) if verbose: sys.stdout.write(" desc: {}\n".format(desc)) sys.stdout.write(" hwid: {}\n".format(hwid))
def grep(regexp): """\ Search for ports using a regular expression. Port name, description and hardware ID are searched. The function returns an iterable that returns the same tuples as comport() would do. """ r = re.compile(regexp, re.I) for port, desc, hwid in comports(): if r.search(port) or r.search(desc) or r.search(hwid): yield port, desc, hwid
def find_smoothie(): iterator = sorted(comports()) for n, (port, name, desc) in enumerate(iterator, 1): # parse the USB serial port's description string port_data = parse_port_descriptors(port, name, desc) # all smoothieboards have a 'name' attribute if port_data.get('pid')=='6015': return port_data
def list_ports(self): import os if os.name == 'nt': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError("Sorry: no implementation for your platform ('%s') available" % (os.name,)) ports = sorted(comports()) for n, (port, desc, hwid) in enumerate(ports, 1): self.port_list.append(port)
def main(self): if os.name == 'nt': # sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError( "Sorry: no implementation for your platform ('{}') available". format(os.name)) for info in comports(): print(info.device)
def find_possible_port(): if os.name == 'nt': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError( "Sorry: no implementation for your platform ('{}') available". format(os.name)) ports = comports(True) outputs = [port.device for port in ports] return outputs
def main(): import argparse parser = argparse.ArgumentParser(description='Serial port enumeration') parser.add_argument( 'regexp', nargs='?', help='only show ports that match this regex') parser.add_argument( '-v', '--verbose', action='store_true', help='show more messages') parser.add_argument( '-q', '--quiet', action='store_true', help='suppress all messages') parser.add_argument( '-n', type=int, help='only output the N-th entry') parser.add_argument( '-s', '--include-links', action='store_true', help='include entries that are symlinks to real devices') args = parser.parse_args() hits = 0 # get iteraror w/ or w/o filter if args.regexp: if not args.quiet: sys.stderr.write("Filtered list with regexp: {!r}\n".format(args.regexp)) iterator = sorted(grep(args.regexp, include_links=args.include_links)) else: iterator = sorted(comports(include_links=args.include_links)) # list them for n, (port, desc, hwid) in enumerate(iterator, 1): if args.n is None or args.n == n: sys.stdout.write("{:20}\n".format(port)) if args.verbose: sys.stdout.write(" desc: {}\n".format(desc)) sys.stdout.write(" hwid: {}\n".format(hwid)) hits += 1 if not args.quiet: if hits: sys.stderr.write("{} ports found\n".format(hits)) else: sys.stderr.write("no ports found\n")
def run(self) -> None: # --- EdgeService.run(self) # --- 1A86:7523 # --------------------------------------------- SERIAL import sys import os from serial.tools.list_ports_common import ListPortInfo if os.name == 'nt' or sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError( "Sorry: no implementation for your platform ('{}') available". format(os.name)) # --- target_vid = "0x1A86" target_pid = "0x7523" # --- tmp_comp = comports(include_links=None) for item in tmp_comp: tmp_item: ListPortInfo = item print("ARDUINO: {:20} desc: {} hwid: {}".format( tmp_item.device, tmp_item.description, tmp_item.hwid)) if tmp_item.vid and tmp_item.pid and not self.serial_port: print(hex(tmp_item.vid), tmp_item.vid == int(target_vid, 16)) print(hex(tmp_item.pid), tmp_item.pid == int(target_pid, 16)) # --- 1A86:7523 if tmp_item.vid == int(target_vid, 16) and tmp_item.pid == int( target_pid, 16): print("-----> arduino add port {}".format(tmp_item)) self.serialport = tmp_item.device try: self.serial_port = serial.Serial(self.serialport, self.baud, timeout=1) except Exception as e: print("{} error: {}".format(self.__class__.__name__, e)) self.serial_port = None # ----------------------------------------------- while True: # --- if self.serial_port: self.read_serial_device() time.sleep(1) else: # --- # ToDo: make plug&play loop scan if new arduino plugged # --- pass
def show_ports(args): logger.info('Searching for available ports') logger.info('Available ports are:') ports = sorted(comports()) avail_ports = [] for n, (port, desc, hwid) in enumerate(ports, 1): logger.info('\t{}'.format(port)) avail_ports.append(port) logger.debug('Finished searching for available ports') return avail_ports
def check_mcu_port(): global MCUport global MCUserialport if MCUserialport[0] != None: MCUserialport[0] = None time.sleep(2) for port, desc, hwid in sorted(list_ports_windows.comports()): #print("{}: {} [{}]".format(port, desc, hwid)+"\n") if MCUserialport[0] == None: if "STM32_MCU" in hwid: MCUport[0] = port MCUserialport[0] = serial.Serial(MCUport[0], 115200, timeout=1) print("\nCommunication_Link = {}\n".format(MCUserialport[0])) print(MCUport[0])
def get_serial_ports(): try: if os.name == 'nt': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError("Sorry: no implementation for your" "platform ('%s') available" % (os.name,)) except ImportError: yield "(couldn't import PySerial)", None else: yield "(disabled)", None for port, desc, _ in comports(): yield '{0} ({1})'.format(port, desc.strip()), port
def get_serial_ports(): try: if os.name == 'nt': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError("Sorry: no implementation for your" "platform ('%s') available" % (os.name, )) except ImportError: yield "(couldn't import PySerial)", None else: yield "(disabled)", None for port, desc, _ in comports(): yield '{0} ({1})'.format(port, desc.strip()), port
def print_ports(): if os.name == 'nt': # sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports #~ elif os.name == 'java': else: raise ImportError( "Sorry: no implementation for your platform ('{}') available". format(os.name)) serial_ports = comports() for n, (port, desc, hwid) in enumerate(serial_ports, 1): print("PORT NAME: {} \t\t DESCRIPTION: {} \t\t HWID: {} ".format( port, desc, hwid))
def check_usb_port(): global UARTport global UARTserialport if UARTserialport[0] != None: UARTserialport[0] = None time.sleep(2) for port, desc, hwid in sorted(list_ports_windows.comports()): print("{}: {} [{}]".format(port, desc, hwid) + "\n") if UARTserialport[0] == None: if "CHERRY_UART" in hwid: UARTport[0] = port UARTserialport[0] = serial.Serial(UARTport[0], 115200, timeout=1) print("\nCommunication_Link = {}\n".format(UARTserialport[0])) print(UARTport[0])
def main(): import argparse parser = argparse.ArgumentParser(description='Serial port enumeration') parser.add_argument('regexp', nargs='?', help='only show ports that match this regex') parser.add_argument('-v', '--verbose', action='store_true', help='show more messages') parser.add_argument('-q', '--quiet', action='store_true', help='suppress all messages') parser.add_argument('-n', type=int, help='only output the N-th entry') args = parser.parse_args() hits = 0 # get iteraror w/ or w/o filter if args.regexp: if not args.quiet: sys.stderr.write("Filtered list with regexp: %r\n" % (args.regexp, )) iterator = sorted(grep(args.regexp)) else: iterator = sorted(comports()) # list them for n, (port, desc, hwid) in enumerate(iterator, 1): if args.n is None or args.n == n: sys.stdout.write("{:20}\n".format(port)) if args.verbose: sys.stdout.write(" desc: {}\n".format(desc)) sys.stdout.write(" hwid: {}\n".format(hwid)) hits += 1 if not args.quiet: if hits: sys.stderr.write("{} ports found\n".format(hits)) else: sys.stderr.write("no ports found\n")
def populate_list(self): """ This function currently only works for Windows. It well use the *serial.tools.list_ports_windows.comports()* function to get all available serial ports. Then it will add the names to the list widget. """ # clear the list self.listWidget_available_ports.clear() # search for all available serial ports and add it to a list self.ports = list_ports_windows.comports() # iterate through and add the description text to the list widget for p in self.ports: item = QtWidgets.QListWidgetItem(p.description) self.listWidget_available_ports.addItem(item) # highlight the saved port if it exists self.highlight_port()
def find_port(): logging.debug('Searching for port...') for port in comports(): device = port[0] try: logging.debug('Trying %s', device) s = serial.Serial(device) except serial.SerialException: logging.debug('Port is busy, continuing...') continue else: s.close() logging.debug('Port is found! - %s', device) if isinstance(device, unicode): device = device.encode('utf-8') return device else: logging.debug('Port not found') return
def comports_list(): """Return a list of comports found from list_ports_windows and comports found in the window registry. See Also: list_ports_winreg.comports(), list_ports_winreg.winreg_comports(), list_ports_windows.comports() Note: This should include virtual comports. This method contains all list_ports_windows.comports() and winreg_comports() that were not found from list_ports_windows. Returns: comports (list): List of ListPortInfo comport details. """ comports = list(list_ports_windows.comports()) comports[len(comports):] = [ li for li in winreg_comports() if li not in comports ] return comports
def comports_list(): """Return a list of comports found from list_ports_windows and comports found in the window registry. See Also: list_ports_winreg.comports(), list_ports_winreg.winreg_comports(), list_ports_windows.comports() Note: This should include virtual comports. This method contains all list_ports_windows.comports() and winreg_comports() that were not found from list_ports_windows. Returns: comports (list): List of ListPortInfo comport details. """ comports = list(list_ports_windows.comports()) comports[len(comports): ] = [li for li in winreg_comports() if li not in comports] return comports
def main(): import argparse parser = argparse.ArgumentParser(description="Serial port enumeration") parser.add_argument("regexp", nargs="?", help="only show ports that match this regex") parser.add_argument("-v", "--verbose", action="store_true", help="show more messages") parser.add_argument("-q", "--quiet", action="store_true", help="suppress all messages") parser.add_argument("-n", type=int, help="only output the N-th entry") args = parser.parse_args() hits = 0 # get iteraror w/ or w/o filter if args.regexp: if not args.quiet: sys.stderr.write("Filtered list with regexp: {!r}\n".format(args.regexp)) iterator = sorted(grep(args.regexp)) else: iterator = sorted(comports()) # list them for n, (port, desc, hwid) in enumerate(iterator, 1): if args.n is None or args.n == n: sys.stdout.write("{:20}\n".format(port)) if args.verbose: sys.stdout.write(" desc: {}\n".format(desc)) sys.stdout.write(" hwid: {}\n".format(hwid)) hits += 1 if not args.quiet: if hits: sys.stderr.write("{} ports found\n".format(hits)) else: sys.stderr.write("no ports found\n")
def list(): return sorted([ i[0] for i in comports() ])
if DEBUG: print "Leaving %s thread" %ME time.sleep(1) # Allow time to close the serial port except Exception as e: showError("Error in execution thread:", str(e) ) finally: return None # ------------------------------------------------------------------------------ # Get a list of valid com ports for this system if os.name == 'nt': # sys.platform == 'win32': from serial.tools.list_ports_windows import comports elif os.name == 'posix': from serial.tools.list_ports_posix import comports else: raise ImportError("Sorry: no implementation for your platform ('{}') available".format(os.name)) ports = comports() for n, (port, desc, hwid) in enumerate(ports, 1): COM_PORTS.append(port) # sys.stdout.write("{:20}\n".format(port)) # sys.stdout.write(" desc: {}\n".format(desc)) # sys.stdout.write(" hwid: {}\n".format(hwid)) # ------------------------------------------------------------------------------ # Check to see that we have at least one usable com port or notify and quit if len(COM_PORTS) < 1: showError("Unable to identify any usable com ports" , "Please ensure that your device is connected." ) sys.exit(15) # ------------------------------------------------------------------------------ # Default Values for Serial Connections