uploader.py 16 KB

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