nodemcu-uploader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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' %(path, 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, 'rb' ); 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 file_remove(self):
  224. log.info('Removing...')
  225. r = self.exchange('file.remove("'+f+'")')
  226. log.info(r)
  227. return r
  228. def node_heap(self):
  229. log.info('Heap')
  230. r = self.exchange('print(node.heap())')
  231. log.info(r)
  232. return r
  233. def node_restart(self):
  234. log.info('Restart')
  235. r = self.exchange('node.restart()')
  236. log.info(r)
  237. return r
  238. def file_compile(self, path):
  239. log.info('Compile '+path)
  240. cmd = 'node.compile("%s")' % path
  241. r = self.exchange(cmd)
  242. log.info(r)
  243. return r
  244. def file_remove(self, path):
  245. log.info('Remove '+path)
  246. cmd = 'file.remove("%s")' % path
  247. r = self.exchange(cmd)
  248. log.info(r)
  249. return r
  250. def terminal(self):
  251. miniterm = MyMiniterm(self._port)
  252. log.info('Started terminal. Hit ctrl-] to leave terminal')
  253. console.setup()
  254. miniterm.start()
  255. try:
  256. miniterm.join(True)
  257. except KeyboardInterrupt:
  258. pass
  259. miniterm.join()
  260. def arg_auto_int(x):
  261. return int(x, 0)
  262. if __name__ == '__main__':
  263. parser = argparse.ArgumentParser(description = 'NodeMCU Lua file uploader', prog = 'nodemcu-uploader')
  264. parser.add_argument(
  265. '--verbose',
  266. help = 'verbose output',
  267. action = 'store_true',
  268. default = False)
  269. parser.add_argument(
  270. '--port', '-p',
  271. help = 'Serial port device',
  272. default = Uploader.PORT)
  273. parser.add_argument(
  274. '--baud', '-b',
  275. help = 'Serial port baudrate',
  276. type = arg_auto_int,
  277. default = Uploader.BAUD)
  278. subparsers = parser.add_subparsers(
  279. dest='operation',
  280. help = 'Run nodemcu-uploader {command} -h for additional help')
  281. upload_parser = subparsers.add_parser(
  282. 'upload',
  283. help = 'Path to one or more files to be uploaded. Destination name will be the same as the file name.')
  284. # upload_parser.add_argument(
  285. # '--filename', '-f',
  286. # help = 'File to upload. You can specify this option multiple times.',
  287. # action='append')
  288. # upload_parser.add_argument(
  289. # '--destination', '-d',
  290. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  291. # action='append')
  292. upload_parser.add_argument('filename', nargs='+', help = 'Lua file to upload. Use colon to give alternate destination.')
  293. upload_parser.add_argument(
  294. '--compile', '-c',
  295. help = 'If file should be uploaded as compiled',
  296. action='store_true',
  297. default=False
  298. )
  299. upload_parser.add_argument(
  300. '--verify', '-v',
  301. help = 'To verify the uploaded data.',
  302. action='store_true',
  303. default=False
  304. )
  305. upload_parser.add_argument(
  306. '--dofile', '-e',
  307. help = 'If file should be run after upload.',
  308. action='store_true',
  309. default=False
  310. )
  311. upload_parser.add_argument(
  312. '--terminal', '-t',
  313. help = 'If miniterm should claim the port after all uploading is done.',
  314. action='store_true',
  315. default=False
  316. )
  317. upload_parser.add_argument(
  318. '--restart', '-r',
  319. help = 'If esp should be restarted',
  320. action='store_true',
  321. default=False
  322. )
  323. exec_parser = subparsers.add_parser(
  324. 'exec',
  325. help = 'Path to one or more files to be executed line by line.')
  326. exec_parser.add_argument('filename', nargs='+', help = 'Lua file to execute.')
  327. download_parser = subparsers.add_parser(
  328. 'download',
  329. help = 'Path to one or more files to be downloaded. Destination name will be the same as the file name.')
  330. # download_parser.add_argument(
  331. # '--filename', '-f',
  332. # help = 'File to download. You can specify this option multiple times.',
  333. # action='append')
  334. # download_parser.add_argument(
  335. # '--destination', '-d',
  336. # help = 'Name to be used when saving in NodeMCU. You should specify one per file.',
  337. # action='append')
  338. download_parser.add_argument('filename', nargs='+', help = 'Lua file to download. Use colon to give alternate destination.')
  339. file_parser = subparsers.add_parser(
  340. 'file',
  341. help = 'File functions')
  342. file_parser.add_argument('cmd', choices=('list', 'do', 'format', 'remove'))
  343. file_parser.add_argument('filename', nargs='*', help = 'Lua file to run.')
  344. node_parse = subparsers.add_parser(
  345. 'node',
  346. help = 'Node functions')
  347. node_parse.add_argument('ncmd', choices=('heap', 'restart'))
  348. args = parser.parse_args()
  349. formatter = logging.Formatter('%(message)s')
  350. logging.basicConfig(level=logging.INFO, format='%(message)s')
  351. if args.verbose:
  352. log.setLevel(logging.DEBUG)
  353. uploader = Uploader(args.port, args.baud)
  354. if args.operation == 'upload' or args.operation == 'download':
  355. sources = args.filename
  356. destinations = []
  357. for i in range(0, len(sources)):
  358. sd = sources[i].split(':')
  359. if len(sd) == 2:
  360. destinations.append(sd[1])
  361. sources[i]=sd[0]
  362. else:
  363. destinations.append(sd[0])
  364. if args.operation == 'upload':
  365. if len(destinations) == len(sources):
  366. uploader.prepare()
  367. for f, d in zip(sources, destinations):
  368. if args.compile:
  369. uploader.file_remove(os.path.splitext(d)[0]+'.lc')
  370. uploader.write_file(f, d, args.verify)
  371. if args.compile and d != 'init.lua':
  372. uploader.file_compile(d)
  373. uploader.file_remove(d)
  374. if args.dofile:
  375. uploader.file_do(os.path.splitext(d)[0]+'.lc')
  376. elif args.dofile:
  377. uploader.file_do(d)
  378. else:
  379. raise Exception('You must specify a destination filename for each file you want to upload.')
  380. if args.terminal:
  381. uploader.terminal()
  382. if args.restart:
  383. uploader.node_restart()
  384. log.info('All done!')
  385. if args.operation == 'download':
  386. if len(destinations) == len(sources):
  387. for f, d in zip(sources, destinations):
  388. uploader.read_file(f, d)
  389. else:
  390. raise Exception('You must specify a destination filename for each file you want to download.')
  391. log.info('All done!')
  392. elif args.operation == 'exec':
  393. sources = args.filename
  394. for f in sources:
  395. uploader.exec_file(f)
  396. elif args.operation == 'file':
  397. if args.cmd == 'list':
  398. uploader.file_list()
  399. if args.cmd == 'do':
  400. for f in args.filename:
  401. uploader.file_do(f)
  402. elif args.cmd == 'format':
  403. uploader.file_format()
  404. elif args.cmd == 'remove':
  405. for f in args.filename:
  406. uploader.file_remove(f)
  407. elif args.operation == 'node':
  408. if args.ncmd == 'heap':
  409. uploader.node_heap()
  410. elif args.ncmd == 'restart':
  411. uploader.node_restart()
  412. uploader.close()