def _discover_devices(self):
comport_lst = list_ports.comports()
return {p.device: '{}, {}'. format(p.manufacturer, p.description) for p in comport_lst}
python类comports()的实例源码
def find_all_serial_ports():
"""
:return: a list of serial port info tuples
:rtype:
"""
all_ports = list_ports.comports()
return iter(all_ports)
def get_modems():
"""Return a list of modems plugged into the computer.
Switched to text mode.
"""
ports = list_ports.comports()
ports = [s.device for s in ports if s.device.startswith(pre)]
no1 = True if 'Modem' in ''.join(ports) else False
ports = [int(p.replace(pre, '')) for p in ports if p[-1].isdigit()]
ports = [(y, z) for x,y,z in seq(ports, 3)]
if no1: ports.append(('Modem', 'Pcui'))
modems, info = {}, []
for i, pair in enumerate(ports):
try:
modems[i] = humod.Modem(
pre+str(pair[0]),
pre+str(pair[1])
)
modems[i].enable_textmode(True)
except SerialException as e:
info.append(('Not connected.', str(e), i+1))
except OSError as e:
info.append(('Power off.', str(e), i+1))
except humod.errors.AtCommandError as e:
info.append(('', str(e), i+1))
del modems[i]
return modems, info
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
def dump_port_list():
if comports:
sys.stderr.write('\n--- Available ports:\n')
for port, desc, hwid in sorted(comports()):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- %-20s %s\n' % (port, desc))
def find_serial_port():
"""
tries to connect to all available serial ports, returns of first successful connection.
exit if none works
:return: serial interface object
"""
if settings.debug_port_detection:
for port in list_ports.comports():
print('trying {}'.format(port[0]))
return serial.Serial(settings.forced_port, settings.baud_rate, timeout=1)
else:
for port in (list_ports.comports()):
print('trying {}'.format(port[0]))
try:
serial_interface = serial.Serial(port[0], settings.baud_rate, timeout=2)
sleep(2) # wait for the device to be ready
# send hello command
serial_interface.write(settings.handshake_challenge)
# check if this device knows what to reply
reply = serial_interface.read(len(settings.handshake_response))
print(reply)
if reply == settings.handshake_response:
return serial_interface
except serial.SerialException:
# print("opening serial failed")
pass
raise ConnectionError("Couldn't connect to any serial ports, exiting...")
def get_available_ports():
ports = []
portlist = list_ports.comports()
if item_count(portlist) == 0:
return
iterator = sorted(list(portlist))
for port, desc, hwid in iterator:
ports.append((port, desc))
return ports
def search(self):
#Return the 1st board founded with Exode installed
logCore("Searching for a board...")
boardList=[]
# Search a port
if platform.system() == 'Windows':
ports = windows_ports()
elif platform.system() == 'Darwin':
ports = [i[0] for i in list_ports.comports()]
else:
ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*")
for p in ports:
try:
logCore("Try to connect to :"+p)
sr = serial.Serial(p, 9600)
except (serial.serialutil.SerialException, OSError) as e:
continue
time.sleep(2)
# This bit array execute the function checkExode()
# on the board
sr.write(bytearray([2, 0, ID('checkExode')]))
sr.flush()
time.sleep(0.25)
# the board should answer 202,404
ans= [0,0]
if sr.inWaiting()>0:
ans[0] = int.from_bytes(sr.read(), byteorder='little')
ans[1] = int.from_bytes(sr.read(4), byteorder='little', signed=False)
logCore(p+" answered "+str(ans))
if ans != [202,404]:
continue
else:
logCore("Arduino board detected with Exode at : "+p)
boardList.append(p)
return boardList
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
def deviceQuery(self):
try:
devices = comports()
for d in devices:
if len(d.hwid.split('PID')) > 1:
if d.hwid.split('PID')[1].split()[0][1:].lower() == self.device['identifier']:
self.device['port'] = d.device
return d.device
except Exception:
return None
return None
def find_microbit():
"""
Finds the port to which the device is connected.
"""
ports = list_serial_ports()
for port in ports:
if "VID:PID=0D28:0204" in port[2].upper():
return port[0]
return None
def get_coms(self):
close_fds = False if sys.platform == 'win32' else True
if sys.platform == 'win32':
cmd_subprc_pipe = subprocess.Popen("%s coms" % self._pjon_piper_path, shell=False, close_fds=close_fds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, startupinfo=self._startupinfo, env=os.environ)
else:
cmd_subprc_pipe = subprocess.Popen([self._pjon_piper_path, "coms"], shell=False, close_fds=close_fds,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
bufsize=0, env=os.environ)
coms = []
#log.debug(">> cmd pipe out")
while cmd_subprc_pipe:
try:
nex_tline = cmd_subprc_pipe.stdout.readline()
if nex_tline == '':
break
#log.debug(nex_tline.strip())
if self.is_string_valid_com_port_name(nex_tline.strip()):
#log.debug("\_got a com port in the stdout")
coms.append(nex_tline.strip())
else:
pass
#log.error("suspicious COM name in the output: %s" % nex_tline.strip())
except AttributeError:
pass
#log.debug("<< cmd pipe out")
cmd_subprc_pipe.terminate()
if coms == []:
log.warn("PJON-piper returned no serial ports; falling back to pyserial to enumerate available serials")
from serial.tools import list_ports
if sys.platform == 'win32':
coms = [item.device for item in list_ports.comports()]
elif sys.platform == 'linux2':
coms = [item[0] for item in list_ports.comports()]
return coms
def setupAvailablePorts(self):
"""
Purpose:
Determine what ports are available for serial reading and populate the combo box with these options
Input:
None
Output:
None
"""
self.comboBox_serialPort.clear()
listPortInfoObjects = list_ports.comports()
portNames = [x[0] for x in listPortInfoObjects]
self.comboBox_serialPort.addItems(portNames)
def serial_port():
def ok():
global ser, port
port = var.get()
port = port.split(' - ')
bracket = '(\''
port_str_index = port[0].find(bracket)
if port_str_index != -1:
port[0] = (port[0])[port_str_index + 2:]
ser = serial.Serial(port[0], 115200)
win.destroy()
global win
win = Tk()
win.wm_title('Choose a Serial Port')
var = StringVar(win)
var.set("Select the port your Arduino is connected to")
ports = list(list_ports.comports())
option = OptionMenu(win, var, ports)
option.pack(side='left')
button = Button(win, text="OK", command=ok)
button.pack()
win.wm_protocol("WM_DELETE_WINDOW", window_exit)
win.mainloop()
# Wait for Arduino to respond
def available_hosts(cls):
return list(p.device for p in comports()
if p.manufacturer in white_list)
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
def list_serial_ports():
"""Prints the open serial ports line per line"""
warn("list_serial_ports now deprecated, use print_all_serial_ports instead", DeprecationWarning)
ports = comports()
for port in ports:
print(port)
def print_all_serial_ports():
"""Prints the open serial ports line per line"""
ports = comports()
for port in ports:
print(port)
def get_serial_ports():
"""Returns the open serial ports"""
return comports()
def list_com_ports(self):
"""
Returns list of com ports found on the system.
This is thin-wrapper of serial.tools.list_ports.
Returned list consists of possible ListPortInfo instances.
You may access attributes of ListPortInfo by extended variable
syntax, e.g.::
@{ports} = List Com Ports
Log ${ports[0].device}
"""
return comports()