uploader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. # -*- coding: utf-8 -*-
  2. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  3. """Main functionality for nodemcu-uploader"""
  4. import time
  5. import logging
  6. import hashlib
  7. import os
  8. import serial
  9. from .exceptions import CommunicationTimeout, DeviceNotFoundException, \
  10. BadResponseException, VerificationError, NoAckException
  11. from .utils import default_port, system
  12. from .luacode import RECV_LUA, SEND_LUA, LUA_FUNCTIONS, \
  13. LIST_FILES, UART_SETUP, PRINT_FILE
  14. log = logging.getLogger(__name__) # pylint: disable=C0103
  15. __all__ = ['Uploader', 'default_port']
  16. SYSTEM = system()
  17. MINIMAL_TIMEOUT = 0.001
  18. BLOCK_START = '\x01'
  19. NUL = '\x00'
  20. ACK = '\x06'
  21. class Uploader(object):
  22. """Uploader is the class for communicating with the nodemcu and
  23. that will allow various tasks like uploading files, formating the filesystem etc.
  24. """
  25. BAUD = 115200
  26. START_BAUD = 115200
  27. TIMEOUT = 5
  28. PORT = default_port()
  29. def __init__(self, port=PORT, baud=BAUD, start_baud=START_BAUD, timeout=TIMEOUT):
  30. self._timeout = Uploader.TIMEOUT
  31. self.set_timeout(timeout)
  32. log.info('opening port %s with %s baud', port, start_baud)
  33. if port == 'loop://':
  34. self._port = serial.serial_for_url(port, start_baud, timeout=timeout)
  35. else:
  36. self._port = serial.Serial(port, start_baud, timeout=timeout)
  37. self.start_baud = start_baud
  38. self.baud = baud
  39. # Keeps things working, if following conections are made:
  40. ## RTS = CH_PD (i.e reset)
  41. ## DTR = GPIO0
  42. self._port.setRTS(False)
  43. self._port.setDTR(False)
  44. def __sync():
  45. """Get in sync with LUA (this assumes that NodeMCU gets reset by the previous two lines)"""
  46. log.debug('getting in sync with LUA')
  47. self.__clear_buffers()
  48. try:
  49. self.__writeln('UUUUUUUUUUUU') # Send enough characters for auto-baud
  50. self.__clear_buffers()
  51. time.sleep(0.15) # Wait for autobaud timer to expire
  52. self.__exchange(';') # Get a defined state
  53. self.__writeln('print("%sync%");')
  54. self.__expect('%sync%\r\n> ')
  55. except CommunicationTimeout:
  56. raise DeviceNotFoundException('Device not found or wrong port')
  57. __sync()
  58. if baud != start_baud:
  59. self.__set_baudrate(baud)
  60. # Get in sync again
  61. __sync()
  62. self.line_number = 0
  63. def __set_baudrate(self, baud):
  64. """setting baudrate if supported"""
  65. log.info('Changing communication to %s baud', baud)
  66. self.__writeln(UART_SETUP.format(baud=baud))
  67. # Wait for the string to be sent before switching baud
  68. time.sleep(0.1)
  69. try:
  70. self._port.setBaudrate(baud)
  71. except AttributeError:
  72. #pySerial 2.7
  73. self._port.baudrate = baud
  74. def set_timeout(self, timeout):
  75. """Set the timeout for the communication with the device."""
  76. timeout = int(timeout) # will raise on Error
  77. self._timeout = timeout == 0 and 999999 or timeout
  78. def __clear_buffers(self):
  79. """Clears the input and output buffers"""
  80. try:
  81. self._port.reset_input_buffer()
  82. self._port.reset_output_buffer()
  83. except AttributeError:
  84. #pySerial 2.7
  85. self._port.flushInput()
  86. self._port.flushOutput()
  87. def __expect(self, exp='> ', timeout=None):
  88. """will wait for exp to be returned from nodemcu or timeout"""
  89. timeout_before = self._port.timeout
  90. timeout = timeout or self._timeout
  91. #do NOT set timeout on Windows
  92. if SYSTEM != 'Windows':
  93. # Checking for new data every 100us is fast enough
  94. if self._port.timeout != MINIMAL_TIMEOUT:
  95. self._port.timeout = MINIMAL_TIMEOUT
  96. end = time.time() + timeout
  97. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  98. data = ''
  99. while not data.endswith(exp) and time.time() <= end:
  100. data += self._port.read()
  101. log.debug('expect returned: `{0}`'.format(data))
  102. if time.time() > end:
  103. raise CommunicationTimeout('Timeout waiting for data', data)
  104. if not data.endswith(exp) and len(exp) > 0:
  105. raise BadResponseException('Bad response.', exp, data)
  106. if SYSTEM != 'Windows':
  107. self._port.timeout = timeout_before
  108. return data
  109. def __write(self, output, binary=False):
  110. """write data on the nodemcu port. If 'binary' is True the debug log
  111. will show the intended output as hex, otherwise as string"""
  112. if not binary:
  113. log.debug('write: %s', output)
  114. else:
  115. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  116. self._port.write(output)
  117. self._port.flush()
  118. def __writeln(self, output):
  119. """write, with linefeed"""
  120. self.__write(output + '\n')
  121. def __exchange(self, output, timeout=None):
  122. """Write output to the port and wait for response"""
  123. self.__writeln(output)
  124. self._port.flush()
  125. return self.__expect(timeout=timeout or self._timeout)
  126. def close(self):
  127. """restores the nodemcu to default baudrate and then closes the port"""
  128. try:
  129. if self.baud != self.start_baud:
  130. self.__set_baudrate(self.start_baud)
  131. self._port.flush()
  132. self.__clear_buffers()
  133. except serial.serialutil.SerialException:
  134. pass
  135. log.debug('closing port')
  136. self._port.close()
  137. def prepare(self):
  138. """
  139. This uploads the protocol functions nessecary to do binary
  140. chunked transfer
  141. """
  142. log.info('Preparing esp for transfer.')
  143. for func in LUA_FUNCTIONS:
  144. detected = self.__exchange('print({0})'.format(func))
  145. if detected.find('function:') == -1:
  146. break
  147. else:
  148. log.info('Preparation already done. Not adding functions again.')
  149. return True
  150. functions = RECV_LUA + '\n' + SEND_LUA
  151. data = functions.format(baud=self._port.baudrate)
  152. ##change any \r\n to just \n and split on that
  153. lines = data.replace('\r', '').split('\n')
  154. #remove some unneccesary spaces to conserve some bytes
  155. for line in lines:
  156. line = line.strip().replace(', ', ',').replace(' = ', '=')
  157. if len(line) == 0:
  158. continue
  159. resp = self.__exchange(line)
  160. #do some basic test of the result
  161. if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:
  162. log.error('error when preparing "%s"', resp)
  163. return False
  164. return True
  165. def download_file(self, filename):
  166. """Download a file from device to local filesystem"""
  167. res = self.__exchange('send("{filename}")'.format(filename=filename))
  168. if ('unexpected' in res) or ('stdin' in res):
  169. log.error('Unexpected error downloading file: %s', res)
  170. raise Exception('Unexpected error downloading file')
  171. #tell device we are ready to receive
  172. self.__write('C')
  173. #we should get a NUL terminated filename to start with
  174. sent_filename = self.__expect(NUL).strip()
  175. log.info('receiveing ' + sent_filename)
  176. #ACK to start download
  177. self.__write(ACK, True)
  178. buf = ''
  179. data = ''
  180. chunk, buf = self.__read_chunk(buf)
  181. #read chunks until we get an empty which is the end
  182. while chunk != '':
  183. self.__write(ACK, True)
  184. data = data + chunk
  185. chunk, buf = self.__read_chunk(buf)
  186. return data
  187. def read_file(self, filename, destination=''):
  188. """reading data from device into local file"""
  189. if not destination:
  190. destination = filename
  191. log.info('Transferring %s to %s', filename, destination)
  192. data = self.download_file(filename)
  193. with open(destination, 'w') as fil:
  194. fil.write(data)
  195. def write_file(self, path, destination='', verify='none'):
  196. """sends a file to the device using the transfer protocol"""
  197. filename = os.path.basename(path)
  198. if not destination:
  199. destination = filename
  200. log.info('Transferring %s as %s', path, destination)
  201. self.__writeln("recv()")
  202. res = self.__expect('C> ')
  203. if not res.endswith('C> '):
  204. log.error('Error waiting for esp "%s"', res)
  205. raise CommunicationTimeout('Error waiting for device to start receiving', res)
  206. log.debug('sending destination filename "%s"', destination)
  207. self.__write(destination + '\x00', True)
  208. if not self.__got_ack():
  209. log.error('did not ack destination filename')
  210. raise NoAckException('Device did not ACK destination filename')
  211. fil = open(path, 'rb')
  212. content = fil.read()
  213. fil.close()
  214. log.debug('sending %d bytes in %s', len(content), filename)
  215. pos = 0
  216. chunk_size = 128
  217. while pos < len(content):
  218. rest = len(content) - pos
  219. if rest > chunk_size:
  220. rest = chunk_size
  221. data = content[pos:pos+rest]
  222. if not self.__write_chunk(data):
  223. resp = self.__expect()
  224. log.error('Bad chunk response "%s" %s', resp, ':'.join(x.encode('hex') for x in resp))
  225. raise BadResponseException('Bad chunk response', ACK, resp)
  226. pos += chunk_size
  227. log.debug('sending zero block')
  228. #zero size block
  229. self.__write_chunk('')
  230. if verify != 'none':
  231. self.verify_file(path, destination, verify)
  232. def verify_file(self, path, destination, verify='none'):
  233. """Tries to verify if path has same checksum as destination.
  234. Valid options for verify is 'raw', 'sha1' or 'none'
  235. """
  236. fil = open(path, 'rb')
  237. content = fil.read()
  238. fil.close()
  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()).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. fil = open(path, 'r')
  266. res = '> '
  267. for line in fil:
  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. fil.close()
  277. def __got_ack(self):
  278. """Returns true if ACK is received"""
  279. log.debug('waiting for ack')
  280. res = self._port.read(1)
  281. log.debug('ack read %s', res.encode('hex'))
  282. return res == '\x06' #ACK
  283. def write_lines(self, data):
  284. """write lines, one by one, separated by \n to device"""
  285. lines = data.replace('\r', '').split('\n')
  286. for line in lines:
  287. self.__exchange(line)
  288. return
  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 ', ':'.join(x.encode('hex') for x in 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 up to 1 minute...')
  343. res = self.__exchange('file.format()', timeout=60)
  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