uploader.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. class Uploader(object):
  14. """Uploader is the class for communicating with the nodemcu and
  15. that will allow various tasks like uploading files, formating the filesystem etc.
  16. """
  17. BAUD = 9600
  18. TIMEOUT = 5
  19. PORT = default_port()
  20. def __init__(self, port=PORT, baud=BAUD):
  21. log.info('opening port %s', port)
  22. if port == 'loop://':
  23. self._port = serial.serial_for_url(port, baud, timeout=Uploader.TIMEOUT)
  24. else:
  25. self._port = serial.Serial(port, baud, timeout=Uploader.TIMEOUT)
  26. # Keeps things working, if following conections are made:
  27. ## RTS = CH_PD (i.e reset)
  28. ## DTR = GPIO0
  29. self._port.setRTS(False)
  30. self._port.setDTR(False)
  31. def sync():
  32. # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
  33. log.debug('getting in sync with LUA');
  34. self.exchange(';') # Get a defined state
  35. self.writeln('print("%sync%");')
  36. self.expect('%sync%\r\n> ')
  37. sync()
  38. if baud != Uploader.BAUD:
  39. log.info('Changing communication to %s baud', baud)
  40. self.writeln(UART_SETUP.format(baud=baud))
  41. # Wait for the string to be sent before switching baud
  42. time.sleep(0.1)
  43. self.set_baudrate(baud)
  44. # Get in sync again
  45. sync()
  46. self.line_number = 0
  47. def set_baudrate(self, baud):
  48. try:
  49. self._port.setBaudrate(baud)
  50. except AttributeError:
  51. self._port.baudrate = baud
  52. def expect(self, exp='> ', timeout=TIMEOUT):
  53. """will wait for exp to be returned from nodemcu or timeout"""
  54. timer = 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 = timer
  65. log.debug('expect return: %s', data)
  66. return data
  67. def write(self, output, binary=False):
  68. """write data on the nodemcu port. If 'binary' is True the debug log
  69. will show the intended output as hex, otherwise as string"""
  70. if not binary:
  71. log.debug('write: %s', output)
  72. else:
  73. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  74. self._port.write(output)
  75. self._port.flush()
  76. def writeln(self, output):
  77. """write, with linefeed"""
  78. self.write(output + '\n')
  79. def exchange(self, output):
  80. self.writeln(output)
  81. return self.expect()
  82. def close(self):
  83. """restores the nodemcu to default baudrate and then closes the port"""
  84. self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
  85. self._port.close()
  86. def prepare(self):
  87. """
  88. This uploads the protocol functions nessecary to do binary
  89. chunked transfer
  90. """
  91. log.info('Preparing esp for transfer.')
  92. data = SAVE_LUA.format(baud=self._port.baudrate)
  93. ##change any \r\n to just \n and split on that
  94. lines = data.replace('\r', '').split('\n')
  95. #remove some unneccesary spaces to conserve some bytes
  96. for line in lines:
  97. line = line.strip().replace(', ', ',').replace(' = ', '=')
  98. if len(line) == 0:
  99. continue
  100. d = self.exchange(line)
  101. #do some basic test of the result
  102. if 'unexpected' in d or len(d) > len(SAVE_LUA)+10:
  103. log.error('error in save_lua "%s"', d)
  104. return
  105. def download_file(self, filename):
  106. chunk_size = 256
  107. bytes_read = 0
  108. data = ""
  109. while True:
  110. d = self.exchange(DOWNLOAD_FILE.format(filename=filename, bytes_read=bytes_read, chunk_size=chunk_size))
  111. cmd, size, tmp_data = d.split('\n', 2)
  112. data = data + tmp_data[0:chunk_size]
  113. bytes_read = bytes_read + chunk_size
  114. if bytes_read > int(size):
  115. break
  116. data = data[0:int(size)]
  117. return data
  118. def read_file(self, filename, destination=''):
  119. if not destination:
  120. destination = filename
  121. log.info('Transfering %s to %s', filename, destination)
  122. data = self.download_file(filename)
  123. with open(destination, 'w') as f:
  124. f.write(data)
  125. def write_file(self, path, destination='', verify='none'):
  126. filename = os.path.basename(path)
  127. if not destination:
  128. destination = filename
  129. log.info('Transfering %s as %s', path, destination)
  130. self.writeln("recv()")
  131. res = self.expect('C> ')
  132. if not res.endswith('C> '):
  133. log.error('Error waiting for esp "%s"', res)
  134. return
  135. log.debug('sending destination filename "%s"', destination)
  136. self.write(destination + '\x00', True)
  137. if not self.got_ack():
  138. log.error('did not ack destination filename')
  139. return
  140. f = open(path, 'rb')
  141. content = f.read()
  142. f.close()
  143. log.debug('sending %d bytes in %s', len(content), filename)
  144. pos = 0
  145. chunk_size = 128
  146. while pos < len(content):
  147. rest = len(content) - pos
  148. if rest > chunk_size:
  149. rest = chunk_size
  150. data = content[pos:pos+rest]
  151. if not self.write_chunk(data):
  152. d = self.expect()
  153. log.error('Bad chunk response "%s" %s', d, ':'.join(x.encode('hex') for x in d))
  154. return
  155. pos += chunk_size
  156. log.debug('sending zero block')
  157. #zero size block
  158. self.write_chunk('')
  159. if verify == 'standard':
  160. log.info('Verifying...')
  161. data = self.download_file(destination)
  162. if content != data:
  163. log.error('Verification failed.')
  164. elif verify == 'sha1':
  165. #Calculate SHA1 on remote file. Extract just hash from result
  166. data = self.exchange('shafile("'+destination+'")').splitlines()[1]
  167. log.info('Remote SHA1: %s', data)
  168. #Calculate hash of local data
  169. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  170. log.info('Local SHA1: %s', filehashhex)
  171. if data != filehashhex:
  172. log.error('Verification failed.')
  173. def exec_file(self, path):
  174. filename = os.path.basename(path)
  175. log.info('Execute %s', filename)
  176. f = open(path, 'rt')
  177. res = '> '
  178. for line in f:
  179. line = line.rstrip('\r\n')
  180. retlines = (res + self.exchange(line)).splitlines()
  181. # Log all but the last line
  182. res = retlines.pop()
  183. for lin in retlines:
  184. log.info(lin)
  185. # last line
  186. log.info(res)
  187. f.close()
  188. def got_ack(self):
  189. log.debug('waiting for ack')
  190. res = self._port.read(1)
  191. log.debug('ack read %s', res.encode('hex'))
  192. return res == '\x06' #ACK
  193. def write_lines(self, data):
  194. lines = data.replace('\r', '').split('\n')
  195. for line in lines:
  196. self.exchange(line)
  197. return
  198. def write_chunk(self, chunk):
  199. log.debug('writing %d bytes chunk', len(chunk))
  200. data = '\x01' + chr(len(chunk)) + chunk
  201. if len(chunk) < 128:
  202. padding = 128 - len(chunk)
  203. log.debug('pad with %d characters', padding)
  204. data = data + (' ' * padding)
  205. log.debug("packet size %d", len(data))
  206. self.write(data)
  207. return self.got_ack()
  208. def file_list(self):
  209. log.info('Listing files')
  210. res = self.exchange(LIST_FILES)
  211. log.info(res)
  212. return res
  213. def file_do(self, f):
  214. log.info('Executing '+f)
  215. res = self.exchange('dofile("'+f+'")')
  216. log.info(res)
  217. return res
  218. def file_format(self):
  219. log.info('Formating...')
  220. res = self.exchange('file.format()')
  221. if 'format done' not in res:
  222. log.error(res)
  223. else:
  224. log.info(res)
  225. return res
  226. def node_heap(self):
  227. log.info('Heap')
  228. res = self.exchange('print(node.heap())')
  229. log.info(res)
  230. return res
  231. def node_restart(self):
  232. log.info('Restart')
  233. res = self.exchange('node.restart()')
  234. log.info(res)
  235. return res
  236. def file_compile(self, path):
  237. log.info('Compile '+path)
  238. cmd = 'node.compile("%s")' % path
  239. res = self.exchange(cmd)
  240. log.info(res)
  241. return res
  242. def file_remove(self, path):
  243. log.info('Remove '+path)
  244. cmd = 'file.remove("%s")' % path
  245. res = self.exchange(cmd)
  246. log.info(res)
  247. return res