/* * Copyright (c) 2021, J2 Innovations. All Rights Reserved */ import { HDict, HGrid, HNum, HRef, HVal } from 'haystack-core' import { useEffect, useState } from 'react' import { useClient } from './client' import { GridRefreshWatchResult, useWatch } from './watch' /** * A Haystack point record with a specific curVal type */ export interface Point extends HDict { /** * Point record id */ id?: HRef /** * Current value of the readTag */ curVal?: Value } /** * A hook that allows using a point from an haystack server as react state. * * Important: This hooks requires a ClientContext to work. @see https://github.com/j2inn/haystack-nclient * * @example Example of usage with a numeric point. * * const point= useReadByFilter('point and temp and zone and sp').grid[0] // One-shot reading the first point that matches the filter * const [pointValue, setPointValue, updatedPoint] = useHaystackPoint(point) // Using the point state * * @param originaryPoint point dict used to retrieve its id and initial value. * @param pollRate poll rate for the value subscription. Expressed in seconds. * @param writeOptions default options for the write callback. * @returns Returns the point value, a function to update it and the point dict. */ export function useHaystackPoint( originaryPoint: Optional>, pollRate = 5, writeOptions?: HaystackPointWriteOptions ): [ Optional, PointWriteFunc | undefined, Optional> ] { const [currentValue, setCurrentValue] = useState>() const [readValue, point] = useReadHaystackPoint( originaryPoint, pollRate ) const write = useWriteHaystackPoint(originaryPoint?.id, writeOptions) const writeFunc: PointWriteFunc | undefined = write ? async (val, options) => { const result = await write?.(val, options) setCurrentValue(val) return result } : undefined useEffect(() => { setCurrentValue(readValue) }, [readValue]) return [currentValue, writeFunc, point] } type PointGridResult = { grid: HGrid> } & GridRefreshWatchResult type Optional = Value | undefined | null function useReadHaystackPoint( originalPoint: Optional>, pollRate = 5 ): [Optional, Optional>] { const { grid: [point], isLoading, } = useWatch({ ids: originalPoint?.id, pollRate: pollRate, }) as PointGridResult return isLoading ? [originalPoint?.curVal, originalPoint] : [point?.curVal, point] } export type PointWriteFunc = ( val: Value, options?: HaystackPointWriteOptions ) => Promise> /** * Options for a PointWrite operation, * See https://project-haystack.org/doc/docHaystack/Ops#pointWrite */ export interface HaystackPointWriteOptions { level?: number who?: string duration?: number | HNum } function useWriteHaystackPoint( id?: string | HRef, generalOptions?: HaystackPointWriteOptions ): PointWriteFunc | undefined { const client = useClient() return id ? (val, options) => client.ops.pointWrite({ id: id, level: generalOptions?.level ?? 17, who: generalOptions?.who, duration: generalOptions?.duration, ...options, val: val, }) : undefined }