uploader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  3. """Main functionality for nodemcu-uploader"""
  4. # Not sure about it, because UnicodeEncodeError throws anyway
  5. # from __future__ import unicode_literals
  6. import time
  7. import logging
  8. import hashlib
  9. import os
  10. import serial
  11. from .exceptions import CommunicationTimeout, DeviceNotFoundException, \
  12. BadResponseException, VerificationError, NoAckException
  13. from .utils import default_port, system, wrap, hexify, from_file, ENCODING
  14. from .luacode import RECV_LUA, SEND_LUA, LUA_FUNCTIONS, \
  15. LIST_FILES, UART_SETUP, PRINT_FILE
  16. log = logging.getLogger(__name__) # pylint: disable=C0103
  17. __all__ = ['Uploader', 'default_port']
  18. SYSTEM = system()
  19. MINIMAL_TIMEOUT = 0.001
  20. BLOCK_START = '\x01'
  21. NUL = '\x00'
  22. ACK = '\x06'
  23. class Uploader(object):
  24. """Uploader is the class for communicating with the nodemcu and
  25. that will allow various tasks like uploading files, formating the filesystem etc.
  26. """
  27. BAUD = 115200
  28. START_BAUD = 115200
  29. TIMEOUT = 5
  30. PORT = default_port()
  31. def __init__(self, port=PORT, baud=BAUD, start_baud=START_BAUD, timeout=TIMEOUT):
  32. self._timeout = Uploader.TIMEOUT
  33. self.set_timeout(timeout)
  34. log.info('opening port %s with %s baud', port, start_baud)
  35. if port == 'loop://':
  36. self._port = serial.serial_for_url(port, start_baud, timeout=timeout)
  37. else:
  38. self._port = serial.Serial(port, start_baud, timeout=timeout)
  39. # black magic aka proxifying
  40. self._port = wrap(self._port)
  41. self.start_baud = start_baud
  42. self.baud = baud
  43. # Keeps things working, if following conections are made:
  44. ## RTS = CH_PD (i.e reset)
  45. ## DTR = GPIO0
  46. self._port.setRTS(False)
  47. self._port.setDTR(False)
  48. def __sync():
  49. """Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)"""
  50. log.debug('getting in sync with LUA')
  51. self.__clear_buffers()
  52. try:
  53. self.__writeln('UUUUUUUUUUUU') # Send enough characters for auto-baud
  54. self.__clear_buffers()
  55. time.sleep(0.30) # Wait for autobaud timer to expire
  56. self.__exchange(';') # Get a defined state
  57. self.__writeln('print("%sync%");')
  58. self.__expect('%sync%\r\n> ')
  59. except CommunicationTimeout:
  60. raise DeviceNotFoundException('Device not found or wrong port')
  61. __sync()
  62. if baud != start_baud:
  63. self.__set_baudrate(baud)
  64. # Get in sync again
  65. __sync()
  66. self.line_number = 0
  67. def __set_baudrate(self, baud):
  68. """setting baudrate if supported"""
  69. log.info('Changing communication to %s baud', baud)
  70. self.__writeln(UART_SETUP.format(baud=baud))
  71. # Wait for the string to be sent before switching baud
  72. time.sleep(0.1)
  73. try:
  74. self._port.setBaudrate(baud)
  75. except AttributeError:
  76. #pySerial 2.7
  77. self._port.baudrate = baud
  78. def set_timeout(self, timeout):
  79. """Set the timeout for the communication with the device."""
  80. timeout = int(timeout) # will raise on Error
  81. self._timeout = timeout == 0 and 999999 or timeout
  82. def __clear_buffers(self):
  83. """Clears the input and output buffers"""
  84. try:
  85. self._port.reset_input_buffer()
  86. self._port.reset_output_buffer()
  87. except AttributeError:
  88. #pySerial 2.7
  89. self._port.flushInput()
  90. self._port.flushOutput()
  91. def __expect(self, exp='> ', timeout=None):
  92. """will wait for exp to be returned from nodemcu or timeout"""
  93. timeout_before = self._port.timeout
  94. timeout = timeout or self._timeout
  95. #do NOT set timeout on Windows
  96. if SYSTEM != 'Windows':
  97. # Checking for new data every 100us is fast enough
  98. if self._port.timeout != MINIMAL_TIMEOUT:
  99. self._port.timeout = MINIMAL_TIMEOUT
  100. end = time.time() + timeout
  101. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  102. data = ''
  103. while not data.endswith(exp) and time.time() <= end:
  104. data += self._port.read()
  105. log.debug('expect returned: `{0}`'.format(data))
  106. if time.time() > end:
  107. raise CommunicationTimeout('Timeout waiting for data', data)
  108. if not data.endswith(exp) and len(exp) > 0:
  109. raise BadResponseException('Bad response.', exp, data)
  110. if SYSTEM != 'Windows':
  111. self._port.timeout = timeout_before
  112. return data
  113. def __write(self, output, binary=False):
  114. """write data on the nodemcu port. If 'binary' is True the debug log
  115. will show the intended output as hex, otherwise as string"""
  116. if not binary:
  117. log.debug('write: %s', output)
  118. else:
  119. log.debug('write binary: %s', hexify(output))
  120. self._port.write(output)
  121. self._port.flush()
  122. def __writeln(self, output):
  123. """write, with linefeed"""
  124. self.__write(output + '\n')
  125. def __exchange(self, output, timeout=None):
  126. """Write output to the port and wait for response"""
  127. self.__writeln(output)
  128. self._port.flush()
  129. return self.__expect(timeout=timeout or self._timeout)
  130. def close(self):
  131. """restores the nodemcu to default baudrate and then closes the port"""
  132. try:
  133. if self.baud != self.start_baud:
  134. self.__set_baudrate(self.start_baud)
  135. self._port.flush()
  136. self.__clear_buffers()
  137. except serial.serialutil.SerialException:
  138. pass
  139. log.debug('closing port')
  140. self._port.close()
  141. def prepare(self):
  142. """
  143. This uploads the protocol functions nessecary to do binary
  144. chunked transfer
  145. """
  146. log.info('Preparing esp for transfer.')
  147. for func in LUA_FUNCTIONS:
  148. detected = self.__exchange('print({0})'.format(func))
  149. if detected.find('function:') == -1:
  150. break
  151. else:
  152. log.info('Preparation already done. Not adding functions again.')
  153. return True
  154. functions = RECV_LUA + '\n' + SEND_LUA
  155. data = functions.format(baud=self._port.baudrate)
  156. ##change any \r\n to just \n and split on that
  157. lines = data.replace('\r', '').split('\n')
  158. #remove some unneccesary spaces to conserve some bytes
  159. for line in lines:
  160. line = line.strip().replace(', ', ',').replace(' = ', '=')
  161. if len(line) == 0:
  162. continue
  163. resp = self.__exchange(line)
  164. #do some basic test of the result
  165. if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:
  166. log.error('error when preparing "%s"', resp)
  167. return False
  168. return True
  169. def download_file(self, filename):
  170. """Download a file from device to local filesystem"""
  171. res = self.__exchange('send("{filename}")'.format(filename=filename))
  172. if ('unexpected' in res) or ('stdin' in res):
  173. log.error('Unexpected error downloading file: %s', res)
  174. raise Exception('Unexpected error downloading file')
  175. #tell device we are ready to receive
  176. self.__write('C')
  177. #we should get a NUL terminated filename to start with
  178. sent_filename = self.__expect(NUL).strip()
  179. log.info('receiveing ' + sent_filename)
  180. #ACK to start download
  181. self.__write(ACK, True)
  182. buf = ''
  183. data = ''
  184. chunk, buf = self.__read_chunk(buf)
  185. #read chunks until we get an empty which is the end
  186. while chunk != '':
  187. self.__write(ACK, True)
  188. data = data + chunk
  189. chunk, buf = self.__read_chunk(buf)
  190. return data
  191. def read_file(self, filename, destination=''):
  192. """reading data from device into local file"""
  193. if not destination:
  194. destination = filename
  195. log.info('Transferring %s to %s', filename, destination)
  196. data = self.download_file(filename)
  197. with open(destination, 'w') as fil:
  198. fil.write(data)
  199. def write_file(self, path, destination='', verify='none'):
  200. """sends a file to the device using the transfer protocol"""
  201. filename = os.path.basename(path)
  202. if not destination:
  203. destination = filename
  204. log.info('Transferring %s as %s', path, destination)
  205. self.__writeln("recv()")
  206. res = self.__expect('C> ')
  207. if not res.endswith('C> '):
  208. log.error('Error waiting for esp "%s"', res)
  209. raise CommunicationTimeout('Error waiting for device to start receiving', res)
  210. log.debug('sending destination filename "%s"', destination)
  211. self.__write(destination + '\x00', True)
  212. if not self.__got_ack():
  213. log.error('did not ack destination filename')
  214. raise NoAckException('Device did not ACK destination filename')
  215. content = from_file(path)
  216. log.debug('sending %d bytes in %s', len(content), filename)
  217. pos = 0
  218. chunk_size = 128
  219. while pos < len(content):
  220. rest = len(content) - pos
  221. if rest > chunk_size:
  222. rest = chunk_size
  223. data = content[pos:pos+rest]
  224. if not self.__write_chunk(data):
  225. resp = self.__expect()
  226. log.error('Bad chunk response "%s" %s', resp, hexify(resp))
  227. raise BadResponseException('Bad chunk response', ACK, resp)
  228. pos += chunk_size
  229. log.debug('sending zero block')
  230. #zero size block
  231. self.__write_chunk('')
  232. if verify != 'none':
  233. self.verify_file(path, destination, verify)
  234. def verify_file(self, path, destination, verify='none'):
  235. """Tries to verify if path has same checksum as destination.
  236. Valid options for verify is 'raw', 'sha1' or 'none'
  237. """
  238. content = from_file(path)
  239. log.info('Verifying using %s...' % verify)
  240. if verify == 'raw':
  241. data = self.download_file(destination)
  242. if content != data:
  243. log.error('Raw verification failed.')
  244. raise VerificationError('Verification failed.')
  245. else:
  246. log.info('Verification successful. Contents are identical.')
  247. elif verify == 'sha1':
  248. #Calculate SHA1 on remote file. Extract just hash from result
  249. data = self.__exchange('shafile("'+destination+'")').splitlines()[1]
  250. log.info('Remote SHA1: %s', data)
  251. #Calculate hash of local data
  252. filehashhex = hashlib.sha1(content.encode(ENCODING)).hexdigest()
  253. log.info('Local SHA1: %s', filehashhex)
  254. if data != filehashhex:
  255. log.error('SHA1 verification failed.')
  256. raise VerificationError('SHA1 Verification failed.')
  257. else:
  258. log.info('Verification successful. Checksums match')
  259. elif verify != 'none':
  260. raise Exception(verify + ' is not a valid verification method.')
  261. def exec_file(self, path):
  262. """execute the lines in the local file 'path'"""
  263. filename = os.path.basename(path)
  264. log.info('Execute %s', filename)
  265. content = from_file(path)
  266. res = '> '
  267. for line in content:
  268. line = line.rstrip('\r\n')
  269. retlines = (res + self.__exchange(line)).splitlines()
  270. # Log all but the last line
  271. res = retlines.pop()
  272. for lin in retlines:
  273. log.info(lin)
  274. # last line
  275. log.info(res)
  276. def __got_ack(self):
  277. """Returns true if ACK is received"""
  278. log.debug('waiting for ack')
  279. res = self._port.read(1)
  280. log.debug('ack read %s', hexify(res))
  281. return res == ACK
  282. def write_lines(self, data):
  283. """write lines, one by one, separated by \n to device"""
  284. lines = data.replace('\r', '').split('\n')
  285. for line in lines:
  286. self.__exchange(line)
  287. def __write_chunk(self, chunk):
  288. """formats and sends a chunk of data to the device according
  289. to transfer protocol"""
  290. log.debug('writing %d bytes chunk', len(chunk))
  291. data = BLOCK_START + chr(len(chunk)) + chunk
  292. if len(chunk) < 128:
  293. padding = 128 - len(chunk)
  294. log.debug('pad with %d characters', padding)
  295. data = data + (' ' * padding)
  296. log.debug("packet size %d", len(data))
  297. self.__write(data)
  298. self._port.flush()
  299. return self.__got_ack()
  300. def __read_chunk(self, buf):
  301. """Read a chunk of data"""
  302. log.debug('reading chunk')
  303. timeout_before = self._port.timeout
  304. if SYSTEM != 'Windows':
  305. # Checking for new data every 100us is fast enough
  306. if self._port.timeout != MINIMAL_TIMEOUT:
  307. self._port.timeout = MINIMAL_TIMEOUT
  308. end = time.time() + timeout_before
  309. while len(buf) < 130 and time.time() <= end:
  310. buf = buf + self._port.read()
  311. if buf[0] != BLOCK_START or len(buf) < 130:
  312. log.debug('buffer binary: %s ', hexify(buf))
  313. raise Exception('Bad blocksize or start byte')
  314. if SYSTEM != 'Windows':
  315. self._port.timeout = timeout_before
  316. chunk_size = ord(buf[1])
  317. data = buf[2:chunk_size+2]
  318. buf = buf[130:]
  319. return (data, buf)
  320. def file_list(self):
  321. """list files on the device"""
  322. log.info('Listing files')
  323. res = self.__exchange(LIST_FILES)
  324. log.info(res)
  325. res = res.split('\r\n')
  326. # skip first and last lines
  327. res = res[1:-1]
  328. files = []
  329. for line in res:
  330. files.append(line.split('\t'))
  331. return files
  332. def file_do(self, filename):
  333. """Execute a file on the device using 'do'"""
  334. log.info('Executing '+filename)
  335. res = self.__exchange('dofile("'+filename+'")')
  336. log.info(res)
  337. return res
  338. def file_format(self):
  339. """Formats device filesystem"""
  340. log.info('Formating, can take minutes depending on flash size...')
  341. res = self.__exchange('file.format()', timeout=300)
  342. if 'format done' not in res:
  343. log.error(res)
  344. else:
  345. log.info(res)
  346. return res
  347. def file_print(self, filename):
  348. """Prints a file on the device to console"""
  349. log.info('Printing ' + filename)
  350. res = self.__exchange(PRINT_FILE.format(filename=filename))
  351. log.info(res)
  352. return res
  353. def node_heap(self):
  354. """Show device heap size"""
  355. log.info('Heap')
  356. res = self.__exchange('print(node.heap())')
  357. log.info(res)
  358. return int(res.split('\r\n')[1])
  359. def node_restart(self):
  360. """Restarts device"""
  361. log.info('Restart')
  362. res = self.__exchange('node.restart()')
  363. log.info(res)
  364. return res
  365. def file_compile(self, path):
  366. """Compiles a file specified by path on the device"""
  367. log.info('Compile '+path)
  368. cmd = 'node.compile("%s")' % path
  369. res = self.__exchange(cmd)
  370. log.info(res)
  371. return res
  372. def file_remove(self, path):
  373. """Removes a file on the device"""
  374. log.info('Remove '+path)
  375. cmd = 'file.remove("%s")' % path
  376. res = self.__exchange(cmd)
  377. log.info(res)
  378. return res