uploader.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  4. import time
  5. import logging
  6. import hashlib
  7. import os
  8. import serial
  9. from .utils import default_port
  10. from .luacode import SAVE_LUA, LIST_FILES, UART_SETUP
  11. log = logging.getLogger(__name__)
  12. __all__ = ['Uploader', 'default_port']
  13. CHUNK_END = '\v'
  14. CHUNK_REPLY = '\v'
  15. class Uploader(object):
  16. BAUD = 9600
  17. TIMEOUT = 5
  18. PORT = default_port()
  19. def __init__(self, port=PORT, baud=BAUD):
  20. log.info('opening port %s', port)
  21. self._port = serial.Serial(port, Uploader.BAUD, timeout=Uploader.TIMEOUT)
  22. # Keeps things working, if following conections are made:
  23. ## RTS = CH_PD (i.e reset)
  24. ## DTR = GPIO0
  25. self._port.setRTS(False)
  26. self._port.setDTR(False)
  27. # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
  28. self.exchange(';') # Get a defined state
  29. self.writeln('print("%sync%");')
  30. self.expect('%sync%\r\n> ')
  31. if baud != Uploader.BAUD:
  32. log.info('Changing communication to %s baud', baud)
  33. self.writeln(UART_SETUP.format(baud=baud))
  34. # Wait for the string to be sent before switching baud
  35. time.sleep(0.1)
  36. self._port.setBaudrate(baud)
  37. # Get in sync again
  38. self.exchange('')
  39. self.exchange('')
  40. self.line_number = 0
  41. def expect(self, exp='> ', timeout=TIMEOUT):
  42. timer = self._port.timeout
  43. # Checking for new data every 100us is fast enough
  44. lt = 0.0001
  45. if self._port.timeout != lt:
  46. self._port.timeout = lt
  47. end = time.time() + timeout
  48. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  49. data = ''
  50. while not data.endswith(exp) and time.time() <= end:
  51. data += self._port.read()
  52. self._port.timeout = timer
  53. log.debug('expect return: %s', data)
  54. return data
  55. def write(self, output, binary=False):
  56. if not binary:
  57. log.debug('write: %s', output)
  58. else:
  59. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  60. self._port.write(output)
  61. self._port.flush()
  62. def writeln(self, output):
  63. self.write(output + '\n')
  64. def exchange(self, output):
  65. self.writeln(output)
  66. return self.expect()
  67. def close(self):
  68. self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
  69. self._port.close()
  70. def prepare(self):
  71. log.info('Preparing esp for transfer.')
  72. data = SAVE_LUA.format(baud=self._port.baudrate)
  73. ##change any \r\n to just \n and split on that
  74. lines = data.replace('\r', '').split('\n')
  75. #remove some unneccesary spaces to conserve some bytes
  76. for line in lines:
  77. line = line.strip().replace(', ', ',').replace(' = ', '=')
  78. if len(line) == 0:
  79. continue
  80. d = self.exchange(line)
  81. #do some basic test of the result
  82. if 'unexpected' in d or len(d) > len(SAVE_LUA)+10:
  83. log.error('error in save_lua "%s"', d)
  84. return
  85. def download_file(self, filename):
  86. chunk_size = 256
  87. bytes_read = 0
  88. data = ""
  89. while True:
  90. d = self.exchange(DOWNLOAD_FILE.format(filename=filename, bytes_read=bytes_read, chunk_size=chunk_size))
  91. cmd, size, tmp_data = d.split('\n', 2)
  92. data = data + tmp_data[0:chunk_size]
  93. bytes_read = bytes_read + chunk_size
  94. if bytes_read > int(size):
  95. break
  96. data = data[0:int(size)]
  97. return data
  98. def read_file(self, filename, destination=''):
  99. if not destination:
  100. destination = filename
  101. log.info('Transfering %s to %s', filename, destination)
  102. data = self.download_file(filename)
  103. with open(destination, 'w') as f:
  104. f.write(data)
  105. def write_file(self, path, destination='', verify='none'):
  106. filename = os.path.basename(path)
  107. if not destination:
  108. destination = filename
  109. log.info('Transfering %s as %s', path, destination)
  110. self.writeln("recv()")
  111. res = self.expect('C> ')
  112. if not res.endswith('C> '):
  113. log.error('Error waiting for esp "%s"', res)
  114. return
  115. log.debug('sending destination filename "%s"', destination)
  116. self.write(destination + '\x00', True)
  117. if not self.got_ack():
  118. log.error('did not ack destination filename')
  119. return
  120. f = open(path, 'rb')
  121. content = f.read()
  122. f.close()
  123. log.debug('sending %d bytes in %s', len(content), filename)
  124. pos = 0
  125. chunk_size = 128
  126. while pos < len(content):
  127. rest = len(content) - pos
  128. if rest > chunk_size:
  129. rest = chunk_size
  130. data = content[pos:pos+rest]
  131. if not self.write_chunk(data):
  132. d = self.expect()
  133. log.error('Bad chunk response "%s" %s', d, ':'.join(x.encode('hex') for x in d))
  134. return
  135. pos += chunk_size
  136. log.debug('sending zero block')
  137. #zero size block
  138. self.write_chunk('')
  139. if verify == 'standard':
  140. log.info('Verifying...')
  141. data = self.download_file(destination)
  142. if content != data:
  143. log.error('Verification failed.')
  144. elif verify == 'sha1':
  145. #Calculate SHA1 on remote file. Extract just hash from result
  146. data = self.exchange('shafile("'+destination+'")').splitlines()[1]
  147. log.info('Remote SHA1: %s', data)
  148. #Calculate hash of local data
  149. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  150. log.info('Local SHA1: %s', filehashhex)
  151. if data != filehashhex:
  152. log.error('Verification failed.')
  153. def exec_file(self, path):
  154. filename = os.path.basename(path)
  155. log.info('Execute %s', filename)
  156. f = open(path, 'rt')
  157. res = '> '
  158. for line in f:
  159. line = line.rstrip('\r\n')
  160. retlines = (res + self.exchange(line)).splitlines()
  161. # Log all but the last line
  162. res = retlines.pop()
  163. for lin in retlines:
  164. log.info(lin)
  165. # last line
  166. log.info(res)
  167. f.close()
  168. def got_ack(self):
  169. log.debug('waiting for ack')
  170. res = self._port.read(1)
  171. log.debug('ack read %s', res.encode('hex'))
  172. return res == '\x06' #ACK
  173. def write_lines(self, data):
  174. lines = data.replace('\r', '').split('\n')
  175. for line in lines:
  176. self.exchange(line)
  177. return
  178. def write_chunk(self, chunk):
  179. log.debug('writing %d bytes chunk', len(chunk))
  180. data = '\x01' + chr(len(chunk)) + chunk
  181. if len(chunk) < 128:
  182. padding = 128 - len(chunk)
  183. log.debug('pad with %d characters', padding)
  184. data = data + (' ' * padding)
  185. log.debug("packet size %d", len(data))
  186. self.write(data)
  187. return self.got_ack()
  188. def file_list(self):
  189. log.info('Listing files')
  190. res = self.exchange(LIST_FILES)
  191. log.info(res)
  192. return res
  193. def file_do(self, f):
  194. log.info('Executing '+f)
  195. res = self.exchange('dofile("'+f+'")')
  196. log.info(res)
  197. return res
  198. def file_format(self):
  199. log.info('Formating...')
  200. res = self.exchange('file.format()')
  201. if 'format done' not in res:
  202. log.error(res)
  203. else:
  204. log.info(res)
  205. return res
  206. def node_heap(self):
  207. log.info('Heap')
  208. res = self.exchange('print(node.heap())')
  209. log.info(res)
  210. return res
  211. def node_restart(self):
  212. log.info('Restart')
  213. res = self.exchange('node.restart()')
  214. log.info(res)
  215. return res
  216. def file_compile(self, path):
  217. log.info('Compile '+path)
  218. cmd = 'node.compile("%s")' % path
  219. res = self.exchange(cmd)
  220. log.info(res)
  221. return res
  222. def file_remove(self, path):
  223. log.info('Remove '+path)
  224. cmd = 'file.remove("%s")' % path
  225. res = self.exchange(cmd)
  226. log.info(res)
  227. return res