This commit is contained in:
2026-06-10 16:31:39 +08:00
parent 1ece1b2336
commit 9657fb42f6
11 changed files with 463 additions and 194 deletions

View File

@@ -1,12 +1,17 @@
package com.maibu.core.business.device;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Queue;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.maibu.core.business.DevicePlanTask;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.PlanPath;
import com.maibu.core.business.WorkRecord;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.business.path.RoutePlanSendEntity;
import com.maibu.core.enums.ConnectorType;
import com.maibu.core.enums.DeviceTaskStaus;
@@ -15,18 +20,11 @@ import com.maibu.mapper.WorkRecordMapper;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.utils.spring.SpringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import com.maibu.core.business.path.LatAndLngEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Queue;
@Slf4j
@EqualsAndHashCode(callSuper = true)
@@ -69,41 +67,15 @@ public class NettyDevice extends Connector {
this.deviceType = deviceType;
}
// abaa 00 18 06 18 06 00 00 00 00 00 00 aaab
//
// ab aa 01 01 00 3c 88
// 2d e0 48 05 40 40
// 22 07 d0 42 c6 33
// 5e 40 e8 03 00 00 aa ab
private static final byte[] PACKET = {(byte) 0xAB, (byte) 0xAA,
(byte) 0x00, (byte) 0x18,(byte) 0x06,(byte) 0x18,(byte) 0x06,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0xAA, (byte) 0xAB};
private static final byte[] route = {(byte) 0xab, (byte) 0xaa,
(byte) 0x01, (byte) 0x01,(byte) 0x00,(byte) 0x3c,(byte) 0x88,
(byte) 0x2d, (byte) 0xe0,(byte) 0x48,(byte) 0x05,(byte) 0x40,(byte) 0x40,
(byte) 0x22, (byte) 0x07,(byte) 0xd0,(byte) 0x42,(byte) 0xc6,(byte) 0x33,
(byte) 0x5e,(byte) 0x40,(byte) 0xe8,(byte) 0x03,(byte) 0x00,(byte) 0x00,
(byte) 0xaa, (byte) 0xab};
// todo 重发
public void sendNextPoint() {
if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE)) return;
if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE))
return;
if (!locationQueue.isEmpty()) {
LatAndLngEntity entity = locationQueue.poll();
if (entity != null) {
RoutePlanSendEntity routePlanSendEntity = new RoutePlanSendEntity();
routePlanSendEntity.setCommandType((byte) 0x01);
routePlanSendEntity.setPointCounts((short) 1);
routePlanSendEntity.setTargetLatitude(entity.getLat());
routePlanSendEntity.setTargetLongitude(entity.getLng());
routePlanSendEntity.setSpeed((short) 1000);
byte[] bytes = routePlanSendEntity.toBytes();
log.debug("下发路径的报文:{}", toHexString(bytes));
sendPathCommand((byte) 0x01, (short) 1, entity.getLat(), entity.getLng(), (short) 1000);
currentPoint = entity;
if (this.getChannel() != null && this.getChannel().isActive()) {
this.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
}
}
}
}
@@ -116,8 +88,8 @@ public class NettyDevice extends Connector {
return sb.toString().trim();
}
public synchronized void finishTask() {
if (executingTask) {
public synchronized Long finishTask() {
long finishId = task.getId();
task.setTaskStaus(DeviceTaskStaus.FINISH);
task.setFinishTime(LocalDateTime.now());
devicePlanTaskMapper.saveOrUpdate(task);
@@ -126,11 +98,12 @@ public class NettyDevice extends Connector {
task = null;
currentTaskId = null;
executingTask = false;
}
return finishId;
}
public synchronized boolean cancelTask() {
if (executingTask) {
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);
@@ -141,9 +114,21 @@ public class NettyDevice extends Connector {
currentTaskId = null;
locationQueue.clear();
executingTask = false;
}
return true;
} else {
return false;
}
public void sendPathCommand(byte coommadnType, short pointCounts, double lat, double lng, short speed) {
RoutePlanSendEntity routePlanSendEntity = new RoutePlanSendEntity();
routePlanSendEntity.setCommandType(coommadnType);
routePlanSendEntity.setPointCounts(pointCounts);
routePlanSendEntity.setTargetLatitude(lat);
routePlanSendEntity.setTargetLongitude(lng);
routePlanSendEntity.setSpeed(speed);
byte[] bytes = routePlanSendEntity.toBytes();
log.debug("下发路径的报文:{}", toHexString(bytes));
if (this.getChannel() != null && this.getChannel().isActive()) {
this.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
}
}
@@ -151,7 +136,8 @@ public class NettyDevice extends Connector {
public synchronized boolean pauseTask() {
if (executingTask) {
task.setTaskStaus(DeviceTaskStaus.PAUSE);
executingTask = false;
sendPathCommand((byte) 0x01, (short) 2, 0.00d, 0.00d, (short) 0);
// executingTask = false;
return true;
} else {
return false;
@@ -160,21 +146,24 @@ public class NettyDevice extends Connector {
}
// todo 优化
public synchronized boolean recoveryTask() {
if (!executingTask) {
public synchronized boolean recoveryTask() throws InterruptedException {
if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE)) {
task.setTaskStaus(DeviceTaskStaus.EXECUTING);
executingTask = true;
sendNextPoint();
sendPathCommand((byte) 0x01, (short) 3, 0.00d, 0.00d, (short) 0);
Thread.sleep(1000);
sendPathCommand((byte) 0x01, (short) 1, currentPoint.getLat(), currentPoint.getLng(), (short) 0);
// sendNextPoint();
return true;
} else {
return false;
}
}
public void startTask() {
try {
if (executingTask) return;
if (executingTask)
return;
if (task != null) {
Long routeId = task.getRouteId();
WorkRecord workRecord = workRecordMapper.selectById(routeId);
@@ -196,4 +185,3 @@ public class NettyDevice extends Connector {
}
}

View File

@@ -13,5 +13,9 @@ public enum RespondCode {
/**
* 设备错误推送
*/
device_error_push
device_error_push,
/**
* 任务状态变化推送
*/
device_task_change
}

View File

@@ -137,7 +137,7 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/recoveryTask")
public AjaxResult recoveryTask(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult recoveryTask(@RequestBody DeviceTaskCommandDTO dto) throws InterruptedException {
String deviceId = dto.getDeviceId();
if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) {
return AjaxResult.error("deviceId或taskId为空!");

View File

@@ -0,0 +1,18 @@
package com.maibu.dto;
import com.maibu.core.enums.DeviceTaskStaus;
import com.maibu.core.enums.RespondCode;
import lombok.Data;
@Data
public class DeviceTaskReportDTO {
private RespondCode event;
private String deviceId;
private Long taskId;
private DeviceTaskStaus status;
}

View File

@@ -8,7 +8,6 @@ import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.core.domain.entity.SysUser;
import com.maibu.core.domain.entity.UserClient;
import com.maibu.core.enums.*;
import com.maibu.core.enums.DeviceStatus;
import com.maibu.dto.*;
import com.maibu.manager.DeviceSessionManager;
import com.maibu.mapper.DeviceRunStatisticsMapper;
@@ -172,7 +171,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
if (StringUtils.isEmpty(sessionId) || sysUser == null) {
t = true;
}
if (sysUser != null && !StringUtils.isEmpty(sessionId) && !StringUtils.isEmpty(sysUser.getSessionId())) {
if (sysUser != null && !StringUtils.isEmpty(sessionId)
&& !StringUtils.isEmpty(sysUser.getSessionId())) {
if (!sysUser.getSessionId().equals(sessionId)) {
t = true;
}
@@ -186,18 +186,21 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
logger.info("上位机连接重连: {}", deviceId);
} else {
// 判断是否账号在控制空 如果在控制设置账号为非active
List<UserClient> userClients = sysUserClientService.selectUserClientByUserName(userName);
List<UserClient> userClients = sysUserClientService
.selectUserClientByUserName(userName);
ConnectorStatus status = ConnectorStatus.ACTIVE;
logger.info("web 上位机连接重连2: {}", JsonUtils.toJsonString(userClients));
UserClient nowClient = null;
if (!CollectionUtils.isEmpty(userClients)) {
long count = userClients.stream().filter(x ->
x.getIsAlive() == 1 && !deviceId.equals(x.getClientName())).count();
long count = userClients.stream().filter(
x -> x.getIsAlive() == 1 && !deviceId.equals(x.getClientName()))
.count();
if (count > 0) {
status = ConnectorStatus.RECEIVER;
}
nowClient = userClients.stream().filter(x ->
x.getIsAlive() == 1 && deviceId.equals(x.getClientName())).findFirst().orElse(null);
nowClient = userClients.stream().filter(
x -> x.getIsAlive() == 1 && deviceId.equals(x.getClientName()))
.findFirst().orElse(null);
}
logger.info("web 上位机连接重连3: {}", JsonUtils.toJsonString(status));
if (!ConnectorStatus.ACTIVE.equals(status)) {
@@ -221,11 +224,13 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
} else {
// 判断是否账号在控制空 如果在控制设置账号为非active
List<UserClient> userClients = sysUserClientService.selectUserClientByUserName(userName);
List<UserClient> userClients = sysUserClientService
.selectUserClientByUserName(userName);
ConnectorStatus status = ConnectorStatus.ACTIVE;
if (!CollectionUtils.isEmpty(userClients)) {
long count = userClients.stream().filter(x ->
x.getIsAlive() == 1 && !deviceId.equals(x.getClientName())).count();
long count = userClients.stream()
.filter(x -> x.getIsAlive() == 1 && !deviceId.equals(x.getClientName()))
.count();
if (count > 0) {
status = ConnectorStatus.RECEIVER;
}
@@ -312,9 +317,29 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
String deviceId = channel.attr(Constant.ATT_DEVICE_ID).get();
NettyDevice device = sessionManager.getDevice(deviceId);
if (CollectionUtils.isEmpty(device.getLocationQueue())) {
device.finishTask();
Long taskId = device.finishTask();
// todo 推送信息给前端
DeviceTaskReportDTO changeDTO = new DeviceTaskReportDTO();
changeDTO.setDeviceId(deviceId);
changeDTO.setStatus(DeviceTaskStaus.FINISH);
changeDTO.setEvent(RespondCode.device_task_change);
changeDTO.setTaskId(taskId);
// ByteBuf buf = ctx.alloc().buffer();
ByteBuf buf = Unpooled.buffer();
CommandUtils.buildCommand(buf, changeDTO, CommandConstant.interaction);
List<NettyDevice> controlMasters = sessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
controlMasters.forEach(x -> {
if (x.getChannel() != null && x.getChannel().isActive()) {
x.getChannel().writeAndFlush(buf);
logger.info("任务完成状态推送 task:{},device:{}", taskId, deviceId);
}
});
}
} else {
device.sendNextPoint();
//todo 推送到点给前端
}
}
}
@@ -367,7 +392,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
* 获取当前请求目标设备的主机
*/
private String getRequestMaster(String slaveId) {
return controlRequestMap.keySet().stream().filter(x -> controlRequestMap.get(x).equals(slaveId)).findFirst().orElse(null);
return controlRequestMap.keySet().stream().filter(x -> controlRequestMap.get(x).equals(slaveId)).findFirst()
.orElse(null);
}
/**
@@ -456,13 +482,13 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
sessionManager.registerDevice(slaveId, ctx.channel(), ConnectorType.SLAVE, ConnectorStatus.ACTIVE, null);
}
private void handleMasterConnect(ChannelHandlerContext ctx, String masterId, String slaveId, ConnectorStatus status) {
private void handleMasterConnect(ChannelHandlerContext ctx, String masterId, String slaveId,
ConnectorStatus status) {
ctx.channel().attr(Constant.ATT_DEVICE_ID).set(masterId);
sessionManager.registerDevice(masterId, ctx.channel(), ConnectorType.MASTER, status, slaveId);
// sessionManager.bindConnector(masterId, slaveId);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
String deviceId = ctx.channel().attr(Constant.ATT_DEVICE_ID).get();

View File

@@ -230,6 +230,7 @@ public class DevicePlanTaskMonitorService {
DevicePlanTask devicePlanTask = tasks.get(0);
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);

View File

@@ -21,6 +21,7 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
@@ -42,14 +43,12 @@ public class DeviceTaskService {
@Autowired
private WorkRecordMapper workRecordMapper;
@Autowired
private DeviceSessionManager deviceSessionManager;
@Autowired
private SysSiteMapper sysSiteMapper;
public int insertOrUpdate(DevicePlan devicePlan, LoginUser loginUser) {
Long id = devicePlan.getId();
SiteMemory siteMemory = GlobalMemory.getSiteMemory(devicePlan.getOrgId(), devicePlan.getSiteId());
@@ -116,7 +115,8 @@ public class DeviceTaskService {
}
}
public List<DevicePlan> getSiteDevicePlan(Long siteId, LocalDate startTime, LocalDate endTime, String deviceId, DeviceTaskStaus taskStaus) {
public List<DevicePlan> getSiteDevicePlan(Long siteId, LocalDate startTime, LocalDate endTime, String deviceId,
DeviceTaskStaus taskStaus) {
if (siteId != null) {
LambdaQueryWrapper<DevicePlan> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DevicePlan::getSiteId, siteId);
@@ -226,7 +226,8 @@ public class DeviceTaskService {
if (!CollectionUtils.isEmpty(devicePlans)) {
List<LocalDate> dates = getMonthDays();
for (LocalDate date : dates) {
List<DevicePlan> plans = devicePlans.stream().filter(x -> x.getCreateTime().toLocalDate().equals(date)).collect(Collectors.toList());
List<DevicePlan> plans = devicePlans.stream().filter(x -> x.getCreateTime().toLocalDate().equals(date))
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(plans)) {
DevicePlanStatisticsDTO dto = new DevicePlanStatisticsDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M.d");
@@ -277,9 +278,11 @@ public class DeviceTaskService {
LambdaQueryWrapper<DevicePlan> query = new LambdaQueryWrapper<>();
query.eq(DevicePlan::getUserId, userId);
List<DevicePlan> devicePlans = transferDevicePlanData(devicePlanMapper.selectList(query));
if (CollectionUtils.isEmpty(devicePlans)) return new ArrayList<>();
if (CollectionUtils.isEmpty(devicePlans))
return new ArrayList<>();
List<Long> planIds = devicePlans.stream().map(DevicePlan::getId).collect(Collectors.toList());
if (CollectionUtils.isEmpty(planIds)) return new ArrayList<>();
if (CollectionUtils.isEmpty(planIds))
return new ArrayList<>();
LambdaQueryWrapper<DevicePlanTask> queryWrapper = new LambdaQueryWrapper<>();
// 核心:筛选 createTime 大于等于起始时间,且小于等于结束时间
@@ -290,16 +293,20 @@ public class DeviceTaskService {
if (!CollectionUtils.isEmpty(devicePlanTasks)) {
List<LocalDate> dates = getMonthDays();
for (LocalDate date : dates) {
List<DevicePlanTask> planTasks = devicePlanTasks.stream().filter(x -> x.getCreateTime().toLocalDate().equals(date)).collect(Collectors.toList());
List<DevicePlanTask> planTasks = devicePlanTasks.stream()
.filter(x -> x.getCreateTime().toLocalDate().equals(date)).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(planTasks)) {
DevicePlanTaskStatisticsDTO dto = new DevicePlanTaskStatisticsDTO();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M.d");
dto.setDate(formatter.format(date));
long finishCount = planTasks.stream().filter(x -> DeviceTaskStaus.FINISH.equals(x.getTaskStaus())).count();
long finishCount = planTasks.stream().filter(x -> DeviceTaskStaus.FINISH.equals(x.getTaskStaus()))
.count();
dto.setSuccess((int) finishCount);
long failedCount = planTasks.stream().filter(x -> DeviceTaskStaus.FAILED.equals(x.getTaskStaus())).count();
long failedCount = planTasks.stream().filter(x -> DeviceTaskStaus.FAILED.equals(x.getTaskStaus()))
.count();
dto.setFailed((int) failedCount);
long pauseCount = planTasks.stream().filter(x -> DeviceTaskStaus.PAUSE.equals(x.getTaskStaus())).count();
long pauseCount = planTasks.stream().filter(x -> DeviceTaskStaus.PAUSE.equals(x.getTaskStaus()))
.count();
dto.setPaused((int) pauseCount);
list.add(dto);
}
@@ -308,7 +315,6 @@ public class DeviceTaskService {
return list;
}
public WorkRecord concurrentDevicePlanTask(String deviceId) {
LambdaQueryWrapper<DevicePlanTask> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(DevicePlanTask::getDeviceId, deviceId)
@@ -318,7 +324,6 @@ public class DeviceTaskService {
return routId == null ? null : workRecordMapper.selectById(routId);
}
public List<DeviceWorkStatisticsDTO> workStatistics(Long userId) {
// todo update
@@ -341,7 +346,6 @@ public class DeviceTaskService {
return result;
}
public List<DevicePlanTask> deviceTaskPool(DeviceTaskQueryDTO dto) {
List<DevicePlanTask> list = new ArrayList<>();
if (dto.getOrgId() == null) {
@@ -394,9 +398,9 @@ public class DeviceTaskService {
return transferDeviceTaskData(devicePlanTaskMapper.selectList(queryWrapper));
}
public List<DevicePlan> transferDevicePlanData(List<DevicePlan> list) {
if (CollectionUtils.isEmpty(list)) return list;
if (CollectionUtils.isEmpty(list))
return list;
list.forEach(x -> {
DeviceTaskStaus taskStaus = x.getTaskStaus();
x.setTaskStausTranslate(taskStaus.getDescription());
@@ -405,11 +409,17 @@ public class DeviceTaskService {
}
public List<DevicePlanTask> transferDeviceTaskData(List<DevicePlanTask> list) {
if (CollectionUtils.isEmpty(list)) return list;
if (CollectionUtils.isEmpty(list))
return list;
list.forEach(x -> {
DeviceTaskStaus taskStaus = x.getTaskStaus();
x.setTaskStausTranslate(taskStaus.getDescription());
});
list.sort(
Comparator.comparing(DevicePlanTask::getFinishTime,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(DevicePlanTask::getCreateTime,
Comparator.nullsLast(Comparator.reverseOrder())));
return list;
}
@@ -467,18 +477,17 @@ public class DeviceTaskService {
Long taskId = dto.getTaskId();
DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId);
if (devicePlanTask != null) {
devicePlanTask.setUpdateTime(LocalDateTime.now());
devicePlanTask.setTaskStaus(DeviceTaskStaus.PAUSE);
devicePlanTask.setUpdateBy(username);
devicePlanTaskMapper.saveOrUpdate(devicePlanTask);
NettyDevice device = deviceSessionManager.getDevice(devicePlanTask.getDeviceId());
if (device != null) {
return device.pauseTask();
}
}
}
return false;
}
// todo 完善
public boolean recoveryTask(DeviceTaskCommandDTO dto, String username) {
public boolean recoveryTask(DeviceTaskCommandDTO dto, String username) throws InterruptedException {
if (!StringUtils.isEmpty(dto.getDeviceId())) {
NettyDevice device = deviceSessionManager.getDevice(dto.getDeviceId());
if (device != null) {
@@ -486,16 +495,12 @@ public class DeviceTaskService {
}
} else {
Long taskId = dto.getTaskId();
Long siteId = dto.getSiteId();
Long orgId = dto.getOrgId();
DevicePlanTask devicePlanTask = devicePlanTaskMapper.selectById(taskId);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(orgId, siteId);
DevicePlanTask executeTask = siteMemory.getDeviceExecuteTask(devicePlanTask.getDeviceId());
if (Objects.equals(devicePlanTask.getId(), executeTask.getId())) {
devicePlanTask.setUpdateTime(LocalDateTime.now());
devicePlanTask.setTaskStaus(DeviceTaskStaus.EXECUTING);
devicePlanTask.setUpdateBy(username);
devicePlanTaskMapper.saveOrUpdate(devicePlanTask);
if (devicePlanTask != null) {
NettyDevice device = deviceSessionManager.getDevice(devicePlanTask.getDeviceId());
if (device != null) {
return device.recoveryTask();
}
}
}
return false;

View File

@@ -7,6 +7,7 @@ public enum MesType {
have_logged_in,//消息
device_status_changed,//上下线状态变化
device_error_push, //错误推送
device_task_change, //任务状态变化推送
heartbeat,
remoteControl,
detectionReport,//障碍物消息

View File

@@ -0,0 +1,15 @@
package com.maibu.dto;
import lombok.Data;
@Data
public class WebDeviceTaskStatusMessageDTO {
private MesType event;
private String deviceId;
private Long taskId;
private String status;
}

View File

@@ -3,6 +3,7 @@ package com.maibu.netty.handler;
import cn.hutool.json.JSONObject;
import com.maibu.common.MiddleCommandConstant;
import com.maibu.common.MiddleConstant;
import com.maibu.core.enums.RespondCode;
import com.maibu.dto.*;
import com.maibu.memory.MiddleGlobalMemory;
import com.maibu.netty.NettyClient;
@@ -49,7 +50,8 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
}
NettyClient nettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
if (nettyClient != null && StringUtils.isEmpty(nettyClient.currentDeviceId)) {
if (nettyClient.lastSwitchTime == -1 || System.currentTimeMillis() - nettyClient.lastSwitchTime > nettyClient.Interval) {
if (nettyClient.lastSwitchTime == -1
|| System.currentTimeMillis() - nettyClient.lastSwitchTime > nettyClient.Interval) {
if (!StringUtils.isEmpty(nettyClient.requestDeviceId) && !StringUtils.isEmpty(key)) {
switchDevice(nettyClient, key);
nettyClient.lastSwitchTime = System.currentTimeMillis();
@@ -92,7 +94,7 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(dto));
} else if ("device_error_push".equals(eventType)) {
// todo 更新推送的错误
String details = obj.get("details").toString();
// String details = obj.get("details").toString();
WebOlineStatusMessageDTO dto = new WebOlineStatusMessageDTO();
dto.setDeviceId(deviceId);
dto.setType(MesType.device_error_push);
@@ -100,6 +102,15 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
dto.setDescription("");
dto.setErrorCode("");
WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(dto));
} else if ("device_task_change".equals(eventType)) {
String taskId = obj.get("taskId").toString();
String status = obj.get("status").toString();
WebDeviceTaskStatusMessageDTO dto = new WebDeviceTaskStatusMessageDTO();
dto.setDeviceId(deviceId);
dto.setEvent(MesType.device_task_change);
dto.setTaskId(Long.valueOf(taskId));
dto.setStatus(status);
WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(dto));
}
} else {
/* 判断 respond 字段 */
@@ -128,17 +139,20 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
// WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(dto));
} else {
// todo respond netty_server返回结果处理
DeviceRespondDTO respond = JsonUtils.parseObject(obj.get("respond").toString(), DeviceRespondDTO.class);
DeviceRespondDTO respond = JsonUtils.parseObject(obj.get("respond").toString(),
DeviceRespondDTO.class);
if (respond != null) {
// 直接转发 websocket 申请
WebSwitchControlResponseDTO responseDTO = new WebSwitchControlResponseDTO();
responseDTO.setType(MesType.switchResult);
responseDTO.setRespond(respond);
WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(responseDTO));
WebsocketHandler.sendMessageToClient(webSocket,
JsonUtils.toJsonString(responseDTO));
}
}
} else {
if (obj.get("type").toString() != null && "detectionReport".equals(obj.get("type").toString())) {
if (obj.get("type").toString() != null
&& "detectionReport".equals(obj.get("type").toString())) {
WebsocketHandler.sendMessageToClient(webSocket, json);
}
}
@@ -324,7 +338,6 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
return transferData;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
@@ -354,7 +367,6 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
}
}
public static void switchDevice(NettyClient nettyClient, String key) {
try {
// 2. 调用 POST 接口:传入 Token B(与 Token A 不同)
@@ -389,7 +401,6 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
}
}
/**
* 启动心跳检测
*/