useControlCommand.ts 2.81 KB
import { ref } from 'vue';
import { useDeviceProfileQueryContext } from '../../palette/hooks/useDeviceProfileQueryContext';
import {
  CommandDeliveryWayEnum,
  CommandTypeEnum,
  ServiceCallTypeEnum,
  TransportTypeEnum,
} from '/@/enums/deviceEnum';
import { useMessage } from '/@/hooks/web/useMessage';

import { useCommandDelivery } from '/@/hooks/business/useCommandDelivery';
import { useI18n } from '/@/hooks/web/useI18n';

export interface DoCommandDeliverDataSourceType {
  deviceId: string;
  deviceProfileId: string;
  attribute: string;
  commandType?: CommandTypeEnum;
  openCommand?: string;
  closeCommand?: string;
  openService?: string;
  closeService?: string;
}

export function useControlComand() {
  const { t } = useI18n();
  const loading = ref(false);

  const { createMessage } = useMessage();

  const { getDeviceProfileTslByIdWithIdentifier } = useDeviceProfileQueryContext();

  const doControlSendCommand = async (
    dataSource: DoCommandDeliverDataSourceType,
    value: any
  ): Promise<boolean> => {
    try {
      const { deviceId, deviceProfileId, attribute, commandType } = dataSource;

      loading.value = true;
      const tsl = getDeviceProfileTslByIdWithIdentifier?.(deviceProfileId, attribute);

      const { doCommandDelivery } = useCommandDelivery();

      await doCommandDelivery({
        deviceId,
        identifier: attribute,
        objectModel: tsl,
        value,
        cmdType: commandType,
        beforeFetch: (rpcCommand, { transportType, isTCPModbus }) => {
          let way = CommandDeliveryWayEnum.ONE_WAY;
          if (transportType === TransportTypeEnum.TCP && !isTCPModbus) {
            rpcCommand.params = value;

            if (commandType === CommandTypeEnum.CUSTOM) {
              const { openCommand, closeCommand } = dataSource;
              rpcCommand.params = !!Number(value) ? openCommand! : closeCommand!;
            } else if (commandType === CommandTypeEnum.SERVICE) {
              const { openService, closeService } = dataSource;
              const serviceIdentifier = !!Number(value) ? openService : closeService;
              const serviceTsl = getDeviceProfileTslByIdWithIdentifier?.(
                deviceProfileId,
                serviceIdentifier!
              );
              rpcCommand.params = serviceTsl?.inputData?.[0].serviceCommand as unknown as string;
              way =
                serviceTsl?.callType === ServiceCallTypeEnum.SYNC
                  ? CommandDeliveryWayEnum.TWO_WAY
                  : CommandDeliveryWayEnum.ONE_WAY;
            }
          }

          return { rpcCommand, way };
        },
      });

      createMessage.success(t('visual.board.commandOkText'));

      return true;
    } catch (e) {
      return false;
    } finally {
      loading.value = false;
    }
  };

  return {
    loading,
    doControlSendCommand,
  };
}