app.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. const SerialScanner = require("../back-end/serial_scanner");
  2. function $(id) { return document.getElementById(id) }
  3. const flashButton = $("flash-button");
  4. const appStatus = $("status");
  5. const portsSelect = $("ports");
  6. const serialScanner = new SerialScanner();
  7. const portToElementMap = {}; // Cache of option elements for the port select
  8. const pollTime = 1000; // One second
  9. var last_notification = "";
  10. flashButton.addEventListener("click", event => {
  11. var notification = new Notification("Flash Finished!");
  12. });
  13. serialScanner.on("ports", (ports) => {
  14. addPortsToSelect(ports);
  15. readyToFlash();
  16. });
  17. serialScanner.on("deviceAdded", (port) => {
  18. appendPortToSelect(port);
  19. new Notification(`Added: ${port}!`);
  20. });
  21. serialScanner.on("deviceRemoved", (port ) => {
  22. removePortFromSelect(port);
  23. new Notification(`Removed: ${port}!`);
  24. });
  25. serialScanner.on("error", onError);
  26. /**
  27. * Removes existing comment, adds ports to the serial port SELECT element.
  28. * @param ports An Array of strings.
  29. */
  30. function addPortsToSelect(ports) {
  31. //Empty Select
  32. ports.forEach(port => {
  33. appendPortToSelect(port);
  34. });
  35. }
  36. /**
  37. * Appends a single port to the end of serial port SELECT element.
  38. * @param port
  39. */
  40. function appendPortToSelect(port){
  41. const option = createPortOption(port);
  42. portToElementMap[port] = option;
  43. portsSelect.appendChild(option);
  44. }
  45. function createPortOption(port) {
  46. const option = document.createElement("option");
  47. option.textContent = port;
  48. option.value = port;
  49. return option;
  50. }
  51. function removePortFromSelect(port) {
  52. portsSelect.removeChild(portToElementMap[port]);
  53. delete portToElementMap[port];
  54. }
  55. /**
  56. * Updates UI to say it's ready
  57. */
  58. function readyToFlash() {
  59. appStatus.textContent = "Ready";
  60. enableInputs();
  61. }
  62. /**
  63. * Enabled the serial port SELECT and flash BUTTON elements.
  64. */
  65. function enableInputs(){
  66. portsSelect.disabled = false;
  67. flashButton.disabled = false;
  68. }
  69. /**
  70. * Generic catch all error. Shows notification at the moment.
  71. * @param error
  72. */
  73. function onError(error){
  74. if(last_notification !== error.message) {
  75. last_notification = error.message;
  76. new Notification(last_notification);
  77. }
  78. appStatus.textContent = error.message;
  79. }
  80. /**
  81. * Sets up UI
  82. */
  83. function init() {
  84. serialScanner.scan();
  85. setInterval(serialScanner.checkForChanges.bind(serialScanner), pollTime);
  86. }
  87. init();