uploader.py 16 KB

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