rom_comm.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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.isOpen = false;
  90. this.config = config;
  91. this.isInBootLoader = false;
  92. }
  93. bindPort() {
  94. this._port.on('error', (error) => debug("PORT ERROR", error));
  95. this.in = new slip.SlipDecoder({debug: debug});
  96. this.out = new slip.SlipEncoder({debug: debug});
  97. this._port.pipe(this.in);
  98. this.out.pipe(this._port);
  99. this.in.on("data", (data) => {
  100. if (data.length < 8) {
  101. debug("Missing header");
  102. return;
  103. }
  104. let headerBytes = data.slice(0, 8);
  105. let header = this.headerPacketFrom(headerBytes);
  106. if (header.direction != 0x01) {
  107. debug("Invaid direction", header.direction);
  108. return;
  109. }
  110. let commandName = commandToKey(header.command);
  111. let body = data.slice(8, header.size);
  112. debug("Emitting", commandName, body);
  113. this.in.emit(commandName, body);
  114. });
  115. }
  116. open() {
  117. return new Promise((resolve, reject) => {
  118. this._port.open((error) => {
  119. debug("Opening port...", this._port);
  120. if (error) {
  121. reject(error);
  122. } else {
  123. resolve();
  124. }
  125. });
  126. }).then(() => this.connect());
  127. }
  128. connectStreamVersion() {
  129. return this.board.resetIntoBootLoader()
  130. .then(() => this.sync());
  131. }
  132. close() {
  133. this._port.close();
  134. this.isOpen = false;
  135. }
  136. calculateChecksum(data) {
  137. // Magic Checksum starts with 0xEF
  138. var result = 0xEF;
  139. for (var i = 0; i < data.length; i++) {
  140. result ^= data[i];
  141. }
  142. return result;
  143. }
  144. sync(ignoreResponse) {
  145. debug("Syncing");
  146. return this.sendCommand(commands.SYNC_FRAME, SYNC_FRAME, ignoreResponse)
  147. .then((response) => {
  148. if (!ignoreResponse) {
  149. debug("Sync response completed!", response);
  150. this.isInBootLoader = true;
  151. }
  152. });
  153. }
  154. connect() {
  155. return repeatPromise(5, () => this._connectAttempt())
  156. .then(() => this.sync())
  157. .then(() => this.isInBootLoader);
  158. }
  159. _connectAttempt() {
  160. return this.board.resetIntoBootLoader()
  161. .then(() => delay(100))
  162. // And a 5x loop here
  163. .then(() => repeatPromise(5, () => this._flushAndSync()));
  164. }
  165. _flushAndSync() {
  166. return new Promise((resolve, reject) => {
  167. this._port.flush((error) => {
  168. if (error) {
  169. reject(error);
  170. }
  171. debug("Port flushed");
  172. resolve();
  173. });
  174. }).then(() => this.sync(true));
  175. }
  176. headerPacketFor(command, data) {
  177. // https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.h#L49
  178. let buf = new ArrayBuffer(8);
  179. let dv = new DataView(buf);
  180. dv.setUint8(0, 0x00);
  181. dv.setUint8(1, command);
  182. dv.setUint16(2, data.byteLength, true);
  183. dv.setUint32(4, this.calculateChecksum(data), true);
  184. return new Buffer(buf);
  185. }
  186. headerPacketFrom(buffer) {
  187. let header = {};
  188. header.direction = buffer.readUInt8(0);
  189. header.command = buffer.readUInt8(1);
  190. header.size = buffer.readUInt16LE(2);
  191. header.checksum = buffer.readUInt32LE(4);
  192. return header;
  193. }
  194. // https://github.com/themadinventor/esptool/blob/master/esptool.py#L108
  195. // https://github.com/igrr/esptool-ck/blob/master/espcomm/espcomm.c#L103
  196. sendCommand(command, data, ignoreResponse) {
  197. return new Promise((resolve, reject) => {
  198. if (command != commands.NO_COMMAND) {
  199. let sendHeader = this.headerPacketFor(command, data);
  200. let message = Buffer.concat([sendHeader, data], sendHeader.length + data.length);
  201. this.out.write(message, 'buffer', (err, res) => {
  202. delay(5).then(() => {
  203. this._port.drain((drainErr, results) => {
  204. debug("Draining", drainErr, results);
  205. if (ignoreResponse) {
  206. resolve("Response was ignored");
  207. }
  208. });
  209. });
  210. });
  211. }
  212. if (!ignoreResponse) {
  213. let commandName = commandToKey(command);
  214. if (this.in.listeners(commandName).length === 0) {
  215. debug("Listening once", commandName);
  216. this.in.once(commandName, (response) => {
  217. resolve(response);
  218. });
  219. } else {
  220. debug("Someone is already awaiting", commandName);
  221. }
  222. }
  223. });
  224. }
  225. }
  226. module.exports = RomComm;