rom_comm.js 16 KB

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