diff --git a/Dashboard/src/redux/middlewares/serialConnection.ts b/Dashboard/src/redux/middlewares/serialConnection.ts index 65ae43a..faf995d 100644 --- a/Dashboard/src/redux/middlewares/serialConnection.ts +++ b/Dashboard/src/redux/middlewares/serialConnection.ts @@ -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); }