uploader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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, system
  10. from .luacode import DOWNLOAD_FILE, RECV_LUA, SEND_LUA, LUA_FUNCTIONS, LIST_FILES, UART_SETUP, PRINT_FILE
  11. log = logging.getLogger(__name__)
  12. __all__ = ['Uploader', 'default_port']
  13. SYSTEM = system()
  14. BLOCK_START='\x01';
  15. NUL = '\x00';
  16. ACK = '\x06';
  17. class Uploader(object):
  18. """Uploader is the class for communicating with the nodemcu and
  19. that will allow various tasks like uploading files, formating the filesystem etc.
  20. """
  21. BAUD = 9600
  22. TIMEOUT = 5
  23. PORT = default_port()
  24. def __init__(self, port=PORT, baud=BAUD):
  25. log.info('opening port %s with %s baud', port, baud)
  26. if port == 'loop://':
  27. self._port = serial.serial_for_url(port, baud, timeout=Uploader.TIMEOUT)
  28. else:
  29. self._port = serial.Serial(port, baud, timeout=Uploader.TIMEOUT)
  30. # Keeps things working, if following conections are made:
  31. ## RTS = CH_PD (i.e reset)
  32. ## DTR = GPIO0
  33. self._port.setRTS(False)
  34. self._port.setDTR(False)
  35. def sync():
  36. # Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)
  37. log.debug('getting in sync with LUA');
  38. self.clear_buffers()
  39. self.exchange(';') # Get a defined state
  40. self.writeln('print("%sync%");')
  41. self.expect('%sync%\r\n> ')
  42. sync()
  43. if baud != Uploader.BAUD:
  44. log.info('Changing communication to %s baud', baud)
  45. self.writeln(UART_SETUP.format(baud=baud))
  46. # Wait for the string to be sent before switching baud
  47. time.sleep(0.1)
  48. self.set_baudrate(baud)
  49. # Get in sync again
  50. sync()
  51. self.line_number = 0
  52. def set_baudrate(self, baud):
  53. try:
  54. self._port.setBaudrate(baud)
  55. except AttributeError:
  56. #pySerial 2.7
  57. self._port.baudrate = baud
  58. def clear_buffers(self):
  59. try:
  60. self._port.reset_input_buffer()
  61. self._port.reset_output_buffer()
  62. except AttributeError:
  63. #pySerial 2.7
  64. self._port.flushInput()
  65. self._port.flushOutput()
  66. def expect(self, exp='> ', timeout=TIMEOUT):
  67. """will wait for exp to be returned from nodemcu or timeout"""
  68. if SYSTEM != 'Windows':
  69. timer = self._port.timeout
  70. # Checking for new data every 100us is fast enough
  71. lt = 0.0001
  72. if self._port.timeout != lt:
  73. self._port.timeout = lt
  74. end = time.time() + timeout
  75. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  76. data = ''
  77. while not data.endswith(exp) and time.time() <= end:
  78. data += self._port.read()
  79. log.debug('expect returned: `{0}`'.format(data))
  80. if time.time() > end and not data.endswith(exp) and len(exp) > 0:
  81. raise Exception('Timeout expecting ' + exp)
  82. if SYSTEM != 'Windows':
  83. self._port.timeout = timer
  84. return data
  85. def write(self, output, binary=False):
  86. """write data on the nodemcu port. If 'binary' is True the debug log
  87. will show the intended output as hex, otherwise as string"""
  88. if not binary:
  89. log.debug('write: %s', output)
  90. else:
  91. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  92. self._port.write(output)
  93. self._port.flush()
  94. def writeln(self, output):
  95. """write, with linefeed"""
  96. self.write(output + '\n')
  97. def exchange(self, output):
  98. self.writeln(output)
  99. self._port.flush()
  100. return self.expect()
  101. def close(self):
  102. """restores the nodemcu to default baudrate and then closes the port"""
  103. try:
  104. self.writeln(UART_SETUP.format(baud=Uploader.BAUD))
  105. self._port.flush()
  106. self.clear_buffers()
  107. except serial.serialutil.SerialException:
  108. pass
  109. log.debug('closing port')
  110. self._port.close()
  111. def prepare(self):
  112. """
  113. This uploads the protocol functions nessecary to do binary
  114. chunked transfer
  115. """
  116. log.info('Preparing esp for transfer.')
  117. for fn in LUA_FUNCTIONS:
  118. d = self.exchange('print({0})'.format(fn))
  119. if d.find('function:') == -1:
  120. break
  121. else:
  122. log.info('Preparation already done. Not adding functions again.')
  123. return True
  124. functions = RECV_LUA + '\n' + SEND_LUA
  125. data = functions.format(baud=self._port.baudrate)
  126. ##change any \r\n to just \n and split on that
  127. lines = data.replace('\r', '').split('\n')
  128. #remove some unneccesary spaces to conserve some bytes
  129. for line in lines:
  130. line = line.strip().replace(', ', ',').replace(' = ', '=')
  131. if len(line) == 0:
  132. continue
  133. d = self.exchange(line)
  134. #do some basic test of the result
  135. if ('unexpected' in d) or ('stdin' in d) or len(d) > len(functions)+10:
  136. log.error('error when preparing "%s"', d)
  137. return False
  138. return True
  139. def download_file(self, filename):
  140. res = self.exchange('send("{filename}")'.format(filename=filename))
  141. if ('unexpected' in res) or ('stdin' in res):
  142. log.error('Unexpected error downloading file', res)
  143. raise Exception('Unexpected error downloading file')
  144. #tell device we are ready to receive
  145. self.write('C')
  146. #we should get a NUL terminated filename to start with
  147. sent_filename = self.expect(NUL).strip()
  148. log.info('receiveing ' + sent_filename)
  149. #ACK to start download
  150. self.write(ACK, True);
  151. buffer = ''
  152. data = ''
  153. chunk, buffer = self.read_chunk(buffer)
  154. #read chunks until we get an empty which is the end
  155. while chunk != '':
  156. self.write(ACK,True);
  157. data = data + chunk
  158. chunk, buffer = self.read_chunk(buffer)
  159. return data
  160. def read_file(self, filename, destination=''):
  161. if not destination:
  162. destination = filename
  163. log.info('Transfering %s to %s', filename, destination)
  164. data = self.download_file(filename)
  165. with open(destination, 'w') as f:
  166. f.write(data)
  167. def write_file(self, path, destination='', verify='none'):
  168. filename = os.path.basename(path)
  169. if not destination:
  170. destination = filename
  171. log.info('Transfering %s as %s', path, destination)
  172. self.writeln("recv()")
  173. res = self.expect('C> ')
  174. if not res.endswith('C> '):
  175. log.error('Error waiting for esp "%s"', res)
  176. return
  177. log.debug('sending destination filename "%s"', destination)
  178. self.write(destination + '\x00', True)
  179. if not self.got_ack():
  180. log.error('did not ack destination filename')
  181. return
  182. f = open(path, 'rb')
  183. content = f.read()
  184. f.close()
  185. log.debug('sending %d bytes in %s', len(content), filename)
  186. pos = 0
  187. chunk_size = 128
  188. while pos < len(content):
  189. rest = len(content) - pos
  190. if rest > chunk_size:
  191. rest = chunk_size
  192. data = content[pos:pos+rest]
  193. if not self.write_chunk(data):
  194. d = self.expect()
  195. log.error('Bad chunk response "%s" %s', d, ':'.join(x.encode('hex') for x in d))
  196. return
  197. pos += chunk_size
  198. log.debug('sending zero block')
  199. #zero size block
  200. self.write_chunk('')
  201. if verify == 'raw':
  202. log.info('Verifying...')
  203. data = self.download_file(destination)
  204. if content != data:
  205. log.error('Verification failed.')
  206. else:
  207. log.info('Verification successfull. Contents are identical.')
  208. elif verify == 'sha1':
  209. #Calculate SHA1 on remote file. Extract just hash from result
  210. data = self.exchange('shafile("'+destination+'")').splitlines()[1]
  211. log.info('Remote SHA1: %s', data)
  212. #Calculate hash of local data
  213. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  214. log.info('Local SHA1: %s', filehashhex)
  215. if data != filehashhex:
  216. log.error('Verification failed.')
  217. else:
  218. log.info('Verification successfull. Checksums match')
  219. elif verify != 'none':
  220. raise Exception(verify + ' is not a valid verification method.')
  221. def exec_file(self, path):
  222. filename = os.path.basename(path)
  223. log.info('Execute %s', filename)
  224. f = open(path, 'rt')
  225. res = '> '
  226. for line in f:
  227. line = line.rstrip('\r\n')
  228. retlines = (res + self.exchange(line)).splitlines()
  229. # Log all but the last line
  230. res = retlines.pop()
  231. for lin in retlines:
  232. log.info(lin)
  233. # last line
  234. log.info(res)
  235. f.close()
  236. def got_ack(self):
  237. log.debug('waiting for ack')
  238. res = self._port.read(1)
  239. log.debug('ack read %s', res.encode('hex'))
  240. return res == '\x06' #ACK
  241. def write_lines(self, data):
  242. lines = data.replace('\r', '').split('\n')
  243. for line in lines:
  244. self.exchange(line)
  245. return
  246. def write_chunk(self, chunk):
  247. log.debug('writing %d bytes chunk', len(chunk))
  248. data = BLOCK_START + chr(len(chunk)) + chunk
  249. if len(chunk) < 128:
  250. padding = 128 - len(chunk)
  251. log.debug('pad with %d characters', padding)
  252. data = data + (' ' * padding)
  253. log.debug("packet size %d", len(data))
  254. self.write(data)
  255. self._port.flush()
  256. return self.got_ack()
  257. def read_chunk(self, buffer):
  258. log.debug('reading chunk')
  259. timeout = self._port.timeout
  260. if SYSTEM != 'Windows':
  261. timer = self._port.timeout
  262. # Checking for new data every 100us is fast enough
  263. lt = 0.0001
  264. if self._port.timeout != lt:
  265. self._port.timeout = lt
  266. end = time.time() + timeout
  267. while len(buffer) < 130 and time.time() <= end:
  268. buffer = buffer + self._port.read()
  269. if buffer[0] != BLOCK_START or len(buffer) < 130:
  270. print 'buffer size:', len(buffer)
  271. log.debug('buffer binary: ', ':'.join(x.encode('hex') for x in buffer))
  272. raise Exception('Bad blocksize or start byte')
  273. chunk_size = ord(buffer[1])
  274. data = buffer[2:chunk_size+2]
  275. buffer = buffer[130:]
  276. return (data, buffer)
  277. def file_list(self):
  278. log.info('Listing files')
  279. res = self.exchange(LIST_FILES)
  280. log.info(res)
  281. return res
  282. def file_do(self, f):
  283. log.info('Executing '+f)
  284. res = self.exchange('dofile("'+f+'")')
  285. log.info(res)
  286. return res
  287. def file_format(self):
  288. log.info('Formating...')
  289. res = self.exchange('file.format()')
  290. if 'format done' not in res:
  291. log.error(res)
  292. else:
  293. log.info(res)
  294. return res
  295. def file_print(self, f):
  296. log.info('Printing ' + f)
  297. res = self.exchange(PRINT_FILE.format(filename=f))
  298. log.info(res)
  299. return res
  300. def node_heap(self):
  301. log.info('Heap')
  302. res = self.exchange('print(node.heap())')
  303. log.info(res)
  304. return res
  305. def node_restart(self):
  306. log.info('Restart')
  307. res = self.exchange('node.restart()')
  308. log.info(res)
  309. return res
  310. def file_compile(self, path):
  311. log.info('Compile '+path)
  312. cmd = 'node.compile("%s")' % path
  313. res = self.exchange(cmd)
  314. log.info(res)
  315. return res
  316. def file_remove(self, path):
  317. log.info('Remove '+path)
  318. cmd = 'file.remove("%s")' % path
  319. res = self.exchange(cmd)
  320. log.info(res)
  321. return res