package com.mes.device.service.impl; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.mes.device.entity.DeviceConfig; import com.mes.device.service.DeviceConfigService; import com.mes.device.service.DeviceControlProfileService; import com.mes.device.vo.DeviceControlProfile; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.HashMap; import java.util.Map; /** * 设备控制参数服务实现 */ @Slf4j @Service @RequiredArgsConstructor public class DeviceControlProfileServiceImpl implements DeviceControlProfileService { private static final String CONTROL_PROFILE_KEY = "controlProfile"; private final DeviceConfigService deviceConfigService; private final ObjectMapper objectMapper; @Override public DeviceControlProfile getProfile(Long deviceId) { DeviceConfig device = deviceConfigService.getDeviceById(deviceId); if (device == null) { throw new IllegalArgumentException("设备不存在: " + deviceId); } Map extraMap = readExtraMap(device); Object profileNode = extraMap.get(CONTROL_PROFILE_KEY); if (profileNode == null) { return DeviceControlProfile.builder().autoRequest(true).build(); } return objectMapper.convertValue(profileNode, DeviceControlProfile.class); } @Override public void updateProfile(Long deviceId, DeviceControlProfile profile) { DeviceConfig device = deviceConfigService.getDeviceById(deviceId); if (device == null) { throw new IllegalArgumentException("设备不存在: " + deviceId); } Map extraMap = readExtraMap(device); extraMap.put(CONTROL_PROFILE_KEY, profile); try { String json = objectMapper.writeValueAsString(extraMap); device.setExtraParams(json); deviceConfigService.updateById(device); } catch (Exception e) { log.error("保存控制参数失败 deviceId={}", deviceId, e); throw new RuntimeException("保存控制参数失败: " + e.getMessage(), e); } } @SuppressWarnings("unchecked") private Map readExtraMap(DeviceConfig device) { try { if (device.getExtraParams() == null || device.getExtraParams().trim().isEmpty()) { return new HashMap<>(); } return objectMapper.readValue(device.getExtraParams(), new TypeReference>() {}); } catch (Exception e) { log.warn("解析设备扩展参数失败 deviceId={}", device.getId(), e); return new HashMap<>(); } } }