rom_comm.js 14 KB

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