uploader.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 DOWNLOAD_FILE, SAVE_LUA, LUA_FUNCTIONS, 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 with %s baud', port, baud)
  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.clear_buffers()
  35. self.exchange(';') # Get a defined state
  36. self.writeln('print("%sync%");')
  37. self.expect('%sync%\r\n> ')
  38. sync()
  39. if baud != Uploader.BAUD:
  40. log.info('Changing communication to %s baud', baud)
  41. self.writeln(UART_SETUP.format(baud=baud))
  42. # Wait for the string to be sent before switching baud
  43. time.sleep(0.1)
  44. self.set_baudrate(baud)
  45. # Get in sync again
  46. sync()
  47. self.line_number = 0
  48. def set_baudrate(self, baud):
  49. try:
  50. self._port.setBaudrate(baud)
  51. except AttributeError:
  52. #pySerial 2.7
  53. self._port.baudrate = baud
  54. def clear_buffers(self):
  55. try:
  56. self._port.reset_input_buffer()
  57. self._port.reset_output_buffer()
  58. except AttributeError:
  59. #pySerial 2.7
  60. self._port.flushInput()
  61. self._port.flushOutput()
  62. def expect(self, exp='> ', timeout=TIMEOUT):
  63. """will wait for exp to be returned from nodemcu or timeout"""
  64. timer = self._port.timeout
  65. # Checking for new data every 100us is fast enough
  66. lt = 0.0001
  67. if self._port.timeout != lt:
  68. self._port.timeout = lt
  69. end = time.time() + timeout
  70. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  71. data = ''
  72. while not data.endswith(exp) and time.time() <= end:
  73. data += self._port.read()
  74. if time.time() > end and not data.endswith(exp) and len(exp) > 0:
  75. raise Exception('Timeout expecting ' + exp)
  76. self._port.timeout = timer
  77. log.debug('expect returned: `{0}`'.format(data))
  78. return data
  79. def write(self, output, binary=False):
  80. """write data on the nodemcu port. If 'binary' is True the debug log
  81. will show the intended output as hex, otherwise as string"""
  82. if not binary:
  83. log.debug('write: %s', output)
  84. else:
  85. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  86. self._port.write(output)
  87. self._port.flush()
  88. def writeln(self, output):
  89. """write, with linefeed"""
  90. self.write(output + '\n')
  91. def exchange(self, output):
  92. self.writeln(output)
  93. self._port.flush()
  94. return self.expect()
  95. def close(self):
  96. """restores the nodemcu to default baudrate and then closes the port"""
  97. self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
  98. self._port.flush()
  99. self.clear_buffers()
  100. log.debug('closing port')
  101. self._port.close()
  102. def prepare(self):
  103. """
  104. This uploads the protocol functions nessecary to do binary
  105. chunked transfer
  106. """
  107. log.info('Preparing esp for transfer.')
  108. for fn in LUA_FUNCTIONS:
  109. d = self.exchange('print({0})'.format(fn))
  110. if d.find('function:') == -1:
  111. break
  112. else:
  113. log.debug('Found all required lua functions, no need to upload them')
  114. return True
  115. data = SAVE_LUA.format(baud=self._port.baudrate)
  116. ##change any \r\n to just \n and split on that
  117. lines = data.replace('\r', '').split('\n')
  118. #remove some unneccesary spaces to conserve some bytes
  119. for line in lines:
  120. line = line.strip().replace(', ', ',').replace(' = ', '=')
  121. if len(line) == 0:
  122. continue
  123. d = self.exchange(line)
  124. #do some basic test of the result
  125. if ('unexpected' in d) or ('stdin' in d) or len(d) > len(SAVE_LUA)+10:
  126. log.error('error in save_lua "%s"', d)
  127. return False
  128. return True
  129. def download_file(self, filename):
  130. chunk_size = 256
  131. bytes_read = 0
  132. data = ""
  133. while True:
  134. d = self.exchange(DOWNLOAD_FILE.format(filename=filename, bytes_read=bytes_read, chunk_size=chunk_size))
  135. cmd, size, tmp_data = d.split('\n', 2)
  136. data = data + tmp_data[0:chunk_size]
  137. bytes_read = bytes_read + chunk_size
  138. if bytes_read > int(size):
  139. break
  140. data = data[0:int(size)]
  141. return data
  142. def read_file(self, filename, destination=''):
  143. if not destination:
  144. destination = filename
  145. log.info('Transfering %s to %s', filename, destination)
  146. data = self.download_file(filename)
  147. with open(destination, 'w') as f:
  148. f.write(data)
  149. def write_file(self, path, destination='', verify='none'):
  150. filename = os.path.basename(path)
  151. if not destination:
  152. destination = filename
  153. log.info('Transfering %s as %s', path, destination)
  154. self.writeln("recv()")
  155. res = self.expect('C> ')
  156. if not res.endswith('C> '):
  157. log.error('Error waiting for esp "%s"', res)
  158. return
  159. log.debug('sending destination filename "%s"', destination)
  160. self.write(destination + '\x00', True)
  161. if not self.got_ack():
  162. log.error('did not ack destination filename')
  163. return
  164. f = open(path, 'rb')
  165. content = f.read()
  166. f.close()
  167. log.debug('sending %d bytes in %s', len(content), filename)
  168. pos = 0
  169. chunk_size = 128
  170. while pos < len(content):
  171. rest = len(content) - pos
  172. if rest > chunk_size:
  173. rest = chunk_size
  174. data = content[pos:pos+rest]
  175. if not self.write_chunk(data):
  176. d = self.expect()
  177. log.error('Bad chunk response "%s" %s', d, ':'.join(x.encode('hex') for x in d))
  178. return
  179. pos += chunk_size
  180. log.debug('sending zero block')
  181. #zero size block
  182. self.write_chunk('')
  183. if verify == 'standard':
  184. log.info('Verifying...')
  185. data = self.download_file(destination)
  186. if content != data:
  187. log.error('Verification failed.')
  188. elif verify == 'sha1':
  189. #Calculate SHA1 on remote file. Extract just hash from result
  190. data = self.exchange('shafile("'+destination+'")').splitlines()[1]
  191. log.info('Remote SHA1: %s', data)
  192. #Calculate hash of local data
  193. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  194. log.info('Local SHA1: %s', filehashhex)
  195. if data != filehashhex:
  196. log.error('Verification failed.')
  197. def exec_file(self, path):
  198. filename = os.path.basename(path)
  199. log.info('Execute %s', filename)
  200. f = open(path, 'rt')
  201. res = '> '
  202. for line in f:
  203. line = line.rstrip('\r\n')
  204. retlines = (res + self.exchange(line)).splitlines()
  205. # Log all but the last line
  206. res = retlines.pop()
  207. for lin in retlines:
  208. log.info(lin)
  209. # last line
  210. log.info(res)
  211. f.close()
  212. def got_ack(self):
  213. log.debug('waiting for ack')
  214. res = self._port.read(1)
  215. log.debug('ack read %s', res.encode('hex'))
  216. return res == '\x06' #ACK
  217. def write_lines(self, data):
  218. lines = data.replace('\r', '').split('\n')
  219. for line in lines:
  220. self.exchange(line)
  221. return
  222. def write_chunk(self, chunk):
  223. log.debug('writing %d bytes chunk', len(chunk))
  224. data = '\x01' + chr(len(chunk)) + chunk
  225. if len(chunk) < 128:
  226. padding = 128 - len(chunk)
  227. log.debug('pad with %d characters', padding)
  228. data = data + (' ' * padding)
  229. log.debug("packet size %d", len(data))
  230. self.write(data)
  231. self._port.flush()
  232. return self.got_ack()
  233. def file_list(self):
  234. log.info('Listing files')
  235. res = self.exchange(LIST_FILES)
  236. log.info(res)
  237. return res
  238. def file_do(self, f):
  239. log.info('Executing '+f)
  240. res = self.exchange('dofile("'+f+'")')
  241. log.info(res)
  242. return res
  243. def file_format(self):
  244. log.info('Formating...')
  245. res = self.exchange('file.format()')
  246. if 'format done' not in res:
  247. log.error(res)
  248. else:
  249. log.info(res)
  250. return res
  251. def node_heap(self):
  252. log.info('Heap')
  253. res = self.exchange('print(node.heap())')
  254. log.info(res)
  255. return res
  256. def node_restart(self):
  257. log.info('Restart')
  258. res = self.exchange('node.restart()')
  259. log.info(res)
  260. return res
  261. def file_compile(self, path):
  262. log.info('Compile '+path)
  263. cmd = 'node.compile("%s")' % path
  264. res = self.exchange(cmd)
  265. log.info(res)
  266. return res
  267. def file_remove(self, path):
  268. log.info('Remove '+path)
  269. cmd = 'file.remove("%s")' % path
  270. res = self.exchange(cmd)
  271. log.info(res)
  272. return res