serial_scanner.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. "use strict";
  2. const serialport = require("serialport");
  3. const EventEmitter = require("events");
  4. class SerialScanner extends EventEmitter {
  5. /**
  6. * Scans for ports and emits a "ports" event with an array of
  7. */
  8. scan() {
  9. this.ports = []; //Initialize array
  10. serialport.list(
  11. (err, ports) => {
  12. this._listWithCallback(err, ports, () => {
  13. this.ports = ports.map(this._portMap);
  14. this.emit("ports", this.ports);
  15. });
  16. }
  17. );
  18. }
  19. /**
  20. * Checks for changes after initial scan.
  21. * Emits deviceAdded for each device added and
  22. * deviceRemoved for each device removed;
  23. */
  24. checkForChanges() {
  25. serialport.list(
  26. (err, ports) => {
  27. this._listWithCallback(err, ports, () => {
  28. const newPorts = ports.map(this._portMap);
  29. this.checkDeviceRemoved(newPorts);
  30. this.checkDeviceAdded(newPorts);
  31. this.ports = newPorts;
  32. });
  33. }
  34. );
  35. }
  36. /**
  37. * Compares the previous scan's port list with the current port list.
  38. * Emits deviceAdded for each new device added.
  39. * @param newPorts an array of string representation of ports
  40. */
  41. checkDeviceAdded(newPorts){
  42. this._comparePortsWithEmittion(newPorts, this.ports, "deviceAdded");
  43. }
  44. /**
  45. * Compares the previous scan's port list with the current port list.
  46. * Emits deviceRemoved for each device removed.
  47. * @param newPorts an array of string representation of ports
  48. */
  49. checkDeviceRemoved(newPorts) {
  50. this._comparePortsWithEmittion(this.ports, newPorts, "deviceRemoved");
  51. }
  52. /**
  53. * Helper function to compare arrays and emit events.
  54. * @param arrayA
  55. * @param arrayB
  56. * @param event
  57. * @private
  58. */
  59. _comparePortsWithEmittion(arrayA, arrayB, event) {
  60. arrayA.forEach((port) => {
  61. if(arrayB.indexOf(port) === -1) {
  62. this.emit(event, port);
  63. }
  64. });
  65. }
  66. /**
  67. * Emits the error of err.
  68. * @param err
  69. * @private
  70. */
  71. _emitError(err) {
  72. this.emit("error", err);
  73. }
  74. _listWithCallback(err, ports, callback) {
  75. if(err) {
  76. this._emitError(err);
  77. }
  78. else if(ports.length === 0) {
  79. this.ports = [];
  80. this._emitError(new Error("No serial ports detected."));
  81. }
  82. else {
  83. callback();
  84. }
  85. }
  86. _portMap(port) {
  87. return port.comName;
  88. }
  89. }
  90. module.exports = SerialScanner;