Commit 136da4eb50456084f38522275932aff5817d98d7

Authored by YunaiV
1 parent 572a3d10

feat:【iot】COAP 协议:增加 3 个单测

yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapUpstreamProtocol.java
@@ -4,12 +4,15 @@ import cn.iocoder.yudao.module.iot.core.util.IotDeviceMessageUtils; @@ -4,12 +4,15 @@ import cn.iocoder.yudao.module.iot.core.util.IotDeviceMessageUtils;
4 import cn.iocoder.yudao.module.iot.gateway.config.IotGatewayProperties; 4 import cn.iocoder.yudao.module.iot.gateway.config.IotGatewayProperties;
5 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthHandler; 5 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthHandler;
6 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthResource; 6 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthResource;
  7 +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapRegisterHandler;
  8 +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapRegisterResource;
7 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamTopicResource; 9 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamTopicResource;
8 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamHandler; 10 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamHandler;
9 import jakarta.annotation.PostConstruct; 11 import jakarta.annotation.PostConstruct;
10 import jakarta.annotation.PreDestroy; 12 import jakarta.annotation.PreDestroy;
11 import lombok.Getter; 13 import lombok.Getter;
12 import lombok.extern.slf4j.Slf4j; 14 import lombok.extern.slf4j.Slf4j;
  15 +import org.eclipse.californium.core.CoapResource;
13 import org.eclipse.californium.core.CoapServer; 16 import org.eclipse.californium.core.CoapServer;
14 import org.eclipse.californium.core.config.CoapConfig; 17 import org.eclipse.californium.core.config.CoapConfig;
15 import org.eclipse.californium.elements.config.Configuration; 18 import org.eclipse.californium.elements.config.Configuration;
@@ -57,14 +60,20 @@ public class IotCoapUpstreamProtocol { @@ -57,14 +60,20 @@ public class IotCoapUpstreamProtocol {
57 IotCoapAuthHandler authHandler = new IotCoapAuthHandler(); 60 IotCoapAuthHandler authHandler = new IotCoapAuthHandler();
58 IotCoapAuthResource authResource = new IotCoapAuthResource(this, authHandler); 61 IotCoapAuthResource authResource = new IotCoapAuthResource(this, authHandler);
59 coapServer.add(authResource); 62 coapServer.add(authResource);
60 - // 2.2 添加 /topic 根资源(用于上行消息) 63 + // 2.2 添加 /auth/register/device 设备动态注册资源(一型一密)
  64 + IotCoapRegisterHandler registerHandler = new IotCoapRegisterHandler();
  65 + IotCoapRegisterResource registerResource = new IotCoapRegisterResource(registerHandler);
  66 + authResource.add(new CoapResource("register") {{
  67 + add(registerResource);
  68 + }});
  69 + // 2.3 添加 /topic 根资源(用于上行消息)
61 IotCoapUpstreamHandler upstreamHandler = new IotCoapUpstreamHandler(); 70 IotCoapUpstreamHandler upstreamHandler = new IotCoapUpstreamHandler();
62 IotCoapUpstreamTopicResource topicResource = new IotCoapUpstreamTopicResource(this, upstreamHandler); 71 IotCoapUpstreamTopicResource topicResource = new IotCoapUpstreamTopicResource(this, upstreamHandler);
63 coapServer.add(topicResource); 72 coapServer.add(topicResource);
64 73
65 // 3. 启动服务器 74 // 3. 启动服务器
66 coapServer.start(); 75 coapServer.start();
67 - log.info("[start][IoT 网关 CoAP 协议启动成功,端口:{},资源:/auth, /topic]", coapProperties.getPort()); 76 + log.info("[start][IoT 网关 CoAP 协议启动成功,端口:{},资源:/auth, /auth/register/device, /topic]", coapProperties.getPort());
68 } catch (Exception e) { 77 } catch (Exception e) {
69 log.error("[start][IoT 网关 CoAP 协议启动失败]", e); 78 log.error("[start][IoT 网关 CoAP 协议启动失败]", e);
70 throw e; 79 throw e;
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java 0 → 100644
  1 +package cn.iocoder.yudao.module.iot.gateway.protocol.coap.router;
  2 +
  3 +import cn.hutool.core.map.MapUtil;
  4 +import cn.hutool.core.util.StrUtil;
  5 +import cn.hutool.extra.spring.SpringUtil;
  6 +import cn.iocoder.yudao.framework.common.pojo.CommonResult;
  7 +import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  8 +import cn.iocoder.yudao.module.iot.core.biz.IotDeviceCommonApi;
  9 +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterReqDTO;
  10 +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterRespDTO;
  11 +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils;
  12 +import lombok.extern.slf4j.Slf4j;
  13 +import org.eclipse.californium.core.coap.CoAP;
  14 +import org.eclipse.californium.core.server.resources.CoapExchange;
  15 +
  16 +import java.util.Map;
  17 +
  18 +/**
  19 + * IoT 网关 CoAP 协议的【设备动态注册】处理器
  20 + * <p>
  21 + * 用于直连设备/网关的一型一密动态注册,不需要认证
  22 + *
  23 + * @author 芋道源码
  24 + * @see <a href="https://help.aliyun.com/zh/iot/user-guide/unique-certificate-per-product-verification">阿里云 - 一型一密</a>
  25 + * @see cn.iocoder.yudao.module.iot.gateway.protocol.http.router.IotHttpRegisterHandler
  26 + */
  27 +@Slf4j
  28 +public class IotCoapRegisterHandler {
  29 +
  30 + private final IotDeviceCommonApi deviceApi;
  31 +
  32 + public IotCoapRegisterHandler() {
  33 + this.deviceApi = SpringUtil.getBean(IotDeviceCommonApi.class);
  34 + }
  35 +
  36 + /**
  37 + * 处理设备动态注册请求
  38 + *
  39 + * @param exchange CoAP 交换对象
  40 + */
  41 + @SuppressWarnings("unchecked")
  42 + public void handle(CoapExchange exchange) {
  43 + try {
  44 + // 1.1 解析请求体
  45 + byte[] payload = exchange.getRequestPayload();
  46 + if (payload == null || payload.length == 0) {
  47 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "请求体不能为空");
  48 + return;
  49 + }
  50 + Map<String, Object> body;
  51 + try {
  52 + body = JsonUtils.parseObject(new String(payload), Map.class);
  53 + } catch (Exception e) {
  54 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "请求体 JSON 格式错误");
  55 + return;
  56 + }
  57 +
  58 + // 1.2 解析参数
  59 + String productKey = MapUtil.getStr(body, "productKey");
  60 + if (StrUtil.isEmpty(productKey)) {
  61 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "productKey 不能为空");
  62 + return;
  63 + }
  64 + String deviceName = MapUtil.getStr(body, "deviceName");
  65 + if (StrUtil.isEmpty(deviceName)) {
  66 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "deviceName 不能为空");
  67 + return;
  68 + }
  69 + String productSecret = MapUtil.getStr(body, "productSecret");
  70 + if (StrUtil.isEmpty(productSecret)) {
  71 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "productSecret 不能为空");
  72 + return;
  73 + }
  74 +
  75 + // 2. 调用动态注册
  76 + IotDeviceRegisterReqDTO reqDTO = new IotDeviceRegisterReqDTO()
  77 + .setProductKey(productKey)
  78 + .setDeviceName(deviceName)
  79 + .setProductSecret(productSecret);
  80 + CommonResult<IotDeviceRegisterRespDTO> result = deviceApi.registerDevice(reqDTO);
  81 + if (result.isError()) {
  82 + log.warn("[handle][设备动态注册失败,productKey: {}, deviceName: {}, 错误: {}]",
  83 + productKey, deviceName, result.getMsg());
  84 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST,
  85 + "设备动态注册失败:" + result.getMsg());
  86 + return;
  87 + }
  88 +
  89 + // 3. 返回成功响应
  90 + log.info("[handle][设备动态注册成功,productKey: {}, deviceName: {}]", productKey, deviceName);
  91 + IotCoapUtils.respondSuccess(exchange, result.getData());
  92 + } catch (Exception e) {
  93 + log.error("[handle][设备动态注册处理异常]", e);
  94 + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.INTERNAL_SERVER_ERROR, "服务器内部错误");
  95 + }
  96 + }
  97 +
  98 +}
yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java 0 → 100644
  1 +package cn.iocoder.yudao.module.iot.gateway.protocol.coap.router;
  2 +
  3 +import lombok.extern.slf4j.Slf4j;
  4 +import org.eclipse.californium.core.CoapResource;
  5 +import org.eclipse.californium.core.server.resources.CoapExchange;
  6 +
  7 +/**
  8 + * IoT 网关 CoAP 协议的设备动态注册资源(/auth/register/device)
  9 + * <p>
  10 + * 用于直连设备/网关的一型一密动态注册,不需要认证
  11 + *
  12 + * @author 芋道源码
  13 + */
  14 +@Slf4j
  15 +public class IotCoapRegisterResource extends CoapResource {
  16 +
  17 + public static final String PATH = "device";
  18 +
  19 + private final IotCoapRegisterHandler registerHandler;
  20 +
  21 + public IotCoapRegisterResource(IotCoapRegisterHandler registerHandler) {
  22 + super(PATH);
  23 + this.registerHandler = registerHandler;
  24 + log.info("[IotCoapRegisterResource][创建 CoAP 设备动态注册资源: /auth/register/{}]", PATH);
  25 + }
  26 +
  27 + @Override
  28 + public void handlePOST(CoapExchange exchange) {
  29 + log.debug("[handlePOST][收到设备动态注册请求]");
  30 + registerHandler.handle(exchange);
  31 + }
  32 +
  33 +}
yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java renamed to yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java
@@ -3,7 +3,12 @@ package cn.iocoder.yudao.module.iot.gateway.protocol.coap; @@ -3,7 +3,12 @@ package cn.iocoder.yudao.module.iot.gateway.protocol.coap;
3 import cn.hutool.core.map.MapUtil; 3 import cn.hutool.core.map.MapUtil;
4 import cn.hutool.core.util.IdUtil; 4 import cn.hutool.core.util.IdUtil;
5 import cn.iocoder.yudao.framework.common.util.json.JsonUtils; 5 import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  6 +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO;
6 import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; 7 import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum;
  8 +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterReqDTO;
  9 +import cn.iocoder.yudao.module.iot.core.topic.event.IotDeviceEventPostReqDTO;
  10 +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPostReqDTO;
  11 +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils;
7 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; 12 import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils;
8 import lombok.extern.slf4j.Slf4j; 13 import lombok.extern.slf4j.Slf4j;
9 import org.eclipse.californium.core.CoapClient; 14 import org.eclipse.californium.core.CoapClient;
@@ -18,35 +23,40 @@ import org.junit.jupiter.api.BeforeAll; @@ -18,35 +23,40 @@ import org.junit.jupiter.api.BeforeAll;
18 import org.junit.jupiter.api.Test; 23 import org.junit.jupiter.api.Test;
19 24
20 /** 25 /**
21 - * IoT 网关 CoAP 协议集成测试(手动测试) 26 + * IoT 直连设备 CoAP 协议集成测试(手动测试)
  27 + *
  28 + * <p>测试场景:直连设备(IotProductDeviceTypeEnum 的 DIRECT 类型)通过 CoAP 协议直接连接平台
22 * 29 *
23 * <p>使用步骤: 30 * <p>使用步骤:
24 * <ol> 31 * <ol>
25 * <li>启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)</li> 32 * <li>启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)</li>
26 - * <li>运行 {@link #testAuth()} 获取 token,将返回的 token 粘贴到 {@link #TOKEN} 常量</li>  
27 - * <li>运行 {@link #testPropertyPost()} 测试属性上报,或运行 {@link #testEventPost()} 测试事件上报</li> 33 + * <li>运行 {@link #testDeviceRegister()} 测试直连设备动态注册(一型一密)</li>
  34 + * <li>运行 {@link #testAuth()} 获取设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量</li>
  35 + * <li>运行以下测试方法:
  36 + * <ul>
  37 + * <li>{@link #testPropertyPost()} - 设备属性上报</li>
  38 + * <li>{@link #testEventPost()} - 设备事件上报</li>
  39 + * </ul>
  40 + * </li>
28 * </ol> 41 * </ol>
29 * 42 *
30 * @author 芋道源码 43 * @author 芋道源码
31 */ 44 */
32 @Slf4j 45 @Slf4j
33 -public class IotCoapProtocolIntegrationTest { 46 +public class IotDirectDeviceCoapProtocolIntegrationTest {
34 47
35 private static final String SERVER_HOST = "127.0.0.1"; 48 private static final String SERVER_HOST = "127.0.0.1";
36 private static final int SERVER_PORT = 5683; 49 private static final int SERVER_PORT = 5683;
37 50
38 - // 设备信息(根据实际情况修改 PRODUCT_KEY、DEVICE_NAME、PASSWORD) 51 + // ===================== 直连设备信息(根据实际情况修改,从 iot_device 表查询子设备) =====================
39 private static final String PRODUCT_KEY = "4aymZgOTOOCrDKRT"; 52 private static final String PRODUCT_KEY = "4aymZgOTOOCrDKRT";
40 private static final String DEVICE_NAME = "small"; 53 private static final String DEVICE_NAME = "small";
41 - private static final String PASSWORD = "509e2b08f7598eb139d276388c600435913ba4c94cd0d50aebc5c0d1855bcb75";  
42 -  
43 - private static final String CLIENT_ID = PRODUCT_KEY + "." + DEVICE_NAME;  
44 - private static final String USERNAME = DEVICE_NAME + "&" + PRODUCT_KEY; 54 + private static final String DEVICE_SECRET = "0baa4c2ecc104ae1a26b4070c218bdf3";
45 55
46 /** 56 /**
47 - * 设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 57 + * 直连设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里
48 */ 58 */
49 - private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTMwNTA1NSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.mf3MEATCn5bp6cXgULunZjs8d00RGUxj96JEz0hMS7k"; 59 + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTk5MjgxOSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.UHLCXsoGNsKbtJcbTV3n1psp03G75hVcVpV4wwd39r4";
50 60
51 @BeforeAll 61 @BeforeAll
52 public static void initCaliforniumConfig() { 62 public static void initCaliforniumConfig() {
@@ -57,26 +67,30 @@ public class IotCoapProtocolIntegrationTest { @@ -57,26 +67,30 @@ public class IotCoapProtocolIntegrationTest {
57 Configuration.setStandard(Configuration.createStandardWithoutFile()); 67 Configuration.setStandard(Configuration.createStandardWithoutFile());
58 } 68 }
59 69
  70 + // ===================== 认证测试 =====================
  71 +
60 /** 72 /**
61 * 认证测试:获取设备 Token 73 * 认证测试:获取设备 Token
62 */ 74 */
63 @Test 75 @Test
64 - @SuppressWarnings("deprecation")  
65 public void testAuth() throws Exception { 76 public void testAuth() throws Exception {
  77 + // 1.1 构建请求
66 String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT); 78 String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT);
67 - String payload = JsonUtils.toJsonString(MapUtil.builder()  
68 - .put("clientId", CLIENT_ID)  
69 - .put("username", USERNAME)  
70 - .put("password", PASSWORD)  
71 - .build());  
72 - 79 + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET);
  80 + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO()
  81 + .setClientId(authInfo.getClientId())
  82 + .setUsername(authInfo.getUsername())
  83 + .setPassword(authInfo.getPassword());
  84 + String payload = JsonUtils.toJsonString(authReqDTO);
  85 + // 1.2 输出请求
  86 + log.info("[testAuth][请求 URI: {}]", uri);
  87 + log.info("[testAuth][请求体: {}]", payload);
  88 +
  89 + // 2.1 发送请求
73 CoapClient client = new CoapClient(uri); 90 CoapClient client = new CoapClient(uri);
74 try { 91 try {
75 - log.info("[testAuth][请求 URI: {}]", uri);  
76 - log.info("[testAuth][请求体: {}]", payload);  
77 -  
78 CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); 92 CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON);
79 - 93 + // 2.2 输出结果
80 log.info("[testAuth][响应码: {}]", response.getCode()); 94 log.info("[testAuth][响应码: {}]", response.getCode());
81 log.info("[testAuth][响应体: {}]", response.getResponseText()); 95 log.info("[testAuth][响应体: {}]", response.getResponseText());
82 log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); 96 log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]");
@@ -85,24 +99,32 @@ public class IotCoapProtocolIntegrationTest { @@ -85,24 +99,32 @@ public class IotCoapProtocolIntegrationTest {
85 } 99 }
86 } 100 }
87 101
  102 + // ===================== 直连设备属性上报测试 =====================
  103 +
88 /** 104 /**
89 * 属性上报测试 105 * 属性上报测试
90 */ 106 */
91 @Test 107 @Test
92 @SuppressWarnings("deprecation") 108 @SuppressWarnings("deprecation")
93 public void testPropertyPost() throws Exception { 109 public void testPropertyPost() throws Exception {
  110 + // 1.1 构建请求
94 String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post", 111 String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post",
95 SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); 112 SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME);
96 String payload = JsonUtils.toJsonString(MapUtil.builder() 113 String payload = JsonUtils.toJsonString(MapUtil.builder()
97 .put("id", IdUtil.fastSimpleUUID()) 114 .put("id", IdUtil.fastSimpleUUID())
98 .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod()) 115 .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod())
99 .put("version", "1.0") 116 .put("version", "1.0")
100 - .put("params", MapUtil.builder() 117 + .put("params", IotDevicePropertyPostReqDTO.of(MapUtil.<String, Object>builder()
101 .put("width", 1) 118 .put("width", 1)
102 .put("height", "2") 119 .put("height", "2")
103 .build()) 120 .build())
  121 + )
104 .build()); 122 .build());
  123 + // 1.2 输出请求
  124 + log.info("[testPropertyPost][请求 URI: {}]", uri);
  125 + log.info("[testPropertyPost][请求体: {}]", payload);
105 126
  127 + // 2.1 发送请求
106 CoapClient client = new CoapClient(uri); 128 CoapClient client = new CoapClient(uri);
107 try { 129 try {
108 Request request = Request.newPost(); 130 Request request = Request.newPost();
@@ -111,11 +133,8 @@ public class IotCoapProtocolIntegrationTest { @@ -111,11 +133,8 @@ public class IotCoapProtocolIntegrationTest {
111 request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); 133 request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
112 request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); 134 request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN));
113 135
114 - log.info("[testPropertyPost][请求 URI: {}]", uri);  
115 - log.info("[testPropertyPost][请求体: {}]", payload);  
116 -  
117 CoapResponse response = client.advanced(request); 136 CoapResponse response = client.advanced(request);
118 - 137 + // 2.2 输出结果
119 log.info("[testPropertyPost][响应码: {}]", response.getCode()); 138 log.info("[testPropertyPost][响应码: {}]", response.getCode());
120 log.info("[testPropertyPost][响应体: {}]", response.getResponseText()); 139 log.info("[testPropertyPost][响应体: {}]", response.getResponseText());
121 } finally { 140 } finally {
@@ -123,29 +142,32 @@ public class IotCoapProtocolIntegrationTest { @@ -123,29 +142,32 @@ public class IotCoapProtocolIntegrationTest {
123 } 142 }
124 } 143 }
125 144
  145 + // ===================== 直连设备事件上报测试 =====================
  146 +
126 /** 147 /**
127 * 事件上报测试 148 * 事件上报测试
128 */ 149 */
129 @Test 150 @Test
130 @SuppressWarnings("deprecation") 151 @SuppressWarnings("deprecation")
131 public void testEventPost() throws Exception { 152 public void testEventPost() throws Exception {
  153 + // 1.1 构建请求
132 String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post", 154 String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post",
133 SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); 155 SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME);
134 String payload = JsonUtils.toJsonString(MapUtil.builder() 156 String payload = JsonUtils.toJsonString(MapUtil.builder()
135 .put("id", IdUtil.fastSimpleUUID()) 157 .put("id", IdUtil.fastSimpleUUID())
136 .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod()) 158 .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod())
137 .put("version", "1.0") 159 .put("version", "1.0")
138 - .put("params", MapUtil.builder()  
139 - .put("identifier", "eat")  
140 - .put("value", MapUtil.builder()  
141 - .put("width", 1)  
142 - .put("height", "2")  
143 - .put("oneThree", "3")  
144 - .build())  
145 - .put("time", System.currentTimeMillis())  
146 - .build()) 160 + .put("params", IotDeviceEventPostReqDTO.of(
  161 + "eat",
  162 + MapUtil.<String, Object>builder().put("rice", 3).build(),
  163 + System.currentTimeMillis())
  164 + )
147 .build()); 165 .build());
  166 + // 1.2 输出请求
  167 + log.info("[testEventPost][请求 URI: {}]", uri);
  168 + log.info("[testEventPost][请求体: {}]", payload);
148 169
  170 + // 2.1 发送请求
149 CoapClient client = new CoapClient(uri); 171 CoapClient client = new CoapClient(uri);
150 try { 172 try {
151 Request request = Request.newPost(); 173 Request request = Request.newPost();
@@ -154,11 +176,8 @@ public class IotCoapProtocolIntegrationTest { @@ -154,11 +176,8 @@ public class IotCoapProtocolIntegrationTest {
154 request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); 176 request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
155 request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); 177 request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN));
156 178
157 - log.info("[testEventPost][请求 URI: {}]", uri);  
158 - log.info("[testEventPost][请求体: {}]", payload);  
159 -  
160 CoapResponse response = client.advanced(request); 179 CoapResponse response = client.advanced(request);
161 - 180 + // 2.2 输出结果
162 log.info("[testEventPost][响应码: {}]", response.getCode()); 181 log.info("[testEventPost][响应码: {}]", response.getCode());
163 log.info("[testEventPost][响应体: {}]", response.getResponseText()); 182 log.info("[testEventPost][响应体: {}]", response.getResponseText());
164 } finally { 183 } finally {
@@ -166,4 +185,40 @@ public class IotCoapProtocolIntegrationTest { @@ -166,4 +185,40 @@ public class IotCoapProtocolIntegrationTest {
166 } 185 }
167 } 186 }
168 187
  188 + // ===================== 动态注册测试 =====================
  189 +
  190 + /**
  191 + * 直连设备动态注册测试(一型一密)
  192 + * <p>
  193 + * 使用产品密钥(productSecret)验证身份,成功后返回设备密钥(deviceSecret)
  194 + * <p>
  195 + * 注意:此接口不需要 Token 认证
  196 + */
  197 + @Test
  198 + public void testDeviceRegister() throws Exception {
  199 + // 1.1 构建请求
  200 + String uri = String.format("coap://%s:%d/auth/register/device", SERVER_HOST, SERVER_PORT);
  201 + // 1.2 构建请求参数
  202 + IotDeviceRegisterReqDTO reqDTO = new IotDeviceRegisterReqDTO();
  203 + reqDTO.setProductKey(PRODUCT_KEY);
  204 + reqDTO.setDeviceName("test-" + System.currentTimeMillis());
  205 + reqDTO.setProductSecret("test-product-secret");
  206 + String payload = JsonUtils.toJsonString(reqDTO);
  207 + // 1.3 输出请求
  208 + log.info("[testDeviceRegister][请求 URI: {}]", uri);
  209 + log.info("[testDeviceRegister][请求体: {}]", payload);
  210 +
  211 + // 2.1 发送请求
  212 + CoapClient client = new CoapClient(uri);
  213 + try {
  214 + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON);
  215 + // 2.2 输出结果
  216 + log.info("[testDeviceRegister][响应码: {}]", response.getCode());
  217 + log.info("[testDeviceRegister][响应体: {}]", response.getResponseText());
  218 + log.info("[testDeviceRegister][成功后可使用返回的 deviceSecret 进行一机一密认证]");
  219 + } finally {
  220 + client.shutdown();
  221 + }
  222 + }
  223 +
169 } 224 }
yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java 0 → 100644
  1 +package cn.iocoder.yudao.module.iot.gateway.protocol.coap;
  2 +
  3 +import cn.hutool.core.map.MapUtil;
  4 +import cn.hutool.core.util.IdUtil;
  5 +import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  6 +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO;
  7 +import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum;
  8 +import cn.iocoder.yudao.module.iot.core.topic.IotDeviceIdentity;
  9 +import cn.iocoder.yudao.module.iot.core.topic.auth.IotSubDeviceRegisterReqDTO;
  10 +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPackPostReqDTO;
  11 +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoAddReqDTO;
  12 +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoDeleteReqDTO;
  13 +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoGetReqDTO;
  14 +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils;
  15 +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils;
  16 +import lombok.extern.slf4j.Slf4j;
  17 +import org.eclipse.californium.core.CoapClient;
  18 +import org.eclipse.californium.core.CoapResponse;
  19 +import org.eclipse.californium.core.coap.MediaTypeRegistry;
  20 +import org.eclipse.californium.core.coap.Option;
  21 +import org.eclipse.californium.core.coap.Request;
  22 +import org.eclipse.californium.core.config.CoapConfig;
  23 +import org.eclipse.californium.elements.config.Configuration;
  24 +import org.eclipse.californium.elements.config.UdpConfig;
  25 +import org.junit.jupiter.api.BeforeAll;
  26 +import org.junit.jupiter.api.Test;
  27 +
  28 +import java.util.Collections;
  29 +import java.util.List;
  30 +import java.util.Map;
  31 +
  32 +/**
  33 + * IoT 网关设备 CoAP 协议集成测试(手动测试)
  34 + *
  35 + * <p>测试场景:网关设备(IotProductDeviceTypeEnum 的 GATEWAY 类型)通过 CoAP 协议管理子设备拓扑关系
  36 + *
  37 + * <p>使用步骤:
  38 + * <ol>
  39 + * <li>启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)</li>
  40 + * <li>运行 {@link #testAuth()} 获取网关设备 token,将返回的 token 粘贴到 {@link #GATEWAY_TOKEN} 常量</li>
  41 + * <li>运行以下测试方法:
  42 + * <ul>
  43 + * <li>{@link #testTopoAdd()} - 添加子设备拓扑关系</li>
  44 + * <li>{@link #testTopoDelete()} - 删除子设备拓扑关系</li>
  45 + * <li>{@link #testTopoGet()} - 获取子设备拓扑关系</li>
  46 + * <li>{@link #testSubDeviceRegister()} - 子设备动态注册</li>
  47 + * <li>{@link #testPropertyPackPost()} - 批量上报属性(网关 + 子设备)</li>
  48 + * </ul>
  49 + * </li>
  50 + * </ol>
  51 + *
  52 + * @author 芋道源码
  53 + */
  54 +@Slf4j
  55 +public class IotGatewayDeviceCoapProtocolIntegrationTest {
  56 +
  57 + private static final String SERVER_HOST = "127.0.0.1";
  58 + private static final int SERVER_PORT = 5683;
  59 +
  60 + // ===================== 网关设备信息(根据实际情况修改,从 iot_device 表查询网关设备) =====================
  61 + private static final String GATEWAY_PRODUCT_KEY = "m6XcS1ZJ3TW8eC0v";
  62 + private static final String GATEWAY_DEVICE_NAME = "sub-ddd";
  63 + private static final String GATEWAY_DEVICE_SECRET = "b3d62c70f8a4495487ed1d35d61ac2b3";
  64 +
  65 + /**
  66 + * 网关设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里
  67 + */
  68 + private static final String GATEWAY_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoibTZYY1MxWkozVFc4ZUMwdiIsImV4cCI6MTc2OTg2NjY3OCwiZGV2aWNlTmFtZSI6InN1Yi1kZGQifQ.nCLSAfHEjXLtTDRXARjOoFqpuo5WfArjFWweUAzrjKU";
  69 +
  70 + // ===================== 子设备信息(根据实际情况修改,从 iot_device 表查询子设备) =====================
  71 + private static final String SUB_DEVICE_PRODUCT_KEY = "jAufEMTF1W6wnPhn";
  72 + private static final String SUB_DEVICE_NAME = "chazuo-it";
  73 + private static final String SUB_DEVICE_SECRET = "d46ef9b28ab14238b9c00a3a668032af";
  74 +
  75 + @BeforeAll
  76 + public static void initCaliforniumConfig() {
  77 + // 注册 Californium 配置定义
  78 + CoapConfig.register();
  79 + UdpConfig.register();
  80 + // 创建默认配置
  81 + Configuration.setStandard(Configuration.createStandardWithoutFile());
  82 + }
  83 +
  84 + // ===================== 认证测试 =====================
  85 +
  86 + /**
  87 + * 网关设备认证测试:获取网关设备 Token
  88 + */
  89 + @Test
  90 + @SuppressWarnings("deprecation")
  91 + public void testAuth() throws Exception {
  92 + // 1.1 构建请求
  93 + String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT);
  94 + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo(
  95 + GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME, GATEWAY_DEVICE_SECRET);
  96 + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO()
  97 + .setClientId(authInfo.getClientId())
  98 + .setUsername(authInfo.getUsername())
  99 + .setPassword(authInfo.getPassword());
  100 + String payload = JsonUtils.toJsonString(authReqDTO);
  101 + // 1.2 输出请求
  102 + log.info("[testAuth][请求 URI: {}]", uri);
  103 + log.info("[testAuth][请求体: {}]", payload);
  104 +
  105 + // 2.1 发送请求
  106 + CoapClient client = new CoapClient(uri);
  107 + try {
  108 + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON);
  109 + // 2.2 输出结果
  110 + log.info("[testAuth][响应码: {}]", response.getCode());
  111 + log.info("[testAuth][响应体: {}]", response.getResponseText());
  112 + log.info("[testAuth][请将返回的 token 复制到 GATEWAY_TOKEN 常量中]");
  113 + } finally {
  114 + client.shutdown();
  115 + }
  116 + }
  117 +
  118 + // ===================== 拓扑管理测试 =====================
  119 +
  120 + /**
  121 + * 添加子设备拓扑关系测试
  122 + * <p>
  123 + * 网关设备向平台上报需要绑定的子设备信息
  124 + */
  125 + @Test
  126 + @SuppressWarnings("deprecation")
  127 + public void testTopoAdd() throws Exception {
  128 + // 1.1 构建请求
  129 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/add",
  130 + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME);
  131 + // 1.2 构建子设备认证信息
  132 + IotDeviceAuthReqDTO subAuthInfo = IotDeviceAuthUtils.getAuthInfo(
  133 + SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME, SUB_DEVICE_SECRET);
  134 + IotDeviceAuthReqDTO subDeviceAuth = new IotDeviceAuthReqDTO()
  135 + .setClientId(subAuthInfo.getClientId())
  136 + .setUsername(subAuthInfo.getUsername())
  137 + .setPassword(subAuthInfo.getPassword());
  138 + // 1.3 构建请求参数
  139 + IotDeviceTopoAddReqDTO params = new IotDeviceTopoAddReqDTO();
  140 + params.setSubDevices(Collections.singletonList(subDeviceAuth));
  141 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  142 + .put("id", IdUtil.fastSimpleUUID())
  143 + .put("method", IotDeviceMessageMethodEnum.TOPO_ADD.getMethod())
  144 + .put("version", "1.0")
  145 + .put("params", params)
  146 + .build());
  147 + // 1.4 输出请求
  148 + log.info("[testTopoAdd][请求 URI: {}]", uri);
  149 + log.info("[testTopoAdd][请求体: {}]", payload);
  150 +
  151 + // 2.1 发送请求
  152 + CoapClient client = new CoapClient(uri);
  153 + try {
  154 + Request request = Request.newPost();
  155 + request.setURI(uri);
  156 + request.setPayload(payload);
  157 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  158 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN));
  159 +
  160 + CoapResponse response = client.advanced(request);
  161 + // 2.2 输出结果
  162 + log.info("[testTopoAdd][响应码: {}]", response.getCode());
  163 + log.info("[testTopoAdd][响应体: {}]", response.getResponseText());
  164 + } finally {
  165 + client.shutdown();
  166 + }
  167 + }
  168 +
  169 + /**
  170 + * 删除子设备拓扑关系测试
  171 + * <p>
  172 + * 网关设备向平台上报需要解绑的子设备信息
  173 + */
  174 + @Test
  175 + @SuppressWarnings("deprecation")
  176 + public void testTopoDelete() throws Exception {
  177 + // 1.1 构建请求
  178 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/delete",
  179 + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME);
  180 + // 1.2 构建请求参数
  181 + IotDeviceTopoDeleteReqDTO params = new IotDeviceTopoDeleteReqDTO();
  182 + params.setSubDevices(Collections.singletonList(
  183 + new IotDeviceIdentity(SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME)));
  184 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  185 + .put("id", IdUtil.fastSimpleUUID())
  186 + .put("method", IotDeviceMessageMethodEnum.TOPO_DELETE.getMethod())
  187 + .put("version", "1.0")
  188 + .put("params", params)
  189 + .build());
  190 + // 1.3 输出请求
  191 + log.info("[testTopoDelete][请求 URI: {}]", uri);
  192 + log.info("[testTopoDelete][请求体: {}]", payload);
  193 +
  194 + // 2.1 发送请求
  195 + CoapClient client = new CoapClient(uri);
  196 + try {
  197 + Request request = Request.newPost();
  198 + request.setURI(uri);
  199 + request.setPayload(payload);
  200 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  201 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN));
  202 +
  203 + CoapResponse response = client.advanced(request);
  204 + // 2.2 输出结果
  205 + log.info("[testTopoDelete][响应码: {}]", response.getCode());
  206 + log.info("[testTopoDelete][响应体: {}]", response.getResponseText());
  207 + } finally {
  208 + client.shutdown();
  209 + }
  210 + }
  211 +
  212 + /**
  213 + * 获取子设备拓扑关系测试
  214 + * <p>
  215 + * 网关设备向平台查询已绑定的子设备列表
  216 + */
  217 + @Test
  218 + @SuppressWarnings("deprecation")
  219 + public void testTopoGet() throws Exception {
  220 + // 1.1 构建请求
  221 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/get",
  222 + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME);
  223 + // 1.2 构建请求参数(目前为空,预留扩展)
  224 + IotDeviceTopoGetReqDTO params = new IotDeviceTopoGetReqDTO();
  225 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  226 + .put("id", IdUtil.fastSimpleUUID())
  227 + .put("method", IotDeviceMessageMethodEnum.TOPO_GET.getMethod())
  228 + .put("version", "1.0")
  229 + .put("params", params)
  230 + .build());
  231 + // 1.3 输出请求
  232 + log.info("[testTopoGet][请求 URI: {}]", uri);
  233 + log.info("[testTopoGet][请求体: {}]", payload);
  234 +
  235 + // 2.1 发送请求
  236 + CoapClient client = new CoapClient(uri);
  237 + try {
  238 + Request request = Request.newPost();
  239 + request.setURI(uri);
  240 + request.setPayload(payload);
  241 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  242 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN));
  243 +
  244 + CoapResponse response = client.advanced(request);
  245 + // 2.2 输出结果
  246 + log.info("[testTopoGet][响应码: {}]", response.getCode());
  247 + log.info("[testTopoGet][响应体: {}]", response.getResponseText());
  248 + } finally {
  249 + client.shutdown();
  250 + }
  251 + }
  252 +
  253 + // ===================== 子设备注册测试 =====================
  254 +
  255 + /**
  256 + * 子设备动态注册测试
  257 + * <p>
  258 + * 网关设备代理子设备进行动态注册,平台返回子设备的 deviceSecret
  259 + * <p>
  260 + * 注意:此接口需要网关 Token 认证
  261 + */
  262 + @Test
  263 + @SuppressWarnings("deprecation")
  264 + public void testSubDeviceRegister() throws Exception {
  265 + // 1.1 构建请求
  266 + String uri = String.format("coap://%s:%d/auth/register/sub-device/%s/%s",
  267 + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME);
  268 + // 1.2 构建请求参数
  269 + IotSubDeviceRegisterReqDTO subDevice = new IotSubDeviceRegisterReqDTO();
  270 + subDevice.setProductKey(SUB_DEVICE_PRODUCT_KEY);
  271 + subDevice.setDeviceName("mougezishebei");
  272 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  273 + .put("id", IdUtil.fastSimpleUUID())
  274 + .put("method", IotDeviceMessageMethodEnum.SUB_DEVICE_REGISTER.getMethod())
  275 + .put("version", "1.0")
  276 + .put("params", Collections.singletonList(subDevice))
  277 + .build());
  278 + // 1.3 输出请求
  279 + log.info("[testSubDeviceRegister][请求 URI: {}]", uri);
  280 + log.info("[testSubDeviceRegister][请求体: {}]", payload);
  281 +
  282 + // 2.1 发送请求
  283 + CoapClient client = new CoapClient(uri);
  284 + try {
  285 + Request request = Request.newPost();
  286 + request.setURI(uri);
  287 + request.setPayload(payload);
  288 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  289 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN));
  290 +
  291 + CoapResponse response = client.advanced(request);
  292 + // 2.2 输出结果
  293 + log.info("[testSubDeviceRegister][响应码: {}]", response.getCode());
  294 + log.info("[testSubDeviceRegister][响应体: {}]", response.getResponseText());
  295 + } finally {
  296 + client.shutdown();
  297 + }
  298 + }
  299 +
  300 + // ===================== 批量上报测试 =====================
  301 +
  302 + /**
  303 + * 批量上报属性测试(网关 + 子设备)
  304 + * <p>
  305 + * 网关设备批量上报自身属性、事件,以及子设备的属性、事件
  306 + */
  307 + @Test
  308 + @SuppressWarnings("deprecation")
  309 + public void testPropertyPackPost() throws Exception {
  310 + // 1.1 构建请求
  311 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/property/pack/post",
  312 + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME);
  313 + // 1.2 构建【网关设备】自身属性
  314 + Map<String, Object> gatewayProperties = MapUtil.<String, Object>builder()
  315 + .put("temperature", 25.5)
  316 + .build();
  317 + // 1.3 构建【网关设备】自身事件
  318 + IotDevicePropertyPackPostReqDTO.EventValue gatewayEvent = new IotDevicePropertyPackPostReqDTO.EventValue();
  319 + gatewayEvent.setValue(MapUtil.builder().put("message", "gateway started").build());
  320 + gatewayEvent.setTime(System.currentTimeMillis());
  321 + Map<String, IotDevicePropertyPackPostReqDTO.EventValue> gatewayEvents = MapUtil.<String, IotDevicePropertyPackPostReqDTO.EventValue>builder()
  322 + .put("statusReport", gatewayEvent)
  323 + .build();
  324 + // 1.4 构建【网关子设备】属性
  325 + Map<String, Object> subDeviceProperties = MapUtil.<String, Object>builder()
  326 + .put("power", 100)
  327 + .build();
  328 + // 1.5 构建【网关子设备】事件
  329 + IotDevicePropertyPackPostReqDTO.EventValue subDeviceEvent = new IotDevicePropertyPackPostReqDTO.EventValue();
  330 + subDeviceEvent.setValue(MapUtil.builder().put("errorCode", 0).build());
  331 + subDeviceEvent.setTime(System.currentTimeMillis());
  332 + Map<String, IotDevicePropertyPackPostReqDTO.EventValue> subDeviceEvents = MapUtil.<String, IotDevicePropertyPackPostReqDTO.EventValue>builder()
  333 + .put("healthCheck", subDeviceEvent)
  334 + .build();
  335 + // 1.6 构建子设备数据
  336 + IotDevicePropertyPackPostReqDTO.SubDeviceData subDeviceData = new IotDevicePropertyPackPostReqDTO.SubDeviceData();
  337 + subDeviceData.setIdentity(new IotDeviceIdentity(SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME));
  338 + subDeviceData.setProperties(subDeviceProperties);
  339 + subDeviceData.setEvents(subDeviceEvents);
  340 + // 1.7 构建请求参数
  341 + IotDevicePropertyPackPostReqDTO params = new IotDevicePropertyPackPostReqDTO();
  342 + params.setProperties(gatewayProperties);
  343 + params.setEvents(gatewayEvents);
  344 + params.setSubDevices(List.of(subDeviceData));
  345 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  346 + .put("id", IdUtil.fastSimpleUUID())
  347 + .put("method", IotDeviceMessageMethodEnum.PROPERTY_PACK_POST.getMethod())
  348 + .put("version", "1.0")
  349 + .put("params", params)
  350 + .build());
  351 + // 1.8 输出请求
  352 + log.info("[testPropertyPackPost][请求 URI: {}]", uri);
  353 + log.info("[testPropertyPackPost][请求体: {}]", payload);
  354 +
  355 + // 2.1 发送请求
  356 + CoapClient client = new CoapClient(uri);
  357 + try {
  358 + Request request = Request.newPost();
  359 + request.setURI(uri);
  360 + request.setPayload(payload);
  361 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  362 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN));
  363 +
  364 + CoapResponse response = client.advanced(request);
  365 + // 2.2 输出结果
  366 + log.info("[testPropertyPackPost][响应码: {}]", response.getCode());
  367 + log.info("[testPropertyPackPost][响应体: {}]", response.getResponseText());
  368 + } finally {
  369 + client.shutdown();
  370 + }
  371 + }
  372 +
  373 +}
yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java 0 → 100644
  1 +package cn.iocoder.yudao.module.iot.gateway.protocol.coap;
  2 +
  3 +import cn.hutool.core.map.MapUtil;
  4 +import cn.hutool.core.util.IdUtil;
  5 +import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  6 +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO;
  7 +import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum;
  8 +import cn.iocoder.yudao.module.iot.core.topic.event.IotDeviceEventPostReqDTO;
  9 +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPostReqDTO;
  10 +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils;
  11 +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils;
  12 +import lombok.extern.slf4j.Slf4j;
  13 +import org.eclipse.californium.core.CoapClient;
  14 +import org.eclipse.californium.core.CoapResponse;
  15 +import org.eclipse.californium.core.coap.MediaTypeRegistry;
  16 +import org.eclipse.californium.core.coap.Option;
  17 +import org.eclipse.californium.core.coap.Request;
  18 +import org.eclipse.californium.core.config.CoapConfig;
  19 +import org.eclipse.californium.elements.config.Configuration;
  20 +import org.eclipse.californium.elements.config.UdpConfig;
  21 +import org.junit.jupiter.api.BeforeAll;
  22 +import org.junit.jupiter.api.Test;
  23 +
  24 +/**
  25 + * IoT 网关子设备 CoAP 协议集成测试(手动测试)
  26 + *
  27 + * <p>测试场景:子设备(IotProductDeviceTypeEnum 的 SUB 类型)通过网关设备代理上报数据
  28 + *
  29 + * <p><b>重要说明:子设备无法直接连接平台,所有请求均由网关设备(Gateway)代为转发。</b>
  30 + * <p>网关设备转发子设备请求时,Token 使用子设备自己的信息。
  31 + *
  32 + * <p>使用步骤:
  33 + * <ol>
  34 + * <li>启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)</li>
  35 + * <li>确保子设备已通过 {@link IotGatewayDeviceCoapProtocolIntegrationTest#testTopoAdd()} 绑定到网关</li>
  36 + * <li>运行 {@link #testAuth()} 获取子设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量</li>
  37 + * <li>运行以下测试方法:
  38 + * <ul>
  39 + * <li>{@link #testPropertyPost()} - 子设备属性上报(由网关代理转发)</li>
  40 + * <li>{@link #testEventPost()} - 子设备事件上报(由网关代理转发)</li>
  41 + * </ul>
  42 + * </li>
  43 + * </ol>
  44 + *
  45 + * @author 芋道源码
  46 + */
  47 +@Slf4j
  48 +public class IotGatewaySubDeviceCoapProtocolIntegrationTest {
  49 +
  50 + private static final String SERVER_HOST = "127.0.0.1";
  51 + private static final int SERVER_PORT = 5683;
  52 +
  53 + // ===================== 网关子设备信息(根据实际情况修改,从 iot_device 表查询子设备) =====================
  54 + private static final String PRODUCT_KEY = "jAufEMTF1W6wnPhn";
  55 + private static final String DEVICE_NAME = "chazuo-it";
  56 + private static final String DEVICE_SECRET = "d46ef9b28ab14238b9c00a3a668032af";
  57 +
  58 + /**
  59 + * 网关子设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里
  60 + */
  61 + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiakF1ZkVNVEYxVzZ3blBobiIsImV4cCI6MTc2OTk1NDY3OSwiZGV2aWNlTmFtZSI6ImNoYXp1by1pdCJ9.jfbUAoU0xkJl4UvO-NUvcJ6yITPRgUjQ4MKATPuwneg";
  62 +
  63 + @BeforeAll
  64 + public static void initCaliforniumConfig() {
  65 + // 注册 Californium 配置定义
  66 + CoapConfig.register();
  67 + UdpConfig.register();
  68 + // 创建默认配置
  69 + Configuration.setStandard(Configuration.createStandardWithoutFile());
  70 + }
  71 +
  72 + // ===================== 认证测试 =====================
  73 +
  74 + /**
  75 + * 子设备认证测试:获取子设备 Token
  76 + */
  77 + @Test
  78 + @SuppressWarnings("deprecation")
  79 + public void testAuth() throws Exception {
  80 + // 1.1 构建请求
  81 + String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT);
  82 + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET);
  83 + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO()
  84 + .setClientId(authInfo.getClientId())
  85 + .setUsername(authInfo.getUsername())
  86 + .setPassword(authInfo.getPassword());
  87 + String payload = JsonUtils.toJsonString(authReqDTO);
  88 + // 1.2 输出请求
  89 + log.info("[testAuth][请求 URI: {}]", uri);
  90 + log.info("[testAuth][请求体: {}]", payload);
  91 +
  92 + // 2.1 发送请求
  93 + CoapClient client = new CoapClient(uri);
  94 + try {
  95 + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON);
  96 + // 2.2 输出结果
  97 + log.info("[testAuth][响应码: {}]", response.getCode());
  98 + log.info("[testAuth][响应体: {}]", response.getResponseText());
  99 + log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]");
  100 + } finally {
  101 + client.shutdown();
  102 + }
  103 + }
  104 +
  105 + // ===================== 子设备属性上报测试 =====================
  106 +
  107 + /**
  108 + * 子设备属性上报测试
  109 + */
  110 + @Test
  111 + @SuppressWarnings("deprecation")
  112 + public void testPropertyPost() throws Exception {
  113 + // 1.1 构建请求
  114 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post",
  115 + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME);
  116 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  117 + .put("id", IdUtil.fastSimpleUUID())
  118 + .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod())
  119 + .put("version", "1.0")
  120 + .put("params", IotDevicePropertyPostReqDTO.of(MapUtil.<String, Object>builder()
  121 + .put("power", 100)
  122 + .put("status", "online")
  123 + .put("temperature", 36.5)
  124 + .build()))
  125 + .build());
  126 + // 1.2 输出请求
  127 + log.info("[testPropertyPost][子设备属性上报 - 请求实际由 Gateway 代为转发]");
  128 + log.info("[testPropertyPost][请求 URI: {}]", uri);
  129 + log.info("[testPropertyPost][请求体: {}]", payload);
  130 +
  131 + // 2.1 发送请求
  132 + CoapClient client = new CoapClient(uri);
  133 + try {
  134 + Request request = Request.newPost();
  135 + request.setURI(uri);
  136 + request.setPayload(payload);
  137 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  138 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN));
  139 +
  140 + CoapResponse response = client.advanced(request);
  141 + // 2.2 输出结果
  142 + log.info("[testPropertyPost][响应码: {}]", response.getCode());
  143 + log.info("[testPropertyPost][响应体: {}]", response.getResponseText());
  144 + } finally {
  145 + client.shutdown();
  146 + }
  147 + }
  148 +
  149 + // ===================== 子设备事件上报测试 =====================
  150 +
  151 + /**
  152 + * 子设备事件上报测试
  153 + */
  154 + @Test
  155 + @SuppressWarnings("deprecation")
  156 + public void testEventPost() throws Exception {
  157 + // 1.1 构建请求
  158 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post",
  159 + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME);
  160 + String payload = JsonUtils.toJsonString(MapUtil.builder()
  161 + .put("id", IdUtil.fastSimpleUUID())
  162 + .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod())
  163 + .put("version", "1.0")
  164 + .put("params", IotDeviceEventPostReqDTO.of(
  165 + "alarm",
  166 + MapUtil.<String, Object>builder()
  167 + .put("level", "warning")
  168 + .put("message", "temperature too high")
  169 + .put("threshold", 40)
  170 + .put("current", 42)
  171 + .build(),
  172 + System.currentTimeMillis()))
  173 + .build());
  174 + // 1.2 输出请求
  175 + log.info("[testEventPost][子设备事件上报 - 请求实际由 Gateway 代为转发]");
  176 + log.info("[testEventPost][请求 URI: {}]", uri);
  177 + log.info("[testEventPost][请求体: {}]", payload);
  178 +
  179 + // 2.1 发送请求
  180 + CoapClient client = new CoapClient(uri);
  181 + try {
  182 + Request request = Request.newPost();
  183 + request.setURI(uri);
  184 + request.setPayload(payload);
  185 + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON);
  186 + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN));
  187 +
  188 + CoapResponse response = client.advanced(request);
  189 + // 2.2 输出结果
  190 + log.info("[testEventPost][响应码: {}]", response.getCode());
  191 + log.info("[testEventPost][响应体: {}]", response.getResponseText());
  192 + } finally {
  193 + client.shutdown();
  194 + }
  195 + }
  196 +
  197 +}