nodemcu-uploader.py 16 KB

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