uploader.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. try:
  98. self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
  99. self._port.flush()
  100. self.clear_buffers()
  101. except serial.serialutil.SerialException:
  102. pass
  103. log.debug('closing port')
  104. self._port.close()
  105. def prepare(self):
  106. """
  107. This uploads the protocol functions nessecary to do binary
  108. chunked transfer
  109. """
  110. log.info('Preparing esp for transfer.')
  111. for fn in LUA_FUNCTIONS:
  112. d = self.exchange('print({0})'.format(fn))
  113. if d.find('function:') == -1:
  114. break
  115. else:
  116. log.debug('Found all required lua functions, no need to upload them')
  117. return True
  118. data = SAVE_LUA.format(baud=self._port.baudrate)
  119. ##change any \r\n to just \n and split on that
  120. lines = data.replace('\r', '').split('\n')
  121. #remove some unneccesary spaces to conserve some bytes
  122. for line in lines:
  123. line = line.strip().replace(', ', ',').replace(' = ', '=')
  124. if len(line) == 0:
  125. continue
  126. d = self.exchange(line)
  127. #do some basic test of the result
  128. if ('unexpected' in d) or ('stdin' in d) or len(d) > len(SAVE_LUA)+10:
  129. log.error('error in save_lua "%s"', d)
  130. return False
  131. return True
  132. def download_file(self, filename):
  133. chunk_size = 256
  134. bytes_read = 0
  135. data = ""
  136. while True:
  137. d = self.exchange(DOWNLOAD_FILE.format(filename=filename, bytes_read=bytes_read, chunk_size=chunk_size))
  138. cmd, size, tmp_data = d.split('\n', 2)
  139. data = data + tmp_data[0:chunk_size]
  140. bytes_read = bytes_read + chunk_size
  141. if bytes_read > int(size):
  142. break
  143. data = data[0:int(size)]
  144. return data
  145. def read_file(self, filename, destination=''):
  146. if not destination:
  147. destination = filename
  148. log.info('Transfering %s to %s', filename, destination)
  149. data = self.download_file(filename)
  150. with open(destination, 'w') as f:
  151. f.write(data)
  152. def write_file(self, path, destination='', verify='none'):
  153. filename = os.path.basename(path)
  154. if not destination:
  155. destination = filename
  156. log.info('Transfering %s as %s', path, destination)
  157. self.writeln("recv()")
  158. res = self.expect('C> ')
  159. if not res.endswith('C> '):
  160. log.error('Error waiting for esp "%s"', res)
  161. return
  162. log.debug('sending destination filename "%s"', destination)
  163. self.write(destination + '\x00', True)
  164. if not self.got_ack():
  165. log.error('did not ack destination filename')
  166. return
  167. f = open(path, 'rb')
  168. content = f.read()
  169. f.close()
  170. log.debug('sending %d bytes in %s', len(content), filename)
  171. pos = 0
  172. chunk_size = 128
  173. while pos < len(content):
  174. rest = len(content) - pos
  175. if rest > chunk_size:
  176. rest = chunk_size
  177. data = content[pos:pos+rest]
  178. if not self.write_chunk(data):
  179. d = self.expect()
  180. log.error('Bad chunk response "%s" %s', d, ':'.join(x.encode('hex') for x in d))
  181. return
  182. pos += chunk_size
  183. log.debug('sending zero block')
  184. #zero size block
  185. self.write_chunk('')
  186. if verify == 'standard':
  187. log.info('Verifying...')
  188. data = self.download_file(destination)
  189. if content != data:
  190. log.error('Verification failed.')
  191. elif verify == 'sha1':
  192. #Calculate SHA1 on remote file. Extract just hash from result
  193. data = self.exchange('shafile("'+destination+'")').splitlines()[1]
  194. log.info('Remote SHA1: %s', data)
  195. #Calculate hash of local data
  196. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  197. log.info('Local SHA1: %s', filehashhex)
  198. if data != filehashhex:
  199. log.error('Verification failed.')
  200. def exec_file(self, path):
  201. filename = os.path.basename(path)
  202. log.info('Execute %s', filename)
  203. f = open(path, 'rt')
  204. res = '> '
  205. for line in f:
  206. line = line.rstrip('\r\n')
  207. retlines = (res + self.exchange(line)).splitlines()
  208. # Log all but the last line
  209. res = retlines.pop()
  210. for lin in retlines:
  211. log.info(lin)
  212. # last line
  213. log.info(res)
  214. f.close()
  215. def got_ack(self):
  216. log.debug('waiting for ack')
  217. res = self._port.read(1)
  218. log.debug('ack read %s', res.encode('hex'))
  219. return res == '\x06' #ACK
  220. def write_lines(self, data):
  221. lines = data.replace('\r', '').split('\n')
  222. for line in lines:
  223. self.exchange(line)
  224. return
  225. def write_chunk(self, chunk):
  226. log.debug('writing %d bytes chunk', len(chunk))
  227. data = '\x01' + chr(len(chunk)) + chunk
  228. if len(chunk) < 128:
  229. padding = 128 - len(chunk)
  230. log.debug('pad with %d characters', padding)
  231. data = data + (' ' * padding)
  232. log.debug("packet size %d", len(data))
  233. self.write(data)
  234. self._port.flush()
  235. return self.got_ack()
  236. def file_list(self):
  237. log.info('Listing files')
  238. res = self.exchange(LIST_FILES)
  239. log.info(res)
  240. return res
  241. def file_do(self, f):
  242. log.info('Executing '+f)
  243. res = self.exchange('dofile("'+f+'")')
  244. log.info(res)
  245. return res
  246. def file_format(self):
  247. log.info('Formating...')
  248. res = self.exchange('file.format()')
  249. if 'format done' not in res:
  250. log.error(res)
  251. else:
  252. log.info(res)
  253. return res
  254. def node_heap(self):
  255. log.info('Heap')
  256. res = self.exchange('print(node.heap())')
  257. log.info(res)
  258. return res
  259. def node_restart(self):
  260. log.info('Restart')
  261. res = self.exchange('node.restart()')
  262. log.info(res)
  263. return res
  264. def file_compile(self, path):
  265. log.info('Compile '+path)
  266. cmd = 'node.compile("%s")' % path
  267. res = self.exchange(cmd)
  268. log.info(res)
  269. return res
  270. def file_remove(self, path):
  271. log.info('Remove '+path)
  272. cmd = 'file.remove("%s")' % path
  273. res = self.exchange(cmd)
  274. log.info(res)
  275. return res