import { useState } from "react"; import Button from "@material-ui/core/Button"; const SerialMonitor = () => { const [serialPortContent, setSerialPortContent] = useState([]); const [checked, setChecked] = useState(false); const handleClick = () => setChecked(!checked); const connectPort = async () => { try { const port = await navigator.serial.requestPort(); await port.open({ baudRate: 9600 }); while (port.readable) { const reader = port.readable.getReader(); try { while (true) { const { value, done } = await reader.read(); if (done) { // Allow the serial port to be closed later. reader.releaseLock(); break; } if (value) { // byte array to string: https://stackoverflow.com/a/37542820 const text = String.fromCharCode.apply(null, value); setSerialPortContent((prevContent) => [ ...prevContent, [new Date(), text], ]); } } } catch (error) { setSerialPortContent((prevContent) => [ ...prevContent, [new Date(), error], ]); } } } catch (error) { setSerialPortContent((prevContent) => [ ...prevContent, [new Date(), error], ]); } }; return ( <>
{checked && ( {log[0].toISOString()} )} {log[1]}
); })}