rom_comm.js 16 KB

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