12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8" />
- <title>CocoBlockly Pi – Preview</title>
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta http-equiv="Content-Type" content="text/html; scharset=UTF-8">
- <meta name="theme-color" content="#2C4FCD">
- <!-- <script src="./webusb.js" type="module"></script> -->
- <!-- <script type="text/javascript" src="uform.js"></script>
- <script type="text/javascript" src="libs/jquery-3.3.1.min.js"></script>
- <script type="text/javascript" src="libs/jquery-ui.min.js"></script>
- <script type="text/javascript" src="libs/jquery.hotkeys.js"></script>
- <script type="text/javascript" src="libs/jquery.multi-select.js"></script>
- <script type="text/javascript" src="//x.cocorobo.cn/src/blockly/web.js"></script> -->
- <script type="module">
- import Pl2303WebUsbSerial from './webusb.js';
- // import { debounce } from '';
- const VENDOR_ID = 0x01000000;
- const PRODUCT_ID = 0x01000001
- const NUMBER_OF_BYTES_TO_READ = 64;
- const READ_DEBOUNCE_DELAY_IN_MILLIS = 100;
- let usbDevice;
- // Invoke this function when the user clicked on a button to connect to the USB device. Due to security limitations of
- // WebUSB, it's required to request the device within the event handler.
- // E.g. <button onclick="handleConnectButtonClick">Connect to USB device</button>
- const handleConnectButtonClick = async () => {
- const device = await navigator.usb.requestDevice({ filters: [{ vendorId: VENDOR_ID, productId: PRODUCT_ID }] });
- usbDevice = new Pl2303WebUsbSerial(device);
- await usbDevice.connect();
- await readUntilSilent();
- };
- // This function is used to (trivially) batch-process read bytes. To do so, the USB device is read, and the received
- // bytes are stored in a local buffer. A function is debounced inovked to consume the buffer. After the wait
- // (here: 100 ms) the consume function is executed, the buffer is processed and emptied.
- // Reading from the USB device is done in a loop.
- const readUntilSilent = async () => {
- let buffer = new Blob();
- const debouncedConsumeBuffer = debounce(async () => {
- const array = await buffer.arrayBuffer();
- console.log(`debounced transfer in: ${new TextDecoder().decode(array)}`);
- buffer = new Blob();
- }, READ_DEBOUNCE_DELAY_IN_MILLIS);
- while (usbDevice) {
- try {
- const readout = await usbDevice.read(NUMBER_OF_BYTES_TO_READ);
- buffer = new Blob([buffer, readout.data.buffer]);
- debouncedConsumeBuffer();
- } catch (error) {
- console.debug(`Readout error: ${error}`, error);
- }
- }
- }
- document.getElementById("testclick").onclick = function () { handleConnectButtonClick(); }
- </script>
- </head>
- <body>
- <div id="testclick">点击测试</div>
- </body>
- </html>
|