uploader.py 9.6 KB

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