From 08888ab6122f02e743fd6499f3ff3d268677ae57 Mon Sep 17 00:00:00 2001 From: rqian <1206436827@qq.com> Date: Mon, 16 Nov 2026 13:38:56 +0800 Subject: [PATCH] #update --- .../java/com/maibu/constant/Constant.java | 2 +- .../com/maibu/constant/NettyCacheKey.java | 2 + .../maibu/core/business/DevicePlanTask.java | 5 + .../core/business/DeviceRunStatistics.java | 2 +- .../core/business/DeviceStatusRecordDTO.java | 5 +- .../business/ErrorIdentificationStandard.java | 2 + .../com/maibu/core/business/ErrorRecord.java | 21 ++ .../core/business/alarm_center/Alarm.java | 2 +- .../core/business/device/NettyDevice.java | 61 ++++ .../core/business/dto/DeviceMapPushDTO.java | 2 + .../business/dto/VehicleMessageRecordDTO.java | 14 + .../maibu/core/host/HostEstopChangeDTO.java | 16 + .../com/maibu/core/host/HostFaultPostDTO.java | 12 + .../maibu/core/host/HostFaultPostDetail.java | 17 ++ .../core/host/HostModeChangeReplyDTO.java | 4 +- .../core/host/HostTaskStatusDetailDTO.java | 2 + .../core/host/ObstacleDetectionData.java | 1 + .../com/maibu/core/host/ObstaclePostDTO.java | 5 +- .../java/com/maibu/core/host/ParamDetail.java | 2 +- .../com/maibu/core/host/VehicleMessage.java | 20 ++ .../mapper/DeviceRunStatisticsMapper.java | 0 .../java/com/maibu/memory/GlobalMemory.java | 3 +- .../java/com/maibu/memory/SiteMemory.java | 78 +++++ .../com/maibu/mqtt/HostMessageHandler.java | 278 ++++++++++++++++-- .../main/java/com/maibu/mqtt/MqttTopic.java | 6 + .../controller/DeviceTaskController.java | 64 ++-- .../netty/handler/CommandForwardHandler.java | 8 +- .../netty/handler/DataToDataBaseHandler.java | 10 +- .../netty/handler/DeviceConnectHandler.java | 2 +- .../com/maibu/scheduled/ScheduledTask.java | 84 +++--- .../com/maibu/service/AlertPushService.java | 115 ++++---- .../service/DevicePlanTaskMonitorService.java | 36 ++- .../com/maibu/service/DeviceTaskService.java | 22 +- .../maibu/service/DeviceThreadService.java | 155 ++++------ .../java/com/maibu/utils/CompareUtils.java | 184 +++++++++--- .../src/main/resources/errorStandard.json | 114 ++++++- .../maibu/controller/DeviceController.java | 31 +- .../controller/HostComputerController.java | 7 +- .../controller/WorkRecordController.java | 9 +- .../com/maibu/service/IDeviceService.java | 3 + .../maibu/service/impl/DeviceServiceImpl.java | 44 ++- .../service/impl/HostComputerService.java | 57 ++-- .../maibu/mapper/VehicleMessageMapper.java | 11 + .../java/com/maibu/utils/ControlUtils.java | 21 +- 44 files changed, 1162 insertions(+), 377 deletions(-) create mode 100644 maibu-common/src/main/java/com/maibu/core/business/ErrorRecord.java create mode 100644 maibu-common/src/main/java/com/maibu/core/business/dto/VehicleMessageRecordDTO.java create mode 100644 maibu-common/src/main/java/com/maibu/core/host/HostEstopChangeDTO.java create mode 100644 maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDTO.java create mode 100644 maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDetail.java rename {maibu-service/maibu-iot-service => maibu-common}/src/main/java/com/maibu/mapper/DeviceRunStatisticsMapper.java (100%) create mode 100644 maibu-service/maibu-system-service/src/main/java/com/maibu/mapper/VehicleMessageMapper.java diff --git a/maibu-common/src/main/java/com/maibu/constant/Constant.java b/maibu-common/src/main/java/com/maibu/constant/Constant.java index a416705..20b68d7 100644 --- a/maibu-common/src/main/java/com/maibu/constant/Constant.java +++ b/maibu-common/src/main/java/com/maibu/constant/Constant.java @@ -30,7 +30,7 @@ public class Constant { public static final Long hostOfflineInterval = 10000L; // 单位毫秒 // ==================== 远程控制 ==================== - public static final String protocol_version = "1.4.5"; + public static final String protocol_version = "1.4.6"; public static final String remote_control_msg_prefix = "remote-msg"; public static final String remote_control_cmd_prefix = "remote-cmd"; } diff --git a/maibu-common/src/main/java/com/maibu/constant/NettyCacheKey.java b/maibu-common/src/main/java/com/maibu/constant/NettyCacheKey.java index 6673423..56e381b 100644 --- a/maibu-common/src/main/java/com/maibu/constant/NettyCacheKey.java +++ b/maibu-common/src/main/java/com/maibu/constant/NettyCacheKey.java @@ -4,6 +4,8 @@ public class NettyCacheKey { public static final String deviceRunningStatusKey = "running_status:"; + public static final String vehicleMessageKey = "vehicle_message:"; + public static final String latestPositonKey = "latest_position:"; } diff --git a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java index 4dbeced..62a90b1 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DevicePlanTask.java @@ -55,4 +55,9 @@ public class DevicePlanTask extends OrgBaseDO { @TableField(exist = false) private RestPoint backTaskPoint; + @TableField(exist = false) + private double taskDistance; // 记录当前任务的累计里程 + @TableField(exist = false) + private double taskTime; // s + } diff --git a/maibu-common/src/main/java/com/maibu/core/business/DeviceRunStatistics.java b/maibu-common/src/main/java/com/maibu/core/business/DeviceRunStatistics.java index 331f035..69b671d 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DeviceRunStatistics.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DeviceRunStatistics.java @@ -25,7 +25,7 @@ public class DeviceRunStatistics implements Serializable { private Double distance; //作业距离 - private Long time; //时长 分钟 + private Double time; //时长 分钟 private String deviceId; diff --git a/maibu-common/src/main/java/com/maibu/core/business/DeviceStatusRecordDTO.java b/maibu-common/src/main/java/com/maibu/core/business/DeviceStatusRecordDTO.java index 2e9fb3c..a2a5b2d 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/DeviceStatusRecordDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/business/DeviceStatusRecordDTO.java @@ -1,11 +1,12 @@ package com.maibu.core.business; -import lombok.Data; - import java.util.List; +import lombok.Data; + @Data public class DeviceStatusRecordDTO { private List histories; + private long lastRecordTime; } diff --git a/maibu-common/src/main/java/com/maibu/core/business/ErrorIdentificationStandard.java b/maibu-common/src/main/java/com/maibu/core/business/ErrorIdentificationStandard.java index 93619a3..307cc18 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/ErrorIdentificationStandard.java +++ b/maibu-common/src/main/java/com/maibu/core/business/ErrorIdentificationStandard.java @@ -24,4 +24,6 @@ public class ErrorIdentificationStandard extends OrgBaseDO { private String errorCode; private ErrorLevel errorLevel; private String suggestion; + + private int codeIndex; //对应解析code某一位 } diff --git a/maibu-common/src/main/java/com/maibu/core/business/ErrorRecord.java b/maibu-common/src/main/java/com/maibu/core/business/ErrorRecord.java new file mode 100644 index 0000000..7e76adb --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/business/ErrorRecord.java @@ -0,0 +1,21 @@ +package com.maibu.core.business; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.maibu.core.domain.OrgNoUserDO; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("iot_error_record") +public class ErrorRecord extends OrgNoUserDO { + @TableId(type = IdType.AUTO) + private Long id; + private String deviceId; + private String errorDescription; + private String errorName; + private Long standardId; +} diff --git a/maibu-common/src/main/java/com/maibu/core/business/alarm_center/Alarm.java b/maibu-common/src/main/java/com/maibu/core/business/alarm_center/Alarm.java index 53da9d4..7687c2e 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/alarm_center/Alarm.java +++ b/maibu-common/src/main/java/com/maibu/core/business/alarm_center/Alarm.java @@ -46,7 +46,7 @@ public class Alarm extends TenantBaseDO { @Excel(name = "告警内容") private String alarmContent; - private String timeValues; //告警时上报的值 + private String timeValues; // 告警时上报的值 @ApiModelProperty("设备ID") @Excel(name = "设备ID", cellType = Excel.ColumnType.NUMERIC) diff --git a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java index 086b791..c8069bc 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java +++ b/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java @@ -1,5 +1,6 @@ package com.maibu.core.business.device; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.fasterxml.jackson.annotation.JsonIgnore; import com.maibu.constant.Constant; import com.maibu.core.business.*; @@ -8,12 +9,14 @@ import com.maibu.core.business.path.RoutePlanSendEntity; import com.maibu.core.enums.ConnectorType; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.core.enums.RouteType; +import com.maibu.core.host.HostEstopChangeDTO; import com.maibu.core.host.HostModeChangeDTO; import com.maibu.core.host.HostWorkRecordCreateDTO; import com.maibu.core.host.MutiPointEntity; import com.maibu.core.host.PointEntity; import com.maibu.core.ota.DeviceOtaFirmware; import com.maibu.mapper.DevicePlanTaskMapper; +import com.maibu.mapper.DeviceRunStatisticsMapper; import com.maibu.mapper.RegionConsecutiveTaskRecordMapper; import com.maibu.mapper.WorkRecordMapper; import com.maibu.memory.GlobalMemory; @@ -77,6 +80,9 @@ public class NettyDevice extends Connector { @JsonIgnore private WorkRecordMapper workRecordMapper = SpringUtils.getBean(WorkRecordMapper.class); + @JsonIgnore + private DeviceRunStatisticsMapper runStatisticsMapper = SpringUtils.getBean(DeviceRunStatisticsMapper.class); + @JsonIgnore private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); @@ -127,11 +133,40 @@ public class NettyDevice extends Connector { return sb.toString().trim(); } + public void updateWorkArea() { + + double taskDistance = task.getTaskDistance(); + double taskTime = task.getTaskTime(); + double workArea = taskDistance * 0.8; + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(DeviceRunStatistics::getDeviceId, task.getDeviceId()); + DeviceRunStatistics existing = runStatisticsMapper + .selectOne(queryWrapper); + if (existing != null) { + existing.setDistance( + existing.getDistance() + taskDistance); + existing.setWorkArea( + existing.getWorkArea() + workArea); + existing.setTime(existing.getTime() + taskTime); // 累加时长,单位为分钟 + } else { + existing = new DeviceRunStatistics(); + existing.setDistance(taskDistance); + existing.setWorkArea(workArea); + existing.setTime(taskTime); // 累加时长,单位为分钟 + existing.setDeviceId(task.getDeviceId()); + } + runStatisticsMapper.saveOrUpdate(existing); + } + public synchronized Long finishTask() { // sendPathCommand((byte) 0x01, (short) 0, 0.00d, 0.00d, (short) 0); long finishId = task.getId(); task.setTaskStaus(DeviceTaskStaus.FINISH); task.setFinishTime(LocalDateTime.now()); + + // 更新累计里程 + updateWorkArea(); + devicePlanTaskMapper.saveOrUpdate(task); SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId()); @@ -190,6 +225,9 @@ public class NettyDevice extends Connector { Long taskId = task.getId(); task.setTaskStaus(DeviceTaskStaus.CANCELED); task.setUpdateTime(LocalDateTime.now()); + + // 更新累计里程 + updateWorkArea(); devicePlanTaskMapper.saveOrUpdate(task); SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId()); siteMemory.removeDevicePlanPrepare(task); @@ -555,4 +593,27 @@ public class NettyDevice extends Connector { JsonUtils.toJsonString(payload)); } + /** + * 急停更新 + * + * @param deviceId + * @throws MqttException + */ + public void eStopChange(String deviceId, Integer eStop) throws MqttException { + HostEstopChangeDTO payload = new HostEstopChangeDTO(); + payload.setSn(deviceId); + payload.setTimestamp(System.currentTimeMillis()); + payload.setMessage_id("eStopChange_" + System.currentTimeMillis()); + payload.setCommand_id("eStopChangeCommand_ " + System.currentTimeMillis()); + payload.setProtocol_version(Constant.protocol_version); + Map data = new HashMap<>(); + data.put("emergency_stop", eStop); + payload.setData(data); + + GlobalMemory.customMqttDeviceMonitor.publish( + mqttClientId, + String.format(MqttTopic.MOWER_ESTOP_SET, deviceId), + JsonUtils.toJsonString(payload)); + } + } diff --git a/maibu-common/src/main/java/com/maibu/core/business/dto/DeviceMapPushDTO.java b/maibu-common/src/main/java/com/maibu/core/business/dto/DeviceMapPushDTO.java index 5cbc519..36dd827 100644 --- a/maibu-common/src/main/java/com/maibu/core/business/dto/DeviceMapPushDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/business/dto/DeviceMapPushDTO.java @@ -19,6 +19,8 @@ public class DeviceMapPushDTO { private Integer cm;// 控制模式 manual_remote|auto + private Integer sm;// 系统控制的模式 只有2,3 远程遥控 自动任务; + private String ms; // 运动状态 moving|stopped|blocked } diff --git a/maibu-common/src/main/java/com/maibu/core/business/dto/VehicleMessageRecordDTO.java b/maibu-common/src/main/java/com/maibu/core/business/dto/VehicleMessageRecordDTO.java new file mode 100644 index 0000000..4336b35 --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/business/dto/VehicleMessageRecordDTO.java @@ -0,0 +1,14 @@ +package com.maibu.core.business.dto; + +import lombok.Data; + +import java.util.List; + +import com.maibu.core.host.VehicleMessage; + +@Data +public class VehicleMessageRecordDTO { + private List histories; + + private long lastRecordTime; +} diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostEstopChangeDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostEstopChangeDTO.java new file mode 100644 index 0000000..3c6bad9 --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/host/HostEstopChangeDTO.java @@ -0,0 +1,16 @@ +package com.maibu.core.host; + +import java.util.Map; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class HostEstopChangeDTO extends HostBase { + + private String command_id; + + private Map data; // map key control_mode 2=自动任务,3=远程遥控 + +} diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDTO.java new file mode 100644 index 0000000..15ca52e --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDTO.java @@ -0,0 +1,12 @@ +package com.maibu.core.host; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class HostFaultPostDTO extends HostBase { + + private HostFaultPostDetail data; + +} diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDetail.java b/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDetail.java new file mode 100644 index 0000000..08e208d --- /dev/null +++ b/maibu-common/src/main/java/com/maibu/core/host/HostFaultPostDetail.java @@ -0,0 +1,17 @@ +package com.maibu.core.host; + +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class HostFaultPostDetail extends HostBase { + + private Boolean active; + private String fault_code; + private String message; + private String related_message_id; + private String severity; + private String source; + +} diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostModeChangeReplyDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostModeChangeReplyDTO.java index a1b93c3..e9f4646 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/HostModeChangeReplyDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/host/HostModeChangeReplyDTO.java @@ -7,10 +7,12 @@ import lombok.EqualsAndHashCode; @Data public class HostModeChangeReplyDTO extends HostBase { - private Boolean accepted; + private Boolean accepted; private String code; private String message; + private Integer mode; + } diff --git a/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDetailDTO.java b/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDetailDTO.java index 4d5c43c..22e80fe 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDetailDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/host/HostTaskStatusDetailDTO.java @@ -22,4 +22,6 @@ public class HostTaskStatusDetailDTO { private double distance_traveled_m; private double execution_time_s; private Integer cells_completed; + + } diff --git a/maibu-common/src/main/java/com/maibu/core/host/ObstacleDetectionData.java b/maibu-common/src/main/java/com/maibu/core/host/ObstacleDetectionData.java index 9d0cf6e..bc1e0af 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/ObstacleDetectionData.java +++ b/maibu-common/src/main/java/com/maibu/core/host/ObstacleDetectionData.java @@ -9,6 +9,7 @@ import lombok.Data; @Data public class ObstacleDetectionData { + private MesType type; /** diff --git a/maibu-common/src/main/java/com/maibu/core/host/ObstaclePostDTO.java b/maibu-common/src/main/java/com/maibu/core/host/ObstaclePostDTO.java index c183394..9d6d3bc 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/ObstaclePostDTO.java +++ b/maibu-common/src/main/java/com/maibu/core/host/ObstaclePostDTO.java @@ -1,6 +1,5 @@ package com.maibu.core.host; - import lombok.Data; import lombok.EqualsAndHashCode; @@ -8,6 +7,6 @@ import lombok.EqualsAndHashCode; @Data public class ObstaclePostDTO extends HostBase { - private ObstacleDetectionData fusion_obstacle; - + private ObstacleDetectionData data; + } diff --git a/maibu-common/src/main/java/com/maibu/core/host/ParamDetail.java b/maibu-common/src/main/java/com/maibu/core/host/ParamDetail.java index 73779b1..12ee666 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/ParamDetail.java +++ b/maibu-common/src/main/java/com/maibu/core/host/ParamDetail.java @@ -13,6 +13,6 @@ public class ParamDetail { private int chassis_lift; // 底盘升降 0:停止 1:升 2:降 private int cutter; // 割刀加减速 0:停止 1:加速 2:减速 private int ignition; // 点火熄火 0:停止 1:点火 2:熄火 - private int emergency_stop; // 急停 0:正常 1:急停 + // private int emergency_stop; // 急停 0:正常 1:急停 private int valid_for_ms; // 指令有效时间,单位毫秒 } diff --git a/maibu-common/src/main/java/com/maibu/core/host/VehicleMessage.java b/maibu-common/src/main/java/com/maibu/core/host/VehicleMessage.java index 81430a6..ce4a89b 100644 --- a/maibu-common/src/main/java/com/maibu/core/host/VehicleMessage.java +++ b/maibu-common/src/main/java/com/maibu/core/host/VehicleMessage.java @@ -1,10 +1,24 @@ 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; +import com.baomidou.mybatisplus.annotation.TableName; + import lombok.Data; @Data +@TableName("iot_vehicle_message") public class VehicleMessage { + /** + * 主键 + */ + @TableId(type = IdType.AUTO) + private Long id; + private String deviceId; private double cutter_speed;// 割刀实际转速 @@ -41,4 +55,10 @@ public class VehicleMessage { private double linear_speed; // 实时线速度 private double angular_speed; // 实时角速度 + private Integer systemMode; // 当前 没有遥控器控制的模式 control_mode 为0,当前的系统控制的模式 只有2,3 + + private LocalDateTime createTime; + + private Long error_code; // 暂时用于上报错误 + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DeviceRunStatisticsMapper.java b/maibu-common/src/main/java/com/maibu/mapper/DeviceRunStatisticsMapper.java similarity index 100% rename from maibu-service/maibu-iot-service/src/main/java/com/maibu/mapper/DeviceRunStatisticsMapper.java rename to maibu-common/src/main/java/com/maibu/mapper/DeviceRunStatisticsMapper.java diff --git a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java index a4a1963..9e916d1 100644 --- a/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java @@ -120,7 +120,8 @@ public class GlobalMemory { MqttTopic.MOWER_OBSTACLE, // 障碍物 MqttTopic.MOWER_MODE_REPLY, // 模式切换回复 MqttTopic.MOWER_FAULT_POST, // 故障上报 - MqttTopic.MOWER_FAULT_RECOVERY_REPLY // 故障恢复回复 + MqttTopic.MOWER_FAULT_RECOVERY_REPLY, // 故障恢复回复 + MqttTopic.MOWER_ESTOP_REPLY // 急停的回复 )); deviceConfig.setHandlerType(Constant.mqttHandleKey); // 唯一的 用于处理上位机mqtt的 customMqttDeviceMonitor.registerDevice(deviceConfig); diff --git a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java index f618a98..6f51e72 100644 --- a/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java +++ b/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.lang3.StringUtils; import org.eclipse.paho.client.mqttv3.MqttClient; @@ -23,6 +24,7 @@ import com.maibu.core.business.IoTCommonDevice; import com.maibu.core.business.OrderModel; import com.maibu.core.business.Product; import com.maibu.core.business.RegionConsecutiveTaskRecord; +import com.maibu.core.business.alarm_center.AlarmMessage; import com.maibu.core.business.dto.ConsecutiveTaskDTO; import com.maibu.core.business.dto.DeviceMapPushDTO; import com.maibu.core.domain.entity.SysSite; @@ -80,6 +82,71 @@ public class SiteMemory { public static final ConcurrentHashMap regionConsecutiveTaskMap = new ConcurrentHashMap<>(); + public static final ConcurrentHashMap> alarmMap = new ConcurrentHashMap<>(); + + public void saveAlarm(String deviceSn, AlarmMessage alarmMessage) { + if (deviceSn == null || alarmMessage == null) { + return; + } + + alarmMap.compute(deviceSn, (key, list) -> { + if (list == null) { + list = new CopyOnWriteArrayList<>(); + } + + list.add(alarmMessage); + return list; + }); + } + + /** + * 批量替换设备告警 + * + * @param deviceSn 设备SN + * @param alarms 新的告警集合 + */ + public void replaceAlarms(String deviceSn, List alarms) { + if (deviceSn == null) { + return; + } + + if (alarms == null || alarms.isEmpty()) { + alarmMap.remove(deviceSn); + return; + } + + alarmMap.put(deviceSn, new CopyOnWriteArrayList<>(alarms)); + } + + /** + * 根据设备SN和告警编号查询告警 + */ + public AlarmMessage getAlarm(String deviceSn, String alarmNo) { + if (deviceSn == null || alarmNo == null) { + return null; + } + + List list = alarmMap.get(deviceSn); + if (list == null || list.isEmpty()) { + return null; + } + + return list.stream() + .filter(x -> alarmNo.equals(x.getNo())) + .findFirst() + .orElse(null); + } + + /** + * 根据设备SN删除所有告警 + */ + public void removeAlarms(String deviceSn) { + if (deviceSn == null) { + return; + } + alarmMap.remove(deviceSn); + } + public void saveRegionConsecutiveTask(String deviceId, ConsecutiveTaskDTO dto, String username) { RegionConsecutiveTaskRecord record = new RegionConsecutiveTaskRecord(); record.setDeviceId(deviceId); @@ -139,7 +206,18 @@ public class SiteMemory { return vehicleMessageMap.get(deviceId); } + public void saveVehicleSystemMode(String deviceId, Integer systemMode) { + VehicleMessage vehicleMessage = getVehicleMessage(deviceId); + if (vehicleMessage != null) { + vehicleMessage.setSystemMode(systemMode); + } + } + public void saveVehicleMessage(String deviceId, VehicleMessage vehicleMessage) { + VehicleMessage oldVehicle = getVehicleMessage(deviceId); + if (oldVehicle != null) { + vehicleMessage.setSystemMode(oldVehicle.getSystemMode()); + } vehicleMessage.setDeviceId(deviceId); vehicleMessageMap.put(deviceId, vehicleMessage); } diff --git a/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java b/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java index 348939c..a0530a6 100644 --- a/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java +++ b/maibu-common/src/main/java/com/maibu/mqtt/HostMessageHandler.java @@ -1,19 +1,43 @@ package com.maibu.mqtt; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + +import org.eclipse.paho.client.mqttv3.MqttException; +import org.springframework.util.CollectionUtils; + import com.maibu.constant.Constant; import com.maibu.constant.NettyCacheKey; +import com.maibu.core.business.DevicePlanTask; 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.ErrorRecord; +import com.maibu.core.business.alarm_center.AlarmMessage; import com.maibu.core.business.device.DeviceStatusDetail; import com.maibu.core.business.device.NettyDevice; import com.maibu.core.business.dto.DeviceMapPushDTO; +import com.maibu.core.business.dto.VehicleMessageRecordDTO; import com.maibu.core.business.dto.WebDeviceTaskStatusMessageDTO; -import com.maibu.core.business.dto.WebMapMessageDTO; import com.maibu.core.business.dto.WebStatusMessageDTO; import com.maibu.core.business.inter.WebsocketMesDispather; import com.maibu.core.enums.DeviceTaskStaus; +import com.maibu.core.enums.ErrorSource; import com.maibu.core.enums.MesType; -import com.maibu.core.host.*; +import com.maibu.core.enums.RespondCode; +import com.maibu.core.host.HeartBeatDTO; +import com.maibu.core.host.HostLocationRelTimeDTO; +import com.maibu.core.host.HostModeChangeReplyDTO; +import com.maibu.core.host.HostNavigationReplyDTO; +import com.maibu.core.host.HostTaskStatusDTO; +import com.maibu.core.host.HostVehicleRelTimeDTO; +import com.maibu.core.host.LocationMessage; +import com.maibu.core.host.ObstaclePostDTO; +import com.maibu.core.host.VehicleMessage; import com.maibu.core.redis.RedisCache; import com.maibu.enums.DeviceStatusEnum; import com.maibu.memory.DeviceSessionManager; @@ -22,13 +46,8 @@ import com.maibu.memory.SiteMemory; import com.maibu.utils.StringUtils; import com.maibu.utils.json.JsonUtils; import com.maibu.utils.spring.SpringUtils; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.util.CollectionUtils; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; +import lombok.extern.slf4j.Slf4j; /** * mqtt相关的 上位机处理器 @@ -44,6 +63,8 @@ public class HostMessageHandler implements CustomMqttMessageHandler { private final RedisCache redisCache = SpringUtils.getBean(RedisCache.class); + private final Long recordInterval = 2000L; + @Override public String getHandlerType() { return Constant.mqttHandleKey; @@ -121,6 +142,9 @@ public class HostMessageHandler implements CustomMqttMessageHandler { case "fault_recovery_reply": handleFaultRecoveryReply(deviceId, topic, payload); break; + case "eStop_reply": + handleEstopReply(deviceId, topic, payload); + break; default: log.debug("割草机消息: deviceId={}, topic={}, action={}", deviceId, topic, action); @@ -264,6 +288,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler { dto.setCm(vehicleMessage.getControl_mode()); dto.setMs(vehicleMessage.getMotion()); dto.setB(vehicleMessage.getBattery_percentage()); + dto.setSm(vehicleMessage.getSystemMode()); } dto.setWk(nettyDevice.getTask() != null ? nettyDevice.getTask().getWorkName() : ""); siteMemory.saveMapPushDTO(deviceId, dto); @@ -454,7 +479,6 @@ public class HostMessageHandler implements CustomMqttMessageHandler { try { HostVehicleRelTimeDTO vehicleRelTimeDTO = JsonUtils.parseObject(payload, HostVehicleRelTimeDTO.class); if (vehicleRelTimeDTO != null) { - // todo 更新里程数 里程数 * 割幅0.8 vehicleRelTimeDTO.getData().getTotal_work_distance(); NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId); @@ -473,6 +497,16 @@ public class HostMessageHandler implements CustomMqttMessageHandler { siteMemory.saveRunStatistics(deviceRunStatistics); siteMemory.saveVehicleMessage(deviceId, vehicleRelTimeDTO.getData()); + + // 故障处理 + Long errorCode = vehicleRelTimeDTO.getData().getError_code(); + if (errorCode != null && errorCode != 0) { + List standards = parseErrorCode(errorCode, siteMemory); + List alMessages = parseAlarm(standards, deviceId, siteId, orgId); + siteMemory.replaceAlarms(deviceId, alMessages); + } else { + siteMemory.replaceAlarms(deviceId, new ArrayList<>()); + } } } @@ -513,6 +547,164 @@ public class HostMessageHandler implements CustomMqttMessageHandler { } } + /** + * 根据设备故障码解析告警 + * + * @param errorCode 设备上报的十进制故障掩码(uint32) + * @param standards 故障标准配置集合 + * @param deviceName 设备名称 + * @param deviceSn 设备SN + * @param siteId 场站ID + * @param orgId 组织ID + * @return 告警集合 + */ + public static List parseAlarm( + List standards, + String deviceId, + Long siteId, + Long orgId) { + + List result = new ArrayList<>(); + + if (standards == null || standards.isEmpty()) { + return result; + } + + for (ErrorIdentificationStandard standard : standards) { + + if (standard == null) { + continue; + } + + AlarmMessage alarm = new AlarmMessage(); + + alarm.setNo(standard.getErrorCode()); + alarm.setName(standard.getErrorName()); + alarm.setLevel(standard.getErrorLevel()); + alarm.setContent(standard.getErrorDescription()); + alarm.setSuggestion(standard.getSuggestion()); + + alarm.setTime(LocalDateTime.now()); + alarm.setDeviceName(deviceId); + alarm.setDeviceSn(deviceId); + alarm.setSiteId(siteId); + alarm.setOrgId(orgId); + + result.add(alarm); + + } + + return result; + } + + public void addStandards(int index, List errorList, + List eStandards) { + ErrorIdentificationStandard eStandard = eStandards.stream().filter(x -> x.getCodeIndex() == index).findFirst() + .orElse(null); + if (eStandard != null) { + errorList.add(eStandard); + } + } + + /** + * 根据设备故障码解析故障信息 + * + * @param errorCode 十进制故障码 + * @return 故障描述集合 + */ + public List parseErrorCode(long errorCode, SiteMemory siteMemory) { + List errorList = new ArrayList<>(); + + if (errorCode <= 0 || siteMemory == null) { + return errorList; + } + List eStandards = siteMemory.getStandards().get(ErrorSource.MOWER); + // bit0:遥控器链路超时 + if ((errorCode & (1L << 0)) != 0) { + addStandards(0, errorList, eStandards); + } + + // bit2:整车控制器心跳反馈超时 + if ((errorCode & (1L << 2)) != 0) { + addStandards(2, errorList, eStandards); + } + + // bit3:无效工作模式 + if ((errorCode & (1L << 3)) != 0) { + addStandards(3, errorList, eStandards); + } + + // bit4:控制器请求慢停或停车 + if ((errorCode & (1L << 4)) != 0) { + addStandards(4, errorList, eStandards); + } + + // bit5:底盘轮速反馈超时 + if ((errorCode & (1L << 5)) != 0) { + addStandards(5, errorList, eStandards); + } + + // bit6:上位机控制指令超时 + if ((errorCode & (1L << 6)) != 0) { + addStandards(6, errorList, eStandards); + } + + // bit7:左侧电机电流超限 + if ((errorCode & (1L << 7)) != 0) { + addStandards(7, errorList, eStandards); + } + + // bit8:右侧电机电流超限 + if ((errorCode & (1L << 8)) != 0) { + addStandards(8, errorList, eStandards); + } + + // bit9:母线电流超限 + if ((errorCode & (1L << 9)) != 0) { + addStandards(9, errorList, eStandards); + } + + // bit10:俯仰倾角超限 + if ((errorCode & (1L << 10)) != 0) { + addStandards(10, errorList, eStandards); + } + + return errorList; + } + + public void recordRealtimeMessage(String deviceId, VehicleMessage vehicleMessage) { + String key = NettyCacheKey.vehicleMessageKey + deviceId; + VehicleMessageRecordDTO recordDto = redisCache.getCacheObject(key); + boolean record = false; + List histories; + if (recordDto == null) { + recordDto = new VehicleMessageRecordDTO(); + histories = new ArrayList<>(); + record = true; + } else { + long lastRecordTime = recordDto.getLastRecordTime(); + histories = recordDto.getHistories(); + if (System.currentTimeMillis() - lastRecordTime >= recordInterval) { + record = true; + } + } + if (record) { + if (histories == null) { + histories = new ArrayList<>(); + } + vehicleMessage.setCreateTime(LocalDateTime.now()); + histories.add(vehicleMessage); + recordDto.setHistories(histories); + recordDto.setLastRecordTime(System.currentTimeMillis()); + redisCache.setCacheObject(key, recordDto); + + // todo 记录到InfluxDB 是否删除redis中的记录 目前先保留最近一次的记录在redis中 + // MowerRealTimeData data = processInfluxData(deviceID, split); + // String line = InfluxSqlBuilder.buildLine(data); + // GlobalMemory.influxDBUtil.write(line); + } + } + /** * 处理心跳 * topic: mower/{deviceId}/event/heartbeat/post @@ -567,10 +759,15 @@ public class HostMessageHandler implements CustomMqttMessageHandler { // NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId); // nettyDevice.finishTask(); // } - // if("running".equals(dto.getStatus())){ - // NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId); - // nettyDevice.finishTask(); - // } + if ("running".equals(dto.getStatus())) { + // 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()); + } + + } // 任务进度 百分比 Long siteId = nettyDevice.getDevice().getSiteId(); Long orgId = nettyDevice.getDevice().getOrgId(); @@ -717,16 +914,18 @@ public class HostMessageHandler implements CustomMqttMessageHandler { log.debug("【障碍物提示】deviceId={}, payload={}", deviceId, payload); - ObstacleDetectionData data = JsonUtils.parseObject(payload, ObstacleDetectionData.class); + ObstaclePostDTO data = JsonUtils.parseObject(payload, ObstaclePostDTO.class); + if (data == null || data.getData() == null) + return; List controlMasters = deviceSessionManager .getAllSlaveControl(deviceId); - data.setType(MesType.detectionReport); + data.getData().setType(MesType.detectionReport); if (!CollectionUtils.isEmpty(controlMasters)) { for (NettyDevice x : controlMasters) { try { - websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(data)); + websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(data.getData())); } catch (Exception e) { log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(), e.getMessage(), e); @@ -738,7 +937,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler { if (device != null && device.getDevice() != null) { Long siteId = device.getDevice().getSiteId(); websocketMesDispather.mapMessageDispather(siteId, - JsonUtils.toJsonString(data)); + JsonUtils.toJsonString(data.getData())); } } catch (Exception e) { log.error("实时地图数据websocket推送失败: siteId={}, error={}", e); @@ -746,7 +945,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler { try { GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_OBSTACLE_PUSH_TOPIC, deviceId), - JsonUtils.toJsonString(data)); + JsonUtils.toJsonString(data.getData())); } catch (MqttException e) { log.error("实时数据websocket推送失败: deviceId={}, error={}", deviceId, e.getMessage(), e); } @@ -757,6 +956,18 @@ public class HostMessageHandler implements CustomMqttMessageHandler { log.debug("【模式切换回复】deviceId={}, payload={}", deviceId, payload); HostModeChangeReplyDTO data = JsonUtils.parseObject(payload, HostModeChangeReplyDTO.class); + if (data != null && data.getAccepted() != null) { + + NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId); + if (nettyDevice != null && nettyDevice.getDevice() != null) { + Long siteId = nettyDevice.getDevice().getSiteId(); + Long orgId = nettyDevice.getDevice().getOrgId(); + SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); + if (siteMemory != null) { + siteMemory.saveVehicleSystemMode(deviceId, data.getMode()); + } + } + } CompletableFuture future = GlobalMemory.modeFutureMap.get(deviceId); @@ -791,6 +1002,31 @@ 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 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 future = GlobalMemory.modeFutureMap.get(deviceId); + + if (future != null && data != null) { + future.complete(data.getAccepted()); + } + } + /** * 从 Topic 中解析 deviceId * Topic 格式:mower/{deviceId}/... @@ -845,12 +1081,14 @@ public class HostMessageHandler implements CustomMqttMessageHandler { return "upgrade_reply"; if (remaining.equals("perception/obstacle/post")) return "obstacle_post"; - if (remaining.equals("control/mode/set/reply")) + if (remaining.equals("control/mode/reply")) return "mode_reply"; if (remaining.equals("event/fault/post")) return "fault_post"; if (remaining.equals("fault/recovery/reply")) return "fault_recovery_reply"; + if (remaining.equals("control/emergency_stop/reply")) + return "eStop_reply"; return null; } diff --git a/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java b/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java index 6ac8392..27baf3d 100644 --- a/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java +++ b/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java @@ -127,6 +127,12 @@ public class MqttTopic { // 故障恢复回复 public static final String MOWER_FAULT_RECOVERY_REPLY = "mower/+/fault/recovery/reply"; + /** 设置无遥控器时候的急停(平台->设备) */ + 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"; + /** * 格式化 Topic 模板,将 %s 替换为设备ID * diff --git a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java index 3ecbee9..5561274 100644 --- a/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java +++ b/maibu-netty-server/src/main/java/com/maibu/controller/DeviceTaskController.java @@ -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(); } diff --git a/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java b/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java index e4116a8..4cf760c 100644 --- a/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java +++ b/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java @@ -114,10 +114,12 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler { 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()); diff --git a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java index ecdb468..41c14ef 100644 --- a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java +++ b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java @@ -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; diff --git a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java index 6fbef16..202dd82 100644 --- a/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java +++ b/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java @@ -160,7 +160,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler { 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()); } diff --git a/maibu-netty-server/src/main/java/com/maibu/scheduled/ScheduledTask.java b/maibu-netty-server/src/main/java/com/maibu/scheduled/ScheduledTask.java index 85341e3..bb9ff2e 100644 --- a/maibu-netty-server/src/main/java/com/maibu/scheduled/ScheduledTask.java +++ b/maibu-netty-server/src/main/java/com/maibu/scheduled/ScheduledTask.java @@ -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 keys = redisCache.keys(key); + String key = NettyCacheKey.vehicleMessageKey; + // Collection keys = redisCache.keys(key); Collection 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)); // } } \ No newline at end of file diff --git a/maibu-netty-server/src/main/java/com/maibu/service/AlertPushService.java b/maibu-netty-server/src/main/java/com/maibu/service/AlertPushService.java index c2a389f..addff76 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/AlertPushService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/AlertPushService.java @@ -54,7 +54,7 @@ public class AlertPushService { @Autowired private WorkOrderServiceImpl wService; - public void messagePushHandler(String deviceId, List dtos) { + public void messagePushHandler(String deviceId, List 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 newList = new ArrayList<>(); - List 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 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 newList = new ArrayList<>(); + List 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 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); + } } - }); + } + } } } diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java index f3f6751..16d6777 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DevicePlanTaskMonitorService.java @@ -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 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 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 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); diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java index 50649d9..be3cfec 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DeviceTaskService.java @@ -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 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; + } + } diff --git a/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java b/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java index 45b7f5a..1021afe 100644 --- a/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java +++ b/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java @@ -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 keys = redisCache.getListKeyByPrefix(key); - if (!CollectionUtils.isEmpty(keys)) { - List 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 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> 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) { diff --git a/maibu-netty-server/src/main/java/com/maibu/utils/CompareUtils.java b/maibu-netty-server/src/main/java/com/maibu/utils/CompareUtils.java index 97028b7..46617c5 100644 --- a/maibu-netty-server/src/main/java/com/maibu/utils/CompareUtils.java +++ b/maibu-netty-server/src/main/java/com/maibu/utils/CompareUtils.java @@ -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); } + } \ No newline at end of file diff --git a/maibu-netty-server/src/main/resources/errorStandard.json b/maibu-netty-server/src/main/resources/errorStandard.json index 38d2ff8..3b6e5e5 100644 --- a/maibu-netty-server/src/main/resources/errorStandard.json +++ b/maibu-netty-server/src/main/resources/errorStandard.json @@ -1,24 +1,122 @@ [ { "field": "voltage", - "errorCode": "1001", + "errorCode": "SAFETY_FAULT_REMOTE_TIMEOUT", "compareValues": 58, "compareType": "GT", - "errorName": "电压过高", - "errorDescription": "当前电池电压过高,超过正常范围", + "errorName": "SAFETY_FAULT_REMOTE_TIMEOUT", + "errorDescription": "遥控器链路超时且当前未由上位机接管。", "errorSource": "MOWER", "errorLevel": "WARNING", - "suggestion": "请检查电池连接或更换电池" + "suggestion": "请检查电池连接或更换电池", + "codeIndex": 0 }, { "field": "battery", - "errorCode": "1002", + "errorCode": "SAFETY_FAULT_HEARTBEAT_TIMEOUT", "compareValues": 20, "compareType": "LT", - "errorName": "电量过低", - "errorDescription": "当前电池电量过低,请及时充电", + "errorName": "SAFETY_FAULT_HEARTBEAT_TIMEOUT", + "errorDescription": "整车控制器心跳反馈超时", "errorSource": "MOWER", "errorLevel": "WARNING", - "suggestion": "请检查电池电量,及时充电" + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 2 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_HEARTBEAT_MODE", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_HEARTBEAT_MODE", + "errorDescription": "整车控制器上报了无效的工作模式。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 3 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_CONTROLLER_STOP", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_CONTROLLER_STOP", + "errorDescription": "整车控制器请求慢停或停车。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 4 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_CHASSIS_TIMEOUT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_CHASSIS_TIMEOUT", + "errorDescription": "底盘轮速反馈超时。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 5 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_HOST_TIMEOUT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_HOST_TIMEOUT", + "errorDescription": "上位机控制模式下控制指令超时。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 6 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_LEFT_CURRENT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_LEFT_CURRENT", + "errorDescription": "整车控制器心跳反馈超时", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "左侧电机电流超过安全阈值。", + "codeIndex": 7 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_RIGHT_CURRENT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_RIGHT_CURRENT", + "errorDescription": "右侧电机电流超过安全阈值。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 8 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_BUS_CURRENT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_BUS_CURRENT", + "errorDescription": "母线电流超过安全阈值。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 9 + }, + { + "field": "battery", + "errorCode": "SAFETY_FAULT_PITCH_TILT", + "compareValues": 20, + "compareType": "LT", + "errorName": "SAFETY_FAULT_PITCH_TILT", + "errorDescription": "俯仰倾角持续超限,由倾角任务判断、安全任务统一汇总。", + "errorSource": "MOWER", + "errorLevel": "WARNING", + "suggestion": "请检查电池电量,及时充电", + "codeIndex": 10 } ] \ No newline at end of file diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java index dd16583..3e38e37 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/DeviceController.java @@ -53,7 +53,6 @@ public class DeviceController extends BaseController { @Autowired private DeviceRunStatisticsMapper deviceRunStatisticsMapper; - /** * 查询设备列表 */ @@ -65,14 +64,12 @@ public class DeviceController extends BaseController { return getDataTable(deviceService.selectDeviceList(device)); } - @GetMapping("/userDevice") @PreAuthorize("@ss.hasPermi('iot:device:list')") public AjaxResult userDevice(Device device) { return AjaxResult.success(deviceService.selectDeviceList(device)); } - /** * 导出设备列表 */ @@ -86,7 +83,6 @@ public class DeviceController extends BaseController { util.exportExcel(response, list, "设备数据"); } - /** * 根据设备编号详细信息 */ @@ -97,7 +93,6 @@ public class DeviceController extends BaseController { return AjaxResult.success(deviceService.selectDeviceBySerialNumber(serialNumber)); } - /** * 重置设备状态 */ @@ -111,7 +106,6 @@ public class DeviceController extends BaseController { return toAjax(deviceService.resetDeviceStatus(device.getSerialNumber())); } - @GetMapping("/getDeviceRunStatistics") public AjaxResult getDeviceRunStatistics(@RequestParam("deviceId") String deviceId) { if (StringUtils.isEmpty(deviceId)) { @@ -149,7 +143,7 @@ public class DeviceController extends BaseController { List list; if (day) { LambdaQueryWrapperX wrapper = new LambdaQueryWrapperX<>(); - LocalDateTime start = LocalDate.now().atStartOfDay(); // 今天 00:00:00 + LocalDateTime start = LocalDate.now().atStartOfDay(); // 今天 00:00:00 LocalDateTime end = LocalDate.now().plusDays(1).atStartOfDay(); // 明天 00:00:00 wrapper.ge(DeviceRunStatistics::getStartTime, start) @@ -171,12 +165,10 @@ public class DeviceController extends BaseController { sum.setDeviceId(group.get(0).getDeviceId()); sum.setWorkArea( - group.stream().mapToDouble(DeviceRunStatistics::getWorkArea).sum() - ); + group.stream().mapToDouble(DeviceRunStatistics::getWorkArea).sum()); sum.setTime( - group.stream().mapToLong(DeviceRunStatistics::getTime).sum() - ); + group.stream().mapToDouble(DeviceRunStatistics::getTime).sum()); return sum; }) @@ -191,7 +183,7 @@ public class DeviceController extends BaseController { if (!l.contains(device.getDeviceName())) { DeviceRunStatistics statistics = new DeviceRunStatistics(); statistics.setDeviceId(device.getDeviceName()); - statistics.setTime(0L); + statistics.setTime(0d); statistics.setWorkArea(0.0); resultList.add(statistics); } @@ -211,7 +203,7 @@ public class DeviceController extends BaseController { response.setHeader("Content-Disposition", "attachment;filename=" + fileName); try (Workbook workbook = new XSSFWorkbook(); - OutputStream os = response.getOutputStream()) { + OutputStream os = response.getOutputStream()) { Sheet sheet = workbook.createSheet("当日工作量统计"); @@ -236,7 +228,6 @@ public class DeviceController extends BaseController { sheet.autoSizeColumn(i); } - // ✅ 5. 写出 workbook.write(os); os.flush(); @@ -273,8 +264,8 @@ public class DeviceController extends BaseController { return getDataTable(deviceService.getSiteList(getLoginUser(), device)); } - /** - * 查询设备列表 分配页面 + /** + * 查询设备列表 分配页面 */ @GetMapping("/getDeviceBySpiltCode") public AjaxResult getDeviceBySpiltCode(@RequestParam String code) { @@ -282,7 +273,7 @@ public class DeviceController extends BaseController { } /** - * 查询设备列表 分配页面 + * 查询设备列表 分配页面 */ @GetMapping("/getDeviceList") public TableDataInfo getDeviceList(Device device) { @@ -306,14 +297,12 @@ public class DeviceController extends BaseController { return AjaxResult.success(deviceService.hasPermission(deviceId)); } - - /** + /** * 查看当前设备有没授权修改参数 */ @PostMapping("/runningHistoryStatistics") public AjaxResult runningHistoryStatistics(@RequestBody DeviceRunningStatisticsQueryDTO dto) { - return AjaxResult.success(deviceService.runningHistoryStatistics(dto)); + return AjaxResult.success(deviceService.vehicleMessageList(dto)); } - } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java index 81f9859..8406774 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/HostComputerController.java @@ -11,7 +11,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; @@ -296,4 +295,10 @@ public class HostComputerController extends BaseController { return AjaxResult.success(hostComputerService.modeChage(deviceId, controlMode)); } + @GetMapping("/eStopChange") + public AjaxResult searchDevice(@RequestParam String deviceId, @RequestParam Integer eStop) throws Exception { + + return AjaxResult.success(hostComputerService.eStopChange(deviceId, eStop)); + } + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java index f3de21d..7d5c523 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/controller/WorkRecordController.java @@ -85,11 +85,12 @@ public class WorkRecordController extends BaseController { String fileName = "routePlanImage/rt" + workRecord.getWorkName() + System.currentTimeMillis() + ".png"; - // 上传到 MinIO - minioUtil.uploadFile(fileName, inputStream, "image/png"); + // // 上传到 MinIO + // minioUtil.uploadFile(fileName, inputStream, "image/png"); - // 获取访问 URL - String url = minioUtil.getPublicUrl(fileName); + // // 获取访问 URL + // String url = minioUtil.getPublicUrl(fileName); + String url = ""; System.out.println("✅ 图片上传成功,访问地址: " + url); // 这里可以把 URL 存到 workRecord 里 diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IDeviceService.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IDeviceService.java index 9eff6f6..6c92c2f 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IDeviceService.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/IDeviceService.java @@ -5,6 +5,7 @@ import com.maibu.core.business.DeviceRunningStatusHistory; import com.maibu.core.business.dto.DeviceBindDTO; import com.maibu.core.domain.AjaxResult; import com.maibu.core.domain.model.LoginUser; +import com.maibu.core.host.VehicleMessage; import com.maibu.dto.DeviceParamAuthDTO; import com.maibu.dto.DeviceRunningStatisticsQueryDTO; @@ -92,4 +93,6 @@ public interface IDeviceService { public List runningHistoryStatistics(DeviceRunningStatisticsQueryDTO dto); + public List vehicleMessageList(DeviceRunningStatisticsQueryDTO dto); + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java index f3f2c68..be6b1c9 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java @@ -28,20 +28,24 @@ import com.maibu.core.business.DevicePlan; import com.maibu.core.business.DeviceRunningStatusHistory; import com.maibu.core.business.DeviceStatusRecordDTO; import com.maibu.core.business.dto.DeviceBindDTO; +import com.maibu.core.business.dto.VehicleMessageRecordDTO; import com.maibu.core.domain.AjaxResult; import com.maibu.core.domain.entity.SysRole; import com.maibu.core.domain.entity.SysSite; import com.maibu.core.domain.model.LoginUser; import com.maibu.core.enums.DeviceTaskStaus; import com.maibu.core.host.LocationMessage; +import com.maibu.core.host.VehicleMessage; import com.maibu.core.redis.RedisCache; import com.maibu.dto.DeviceParamAuthDTO; import com.maibu.dto.DeviceRunningStatisticsQueryDTO; +import com.maibu.exception.ServiceException; import com.maibu.mapper.DeviceMapper; import com.maibu.mapper.DevicePlanMapper; import com.maibu.mapper.DeviceStatusHistoryMapper; import com.maibu.mapper.HostLocationMapper; import com.maibu.mapper.SysSiteMapper; +import com.maibu.mapper.VehicleMessageMapper; import com.maibu.memory.GlobalMemory; import com.maibu.memory.SiteMemory; import com.maibu.service.IDeviceService; @@ -78,6 +82,9 @@ public class DeviceServiceImpl implements IDeviceService { @Autowired private HostLocationMapper hostLocationMapper; + @Autowired + private VehicleMessageMapper vehicleMessageMapper; + /** * 根据设备编号查询设备 * @@ -258,6 +265,12 @@ public class DeviceServiceImpl implements IDeviceService { if (CollectionUtils.isEmpty(list)) { return false; } else { + + Device d = list.stream().filter(x -> x.getSiteId() != null).findFirst().orElse(null); + if (d != null) { + throw new ServiceException("当前存在已绑定设备请先解绑!"); + } + list.forEach(device -> { if (bindDTO.getUserId() != null) { device.setTenantId(bindDTO.getUserId()); @@ -270,7 +283,7 @@ public class DeviceServiceImpl implements IDeviceService { return deviceMapper.saveOrUpdateBatch(list); } } catch (Exception e) { - log.error("设备绑定失败: {}", e.getMessage(), e); + log.error("设备绑定失败", e); } return false; } @@ -381,6 +394,7 @@ public class DeviceServiceImpl implements IDeviceService { locationMessage = locationMap.get(x.getDeviceName()); } x.setLocationMessage(locationMessage); + x.setVehicleMessage(siteMemory.getVehicleMessage(x.getSerialNumber())); } statusStatistics.put(0, work); @@ -474,4 +488,32 @@ public class DeviceServiceImpl implements IDeviceService { return list; } + @Override + public List vehicleMessageList(DeviceRunningStatisticsQueryDTO dto) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + if (dto != null && !StringUtils.isEmpty(dto.getDeviceId())) { + queryWrapper.eq(VehicleMessage::getDeviceId, dto.getDeviceId()); + } + if (dto != null && dto.getStartTime() != null && dto.getEndTime() != null) { + queryWrapper.ge(VehicleMessage::getCreateTime, dto.getStartTime()); + queryWrapper.le(VehicleMessage::getCreateTime, dto.getEndTime()); + } + List list = vehicleMessageMapper.selectList(queryWrapper); + + String key = NettyCacheKey.vehicleMessageKey + dto.getDeviceId(); + VehicleMessageRecordDTO recordDTO = redisCache.getCacheObject(key); + List cacheList; + if (recordDTO != null) { + cacheList = recordDTO.getHistories(); + if (!CollectionUtils.isEmpty(list)) { + if (!CollectionUtils.isEmpty(cacheList)) { + list.addAll(cacheList); + } + } else { + return cacheList; + } + } + return list; + } + } diff --git a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java index 2fa83d4..595634b 100644 --- a/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java +++ b/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/HostComputerService.java @@ -26,33 +26,46 @@ public class HostComputerService { public void searchDevice(String deviceId) throws Exception { NettyDevice device = deviceSessionManager.getDevice(deviceId); - if (device != null && device.getOnlineStatus() == 1) { + if (device != null && device.getOnlineStatus() != null && device.getOnlineStatus() == 1) { device.searchDevice(deviceId); } } - // public void modeChage(String deviceId, Integer controlMode) throws Exception - // { - // NettyDevice device = deviceSessionManager.getDevice(deviceId); + public boolean eStopChange(String deviceId, Integer eStop) throws Exception { + NettyDevice device = deviceSessionManager.getDevice(deviceId); - // if (device == null || device.getOnlineStatus() == null || - // device.getOnlineStatus() == 0) { - // throw new ServiceException("设备不在线"); - // } - // Long orgId = device.getDevice().getOrgId(); - // Long siteId = device.getDevice().getSiteId(); - // SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId); - // if (siteMemory != null) { - // VehicleMessage vehicleMessage = siteMemory.getVehicleMessage(deviceId); - // if (vehicleMessage != null && vehicleMessage.getControl_mode() != null) { - // Integer nowMode = vehicleMessage.getControl_mode(); - // if (controlMode.equals(nowMode)) { - // throw new ServiceException("设备已处于该模式"); - // } - // } - // } - // device.modeChage(deviceId, controlMode); - // } + if (device == null || device.getOnlineStatus() == null + || device.getOnlineStatus() == 0) { + throw new ServiceException("设备不在线"); + } + + // 创建等待回传的 Future + CompletableFuture future = new CompletableFuture<>(); + + // 一个设备同时只允许一个模式切换请求 + CompletableFuture oldFuture = GlobalMemory.modeFutureMap.putIfAbsent(deviceId, future); + + if (oldFuture != null) { + throw new ServiceException("设备正在执行模式切换,请稍后再试"); + } + + try { + // 下发指令 + device.eStopChange(deviceId, eStop); + + // 等待设备回传,最多等待 5 秒 + Boolean result = future.get(5, TimeUnit.SECONDS); + + return result; + + } catch (Exception e) { + throw new ServiceException("设备模式切换失败"); + + } finally { + // 无论成功、失败还是超时,都清理 Future + GlobalMemory.modeFutureMap.remove(deviceId, future); + } + } public Boolean modeChage(String deviceId, Integer controlMode) throws Exception { NettyDevice device = deviceSessionManager.getDevice(deviceId); diff --git a/maibu-service/maibu-system-service/src/main/java/com/maibu/mapper/VehicleMessageMapper.java b/maibu-service/maibu-system-service/src/main/java/com/maibu/mapper/VehicleMessageMapper.java new file mode 100644 index 0000000..c696e5d --- /dev/null +++ b/maibu-service/maibu-system-service/src/main/java/com/maibu/mapper/VehicleMessageMapper.java @@ -0,0 +1,11 @@ +package com.maibu.mapper; + +import org.springframework.stereotype.Repository; + +import com.maibu.core.host.VehicleMessage; +import com.maibu.mybatis.mapper.BaseMapperX; + +@Repository +public interface VehicleMessageMapper extends BaseMapperX { + +} diff --git a/maibu-web-middleware/src/main/java/com/maibu/utils/ControlUtils.java b/maibu-web-middleware/src/main/java/com/maibu/utils/ControlUtils.java index 2e5a446..0e859e7 100644 --- a/maibu-web-middleware/src/main/java/com/maibu/utils/ControlUtils.java +++ b/maibu-web-middleware/src/main/java/com/maibu/utils/ControlUtils.java @@ -40,13 +40,22 @@ public class ControlUtils { chassisLiftFlag = 2; } state.setChassisLiftFlag((byte) chassisLiftFlag); - // 割刀加减速 - int mowerSpeedFlag = 0; - if (X & !Y) { - mowerSpeedFlag = 1; - } else if (!X & Y) { + // // 割刀加减速 + // int mowerSpeedFlag = 0; + // if (X & !Y) { + // mowerSpeedFlag = 1; + // } else if (!X & Y) { + // mowerSpeedFlag = 2; + // } + + // 割刀开启关闭 + int mowerSpeedFlag; + if (X == null) { mowerSpeedFlag = 2; + } else { + mowerSpeedFlag = X ? 1 : 0; } + state.setMowerSpeedFlag((byte) mowerSpeedFlag); // 点火熄火 int ignitionFlag = 0; @@ -75,7 +84,7 @@ public class ControlUtils { // buffer.putShort(entity.getLeftWheelSpeed());//左轮速度 // buffer.putShort(entity.getRightWheelSpeed());//右轮速度 - buffer.putDouble(entity.getLinearSpeed());// + buffer.putDouble(entity.getLinearSpeed());// buffer.putDouble(entity.getAngularSpeed());// 右轮速度 buffer.put(entity.getChassisLiftFlag());// 底盘升降