Skip to content
This repository has been archived by the owner on Jun 27, 2022. It is now read-only.

Commit

Permalink
LL-8941 Automatically release USB connection after 5s
Browse files Browse the repository at this point in the history
  • Loading branch information
juan-cortes committed Jan 12, 2022
1 parent ae240fb commit ee60579
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion packages/hw-transport-node-hid-singleton/src/TransportNodeHid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,22 @@ import { identifyUSBProductId } from "@ledgerhq/devices";
import { CantOpenDevice } from "@ledgerhq/errors";
import { listenDevices } from "./listenDevices";
let transportInstance;

const DISCONNECT_TIMEOUT = 5000;
let disconnectTimeout;
const clearDisconnectTimeout = () => {
if (disconnectTimeout) {
clearTimeout(disconnectTimeout);
}
};

const setDisconnectTimeout = () => {
disconnectTimeout = setTimeout(
() => TransportNodeHidSingleton.disconnect(),
DISCONNECT_TIMEOUT
);
};

/**
* node-hid Transport implementation
* @example
Expand Down Expand Up @@ -97,12 +113,14 @@ export default class TransportNodeHidSingleton extends TransportNodeHidNoEvents
transportInstance.emit("disconnect");
transportInstance = null;
}
clearDisconnectTimeout();
}

/**
* if path="" is not provided, the library will take the first device
*/
static open(): Promise<TransportNodeHidSingleton> {
clearDisconnectTimeout();
return Promise.resolve().then(() => {
if (transportInstance) {
log("hid-verbose", "reusing opened transport instance");
Expand Down Expand Up @@ -138,7 +156,19 @@ export default class TransportNodeHidSingleton extends TransportNodeHidNoEvents
});
}

close() {
/**
* Exchange with the device using APDU protocol.
* @param apdu
* @returns a promise of apdu response
*/
async exchange(apdu: Buffer): Promise<Buffer> {
clearDisconnectTimeout();
const result = await super.exchange(apdu);
setDisconnectTimeout();
return result;
}

close(): Promise<void> {
// intentionally, a close will not effectively close the hid connection
return Promise.resolve();
}
Expand Down

0 comments on commit ee60579

Please sign in to comment.