digitale Eingänge Redux Slice erstellt für mehr Übersicht
This commit is contained in:
77
hooks/windowVariables/useLoadWindowVariables.ts
Normal file
77
hooks/windowVariables/useLoadWindowVariables.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
// hooks/windowvariables/useLoadWindowVariables.ts
|
||||
import { useEffect } from "react";
|
||||
import { useDispatch } from "react-redux";
|
||||
import { setInputs } from "../../redux/slices/digitalInputsSlice";
|
||||
|
||||
const requiredVars: string[] = [
|
||||
// Liste der benötigten Variablennamen
|
||||
"win_de_state",
|
||||
"win_de_label",
|
||||
// weitere Variablen...
|
||||
];
|
||||
|
||||
const scripts: string[] = [
|
||||
"da.js",
|
||||
"de.js",
|
||||
"ae.js",
|
||||
"kueData.js",
|
||||
"Start.js",
|
||||
"System.js",
|
||||
"opcua.js",
|
||||
];
|
||||
|
||||
const loadScript = (src: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
const environment = process.env.NEXT_PUBLIC_NODE_ENV || "production";
|
||||
script.src =
|
||||
environment === "production"
|
||||
? `/CPL?/CPL/SERVICE/${src}`
|
||||
: `/CPLmockData/SERVICE/${src}`;
|
||||
script.async = true;
|
||||
script.onload = () => resolve();
|
||||
script.onerror = () => reject(new Error(`Script load error: ${src}`));
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
};
|
||||
|
||||
export const useLoadWindowVariables = () => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
useEffect(() => {
|
||||
const loadVariables = async () => {
|
||||
try {
|
||||
for (const script of scripts) {
|
||||
await loadScript(script);
|
||||
}
|
||||
|
||||
const variablesObj: { [key: string]: any } = requiredVars.reduce(
|
||||
(acc, variable) => {
|
||||
const winVar = (window as any)[variable];
|
||||
if (winVar !== undefined) {
|
||||
acc[variable.replace("win_", "")] = winVar;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{}
|
||||
);
|
||||
|
||||
// Beispiel: Aktualisieren des Redux-Stores mit geladenen Variablen
|
||||
if (variablesObj.de_state && variablesObj.de_label) {
|
||||
const initialInputs = variablesObj.de_state.map(
|
||||
(status: number, index: number) => ({
|
||||
id: index + 1,
|
||||
label: variablesObj.de_label[index] || `Eingang ${index + 1}`,
|
||||
status: status === 1,
|
||||
})
|
||||
);
|
||||
dispatch(setInputs(initialInputs));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Fehler beim Laden der Skripte oder Variablen:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadVariables();
|
||||
}, [dispatch]);
|
||||
};
|
||||
Reference in New Issue
Block a user