nodemcu-uploader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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. from serial.tools.miniterm import Miniterm, console, NEWLINE_CONVERISON_MAP
  36. class MyMiniterm(Miniterm):
  37. def __init__(self, serial):
  38. self.serial = serial
  39. self.echo = False
  40. self.convert_outgoing = 2
  41. self.repr_mode = 1
  42. self.newline = NEWLINE_CONVERISON_MAP[self.convert_outgoing]
  43. self.dtr_state = True
  44. self.rts_state = True
  45. self.break_state = False
  46. class Uploader:
  47. BAUD = 9600
  48. PORT = '/dev/ttyUSB0'
  49. TIMEOUT = 5
  50. def expect(self, exp='> ', timeout=TIMEOUT):
  51. t = self._port.timeout
  52. # Checking for new data every 100us is fast enough
  53. lt = 0.0001
  54. if self._port.timeout != lt:
  55. self._port.timeout = lt
  56. end = time.time() + timeout
  57. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  58. data = ''
  59. while not data.endswith(exp) and time.time() <= end:
  60. data += self._port.read()
  61. self._port.timeout = t
  62. log.debug('expect return: %s', data)
  63. return data
  64. def write(self, output, binary=False):
  65. if not binary:
  66. log.debug('write: %s', output)
  67. else:
  68. log.debug('write binary: %s' % ':'.join(x.encode('hex') for x in output))
  69. self._port.write(output)
  70. self._port.flush()
  71. def writeln(self, output):
  72. self.write(output + '\n')
  73. def exchange(self, output):
  74. self.writeln(output)
  75. return self.expect()
  76. def __init__(self, port = 0, baud = BAUD):
  77. self._port = serial.Serial(port, Uploader.BAUD, timeout=Uploader.TIMEOUT)
  78. # Keeps things working, if following conections are made:
  79. ## RTS = CH_PD (i.e reset)
  80. ## DTR = GPIO0
  81. self._port.setRTS(False)
  82. self._port.setDTR(False)
  83. # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
  84. self.exchange(';'); # Get a defined state
  85. self.writeln('print("%sync%");');
  86. self.expect('%sync%\r\n> ');
  87. if baud != Uploader.BAUD:
  88. log.info('Changing communication to %s baud', baud)
  89. self.writeln('uart.setup(0,%s,8,0,1,1)' % baud)
  90. # Wait for the string to be sent before switching baud
  91. time.sleep(0.1)
  92. self._port.setBaudrate(baud)
  93. # Get in sync again
  94. self.exchange('')
  95. self.exchange('')
  96. self.line_number = 0
  97. def close(self):
  98. self.writeln('uart.setup(0,%s,8,0,1,1)' % Uploader.BAUD)
  99. self._port.close()
  100. def prepare(self):
  101. log.info('Preparing esp for transfer.')
  102. data = save_lua.replace('9600', '%d' % self._port.baudrate)
  103. lines = data.replace('\r', '').split('\n')
  104. for line in lines:
  105. line = line.strip().replace(', ', ',').replace(' = ', '=')
  106. if len(line) == 0:
  107. continue
  108. d = self.exchange(line)
  109. if 'unexpected' in d or len(d) > len(save_lua)+10:
  110. log.error('error in save_lua "%s"' % d)
  111. return
  112. def download_file(self, filename):
  113. chunk_size=256
  114. bytes_read = 0
  115. data=""
  116. while True:
  117. d = self.exchange("file.open('" + filename + r"') print(file.seek('end', 0)) file.seek('set', %d) uart.write(0, file.read(%d))file.close()" % (bytes_read, chunk_size))
  118. cmd, size, tmp_data = d.split('\n', 2)
  119. data=data+tmp_data[0:chunk_size]
  120. bytes_read=bytes_read+chunk_size
  121. if bytes_read > int(size):
  122. break
  123. data = data[0:int(size)]
  124. return data
  125. def read_file(self, filename, destination = ''):
  126. if not destination:
  127. destination = filename
  128. log.info('Transfering %s to %s' %(filename, destination))
  129. data = self.download_file(filename)
  130. with open(destination, 'w') as f:
  131. f.write(data)
  132. def write_file(self, path, destination = '', verify = False):
  133. filename = os.path.basename(path)
  134. if not destination:
  135. destination = filename
  136. log.info('Transfering %s as %s' %(filename, destination))
  137. self.writeln("recv()")
  138. r = self.expect('C> ')
  139. if not r.endswith('C> '):
  140. log.error('Error waiting for esp "%s"' % r)
  141. return
  142. log.debug('sending destination filename "%s"', destination)
  143. self.write(destination + '\x00', True)
  144. if not self.got_ack():
  145. log.error('did not ack destination filename')
  146. return
  147. f = open( path, 'rt' ); content = f.read(); f.close()
  148. log.debug('sending %d bytes in %s' % (len(content), filename))
  149. pos = 0
  150. chunk_size = 128
  151. error = False
  152. while pos < len(content):
  153. rest = len(content) - pos
  154. if rest > chunk_size:
  155. rest = chunk_size
  156. data = content[pos:pos+rest]
  157. if not self.write_chunk(data):
  158. d = self.expect()
  159. log.error('Bad chunk response "%s" %s' % (d, ':'.join(x.encode('hex') for x in d)))
  160. return
  161. pos += chunk_size
  162. log.debug('sending zero block')
  163. #zero size block
  164. self.write_chunk('')
  165. if verify:
  166. log.info('Verifying...')
  167. data = self.download_file(destination)
  168. if content != data:
  169. log.error('Verification failed.')
  170. def exec_file(self, path):
  171. filename = os.path.basename(path)
  172. log.info('Execute %s' %(filename,))
  173. f = open( path, 'rt' );
  174. res = '> '
  175. for line in f:
  176. line = line.rstrip('\r\n')
  177. retlines = (res + self.exchange(line)).splitlines()
  178. # Log all but the last line
  179. res = retlines.pop()
  180. for l in retlines:
  181. log.info(l)
  182. # last line
  183. log.info(res)
  184. f.close()
  185. def got_ack(self):
  186. log.debug('waiting for ack')
  187. r = self._port.read(1)
  188. log.debug('ack read %s', r.encode('hex'))
  189. return r == '\x06' #ACK
  190. def write_lines(self, data):
  191. lines = data.replace('\r', '').split('\n')
  192. for line in lines:
  193. self.exchange(line)
  194. return
  195. def write_chunk(self, chunk):
  196. log.debug('writing %d bytes chunk' % len(chunk))
  197. data = '\x01' + chr(len(chunk)) + chunk
  198. if len(chunk) < 128:
  199. padding = 128 - len(chunk)
  200. log.debug('pad with %d characters' % padding)
  201. data = data + (' ' * padding)
  202. log.debug("packet size %d" % len(data))
  203. self.write(data)
  204. return self.got_ack()
  205. def file_list(self):
  206. log.info('Listing files')
  207. r = self.exchange('for key,value in pairs(file.list()) do print(key,value) end')
  208. log.info(r)
  209. return r
  210. def file_do(self, f):
  211. log.info('Executing '+f)
  212. r = self.exchange('dofile("'+f+'")')
  213. log.info(r)
  214. return r
  215. def file_format(self):
  216. log.info('Formating...')
  217. r = self.exchange('file.format()')
  218. if 'format done' not in r:
  219. log.error(r)
  220. else:
  221. log.info(r)
  222. return r
  223. def node_heap(self):
  224. log.info('Heap')
  225. r = self.exchange('print(node.heap())')
  226. log.info(r)
  227. return r
  228. def node_restart(self):
  229. log.info('Restart')
  230. r = self.exchange('node.restart()')
  231. log.info(r)
  232. return r
  233. def file_compile(self, path):
  234. log.info('Compile '+path)
  235. cmd = 'node.compile("%s")' % path
  236. r = self.exchange(cmd)
  237. log.info(r)
  238. return r
  239. def file_remove(self, path):
  240. log.info('Remove '+path)
  241. cmd = 'file.remove("%s")' % path
  242. r = self.exchange(cmd)
  243. log.info(r)
  244. return r
  245. def terminal(self):
  246. miniterm = MyMiniterm(self._port)
  247. log.info('Started terminal. Hit ctrl-] to leave terminal')
  248. console.setup()
  249. miniterm.start()
  250. try:
  251. miniterm.join(True)
  252. except KeyboardInterrupt:
  253. pass
  254. miniterm.join()
  255. def arg_auto_int(x):
  256. return int(x, 0)
  257. if __name__ == '__main__':
  258. parser = argparse.ArgumentParser(description = 'NodeMCU Lua file uploader', prog = 'nodemcu-uploader')
  259. parser.add_argument(
  260. '--verbose',
  261. help = 'verbose output',
  262. action = 'store_true',
  263. default = False)
  264. parser.add_argument(
  265. '--port', '-p',
  266. help = 'Serial port device',
  267. default = Uploader.PORT)
  268. parser.add_argument(
  269. '--baud', '-b',
  270. help = 'Serial port baudrate',
  271. type = arg_auto_int,
  272. default = Uploader.BAUD)
  273. subparsers = parser.add_subparsers(
  274. dest='operation',
  275. help = 'Run nodemcu-uploader {command} -h for additional help')
  276. upload_parser = subparsers.add_parser(
  277. 'upload',
  278. help = 'Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  279. # upload_parser.add_argument(
  280. # '--filename', '-f',
  281. # help = 'File to upload. You can specify this option multiple times.',
  282. # action='append')
  283. # upload_parser.add_argument(
  284. # '--destination', '-d',
  285. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  286. # action='append')
  287. upload_parser.add_argument('filename', nargs='+', help = 'Lua file to upload. Use colon to give alternate destination.')
  288. upload_parser.add_argument(
  289. '--compile', '-c',
  290. help = 'If file should be uploaded as compiled',
  291. action='store_true',
  292. default=False
  293. )
  294. upload_parser.add_argument(
  295. '--verify', '-v',
  296. help = 'To verify the uploaded data.',
  297. action='store_true',
  298. default=False
  299. )
  300. upload_parser.add_argument(
  301. '--dofile', '-e',
  302. help = 'If file should be run after upload.',
  303. action='store_true',
  304. default=False
  305. )
  306. upload_parser.add_argument(
  307. '--terminal', '-t',
  308. help = 'If miniterm should claim the port after all uploading is done.',
  309. action='store_true',
  310. default=False
  311. )
  312. upload_parser.add_argument(
  313. '--restart', '-r',
  314. help = 'If esp should be restarted',
  315. action='store_true',
  316. default=False
  317. )
  318. exec_parser = subparsers.add_parser(
  319. 'exec',
  320. help = 'Path to one or more files to be executed line by line.')
  321. exec_parser.add_argument('filename', nargs='+', help = 'Lua file to execute.')
  322. download_parser = subparsers.add_parser(
  323. 'download',
  324. help = 'Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  325. # download_parser.add_argument(
  326. # '--filename', '-f',
  327. # help = 'File to download. You can specify this option multiple times.',
  328. # action='append')
  329. # download_parser.add_argument(
  330. # '--destination', '-d',
  331. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  332. # action='append')
  333. download_parser.add_argument('filename', nargs='+', help = 'Lua file to download. Use colon to give alternate destination.')
  334. file_parser = subparsers.add_parser(
  335. 'file',
  336. help = 'File functions')
  337. file_parser.add_argument('cmd', choices=('list', 'do', 'format'))
  338. file_parser.add_argument('filename', nargs='*', help = 'Lua file to run.')
  339. node_parse = subparsers.add_parser(
  340. 'node',
  341. help = 'Node functions')
  342. node_parse.add_argument('ncmd', choices=('heap', 'restart'))
  343. args = parser.parse_args()
  344. formatter = logging.Formatter('%(message)s')
  345. logging.basicConfig(level=logging.INFO, format='%(message)s')
  346. if args.verbose:
  347. log.setLevel(logging.DEBUG)
  348. uploader = Uploader(args.port, args.baud)
  349. if args.operation == 'upload' or args.operation == 'download':
  350. sources = args.filename
  351. destinations = []
  352. for i in range(0, len(sources)):
  353. sd = sources[i].split(':')
  354. if len(sd) == 2:
  355. destinations.append(sd[1])
  356. sources[i]=sd[0]
  357. else:
  358. destinations.append(sd[0])
  359. if args.operation == 'upload':
  360. if len(destinations) == len(sources):
  361. uploader.prepare()
  362. for f, d in zip(sources, destinations):
  363. if args.compile:
  364. uploader.file_remove(os.path.splitext(d)[0]+'.lc')
  365. uploader.write_file(f, d, args.verify)
  366. if args.compile and d != 'init.lua':
  367. uploader.file_compile(d)
  368. uploader.file_remove(d)
  369. if args.dofile:
  370. uploader.file_do(os.path.splitext(d)[0]+'.lc')
  371. elif args.dofile:
  372. uploader.file_do(d)
  373. else:
  374. raise Exception('You must specify a destination filename for each file you want to upload.')
  375. if args.terminal:
  376. uploader.terminal()
  377. if args.restart:
  378. uploader.node_restart()
  379. log.info('All done!')
  380. if args.operation == 'download':
  381. if len(destinations) == len(sources):
  382. for f, d in zip(sources, destinations):
  383. uploader.read_file(f, d)
  384. else:
  385. raise Exception('You must specify a destination filename for each file you want to download.')
  386. log.info('All done!')
  387. elif args.operation == 'exec':
  388. sources = args.filename
  389. for f in sources:
  390. uploader.exec_file(f)
  391. elif args.operation == 'file':
  392. if args.cmd == 'list':
  393. uploader.file_list()
  394. if args.cmd == 'do':
  395. for f in args.filename:
  396. uploader.file_do(f)
  397. elif args.cmd == 'format':
  398. uploader.file_format()
  399. elif args.operation == 'node':
  400. if args.ncmd == 'heap':
  401. uploader.node_heap()
  402. elif args.ncmd == 'restart':
  403. uploader.node_restart()
  404. uploader.close()