#老板的上位机登录

This commit is contained in:
2026-09-09 13:00:31 +08:00
parent 4ee3f6be90
commit a6f662b15b
4 changed files with 165 additions and 81 deletions

View File

@@ -105,7 +105,7 @@ public class Device extends BaseDO {
/** /**
* 设备在线状态(1-在线,2-离线) * 设备在线状态(1-在线,2-离线)
*/ */
@ApiModelProperty("设备状态(1-在线,2-离线)") @ApiModelProperty("设备状态(1-在线,0-离线)")
@Excel(name = "设备在线状态") @Excel(name = "设备在线状态")
private Integer onlineStatus; private Integer onlineStatus;
@@ -230,9 +230,9 @@ public class Device extends BaseDO {
@TableField(exist = false) @TableField(exist = false)
private DeviceRunParam runParam; private DeviceRunParam runParam;
private boolean hasRegistered = false; private Boolean hasRegistered;
private boolean hasHost = false; private Boolean hasHost;
@TableField(exist = false) @TableField(exist = false)
private LocationMessage locationMessage; private LocationMessage locationMessage;

View File

@@ -1,5 +1,6 @@
package com.maibu.netty.handler; package com.maibu.netty.handler;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.List; import java.util.List;
@@ -183,12 +184,60 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
NettyDevice masterDevice = sessionManager.getDevice(sessionId); NettyDevice masterDevice = sessionManager.getDevice(sessionId);
if (masterDevice == null) { if (masterDevice == null) {
// sessionManager.getControl(sessionId); // sessionManager.getControl(sessionId);
handleMasterConnect(ctx, sessionId, null, ConnectorStatus.ACTIVE); handleMasterConnect(ctx, sessionId, null, ConnectorStatus.ACTIVE);
} else { } else {
ctx.channel().attr(Constant.ATT_DEVICE_ID).set(sessionId); 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) { } else if (cmdType == CommandConstant.interaction) {
@@ -244,7 +293,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
changeDTO.setType(MesType.device_task_change); changeDTO.setType(MesType.device_task_change);
changeDTO.setTaskId(taskId); 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)); JsonUtils.toJsonString(changeDTO));
List<NettyDevice> controlMasters = sessionManager List<NettyDevice> controlMasters = sessionManager
.getAllSlaveControl(deviceId); .getAllSlaveControl(deviceId);
@@ -267,7 +317,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
reportDTO.setTaskId(taskId); reportDTO.setTaskId(taskId);
reportDTO.setEntity(device.getCurrentPoint()); reportDTO.setEntity(device.getCurrentPoint());
reportDTO.setType(MesType.device_task_arrive_point); 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)); JsonUtils.toJsonString(reportDTO));
List<NettyDevice> controlMasters = sessionManager List<NettyDevice> controlMasters = sessionManager
@@ -300,10 +351,10 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
logger.info("12指令切换权限,c:{}", c.getConnectorId()); logger.info("12指令切换权限,c:{}", c.getConnectorId());
if (!c.getConnectorId().equals(masterId)) { if (!c.getConnectorId().equals(masterId)) {
// c.setCurrentSlaveId(null); // c.setCurrentSlaveId(null);
// c.removeConnectedDevice(slaveDevice); // c.removeConnectedDevice(slaveDevice);
c.setConnectorStatus(ConnectorStatus.RECEIVER); c.setConnectorStatus(ConnectorStatus.RECEIVER);
sessionManager.unLock(c.getConnectorId()); sessionManager.unLock(c.getConnectorId());
// sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2); // sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
} }
}); });
} }
@@ -312,7 +363,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
masterDevice.setCurrentSlaveId(slaveId); masterDevice.setCurrentSlaveId(slaveId);
masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE); masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
masterDevice.addConnectedDevice(slaveDevice); masterDevice.addConnectedDevice(slaveDevice);
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1); // sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(),
// slaveId, 1);
} else { } else {
logger.info("权限切换请求被拒绝"); logger.info("权限切换请求被拒绝");
} }
@@ -343,73 +395,81 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
} }
} }
// /** // /**
// * 找到当前设备控制的主机 转发控制请求 // * 找到当前设备控制的主机 转发控制请求
// */ // */
// private void handlePermissionRequest(DeviceRequestDTO requestDTO, byte[] bytes, ChannelHandlerContext ctx) { // private void handlePermissionRequest(DeviceRequestDTO requestDTO, byte[]
// logger.info("转发控制请求 :{}", JsonUtils.toJsonString(requestDTO)); // bytes, ChannelHandlerContext ctx) {
// String slaveId = requestDTO.getDeviceId(); // logger.info("转发控制请求 :{}", JsonUtils.toJsonString(requestDTO));
// List<NettyDevice> controlList = sessionManager.getSlaveControl(slaveId); // String slaveId = requestDTO.getDeviceId();
// String masterId = requestDTO.getUserId() + ":" + requestDTO.getPlatform(); // List<NettyDevice> controlList = sessionManager.getSlaveControl(slaveId);
// logger.info("转发控制请求 controlList :{}", JsonUtils.toJsonString(controlList)); // String masterId = requestDTO.getUserId() + ":" + requestDTO.getPlatform();
// if (!CollectionUtils.isEmpty(controlList)) { // logger.info("转发控制请求 controlList :{}", JsonUtils.toJsonString(controlList));
// // 如果当前设备有控制 // if (!CollectionUtils.isEmpty(controlList)) {
// logger.info("转发控制请求 发送报文"); // // 如果当前设备有控制
// NettyDevice controlDevice = controlList.get(0); // logger.info("转发控制请求 发送报文");
// if (controlDevice != null && controlDevice.getChannel() != null && controlDevice.getChannel().isActive()) { // NettyDevice controlDevice = controlList.get(0);
// controlDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes)); // if (controlDevice != null && controlDevice.getChannel() != null &&
// logger.info("转发控制请求 发送报文结束 deviceId :{}", controlDevice.getConnectorId()); // controlDevice.getChannel().isActive()) {
// controlRequestMap.put(masterId, slaveId); // controlDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// logger.info("转发控制请求 controlRequestMap:{}", JsonUtils.toJsonString(controlRequestMap)); // logger.info("转发控制请求 发送报文结束 deviceId :{}", controlDevice.getConnectorId());
// } // controlRequestMap.put(masterId, slaveId);
// // logger.info("转发控制请求 controlRequestMap:{}",
// } else { // JsonUtils.toJsonString(controlRequestMap));
// // 判断直接给权限 还是 判断是否有该账号其他端的的控制有权限 // }
// NettyDevice activeDevice = sessionManager.getUserControl(requestDTO.getUserId()); //
// boolean sendMes = true; // } else {
// if (activeDevice == null) { // // 判断直接给权限 还是 判断是否有该账号其他端的的控制有权限
// sendMes = false; // NettyDevice activeDevice =
// } else { // sessionManager.getUserControl(requestDTO.getUserId());
// if (activeDevice.getConnectorId().equals(masterId)) { // boolean sendMes = true;
// sendMes = false; // if (activeDevice == null) {
// } // sendMes = false;
// } // } else {
// if (sendMes) { // if (activeDevice.getConnectorId().equals(masterId)) {
// if (activeDevice.getChannel() != null && activeDevice.getChannel().isActive()) { // sendMes = false;
// activeDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes)); // }
// logger.info("转发控制请求2 发送报文结束 deviceId :{}", activeDevice.getConnectorId()); // }
// controlRequestMap.put(masterId, slaveId); // if (sendMes) {
// logger.info("转发控制请求2 controlRequestMap:{}", JsonUtils.toJsonString(controlRequestMap)); // if (activeDevice.getChannel() != null &&
// } // activeDevice.getChannel().isActive()) {
// } else { // activeDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
// NettyDevice masterDevice = sessionManager.getDevice(masterId); // logger.info("转发控制请求2 发送报文结束 deviceId :{}", activeDevice.getConnectorId());
// if (masterDevice != null) { // controlRequestMap.put(masterId, slaveId);
// NettyDevice slaveDevice = sessionManager.getDevice(slaveId); // logger.info("转发控制请求2 controlRequestMap:{}",
// masterDevice.setCurrentSlaveId(slaveId); // JsonUtils.toJsonString(controlRequestMap));
// masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE); // }
// masterDevice.addConnectedDevice(slaveDevice); // } else {
// // NettyDevice masterDevice = sessionManager.getDevice(masterId);
// sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(), slaveId, 1); // if (masterDevice != null) {
// if (masterDevice.getChannel() != null && masterDevice.getChannel().isActive()) { // NettyDevice slaveDevice = sessionManager.getDevice(slaveId);
// DeviceRequestDTO reDto = new DeviceRequestDTO(); // masterDevice.setCurrentSlaveId(slaveId);
// reDto.setPlatform(requestDTO.getPlatform()); // masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
// DeviceRespondDTO respond = new DeviceRespondDTO(); // masterDevice.addConnectedDevice(slaveDevice);
// respond.setSwitchResult(true); //
// respond.setHolder("you"); // sysUserClientService.updateAliveStatus(masterDevice.getConnectorId(),
// respond.setDeviceId(slaveId); // slaveId, 1);
// reDto.setRespond(respond); // if (masterDevice.getChannel() != null &&
// ByteBuf buf = ctx.alloc().buffer(); // masterDevice.getChannel().isActive()) {
// CommandUtils.buildCommand(buf, reDto, CommandConstant.interaction); // DeviceRequestDTO reDto = new DeviceRequestDTO();
// String content = buf.toString(CharsetUtil.UTF_8); // reDto.setPlatform(requestDTO.getPlatform());
// masterDevice.getChannel().writeAndFlush(buf); // DeviceRespondDTO respond = new DeviceRespondDTO();
// logger.info("转发控制请求设置当前控制2 发送报文:{} deviceId :{}", content, masterId); // respond.setSwitchResult(true);
// } // respond.setHolder("you");
// } else { // 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 {
//
// }
// }
// }
// }
/** /**
* 找到当前设备控制的主机 转发控制请求 * 找到当前设备控制的主机 转发控制请求
@@ -462,7 +522,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
} }
private void handleMasterConnect(ChannelHandlerContext ctx, String masterId, String slaveId, private void handleMasterConnect(ChannelHandlerContext ctx, String masterId, String slaveId,
ConnectorStatus status) { ConnectorStatus status) {
ctx.channel().attr(Constant.ATT_DEVICE_ID).set(masterId); ctx.channel().attr(Constant.ATT_DEVICE_ID).set(masterId);
sessionManager.registerDevice(masterId, ctx.channel(), ConnectorType.MASTER, status, slaveId); sessionManager.registerDevice(masterId, ctx.channel(), ConnectorType.MASTER, status, slaveId);
// sessionManager.bindConnector(masterId, slaveId); // sessionManager.bindConnector(masterId, slaveId);

View File

@@ -299,6 +299,12 @@ public class DeviceThreadService {
} }
hostLocationMapper.saveOrUpdate(locationMessage); hostLocationMapper.saveOrUpdate(locationMessage);
} }
Device device = deviceService.selectDeviceBySerialNumber(deviceId);
if (device != null) {
device.setOnlineStatus(DeviceStatus.offline.getType());
device.setUpdateTime(LocalDateTime.now());
deviceService.updateDeviceBySelf(device);
}
} }
} else { } else {
if (nettyDevice == null) { if (nettyDevice == null) {
@@ -322,9 +328,7 @@ public class DeviceThreadService {
device.setStatus(3); device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType()); device.setOnlineStatus(DeviceStatus.online.getType());
device.setUpdateTime(LocalDateTime.now()); device.setUpdateTime(LocalDateTime.now());
if (!device.isHasHost()) { device.setHasHost(true);
device.setHasHost(true);
}
deviceService.updateDeviceBySelf(device); deviceService.updateDeviceBySelf(device);
} }
// 推送json 找到设备绑定的主机进行推送 // 推送json 找到设备绑定的主机进行推送

View File

@@ -328,13 +328,24 @@ public class DeviceServiceImpl implements IDeviceService {
if (!CollectionUtils.isEmpty(deviceList)) { if (!CollectionUtils.isEmpty(deviceList)) {
List<String> ids = deviceList.stream().map(Device::getDeviceName).collect(Collectors.toList()); List<String> ids = deviceList.stream().map(Device::getDeviceName).collect(Collectors.toList());
List<DeviceRunningStatusHistory> allStatusList = deviceStatusHistoryMapper.selectLatestByDeviceIds(ids); 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) { for (Device x : deviceList) {
if (siteMemory.hasTask(x.getSerialNumber())) { if (siteMemory.hasTask(x.getSerialNumber())) {
work += 1; work += 1;
x.setFeStatus(1); x.setFeStatus(1);
} else { } else {
free += 1; 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(); String key = "running_status:" + x.getDeviceName();
DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(key); DeviceStatusRecordDTO recordDTO = redisCache.getCacheObject(key);
@@ -360,7 +371,16 @@ public class DeviceServiceImpl implements IDeviceService {
} }
} }
} }
x.setLastRunningStatus(lastRunningStatus); 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(0, work);
statusStatistics.put(1, free); statusStatistics.put(1, free);