app.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. "use strict";
  2. /**
  3. * Constants for application
  4. *
  5. * manifestList is the url that contains all possible manifests
  6. * pollTime is used to check for changes in the serial ports
  7. *
  8. * @type {{manifestList: string, pollTime: number}}
  9. */
  10. const CONSTANTS = {
  11. manifestList: "http://flasher.thingssdk.com/v1/manifest-list.json",
  12. pollTime: 1000
  13. };
  14. var last_notification = "";
  15. /************************
  16. * Backend dependencies.
  17. * Note: Paths are relative to index.html not app.js
  18. ************************/
  19. const remote = require("remote");
  20. const SerialScanner = require("../back-end/serial_scanner");
  21. const PortSelect = require("./js/port_select");
  22. const prepareBinaries = require("../back-end/prepare_binaries");
  23. const log = require("../back-end/logger");
  24. const RomComm = require("../back-end/rom_comm");
  25. const serialScanner = new SerialScanner();
  26. /************************
  27. * UI Elements
  28. ************************/
  29. const flashButton = $("flash-button");
  30. const appStatus = $("status");
  31. const portsSelect = new PortSelect($("ports"));
  32. const manifestsSelect = $("manifests");
  33. const progressHolder = $("progressBar");
  34. const progressBar = $("progress");
  35. const form = $("form");
  36. /************************
  37. * Utility Functions
  38. ************************/
  39. /**
  40. * Simple helper returns HTML element from an element's id
  41. *
  42. * @param id a string of the id of an HTML element
  43. * @returns {Element}
  44. */
  45. function $(id) { return document.getElementById(id); }
  46. /**
  47. * Processes the response from an HTTP fetch and returns the JSON promise.
  48. *
  49. * @param response from a fetch call
  50. * @returns {Promise}
  51. */
  52. function processJSON(response) {
  53. return response.json();
  54. }
  55. /************************
  56. * Handle UI
  57. ************************/
  58. flashButton.addEventListener("click", (event) => {
  59. disableInputs();
  60. fetch(manifestsSelect.value)
  61. .then(processJSON)
  62. .then(flashWithManifest);
  63. });
  64. /************************
  65. * Manage serial port events
  66. ************************/
  67. serialScanner.on("ports", (ports) => {
  68. portsSelect.addAll(ports);
  69. readyToFlash();
  70. });
  71. serialScanner.on("deviceAdded", (port) => {
  72. portsSelect.add(port);
  73. new Notification(`Added: ${port}!`);
  74. });
  75. serialScanner.on("deviceRemoved", (port) => {
  76. portsSelect.remove(port);
  77. new Notification(`Removed: ${port}!`);
  78. });
  79. serialScanner.on("error", onError);
  80. /**
  81. * Updates UI to say it's ready
  82. */
  83. function readyToFlash() {
  84. progressHolder.style.display = "none";
  85. form.style.display = "block";
  86. appStatus.textContent = "Ready";
  87. enableInputs();
  88. }
  89. /**
  90. * Enabled the serial port SELECT and flash BUTTON elements.
  91. */
  92. function enableInputs() {
  93. portsSelect.disabled = false;
  94. manifestsSelect.disabled = false;
  95. flashButton.disabled = false;
  96. }
  97. function disableInputs() {
  98. portsSelect.disabled = true;
  99. manifestsSelect.disabled = true;
  100. flashButton.disabled = true;
  101. }
  102. /**
  103. * Generic catch all error. Shows notification at the moment.
  104. * @param error
  105. */
  106. function onError(error){
  107. if(last_notification !== error.message) {
  108. last_notification = error.message;
  109. new Notification(last_notification);
  110. }
  111. appStatus.textContent = error.message;
  112. }
  113. function generateManifestList(manifestsJSON) {
  114. manifestsJSON.options.forEach((option) => {
  115. option.versions.forEach((version) => {
  116. const optionElement = document.createElement("option");
  117. optionElement.textContent = `${option.name} - ${version.version}`;
  118. optionElement.value = version.manifest;
  119. manifestsSelect.appendChild(optionElement);
  120. manifestsSelect.disabled = false;
  121. });
  122. });
  123. }
  124. function getManifests() {
  125. appStatus.textContent = "Getting latest manifests.";
  126. // Break the cache to get the latest
  127. remote.getCurrentWindow().webContents.session.clearCache(() => {
  128. fetch(CONSTANTS.manifestList)
  129. .then(processJSON)
  130. .then(generateManifestList).catch(error => {
  131. setTimeout(getManifests, pollTime);
  132. });
  133. });
  134. }
  135. function flashWithManifest(manifest) {
  136. form.style.display = "none";
  137. progressHolder.style.display = "block";
  138. appStatus.textContent = `Flashing ${portsSelect.value}`;
  139. const numberOfSteps = manifest.flash.length * 2;
  140. let correctStepNumber = 1;
  141. prepareBinaries(manifest, (err, flashSpec) => {
  142. if(err) throw err;
  143. const esp = new RomComm({
  144. portName: portsSelect.value,
  145. baudRate: 115200
  146. });
  147. esp.on('progress', (progress) => {
  148. const flashPercent = Math.round((progress.details.flashedBytes/progress.details.totalBytes) * 100);
  149. const processSoFar = 50; //From download and extracting.
  150. const flashProcess = flashPercent / 2; //To add to the overall progress
  151. updateProgressBar(processSoFar + flashProcess);
  152. appStatus.textContent = `${progress.display} - ${flashPercent}%`;
  153. });
  154. esp.open().then((result) => {
  155. appStatus.textContent = `Flashing device connected to ${portsSelect.value}`;
  156. let promise = Promise.resolve();
  157. return esp.flashSpecifications(flashSpec)
  158. .then(() => esp.close())
  159. .then((result) => {
  160. new Notification("Flash Finished!");
  161. readyToFlash();
  162. log.info("Flashed to latest Espruino build!", result);
  163. });
  164. }).catch((error) => {
  165. new Notification("An error occured during flashing.");
  166. readyToFlash();
  167. log.error("Oh noes!", error);
  168. });
  169. }).on("entry", (progress) => {
  170. //For the download/extract progress. The other half is flashing.
  171. const extractPercent = Math.round((correctStepNumber++/numberOfSteps) * 50);
  172. updateProgressBar(extractPercent);
  173. appStatus.textContent = progress.display;
  174. });
  175. }
  176. function updateProgressBar(percent) {
  177. progressBar.style.width = `${percent}%`;
  178. }
  179. /**
  180. * Get's manifest list for possibilities for flashing,
  181. * scans serial ports and sets up timer for checking for changes.
  182. */
  183. function start() {
  184. getManifests();
  185. serialScanner.scan();
  186. setInterval(serialScanner.checkForChanges.bind(serialScanner), CONSTANTS.pollTime);
  187. }
  188. /**
  189. * Start Application
  190. */
  191. start();