main.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  3. """This module is the cli for the Uploader class"""
  4. from __future__ import print_function
  5. import argparse
  6. import logging
  7. import os
  8. import glob
  9. from .uploader import Uploader
  10. from .term import terminal
  11. from serial import VERSION as serialversion
  12. log = logging.getLogger(__name__) # pylint: disable=C0103
  13. from .version import __version__
  14. def destination_from_source(sources, use_glob=True):
  15. """
  16. Split each of the sources in the array on ':'
  17. First part will be source, second will be destination.
  18. Modifies the the original array to contain only sources
  19. and returns an array of destinations.
  20. """
  21. destinations = []
  22. newsources = []
  23. for i in range(0, len(sources)):
  24. srcdst = sources[i].split(':')
  25. if len(srcdst) == 2:
  26. destinations.append(srcdst[1])
  27. newsources.append(srcdst[0]) #proper list assignment
  28. else:
  29. if use_glob:
  30. listing = glob.glob(srcdst[0])
  31. for filename in listing:
  32. newsources.append(filename)
  33. #always use forward slash at destination
  34. destinations.append(filename.replace('\\', '/'))
  35. else:
  36. newsources.append(srcdst[0])
  37. destinations.append(srcdst[0])
  38. return [newsources, destinations]
  39. def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):
  40. """The upload operation"""
  41. sources, destinations = destination_from_source(sources)
  42. if len(destinations) == len(sources):
  43. if uploader.prepare():
  44. for filename, dst in zip(sources, destinations):
  45. if do_compile:
  46. uploader.file_remove(os.path.splitext(dst)[0]+'.lc')
  47. uploader.write_file(filename, dst, verify)
  48. #init.lua is not allowed to be compiled
  49. if do_compile and dst != 'init.lua':
  50. uploader.file_compile(dst)
  51. uploader.file_remove(dst)
  52. if do_file:
  53. uploader.file_do(os.path.splitext(dst)[0]+'.lc')
  54. elif do_file:
  55. uploader.file_do(dst)
  56. else:
  57. raise Exception('Error preparing nodemcu for reception')
  58. else:
  59. raise Exception('You must specify a destination filename for each file you want to upload.')
  60. if do_restart:
  61. uploader.node_restart()
  62. log.info('All done!')
  63. def operation_download(uploader, sources):
  64. """The download operation"""
  65. sources, destinations = destination_from_source(sources, False)
  66. print('sources', sources)
  67. print('destinations', destinations)
  68. if len(destinations) == len(sources):
  69. if uploader.prepare():
  70. for filename, dst in zip(sources, destinations):
  71. uploader.read_file(filename, dst)
  72. else:
  73. raise Exception('You must specify a destination filename for each file you want to download.')
  74. log.info('All done!')
  75. def operation_list(uploader):
  76. """List file on target"""
  77. files = uploader.file_list()
  78. for f in files:
  79. log.info("{file:30s} {size}".format(file=f[0], size=f[1]))
  80. def operation_file(uploader, cmd, filename=''):
  81. """File operations"""
  82. if cmd == 'list':
  83. operation_list(uploader)
  84. if cmd == 'do':
  85. for path in filename:
  86. uploader.file_do(path)
  87. elif cmd == 'format':
  88. uploader.file_format()
  89. elif cmd == 'remove':
  90. for path in filename:
  91. uploader.file_remove(path)
  92. elif cmd == 'print':
  93. for path in filename:
  94. uploader.file_print(path)
  95. def arg_auto_int(value):
  96. """parsing function for integer arguments"""
  97. return int(value, 0)
  98. def main_func():
  99. """Main function for cli"""
  100. parser = argparse.ArgumentParser(
  101. description='NodeMCU Lua file uploader',
  102. prog='nodemcu-uploader'
  103. )
  104. parser.add_argument(
  105. '--verbose',
  106. help='verbose output',
  107. action='store_true',
  108. default=False)
  109. parser.add_argument(
  110. '--version',
  111. help='prints the version and exists',
  112. action='version',
  113. version='%(prog)s {version} (serial {serialversion})'.format(version=__version__, serialversion=serialversion)
  114. )
  115. parser.add_argument(
  116. '--port', '-p',
  117. help='Serial port device',
  118. default=Uploader.PORT)
  119. parser.add_argument(
  120. '--baud', '-b',
  121. help='Serial port baudrate',
  122. type=arg_auto_int,
  123. default=Uploader.BAUD)
  124. parser.add_argument(
  125. '--start_baud', '-B',
  126. help='Initial Serial port baudrate',
  127. type=arg_auto_int,
  128. default=Uploader.START_BAUD)
  129. parser.add_argument(
  130. '--timeout', '-t',
  131. help='Timeout for operations',
  132. type=arg_auto_int,
  133. default=Uploader.TIMEOUT)
  134. parser.add_argument(
  135. '--autobaud_time', '-a',
  136. help='Duration of the autobaud timer',
  137. type=float,
  138. default=Uploader.AUTOBAUD_TIME,
  139. )
  140. subparsers = parser.add_subparsers(
  141. dest='operation',
  142. help='Run nodemcu-uploader {command} -h for additional help')
  143. backup_parser = subparsers.add_parser(
  144. 'backup',
  145. help='Backup all the files on the nodemcu board')
  146. backup_parser.add_argument('path', help='Folder where to store the backup')
  147. upload_parser = subparsers.add_parser(
  148. 'upload',
  149. help='Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  150. upload_parser.add_argument(
  151. 'filename',
  152. nargs='+',
  153. help='Lua file to upload. Use colon to give alternate destination.'
  154. )
  155. upload_parser.add_argument(
  156. '--compile', '-c',
  157. help='If file should be uploaded as compiled',
  158. action='store_true',
  159. default=False
  160. )
  161. upload_parser.add_argument(
  162. '--verify', '-v',
  163. help='To verify the uploaded data.',
  164. action='store',
  165. nargs='?',
  166. choices=['none', 'raw', 'sha1'],
  167. default='none'
  168. )
  169. upload_parser.add_argument(
  170. '--dofile', '-e',
  171. help='If file should be run after upload.',
  172. action='store_true',
  173. default=False
  174. )
  175. upload_parser.add_argument(
  176. '--restart', '-r',
  177. help='If esp should be restarted',
  178. action='store_true',
  179. default=False
  180. )
  181. exec_parser = subparsers.add_parser(
  182. 'exec',
  183. help='Path to one or more files to be executed line by line.')
  184. exec_parser.add_argument('filename', nargs='+', help='Lua file to execute.')
  185. download_parser = subparsers.add_parser(
  186. 'download',
  187. help='Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  188. download_parser.add_argument('filename',
  189. nargs='+',
  190. help='Lua file to download. Use colon to give alternate destination.')
  191. file_parser = subparsers.add_parser(
  192. 'file',
  193. help='File functions')
  194. file_parser.add_argument(
  195. 'cmd',
  196. choices=('list', 'do', 'format', 'remove', 'print'),
  197. help="list=list files, do=dofile given path, format=formate file area, remove=remove given path")
  198. file_parser.add_argument('filename', nargs='*', help='path for cmd')
  199. node_parse = subparsers.add_parser(
  200. 'node',
  201. help='Node functions')
  202. node_parse.add_argument('ncmd', choices=('heap', 'restart'), help="heap=print heap memory, restart=restart nodemcu")
  203. subparsers.add_parser(
  204. 'terminal',
  205. help='Run pySerials miniterm'
  206. )
  207. args = parser.parse_args()
  208. default_level = logging.INFO
  209. if args.verbose:
  210. default_level = logging.DEBUG
  211. #formatter = logging.Formatter('%(message)s')
  212. logging.basicConfig(level=default_level, format='%(message)s')
  213. if args.operation == 'terminal':
  214. #uploader can not claim the port
  215. terminal(args.port, str(args.start_baud))
  216. return
  217. # let uploader user the default (short) timeout for establishing connection
  218. uploader = Uploader(args.port, args.baud, start_baud=args.start_baud, autobaud_time=args.autobaud_time)
  219. # and reset the timeout (if we have the uploader&timeout)
  220. if args.timeout:
  221. uploader.set_timeout(args.timeout)
  222. if args.operation == 'upload':
  223. operation_upload(uploader, args.filename, args.verify, args.compile, args.dofile,
  224. args.restart)
  225. elif args.operation == 'download':
  226. operation_download(uploader, args.filename)
  227. elif args.operation == 'exec':
  228. sources = args.filename
  229. for path in sources:
  230. uploader.exec_file(path)
  231. elif args.operation == 'file':
  232. operation_file(uploader, args.cmd, args.filename)
  233. elif args.operation == 'node':
  234. if args.ncmd == 'heap':
  235. uploader.node_heap()
  236. elif args.ncmd == 'restart':
  237. uploader.node_restart()
  238. elif args.operation == 'backup':
  239. uploader.backup(args.path)
  240. #no uploader related commands after this point
  241. uploader.close()