main.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. subparsers = parser.add_subparsers(
  115. dest='operation',
  116. help='Run nodemcu-uploader {command} -h for additional help')
  117. upload_parser = subparsers.add_parser(
  118. 'upload',
  119. help='Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  120. upload_parser.add_argument(
  121. 'filename',
  122. nargs='+',
  123. help='Lua file to upload. Use colon to give alternate destination.'
  124. )
  125. upload_parser.add_argument(
  126. '--compile', '-c',
  127. help='If file should be uploaded as compiled',
  128. action='store_true',
  129. default=False
  130. )
  131. upload_parser.add_argument(
  132. '--verify', '-v',
  133. help='To verify the uploaded data.',
  134. action='store',
  135. nargs='?',
  136. choices=['none', 'raw', 'sha1'],
  137. default='none'
  138. )
  139. upload_parser.add_argument(
  140. '--dofile', '-e',
  141. help='If file should be run after upload.',
  142. action='store_true',
  143. default=False
  144. )
  145. upload_parser.add_argument(
  146. '--restart', '-r',
  147. help='If esp should be restarted',
  148. action='store_true',
  149. default=False
  150. )
  151. exec_parser = subparsers.add_parser(
  152. 'exec',
  153. help='Path to one or more files to be executed line by line.')
  154. exec_parser.add_argument('filename', nargs='+', help='Lua file to execute.')
  155. download_parser = subparsers.add_parser(
  156. 'download',
  157. help='Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  158. download_parser.add_argument('filename', nargs='+', help='Lua file to download. Use colon to give alternate destination.')
  159. file_parser = subparsers.add_parser(
  160. 'file',
  161. help='File functions')
  162. file_parser.add_argument(
  163. 'cmd',
  164. choices=('list', 'do', 'format', 'remove', 'print'),
  165. help="list=list files, do=dofile given path, format=formate file area, remove=remove given path")
  166. file_parser.add_argument('filename', nargs='*', help='path for cmd')
  167. node_parse = subparsers.add_parser(
  168. 'node',
  169. help='Node functions')
  170. node_parse.add_argument('ncmd', choices=('heap', 'restart'), help="heap=print heap memory, restart=restart nodemcu")
  171. terminal_parser = subparsers.add_parser(
  172. 'terminal',
  173. help='Run pySerials miniterm'
  174. )
  175. args = parser.parse_args()
  176. default_level = logging.INFO
  177. if args.verbose:
  178. default_level = logging.DEBUG
  179. #formatter = logging.Formatter('%(message)s')
  180. logging.basicConfig(level=default_level, format='%(message)s')
  181. if args.operation == 'terminal':
  182. #uploader can not claim the port
  183. terminal(args.port, str(args.start_baud))
  184. return
  185. uploader = Uploader(args.port, args.baud, start_baud=args.start_baud)
  186. if args.operation == 'upload':
  187. operation_upload(uploader, args.filename, args.verify, args.compile, args.dofile,
  188. args.restart)
  189. elif args.operation == 'download':
  190. operation_download(uploader, args.filename)
  191. elif args.operation == 'exec':
  192. sources = args.filename
  193. for f in sources:
  194. uploader.exec_file(f)
  195. elif args.operation == 'file':
  196. operation_file(uploader, args.cmd, args.filename)
  197. elif args.operation == 'node':
  198. if args.ncmd == 'heap':
  199. uploader.node_heap()
  200. elif args.ncmd == 'restart':
  201. uploader.node_restart()
  202. #no uploader related commands after this point
  203. uploader.close()