rom_comm.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. "use strict";
  2. const SerialPort = require("serialport").SerialPort;
  3. const slip = require("./streams/slip");
  4. // ../esptool.py --port /dev/cu.SLAB_USBtoUART --baud 115200 \
  5. // write_flash --flash_freq 80m --flash_mode qio --flash_size 32m \
  6. // 0x0000 "boot_v1.4(b1).bin" 0x1000 espruino_esp8266_user1.bin \
  7. // 0x3FC000 esp_init_data_default.bin 0x3FE000 blank.bin
  8. const commands = {
  9. CMD0: 0x00,
  10. CMD1: 0x01,
  11. FLASH_DOWNLOAD_BEGIN: 0x02,
  12. FLASH_DOWNLOAD_DATA: 0x03,
  13. FLASH_DOWNLOAD_DONE: 0x04,
  14. RAM_DOWNLOAD_BEGIN: 0x05,
  15. RAM_DOWNLOAD_END: 0x06,
  16. RAM_DOWNLOAD_DATA: 0x07,
  17. SYNC_FRAME: 0x08,
  18. WRITE_REGISTER: 0x09,
  19. READ_REGISTER: 0x0A,
  20. SET_FLASH_PARAMS: 0x0B,
  21. NO_COMMAND: 0xFF
  22. };
  23. function commandToKey(command) {
  24. // value to key
  25. return Object.keys(commands).find((key) => commands[key] === command);
  26. }
  27. const SYNC_FRAME = new Buffer([0x07, 0x07, 0x12, 0x20,
  28. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  29. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  30. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
  31. 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55]);
  32. var debug = function() {};
  33. function delay(time) {
  34. return new Promise((resolve) => {
  35. debug("Delaying for", time);
  36. setTimeout(resolve, time);
  37. });
  38. }
  39. function repeatPromise(times, callback) {
  40. let chain = Promise.resolve();
  41. for (let i = 0; i < times; i++) {
  42. chain = chain.then(() => callback());
  43. }
  44. return chain;
  45. }
  46. class EspBoard {
  47. constructor(port) {
  48. this.port = port;
  49. }
  50. portSet(options) {
  51. return new Promise((resolve, reject) => {
  52. debug("Setting port", options);
  53. this.port.set(options, (err, result) => {
  54. if (err) {
  55. reject(err);
  56. }
  57. resolve(result);
  58. });
  59. });
  60. }
  61. resetIntoBootLoader() {
  62. // RTS - Request To Send
  63. // DTR - Data Terminal Ready
  64. debug("Resetting board");
  65. return this.portSet({rts: true, dtr:false})
  66. .then(() => delay(5))
  67. .then(() => this.portSet({rts: false, dtr: true}))
  68. .then(() => delay(50))
  69. .then(() => this.portSet({rts: false, dtr: false}));
  70. }
  71. }
  72. class RomComm {
  73. constructor(config) {
  74. if (config.debug) {
  75. debug = config.debug;
  76. }
  77. this._port = new SerialPort(config.portName, {
  78. baudRate: config.baudRate,
  79. parity: 'none',
  80. stopBits: 1,
  81. xon: false,
  82. xoff: false,
  83. rtscts: false,
  84. dsrdtr: false
  85. }, false);
  86. this.bindPort();
  87. var BoardFactory = config.BoardFactory ? config.BoardFactory : EspBoard;
  88. this.board = new BoardFactory(this._port);
  89. this.config = config;
  90. this.isInBootLoader = false;
  91. }
  92. bindPort() {
  93. this._port.on('error', (error) => debug("PORT ERROR", error));
  94. this.in = new slip.SlipDecoder({debug: debug});
  95. this.out = new slip.SlipEncoder({debug: debug});
  96. this._port.pipe(this.in);
  97. this.out.pipe(this._port);
  98. this.in.on("data", (data) => {
  99. if (data.length < 8) {
  100. debug("Missing header");
  101. return;
  102. }
  103. let headerBytes = data.slice(0, 8);
  104. let header = this.headerPacketFrom(headerBytes);
  105. if (header.direction != 0x01) {
  106. debug("Invaid direction", header.direction);
  107. return;
  108. }
  109. let commandName = commandToKey(header.command);
  110. let body = data.slice(8, header.size);
  111. debug("Emitting", commandName, body);
  112. this.in.emit(commandName, body);
  113. });
  114. }
  115. open() {
  116. return new Promise((resolve, reject) => {
  117. this._port.open((error) => {
  118. debug("Opening port...", this._port);
  119. if (error) {
  120. reject(error);
  121. } else {
  122. resolve();
  123. }
  124. });
  125. }).then(() => this.connect());
  126. }
  127. close() {
  128. // TODO: Remove from boot loader
  129. this._port.close();
  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. sync(ignoreResponse) {
  140. debug("Syncing");
  141. return this.sendCommand(commands.SYNC_FRAME, SYNC_FRAME, ignoreResponse)
  142. .then((response) => {
  143. if (!ignoreResponse) {
  144. debug("Sync response completed!", response);
  145. this.isInBootLoader = true;
  146. }
  147. });
  148. }
  149. connect() {
  150. return repeatPromise(5, () => this._connectAttempt())
  151. .then(() => this.sync())
  152. .then(() => this.isInBootLoader);
  153. }
  154. _connectAttempt() {
  155. return this.board.resetIntoBootLoader()
  156. .then(() => delay(100))
  157. // And a 5x loop here
  158. .then(() => repeatPromise(5, () => this._flushAndSync()));
  159. }
  160. _flushAndSync() {
  161. return new Promise((resolve, reject) => {
  162. this._port.flush((error) => {
  163. if (error) {
  164. reject(error);
  165. }
  166. debug("Port flushed");
  167. resolve();
  168. });
  169. }).then(() => this.sync(true));
  170. }
  171. headerPacketFor(command, data) {
  172. // https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.h#L49
  173. let buf = new ArrayBuffer(8);
  174. let dv = new DataView(buf);
  175. dv.setUint8(0, 0x00);
  176. dv.setUint8(1, command);
  177. dv.setUint16(2, data.byteLength, true);
  178. dv.setUint32(4, this.calculateChecksum(data), true);
  179. return new Buffer(buf);
  180. }
  181. headerPacketFrom(buffer) {
  182. let header = {};
  183. header.direction = buffer.readUInt8(0);
  184. header.command = buffer.readUInt8(1);
  185. header.size = buffer.readUInt16LE(2);
  186. header.checksum = buffer.readUInt32LE(4);
  187. return header;
  188. }
  189. // https://github.com/themadinventor/esptool/blob/master/esptool.py#L108
  190. // https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.c#L103
  191. sendCommand(command, data, ignoreResponse) {
  192. return new Promise((resolve, reject) => {
  193. if (command != commands.NO_COMMAND) {
  194. let sendHeader = this.headerPacketFor(command, data);
  195. let message = Buffer.concat([sendHeader, data], sendHeader.length + data.length);
  196. this.out.write(message, 'buffer', (err, res) => {
  197. delay(5).then(() => {
  198. this._port.drain((drainErr, results) => {
  199. debug("Draining", drainErr, results);
  200. if (ignoreResponse) {
  201. resolve("Response was ignored");
  202. }
  203. });
  204. });
  205. });
  206. }
  207. if (!ignoreResponse) {
  208. let commandName = commandToKey(command);
  209. if (this.in.listeners(commandName).length === 0) {
  210. debug("Listening once", commandName);
  211. this.in.once(commandName, (response) => {
  212. resolve(response);
  213. });
  214. } else {
  215. debug("Someone is already awaiting", commandName);
  216. }
  217. }
  218. });
  219. }
  220. }
  221. module.exports = RomComm;