@adcops/autocore-react 3.0.18 → 3.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,208 @@
1
+ /*
2
+ * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2024-04-26 09:04:40
4
+ * -----
5
+ * Last Modified: 2024-04-28 20:07:12
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+
12
+ import { useContext, useRef, useEffect } from 'react';
13
+ import { EventEmitterContext } from '../core/EventEmitterContext';
14
+
15
+
16
+ /**
17
+ * Sleep for a given number of milliseconds.
18
+ * @param ms Number of milliseconds to sleep.
19
+ */
20
+ function sleep(ms: number): Promise<void> {
21
+ return new Promise(resolve => setTimeout(resolve, ms));
22
+ }
23
+
24
+
25
+
26
+
27
+ /**
28
+ * Custom hook for registering symbols and subscribing to updates on the
29
+ * ADS domain via the EventEmitterContext.
30
+ * This hook abstracts the common pattern of registering symbols and handling subscriptions
31
+ * to updates in components that need real-time data from a backend service.
32
+ *
33
+ * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
34
+ * related to a symbol, and each value is the setter function for that state.
35
+ * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
36
+ * Each key should match a key in the `setters` object, and each value should be a string
37
+ * that represents the symbol name to register and subscribe to.
38
+ *
39
+ * ## Usage Example:
40
+ * ```typescript
41
+ * const setters = {
42
+ * speed: setSpeed,
43
+ * temperature: setTemperature
44
+ * };
45
+ *
46
+ * const symbols = {
47
+ * speed: "Sensor.speed",
48
+ * temperature: "Sensor.temperature"
49
+ * };
50
+ *
51
+ * useRegisterSymbols(setters, symbols);
52
+ * ```
53
+ *
54
+ * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
55
+ * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
56
+ * whenever new data is received.
57
+ */
58
+ export const useAdsRegisterSymbols = (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => {
59
+ const { invoke, subscribe, unsubscribe, isConnected } = useContext(EventEmitterContext);
60
+ const subscriptions = useRef<number[]>([]);
61
+ const isMounted = useRef(true);
62
+
63
+ useEffect(() => {
64
+ isMounted.current = true;
65
+
66
+ const registerAndSubscribe = async () => {
67
+ for (const [key, symbolName] of Object.entries(symbols)) {
68
+ try {
69
+ await invoke("ADS", "register_symbol", { symbol_name: symbolName });
70
+ //console.log(`Subscribe... ADS/${symbolName}`);
71
+ const subscriptionId = subscribe(`ADS/${symbolName}`, (data) => {
72
+ if (isMounted.current) {
73
+ const setter = setters[key];
74
+ if (setter) {
75
+ setter(data.value);
76
+ }
77
+ }
78
+ });
79
+ subscriptions.current.push(subscriptionId);
80
+ } catch (err) {
81
+ console.error(`Failed to register symbol ${symbolName}: ${err}`);
82
+ }
83
+ }
84
+ await invoke("ADS", "refresh", {});
85
+ };
86
+
87
+ if (!isConnected() ) {
88
+ //console.log("SCHEDULE LATER...");
89
+ let connectionSubId = subscribe("HUB/connected", () => {
90
+ registerAndSubscribe();
91
+ unsubscribe(connectionSubId);
92
+ });
93
+ subscriptions.current.push(connectionSubId);
94
+ }
95
+ else {
96
+ //console.log("ALREADY CONNECTED...");
97
+ registerAndSubscribe();
98
+ }
99
+
100
+
101
+ return () => {
102
+ //console.log("UNSUBSCRIBE");
103
+ isMounted.current = false;
104
+ subscriptions.current.forEach(subscriptionId => unsubscribe(subscriptionId));
105
+ subscriptions.current = [];
106
+ };
107
+ }, []); // Ensure setters and symbols are included if they can change
108
+
109
+ return null; // This hook does not render anything
110
+ };
111
+
112
+
113
+ /**
114
+ * Custom hook to create a function that sends a specified value to a remote device or server.
115
+ * This hook abstracts the repetitive logic involved in sending these values,
116
+ * such as invoking the command and handling errors.
117
+ *
118
+ * @param {string} domain The domain under which the backend function is grouped.
119
+ * @param {string} fname The name of the function to be called on the backend.
120
+ * @param {string} symbolName The symbol name that identifies the specific value or setting in the backend.
121
+ * @returns {Function} A function that accepts a value (number or boolean) and sends it to the configured backend.
122
+ *
123
+ * @example
124
+ * ```tsx
125
+ * import React, { useState } from 'react';
126
+ * import { Button } from 'primereact/button';
127
+ * import useWriteValue from './useWriteValue'; // adjust the import path as necessary
128
+ *
129
+ * const Component: React.FC = () => {
130
+ * const [value, setValue] = useState<number>(0);
131
+ * const writeToBackend = useAdsWriteValue("ADS", "write_value", "GNV.mySymbol");
132
+ *
133
+ * return (
134
+ * <div>
135
+ * <input
136
+ * type="number"
137
+ * value={value}
138
+ * onChange={(e) => setValue(Number(e.target.value))}
139
+ * />
140
+ * <Button
141
+ * label="Send to Backend"
142
+ * onClick={() => writeToBackend(value)}
143
+ * />
144
+ * </div>
145
+ * );
146
+ * };
147
+ */
148
+ export function useAdsWriteValue(symbolName: string) {
149
+ const { invoke } = useContext(EventEmitterContext);
150
+ const domain = "ADS";
151
+ const fname = "write_value";
152
+
153
+ // Return a function that takes a value and sends it to the backend
154
+ return async (value: object | boolean | number | string ) => {
155
+ try {
156
+ await invoke(domain, fname, { symbol_name: symbolName, value });
157
+ } catch (err) {
158
+ console.error(`Error writing tag ${symbolName}: ${err}`);
159
+ }
160
+ };
161
+ }
162
+
163
+
164
+
165
+
166
+ /**
167
+ * Custom hook to send a "tap" action, which sends true followed by false after a short delay,
168
+ * to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
169
+ *
170
+ * @param {string} domain - The domain under which the backend function is grouped.
171
+ * @param {string} fname - The function name to be called on the backend.
172
+ * @param {string} symbolName - The symbol name to target for the tap action.
173
+ * @returns {Function} A function that triggers the tap action.
174
+ *
175
+ * @example
176
+ * ```tsx
177
+ * import React from 'react';
178
+ * import { Button } from 'primereact/button';
179
+ * import useTapValue from './useTapValue'; // Ensure the correct import path
180
+ *
181
+ * const MyComponent: React.FC = () => {
182
+ * const sendTapAction = useTapValue("ADS", "write_value", "GNV.myButton");
183
+ *
184
+ * return (
185
+ * <Button
186
+ * label="Tap Button"
187
+ * onClick={() => sendTapAction()}
188
+ * />
189
+ * );
190
+ * };
191
+ * ```
192
+ */
193
+ export function useAdsTapValue(symbolName: string): () => Promise<void> {
194
+ const { invoke } = useContext(EventEmitterContext);
195
+ const domain = "ADS";
196
+ const fname = "write_value";
197
+
198
+ return async () => {
199
+ try {
200
+ await invoke(domain, fname, { symbol_name: symbolName, value: true });
201
+ await sleep(300); // Sleep for 300ms before writing false
202
+ await invoke(domain, fname, { symbol_name: symbolName, value: false });
203
+ } catch (err) {
204
+ console.error(`Error handling tap action for ${symbolName}: ${err}`);
205
+ }
206
+ };
207
+ }
208
+
@@ -1,32 +0,0 @@
1
- /**
2
- * Custom hook for registering symbols and subscribing to updates on the
3
- * ADS domain via the EventEmitterContext.
4
- * This hook abstracts the common pattern of registering symbols and handling subscriptions
5
- * to updates in components that need real-time data from a backend service.
6
- *
7
- * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
8
- * related to a symbol, and each value is the setter function for that state.
9
- * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
10
- * Each key should match a key in the `setters` object, and each value should be a string
11
- * that represents the symbol name to register and subscribe to.
12
- *
13
- * ## Usage Example:
14
- * ```typescript
15
- * const setters = {
16
- * speed: setSpeed,
17
- * temperature: setTemperature
18
- * };
19
- *
20
- * const symbols = {
21
- * speed: "Sensor.speed",
22
- * temperature: "Sensor.temperature"
23
- * };
24
- *
25
- * useRegisterSymbols(setters, symbols);
26
- * ```
27
- *
28
- * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
29
- * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
30
- * whenever new data is received.
31
- */
32
- export declare const useAdsRegisterSymbols: (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => null;
@@ -1 +0,0 @@
1
- import{useEffect,useContext,useRef}from"react";import{EventEmitterContext}from"../core/EventEmitterContext";export const useAdsRegisterSymbols=(e,t)=>{const{invoke:r,subscribe:n,unsubscribe:s,isConnected:c}=useContext(EventEmitterContext),o=useRef([]),u=useRef(!0);return useEffect((()=>{u.current=!0;const i=async()=>{for(const[s,c]of Object.entries(t))try{await r("ADS","register_symbol",{symbol_name:c});const t=n(`ADS/${c}`,(t=>{if(u.current){const r=e[s];r&&r(t.value)}}));o.current.push(t)}catch(e){}await r("ADS","refresh",{})};if(c())i();else{let e=n("HUB/connected",(()=>{i(),s(e)}));o.current.push(e)}return()=>{u.current=!1,o.current.forEach((e=>s(e))),o.current=[]}}),[]),null};
@@ -1,97 +0,0 @@
1
- /*
2
- * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
- * Created Date: 2024-04-25 09:17:05
4
- * -----
5
- * Last Modified: 2024-04-25 16:03:15
6
- * -----
7
- *
8
- */
9
-
10
-
11
- import { useEffect, useContext, useRef } from 'react';
12
- import {EventEmitterContext} from "../core/EventEmitterContext";
13
-
14
- /**
15
- * Custom hook for registering symbols and subscribing to updates on the
16
- * ADS domain via the EventEmitterContext.
17
- * This hook abstracts the common pattern of registering symbols and handling subscriptions
18
- * to updates in components that need real-time data from a backend service.
19
- *
20
- * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
21
- * related to a symbol, and each value is the setter function for that state.
22
- * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
23
- * Each key should match a key in the `setters` object, and each value should be a string
24
- * that represents the symbol name to register and subscribe to.
25
- *
26
- * ## Usage Example:
27
- * ```typescript
28
- * const setters = {
29
- * speed: setSpeed,
30
- * temperature: setTemperature
31
- * };
32
- *
33
- * const symbols = {
34
- * speed: "Sensor.speed",
35
- * temperature: "Sensor.temperature"
36
- * };
37
- *
38
- * useRegisterSymbols(setters, symbols);
39
- * ```
40
- *
41
- * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
42
- * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
43
- * whenever new data is received.
44
- */
45
- export const useAdsRegisterSymbols = (setters: Record<string, (value: any) => void>, symbols: Record<string, string>) => {
46
- const { invoke, subscribe, unsubscribe, isConnected } = useContext(EventEmitterContext);
47
- const subscriptions = useRef<number[]>([]);
48
- const isMounted = useRef(true);
49
-
50
- useEffect(() => {
51
- isMounted.current = true;
52
-
53
- const registerAndSubscribe = async () => {
54
- for (const [key, symbolName] of Object.entries(symbols)) {
55
- try {
56
- await invoke("ADS", "register_symbol", { symbol_name: symbolName });
57
- //console.log(`Subscribe... ADS/${symbolName}`);
58
- const subscriptionId = subscribe(`ADS/${symbolName}`, (data) => {
59
- if (isMounted.current) {
60
- const setter = setters[key];
61
- if (setter) {
62
- setter(data.value);
63
- }
64
- }
65
- });
66
- subscriptions.current.push(subscriptionId);
67
- } catch (err) {
68
- console.error(`Failed to register symbol ${symbolName}: ${err}`);
69
- }
70
- }
71
- await invoke("ADS", "refresh", {});
72
- };
73
-
74
- if (!isConnected() ) {
75
- //console.log("SCHEDULE LATER...");
76
- let connectionSubId = subscribe("HUB/connected", () => {
77
- registerAndSubscribe();
78
- unsubscribe(connectionSubId);
79
- });
80
- subscriptions.current.push(connectionSubId);
81
- }
82
- else {
83
- //console.log("ALREADY CONNECTED...");
84
- registerAndSubscribe();
85
- }
86
-
87
-
88
- return () => {
89
- //console.log("UNSUBSCRIBE");
90
- isMounted.current = false;
91
- subscriptions.current.forEach(subscriptionId => unsubscribe(subscriptionId));
92
- subscriptions.current = [];
93
- };
94
- }, []); // Ensure setters and symbols are included if they can change
95
-
96
- return null; // This hook does not render anything
97
- };