nodemcu-uploader.py 15 KB

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