feat: tauri serial polyfill

This commit is contained in:
2023-08-04 00:08:28 +02:00
parent 9c1918e683
commit 42922e7ce0
23 changed files with 660 additions and 486 deletions

View File

@@ -1,22 +1,65 @@
import {invoke} from "@tauri-apps/api"
import TauriSerialDialog from "$lib/serial/TauriSerialDialog.svelte"
export type TauriSerialPort = Pick<
SerialPort,
"getInfo" | "open" | "close" | "readable" | "writable" | "forget"
>
function NativeSerialPort(info: SerialPortInfo): TauriSerialPort {
return {
getInfo() {
return info
},
async open({baudRate}: SerialOptions) {
await invoke("plugin:serial|open", {path: info.name, baudRate})
},
async close() {
await invoke("plugin:serial|close", {path: info.name})
},
async forget() {
// noop
},
readable: new ReadableStream({
async pull(controller) {
const result = await invoke<number[]>("plugin:serial|read", {path: info.name})
controller.enqueue(new Uint8Array(result))
},
}),
writable: new WritableStream({
async write(chunk) {
await invoke("plugin:serial|write", {path: info.name, chunk: Array.from(chunk)})
},
}),
}
}
// @ts-expect-error polyfill
// noinspection JSConstantReassignment
navigator.serial = {
getPorts(): Promise<SerialPort[]> {
async getPorts(): Promise<SerialPort[]> {
return invoke<any[]>("plugin:serial|get_serial_ports").then(ports =>
ports.map<Partial<SerialPort>>(port => ({
getInfo() {
return {
name: port["name"],
usbVendorId: port["vendor_id"],
usbProductId: port["product_id"],
serialNumber: port["serial_number"],
manufacturer: port["manufacturer"],
product: port["product"],
} as SerialPortInfo
},
})),
ports.map(NativeSerialPort),
) as Promise<SerialPort[]>
},
async requestPort(options?: SerialPortRequestOptions): Promise<SerialPort> {
const ports = await navigator.serial.getPorts().then(ports =>
options?.filters !== undefined
? ports.filter(port =>
options.filters!.some(({usbVendorId, usbProductId}) => {
const info = port.getInfo()
return (
(usbVendorId === undefined || info.usbVendorId === usbVendorId) &&
(usbProductId === undefined || info.usbProductId === usbProductId)
)
}),
)
: ports,
)
const dialog = new TauriSerialDialog({target: document.body, props: {ports}})
const port = await new Promise<SerialPort>(resolve => dialog.$on("confirm", resolve))
dialog.$destroy()
return port
},
}