uploader.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 = 9600
  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.__exchange(';') # Get a defined state
  50. self.__writeln('print("%sync%");')
  51. self.__expect('%sync%\r\n> ')
  52. except CommunicationTimeout:
  53. raise DeviceNotFoundException('Device not found or wrong port')
  54. __sync()
  55. if baud != start_baud:
  56. self.__set_baudrate(baud)
  57. # Get in sync again
  58. __sync()
  59. self.line_number = 0
  60. def __set_baudrate(self, baud):
  61. """setting baudrate if supported"""
  62. log.info('Changing communication to %s baud', baud)
  63. self.__writeln(UART_SETUP.format(baud=baud))
  64. # Wait for the string to be sent before switching baud
  65. time.sleep(0.1)
  66. try:
  67. self._port.setBaudrate(baud)
  68. except AttributeError:
  69. #pySerial 2.7
  70. self._port.baudrate = baud
  71. def set_timeout(self, timeout):
  72. """Set the timeout for the communication with the device."""
  73. timeout = int(timeout) # will raise on Error
  74. self._timeout = timeout == 0 and 999999 or timeout
  75. def __clear_buffers(self):
  76. """Clears the input and output buffers"""
  77. try:
  78. self._port.reset_input_buffer()
  79. self._port.reset_output_buffer()
  80. except AttributeError:
  81. #pySerial 2.7
  82. self._port.flushInput()
  83. self._port.flushOutput()
  84. def __expect(self, exp='> ', timeout=None):
  85. """will wait for exp to be returned from nodemcu or timeout"""
  86. timeout_before = self._port.timeout
  87. timeout = timeout or self._timeout
  88. #do NOT set timeout on Windows
  89. if SYSTEM != 'Windows':
  90. # Checking for new data every 100us is fast enough
  91. if self._port.timeout != MINIMAL_TIMEOUT:
  92. self._port.timeout = MINIMAL_TIMEOUT
  93. end = time.time() + timeout
  94. # Finish as soon as either exp matches or we run out of time (work like dump, but faster on success)
  95. data = ''
  96. while not data.endswith(exp) and time.time() <= end:
  97. data += self._port.read()
  98. log.debug('expect returned: `{0}`'.format(data))
  99. if time.time() > end:
  100. raise CommunicationTimeout('Timeout waiting for data', data)
  101. if not data.endswith(exp) and len(exp) > 0:
  102. raise BadResponseException('Bad response.', exp, data)
  103. if SYSTEM != 'Windows':
  104. self._port.timeout = timeout_before
  105. return data
  106. def __write(self, output, binary=False):
  107. """write data on the nodemcu port. If 'binary' is True the debug log
  108. will show the intended output as hex, otherwise as string"""
  109. if not binary:
  110. log.debug('write: %s', output)
  111. else:
  112. log.debug('write binary: %s', ':'.join(x.encode('hex') for x in output))
  113. self._port.write(output)
  114. self._port.flush()
  115. def __writeln(self, output):
  116. """write, with linefeed"""
  117. self.__write(output + '\n')
  118. def __exchange(self, output, timeout=None):
  119. """Write output to the port and wait for response"""
  120. self.__writeln(output)
  121. self._port.flush()
  122. return self.__expect(timeout=timeout or self._timeout)
  123. def close(self):
  124. """restores the nodemcu to default baudrate and then closes the port"""
  125. try:
  126. if self.baud != self.start_baud:
  127. self.__set_baudrate(self.start_baud)
  128. self._port.flush()
  129. self.__clear_buffers()
  130. except serial.serialutil.SerialException:
  131. pass
  132. log.debug('closing port')
  133. self._port.close()
  134. def prepare(self):
  135. """
  136. This uploads the protocol functions nessecary to do binary
  137. chunked transfer
  138. """
  139. log.info('Preparing esp for transfer.')
  140. for func in LUA_FUNCTIONS:
  141. detected = self.__exchange('print({0})'.format(func))
  142. if detected.find('function:') == -1:
  143. break
  144. else:
  145. log.info('Preparation already done. Not adding functions again.')
  146. return True
  147. functions = RECV_LUA + '\n' + SEND_LUA
  148. data = functions.format(baud=self._port.baudrate)
  149. ##change any \r\n to just \n and split on that
  150. lines = data.replace('\r', '').split('\n')
  151. #remove some unneccesary spaces to conserve some bytes
  152. for line in lines:
  153. line = line.strip().replace(', ', ',').replace(' = ', '=')
  154. if len(line) == 0:
  155. continue
  156. resp = self.__exchange(line)
  157. #do some basic test of the result
  158. if ('unexpected' in resp) or ('stdin' in resp) or len(resp) > len(functions)+10:
  159. log.error('error when preparing "%s"', resp)
  160. return False
  161. return True
  162. def download_file(self, filename):
  163. """Download a file from device to local filesystem"""
  164. res = self.__exchange('send("{filename}")'.format(filename=filename))
  165. if ('unexpected' in res) or ('stdin' in res):
  166. log.error('Unexpected error downloading file: %s', res)
  167. raise Exception('Unexpected error downloading file')
  168. #tell device we are ready to receive
  169. self.__write('C')
  170. #we should get a NUL terminated filename to start with
  171. sent_filename = self.__expect(NUL).strip()
  172. log.info('receiveing ' + sent_filename)
  173. #ACK to start download
  174. self.__write(ACK, True)
  175. buf = ''
  176. data = ''
  177. chunk, buf = self.__read_chunk(buf)
  178. #read chunks until we get an empty which is the end
  179. while chunk != '':
  180. self.__write(ACK, True)
  181. data = data + chunk
  182. chunk, buf = self.__read_chunk(buf)
  183. return data
  184. def read_file(self, filename, destination=''):
  185. """reading data from device into local file"""
  186. if not destination:
  187. destination = filename
  188. log.info('Transfering %s to %s', filename, destination)
  189. data = self.download_file(filename)
  190. with open(destination, 'w') as fil:
  191. fil.write(data)
  192. def write_file(self, path, destination='', verify='none'):
  193. """sends a file to the device using the transfer protocol"""
  194. filename = os.path.basename(path)
  195. if not destination:
  196. destination = filename
  197. log.info('Transfering %s as %s', path, destination)
  198. self.__writeln("recv()")
  199. res = self.__expect('C> ')
  200. if not res.endswith('C> '):
  201. log.error('Error waiting for esp "%s"', res)
  202. raise CommunicationTimeout('Error waiting for device to start receiving', res)
  203. log.debug('sending destination filename "%s"', destination)
  204. self.__write(destination + '\x00', True)
  205. if not self.__got_ack():
  206. log.error('did not ack destination filename')
  207. raise NoAckException('Device did not ACK destination filename')
  208. fil = open(path, 'rb')
  209. content = fil.read()
  210. fil.close()
  211. log.debug('sending %d bytes in %s', len(content), filename)
  212. pos = 0
  213. chunk_size = 128
  214. while pos < len(content):
  215. rest = len(content) - pos
  216. if rest > chunk_size:
  217. rest = chunk_size
  218. data = content[pos:pos+rest]
  219. if not self.__write_chunk(data):
  220. resp = self.__expect()
  221. log.error('Bad chunk response "%s" %s', resp, ':'.join(x.encode('hex') for x in resp))
  222. raise BadResponseException('Bad chunk response', ACK, resp)
  223. pos += chunk_size
  224. log.debug('sending zero block')
  225. #zero size block
  226. self.__write_chunk('')
  227. if verify != 'none':
  228. self.verify_file(path, destination, verify)
  229. def verify_file(self, path, destination, verify='none'):
  230. """Tries to verify if path has same checksum as destination.
  231. Valid options for verify is 'raw', 'sha1' or 'none'
  232. """
  233. fil = open(path, 'rb')
  234. content = fil.read()
  235. fil.close()
  236. if verify == 'raw':
  237. log.info('Verifying...')
  238. data = self.download_file(destination)
  239. if content != data:
  240. log.error('Raw verification failed.')
  241. raise VerificationError('Verification failed.')
  242. else:
  243. log.info('Verification successfull. Contents are identical.')
  244. elif verify == 'sha1':
  245. #Calculate SHA1 on remote file. Extract just hash from result
  246. data = self.__exchange('shafile("'+destination+'")').splitlines()[1]
  247. log.info('Remote SHA1: %s', data)
  248. #Calculate hash of local data
  249. filehashhex = hashlib.sha1(content.encode()).hexdigest()
  250. log.info('Local SHA1: %s', filehashhex)
  251. if data != filehashhex:
  252. log.error('SHA1 verification failed.')
  253. raise VerificationError('SHA1 Verification failed.')
  254. else:
  255. log.info('Verification successfull. Checksums match')
  256. elif verify != 'none':
  257. raise Exception(verify + ' is not a valid verification method.')
  258. def exec_file(self, path):
  259. """execute the lines in the local file 'path'"""
  260. filename = os.path.basename(path)
  261. log.info('Execute %s', filename)
  262. fil = open(path, 'r')
  263. res = '> '
  264. for line in fil:
  265. line = line.rstrip('\r\n')
  266. retlines = (res + self.__exchange(line)).splitlines()
  267. # Log all but the last line
  268. res = retlines.pop()
  269. for lin in retlines:
  270. log.info(lin)
  271. # last line
  272. log.info(res)
  273. fil.close()
  274. def __got_ack(self):
  275. """Returns true if ACK is received"""
  276. log.debug('waiting for ack')
  277. res = self._port.read(1)
  278. log.debug('ack read %s', res.encode('hex'))
  279. return res == '\x06' #ACK
  280. def write_lines(self, data):
  281. """write lines, one by one, separated by \n to device"""
  282. lines = data.replace('\r', '').split('\n')
  283. for line in lines:
  284. self.__exchange(line)
  285. return
  286. def __write_chunk(self, chunk):
  287. """formats and sends a chunk of data to the device according
  288. to transfer protocol"""
  289. log.debug('writing %d bytes chunk', len(chunk))
  290. data = BLOCK_START + chr(len(chunk)) + chunk
  291. if len(chunk) < 128:
  292. padding = 128 - len(chunk)
  293. log.debug('pad with %d characters', padding)
  294. data = data + (' ' * padding)
  295. log.debug("packet size %d", len(data))
  296. self.__write(data)
  297. self._port.flush()
  298. return self.__got_ack()
  299. def __read_chunk(self, buf):
  300. """Read a chunk of data"""
  301. log.debug('reading chunk')
  302. timeout_before = self._port.timeout
  303. if SYSTEM != 'Windows':
  304. # Checking for new data every 100us is fast enough
  305. if self._port.timeout != MINIMAL_TIMEOUT:
  306. self._port.timeout = MINIMAL_TIMEOUT
  307. end = time.time() + timeout_before
  308. while len(buf) < 130 and time.time() <= end:
  309. buf = buf + self._port.read()
  310. if buf[0] != BLOCK_START or len(buf) < 130:
  311. print 'buffer size:', len(buf)
  312. log.debug('buffer binary: %s ', ':'.join(x.encode('hex') for x in 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 up to 1 minute...')
  341. res = self.__exchange('file.format()', timeout=60)
  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