package com.mes.interaction; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.mes.device.entity.DeviceConfig; import com.mes.device.service.DevicePlcOperationService; import com.mes.device.vo.DevicePlcVO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; /** * 设备逻辑处理器基类 * 提供通用的功能实现 * * @author mes * @since 2025-01-XX */ @Slf4j @RequiredArgsConstructor public abstract class BaseDeviceLogicHandler implements DeviceLogicHandler { protected final DevicePlcOperationService devicePlcOperationService; protected final ObjectMapper objectMapper = new ObjectMapper(); @Override public DevicePlcVO.OperationResult execute(DeviceConfig deviceConfig, String operation, Map params) { try { // 验证设备配置 String validationError = validateLogicParams(deviceConfig); if (validationError != null) { return DevicePlcVO.OperationResult.builder() .success(false) .message("设备逻辑参数验证失败: " + validationError) .build(); } // 解析设备逻辑参数(从 extraParams.deviceLogic 中读取) Map logicParams = parseLogicParams(deviceConfig); // 执行具体操作(由子类实现) return doExecute(deviceConfig, operation, params, logicParams); } catch (Exception e) { log.error("执行设备逻辑操作失败, deviceId={}, operation={}", deviceConfig.getId(), operation, e); return DevicePlcVO.OperationResult.builder() .success(false) .message("执行失败: " + e.getMessage()) .build(); } } /** * 子类实现具体的操作逻辑 * * @param deviceConfig 设备配置 * @param operation 操作类型 * @param params 运行时参数(动态传入) * @param logicParams 逻辑配置参数(从 extraParams.deviceLogic 解析) * @return 操作结果 */ protected abstract DevicePlcVO.OperationResult doExecute( DeviceConfig deviceConfig, String operation, Map params, Map logicParams ); /** * 解析设备逻辑参数(从 extraParams 中提取 deviceLogic) */ protected Map parseLogicParams(DeviceConfig deviceConfig) { String extraParams = deviceConfig.getExtraParams(); if (extraParams == null || extraParams.trim().isEmpty()) { return new HashMap<>(); } try { Map extra = objectMapper.readValue(extraParams, new TypeReference>() {}); @SuppressWarnings("unchecked") Map deviceLogic = (Map) extra.get("deviceLogic"); return deviceLogic != null ? deviceLogic : new HashMap<>(); } catch (Exception e) { log.warn("解析设备逻辑参数失败, deviceId={}", deviceConfig.getId(), e); return new HashMap<>(); } } /** * 获取逻辑参数中的值(带默认值) */ @SuppressWarnings("unchecked") protected T getLogicParam(Map logicParams, String key, T defaultValue) { Object value = logicParams.get(key); if (value == null) { return defaultValue; } try { return (T) value; } catch (ClassCastException e) { log.warn("逻辑参数类型转换失败, key={}, value={}", key, value, e); return defaultValue; } } /** * 获取逻辑参数中的值(不带默认值) */ @SuppressWarnings("unchecked") protected T getLogicParam(Map logicParams, String key) { Object value = logicParams.get(key); if (value == null) { return null; } try { return (T) value; } catch (ClassCastException e) { log.warn("逻辑参数类型转换失败, key={}, value={}", key, value, e); return null; } } }