Skip to content

Commit

Permalink
improve WebHID receive packet handling
Browse files Browse the repository at this point in the history
  • Loading branch information
gniezen committed Oct 20, 2022
1 parent 7ad3074 commit 5d0a59e
Showing 1 changed file with 21 additions and 11 deletions.
32 changes: 21 additions & 11 deletions lib/hidDevice.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,14 @@ module.exports = (config) => {
if (packets.length > 0) {
return cb(null, packets.shift());
}

const response = new Promise((resolve) => {
webHid.addEventListener('data', () => {
resolve(packets.shift());
if (packets.length === 0) {
return resolve([]);
} else {
return resolve(packets.shift());
}
}, { once: true });
});

Expand All @@ -81,20 +85,26 @@ module.exports = (config) => {
}

async function receiveTimeout(timeout) {
const abortTimer = setTimeout(() => {
return([]);
}, timeout);

if (packets.length > 0) {
clearTimeout(abortTimer);
return(Array.from(packets.shift()));
return Array.from(packets.shift());
}

const response = new Promise((resolve) => {
webHid.addEventListener('data', () => {
const getData = () => {
clearTimeout(abortTimer);
resolve(Array.from(packets.shift()));
}, { once: true });
if (packets.length === 0) {
return resolve([]);
} else {
return resolve(Array.from(packets.shift()));
}
};

const abortTimer = setTimeout(() => {
webHid.removeEventListener('data', getData);
return resolve([]);
}, timeout);

webHid.addEventListener('data', getData, { once: true });
});

// no packet yet, let's wait
Expand Down

0 comments on commit 5d0a59e

Please sign in to comment.