rom_comm.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. "use strict";
  2. const EventEmitter = require("events");
  3. const fs = require("fs");
  4. const SerialPort = require("serialport").SerialPort;
  5. const log = require("./logger");
  6. const slip = require("./streams/slip");
  7. const boards = require("./boards");
  8. const delay = require("./utilities").delay;
  9. const retryPromiseUntil = require("./utilities").retryPromiseUntil;
  10. const promiseChain = require("./utilities").promiseChain;
  11. const commands = {
  12. CMD0: 0x00,
  13. CMD1: 0x01,
  14. FLASH_DOWNLOAD_BEGIN: 0x02,
  15. FLASH_DOWNLOAD_DATA: 0x03,
  16. FLASH_DOWNLOAD_DONE: 0x04,
  17. RAM_DOWNLOAD_BEGIN: 0x05,
  18. RAM_DOWNLOAD_END: 0x06,
  19. RAM_DOWNLOAD_DATA: 0x07,
  20. SYNC_FRAME: 0x08,
  21. WRITE_REGISTER: 0x09,
  22. READ_REGISTER: 0x0A,
  23. SET_FLASH_PARAMS: 0x0B,
  24. NO_COMMAND: 0xFF
  25. };
  26. const validateCommandSuccess = [
  27. commands.SYNC_FRAME,
  28. commands.FLASH_DOWNLOAD_BEGIN,
  29. commands.FLASH_DOWNLOAD_DATA,
  30. commands.FLASH_DOWNLOAD_DONE
  31. ];
  32. function commandToKey(command) {
  33. // value to key
  34. return Object.keys(commands).find((key) => commands[key] === command);
  35. }
  36. const SYNC_FRAME = new Buffer([0x07, 0x07, 0x12, 0x20,
  37. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  38. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  39. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  40. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]);
  41. const FLASH_BLOCK_SIZE = 0x400;
  42. const SUCCESS = new Buffer([0x00, 0x00]);
  43. const REQUIRED_SUCCESSFUL_SYNC_COUNT = 10;
  44. /**
  45. * An abstraction of talking to the ever so finicky ESP8266 ROM.
  46. * Many thanks to the C library (https://github.com/igrr/esptool-ck)
  47. * and the Python version of the same regard (https://github.com/themadinventor/esptool/)
  48. * that helped suss out the weird cases.
  49. */
  50. class RomComm extends EventEmitter {
  51. constructor(config) {
  52. super();
  53. this._port = new SerialPort(config.portName, {
  54. baudRate: config.baudRate,
  55. parity: 'none',
  56. stopBits: 1,
  57. xon: false,
  58. xoff: false,
  59. rtscts: false,
  60. dsrdtr: false
  61. }, false);
  62. this.bindPort();
  63. this.resetState();
  64. var boardName = config.boardName ? config.boardName : "Esp12";
  65. var BoardFactory = boards[boardName];
  66. if (BoardFactory === undefined) {
  67. throw new Error("Unkown board " + boardName);
  68. }
  69. this.board = new BoardFactory(this._port);
  70. this.config = config;
  71. }
  72. resetState() {
  73. this.setState("Unknown", {});
  74. }
  75. bindPort() {
  76. this._port.on('error', (error) => log.error("PORT ERROR", error));
  77. this.in = new slip.SlipDecoder();
  78. this.out = new slip.SlipEncoder();
  79. this._port.pipe(this.in);
  80. this.out.pipe(this._port);
  81. this.in.on("data", (data) => this.handleResponse(data));
  82. }
  83. setState(status, details) {
  84. this.state = {
  85. display: status,
  86. details: details
  87. };
  88. }
  89. /**
  90. * Response from the device are eventually sensical. Hold tight.
  91. */
  92. handleResponse(data) {
  93. // Data coming in here has been SLIP escaped
  94. if (data.length < 8) {
  95. log.error("Missing header");
  96. // Not throwing error, let it fall through
  97. return false;
  98. }
  99. let headerBytes = data.slice(0, 8);
  100. let header = this.headerPacketFrom(headerBytes);
  101. if (header.direction != 0x01) {
  102. log.error("Invaid direction", header.direction);
  103. // Again, intentionally not throwing error, it will communicate correctly eventually
  104. return false;
  105. }
  106. let commandName = commandToKey(header.command);
  107. let body = data.slice(8, 8 + header.size);
  108. // Most commands just return `SUCCESS` or 0x00 0x00
  109. if (header.command in validateCommandSuccess) {
  110. if (!body.equals(SUCCESS)) {
  111. log.error("%s returned %s", commandName, body);
  112. throw new Error("Invalid status from " + commandName + " was " + body);
  113. }
  114. }
  115. log.info("Emitting", commandName, body);
  116. this.emit("RECEIVED-" + commandName, body);
  117. return true;
  118. }
  119. /**
  120. * Opens the port and flips into bootloader
  121. */
  122. open() {
  123. return new Promise((resolve, reject) => {
  124. this._port.open((error) => {
  125. log.info("Opening port...", this._port);
  126. if (error) {
  127. reject(error);
  128. } else {
  129. this.portIsOpen = true;
  130. resolve();
  131. }
  132. });
  133. }).then(() => this.connect());
  134. }
  135. /**
  136. * Leaves bootloader mode and closes the port
  137. */
  138. close() {
  139. return this.flashAddress(0, 0)
  140. .then((result) => this.flashFinish(false))
  141. .then((result) => this._port.close((err) => {
  142. log.info("Closing port...");
  143. this.portIsOpen = false;
  144. }));
  145. }
  146. calculateChecksum(data) {
  147. // Magic Checksum starts with 0xEF
  148. var result = 0xEF;
  149. for (var i = 0; i < data.length; i++) {
  150. result ^= data[i];
  151. }
  152. return result;
  153. }
  154. /**
  155. * The process of syncing gets the software and hardware aligned.
  156. * Due to the whacky responses, you can't really wait for a proper response
  157. */
  158. sync(ignoreResponse) {
  159. log.info("Syncing");
  160. return this.sendCommand(commands.SYNC_FRAME, SYNC_FRAME, ignoreResponse)
  161. .then((response) => {
  162. if (!ignoreResponse) {
  163. log.info("Sync response completed!", response);
  164. this.board.isInBootLoader = true;
  165. }
  166. });
  167. }
  168. connect() {
  169. // Eventually responses calm down, but on initial contact, responses are not standardized.
  170. // This tries until break through is made.
  171. this._listenForSuccessfulSync();
  172. return retryPromiseUntil(() => this._connectAttempt(), () => this.board.isInBootLoader);
  173. }
  174. _connectAttempt() {
  175. return this.board.resetIntoBootLoader()
  176. .then(() => delay(100))
  177. .then(() => retryPromiseUntil(() => this._flushAndSync(), () => this.board.isInBootLoader, 10));
  178. }
  179. _flushAndSync() {
  180. return new Promise((resolve, reject) => {
  181. this._port.flush((error) => {
  182. if (error) {
  183. reject(error);
  184. }
  185. log.info("Port flushed");
  186. resolve();
  187. });
  188. }).then(() => this.sync(true));
  189. }
  190. _listenForSuccessfulSync() {
  191. let commandName = commandToKey(commands.SYNC_FRAME);
  192. let successfulSyncs = 0;
  193. this.on("RECEIVED-" + commandName, (response) => {
  194. successfulSyncs++;
  195. if (successfulSyncs >= REQUIRED_SUCCESSFUL_SYNC_COUNT) {
  196. log.info("Got enough successful syncs");
  197. this.board.isInBootLoader = true;
  198. this.removeAllListeners("RECEIVED-" + commandName);
  199. }
  200. });
  201. }
  202. /**
  203. * Send appropriate C struct header along with command as required
  204. * SEE: https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.h#L49
  205. */
  206. headerPacketFor(command, data) {
  207. let buf = new ArrayBuffer(8);
  208. let dv = new DataView(buf);
  209. let checksum = 0;
  210. if (command === commands.FLASH_DOWNLOAD_DATA) {
  211. // There are additional headers here....
  212. checksum = this.calculateChecksum(data.slice(16));
  213. } else if (command === commands.FLASH_DOWNLOAD_DONE) {
  214. // Nothing to see here
  215. } else {
  216. // Most commands want the checksum of the entire data packet
  217. checksum = this.calculateChecksum(data);
  218. }
  219. dv.setUint8(0, 0x00); // Direction, 0x00 is request
  220. dv.setUint8(1, command); // Command, see commands constant
  221. dv.setUint16(2, data.byteLength, true); // Size of request
  222. dv.setUint32(4, checksum, true);
  223. return new Buffer(buf);
  224. }
  225. /**
  226. * Unpack the response header
  227. */
  228. headerPacketFrom(buffer) {
  229. let header = {};
  230. header.direction = buffer.readUInt8(0);
  231. header.command = buffer.readUInt8(1);
  232. header.size = buffer.readUInt16LE(2);
  233. header.checksum = buffer.readUInt32LE(4);
  234. return header;
  235. }
  236. determineNumBlocks(blockSize, length) {
  237. return Math.floor((length + blockSize - 1) / blockSize);
  238. }
  239. /**
  240. * Erases the area before flashing it
  241. */
  242. prepareFlashAddress(address, size) {
  243. log.info("Preparing flash address", address, size);
  244. let numBlocks = this.determineNumBlocks(FLASH_BLOCK_SIZE, size);
  245. let sectorsPerBlock = 16;
  246. let sectorSize = 4096;
  247. let numSectors = Math.floor((size + sectorSize - 1) / sectorSize);
  248. let startSector = Math.floor(address / sectorSize);
  249. // Leave some room for header space
  250. let headSectors = sectorsPerBlock - (startSector % sectorsPerBlock);
  251. if (numSectors < headSectors) {
  252. headSectors = numSectors;
  253. }
  254. let eraseSize = (numSectors - headSectors) * sectorSize;
  255. // TODO:csd - Research this...
  256. /* SPIEraseArea function in the esp8266 ROM has a bug which causes extra area to be erased.
  257. If the address range to be erased crosses the block boundary,
  258. then extra head_sector_count sectors are erased.
  259. If the address range doesn't cross the block boundary,
  260. then extra total_sector_count sectors are erased.
  261. */
  262. if (numSectors < (2 * headSectors)) {
  263. eraseSize = ((numSectors + 1) / 2) * sectorSize;
  264. }
  265. var buffer = new ArrayBuffer(16);
  266. var dv = new DataView(buffer);
  267. dv.setUint32(0, eraseSize, true);
  268. dv.setUint32(4, numBlocks, true);
  269. dv.setUint32(8, FLASH_BLOCK_SIZE, true);
  270. dv.setUint32(12, address, true);
  271. return this.sendCommand(commands.FLASH_DOWNLOAD_BEGIN, new Buffer(buffer));
  272. }
  273. flashAddressFromFile(address, fileName) {
  274. return new Promise((resolve, reject) => {
  275. fs.readFile(fileName, (err, data) => {
  276. if (err) {
  277. reject(err);
  278. }
  279. return this.flashAddress(address, data)
  280. .then((result) => resolve(result));
  281. });
  282. });
  283. }
  284. flashSpecifications(specs) {
  285. let totalBytes = specs.reduce((counter, spec) => {
  286. return counter + spec.buffer.length;
  287. }, 0);
  288. let details = {
  289. totalFiles: specs.length,
  290. totalBytes: totalBytes,
  291. flashedBytes: 0
  292. };
  293. this.setState("Flashing", details);
  294. let promiseFunctions = specs.map((spec, index) => () => {
  295. details.currentIndex = index;
  296. details.currentAddress = spec.address;
  297. details.currentSize = spec.buffer.length;
  298. return this.flashAddress(Number.parseInt(spec.address), spec.buffer);
  299. });
  300. return promiseChain(promiseFunctions);
  301. }
  302. flashAddress(address, data) {
  303. return new Promise((resolve, reject) => {
  304. this.prepareFlashAddress(address, data.length)
  305. .then(() => {
  306. let numBlocks = this.determineNumBlocks(FLASH_BLOCK_SIZE, data.length);
  307. let requests = [];
  308. for (let seq = 0; seq < numBlocks; seq++) {
  309. let startIndex = seq * FLASH_BLOCK_SIZE;
  310. let endIndex = Math.min((seq + 1) * FLASH_BLOCK_SIZE, data.length);
  311. let block = data.slice(startIndex, endIndex);
  312. // On the first block of the first sequence, override the flash info...
  313. if (address === 0 && seq === 0 && block[0] === 0xe9) {
  314. // ... which lives in the 3rd and 4th bytes
  315. let flashInfoBuffer = this.board.flashInfoAsBytes();
  316. block[2] = flashInfoBuffer[0];
  317. block[3] = flashInfoBuffer[1];
  318. }
  319. // On the last block
  320. if (endIndex === data.length) {
  321. // Pad the remaining bits
  322. let padAmount = FLASH_BLOCK_SIZE - block.length;
  323. block = Buffer.concat([block, new Buffer(padAmount).fill(0xFF)]);
  324. }
  325. var buffer = new ArrayBuffer(16);
  326. var dv = new DataView(buffer);
  327. dv.setUint32(0, block.length, true);
  328. dv.setUint32(4, seq, true);
  329. dv.setUint32(8, 0, true); // Uhhh
  330. dv.setUint32(12, 0, true); // Uhhh
  331. requests.push(Buffer.concat([new Buffer(buffer), block]));
  332. }
  333. let promiseFunctions = requests.map((req, index) => () => {
  334. // 16 is the header
  335. this.reportBlockProgress(req.length - 16, index, requests.length);
  336. return this.sendCommand(commands.FLASH_DOWNLOAD_DATA, req);
  337. });
  338. return promiseChain(promiseFunctions);
  339. }).then((result) => resolve(result));
  340. });
  341. }
  342. reportBlockProgress(length, index, total) {
  343. this.state.details.flashedBytes += length;
  344. this.state.details.blockSize = length;
  345. this.state.details.blockIndex = index;
  346. this.state.details.totalBlocks = total;
  347. this.emit('progress', this.state);
  348. }
  349. /**
  350. * Must be called after flashing has occurred to switch modes
  351. */
  352. flashFinish(reboot) {
  353. let buffer = new ArrayBuffer(4);
  354. let dv = new DataView(buffer);
  355. // FIXME:csd - That inverted logic is correct...probably a better variable name than reboot
  356. dv.setUint32(0, reboot ? 0 : 1, true);
  357. return this.sendCommand(commands.FLASH_DOWNLOAD_DONE, new Buffer(buffer))
  358. .then((result) => {
  359. log.info("Received result", result);
  360. this.board.isInBootLoader = false;
  361. });
  362. }
  363. /**
  364. * Sends defined commands to ESP8266 and patiently awaits response through asynchronous nature of
  365. * node-serialport.
  366. */
  367. sendCommand(command, data, ignoreResponse) {
  368. // https://github.com/themadinventor/esptool/blob/master/esptool.py#L108
  369. // https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.c#L103
  370. return new Promise((resolve, reject) => {
  371. if (command != commands.NO_COMMAND) {
  372. let sendHeader = this.headerPacketFor(command, data);
  373. let message = Buffer.concat([sendHeader, data], sendHeader.length + data.length);
  374. this.out.write(message, 'buffer', (err, res) => {
  375. delay(10).then(() => {
  376. if (ignoreResponse) {
  377. resolve("Response was ignored");
  378. }
  379. if (this.portIsOpen) {
  380. this._port.drain((drainErr, results) => {
  381. log.info("Draining after write", drainErr, results);
  382. });
  383. }
  384. });
  385. });
  386. }
  387. if (!ignoreResponse) {
  388. let commandName = commandToKey(command);
  389. let key = "RECEIVED-" + commandName;
  390. if (this.listeners(key).length === 0) {
  391. log.info("Listening once", commandName);
  392. this.once(key, (response) => {
  393. resolve(response);
  394. });
  395. } else {
  396. log.warn("Someone is already awaiting for %s", commandName);
  397. }
  398. }
  399. });
  400. }
  401. }
  402. module.exports = RomComm;