@adcops/autocore-react 3.0.31 → 3.0.32

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,145 @@
1
+ /**
2
+ * Custom hook for registering symbols and subscribing to updates on
3
+ * a 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 useRegisterSymbols: (domain: string, setters: Record<string, (value: any) => void>, symbols: Record<string, string>, options?: Record<string, {}>) => null;
33
+ /**
34
+ * Custom hook to create a function that sends a specified value to a remote device or server.
35
+ * This hook abstracts the repetitive logic involved in sending these values,
36
+ * such as invoking the command and handling errors.
37
+ *
38
+ * @param {string} domain The domain under which the backend function is grouped.
39
+ * @param {string} fname The name of the function to be called on the backend.
40
+ * @param {string} symbolName The symbol name that identifies the specific value or setting in the backend.
41
+ * @returns {Function} A function that accepts a value (number or boolean) and sends it to the configured backend.
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * import React, { useState } from 'react';
46
+ * import { Button } from 'primereact/button';
47
+ * import useWriteValue from './commandHooks';
48
+ *
49
+ * const Component: React.FC = () => {
50
+ * const [value, setValue] = useState<number>(0);
51
+ * const writeToBackend = useAdsWriteValue("ADS", "write_value", "GNV.mySymbol");
52
+ *
53
+ * return (
54
+ * <div>
55
+ * <input
56
+ * type="number"
57
+ * value={value}
58
+ * onChange={(e) => setValue(Number(e.target.value))}
59
+ * />
60
+ * <Button
61
+ * label="Send to Backend"
62
+ * onClick={() => writeToBackend(value)}
63
+ * />
64
+ * </div>
65
+ * );
66
+ * };
67
+ */
68
+ export declare function useAdsWriteValue(domain: string, symbolName: string, fname?: string): (value: object | boolean | number | string) => Promise<void>;
69
+ /**
70
+ * useWriteScaledValue is a custom React hook that enables writing scaled numerical values to the autocore backend system.
71
+ * It applies a specified scale and offset to a numeric value before sending it over the websocket connection.
72
+ * This hook is ideal for scenarios where numeric data needs to be adjusted according to dynamically configurable
73
+ * scale factors before being persisted or processed by a backend system.
74
+ *
75
+ * @param symbolName The symbol name in the backend system where the value will be written.
76
+ * @param scale The scale factor to be applied to the value.
77
+ * @param offset The offset to be applied after scaling the value.
78
+ * @returns A function that takes a numeric value, applies the scaling and offset, and sends the modified value to the backend.
79
+ *
80
+ * @example
81
+ * This example demonstrates how to use the `useAdsWriteScaledValue` hook within a component that allows users
82
+ * to input a value in inches, which is then automatically converted to millimeters (if the scale is set for such conversion)
83
+ * based on a dynamic scale factor managed in the component's state.
84
+ *
85
+ * ```tsx
86
+ * import React, { useState } from 'react';
87
+ * import { useWriteScaledValue } from './commandHooks';
88
+ *
89
+ * const MeasurementInput: React.FC = () => {
90
+ * const [scale, setScale] = useState<number>(1 / 25.4); // Initial scale for converting inches to millimeters.
91
+ * const [offset, setOffset] = useState<number>(0); // No offset by default.
92
+ *
93
+ * // The hook is used here with the scale and offset state variables.
94
+ * const writeMeasurement = useWriteScaledValue("ADS", "GIO.axisX.position", scale, offset);
95
+ *
96
+ * // This function is called when the input field value changes.
97
+ * const handleMeasurementChange = (event: React.ChangeEvent<HTMLInputElement>) => {
98
+ * const valueInInches = parseFloat(event.target.value);
99
+ * writeMeasurement(valueInInches); // Write the scaled value (converted to millimeters).
100
+ * };
101
+ *
102
+ * return (
103
+ * <div>
104
+ * <label>Enter measurement in inches:</label>
105
+ * <input type="number" onChange={handleMeasurementChange} />
106
+ * </div>
107
+ * );
108
+ * };
109
+ *
110
+ * export default MeasurementInput;
111
+ * ```
112
+ *
113
+ * In this component, `writeMeasurement` is a function returned by the `useAdsWriteScaledValue` hook that takes a value in inches,
114
+ * converts it to millimeters using the current `scale`, and writes the result to a backend symbol. The `scale` and `offset` can be adjusted
115
+ * dynamically if needed, for instance, based on user selection or other external configurations.
116
+ */
117
+ export declare function useWriteScaledValue(domain: string, symbolName: string, scale: number, offset: number, fname?: string): (value: number) => Promise<void>;
118
+ /**
119
+ * Custom hook to send a "tap" action, which sends true followed by false after a short delay,
120
+ * to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
121
+ *
122
+ * @param {string} domain - The domain under which the backend function is grouped.
123
+ * @param {string} fname - The function name to be called on the backend.
124
+ * @param {string} symbolName - The symbol name to target for the tap action.
125
+ * @returns {Function} A function that triggers the tap action.
126
+ *
127
+ * @example
128
+ * ```tsx
129
+ * import React from 'react';
130
+ * import { Button } from 'primereact/button';
131
+ * import useTapValue from './useTapValue'; // Ensure the correct import path
132
+ *
133
+ * const MyComponent: React.FC = () => {
134
+ * const sendTapAction = useTapValue("ADS", "write_value", "GNV.myButton");
135
+ *
136
+ * return (
137
+ * <Button
138
+ * label="Tap Button"
139
+ * onClick={() => sendTapAction()}
140
+ * />
141
+ * );
142
+ * };
143
+ * ```
144
+ */
145
+ export declare function useTapValue(domain: string, symbolName: string, fname?: string): () => Promise<void>;
@@ -0,0 +1 @@
1
+ import{useContext,useRef,useEffect,useCallback}from"react";import{EventEmitterContext}from"../core/EventEmitterContext";function sleep(e){return new Promise((t=>setTimeout(t,e)))}export const useRegisterSymbols=(e,t,n,r={})=>{const{subscribe:u,unsubscribe:s,isConnected:o}=useContext(EventEmitterContext),c=useRef([]),a=useRef(!0);return useEffect((()=>{a.current=!0;const r=async()=>{for(const[r,s]of Object.entries(n))try{const n=u(`${e}/${s}`,(e=>{if(a.current){const n=t[r];n&&n(e.value)}}));c.current.push(n)}catch(e){}};if(o())r();else{let e=u("HUB/connected",(()=>{setTimeout((()=>{r(),s(e)}),500)}));c.current.push(e)}return()=>{a.current=!1,c.current.forEach((e=>s(e))),c.current=[]}}),[]),null};export function useAdsWriteValue(e,t,n="write_value"){const{invoke:r}=useContext(EventEmitterContext);return async u=>{try{await r(e,n,{symbol_name:t,value:u})}catch(e){}}}export function useWriteScaledValue(e,t,n,r,u="write_value"){const{invoke:s}=useContext(EventEmitterContext);return useCallback((async o=>{const c=(o-r)/n;try{await s(e,u,{symbol_name:t,value:c})}catch(e){}}),[t,n,r,s])}export function useTapValue(e,t,n="write_value"){const{invoke:r}=useContext(EventEmitterContext);return async()=>{try{await r(e,n,{symbol_name:t,value:!0}),await sleep(300),await r(e,n,{symbol_name:t,value:!1})}catch(e){}}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adcops/autocore-react",
3
- "version": "3.0.31",
3
+ "version": "3.0.32",
4
4
  "description": "A React component library for industrial user interfaces.",
5
5
  "private": false,
6
6
  "type": "module",
@@ -10,6 +10,7 @@
10
10
  "tsc": "tsc",
11
11
  "generate-docs": "typedoc",
12
12
  "build": "npm run clean && tsc && node ./tools/copy-distribution-files.cjs && npm run minify",
13
+ "dev": "npm run clean && tsc && node ./tools/copy-distribution-files.cjs",
13
14
  "prestart": "tsc",
14
15
  "publish-package": "npm run build && npm version patch && npm publish",
15
16
  "release:patch": "npm version patch && npm publish",
@@ -0,0 +1,293 @@
1
+ /*
2
+ * Copyright (C) 2025 Automated Design Corp. All Rights Reserved.
3
+ * Created Date: 2025-03-31 06:38:50
4
+ * -----
5
+ * Last Modified: 2025-03-31 08:34:03
6
+ * -----
7
+ *
8
+ */
9
+
10
+
11
+
12
+
13
+
14
+
15
+ import { useContext, useRef, useEffect, useCallback } from 'react';
16
+ import { EventEmitterContext } from '../core/EventEmitterContext';
17
+
18
+
19
+ /**
20
+ * Sleep for a given number of milliseconds.
21
+ * @param ms Number of milliseconds to sleep.
22
+ */
23
+ function sleep(ms: number): Promise<void> {
24
+ return new Promise(resolve => setTimeout(resolve, ms));
25
+ }
26
+
27
+
28
+
29
+
30
+ /**
31
+ * Custom hook for registering symbols and subscribing to updates on
32
+ * a domain via the EventEmitterContext.
33
+ * This hook abstracts the common pattern of registering symbols and handling subscriptions
34
+ * to updates in components that need real-time data from a backend service.
35
+ *
36
+ * @param setters A mapping of state setter functions, where each key corresponds to a piece of state
37
+ * related to a symbol, and each value is the setter function for that state.
38
+ * @param symbols A mapping of state keys to their corresponding symbol names in the backend system.
39
+ * Each key should match a key in the `setters` object, and each value should be a string
40
+ * that represents the symbol name to register and subscribe to.
41
+ *
42
+ * ## Usage Example:
43
+ * ```typescript
44
+ * const setters = {
45
+ * speed: setSpeed,
46
+ * temperature: setTemperature
47
+ * };
48
+ *
49
+ * const symbols = {
50
+ * speed: "Sensor.speed",
51
+ * temperature: "Sensor.temperature"
52
+ * };
53
+ *
54
+ * useRegisterSymbols(setters, symbols);
55
+ * ```
56
+ *
57
+ * This will register and subscribe to updates for "Sensor.speed" and "Sensor.temperature",
58
+ * and update the `speed` and `temperature` states via `setSpeed` and `setTemperature` respectively
59
+ * whenever new data is received.
60
+ */
61
+ export const useRegisterSymbols = (
62
+ domain : string,
63
+ setters: Record<string, (value: any) => void>,
64
+ symbols: Record<string, string>,
65
+ options: Record<string, {}> = {},
66
+ ) => {
67
+ const { subscribe, unsubscribe, isConnected } = useContext(EventEmitterContext);
68
+ const subscriptions = useRef<number[]>([]);
69
+ const isMounted = useRef(true);
70
+
71
+ /// Options is reserved for future use.
72
+ options;
73
+
74
+ useEffect(() => {
75
+ isMounted.current = true;
76
+
77
+ const registerAndSubscribe = async () => {
78
+ for (const [key, symbolName] of Object.entries(symbols)) {
79
+ try {
80
+ //console.log(`Subscribe... ${domain}/${symbolName}`);
81
+ const subscriptionId = subscribe(`${domain}/${symbolName}`, (data) => {
82
+
83
+ //console.log(`Value received for ${key} to ${data.value}`);
84
+ if (isMounted.current) {
85
+ //console.log(`Setting ${key} to ${data.value}`);
86
+ const setter = setters[key];
87
+ if (setter) {
88
+ setter(data.value);
89
+ }
90
+ }
91
+ });
92
+ subscriptions.current.push(subscriptionId);
93
+ } catch (err) {
94
+ console.error(`Failed to register symbol ${symbolName}: ${err}`);
95
+ }
96
+ }
97
+
98
+ // Currently, there isn't a global mechanism in autocore-server for refreshing all tags.
99
+ // await invoke(domain, "refresh", {});
100
+ };
101
+
102
+ if (!isConnected() ) {
103
+ //console.log("SCHEDULE LATER...");
104
+ let connectionSubId = subscribe("HUB/connected", () => {
105
+ setTimeout(() => {
106
+ registerAndSubscribe();
107
+ unsubscribe(connectionSubId);
108
+ }, 500);
109
+ });
110
+ subscriptions.current.push(connectionSubId);
111
+ }
112
+ else {
113
+ //console.log("ALREADY CONNECTED...");
114
+ registerAndSubscribe();
115
+ }
116
+
117
+
118
+ return () => {
119
+ //console.log("UNSUBSCRIBE");
120
+ isMounted.current = false;
121
+ subscriptions.current.forEach(subscriptionId => unsubscribe(subscriptionId));
122
+ subscriptions.current = [];
123
+ };
124
+ }, []); // Ensure setters and symbols are included if they can change
125
+
126
+ return null; // This hook does not render anything
127
+ };
128
+
129
+
130
+ /**
131
+ * Custom hook to create a function that sends a specified value to a remote device or server.
132
+ * This hook abstracts the repetitive logic involved in sending these values,
133
+ * such as invoking the command and handling errors.
134
+ *
135
+ * @param {string} domain The domain under which the backend function is grouped.
136
+ * @param {string} fname The name of the function to be called on the backend.
137
+ * @param {string} symbolName The symbol name that identifies the specific value or setting in the backend.
138
+ * @returns {Function} A function that accepts a value (number or boolean) and sends it to the configured backend.
139
+ *
140
+ * @example
141
+ * ```tsx
142
+ * import React, { useState } from 'react';
143
+ * import { Button } from 'primereact/button';
144
+ * import useWriteValue from './commandHooks';
145
+ *
146
+ * const Component: React.FC = () => {
147
+ * const [value, setValue] = useState<number>(0);
148
+ * const writeToBackend = useAdsWriteValue("ADS", "write_value", "GNV.mySymbol");
149
+ *
150
+ * return (
151
+ * <div>
152
+ * <input
153
+ * type="number"
154
+ * value={value}
155
+ * onChange={(e) => setValue(Number(e.target.value))}
156
+ * />
157
+ * <Button
158
+ * label="Send to Backend"
159
+ * onClick={() => writeToBackend(value)}
160
+ * />
161
+ * </div>
162
+ * );
163
+ * };
164
+ */
165
+ export function useAdsWriteValue(domain : string, symbolName: string, fname : string = "write_value") {
166
+ const { invoke } = useContext(EventEmitterContext);
167
+
168
+ // Return a function that takes a value and sends it to the backend
169
+ return async (value: object | boolean | number | string ) => {
170
+ try {
171
+ await invoke(domain, fname, { symbol_name: symbolName, value });
172
+ } catch (err) {
173
+ console.error(`Error writing tag ${symbolName}: ${err}`);
174
+ }
175
+ };
176
+ }
177
+
178
+
179
+
180
+
181
+
182
+
183
+ /**
184
+ * useWriteScaledValue is a custom React hook that enables writing scaled numerical values to the autocore backend system.
185
+ * It applies a specified scale and offset to a numeric value before sending it over the websocket connection.
186
+ * This hook is ideal for scenarios where numeric data needs to be adjusted according to dynamically configurable
187
+ * scale factors before being persisted or processed by a backend system.
188
+ *
189
+ * @param symbolName The symbol name in the backend system where the value will be written.
190
+ * @param scale The scale factor to be applied to the value.
191
+ * @param offset The offset to be applied after scaling the value.
192
+ * @returns A function that takes a numeric value, applies the scaling and offset, and sends the modified value to the backend.
193
+ *
194
+ * @example
195
+ * This example demonstrates how to use the `useAdsWriteScaledValue` hook within a component that allows users
196
+ * to input a value in inches, which is then automatically converted to millimeters (if the scale is set for such conversion)
197
+ * based on a dynamic scale factor managed in the component's state.
198
+ *
199
+ * ```tsx
200
+ * import React, { useState } from 'react';
201
+ * import { useWriteScaledValue } from './commandHooks';
202
+ *
203
+ * const MeasurementInput: React.FC = () => {
204
+ * const [scale, setScale] = useState<number>(1 / 25.4); // Initial scale for converting inches to millimeters.
205
+ * const [offset, setOffset] = useState<number>(0); // No offset by default.
206
+ *
207
+ * // The hook is used here with the scale and offset state variables.
208
+ * const writeMeasurement = useWriteScaledValue("ADS", "GIO.axisX.position", scale, offset);
209
+ *
210
+ * // This function is called when the input field value changes.
211
+ * const handleMeasurementChange = (event: React.ChangeEvent<HTMLInputElement>) => {
212
+ * const valueInInches = parseFloat(event.target.value);
213
+ * writeMeasurement(valueInInches); // Write the scaled value (converted to millimeters).
214
+ * };
215
+ *
216
+ * return (
217
+ * <div>
218
+ * <label>Enter measurement in inches:</label>
219
+ * <input type="number" onChange={handleMeasurementChange} />
220
+ * </div>
221
+ * );
222
+ * };
223
+ *
224
+ * export default MeasurementInput;
225
+ * ```
226
+ *
227
+ * In this component, `writeMeasurement` is a function returned by the `useAdsWriteScaledValue` hook that takes a value in inches,
228
+ * converts it to millimeters using the current `scale`, and writes the result to a backend symbol. The `scale` and `offset` can be adjusted
229
+ * dynamically if needed, for instance, based on user selection or other external configurations.
230
+ */
231
+ export function useWriteScaledValue(domain : string, symbolName: string, scale: number, offset: number, fname : string = "write_value") {
232
+ const { invoke } = useContext(EventEmitterContext);
233
+
234
+ return useCallback(async (value: number) => {
235
+
236
+ // In autocore-react, we multiple to scale incoming values,
237
+ // divide to scale outgoing values.
238
+ // This is an OUTGOING value, so we divide.
239
+
240
+ const scaledValue = (value - offset) / scale;
241
+ try {
242
+ await invoke(domain, fname, { symbol_name: symbolName, value: scaledValue });
243
+ } catch (err) {
244
+ console.error(`Error writing scaled value to tag ${symbolName}: ${err}`);
245
+ }
246
+ }, [symbolName, scale, offset, invoke]);
247
+ }
248
+
249
+
250
+
251
+
252
+
253
+ /**
254
+ * Custom hook to send a "tap" action, which sends true followed by false after a short delay,
255
+ * to a specified symbol in the backend. This is used to simulate a button tap or momentary switch.
256
+ *
257
+ * @param {string} domain - The domain under which the backend function is grouped.
258
+ * @param {string} fname - The function name to be called on the backend.
259
+ * @param {string} symbolName - The symbol name to target for the tap action.
260
+ * @returns {Function} A function that triggers the tap action.
261
+ *
262
+ * @example
263
+ * ```tsx
264
+ * import React from 'react';
265
+ * import { Button } from 'primereact/button';
266
+ * import useTapValue from './useTapValue'; // Ensure the correct import path
267
+ *
268
+ * const MyComponent: React.FC = () => {
269
+ * const sendTapAction = useTapValue("ADS", "write_value", "GNV.myButton");
270
+ *
271
+ * return (
272
+ * <Button
273
+ * label="Tap Button"
274
+ * onClick={() => sendTapAction()}
275
+ * />
276
+ * );
277
+ * };
278
+ * ```
279
+ */
280
+ export function useTapValue(domain : string, symbolName: string, fname : string = "write_value"): () => Promise<void> {
281
+ const { invoke } = useContext(EventEmitterContext);
282
+
283
+ return async () => {
284
+ try {
285
+ await invoke(domain, fname, { symbol_name: symbolName, value: true });
286
+ await sleep(300); // Sleep for 300ms before writing false
287
+ await invoke(domain, fname, { symbol_name: symbolName, value: false });
288
+ } catch (err) {
289
+ console.error(`Error handling tap action for ${symbolName}: ${err}`);
290
+ }
291
+ };
292
+ }
293
+
@@ -3,7 +3,7 @@
3
3
  * Created Date: 2023-12-15 14:21:33
4
4
  * Author: Thomas C. Bitsky Jr.
5
5
  * -----
6
- * Last Modified: 2024-04-25 14:44:14
6
+ * Last Modified: 2025-03-31 08:35:09
7
7
  * Modified By: ADC
8
8
  * -----
9
9
  *
@@ -166,6 +166,8 @@ export abstract class HubBase {
166
166
  */
167
167
  publish(topic : string, data : any | undefined) : void {
168
168
  const convertedTopic = this.toLocalTopic(topic);
169
+
170
+ console.log(`HUB Dispatch topic ${convertedTopic} payload ${JSON.stringify(data)}`);
169
171
  this.context?.dispatch({
170
172
  topic: convertedTopic,
171
173
  payload: data
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-04-17 09:13:07
4
4
  * -----
5
- * Last Modified: 2024-04-25 14:42:02
5
+ * Last Modified: 2025-03-31 08:35:12
6
6
  * -----
7
7
  *
8
8
  */
@@ -158,6 +158,8 @@ export class HubWebSocket extends HubBase {
158
158
  this.socket.onmessage = (event) => {
159
159
  const data: CommandMessage = JSON.parse(event.data);
160
160
 
161
+ // console.log(`MSG: ${JSON.stringify(data)}`);
162
+
161
163
  if (data.request_id && this.pendingRequests.has(data.request_id)) {
162
164
 
163
165
  const { resolve, reject } = this.pendingRequests.get(data.request_id)!;
@@ -253,9 +255,15 @@ export class HubWebSocket extends HubBase {
253
255
  && msg.result !== undefined && msg.result !== null
254
256
  && msg.result.data !== undefined && msg.result.data !== null
255
257
  ) {
258
+
256
259
  let topic = `${msg.domain}/${msg.result.data["topic"]}`;
260
+
261
+ //console.log(`HUB PUBLISHING: ${topic} : ${JSON.stringify(msg.result.data)}`);
257
262
  this.publish(topic, msg.result.data);
258
263
  }
264
+ // else {
265
+ // console.error("INVALID BROADCAST RECEIVED!");
266
+ // }
259
267
  }
260
268
 
261
269
  disconnect= (): void => {