Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add port filtering while requesting new port #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 9 additions & 1 deletion src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,15 @@ class MessageHandler {
*/
async listAvailablePorts({ origin, options }: BackgroundRequest) {
const originAuth = await readOriginAuth(origin)
const ports = await listPortsNative()
const ports = (await listPortsNative()).filter(port => {
return !options || !options.filters || options.filters.filter(filter => {
return (!filter.usbVendorId || filter.usbVendorId === port.usb?.vid) &&
(!filter.usbProductId || filter.usbProductId === port.usb?.pid) &&
(!("id" in filter) || filter["id"] === port.id) &&
(!("name" in filter) || filter["name"] === port.name) &&
(!("transport" in filter) || filter["transport"] === port.transport)
Comment on lines +77 to +79
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is TypeScript, a new type for "extended" filters should be added. The SerialPortFilter type can be extended in types.ts and each filter can then be typecast to that extended type.

Also, please consider creating another (sub)function like checkPortMatch(port: SerialPortData, filter: SerialPortFilter): boolean. Each port could then be checked against each provided filter. The current form is complex to understand, because it uses ! and || with negative logic values.
A function built with if (filter.<value> && filter.<value> != port.<value>) return false; would be also less error-prone.

See:
https://wicg.github.io/serial/#dom-serialportfilter

}).length > 0
})
for (const port of ports) {
port.isPaired = port.id in originAuth
}
Expand Down
Loading