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

@@ -30,7 +30,7 @@ public class Constant {
public static final Long hostOfflineInterval = 10000L; // 单位毫秒
// ==================== 远程控制 ====================
public static final String protocol_version = "1.4.6";
public static final String protocol_version = "1.4.7";
public static final String remote_control_msg_prefix = "remote-msg";
public static final String remote_control_cmd_prefix = "remote-cmd";
}

View File

@@ -60,4 +60,12 @@ public class DevicePlanTask extends OrgBaseDO {
@TableField(exist = false)
private double taskTime; // s
@TableField(exist = false)
private double totalTaskDistance; // 记录当前任务的累计里程
@TableField(exist = false)
private double totalTaskTime; // s
@TableField(exist = false)
private double progress;
}

View File

@@ -25,7 +25,7 @@ public class DeviceRunStatistics implements Serializable {
private Double distance; //作业距离
private Double time; //时长 分钟
private Double time; //时长
private String deviceId;

View File

@@ -56,6 +56,8 @@ public class Alarm extends TenantBaseDO {
@Excel(name = "设备名称")
private String deviceName;
private String deviceAlias;
@ApiModelProperty("设备类型:1-逆变器 2-汇流箱 3-组串 4-气象站 5-电表 6-智能汇流箱 7-箱变 8-SVG")
@Excel(name = "设备类型", readConverterExp = "1=逆变器,2=汇流箱,3=组串,4=气象站,5=电表,6=智能汇流箱,7=箱变,8=SVG")
private ErrorSource deviceType;

View File

@@ -31,6 +31,7 @@ import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
@@ -135,8 +136,8 @@ public class NettyDevice extends Connector {
public void updateWorkArea() {
double taskDistance = task.getTaskDistance();
double taskTime = task.getTaskTime();
double taskDistance = task.getTotalTaskDistance();
double taskTime = task.getTotalTaskTime();
double workArea = taskDistance * 0.8;
LambdaQueryWrapper<DeviceRunStatistics> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DeviceRunStatistics::getDeviceId, task.getDeviceId());
@@ -144,15 +145,20 @@ public class NettyDevice extends Connector {
.selectOne(queryWrapper);
if (existing != null) {
existing.setDistance(
existing.getDistance() + taskDistance);
BigDecimal.valueOf(existing.getDistance())
.add(BigDecimal.valueOf(taskDistance))
.doubleValue());
existing.setWorkArea(
existing.getWorkArea() + workArea);
existing.setTime(existing.getTime() + taskTime); // 累加时长,单位为分钟
BigDecimal.valueOf(existing.getWorkArea())
.add(BigDecimal.valueOf(workArea))
.doubleValue());
existing.setTime(existing.getTime() + taskTime); // 累加时长,单位为s
} else {
existing = new DeviceRunStatistics();
existing.setDistance(taskDistance);
existing.setWorkArea(workArea);
existing.setTime(taskTime); // 累加时长,单位为分钟
existing.setTime(taskTime); // 累加时长,单位为s
existing.setDeviceId(task.getDeviceId());
}
runStatisticsMapper.saveOrUpdate(existing);
@@ -190,7 +196,7 @@ public class NettyDevice extends Connector {
task = null;
currentTaskId = null;
currentPoint = null;
locationQueue.clear();
// locationQueue.clear();
executingTask = false;
return finishId;
}
@@ -236,7 +242,7 @@ public class NettyDevice extends Connector {
task = null;
currentTaskId = null;
currentPoint = null;
locationQueue.clear();
// locationQueue.clear();
executingTask = false;
return taskId;
}
@@ -256,7 +262,7 @@ public class NettyDevice extends Connector {
task = null;
currentTaskId = null;
currentPoint = null;
locationQueue.clear();
// locationQueue.clear();
executingTask = false;
return taskId;
}
@@ -333,7 +339,7 @@ public class NettyDevice extends Connector {
// todo 优化
public synchronized boolean pauseTask() throws MqttException {
if (executingTask) {
task.setTaskStaus(DeviceTaskStaus.PAUSE);
// task.setTaskStaus(DeviceTaskStaus.PAUSE);
HostWorkRecordCreateDTO dto = new HostWorkRecordCreateDTO();
dto.setAction("pause");
dto.setCommand_id(task.getId() + "_" + System.currentTimeMillis());
@@ -361,7 +367,7 @@ public class NettyDevice extends Connector {
// todo 优化
public synchronized boolean recoveryTask() throws InterruptedException, MqttException {
if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE)) {
task.setTaskStaus(DeviceTaskStaus.PAUSE);
// task.setTaskStaus(DeviceTaskStaus.EXECUTING);
HostWorkRecordCreateDTO dto = new HostWorkRecordCreateDTO();
dto.setAction("resume");
dto.setCommand_id(task.getId() + "_" + System.currentTimeMillis());
@@ -410,10 +416,11 @@ public class NettyDevice extends Connector {
if (current >= 10) {
futureHolder[0].cancel(false);
log.warn("任务执行达到最大次数,停止执行");
executingTask = false;
task.setTaskStaus(DeviceTaskStaus.FAILED);
devicePlanTaskMapper.saveOrUpdate(task);
task = null;
// executingTask = false;
// task.setTaskStaus(DeviceTaskStaus.FAILED);
// devicePlanTaskMapper.saveOrUpdate(task);
// task = null;
failedTask();
}
} catch (Exception e) {

View File

@@ -23,4 +23,6 @@ public class AlarmHandleDTO {
@ApiModelProperty("处理结果")
private AlarmHandleResult handleResult;
private String deviceId;
}

View File

@@ -23,4 +23,6 @@ public class DeviceMapPushDTO {
private String ms; // 运动状态 moving|stopped|blocked
private Boolean e; // 急停状态
}

View File

@@ -1,5 +1,8 @@
package com.maibu.core.business.dto;
import java.util.List;
import com.maibu.core.business.alarm_center.Alarm;
import com.maibu.core.enums.MesType;
import lombok.Data;
@@ -7,11 +10,13 @@ import lombok.Data;
@Data
public class WebOlineStatusMessageDTO {
private String deviceId;
private String deviceAlias;
private Integer onlineStatus;
private Integer hasError;
private String errorCode;
private String description;
private MesType type;
private List<Alarm> alarms;
private Long time;
}

View File

@@ -1,7 +1,6 @@
package com.maibu.core.host;
import java.time.LocalDateTime;
import java.util.List;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

View File

@@ -32,6 +32,7 @@ public class GlobalMemory {
public static ConcurrentHashMap<String, CompletableFuture<Boolean>> modeFutureMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, CompletableFuture<Boolean>> eStopFutureMap = new ConcurrentHashMap<>();
// public static MqttClientUtil mqttClientUtil;
public static CustomMqttDeviceMonitor customMqttDeviceMonitor = null; // 这里面包含了 连我们自己的mqtt 和外部的一些设备,自己的用clientId

View File

@@ -48,41 +48,41 @@ public class SiteMemory {
public SysSite sysSite;
public static final ConcurrentHashMap<String, MqttClient> mqttClientMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, MqttClient> mqttClientMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<Long, OrderModel> orderModelMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<Long, OrderModel> orderModelMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, AlarmOrderConfig> orderConfigMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, AlarmOrderConfig> orderConfigMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, DeviceRunParam> deviceRunParamMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, DeviceRunParam> deviceRunParamMap = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, Device> deviceMap = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String, IoTCommonDevice> commonDeviceMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, IoTCommonDevice> commonDeviceMap = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Long, Product> productMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, Product> productMap = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<Long, DeviceModel> deviceModelMap = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Long, DeviceModel> deviceModelMap = new ConcurrentHashMap<>();
// key deviceId
public static ConcurrentHashMap<String, List<DevicePlan>> devicePlanMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, List<DevicePlan>> devicePlanMap = new ConcurrentHashMap<>();
// key deviceId prepare
public static ConcurrentHashMap<String, List<DevicePlanTask>> devicePlanTaskPrepareMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, List<DevicePlanTask>> devicePlanTaskPrepareMap = new ConcurrentHashMap<>();
// key deviceId execute
public static ConcurrentHashMap<String, DevicePlanTask> devicePlanTaskExecuteMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, DevicePlanTask> devicePlanTaskExecuteMap = new ConcurrentHashMap<>();
// 记录 设备上线后的运行数据 下线后清除并保存到数据库
public static ConcurrentHashMap<String, DeviceRunStatistics> deviceRunStatisticsMap = new ConcurrentHashMap<>();
public ConcurrentHashMap<String, DeviceRunStatistics> deviceRunStatisticsMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, DeviceMapPushDTO> deviceMapPushMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, DeviceMapPushDTO> deviceMapPushMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, VehicleMessage> vehicleMessageMap = new ConcurrentHashMap<>();
public ConcurrentHashMap<String, VehicleMessage> vehicleMessageMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<RuleType, List<IotAutoRule>> iotAutoRuleMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<RuleType, List<IotAutoRule>> iotAutoRuleMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, RegionConsecutiveTaskRecord> regionConsecutiveTaskMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, RegionConsecutiveTaskRecord> regionConsecutiveTaskMap = new ConcurrentHashMap<>();
public static final ConcurrentHashMap<String, List<AlarmMessage>> alarmMap = new ConcurrentHashMap<>();
public final ConcurrentHashMap<String, List<AlarmMessage>> alarmMap = new ConcurrentHashMap<>();
public void saveAlarm(String deviceSn, AlarmMessage alarmMessage) {
if (deviceSn == null || alarmMessage == null) {
@@ -206,14 +206,14 @@ public class SiteMemory {
return vehicleMessageMap.get(deviceId);
}
public void saveVehicleSystemMode(String deviceId, Integer systemMode) {
public synchronized void saveVehicleSystemMode(String deviceId, Integer systemMode) {
VehicleMessage vehicleMessage = getVehicleMessage(deviceId);
if (vehicleMessage != null) {
vehicleMessage.setSystemMode(systemMode);
}
}
public void saveVehicleMessage(String deviceId, VehicleMessage vehicleMessage) {
public synchronized void saveVehicleMessage(String deviceId, VehicleMessage vehicleMessage) {
VehicleMessage oldVehicle = getVehicleMessage(deviceId);
if (oldVehicle != null) {
vehicleMessage.setSystemMode(oldVehicle.getSystemMode());

View File

@@ -1,9 +1,12 @@
package com.maibu.mqtt;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import org.eclipse.paho.client.mqttv3.MqttException;
@@ -289,8 +292,10 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
dto.setMs(vehicleMessage.getMotion());
dto.setB(vehicleMessage.getBattery_percentage());
dto.setSm(vehicleMessage.getSystemMode());
dto.setE(vehicleMessage.getEmergency_stop());
}
dto.setWk(nettyDevice.getTask() != null ? nettyDevice.getTask().getWorkName() : "");
dto.setP(nettyDevice.getTask() != null ? nettyDevice.getTask().getProgress() : 0d);
siteMemory.saveMapPushDTO(deviceId, dto);
}
}
@@ -298,7 +303,8 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
return webStatusMessageDTO;
}
public WebStatusMessageDTO createWebDeviceRealtimeMessage(HostVehicleRelTimeDTO vehicleRelTimeDTO) {
public WebStatusMessageDTO createWebDeviceRealtimeMessage(HostVehicleRelTimeDTO vehicleRelTimeDTO,
Integer systemMode) {
// todo 状态消息
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
@@ -466,6 +472,12 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
angular_speed.setUnit("");
transferData.add(angular_speed);
DeviceStatusDetail system_mode = new DeviceStatusDetail();
system_mode.setName("systemMode");
system_mode.setValue(String.valueOf(systemMode));
system_mode.setUnit("");
transferData.add(system_mode);
webStatusMessageDTO.setData(transferData);
webStatusMessageDTO.setType(MesType.deviceInfo);
return webStatusMessageDTO;
@@ -480,24 +492,36 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
HostVehicleRelTimeDTO vehicleRelTimeDTO = JsonUtils.parseObject(payload, HostVehicleRelTimeDTO.class);
if (vehicleRelTimeDTO != null) {
// todo 更新里程数 里程数 * 割幅0.8
vehicleRelTimeDTO.getData().getTotal_work_distance();
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
Integer systemMode = null;
if (nettyDevice != null) {
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
DeviceRunStatistics deviceRunStatistics = siteMemory.getRunStatistics(deviceId);
if (deviceRunStatistics == null) {
deviceRunStatistics = new DeviceRunStatistics();
}
deviceRunStatistics.setDeviceId(deviceId);
deviceRunStatistics.setDistance(vehicleRelTimeDTO.getData().getTotal_work_distance());
deviceRunStatistics.setWorkArea(vehicleRelTimeDTO.getData().getTotal_work_distance() * 0.8);
siteMemory.saveRunStatistics(deviceRunStatistics);
// DeviceRunStatistics deviceRunStatistics =
// siteMemory.getRunStatistics(deviceId);
// if (deviceRunStatistics == null) {
// deviceRunStatistics = new DeviceRunStatistics();
// }
// deviceRunStatistics.setDeviceId(deviceId);
// deviceRunStatistics.setDistance(vehicleRelTimeDTO.getData().getTotal_work_distance());
// deviceRunStatistics.setWorkArea(vehicleRelTimeDTO.getData().getTotal_work_distance()
// * 0.8);
// siteMemory.saveRunStatistics(deviceRunStatistics);
siteMemory.saveVehicleMessage(deviceId, vehicleRelTimeDTO.getData());
systemMode = siteMemory.getVehicleMessage(deviceId).getSystemMode();
Integer oldSystemMode = siteMemory.getVehicleMessage(deviceId).getControl_mode();
Integer controlMode = vehicleRelTimeDTO.getData().getControl_mode();
if (Objects.equals(oldSystemMode, 0) && !Objects.equals(controlMode, 0)) {
// 清除 systemcode;
siteMemory.saveVehicleSystemMode(deviceId, null);
}
// 故障处理
Long errorCode = vehicleRelTimeDTO.getData().getError_code();
if (errorCode != null && errorCode != 0) {
@@ -510,7 +534,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
}
}
WebStatusMessageDTO dto = createWebDeviceRealtimeMessage(vehicleRelTimeDTO);
WebStatusMessageDTO dto = createWebDeviceRealtimeMessage(vehicleRelTimeDTO, systemMode);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
@@ -736,20 +760,34 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
HostTaskStatusDTO dto = JsonUtils.parseObject(payload, HostTaskStatusDTO.class);
if (dto != null && !StringUtils.isEmpty(dto.getStatus())) {
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
if (nettyDevice == null)
return;
double progress = 0d;
if ("completed".equals(dto.getStatus())) {
Long taskId = nettyDevice.finishTask();
pushTaskChangeMessage(deviceId, taskId, DeviceTaskStaus.FINISH.toString());
progress = 100d;
}
if ("cancelled".equals(dto.getStatus())) {
// todo 记录累计里程
if (nettyDevice != null && nettyDevice.getTask() != null) {
DevicePlanTask task = nettyDevice.getTask();
task.setTotalTaskDistance(dto.getData().getTotal_distance_m());
task.setTotalTaskTime(dto.getData().getExecution_time_s());
}
Long taskId = nettyDevice.canceledTask();
pushTaskChangeMessage(deviceId, taskId, DeviceTaskStaus.CANCELED.toString());
}
// if("paused".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
if ("paused".equals(dto.getStatus())) {
if (nettyDevice != null && nettyDevice.getTask() != null) {
DevicePlanTask task = nettyDevice.getTask();
if (!DeviceTaskStaus.PAUSE.equals(task.getTaskStaus())) {
task.setTaskStaus(DeviceTaskStaus.PAUSE);
}
}
}
if ("failed".equals(dto.getStatus())) {
Long taskId = nettyDevice.failedTask();
pushTaskChangeMessage(deviceId, taskId, DeviceTaskStaus.FAILED.toString());
@@ -763,20 +801,23 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
// todo 记录累计里程
if (nettyDevice != null && nettyDevice.getTask() != null) {
DevicePlanTask task = nettyDevice.getTask();
task.setTaskDistance(dto.getData().getDistance_traveled_m());
task.setTaskTime(dto.getData().getExecution_time_s());
if (!DeviceTaskStaus.EXECUTING.equals(task.getTaskStaus())) {
task.setTaskStaus(DeviceTaskStaus.EXECUTING);
}
task.setTaskDistance(dto.getData().getDistance_traveled());
task.setTaskTime(dto.getData().getElapsed_s());
}
}
// 任务进度 百分比
Long siteId = nettyDevice.getDevice().getSiteId();
Long orgId = nettyDevice.getDevice().getOrgId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
DeviceMapPushDTO pushDto = siteMemory.getDeviceMapPusById(deviceId);
if (pushDto != null && dto.getData() != null) {
pushDto.setP(dto.getData().getProgress());
}
if (progress != 100d) {
progress = BigDecimal.valueOf(dto.getData().getProgress())
.multiply(BigDecimal.valueOf(100))
.setScale(2, RoundingMode.HALF_UP)
.doubleValue();
}
if (nettyDevice.getTask() != null) {
nettyDevice.getTask().setProgress(progress);
}
}
@@ -956,7 +997,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
log.debug("【模式切换回复】deviceId={}, payload={}", deviceId, payload);
HostModeChangeReplyDTO data = JsonUtils.parseObject(payload, HostModeChangeReplyDTO.class);
if (data != null && data.getAccepted() != null) {
if (data != null && data.getAccepted() != null && data.getAccepted()) {
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
if (nettyDevice != null && nettyDevice.getDevice() != null) {
@@ -1002,25 +1043,12 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
// }
}
private void handleEstopPost(String deviceId, String topic, String payload) {
log.debug("【故障恢复回复】deviceId={}, payload={}", deviceId, payload);
// HostFaultRecoveryReplyDTO data = JsonUtils.parseObject(payload,
// HostFaultRecoveryReplyDTO.class);
// CompletableFuture<Boolean> future = GlobalMemory.modeFutureMap.get(deviceId);
// if (future != null && data != null) {
// future.complete(data.getAccepted());
// }
}
private void handleEstopReply(String deviceId, String topic, String payload) {
log.debug("【故障恢复回复】deviceId={}, payload={}", deviceId, payload);
HostModeChangeReplyDTO data = JsonUtils.parseObject(payload, HostModeChangeReplyDTO.class);
CompletableFuture<Boolean> future = GlobalMemory.modeFutureMap.get(deviceId);
CompletableFuture<Boolean> future = GlobalMemory.eStopFutureMap.get(deviceId);
if (future != null && data != null) {
future.complete(data.getAccepted());

View File

@@ -13,7 +13,7 @@ public class MqttTopic {
/** 通用设备主题,建议使用 MOWER_* 系列主题 */
public static final String DEVICE_TASK_ARRIVE_TOPIC = "task/%s/arrive";
/** 通用设备主题,建议使用 MOWER_* 系列主题 */
public static final String DEVICE_ERROR_PUSH_TOPIC = "device/%s/error";
public static final String DEVICE_ERROR_PUSH_TOPIC = "device/%s/error/post";
public static final String DEVICE_ROUTE_PUSH_TOPIC = "device/%s/route/post";
public static final String DEVICE_STATUS_PUSH_TOPIC = "device/%s/status/change";
@@ -131,7 +131,7 @@ public class MqttTopic {
public static final String MOWER_ESTOP_SET = "mower/%s/control/emergency_stop/set";
/** 设置无遥控器时候的急停回复(设备->平台) */
public static final String MOWER_ESTOP_REPLY = "mower/%s/control/emergency_stop/reply";
public static final String MOWER_ESTOP_REPLY = "mower/+/control/emergency_stop/reply";
/**
* 格式化 Topic 模板,将 %s 替换为设备ID

View File

@@ -56,12 +56,12 @@ public class InitIotResource implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
logger.info("InitResource 开始初始化系统资源...");
// logger.info("InitResource 开始初始化系统资源...");
// 初始化Vert.x
initResource();
logger.info("InitResource 系统资源初始化完成");
initDeviceConnectAndMesPush();
// // 初始化Vert.x
// initResource();
// logger.info("InitResource 系统资源初始化完成");
// initDeviceConnectAndMesPush();
}

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());

View File

@@ -17,6 +17,7 @@
<dependency>
<groupId>com.maibu</groupId>
<artifactId>maibu-common</artifactId>
<version>${maibu.version}</version>
</dependency>
<dependency>

View File

@@ -86,11 +86,11 @@ public class WorkRecordController extends BaseController {
String fileName = "routePlanImage/rt" + workRecord.getWorkName() + System.currentTimeMillis() + ".png";
// // 上传到 MinIO
// minioUtil.uploadFile(fileName, inputStream, "image/png");
minioUtil.uploadFile(fileName, inputStream, "image/png");
// // 获取访问 URL
// String url = minioUtil.getPublicUrl(fileName);
String url = "";
// 获取访问 URL
String url = minioUtil.getPublicUrl(fileName);
// String url = "";
System.out.println("✅ 图片上传成功,访问地址: " + url);
// 这里可以把 URL 存到 workRecord 里

View File

@@ -6,30 +6,33 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.maibu.core.enums.AlarmType;
import com.maibu.core.redis.RedisCache;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maibu.core.business.Device;
import com.maibu.core.business.alarm_center.Alarm;
import com.maibu.core.business.alarm_center.AlarmMessage;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.AlarmHandleDTO;
import com.maibu.core.business.dto.AlarmQueryDTO;
import com.maibu.core.business.dto.WebOlineStatusMessageDTO;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.domain.model.LoginUser;
import com.maibu.core.enums.AlarmType;
import com.maibu.core.enums.ErrorSource;
import com.maibu.core.page.TableDataInfo;
import com.maibu.core.enums.MesType;
import com.maibu.core.redis.RedisCache;
import com.maibu.exception.ServiceException;
import com.maibu.mapper.AlarmMapper;
import com.maibu.mapper.DeviceMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.service.IAlarmService;
@@ -52,10 +55,15 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
@Autowired
private RedisCache redisCache;
@Autowired
private DeviceSessionManager deviceSessionManager;
@Autowired
private WebsocketMesDispather websocketMesDispather;
@Value("${mqtt.client-id}")
private String mqttClientId;
@Override
public List<Alarm> selectAlarmPage(AlarmQueryDTO queryDTO) {
// validateQueryParams(queryDTO);
@@ -82,7 +90,8 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
Map<String, Object> statistics = new HashMap<>();
statistics.put("total", alarms.size());
statistics.put("pending", alarms.stream().filter(a -> a.getHandleStatus() == 1).count());
// statistics.put("processing", alarms.stream().filter(a -> a.getHandleStatus() == 2).count());
// statistics.put("processing", alarms.stream().filter(a -> a.getHandleStatus()
// == 2).count());
statistics.put("closed", alarms.stream().filter(a -> a.getHandleStatus() == 2).count());
statistics.put("levelStats",
@@ -240,10 +249,10 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
Alarm alarm = alarmMapper.selectById(id);
if (alarm == null)
throw new ServiceException("告警不存在");
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getDeviceId() != null) {
// validateDeviceAccess(alarm.getDeviceId());
// }
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getDeviceId() != null) {
// validateDeviceAccess(alarm.getDeviceId());
// }
return alarm;
}
@@ -261,13 +270,13 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
@Override
public boolean updateAlarm(Alarm alarm) {
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getId() != null) {
// Alarm existAlarm = alarmMapper.selectById(alarm.getId());
// if (existAlarm != null && existAlarm.getDeviceId() != null) {
// validateDeviceAccess(existAlarm.getDeviceId());
// }
// }
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getId() != null) {
// Alarm existAlarm = alarmMapper.selectById(alarm.getId());
// if (existAlarm != null && existAlarm.getDeviceId() != null) {
// validateDeviceAccess(existAlarm.getDeviceId());
// }
// }
return alarmMapper.saveOrUpdate(alarm);
}
@@ -277,13 +286,14 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
if (alarm == null)
throw new ServiceException("告警不存在");
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getDeviceId() != null) {
// validateDeviceAccess(alarm.getDeviceId());
// }
// Long userId = SecurityUtils.getUserId();
// if (!SecurityUtils.isAdmin(userId) && alarm.getDeviceId() != null) {
// validateDeviceAccess(alarm.getDeviceId());
// }
// Alarm updateAlarm = new Alarm();
// updateAlarm.setId(handleDTO.getAlarmId());
// Alarm updateAlarm = new Alarm();
// updateAlarm.setId(handleDTO.getAlarmId());
alarm.setHandleStatus(handleDTO.getHandleStatus());
alarm.setHandleUserId(SecurityUtils.getUserId());
alarm.setHandleUserName(SecurityUtils.getLoginUser().getUser().getNickName());
@@ -296,24 +306,25 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
}
public void removeRedisAlarm(String deviceId, String alarmNo) {
if (StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(alarmNo)) return;
if (StringUtils.isEmpty(deviceId) || StringUtils.isEmpty(alarmNo))
return;
String pushKey = "alarm:" + "dingtalk:" + deviceId + ":" + alarmNo;
// Boolean exists = redisCache.hasKey(pushKey);
// if (exists != null && exists) {
// redisCache.deleteObject(pushKey);
// }
// Boolean exists = redisCache.hasKey(pushKey);
// if (exists != null && exists) {
// redisCache.deleteObject(pushKey);
// }
String pushKey2 = "alarm:" + "email:" + deviceId + ":" + alarmNo;
// Boolean exists2 = redisCache.hasKey(pushKey2);
// if (exists2 != null && exists2) {
// redisCache.deleteObject(pushKey2);
// }
// Boolean exists2 = redisCache.hasKey(pushKey2);
// if (exists2 != null && exists2) {
// redisCache.deleteObject(pushKey2);
// }
String pushKey3 = "alarm:" + "mqtt:" + deviceId + ":" + alarmNo;
// Boolean exists3 = redisCache.hasKey(pushKey3);
// if (exists3 != null && exists3) {
// redisCache.deleteObject(pushKey3);
// }
// Boolean exists3 = redisCache.hasKey(pushKey3);
// if (exists3 != null && exists3) {
// redisCache.deleteObject(pushKey3);
// }
redisCache.deleteObject(pushKey);
redisCache.deleteObject(pushKey2);
@@ -382,8 +393,8 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
return statistics;
}
public List<Alarm> pushAlertMes(List<AlarmMessage> alarmMessages) {
if (alarmMessages == null || alarmMessages.isEmpty()) {
public List<Alarm> pushAlertMes(List<AlarmMessage> alarmMessages, String deviceId, String deviceName) {
if (alarmMessages == null || alarmMessages.isEmpty() || StringUtils.isEmpty(deviceId)) {
return null;
}
List<Alarm> list = new ArrayList<>();
@@ -402,18 +413,59 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
alarm.setTimeValues(alarmMessage.getTimeValues());
alarm.setSiteId(alarmMessage.getSiteId());
alarm.setAlarmTime(LocalDateTime.now());
pushErrorMessage(alarmMessage.getDeviceName(), JsonUtils.toJsonString(alarm));
alarm.setDeviceAlias(deviceName);
// 单条保存,数据库生成的 ID 会回填到 alarm
alarmMapper.insert(alarm);
pushErrorMessage(
alarmMessage.getDeviceName(),
JsonUtils.toJsonString(alarm));
list.add(alarm);
}
alarmMapper.saveOrUpdateBatch(list);
return list;
// todo 推送websocket?
WebOlineStatusMessageDTO dto = new WebOlineStatusMessageDTO();
dto.setAlarms(list);
dto.setDeviceId(deviceId);
dto.setType(MesType.device_error_push);
NettyDevice device = deviceSessionManager.getDevice(deviceId);
if (device != null && device.getDevice() != null) {
dto.setDeviceAlias(device.getDevice().getDeviceAlias());
}
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());
}
}
}
try {
if (device != null && device.getDevice() != null) {
Long siteId = device.getDevice().getSiteId();
websocketMesDispather.mapMessageDispather(siteId,
JsonUtils.toJsonString(dto));
}
} catch (Exception e) {
log.error("实时地图数据websocket推送失败: siteId={}, error={}", e);
}
return list;
}
public void pushErrorMessage(String deviceId, String dto) {
try {
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC,
// deviceId), dto);
// List<NettyDevice> controlMasters =
// sessionManager.getAllSlaveControl(deviceId);
// if (!CollectionUtils.isEmpty(controlMasters)) {

View File

@@ -43,7 +43,7 @@ public class HostComputerService {
CompletableFuture<Boolean> future = new CompletableFuture<>();
// 一个设备同时只允许一个模式切换请求
CompletableFuture<Boolean> oldFuture = GlobalMemory.modeFutureMap.putIfAbsent(deviceId, future);
CompletableFuture<Boolean> oldFuture = GlobalMemory.eStopFutureMap.putIfAbsent(deviceId, future);
if (oldFuture != null) {
throw new ServiceException("设备正在执行模式切换,请稍后再试");
@@ -59,11 +59,12 @@ public class HostComputerService {
return result;
} catch (Exception e) {
throw new ServiceException("设备模式切换失败");
log.error("切换急停失败", e);
throw new ServiceException("急停切换失败");
} finally {
// 无论成功、失败还是超时,都清理 Future
GlobalMemory.modeFutureMap.remove(deviceId, future);
GlobalMemory.eStopFutureMap.remove(deviceId, future);
}
}
@@ -112,6 +113,7 @@ public class HostComputerService {
return result;
} catch (Exception e) {
log.error("切换模式失败", e);
throw new ServiceException("设备模式切换失败");
} finally {