uploader.py 13 KB

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