First implementation of connection in middleware

This commit is contained in:
GHOSCHT 2021-12-31 22:48:00 +01:00
parent e9364c73bf
commit a7af6cc8de
No known key found for this signature in database
GPG key ID: A35BD466B8871994
3 changed files with 36 additions and 5 deletions

View file

@ -4,6 +4,8 @@ import { createGlobalStyle } from "styled-components";
import Select from "react-select";
import SerialPort from "serialport";
import KnobSection from "./Components/KnobSection";
import { useAppDispatch } from "./redux/hooks";
import { connect, setSerialPort } from "./redux/slices/serialConnectionSlice";
const GlobalStyle = createGlobalStyle`
html {
@ -26,14 +28,14 @@ const fetchPorts = async () => {
};
const App = () => {
// const dispatch = useDispatch();
const dispatch = useAppDispatch();
fetchPorts();
const [portSelectionValue, setPortSelectionValue] = useState(options[0]);
const handlePortChange = async (selectedOption: any) => {
setPortSelectionValue(selectedOption);
// dispatch(setSerialPort(selectedOption.value));
dispatch(setSerialPort(selectedOption.value));
};
return (
@ -43,7 +45,7 @@ const App = () => {
<button
type="button"
onClick={() => {
// dispatch(connect());
dispatch(connect());
}}
>
connect

View file

@ -0,0 +1,29 @@
import { Middleware, Action } from "@reduxjs/toolkit";
import { RootState } from "../store/types.d";
import {
connect, disconnect, setSerialPort, setMessage,
} 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) => {
if (connect.match(action)) {
serialPort?.open(errorCalbackHandler, closeCalbackHandler);
serialPort?.parser.on("data", serialDataListener);
console.log("connect");
} else if (disconnect.match(action)) {
serialPort?.close();
console.log("disconnect");
} else if (setSerialPort.match(action)) {
serialPort = new PortController(action.payload);
console.log("setSerialPort");
}
return next(action);
};
export default serialConnection;

View file

@ -1,9 +1,9 @@
import thunk from "redux-thunk";
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./root-reducer";
import logger from "../middlewares/logger";
import serialConnection from "../middlewares/serialConnection";
const middlewares = [thunk, logger];
const middlewares = [thunk, serialConnection];
const store = configureStore(
{