fix:修改大屏设备点位数据接口

plp
86158 1 month ago
parent dae064a912
commit 3a65a27e17

@ -318,10 +318,10 @@ public class DeviceController {
@GetMapping("/device-attribute/batchList") @GetMapping("/device-attribute/batchList")
@Operation(summary = "获得多个设备的属性数据") @Operation(summary = "获得多个设备的属性数据")
@Parameter(name = "deviceIds", description = "设备ID列表用逗号分隔", required = true) @Parameter(name = "goviewId", description = "大屏ID", required = true)
@PreAuthorize("@ss.hasPermission('iot:device:query')") @PreAuthorize("@ss.hasPermission('iot:device:query')")
public CommonResult<List<Map<String, Object>>> getMultiDeviceAttributes(@RequestParam("deviceIds") String deviceIds) { public CommonResult<List<Map<String, Object>>> getMultiDeviceAttributes(@RequestParam("goviewId") Long goviewId) {
return success(deviceService.getMultiDeviceAttributes(deviceIds)); return success(deviceService.getMultiDeviceAttributes(goviewId));
} }

@ -14,6 +14,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -109,4 +110,12 @@ public interface DeviceMapper extends BaseMapperX<DeviceDO> {
int selectIsReference(@Param("deviceId") Long deviceId); int selectIsReference(@Param("deviceId") Long deviceId);
/**
* goviewIddeviceIds
*
* @param goviewId ID
* @return deviceIds
*/
@Select("SELECT device_ids FROM mes_goview WHERE id = #{goviewId}")
String selectDeviceIdsByGoviewId(@Param("goviewId") Long goviewId);
} }

@ -136,7 +136,7 @@ public interface DeviceService {
DeviceOperationStatusRespVO getDeviceOperationalStatus(); DeviceOperationStatusRespVO getDeviceOperationalStatus();
List<Map<String, Object>> getMultiDeviceAttributes(String deviceIds); List<Map<String, Object>> getMultiDeviceAttributes(Long goviewId);
List<DeviceContactModelDO> getDeviceAttributeList(Long deviceId); List<DeviceContactModelDO> getDeviceAttributeList(Long deviceId);

@ -986,68 +986,218 @@ public class DeviceServiceImpl implements DeviceService {
} }
@Override @Override
public List<Map<String, Object>> getMultiDeviceAttributes(String deviceIds) { public List<Map<String, Object>> getMultiDeviceAttributes(Long goviewId) {
List<Map<String, Object>> result = new ArrayList<>(); List<Map<String, Object>> result = new ArrayList<>();
// 解析设备ID列表 try {
if (StringUtils.isBlank(deviceIds)) { // 直接从数据库查询deviceIds JSON字符串
return result; String deviceIdsJson = deviceMapper.selectDeviceIdsByGoviewId(goviewId);
} if (StringUtils.isBlank(deviceIdsJson)) {
log.info("No deviceIds found for goviewId: {}", goviewId);
List<Long> idList = Arrays.stream(deviceIds.split(",")) return result;
.map(String::trim) }
.map(Long::valueOf)
.collect(Collectors.toList());
// 遍历每个设备ID获取设备属性数据 // 解析JSON格式的deviceIds
for (Long deviceId : idList) { Map<Long, Set<Long>> deviceAttributeMap = parseDeviceIdsJson(deviceIdsJson);
// 获取设备信息 if (deviceAttributeMap.isEmpty()) {
DeviceDO device = deviceMapper.selectById(deviceId); log.warn("No valid device-attribute mapping found for goviewId: {}", goviewId);
if (device == null) { return result;
continue;
} }
// 创建设备层级的Map // 批量获取所有设备的最新运行记录,减少数据库查询次数
Map<String, Object> deviceMap = new HashMap<>(); Map<Long, DeviceOperationRecordDO> latestRecordMap = getLatestDeviceOperationRecords(deviceAttributeMap.keySet());
deviceMap.put("deviceId", deviceId);
deviceMap.put("deviceName", device.getDeviceName());
// 获取设备属性列表 log.info("Found {} devices with attribute mappings for goviewId {}: {}",
List<DeviceContactModelDO> attributes = deviceContactModelMapper.selectList( deviceAttributeMap.size(), goviewId, deviceAttributeMap);
Wrappers.<DeviceContactModelDO>lambdaQuery()
.eq(DeviceContactModelDO::getDeviceId, deviceId)); // 遍历每个设备ID获取设备属性数据
for (Map.Entry<Long, Set<Long>> entry : deviceAttributeMap.entrySet()) {
// 获取设备最新数据 Long deviceId = entry.getKey();
Map<Long, Map<String, Object>> deviceDataMap = createDeviceDataMap(deviceId); Set<Long> attributeIds = entry.getValue();
// 创建点位集合 try {
List<Map<String, Object>> attributeList = new ArrayList<>(); // 获取设备信息
for (DeviceContactModelDO attribute : attributes) { DeviceDO device = deviceMapper.selectById(deviceId);
Map<String, Object> attributeData = new HashMap<>(); if (device == null) {
attributeData.put("attributeId", attribute.getId()); log.warn("Device not found for ID: {}", deviceId);
attributeData.put("attributeName", attribute.getAttributeName()); continue;
attributeData.put("attributeCode", attribute.getAttributeCode()); }
attributeData.put("dataType", attribute.getDataType());
attributeData.put("dataUnit", attribute.getDataUnit()); // 创建设备层级的Map
Map<String, Object> deviceMap = new HashMap<>();
// 获取最新数据 deviceMap.put("deviceId", deviceId);
Map<String, Object> latestData = deviceDataMap.get(attribute.getId()); deviceMap.put("deviceName", device.getDeviceName());
if (latestData != null) { deviceMap.put("deviceCode", device.getDeviceCode());
attributeData.put("addressValue", adjustByRatio(latestData.get("addressValue"), attribute.getRatio()));
attributeData.put("latestCollectionTime", latestData.get("timestamp")); // 添加设备运行状态
String operatingStatus = getDeviceOperatingStatus(deviceId, latestRecordMap);
deviceMap.put("operatingStatus", operatingStatus);
// 获取设备属性列表只查询指定的属性ID
List<DeviceContactModelDO> attributes = deviceContactModelMapper.selectList(
Wrappers.<DeviceContactModelDO>lambdaQuery()
.eq(DeviceContactModelDO::getDeviceId, deviceId)
.in(DeviceContactModelDO::getId, attributeIds));
// 获取设备最新数据
Map<Long, Map<String, Object>> deviceDataMap = createDeviceDataMap(deviceId);
// 创建属性集合
List<Map<String, Object>> attributeList = new ArrayList<>();
for (DeviceContactModelDO attribute : attributes) {
Map<String, Object> attributeData = new HashMap<>();
attributeData.put("attributeId", attribute.getId());
attributeData.put("attributeName", attribute.getAttributeName());
attributeData.put("attributeCode", attribute.getAttributeCode());
attributeData.put("dataType", attribute.getDataType());
attributeData.put("dataUnit", attribute.getDataUnit());
// 获取最新数据
Map<String, Object> latestData = deviceDataMap.get(attribute.getId());
if (latestData != null) {
attributeData.put("addressValue", adjustByRatio(latestData.get("addressValue"), attribute.getRatio()));
attributeData.put("latestCollectionTime", latestData.get("timestamp"));
}
attributeList.add(attributeData);
}
// 将属性集合添加到设备层级
deviceMap.put("attributes", attributeList);
// 添加到结果列表
result.add(deviceMap);
} catch (Exception e) {
log.error("Error processing device ID: {} with attributes: {}", deviceId, attributeIds, e);
// 继续处理其他设备,不中断整体流程
} }
}
} catch (Exception e) {
log.error("Failed to get multi-device attributes by goviewId: {}", goviewId, e);
}
return result;
}
/**
*
* @param deviceId ID
* @param latestRecordMap ID
* @return
*/
private String getDeviceOperatingStatus(Long deviceId, Map<Long, DeviceOperationRecordDO> latestRecordMap) {
DeviceOperationRecordDO record = latestRecordMap.get(deviceId);
if (record != null) {
// 根据运行记录的rule字段获取设备状态
DeviceStatusEnum statusEnum = DeviceStatusEnum.getByCode(record.getRule());
return statusEnum != null ? statusEnum.getName() : DeviceStatusEnum.OFFLINE.getName();
} else {
// 如果没有运行记录,默认为离线状态
return DeviceStatusEnum.OFFLINE.getName();
}
}
/**
*
* @param deviceIds ID
* @return ID
*/
private Map<Long, DeviceOperationRecordDO> getLatestDeviceOperationRecords(Set<Long> deviceIds) {
if (deviceIds.isEmpty()) {
return Collections.emptyMap();
}
attributeList.add(attributeData); // 查询所有设备的最新运行记录
List<DeviceOperationRecordDO> records = deviceOperationRecordMapper.selectList(
Wrappers.<DeviceOperationRecordDO>lambdaQuery()
.in(DeviceOperationRecordDO::getDeviceId, deviceIds)
.orderByDesc(DeviceOperationRecordDO::getCreateTime));
// 构建设备ID到最新记录的映射
Map<Long, DeviceOperationRecordDO> latestRecordMap = new HashMap<>();
for (DeviceOperationRecordDO record : records) {
// 只保留每个设备的第一条记录(因为已经按创建时间倒序排序)
if (!latestRecordMap.containsKey(record.getDeviceId())) {
latestRecordMap.put(record.getDeviceId(), record);
} }
}
// 将点位集合添加到设备层级 return latestRecordMap;
deviceMap.put("attributes", attributeList); }
/**
* JSONdeviceIds
* @param deviceIdsJson JSON
* @return IDID
*/
private Map<Long, Set<Long>> parseDeviceIdsJson(String deviceIdsJson) {
Map<Long, Set<Long>> deviceAttributeMap = new HashMap<>();
// 添加到结果列表 if (StringUtils.isBlank(deviceIdsJson)) {
result.add(deviceMap); return deviceAttributeMap;
} }
return result; try {
// 使用Jackson解析JSON字符串
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String, Object>> deviceAttributeList = objectMapper.readValue(
deviceIdsJson, new TypeReference<List<Map<String, Object>>>() {});
// 遍历解析结果,构建设备-属性映射并去重
for (Map<String, Object> item : deviceAttributeList) {
try {
// 提取设备ID
Object deviceIdObj = item.get("deviceId");
if (deviceIdObj == null) {
log.warn("Device ID is null in item: {}", item);
continue;
}
Long deviceId = null;
if (deviceIdObj instanceof Number) {
deviceId = ((Number) deviceIdObj).longValue();
} else {
deviceId = Long.parseLong(deviceIdObj.toString());
}
// 提取属性ID数组
List<Long> attributeIds = new ArrayList<>();
Object attributesIdsObj = item.get("attributesIds");
if (attributesIdsObj instanceof List) {
List<?> attributesList = (List<?>) attributesIdsObj;
for (Object attrIdObj : attributesList) {
if (attrIdObj instanceof Number) {
attributeIds.add(((Number) attrIdObj).longValue());
} else if (attrIdObj != null) {
try {
attributeIds.add(Long.parseLong(attrIdObj.toString()));
} catch (NumberFormatException e) {
log.warn("Invalid attribute ID: {}", attrIdObj);
}
}
}
}
// 合并属性ID到现有设备映射中避免Lambda变量捕获问题
Set<Long> existingAttributes = deviceAttributeMap.get(deviceId);
if (existingAttributes == null) {
// 如果设备不存在,创建新的属性集合
Set<Long> newAttributesSet = new HashSet<>(attributeIds);
deviceAttributeMap.put(deviceId, newAttributesSet);
} else {
// 如果设备已存在将新的属性ID添加到现有集合中
for (Long attrId : attributeIds) {
existingAttributes.add(attrId);
}
}
} catch (Exception e) {
log.warn("Error parsing device-attribute item: {}", item, e);
}
}
} catch (Exception e) {
log.error("Error parsing deviceIds JSON: {}", deviceIdsJson, e);
}
return deviceAttributeMap;
} }
@Override @Override

@ -49,7 +49,7 @@ public class GoviewPageReqVO extends PageParam {
@Schema(description = "大屏类型") @Schema(description = "大屏类型")
private String type; private String type;
@Schema(description = "设备ids") @Schema(description = "设备ids与点位ids")
private String deviceIds; private String deviceIds;
} }

@ -63,4 +63,15 @@ public class GoviewRespVO {
@ExcelProperty("设备ids") @ExcelProperty("设备ids")
private String deviceIds; private String deviceIds;
@Schema(description = "设备ids与点位ids列表")
private List<GoviewSaveReqVO.DevicePointVO> deviceIdsList;
@Data
public static class DevicePointVO {
@Schema(description = "设备ID", example = "12")
private Long deviceId;
@Schema(description = "点位ID列表", example = "[1,5,9]")
private List<Long> attributesIds;
}
} }

@ -39,7 +39,18 @@ public class GoviewSaveReqVO {
@Schema(description = "大屏类型") @Schema(description = "大屏类型")
private String type; private String type;
@Schema(description = "设备ids") @Schema(description = "设备ids与点位ids")
private String deviceIds; private String deviceIds;
@Schema(description = "设备ids与点位ids列表")
private List<DevicePointVO> deviceIdsList;
@Data
public static class DevicePointVO {
@Schema(description = "设备ID", example = "12")
private Long deviceId;
@Schema(description = "点位ID列表", example = "[1,5,9]")
private List<Long> attributesIds;
}
} }

@ -1,5 +1,6 @@
package cn.iocoder.yudao.module.mes.service.goview; package cn.iocoder.yudao.module.mes.service.goview;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
@ -33,6 +34,11 @@ public class GoviewServiceImpl implements GoviewService {
public Long createGoview(GoviewSaveReqVO createReqVO) { public Long createGoview(GoviewSaveReqVO createReqVO) {
// 插入 // 插入
GoviewDO goview = BeanUtils.toBean(createReqVO, GoviewDO.class); GoviewDO goview = BeanUtils.toBean(createReqVO, GoviewDO.class);
if (!createReqVO.getDeviceIdsList().isEmpty()){
String jsonString = JSON.toJSONString(createReqVO.getDeviceIdsList());
goview.setDeviceIds(jsonString);
}
goviewMapper.insert(goview); goviewMapper.insert(goview);
// 返回 // 返回
return goview.getId(); return goview.getId();
@ -44,6 +50,12 @@ public class GoviewServiceImpl implements GoviewService {
validateGoviewExists(updateReqVO.getId()); validateGoviewExists(updateReqVO.getId());
// 更新 // 更新
GoviewDO updateObj = BeanUtils.toBean(updateReqVO, GoviewDO.class); GoviewDO updateObj = BeanUtils.toBean(updateReqVO, GoviewDO.class);
if (!updateReqVO.getDeviceIdsList().isEmpty()){
String jsonString = JSON.toJSONString(updateReqVO.getDeviceIdsList());
updateObj.setDeviceIds(jsonString);
}
goviewMapper.updateById(updateObj); goviewMapper.updateById(updateObj);
} }

Loading…
Cancel
Save