cli.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. # Adafruit MicroPython Tool - Command Line Interface
  2. # Author: Tony DiCola
  3. # Copyright (c) 2016 Adafruit Industries
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. #
  23. # Change Logs:
  24. # Date Author Notes
  25. # 2019-10-10 SummerGift Improve the code architecture
  26. from __future__ import print_function
  27. import os
  28. import platform
  29. import posixpath
  30. import re
  31. import serial
  32. import serial.serialutil
  33. import serial.tools.list_ports
  34. import threading
  35. import click
  36. import dotenv
  37. import sys
  38. import time
  39. import hashlib
  40. import json
  41. import ampy.files as files
  42. import ampy.pyboard as pyboard
  43. import gc
  44. from ampy.getch import getch
  45. from ampy.file_sync import file_sync_info
  46. from ampy.file_sync import _get_file_crc32
  47. from ampy.pyboard import stdout
  48. # Load AMPY_PORT et al from .ampy file
  49. # Performed here because we need to beat click's decorators.
  50. config = dotenv.find_dotenv(filename=".ampy", usecwd=True)
  51. if config:
  52. dotenv.load_dotenv(dotenv_path=config)
  53. serial_reader_running = None
  54. serial_out_put_enable = True
  55. serial_out_put_count = 0
  56. _board = None
  57. _system = None
  58. class CliError(BaseException):
  59. pass
  60. def windows_full_port_name(portname):
  61. # Helper function to generate proper Windows COM port paths. Apparently
  62. # Windows requires COM ports above 9 to have a special path, where ports below
  63. # 9 are just referred to by COM1, COM2, etc. (wacky!) See this post for
  64. # more info and where this code came from:
  65. # http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/
  66. m = re.match("^COM(\d+)$", portname)
  67. if m and int(m.group(1)) < 10:
  68. return portname
  69. else:
  70. return "\\\\.\\{0}".format(portname)
  71. @click.group()
  72. @click.option(
  73. "--port",
  74. "-p",
  75. envvar="AMPY_PORT",
  76. required=True,
  77. type=click.STRING,
  78. help="Name of serial port for connected board. Can optionally specify with AMPY_PORT environment variable.",
  79. metavar="PORT",
  80. )
  81. @click.option(
  82. "--baud",
  83. "-b",
  84. envvar="AMPY_BAUD",
  85. default=115200,
  86. type=click.INT,
  87. help="Baud rate for the serial connection (default 115200). Can optionally specify with AMPY_BAUD environment variable.",
  88. metavar="BAUD",
  89. )
  90. @click.option(
  91. "--delay",
  92. "-d",
  93. envvar="AMPY_DELAY",
  94. default=0,
  95. type=click.FLOAT,
  96. help="Delay in seconds before entering RAW MODE (default 0). Can optionally specify with AMPY_DELAY environment variable.",
  97. metavar="DELAY",
  98. )
  99. @click.version_option()
  100. def cli(port, baud, delay):
  101. """ampy - Adafruit MicroPython Tool
  102. Ampy is a tool to control MicroPython boards over a serial connection. Using
  103. ampy you can manipulate files on the board's internal filesystem and even run
  104. scripts.
  105. """
  106. global _board
  107. global _system
  108. if platform.system() == "Windows":
  109. _system = "Windows"
  110. if platform.system() == "Linux":
  111. _system = "Linux"
  112. if port != "query":
  113. # On Windows fix the COM port path name for ports above 9 (see comment in
  114. # windows_full_port_name function).
  115. if platform.system() == "Windows":
  116. port = windows_full_port_name(port)
  117. _board = pyboard.Pyboard(port, baudrate=baud, rawdelay=delay)
  118. @cli.command()
  119. @click.argument("remote_file")
  120. @click.argument("local_file", type=click.File("wb"), required=False)
  121. def get(remote_file, local_file):
  122. """
  123. Retrieve a file from the board.
  124. Get will download a file from the board and print its contents or save it
  125. locally. You must pass at least one argument which is the path to the file
  126. to download from the board. If you don't specify a second argument then
  127. the file contents will be printed to standard output. However if you pass
  128. a file name as the second argument then the contents of the downloaded file
  129. will be saved to that file (overwriting anything inside it!).
  130. For example to retrieve the boot.py and print it out run:
  131. ampy --port /board/serial/port get boot.py
  132. Or to get main.py and save it as main.py locally run:
  133. ampy --port /board/serial/port get main.py main.py
  134. """
  135. # Get the file contents.
  136. board_files = files.Files(_board)
  137. contents = board_files.get(remote_file)
  138. # Print the file out if no local file was provided, otherwise save it.
  139. if local_file is None:
  140. print(contents.decode("utf-8"))
  141. else:
  142. local_file.write(contents)
  143. @cli.command()
  144. @click.option(
  145. "--exists-okay", is_flag=True, help="Ignore if the directory already exists."
  146. )
  147. @click.argument("directory")
  148. def mkdir(directory, exists_okay):
  149. """
  150. Create a directory on the board.
  151. Mkdir will create the specified directory on the board. One argument is
  152. required, the full path of the directory to create.
  153. Note that you cannot recursively create a hierarchy of directories with one
  154. mkdir command, instead you must create each parent directory with separate
  155. mkdir command calls.
  156. For example to make a directory under the root called 'code':
  157. ampy --port /board/serial/port mkdir /code
  158. """
  159. # Run the mkdir command.
  160. board_files = files.Files(_board)
  161. board_files.mkdir(directory, exists_okay=exists_okay)
  162. @cli.command()
  163. @click.argument("directory", default="/")
  164. @click.option(
  165. "--long_format",
  166. "-l",
  167. is_flag=True,
  168. help="Print long format info including size of files. Note the size of directories is not supported and will show 0 values.",
  169. )
  170. @click.option(
  171. "--recursive",
  172. "-r",
  173. is_flag=True,
  174. help="recursively list all files and (empty) directories.",
  175. )
  176. def ls(directory, long_format, recursive):
  177. """List contents of a directory on the board.
  178. Can pass an optional argument which is the path to the directory. The
  179. default is to list the contents of the root, /, path.
  180. For example to list the contents of the root run:
  181. ampy --port /board/serial/port ls
  182. Or to list the contents of the /foo/bar directory on the board run:
  183. ampy --port /board/serial/port ls /foo/bar
  184. Add the -l or --long_format flag to print the size of files (however note
  185. MicroPython does not calculate the size of folders and will show 0 bytes):
  186. ampy --port /board/serial/port ls -l /foo/bar
  187. """
  188. # List each file/directory on a separate line.
  189. board_files = files.Files(_board)
  190. for f in board_files.ls(directory, long_format=long_format, recursive=recursive):
  191. print(f)
  192. @cli.command()
  193. @click.argument("local", type=click.Path(exists=True))
  194. @click.argument("remote", required=False)
  195. def put(local, remote):
  196. """Put a file or folder and its contents on the board.
  197. Put will upload a local file or folder to the board. If the file already
  198. exists on the board it will be overwritten with no warning! You must pass
  199. at least one argument which is the path to the local file/folder to
  200. upload. If the item to upload is a folder then it will be copied to the
  201. board recursively with its entire child structure. You can pass a second
  202. optional argument which is the path and name of the file/folder to put to
  203. on the connected board.
  204. For example to upload a main.py from the current directory to the board's
  205. root run:
  206. ampy --port /board/serial/port put main.py
  207. Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py
  208. in the board's root run:
  209. ampy --port /board/serial/port put ./foo/board_boot.py boot.py
  210. To upload a local folder adafruit_library and all of its child files/folders
  211. as an item under the board's root run:
  212. ampy --port /board/serial/port put adafruit_library
  213. Or to put a local folder adafruit_library on the board under the path
  214. /lib/adafruit_library on the board run:
  215. ampy --port /board/serial/port put adafruit_library /lib/adafruit_library
  216. """
  217. # Use the local filename if no remote filename is provided.
  218. if remote is None:
  219. remote = os.path.basename(os.path.abspath(local))
  220. # Check if path is a folder and do recursive copy of everything inside it.
  221. # Otherwise it's a file and should simply be copied over.
  222. if os.path.isdir(local):
  223. # Directory copy, create the directory and walk all children to copy
  224. # over the files.
  225. dir_del_flag = True
  226. board_files = files.Files(_board)
  227. for parent, child_dirs, child_files in os.walk(local):
  228. # Create board filesystem absolute path to parent directory.
  229. remote_parent = posixpath.normpath(
  230. posixpath.join(remote, os.path.relpath(parent, local))
  231. )
  232. try:
  233. # if dir already exist, remove that dir, only perform once.
  234. if dir_del_flag:
  235. board_files.rmdir(remote_parent, missing_okay=True)
  236. dir_del_flag = False
  237. # Create remote parent directory.
  238. board_files.mkdir(remote_parent)
  239. # Loop through all the files and put them on the board too.
  240. for filename in child_files:
  241. with open(os.path.join(parent, filename), "rb") as infile:
  242. remote_filename = posixpath.join(remote_parent, filename)
  243. board_files.put(remote_filename, infile.read())
  244. except files.DirectoryExistsError:
  245. # Ignore errors for directories that already exist.
  246. pass
  247. else:
  248. # File copy, open the file and copy its contents to the board.
  249. # Put the file on the board.
  250. with open(local, "rb") as infile:
  251. board_files = files.Files(_board)
  252. board_files.put(remote, infile.read())
  253. @cli.command()
  254. @click.argument("remote_file")
  255. def rm(remote_file):
  256. """Remove a file from the board.
  257. Remove the specified file from the board's filesystem. Must specify one
  258. argument which is the path to the file to delete. Note that this can't
  259. delete directories which have files inside them, but can delete empty
  260. directories.
  261. For example to delete main.py from the root of a board run:
  262. ampy --port /board/serial/port rm main.py
  263. """
  264. # Delete the provided file/directory on the board.
  265. board_files = files.Files(_board)
  266. board_files.rm(remote_file)
  267. @cli.command()
  268. @click.option(
  269. "--missing-okay", is_flag=True, help="Ignore if the directory does not exist."
  270. )
  271. @click.argument("remote_folder")
  272. def rmdir(remote_folder, missing_okay):
  273. """Forcefully remove a folder and all its children from the board.
  274. Remove the specified folder from the board's filesystem. Must specify one
  275. argument which is the path to the folder to delete. This will delete the
  276. directory and ALL of its children recursively, use with caution!
  277. For example to delete everything under /adafruit_library from the root of a
  278. board run:
  279. ampy --port /board/serial/port rmdir adafruit_library
  280. """
  281. # Delete the provided file/directory on the board.
  282. board_files = files.Files(_board)
  283. board_files.rmdir(remote_folder, missing_okay=missing_okay)
  284. @cli.command()
  285. @click.argument("local_file")
  286. @click.option(
  287. "--no-output",
  288. "-n",
  289. is_flag=True,
  290. help="Run the code without waiting for it to finish and print output. Use this when running code with main loops that never return.",
  291. )
  292. @click.option(
  293. "--device_file",
  294. "-d",
  295. envvar="run file in device",
  296. default=0,
  297. type=click.STRING,
  298. help="run file in device",
  299. metavar="run file in device",
  300. )
  301. def run(local_file, no_output, device_file):
  302. """Run a script and print its output.
  303. Run will send the specified file to the board and execute it immediately.
  304. Any output from the board will be printed to the console (note that this is
  305. not a 'shell' and you can't send input to the program).
  306. Note that if your code has a main or infinite loop you should add the --no-output
  307. option. This will run the script and immediately exit without waiting for
  308. the script to finish and print output.
  309. For example to run a test.py script and print any output after it finishes:
  310. ampy --port /board/serial/port run test.py
  311. Or to run test.py and not wait for it to finish:
  312. ampy --port /board/serial/port run --no-output test.py
  313. """
  314. # Run the provided file and print its output.
  315. board_files = files.Files(_board)
  316. try:
  317. if device_file:
  318. output = board_files.run_in_device(device_file, not no_output)
  319. else:
  320. output = board_files.run(local_file, not no_output)
  321. if output is not None:
  322. print(output.decode("utf-8"), end="")
  323. except IOError:
  324. click.echo(
  325. "Failed to find or read input file: {0}".format(local_file), err=True
  326. )
  327. @cli.command()
  328. @click.option(
  329. "--bootloader", "mode", flag_value="BOOTLOADER", help="Reboot into the bootloader"
  330. )
  331. @click.option(
  332. "--hard",
  333. "mode",
  334. flag_value="NORMAL",
  335. help="Perform a hard reboot, including running init.py",
  336. )
  337. @click.option(
  338. "--repl",
  339. "mode",
  340. flag_value="SOFT",
  341. default=True,
  342. help="Perform a soft reboot, entering the REPL [default]",
  343. )
  344. @click.option(
  345. "--safe",
  346. "mode",
  347. flag_value="SAFE_MODE",
  348. help="Perform a safe-mode reboot. User code will not be run and the filesystem will be writeable over USB",
  349. )
  350. def reset(mode):
  351. """Perform soft reset/reboot of the board.
  352. Will connect to the board and perform a reset. Depending on the board
  353. and firmware, several different types of reset may be supported.
  354. ampy --port /board/serial/port reset
  355. """
  356. _board.enter_raw_repl()
  357. if mode == "SOFT":
  358. _board.exit_raw_repl()
  359. return
  360. _board.exec_(
  361. """if 1:
  362. def on_next_reset(x):
  363. try:
  364. import microcontroller
  365. except:
  366. if x == 'NORMAL': return ''
  367. return 'Reset mode only supported on CircuitPython'
  368. try:
  369. microcontroller.on_next_reset(getattr(microcontroller.RunMode, x))
  370. except ValueError as e:
  371. return str(e)
  372. return ''
  373. def reset():
  374. try:
  375. import microcontroller
  376. except:
  377. import machine as microcontroller
  378. microcontroller.reset()
  379. """
  380. )
  381. r = _board.eval("on_next_reset({})".format(repr(mode)))
  382. print("here we are", repr(r))
  383. if r:
  384. click.echo(r, err=True)
  385. return
  386. try:
  387. _board.exec_("reset()")
  388. except serial.serialutil.SerialException as e:
  389. # An error is expected to occur, as the board should disconnect from
  390. # serial when restarted via microcontroller.reset()
  391. pass
  392. def repl_serial_to_stdout(serial):
  393. global _system
  394. global serial_out_put_count
  395. def hexsend(string_data=''):
  396. hex_data = string_data.decode("hex")
  397. return hex_data
  398. try:
  399. data = b''
  400. while serial_reader_running:
  401. count = serial.inWaiting()
  402. if count == 0:
  403. time.sleep(0.01)
  404. continue
  405. if count > 0:
  406. try:
  407. data += serial.read(count)
  408. if len(data) < 20:
  409. try:
  410. data.decode()
  411. except UnicodeDecodeError:
  412. continue
  413. if data != b'':
  414. if serial_out_put_enable and serial_out_put_count > 0:
  415. if _system == "Linux":
  416. sys.stdout.buffer.write(data)
  417. else:
  418. sys.stdout.buffer.write(data.replace(b"\r", b""))
  419. sys.stdout.buffer.flush()
  420. else:
  421. serial.write(hexsend(data))
  422. data = b''
  423. serial_out_put_count += 1
  424. except serial.serialutil.SerialException:
  425. # This happens if the pyboard reboots, or a USB port
  426. # goes away.
  427. return
  428. except TypeError:
  429. # This is a bug in serialposix.py starting with python 3.3
  430. # which causes a TypeError during the handling of the
  431. # select.error. So we treat this the same as
  432. # serial.serialutil.SerialException:
  433. return
  434. except ConnectionResetError:
  435. # This happens over a telnet session, if it resets
  436. return
  437. except KeyboardInterrupt:
  438. if serial != None:
  439. serial.close()
  440. @cli.command()
  441. @click.option(
  442. "--query",
  443. "-q",
  444. envvar="query_is_can_be_connected",
  445. # required=True,
  446. default=None,
  447. type=click.STRING,
  448. help="Query whether the com port can be connected",
  449. metavar="query",
  450. )
  451. def repl(query = None):
  452. global serial_reader_running
  453. global serial_out_put_enable
  454. global serial_out_put_count
  455. serial_out_put_count = 1
  456. serial_reader_running = True
  457. if query != None:
  458. return
  459. _board.read_until_hit()
  460. serial = _board.serial
  461. repl_thread = threading.Thread(target = repl_serial_to_stdout, args=(serial,), name='REPL_serial_to_stdout')
  462. repl_thread.daemon = True
  463. repl_thread.start()
  464. try:
  465. # Wake up the prompt
  466. serial.write(b'\r')
  467. count = 0
  468. while True:
  469. char = getch()
  470. if char == b'\x16':
  471. char = b'\x03'
  472. count += 1
  473. if count == 1000:
  474. time.sleep(0.1)
  475. count = 0
  476. if char == b'\x07':
  477. serial_out_put_enable = False
  478. continue
  479. if char == b'\x0F':
  480. serial_out_put_enable = True
  481. serial_out_put_count = 0
  482. continue
  483. if char == b'\x00':
  484. continue
  485. if not char:
  486. continue
  487. if char == b'\x18': # enter ctrl + x to exit repl mode
  488. serial_reader_running = False
  489. # When using telnet with the WiPy, it doesn't support
  490. # an initial timeout. So for the meantime, we send a
  491. # space which should cause the wipy to echo back a
  492. # space which will wakeup our reader thread so it will
  493. # notice the quit.
  494. serial.write(b' ')
  495. # Give the reader thread a chance to detect the quit
  496. # then we don't have to call getch() above again which
  497. # means we'd need to wait for another character.
  498. time.sleep(0.1)
  499. # Print a newline so that the rshell prompt looks good.
  500. print('')
  501. # We stay in the loop so that we can still enter
  502. # characters until we detect the reader thread quitting
  503. # (mostly to cover off weird states).
  504. return
  505. if char == b'\n':
  506. serial.write(b'\r')
  507. else:
  508. serial.write(char)
  509. except DeviceError as err:
  510. # The device is no longer present.
  511. self.print('')
  512. self.stdout.flush()
  513. print_err(err)
  514. print("exit repl")
  515. repl_thread.join()
  516. @cli.command()
  517. @click.option(
  518. "--local_path",
  519. "-l",
  520. envvar="local_path",
  521. required=True,
  522. default=0,
  523. type=click.STRING,
  524. help="local_path",
  525. metavar="local_path",
  526. )
  527. @click.option(
  528. "--file_pathname",
  529. "-f",
  530. envvar="file_pathname",
  531. required=True,
  532. default=0,
  533. type=click.STRING,
  534. help="file pathname",
  535. metavar="file_pathname",
  536. )
  537. @click.option(
  538. "--remote_path",
  539. "-r",
  540. envvar="remote_path",
  541. required=True,
  542. default=0,
  543. type=click.STRING,
  544. help="remote_path",
  545. metavar="remote_path",
  546. )
  547. @click.option(
  548. "--info_pathname",
  549. "-i",
  550. envvar="info_pathname",
  551. # required=True,
  552. default=None,
  553. type=click.STRING,
  554. help="info_pathname",
  555. metavar="info_pathname",
  556. )
  557. @click.option(
  558. "--query",
  559. "-q",
  560. envvar="query",
  561. # required=True,
  562. default=None,
  563. type=click.STRING,
  564. help="query",
  565. metavar="query",
  566. )
  567. def sync(local_path, file_pathname, remote_path = None, info_pathname = None, query = None):
  568. def _sync_file(sync_info, local, remote = None):
  569. local = local.replace('\\', '/')
  570. delete_file_list = sync_info["delete"]
  571. sync_file_list = sync_info["sync"]
  572. if delete_file_list == [] and sync_file_list == []:
  573. return
  574. board_files = files.Files(_board)
  575. # Directory copy, create the directory and walk all children to copy
  576. # over the files.
  577. for parent, child_dirs, child_files in os.walk(local):
  578. # Create board filesystem absolute path to parent directory.
  579. remote_parent = posixpath.normpath(
  580. posixpath.join(local, os.path.relpath(parent, local))
  581. )
  582. try:
  583. # Create remote parent directory.
  584. dir_name = remote_parent[len(local_path) + 1:]
  585. if dir_name != "":
  586. board_files.mkdir(dir_name)
  587. # Loop through all the files and put them on the board too.
  588. except files.DirectoryExistsError:
  589. # Ignore errors for directories that already exist.
  590. pass
  591. # add sync files
  592. for item in sync_file_list:
  593. # File copy, open the file and copy its contents to the board.
  594. # Put the file on the board.
  595. print("file to add:%s"%item)
  596. item_local = os.path.join(local_path, item).replace('\\', '/')
  597. with open(item_local, "rb") as infile:
  598. board_files = files.Files(_board)
  599. board_files.put(item, infile.read())
  600. # delete files
  601. for item in delete_file_list:
  602. # Delete the provided file/directory on the board.
  603. # board_files.rmdir(item, True)
  604. print("file to del:%s"%item)
  605. if item != '':
  606. board_files.rm(item)
  607. # check if need sync
  608. if query == "ifneedsync":
  609. if not os.path.exists(info_pathname):
  610. print("<file need sync>")
  611. else:
  612. # Gets file synchronization information
  613. sync_info, pc_file_info = file_sync_info(local_path, info_pathname)
  614. if sync_info['delete'] == [] and sync_info['sync'] == []:
  615. print("<no need to sync>")
  616. else:
  617. print("<file need sync>")
  618. return
  619. # check repl rtt uos
  620. _board.get_board_identity()
  621. if not _board.is_have_uos():
  622. raise PyboardError('Error: The uos module is not enabled')
  623. rtt_version_flag = False
  624. if _board.is_rtt_micropython():
  625. rtt_version_flag = True
  626. # ready to sync
  627. if info_pathname == None:
  628. info_pathname = "file_info.json"
  629. if not os.path.exists(info_pathname):
  630. # List each file/directory on a separate line.
  631. board_files = files.Files(_board)
  632. board_files._ls_sync(long_format=True, recursive=True, pathname = info_pathname)
  633. # Gets file synchronization information
  634. sync_info, pc_file_info = file_sync_info(local_path, info_pathname, rtt_version_flag)
  635. # print("sync_info------------------------------")
  636. # print(sync_info)
  637. # print("pc_file_info------------------------------")
  638. # print(pc_file_info)
  639. if sync_info['delete'] == [] and sync_info['sync'] == []:
  640. print("<no need to sync>")
  641. return
  642. try:
  643. # Perform file synchronization
  644. _sync_file(sync_info, local_path)
  645. except:
  646. raise CliError("error: _file_sync failed, please restart and retry.")
  647. # After successful file synchronization, update the local cache file information
  648. with open(info_pathname, 'w') as f:
  649. f.write(str(pc_file_info))
  650. _board.soft_reset_board()
  651. @cli.command()
  652. def portscan(port=None):
  653. """Scan all serial ports on your system."""
  654. port_list = list(serial.tools.list_ports.comports())
  655. if len(port_list) <= 0:
  656. print("can't find any serial in system.")
  657. else:
  658. print([list(port_list[i])[0] for i in range(0, len(port_list))])
  659. del port_list
  660. gc.collect()
  661. # os._exit(0)
  662. if __name__ == "__main__":
  663. try:
  664. cli()
  665. finally:
  666. # Try to ensure the board serial connection is always gracefully closed.
  667. if _board is not None:
  668. try:
  669. _board.close()
  670. except:
  671. # Swallow errors when attempting to close as it's just a best effort
  672. # and shouldn't cause a new error or problem if the connection can't
  673. # be closed.
  674. pass