Skip to content

Commit db3a7e5

Browse files
Add exclusion filters to requestDevice for usb connections (#28)
1 parent 6e5d108 commit db3a7e5

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

lib/usb.ts

+6
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ export class MicrobitWebUSBConnection
5252
? ConnectionStatus.NO_AUTHORIZED_DEVICE
5353
: ConnectionStatus.NOT_SUPPORTED;
5454

55+
private exclusionFilters: USBDeviceFilter[] | undefined;
5556
/**
5657
* The USB device we last connected to.
5758
* Cleared if it is disconnected.
@@ -175,6 +176,10 @@ export class MicrobitWebUSBConnection
175176
}
176177
}
177178

179+
setRequestDeviceExclusionFilters(exclusionFilters: USBDeviceFilter[]) {
180+
this.exclusionFilters = exclusionFilters;
181+
}
182+
178183
async connect(): Promise<ConnectionStatus> {
179184
return this.withEnrichedErrors(async () => {
180185
await this.connectInternal();
@@ -421,6 +426,7 @@ export class MicrobitWebUSBConnection
421426
}
422427
this.dispatchTypedEvent("beforerequestdevice", new BeforeRequestDevice());
423428
this.device = await navigator.usb.requestDevice({
429+
exclusionFilters: this.exclusionFilters,
424430
filters: [{ vendorId: 0x0d28, productId: 0x0204 }],
425431
});
426432
this.dispatchTypedEvent("afterrequestdevice", new AfterRequestDevice());

src/demo.ts

+29
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ recreateUi("usb");
8383
const createConnectSection = (type: ConnectionType): Section => {
8484
const statusParagraph = crelt("p");
8585
let name = "";
86+
let exclusionFilters = JSON.stringify([{ serialNumber: "XXXX" }]);
8687
const dom = crelt(
8788
"section",
8889
crelt("h2", "Connect"),
@@ -119,10 +120,38 @@ const createConnectSection = (type: ConnectionType): Section => {
119120
},
120121
}),
121122
),
123+
type === "usb"
124+
? crelt(
125+
"label",
126+
"Exclusion filters",
127+
crelt("input", {
128+
type: "text",
129+
value: exclusionFilters,
130+
onchange: (e: Event) => {
131+
exclusionFilters = (e.currentTarget as HTMLInputElement).value;
132+
},
133+
}),
134+
)
135+
: undefined,
122136
crelt(
123137
"button",
124138
{
125139
onclick: () => {
140+
if (type === "usb") {
141+
let parsedExclusionFilters;
142+
try {
143+
if (exclusionFilters) {
144+
parsedExclusionFilters = JSON.parse(exclusionFilters);
145+
}
146+
} catch (err) {
147+
console.error("Invalid exclusion filters");
148+
}
149+
(
150+
connection as MicrobitWebUSBConnection
151+
).setRequestDeviceExclusionFilters(parsedExclusionFilters);
152+
} else if (type === "bluetooth") {
153+
(connection as MicrobitWebBluetoothConnection).setNameFilter(name);
154+
}
126155
void connection.connect();
127156
},
128157
},

0 commit comments

Comments
 (0)