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

LL-8941 Automatically release USB connection after 5s #761

Merged
merged 1 commit into from
Jan 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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