This commit is contained in:
2026-11-16 13:38:56 +08:00
parent c3a2aee8fb
commit 08888ab612
44 changed files with 1162 additions and 377 deletions

View File

@@ -54,7 +54,7 @@ public class AlertPushService {
@Autowired
private WorkOrderServiceImpl wService;
public void messagePushHandler(String deviceId, List<DeviceErrorPushDTO> dtos) {
public void messagePushHandler(String deviceId, List<AlarmMessage> dtos) {
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
if (nettyDevice != null && nettyDevice.getDevice() != null) {
Long siteId = nettyDevice.getDevice().getSiteId();
@@ -66,65 +66,66 @@ public class AlertPushService {
Integer alertPush = siteMemory.getSysSite().getAlertPush();
String secret = siteMemory.getSysSite().getDingTalkSecret();
String token = siteMemory.getSysSite().getDingTalkToken();
dtos.forEach(dto -> {
if (!CollectionUtils.isEmpty(dto.getDetails())) {
List<AlarmMessage> newList = new ArrayList<>();
List<IOTWorkOrder> workOrders = new ArrayList<>();
dto.getDetails().forEach(detail -> {
if (dingTalkPush == 1) {
String pushKey = "alarm:" + "dingtalk:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
pushDingTalkMessage(secret, token, DingTalkTemplate.buildText(detail));
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail), 10,
TimeUnit.MINUTES);
}
}
if (emailPush == 1) {
String pushKey = "alarm:" + "email:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
pushEmailMessage(null, null);
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail), 10,
TimeUnit.MINUTES);
}
}
if (alertPush == 1) {
String pushKey = "alarm:" + "mqtt:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
newList.add(detail);
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail));
AlarmOrderConfig config = siteMemory.getAlarmOrderConfig(detail.getNo());
log.debug("compare config:{}", JsonUtils.toJsonString(config));
if (config != null && config.isAutoGenerateOrder()) {
IOTWorkOrder workOrder = wService.generateWorkOrders(siteId, deviceId, orgId, config.getModelId(), detail.getNo());
workOrders.add(workOrder);
}
}
}
});
//todo 后续添加配置推送的告警等级
if (alertPush == 1) {
List<Alarm> alarms = alarmService.pushAlertMes(newList);
log.debug("alarms : {}", JsonUtils.toJsonString(alarms));
log.debug("workOrders : {}", JsonUtils.toJsonString(workOrders));
if (!CollectionUtils.isEmpty(workOrders)) {
if (!CollectionUtils.isEmpty(alarms)) {
workOrders.forEach(x -> {
alarms.forEach(y -> {
if (x.getAlarmNo().equals(y.getAlarmNo())) {
x.setAlarmId(y.getId());
x.setTaskDescription(y.getAlarmContent());
}
});
});
}
wService.saveAll(workOrders);
if (!CollectionUtils.isEmpty(dtos)) {
List<AlarmMessage> newList = new ArrayList<>();
List<IOTWorkOrder> workOrders = new ArrayList<>();
dtos.forEach(detail -> {
if (dingTalkPush == 1) {
String pushKey = "alarm:" + "dingtalk:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
pushDingTalkMessage(secret, token, DingTalkTemplate.buildText(detail));
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail), 10,
TimeUnit.MINUTES);
}
}
if (emailPush == 1) {
String pushKey = "alarm:" + "email:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
pushEmailMessage(null, null);
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail), 10,
TimeUnit.MINUTES);
}
}
if (alertPush == 1) {
String pushKey = "alarm:" + "mqtt:" + deviceId + ":" + detail.getNo();
Boolean exists = redisCache.hasKey(pushKey);
if (exists != null && !exists) {
newList.add(detail);
redisCache.setCacheObject(pushKey, JsonUtils.toJsonString(detail));
AlarmOrderConfig config = siteMemory.getAlarmOrderConfig(detail.getNo());
log.debug("compare config:{}", JsonUtils.toJsonString(config));
if (config != null && config.isAutoGenerateOrder()) {
IOTWorkOrder workOrder = wService.generateWorkOrders(siteId, deviceId, orgId,
config.getModelId(), detail.getNo());
workOrders.add(workOrder);
}
}
}
});
// todo 后续添加配置推送的告警等级
if (alertPush == 1) {
List<Alarm> alarms = alarmService.pushAlertMes(newList);
log.debug("alarms : {}", JsonUtils.toJsonString(alarms));
log.debug("workOrders : {}", JsonUtils.toJsonString(workOrders));
if (!CollectionUtils.isEmpty(workOrders)) {
if (!CollectionUtils.isEmpty(alarms)) {
workOrders.forEach(x -> {
alarms.forEach(y -> {
if (x.getAlarmNo().equals(y.getAlarmNo())) {
x.setAlarmId(y.getId());
x.setTaskDescription(y.getAlarmContent());
}
});
});
}
wService.saveAll(workOrders);
}
}
});
}
}
}
}

View File

@@ -52,6 +52,9 @@ public class DevicePlanTaskMonitorService {
@Autowired
private ScheduledExecutorService executor;
@Autowired
private DeviceTaskService deviceTaskService;
/**
* 计划迟的任务生成机器执行任务
*/
@@ -65,17 +68,23 @@ public class DevicePlanTaskMonitorService {
String key = iterator.next();
List<DevicePlan> list = planMap.get(key);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(this::createPlanTask);
list.forEach(t -> {
try {
createPlanTask(t);
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
}
});
}
}
}
} catch (Exception e) {
log.error("执行任务生成线程错误", e);
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}, 0, 5000, TimeUnit.MILLISECONDS);
}
private void createPlanTask(DevicePlan devicePlan) {
private void createPlanTask(DevicePlan devicePlan) throws Exception {
if (devicePlan.isDayTriggerFlag())
return; // 当天应该创建的全部创建完
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
@@ -98,7 +107,7 @@ public class DevicePlanTaskMonitorService {
}
}
public void dayPlan(DevicePlan devicePlan) {
public void dayPlan(DevicePlan devicePlan) throws Exception {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
LocalTime nowTime = LocalTime.now();
LocalTime dayTime = LocalTime.parse(rules.getDayTime());
@@ -121,6 +130,12 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setSiteId(devicePlan.getSiteId());
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建dayPlan切换权限失败!");
return;
} // 检验权限
siteMemory.addDevicePlanPrepare(devicePlanTask);
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
@@ -138,7 +153,7 @@ public class DevicePlanTaskMonitorService {
}
}
public void weekPlan(DevicePlan devicePlan) {
public void weekPlan(DevicePlan devicePlan) throws Exception {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
LocalTime nowTime = LocalTime.now();
List<DayOfWeek> days = devicePlan.getDeviceTaskPlanRules().getDays();
@@ -164,6 +179,10 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setTaskType("");// 待拓展任务类型
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建weekPlan切换权限失败!");
return;
} // 检验权限
siteMemory.addDevicePlanPrepare(devicePlanTask);
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);
@@ -180,7 +199,7 @@ public class DevicePlanTaskMonitorService {
}
}
public void monthPlan(DevicePlan devicePlan) {
public void monthPlan(DevicePlan devicePlan) throws Exception {
DeviceTaskPlanRule rules = devicePlan.getDeviceTaskPlanRules();
List<Integer> dayOfMonthList = rules.getDayOfMonth();
LocalDate today = LocalDate.now();
@@ -206,6 +225,11 @@ public class DevicePlanTaskMonitorService {
devicePlanTask.setSiteId(devicePlan.getSiteId());
devicePlanTaskMapper.insert(devicePlanTask);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
if (!deviceTaskService.sendAutoTaskModeResult(siteMemory, devicePlan.getDeviceId())) {
log.debug("创建monthPlan切换权限失败!");
return;
} // 检验权限
siteMemory.addDevicePlanPrepare(devicePlanTask);
// 啥时候重置?每日0点?
devicePlan.setDayTriggerFlag(true);

View File

@@ -526,7 +526,7 @@ public class DeviceTaskService {
return list;
}
public Long createDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
public synchronized Long createDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
SiteMemory siteMemory = GlobalMemory.getSiteMemory(dto.getOrgId(), dto.getSiteId());
sendAutoTaskMode(siteMemory, dto.getDeviceId()); // 检验权限
@@ -558,7 +558,7 @@ public class DeviceTaskService {
return task.getId();
}
public Long createRegionDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
public synchronized Long createRegionDeviceTask(DeviceTaskCommandDTO dto, String username) throws Exception {
LambdaQueryWrapper<SysRegion> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRegion::getId, dto.getRegionId());
SysRegion region = sysRegionMapper.selectOne(queryWrapper);
@@ -675,7 +675,7 @@ public class DeviceTaskService {
return false;
}
public Long backToRestPoint(DeviceTaskCommandDTO dto, String username) throws Exception {
public synchronized Long backToRestPoint(DeviceTaskCommandDTO dto, String username) throws Exception {
// 先判断 mode 是不是 0 是0 切换成2 成功 失败返回 不是 0 判断是不是2 ,是2 执行 不是2 切换 等结果
@@ -735,7 +735,7 @@ public class DeviceTaskService {
return task.getId();
}
public void createConsecutiveTasks(ConsecutiveTaskDTO dto, String username) throws Exception {
public synchronized void createConsecutiveTasks(ConsecutiveTaskDTO dto, String username) throws Exception {
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
@@ -816,4 +816,18 @@ public class DeviceTaskService {
}
}
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

@@ -4,8 +4,6 @@ import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -29,7 +27,6 @@ import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.Device;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.DeviceRunningStatusHistory;
import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.business.ErrorIdentificationStandard;
import com.maibu.core.business.RegionConsecutiveTaskRecord;
import com.maibu.core.business.alarm_center.AlarmMessage;
@@ -46,15 +43,12 @@ import com.maibu.core.enums.ActionType;
import com.maibu.core.enums.CompareEnum;
import com.maibu.core.enums.ConnectorStatus;
import com.maibu.core.enums.DeviceStatus;
import com.maibu.core.enums.ErrorSource;
import com.maibu.core.enums.MesType;
import com.maibu.core.enums.RespondCode;
import com.maibu.core.enums.RuleType;
import com.maibu.core.host.HeartBeatDTO;
import com.maibu.core.host.LocationMessage;
import com.maibu.core.host.VehicleMessage;
import com.maibu.core.redis.RedisCache;
import com.maibu.dto.DeviceErrorPushDTO;
import com.maibu.mapper.DeviceRunStatisticsMapper;
import com.maibu.mapper.ErrorIdentificationStandardMapper;
import com.maibu.mapper.HostLocationMapper;
@@ -120,48 +114,14 @@ public class DeviceThreadService {
// 有还需要更新接受故障方式。
executor.scheduleWithFixedDelay(() -> {
try {
String key = NettyCacheKey.deviceRunningStatusKey;
Collection<String> keys = redisCache.getListKeyByPrefix(key);
if (!CollectionUtils.isEmpty(keys)) {
List<DeviceErrorPushDTO> pushList = new ArrayList<>();
keys.forEach(k -> {
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(k);
if (recordDTO != null && !CollectionUtils.isEmpty(recordDTO.getHistories())) {
recordDTO.getHistories()
.sort(Comparator.comparing(DeviceRunningStatusHistory::getCreateTime).reversed());
DeviceRunningStatusHistory history = recordDTO.getHistories().get(0);
String[] parts = k.split(":");
String deviceId = parts[1];
NettyDevice slaveDevice = sessionManager.getDevice(deviceId);
if (slaveDevice != null && slaveDevice.getOnlineStatus() == 1) {
Long siteId = slaveDevice.getDevice().getSiteId();
Long orgId = slaveDevice.getDevice().getOrgId();
log.debug("compare siteId:{},orgId:{}", siteId, orgId);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
List<AlarmMessage> compared = compareErrorStandard(siteId, orgId, history,
siteMemory.standards.get(ErrorSource.MOWER));
DeviceErrorPushDTO pushDTO = new DeviceErrorPushDTO();
pushDTO.setDeviceId(deviceId);
pushDTO.setTime(System.currentTimeMillis());
pushDTO.setDetails(compared);
pushDTO.setEvent(RespondCode.device_error_push);
pushList.add(pushDTO);
}
}
}
});
// 按实际deviceId分组,推送错误信息
Map<String, List<DeviceErrorPushDTO>> pushMap = pushList.stream()
.collect(java.util.stream.Collectors.groupingBy(DeviceErrorPushDTO::getDeviceId));
pushMap.forEach((deviceId, dtos) -> {
// pushErrorMessage(deviceId, JSON.toJSONString(dtos));
GlobalMemory.getAllSiteMemory().forEach(siteMemory -> {
siteMemory.alarmMap.forEach((deviceId, dtos) -> {
// todo 判断错误级别,是否需要推送邮件 或者钉钉。
// 找到这个设备的场站 添加场站是否开启关闭 钉钉或者邮件推送,推送邮件 添加人员是否订阅邮件,钉钉是加入钉钉群
alertPushService.messagePushHandler(deviceId, dtos);
});
}
});
} catch (Exception e) {
log.error("执行监测错误线程错误", e);
}
@@ -308,32 +268,46 @@ public class DeviceThreadService {
}
String deviceId = x.getSn();
Long lastActiveTime = x.getSysTimestamp();
NettyDevice nettyDevice = sessionManager.getDevice(x.getSn());
if (lastActiveTime == null) {
log.error("设备心跳时间为空,deviceId={}", deviceId);
return;
}
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
Device device = null;
if (nettyDevice == null) {
sessionManager.registerSlaveDevice(deviceId, ConnectorStatus.ACTIVE, null);
nettyDevice = sessionManager.getDevice(deviceId);
if (nettyDevice != null) {
device = loadDevice(device, deviceId);
nettyDevice.setDevice(device);
}
} else {
device = loadDevice(nettyDevice.getDevice(), deviceId);
nettyDevice.setDevice(device);
}
if (nettyDevice == null || device == null) {
return;
}
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (nowTime - lastActiveTime >= Constant.hostOfflineInterval) {
// 超时了判断离线
if (nettyDevice != null && nettyDevice.getOnlineStatus() != null
&& nettyDevice.getOnlineStatus() == 1) {
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
try {
// 标记离线
nettyDevice.status(DeviceStatus.offline.getType());
updatelatestLocation(deviceId);
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
updateTotalArea(nettyDevice, siteMemory, deviceId);
}
@@ -347,7 +321,6 @@ public class DeviceThreadService {
} finally {
// 必须执行:清理实时缓存
try {
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
siteMemory.removeMapPushDTO(deviceId);
siteMemory.removeVehicleMessage(deviceId);
@@ -358,48 +331,23 @@ public class DeviceThreadService {
}
}
} else {
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
if (device == null) {
device = new Device();
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setSerialNumber(deviceId);
device.setDeviceName(deviceId);
device.setProductId(-1L);
device.setTenantId(-1L);
device.setFirmwareVersion("1.0");
device.setProductName("割草机产品MC700");
device.setCreateTime(LocalDateTime.now());
device.setUpdateTime(LocalDateTime.now());
device.setHasHost(true);
deviceService.insertDeviceBySelf(device);
} else {
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setUpdateTime(LocalDateTime.now());
device.setHasHost(true);
deviceService.updateDeviceBySelf(device);
}
if (nettyDevice == null) {
sessionManager.registerSlaveDevice(deviceId, ConnectorStatus.ACTIVE, null);
NettyDevice slaveDevice = sessionManager.getDevice(deviceId);
if (slaveDevice != null) {
slaveDevice.setOnlineStatus(1);
slaveDevice.setDevice(device);
statusChangePush(deviceId, device.getSiteId(), 1);
}
} else {
Integer lastOnlineStatus = nettyDevice.getOnlineStatus();
if (lastOnlineStatus == null || lastOnlineStatus == 0) {
statusChangePush(deviceId, device.getSiteId(), 1);
Integer lastOnlineStatus = nettyDevice.getOnlineStatus();
// 判断从离线到上线
if (lastOnlineStatus == null || lastOnlineStatus == 0) {
statusChangePush(deviceId, nettyDevice.getDevice().getSiteId(), 1);
if (device != null) {
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
// todo 推送设备上线
nettyDevice.status(1);
nettyDevice.setDevice(device);
nettyDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
}
// todo 推送设备上线
nettyDevice.status(1);
nettyDevice.setDevice(device);
nettyDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
}
});
}
@@ -409,6 +357,29 @@ public class DeviceThreadService {
}, 0, 500, TimeUnit.MILLISECONDS);
}
public Device loadDevice(Device device, String deviceId) {
if (device == null) {
device = deviceService.selectDeviceBySerialNumber(deviceId);
}
// 新增设备s
if (device == null) {
device = new Device();
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setSerialNumber(deviceId);
device.setDeviceName(deviceId);
device.setProductId(-1L);
device.setTenantId(-1L);
device.setFirmwareVersion("1.0");
device.setProductName("割草机产品MC700");
device.setCreateTime(LocalDateTime.now());
device.setUpdateTime(LocalDateTime.now());
device.setHasHost(true);
deviceService.insertDeviceBySelf(device);
}
return device;
}
public void updatelatestLocation(String deviceId) {
// todo 推送设备离线
String key = NettyCacheKey.latestPositonKey + deviceId;
@@ -447,7 +418,7 @@ public class DeviceThreadService {
} else {
long time = System.currentTimeMillis()
- nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(time / (1000 * 60)); // 累加时长,单位为分钟
// deviceRunStatistics.setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(deviceRunStatistics);
}
@@ -548,6 +519,8 @@ public class DeviceThreadService {
String deviceId = x.getDeviceId();
String value = classFieldFinding(key, x);
boolean result = CompareUtils.compare(compareType, value, compareValue);
log.debug("conditions:{},compareValue:{},value:{},result:{}", conditions, compareValue, value,
result);
if (result) {
ActionConfig aConfig = rule.getActionConfig();
if (aConfig != null && aConfig.getActionType() != null) {