9 Commits

Author SHA1 Message Date
64f54c4191 #地图相关推送修改 2026-09-21 10:25:49 +08:00
4f7f32eeb2 #update 地图统一推送功能 2026-09-14 10:37:27 +08:00
cfd2906b71 #位置信息增加当前设备任务执行情况 2026-09-11 09:29:06 +08:00
985f501e76 #更新计算累计路程相关 2026-09-10 14:35:02 +08:00
a6f662b15b #老板的上位机登录 2026-09-09 13:00:31 +08:00
4ee3f6be90 #优化更新 连接上位机相关 2026-09-09 09:01:54 +08:00
fda1060b38 # update 更新导入 设备属性的功能 2026-09-03 10:32:57 +08:00
5f369a159d #更新优化 2026-09-02 05:03:10 +00:00
a92ec91cd2 #优化路径规划下发 任务状态接收相关 2026-08-28 06:32:11 +00:00
56 changed files with 1350 additions and 693 deletions

View File

@@ -102,6 +102,11 @@ public class DeviceTask {
return builder(FastBeeConstant.TASK.DEVICE_HEARTBEAT_MONITOR);
}
@Bean(FastBeeConstant.TASK.MAP_MESSAGE_PUSH)
public Executor mapMessagePush() {
return builder(FastBeeConstant.TASK.MAP_MESSAGE_PUSH);
}
@Bean(FastBeeConstant.TASK.DEVICE_TASK_HANDLER)
public Executor deviceTaskHandler() {
return builder(FastBeeConstant.TASK.DEVICE_TASK_HANDLER);

View File

@@ -105,6 +105,13 @@ public interface FastBeeConstant {
* 设备错误
*/
String DEVICE_HEARTBEAT_MONITOR = "deviceHeartBeatMonitor";
/**
* 设备错误
*/
String MAP_MESSAGE_PUSH = "mapMessagePush";
/**
* 设备任务处理线程
*/

View File

@@ -1,9 +1,9 @@
package com.maibu.common;
import lombok.Data;
package com.maibu.constant;
public class NettyCacheKey {
public static final String deviceRunningStatusKey = "running_status:";
public static final String latestPositonKey = "latest_position:";
}

View File

@@ -13,6 +13,8 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.maibu.annotation.Excel;
import com.maibu.core.domain.BaseDO;
import com.maibu.core.host.LocationMessage;
import com.maibu.core.host.VehicleMessage;
import com.maibu.influxdb.MowerRealTimeData;
import io.swagger.annotations.ApiModel;
@@ -72,7 +74,6 @@ public class Device extends BaseDO {
@Excel(name = "产品名称")
private String productName;
/**
* 租户名称
*/
@@ -87,7 +88,6 @@ public class Device extends BaseDO {
@Excel(name = "固件版本")
private BigDecimal firmwareVersion;
/**
* WIFI固件版本
*/
@@ -95,7 +95,6 @@ public class Device extends BaseDO {
@Excel(name = "HTTP推送固件版本")
private BigDecimal wirelessVersion;
/**
* 设备状态(1-未激活,2-禁用,3-在线,4-离线)
*/
@@ -106,12 +105,12 @@ public class Device extends BaseDO {
/**
* 设备在线状态(1-在线,2-离线)
*/
@ApiModelProperty("设备状态(1-在线,2-离线)")
@ApiModelProperty("设备状态(1-在线,0-离线)")
@Excel(name = "设备在线状态")
private Integer onlineStatus;
@TableField(exist = false)
private Integer feStatus; //前端大屏显示 1任务中/2空闲
private Integer feStatus; // 前端大屏显示 1任务中/2空闲
/**
* wifi信号强度(信号极好4格[-55— 0],信号好3格[-70— -55],信号一般2格[-85— -70],信号差1格[-100— -85])
@@ -194,7 +193,6 @@ public class Device extends BaseDO {
@ApiModelProperty("设备摘要")
private String summary;
/**
* 是否是模拟设备
*/
@@ -206,12 +204,12 @@ public class Device extends BaseDO {
@ApiModelProperty("子设备地址")
private Integer slaveId;
@TableField(updateStrategy = FieldStrategy.IGNORED)
private Long siteId;
@TableField(updateStrategy = FieldStrategy.IGNORED)
private Long orgId;
/**
* 租户ID
*/
@@ -220,7 +218,6 @@ public class Device extends BaseDO {
@TableField(updateStrategy = FieldStrategy.IGNORED)
private Long tenantId;
@TableField(exist = false)
private DeviceRunningStatusHistory lastRunningStatus;
@@ -228,12 +225,19 @@ public class Device extends BaseDO {
private MowerRealTimeData lastMowerRealTimeData;
@TableField(exist = false)
private Map<Integer,Integer> statusStatistics;
private Map<Integer, Integer> statusStatistics;
@TableField(exist = false)
private DeviceRunParam runParam;
private Boolean hasRegistered;
private boolean hasRegistered = false;
private Boolean hasHost;
@TableField(exist = false)
private LocationMessage locationMessage;
@TableField(exist = false)
private VehicleMessage vehicleMessage;
}

View File

@@ -1,18 +1,14 @@
package com.maibu.core.business;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.maibu.core.domain.BaseDO;
import com.maibu.core.enums.ConnectType;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@JsonInclude(JsonInclude.Include.NON_NULL)

View File

@@ -1,17 +1,17 @@
package com.maibu.core.business;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.maibu.core.domain.BaseDO;
import com.maibu.core.domain.OrgBaseDO;
import com.maibu.core.enums.DeviceTaskStaus;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("iot_device_task")

View File

@@ -4,6 +4,8 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.maibu.annotation.Excel;
import com.maibu.constant.CommandConstant;
import com.maibu.core.domain.BaseDO;
@@ -13,6 +15,7 @@ import lombok.EqualsAndHashCode;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.List;
@EqualsAndHashCode(callSuper = true)
@Data
@@ -22,7 +25,7 @@ public class DeviceRunParam extends BaseDO {
@TableId(type = IdType.AUTO)
private Long id;
private String deviceId;
// private String deviceId;
private Long siteId;
@@ -30,6 +33,40 @@ public class DeviceRunParam extends BaseDO {
private Integer runSpeed; //不下发到设备自己用
@Excel(name = "设备序列号", cellType = Excel.ColumnType.STRING, prompt = "设备序列号")
private String deviceId;//设备序列号
@Excel(name = "产品型号", cellType = Excel.ColumnType.STRING, prompt = "产品型号")
private String productModel;//产品型号
@Excel(name = "设备类型", cellType = Excel.ColumnType.STRING, prompt = "设备类型")
private String deviceType;//设备类型:mower-割草机器人
@Excel(name = "RTK模式", cellType = Excel.ColumnType.STRING, prompt = "RTK模式")
private String rtkMode;//RTK模式:network-4G网络差分
@Excel(name = "摄像头数量", cellType = Excel.ColumnType.STRING, prompt = "摄像头数量")
private Integer cameraNum;//摄像头数量
@Excel(name = "动力类型", cellType = Excel.ColumnType.STRING, prompt = "动力类型")
private String powerType;//动力类型:hybrid-混动
@Excel(name = "车轮类型", cellType = Excel.ColumnType.STRING, prompt = "车轮类型")
private String wheelType;//车轮类型:track-履带式
@Excel(name = "发动机类型", cellType = Excel.ColumnType.STRING, prompt = "发动机类型")
private String engineType;//发动机类型:honda-本田发动机
@Excel(name = "是否搭载上位机",cellType = Excel.ColumnType.NUMERIC)
private Integer hasHost = 1;//是否搭载上位机
@Excel(name = "设备能力列表")
@TableField(exist = false)
private String capabilities;
@TableField(typeHandler = JacksonTypeHandler.class)
private List<String> capabilityList;//设备能力列表:heartbeat-上报心跳/location-上报位置/vehicle_status-上报整机状态/task_control-任务控制/single_point-单点作业/coverage-全覆盖割草作业/path_upload-作业路径上传
@TableField(exist = false)
public byte header1;
@@ -117,112 +154,6 @@ public class DeviceRunParam extends BaseDO {
return buffer.array();
}
// public static byte[] toWriteBytes(DeviceRunParam p) {
//
// ByteBuffer buffer = ByteBuffer.allocate(178);
// buffer.order(ByteOrder.LITTLE_ENDIAN);
//
// // 包头
// buffer.put((byte) 0xAB);
// buffer.put((byte) 0xAA);
//
// // 指令
// buffer.put(CommandConstant.writeConfig);
//
// // UID固化标志
// buffer.put(p.getChipUidSign());
//
// // UID
// putFixedString(buffer, p.getChipUid(), 45);
//
// // Byte68
// byte remote = 0;
// remote |= (p.getKnifeMotorMode() & 0x03);
// remote |= (p.getWalkMotorMode() & 0x03) << 2;
// remote |= (p.getLeftMotorReverse() & 0x01) << 4;
// remote |= (p.getRightMotorReverse() & 0x01) << 5;
// remote |= (p.getSwapChannel() & 0x01) << 6;
// remote |= (p.getUse4G() & 0x01) << 7;
// buffer.put(remote);
//
// // 69~72
// buffer.putShort((short) p.getForwardSpeedLimit());
// buffer.putShort((short) p.getTurnSpeedLimit());
//
// //73
// byte b73 = 0;
// b73 |= (p.getKnifePolarity() & 1);
// b73 |= (p.getFanPolarity() & 1) << 1;
// b73 |= (p.getThrottlePolarity() & 1) << 2;
// b73 |= (p.getLiftProtectTime() & 0x0F) << 3;
// b73 |= (p.getDualRtk() & 1) << 7;
// buffer.put(b73);
//
// //74
// byte b74 = 0;
// b74 |= (p.getKnifeChannel() & 0x0F);
// b74 |= (p.getFanChannel() & 0x0F) << 4;
// buffer.put(b74);
//
// //75
// byte b75 = 0;
// b75 |= (p.getThrottleChannel() & 0x0F);
// b75 |= (p.getRemoteType() & 0x07) << 4;
// if (p.isRelayBoard()) {
// b75 |= 1 << 7;
// }
// buffer.put(b75);
//
// //76
// byte b76 = 0;
// b76 |= (p.getLiftChannel() & 0x0F);
// b76 |= (p.getChassisChannel() & 0x0F) << 4;
// buffer.put(b76);
//
// //77
// byte b77 = 0;
// b77 |= (p.getArmChannel() & 0x0F);
// b77 |= (p.getFuelPumpChannel() & 0x0F) << 4;
// buffer.put(b77);
//
// //wifi
// putFixedString(buffer, p.getWifiName(), 20);
// putFixedString(buffer, p.getWifiPassword(), 20);
//
// //118
// byte b118 = 0;
// b118 |= (p.getBatteryType() & 0x03);
// b118 |= (p.getDriveType() & 0x03) << 2;
// buffer.put(b118);
//
// //119~158 float
// buffer.putFloat(p.getGearRatio());
// buffer.putFloat(p.getRobotLength());
// buffer.putFloat(p.getRobotWidth());
// buffer.putFloat(p.getRobotHeight());
// buffer.putFloat(p.getKnifeWidth());
// buffer.putFloat(p.getTyreSize());
// buffer.putFloat(p.getLeftForwardGain());
// buffer.putFloat(p.getLeftBackwardGain());
// buffer.putFloat(p.getRightForwardGain());
// buffer.putFloat(p.getRightBackwardGain());
//
// //159~173
// putFixedString(buffer, p.getFirmwareVersion(), 15);
//
// //CRC
//
// / / byte[] bytes = buffer.array();
// / / int crc = CRC16Util.crc16(bytes, 0, 174);
// buffer.putShort((short) 0);
//
// //Tail
// buffer.put((byte) 0xAA);
// buffer.put((byte) 0xAB);
//
// return buffer.array();
// }
public byte[] toWriteBytes() {
// 如果没有原始数据,使用静态方法重新构建
if (originalData == null || originalData.length < 178) {

View File

@@ -138,24 +138,6 @@ public class NettyDevice extends Connector {
return finishId;
}
// public synchronized boolean cancelTask() {
// if (task != null) {
// sendPathCommand((byte) 0x01, (short) 0, 0.00d, 0.00d, (short) 0);
// task.setTaskStaus(DeviceTaskStaus.CANCELED);
// task.setUpdateTime(LocalDateTime.now());
// devicePlanTaskMapper.saveOrUpdate(task);
// SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(),
// task.getSiteId());
// siteMemory.removeDevicePlanPrepare(task);
// siteMemory.removeDevicePlanExecute(task.getDeviceId());
// task = null;
// currentTaskId = null;
// currentPoint = null;
// locationQueue.clear();
// executingTask = false;
// }
// return true;
// }
public synchronized boolean cancelingTask() throws MqttException {
if (task != null) {
@@ -200,6 +182,24 @@ public class NettyDevice extends Connector {
return true;
}
public synchronized boolean failedTask() {
if (task != null) {
task.setTaskStaus(DeviceTaskStaus.FAILED);
task.setUpdateTime(LocalDateTime.now());
devicePlanTaskMapper.saveOrUpdate(task);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId());
siteMemory.removeDevicePlanPrepare(task);
siteMemory.removeDevicePlanExecute(task.getDeviceId());
GlobalMemory.taskPathMap.remove(task.getId());
task = null;
currentTaskId = null;
currentPoint = null;
locationQueue.clear();
executingTask = false;
}
return true;
}
public void sendPathCommand(byte commandType, short pointCounts, double lat, double lng, short speed) {
RoutePlanSendEntity routePlanSendEntity = new RoutePlanSendEntity();
routePlanSendEntity.setCommandType(commandType);
@@ -296,29 +296,6 @@ public class NettyDevice extends Connector {
}
}
// public void startTask() {
// try {
// if (executingTask)
// return;
// if (task != null) {
// Long routeId = task.getRouteId();
// WorkRecord workRecord = workRecordMapper.selectById(routeId);
// if (workRecord != null) {
// PlanPath planPath = workRecord.getJsonData();
// if (planPath != null && !CollectionUtils.isEmpty(planPath.getPath())) {
// planPath.getPath().forEach(x -> {
// locationQueue.offer(x);
// });
// }
// }
// task.setStartTime(LocalDateTime.now());
// }
// executingTask = true;
// sendNextPoint();
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
public void startTask() {
try {
@@ -367,7 +344,7 @@ public class NettyDevice extends Connector {
}, 0, 5, TimeUnit.SECONDS);
}
} catch (Exception e) {
throw new RuntimeException(e);
log.error("发送开始任务:error {} ", e.getMessage());
}
}

View File

@@ -0,0 +1,18 @@
package com.maibu.core.business.dto;
import lombok.Data;
@Data
public class DeviceMapPushDTO {
private String id;
private double lat;
private double lng;
private double y; //yaw
private String f; //fix_status
private double a; //altitude
private String s;//status 运行状态
private Long t; //taskId 任务id
private double b; //电量
private boolean ha = false;//hasAlarm 有无告警
}

View File

@@ -20,6 +20,8 @@ public class DeviceTaskCommandDTO {
private Long taskId;
private Long regionId;
private boolean forceCancel = false; //强制取消 不等回复
}

View File

@@ -1,4 +1,4 @@
package com.maibu.dto;
package com.maibu.core.business.dto;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.enums.MesType;

View File

@@ -0,0 +1,12 @@
package com.maibu.core.business.dto;
import com.maibu.core.enums.MesType;
import lombok.Data;
import java.util.List;
@Data
public class WebMapMessageDTO {
private List<DeviceMapPushDTO> data;
private MesType type;
}

View File

@@ -0,0 +1,16 @@
package com.maibu.core.business.dto;
import java.util.List;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.enums.MesType;
import lombok.Data;
@Data
public class WebRouteStatusMessageDTO {
private List<LatAndLngEntity> data;
private String deviceId;
private Long taskId;
private MesType type;
}

View File

@@ -1,7 +0,0 @@
package com.maibu.core.business.inter;
public interface DeviceWebSocketInterace {
void sendWebsoketMes(String key, String data);
}

View File

@@ -0,0 +1,10 @@
package com.maibu.core.business.inter;
public interface DeviceWebSocketInterface {
void sendWebsocketMes(String key, String data);
void sendMapWebsocketMes(Long siteId,String data);
}

View File

@@ -14,10 +14,19 @@ public class WebsocketMesDispather {
private ApplicationContext applicationContext;
public void dispather(String key, String data) {
Map<String, DeviceWebSocketInterace> beanMap = applicationContext.getBeansOfType(DeviceWebSocketInterace.class);
Map<String, DeviceWebSocketInterface> beanMap = applicationContext.getBeansOfType(DeviceWebSocketInterface.class);
// 遍历
beanMap.values().forEach(x -> {
x.sendWebsoketMes(key, data);
x.sendWebsocketMes(key, data);
});
}
public void mapMessageDispather(Long siteId, String data) {
Map<String, DeviceWebSocketInterface> beanMap = applicationContext.getBeansOfType(DeviceWebSocketInterface.class);
// 遍历
beanMap.values().forEach(x -> {
x.sendMapWebsocketMes(siteId, data);
});
}

View File

@@ -1,14 +1,15 @@
package com.maibu.core.domain.entity;
import java.util.List;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.maibu.core.domain.BaseDO;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
@EqualsAndHashCode(callSuper = true)
@Data
@TableName(value = "sys_region")
@@ -29,4 +30,6 @@ public class SysRegion extends BaseDO {
private Integer status;
private Long bindRoute;// 绑定的线路id
}

View File

@@ -43,4 +43,6 @@ public class SysSite extends BaseDO {
private boolean dingTalkOrderPush = false;// 工单是否推送
private String siteMapName; // geoserver 地图名称
}

View File

@@ -14,5 +14,7 @@ public enum MesType {
remoteControl,
detectionReport, // 障碍物消息
switchPermission, // 切换控制申请
switchResult;// 切换结果
switchResult,// 切换结果
route_post,// 路径规划 点位推送
mapPush;
}

View File

@@ -1,14 +1,26 @@
package com.maibu.core.host;
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
public class LocationMessage {
@EqualsAndHashCode(callSuper = true)
@TableName("iot_host_location_message")
public class LocationMessage extends OrgNoUserDO {
@TableId(type = IdType.AUTO)
private Long id;
private String deviceId;
private double latitude;
private double longitude;
private double yaw;//目标航向,正北0°、顺时针正、0-360°
private double yaw;// 目标航向,正北0°、顺时针正、0-360°
private String fix_status;
private double altitude;

View File

@@ -1,15 +1,16 @@
package com.maibu.core.host;
import lombok.Data;
@Data
public class VehicleMessage {
private double speed;
private double battery_percentage;//电量
private double battery_voltage;//电压
private String motion;//moving|stopped|blocked
private boolean emergency_stop; //急停状态
private double battery_percentage;// 电量
private double battery_voltage;// 电压
private String motion;// moving|stopped|blocked
private boolean emergency_stop; // 急停状态
private double distance; // 里程数
}

View File

@@ -0,0 +1,24 @@
package com.maibu.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 设备回调状态
*
* @author bill
*/
@Getter
@AllArgsConstructor
public enum DeviceStatusEnum {
working("1", "工作中"),
idle("2", "空闲中"),
offline("3", "离线"),
charging("4", "充电中"),
error("5", "故障");
String code;
String message;
}

View File

@@ -6,8 +6,6 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.maibu.influxdb.inter.InfluxField;

View File

@@ -0,0 +1,14 @@
package com.maibu.mapper;
import org.springframework.stereotype.Repository;
import com.maibu.core.host.LocationMessage;
import com.maibu.mybatis.mapper.BaseMapperX;
/**
* 设备历史状态
*/
@Repository
public interface HostLocationMapper extends BaseMapperX<LocationMessage> {
}

View File

@@ -1,6 +1,5 @@
package com.maibu.memory;
import cn.hutool.core.util.ObjectUtil;
import com.maibu.core.business.device.Connector;
import com.maibu.core.business.device.NettyDevice;
@@ -30,7 +29,7 @@ public class DeviceSessionManager {
// 设备ID -> 设备对象(业务实体)
private final ConcurrentHashMap<String, NettyDevice> deviceMap = new ConcurrentHashMap<>();
//当前设备的控制权在哪 登录的账号 deviceId(下位机) -> token key 唯一保证一个deviceId 只有一个控制权
// 当前设备的控制权在哪 登录的账号 deviceId(下位机) -> token key 唯一保证一个deviceId 只有一个控制权
private final ConcurrentHashMap<String, String> controllerMap = new ConcurrentHashMap<>();
// 设备ID -> Channel(通信通道)
@@ -39,7 +38,6 @@ public class DeviceSessionManager {
// Channel -> 设备ID(反查)
private final ConcurrentHashMap<Channel, String> channelToDeviceIdMap = new ConcurrentHashMap<>();
public void clearChannelToDeviceIdMap(String deviceId) {
if (StringUtils.isEmpty(deviceId) || CollectionUtils.isEmpty(channelToDeviceIdMap)) {
return;
@@ -67,7 +65,6 @@ public class DeviceSessionManager {
}
}
/**
* 注册设备连接(设备上线)
*
@@ -75,7 +72,8 @@ public class DeviceSessionManager {
* @param channel 通信通道
* @param deviceType 设备类型(MASTER/SLAVE)
*/
public void registerDevice(String deviceId, Channel channel, ConnectorType deviceType, ConnectorStatus status, String slaveId) {
public void registerDevice(String deviceId, Channel channel, ConnectorType deviceType, ConnectorStatus status,
String slaveId) {
NettyDevice nettyDevice = deviceMap.computeIfAbsent(deviceId, id -> new NettyDevice(id, deviceType));
nettyDevice.setChannel(channel);
nettyDevice.setConnectorStatus(status); // 默认上线即ACTIVE
@@ -109,7 +107,8 @@ public class DeviceSessionManager {
*/
public void bindConnector(String masterId, String slaveId) {
NettyDevice master = deviceMap.get(masterId);
if (master == null) return;
if (master == null)
return;
NettyDevice slave = deviceMap.computeIfAbsent(slaveId, id -> new NettyDevice(id, ConnectorType.SLAVE));
master.addConnectedDevice(slave);
System.out.println("Bind connectors for master " + masterId + " and slave " + slaveId);
@@ -147,7 +146,6 @@ public class DeviceSessionManager {
}
}
public boolean unLock(String token) {
if (!StringUtils.isEmpty(token)) {
Iterator<String> iterator = controllerMap.keySet().iterator();
@@ -179,7 +177,6 @@ public class DeviceSessionManager {
}
// 模糊匹配
public List<NettyDevice> getDevicesLike(String query) {
return deviceMap.values().stream()
@@ -187,7 +184,6 @@ public class DeviceSessionManager {
.collect(Collectors.toList());
}
public List<NettyDevice> getSlaveControl(String slaveId) {
// 获取所有连接的主机 且是active状态的
return deviceMap.values().stream()
@@ -196,7 +192,6 @@ public class DeviceSessionManager {
.collect(Collectors.toList());
}
public List<NettyDevice> getAllSlaveControl(String slaveId) {
// 获取所有连接的主机 不区分状态
return deviceMap.values().stream()
@@ -212,7 +207,6 @@ public class DeviceSessionManager {
.findFirst().orElse(null);
}
/// 模糊匹配
public NettyDevice getUserControl(String userName) {
return deviceMap.values().stream()
@@ -221,7 +215,6 @@ public class DeviceSessionManager {
.findFirst().orElse(null);
}
/**
* 根据设备ID获取Channel
*/
@@ -236,7 +229,6 @@ public class DeviceSessionManager {
return channelToDeviceIdMap.get(channel);
}
/**
* 根据从机查控制的主机
*/
@@ -249,7 +241,8 @@ public class DeviceSessionManager {
* 根据从机查所有主机
*/
public List<NettyDevice> getMastersBySlaveId(String slaveId) {
return deviceMap.values().stream().filter(x -> Objects.equals(x.getCurrentSlaveId(), slaveId)).collect(Collectors.toList());
return deviceMap.values().stream().filter(x -> Objects.equals(x.getCurrentSlaveId(), slaveId))
.collect(Collectors.toList());
}
/**
@@ -257,18 +250,25 @@ public class DeviceSessionManager {
*/
public void removeDevice(String deviceId) {
NettyDevice nettyDevice = deviceMap.remove(deviceId);
// Channel channel = channelMap.remove(deviceId);
// Channel channel = channelMap.remove(deviceId);
clearChannelToDeviceIdMap(deviceId);
// if (channel != null) {
// channelToDeviceIdMap.remove(channel);
// channel.close();
// }
// if (channel != null) {
// channelToDeviceIdMap.remove(channel);
// channel.close();
// }
if (nettyDevice != null) {
// 仅当设备是上位机时,才解绑绑定关系
if (nettyDevice.getDeviceType() == ConnectorType.MASTER) {
for (Connector connected : new HashSet<>(nettyDevice.getConnectedConnectors())) {
nettyDevice.removeConnectedDevice(connected);
}
// 清理channel和状态
nettyDevice.setChannel(null);
Channel channel = channelMap.remove(deviceId);
if (channel != null) {
channelToDeviceIdMap.remove(channel);
channel.close();
}
} else {
// 如果是下位机,则保留绑定关系,只清理channel和状态
nettyDevice.setChannel(null);
@@ -281,7 +281,6 @@ public class DeviceSessionManager {
}
}
/**
* 判断设备是否在线
*/
@@ -306,5 +305,20 @@ public class DeviceSessionManager {
return nettyDevice != null && nettyDevice.canReceive();
}
/**
* 获取客户端当前 控制的设备
*/
public String getDeviceByTaskId(Long taskId) {
if (taskId == null) {
return null;
}
for (String key : deviceMap.keySet()) {
NettyDevice nettyDevice = deviceMap.get(key);
if (nettyDevice != null && Objects.equals(nettyDevice.getCurrentTaskId(), taskId)) {
return nettyDevice.getConnectorId();
}
}
return null;
}
}

View File

@@ -108,6 +108,7 @@ public class GlobalMemory {
MqttTopic.MOWER_HEARTBEAT,//心跳
MqttTopic.MOWER_WILDCARD_LOCATION,//位置 经纬度
MqttTopic.MOWER_WILDCARD_TASK_ROUTE, //路径回复
MqttTopic.MOWER_WILDCARD_TASK_STATUS,//任务状态
MqttTopic.MOWER_WILDCARD_ERROR,//错误
MqttTopic.MOWER_WILDCARD_REALTIME, //状态消息
MqttTopic.MOWER_WILDCARD_TASK_TARGET_REPLY //路径规划下发回复

View File

@@ -7,6 +7,7 @@ import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import com.maibu.core.business.*;
import com.maibu.core.business.dto.DeviceMapPushDTO;
import com.maibu.mqtt.CustomMqttDeviceMonitor;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttClient;
@@ -53,6 +54,39 @@ public class SiteMemory {
// key deviceId execute
public static ConcurrentHashMap<String, DevicePlanTask> devicePlanTaskExecuteMap = new ConcurrentHashMap<>();
// 记录 设备上线后的运行数据 下线后清除并保存到数据库
public static ConcurrentHashMap<String, DeviceRunStatistics> deviceRunStatisticsMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, DeviceMapPushDTO> deviceMapPushMap = new ConcurrentHashMap<>();
public Map<String, DeviceMapPushDTO> getAllDeviceMapPush() {
return deviceMapPushMap;
}
public void saveMaPushDTO(String deviceId, DeviceMapPushDTO dto) {
deviceMapPushMap.put(deviceId, dto);
}
public void saveRunStatistics(DeviceRunStatistics deviceRunStatistics) {
if (deviceRunStatistics != null && !StringUtils.isEmpty(deviceRunStatistics.getDeviceId())) {
deviceRunStatisticsMap.put(deviceRunStatistics.getDeviceId(), deviceRunStatistics);
}
}
public DeviceRunStatistics getRunStatistics(String deviceId) {
if (!StringUtils.isEmpty(deviceId)) {
return deviceRunStatisticsMap.get(deviceId);
}
return null;
}
public void removeRunStatistics(String deviceId) {
if (!StringUtils.isEmpty(deviceId)) {
deviceRunStatisticsMap.remove(deviceId);
}
}
public static void saveDevice(Device device) {
deviceMap.put(device.getSerialNumber(), device);
}
@@ -135,7 +169,6 @@ public class SiteMemory {
}
}
public void saveDeviceRunParam(DeviceRunParam deviceRunParam) {
deviceRunParamMap.put(deviceRunParam.getDeviceId(), deviceRunParam);
}

View File

@@ -1,25 +1,39 @@
package com.maibu.mqtt;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maibu.constant.Constant;
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.host.*;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.utils.StringUtils;
import com.maibu.utils.json.JsonUtils;
import com.maibu.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import com.maibu.core.business.dto.DeviceMapPushDTO;
import org.springframework.util.CollectionUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.maibu.constant.Constant;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.device.DeviceStatusDetail;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.WebDeviceTaskStatusMessageDTO;
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.MesType;
import com.maibu.core.host.HeartBeatDTO;
import com.maibu.core.host.HostLocationRelTimeDTO;
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.redis.RedisCache;
import com.maibu.enums.DeviceStatusEnum;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
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;
/**
* mqtt相关的 上位机处理器
@@ -33,9 +47,10 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
private final WebsocketMesDispather websocketMesDispather = SpringUtils.getBean(WebsocketMesDispather.class);
private final String mqttClientId = "maibu-mqtt-client";
private final RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
@Override
public String getHandlerType() {
return Constant.mqttHandleKey;
@@ -49,8 +64,10 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
/**
* 处理 MQTT 消息
*
* <p>通配符订阅场景下,deviceKey 为配置中的固定标识(如 "host-monitor"),
* 真正的设备 ID 需从 topic 中解析,通过 {@link #extractDeviceId(String)} 获取。</p>
* <p>
* 通配符订阅场景下,deviceKey 为配置中的固定标识(如 "host-monitor"),
* 真正的设备 ID 需从 topic 中解析,通过 {@link #extractDeviceId(String)} 获取。
* </p>
*/
@Override
public void handleMessage(String deviceKey, String topic, String payload, CustomMqttDeviceConfig config) {
@@ -74,21 +91,17 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
case "realtime_post":
handleRealtimePost(deviceId, topic, payload);
break;
case "status_post":
handleStatusPost(deviceId, topic, payload);
break;
case "heartbeat_post":
handleHeartbeatPost(deviceId, topic, payload);
break;
case "error_post":
handleErrorPost(deviceId, topic, payload);
break;
case "route_post":
case "point_post":
handleTaskPost(deviceId, topic, payload, action);
break;
// case "route_post":
// case "point_post":
// handleTaskPost(deviceId, topic, payload, action);
// break;
case "task_status_post":
case "task_finish_post":
handleTaskPost(deviceId, topic, payload, action);
break;
case "config_reply":
@@ -117,7 +130,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
log.debug("【位置数据】deviceId={}, payload={}", deviceId, payload);
HostLocationRelTimeDTO locationRelTimeDTO = JsonUtils.parseObject(payload, HostLocationRelTimeDTO.class);
if (locationRelTimeDTO != null) {
WebStatusMessageDTO dto = createWebDeviceLocationMessage(locationRelTimeDTO);
WebStatusMessageDTO dto = createWebDeviceLocationMessage(locationRelTimeDTO, deviceId);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
@@ -125,22 +138,30 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("位置数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(), e.getMessage());
log.error("位置数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());
}
}
}
//todo 推送实时位置和状态消息到外部
//todo 记录到内存 开线程池队列 逐一转发
// GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_LOCATION_TOPIC, deviceId),
// JsonUtils.toJsonString(dto));
// todo 推送实时位置和状态消息到外部
// todo 记录到内存 开线程池队列 逐一转发
// GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
// String.format(MqttTopic.DEVICE_LOCATION_TOPIC, deviceId),
// JsonUtils.toJsonString(dto));
// todo 保存到内存
String key = NettyCacheKey.latestPositonKey + deviceId;
LocationMessage locationMessage = locationRelTimeDTO.getData();
locationMessage.setDeviceId(deviceId);
redisCache.setCacheObject(key, locationMessage);
}
} catch (Exception e) {
log.error("位置消息解析失败: deviceId={}, payload={}, error={}", deviceId, payload, e.getMessage());
log.error("位置消息解析失败: deviceId={}, payload={}, error={}", deviceId, payload, e);
}
}
public WebStatusMessageDTO createWebDeviceLocationMessage(HostLocationRelTimeDTO locationRelTimeDTO) {
public WebStatusMessageDTO createWebDeviceLocationMessage(HostLocationRelTimeDTO locationRelTimeDTO,
String deviceId) {
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
List<DeviceStatusDetail> transferData = new ArrayList<>();
DeviceStatusDetail lat = new DeviceStatusDetail();
@@ -156,13 +177,73 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
lng.setUnit("");
transferData.add(lng);
DeviceStatusDetail yaw = new DeviceStatusDetail();
yaw.setName("yaw");
yaw.setValue(String.valueOf(locationRelTimeDTO.getData().getYaw()));
yaw.setUnit("");
transferData.add(yaw);
DeviceStatusDetail fix_status = new DeviceStatusDetail();
fix_status.setName("fix_status");
fix_status.setValue(String.valueOf(locationRelTimeDTO.getData().getFix_status()));
fix_status.setUnit("");
transferData.add(fix_status);
DeviceStatusDetail altitude = new DeviceStatusDetail();
altitude.setName("altitude");
altitude.setValue(String.valueOf(locationRelTimeDTO.getData().getAltitude()));
altitude.setUnit("");
transferData.add(altitude);
DeviceStatusDetail status = new DeviceStatusDetail();
status.setName("status");
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// todo error故障
if (nettyDevice != null) {
if (nettyDevice.getOnlineStatus() == 0) {
status.setValue(DeviceStatusEnum.offline.getCode());
} else {
if (nettyDevice.getTask() != null && nettyDevice.getTask().isTaskAccepted()) {
status.setValue(DeviceStatusEnum.working.getCode());
} else {
status.setValue(DeviceStatusEnum.idle.getCode());
}
}
} else {
status.setValue(DeviceStatusEnum.offline.getCode());
}
status.setUnit("");
transferData.add(status);
webStatusMessageDTO.setData(transferData);
webStatusMessageDTO.setType(MesType.locationInfo);
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) {
DeviceMapPushDTO dto = new DeviceMapPushDTO();
dto.setA(Double.parseDouble(altitude.getValue()));
dto.setId(deviceId);
// dto.setB();
// dto.setHa();
dto.setF(fix_status.getValue());
dto.setS(status.getValue());
dto.setLat(Double.parseDouble(lat.getValue()));
dto.setLng(Double.parseDouble(lng.getValue()));
dto.setT(nettyDevice.getCurrentTaskId());
dto.setY(Double.parseDouble(yaw.getValue()));
siteMemory.saveMaPushDTO(deviceId, dto);
}
}
return webStatusMessageDTO;
}
public WebStatusMessageDTO createWebDeviceRealtimeMessage(HostVehicleRelTimeDTO vehicleRelTimeDTO) {
//todo 状态消息
// todo 状态消息
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
List<DeviceStatusDetail> transferData = new ArrayList<>();
@@ -204,6 +285,26 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
try {
HostVehicleRelTimeDTO vehicleRelTimeDTO = JsonUtils.parseObject(payload, HostVehicleRelTimeDTO.class);
if (vehicleRelTimeDTO != null) {
// todo 更新里程数 里程数 * 割幅0.8
vehicleRelTimeDTO.getData().getDistance();
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
if (nettyDevice != null) {
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
DeviceRunStatistics deviceRunStatistics = siteMemory.getRunStatistics(deviceId);
if (deviceRunStatistics == null) {
deviceRunStatistics = new DeviceRunStatistics();
}
deviceRunStatistics.setDeviceId(deviceId);
deviceRunStatistics.setDistance(vehicleRelTimeDTO.getData().getDistance());
deviceRunStatistics.setWorkArea(vehicleRelTimeDTO.getData().getDistance() * 0.8);
siteMemory.saveRunStatistics(deviceRunStatistics);
}
}
WebStatusMessageDTO dto = createWebDeviceRealtimeMessage(vehicleRelTimeDTO);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
@@ -212,27 +313,17 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(), e.getMessage());
log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());
}
}
}
// GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceId),
// JsonUtils.toJsonString(dto));
}
} catch (Exception e) {
log.error("实时消息解析失败: deviceId={}, payload={}, error={}", deviceId, payload, e.getMessage());
}
}
/**
* 处理状态变更事件
* topic: mower/{deviceId}/event/status/post
*/
private void handleStatusPost(String deviceId, String topic, String payload) {
log.info("【状态变更】deviceId={}, payload={}", deviceId, payload);
}
/**
* 处理心跳
* topic: mower/{deviceId}/event/heartbeat/post
@@ -261,35 +352,52 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
private void handleTaskPost(String deviceId, String topic, String payload, String action) {
log.info("【任务上报】deviceId={}, action={}, payload={}", deviceId, action, payload);
HostTaskStatusDTO dto = JsonUtils.parseObject(payload, HostTaskStatusDTO.class);
if (dto != null && !StringUtils.isEmpty(dto.getStatus())) {
NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
if ("completed".equals(dto.getStatus())) {
nettyDevice.finishTask();
Long taskId = nettyDevice.finishTask();
WebDeviceTaskStatusMessageDTO sendDto = new WebDeviceTaskStatusMessageDTO();
sendDto.setDeviceId(deviceId);
sendDto.setTaskId(taskId);
sendDto.setStatus(DeviceTaskStaus.FINISH.toString());
sendDto.setType(MesType.device_task_change);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(sendDto));
} catch (Exception e) {
log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());
}
}
}
}
if ("cancelled".equals(dto.getStatus())) {
nettyDevice.canceledTask();
}
// if("paused".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
// if("failed".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
// if("accepted".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
// if("running".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
// if("paused".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
if ("failed".equals(dto.getStatus())) {
nettyDevice.failedTask();
}
// if("accepted".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
// if("running".equals(dto.getStatus())){
// NettyDevice nettyDevice = deviceSessionManager.getDevice(deviceId);
// nettyDevice.finishTask();
// }
}
}
/**
@@ -306,24 +414,23 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
log.debug("【控制响应】deviceId={}, payload={}", deviceId, payload);
}
/**
* 处理控制指令响应
*/
private void handleRouteReply(String deviceId, String topic, String payload) {
log.debug("【路径任务下发响应】deviceId={}, payload={}", deviceId, payload);
//todo 更新任务接收状态
// todo 更新任务接收状态
HostNavigationReplyDTO replyDTO = JsonUtils.parseObject(payload, HostNavigationReplyDTO.class);
NettyDevice device = deviceSessionManager.getDevice(deviceId);
if (replyDTO.isAccepted()) {
if (device != null && device.getTask() != null && String.valueOf(device.getTask().getId()).equals(replyDTO.getTask_id())) {
if (device != null && device.getTask() != null
&& String.valueOf(device.getTask().getId()).equals(replyDTO.getTask_id())) {
device.getTask().setTaskAccepted(true);
}
}
}
/**
* 从 Topic 中解析 deviceId
* Topic 格式:mower/{deviceId}/...
@@ -350,79 +457,34 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
}
StringBuilder path = new StringBuilder();
for (int i = 2; i < parts.length; i++) {
if (i > 2) path.append("/");
if (i > 2)
path.append("/");
path.append(parts[i]);
}
String remaining = path.toString();
if (remaining.equals("property/location/post")) return "location_post";
if (remaining.equals("property/realtime/post")) return "realtime_post";
if (remaining.equals("event/status/post")) return "status_post";
if (remaining.equals("event/heartbeat/post")) return "heartbeat_post";
if (remaining.equals("event/error/post")) return "error_post";
if (remaining.equals("task/route/post")) return "route_post";
if (remaining.equals("task/point/post")) return "point_post";
if (remaining.equals("task/status/post")) return "task_status_post";
if (remaining.equals("task/finish/post")) return "task_finish_post";
if (remaining.equals("action/config/reply")) return "config_reply";
if (remaining.equals("action/control/reply")) return "control_reply";
if (remaining.equals("task/target/reply")) return "route_reply";
if (remaining.equals("property/location/post"))
return "location_post";
if (remaining.equals("property/realtime/post"))
return "realtime_post";
if (remaining.equals("event/heartbeat/post"))
return "heartbeat_post";
if (remaining.equals("event/error/post"))
return "error_post";
// if (remaining.equals("task/route/post")) return "route_post";
// if (remaining.equals("task/point/post")) return "point_post";
if (remaining.equals("task/status/post"))
return "task_status_post";
if (remaining.equals("action/config/reply"))
return "config_reply";
if (remaining.equals("action/control/reply"))
return "control_reply";
if (remaining.equals("task/target/reply"))
return "route_reply";
return null;
}
private double getDouble(JsonNode node, String... names) {
for (String name : names) {
JsonNode fn = node.get(name);
if (fn != null && !fn.isNull()) {
if (fn.isNumber()) return fn.asDouble();
try {
return Double.parseDouble(fn.asText());
} catch (Exception ignored) {
}
}
}
return -1.0;
}
private Double getDoubleObj(JsonNode node, String... names) {
for (String name : names) {
JsonNode fn = node.get(name);
if (fn != null && !fn.isNull()) {
if (fn.isNumber()) return fn.asDouble();
try {
return Double.parseDouble(fn.asText());
} catch (Exception ignored) {
}
}
}
return null;
}
private int getInt(JsonNode node, String... names) {
for (String name : names) {
JsonNode fn = node.get(name);
if (fn != null && !fn.isNull()) {
if (fn.isNumber()) return fn.asInt();
try {
return Integer.parseInt(fn.asText());
} catch (Exception ignored) {
}
}
}
return -1;
}
private String getString(JsonNode node, String... names) {
for (String name : names) {
JsonNode fn = node.get(name);
if (fn != null && !fn.isNull()) {
return fn.asText();
}
}
return null;
}
@Override
public void onConnectionLost(String deviceKey, Throwable cause) {
log.warn("主机监控连接断开: deviceKey={}, reason={}", deviceKey, cause.getMessage());

View File

@@ -1,6 +1,5 @@
package com.maibu.mqtt;
public class MqttTopic {
/** @deprecated 通用设备主题,建议使用 MOWER_* 系列主题 */
@@ -13,6 +12,7 @@ public class MqttTopic {
public static final String DEVICE_TASK_ARRIVE_TOPIC = "task/%s/arrive";
/** @deprecated 通用设备主题,建议使用 MOWER_* 系列主题 */
public static final String DEVICE_ERROR_PUSH_TOPIC = "device/%s/error";
public static final String DEVICE_ROUTE_PUSH_TOPIC = "device/%s/route/post";
/** 产品标识:割草机 */
public static final String MOWER_PRODUCT = "mower";
@@ -47,8 +47,9 @@ public class MqttTopic {
// ==================== 任务管理 ====================
/** 路径规划下发(平台->设备),对应 TCP 0x01 path */
// public static final String MOWER_TASK_ROUTE_SET = "mower/%s/task/route/set";
// public static final String MOWER_TASK_ROUTE_POST = "mower/%s/task/route/post";
// public static final String MOWER_TASK_ROUTE_SET = "mower/%s/task/route/set";
// public static final String MOWER_TASK_ROUTE_POST =
// "mower/%s/task/route/post";
public static final String MOWER_TASK_ROUTE_SET = "mower/%s/task/target/set";
@@ -57,28 +58,32 @@ public class MqttTopic {
public static final String MOWER_TASK_POINT_POST = "mower/%s/task/point/post";
/** 任务状态变更上报:执行中/暂停/完成等(设备->平台) */
public static final String MOWER_TASK_STATUS_POST = "mower/%s/task/status/post";
/** 任务完成上报(设备->平台) */
public static final String MOWER_TASK_FINISH_POST = "mower/%s/task/finish/post";
// ==================== 错误告警 ====================
/** 设备错误告警上报:电机故障/传感器异常等(设备->平台) */
public static final String MOWER_ERROR_POST = "mower/%s/event/error/post";
// ==================== OTA 固件升级 ====================
// /** 下发 OTA 升级指令(平台->设备) */
// public static final String MOWER_OTA_UPGRADE_SET = "mower/%s/ota/upgrade/set";
// /** OTA 升级进度上报(设备->平台) */
// public static final String MOWER_OTA_PROGRESS_POST = "mower/%s/ota/progress/post";
// /** OTA 升级结果上报(设备->平台) */
// public static final String MOWER_OTA_RESULT_POST = "mower/%s/ota/result/post";
// /** 下发 OTA 升级指令(平台->设备) */
// public static final String MOWER_OTA_UPGRADE_SET =
// "mower/%s/ota/upgrade/set";
// /** OTA 升级进度上报(设备->平台) */
// public static final String MOWER_OTA_PROGRESS_POST =
// "mower/%s/ota/progress/post";
// /** OTA 升级结果上报(设备->平台) */
// public static final String MOWER_OTA_RESULT_POST =
// "mower/%s/ota/result/post";
// ==================== 设备信息 ====================
// /** 查询设备信息(平台->设备) */
// public static final String MOWER_INFO_DEVICE_GET = "mower/%s/info/device/get";
// /** 设备信息响应(设备->平台) */
// public static final String MOWER_INFO_DEVICE_REPLY = "mower/%s/info/device/reply";
// /** 查询设备信息(平台->设备) */
// public static final String MOWER_INFO_DEVICE_GET =
// "mower/%s/info/device/get";
// /** 设备信息响应(设备->平台) */
// public static final String MOWER_INFO_DEVICE_REPLY =
// "mower/%s/info/device/reply";
/** 设备版本信息上报(设备->平台) */
// public static final String MOWER_INFO_VERSION_POST = "mower/%s/info/version/post";
// public static final String MOWER_INFO_VERSION_POST =
// "mower/%s/info/version/post";
// ==================== 通配符订阅 ====================
/** 订阅所有设备的状态变更事件 */
@@ -98,9 +103,6 @@ public class MqttTopic {
public static final String MOWER_HEARTBEAT = "mower/+/event/heartbeat/post";
/**
* 格式化 Topic 模板,将 %s 替换为设备ID
*

View File

@@ -6,7 +6,7 @@ import com.huaweicloud.sdk.iot.device.client.requests.CommandRsp;
import com.huaweicloud.sdk.iot.device.client.requests.DeviceMessage;
import com.huaweicloud.sdk.iot.device.client.requests.ServiceProperty;
import com.huaweicloud.sdk.iot.device.transport.ActionListener;
import com.maibu.common.NettyCacheKey;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DeviceRunningStatusHistory;
import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.redis.RedisCache;

View File

@@ -46,10 +46,10 @@ public class DeviceTaskController extends BaseController {
@GetMapping("/getSiteDevicePlan")
public AjaxResult getSiteDevicePlan(@RequestParam Long siteId,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
@RequestParam(required = false) String deviceId,
@RequestParam(required = false) DeviceTaskStaus taskStaus) {
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startTime,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endTime,
@RequestParam(required = false) String deviceId,
@RequestParam(required = false) DeviceTaskStaus taskStaus) {
return AjaxResult.success(deviceTaskService.getSiteDevicePlan(siteId, startTime, endTime, deviceId, taskStaus));
}
@@ -86,7 +86,6 @@ public class DeviceTaskController extends BaseController {
return AjaxResult.success(deviceTaskService.concurrentDevicePlanTask(deviceId));
}
@GetMapping("/workStatistics")
public AjaxResult workStatistics(@RequestParam Long userId) {
return AjaxResult.success(deviceTaskService.workStatistics(userId));
@@ -94,13 +93,13 @@ public class DeviceTaskController extends BaseController {
@PostMapping("/deviceTaskPool")
public TableDataInfo deviceTaskPool(@RequestBody DeviceTaskQueryDTO dto) {
startPostPage(dto.getPageNum(),dto.getPageSize());
startPostPage(dto.getPageNum(), dto.getPageSize());
return getDataTable(deviceTaskService.deviceTaskPool(dto));
}
@PostMapping("/getSiteDeviceTaskHistory")
public TableDataInfo getSiteDeviceTaskHistory(@RequestBody DeviceTaskQueryDTO dto) {
startPostPage(dto.getPageNum(),dto.getPageSize());
startPostPage(dto.getPageNum(), dto.getPageSize());
return getDataTable(deviceTaskService.getSiteDeviceTaskHistory(dto));
}
@@ -125,6 +124,31 @@ public class DeviceTaskController extends BaseController {
return AjaxResult.success(deviceTaskService.createDeviceTask(dto, getLoginUser().getUsername()));
}
@PostMapping("/createRegionDeviceTask")
public AjaxResult createRegionDeviceTask(@RequestBody DeviceTaskCommandDTO dto) {
String deviceId = dto.getDeviceId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
Long regionId = dto.getRegionId();
if (StringUtils.isEmpty(deviceId)) {
return AjaxResult.error("deviceId为空!");
}
if (siteId == null) {
return AjaxResult.error("siteId为空!");
}
if (orgId == null) {
return AjaxResult.error("orgId为空!");
}
if (regionId == null) {
return AjaxResult.error("regionId为空!");
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory.hasTask(deviceId)) {
return AjaxResult.error("当前设备存在任务!");
}
return AjaxResult.success(deviceTaskService.createRegionDeviceTask(dto, getLoginUser().getUsername()));
}
@PostMapping("/cancelTask")
public AjaxResult cancelTask(@RequestBody DeviceTaskCommandDTO dto) throws MqttException {
String deviceId = dto.getDeviceId();
@@ -152,5 +176,4 @@ public class DeviceTaskController extends BaseController {
return AjaxResult.success(deviceTaskService.recoveryTask(dto, getUsername()));
}
}

View File

@@ -42,6 +42,9 @@ public class InitThread implements ApplicationRunner {
@Resource(name = FastBeeConstant.TASK.DEVICE_HEARTBEAT_MONITOR)
private Executor deviceHeartBeatMonitorExecutor;
@Resource(name = FastBeeConstant.TASK.MAP_MESSAGE_PUSH)
private Executor mapMessagePushExecutor;
@Resource(name = FastBeeConstant.TASK.COMMON_DEVICE_MONITOR)
private Executor commonDeviceMonitorExecutor;
@@ -127,6 +130,11 @@ public class InitThread implements ApplicationRunner {
GlobalMemory.initMqttDeviceMonitor(mqttHostUrl, mqttClientId, mqttUsername, mqttPassword);
// 地图监控推送
mapMessagePushExecutor.execute(() -> {
deviceThreadService.mapMessagePush();
});
// 上位机设备心跳监控
deviceHeartBeatMonitorExecutor.execute(() -> {
deviceThreadService.heartBeatMonitor();

View File

@@ -23,7 +23,7 @@ import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.maibu.constant.CommandConstant;
import com.maibu.common.NettyCacheKey;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.DeviceRunningStatusHistory;
import com.maibu.core.business.DeviceStatusRecordDTO;
@@ -62,7 +62,6 @@ public class DataToDataBaseHandler extends SimpleChannelInboundHandler<String> {
@Autowired
private DeviceRunParamMapper deviceRunParamMapper;
@Value("${mqtt.client-id}")
private String mqttClientId;
@@ -99,8 +98,9 @@ public class DataToDataBaseHandler extends SimpleChannelInboundHandler<String> {
String deviceStatus = new String(bytes, 2, bytes.length - 4, StandardCharsets.UTF_8).trim();
String[] split = deviceStatus.split(",");
WebStatusMessageDTO dto = createWebDeviceStatusMessage(split);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceID),
JsonUtils.toJsonString(dto));
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceID),
JsonUtils.toJsonString(dto));
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceID);
if (!CollectionUtils.isEmpty(controlMasters)) {
@@ -134,19 +134,15 @@ public class DataToDataBaseHandler extends SimpleChannelInboundHandler<String> {
latestStatus.setDeviceId(deviceID);
} else {
latestStatus = nettyDevice.getLatestStatus();
// 使用Duration.between计算两个时间点之间的持续时间
Duration duration = Duration.between(latestStatus.getStartTime(), LocalDateTime.now());
long minutes = duration.toMinutes();
latestStatus.setTime(minutes);
}
latestStatus.setWorkArea(Double.valueOf(workArea));
latestStatus.setDistance(Double.valueOf(workArea) / 0.8);
nettyDevice.setLatestStatus(latestStatus);
}
} else if (bytes[2] == CommandConstant.readConfig) {
DeviceRunParam runParam = DeviceRunParam.fromBytes(bytes);
logger.debug("收到返回的设备运行参数: {}", JsonUtils.toJsonString(runParam));
CompletableFuture<DeviceRunParam> future =
ctx.channel().attr(Constant.READ_CONFIG_KEY).get();
CompletableFuture<DeviceRunParam> future = ctx.channel().attr(Constant.READ_CONFIG_KEY).get();
if (future != null) {
future.complete(runParam);
ctx.channel().attr(Constant.READ_CONFIG_KEY).set(null);
@@ -158,7 +154,6 @@ public class DataToDataBaseHandler extends SimpleChannelInboundHandler<String> {
}
}
public WebStatusMessageDTO createWebDeviceStatusMessage(String[] split) {
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
List<DeviceStatusDetail> transferData = transferStatusData(split);

View File

@@ -8,7 +8,6 @@ import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import com.maibu.memory.DeviceSessionManager;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
@@ -19,13 +18,13 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.constant.CommandConstant;
import com.maibu.constant.Constant;
import com.maibu.core.business.Device;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.domain.entity.SysUser;
import com.maibu.core.domain.entity.UserClient;
import com.maibu.core.enums.CommandRequestType;
import com.maibu.core.enums.ConnectionCloseReason;
import com.maibu.core.enums.ConnectorStatus;
@@ -34,12 +33,12 @@ import com.maibu.core.enums.DeviceStatus;
import com.maibu.core.enums.DeviceTaskStaus;
import com.maibu.core.enums.MesType;
import com.maibu.core.enums.RespondCode;
import com.maibu.dto.DeviceLoginResponseDTO;
import com.maibu.dto.DeviceRequestDTO;
import com.maibu.dto.DeviceRespondDTO;
import com.maibu.dto.DeviceStatusChangeDTO;
import com.maibu.dto.DeviceTaskStatusMessageDTO;
import com.maibu.mapper.DeviceRunStatisticsMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.service.IDeviceService;
@@ -74,9 +73,6 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
@Autowired
private IDeviceService deviceService;
@Autowired
private ISysUserService userService;
@Autowired
private DeviceRunStatisticsMapper deviceRunStatisticsMapper;
@@ -149,8 +145,24 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
// todo 更新历史作业消息
}
if (nettyDevice.getLatestStatus() != null) {
nettyDevice.getLatestStatus().setEndTime(LocalDateTime.now());
deviceRunStatisticsMapper.insert(nettyDevice.getLatestStatus());
LambdaQueryWrapper<DeviceRunStatistics> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DeviceRunStatistics::getDeviceId, deviceId);
DeviceRunStatistics existing = deviceRunStatisticsMapper
.selectOne(queryWrapper);
if (existing != null) {
nettyDevice.getLatestStatus().setId(existing.getId());
nettyDevice.getLatestStatus().setDistance(
existing.getDistance() + nettyDevice.getLatestStatus().getDistance());
nettyDevice.getLatestStatus().setWorkArea(
existing.getWorkArea() + nettyDevice.getLatestStatus().getWorkArea());
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
nettyDevice.getLatestStatus().setTime(existing.getTime() + time / (1000 * 60)); // 累加时长,单位为分钟
} else {
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
nettyDevice.getLatestStatus().setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(nettyDevice.getLatestStatus());
}
}
sessionManager.removeDevice(deviceId);
@@ -190,12 +202,60 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
NettyDevice masterDevice = sessionManager.getDevice(sessionId);
if (masterDevice == null) {
// sessionManager.getControl(sessionId);
// sessionManager.getControl(sessionId);
handleMasterConnect(ctx, sessionId, null, ConnectorStatus.ACTIVE);
} else {
ctx.channel().attr(Constant.ATT_DEVICE_ID).set(sessionId);
}
}
} else {
handleSlaveConnect(ctx, data);
logger.info("{}: 下位机连接", data);
Device device = deviceService.selectDeviceBySerialNumber(data);
if (device == null) {
device = new Device();
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setSerialNumber(data);
device.setDeviceName(data);
device.setProductId(-1L);
device.setTenantId(-1L);
device.setFirmwareVersion(BigDecimal.valueOf(1.0));
device.setProductName("割草机产品MC700");
device.setCreateTime(LocalDateTime.now());
device.setUpdateTime(LocalDateTime.now());
device.setHasHost(false);
deviceService.insertDeviceBySelf(device);
} else {
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setUpdateTime(LocalDateTime.now());
device.setHasHost(false);
deviceService.updateDeviceBySelf(device);
}
NettyDevice slaveDevice = sessionManager.getDevice(data);
if (slaveDevice != null) {
slaveDevice.setOnlineStatus(1);
slaveDevice.setDevice(device);
}
// // 推送json 找到设备绑定的主机进行推送
// List<NettyDevice> controlMasters =
// sessionManager.getAllSlaveControl(device.getSerialNumber());
// if (!CollectionUtils.isEmpty(controlMasters)) {
// controlMasters.forEach(x -> {
// DeviceStatusChangeDTO changeDTO = new DeviceStatusChangeDTO();
// changeDTO.setDeviceId(data);
// changeDTO.setStatus(DeviceStatus.online.getCode());
// changeDTO.setEvent(RespondCode.device_status_changed);
// ByteBuf buf = ctx.alloc().buffer();
// CommandUtils.buildCommand(buf, changeDTO, CommandConstant.interaction);
// String content = buf.toString(CharsetUtil.UTF_8);
// logger.info("推送下位机登录状态消息:{}", content);
// if (x.getChannel() != null && x.getChannel().isActive()) {
// x.getChannel().writeAndFlush(buf);
// }
// });
// }
}
}
} else if (cmdType == CommandConstant.interaction) {
@@ -251,7 +311,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
changeDTO.setType(MesType.device_task_change);
changeDTO.setTaskId(taskId);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_STATUS_TOPIC, taskId),
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_TASK_STATUS_TOPIC, taskId),
JsonUtils.toJsonString(changeDTO));
List<NettyDevice> controlMasters = sessionManager
.getAllSlaveControl(deviceId);
@@ -274,7 +335,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
reportDTO.setTaskId(taskId);
reportDTO.setEntity(device.getCurrentPoint());
reportDTO.setType(MesType.device_task_arrive_point);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_ARRIVE_TOPIC, taskId),
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_TASK_ARRIVE_TOPIC, taskId),
JsonUtils.toJsonString(reportDTO));
List<NettyDevice> controlMasters = sessionManager
@@ -307,10 +369,10 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
logger.info("12指令切换权限,c:{}", c.getConnectorId());
if (!c.getConnectorId().equals(masterId)) {
// c.setCurrentSlaveId(null);
// c.removeConnectedDevice(slaveDevice);
// c.removeConnectedDevice(slaveDevice);
c.setConnectorStatus(ConnectorStatus.RECEIVER);
sessionManager.unLock(c.getConnectorId());
// sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
// sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
}
});
}
@@ -319,7 +381,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
masterDevice.setCurrentSlaveId(slaveId);
masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
masterDevice.addConnectedDevice(slaveDevice);
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1);
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(),
// slaveId, 1);
} else {
logger.info("权限切换请求被拒绝");
}
@@ -350,73 +413,81 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
}
// /**
// * 找到当前设备控制的主机 转发控制请求
// */
// private void handlePermissionRequest(DeviceRequestDTO requestDTO, byte[] bytes, ChannelHandlerContext ctx) {
// logger.info("转发控制请求 :{}", JsonUtils.toJsonString(requestDTO));
// String slaveId = requestDTO.getDeviceId();
// List<NettyDevice> controlList = sessionManager.getSlaveControl(slaveId);
// String masterId = requestDTO.getUserId() + ":" + requestDTO.getPlatform();
// logger.info("转发控制请求 controlList :{}", JsonUtils.toJsonString(controlList));
// if (!CollectionUtils.isEmpty(controlList)) {
// // 如果当前设备有控制
// logger.info("转发控制请求 发送报文");
// NettyDevice controlDevice = controlList.get(0);
// if (controlDevice != null && controlDevice.getChannel() != null && controlDevice.getChannel().isActive()) {
// controlDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// logger.info("转发控制请求 发送报文结束 deviceId :{}", controlDevice.getConnectorId());
// controlRequestMap.put(masterId, slaveId);
// logger.info("转发控制请求 controlRequestMap:{}", JsonUtils.toJsonString(controlRequestMap));
// }
//
// } else {
// // 判断直接给权限 还是 判断是否有该账号其他端的的控制有权限
// NettyDevice activeDevice = sessionManager.getUserControl(requestDTO.getUserId());
// boolean sendMes = true;
// if (activeDevice == null) {
// sendMes = false;
// } else {
// if (activeDevice.getConnectorId().equals(masterId)) {
// sendMes = false;
// }
// }
// if (sendMes) {
// if (activeDevice.getChannel() != null && activeDevice.getChannel().isActive()) {
// activeDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// logger.info("转发控制请求2 发送报文结束 deviceId :{}", activeDevice.getConnectorId());
// controlRequestMap.put(masterId, slaveId);
// logger.info("转发控制请求2 controlRequestMap:{}", JsonUtils.toJsonString(controlRequestMap));
// }
// } else {
// NettyDevice masterDevice = sessionManager.getDevice(masterId);
// if (masterDevice != null) {
// NettyDevice slaveDevice = sessionManager.getDevice(slaveId);
// masterDevice.setCurrentSlaveId(slaveId);
// masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
// masterDevice.addConnectedDevice(slaveDevice);
//
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1);
// if (masterDevice.getChannel() != null && masterDevice.getChannel().isActive()) {
// DeviceRequestDTO reDto = new DeviceRequestDTO();
// reDto.setPlatform(requestDTO.getPlatform());
// DeviceRespondDTO respond = new DeviceRespondDTO();
// respond.setSwitchResult(true);
// respond.setHolder("you");
// respond.setDeviceId(slaveId);
// reDto.setRespond(respond);
// ByteBuf buf = ctx.alloc().buffer();
// CommandUtils.buildCommand(buf, reDto, CommandConstant.interaction);
// String content = buf.toString(CharsetUtil.UTF_8);
// masterDevice.getChannel().writeAndFlush(buf);
// logger.info("转发控制请求设置当前控制2 发送报文:{} deviceId :{}", content, masterId);
// }
// } else {
//
// }
// }
// }
// }
// /**
// * 找到当前设备控制的主机 转发控制请求
// */
// private void handlePermissionRequest(DeviceRequestDTO requestDTO, byte[]
// bytes, ChannelHandlerContext ctx) {
// logger.info("转发控制请求 :{}", JsonUtils.toJsonString(requestDTO));
// String slaveId = requestDTO.getDeviceId();
// List<NettyDevice> controlList = sessionManager.getSlaveControl(slaveId);
// String masterId = requestDTO.getUserId() + ":" + requestDTO.getPlatform();
// logger.info("转发控制请求 controlList :{}", JsonUtils.toJsonString(controlList));
// if (!CollectionUtils.isEmpty(controlList)) {
// // 如果当前设备有控制
// logger.info("转发控制请求 发送报文");
// NettyDevice controlDevice = controlList.get(0);
// if (controlDevice != null && controlDevice.getChannel() != null &&
// controlDevice.getChannel().isActive()) {
// controlDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// logger.info("转发控制请求 发送报文结束 deviceId :{}", controlDevice.getConnectorId());
// controlRequestMap.put(masterId, slaveId);
// logger.info("转发控制请求 controlRequestMap:{}",
// JsonUtils.toJsonString(controlRequestMap));
// }
//
// } else {
// // 判断直接给权限 还是 判断是否有该账号其他端的的控制有权限
// NettyDevice activeDevice =
// sessionManager.getUserControl(requestDTO.getUserId());
// boolean sendMes = true;
// if (activeDevice == null) {
// sendMes = false;
// } else {
// if (activeDevice.getConnectorId().equals(masterId)) {
// sendMes = false;
// }
// }
// if (sendMes) {
// if (activeDevice.getChannel() != null &&
// activeDevice.getChannel().isActive()) {
// activeDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// logger.info("转发控制请求2 发送报文结束 deviceId :{}", activeDevice.getConnectorId());
// controlRequestMap.put(masterId, slaveId);
// logger.info("转发控制请求2 controlRequestMap:{}",
// JsonUtils.toJsonString(controlRequestMap));
// }
// } else {
// NettyDevice masterDevice = sessionManager.getDevice(masterId);
// if (masterDevice != null) {
// NettyDevice slaveDevice = sessionManager.getDevice(slaveId);
// masterDevice.setCurrentSlaveId(slaveId);
// masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
// masterDevice.addConnectedDevice(slaveDevice);
//
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(),
// slaveId, 1);
// if (masterDevice.getChannel() != null &&
// masterDevice.getChannel().isActive()) {
// DeviceRequestDTO reDto = new DeviceRequestDTO();
// reDto.setPlatform(requestDTO.getPlatform());
// DeviceRespondDTO respond = new DeviceRespondDTO();
// respond.setSwitchResult(true);
// respond.setHolder("you");
// respond.setDeviceId(slaveId);
// reDto.setRespond(respond);
// ByteBuf buf = ctx.alloc().buffer();
// CommandUtils.buildCommand(buf, reDto, CommandConstant.interaction);
// String content = buf.toString(CharsetUtil.UTF_8);
// masterDevice.getChannel().writeAndFlush(buf);
// logger.info("转发控制请求设置当前控制2 发送报文:{} deviceId :{}", content, masterId);
// }
// } else {
//
// }
// }
// }
// }
/**
* 找到当前设备控制的主机 转发控制请求
@@ -469,7 +540,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
private void handleMasterConnect(ChannelHandlerContext ctx, String masterId, String slaveId,
ConnectorStatus status) {
ConnectorStatus status) {
ctx.channel().attr(Constant.ATT_DEVICE_ID).set(masterId);
sessionManager.registerDevice(masterId, ctx.channel(), ConnectorType.MASTER, status, slaveId);
// sessionManager.bindConnector(masterId, slaveId);

View File

@@ -1,6 +1,6 @@
package com.maibu.scheduled;
import com.maibu.common.NettyCacheKey;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.core.business.DeviceStatusRecordDTO;

View File

@@ -229,9 +229,9 @@ public class DevicePlanTaskMonitorService {
String deviceId = devicePlanTask.getDeviceId();
if (!StringUtils.isEmpty(deviceId) && deviceId.equals(key)) {
devicePlanTask.setTaskStaus(DeviceTaskStaus.EXECUTING);
siteMemory.addDevicePlanExecute(devicePlanTask);
device.setCurrentTaskId(devicePlanTask.getId());
device.setTask(devicePlanTask);
siteMemory.addDevicePlanExecute(devicePlanTask);
siteMemory.removeDevicePlanPrepare(devicePlanTask);
}
}

View File

@@ -24,6 +24,7 @@ import com.maibu.core.business.DeviceTaskPlanRule;
import com.maibu.core.business.WorkRecord;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.DeviceTaskCommandDTO;
import com.maibu.core.domain.entity.SysRegion;
import com.maibu.core.domain.entity.SysSite;
import com.maibu.core.domain.model.LoginUser;
import com.maibu.core.enums.DeviceTaskStaus;
@@ -34,6 +35,7 @@ import com.maibu.dto.DeviceWorkStatisticsDTO;
import com.maibu.mapper.DeviceMapper;
import com.maibu.mapper.DevicePlanMapper;
import com.maibu.mapper.DevicePlanTaskMapper;
import com.maibu.mapper.SysRegionMapper;
import com.maibu.mapper.SysSiteMapper;
import com.maibu.mapper.WorkRecordMapper;
import com.maibu.memory.GlobalMemory;
@@ -63,6 +65,9 @@ public class DeviceTaskService {
@Autowired
private SysSiteMapper sysSiteMapper;
@Autowired
private SysRegionMapper sysRegionMapper;
public int insertOrUpdate(DevicePlan devicePlan, LoginUser loginUser) {
Long id = devicePlan.getId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
@@ -477,6 +482,35 @@ public class DeviceTaskService {
return task.getId();
}
public Long createRegionDeviceTask(DeviceTaskCommandDTO dto, String username) {
LambdaQueryWrapper<SysRegion> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(SysRegion::getId, dto.getRegionId());
SysRegion region = sysRegionMapper.selectOne(queryWrapper);
if (region == null || region.getBindRoute() == null) {
throw new RuntimeException("区域未绑定线路!");
}
DevicePlanTask task = new DevicePlanTask();
task.setRouteId(region.getBindRoute());
task.setOrgId(dto.getOrgId());
task.setSiteId(dto.getSiteId());
task.setTaskStaus(DeviceTaskStaus.NEW);
task.setDeviceId(dto.getDeviceId());
task.setCreateBy(username);
task.setCreateTime(LocalDateTime.now());
task.setStartTime(dto.getStartTime());
devicePlanTaskMapper.saveOrUpdate(task);
if (dto.getOrgId() == null) {
SysSite site = sysSiteMapper.selectById(dto.getSiteId());
if (site != null) {
dto.setOrgId(site.getOrgId());
}
}
SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId());
siteMemory.addDevicePlanPrepare(task);
return task.getId();
}
public boolean cancelTask(DeviceTaskCommandDTO dto) throws MqttException {
String deviceId = dto.getDeviceId();
DevicePlanTask devicePlanTask = null;
@@ -489,9 +523,9 @@ public class DeviceTaskService {
}
NettyDevice device = deviceSessionManager.getDevice(deviceId);
if (device != null && device.getTask() != null) {
if(dto.isForceCancel()){
if (dto.isForceCancel()) {
return device.canceledTask();
}else {
} else {
return device.cancelingTask();
}
} else {

View File

@@ -1,30 +1,25 @@
package com.maibu.service;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.common.NettyCacheKey;
import com.maibu.constant.Constant;
import com.maibu.core.business.Device;
import com.maibu.core.business.DeviceRunningStatusHistory;
import com.maibu.core.business.DeviceStatusRecordDTO;
import com.maibu.core.business.ErrorIdentificationStandard;
import com.maibu.core.business.alarm_center.AlarmMessage;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.inter.WebsocketMesDispather;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
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;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.maibu.core.business.dto.DeviceMapPushDTO;
import com.maibu.core.business.dto.WebMapMessageDTO;
import com.maibu.core.enums.*;
import com.maibu.core.host.HeartBeatDTO;
import com.maibu.core.redis.RedisCache;
import com.maibu.dto.DeviceErrorPushDTO;
import com.maibu.mapper.ErrorIdentificationStandardMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.utils.CompareUtils;
import lombok.extern.slf4j.Slf4j;
import com.maibu.utils.json.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.s;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
@@ -32,17 +27,34 @@ import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.constant.Constant;
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.alarm_center.AlarmMessage;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.host.HeartBeatDTO;
import com.maibu.core.host.LocationMessage;
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;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.utils.CompareUtils;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@@ -75,10 +87,16 @@ public class DeviceThreadService {
@Autowired
private ScheduledExecutorService executor;
@Autowired
private HostLocationMapper hostLocationMapper;
@Autowired
private DeviceRunStatisticsMapper deviceRunStatisticsMapper;
public void deviceErrorMonitor() throws InterruptedException, IOException {
initStandard();
// TODO fix 后续是否分多个线程 一个site一个线程
// TODO fix 后续是否分多个线程 一个site一个线程
// 有还需要更新接受故障方式。
executor.scheduleWithFixedDelay(() -> {
try {
@@ -188,8 +206,10 @@ public class DeviceThreadService {
// }
// }
try {
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC, deviceId), dto);
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_ERROR_PUSH_TOPIC,
// deviceId), dto);
List<NettyDevice> controlMasters = sessionManager.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
controlMasters.forEach(x -> {
@@ -212,7 +232,8 @@ public class DeviceThreadService {
String compareValues = standard.getCompareValues();
CompareEnum compareType = standard.getCompareType();
String targetValue = knownClassFieldFinding(fieldName, history);
log.debug("compare2 compareType:{} compareValues:{},targetValue:{}", compareType, compareValues, targetValue);
log.debug("compare2 compareType:{} compareValues:{},targetValue:{}", compareType, compareValues,
targetValue);
if (!StringUtils.isEmpty(compareValues) && !StringUtils.isEmpty(targetValue)) {
boolean result = CompareUtils.compare(compareType, targetValue, compareValues);
log.debug("compare3 result:{}", result);
@@ -253,7 +274,6 @@ public class DeviceThreadService {
return null;
}
/**
* 监控心跳
*/
@@ -264,65 +284,145 @@ public class DeviceThreadService {
List<HeartBeatDTO> heartBeatDTOS = GlobalMemory.customMqttDeviceMonitor.getAllHeartBeat();
if (!CollectionUtils.isEmpty(heartBeatDTOS)) {
heartBeatDTOS.forEach(x -> {
if (x == null) {
return;
}
String deviceId = x.getSn();
Long lastActiveTime = x.getSysTimestamp();
NettyDevice nettyDevice = sessionManager.getDevice(x.getSn());
if (lastActiveTime == null) {
log.error("设备心跳时间为空,deviceId={}", deviceId);
return;
}
if (nowTime - lastActiveTime >= Constant.hostOfflineInterval) {
//超时了判断离线
// 超时了判断离线
if (nettyDevice != null) {
nettyDevice.status(0);
//todo 推送设备离线
}
} else {
if (nettyDevice == null) {
sessionManager.registerSlaveDevice(deviceId, ConnectorStatus.ACTIVE, null);
nettyDevice.status(DeviceStatus.offline.getType());
// todo 推送设备离线
String key = NettyCacheKey.latestPositonKey + deviceId;
// 保存一下最新一次的数据到 数据库
LocationMessage locationMessage = redisCache.getCacheObject(key);
if (locationMessage != null) {
LambdaQueryWrapper<LocationMessage> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(LocationMessage::getDeviceId, deviceId);
LocationMessage existing = hostLocationMapper.selectOne(queryWrapper);
if (existing != null) {
locationMessage.setId(existing.getId());
}
hostLocationMapper.saveOrUpdate(locationMessage);
}
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(BigDecimal.valueOf(1.0));
device.setProductName("割草机产品MC700");
device.setCreateTime(LocalDateTime.now());
device.setUpdateTime(LocalDateTime.now());
deviceService.insertDeviceBySelf(device);
} else {
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
// 推送json 找到设备绑定的主机进行推送
// List<NettyDevice> controlMasters = sessionManager.getAllSlaveControl(device.getSerialNumber());
// if (!CollectionUtils.isEmpty(controlMasters)) {
// controlMasters.forEach(x -> {
// DeviceStatusChangeDTO changeDTO = new DeviceStatusChangeDTO();
// changeDTO.setDeviceId(data);
// changeDTO.setStatus(DeviceStatus.online.getCode());
// changeDTO.setEvent(RespondCode.device_status_changed);
// ByteBuf buf = ctx.alloc().buffer();
// CommandUtils.buildCommand(buf, changeDTO, CommandConstant.interaction);
// String content = buf.toString(CharsetUtil.UTF_8);
// logger.info("推送下位机登录状态消息:{}", content);
// if (x.getChannel() != null && x.getChannel().isActive()) {
// x.getChannel().writeAndFlush(buf);
// }
// });
} else {
//todo 推送设备上线
nettyDevice.status(1);
Long orgId = nettyDevice.getDevice().getOrgId();
Long siteId = nettyDevice.getDevice().getSiteId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
if (siteMemory != null) {
DeviceRunStatistics deviceRunStatistics = siteMemory.getRunStatistics(deviceId);
if (deviceRunStatistics != null) {
LambdaQueryWrapper<DeviceRunStatistics> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DeviceRunStatistics::getDeviceId, deviceId);
DeviceRunStatistics existing = deviceRunStatisticsMapper
.selectOne(queryWrapper);
if (existing != null) {
deviceRunStatistics.setId(existing.getId());
deviceRunStatistics.setDistance(
existing.getDistance() + deviceRunStatistics.getDistance());
deviceRunStatistics.setWorkArea(
existing.getWorkArea() + deviceRunStatistics.getWorkArea());
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(existing.getTime() + time / (1000 * 60)); // 累加时长,单位为分钟
} else {
long time = System.currentTimeMillis() - nettyDevice.getLatestLoginTime();
deviceRunStatistics.setTime(time / (1000 * 60)); // 累加时长,单位为分钟
}
deviceRunStatisticsMapper.saveOrUpdate(deviceRunStatistics);
}
}
sessionManager.removeDevice(deviceId);
// TODO 统计总里程、总作业面积
}
} 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(BigDecimal.valueOf(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);
}
} else {
// todo 推送设备上线
nettyDevice.status(1);
nettyDevice.setDevice(device);
}
}
});
}
} catch (Exception e) {
log.error("执行监测心跳线程错误", e);
}
}, 0, 500, TimeUnit.MILLISECONDS);
}
/**
* 监控心跳
*/
public void mapMessagePush() {
executor.scheduleWithFixedDelay(() -> {
try {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
if (!CollectionUtils.isEmpty(list)) {
list.forEach(x -> {
Map<String, DeviceMapPushDTO> map = x.getAllDeviceMapPush();
if (!CollectionUtils.isEmpty(map)) {
List<DeviceMapPushDTO> pushList = new ArrayList<>(map.values());
WebMapMessageDTO dto = new WebMapMessageDTO();
dto.setData(pushList);
dto.setType(MesType.mapPush);
try {
websocketMesDispather.mapMessageDispather(x.getSiteId(), JsonUtils.toJsonString(pushList));
} catch (Exception e) {
log.error("实时地图数据websocket推送失败: siteId={}, error={}", x.getSiteId(),
e.getMessage(), e);
}
}
});
}
} catch (Exception e) {
log.error("执行监测心跳线程错误:{}", e.getMessage());
}
}, 0, 500, TimeUnit.MILLISECONDS);
}, 0, 100, TimeUnit.MILLISECONDS);
}
}

View File

@@ -333,7 +333,7 @@ public class TransferDeviceService {
}
masterDevice.setCurrentSlaveId(slaveId);
masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1);
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1);
dto.setSwitchControl(true);
dto.setHolder(platform);

View File

@@ -272,6 +272,14 @@ public class DeviceController extends BaseController {
return getDataTable(deviceService.getSiteList(getLoginUser(), device));
}
/**
* 查询设备列表 分配页面
*/
@GetMapping("/getDeviceBySpiltCode")
public AjaxResult getDeviceBySpiltCode(@RequestParam String code) {
return AjaxResult.success(deviceService.getDeviceBySpiltCode(code));
}
/**
* 查询设备列表 分配页面
*/

View File

@@ -4,6 +4,11 @@ import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import com.maibu.annotation.Log;
import com.maibu.core.domain.entity.SysUser;
import com.maibu.enums.BusinessType;
import com.maibu.utils.poi.ExcelUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@@ -18,6 +23,7 @@ import com.maibu.core.domain.AjaxResult;
import com.maibu.core.page.TableDataInfo;
import com.maibu.dto.BaseQueryDTO;
import com.maibu.service.impl.DeviceRunParamService;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/iot/deviceRunParam")
@@ -47,5 +53,12 @@ public class DeviceRunParamController extends BaseController {
public AjaxResult delete(@RequestBody List<Long> ids) {
return AjaxResult.success(service.delete(ids));
}
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file) throws Exception {
ExcelUtil<DeviceRunParam> util = new ExcelUtil<DeviceRunParam>(DeviceRunParam.class);
List<DeviceRunParam> paramList = util.importExcel(file.getInputStream());
boolean message = service.importParam(paramList);
return success(message);
}
}

View File

@@ -1,16 +1,5 @@
package com.maibu.controller;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.controller.BaseController;
import com.maibu.core.domain.R;
import com.maibu.memory.GlobalMemory;
import com.maibu.service.impl.HostComputerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
@@ -18,6 +7,32 @@ import java.util.Arrays;
import java.util.List;
import java.util.zip.GZIPInputStream;
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.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.WebRouteStatusMessageDTO;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.controller.BaseController;
import com.maibu.core.domain.R;
import com.maibu.core.enums.MesType;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.service.impl.HostComputerService;
import com.maibu.utils.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/iot/host")
@@ -28,10 +43,21 @@ public class HostComputerController extends BaseController {
@Autowired
private HostComputerService hostComputerService;
@Autowired
private WebsocketMesDispather websocketMesDispather;
@Autowired
private DeviceSessionManager deviceSessionManager;
@Value("${mqtt.client-id}")
private String mqttClientId;
/**
* 上传 csv.gz 轨迹文件并解析为 LatAndLngEntity 列表(分批处理,每批 BATCH_SIZE 条)
*
* <p>CSV 格式:第 1 列=cell_index,第 2 列=x(lat),第 3 列=y(lng)</p>
* <p>
* CSV 格式:第 1 列=cell_index,第 2 列=x(lat),第 3 列=y(lng)
* </p>
*
* @param file csv.gz 压缩文件
* @param taskId 任务ID
@@ -40,8 +66,7 @@ public class HostComputerController extends BaseController {
@PostMapping(value = "/upload-path-csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R uploadCsv(
@RequestPart("file") MultipartFile file,
@RequestParam("taskId") Long taskId
) {
@RequestParam("taskId") Long taskId) {
if (file == null || file.isEmpty()) {
return R.fail("文件不能为空");
}
@@ -61,7 +86,7 @@ public class HostComputerController extends BaseController {
int batchIndex = 0;
try (GZIPInputStream gzipInputStream = new GZIPInputStream(file.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream))) {
BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream))) {
String line;
int lineNum = 0;
@@ -74,7 +99,7 @@ public class HostComputerController extends BaseController {
String[] values = line.split(",");
if (lineNum == 1) {
if (lineNum < 4) {
log.info("CSV 表头: {}", Arrays.toString(values));
continue;
}
@@ -109,7 +134,8 @@ public class HostComputerController extends BaseController {
log.info("csv 解析完成: taskId={}, 共 {} 个轨迹点, 分 {} 批处理", taskId, allPath.size(), batchIndex);
GlobalMemory.taskPathMap.put(taskId, allPath);
sendMessage(taskId, allPath);
// TODO 推送数据到前端
return R.ok();
@@ -119,14 +145,49 @@ public class HostComputerController extends BaseController {
}
}
/**
* 定位信息 经纬度
*/
private void sendMessage(Long taskId, List<LatAndLngEntity> data) {
try {
WebRouteStatusMessageDTO dto = new WebRouteStatusMessageDTO();
String deviceId = deviceSessionManager.getDeviceByTaskId(taskId);
log.debug("sendMessage: taskId={}, deviceId={}", taskId, deviceId);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
log.debug("sendMessage: controlMasters={}", JsonUtils.toJsonString(controlMasters));
dto.setData(data);
dto.setDeviceId(deviceId);
dto.setTaskId(taskId);
dto.setType(MesType.route_post);
if (!CollectionUtils.isEmpty(controlMasters)) {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
log.info("sendMessage推送成功: connectorId={}, taskId={}", x.getConnectorId(), taskId);
} catch (Exception e) {
log.error("sendMessage推送失败: connectorId={}, error={}", x.getConnectorId(),
e.getMessage());
}
}
}
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId,
String.format(MqttTopic.DEVICE_ROUTE_PUSH_TOPIC, deviceId),
JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("sendMessage失败: taskId={}", taskId, e);
}
}
/**
* 从 CSV 行解析 LatAndLngEntity
* 第 2 列(x) → lat,第 3 列(y) → lng
* 第 3 列(x) → lat,第 4 列(y) → lng
*/
private LatAndLngEntity parseLatLng(String[] values) {
try {
String xStr = values[1].trim();
String yStr = values[2].trim();
String xStr = values[2].trim();
String yStr = values[3].trim();
if (xStr.isEmpty() || yStr.isEmpty()) {
return null;
@@ -145,11 +206,13 @@ public class HostComputerController extends BaseController {
/**
* 分批处理轨迹数据
*
* <p>每批 BATCH_SIZE 条数据触发一次,可用于:</p>
* <p>
* 每批 BATCH_SIZE 条数据触发一次,可用于:
* </p>
* <ul>
* <li>批量入库(insertBatch)</li>
* <li>发布 MQTT 消息到上位机</li>
* <li>数据校验/统计</li>
* <li>批量入库(insertBatch)</li>
* <li>发布 MQTT 消息到上位机</li>
* <li>数据校验/统计</li>
* </ul>
*
* @param taskId 任务ID
@@ -166,10 +229,14 @@ public class HostComputerController extends BaseController {
double minLng = Double.MAX_VALUE, maxLng = -Double.MAX_VALUE;
for (LatAndLngEntity p : path) {
if (p.getLat() < minLat) minLat = p.getLat();
if (p.getLat() > maxLat) maxLat = p.getLat();
if (p.getLng() < minLng) minLng = p.getLng();
if (p.getLng() > maxLng) maxLng = p.getLng();
if (p.getLat() < minLat)
minLat = p.getLat();
if (p.getLat() > maxLat)
maxLat = p.getLat();
if (p.getLng() < minLng)
minLng = p.getLng();
if (p.getLng() > maxLng)
maxLng = p.getLng();
}
log.info("【第 {} 批处理】taskId={}, 本批 {} 条, lat范围=[{}, {}], lng范围=[{}, {}]",

View File

@@ -40,9 +40,11 @@ public class WorkRecordController extends BaseController {
) {
int i = -1;
// WorkRecord workRecordObj = JsonUtils.parseObject(workRecord, WorkRecord.class);
// WorkRecord workRecordObj = JsonUtils.parseObject(workRecord,
// WorkRecord.class);
WorkRecord workRecord1 = workRecordService.selectWorkRecordByWorkNameAndSiteId(workRecord.getWorkName(), workRecord.getSiteId());
WorkRecord workRecord1 = workRecordService.selectWorkRecordByWorkNameAndSiteId(workRecord.getWorkName(),
workRecord.getSiteId());
if (workRecord1 != null) {
return R.fail("该任务已存在");
}
@@ -108,8 +110,8 @@ public class WorkRecordController extends BaseController {
@GetMapping("/selectByTaskId")
public R selectByTaskId(@RequestParam Long taskId) {
List<LatAndLngEntity> path = workRecordService.selectByTaskId(taskId);
return R.ok(path);
WorkRecord workRecord = workRecordService.selectByTaskId(taskId);
return R.ok(workRecord);
}
@GetMapping("getTaskPath")

View File

@@ -16,7 +16,6 @@ import java.util.List;
@Repository
public interface DeviceMapper extends BaseMapperX<Device> {
/**
* 根据设备编号查询设备
*
@@ -25,7 +24,6 @@ public interface DeviceMapper extends BaseMapperX<Device> {
*/
public Device selectDeviceBySerialNumber(String serialNumber);
/**
* 查询设备列表
*
@@ -34,7 +32,6 @@ public interface DeviceMapper extends BaseMapperX<Device> {
*/
public List<Device> selectDeviceList(Device device);
/**
* 根据产品ID查询产品下所有设备的编号
*
@@ -66,7 +63,6 @@ public interface DeviceMapper extends BaseMapperX<Device> {
*/
public int updateDevice(Device device);
/**
* 重置设备状态
*
@@ -74,7 +70,6 @@ public interface DeviceMapper extends BaseMapperX<Device> {
*/
public int resetDeviceStatus(String deviceNum);
/**
* 根据产品ID获取产品下所有编号
*
@@ -91,4 +86,6 @@ public interface DeviceMapper extends BaseMapperX<Device> {
*/
public List<String> selectSerialNumbersByProductId(@Param("productId") Long productId);
public Device selectDeviceBySpiltCode(@Param("code") String code);
}

View File

@@ -16,10 +16,8 @@ import java.util.List;
*/
public interface IDeviceService {
public AjaxResult updateDeviceBySelf(Device device);
public Device insertDeviceBySelf(Device device);
/**
@@ -30,7 +28,6 @@ public interface IDeviceService {
*/
public Device selectDeviceBySerialNumber(String serialNumber);
/**
* 查询设备列表
*
@@ -39,7 +36,6 @@ public interface IDeviceService {
*/
public List<Device> selectDeviceList(Device device);
/**
* 根据产品ID查询产品下所有设备的编号
*
@@ -55,7 +51,6 @@ public interface IDeviceService {
*/
public int selectDeviceCountByProductId(Long productId);
/**
* 重置设备状态
*
@@ -63,7 +58,6 @@ public interface IDeviceService {
*/
public int resetDeviceStatus(String deviceNum);
/**
* 根据产品ID获取产品下所有编号
*
@@ -72,7 +66,6 @@ public interface IDeviceService {
*/
public String[] getDeviceNumsByProductId(Long productId);
/**
* 查询产品下所有设备,返回设备编号
*
@@ -81,17 +74,16 @@ public interface IDeviceService {
*/
public List<String> selectSerialNumbersByProductId(Long productId);
public boolean bind(DeviceBindDTO bindDTO, String username);
public boolean unbind(DeviceBindDTO bindDTO, String username);
public List<Device> getSiteList(LoginUser loginUser, Device device);
public List<Device> getDeviceList(LoginUser loginUser, Device device);
public Device getDeviceBySpiltCode(String code);
public boolean paramModifyAuth(DeviceParamAuthDTO dto);
public boolean hasPermission(String deviceId);

View File

@@ -1,5 +1,21 @@
package com.maibu.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceRunParam;
@@ -10,17 +26,8 @@ import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
@@ -32,7 +39,8 @@ public class DeviceRunParamService {
@Autowired
private DeviceSessionManager sessionManager;
public boolean save(DeviceRunParam deviceRunParam) throws ExecutionException, InterruptedException, TimeoutException {
public boolean save(DeviceRunParam deviceRunParam)
throws ExecutionException, InterruptedException, TimeoutException {
NettyDevice nettyDevice = sessionManager.getDevice(deviceRunParam.getDeviceId());
if (nettyDevice == null || !nettyDevice.getChannel().isActive()) {
@@ -87,30 +95,73 @@ public class DeviceRunParamService {
return deviceRunParamMapper.selectList(queryWrapper);
}
public DeviceRunParam selectByDeviceId(String deviceId) throws ExecutionException, InterruptedException, TimeoutException {
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
if (nettyDevice != null && nettyDevice.getChannel() != null && nettyDevice.getChannel().isActive()) {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
try {
nettyDevice.readConfigCommand();
DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// public DeviceRunParam selectByDeviceId(String deviceId)
// throws ExecutionException, InterruptedException, TimeoutException {
LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(deviceId)) {
queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
// CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
// if (nettyDevice != null && nettyDevice.getChannel() != null &&
// nettyDevice.getChannel().isActive()) {
// nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
// try {
// nettyDevice.readConfigCommand();
// DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
// if (!StringUtils.isEmpty(deviceId)) {
// queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// }
// DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
// if (result != null) {
// param.setId(result.getId());
// param.setDeviceId(result.getDeviceId());
// param.setRunSpeed(result.getRunSpeed());
// param.setOrgId(nettyDevice.getDevice().getOrgId());
// param.setSiteId(nettyDevice.getDevice().getSiteId());
// }
// return param;
// } finally {
// nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
// }
// }
// return null;
// }
public DeviceRunParam selectByDeviceId(String deviceId)
throws ExecutionException, InterruptedException, TimeoutException {
LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
if (!StringUtils.isEmpty(deviceId)) {
queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
}
DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null && result.getHasHost() != null && result.getHasHost() == 1) {
return result;
} else {
NettyDevice nettyDevice = sessionManager.getDevice(deviceId);
CompletableFuture<DeviceRunParam> future = new CompletableFuture<>();
if (nettyDevice != null && nettyDevice.getChannel() != null && nettyDevice.getChannel().isActive()) {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(future);
try {
nettyDevice.readConfigCommand();
DeviceRunParam param = future.get(5, TimeUnit.SECONDS);
// LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
// if (!StringUtils.isEmpty(deviceId)) {
// queryWrapper.eq(DeviceRunParam::getDeviceId, deviceId);
// }
// DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null) {
param.setId(result.getId());
param.setDeviceId(result.getDeviceId());
param.setRunSpeed(result.getRunSpeed());
param.setOrgId(nettyDevice.getDevice().getOrgId());
param.setSiteId(nettyDevice.getDevice().getSiteId());
}
return param;
} finally {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
}
DeviceRunParam result = deviceRunParamMapper.selectOne(queryWrapper);
if (result != null) {
param.setId(result.getId());
param.setDeviceId(result.getDeviceId());
param.setRunSpeed(result.getRunSpeed());
param.setOrgId(nettyDevice.getDevice().getOrgId());
param.setSiteId(nettyDevice.getDevice().getSiteId());
}
return param;
} finally {
nettyDevice.getChannel().attr(Constant.READ_CONFIG_KEY).set(null);
}
}
return null;
@@ -130,5 +181,56 @@ public class DeviceRunParamService {
return i;
}
public boolean importParam(List<DeviceRunParam> params) {
try {
if (!CollectionUtils.isEmpty(params)) {
List<String> snList = params.stream().map(DeviceRunParam::getDeviceId).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(snList)) {
LambdaQueryWrapper<DeviceRunParam> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.in(DeviceRunParam::getDeviceId, snList);
List<DeviceRunParam> oldList = deviceRunParamMapper.selectList(queryWrapper);
Map<String, DeviceRunParam> map = oldList.stream()
.collect(Collectors.toMap(
DeviceRunParam::getDeviceId,
Function.identity()));
List<DeviceRunParam> saveList = new ArrayList<>();
params.forEach(x -> {
if (StringUtils.isEmpty(x.getDeviceId()))
return;
DeviceRunParam deviceRunParam = null;
if (!CollectionUtils.isEmpty(map)) {
deviceRunParam = map.get(x.getDeviceId());
}
if (!StringUtils.isEmpty(x.getCapabilities())) {
List<String> list = Arrays.stream(x.getCapabilities().split(","))
.map(String::trim)
.collect(Collectors.toList());
x.setCapabilityList(list);
}
if (deviceRunParam != null) {
deviceRunParam.setCapabilityList(x.getCapabilityList());
deviceRunParam.setProductModel(x.getProductModel());
deviceRunParam.setRtkMode(x.getRtkMode());
deviceRunParam.setDeviceType(x.getDeviceType());
deviceRunParam.setPowerType(x.getPowerType());
deviceRunParam.setCameraNum(x.getCameraNum());
deviceRunParam.setWheelType(x.getWheelType());
deviceRunParam.setEngineType(x.getEngineType());
deviceRunParam.setHasHost(x.getHasHost());
saveList.add(deviceRunParam);
} else {
saveList.add(x);
}
});
return deviceRunParamMapper.saveOrUpdateBatch(saveList);
}
}
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -8,12 +8,11 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import com.maibu.constant.CacheConstants;
import com.maibu.dto.DeviceParamAuthDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -22,8 +21,8 @@ import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;
import com.maibu.constant.CacheConstants;
import com.maibu.constant.NettyCacheKey;
import com.maibu.core.business.Device;
import com.maibu.core.business.DevicePlan;
import com.maibu.core.business.DeviceRunningStatusHistory;
@@ -34,13 +33,13 @@ 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.redis.RedisCache;
import com.maibu.influxdb.MowerRealTimeData;
import com.maibu.influxdb.util.InfluxSqlBuilder;
import com.maibu.influxdb.util.LambdaUtils;
import com.maibu.dto.DeviceParamAuthDTO;
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.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
@@ -75,6 +74,9 @@ public class DeviceServiceImpl implements IDeviceService {
@Autowired
private SysSiteMapper sysSiteMapper;
@Autowired
private HostLocationMapper hostLocationMapper;
/**
* 根据设备编号查询设备
*
@@ -147,6 +149,13 @@ public class DeviceServiceImpl implements IDeviceService {
Map<String, List<DeviceRunningStatusHistory>> statusMap = allStatusList.stream()
.collect(Collectors.groupingBy(DeviceRunningStatusHistory::getDeviceId));
LambdaQueryWrapper<LocationMessage> query = new LambdaQueryWrapper<>();
query.in(LocationMessage::getDeviceId, ids);
List<LocationMessage> hostLocations = hostLocationMapper.selectList(query);
Map<String, LocationMessage> locationMap = hostLocations.stream()
.collect(Collectors.toMap(LocationMessage::getDeviceId, Function.identity()));
deviceList.forEach(x -> {
Integer s = x.getOnlineStatus() == null ? 0 : x.getOnlineStatus();
if (0 == s) {
@@ -183,6 +192,13 @@ public class DeviceServiceImpl implements IDeviceService {
}
}
x.setLastRunningStatus(lastRunningStatus);
String locationKey = NettyCacheKey.latestPositonKey + x.getDeviceName();
LocationMessage locationMessage = redisCache.getCacheObject(locationKey);
if (locationMessage == null) {
locationMessage = locationMap.get(x.getDeviceName());
}
x.setLocationMessage(locationMessage);
});
deviceList.sort(Comparator.comparing(Device::getFeStatus));
}
@@ -312,13 +328,24 @@ public class DeviceServiceImpl implements IDeviceService {
if (!CollectionUtils.isEmpty(deviceList)) {
List<String> ids = deviceList.stream().map(Device::getDeviceName).collect(Collectors.toList());
List<DeviceRunningStatusHistory> allStatusList = deviceStatusHistoryMapper.selectLatestByDeviceIds(ids);
// 有上位机的
LambdaQueryWrapper<LocationMessage> query = new LambdaQueryWrapper<>();
query.in(LocationMessage::getDeviceId, ids);
List<LocationMessage> hostLocations = hostLocationMapper.selectList(query);
Map<String, LocationMessage> locationMap = hostLocations.stream()
.collect(Collectors.toMap(LocationMessage::getDeviceId, Function.identity()));
for (Device x : deviceList) {
if (siteMemory.hasTask(x.getSerialNumber())) {
work += 1;
x.setFeStatus(1);
} else {
free += 1;
x.setFeStatus(2);
if (x.getOnlineStatus() == null || x.getOnlineStatus() == 0) {
x.setFeStatus(3);
} else {
x.setFeStatus(2);
}
}
String key = "running_status:" + x.getDeviceName();
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(key);
@@ -344,7 +371,16 @@ public class DeviceServiceImpl implements IDeviceService {
}
}
}
x.setLastRunningStatus(lastRunningStatus);
String locationKey = NettyCacheKey.latestPositonKey + x.getDeviceName();
LocationMessage locationMessage = redisCache.getCacheObject(locationKey);
if (locationMessage == null) {
locationMessage = locationMap.get(x.getDeviceName());
}
x.setLocationMessage(locationMessage);
}
statusStatistics.put(0, work);
statusStatistics.put(1, free);
@@ -353,7 +389,9 @@ public class DeviceServiceImpl implements IDeviceService {
});
}
}
deviceList.sort(Comparator.comparing(Device::getFeStatus));
if (!CollectionUtils.isEmpty(deviceList)) {
deviceList.sort(Comparator.comparing(Device::getFeStatus));
}
return deviceList;
}
@@ -402,4 +440,9 @@ public class DeviceServiceImpl implements IDeviceService {
return false;
}
@Override
public Device getDeviceBySpiltCode(String code) {
return deviceMapper.selectDeviceBySpiltCode(code);
}
}

View File

@@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Comparator;
import java.util.List;
@Service
@@ -64,6 +65,7 @@ public class WorkRecordService {
list.forEach(workRecord -> {
workRecord.setJsonData(null);
});
list.sort(Comparator.comparing(WorkRecord::getId).reversed());
}
return list;
}
@@ -72,16 +74,13 @@ public class WorkRecordService {
return workRecordMapper.selectById(id);
}
public List<LatAndLngEntity> selectByTaskId(Long taskId) {
public WorkRecord selectByTaskId(Long taskId) {
DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId); // 先查询设备任务,确认任务存在
if (devicePlanTask == null) {
return null;
}
Long routeId = devicePlanTask.getRouteId(); // 获取任务关联的路线ID
WorkRecord workRecord = workRecordMapper.selectById(routeId); // 查询路线ID对应的工作记录
if (workRecord != null && workRecord.getJsonData() != null) {
return workRecord.getJsonData().getPath(); // 返回路线数据
}
return null; // 如果没有找到对应的工作记录或路线数据,返回 null
return workRecord; // 如果没有找到对应的工作记录或路线数据,返回 null
}
}

View File

@@ -39,10 +39,14 @@
<result property="guid" column="guid"/>
<result property="protocolCode" column="protocol_code"/>
<result property="onlineStatus" column="online_status"/>
<result property="hasHost" column="has_host"/>
<result property="hasRegistered" column="has_registered"/>
</resultMap>
<sql id="selectDeviceVo">
select d.online_status,
d.has_host,
d.has_registered,
d.device_alias,
d.device_id,
d.org_id,
@@ -145,6 +149,8 @@
and d.active_time between #{params.beginActiveTime} and #{params.endActiveTime}
</if>
<if test="onlineStatus != null ">and d.online_status = #{onlineStatus}</if>
<if test="hasHost != null ">and d.has_host = #{hasHost}</if>
<if test="hasRegistered != null ">and d.has_registered = #{hasRegistered}</if>
</where>
order by d.create_time desc
</select>
@@ -302,6 +308,8 @@
<if test="onlineStatus != null">online_status,</if>
<if test="orgId != null">org_id,</if>
<if test="siteId != null">site_id,</if>
<if test="hasHost != null">has_host,</if>
<if test="hasRegistered != null">has_registered,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="deviceName != null and deviceName != ''">#{deviceName},</if>
@@ -335,6 +343,8 @@
<if test="onlineStatus != null">#{onlineStatus},</if>
<if test="orgId != null">#{orgId},</if>
<if test="siteId != null">#{siteId},</if>
<if test="hasHost != null">#{hasHost},</if>
<if test="hasRegistered != null">#{hasRegistered},</if>
</trim>
</insert>
@@ -395,6 +405,8 @@
<if test="onlineStatus != null">online_status = #{onlineStatus},</if>
<if test="orgId != null">org_id = #{orgId},</if>
<if test="siteId != null">site_id = #{siteId},</if>
<if test="hasHost != null">has_host = #{hasHost},</if>
<if test="hasRegistered != null">has_registered = #{hasRegistered},</if>
</trim>
where device_id = #{deviceId}
</update>
@@ -492,4 +504,9 @@
#{deviceId}
</foreach>
</update>
<select id="selectDeviceBySpiltCode" parameterType="String" resultMap="DeviceResult">
<include refid="selectDeviceVo"/>
where device_name like concat('%', #{code}, '%')
</select>
</mapper>

View File

@@ -44,7 +44,6 @@ import java.util.concurrent.TimeUnit;
@Service
public class IotDeviceCommonService {
@Autowired
private IotDeviceCommonMapper iotDeviceCommonMapper;
@@ -92,16 +91,13 @@ public class IotDeviceCommonService {
device.setDelFlag(false);
device.setCreateTime(LocalDateTime.now());
log.info("设备 {} 已加入未注册缓存", deviceDTO.getSn());
}
public List<IoTCommonDevice> getUnRegisterDevices() {
return new ArrayList<>(GlobalMemory.unRegisterCommonDeviceMap.values());
}
public Page<IoTCommonDevice> selectDevicePage(Page<IoTCommonDevice> page, IoTCommonDevice device) {
LambdaQueryWrapper<IoTCommonDevice> wrapper = new LambdaQueryWrapper<>();
@@ -123,7 +119,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.selectPage(page, wrapper);
}
public IoTCommonDevice getBySn(String sn) {
LambdaQueryWrapper<IoTCommonDevice> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(IoTCommonDevice::getDeviceId, sn)
@@ -131,7 +126,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.selectOne(wrapper);
}
public void registerDevice(IoTCommonDevice device) {
device.setHasRegister(true);
device.setUpdateTime(LocalDateTime.now());
@@ -144,7 +138,6 @@ public class IotDeviceCommonService {
GlobalMemory.unRegisterCommonDeviceMap.remove(device.getSn());
}
@Transactional(rollbackFor = Exception.class)
public boolean updateDevice(DeviceConfigDTO deviceDTO) {
// 1. 查询设备是否存在
@@ -181,7 +174,6 @@ public class IotDeviceCommonService {
return iotDeviceCommonMapper.saveOrUpdate(device);
}
/**
* 设备连接测试(根据协议类型)
*/
@@ -201,12 +193,10 @@ public class IotDeviceCommonService {
}
}
public IoTCommonDevice getFromUnRegisterCache(String sn) {
return GlobalMemory.unRegisterCommonDeviceMap.get(sn);
}
public void updateUnRegisterCache(IoTCommonDevice device) {
if (device.getDeviceId() == null) {
throw new RuntimeException("设备 ID (SN) 不能为空");
@@ -216,14 +206,14 @@ public class IotDeviceCommonService {
log.info("未注册设备 {} 缓存配置已更新", device.getDeviceId());
}
/**
* MQTT 连接测试
*/
private boolean testMqttConnection(String ip, Integer port, String username, String password) {
try {
// TODO: 使用 MQTT 客户端测试连接
// MqttClient client = new MqttClient("tcp://" + ip + ":" + port, "test-" + UUID.randomUUID());
// MqttClient client = new MqttClient("tcp://" + ip + ":" + port, "test-" +
// UUID.randomUUID());
// ...
return true; // 暂时返回 true,后续接入真实 MQTT 库
} catch (Exception e) {
@@ -258,14 +248,13 @@ public class IotDeviceCommonService {
}
}
public void removeByIds(List<Long> ids) {
if (CollectionUtils.isEmpty(ids)) return;
if (CollectionUtils.isEmpty(ids))
return;
iotDeviceCommonMapper.deleteBatchIds(ids);
}
// 3. 按 productId 分组,缓存映射配置避免重复查询
public static Map<Long, List<DeviceModelPropertyMapping>> mappingCache = new ConcurrentHashMap<>();
@@ -300,7 +289,8 @@ public class IotDeviceCommonService {
// 注册到处理器,用 productId 区分不同产品的映射
String handlerType = "property-" + productId;
GenericPropertyMessageHandler handler = (GenericPropertyMessageHandler) monitor.getMessageHandler(handlerType);
GenericPropertyMessageHandler handler = (GenericPropertyMessageHandler) monitor
.getMessageHandler(handlerType);
handler.registerMappingConfig(handlerType, mappingConfig);
// 获取产品信息
@@ -334,11 +324,14 @@ public class IotDeviceCommonService {
/**
* 根据数据库映射列表构建 PropertyMappingConfig
*
* <p>将 {@link DeviceModelPropertyMapping} 转换为 {@link PropertyMappingConfig.FieldMapping}:</p>
* <p>
* 将 {@link DeviceModelPropertyMapping} 转换为
* {@link PropertyMappingConfig.FieldMapping}:
* </p>
* <ul>
* <li>sourceKey → FieldMapping.source(外部 JSON 中的字段名)</li>
* <li>standardKey → FieldMapping.target(统一后的内部属性名)</li>
* <li>dataType → FieldMapping.valueType(自动类型转换)</li>
* <li>sourceKey → FieldMapping.source(外部 JSON 中的字段名)</li>
* <li>standardKey → FieldMapping.target(统一后的内部属性名)</li>
* <li>dataType → FieldMapping.valueType(自动类型转换)</li>
* </ul>
*/
private PropertyMappingConfig buildMappingConfig(List<DeviceModelPropertyMapping> mappings) {

View File

@@ -67,6 +67,7 @@ public class WebMiddlewareController extends BaseController {
});
res.put("nettyClientMap", nettyClients);
res.put("controllerMap", deviceSessionManager.getControllerMap());
res.put("taskPathMap", GlobalMemory.taskPathMap);
res.put("siteMemory", GlobalMemory.getAllSiteMemory());
return AjaxResult.success(res);
}

View File

@@ -8,6 +8,8 @@ import lombok.Data;
public class WebMessageBaseDTO {
private MesType type;
private String userName;
private Long siteId;
private Long orgId;
private String deviceId;
private String token;
private String message;

View File

@@ -9,8 +9,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Objects;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@Component
@@ -25,6 +24,8 @@ public class MiddleGlobalMemory {
*/
public static Vertx vertx;
//TODO 推送全局的时候需要 判断是不是单个的控制
public static ConcurrentHashMap<Long, Map<String, WebSocket>> mapPushMap = new ConcurrentHashMap<>();
// 存储所有在线WebSocket连接
// key: test:web:token
public static final ConcurrentHashMap<String, WebSocket> onlineSockets = new ConcurrentHashMap<>();
@@ -84,6 +85,7 @@ public class MiddleGlobalMemory {
.findFirst().orElse(null);
}
public static String findNettyClient(NettyClient nettyClient) {
return nettyClientMap.entrySet().stream()
.filter(entry -> Objects.equals(entry.getValue(), nettyClient))
@@ -91,5 +93,38 @@ public class MiddleGlobalMemory {
.findFirst().orElse(null);
}
public static void addMapSocket(Long siteId, String token, WebSocket webSocket) {
mapPushMap
.computeIfAbsent(siteId, k -> new ConcurrentHashMap<>())
.put(token, webSocket);
}
public static void removeByWebSocket(WebSocket webSocket) {
if (webSocket == null) {
return;
}
mapPushMap.forEach((siteId, socketMap) -> {
socketMap.entrySet().removeIf(entry ->
entry.getValue() == webSocket
);
// siteId 下没有连接了,删除整个 siteId
if (socketMap.isEmpty()) {
mapPushMap.remove(siteId, socketMap);
}
});
}
public static List<WebSocket> getMapSockets(Long siteId) {
Map<String, WebSocket> map = mapPushMap.get(siteId);
if (map == null || map.isEmpty()) {
return Collections.emptyList();
}
return new ArrayList<>(map.values());
}
}

View File

@@ -7,6 +7,7 @@ import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.maibu.core.business.dto.WebDeviceTaskStatusMessageDTO;
import com.maibu.core.business.dto.WebStatusMessageDTO;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;
@@ -23,7 +24,6 @@ import com.maibu.dto.DeviceRespondDTO;
import com.maibu.dto.NettySwitchDeviceDTO;
import com.maibu.dto.ResultDTO;
import com.maibu.dto.WebAuthResponseDTO;
import com.maibu.dto.WebDeviceTaskStatusMessageDTO;
import com.maibu.dto.WebOlineStatusMessageDTO;
import com.maibu.dto.WebSwitchControlResponseDTO;
import com.maibu.memory.MiddleGlobalMemory;

View File

@@ -64,6 +64,7 @@ public class WebsocketHandler extends WebSocketServer {
releaseResource(key);
logger.info("客户端断开连接: remoteAddress={}, code={}, reason={}, 当前在线数: {}", conn.getRemoteSocketAddress(), code, reason, MiddleGlobalMemory.onlineSockets.size());
}
MiddleGlobalMemory.removeByWebSocket(conn);
}
@Override
@@ -77,22 +78,15 @@ public class WebsocketHandler extends WebSocketServer {
String deviceId = webMessageBaseDTO.getDeviceId();
MesType type = webMessageBaseDTO.getType();
String key = userName + ":web" + ":" + token;
if (MesType.AUTH.equals(type)) {
if (MesType.mapPush.equals(type)) {
Long siteId = webMessageBaseDTO.getSiteId();
MiddleGlobalMemory.addMapSocket(siteId, token, conn);
} else if (MesType.AUTH.equals(type)) {
if (StringUtils.isEmpty(deviceId)) {
return;
}
//todo 先关闭原先的
// WebSocket oldWebsocket = MiddleGlobalMemory.onlineSockets.get(key);
NettyClient client = MiddleGlobalMemory.nettyClientMap.get(key);
// if (oldWebsocket != null && oldWebsocket.isOpen()) {
// oldWebsocket.close();
// }
// if (oldNettyClient != null && oldNettyClient.isConnected()) {
// oldNettyClient.disconnect();
// }
MiddleGlobalMemory.onlineSockets.put(key, conn);
//这里可以根据需要初始化Netty客户端
if (client == null) {
client = new NettyClient();
}

View File

@@ -1,16 +1,19 @@
package com.maibu.websocket;
import com.maibu.core.business.inter.DeviceWebSocketInterace;
import com.maibu.core.business.inter.DeviceWebSocketInterface;
import com.maibu.memory.MiddleGlobalMemory;
import org.java_websocket.WebSocket;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
@Component
public class WebsocketMesHandler implements DeviceWebSocketInterace {
public class WebsocketMesHandler implements DeviceWebSocketInterface {
@Override
public void sendWebsoketMes(String key, String data) {
public void sendWebsocketMes(String key, String data) {
MiddleGlobalMemory.onlineSockets.keySet().forEach(x -> {
// key: test:web:token
if (x.contains(key)) {
@@ -21,4 +24,14 @@ public class WebsocketMesHandler implements DeviceWebSocketInterace {
}
@Override
public void sendMapWebsocketMes(Long siteId, String data) {
List<WebSocket> webSocketList = MiddleGlobalMemory.getMapSockets(siteId);
if (!CollectionUtils.isEmpty(webSocketList)) {
webSocketList.forEach(webSocket -> {
WebsocketHandler.sendMessageToClient(webSocket, data);
});
}
}
}