diff --git a/README.md b/README.md index 8f543c0..0a57834 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,8 @@ watcher.on('connected', (xkeysPanel) => { }) // To stop watching, call -// watcher.stop() +// watcher.stop() // Returns a promise +// .catch(console.error) ``` ### Connect to a devices manually @@ -296,6 +297,14 @@ The most notable changes are: | `myXkeys.setAllBacklights(...)` | Arguments have changed, see docs | | `myXkeys.setLED(index, ...)` | `myXkeys.setIndicatorLED(index, ...)` (index 1 = the red, 2 = the green one) | +### 2.1.1 + +Version `2.1.1` has a minor change for when stopping the XKeysWatcher instance: +``` +const watcher = new XKeysWatcher() +await watcher.stop() // Now returns a promise +``` + ## For developers This is a mono-repo, using [Lerna](https://github.com/lerna/lerna) and [Yarn](https://yarnpkg.com). diff --git a/packages/node/examples/basic-log-all-events.js b/packages/node/examples/basic-log-all-events.js index 7bd125a..8bcf59e 100644 --- a/packages/node/examples/basic-log-all-events.js +++ b/packages/node/examples/basic-log-all-events.js @@ -56,4 +56,4 @@ watcher.on('connected', (xkeysPanel) => { }) // To stop watching, call -// watcher.stop() +// watcher.stop().catch(console.error) diff --git a/packages/node/src/watcher.ts b/packages/node/src/watcher.ts index 99c11cf..b940e0a 100644 --- a/packages/node/src/watcher.ts +++ b/packages/node/src/watcher.ts @@ -65,6 +65,8 @@ export class XKeysWatcher extends EventEmitter { private shouldFindChangedReTries = 0 public debug = false + /** A list of the devices we've called setupXkeysPanels for */ + private setupXkeysPanels: XKeys[] = [] constructor() { super() @@ -82,7 +84,11 @@ export class XKeysWatcher extends EventEmitter { // Also do a sweep for all currently connected X-keys panels: this.updateConnectedDevices() } - public stop(): void { + /** + * Stop the watcher + * @param closeAllDevices Set to false in order to NOT close all devices. Use this if you only want to stop the watching. Defaults to true + */ + public async stop(closeAllDevices: boolean = true): Promise { this.isMonitoring = false // Remove the listeners: @@ -95,6 +101,14 @@ export class XKeysWatcher extends EventEmitter { if (watcherCount === 0) { USBDetect().stopMonitoring() } + + if (closeAllDevices) { + // In order for an application to close gracefully, + // we need to close all devices that we've called setupXkeysPanel() on: + for (const xKeysPanel of this.setupXkeysPanels) { + await xKeysPanel.close() + } + } } private onAddedUSBDevice = (_device: USBDetectNS.Device) => { // Called whenever a new USB device is added @@ -175,6 +189,7 @@ export class XKeysWatcher extends EventEmitter { setupXkeysPanel(devicePath) .then((xkeysPanel) => { + this.setupXkeysPanels.push(xkeysPanel) // Since this is async, check if the panel is still connected if (this.seenDevicePaths[devicePath]) { // yes, it is still connected