Readd complex connection logic

This commit is contained in:
GHOSCHT 2021-12-31 23:38:10 +01:00
parent 0c270ee199
commit 0c914a3dfe
No known key found for this signature in database
GPG key ID: A35BD466B8871994

View file

@ -1,27 +1,47 @@
import { Middleware, Action } from "@reduxjs/toolkit";
import { RootState } from "../store/types.d";
import {
connect, disconnect, setSerialPort, setMessage, sendMessage,
connect, disconnect, setSerialPort, setMessage, sendMessage, connectionStart, connectionFailure, connectionSuccess, connectionEnd,
} from "../slices/serialConnectionSlice";
import PortController from "../../serial/PortController";
import store from "../store";
let serialPort: PortController|null = null;
const errorCalbackHandler = () => {};
const closeCalbackHandler = () => {};
const serialDataListener = (msg: string) => { store.dispatch(setMessage(msg)); };
const serialConnection: Middleware<{}, RootState> = () => (next) => (action: Action) => {
const serialConnection: Middleware<{}, RootState> = (state) => (next) => (action: Action) => {
const errorCalbackHandler = (error: Error | null | undefined) => {
if (error === null || error === undefined) {
state.dispatch(connectionSuccess());
} else {
state.dispatch(connectionFailure(error.message));
}
};
const closeCalbackHandler = (error: Error | null | undefined) => {
if (error !== null && error !== undefined) {
if (error.message === "Reading from COM port (ReadIOCompletion): Access denied") {
state.dispatch(connectionFailure(`Device ${state.getState().serialConnection.port} disconnected`));
state.dispatch(connectionEnd());
}
}
};
const serialDataListener = (msg: string) => {
if (msg !== state.getState().serialConnection.message) {
state.dispatch(setMessage(msg));
}
};
if (connect.match(action)) {
state.dispatch(connectionStart());
if (state.getState().serialConnection.port === "") {
state.dispatch(connectionFailure("No Serial Port set"));
return next(action);
}
serialPort?.open(errorCalbackHandler, closeCalbackHandler);
serialPort?.parser.on("data", serialDataListener);
console.log("connect");
} else if (disconnect.match(action)) {
serialPort?.close();
console.log("disconnect");
state.dispatch(connectionEnd());
} else if (setSerialPort.match(action)) {
serialPort = new PortController(action.payload);
console.log("setSerialPort");
} else if (sendMessage.match(action)) {
serialPort?.write(action.payload);
}