Commit d1b2fb41ae70a06cc8374a33f6a94d6af8e80617

Authored by YunaiV
1 parent 7b10b595

review:【IoT 物联网】mqtt 协议的 review

yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/config/IotGatewayConfiguration.java
... ... @@ -44,9 +44,6 @@ public class IotGatewayConfiguration {
44 44 @Slf4j
45 45 public static class MqttProtocolConfiguration {
46 46  
47   - /**
48   - * MQTT 统一协议:集成上行协议和HTTP认证协议
49   - */
50 47 @Bean
51 48 public IotMqttUpstreamProtocol iotMqttUnifiedProtocol(IotGatewayProperties gatewayProperties) {
52 49 return new IotMqttUpstreamProtocol(gatewayProperties.getProtocol().getEmqx());
... ...
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotHttpUpstreamProtocol.java
... ... @@ -11,7 +11,7 @@ import io.vertx.ext.web.Router;
11 11 import io.vertx.ext.web.handler.BodyHandler;
12 12 import jakarta.annotation.PostConstruct;
13 13 import jakarta.annotation.PreDestroy;
14   -import lombok.RequiredArgsConstructor;
  14 +import lombok.Getter;
15 15 import lombok.extern.slf4j.Slf4j;
16 16  
17 17 /**
... ... @@ -19,7 +19,6 @@ import lombok.extern.slf4j.Slf4j;
19 19 *
20 20 * @author 芋道源码
21 21 */
22   -@RequiredArgsConstructor
23 22 @Slf4j
24 23 public class IotHttpUpstreamProtocol extends AbstractVerticle {
25 24  
... ... @@ -27,6 +26,14 @@ public class IotHttpUpstreamProtocol extends AbstractVerticle {
27 26  
28 27 private HttpServer httpServer;
29 28  
  29 + @Getter
  30 + private final String serverId;
  31 +
  32 + public IotHttpUpstreamProtocol(IotGatewayProperties.HttpProperties httpProperties) {
  33 + this.httpProperties = httpProperties;
  34 + this.serverId = IotDeviceMessageUtils.generateServerId(httpProperties.getServerPort());
  35 + }
  36 +
30 37 @Override
31 38 @PostConstruct
32 39 public void start() {
... ... @@ -67,8 +74,4 @@ public class IotHttpUpstreamProtocol extends AbstractVerticle {
67 74 }
68 75 }
69 76  
70   - public String getServerId() {
71   - return IotDeviceMessageUtils.generateServerId(httpProperties.getServerPort());
72   - }
73   -
74 77 }
... ...
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/mqtt/IotMqttDownstreamSubscriber.java
... ... @@ -61,6 +61,7 @@ public class IotMqttDownstreamSubscriber implements IotMessageSubscriber<IotDevi
61 61  
62 62 // 过滤上行消息:下行订阅者只处理下行消息
63 63 if (isUpstreamMessage(method)) {
  64 + // TODO @haohao:打个 erroor log,按道理不会发生;
64 65 log.debug("[onMessage][忽略上行消息][method: {}][messageId: {}]", method, message.getId());
65 66 return;
66 67 }
... ... @@ -149,6 +150,7 @@ public class IotMqttDownstreamSubscriber implements IotMessageSubscriber<IotDevi
149 150 return null;
150 151 }
151 152  
  153 + // TODO @haohao:按道理说,这里的应该是通过 encodeMessage;
152 154 /**
153 155 * 构建下行消息载荷
154 156 *
... ...
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/mqtt/IotMqttUpstreamProtocol.java
1 1 package cn.iocoder.yudao.module.iot.gateway.protocol.mqtt;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
4   -import cn.hutool.core.util.ObjUtil;
5 4 import cn.hutool.core.util.StrUtil;
6 5 import cn.iocoder.yudao.module.iot.core.util.IotDeviceMessageUtils;
7 6 import cn.iocoder.yudao.module.iot.gateway.config.IotGatewayProperties;
... ... @@ -18,34 +17,39 @@ import io.vertx.mqtt.MqttClient;
18 17 import io.vertx.mqtt.MqttClientOptions;
19 18 import jakarta.annotation.PostConstruct;
20 19 import jakarta.annotation.PreDestroy;
  20 +import lombok.Getter;
21 21 import lombok.extern.slf4j.Slf4j;
22 22  
23 23 import java.util.List;
24 24 import java.util.concurrent.CompletableFuture;
25 25 import java.util.concurrent.TimeUnit;
26 26  
  27 +// TODO @haohao:看看有没多余的 log,可以不打噢。
  28 +// TODO @haohao:有没多余的注释可以去掉,减少 ai 味,保持简洁;
27 29 /**
28 30 * IoT 网关 MQTT 统一协议
29 31 * <p>
30   - * 集成了 MQTT 上行协议和 HTTP 认证协议的功能:
31   - * 1. MQTT 客户端:连接 EMQX,处理设备上行和下行消息
32   - * 2. HTTP 认证服务:为 EMQX 提供设备认证接口
  32 + * 1. MQTT 客户端:连接 EMQX,消费处理设备上行和下行消息
  33 + * 2. HTTP 认证服务:为 EMQX 提供设备认证、连接、断开接口
33 34 *
34 35 * @author 芋道源码
35 36 */
36 37 @Slf4j
37 38 public class IotMqttUpstreamProtocol {
38 39  
  40 + // TODO @haohao:是不是也丢到配置里?
39 41 /**
40 42 * 默认 QoS 级别 - 至少一次
41 43 */
42 44 private static final MqttQoS DEFAULT_QOS = MqttQoS.AT_LEAST_ONCE;
43 45  
  46 + // TODO @haohao:这个也是;
44 47 /**
45 48 * 连接超时时间(秒)
46 49 */
47 50 private static final int CONNECT_TIMEOUT_SECONDS = 10;
48 51  
  52 + // TODO @haohao:重连也是;
49 53 /**
50 54 * 重连延迟时间(毫秒)
51 55 */
... ... @@ -53,15 +57,18 @@ public class IotMqttUpstreamProtocol {
53 57  
54 58 private final IotGatewayProperties.EmqxProperties emqxProperties;
55 59  
56   - // 共享资源
57 60 private Vertx vertx;
58 61  
  62 + @Getter
  63 + private final String serverId;
  64 +
59 65 // MQTT 客户端相关
60 66 private MqttClient mqttClient;
61 67 private IotMqttUpstreamHandler upstreamHandler;
62 68  
63 69 // HTTP 认证服务相关
64 70 private HttpServer httpAuthServer;
  71 + // TODO @haohao:authHandler 可以 local 哈;
65 72 private IotMqttHttpAuthHandler authHandler;
66 73  
67 74 /**
... ... @@ -69,11 +76,9 @@ public class IotMqttUpstreamProtocol {
69 76 */
70 77 private volatile boolean isRunning = false;
71 78  
72   - /**
73   - * 构造函数
74   - */
75 79 public IotMqttUpstreamProtocol(IotGatewayProperties.EmqxProperties emqxProperties) {
76 80 this.emqxProperties = emqxProperties;
  81 + this.serverId = IotDeviceMessageUtils.generateServerId(emqxProperties.getMqttPort());
77 82 }
78 83  
79 84 @PostConstruct
... ... @@ -98,6 +103,7 @@ public class IotMqttUpstreamProtocol {
98 103 isRunning = true;
99 104 log.info("[start][MQTT 统一协议服务启动完成]");
100 105 } catch (Exception e) {
  106 + // TODO @haohao:失败,是不是直接 System.exit 哈!
101 107 log.error("[start][MQTT 统一协议服务启动失败]", e);
102 108 // 启动失败时清理资源
103 109 stop();
... ... @@ -169,6 +175,7 @@ public class IotMqttUpstreamProtocol {
169 175 * 停止 HTTP 认证服务
170 176 */
171 177 private void stopHttpAuthServer() {
  178 + // TODO @haohao:一些 if return 最好搞下;
172 179 if (httpAuthServer != null) {
173 180 try {
174 181 httpAuthServer.close().result();
... ... @@ -195,8 +202,7 @@ public class IotMqttUpstreamProtocol {
195 202 .setClientId(emqxProperties.getMqttClientId())
196 203 .setUsername(emqxProperties.getMqttUsername())
197 204 .setPassword(emqxProperties.getMqttPassword())
198   - .setSsl(ObjUtil.defaultIfNull(emqxProperties.getMqttSsl(), false));
199   -
  205 + .setSsl(emqxProperties.getMqttSsl());
200 206 this.mqttClient = MqttClient.create(vertx, options);
201 207  
202 208 // 连接 MQTT Broker
... ... @@ -256,6 +262,7 @@ public class IotMqttUpstreamProtocol {
256 262 .toCompletionStage()
257 263 .toCompletableFuture()
258 264 .thenAccept(connAck -> {
  265 + // TODO @haohao:是不是可以连接完,然后在执行里面;不用 通过 thenAccept 哈;
259 266 log.info("[connectMqtt][MQTT 客户端连接成功][host: {}][port: {}]", host, port);
260 267 // 设置断开重连监听器
261 268 mqttClient.closeHandler(closeEvent -> {
... ... @@ -268,6 +275,7 @@ public class IotMqttUpstreamProtocol {
268 275 subscribeToTopics();
269 276 })
270 277 .exceptionally(error -> {
  278 + // TODO @haohao:这里的异常,是不是不用重连哈?因为直接就退出了。然后有 closeHandler 监听重连了;
271 279 log.error("[connectMqtt][连接 MQTT Broker 失败][host: {}][port: {}]", host, port, error);
272 280 // 连接失败时也要尝试重连
273 281 reconnectWithDelay();
... ... @@ -297,16 +305,10 @@ public class IotMqttUpstreamProtocol {
297 305 */
298 306 private void subscribeToTopics() {
299 307 List<String> topicList = emqxProperties.getMqttTopics();
300   - // @NotEmpty 注解已保证 topicList 不为空,无需重复校验
301 308  
302 309 log.info("[subscribeToTopics][开始订阅主题,共 {} 个]", topicList.size());
303 310  
304 311 for (String topic : topicList) {
305   - if (StrUtil.isBlank(topic)) {
306   - log.warn("[subscribeToTopics][跳过空主题]");
307   - continue;
308   - }
309   -
310 312 mqttClient.subscribe(topic, DEFAULT_QOS.value(), subscribeResult -> {
311 313 if (subscribeResult.succeeded()) {
312 314 log.info("[subscribeToTopics][订阅主题成功: {}][QoS: {}]", topic, DEFAULT_QOS.value());
... ... @@ -322,6 +324,7 @@ public class IotMqttUpstreamProtocol {
322 324 */
323 325 private void reconnectWithDelay() {
324 326 vertx.setTimer(RECONNECT_DELAY_MS, timerId -> {
  327 + // TODO @haohao:if return,括号少一些;
325 328 if (isRunning && (mqttClient == null || !mqttClient.isConnected())) {
326 329 log.info("[reconnectWithDelay][开始重连 MQTT Broker,延迟 {} 毫秒]", RECONNECT_DELAY_MS);
327 330 try {
... ... @@ -350,11 +353,4 @@ public class IotMqttUpstreamProtocol {
350 353 }
351 354 }
352 355  
353   - /**
354   - * 获取服务器 ID
355   - */
356   - public String getServerId() {
357   - return IotDeviceMessageUtils.generateServerId(emqxProperties.getMqttPort());
358   - }
359   -
360 356 }
361 357 \ No newline at end of file
... ...
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/mqtt/router/IotMqttAbstractHandler.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.iot.gateway.protocol.mqtt.router;
3 3 import cn.hutool.core.util.StrUtil;
4 4 import lombok.extern.slf4j.Slf4j;
5 5  
  6 +// TODO @haohao:是不是不用基类哈;
6 7 /**
7 8 * IoT 网关 MQTT 协议的处理器抽象基类
8 9 * <p>
... ...
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/mqtt/router/IotMqttUpstreamHandler.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.iot.gateway.protocol.mqtt.router;
3 3 import cn.hutool.extra.spring.SpringUtil;
4 4 import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage;
5 5 import cn.iocoder.yudao.module.iot.gateway.enums.IotDeviceTopicEnum;
  6 +import cn.iocoder.yudao.module.iot.gateway.protocol.mqtt.IotMqttUpstreamProtocol;
6 7 import cn.iocoder.yudao.module.iot.gateway.service.device.message.IotDeviceMessageService;
7 8 import io.vertx.mqtt.messages.MqttPublishMessage;
8 9 import lombok.extern.slf4j.Slf4j;
... ... @@ -20,9 +21,10 @@ import java.nio.charset.StandardCharsets;
20 21 public class IotMqttUpstreamHandler extends IotMqttAbstractHandler {
21 22  
22 23 private final IotDeviceMessageService deviceMessageService;
  24 +
23 25 private final String serverId;
24 26  
25   - public IotMqttUpstreamHandler(cn.iocoder.yudao.module.iot.gateway.protocol.mqtt.IotMqttUpstreamProtocol protocol) {
  27 + public IotMqttUpstreamHandler(IotMqttUpstreamProtocol protocol) {
26 28 this.deviceMessageService = SpringUtil.getBean(IotDeviceMessageService.class);
27 29 this.serverId = protocol.getServerId();
28 30 }
... ... @@ -32,6 +34,7 @@ public class IotMqttUpstreamHandler extends IotMqttAbstractHandler {
32 34 */
33 35 public void handle(MqttPublishMessage message) {
34 36 String topic = message.topicName();
  37 + // TODO @haohao: message.payload().getBytes();
35 38 String payload = message.payload().toString(StandardCharsets.UTF_8);
36 39  
37 40 log.debug("[handle][收到 MQTT 消息][topic: {}]", topic);
... ... @@ -44,6 +47,7 @@ public class IotMqttUpstreamHandler extends IotMqttAbstractHandler {
44 47 // 1. 识别并验证消息类型
45 48 String messageType = getMessageType(topic);
46 49 if (messageType == null) {
  50 + // TODO @haohao:log 是不是把 payload 也打印下哈
47 51 log.warn("[doHandle][未知的消息类型][topic: {}]", topic);
48 52 return;
49 53 }
... ... @@ -56,9 +60,11 @@ public class IotMqttUpstreamHandler extends IotMqttAbstractHandler {
56 60 * 处理消息的统一逻辑
57 61 */
58 62 private void processMessage(String topic, String payload, String messageType) {
  63 + // TODO @haohao:messageType 解析,是不是作用不大哈?
59 64 log.info("[processMessage][接收到{}][topic: {}]", messageType, topic);
60 65  
61 66 // 解析主题获取设备信息
  67 + // TODO @haohao:不一定是 7 个哈;阿里云 topic 有点差异的;可以考虑解析到 topicParts[2]、topicParts[3] 的 topic
62 68 String[] topicParts = parseTopic(topic);
63 69 if (topicParts == null) {
64 70 return;
... ... @@ -66,19 +72,21 @@ public class IotMqttUpstreamHandler extends IotMqttAbstractHandler {
66 72  
67 73 String productKey = topicParts[2];
68 74 String deviceName = topicParts[3];
  75 + // TODO @haohao:解析不到,可以打个 error log;
69 76  
70 77 // 解码消息
71 78 byte[] messageBytes = payload.getBytes(StandardCharsets.UTF_8);
72 79 IotDeviceMessage message = deviceMessageService.decodeDeviceMessage(
73 80 messageBytes, productKey, deviceName);
74 81  
75   - // 发送消息到队列(需要补充设备信息)
  82 + // 发送消息到队列
76 83 deviceMessageService.sendDeviceMessage(message, productKey, deviceName, serverId);
77 84  
78 85 // 记录成功日志
79 86 log.info("[processMessage][处理{}成功][topic: {}]", messageType, topic);
80 87 }
81 88  
  89 + // TODO @haohao:合并下处理;不搞成每个 topic 一个处理;
82 90 /**
83 91 * 识别消息类型
84 92 *
... ...