Skip to content

Commit

Permalink
Merge pull request #22 from portapack-mayhem/write_lock
Browse files Browse the repository at this point in the history
Now can get reponse for command sent
  • Loading branch information
jLynx authored Jan 9, 2024
2 parents b1c577a + e4a8fca commit c8d2f53
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 5 deletions.
16 changes: 12 additions & 4 deletions src/app/components/Controller/Controller.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import React, { useEffect, useRef, useState } from "react";
import HotkeyButton from "../HotkeyButton/HotkeyButton";
import { useSerial } from "../SerialLoader/SerialLoader";
import { DataPacket } from "../SerialProvider/SerialProvider";
import ToggleSwitch from "../ToggleSwitch/ToggleSwitch";

const Controller = () => {
Expand All @@ -15,16 +16,23 @@ const Controller = () => {

const started = useRef<boolean>(false);

const write = async (command: string, updateFrame: boolean) => {
serial.queueWrite(command);
const write = async (
command: string,
updateFrame: boolean,
awaitResponse: boolean = false
) => {
let data: DataPacket | undefined = undefined;
if (awaitResponse) data = await serial.queueWriteAndResponse(command);
else serial.queueWrite(command);
if (updateFrame) {
serial.queueWrite("screenframeshort");
setLoadingFrame(true);
}
return data;
};

const sendCommand = () => {
write(command, false);
const sendCommand = async () => {
await write(command, false);
setCommand("");
};

Expand Down
60 changes: 59 additions & 1 deletion src/app/components/SerialProvider/SerialProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ const webSerialContext: WebSerialContext = {
ports: [],
};

export interface DataPacket {
id: number;
command: string;
response: string | null;
}

/**
*
* @param {() => void} callback
Expand Down Expand Up @@ -64,7 +70,9 @@ export interface UseWebSerialReturn {
startReading: () => Promise<void>;
stopReading: () => Promise<void>;
write: () => Promise<void>;
queueWrite: (message: string) => void;
queueWrite: (message: string) => number;
queueWriteAndResponse: (message: string) => Promise<DataPacket>;
commandResponseMap: DataPacket[];
options: {
baudRate: BaudRatesType;
bufferSize: number;
Expand Down Expand Up @@ -133,6 +141,8 @@ const useWebSerial = ({
const [ringIndicator, setRingIndicator] = useState(false);

const [messageQueue, setMessageQueue] = useState<Array<string>>([]);
const commandResponseMap = useRef<DataPacket[]>([]);
const commandCounter = useRef(0);

useInterval(() => {
const port = portRef.current;
Expand Down Expand Up @@ -297,11 +307,21 @@ const useWebSerial = ({
let completeString = "";

try {
let lastProcessedCommand = 0;
do {
await reader.read().then(({ done, value }) => {
completeString += decoder.decode(value);
if (done || completeString.endsWith("ch> ")) {
onData(completeString);

let lastCommandIndex = commandResponseMap.current.find(
(item) => item.id === lastProcessedCommand
);

if (lastCommandIndex) {
lastCommandIndex.response = completeString;
lastProcessedCommand = lastProcessedCommand + 1;
}
completeString = "";
return;
}
Expand Down Expand Up @@ -349,6 +369,7 @@ const useWebSerial = ({
writer.releaseLock();
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [messageQueue]);

useEffect(() => {
Expand All @@ -358,7 +379,42 @@ const useWebSerial = ({
}, [messageQueue, write]); // This effect will run every time `messageQueue` changes

const queueWrite = (message: string) => {
const id = commandCounter.current++;
commandResponseMap.current = [
...commandResponseMap.current,
{
id: id,
command: message,
response: null,
},
];
setMessageQueue((prevQueue) => [...prevQueue, message]); // Add the new message to the end of the queue

return id;
};

const queueWriteAndResponse = async (message: string) => {
const id = commandCounter.current++;
commandResponseMap.current = [
...commandResponseMap.current,
{
id: id,
command: message,
response: null,
},
];
setMessageQueue((prevQueue) => [...prevQueue, message]); // Add the new message to the end of the queue

let commandResponse;
while (
!(commandResponse = commandResponseMap.current.find(
(item) => item.id === id && item.response !== null
))
) {
await new Promise((r) => setTimeout(r, 50));
}

return commandResponse;
};

useEffect(() => {
Expand Down Expand Up @@ -427,6 +483,7 @@ const useWebSerial = ({
canUseSerial,
portState: portState.current,
hasTriedAutoconnect,
commandResponseMap: commandResponseMap.current,
portInfo,
manualConnectToPort,
openPort,
Expand All @@ -435,6 +492,7 @@ const useWebSerial = ({
stopReading,
write,
queueWrite,
queueWriteAndResponse,
options: {
baudRate,
bufferSize,
Expand Down

0 comments on commit c8d2f53

Please sign in to comment.