|
| 1 | +import {SerialPort} from "serialport"; |
| 2 | +import {Page} from "playwright"; |
| 3 | +import Board from "./board.ts"; |
| 4 | +import {randomUUID} from "node:crypto"; |
| 5 | +import {clearTimeout} from "node:timers"; |
| 6 | +import * as fs from "node:fs"; |
| 7 | + |
| 8 | +type CallbackEvent = { |
| 9 | + resolve: (value: unknown) => void, |
| 10 | + type: string, |
| 11 | + args: any[] |
| 12 | +} |
| 13 | + |
| 14 | +declare module globalThis { |
| 15 | + let requestSerial: (options: SerialPortRequestOptions) => Promise<string>, |
| 16 | + openSerial: (id: string, options: SerialOptions) => Promise<void|Error>, |
| 17 | + readPort: (id: string) => Promise<number[]|Error>, |
| 18 | + readCallback: (data: number[]) => void, |
| 19 | + writePort: (id: string, data: number[]) => Promise<void|Error>, |
| 20 | + closePort: (id: string) => Promise<void|Error>, |
| 21 | + setSignals: (id: string, signals: SerialOutputSignals) => Promise<void|Error>, |
| 22 | + getPorts: () => Promise<string[]>, |
| 23 | + onDone: Record<string, (value: any) => void>, |
| 24 | + reader: ReadableStreamDefaultReader<CallbackEvent> |
| 25 | +} |
| 26 | + |
| 27 | +const ports: Record<string, SerialPort|null> = {} |
| 28 | +export default async function setup(page: Page) { |
| 29 | + const arduino = new Board() |
| 30 | + |
| 31 | + const methods: Record<string, (...args: any[]) => Promise<any>> = { |
| 32 | + async requestSerial(_page: Page, _options: SerialPortRequestOptions) { |
| 33 | + const id = randomUUID() |
| 34 | + ports[id] = null |
| 35 | + |
| 36 | + return String(id) |
| 37 | + }, |
| 38 | + async openSerial(_page: Page, id: string, options: SerialOptions) { |
| 39 | + if (ports[id]) throw new DOMException('Port already open!') |
| 40 | + |
| 41 | + return new Promise<void|Error>(resolve => { |
| 42 | + ports[id] = new SerialPort({ |
| 43 | + baudRate: options.baudRate, |
| 44 | + path: arduino.port, |
| 45 | + dataBits: 8, |
| 46 | + parity: 'none', |
| 47 | + stopBits: 1, |
| 48 | + }, err => { |
| 49 | + if (err) return resolve(err) |
| 50 | + resolve() |
| 51 | + }) |
| 52 | + }) |
| 53 | + }, |
| 54 | + async readPort(page: Page, id: string) { |
| 55 | + if (!ports[id]) throw new Error(`User read request to undefined port: ${id}`) |
| 56 | + |
| 57 | + const port = ports[id] as SerialPort |
| 58 | + try { |
| 59 | + let buffer: number[]|null = null |
| 60 | + let timeout: NodeJS.Timeout|null |
| 61 | + port.on('data', async (data: Buffer) => { |
| 62 | + if (!buffer) buffer = [] |
| 63 | + buffer.push(...Array.from(data.values())) |
| 64 | + |
| 65 | + if (timeout) clearTimeout(timeout) |
| 66 | + timeout = setTimeout(async () => { |
| 67 | + const copy = buffer |
| 68 | + buffer = null |
| 69 | + |
| 70 | + await page.evaluate((result) => { |
| 71 | + if (!result) return |
| 72 | + globalThis.readCallback(result) |
| 73 | + }, copy) |
| 74 | + }, 25) |
| 75 | + }) |
| 76 | + } catch (e) { |
| 77 | + return e |
| 78 | + } |
| 79 | + }, |
| 80 | + async writePort(_page: Page, id: string, data: number[]) { |
| 81 | + if (!ports[id]) throw new Error(`User write request to undefined port: ${id}`) |
| 82 | + |
| 83 | + const port = ports[id] as SerialPort |
| 84 | + return new Promise<void|Error>(resolve => { |
| 85 | + port.write(Buffer.from(data), err => { |
| 86 | + if (err) return resolve(err) |
| 87 | + resolve() |
| 88 | + }) |
| 89 | + }) |
| 90 | + }, |
| 91 | + async closePort(_page: Page, id: string) { |
| 92 | + if (!ports[id]) throw new Error(`User close request to undefined port: ${id}`) |
| 93 | + |
| 94 | + const port = ports[id] as SerialPort |
| 95 | + ports[id] = null |
| 96 | + return new Promise<void|Error>(resolve => port.close(err => { |
| 97 | + if (err) return resolve(err) |
| 98 | + resolve() |
| 99 | + })) |
| 100 | + }, |
| 101 | + setSignals(_page: Page, id: string, signals: SerialOutputSignals) { |
| 102 | + if (!ports[id]) throw new Error(`User setSignals request to undefined port: ${id}`) |
| 103 | + |
| 104 | + const port = ports[id] as SerialPort |
| 105 | + return new Promise<void|Error>(resolve => { |
| 106 | + port.set({ |
| 107 | + dtr: signals.dataTerminalReady, |
| 108 | + rts: signals.requestToSend, |
| 109 | + brk: signals.break |
| 110 | + }, () => { |
| 111 | + resolve() |
| 112 | + }) |
| 113 | + }) |
| 114 | + }, |
| 115 | + async getPorts(_page: Page) { |
| 116 | + return Array.from(Object.keys(ports)) |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + await Promise.all(Object.entries(methods).map(async ([type, implementation]) => { |
| 121 | + await page.exposeFunction(type, (...args: any[]) => implementation(page, ...args)) |
| 122 | + })) |
| 123 | + |
| 124 | + await page.route('**/avrdude-worker.js', async route => { |
| 125 | + const response = await route.fetch(); |
| 126 | + const script = await response.text(); |
| 127 | + await route.fulfill({ response, body: `${fs.readFileSync(`${import.meta.dirname}/page.js`)}\n\n${script}` }); |
| 128 | + }); |
| 129 | + |
| 130 | + await page.addInitScript({ |
| 131 | + path: `${import.meta.dirname}/page.js` |
| 132 | + }) |
| 133 | + |
| 134 | + page.on('worker', async worker => { |
| 135 | + let open = true |
| 136 | + worker.on('close', () => open = false) |
| 137 | + while (open) { |
| 138 | + try { |
| 139 | + const action = await worker.evaluate(async () => { |
| 140 | + if (!globalThis.reader) return |
| 141 | + |
| 142 | + const {value, done} = await globalThis.reader.read() |
| 143 | + if (done || !value) return |
| 144 | + |
| 145 | + const execution = crypto.randomUUID() |
| 146 | + globalThis.onDone[execution] = value.resolve |
| 147 | + return { |
| 148 | + execution, |
| 149 | + type: value.type, |
| 150 | + args: value.args |
| 151 | + } |
| 152 | + }) |
| 153 | + |
| 154 | + if (!action) continue |
| 155 | + if (!methods[action.type]) continue |
| 156 | + |
| 157 | + methods[action.type](worker, ...action.args).then(async result => { |
| 158 | + await worker.evaluate(async ({ execution, result }) => { |
| 159 | + globalThis.onDone[execution](result) |
| 160 | + }, { |
| 161 | + execution: action.execution, |
| 162 | + result |
| 163 | + }) |
| 164 | + }) |
| 165 | + } catch { /* Once the worker has closed it will throw */ } |
| 166 | + } |
| 167 | + }) |
| 168 | + |
| 169 | +} |
0 commit comments