Skip to content

Commit 3989047

Browse files
committed
chore: refactor serial port selection
Signed-off-by: Maximilian Deubel <[email protected]>
1 parent 7b965de commit 3989047

File tree

4 files changed

+110
-252
lines changed

4 files changed

+110
-252
lines changed

src/nrfcloud_utils/claim_and_provision_device.py

Lines changed: 5 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from serial.tools import list_ports
2323
from cryptography import x509
2424
from cryptography.hazmat.primitives import serialization
25+
from nrfcloud_utils.nordic_boards import ask_for_port
2526

2627
full_encoding = 'mbcs' if is_windows else 'ascii'
2728
serial_timeout = 1
@@ -114,79 +115,6 @@ def parse_args(in_args):
114115
args = parser.parse_args(in_args)
115116
return args
116117

117-
def ask_for_port(selected_port, list_all, verbose):
118-
"""
119-
Show a list of ports and ask the user for a choice, unless user specified
120-
a specific port on the command line. To make selection easier on systems
121-
with long device names, also allow the input of an index.
122-
"""
123-
ports = []
124-
dev_types = []
125-
126-
if selected_port == None and not list_all:
127-
pattern = r'SER=(' + r'|'.join(name[0] for name in usb_patterns) + r')'
128-
print(send_style('Available ports:'))
129-
else:
130-
pattern = r''
131-
132-
port_num = 1
133-
for n, (port, desc, hwid) in enumerate(sorted(list_ports.grep(pattern)), 1):
134-
135-
if not is_macos:
136-
# if a specific port is not requested, filter out ports with
137-
# LOCATION in hwid that do not end in '.0' because these are
138-
# usually not the logging or shell ports
139-
if selected_port == None and not list_all and 'LOCATION' in hwid:
140-
if hwid[-2] != '.' or hwid[-1] != '0':
141-
if verbose:
142-
print(send_style('Skipping: {:2}: {:20} {!r} {!r}'.
143-
format(port_num, port, desc, hwid)))
144-
continue
145-
else:
146-
# if a specific port not requested, filter out ports whose /dev
147-
# does not end in a 1
148-
if selected_port == None and not list_all and port[-1] != '1':
149-
if verbose:
150-
print(send_style('Skipping: {:2}: {:20} {!r} {!r}'.
151-
format(port_num, port, desc, hwid)))
152-
continue
153-
154-
name = ''
155-
for nm in usb_patterns:
156-
if nm[0] in hwid:
157-
name = nm[1]
158-
break
159-
160-
if selected_port != None:
161-
if selected_port == port:
162-
return port
163-
else:
164-
print(send_style('{:2}: {:20} {:17}'.format(port_num, port, name)))
165-
if verbose:
166-
print(send_style(' {!r} {!r}'.format(desc, hwid)))
167-
168-
ports.append(port)
169-
dev_types.append(False)
170-
port_num += 1
171-
172-
if len(ports) == 0:
173-
sys.stderr.write(error_style('No device found\n'))
174-
return None
175-
if len(ports) == 1:
176-
return ports[0]
177-
while True:
178-
port = input('--- Enter port index: ')
179-
try:
180-
index = int(port) - 1
181-
if not 0 <= index < len(ports):
182-
sys.stderr.write(error_style('--- Invalid index!\n'))
183-
continue
184-
except ValueError:
185-
pass
186-
else:
187-
port = ports[index]
188-
return port
189-
190118
def write_line(line, hidden = False):
191119
if not hidden:
192120
print(send_style('-> {}'.format(line)))
@@ -388,7 +316,10 @@ def main(in_args):
388316

389317
# get a serial port to use
390318
print(local_style('Opening serial port...'))
391-
port = ask_for_port(args.port, args.all, args.verbose)
319+
if args.port:
320+
port = args.port
321+
else:
322+
port = ask_for_port(args.all)
392323
if port == None:
393324
sys.exit(1)
394325

src/nrfcloud_utils/device_credentials_installer.py

Lines changed: 5 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from nrfcloud_utils import create_device_credentials, ca_certs, rtt_interface
1616
from nrfcloud_utils.cli_helpers import error_style, local_style, send_style, hivis_style, init_colorama, cli_disable_styles, write_file, save_devinfo_csv, save_onboarding_csv, is_linux, is_windows, is_macos, full_encoding
1717
from nrfcloud_utils.command_interface import ATCommandInterface, ATKeygenException, TLSCredShellInterface
18-
from nrfcloud_utils.nordic_boards import usb_patterns
18+
from nrfcloud_utils.nordic_boards import ask_for_port
1919

2020
from serial.tools import list_ports
2121
from cryptography import x509
@@ -158,83 +158,6 @@ def parse_args(in_args):
158158
args = parser.parse_args(in_args)
159159
return args
160160

161-
162-
def ask_for_port(selected_port, list_all):
163-
"""
164-
Show a list of ports and ask the user for a choice, unless user specified
165-
a specific port on the command line. To make selection easier on systems
166-
with long device names, also allow the input of an index.
167-
"""
168-
global is_gateway
169-
ports = []
170-
dev_types = []
171-
172-
if selected_port == None and not list_all:
173-
pattern = r'SER=(' + r'|'.join(name[0] for name in usb_patterns) + r')'
174-
print(local_style('Available ports:'))
175-
else:
176-
pattern = r''
177-
178-
port_num = 1
179-
for n, (port, desc, hwid) in enumerate(sorted(list_ports.grep(pattern)), 1):
180-
181-
if not is_macos:
182-
# if a specific port is not requested, filter out ports with
183-
# LOCATION in hwid that do not end in '.0' because these are
184-
# usually not the logging or shell ports
185-
if selected_port == None and not list_all and 'LOCATION' in hwid:
186-
if hwid[-2] != '.' or hwid[-1] != '0':
187-
if verbose:
188-
print(local_style('Skipping: {:2}: {:20} {!r} {!r}'.
189-
format(port_num, port, desc, hwid)))
190-
continue
191-
else:
192-
# if a specific port not requested, filter out ports whose /dev
193-
# does not end in a 1
194-
if selected_port == None and not list_all and port[-1] != '1':
195-
if verbose:
196-
print(local_style('Skipping: {:2}: {:20} {!r} {!r}'.
197-
format(port_num, port, desc, hwid)))
198-
continue
199-
200-
name = ''
201-
is_gateway = False
202-
for nm in usb_patterns:
203-
if nm[0] in hwid:
204-
name = nm[1]
205-
is_gateway = nm[2]
206-
break
207-
208-
if selected_port != None:
209-
if selected_port == port:
210-
return port
211-
else:
212-
print(local_style('{:2}: {:20} {:17}'.format(port_num, port, name)))
213-
if verbose:
214-
print(local_style(' {!r} {!r}'.format(desc, hwid)))
215-
216-
ports.append(port)
217-
dev_types.append(is_gateway)
218-
port_num += 1
219-
220-
if len(ports) == 0:
221-
sys.stderr.write(error_style('No device found\n'))
222-
return None
223-
if len(ports) == 1:
224-
return ports[0]
225-
while True:
226-
port = input('--- Enter port index: ')
227-
try:
228-
index = int(port) - 1
229-
if not 0 <= index < len(ports):
230-
sys.stderr.write(error_style('--- Invalid index!\n'))
231-
continue
232-
except ValueError:
233-
pass
234-
else:
235-
port = ports[index]
236-
return port
237-
238161
def write_line(line, hidden = False):
239162
global cmd_term_key
240163
if not hidden:
@@ -482,7 +405,10 @@ def main(in_args):
482405
ser = None
483406
else:
484407
# get a serial port to use
485-
port = ask_for_port(args.port, args.all)
408+
if args.port:
409+
port = args.port
410+
else:
411+
port = ask_for_port(args.all)
486412
if port == None:
487413
sys.exit(4)
488414

src/nrfcloud_utils/gather_attestation_tokens.py

Lines changed: 13 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import platform
1414
from nrfcloud_utils import modem_credentials_parser, rtt_interface
1515
from nrfcloud_utils.cli_helpers import is_linux, is_windows, is_macos
16-
from nrfcloud_utils.nordic_boards import usb_patterns
16+
from nrfcloud_utils.nordic_boards import ask_for_port
1717
from serial.tools import list_ports
1818
from datetime import datetime, timezone
1919
from colorama import init, Fore, Back, Style
@@ -106,79 +106,6 @@ def send_style(line):
106106
def error_style(line):
107107
return ensure_lf(Fore.RED + line + Style.RESET_ALL) if not plain else line
108108

109-
def ask_for_port(selected_port, list_all):
110-
"""
111-
Show a list of ports and ask the user for a choice, unless user specified
112-
a specific port on the command line. To make selection easier on systems
113-
with long device names, also allow the input of an index.
114-
"""
115-
ports = []
116-
dev_types = []
117-
118-
if selected_port == None and not list_all:
119-
pattern = r'SER=(' + r'|'.join(name[0] for name in usb_patterns) + r')'
120-
print(send_style('Available ports:'))
121-
else:
122-
pattern = r''
123-
124-
port_num = 1
125-
for n, (port, desc, hwid) in enumerate(sorted(list_ports.grep(pattern)), 1):
126-
127-
if not is_macos:
128-
# if a specific port is not requested, filter out ports with
129-
# LOCATION in hwid that do not end in '.0' because these are
130-
# usually not the logging or shell ports
131-
if selected_port == None and not list_all and 'LOCATION' in hwid:
132-
if hwid[-2] != '.' or hwid[-1] != '0':
133-
if verbose:
134-
print(send_style('Skipping: {:2}: {:20} {!r} {!r}'.
135-
format(port_num, port, desc, hwid)))
136-
continue
137-
else:
138-
# if a specific port not requested, filter out ports whose /dev
139-
# does not end in a 1
140-
if selected_port == None and not list_all and port[-1] != '1':
141-
if verbose:
142-
print(send_style('Skipping: {:2}: {:20} {!r} {!r}'.
143-
format(port_num, port, desc, hwid)))
144-
continue
145-
146-
name = ''
147-
for nm in usb_patterns:
148-
if nm[0] in hwid:
149-
name = nm[1]
150-
break
151-
152-
if selected_port != None:
153-
if selected_port == port:
154-
return port
155-
else:
156-
print(send_style('{:2}: {:20} {:17}'.format(port_num, port, name)))
157-
if verbose:
158-
print(send_style(' {!r} {!r}'.format(desc, hwid)))
159-
160-
ports.append(port)
161-
dev_types.append(False)
162-
port_num += 1
163-
164-
if len(ports) == 0:
165-
sys.stderr.write(error_style('No device found\n'))
166-
return None
167-
if len(ports) == 1:
168-
return ports[0]
169-
while True:
170-
port = input('--- Enter port index: ')
171-
try:
172-
index = int(port) - 1
173-
if not 0 <= index < len(ports):
174-
sys.stderr.write(error_style('--- Invalid index!\n'))
175-
continue
176-
except ValueError:
177-
pass
178-
else:
179-
port = ports[index]
180-
return port
181-
182109
def write_line(line, hidden = False):
183110
global cmd_term_key
184111
if not hidden:
@@ -412,22 +339,25 @@ def main(in_args):
412339
else:
413340
# get a serial port to use
414341
print(local_style('Opening serial port...'))
415-
port = ask_for_port(args.port, args.all)
342+
if args.port:
343+
port = args.port
344+
else:
345+
port = ask_for_port(args.all)
416346
if port == None:
417-
sys.exit(1)
347+
sys.exit(1)
418348

419349
print(local_style('Selected serial port: {}'.format(port)))
420350

421351
# try to open the serial port
422352
try:
423-
ser = serial.Serial(port, args.baud, xonxoff= args.xonxoff, rtscts=(not args.rtscts_off),
424-
dsrdtr=args.dsrdtr, timeout=serial_timeout)
425-
ser.reset_output_buffer()
426-
write_line('')
427-
time.sleep(0.2)
428-
ser.reset_input_buffer()
353+
ser = serial.Serial(port, args.baud, xonxoff= args.xonxoff, rtscts=(not args.rtscts_off),
354+
dsrdtr=args.dsrdtr, timeout=serial_timeout)
355+
ser.reset_output_buffer()
356+
write_line('')
357+
time.sleep(0.2)
358+
ser.reset_input_buffer()
429359
except serial.serialutil.SerialException:
430-
error_exit('Port could not be opened; not a device, or open already')
360+
error_exit('Port could not be opened; not a device, or open already')
431361

432362
# get attestation token
433363
attest_tok = get_attestation_token()

0 commit comments

Comments
 (0)