main.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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_file(uploader, cmd, filename=''):
  76. """File operations"""
  77. if cmd == 'list':
  78. uploader.file_list()
  79. if cmd == 'do':
  80. for path in filename:
  81. uploader.file_do(path)
  82. elif cmd == 'format':
  83. uploader.file_format()
  84. elif cmd == 'remove':
  85. for path in filename:
  86. uploader.file_remove(path)
  87. elif cmd == 'print':
  88. for path in filename:
  89. uploader.file_print(path)
  90. def arg_auto_int(value):
  91. """parsing function for integer arguments"""
  92. return int(value, 0)
  93. def main_func():
  94. """Main function for cli"""
  95. parser = argparse.ArgumentParser(
  96. description='NodeMCU Lua file uploader',
  97. prog='nodemcu-uploader'
  98. )
  99. parser.add_argument(
  100. '--verbose',
  101. help='verbose output',
  102. action='store_true',
  103. default=False)
  104. parser.add_argument(
  105. '--version',
  106. help='prints the version and exists',
  107. action='version',
  108. version='%(prog)s {version} (serial {serialversion})'.format(version=__version__, serialversion=serialversion)
  109. )
  110. parser.add_argument(
  111. '--port', '-p',
  112. help='Serial port device',
  113. default=Uploader.PORT)
  114. parser.add_argument(
  115. '--baud', '-b',
  116. help='Serial port baudrate',
  117. type=arg_auto_int,
  118. default=Uploader.BAUD)
  119. parser.add_argument(
  120. '--start_baud', '-B',
  121. help='Initial Serial port baudrate',
  122. type=arg_auto_int,
  123. default=Uploader.START_BAUD)
  124. parser.add_argument(
  125. '--timeout', '-t',
  126. help='Timeout for operations',
  127. type=arg_auto_int,
  128. default=Uploader.TIMEOUT)
  129. subparsers = parser.add_subparsers(
  130. dest='operation',
  131. help='Run nodemcu-uploader {command} -h for additional help')
  132. upload_parser = subparsers.add_parser(
  133. 'upload',
  134. help='Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  135. upload_parser.add_argument(
  136. 'filename',
  137. nargs='+',
  138. help='Lua file to upload. Use colon to give alternate destination.'
  139. )
  140. upload_parser.add_argument(
  141. '--compile', '-c',
  142. help='If file should be uploaded as compiled',
  143. action='store_true',
  144. default=False
  145. )
  146. upload_parser.add_argument(
  147. '--verify', '-v',
  148. help='To verify the uploaded data.',
  149. action='store',
  150. nargs='?',
  151. choices=['none', 'raw', 'sha1'],
  152. default='none'
  153. )
  154. upload_parser.add_argument(
  155. '--dofile', '-e',
  156. help='If file should be run after upload.',
  157. action='store_true',
  158. default=False
  159. )
  160. upload_parser.add_argument(
  161. '--restart', '-r',
  162. help='If esp should be restarted',
  163. action='store_true',
  164. default=False
  165. )
  166. exec_parser = subparsers.add_parser(
  167. 'exec',
  168. help='Path to one or more files to be executed line by line.')
  169. exec_parser.add_argument('filename', nargs='+', help='Lua file to execute.')
  170. download_parser = subparsers.add_parser(
  171. 'download',
  172. help='Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  173. download_parser.add_argument('filename',
  174. nargs='+',
  175. help='Lua file to download. Use colon to give alternate destination.')
  176. file_parser = subparsers.add_parser(
  177. 'file',
  178. help='File functions')
  179. file_parser.add_argument(
  180. 'cmd',
  181. choices=('list', 'do', 'format', 'remove', 'print'),
  182. help="list=list files, do=dofile given path, format=formate file area, remove=remove given path")
  183. file_parser.add_argument('filename', nargs='*', help='path for cmd')
  184. node_parse = subparsers.add_parser(
  185. 'node',
  186. help='Node functions')
  187. node_parse.add_argument('ncmd', choices=('heap', 'restart'), help="heap=print heap memory, restart=restart nodemcu")
  188. subparsers.add_parser(
  189. 'terminal',
  190. help='Run pySerials miniterm'
  191. )
  192. args = parser.parse_args()
  193. default_level = logging.INFO
  194. if args.verbose:
  195. default_level = logging.DEBUG
  196. #formatter = logging.Formatter('%(message)s')
  197. logging.basicConfig(level=default_level, format='%(message)s')
  198. if args.operation == 'terminal':
  199. #uploader can not claim the port
  200. terminal(args.port, str(args.start_baud))
  201. return
  202. # let uploader user the default (short) timeout for establishing connection
  203. uploader = Uploader(args.port, args.baud, start_baud=args.start_baud)
  204. # and reset the timeout (if we have the uploader&timeout)
  205. if args.timeout:
  206. uploader.set_timeout(args.timeout)
  207. if args.operation == 'upload':
  208. operation_upload(uploader, args.filename, args.verify, args.compile, args.dofile,
  209. args.restart)
  210. elif args.operation == 'download':
  211. operation_download(uploader, args.filename)
  212. elif args.operation == 'exec':
  213. sources = args.filename
  214. for path in sources:
  215. uploader.exec_file(path)
  216. elif args.operation == 'file':
  217. operation_file(uploader, args.cmd, args.filename)
  218. elif args.operation == 'node':
  219. if args.ncmd == 'heap':
  220. uploader.node_heap()
  221. elif args.ncmd == 'restart':
  222. uploader.node_restart()
  223. #no uploader related commands after this point
  224. uploader.close()