uploader.py 14 KB

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