uploader.py 9.3 KB

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