package com.iflytop.gd.hardware.command; import cn.hutool.core.util.StrUtil; import com.iflytop.gd.common.cmd.DeviceCommand; import com.iflytop.gd.common.enums.cmd.CmdAction; import com.iflytop.gd.common.enums.cmd.CmdDevice; import com.iflytop.gd.hardware.type.MId; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * 命令处理器 * H - 硬件 C - 命令 */ public abstract class CommandHandler { abstract protected Map getSupportCmdDeviceMIdMap(); abstract protected Set getSupportActions(); /** * 发送指令 */ public void sendCommand(DeviceCommand command) throws Exception { // 校验动作是否合法 checkAction(command.getAction()); // 校验参数是否合法 checkParams(command); // 处理指令 handleCommand(command); } abstract protected void handleCommand(DeviceCommand command) throws Exception; /** * 获取支持的设备 */ protected Set getSupportedDevices() { Map cmdDeviceMIdMap = getSupportCmdDeviceMIdMap(); return cmdDeviceMIdMap.keySet(); } /** * 检查Action 是否合法 * @param action */ protected void checkAction(CmdAction action) throws Exception { Set supportedActions = getSupportActions(); if (!supportedActions.contains(action)) { // 生成支持的动作列表字符串 String supported = supportedActions.stream() .map(Enum::name) .collect(Collectors.joining(", ")); throw new IllegalArgumentException( StrUtil.format("action [{}] not supported! Supported actions: {}", action.name(), supported)); } } /** * 检查参数是否合法 */ protected void checkParams(DeviceCommand command) throws Exception {} }