app.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const availableSerialPorts = require("../back-end/available_serial_ports");
  2. function $(id) { return document.getElementById(id) }
  3. const flashButton = $("flash-button");
  4. const appStatus = $("status");
  5. const portsSelect = $("ports");
  6. var last_notification = "";
  7. flashButton.addEventListener("click", event => {
  8. var notification = new Notification("Flash Finished!");
  9. });
  10. function checkPorts() {
  11. availableSerialPorts()
  12. .then(addPortsToSelect)
  13. .then(readyToFlash)
  14. .catch(onError);
  15. }
  16. /**
  17. * Removes existing comment, adds ports to the serial port SELECT element.
  18. * @param ports An Array of strings.
  19. */
  20. function addPortsToSelect(ports) {
  21. //Gets currently selected
  22. const previousValue = portsSelect.value;
  23. //Empty Select
  24. portsSelect.innerHTML = "";
  25. ports.forEach(port => {
  26. appendPortToSelect(port, previousValue)
  27. });
  28. }
  29. /**
  30. * Appends a single port to the end of serial port SELECT element.
  31. * @param port
  32. */
  33. function appendPortToSelect(port, previousValue){
  34. const option = document.createElement("option");
  35. option.textContent = port;
  36. option.value = port;
  37. option.selected = previousValue === port;
  38. portsSelect.appendChild(option);
  39. }
  40. /**
  41. * Updates UI to say it's ready
  42. */
  43. function readyToFlash() {
  44. appStatus.textContent = "Ready";
  45. enableInputs();
  46. }
  47. /**
  48. * Enabled the serial port SELECT and flash BUTTON elements.
  49. */
  50. function enableInputs(){
  51. portsSelect.disabled = false;
  52. flashButton.disabled = false;
  53. }
  54. /**
  55. * Generic catch all error. Shows notification at the moment.
  56. * @param error
  57. */
  58. function onError(error){
  59. if(last_notification !== error.message) {
  60. last_notification = error.message;
  61. new Notification(last_notification);
  62. }
  63. appStatus.textContent = error.message;
  64. }
  65. /**
  66. * Sets up UI
  67. */
  68. function init() {
  69. checkPorts();
  70. setInterval(checkPorts, 1000);
  71. }
  72. init();