nodemcu-uploader.py 16 KB

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