Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // serialHandler.ts
- let reader: ReadableStreamDefaultReader;
- let writer: WritableStreamDefaultWriter;
- const decoder = new TextDecoder();
- async function serialHandler() {
- const outputElem =
- document.querySelector<HTMLInputElement>(`#Connect-messages`);
- if (!outputElem) {
- throw new Error("Output element not found");
- }
- if ("serial" in navigator) {
- try {
- const port = await (navigator as any).serial.requestPort();
- outputElem.innerHTML = outputElem.innerHTML + "\r\n Opening port";
- console.log("Opening port");
- let wasAlreadyOpen = await retry(openPort, [port], 5);
- if (!wasAlreadyOpen) {
- if (writer) writer.releaseLock(); // Release existing writer lock if necessary
- if (reader) reader.releaseLock(); // Release existing reader lock if necessary
- //only assign writable & readable streams when port wasn't previously opened
- writer = port.writable.getWriter();
- reader = port.readable.getReader();
- }
- outputElem.innerHTML =
- outputElem.innerHTML + "\r\n Port successfully opened";
- } catch (err) {
- alert("There was an error opening the serial port: " + err);
- }
- } else {
- console.error(
- "Web serial doesn't seem to be enabled in your browser. Check https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API#browser_compatibility for more info."
- );
- }
- }
- /**
- * Takes a string of data, encodes it and then writes it using the `writer` attached to the serial port.
- * @param data - A string of data that will be sent to the Serial port.
- * @returns An empty promise after the message has been written.
- */
- async function write(data: string): Promise<void> {
- try {
- console.log("sending data: ", data);
- const dataArrayBuffer = await toAscii(data);
- await writer.write(dataArrayBuffer);
- await writer.ready;
- } catch (err) {
- console.error("Error writing to serial port:", err);
- }
- }
- /**
- * Reads data from the serial port using the `reader` attached to the serial port.
- * @returns A promise that resolves to the decoded string of data read from the serial port.
- */
- async function read(): Promise<string> {
- try {
- const readerData = await reader.read();
- var msg = decoder.decode(readerData.value);
- console.log("response received: ", msg);
- return msg;
- } catch (err) {
- const errorMessage = `error reading data: ${err}`;
- console.error(errorMessage);
- return errorMessage;
- }
- }
- function toAscii(text: String): Uint8Array {
- let convertedChar;
- var array = new Uint8Array(text.length);
- for (let i = 0; i < text.length; i++) {
- convertedChar = text.charCodeAt(i);
- array[i] = convertedChar;
- }
- return array;
- }
- // sendMessage.ts
- import serialHandler from "./serialHandler";
- export default async function sendMessage(
- message: string,
- label: string
- ): Promise<string[]> {
- try {
- const outputElem = document.querySelector<HTMLInputElement>(
- `#${label}-messages`
- );
- if (!outputElem) {
- throw new Error("Output element not found");
- }
- await serialHandler.write(message);
- outputElem.innerHTML = outputElem.innerHTML + "\r\nMessage sent:" + message;
- const result = await serialHandler.read();
- outputElem.innerHTML =
- outputElem.innerHTML + "\r\nResponse received:" + result;
- let results = result.substring(0, result.indexOf("\r\n")).split(",");
- return results;
- } catch (e) {
- console.error(e);
- return [];
- }
- }
- // startDevice.ts
- import sendMessage from "./sendMessage";
- /**
- * Sends a command to start the device.
- * @returns A promise resolving to a boolean indicating success or failure.
- */
- export default async function startDevice(): Promise<boolean> {
- try {
- console.log("Sending start command to the device...");
- // HELO handshake
- const heloResponse = await sendMessage(":HELO? [''] 1\r\n", "startDevice");
- if (heloResponse[0] !== "ACK") {
- throw new Error("Device did not acknowledge the HELO command.");
- }
- // Send the start command
- const startResponse = await sendMessage(":START\r\n", "startDevice");
- await sendMessage(":END?\r\n", "sendMessages");
- if (startResponse[0] === "OK") {
- console.log("Device started successfully.");
- return true;
- } else {
- console.error("Failed to start the device:", startResponse);
- return false;
- }
- } catch (error) {
- console.error("Error in startDevice:", error);
- return false;
- }
- }
- // stopDevice.ts
- import sendMessage from "./sendMessage";
- /**
- * Sends a command to stop the device.
- * @returns A promise resolving to a boolean indicating success or failure.
- */
- export default async function stopDevice(): Promise<boolean> {
- try {
- console.log("Sending stop command to the device...");
- // HELO handshake
- const heloResponse = await sendMessage(":HELO? [''] 1\r\n", "stopDevice");
- if (heloResponse[0] !== "ACK") {
- throw new Error("Device did not acknowledge the HELO command.");
- }
- // Send the stop command
- const stopResponse = await sendMessage(":STOP\r\n", "stopDevice");
- await sendMessage(":END?\r\n", "sendMessages");
- if (stopResponse[0] === "OK") {
- console.log("Device stopped successfully.");
- return true;
- } else {
- console.error("Failed to stop the device:", stopResponse);
- return false;
- }
- } catch (error) {
- console.error("Error in stopDevice:", error);
- return false;
- }
- }
- import { useState } from "react";
- import serialHandler from "./utils/serialHandler";
- import ActionButton from "./component/ActionButton";
- import StatusDisplay from "./component/StatusDisplay";
- import startDevice from "./utils/startDevice";
- import stopDevice from "./utils/stopDevice";
- function App() {
- const [status, setStatus] = useState<boolean>(false);
- const [data, setData] = useState<any>(null);
- const [device, setDevice] = useState<string>("");
- const handleConnect = async () => {
- await serialHandler.init();
- await serialHandler.write("*IDN?\r\n");
- let device = await serialHandler.read();
- setDevice(device);
- setStatus(true);
- };
- const handleGetMeasurementData = async () => {
- const [success, receivedData] = await GetMeasurementData();
- if (success) {
- setData(receivedData);
- console.log("Received Data:", data);
- } else {
- console.error("Failed to get measurement data.");
- }
- };
- const actions = [
- { name: "startDevice", handler: () => startDevice() },
- { name: "stopDevice", handler: () => stopDevice() },
- ];
- return (
- <div className="container mx-auto p-4">
- <StatusDisplay status={status} deviceName={device} />
- <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
- <ActionButton
- label={"Connect"}
- onClick={handleConnect}
- disabled={status}
- />
- {actions.map((action) => (
- <ActionButton
- key={action.name}
- label={action.name}
- onClick={action.handler}
- disabled={!status}
- />
- ))}
- </div>
- </div>
- );
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement