nodemcu-uploader.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #!/usr/bin/env python
  2. # Copyright (C) 2015 Peter Magnusson
  3. # For NodeMCU version 0.9.4 build 2014-12-30 and newer.
  4. import os
  5. import serial
  6. import sys
  7. import argparse
  8. import time
  9. import logging
  10. log = logging.getLogger(__name__)
  11. save_lua = \
  12. r"""
  13. function recv_block(d)
  14. if string.byte(d, 1) == 1 then
  15. size = string.byte(d, 2)
  16. uart.write(0,'\006')
  17. if size > 0 then
  18. file.write(string.sub(d, 3, 3+size-1))
  19. else
  20. file.close()
  21. uart.on('data')
  22. uart.setup(0,9600,8,0,1,1)
  23. end
  24. else
  25. uart.write(0, '\021' .. d)
  26. uart.setup(0,9600,8,0,1,1)
  27. uart.on('data')
  28. end
  29. end
  30. function recv_name(d) d = string.gsub(d, '\000', '') file.remove(d) file.open(d, 'w') uart.on('data', 130, recv_block, 0) uart.write(0, '\006') end
  31. function recv() uart.setup(0,9600,8,0,1,0) uart.on('data', '\000', recv_name, 0) uart.write(0, 'C') end
  32. """
  33. CHUNK_END = '\v'
  34. CHUNK_REPLY = '\v'
  35. class Uploader:
  36. BAUD = 9600
  37. PORT = '/dev/ttyUSB0'
  38. TIMEOUT = 5
  39. def expect(self, exp='> ', timeout=TIMEOUT):
  40. t = self._port.timeout
  41. # Checking for new data every 100us is fast enough
  42. lt = 0.0001
  43. if self._port.timeout != lt:
  44. self._port.timeout = lt
  45. end = time.time() + timeout
  46. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  47. data = ''
  48. while not data.endswith(exp) and time.time() <= end:
  49. data += self._port.read()
  50. self._port.timeout = t
  51. log.debug('expect return: %s', data)
  52. return data
  53. def write(self, output, binary=False):
  54. if not binary:
  55. log.debug('write: %s', output)
  56. else:
  57. log.debug('write binary: %s' % ':'.join(x.encode('hex') for x in output))
  58. self._port.write(output)
  59. self._port.flush()
  60. def writeln(self, output):
  61. self.write(output + '\n')
  62. def exchange(self, output):
  63. self.writeln(output)
  64. return self.expect()
  65. def __init__(self, port = 0, baud = BAUD):
  66. self._port = serial.Serial(port, Uploader.BAUD, timeout=Uploader.TIMEOUT)
  67. # Keeps things working, if following conections are made:
  68. ## RTS = CH_PD (i.e reset)
  69. ## DTR = GPIO0
  70. self._port.setRTS(False)
  71. self._port.setDTR(False)
  72. # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
  73. self.expect('NodeMCU ')
  74. self.expect()
  75. self.exchange('')
  76. if baud != Uploader.BAUD:
  77. log.info('Changing communication to %s baud', baud)
  78. self.writeln('uart.setup(0,%s,8,0,1,1)' % baud)
  79. # Wait for the string to be sent before switching baud
  80. time.sleep(0.1)
  81. self._port.setBaudrate(baud)
  82. # Get in sync again
  83. self.exchange('')
  84. self.exchange('')
  85. self.line_number = 0
  86. def close(self):
  87. self.writeln('uart.setup(0,%s,8,0,1,1)' % Uploader.BAUD)
  88. self._port.close()
  89. def prepare(self):
  90. log.info('Preparing esp for transfer.')
  91. data = save_lua.replace('9600', '%d' % self._port.baudrate)
  92. lines = data.replace('\r', '').split('\n')
  93. for line in lines:
  94. line = line.strip().replace(', ', ',').replace(' = ', '=')
  95. if len(line) == 0:
  96. continue
  97. d = self.exchange(line)
  98. if 'unexpected' in d or len(d) > len(save_lua)+10:
  99. log.error('error in save_lua "%s"' % d)
  100. return
  101. def download_file(self, filename):
  102. d = self.exchange(r"file.open('" + filename + r"') print(file.seek('end', 0)) file.seek('set', 0) uart.write(0, file.read()) file.close()")
  103. cmd, size, data = d.split('\n', 2)
  104. data = data[0:int(size)]
  105. return data
  106. def read_file(self, filename, destination = ''):
  107. if not destination:
  108. destination = filename
  109. log.info('Transfering %s to %s' %(filename, destination))
  110. data = self.download_file(filename)
  111. with open(destination, 'w') as f:
  112. f.write(data)
  113. def write_file(self, path, destination = '', verify = False):
  114. filename = os.path.basename(path)
  115. if not destination:
  116. destination = filename
  117. log.info('Transfering %s as %s' %(filename, destination))
  118. self.writeln("recv()")
  119. r = self.expect('C> ')
  120. if not r.endswith('C> '):
  121. log.error('Error waiting for esp "%s"' % r)
  122. return
  123. log.debug('sending destination filename "%s"', destination)
  124. self.write(destination + '\x00', True)
  125. if not self.got_ack():
  126. log.error('did not ack destination filename')
  127. return
  128. f = open( path, 'rt' ); content = f.read(); f.close()
  129. log.debug('sending %d bytes in %s' % (len(content), filename))
  130. pos = 0
  131. chunk_size = 128
  132. error = False
  133. while pos < len(content):
  134. rest = len(content) - pos
  135. if rest > chunk_size:
  136. rest = chunk_size
  137. data = content[pos:pos+rest]
  138. if not self.write_chunk(data):
  139. d = self.expect()
  140. log.error('Bad chunk response "%s" %s' % (d, ':'.join(x.encode('hex') for x in d)))
  141. return
  142. pos += chunk_size
  143. log.debug('sending zero block')
  144. #zero size block
  145. self.write_chunk('')
  146. if verify:
  147. log.info('Verifying...')
  148. data = self.download_file(destination)
  149. if content != data:
  150. log.error('Verification failed.')
  151. def got_ack(self):
  152. log.debug('waiting for ack')
  153. r = self._port.read(1)
  154. log.debug('ack read %s', r.encode('hex'))
  155. return r == '\x06' #ACK
  156. def write_lines(self, data):
  157. lines = data.replace('\r', '').split('\n')
  158. for line in lines:
  159. self.exchange(line)
  160. return
  161. def write_chunk(self, chunk):
  162. log.debug('writing %d bytes chunk' % len(chunk))
  163. data = '\x01' + chr(len(chunk)) + chunk
  164. if len(chunk) < 128:
  165. padding = 128 - len(chunk)
  166. log.debug('pad with %d characters' % padding)
  167. data = data + (' ' * padding)
  168. log.debug("packet size %d" % len(data))
  169. self.write(data)
  170. return self.got_ack()
  171. def file_list(self):
  172. log.info('Listing files')
  173. r = self.exchange('for key,value in pairs(file.list()) do print(key,value) end')
  174. log.info(r)
  175. return r
  176. def file_do(self, f):
  177. log.info('Executing '+f)
  178. r = self.exchange('dofile("'+f+'")')
  179. log.info(r)
  180. return r
  181. def file_format(self):
  182. log.info('Formating...')
  183. r = self.exchange('file.format()')
  184. if 'format done' not in r:
  185. log.error(r)
  186. else:
  187. log.info(r)
  188. return r
  189. def node_heap(self):
  190. log.info('Heap')
  191. r = self.exchange('print(node.heap())')
  192. log.info(r)
  193. return r
  194. def node_restart(self):
  195. log.info('Restart')
  196. r = self.exchange('node.restart()')
  197. log.info(r)
  198. return r
  199. def file_compile(self, path):
  200. log.info('Compile '+path)
  201. cmd = 'node.compile("%s")' % path
  202. r = self.exchange(cmd)
  203. log.info(r)
  204. return r
  205. def file_remove(self, path):
  206. log.info('Remove '+path)
  207. cmd = 'file.remove("%s")' % path
  208. r = self.exchange(cmd)
  209. log.info(r)
  210. return r
  211. def arg_auto_int(x):
  212. return int(x, 0)
  213. if __name__ == '__main__':
  214. parser = argparse.ArgumentParser(description = 'NodeMCU Lua file uploader', prog = 'nodemcu-uploader')
  215. parser.add_argument(
  216. '--verbose',
  217. help = 'verbose output',
  218. action = 'store_true',
  219. default = False)
  220. parser.add_argument(
  221. '--port', '-p',
  222. help = 'Serial port device',
  223. default = Uploader.PORT)
  224. parser.add_argument(
  225. '--baud', '-b',
  226. help = 'Serial port baudrate',
  227. type = arg_auto_int,
  228. default = Uploader.BAUD)
  229. subparsers = parser.add_subparsers(
  230. dest='operation',
  231. help = 'Run nodemcu-uploader {command} -h for additional help')
  232. upload_parser = subparsers.add_parser(
  233. 'upload',
  234. help = 'Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  235. # upload_parser.add_argument(
  236. # '--filename', '-f',
  237. # help = 'File to upload. You can specify this option multiple times.',
  238. # action='append')
  239. # upload_parser.add_argument(
  240. # '--destination', '-d',
  241. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  242. # action='append')
  243. upload_parser.add_argument('filename', nargs='+', help = 'Lua file to upload. Use colon to give alternate destination.')
  244. upload_parser.add_argument(
  245. '--compile', '-c',
  246. help = 'If file should be uploaded as compiled',
  247. action='store_true',
  248. default=False
  249. )
  250. upload_parser.add_argument(
  251. '--verify', '-v',
  252. help = 'To verify the uploaded data.',
  253. action='store_true',
  254. default=False
  255. )
  256. upload_parser.add_argument(
  257. '--dofile', '-e',
  258. help = 'If file should be run after upload.',
  259. action='store_true',
  260. default=False
  261. )
  262. upload_parser.add_argument(
  263. '--restart', '-r',
  264. help = 'If esp should be restarted',
  265. action='store_true',
  266. default=False
  267. )
  268. download_parser = subparsers.add_parser(
  269. 'download',
  270. help = 'Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  271. # download_parser.add_argument(
  272. # '--filename', '-f',
  273. # help = 'File to download. You can specify this option multiple times.',
  274. # action='append')
  275. # download_parser.add_argument(
  276. # '--destination', '-d',
  277. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  278. # action='append')
  279. download_parser.add_argument('filename', nargs='+', help = 'Lua file to download. Use colon to give alternate destination.')
  280. file_parser = subparsers.add_parser(
  281. 'file',
  282. help = 'File functions')
  283. file_parser.add_argument('cmd', choices=('list', 'do', 'format'))
  284. file_parser.add_argument('filename', nargs='*', help = 'Lua file to run.')
  285. node_parse = subparsers.add_parser(
  286. 'node',
  287. help = 'Node functions')
  288. node_parse.add_argument('ncmd', choices=('heap', 'restart'))
  289. args = parser.parse_args()
  290. formatter = logging.Formatter('%(message)s')
  291. logging.basicConfig(level=logging.INFO, format='%(message)s')
  292. if args.verbose:
  293. log.setLevel(logging.DEBUG)
  294. uploader = Uploader(args.port, args.baud)
  295. if args.operation == 'upload' or args.operation == 'download':
  296. sources = args.filename
  297. destinations = []
  298. for i in range(0, len(sources)):
  299. sd = sources[i].split(':')
  300. if len(sd) == 2:
  301. destinations.append(sd[1])
  302. sources[i]=sd[0]
  303. else:
  304. destinations.append(sd[0])
  305. if args.operation == 'upload':
  306. if len(destinations) == len(sources):
  307. uploader.prepare()
  308. for f, d in zip(sources, destinations):
  309. uploader.write_file(f, d, args.verify)
  310. if args.compile:
  311. uploader.file_compile(d)
  312. uploader.file_remove(d)
  313. if args.dofile:
  314. uploader.file_do(d)
  315. else:
  316. raise Exception('You must specify a destination filename for each file you want to upload.')
  317. if args.restart:
  318. uploader.node_restart()
  319. log.info('All done!')
  320. if args.operation == 'download':
  321. if len(destinations) == len(sources):
  322. for f, d in zip(sources, destinations):
  323. uploader.read_file(f, d)
  324. else:
  325. raise Exception('You must specify a destination filename for each file you want to download.')
  326. log.info('All done!')
  327. elif args.operation == 'file':
  328. if args.cmd == 'list':
  329. uploader.file_list()
  330. if args.cmd == 'do':
  331. for f in args.filename:
  332. uploader.file_do(f)
  333. elif args.cmd == 'format':
  334. uploader.file_format()
  335. elif args.operation == 'node':
  336. if args.ncmd == 'heap':
  337. uploader.node_heap()
  338. elif args.ncmd == 'restart':
  339. uploader.node_restart()
  340. uploader.close()