This commit is contained in:
2026-11-19 09:18:17 +08:00
parent 08888ab612
commit 21b3dbaddb
24 changed files with 449 additions and 220 deletions

View File

@@ -84,14 +84,16 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
for (Connector target : connectedDevices) {
if (target == null || !target.canReceive()) {
logger.debug("发送拒绝master:{},消息到达的slave设备:{},处于禁止接收状态", senderDeviceId, target.getConnectorId());
logger.debug("发送拒绝master:{},消息到达的slave设备:{},处于禁止接收状态",
senderDeviceId,
target == null ? null : target.getConnectorId());
continue;
}
NettyDevice targetDevice = deviceSessionManager.getDevice(target.getConnectorId());
if (targetDevice == null)
if (targetDevice == null || targetDevice.getDevice() == null)
continue;
// 区分有上位机的还有无上位机的 有上位机的通过上位机下发 没有上位机的按照原来的方式下发
if (targetDevice.getDevice().getHasHost()) {
if (Boolean.TRUE.equals(targetDevice.getDevice().getHasHost())) {
if (bytes[2] == CommandConstant.remoteControl) {
// todo 转换 原先的报文重新组装成上位机的报文格式
DeviceRemoteControlDTO deviceRemoteControlDTO = new DeviceRemoteControlDTO();
@@ -119,7 +121,7 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
}
data.setIgnition(pEntity.getIgnitionFlag());
// data.setEmergency_stop(pEntity.getEmergencyStopFlag());
data.setValid_for_ms(200); // 间隔 可调整
data.setValid_for_ms(250); // 间隔 可调整
deviceRemoteControlDTO.setData(data);
deviceRemoteControlDTO
.setCommand_id(Constant.remote_control_cmd_prefix + System.currentTimeMillis());

View File

@@ -17,6 +17,7 @@ import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.business.dto.VehicleMessageRecordDTO;
import com.maibu.core.redis.RedisCache;
import com.maibu.mapper.VehicleMessageMapper;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
@Component
@@ -57,16 +58,21 @@ public class ScheduledTask {
@Scheduled(cron = "0 0 0 * * ?")
public void refreshDevicePlanTask() {
System.out.println("0点定时刷新状态");
Map<String, List<DevicePlan>> map = SiteMemory.devicePlanMap;
if (!CollectionUtils.isEmpty(map.keySet())) {
map.values().forEach(x -> {
if (!CollectionUtils.isEmpty(x)) {
x.forEach(y -> {
y.setDayTriggerFlag(false);
});
}
});
}
List<SiteMemory> siteMemories = GlobalMemory.getAllSiteMemory();
if (CollectionUtils.isEmpty(siteMemories))
return;
siteMemories.forEach(z -> {
Map<String, List<DevicePlan>> map = z.devicePlanMap;
if (!CollectionUtils.isEmpty(map.keySet())) {
map.values().forEach(x -> {
if (!CollectionUtils.isEmpty(x)) {
x.forEach(y -> {
y.setDayTriggerFlag(false);
});
}
});
}
});
System.out.println("0点定时刷新状态执行完成");
}

View File

@@ -107,7 +107,8 @@ public class AlertPushService {
});
// todo 后续添加配置推送的告警等级
if (alertPush == 1) {
List<Alarm> alarms = alarmService.pushAlertMes(newList);
List<Alarm> alarms = alarmService.pushAlertMes(newList, deviceId,
nettyDevice.getDevice().getDeviceAlias());
log.debug("alarms : {}", JsonUtils.toJsonString(alarms));
log.debug("workOrders : {}", JsonUtils.toJsonString(workOrders));
if (!CollectionUtils.isEmpty(workOrders)) {

View File

@@ -61,23 +61,29 @@ public class DevicePlanTaskMonitorService {
public void generatePlanTask() throws InterruptedException {
executor.scheduleWithFixedDelay(() -> {
try {
Map<String, List<DevicePlan>> planMap = SiteMemory.devicePlanMap;
if (!CollectionUtils.isEmpty(planMap.values())) {
Iterator<String> iterator = planMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<DevicePlan> list = planMap.get(key);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(t -> {
try {
createPlanTask(t);
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
if (!CollectionUtils.isEmpty(list)) {
list.forEach(siteMemory -> {
Map<String, List<DevicePlan>> planMap = siteMemory.devicePlanMap;
if (!CollectionUtils.isEmpty(planMap.values())) {
Iterator<String> iterator = planMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
List<DevicePlan> pLlist = planMap.get(key);
if (!CollectionUtils.isEmpty(pLlist)) {
pLlist.forEach(t -> {
try {
createPlanTask(t);
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
}
});
}
});
}
}
}
});
}
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
}
@@ -131,7 +137,7 @@ public class DevicePlanTaskMonitorService {
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建dayPlan切换权限失败!");
return;
} // 检验权限
@@ -179,7 +185,7 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setTaskType("");// 待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建weekPlan切换权限失败!");
return;
} // 检验权限
@@ -226,7 +232,7 @@ public class DevicePlanTaskMonitorService {
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
if (!deviceTaskService.sendAutoTaskMode(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建monthPlan切换权限失败!");
return;
} // 检验权限

View File

@@ -400,7 +400,7 @@ public class DeviceTaskService {
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
siteMemory.devicePlanTaskPrepareMap.values().forEach(list::addAll);
list.addAll(SiteMemory.devicePlanTaskExecuteMap.values());
list.addAll(siteMemory.devicePlanTaskExecuteMap.values());
if (dto.getTaskStaus() != null) {
list = list.stream().filter(x -> x.getTaskStaus().equals(dto.getTaskStaus())).collect(Collectors.toList());
}
@@ -529,7 +529,10 @@ public class DeviceTaskService {
public synchronized Long createDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
if (!b) {
throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!"));
}
DevicePlanTask task = new DevicePlanTask();
task.setOrgId(dto.getOrgId());
task.setSiteId(dto.getSiteId());
@@ -572,7 +575,10 @@ public class DeviceTaskService {
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
if (!b) {
throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!"));
}
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
if (site != null) {
@@ -691,14 +697,17 @@ public class DeviceTaskService {
throw new ServiceException(MessageUtils.message("任务下发出错!"));
}
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
SiteMapInfo siteMapInfo = siteMemory.getSysSite().getSiteMapInfo();
if (siteMapInfo == null || CollectionUtils.isEmpty(siteMapInfo.getRestPoints())) {
throw new ServiceException(MessageUtils.message("当前机器未配置返回点!"));
}
boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
if (!b) {
throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!"));
}
List<RestPoint> restPoints = objectMapper.convertValue(
siteMapInfo.getRestPoints(),
new TypeReference<List<RestPoint>>() {
@@ -747,7 +756,10 @@ public class DeviceTaskService {
if (siteMemory == null) {
throw new ServiceException(MessageUtils.message("任务下发出错!"));
}
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
boolean b = sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
if (!b) {
throw new ServiceException(MessageUtils.message("当前状态无法执行自动任务!"));
}
siteMemory.saveRegionConsecutiveTask(dto.getDeviceId(), dto, username);
}
@@ -801,33 +813,32 @@ public class DeviceTaskService {
return regionConsecutiveTaskRecordMapper.selectList(queryWrapper);
}
public void sendAutoTaskMode(SiteMemory siteMemory, String deviceId) throws Exception {
public synchronized boolean sendAutoTaskMode(SiteMemory siteMemory, String deviceId) throws Exception {
VehicleMessage vehicleMessage = siteMemory.getVehicleMessage(deviceId);
if (vehicleMessage == null || vehicleMessage.getControl_mode() == null) {
throw new ServiceException(MessageUtils.message("当前机器未连接!"));
}
boolean result = true;
Integer controlMode = vehicleMessage.getControl_mode();
boolean isSend = controlMode != 2;
if (isSend) {
boolean result = hostComputerService.modeChage(deviceId, 2);
if (!result) {
throw new ServiceException(MessageUtils.message("当前设备切换模式失败!"));
Integer systemCode = vehicleMessage.getSystemMode();
// 控制模式不为0 同时不为2 不能操作 直接返回false
if (controlMode != 0) {
if (controlMode != 2) {
result = false;
}
} else {
// boolean isSend = systemCode != 2;
boolean isSend = !Objects.equals(systemCode, 2);
if (isSend) {
result = hostComputerService.modeChage(deviceId, 2);
if (!result) {
throw new ServiceException(MessageUtils.message("当前设备切换模式失败!"));
}
}
}
}
return result;
public boolean sendAutoTaskModeResult(SiteMemory siteMemory, String deviceId) throws Exception {
VehicleMessage vehicleMessage = siteMemory.getVehicleMessage(deviceId);
if (vehicleMessage == null || vehicleMessage.getControl_mode() == null) {
return false;
}
Integer controlMode = vehicleMessage.getControl_mode();
boolean isSend = controlMode != 2;
if (isSend) {
boolean result = hostComputerService.modeChage(deviceId, 2);
return result;
}
return true;
}
}

View File

@@ -6,6 +6,7 @@ import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -22,6 +23,7 @@ import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maibu.constant.Constant;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.Device;
@@ -36,6 +38,8 @@ import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.business.dto.WebMapMessageDTO;
import com.maibu.core.business.dto.WebOlineStatusMessageDTO;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.domain.map.RestPoint;
import com.maibu.core.domain.map.SiteMapInfo;
import com.maibu.core.domain.rule.ActionConfig;
import com.maibu.core.domain.rule.IotAutoRule;
import com.maibu.core.domain.rule.TriggerConditions;
@@ -63,6 +67,7 @@ import com.maibu.utils.json.JsonUtils;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.core.type.TypeReference;
@Slf4j
@Service
@@ -104,9 +109,11 @@ public class DeviceThreadService {
@Autowired
private DeviceTaskService deviceTaskService;
@JsonIgnore
@Autowired
private RegionConsecutiveTaskRecordMapper regionConsecutiveTaskRecordMapper;
private static final ObjectMapper objectMapper = new ObjectMapper();
public void deviceErrorMonitor() throws InterruptedException, IOException {
initStandard();
@@ -155,7 +162,6 @@ public class DeviceThreadService {
ErrorIdentificationStandard::getErrorSource,
ConcurrentHashMap::new,
Collectors.toList()));
}
} catch (IORuntimeException e) {
// TODO Auto-generated catch block
@@ -295,40 +301,73 @@ public class DeviceThreadService {
if (nowTime - lastActiveTime >= Constant.hostOfflineInterval) {
// 超时了判断离线
if (nettyDevice != null && nettyDevice.getOnlineStatus() != null
&& nettyDevice.getOnlineStatus() == 1) {
// if (nettyDevice != null && nettyDevice.getOnlineStatus() != null
// && nettyDevice.getOnlineStatus() == 1) {
try {
// 标记离线
nettyDevice.status(DeviceStatus.offline.getType());
updatelatestLocation(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
// try {
// // 标记离线
// nettyDevice.status(DeviceStatus.offline.getType());
// updatelatestLocation(deviceId);
// if (device != null) {
// device.setOnlineStatus(DeviceStatus.offline.getType());
// device.setUpdateTime(LocalDateTime.now());
// deviceService.updateDeviceBySelf(device);
// }
if (siteMemory != null) {
updateTotalArea(nettyDevice, siteMemory, deviceId);
}
// TODO 统计总里程、总作业面积
statusChangePush(deviceId, siteId, 0);
sessionManager.removeDevice(deviceId);
// if (siteMemory != null) {
// updateTotalArea(nettyDevice, siteMemory, deviceId);
// }
// // TODO 统计总里程、总作业面积
// statusChangePush(deviceId, siteId, 0);
// sessionManager.removeDevice(deviceId);
} catch (Exception e) {
log.error("设备离线处理异常,deviceId={}", deviceId, e);
// } catch (Exception e) {
// log.error("设备离线处理异常,deviceId={}", deviceId, e);
// } finally {
// // 必须执行:清理实时缓存
// try {
// if (siteMemory != null) {
// siteMemory.removeMapPushDTO(deviceId);
// siteMemory.removeVehicleMessage(deviceId);
// }
// } catch (Exception e) {
// log.error("设备离线缓存清理失败,deviceId={}", deviceId, e);
// }
// }
// }
try {
if (nettyDevice != null
&& Objects.equals(nettyDevice.getOnlineStatus(), 1)) {
} finally {
// 必须执行:清理实时缓存
try {
if (siteMemory != null) {
siteMemory.removeMapPushDTO(deviceId);
siteMemory.removeVehicleMessage(deviceId);
// 标记离线
nettyDevice.status(DeviceStatus.offline.getType());
updatelatestLocation(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
if (siteMemory != null) {
updateTotalArea(nettyDevice, siteMemory, deviceId);
}
statusChangePush(deviceId, siteId, 0);
sessionManager.removeDevice(deviceId);
} catch (Exception e) {
log.error("设备离线缓存清理失败,deviceId={}", deviceId, e);
log.error("设备离线处理异常,deviceId={}", deviceId, e);
}
}
} finally {
// 外层兜底清理
if (siteMemory != null) {
siteMemory.removeMapPushDTO(deviceId);
siteMemory.removeVehicleMessage(deviceId);
}
}
} else {
@@ -506,6 +545,53 @@ public class DeviceThreadService {
}, 0, 500, TimeUnit.MILLISECONDS);
}
public static double calculateDistance(
double lat1, double lon1,
double lat2, double lon2) {
double earthRadius = 6371000;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2))
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
return earthRadius * 2 * Math.atan2(
Math.sqrt(a), Math.sqrt(1 - a));
}
private boolean isAtRestPoint(String deviceId, SiteMemory siteMemory) {
DeviceMapPushDTO pushDto = siteMemory.getDeviceMapPusById(deviceId);
SiteMapInfo siteMapInfo = siteMemory.getSysSite().getSiteMapInfo();
if (pushDto == null || siteMapInfo == null)
return false;
List<RestPoint> restPoints = objectMapper.convertValue(
siteMapInfo.getRestPoints(),
new TypeReference<List<RestPoint>>() {
});
if (CollectionUtils.isEmpty(restPoints))
return false;
RestPoint switchRestPoint = restPoints.stream()
.filter(x -> deviceId.equals(x.getBindDeviceId())).findFirst().orElse(null);
if (switchRestPoint == null)
return false;
// 距离小于5米认为到位了
double distance = calculateDistance(
pushDto.getLat(), pushDto.getLng(),
switchRestPoint.getPosition().getLat(), switchRestPoint.getPosition().getLng());
boolean arrived = distance <= 2;
return arrived;
}
public void handleAutoRule(IotAutoRule rule, SiteMemory siteMemory) {
if (RuleType.LOW_BATTERY_RETURN.equals(rule.getRuleType())) {
@@ -518,6 +604,10 @@ public class DeviceThreadService {
vList.forEach(x -> {
String deviceId = x.getDeviceId();
String value = classFieldFinding(key, x);
// 电量小于0 不信任电量上报
if (Integer.parseInt(value) <= 0) {
return;
}
boolean result = CompareUtils.compare(compareType, value, compareValue);
log.debug("conditions:{},compareValue:{},value:{},result:{}", conditions, compareValue, value,
result);
@@ -529,6 +619,10 @@ public class DeviceThreadService {
if (siteMemory.hasTask(deviceId)) {
return;
}
if (isAtRestPoint(deviceId, siteMemory)) {
return;
}
DeviceTaskCommandDTO dto = new DeviceTaskCommandDTO();
dto.setDeviceId(deviceId);
dto.setOrgId(siteMemory.getSysSite().getOrgId());