#优化更新 连接上位机相关

This commit is contained in:
2026-09-09 09:01:54 +08:00
parent fda1060b38
commit 4ee3f6be90
21 changed files with 330 additions and 218 deletions

View File

@@ -162,6 +162,7 @@ public class HostComputerController extends BaseController {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
log.info("位置数据websocket推送成功: connectorId={}, taskId={}", x.getConnectorId(), taskId);
} catch (Exception e) {
log.error("位置数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());

View File

@@ -40,9 +40,11 @@ public class WorkRecordController extends BaseController {
) {
int i = -1;
// WorkRecord workRecordObj = JsonUtils.parseObject(workRecord, WorkRecord.class);
// WorkRecord workRecordObj = JsonUtils.parseObject(workRecord,
// WorkRecord.class);
WorkRecord workRecord1 = workRecordService.selectWorkRecordByWorkNameAndSiteId(workRecord.getWorkName(), workRecord.getSiteId());
WorkRecord workRecord1 = workRecordService.selectWorkRecordByWorkNameAndSiteId(workRecord.getWorkName(),
workRecord.getSiteId());
if (workRecord1 != null) {
return R.fail("该任务已存在");
}
@@ -108,8 +110,8 @@ public class WorkRecordController extends BaseController {
@GetMapping("/selectByTaskId")
public R selectByTaskId(@RequestParam Long taskId) {
List<LatAndLngEntity> path = workRecordService.selectByTaskId(taskId);
return R.ok(path);
WorkRecord workRecord = workRecordService.selectByTaskId(taskId);
return R.ok(workRecord);
}
@GetMapping("getTaskPath")

View File

@@ -1,22 +1,5 @@
package com.maibu.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.annotation.Excel;
import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.dto.BaseQueryDTO;
import com.maibu.exception.ServiceException;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -28,6 +11,24 @@ import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.dto.BaseQueryDTO;
import com.maibu.exception.ServiceException;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class DeviceRunParamService {
@@ -38,7 +39,8 @@ public class DeviceRunParamService {
@Autowired
private DeviceSessionManager sessionManager;
public boolean save(DeviceRunParam deviceRunParam) throws ExecutionException, InterruptedException, TimeoutException {
public boolean save(DeviceRunParam deviceRunParam)
throws ExecutionException, InterruptedException, TimeoutException {
NettyDevice nettyDevice = sessionManager.getDevice(deviceRunParam.getDeviceId());
if (nettyDevice == null || !nettyDevice.getChannel().isActive()) {
@@ -93,30 +95,73 @@ public class DeviceRunParamService {
return deviceRunParamMapper.selectList(queryWrapper);
}
public DeviceRunParam selectByDeviceId(String deviceId) throws ExecutionException, InterruptedException, TimeoutException {
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
if (nettyDevice != null && nettyDevice.getChannel() != null && nettyDevice.getChannel().isActive()) {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
try {
nettyDevice.readConfigCommand();
DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// public DeviceRunParam selectByDeviceId(String deviceId)
// throws ExecutionException, InterruptedException, TimeoutException {
LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(deviceId)) {
queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
// CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
// if (nettyDevice != null && nettyDevice.getChannel() != null &&
// nettyDevice.getChannel().isActive()) {
// nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
// try {
// nettyDevice.readConfigCommand();
// DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
// if (!StringUtils.isEmpty(deviceId)) {
// queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// }
// DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
// if (result != null) {
// param.setId(result.getId());
// param.setDeviceId(result.getDeviceId());
// param.setRunSpeed(result.getRunSpeed());
// param.setOrgId(nettyDevice.getDevice().getOrgId());
// param.setSiteId(nettyDevice.getDevice().getSiteId());
// }
// return param;
// } finally {
// nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
// }
// }
// return null;
// }
public DeviceRunParam selectByDeviceId(String deviceId)
throws ExecutionException, InterruptedException, TimeoutException {
LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(deviceId)) {
queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
}
DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null && result.getHasHost() != null && result.getHasHost() == 1) {
return result;
} else {
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
if (nettyDevice != null && nettyDevice.getChannel() != null && nettyDevice.getChannel().isActive()) {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
try {
nettyDevice.readConfigCommand();
DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
// if (!StringUtils.isEmpty(deviceId)) {
// queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// }
// DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null) {
param.setId(result.getId());
param.setDeviceId(result.getDeviceId());
param.setRunSpeed(result.getRunSpeed());
param.setOrgId(nettyDevice.getDevice().getOrgId());
param.setSiteId(nettyDevice.getDevice().getSiteId());
}
return param;
} finally {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
}
DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null) {
param.setId(result.getId());
param.setDeviceId(result.getDeviceId());
param.setRunSpeed(result.getRunSpeed());
param.setOrgId(nettyDevice.getDevice().getOrgId());
param.setSiteId(nettyDevice.getDevice().getSiteId());
}
return param;
} finally {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
}
}
return null;
@@ -149,10 +194,11 @@ public class DeviceRunParamService {
Map<String, DeviceRunParam> map = oldList.stream()
.collect(Collectors.toMap(
DeviceRunParam::getDeviceId,
Function.identity()
));
Function.identity()));
List<DeviceRunParam> saveList = new ArrayList<>();
params.forEach(x -> {
if (StringUtils.isEmpty(x.getDeviceId()))
return;
DeviceRunParam deviceRunParam = null;
if (!CollectionUtils.isEmpty(map)) {
deviceRunParam = map.get(x.getDeviceId());
@@ -188,4 +234,3 @@ public class DeviceRunParamService {
}
}

View File

@@ -8,12 +8,11 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.maibu.constant.CacheConstants;
import com.maibu.dto.DeviceParamAuthDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -22,8 +21,8 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.maibu.constant.CacheConstants;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.Device;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.DeviceRunningStatusHistory;
@@ -34,13 +33,13 @@ import com.maibu.core.domain.entity.SysRole;
import com.maibu.core.domain.entity.SysSite;
import com.maibu.core.domain.model.LoginUser;
import com.maibu.core.enums.DeviceTaskStaus;
import com.maibu.core.host.LocationMessage;
import com.maibu.core.redis.RedisCache;
import com.maibu.influxdb.MowerRealTimeData;
import com.maibu.influxdb.util.InfluxSqlBuilder;
import com.maibu.influxdb.util.LambdaUtils;
import com.maibu.dto.DeviceParamAuthDTO;
import com.maibu.mapper.DeviceMapper;
import com.maibu.mapper.DevicePlanMapper;
import com.maibu.mapper.DeviceStatusHistoryMapper;
import com.maibu.mapper.HostLocationMapper;
import com.maibu.mapper.SysSiteMapper;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
@@ -75,6 +74,9 @@ public class DeviceServiceImpl implements IDeviceService {
@Autowired
private SysSiteMapper sysSiteMapper;
@Autowired
private HostLocationMapper hostLocationMapper;
/**
* 根据设备编号查询设备
*
@@ -147,6 +149,13 @@ public class DeviceServiceImpl implements IDeviceService {
Map<String, List<DeviceRunningStatusHistory>> statusMap = allStatusList.stream()
.collect(Collectors.groupingBy(DeviceRunningStatusHistory::getDeviceId));
LambdaQueryWrapper<LocationMessage> query = new LambdaQueryWrapper<>();
query.in(LocationMessage::getDeviceId, ids);
List<LocationMessage> hostLocations = hostLocationMapper.selectList(query);
Map<String, LocationMessage> locationMap = hostLocations.stream()
.collect(Collectors.toMap(LocationMessage::getDeviceId, Function.identity()));
deviceList.forEach(x -> {
Integer s = x.getOnlineStatus() == null ? 0 : x.getOnlineStatus();
if (0 == s) {
@@ -183,6 +192,13 @@ public class DeviceServiceImpl implements IDeviceService {
}
}
x.setLastRunningStatus(lastRunningStatus);
String locationKey = NettyCacheKey.latestPositonKey + x.getDeviceName();
LocationMessage locationMessage = redisCache.getCacheObject(locationKey);
if (locationMessage == null) {
locationMessage = locationMap.get(x.getDeviceName());
}
x.setLocationMessage(locationMessage);
});
deviceList.sort(Comparator.comparing(Device::getFeStatus));
}
@@ -353,7 +369,9 @@ public class DeviceServiceImpl implements IDeviceService {
});
}
}
deviceList.sort(Comparator.comparing(Device::getFeStatus));
if (!CollectionUtils.isEmpty(deviceList)) {
deviceList.sort(Comparator.comparing(Device::getFeStatus));
}
return deviceList;
}

View File

@@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Comparator;
import java.util.List;
@Service
@@ -64,6 +65,7 @@ public class WorkRecordService {
list.forEach(workRecord -> {
workRecord.setJsonData(null);
});
list.sort(Comparator.comparing(WorkRecord::getId).reversed());
}
return list;
}
@@ -72,16 +74,13 @@ public class WorkRecordService {
return workRecordMapper.selectById(id);
}
public List<LatAndLngEntity> selectByTaskId(Long taskId) {
public WorkRecord selectByTaskId(Long taskId) {
DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId); // 先查询设备任务,确认任务存在
if (devicePlanTask == null) {
return null;
}
Long routeId = devicePlanTask.getRouteId(); // 获取任务关联的路线ID
WorkRecord workRecord = workRecordMapper.selectById(routeId); // 查询路线ID对应的工作记录
if (workRecord != null && workRecord.getJsonData() != null) {
return workRecord.getJsonData().getPath(); // 返回路线数据
}
return null; // 如果没有找到对应的工作记录或路线数据,返回 null
return workRecord; // 如果没有找到对应的工作记录或路线数据,返回 null
}
}

View File

@@ -39,10 +39,14 @@
<result property="guid" column="guid"/>
<result property="protocolCode" column="protocol_code"/>
<result property="onlineStatus" column="online_status"/>
<result property="hasHost" column="has_host"/>
<result property="hasRegistered" column="has_registered"/>
</resultMap>
<sql id="selectDeviceVo">
select d.online_status,
d.has_host,
d.has_registered,
d.device_alias,
d.device_id,
d.org_id,
@@ -145,6 +149,8 @@
and d.active_time between #{params.beginActiveTime} and #{params.endActiveTime}
</if>
<if test="onlineStatus != null ">and d.online_status = #{onlineStatus}</if>
<if test="hasHost != null ">and d.has_host = #{hasHost}</if>
<if test="hasRegistered != null ">and d.has_registered = #{hasRegistered}</if>
</where>
order by d.create_time desc
</select>
@@ -302,6 +308,8 @@
<if test="onlineStatus != null">online_status,</if>
<if test="orgId != null">org_id,</if>
<if test="siteId != null">site_id,</if>
<if test="hasHost != null">has_host,</if>
<if test="hasRegistered != null">has_registered,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="deviceName != null and deviceName != ''">#{deviceName},</if>
@@ -335,6 +343,8 @@
<if test="onlineStatus != null">#{onlineStatus},</if>
<if test="orgId != null">#{orgId},</if>
<if test="siteId != null">#{siteId},</if>
<if test="hasHost != null">#{hasHost},</if>
<if test="hasRegistered != null">#{hasRegistered},</if>
</trim>
</insert>
@@ -395,6 +405,8 @@
<if test="onlineStatus != null">online_status = #{onlineStatus},</if>
<if test="orgId != null">org_id = #{orgId},</if>
<if test="siteId != null">site_id = #{siteId},</if>
<if test="hasHost != null">has_host = #{hasHost},</if>
<if test="hasRegistered != null">has_registered = #{hasRegistered},</if>
</trim>
where device_id = #{deviceId}
</update>

View File

@@ -44,7 +44,6 @@ import java.util.concurrent.TimeUnit;
@Service
public class IotDeviceCommonService {
@Autowired
private IotDeviceCommonMapper iotDeviceCommonMapper;
@@ -92,16 +91,13 @@ public class IotDeviceCommonService {
device.setDelFlag(false);
device.setCreateTime(LocalDateTime.now());
log.info("设备 {} 已加入未注册缓存", deviceDTO.getSn());
}
public List<IoTCommonDevice> getUnRegisterDevices() {
return new ArrayList<>(GlobalMemory.unRegisterCommonDeviceMap.values());
}
public Page<IoTCommonDevice> selectDevicePage(Page<IoTCommonDevice> page, IoTCommonDevice device) {
LambdaQueryWrapper<IoTCommonDevice> wrapper = new LambdaQueryWrapper<>();
@@ -123,7 +119,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.selectPage(page, wrapper);
}
public IoTCommonDevice getBySn(String sn) {
LambdaQueryWrapper<IoTCommonDevice> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(IoTCommonDevice::getDeviceId, sn)
@@ -131,7 +126,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.selectOne(wrapper);
}
public void registerDevice(IoTCommonDevice device) {
device.setHasRegister(true);
device.setUpdateTime(LocalDateTime.now());
@@ -144,7 +138,6 @@ public class IotDeviceCommonService {
GlobalMemory.unRegisterCommonDeviceMap.remove(device.getSn());
}
@Transactional(rollbackFor = Exception.class)
public boolean updateDevice(DeviceConfigDTO deviceDTO) {
// 1. 查询设备是否存在
@@ -181,7 +174,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.saveOrUpdate(device);
}
/**
* 设备连接测试(根据协议类型)
*/
@@ -201,12 +193,10 @@ public class IotDeviceCommonService {
}
}
public IoTCommonDevice getFromUnRegisterCache(String sn) {
return GlobalMemory.unRegisterCommonDeviceMap.get(sn);
}
public void updateUnRegisterCache(IoTCommonDevice device) {
if (device.getDeviceId() == null) {
throw new RuntimeException("设备 ID (SN) 不能为空");
@@ -216,14 +206,14 @@ public class IotDeviceCommonService {
log.info("未注册设备 {} 缓存配置已更新", device.getDeviceId());
}
/**
* MQTT 连接测试
*/
private boolean testMqttConnection(String ip, Integer port, String username, String password) {
try {
// TODO: 使用 MQTT 客户端测试连接
// MqttClient client = new MqttClient("tcp://" + ip + ":" + port, "test-" + UUID.randomUUID());
// MqttClient client = new MqttClient("tcp://" + ip + ":" + port, "test-" +
// UUID.randomUUID());
// ...
return true; // 暂时返回 true,后续接入真实 MQTT 库
} catch (Exception e) {
@@ -258,14 +248,13 @@ public class IotDeviceCommonService {
}
}
public void removeByIds(List<Long> ids) {
if (CollectionUtils.isEmpty(ids)) return;
if (CollectionUtils.isEmpty(ids))
return;
iotDeviceCommonMapper.deleteBatchIds(ids);
}
// 3. 按 productId 分组,缓存映射配置避免重复查询
public static Map<Long, List<DeviceModelPropertyMapping>> mappingCache = new ConcurrentHashMap<>();
@@ -300,7 +289,8 @@ public class IotDeviceCommonService {
// 注册到处理器,用 productId 区分不同产品的映射
String handlerType = "property-" + productId;
GenericPropertyMessageHandler handler = (GenericPropertyMessageHandler) monitor.getMessageHandler(handlerType);
GenericPropertyMessageHandler handler = (GenericPropertyMessageHandler) monitor
.getMessageHandler(handlerType);
handler.registerMappingConfig(handlerType, mappingConfig);
// 获取产品信息
@@ -334,11 +324,14 @@ public class IotDeviceCommonService {
/**
* 根据数据库映射列表构建 PropertyMappingConfig
*
* <p>将 {@link DeviceModelPropertyMapping} 转换为 {@link PropertyMappingConfig.FieldMapping}:</p>
* <p>
* 将 {@link DeviceModelPropertyMapping} 转换为
* {@link PropertyMappingConfig.FieldMapping}:
* </p>
* <ul>
* <li>sourceKey → FieldMapping.source(外部 JSON 中的字段名)</li>
* <li>standardKey → FieldMapping.target(统一后的内部属性名)</li>
* <li>dataType → FieldMapping.valueType(自动类型转换)</li>
* <li>sourceKey → FieldMapping.source(外部 JSON 中的字段名)</li>
* <li>standardKey → FieldMapping.target(统一后的内部属性名)</li>
* <li>dataType → FieldMapping.valueType(自动类型转换)</li>
* </ul>
*/
private PropertyMappingConfig buildMappingConfig(List<DeviceModelPropertyMapping> mappings) {