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

@@ -125,14 +125,14 @@ public class DeviceTaskController extends BaseController {
if (siteMemory.hasTask(deviceId)) {
return AjaxResult.error("当前设备存在任务!");
}
Integer mode = siteMemory.getDeviceControlMode(deviceId);
if (mode == null) {
return AjaxResult.error("当前设备模式不存在,无法自动任务!");
}
if (mode != 2) {
String modeStr = switchMode(mode);
return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
}
// Integer mode = siteMemory.getDeviceControlMode(deviceId);
// if (mode == null) {
// return AjaxResult.error("当前设备模式不存在,无法自动任务!");
// }
// if (mode != 2) {
// String modeStr = switchMode(mode);
// return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
// }
return AjaxResult.success(deviceTaskService.createDeviceTask(dto, getLoginUser().getUsername()));
}
@@ -158,14 +158,14 @@ public class DeviceTaskController extends BaseController {
if (siteMemory.hasTask(deviceId)) {
return AjaxResult.error("当前设备存在任务!");
}
Integer mode = siteMemory.getDeviceControlMode(deviceId);
if (mode == null) {
return AjaxResult.error("当前设备模式不存在,无法自动任务!");
}
if (mode != 2) {
String modeStr = switchMode(mode);
return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
}
// Integer mode = siteMemory.getDeviceControlMode(deviceId);
// if (mode == null) {
// return AjaxResult.error("当前设备模式不存在,无法自动任务!");
// }
// if (mode != 2) {
// String modeStr = switchMode(mode);
// return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
// }
return AjaxResult.success(deviceTaskService.createRegionDeviceTask(dto, getLoginUser().getUsername()));
}
@@ -214,14 +214,14 @@ public class DeviceTaskController extends BaseController {
if (siteMemory.hasTask(deviceId)) {
return AjaxResult.error("当前设备存在任务!");
}
Integer mode = siteMemory.getDeviceControlMode(deviceId);
if (mode == null) {
return AjaxResult.error("当前设备模式不存在,无法自动任务!");
}
if (mode != 2) {
String modeStr = switchMode(mode);
return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
}
// Integer mode = siteMemory.getDeviceControlMode(deviceId);
// if (mode == null) {
// return AjaxResult.error("当前设备模式不存在,无法自动任务!");
// }
// if (mode != 2) {
// String modeStr = switchMode(mode);
// return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
// }
return AjaxResult.success(deviceTaskService.backToRestPoint(dto, getLoginUser().getUsername()));
}
@@ -243,14 +243,14 @@ public class DeviceTaskController extends BaseController {
if (siteMemory.hasTask(deviceId)) {
return AjaxResult.error("当前设备存在任务!");
}
Integer mode = siteMemory.getDeviceControlMode(deviceId);
if (mode == null) {
return AjaxResult.error("当前设备模式不存在,无法自动任务!");
}
if (mode != 2) {
String modeStr = switchMode(mode);
return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
}
// Integer mode = siteMemory.getDeviceControlMode(deviceId);
// if (mode == null) {
// return AjaxResult.error("当前设备模式不存在,无法自动任务!");
// }
// if (mode != 2) {
// String modeStr = switchMode(mode);
// return AjaxResult.error("当前设备模式:" + modeStr + ",无法自动任务!");
// }
deviceTaskService.createConsecutiveTasks(dto, getLoginUser().getUsername());
return AjaxResult.success();
}

View File

@@ -114,10 +114,12 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
data.setAngular_z(angularSpeed);
data.setChassis_lift(pEntity.getChassisLiftFlag());
data.setCutter(pEntity.getMowerSpeedFlag());
if (pEntity.getMowerSpeedFlag() != 2) {
data.setCutter(pEntity.getMowerSpeedFlag());
}
data.setIgnition(pEntity.getIgnitionFlag());
data.setEmergency_stop(pEntity.getEmergencyStopFlag());
data.setValid_for_ms(200); //间隔 可调整
// data.setEmergency_stop(pEntity.getEmergencyStopFlag());
data.setValid_for_ms(200); // 间隔 可调整
deviceRemoteControlDTO.setData(data);
deviceRemoteControlDTO
.setCommand_id(Constant.remote_control_cmd_prefix + System.currentTimeMillis());

View File

@@ -1,18 +1,12 @@
package com.maibu.netty.handler;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
@@ -29,12 +23,14 @@ import com.maibu.core.business.DeviceRunningStatusHistory;
import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.business.device.DeviceStatusDetail;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.WebStatusMessageDTO;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.enums.MesType;
import com.maibu.core.redis.RedisCache;
import com.maibu.core.business.dto.WebStatusMessageDTO;
import com.maibu.influxdb.MowerRealTimeData;
import com.maibu.influxdb.util.InfluxSqlBuilder;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.utils.json.JsonUtils;

View File

@@ -160,7 +160,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
nettyDevice.getLatestStatus().setTime(existing.getTime() + time / (1000 * 60)); // 累加时长,单位为分钟
} else {
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
nettyDevice.getLatestStatus().setTime(time / (1000 * 60)); // 累加时长,单位为分钟
// nettyDevice.getLatestStatus().setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(nettyDevice.getLatestStatus());
}

View File

@@ -1,26 +1,24 @@
package com.maibu.scheduled;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.redis.RedisCache;
import com.maibu.mapper.DeviceStatusHistoryMapper;
import com.maibu.memory.SiteMemory;
import com.maibu.utils.json.JsonUtils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DevicePlan;
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.SiteMemory;
@Component
public class ScheduledTask {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -29,27 +27,25 @@ public class ScheduledTask {
private RedisCache redisCache;
@Autowired
private DeviceStatusHistoryMapper deviceStatusHistoryMapper;
private VehicleMessageMapper vehicleMessageMapper;
//整点更新设备状态
// 整点更新设备状态
@Scheduled(cron = "0 0 * * * ?")
// @Scheduled(cron = "0 * * * * ?")
// @Scheduled(cron = "0 * * * * ?")
public void executeHourlyTask() {
System.out.println("整点定时任务执行时间: " + dateFormat.format(new Date()));
String key = NettyCacheKey.deviceRunningStatusKey;
// Collection<String> keys = redisCache.keys(key);
String key = NettyCacheKey.vehicleMessageKey;
// Collection<String> keys = redisCache.keys(key);
Collection<String> keys = redisCache.getListKeyByPrefix(key);
if (!CollectionUtils.isEmpty(keys)) {
keys.forEach(k -> {
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(k);
VehicleMessageRecordDTO recordDTO = redisCache.getCacheObject(k);
if (recordDTO != null && !CollectionUtils.isEmpty(recordDTO.getHistories())) {
// recordDTO.getHistories().forEach(x -> {
// deviceStatusHistoryMapper.insert(x);
// });
deviceStatusHistoryMapper.insertBatch(recordDTO.getHistories());
// recordDTO.getHistories().forEach(x -> {
// deviceStatusHistoryMapper.insert(x);
// });
vehicleMessageMapper.insertBatch(recordDTO.getHistories());
}
redisCache.deleteObject(k);
});
@@ -57,8 +53,7 @@ public class ScheduledTask {
System.out.println("任务执行完成");
}
//0点刷新任务创建状态
// 0点刷新任务创建状态
@Scheduled(cron = "0 0 0 * * ?")
public void refreshDevicePlanTask() {
System.out.println("0点定时刷新状态");
@@ -76,19 +71,26 @@ public class ScheduledTask {
}
// public static void main(String[] args) throws DecoderException {
// String hex = "AB AA 05 88 4D 43 37 30 30 50 4C 55 53 2D 43 4E 2D 4A 53 2D 31 37 38 34 38 37 31 39 37 39 31 39 30 2D 30 30 30 30 30 30 30 41 2D 36 30 00 B1 FB 7F FE FE FE 00 00 00 00 00 00 00 00 00 00 00 00 00 12 01 48 95 E8 03 E8 03 28 32 91 53 24 4D 43 37 30 30 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 31 32 33 34 35 36 37 38 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 CD CC A4 41 00 00 80 3F 33 33 33 3F B8 1E 05 3F 33 33 33 3F 9A 99 19 3E 00 00 80 3F 00 00 80 3F 00 00 80 3F 32 36 2D 34 2D 32 37 00 2D 32 37 00 50 B1 BF 00 00 AA AB";
// String cleanHex = hex.replaceAll("\\s+", ""); // 移除所有空白字符
// byte[] bytes = Hex.decodeHex(cleanHex);
// DeviceRunParam runParam = DeviceRunParam.fromBytes(bytes);
// System.out.println(JsonUtils.toJsonString(runParam));
// String hex = "AB AA 05 88 4D 43 37 30 30 50 4C 55 53 2D 43 4E 2D 4A 53 2D 31
// 37 38 34 38 37 31 39 37 39 31 39 30 2D 30 30 30 30 30 30 30 41 2D 36 30 00 B1
// FB 7F FE FE FE 00 00 00 00 00 00 00 00 00 00 00 00 00 12 01 48 95 E8 03 E8 03
// 28 32 91 53 24 4D 43 37 30 30 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 31
// 32 33 34 35 36 37 38 00 00 00 00 00 00 00 00 00 00 00 00 00 08 00 00 00 CD CC
// A4 41 00 00 80 3F 33 33 33 3F B8 1E 05 3F 33 33 33 3F 9A 99 19 3E 00 00 80 3F
// 00 00 80 3F 00 00 80 3F 32 36 2D 34 2D 32 37 00 2D 32 37 00 50 B1 BF 00 00 AA
// AB";
// String cleanHex = hex.replaceAll("\\s+", ""); // 移除所有空白字符
// byte[] bytes = Hex.decodeHex(cleanHex);
// DeviceRunParam runParam = DeviceRunParam.fromBytes(bytes);
// System.out.println(JsonUtils.toJsonString(runParam));
// runParam.setLeftBackwardGain(0.2f);
// runParam.setLeftForwardGain(0.2f);
// runParam.setRightForwardGain(0.2f);
// runParam.setRightBackwardGain(0.2f);
// runParam.setLeftBackwardGain(0.2f);
// runParam.setLeftForwardGain(0.2f);
// runParam.setRightForwardGain(0.2f);
// runParam.setRightBackwardGain(0.2f);
// byte[] newB = runParam.toWriteBytes();
// System.out.println(Hex.encodeHexString(newB));
// byte[] newB = runParam.toWriteBytes();
// System.out.println(Hex.encodeHexString(newB));
// }
}

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) {

View File

@@ -1,6 +1,11 @@
package com.maibu.utils;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.maibu.core.enums.CompareEnum;
import lombok.extern.slf4j.Slf4j;
/**
@@ -10,79 +15,176 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CompareUtils {
// /**
// * 比较两个值是否满足指定的操作符条件
// *
// * @param operator 比较操作符
// * @param targetValue 目标值(用于比较的值)
// * @param compareValue 比较值(要比较的值)
// * @return 是否满足条件
// */
// public static boolean compare(CompareEnum operator, String targetValue,
// String compareValue) {
// if (operator == null || targetValue == null || compareValue == null) {
// return false;
// }
// try {
// // 根据操作符执行不同的比较逻辑
// switch (operator) {
// case EQ:
// return compareValue.equals(targetValue);
// case NEQ:
// return !compareValue.equals(targetValue);
// case GT:
// return isNumeric(compareValue) && isNumeric(targetValue) &&
// Double.parseDouble(targetValue) > Double.parseDouble(compareValue);
// case LT:
// return isNumeric(compareValue) && isNumeric(targetValue) &&
// Double.parseDouble(targetValue) < Double.parseDouble(compareValue);
// case GTE:
// return isNumeric(compareValue) && isNumeric(targetValue) &&
// Double.parseDouble(targetValue) >= Double.parseDouble(compareValue);
// case LTE:
// return isNumeric(compareValue) && isNumeric(targetValue) &&
// Double.parseDouble(targetValue) <= Double.parseDouble(compareValue);
// case BETWEEN:
// // 范围值用英文中划线分割
// String[] rangeValues = compareValue.split("-");
// if (rangeValues.length != 2) {
// return false;
// }
// return isNumeric(rangeValues[0]) && isNumeric(rangeValues[1]) &&
// Double.parseDouble(targetValue) >= Double.parseDouble(rangeValues[0]) &&
// Double.parseDouble(targetValue) <= Double.parseDouble(rangeValues[1]);
// case NOT_BETWEEN:
// // 范围值用英文中划线分割
// String[] notRangeValues = compareValue.split("-");
// if (notRangeValues.length != 2) {
// return false;
// }
// return isNumeric(notRangeValues[0]) && isNumeric(notRangeValues[1]) &&
// (Double.parseDouble(targetValue) < Double.parseDouble(notRangeValues[0]) ||
// Double.parseDouble(targetValue) > Double.parseDouble(notRangeValues[1]));
// case CONTAIN:
// return targetValue.contains(compareValue);
// case NOT_CONTAIN:
// return !targetValue.contains(compareValue);
// default:
// return false;
// }
// } catch (Exception e) {
// log.error("比较操作失败,操作符: {}, 目标值: {}, 比较值: {}", operator.getValue(),
// targetValue, compareValue, e);
// return false;
// }
// }
// /**
// * 判断字符串是否为数字
// *
// * @param str 要判断的字符串
// * @return 是否为数字
// */
// private static boolean isNumeric(String str) {
// if (str == null || str.isEmpty()) {
// return false;
// }
// // 使用正则表达式判断是否为数字
// return str.matches("^[+-]?\\d*(\\.\\d+)?$");
// }
private static final Pattern RANGE_PATTERN = Pattern.compile(
"^\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+))\\s*-\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+))\\s*$");
/**
* 比较两个值是否满足指定的操作符条件
*
* @param operator 比较操作符
* @param targetValue 目标值(用于比较的值)
* @param compareValue 比较值(要比较的值)
* @param targetValue 目标值(实际采集值)
* @param compareValue 比较值(阈值或范围)
* @return 是否满足条件
*/
public static boolean compare(CompareEnum operator, String targetValue, String compareValue) {
public static boolean compare(CompareEnum operator,
String targetValue,
String compareValue) {
if (operator == null || targetValue == null || compareValue == null) {
return false;
}
try {
// 根据操作符执行不同的比较逻辑
String target = targetValue.trim();
String compare = compareValue.trim();
switch (operator) {
case EQ:
return compareValue.equals(targetValue);
return target.equals(compare);
case NEQ:
return !compareValue.equals(targetValue);
return !target.equals(compare);
case GT:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(targetValue) > Double.parseDouble(compareValue);
return toDecimal(target).compareTo(toDecimal(compare)) > 0;
case LT:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(targetValue) < Double.parseDouble(compareValue);
return toDecimal(target).compareTo(toDecimal(compare)) < 0;
case GTE:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(targetValue) >= Double.parseDouble(compareValue);
return toDecimal(target).compareTo(toDecimal(compare)) >= 0;
case LTE:
return isNumeric(compareValue) && isNumeric(targetValue) &&
Double.parseDouble(targetValue) <= Double.parseDouble(compareValue);
return toDecimal(target).compareTo(toDecimal(compare)) <= 0;
case BETWEEN:
// 范围值用英文中划线分割
String[] rangeValues = compareValue.split("-");
if (rangeValues.length != 2) {
return false;
}
return isNumeric(compareValue) && isNumeric(rangeValues[0]) && isNumeric(rangeValues[1]) &&
Double.parseDouble(targetValue) >= Double.parseDouble(rangeValues[0]) &&
Double.parseDouble(targetValue) <= Double.parseDouble(rangeValues[1]);
case NOT_BETWEEN:
// 范围值用英文中划线分割
String[] notRangeValues = compareValue.split("-");
if (notRangeValues.length != 2) {
Matcher matcher = RANGE_PATTERN.matcher(compare);
if (!matcher.matches()) {
return false;
}
return isNumeric(compareValue) && isNumeric(notRangeValues[0]) && isNumeric(notRangeValues[1]) &&
(Double.parseDouble(targetValue) < Double.parseDouble(notRangeValues[0]) ||
Double.parseDouble(targetValue) > Double.parseDouble(notRangeValues[1]));
BigDecimal value = toDecimal(target);
BigDecimal min = toDecimal(matcher.group(1));
BigDecimal max = toDecimal(matcher.group(2));
// 范围上下限不合法
if (min.compareTo(max) > 0) {
return false;
}
boolean inRange = value.compareTo(min) >= 0
&& value.compareTo(max) <= 0;
return operator == CompareEnum.BETWEEN
? inRange
: !inRange;
case CONTAIN:
return targetValue.contains(compareValue);
return target.contains(compare);
case NOT_CONTAIN:
return !targetValue.contains(compareValue);
return !target.contains(compare);
default:
return false;
}
} catch (NumberFormatException e) {
log.warn("比较值格式错误,操作符: {}, 目标值: {}, 比较值: {}",
operator.getValue(), targetValue, compareValue);
return false;
} catch (Exception e) {
log.error("比较操作失败,操作符: {}, 目标值: {}, 比较值: {}", operator.getValue(), targetValue, compareValue, e);
log.error("比较操作失败,操作符: {}, 目标值: {}, 比较值: {}",
operator.getValue(), targetValue, compareValue, e);
return false;
}
}
/**
* 判断字符串是否为数字
*
* @param str 要判断的字符串
* @return 是否为数字
* 转换为 BigDecimal
*/
private static boolean isNumeric(String str) {
if (str == null || str.isEmpty()) {
return false;
}
// 使用正则表达式判断是否为数字
return str.matches("^[+-]?\\d*(\\.\\d+)?$");
private static BigDecimal toDecimal(String value) {
return new BigDecimal(value);
}
}