@adcops/autocore-react 3.0.29 → 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.
@@ -55,6 +55,12 @@ type FileListProps = {
55
55
  * The component uses the `EventEmitterContext` to make API calls to a backend to list, download, and delete files.
56
56
  * It dynamically handles file operations based on the `domain` prop which determines the API endpoints for these actions.
57
57
  *
58
+ * Requires
59
+ * ```tsx
60
+ * <ConfirmPopup />
61
+ * ```
62
+ * somewhere in a top-level page.
63
+ *
58
64
  * Props:
59
65
  * - `domain` (string): The domain name assigned to the DATASTORE servelet containing the data.
60
66
  * Default: "DATASTORE"
@@ -1 +1 @@
1
- import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import React,{useState,useContext,useEffect}from"react";import{DataTable}from"primereact/datatable";import{Column}from"primereact/column";import{Toolbar}from"primereact/toolbar";import{Button}from"primereact/button";import{ConfirmPopup,confirmPopup}from"primereact/confirmpopup";import{FileUpload}from"primereact/fileupload";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileList=({domain:e="DATASTORE",enableUpload:t=!1,subdir:o,filter:a=".json",onSuccess:n,onError:i})=>{const[r,l]=useState(0),{invoke:s}=useContext(EventEmitterContext),[c,m]=useState(),d=e=>null!==e?void 0!==o?`${o}/${e}`:e:"",p=async()=>{try{const t=void 0!==o?{subdir:o}:{};let a=await s(e,"list_files",t),n=[];for(let e=0;e<a.data.length;++e){const t=a.data[e];n.push({id:e+1,name:t})}m(n)}catch(e){i&&i(`Failed to upload file list: ${e}`)}};const u=()=>{l((e=>e+1))},f=`File Listing [/${void 0!==o?o:""}]`,x=_jsx(React.Fragment,{children:_jsx("span",{style:{fontWeight:600},children:f})}),b=_jsxs(React.Fragment,{children:[t&&_jsx(FileUpload,{customUpload:!0,auto:!0,uploadHandler:async t=>{const o=t.files[0];let a=d(o.name);const r=new FileReader;r.onload=async t=>{const r=t.target?.result,l=function c(e){let t="",o=new Uint8Array(e),a=o.byteLength;for(let e=0;e<a;e++)t+=String.fromCharCode(o[e]);return window.btoa(t)}(r);try{await s(e,"write_file",{file_name:a,value:l,options:{base64:!0}}),n&&n(`Uploaded file ${o.name}`),p()}catch(e){i&&i(`Failed to upload file: ${e}`)}u()},r.onerror=e=>{i&&i(`Error reading file: ${e}`)},r.readAsArrayBuffer(o)},accept:a,maxFileSize:25e3,mode:"basic",chooseLabel:"",chooseOptions:{icon:"pi pi-upload",className:"p-button-icon-only p-button-text p-button-rounded p-mr-2"}},r),_jsx(Button,{icon:"pi pi-refresh",onClick:()=>{p()},className:"p-button-rounded p-mr-2","aria-label":"Refresh",size:"small",rounded:!0,text:!0})]}),_=(t,o)=>{confirmPopup({target:o.currentTarget,message:`Are you want to delete file ${t.name}?\nWARNING: This cannot be undone.`,icon:"pi pi-info-circle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>(async t=>{let o=d(t);try{await s(e,"delete_file",{file_name:o}),n&&n(`Deleted file: ${t}`),p()}catch(e){i&&i(`Failed to delete file: ${e}`)}p()})(t.name)})};return useEffect((()=>(p(),()=>{})),[e,t]),_jsxs("div",{children:[_jsx(Toolbar,{start:x,end:b,style:{padding:"1mm"}}),_jsx(ConfirmPopup,{}),_jsxs(DataTable,{value:c,children:[_jsx(Column,{field:"name",header:"Name"}),_jsx(Column,{body:t=>_jsxs(_Fragment,{children:[_jsx(Button,{icon:"pi pi-download",onClick:()=>(async t=>{let o=d(t.name);try{await s(e,"download_file",{file_name:o}),n&&n(`Downloaded file: ${t.name}`)}catch(e){i&&i(`Failed downloading file: ${e}`)}})(t),className:"p-button-rounded p-button-success p-mr-2",style:{marginRight:"2mm"},size:"small"}),_jsx(Button,{icon:"pi pi-trash",onClick:e=>_(t,e),className:"p-button-rounded p-button-danger",size:"small"})]}),header:"Actions"})]})]})};export default FileList;
1
+ import{jsx as _jsx,jsxs as _jsxs,Fragment as _Fragment}from"react/jsx-runtime";import React,{useState,useContext,useEffect}from"react";import{DataTable}from"primereact/datatable";import{Column}from"primereact/column";import{Toolbar}from"primereact/toolbar";import{Button}from"primereact/button";import{confirmPopup}from"primereact/confirmpopup";import{FileUpload}from"primereact/fileupload";import{EventEmitterContext}from"../core/EventEmitterContext";export const FileList=({domain:e="DATASTORE",enableUpload:t=!1,subdir:o,filter:a=".json",onSuccess:n,onError:i})=>{const[r,l]=useState(0),{invoke:s}=useContext(EventEmitterContext),[c,d]=useState(),m=e=>null!==e?void 0!==o?`${o}/${e}`:e:"",p=async()=>{try{const t=void 0!==o?{subdir:o}:{};let a=await s(e,"list_files",t),n=[];for(let e=0;e<a.data.length;++e){const t=a.data[e];n.push({id:e+1,name:t})}d(n)}catch(e){i&&i(`Failed to upload file list: ${e}`)}};const u=()=>{l((e=>e+1))},f=`File Listing [/${void 0!==o?o:""}]`,x=_jsx(React.Fragment,{children:_jsx("span",{style:{fontWeight:600},children:f})}),b=_jsxs(React.Fragment,{children:[t&&_jsx(FileUpload,{customUpload:!0,auto:!0,uploadHandler:async t=>{const o=t.files[0];let a=m(o.name);const r=new FileReader;r.onload=async t=>{const r=t.target?.result,l=function c(e){let t="",o=new Uint8Array(e),a=o.byteLength;for(let e=0;e<a;e++)t+=String.fromCharCode(o[e]);return window.btoa(t)}(r);try{await s(e,"write_file",{file_name:a,value:l,options:{base64:!0}}),n&&n(`Uploaded file ${o.name}`),p()}catch(e){i&&i(`Failed to upload file: ${e}`)}u()},r.onerror=e=>{i&&i(`Error reading file: ${e}`)},r.readAsArrayBuffer(o)},accept:a,maxFileSize:25e3,mode:"basic",chooseLabel:"",chooseOptions:{icon:"pi pi-upload",className:"p-button-icon-only p-button-text p-button-rounded p-mr-2"}},r),_jsx(Button,{icon:"pi pi-refresh",onClick:()=>{p()},className:"p-button-rounded p-mr-2","aria-label":"Refresh",size:"small",rounded:!0,text:!0})]}),h=(t,o)=>{confirmPopup({target:o.currentTarget,message:`Are you want to delete file ${t.name}?\nWARNING: This cannot be undone.`,icon:"pi pi-info-circle",defaultFocus:"reject",acceptClassName:"p-button-danger",accept:()=>(async t=>{let o=m(t);try{await s(e,"delete_file",{file_name:o}),n&&n(`Deleted file: ${t}`),p()}catch(e){i&&i(`Failed to delete file: ${e}`)}p()})(t.name)})};return useEffect((()=>(p(),()=>{})),[e,t]),_jsxs("div",{children:[_jsx(Toolbar,{start:x,end:b,style:{padding:"1mm"}}),_jsxs(DataTable,{value:c,children:[_jsx(Column,{field:"name",header:"Name"}),_jsx(Column,{body:t=>_jsxs(_Fragment,{children:[_jsx(Button,{icon:"pi pi-download",onClick:()=>(async t=>{let o=m(t.name);try{await s(e,"download_file",{file_name:o}),n&&n(`Downloaded file: ${t.name}`)}catch(e){i&&i(`Failed downloading file: ${e}`)}})(t),className:"p-button-rounded p-button-success p-mr-2",style:{marginRight:"2mm"},size:"small"}),_jsx(Button,{icon:"pi pi-trash",onClick:e=>h(t,e),className:"p-button-rounded p-button-danger",size:"small"})]}),header:"Actions"})]})]})};export default FileList;
@@ -0,0 +1,87 @@
1
+ import { Component } from 'react';
2
+ import { EventEmitterContextType } from '../core/EventEmitterContext';
3
+ import { IndicatorColor } from "../core/IndicatorColor";
4
+ export { IndicatorColor };
5
+ /**
6
+ * Common properties for an indicator rectangle component.
7
+ * This component is used for displaying states and is not interactive.
8
+ * It is commonly used in industrial HMIs for visual indication purposes.
9
+ *
10
+ * These properties support displaying values of boolean, number, and string states.
11
+ *
12
+ * Available boolean states: **on**, **off**, and **not available**:
13
+ *
14
+ * * `true` is treated as **on**
15
+ * * `false` is treated as **off**
16
+ * * `undefined` is treated as **not available**
17
+ *
18
+ * Numeric values can be used. When there are 2 or fewer possible states,
19
+ * 0 will be considered false (OFF), anything else will be considered true (ON).
20
+ * Undefined will be treated as "not available."
21
+ *
22
+ * When the indicator contains more than 2 states, the number will be matched
23
+ * to the available state, in order. More than two states requires usage of the
24
+ * `options` field and declaring more than two states there.
25
+ *
26
+ * If a string state is used, it will be matched exactly to the corresponding
27
+ * label in the `options` field.
28
+ */
29
+ export interface IndicatorRectProps {
30
+ /**
31
+ * Topic name to monitor for state indication.
32
+ */
33
+ topic?: string;
34
+ /**
35
+ * State to be displayed.
36
+ */
37
+ value?: boolean | number | string;
38
+ /**
39
+ * Color for the rectangle when the state is TRUE.
40
+ */
41
+ onColor?: IndicatorColor;
42
+ /**
43
+ * Color for the rectangle when the state is FALSE.
44
+ */
45
+ offColor?: IndicatorColor;
46
+ /**
47
+ * An array of string labels to display as the available options.
48
+ *
49
+ * For items with 2 states or less:
50
+ * Index 0 is the label when value is OFF.
51
+ * Index 1 is the label when value is ON.
52
+ *
53
+ * If only one value is given (Index 0), then that value is used for all states.
54
+ */
55
+ options?: string[];
56
+ /**
57
+ * Additional CSS class name to apply to the rectangle.
58
+ */
59
+ className?: string;
60
+ /**
61
+ * Additional inline styles to apply to the rectangle.
62
+ */
63
+ style?: React.CSSProperties;
64
+ }
65
+ interface IndicatorRectState {
66
+ currentValue?: boolean | number | string;
67
+ }
68
+ export declare class IndicatorRect extends Component<IndicatorRectProps, IndicatorRectState> {
69
+ static contextType: import("react").Context<EventEmitterContextType>;
70
+ static defaultProps: {
71
+ onColor: IndicatorColor;
72
+ offColor: string;
73
+ };
74
+ constructor(props: IndicatorRectProps);
75
+ componentDidMount(): void;
76
+ componentWillUnmount(): void;
77
+ /**
78
+ * Sets up subscriptions based on the provided topic.
79
+ */
80
+ private setupSubscriptions;
81
+ /**
82
+ * Handles updates for the main topic.
83
+ */
84
+ private handleTopicUpdate;
85
+ render(): import("react/jsx-runtime").JSX.Element;
86
+ }
87
+ export default IndicatorRect;
@@ -0,0 +1 @@
1
+ import{jsx as _jsx}from"react/jsx-runtime";import{Component}from"react";import{EventEmitterContext}from"../core/EventEmitterContext";import{IndicatorColor}from"../core/IndicatorColor";export{IndicatorColor};export class IndicatorRect extends Component{constructor(t){super(t),Object.defineProperty(this,"handleTopicUpdate",{enumerable:!0,configurable:!0,writable:!0,value:t=>{this.setState({currentValue:t})}}),this.state={currentValue:void 0}}componentDidMount(){this.setupSubscriptions()}componentWillUnmount(){}setupSubscriptions(){const{topic:t}=this.props,{subscribe:e}=this.context;t&&e(t,this.handleTopicUpdate)}render(){const{currentValue:t}=this.state,{className:e,style:o,value:r,onColor:n,offColor:i,options:c}=this.props;let a,l=t;void 0!==r&&(l=r),void 0!==c&&c.length>0&&(a=l?c[1]:c[0]);let s=l?n:i;return void 0===l&&(s=IndicatorColor.IndicatorInvalid),_jsx("div",{className:`indicator-rect ${e||""}`,style:{backgroundColor:s,color:"white",width:"100px",height:"100px",display:"flex",alignItems:"center",justifyContent:"center",...o},children:a})}}Object.defineProperty(IndicatorRect,"contextType",{enumerable:!0,configurable:!0,writable:!0,value:EventEmitterContext}),Object.defineProperty(IndicatorRect,"defaultProps",{enumerable:!0,configurable:!0,writable:!0,value:{onColor:IndicatorColor.IndicatorGreen,offColor:"gray"}});export default IndicatorRect;
@@ -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.29",
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",
@@ -2,7 +2,7 @@
2
2
  * Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
3
3
  * Created Date: 2024-04-24 16:01:53
4
4
  * -----
5
- * Last Modified: 2024-05-21 13:38:23
5
+ * Last Modified: 2025-01-20 19:15:50
6
6
  * -----
7
7
  *
8
8
  */
@@ -20,7 +20,7 @@ import { DataTable } from 'primereact/datatable';
20
20
  import { Column } from 'primereact/column';
21
21
  import { Toolbar } from 'primereact/toolbar';
22
22
  import { Button } from 'primereact/button';
23
- import { ConfirmPopup, confirmPopup } from 'primereact/confirmpopup';
23
+ import { confirmPopup } from 'primereact/confirmpopup';
24
24
  import { FileUpload, FileUploadHandlerEvent} from 'primereact/fileupload';
25
25
 
26
26
  import { EventEmitterContext } from '../core/EventEmitterContext';
@@ -95,6 +95,12 @@ type FileItem = {
95
95
  * The component uses the `EventEmitterContext` to make API calls to a backend to list, download, and delete files.
96
96
  * It dynamically handles file operations based on the `domain` prop which determines the API endpoints for these actions.
97
97
  *
98
+ * Requires
99
+ * ```tsx
100
+ * <ConfirmPopup />
101
+ * ```
102
+ * somewhere in a top-level page.
103
+ *
98
104
  * Props:
99
105
  * - `domain` (string): The domain name assigned to the DATASTORE servelet containing the data.
100
106
  * Default: "DATASTORE"
@@ -354,8 +360,7 @@ export const FileList: React.FC<FileListProps> = ({
354
360
  return (
355
361
 
356
362
  <div>
357
- <Toolbar start={toolbarStartContents} end={toolbarEndContents} style={{ padding: "1mm" }} />
358
- <ConfirmPopup />
363
+ <Toolbar start={toolbarStartContents} end={toolbarEndContents} style={{ padding: "1mm" }} />
359
364
  <DataTable value={files}>
360
365
  <Column field="name" header="Name"></Column>
361
366
 
@@ -0,0 +1,172 @@
1
+ /*
2
+ * Copyright (C) 2025 Automated Design Corp.. All Rights Reserved.
3
+ * Created Date: 2025-01-20 15:09:55
4
+ * -----
5
+ * Last Modified: 2025-01-20 15:10:06
6
+ * -----
7
+ *
8
+ */
9
+
10
+ import { Component } from 'react';
11
+ import { EventEmitterContext, EventEmitterContextType } from '../core/EventEmitterContext';
12
+ import { IndicatorColor } from "../core/IndicatorColor";
13
+ export { IndicatorColor };
14
+
15
+ /**
16
+ * Common properties for an indicator rectangle component.
17
+ * This component is used for displaying states and is not interactive.
18
+ * It is commonly used in industrial HMIs for visual indication purposes.
19
+ *
20
+ * These properties support displaying values of boolean, number, and string states.
21
+ *
22
+ * Available boolean states: **on**, **off**, and **not available**:
23
+ *
24
+ * * `true` is treated as **on**
25
+ * * `false` is treated as **off**
26
+ * * `undefined` is treated as **not available**
27
+ *
28
+ * Numeric values can be used. When there are 2 or fewer possible states,
29
+ * 0 will be considered false (OFF), anything else will be considered true (ON).
30
+ * Undefined will be treated as "not available."
31
+ *
32
+ * When the indicator contains more than 2 states, the number will be matched
33
+ * to the available state, in order. More than two states requires usage of the
34
+ * `options` field and declaring more than two states there.
35
+ *
36
+ * If a string state is used, it will be matched exactly to the corresponding
37
+ * label in the `options` field.
38
+ */
39
+ export interface IndicatorRectProps {
40
+
41
+ /**
42
+ * Topic name to monitor for state indication.
43
+ */
44
+ topic?: string;
45
+
46
+ /**
47
+ * State to be displayed.
48
+ */
49
+ value?: boolean | number | string;
50
+
51
+ /**
52
+ * Color for the rectangle when the state is TRUE.
53
+ */
54
+ onColor?: IndicatorColor;
55
+
56
+ /**
57
+ * Color for the rectangle when the state is FALSE.
58
+ */
59
+ offColor?: IndicatorColor;
60
+
61
+ /**
62
+ * An array of string labels to display as the available options.
63
+ *
64
+ * For items with 2 states or less:
65
+ * Index 0 is the label when value is OFF.
66
+ * Index 1 is the label when value is ON.
67
+ *
68
+ * If only one value is given (Index 0), then that value is used for all states.
69
+ */
70
+ options?: string[];
71
+
72
+ /**
73
+ * Additional CSS class name to apply to the rectangle.
74
+ */
75
+ className?: string;
76
+
77
+ /**
78
+ * Additional inline styles to apply to the rectangle.
79
+ */
80
+ style?: React.CSSProperties;
81
+
82
+ }
83
+
84
+ interface IndicatorRectState {
85
+ currentValue?: boolean | number | string;
86
+ }
87
+
88
+ export class IndicatorRect extends Component<IndicatorRectProps, IndicatorRectState> {
89
+ static contextType = EventEmitterContext;
90
+
91
+ // Define default props
92
+ static defaultProps = {
93
+ onColor: IndicatorColor.IndicatorGreen,
94
+ offColor: "gray", // Default offColor
95
+ };
96
+
97
+ constructor(props: IndicatorRectProps) {
98
+ super(props);
99
+ this.state = {
100
+ currentValue: undefined,
101
+ };
102
+ }
103
+
104
+ componentDidMount() {
105
+ this.setupSubscriptions();
106
+ }
107
+
108
+ componentWillUnmount() {
109
+ // Unsubscribe logic if needed
110
+ }
111
+
112
+ /**
113
+ * Sets up subscriptions based on the provided topic.
114
+ */
115
+ private setupSubscriptions() {
116
+ const { topic } = this.props;
117
+ const { subscribe } = this.context as EventEmitterContextType;
118
+
119
+ if (topic) {
120
+ subscribe(topic, this.handleTopicUpdate);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Handles updates for the main topic.
126
+ */
127
+ private handleTopicUpdate = (value: boolean | number | string) => {
128
+ this.setState({ currentValue: value });
129
+ };
130
+
131
+ render() {
132
+ const { currentValue } = this.state;
133
+ const { className, style, value, onColor, offColor, options } = this.props;
134
+
135
+ // Load the value from the proper source
136
+ let displayValue = currentValue;
137
+ if (value !== undefined) {
138
+ displayValue = value;
139
+ }
140
+
141
+ // Determine the label and color based on the current state
142
+ let rectLabel = undefined;
143
+ if (options !== undefined && options.length > 0) {
144
+ rectLabel = displayValue ? options[1] : options[0];
145
+ }
146
+
147
+ let color = displayValue ? onColor : offColor;
148
+ if (displayValue === undefined) {
149
+ color = IndicatorColor.IndicatorInvalid;
150
+ }
151
+
152
+ return (
153
+ <div
154
+ className={`indicator-rect ${className || ""}`}
155
+ style={{
156
+ backgroundColor: color,
157
+ color: "white",
158
+ width: "100px",
159
+ height: "100px",
160
+ display: "flex",
161
+ alignItems: "center",
162
+ justifyContent: "center",
163
+ ...style,
164
+ }}
165
+ >
166
+ {rectLabel}
167
+ </div>
168
+ );
169
+ }
170
+ }
171
+
172
+ export default IndicatorRect;
@@ -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 => {