Compare commits

10 Commits

Author SHA1 Message Date
544efbd0f9 # update 权限相关 2026-08-25 12:36:10 +08:00
33df2ff0f7 # update 权限相关 2026-08-25 09:19:12 +08:00
27f4796c55 # update 2026-08-21 09:20:08 +08:00
16ec98e36a # 上位机心跳 以及定位信息发送部分 2026-08-19 16:57:55 +08:00
2f94639f0a Merge branch 'dev_control' into dev_new_connect
# Conflicts:
#	.idea/workspace.xml
2026-08-19 11:05:09 +08:00
3eb7f7bc31 #update 2026-08-19 11:03:00 +08:00
1b19e32aa5 #update 2026-08-19 11:02:52 +08:00
80bfdd134d #update mqtt 上位机 2026-08-17 11:49:33 +08:00
ffd9720939 #update mqtt 上位机 2026-08-07 10:22:03 +08:00
5f3929ae16 #update mqtt 上位机 2026-08-07 09:46:55 +08:00
55 changed files with 1484 additions and 571 deletions

119
.idea/workspace.xml generated
View File

@@ -4,18 +4,16 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="84ac1b15-3cfa-4375-9957-45b7b581d04e" name="Changes" comment="#update">
<list default="true" id="84ac1b15-3cfa-4375-9957-45b7b581d04e" name="Changes" comment="# commit">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/constant/Constant.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/constant/Constant.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/GlobalMemory.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/SiteMemory.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/mqtt/MqttTopic.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/init/InitThread.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/DataToDataBaseHandler.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/core/business/device/NettyDevice.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/DeviceSessionManager.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-common/src/main/java/com/maibu/memory/DeviceSessionManager.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/dto/DeviceBindDTO.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/dto/DeviceBindDTO.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/CommandForwardHandler.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/netty/handler/DeviceConnectHandler.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/service/DeviceThreadService.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/AlarmServiceImpl.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/AlarmServiceImpl.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-service/maibu-system-service/src/main/java/com/maibu/service/impl/IotDeviceCommonService.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-service/maibu-system-service/src/main/java/com/maibu/service/impl/IotDeviceCommonService.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/service/TransferDeviceService.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-netty-server/src/main/java/com/maibu/service/TransferDeviceService.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-web-middleware/src/main/java/com/maibu/dto/NettySwitchDeviceDTO.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-web-middleware/src/main/java/com/maibu/dto/NettySwitchDeviceDTO.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/maibu-web-middleware/src/main/java/com/maibu/netty/handler/ClientHandler.java" beforeDir="false" afterPath="$PROJECT_DIR$/maibu-web-middleware/src/main/java/com/maibu/netty/handler/ClientHandler.java" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -79,40 +77,40 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;Application.test.executor&quot;: &quot;Debug&quot;,
&quot;HTTP Request.MiddlePlatformApplication | #1.executor&quot;: &quot;Run&quot;,
&quot;HTTP Request.MiddlePlatformApplication | #2.executor&quot;: &quot;Run&quot;,
&quot;HTTP Request.MiddlePlatformApplication | #3.executor&quot;: &quot;Run&quot;,
&quot;Maven.MiddlePlatform [clean].executor&quot;: &quot;Run&quot;,
&quot;Maven.MiddlePlatform [install].executor&quot;: &quot;Run&quot;,
&quot;Maven.maibu-netty-server [clean].executor&quot;: &quot;Run&quot;,
&quot;ModuleVcsDetector.initialDetectionPerformed&quot;: &quot;true&quot;,
&quot;RequestMappingsPanelOrder0&quot;: &quot;0&quot;,
&quot;RequestMappingsPanelOrder1&quot;: &quot;1&quot;,
&quot;RequestMappingsPanelWidth0&quot;: &quot;75&quot;,
&quot;RequestMappingsPanelWidth1&quot;: &quot;75&quot;,
&quot;RunOnceActivity.MCP Project settings loaded&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252&quot;: &quot;true&quot;,
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
&quot;RunOnceActivity.typescript.service.memoryLimit.init&quot;: &quot;true&quot;,
&quot;Spring Boot.MiddlePlatformApplication.executor&quot;: &quot;Debug&quot;,
&quot;git-widget-placeholder&quot;: &quot;dev__new__connect&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;/home/maibu/Test/MiddlePlatform/maibu-external/src/main/java/com/maibu/uav&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;onboarding.tips.debug.path&quot;: &quot;D:/code/MiddlePlatform/maibu-service/maibu-system-service/src/main/java/com/maibu/Main.java&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;project.propVCSSupport.CommitDialog&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
"Application.test.executor": "Debug",
"HTTP Request.MiddlePlatformApplication | #1.executor": "Run",
"HTTP Request.MiddlePlatformApplication | #2.executor": "Run",
"HTTP Request.MiddlePlatformApplication | #3.executor": "Run",
"Maven.MiddlePlatform [clean].executor": "Run",
"Maven.MiddlePlatform [install].executor": "Run",
"Maven.maibu-netty-server [clean].executor": "Run",
"ModuleVcsDetector.initialDetectionPerformed": "true",
"RequestMappingsPanelOrder0": "0",
"RequestMappingsPanelOrder1": "1",
"RequestMappingsPanelWidth0": "75",
"RequestMappingsPanelWidth1": "75",
"RunOnceActivity.MCP Project settings loaded": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
"RunOnceActivity.git.unshallow": "true",
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
"Spring Boot.MiddlePlatformApplication.executor": "Debug",
"git-widget-placeholder": "dev__control",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "/home/maibu/Test/MiddlePlatform/maibu-external/src/main/java/com/maibu/uav",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"onboarding.tips.debug.path": "D:/code/MiddlePlatform/maibu-service/maibu-system-service/src/main/java/com/maibu/Main.java",
"settings.editor.selected.configurable": "project.propVCSSupport.CommitDialog",
"vue.rearranger.settings.migration": "true"
}
}</component>
}]]></component>
<component name="RdControllerToolWindowsLayoutState" isNewUi="true">
<layout>
<window_info id="Bookmarks" side_tool="true" />
@@ -160,11 +158,11 @@
<recent name="$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service" />
</key>
<key name="CopyClassDialog.RECENTS_KEY">
<recent name="com.maibu.mqtt" />
<recent name="com.maibu.core.business.dto" />
<recent name="com.maibu.uav.dto" />
<recent name="com.maibu.uav.controller" />
<recent name="com.maibu.mapper" />
<recent name="com.maibu.core.business.uav" />
</key>
</component>
<component name="RunManager" selected="Spring Boot.MiddlePlatformApplication">
@@ -224,8 +222,8 @@
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-30f59d01ecdd-26cb7f24e5b0-intellij.indexing.shared.core-IU-253.29346.138" />
<option value="bundled-js-predefined-d6986cc7102b-9b0f141eb926-JavaScript-IU-253.29346.138" />
<option value="bundled-jdk-30f59d01ecdd-cffe25b9f5b3-intellij.indexing.shared.core-IU-253.28294.251" />
<option value="bundled-js-predefined-d6986cc7102b-c7e53b3be11b-JavaScript-IU-253.28294.251" />
</set>
</attachedChunks>
</component>
@@ -283,7 +281,6 @@
<workItem from="1779683678663" duration="17250000" />
<workItem from="1779755672380" duration="9935000" />
<workItem from="1779770107645" duration="17442000" />
<workItem from="1786062684292" duration="833000" />
</task>
<task id="LOCAL-00001" summary="#update">
<option name="closed" value="true" />
@@ -533,23 +530,7 @@
<option name="project" value="LOCAL" />
<updated>1779242181619</updated>
</task>
<task id="LOCAL-00032" summary="#update">
<option name="closed" value="true" />
<created>1785982626224</created>
<option name="number" value="00032" />
<option name="presentableId" value="LOCAL-00032" />
<option name="project" value="LOCAL" />
<updated>1785982626225</updated>
</task>
<task id="LOCAL-00033" summary="#update">
<option name="closed" value="true" />
<created>1785991726504</created>
<option name="number" value="00033" />
<option name="presentableId" value="LOCAL-00033" />
<option name="project" value="LOCAL" />
<updated>1785991726504</updated>
</task>
<option name="localTasksCounter" value="34" />
<option name="localTasksCounter" value="32" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
@@ -600,6 +581,7 @@
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<option name="CHECK_NEW_TODO" value="false" />
<MESSAGE value="#init" />
<MESSAGE value="#update" />
<MESSAGE value="物模型的新增和修改和查看列表接口" />
<MESSAGE value="SysUser新增权限字段,和需改增加和修改和查询列表接口" />
<MESSAGE value="修改接口system/site/list 根据组织id得到场站list" />
@@ -622,8 +604,7 @@
<MESSAGE value="#id重复bug" />
<MESSAGE value="#修复工单修改接口" />
<MESSAGE value="# commit" />
<MESSAGE value="#update" />
<option name="LAST_COMMIT_MESSAGE" value="#update" />
<option name="LAST_COMMIT_MESSAGE" value="# commit" />
<option name="NON_MODAL_COMMIT_POSTPONE_SLOW_CHECKS" value="false" />
</component>
<component name="XDebuggerManager">
@@ -706,17 +687,17 @@
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java</url>
<line>237</line>
<line>234</line>
<option name="timeStamp" value="51" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java</url>
<line>250</line>
<line>247</line>
<option name="timeStamp" value="52" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-line">
<url>file://$PROJECT_DIR$/maibu-service/maibu-iot-service/src/main/java/com/maibu/service/impl/DeviceServiceImpl.java</url>
<line>285</line>
<line>282</line>
<option name="timeStamp" value="61" />
</line-breakpoint>
<line-breakpoint enabled="true" type="java-method">

View File

@@ -3,7 +3,7 @@ spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/maibu?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
url: jdbc:mysql://1.95.137.212:3306/maibu?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: satabot
password: satabot
@@ -31,7 +31,7 @@ spring:
mqtt:
username: maibu # 账号
password: jsmbzn520 # 密码
host-url: tcp://localhost:1883 # mqtt连接tcp地址
host-url: tcp://1.95.137.212:1883 # mqtt连接tcp地址
client-id: maibu-mqtt-client # 客户端Id,不能相同,采用随机数 ${random.value}
default-topic: test # 默认主题
timeout: 30 # 超时时间

View File

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

View File

@@ -21,9 +21,11 @@ public class Constant {
public static final AttributeKey<String> ATT_SITE_ID = AttributeKey.valueOf("siteId");
public static final String WheelGainCoefficients = "WheelGainCoefficients";
public static final String WheelGainCoefficients = "WheelGainCoefficients";
public static final String mqttClientPrefix = "common-device-client-";
public static final String mqttClientPrefix = "common-device-client-";
public static final String mqttHandleKey = "hostHandle";
public static final Long hostOfflineInterval = 10000L; //单位毫秒
}

View File

@@ -100,6 +100,11 @@ public interface FastBeeConstant {
* 设备错误
*/
String DEVICE_ERROR_MONITOR = "deviceErrorMonitor";
/**
* 设备错误
*/
String DEVICE_HEARTBEAT_MONITOR = "deviceHeartBeatMonitor";
/**
* 设备任务处理线程
*/

View File

@@ -39,4 +39,7 @@ public class DevicePlanTask extends OrgBaseDO {
private LocalDateTime canExecuteTime; // 这个时间之前都不能执行
@TableField(exist = false)
private volatile boolean taskAccepted = false; //任务被上位机接收
}

View File

@@ -20,6 +20,8 @@ public class WorkRecord extends OrgBaseDO {
private String workName;
private Long userId;
private String mode;//导航任务模式 single_point|coverage
// private String jsonData;
@TableField(typeHandler = JacksonTypeHandler.class)

View File

@@ -1,35 +1,39 @@
package com.maibu.core.business.device;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.Queue;
import com.maibu.utils.json.JsonUtils;
import org.springframework.util.CollectionUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.maibu.core.business.Device;
import com.maibu.core.business.DevicePlanTask;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.core.business.DeviceRunStatistics;
import com.maibu.core.business.PlanPath;
import com.maibu.core.business.WorkRecord;
import com.maibu.core.business.*;
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;
import com.maibu.core.host.HostWorkRecordCreateDTO;
import com.maibu.core.host.MutiPointEntity;
import com.maibu.core.host.PointEntity;
import com.maibu.mapper.DevicePlanTaskMapper;
import com.maibu.mapper.WorkRecordMapper;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.mqtt.MqttTopic;
import com.maibu.utils.StringUtils;
import com.maibu.utils.json.JsonUtils;
import com.maibu.utils.spring.SpringUtils;
import io.netty.buffer.Unpooled;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@EqualsAndHashCode(callSuper = true)
@@ -58,8 +62,8 @@ public class NettyDevice extends Connector {
// todo 注册的时候更新 siteId
private Device device;
//todo 假如设置一个当前控制的token
private String currentControlToken;
//todo 当前登录的账号的token 以token为控制的权限
private String token;
@JsonIgnore
private DevicePlanTaskMapper devicePlanTaskMapper = SpringUtils.getBean(DevicePlanTaskMapper.class);
@@ -67,6 +71,11 @@ public class NettyDevice extends Connector {
@JsonIgnore
private WorkRecordMapper workRecordMapper = SpringUtils.getBean(WorkRecordMapper.class);
@JsonIgnore
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
private static final String mqttClientId = "maibu-mqtt-client";
public NettyDevice(String connectorId) {
super(connectorId);
this.deviceType = ConnectorType.MASTER; // 默认上位机角色
@@ -77,6 +86,11 @@ public class NettyDevice extends Connector {
this.deviceType = deviceType;
}
public void status(Integer onlineStatus) {
this.onlineStatus = onlineStatus;
}
// todo 如何确定命令已收到?
public void sendNextPoint() {
if (task.getTaskStaus().equals(DeviceTaskStaus.PAUSE))
@@ -109,13 +123,14 @@ public class NettyDevice extends Connector {
}
public synchronized Long finishTask() {
sendPathCommand((byte) 0x01, (short) 0, 0.00d, 0.00d, (short) 0);
// sendPathCommand((byte) 0x01, (short) 0, 0.00d, 0.00d, (short) 0);
long finishId = task.getId();
task.setTaskStaus(DeviceTaskStaus.FINISH);
task.setFinishTime(LocalDateTime.now());
devicePlanTaskMapper.saveOrUpdate(task);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(task.getOrgId(), task.getSiteId());
siteMemory.removeDevicePlanExecute(task.getDeviceId());
GlobalMemory.taskPathMap.remove(task.getId());
task = null;
currentTaskId = null;
currentPoint = null;
@@ -124,15 +139,58 @@ public class NettyDevice extends Connector {
return finishId;
}
public synchronized boolean cancelTask() {
// 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) {
WorkRecord workRecord = workRecordMapper.selectById(task.getRouteId());
if (workRecord != null) {
HostWorkRecordCreateDTO dto = new HostWorkRecordCreateDTO();
dto.setAction("cancel");
dto.setCommand_id(task.getId() + "_" + System.currentTimeMillis());
dto.setTask_id(String.valueOf(task.getId()));
dto.setSn(task.getDeviceId());
dto.setMode(workRecord.getMode());
dto.setTimestamp(System.currentTimeMillis());
dto.setMessage_id(task.getId() + "_" + System.currentTimeMillis());
dto.setProtocol_version("1.4");
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.MOWER_TASK_ROUTE_SET, task.getDeviceId()),
JsonUtils.toJsonString(dto));
task.setTaskStaus(DeviceTaskStaus.CANCELING);
task.setUpdateTime(LocalDateTime.now());
devicePlanTaskMapper.saveOrUpdate(task);
}
}
return true;
}
public synchronized boolean canceledTask() {
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());
GlobalMemory.taskPathMap.remove(task.getId());
task = null;
currentTaskId = null;
currentPoint = null;
@@ -238,28 +296,133 @@ 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 {
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);
});
}
}
// startTime 在启动前记录
task.setStartTime(LocalDateTime.now());
AtomicInteger count = new AtomicInteger(0);
ScheduledFuture<?>[] futureHolder = new ScheduledFuture<?>[1];
futureHolder[0] = executor.scheduleWithFixedDelay(() -> {
int current = count.incrementAndGet();
try {
executingTask = true;
if (task.isTaskAccepted()) {
// 成功,停止后续执行
futureHolder[0].cancel(false);
log.info("任务执行成功,停止重试,执行次数={}", current);
return;
}
sendNavigationCommand();
// 达到最大次数
if (current >= 10) {
futureHolder[0].cancel(false);
log.warn("任务执行达到最大次数,停止执行");
executingTask = false;
task.setTaskStaus(DeviceTaskStaus.FAILED);
devicePlanTaskMapper.saveOrUpdate(task);
task = null;
}
} catch (Exception e) {
log.error("任务执行异常,次数={}", current, e);
// 异常是否算一次,可以根据你的业务决定
if (current >= 10) {
futureHolder[0].cancel(false);
}
executingTask = false;
task.setTaskStaus(DeviceTaskStaus.FAILED);
devicePlanTaskMapper.saveOrUpdate(task);
task = null;
}
}, 0, 3, TimeUnit.SECONDS);
}
executingTask = true;
sendNextPoint();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void sendNavigationCommand() throws MqttException {
log.debug("发送开始任务 taskStatus:{},routeId:{}", task.getTaskStaus(), task.getRouteId());
if (!task.getTaskStaus().equals(DeviceTaskStaus.EXECUTING))
return;
WorkRecord workRecord = workRecordMapper.selectById(task.getRouteId());
log.debug("发送开始任务 workRecord {}", workRecord);
if (workRecord != null) {
HostWorkRecordCreateDTO dto = new HostWorkRecordCreateDTO();
dto.setAction("start");
dto.setCommand_id(task.getId() + "_" + System.currentTimeMillis());
dto.setTask_id(String.valueOf(task.getId()));
dto.setSn(task.getDeviceId());
dto.setMode(workRecord.getMode());
dto.setTimestamp(System.currentTimeMillis());
dto.setMessage_id(task.getId() + "_" + System.currentTimeMillis());
dto.setProtocol_version("1.4");
PointEntity point = new PointEntity();
if (!StringUtils.isEmpty(workRecord.getMode())) {
if (workRecord.getMode().equals("single_point")) {
point.setLongitude(workRecord.getJsonData().getPath().get(0).getLng());
point.setLatitude(workRecord.getJsonData().getPath().get(0).getLat());
}
if (workRecord.getMode().equals("coverage")) {
List<MutiPointEntity> boundary_points = new ArrayList<>();
// workRecord.getJsonData().getPath().forEach(x -> {
// MutiPointEntity mutiPoint = new MutiPointEntity();
// mutiPoint.setLongitude(x.getLng());
// mutiPoint.setLatitude(x.getLat());
// mutiPoint.setIndex();
// boundary_points.add(mutiPoint);
// });
List<LatAndLngEntity> path = workRecord.getJsonData().getPath();
for (int i = 0; i < path.size(); i++) {
LatAndLngEntity x = path.get(i);
MutiPointEntity mutiPoint = new MutiPointEntity();
mutiPoint.setLongitude(x.getLng());
mutiPoint.setLatitude(x.getLat());
mutiPoint.setIndex(i);
boundary_points.add(mutiPoint);
}
point.setBoundary_points(boundary_points);
}
}
dto.setData(point);
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.MOWER_TASK_ROUTE_SET, task.getDeviceId()),
JsonUtils.toJsonString(dto));
}
}
}

View File

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

View File

@@ -1,4 +1,4 @@
package com.maibu.dto;
package com.maibu.core.business.dto;
import lombok.Data;

View File

@@ -48,6 +48,12 @@ public class LoginUser implements UserDetails {
*/
private String token;
/**
* 用户唯一标识 用户控制设备
*/
private String realToken;
/**
* 登录时间
*/
@@ -108,7 +114,7 @@ public class LoginUser implements UserDetails {
this.permissions = permissions;
}
public LoginUser(Long userId, Long deptId, Long orgId, Long siteId, Long roleId,String language, SysUser user, Set<String> permissions) {
public LoginUser(Long userId, Long deptId, Long orgId, Long siteId, Long roleId, String language, SysUser user, Set<String> permissions) {
this.userId = userId;
this.deptId = deptId;
this.orgId = orgId;

View File

@@ -7,12 +7,13 @@ import lombok.Getter;
@AllArgsConstructor
public enum DeviceTaskStaus {
NEW("NEW","新建"),
EXECUTING("EXECUTING","执行中"),
PAUSE("PAUSE","暂停中"),
CANCELED("CANCELED","已取消"),
FINISH("FINISH","执行成功"),
FAILED("FAILED","执行失败");
NEW("NEW", "新建"),
EXECUTING("EXECUTING", "执行中"),
PAUSE("PAUSE", "暂停中"),
CANCELED("CANCELED", "已取消"),
CANCELING("CANCELING", "取消中"),
FINISH("FINISH", "执行成功"),
FAILED("FAILED", "执行失败");
private final String code;

View File

@@ -3,6 +3,7 @@ package com.maibu.core.enums;
public enum MesType {
AUTH, // 登录连接权限web->be
deviceInfo, // 设备状态 be->web
locationInfo,
path, // 路径下发 web->be
have_logged_in, // 消息
device_status_changed, // 上下线状态变化

View File

@@ -0,0 +1,12 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HeartBeatDTO extends HostBase {
private String status;
private Long sysTimestamp; //服务器的时间
}

View File

@@ -0,0 +1,13 @@
package com.maibu.core.host;
import lombok.Data;
@Data
public class HostBase {
private String protocol_version;
private String message_id;
private String sn;
private Long timestamp; //上位机的时间
}

View File

@@ -0,0 +1,13 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HostLocationRelTimeDTO extends HostBase {
private LocationMessage data;
}

View File

@@ -0,0 +1,19 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HostNavigationReplyDTO extends HostBase {
private String task_id; //任务唯一编号
private String command_id;//指令唯一编号
private boolean accepted;//是否接收
private String code;//任务动作 OK|INVALID|BUSY|ERROR
private String message;
}

View File

@@ -0,0 +1,19 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HostTaskStatusDTO extends HostBase{
private String task_id; //任务唯一编号
private String command_id;//指令唯一编号
private String mode;//导航任务模式 single_point|coverage
private String status;//任务动作 accepted|running|paused|completed|cancelled|failed
private HostTaskStatusDetailDTO data;
}

View File

@@ -0,0 +1,12 @@
package com.maibu.core.host;
import lombok.Data;
@Data
public class HostTaskStatusDetailDTO {
private float progress;
private String error_code;
private String error_message;
}

View File

@@ -0,0 +1,13 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HostVehicleRelTimeDTO extends HostBase {
private VehicleMessage data;
}

View File

@@ -0,0 +1,20 @@
package com.maibu.core.host;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public class HostWorkRecordCreateDTO extends HostBase {
private String task_id; //任务唯一编号
private String command_id;//指令唯一编号
private String mode;//导航任务模式 single_point|coverage
private String action;//任务动作 start/pause/resume/cancel
// private String frame_id; //WGS84
private PointEntity data;
}

View File

@@ -0,0 +1,15 @@
package com.maibu.core.host;
import lombok.Data;
@Data
public class LocationMessage {
private double latitude;
private double longitude;
private double yaw;//目标航向,正北0°、顺时针正、0-360°
private String fix_status;
private double altitude;
}

View File

@@ -0,0 +1,14 @@
package com.maibu.core.host;
import lombok.Data;
@Data
public class MutiPointEntity {
private int index;
private double latitude;
private double longitude;
private double yaw;//目标航向,正北0°、顺时针正、0-360°
}

View File

@@ -0,0 +1,20 @@
package com.maibu.core.host;
import lombok.Data;
import java.util.List;
@Data
public class PointEntity {
private double latitude;
private double longitude;
private double yaw;//目标航向,正北0°、顺时针正、0-360°
private List<MutiPointEntity> boundary_points;
private double cell_size;//覆盖分辨率,单位m
private double angle;//覆盖作业方向,单位度
}

View File

@@ -0,0 +1,15 @@
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; //急停状态
}

View File

@@ -30,6 +30,9 @@ public class DeviceSessionManager {
// 设备ID -> 设备对象(业务实体)
private final ConcurrentHashMap<String, NettyDevice> deviceMap = new ConcurrentHashMap<>();
//当前设备的控制权在哪 登录的账号 deviceId(下位机) -> token key 唯一保证一个deviceId 只有一个控制权
private final ConcurrentHashMap<String, String> controllerMap = new ConcurrentHashMap<>();
// 设备ID -> Channel(通信通道)
private final ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();
@@ -84,6 +87,20 @@ public class DeviceSessionManager {
System.out.println("Registered device: " + deviceId + " type: " + deviceType);
}
/**
* 注册下位机设备
*
* @param deviceId 设备ID
*/
public void registerSlaveDevice(String deviceId, ConnectorStatus status, String slaveId) {
NettyDevice nettyDevice = deviceMap.computeIfAbsent(deviceId, id -> new NettyDevice(id, ConnectorType.SLAVE));
nettyDevice.setConnectorStatus(status); // 默认上线即ACTIVE
nettyDevice.setCurrentSlaveId(slaveId);
nettyDevice.setLatestLoginTime(System.currentTimeMillis());
deviceMap.put(deviceId, nettyDevice);
logger.debug("Registered slave device:{},type:{}", deviceId, ConnectorType.SLAVE);
}
/**
* 上位机绑定下位机,建立双向绑定关系
*
@@ -105,6 +122,64 @@ public class DeviceSessionManager {
return deviceMap.get(deviceId);
}
/**
* 获取有控制权的 客户端
*/
public String getMaster(String deviceId) {
return controllerMap.get(deviceId);
}
/**
* 获取客户端当前 控制的设备
*/
public String getControl(String token) {
for (String key : controllerMap.keySet()) {
if (controllerMap.get(key).equals(token)) {
return controllerMap.get(token);
}
}
return null;
}
public void lock(String deviceId, String token) {
if (!StringUtils.isEmpty(deviceId) && !StringUtils.isEmpty(token)) {
controllerMap.put(deviceId, token);
}
}
public boolean unLock(String token) {
if (!StringUtils.isEmpty(token)) {
Iterator<String> iterator = controllerMap.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
if (controllerMap.get(key).equals(token)) {
iterator.remove();
}
}
}
return true;
}
public boolean unLock(String deviceId, String token, boolean force) {
if (!StringUtils.isEmpty(deviceId)) {
if (force) {
controllerMap.remove(deviceId);
return true;
} else {
String nowToken = controllerMap.get(deviceId);
if (!StringUtils.isEmpty(token) && nowToken.equals(token)) {
controllerMap.remove(deviceId);
return true;
}
}
}
return false;
}
// 模糊匹配
public List<NettyDevice> getDevicesLike(String query) {
return deviceMap.values().stream()

View File

@@ -3,6 +3,7 @@ package com.maibu.memory;
import com.maibu.constant.Constant;
import com.maibu.core.business.Device;
import com.maibu.core.business.IoTCommonDevice;
import com.maibu.core.business.path.LatAndLngEntity;
import com.maibu.influxdb.util.InfluxDBUtil;
import com.maibu.mqtt.*;
import lombok.Data;
@@ -24,6 +25,8 @@ public class GlobalMemory {
// key:orgId - siteId
public static ConcurrentHashMap<Long, Map<Long, SiteMemory>> orgAttrs = new ConcurrentHashMap<>();
public static ConcurrentHashMap<Long, List<LatAndLngEntity>> taskPathMap = new ConcurrentHashMap<>();
public static InfluxDBUtil influxDBUtil;
// public static MqttClientUtil mqttClientUtil;
@@ -101,11 +104,16 @@ public class GlobalMemory {
deviceConfig.setUsername(mqttUsername);
deviceConfig.setPassword(mqttPassword);
//TODO 添加所有需要订阅的
deviceConfig.setSubscribeTopics(Arrays.asList(MqttTopic.MOWER_WILDCARD_LOCATION));
deviceConfig.setSubscribeTopics(Arrays.asList(
MqttTopic.MOWER_HEARTBEAT,//心跳
MqttTopic.MOWER_WILDCARD_LOCATION,//位置 经纬度
MqttTopic.MOWER_WILDCARD_TASK_ROUTE, //路径回复
MqttTopic.MOWER_WILDCARD_ERROR,//错误
MqttTopic.MOWER_WILDCARD_REALTIME, //状态消息
MqttTopic.MOWER_WILDCARD_TASK_TARGET_REPLY //路径规划下发回复
));
deviceConfig.setHandlerType(Constant.mqttHandleKey); //唯一的 用于处理上位机mqtt的
customMqttDeviceMonitor.registerDevice(deviceConfig);
}
}

View File

@@ -1,17 +1,24 @@
package com.maibu.mqtt;
import com.maibu.core.host.HeartBeatDTO;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 自定义外部设备 MQTT 订阅管理器
@@ -66,6 +73,24 @@ public class CustomMqttDeviceMonitor {
*/
private ScheduledExecutorService scheduler;
private final ConcurrentHashMap<String, HeartBeatDTO> hearBeatMap = new ConcurrentHashMap<>();
private final ThreadPoolExecutor messageExecutor = new ThreadPoolExecutor(
4, 8, 30L, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(256),
new ThreadFactory() {
private final AtomicInteger counter = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "mqtt-message-worker-" + counter.getAndIncrement());
t.setDaemon(true);
return t;
}
},
new ThreadPoolExecutor.CallerRunsPolicy()
);
/**
* 巡检间隔(秒)
*/
@@ -74,7 +99,7 @@ public class CustomMqttDeviceMonitor {
// ==================== 消息处理器管理 ====================
public CustomMqttMessageHandler getMessageHandler(String key){
public CustomMqttMessageHandler getMessageHandler(String key) {
return handlerMap.get(key);
}
@@ -152,6 +177,25 @@ public class CustomMqttDeviceMonitor {
return client != null && client.isConnected();
}
/**
* 保存心跳
*/
public void saveHeartBeat(String sn, HeartBeatDTO dto) {
hearBeatMap.put(sn, dto);
}
/**
* 获取心跳
*/
public HeartBeatDTO getHeartBeat(String sn) {
return hearBeatMap.get(sn);
}
public List<HeartBeatDTO> getAllHeartBeat() {
return new ArrayList<>(hearBeatMap.values());
}
// ==================== 连接管理 ====================
/**
@@ -180,6 +224,7 @@ public class CustomMqttDeviceMonitor {
if (scheduler != null) {
scheduler.shutdown();
}
messageExecutor.shutdown();
clientMap.keySet().forEach(this::disconnectDevice);
log.info("CustomMqttDeviceMonitor 已停止");
}
@@ -226,7 +271,7 @@ public class CustomMqttDeviceMonitor {
public void messageArrived(String topic, MqttMessage message) {
String payload = new String(message.getPayload());
log.debug("收到消息: deviceKey={}, topic={}, payload={}", deviceKey, topic, payload);
dispatchMessage(deviceKey, topic, payload, config);
messageExecutor.submit(() -> dispatchMessage(deviceKey, topic, payload, config));
}
@Override
@@ -373,6 +418,7 @@ public class CustomMqttDeviceMonitor {
/**
* 向指定设备发布消息(指定 QoS)
* 异步投递到线程池执行,避免阻塞 MQTT 回调线程
*/
public void publish(String deviceKey, String topic, String payload, int qos) throws MqttException {
MqttClient client = clientMap.get(deviceKey);
@@ -383,7 +429,7 @@ public class CustomMqttDeviceMonitor {
MqttMessage message = new MqttMessage(payload.getBytes());
message.setQos(qos);
client.publish(topic, message);
log.debug("发布消息: deviceKey={}, topic={}", deviceKey, topic);
log.debug("发布消息: deviceKey={}, topic={},payload:{}", deviceKey, topic, payload);
}
/**

View File

@@ -3,7 +3,22 @@ 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;
/**
@@ -14,6 +29,12 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
private final ObjectMapper objectMapper = new ObjectMapper();
private final DeviceSessionManager deviceSessionManager = SpringUtils.getBean(DeviceSessionManager.class);
private final WebsocketMesDispather websocketMesDispather = SpringUtils.getBean(WebsocketMesDispather.class);
private final String mqttClientId = "maibu-mqtt-client";
@Override
public String getHandlerType() {
@@ -76,6 +97,9 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
case "control_reply":
handleControlReply(deviceId, topic, payload);
break;
case "route_reply":
handleRouteReply(deviceId, topic, payload);
break;
default:
log.debug("割草机消息: deviceId={}, topic={}, action={}", deviceId, topic, action);
break;
@@ -86,38 +110,119 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
}
/**
* 处理 GPS 位置数据上报
* topic: mower/{deviceId}/property/location/post
* 定位信息 经纬度
*/
private void handleLocationPost(String deviceId, String topic, String payload) {
try {
JsonNode jsonNode = objectMapper.readTree(payload);
double latitude = getDouble(jsonNode, "latitude", "lat");
double longitude = getDouble(jsonNode, "longitude", "lng", "lon");
double speed = getDouble(jsonNode, "speed");
double heading = getDouble(jsonNode, "heading", "direction");
double altitude = getDouble(jsonNode, "altitude", "alt");
int satellites = getInt(jsonNode, "satellites", "sats");
String fixQuality = getString(jsonNode, "fixQuality", "fix_quality");
Double batteryLevel = getDoubleObj(jsonNode, "batteryLevel", "battery");
log.info("【位置数据】deviceId={}, lat={}, lng={}, speed={}, heading={}, sats={}",
deviceId, latitude, longitude, speed, heading, satellites);
onLocationUpdate(deviceId, latitude, longitude, speed, heading, altitude, satellites, fixQuality, batteryLevel);
log.debug("【位置数据】deviceId={}, payload={}", deviceId, payload);
HostLocationRelTimeDTO locationRelTimeDTO = JsonUtils.parseObject(payload, HostLocationRelTimeDTO.class);
if (locationRelTimeDTO != null) {
WebStatusMessageDTO dto = createWebDeviceLocationMessage(locationRelTimeDTO);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("位置数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(), e.getMessage());
}
}
}
//todo 推送实时位置和状态消息到外部
//todo 记录到内存 开线程池队列 逐一转发
// GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_LOCATION_TOPIC, deviceId),
// JsonUtils.toJsonString(dto));
}
} catch (Exception e) {
log.error("位置消息解析失败: deviceId={}, payload={}, error={}", deviceId, payload, e.getMessage());
}
}
public WebStatusMessageDTO createWebDeviceLocationMessage(HostLocationRelTimeDTO locationRelTimeDTO) {
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
List<DeviceStatusDetail> transferData = new ArrayList<>();
DeviceStatusDetail lat = new DeviceStatusDetail();
lat.setName("latitude");
lat.setValue(String.valueOf(locationRelTimeDTO.getData().getLatitude()));
lat.setUnit("");
transferData.add(lat);
DeviceStatusDetail lng = new DeviceStatusDetail();
lng.setName("longitude");
lng.setValue(String.valueOf(locationRelTimeDTO.getData().getLongitude()));
lng.setUnit("");
transferData.add(lng);
webStatusMessageDTO.setData(transferData);
webStatusMessageDTO.setType(MesType.locationInfo);
return webStatusMessageDTO;
}
public WebStatusMessageDTO createWebDeviceRealtimeMessage(HostVehicleRelTimeDTO vehicleRelTimeDTO) {
//todo 状态消息
WebStatusMessageDTO webStatusMessageDTO = new WebStatusMessageDTO();
List<DeviceStatusDetail> transferData = new ArrayList<>();
DeviceStatusDetail voltage = new DeviceStatusDetail();
voltage.setName("voltage");
voltage.setValue(String.valueOf(vehicleRelTimeDTO.getData().getBattery_voltage()));
voltage.setUnit("");
transferData.add(voltage);
DeviceStatusDetail speed = new DeviceStatusDetail();
speed.setName("speed");
speed.setValue(String.valueOf(vehicleRelTimeDTO.getData().getSpeed()));
speed.setUnit("");
transferData.add(speed);
DeviceStatusDetail motion = new DeviceStatusDetail();
motion.setName("motion");
motion.setValue(String.valueOf(vehicleRelTimeDTO.getData().getMotion()));
motion.setUnit("");
transferData.add(motion);
DeviceStatusDetail percentage = new DeviceStatusDetail();
percentage.setName("percentage");
percentage.setValue(String.valueOf(vehicleRelTimeDTO.getData().getBattery_percentage()));
percentage.setUnit("");
transferData.add(percentage);
webStatusMessageDTO.setData(transferData);
webStatusMessageDTO.setType(MesType.deviceInfo);
return webStatusMessageDTO;
}
/**
* 处理实时运行数据
* topic: mower/{deviceId}/property/realtime/post
* 上位机数据
*/
private void handleRealtimePost(String deviceId, String topic, String payload) {
log.debug("【实时数据】deviceId={}, payload={}", deviceId, payload);
try {
HostVehicleRelTimeDTO vehicleRelTimeDTO = JsonUtils.parseObject(payload, HostVehicleRelTimeDTO.class);
if (vehicleRelTimeDTO != null) {
WebStatusMessageDTO dto = createWebDeviceRealtimeMessage(vehicleRelTimeDTO);
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
for (NettyDevice x : controlMasters) {
try {
websocketMesDispather.dispather(x.getConnectorId(), JsonUtils.toJsonString(dto));
} catch (Exception e) {
log.error("实时数据websocket推送失败: connectorId={}, error={}", x.getConnectorId(), e.getMessage());
}
}
}
// 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());
}
}
/**
@@ -133,7 +238,13 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
* topic: mower/{deviceId}/event/heartbeat/post
*/
private void handleHeartbeatPost(String deviceId, String topic, String payload) {
log.debug("【心跳】deviceId={}", deviceId);
log.debug("【心跳】payload={}", payload);
// 心跳处理
HeartBeatDTO beatDTO = JsonUtils.parseObject(payload, HeartBeatDTO.class);
if (beatDTO != null) {
beatDTO.setSysTimestamp(System.currentTimeMillis());
GlobalMemory.customMqttDeviceMonitor.saveHeartBeat(beatDTO.getSn(), beatDTO);
}
}
/**
@@ -149,6 +260,36 @@ 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();
}
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();
// }
}
}
/**
@@ -165,14 +306,24 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
log.debug("【控制响应】deviceId={}, payload={}", deviceId, payload);
}
/**
* 位置数据回调,子类可覆盖实现业务逻辑
* 处理控制指令响应
*/
protected void onLocationUpdate(String deviceId, double latitude, double longitude,
double speed, double heading, double altitude,
int satellites, String fixQuality, Double batteryLevel) {
private void handleRouteReply(String deviceId, String topic, String payload) {
log.debug("【路径任务下发响应】deviceId={}, payload={}", deviceId, payload);
//todo 更新任务接收状态
HostNavigationReplyDTO replyDTO = SpringUtils.getBean(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())) {
device.getTask().setTaskAccepted(true);
}
}
}
/**
* 从 Topic 中解析 deviceId
* Topic 格式:mower/{deviceId}/...
@@ -215,6 +366,7 @@ public class HostMessageHandler implements CustomMqttMessageHandler {
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";
return null;
}

View File

@@ -5,6 +5,8 @@ public class MqttTopic {
/** @deprecated 通用设备主题,建议使用 MOWER_* 系列主题 */
public static final String DEVICE_STATUS_TOPIC = "device/%s/realTimeMessage";
public static final String DEVICE_LOCATION_TOPIC = "device/%s/locationMessage";
/** @deprecated 通用设备主题,建议使用 MOWER_* 系列主题 */
public static final String DEVICE_TASK_STATUS_TOPIC = "task/%s/status";
/** @deprecated 通用设备主题,建议使用 MOWER_* 系列主题 */
@@ -45,8 +47,11 @@ 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";
/** 启动任务执行(平台->设备),对应 TCP 0x12 interaction */
public static final String MOWER_TASK_STATUS_SET = "mower/%s/task/status/set";
public static final String MOWER_TASK_POINT_POST = "mower/%s/task/point/post";
@@ -87,6 +92,15 @@ public class MqttTopic {
/** 订阅所有设备的任务状态变更 */
public static final String MOWER_WILDCARD_TASK_STATUS = "mower/+/task/status/post";
public static final String MOWER_WILDCARD_TASK_ROUTE = "mower/+/task/route/post";
public static final String MOWER_WILDCARD_TASK_TARGET_REPLY = "mower/+/task/target/reply";
public static final String MOWER_HEARTBEAT = "mower/+/event/heartbeat/post";
/**
* 格式化 Topic 模板,将 %s 替换为设备ID
*

View File

@@ -29,6 +29,7 @@ import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
@@ -58,6 +59,9 @@ public class UAVService {
@Autowired
private RedisCache redisCache;
@Autowired
private ScheduledExecutorService executor;
public static final Map<String, Long> latestActiveTime = new ConcurrentHashMap<>();
@@ -669,7 +673,6 @@ public class UAVService {
@PostConstruct
public void heartbeatMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
Long nowTime = System.currentTimeMillis();
@@ -821,4 +824,5 @@ public class UAVService {
return false;
}
}

View File

@@ -116,7 +116,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 过滤请求
.authorizeRequests()
// 对于登录login 注册register 验证码captchaImage 允许匿名访问
.antMatchers("/api/thermal/**","/iotDA/device/**", "/websocket/allMemory", "/iot/UAV/**", "/iot/api/**", "/iot/device/userDevice", "/external/sms/sendAliSmsCode", "/login", "/register", "/captchaImage", "/iot/tool/register", "/iot/tool/ntp",
.antMatchers("/iot/host/upload-path-csv","/api/thermal/**","/iotDA/device/**", "/websocket/allMemory", "/iot/UAV/**", "/iot/api/**", "/iot/device/userDevice", "/external/sms/sendAliSmsCode", "/login", "/register", "/captchaImage", "/iot/tool/register", "/iot/tool/ntp",
"/iot/tool/mqtt/auth", "/iot/workRecord/**", "/iot/tool/mqtt/authv5", "/iot/tool/mqtt/webhook", "/iot/tool/mqtt/webhookv5", "/auth/**/**",
"/wechat/mobileLogin", "/wechat/miniLogin", "/wechat/wxBind/callback").permitAll()
.antMatchers("/zlmhook/**").permitAll()

View File

@@ -170,8 +170,9 @@ public class TokenService {
Map<String, Object> claims = new HashMap<>();
claims.put(Constants.LOGIN_USER_KEY, token);
return createToken(claims);
String realToken = createToken(claims);
loginUser.setRealToken(realToken);
return realToken;
}
public int addToken(SysUser user, SysClient sysClient) {

View File

@@ -3,6 +3,7 @@ package com.maibu.controller;
import java.time.LocalDate;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
@@ -125,12 +126,12 @@ public class DeviceTaskController extends BaseController {
}
@PostMapping("/cancelTask")
public AjaxResult cancelTask(@RequestBody DeviceTaskCommandDTO dto) {
public AjaxResult cancelTask(@RequestBody DeviceTaskCommandDTO dto) throws MqttException {
String deviceId = dto.getDeviceId();
if (StringUtils.isEmpty(deviceId) && dto.getTaskId() == null) {
return AjaxResult.error("deviceId或taskId为空!");
}
return AjaxResult.success(deviceTaskService.cancelTask(dto, getUsername()));
return AjaxResult.success(deviceTaskService.cancelTask(dto));
}
@PostMapping("/pauseTask")

View File

@@ -66,11 +66,7 @@ public class TransferDeviceController extends BaseController {
if (StringUtils.isEmpty(bindDTO.getPlatform())) {
return AjaxResult.error("平台为空!");
}
LoginUser user = getLoginUser();
if (user == null) {
return AjaxResult.error("当前token用户不存在!");
}
return AjaxResult.success(transferDeviceService.switchDevice(bindDTO, user));
return AjaxResult.success(transferDeviceService.switchDevice(bindDTO));
}
/**
@@ -87,8 +83,7 @@ public class TransferDeviceController extends BaseController {
if (StringUtils.isEmpty(bindDTO.getPlatform())) {
return AjaxResult.error("平台为空!");
}
LoginUser user = getLoginUser();
return AjaxResult.success(transferDeviceService.remoteControl(bindDTO, user));
return AjaxResult.success(transferDeviceService.remoteControl(bindDTO));
} catch (Exception e) {
logger.error("获取设备控制权出错", e);
return AjaxResult.error();
@@ -122,8 +117,7 @@ public class TransferDeviceController extends BaseController {
if (StringUtils.isEmpty(bindDTO.getPlatform())) {
return AjaxResult.error("平台为空!");
}
LoginUser user = getLoginUser();
transferDeviceService.releaseControl(bindDTO, user);
transferDeviceService.releaseControl(bindDTO);
return AjaxResult.success();
}
}

View File

@@ -24,4 +24,6 @@ public class DeviceBindDTO {
private Integer type; // releaseControl 1 完全释放 2 释放控制权 可监听数据
private String token;
}

View File

@@ -39,6 +39,9 @@ public class InitThread implements ApplicationRunner {
@Resource(name = FastBeeConstant.TASK.DEVICE_ERROR_MONITOR)
private Executor deviceErrorMonitorExecutor;
@Resource(name = FastBeeConstant.TASK.DEVICE_HEARTBEAT_MONITOR)
private Executor deviceHeartBeatMonitorExecutor;
@Resource(name = FastBeeConstant.TASK.COMMON_DEVICE_MONITOR)
private Executor commonDeviceMonitorExecutor;
@@ -124,6 +127,11 @@ public class InitThread implements ApplicationRunner {
GlobalMemory.initMqttDeviceMonitor(mqttHostUrl, mqttClientId, mqttUsername, mqttPassword);
// 上位机设备心跳监控
deviceHeartBeatMonitorExecutor.execute(() -> {
deviceThreadService.heartBeatMonitor();
});
// 设备错误监听线程
deviceErrorMonitorExecutor.execute(() -> {
try {

View File

@@ -4,10 +4,13 @@ import java.util.List;
import java.util.Set;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.GlobalMemory;
import com.maibu.mqtt.MqttTopic;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@@ -32,6 +35,9 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
@Autowired
private DeviceSessionManager deviceSessionManager;
@Value("${mqtt.client-id}")
private String mqttClientId;
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
Channel currentChannel = ctx.channel();
@@ -78,11 +84,14 @@ public class CommandForwardHandler extends SimpleChannelInboundHandler<String> {
logger.debug("发送拒绝master:{},消息到达的slave设备:{},处于禁止接收状态", senderDeviceId, target.getConnectorId());
continue;
}
Channel targetChannel = target.getChannel();
if (targetChannel != null && targetChannel.isActive()) {
targetChannel.writeAndFlush(msg);
logger.debug("从master:{},向slave:{}, 转发消息:{}", senderDeviceId, target.getConnectorId(), msg);
}
// todo 向上位机发送控制消息
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.MOWER_CONTROL_SET, target.getConnectorId()), msg);
// Channel targetChannel = target.getChannel();
// if (targetChannel != null && targetChannel.isActive()) {
// targetChannel.writeAndFlush(msg);
// logger.debug("从master:{},向slave:{}, 转发消息:{}", senderDeviceId, target.getConnectorId(), msg);
// }
}
} else if (ConnectorType.SLAVE.equals(senderNettyDevice.getDeviceType())) {
List<NettyDevice> masters = deviceSessionManager.getMastersBySlaveId(senderDeviceId);

View File

@@ -13,10 +13,8 @@ import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceRunParam;
import com.maibu.mapper.DeviceRunParamMapper;
import com.maibu.memory.DeviceSessionManager;
import com.maibu.memory.SiteMemory;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -34,7 +32,7 @@ import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.inter.WebsocketMesDispather;
import com.maibu.core.enums.MesType;
import com.maibu.core.redis.RedisCache;
import com.maibu.dto.WebStatusMessageDTO;
import com.maibu.core.business.dto.WebStatusMessageDTO;
import com.maibu.influxdb.MowerRealTimeData;
import com.maibu.influxdb.util.InfluxSqlBuilder;
import com.maibu.memory.GlobalMemory;
@@ -101,15 +99,8 @@ 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);
try {
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceID),
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceID),
JsonUtils.toJsonString(dto));
// GlobalMemory.mqttClientUtil.publish(
// String.format(MqttTopic.DEVICE_STATUS_TOPIC, deviceID),
// JsonUtils.toJsonString(dto));
} catch (MqttException e) {
logger.error("发送实时状态数据错误: {}", e.getMessage());
}
List<NettyDevice> controlMasters = deviceSessionManager
.getAllSlaveControl(deviceID);
if (!CollectionUtils.isEmpty(controlMasters)) {

View File

@@ -119,6 +119,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
logger.info("{}: 设备断开 status: {}", deviceId, ConnectorStatus.DISABLED);
// updateLogoutSingle(deviceId);
// todo 自动切换到其他?
sessionManager.unLock(deviceId);
}
if (nettyDevice != null && nettyDevice.getDeviceType() == ConnectorType.SLAVE) {
nettyDevice.setOnlineStatus(0);
@@ -159,7 +161,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
protected void channelRead0(ChannelHandlerContext ctx, String msg) {
try {
byte[] bytes = Hex.decodeHex(msg.toCharArray());
@@ -185,133 +187,15 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
logger.info("上位机连接 sessionId: {}", sessionId);
logger.info("上位机连接 userName: {}", userName);
logger.info("上位机连接 type: {}", parts[1]);
SysUser sysUser = userService.selectUserByUserName(userName);
if (sysUser != null) {
sysUserClientService.insertUserClient(sysUser.getUserId(), userName, deviceId, "", 0);
}
// 如果 当前角色存在sessionId同时和当前的穿过来不同则下发剔除指令
boolean t = false;
if (StringUtils.isEmpty(sessionId) || sysUser == null) {
t = true;
}
if (sysUser != null && !StringUtils.isEmpty(sessionId)
&& !StringUtils.isEmpty(sysUser.getSessionId())) {
if (!sysUser.getSessionId().equals(sessionId)) {
t = true;
}
}
if (t) {
// 发送已登录状态到客户端
if ("web".equals(parts[1])) {
NettyDevice device = sessionManager.getDevice(deviceId);
logger.info("web 上位机连接重连: {}", JsonUtils.toJsonString(device));
if (device != null && !StringUtils.isEmpty(device.getCurrentSlaveId())) {
logger.info("上位机连接重连: {}", deviceId);
} else {
// 判断是否账号在控制空 如果在控制设置账号为非active
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();
if (count > 0) {
status = ConnectorStatus.RECEIVER;
}
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)) {
handleMasterConnect(ctx, deviceId, null, status);
} else {
logger.info("web 上位机连接重连4: {}", JsonUtils.toJsonString(nowClient));
if (nowClient != null) {
handleMasterConnect(ctx, deviceId, nowClient.getDeviceName(), status);
} else {
handleMasterConnect(ctx, deviceId, null, status);
}
}
}
} else {
DeviceLoginResponseDTO responseDTO = new DeviceLoginResponseDTO();
responseDTO.setRespond(RespondCode.have_logged_in);
ByteBuf buf = ctx.alloc().buffer();
CommandUtils.buildCommand(buf, responseDTO, CommandConstant.interaction);
ctx.channel().writeAndFlush(buf);
}
NettyDevice masterDevice = sessionManager.getDevice(sessionId);
if (masterDevice == null) {
// sessionManager.getControl(sessionId);
handleMasterConnect(ctx, sessionId, null, ConnectorStatus.ACTIVE);
} else {
// 判断是否账号在控制空 如果在控制设置账号为非active
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();
if (count > 0) {
status = ConnectorStatus.RECEIVER;
}
}
logger.info("上位机上线:{}", status);
// if (ConnectorStatus.ACTIVE.equals(status)) {
// //todo 设置当前控制的token
// sysUser.setSessionId(sessionId);
// userService.updateUserProfile(sysUser);
// }
handleMasterConnect(ctx, deviceId, null, status);
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());
deviceService.insertDeviceBySelf(device);
} else {
device.setStatus(3);
device.setOnlineStatus(DeviceStatus.online.getType());
device.setUpdateTime(LocalDateTime.now());
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) {
@@ -358,7 +242,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
}
public void pushFinishData(NettyDevice device, String deviceId) {
public void pushFinishData(NettyDevice device, String deviceId) throws MqttException {
Long taskId = device.finishTask();
// todo 推送信息给前端
DeviceTaskStatusMessageDTO changeDTO = new DeviceTaskStatusMessageDTO();
@@ -367,16 +251,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
changeDTO.setType(MesType.device_task_change);
changeDTO.setTaskId(taskId);
try {
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_STATUS_TOPIC, taskId),
JsonUtils.toJsonString(changeDTO));
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_TASK_STATUS_TOPIC, taskId),
// JsonUtils.toJsonString(changeDTO));
} catch (MqttException e) {
logger.error("任务完成状态推送失败 task:{},device:{}error:{}", taskId, deviceId, e.getMessage());
}
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_STATUS_TOPIC, taskId),
JsonUtils.toJsonString(changeDTO));
List<NettyDevice> controlMasters = sessionManager
.getAllSlaveControl(deviceId);
if (!CollectionUtils.isEmpty(controlMasters)) {
@@ -390,7 +266,7 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
}
}
public void pushArriveData(NettyDevice device, String deviceId) {
public void pushArriveData(NettyDevice device, String deviceId) throws MqttException {
Long taskId = device.getTask() == null ? null : device.getTask().getId();
// todo 推送信息给前端
DeviceTaskStatusMessageDTO reportDTO = new DeviceTaskStatusMessageDTO();
@@ -398,15 +274,8 @@ public class DeviceConnectHandler extends SimpleChannelInboundHandler<String> {
reportDTO.setTaskId(taskId);
reportDTO.setEntity(device.getCurrentPoint());
reportDTO.setType(MesType.device_task_arrive_point);
try {
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_ARRIVE_TOPIC, taskId),
JsonUtils.toJsonString(reportDTO));
// GlobalMemory.mqttClientUtil.publish(String.format(MqttTopic.DEVICE_TASK_ARRIVE_TOPIC, taskId),
// JsonUtils.toJsonString(reportDTO));
} catch (MqttException e) {
logger.error("任务点位到达推送失败 task:{},device:{}error:{}", taskId, deviceId, e.getMessage());
}
GlobalMemory.customMqttDeviceMonitor.publish(mqttClientId, String.format(MqttTopic.DEVICE_TASK_ARRIVE_TOPIC, taskId),
JsonUtils.toJsonString(reportDTO));
List<NettyDevice> controlMasters = sessionManager
.getAllSlaveControl(deviceId);
@@ -438,17 +307,19 @@ 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);
sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
sessionManager.unLock(c.getConnectorId());
// sysUserClientService.updateAliveStatus(c.getConnectorId(), slaveId, 2);
}
});
}
logger.info("12指令解析,切换权限,slaveId:{},masterId :{}", slaveId, masterId);
sessionManager.lock(slaveId, masterId);
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("权限切换请求被拒绝");
}
@@ -479,69 +350,114 @@ 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)) {
String token = requestDTO.getToken();
String master = sessionManager.getMaster(slaveId);
if (!StringUtils.isEmpty(master)) {
// 如果当前设备有控制
logger.info("转发控制请求 发送报文");
NettyDevice controlDevice = controlList.get(0);
NettyDevice controlDevice = sessionManager.getDevice(master);
if (controlDevice != null && controlDevice.getChannel() != null && controlDevice.getChannel().isActive()) {
controlDevice.getChannel().writeAndFlush(Unpooled.wrappedBuffer(bytes));
logger.info("转发控制请求 发送报文结束 deviceId :{}", controlDevice.getConnectorId());
controlRequestMap.put(masterId, slaveId);
controlRequestMap.put(token, 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 {
NettyDevice masterDevice = sessionManager.getDevice(token);
if (masterDevice != null) {
NettyDevice slaveDevice = sessionManager.getDevice(slaveId);
masterDevice.setCurrentSlaveId(slaveId);
masterDevice.setConnectorStatus(ConnectorStatus.ACTIVE);
masterDevice.addConnectedDevice(slaveDevice);
sessionManager.lock(slaveId, token);
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, token);
}
}
}

View File

@@ -31,6 +31,8 @@ public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);
private static final long DEVICE_REGISTER_TIMEOUT_MS = 10_000; // 10秒注册超时
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// 连接建立后启动定时任务,主动发心跳
@@ -39,6 +41,7 @@ public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
}
private void scheduleHeartbeat(ChannelHandlerContext ctx) {
final long startTime = System.currentTimeMillis();
ctx.executor().scheduleAtFixedRate(() -> {
try {
if (ctx.channel().isActive()) {
@@ -47,6 +50,12 @@ public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
ByteBuf heartbeat = Unpooled.wrappedBuffer(HEARTBEAT_PACKET);
ctx.writeAndFlush(heartbeat);
logger.debug("发送心跳包给客户端:{},deviceId:{}", ctx.channel().remoteAddress(), deviceId);
} else {
long elapsed = System.currentTimeMillis() - startTime;
if (elapsed > DEVICE_REGISTER_TIMEOUT_MS) {
logger.warn("设备超过{}ms未注册,断开连接:{}", DEVICE_REGISTER_TIMEOUT_MS, ctx.channel().remoteAddress());
ctx.close();
}
}
}
} catch (Exception e) {
@@ -55,6 +64,24 @@ public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
}, 0, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
}
// private void scheduleHeartbeat(ChannelHandlerContext ctx) {
// ctx.executor().scheduleAtFixedRate(() -> {
// try {
// if (ctx.channel().isActive()) {
// String deviceId = ctx.channel().attr(Constant.ATT_DEVICE_ID).get();
// if (!StringUtils.isEmpty(deviceId)) {
// ByteBuf heartbeat = Unpooled.wrappedBuffer(HEARTBEAT_PACKET);
// ctx.writeAndFlush(heartbeat);
// logger.debug("发送心跳包给客户端:{},deviceId:{}", ctx.channel().remoteAddress(), deviceId);
// }
// }
// } catch (Exception e) {
// logger.error("heartbeat error", e);
// }
// }, 0, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
// }
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof ByteBuf) {

View File

@@ -19,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.PreDestroy;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -44,13 +45,12 @@ public class DevicePlanTaskMonitorService {
@Autowired
private WorkRecordMapper workRecordMapper;
@Autowired
private ScheduledExecutorService executor;
/**
* 计划迟的任务生成机器执行任务
*/
public void generatePlanTask() throws InterruptedException {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
Map<String, List<DevicePlan>> planMap = SiteMemory.devicePlanMap;
@@ -204,7 +204,6 @@ public class DevicePlanTaskMonitorService {
public void doLoop() throws InterruptedException {
//prepare 进执行execute的逻辑
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
@@ -250,7 +249,6 @@ public class DevicePlanTaskMonitorService {
public void doExecute() {
//prepare 进执行execute的逻辑
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
List<SiteMemory> list = GlobalMemory.getAllSiteMemory();
@@ -270,5 +268,4 @@ public class DevicePlanTaskMonitorService {
}
}, 0, 1000, TimeUnit.MILLISECONDS);
}
}

View File

@@ -11,6 +11,7 @@ import java.util.stream.Collectors;
import com.maibu.memory.DeviceSessionManager;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
@@ -476,7 +477,7 @@ public class DeviceTaskService {
return task.getId();
}
public boolean cancelTask(DeviceTaskCommandDTO dto, String username) {
public boolean cancelTask(DeviceTaskCommandDTO dto) throws MqttException {
String deviceId = dto.getDeviceId();
DevicePlanTask devicePlanTask = null;
if (StringUtils.isEmpty(dto.getDeviceId())) {
@@ -488,7 +489,11 @@ public class DeviceTaskService {
}
NettyDevice device = deviceSessionManager.getDevice(deviceId);
if (device != null && device.getTask() != null) {
return device.cancelTask();
if(dto.isForceCancel()){
return device.canceledTask();
}else {
return device.cancelingTask();
}
} else {
if (devicePlanTask != null) {
devicePlanTask.setTaskStaus(DeviceTaskStaus.CANCELED);

View File

@@ -1,23 +1,30 @@
package com.maibu.service;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
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 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.utils.json.JsonUtils;
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 org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
@@ -25,29 +32,17 @@ import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maibu.common.NettyCacheKey;
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.enums.CompareEnum;
import com.maibu.core.enums.ErrorSource;
import com.maibu.core.enums.RespondCode;
import com.maibu.core.redis.RedisCache;
import com.maibu.dto.DeviceErrorPushDTO;
import com.maibu.mapper.ErrorIdentificationStandardMapper;
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;
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;
@Slf4j
@Service
@@ -71,16 +66,20 @@ public class DeviceThreadService {
@Autowired
private AlertPushService alertPushService;
@Autowired
private IDeviceService deviceService;
@Value("${mqtt.client-id}")
private String mqttClientId;
@Autowired
private ScheduledExecutorService executor;
public void deviceErrorMonitor() throws InterruptedException, IOException {
initStandard();
// TODO fix 后续是否分多个线程 一个site一个线程
// 有还需要更新接受故障方式。
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
String key = NettyCacheKey.deviceRunningStatusKey;
@@ -97,7 +96,7 @@ public class DeviceThreadService {
String[] parts = k.split(":");
String deviceId = parts[1];
NettyDevice slaveDevice = sessionManager.getDevice(deviceId);
if (slaveDevice != null && slaveDevice.isOnline()) {
if (slaveDevice != null && slaveDevice.getOnlineStatus() == 1) {
Long siteId = slaveDevice.getDevice().getSiteId();
Long orgId = slaveDevice.getDevice().getOrgId();
log.debug("compare siteId:{},orgId:{}", siteId, orgId);
@@ -198,7 +197,7 @@ public class DeviceThreadService {
log.info("推送错误信息 device:{},content:{}", deviceId, dto);
});
}
} catch (MqttException e) {
} catch (Exception e) {
log.error("推送错误信息失败 device:{}error:{}", deviceId, e.getMessage());
}
}
@@ -254,4 +253,76 @@ public class DeviceThreadService {
return null;
}
/**
* 监控心跳
*/
public void heartBeatMonitor() {
executor.scheduleWithFixedDelay(() -> {
try {
Long nowTime = System.currentTimeMillis();
List<HeartBeatDTO> heartBeatDTOS = GlobalMemory.customMqttDeviceMonitor.getAllHeartBeat();
if (!CollectionUtils.isEmpty(heartBeatDTOS)) {
heartBeatDTOS.forEach(x -> {
String deviceId = x.getSn();
Long lastActiveTime = x.getSysTimestamp();
NettyDevice nettyDevice = sessionManager.getDevice(x.getSn());
if (nowTime - lastActiveTime >= Constant.hostOfflineInterval) {
//超时了判断离线
if (nettyDevice != null) {
nettyDevice.status(0);
//todo 推送设备离线
}
} else {
if (nettyDevice == null) {
sessionManager.registerSlaveDevice(deviceId, ConnectorStatus.ACTIVE, null);
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());
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);
}
}
});
}
} catch (Exception e) {
log.error("执行监测心跳线程错误:{}", e.getMessage());
}
}, 0, 500, TimeUnit.MILLISECONDS);
}
}

View File

@@ -7,10 +7,12 @@ import com.maibu.core.domain.AjaxResult;
import com.maibu.core.domain.entity.UserClient;
import com.maibu.core.domain.model.LoginUser;
import com.maibu.core.enums.ConnectorStatus;
import com.maibu.exception.ServiceException;
import com.maibu.mapper.DeviceMapper;
import com.maibu.mapper.SysUserClientMapper;
import com.maibu.memory.DeviceSessionManager;
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;
@@ -20,6 +22,7 @@ import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Slf4j
@@ -155,62 +158,111 @@ public class TransferDeviceService {
}
}
public synchronized boolean switchDevice(DeviceBindDTO bindDTO, LoginUser user) {
// public synchronized boolean switchDevice(DeviceBindDTO bindDTO, LoginUser user) {
// try {
// String slaveId = bindDTO.getDeviceId();
// String platform = bindDTO.getPlatform();
// String userName = user.getUsername();
// String masterId = userName + ":" + platform;
// //todo 判断是否有权限 正在控制才能切
// //todo 离线没有控制权的怎么切
// log.info("switchDevice:{}", masterId);
// NettyDevice deviceMaster = sessionManager.getDevice(masterId);
// log.info("deviceMaster:{}", deviceMaster);
// if (deviceMaster != null) {
// log.info("ConnectorStatus:{}", deviceMaster.getConnectorStatus());
// if (ConnectorStatus.RECEIVER.equals(deviceMaster.getConnectorStatus())) {
// //当前账号没有控制则可以切换为控制?
// NettyDevice activeDevice = sessionManager.getUserControl(userName);
// deviceMaster.getConnectedConnectors().clear();
// if (activeDevice == null) {
// log.info("bindConnector ACTIVE :{}", masterId);
// sessionManager.bindConnector(masterId, slaveId);
// deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
// deviceMaster.setCurrentSlaveId(slaveId);
// sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
// } else {
// log.info("bindConnector RECEIVER :{}", masterId);
// sessionManager.bindConnector(masterId, slaveId);
// deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
// deviceMaster.setCurrentSlaveId(slaveId);
// sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
// }
// } else {
// //从关联其他设备切换到 当前禁言 假如有控制且不是当前更新为2
// List<NettyDevice> controls = sessionManager.getSlaveControl(slaveId);
// if (CollectionUtils.isEmpty(controls)) {
// deviceMaster.getConnectedConnectors().clear();
// log.info("bindConnector 1:{}", masterId);
// sessionManager.bindConnector(masterId, slaveId);
// deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
// deviceMaster.setCurrentSlaveId(slaveId);
// sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
// } else {
// NettyDevice controlDevice = controls.get(0);
// if (!masterId.equals(controlDevice.getConnectorId())) {
// //当前的设备有控制 的主机
// deviceMaster.getConnectedConnectors().clear();
// log.info("bindConnector RECEIVER 2:{}", masterId);
// sessionManager.bindConnector(masterId, slaveId);
// deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
// deviceMaster.setCurrentSlaveId(slaveId);
// sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
// }
// //当前 切当前不做操作
// }
// }
// return true;
// }
// } catch (Exception e) {
// log.error("切换设备失败: {}", e.getMessage(), e);
// }
// return false;
// }
public synchronized boolean switchDevice(DeviceBindDTO bindDTO) {
try {
String slaveId = bindDTO.getDeviceId();
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
//todo 判断是否有权限 正在控制才能切
//todo 离线没有控制权的怎么切
log.info("switchDevice:{}", masterId);
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
log.info("deviceMaster:{}", deviceMaster);
if (deviceMaster != null) {
log.info("ConnectorStatus:{}", deviceMaster.getConnectorStatus());
if (ConnectorStatus.RECEIVER.equals(deviceMaster.getConnectorStatus())) {
//当前账号没有控制则可以切换为控制?
NettyDevice activeDevice = sessionManager.getUserControl(userName);
deviceMaster.getConnectedConnectors().clear();
if (activeDevice == null) {
log.info("bindConnector ACTIVE :{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
} else {
log.info("bindConnector RECEIVER :{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
}
} else {
//从关联其他设备切换到 当前禁言 假如有控制且不是当前更新为2
List<NettyDevice> controls = sessionManager.getSlaveControl(slaveId);
if (CollectionUtils.isEmpty(controls)) {
deviceMaster.getConnectedConnectors().clear();
log.info("bindConnector 1:{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 1);
} else {
NettyDevice controlDevice = controls.get(0);
if (!masterId.equals(controlDevice.getConnectorId())) {
//当前的设备有控制 的主机
deviceMaster.getConnectedConnectors().clear();
log.info("bindConnector RECEIVER 2:{}", masterId);
sessionManager.bindConnector(masterId, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
deviceMaster.setCurrentSlaveId(slaveId);
sysUserClientService.updateAliveStatus(masterId, slaveId, 2);
}
//当前 切当前不做操作
}
}
return true;
// String platform = bindDTO.getPlatform();
// String userName = user.getUsername();
// String masterId = userName + ":" + platform;
String token = bindDTO.getToken();
log.info("switchDevice slaveId:{},token:{}", slaveId, token);
NettyDevice deviceMaster = sessionManager.getDevice(token);
log.info("switchDevice deviceMaster:{}", deviceMaster);
if (deviceMaster == null) {
throw new ServiceException("功能码当前账号未发送登录请求,不在线");
}
List<NettyDevice> controls = sessionManager.getAllSlaveControl(slaveId);
if (CollectionUtils.isEmpty(controls)) {
deviceMaster.getConnectedConnectors().clear();
sessionManager.bindConnector(token, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sessionManager.lock(slaveId, token);
log.info("switchDevice bindConnector slaveId:{},token:{}", slaveId, token);
} else {
List<String> connectorIds = controls.stream().map(NettyDevice::getConnectorId).collect(Collectors.toList());
if (!connectorIds.contains(token)) {
//当前的设备有控制 的主机
deviceMaster.getConnectedConnectors().clear();
sessionManager.bindConnector(token, slaveId);
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
deviceMaster.setCurrentSlaveId(slaveId);
log.info("switchDevice bindConnector RECEIVER :{}", token);
} else {
deviceMaster.setConnectorStatus(ConnectorStatus.ACTIVE);
deviceMaster.setCurrentSlaveId(slaveId);
sessionManager.lock(slaveId, token);
}
//当前 切当前不做操作
}
return true;
} catch (Exception e) {
log.error("切换设备失败: {}", e.getMessage(), e);
}
@@ -218,53 +270,18 @@ public class TransferDeviceService {
}
public DeviceControlDTO remoteControl(DeviceBindDTO bindDTO, LoginUser user) {
public DeviceControlDTO remoteControl(DeviceBindDTO bindDTO) {
try {
String slaveId = bindDTO.getDeviceId();
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
String token = bindDTO.getToken();
String masterToken = sessionManager.getMaster(bindDTO.getDeviceId());
DeviceControlDTO dto = new DeviceControlDTO();
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
log.info("remoteControl deviceMaster:{}", masterId);
// //TODO 拓展当前控制不是同一个账号
// NettyDevice currentDevice = sessionManager.getCurrentControl(slaveId);
// if(currentDevice != null){
// if(currentDevice.getConnectorId().equals(masterId)){
// dto.setRemoteControl(true);
// dto.setOwner(platform);
// }else{
// dto.setRemoteControl(false);
// dto.setOwner(currentDevice.getConnectorId());
// }
// }else{
// dto.setRemoteControl(false);
// dto.setOwner(null);
// dto.setReason("occupied");
// }
if (deviceMaster != null) {
if (ConnectorStatus.ACTIVE.equals(deviceMaster.getConnectorStatus())) {
dto.setRemoteControl(true);
dto.setOwner(platform);
} else {
dto.setRemoteControl(false);
dto.setReason("occupied");
NettyDevice activeDevice = sessionManager.getUserControl(userName);
if (activeDevice != null) {
String[] l = activeDevice.getConnectorId().split(":");
dto.setOwner(l[1]);
}
}
if (!StringUtils.isEmpty(token) && token.equals(masterToken)) {
dto.setRemoteControl(true);
dto.setOwner("you");
} else {
dto.setRemoteControl(false);
dto.setReason("not exist");
NettyDevice activeDevice = sessionManager.getUserControl(userName);
if (activeDevice != null) {
String[] l = activeDevice.getConnectorId().split(":");
dto.setOwner(l[1]);
}
dto.setReason("occupied");
dto.setOwner(masterToken);
}
return dto;
} catch (Exception e) {
@@ -327,23 +344,20 @@ public class TransferDeviceService {
}
}
public void releaseControl(DeviceBindDTO bindDTO, LoginUser user) {
public void releaseControl(DeviceBindDTO bindDTO) {
try {
String platform = bindDTO.getPlatform();
String userName = user.getUsername();
String masterId = userName + ":" + platform;
Integer type = bindDTO.getType();
NettyDevice deviceMaster = sessionManager.getDevice(masterId);
if (deviceMaster != null && type!=null) {
if(type == 1){
sysUserClientService.updateAliveStatus(masterId, "", 0);
deviceMaster.setCurrentSlaveId(null);
deviceMaster.getConnectedConnectors().clear();
String masterId = sessionManager.getMaster(bindDTO.getDeviceId());
if (type != null && !StringUtils.isEmpty(masterId)) {
NettyDevice device = sessionManager.getDevice(masterId);
if (type == 1) {
device.setCurrentSlaveId(null);
device.getConnectedConnectors().clear();
} else if (type == 2) {
deviceMaster.setConnectorStatus(ConnectorStatus.RECEIVER);
sysUserClientService.updateAliveStatus(masterId, deviceMaster.getCurrentSlaveId(), 2);
device.setConnectorStatus(ConnectorStatus.RECEIVER);
}
}
sessionManager.unLock(bindDTO.getDeviceId(), bindDTO.getToken(), false);
} catch (Exception e) {
log.error(e.getMessage());
}

View File

@@ -0,0 +1,181 @@
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;
import java.util.Arrays;
import java.util.List;
import java.util.zip.GZIPInputStream;
@Slf4j
@RestController
@RequestMapping("/iot/host")
public class HostComputerController extends BaseController {
private static final int BATCH_SIZE = 5000;
@Autowired
private HostComputerService hostComputerService;
/**
* 上传 csv.gz 轨迹文件并解析为 LatAndLngEntity 列表(分批处理,每批 BATCH_SIZE 条)
*
* <p>CSV 格式:第 1 列=cell_index,第 2 列=x(lat),第 3 列=y(lng)</p>
*
* @param file csv.gz 压缩文件
* @param taskId 任务ID
* @return 解析后的完整轨迹数据
*/
@PostMapping(value = "/upload-path-csv", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R uploadCsv(
@RequestPart("file") MultipartFile file,
@RequestParam("taskId") Long taskId
) {
if (file == null || file.isEmpty()) {
return R.fail("文件不能为空");
}
if (taskId == null) {
return R.fail("taskId 不能为空");
}
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || !originalFilename.toLowerCase().endsWith(".csv.gz")) {
return R.fail("只支持 .csv.gz 格式文件");
}
log.info("收到 csv.gz 文件: taskId={}, fileName={}, size={}", taskId, originalFilename, file.getSize());
List<LatAndLngEntity> allPath = new ArrayList<>();
List<LatAndLngEntity> batch = new ArrayList<>(BATCH_SIZE);
int batchIndex = 0;
try (GZIPInputStream gzipInputStream = new GZIPInputStream(file.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(gzipInputStream))) {
String line;
int lineNum = 0;
while ((line = reader.readLine()) != null) {
lineNum++;
if (line.trim().isEmpty()) {
continue;
}
String[] values = line.split(",");
if (lineNum == 1) {
log.info("CSV 表头: {}", Arrays.toString(values));
continue;
}
if (values.length < 3) {
log.warn("第 {} 行列数不足3列,跳过: {}", lineNum, line);
continue;
}
LatAndLngEntity entity = parseLatLng(values);
if (entity != null) {
batch.add(entity);
}
if (batch.size() >= BATCH_SIZE) {
batchIndex++;
processBatch(taskId, batch, batchIndex);
allPath.addAll(batch);
batch.clear();
log.info("csv 解析进度: taskId={}, 第 {} 批({}条), 累计 {} 条",
taskId, batchIndex, BATCH_SIZE, allPath.size());
}
}
if (!batch.isEmpty()) {
batchIndex++;
processBatch(taskId, batch, batchIndex);
allPath.addAll(batch);
batch.clear();
}
log.info("csv 解析完成: taskId={}, 共 {} 个轨迹点, 分 {} 批处理", taskId, allPath.size(), batchIndex);
GlobalMemory.taskPathMap.put(taskId, allPath);
return R.ok();
} catch (Exception e) {
log.error("csv.gz 解析失败: taskId={}, error={}", taskId, e.getMessage(), e);
return R.fail("文件解析失败: " + e.getMessage());
}
}
/**
* 从 CSV 行解析 LatAndLngEntity
* 第 2 列(x) → lat,第 3 列(y) → lng
*/
private LatAndLngEntity parseLatLng(String[] values) {
try {
String xStr = values[1].trim();
String yStr = values[2].trim();
if (xStr.isEmpty() || yStr.isEmpty()) {
return null;
}
LatAndLngEntity entity = new LatAndLngEntity();
entity.setLat(Double.parseDouble(xStr));
entity.setLng(Double.parseDouble(yStr));
return entity;
} catch (NumberFormatException e) {
log.warn("解析轨迹点失败: values={}, error={}", Arrays.toString(values), e.getMessage());
return null;
}
}
/**
* 分批处理轨迹数据
*
* <p>每批 BATCH_SIZE 条数据触发一次,可用于:</p>
* <ul>
* <li>批量入库(insertBatch)</li>
* <li>发布 MQTT 消息到上位机</li>
* <li>数据校验/统计</li>
* </ul>
*
* @param taskId 任务ID
* @param path 当前批次的轨迹点列表
* @param batchIndex 批次序号(从 1 开始)
*/
protected void processBatch(Long taskId, List<LatAndLngEntity> path, int batchIndex) {
if (path == null || path.isEmpty()) {
return;
}
int size = path.size();
double minLat = Double.MAX_VALUE, maxLat = -Double.MAX_VALUE;
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();
}
log.info("【第 {} 批处理】taskId={}, 本批 {} 条, lat范围=[{}, {}], lng范围=[{}, {}]",
batchIndex, taskId, size,
String.format("%.6f", minLat), String.format("%.6f", maxLat),
String.format("%.6f", minLng), String.format("%.6f", maxLng));
}
}

View File

@@ -3,6 +3,8 @@ package com.maibu.controller;
import java.io.InputStream;
import java.util.List;
import com.maibu.core.domain.AjaxResult;
import com.maibu.memory.GlobalMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
@@ -110,4 +112,9 @@ public class WorkRecordController extends BaseController {
return R.ok(path);
}
@GetMapping("getTaskPath")
public AjaxResult getTaskPath(@RequestParam Long taskId) {
return AjaxResult.success(GlobalMemory.taskPathMap.get(taskId));
}
}

View File

@@ -0,0 +1,18 @@
package com.maibu.service.impl;
import com.maibu.core.business.WorkRecord;
import com.maibu.memory.GlobalMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class HostComputerService {
@Autowired
private WorkRecordService workRecordService;
}

View File

@@ -4,21 +4,20 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.maibu.constant.Constant;
import com.maibu.core.business.DeviceModelPropertyMapping;
import com.maibu.core.business.DevicePlanTask;
import com.maibu.core.business.IoTCommonDevice;
import com.maibu.core.business.Product;
import com.maibu.core.business.device.NettyDevice;
import com.maibu.core.business.dto.DeviceConfigDTO;
import com.maibu.core.enums.ConnectType;
import com.maibu.mapper.IotDeviceCommonMapper;
import com.maibu.mapper.SysDeviceModelPropertyMappingMapper;
import com.maibu.memory.GlobalMemory;
import com.maibu.memory.SiteMemory;
import com.maibu.mqtt.*;
import com.maibu.mqtt.CustomMqttDeviceConfig;
import com.maibu.mqtt.CustomMqttDeviceMonitor;
import com.maibu.mqtt.GenericPropertyMessageHandler;
import com.maibu.mqtt.PropertyMappingConfig;
import com.maibu.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@@ -26,14 +25,13 @@ import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.PreDestroy;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -53,6 +51,9 @@ public class IotDeviceCommonService {
@Autowired
private SysDeviceModelPropertyMappingMapper sysDeviceModelPropertyMappingMapper;
@Autowired
private ScheduledExecutorService executor;
public void save(IoTCommonDevice ioTCommonDevice) throws Exception {
iotDeviceCommonMapper.saveOrUpdate(ioTCommonDevice);
SiteMemory siteMemory = GlobalMemory.getSiteMemory(ioTCommonDevice.getOrgId(), ioTCommonDevice.getSiteId());
@@ -269,8 +270,6 @@ public class IotDeviceCommonService {
public static Map<Long, List<DeviceModelPropertyMapping>> mappingCache = new ConcurrentHashMap<>();
public void commonDeviceMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
try {
CustomMqttDeviceMonitor monitor = GlobalMemory.customMqttDeviceMonitor;

View File

@@ -62,10 +62,11 @@ public class WebMiddlewareController extends BaseController {
List<String> nettyClients = new ArrayList<>();
MiddleGlobalMemory.nettyClientMap.values().forEach(x -> {
if (x != null) {
nettyClients.add(x.userName +":"+ x.token);
nettyClients.add(x.userName + ":" + x.token);
}
});
res.put("nettyClientMap", nettyClients);
res.put("controllerMap", deviceSessionManager.getControllerMap());
res.put("siteMemory", GlobalMemory.getAllSiteMemory());
return AjaxResult.success(res);
}

View File

@@ -23,4 +23,9 @@ public class NettySwitchDeviceDTO {
*/
private String userId;
/**
* 用户名
*/
private String token;
}

View File

@@ -1,11 +1,13 @@
package com.maibu.memory;
import com.maibu.utils.spring.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
@@ -19,6 +21,8 @@ import java.util.concurrent.TimeUnit;
public class SystemMonitor {
private final Logger logger = LoggerFactory.getLogger(SystemMonitor.class);
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
// 启动监控任务
@PostConstruct
public void startMonitoring() {
@@ -37,7 +41,6 @@ public class SystemMonitor {
// 内存监控
private void startMemoryMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
Runtime runtime = Runtime.getRuntime();
long totalMemory = runtime.totalMemory() / (1024 * 1024);
@@ -59,7 +62,6 @@ public class SystemMonitor {
// CPU 监控
private void startCpuMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
try {
// 使用 OperatingSystemMXBean 获取 CPU 使用率
@@ -84,7 +86,6 @@ public class SystemMonitor {
// 线程监控
private void startThreadMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
int threadCount = threadBean.getThreadCount();
@@ -105,7 +106,6 @@ public class SystemMonitor {
// 连接数监控
private void startConnectionMonitor() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
int webSocketCount = MiddleGlobalMemory.onlineSockets.size();
int nettyClientCount = MiddleGlobalMemory.nettyClientMap.size();
@@ -114,4 +114,5 @@ public class SystemMonitor {
webSocketCount, nettyClientCount);
}, 1, 5, TimeUnit.MINUTES);
}
}

View File

@@ -4,8 +4,10 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.maibu.core.business.dto.WebStatusMessageDTO;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;
import org.slf4j.Logger;
@@ -23,7 +25,6 @@ import com.maibu.dto.ResultDTO;
import com.maibu.dto.WebAuthResponseDTO;
import com.maibu.dto.WebDeviceTaskStatusMessageDTO;
import com.maibu.dto.WebOlineStatusMessageDTO;
import com.maibu.dto.WebStatusMessageDTO;
import com.maibu.dto.WebSwitchControlResponseDTO;
import com.maibu.memory.MiddleGlobalMemory;
import com.maibu.netty.NettyClient;
@@ -63,10 +64,10 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
ctx.writeAndFlush(data);
}
NettyClient nettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
if (nettyClient != null && StringUtils.isEmpty(nettyClient.currentDeviceId)) {
if (nettyClient != null) {
if (nettyClient.lastSwitchTime == -1
|| System.currentTimeMillis() - nettyClient.lastSwitchTime > nettyClient.Interval) {
if (!StringUtils.isEmpty(nettyClient.requestDeviceId) && !StringUtils.isEmpty(key)) {
if (!StringUtils.isEmpty(nettyClient.requestDeviceId) && !StringUtils.isEmpty(key) && !Objects.equals(nettyClient.requestDeviceId, nettyClient.currentDeviceId)) {
switchDevice(nettyClient, key);
nettyClient.lastSwitchTime = System.currentTimeMillis();
}
@@ -138,7 +139,7 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
}
} else {
/* 判断 respond 字段 */
if (obj.get("request") != null) {
if (obj.get("request") != null && !"null".equals(obj.get("request").toString())) {
String deviceId = obj.get("deviceId").toString();
String userName = obj.get("userId").toString();
String platform = obj.get("platform").toString();
@@ -151,7 +152,7 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
logger.debug("json: {}", JsonUtils.toJsonString(request));
WebsocketHandler.sendMessageToClient(webSocket, JsonUtils.toJsonString(request));
} else {
if (obj.get("respond") != null) {
if (obj.get("respond") != null && !"null".equals(obj.get("respond").toString())) {
if ("have_logged_in".equals(obj.get("respond").toString())) {
/* 如果回复 have_logged_in 则调用logout */
// System.out.println("检测到重复登录,执行 logout");
@@ -400,6 +401,7 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
NettySwitchDeviceDTO dto = new NettySwitchDeviceDTO();
dto.setDeviceId(nettyClient.requestDeviceId);
dto.setPlatform("web");
dto.setToken(token);
String result = httpService.doPost(postUrl, token, dto);
ResultDTO resultDTO = JsonUtils.parseObject(result, ResultDTO.class);
if (resultDTO != null && resultDTO.getData() != null) {
@@ -459,7 +461,9 @@ public class ClientHandler extends ChannelInboundHandlerAdapter {
String key = ctx.channel().attr(MiddleConstant.ATT_MASTER_KEY).get();
NettyClient nettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
// stopHeartbeat(nettyClient);
nettyClient.currentDeviceId = null;
if (nettyClient != null) {
nettyClient.currentDeviceId = null;
}
logger.debug("连接断开channelInactive,ChannelId:{} ", ctx.channel().id().asLongText());
WebSocket webSocket = MiddleGlobalMemory.onlineSockets.get(key);
if (webSocket != null && webSocket.isOpen()) {

View File

@@ -10,6 +10,7 @@ import com.maibu.netty.NettyClient;
import com.maibu.utils.CommandUtils;
import com.maibu.utils.ControlUtils;
import com.maibu.utils.json.JsonUtils;
import com.maibu.utils.spring.SpringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.commons.lang3.StringUtils;
@@ -41,7 +42,7 @@ public class WebsocketHandler extends WebSocketServer {
// 空闲超时时间(10秒):超过10秒无消息则判定为断开
private static final long IDLE_TIMEOUT = 10 * 1000;
// 定时检测线程池(每隔10秒检测一次空闲连接)
private final ScheduledExecutorService idleCheckExecutor = Executors.newSingleThreadScheduledExecutor();
private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");
public WebsocketHandler(int port) {
@@ -81,24 +82,29 @@ public class WebsocketHandler extends WebSocketServer {
return;
}
//todo 先关闭原先的
WebSocket oldWebsocket = MiddleGlobalMemory.onlineSockets.get(key);
NettyClient oldNettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
if (oldWebsocket != null && oldWebsocket.isOpen()) {
oldWebsocket.close();
}
if (oldNettyClient != null && oldNettyClient.isConnected()) {
oldNettyClient.disconnect();
}
// 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客户端
NettyClient client = new NettyClient();
if (client == null) {
client = new NettyClient();
}
client.key = key;
client.requestDeviceId = deviceId;
client.token = token;
client.userName = userName;
client.initClient();
client.initConnect(MiddleConstant.vertxIp, 9001);
MiddleGlobalMemory.nettyClientMap.put(key, client);
if (!client.isConnected()) {
client.initClient();
client.initConnect(MiddleConstant.vertxIp, 9001);
}
} else if (MesType.path.equals(type)) {
//todo下发路径 预留
pathDistribute();
@@ -126,7 +132,7 @@ public class WebsocketHandler extends WebSocketServer {
// else if(MesType.heartbeat.equals(type)){
// clientActiveTimeMap.put(conn,System.currentTimeMillis());
// }
else if(MesType.switchPermission.equals(type)){
else if (MesType.switchPermission.equals(type)) {
DeviceRequestDTO requestDTO = new DeviceRequestDTO();
requestDTO.setRequest(CommandRequestType.switch_control);
requestDTO.setToken(token);
@@ -136,12 +142,12 @@ public class WebsocketHandler extends WebSocketServer {
logger.debug("Netty客户端:{}发送操控请求数据: {}", userName, JsonUtils.toJsonString(requestDTO));
NettyClient nettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
ByteBuf buf = Unpooled.buffer();
CommandUtils.buildCommand(buf,requestDTO, CommandConstant.interaction);
CommandUtils.buildCommand(buf, requestDTO, CommandConstant.interaction);
if (nettyClient != null && nettyClient.isConnected()) {
// if (!nettyClient.isConnected()) nettyClient.connect();
nettyClient.sendData(buf.array());
}
} else if(MesType.switchResult.equals(type)){
} else if (MesType.switchResult.equals(type)) {
DeviceRequestDTO requestDTO = new DeviceRequestDTO();
requestDTO.setToken(token);
requestDTO.setPlatform("web");
@@ -154,7 +160,7 @@ public class WebsocketHandler extends WebSocketServer {
logger.debug("Netty客户端:{}发送切换操控权请求反馈: {}", userName, JsonUtils.toJsonString(requestDTO));
NettyClient nettyClient = MiddleGlobalMemory.nettyClientMap.get(key);
ByteBuf buf = Unpooled.buffer();
CommandUtils.buildCommand(buf,requestDTO, CommandConstant.interaction);
CommandUtils.buildCommand(buf, requestDTO, CommandConstant.interaction);
if (nettyClient != null && nettyClient.isConnected()) {
// if (!nettyClient.isConnected()) nettyClient.connect();
nettyClient.sendData(buf.array());
@@ -225,7 +231,7 @@ public class WebsocketHandler extends WebSocketServer {
// 核心:定时检测空闲连接(每隔10秒执行一次)
private void startIdleCheckTask() {
idleCheckExecutor.scheduleAtFixedRate(() -> {
executor.scheduleAtFixedRate(() -> {
long now = System.currentTimeMillis();
// 遍历所有连接,检测是否超时
for (Map.Entry<WebSocket, Long> entry : clientActiveTimeMap.entrySet()) {

View File

@@ -13,7 +13,7 @@ public class WebsocketMesHandler implements DeviceWebSocketInterace {
public void sendWebsoketMes(String key, String data) {
MiddleGlobalMemory.onlineSockets.keySet().forEach(x -> {
// key: test:web:token
if (x.startsWith(key)) {
if (x.contains(key)) {
WebSocket webSocket = MiddleGlobalMemory.onlineSockets.get(x);
WebsocketHandler.sendMessageToClient(webSocket, data);
}