useObjectModelValue.ts 2.31 KB
import type { DataType, Specs, StructJSON } from '@/api/device/model'
import { TransportTypeEnum } from '@/enums/deviceEnum'
import { DataTypeEnum } from '@/enums/objectModelEnum'
import { useJsonParse } from '@/hooks/business/useJSONParse'
import { useProductsStoreWithOut } from '@/store/modules/products'

function getBoolTypeValue(value: number, Specs: Specs) {
  const { boolOpen, boolClose } = Specs

  return Number(value) ? boolOpen : boolClose
}

function getEnumTypeValue(value: number, specsList: Specs[]) {
  const res = specsList.find(item => item.value === Number(value))

  return res?.name
}

function getStructTypeValue(value: string, specs: StructJSON[]): string {
  const res = useJsonParse(value).value

  function generateStruct(specs: StructJSON[], value: Recordable) {
    if (!value) return {}

    return specs.reduce((prev, next) => {
      return {
        ...prev,
        [next.functionName]: getValueByType(next.dataType!.type, value[next.identifier], next.dataType!),
      }
    }, {})
  }

  return JSON.stringify(generateStruct(specs, res))
}

function getValueByType(type: string, value: any, dataType: DataType) {
  switch (type) {
    case DataTypeEnum.BOOL:
      return getBoolTypeValue(value, dataType.specs as Specs)
    case DataTypeEnum.STRUCT:
      return getStructTypeValue(value, dataType.specs as StructJSON[])
    case DataTypeEnum.ENUM:
      return getEnumTypeValue(value, dataType.specsList as Specs[])
    default:
      return value
  }
}

function getModbusDeviceValueByType(value: any, dataType: DataType) {
  if (dataType.type === DataTypeEnum.BOOL && dataType.specsList && dataType.specsList.length)
    return getEnumTypeValue(value, dataType.specsList as Specs[])

  return value
}

export function useObjectModelValue(deviceProfileId: string, attr: string, value: any) {
  const productsStore = useProductsStoreWithOut()

  const result = productsStore.getObjectModelByIdWithIdentifier(deviceProfileId, attr)
  if (!result)
    return value

  const products = productsStore.getProductDetailById(deviceProfileId)
  const isTCPModbus = products.transportType === TransportTypeEnum.TCP && result.extensionDesc?.originalDataType

  return isTCPModbus ? getModbusDeviceValueByType(value, result.specs.dataType) : getValueByType(result.specs.dataType.type as DataTypeEnum, value, result.specs.dataType)
}