main.py 7.8 KB

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