serial_scanner.js 2.5 KB

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