useSendCommand.ts 1.93 KB
import { ref } from 'vue';
import { DataSource } from '../../palette/types';
import { sendCommandOneway, sendCommandTwoway } from '/@/api/dataBoard';
import { useMessage } from '/@/hooks/web/useMessage';
import { TransportTypeEnum } from '/@/views/device/profiles/components/TransportDescript/const';
import { ServiceCallTypeEnum } from '/@/enums/toolEnum';

const { createMessage } = useMessage();
export function useSendCommand() {
  const loading = ref(false);

  const error = () => {
    // createMessage.error('下发指令失败');
    return false;
  };

  const sendCommand = async (record: DataSource, value: any, isModbusCommand = false) => {
    if (!record) return false;
    const { customCommand, attribute } = record || {};
    const { deviceId } = record;
    if (!deviceId) return false;

    try {
      loading.value = true;
      let params: string | Recordable = {
        [attribute!]: Number(value),
      };
      if (isModbusCommand) {
        params = value;
      }

      let sendCommandFn = sendCommandOneway;
      // 如果是TCP设备从物模型中获取下发命令(TCP网关子设备无物模型服务与事件)
      if (customCommand?.transportType === TransportTypeEnum.TCP && !isModbusCommand) {
        params = customCommand.command!;
        if (customCommand.callType === ServiceCallTypeEnum.SYNC) {
          sendCommandFn = sendCommandTwoway;
        }
      }
      // 控制按钮下发命令为0 或 1
      await sendCommandFn({
        deviceId,
        value: {
          params: params || null,
          persistent: true,
          additionalInfo: {
            cmdType: customCommand.commandType || 'API',
          },
          method: 'methodThingskit',
        },
      });
      createMessage.success('命令下发成功');
      return true;
    } catch (msg) {
      console.error(msg);
      return error();
    } finally {
      loading.value = false;
    }
  };
  return {
    loading,
    sendCommand,
  };
}