From 136da4eb50456084f38522275932aff5817d98d7 Mon Sep 17 00:00:00 2001 From: YunaiV Date: Mon, 26 Jan 2026 12:44:03 +0800 Subject: [PATCH] feat:【iot】COAP 协议:增加 3 个单测 --- yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapUpstreamProtocol.java | 13 +++++++++++-- yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java | 33 +++++++++++++++++++++++++++++++++ yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java | 169 ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java | 224 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java | 373 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java | 197 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 936 insertions(+), 171 deletions(-) create mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java create mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java delete mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java create mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java create mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java create mode 100644 yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapUpstreamProtocol.java b/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapUpstreamProtocol.java index 42f4c8e..e259aa6 100644 --- a/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapUpstreamProtocol.java +++ b/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; import cn.iocoder.yudao.module.iot.gateway.config.IotGatewayProperties; import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthHandler; import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapAuthResource; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapRegisterHandler; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapRegisterResource; import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamTopicResource; import cn.iocoder.yudao.module.iot.gateway.protocol.coap.router.IotCoapUpstreamHandler; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.CoapResource; import org.eclipse.californium.core.CoapServer; import org.eclipse.californium.core.config.CoapConfig; import org.eclipse.californium.elements.config.Configuration; @@ -57,14 +60,20 @@ public class IotCoapUpstreamProtocol { IotCoapAuthHandler authHandler = new IotCoapAuthHandler(); IotCoapAuthResource authResource = new IotCoapAuthResource(this, authHandler); coapServer.add(authResource); - // 2.2 添加 /topic 根资源(用于上行消息) + // 2.2 添加 /auth/register/device 设备动态注册资源(一型一密) + IotCoapRegisterHandler registerHandler = new IotCoapRegisterHandler(); + IotCoapRegisterResource registerResource = new IotCoapRegisterResource(registerHandler); + authResource.add(new CoapResource("register") {{ + add(registerResource); + }}); + // 2.3 添加 /topic 根资源(用于上行消息) IotCoapUpstreamHandler upstreamHandler = new IotCoapUpstreamHandler(); IotCoapUpstreamTopicResource topicResource = new IotCoapUpstreamTopicResource(this, upstreamHandler); coapServer.add(topicResource); // 3. 启动服务器 coapServer.start(); - log.info("[start][IoT 网关 CoAP 协议启动成功,端口:{},资源:/auth, /topic]", coapProperties.getPort()); + log.info("[start][IoT 网关 CoAP 协议启动成功,端口:{},资源:/auth, /auth/register/device, /topic]", coapProperties.getPort()); } catch (Exception e) { log.error("[start][IoT 网关 CoAP 协议启动失败]", e); throw e; diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java b/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java new file mode 100644 index 0000000..8ffbe4f --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterHandler.java @@ -0,0 +1,98 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.coap.router; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.extra.spring.SpringUtil; +import cn.iocoder.yudao.framework.common.pojo.CommonResult; +import cn.iocoder.yudao.framework.common.util.json.JsonUtils; +import cn.iocoder.yudao.module.iot.core.biz.IotDeviceCommonApi; +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterRespDTO; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.coap.CoAP; +import org.eclipse.californium.core.server.resources.CoapExchange; + +import java.util.Map; + +/** + * IoT 网关 CoAP 协议的【设备动态注册】处理器 + *

+ * 用于直连设备/网关的一型一密动态注册,不需要认证 + * + * @author 芋道源码 + * @see 阿里云 - 一型一密 + * @see cn.iocoder.yudao.module.iot.gateway.protocol.http.router.IotHttpRegisterHandler + */ +@Slf4j +public class IotCoapRegisterHandler { + + private final IotDeviceCommonApi deviceApi; + + public IotCoapRegisterHandler() { + this.deviceApi = SpringUtil.getBean(IotDeviceCommonApi.class); + } + + /** + * 处理设备动态注册请求 + * + * @param exchange CoAP 交换对象 + */ + @SuppressWarnings("unchecked") + public void handle(CoapExchange exchange) { + try { + // 1.1 解析请求体 + byte[] payload = exchange.getRequestPayload(); + if (payload == null || payload.length == 0) { + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "请求体不能为空"); + return; + } + Map body; + try { + body = JsonUtils.parseObject(new String(payload), Map.class); + } catch (Exception e) { + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "请求体 JSON 格式错误"); + return; + } + + // 1.2 解析参数 + String productKey = MapUtil.getStr(body, "productKey"); + if (StrUtil.isEmpty(productKey)) { + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "productKey 不能为空"); + return; + } + String deviceName = MapUtil.getStr(body, "deviceName"); + if (StrUtil.isEmpty(deviceName)) { + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "deviceName 不能为空"); + return; + } + String productSecret = MapUtil.getStr(body, "productSecret"); + if (StrUtil.isEmpty(productSecret)) { + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, "productSecret 不能为空"); + return; + } + + // 2. 调用动态注册 + IotDeviceRegisterReqDTO reqDTO = new IotDeviceRegisterReqDTO() + .setProductKey(productKey) + .setDeviceName(deviceName) + .setProductSecret(productSecret); + CommonResult result = deviceApi.registerDevice(reqDTO); + if (result.isError()) { + log.warn("[handle][设备动态注册失败,productKey: {}, deviceName: {}, 错误: {}]", + productKey, deviceName, result.getMsg()); + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.BAD_REQUEST, + "设备动态注册失败:" + result.getMsg()); + return; + } + + // 3. 返回成功响应 + log.info("[handle][设备动态注册成功,productKey: {}, deviceName: {}]", productKey, deviceName); + IotCoapUtils.respondSuccess(exchange, result.getData()); + } catch (Exception e) { + log.error("[handle][设备动态注册处理异常]", e); + IotCoapUtils.respondError(exchange, CoAP.ResponseCode.INTERNAL_SERVER_ERROR, "服务器内部错误"); + } + } + +} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java b/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java new file mode 100644 index 0000000..05fd1ec --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/main/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/router/IotCoapRegisterResource.java @@ -0,0 +1,33 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.coap.router; + +import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.CoapResource; +import org.eclipse.californium.core.server.resources.CoapExchange; + +/** + * IoT 网关 CoAP 协议的设备动态注册资源(/auth/register/device) + *

+ * 用于直连设备/网关的一型一密动态注册,不需要认证 + * + * @author 芋道源码 + */ +@Slf4j +public class IotCoapRegisterResource extends CoapResource { + + public static final String PATH = "device"; + + private final IotCoapRegisterHandler registerHandler; + + public IotCoapRegisterResource(IotCoapRegisterHandler registerHandler) { + super(PATH); + this.registerHandler = registerHandler; + log.info("[IotCoapRegisterResource][创建 CoAP 设备动态注册资源: /auth/register/{}]", PATH); + } + + @Override + public void handlePOST(CoapExchange exchange) { + log.debug("[handlePOST][收到设备动态注册请求]"); + registerHandler.handle(exchange); + } + +} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java deleted file mode 100644 index 5856ced..0000000 --- a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotCoapProtocolIntegrationTest.java +++ /dev/null @@ -1,169 +0,0 @@ -package cn.iocoder.yudao.module.iot.gateway.protocol.coap; - -import cn.hutool.core.map.MapUtil; -import cn.hutool.core.util.IdUtil; -import cn.iocoder.yudao.framework.common.util.json.JsonUtils; -import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; -import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; -import lombok.extern.slf4j.Slf4j; -import org.eclipse.californium.core.CoapClient; -import org.eclipse.californium.core.CoapResponse; -import org.eclipse.californium.core.coap.MediaTypeRegistry; -import org.eclipse.californium.core.coap.Option; -import org.eclipse.californium.core.coap.Request; -import org.eclipse.californium.core.config.CoapConfig; -import org.eclipse.californium.elements.config.Configuration; -import org.eclipse.californium.elements.config.UdpConfig; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -/** - * IoT 网关 CoAP 协议集成测试(手动测试) - * - *

使用步骤: - *

    - *
  1. 启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)
  2. - *
  3. 运行 {@link #testAuth()} 获取 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  4. - *
  5. 运行 {@link #testPropertyPost()} 测试属性上报,或运行 {@link #testEventPost()} 测试事件上报
  6. - *
- * - * @author 芋道源码 - */ -@Slf4j -public class IotCoapProtocolIntegrationTest { - - private static final String SERVER_HOST = "127.0.0.1"; - private static final int SERVER_PORT = 5683; - - // 设备信息(根据实际情况修改 PRODUCT_KEY、DEVICE_NAME、PASSWORD) - private static final String PRODUCT_KEY = "4aymZgOTOOCrDKRT"; - private static final String DEVICE_NAME = "small"; - private static final String PASSWORD = "509e2b08f7598eb139d276388c600435913ba4c94cd0d50aebc5c0d1855bcb75"; - - private static final String CLIENT_ID = PRODUCT_KEY + "." + DEVICE_NAME; - private static final String USERNAME = DEVICE_NAME + "&" + PRODUCT_KEY; - - /** - * 设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 - */ - private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTMwNTA1NSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.mf3MEATCn5bp6cXgULunZjs8d00RGUxj96JEz0hMS7k"; - - @BeforeAll - public static void initCaliforniumConfig() { - // 注册 Californium 配置定义 - CoapConfig.register(); - UdpConfig.register(); - // 创建默认配置 - Configuration.setStandard(Configuration.createStandardWithoutFile()); - } - - /** - * 认证测试:获取设备 Token - */ - @Test - @SuppressWarnings("deprecation") - public void testAuth() throws Exception { - String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT); - String payload = JsonUtils.toJsonString(MapUtil.builder() - .put("clientId", CLIENT_ID) - .put("username", USERNAME) - .put("password", PASSWORD) - .build()); - - CoapClient client = new CoapClient(uri); - try { - log.info("[testAuth][请求 URI: {}]", uri); - log.info("[testAuth][请求体: {}]", payload); - - CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); - - log.info("[testAuth][响应码: {}]", response.getCode()); - log.info("[testAuth][响应体: {}]", response.getResponseText()); - log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); - } finally { - client.shutdown(); - } - } - - /** - * 属性上报测试 - */ - @Test - @SuppressWarnings("deprecation") - public void testPropertyPost() throws Exception { - String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post", - SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); - String payload = JsonUtils.toJsonString(MapUtil.builder() - .put("id", IdUtil.fastSimpleUUID()) - .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod()) - .put("version", "1.0") - .put("params", MapUtil.builder() - .put("width", 1) - .put("height", "2") - .build()) - .build()); - - CoapClient client = new CoapClient(uri); - try { - Request request = Request.newPost(); - request.setURI(uri); - request.setPayload(payload); - request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); - request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); - - log.info("[testPropertyPost][请求 URI: {}]", uri); - log.info("[testPropertyPost][请求体: {}]", payload); - - CoapResponse response = client.advanced(request); - - log.info("[testPropertyPost][响应码: {}]", response.getCode()); - log.info("[testPropertyPost][响应体: {}]", response.getResponseText()); - } finally { - client.shutdown(); - } - } - - /** - * 事件上报测试 - */ - @Test - @SuppressWarnings("deprecation") - public void testEventPost() throws Exception { - String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post", - SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); - String payload = JsonUtils.toJsonString(MapUtil.builder() - .put("id", IdUtil.fastSimpleUUID()) - .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod()) - .put("version", "1.0") - .put("params", MapUtil.builder() - .put("identifier", "eat") - .put("value", MapUtil.builder() - .put("width", 1) - .put("height", "2") - .put("oneThree", "3") - .build()) - .put("time", System.currentTimeMillis()) - .build()) - .build()); - - CoapClient client = new CoapClient(uri); - try { - Request request = Request.newPost(); - request.setURI(uri); - request.setPayload(payload); - request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); - request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); - - log.info("[testEventPost][请求 URI: {}]", uri); - log.info("[testEventPost][请求体: {}]", payload); - - CoapResponse response = client.advanced(request); - - log.info("[testEventPost][响应码: {}]", response.getCode()); - log.info("[testEventPost][响应体: {}]", response.getResponseText()); - } finally { - client.shutdown(); - } - } - -} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java new file mode 100644 index 0000000..b8f9126 --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotDirectDeviceCoapProtocolIntegrationTest.java @@ -0,0 +1,224 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.coap; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.IdUtil; +import cn.iocoder.yudao.framework.common.util.json.JsonUtils; +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO; +import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; +import cn.iocoder.yudao.module.iot.core.topic.auth.IotDeviceRegisterReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.event.IotDeviceEventPostReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPostReqDTO; +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.CoapClient; +import org.eclipse.californium.core.CoapResponse; +import org.eclipse.californium.core.coap.MediaTypeRegistry; +import org.eclipse.californium.core.coap.Option; +import org.eclipse.californium.core.coap.Request; +import org.eclipse.californium.core.config.CoapConfig; +import org.eclipse.californium.elements.config.Configuration; +import org.eclipse.californium.elements.config.UdpConfig; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * IoT 直连设备 CoAP 协议集成测试(手动测试) + * + *

测试场景:直连设备(IotProductDeviceTypeEnum 的 DIRECT 类型)通过 CoAP 协议直接连接平台 + * + *

使用步骤: + *

    + *
  1. 启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)
  2. + *
  3. 运行 {@link #testDeviceRegister()} 测试直连设备动态注册(一型一密)
  4. + *
  5. 运行 {@link #testAuth()} 获取设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  6. + *
  7. 运行以下测试方法: + *
      + *
    • {@link #testPropertyPost()} - 设备属性上报
    • + *
    • {@link #testEventPost()} - 设备事件上报
    • + *
    + *
  8. + *
+ * + * @author 芋道源码 + */ +@Slf4j +public class IotDirectDeviceCoapProtocolIntegrationTest { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 5683; + + // ===================== 直连设备信息(根据实际情况修改,从 iot_device 表查询子设备) ===================== + private static final String PRODUCT_KEY = "4aymZgOTOOCrDKRT"; + private static final String DEVICE_NAME = "small"; + private static final String DEVICE_SECRET = "0baa4c2ecc104ae1a26b4070c218bdf3"; + + /** + * 直连设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 + */ + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTk5MjgxOSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.UHLCXsoGNsKbtJcbTV3n1psp03G75hVcVpV4wwd39r4"; + + @BeforeAll + public static void initCaliforniumConfig() { + // 注册 Californium 配置定义 + CoapConfig.register(); + UdpConfig.register(); + // 创建默认配置 + Configuration.setStandard(Configuration.createStandardWithoutFile()); + } + + // ===================== 认证测试 ===================== + + /** + * 认证测试:获取设备 Token + */ + @Test + public void testAuth() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT); + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET); + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO() + .setClientId(authInfo.getClientId()) + .setUsername(authInfo.getUsername()) + .setPassword(authInfo.getPassword()); + String payload = JsonUtils.toJsonString(authReqDTO); + // 1.2 输出请求 + log.info("[testAuth][请求 URI: {}]", uri); + log.info("[testAuth][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); + // 2.2 输出结果 + log.info("[testAuth][响应码: {}]", response.getCode()); + log.info("[testAuth][响应体: {}]", response.getResponseText()); + log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); + } finally { + client.shutdown(); + } + } + + // ===================== 直连设备属性上报测试 ===================== + + /** + * 属性上报测试 + */ + @Test + @SuppressWarnings("deprecation") + public void testPropertyPost() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post", + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod()) + .put("version", "1.0") + .put("params", IotDevicePropertyPostReqDTO.of(MapUtil.builder() + .put("width", 1) + .put("height", "2") + .build()) + ) + .build()); + // 1.2 输出请求 + log.info("[testPropertyPost][请求 URI: {}]", uri); + log.info("[testPropertyPost][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testPropertyPost][响应码: {}]", response.getCode()); + log.info("[testPropertyPost][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + // ===================== 直连设备事件上报测试 ===================== + + /** + * 事件上报测试 + */ + @Test + @SuppressWarnings("deprecation") + public void testEventPost() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post", + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod()) + .put("version", "1.0") + .put("params", IotDeviceEventPostReqDTO.of( + "eat", + MapUtil.builder().put("rice", 3).build(), + System.currentTimeMillis()) + ) + .build()); + // 1.2 输出请求 + log.info("[testEventPost][请求 URI: {}]", uri); + log.info("[testEventPost][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testEventPost][响应码: {}]", response.getCode()); + log.info("[testEventPost][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + // ===================== 动态注册测试 ===================== + + /** + * 直连设备动态注册测试(一型一密) + *

+ * 使用产品密钥(productSecret)验证身份,成功后返回设备密钥(deviceSecret) + *

+ * 注意:此接口不需要 Token 认证 + */ + @Test + public void testDeviceRegister() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/auth/register/device", SERVER_HOST, SERVER_PORT); + // 1.2 构建请求参数 + IotDeviceRegisterReqDTO reqDTO = new IotDeviceRegisterReqDTO(); + reqDTO.setProductKey(PRODUCT_KEY); + reqDTO.setDeviceName("test-" + System.currentTimeMillis()); + reqDTO.setProductSecret("test-product-secret"); + String payload = JsonUtils.toJsonString(reqDTO); + // 1.3 输出请求 + log.info("[testDeviceRegister][请求 URI: {}]", uri); + log.info("[testDeviceRegister][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); + // 2.2 输出结果 + log.info("[testDeviceRegister][响应码: {}]", response.getCode()); + log.info("[testDeviceRegister][响应体: {}]", response.getResponseText()); + log.info("[testDeviceRegister][成功后可使用返回的 deviceSecret 进行一机一密认证]"); + } finally { + client.shutdown(); + } + } + +} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java new file mode 100644 index 0000000..76c853c --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewayDeviceCoapProtocolIntegrationTest.java @@ -0,0 +1,373 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.coap; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.IdUtil; +import cn.iocoder.yudao.framework.common.util.json.JsonUtils; +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO; +import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; +import cn.iocoder.yudao.module.iot.core.topic.IotDeviceIdentity; +import cn.iocoder.yudao.module.iot.core.topic.auth.IotSubDeviceRegisterReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPackPostReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoAddReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoDeleteReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.topo.IotDeviceTopoGetReqDTO; +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.CoapClient; +import org.eclipse.californium.core.CoapResponse; +import org.eclipse.californium.core.coap.MediaTypeRegistry; +import org.eclipse.californium.core.coap.Option; +import org.eclipse.californium.core.coap.Request; +import org.eclipse.californium.core.config.CoapConfig; +import org.eclipse.californium.elements.config.Configuration; +import org.eclipse.californium.elements.config.UdpConfig; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * IoT 网关设备 CoAP 协议集成测试(手动测试) + * + *

测试场景:网关设备(IotProductDeviceTypeEnum 的 GATEWAY 类型)通过 CoAP 协议管理子设备拓扑关系 + * + *

使用步骤: + *

    + *
  1. 启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)
  2. + *
  3. 运行 {@link #testAuth()} 获取网关设备 token,将返回的 token 粘贴到 {@link #GATEWAY_TOKEN} 常量
  4. + *
  5. 运行以下测试方法: + *
      + *
    • {@link #testTopoAdd()} - 添加子设备拓扑关系
    • + *
    • {@link #testTopoDelete()} - 删除子设备拓扑关系
    • + *
    • {@link #testTopoGet()} - 获取子设备拓扑关系
    • + *
    • {@link #testSubDeviceRegister()} - 子设备动态注册
    • + *
    • {@link #testPropertyPackPost()} - 批量上报属性(网关 + 子设备)
    • + *
    + *
  6. + *
+ * + * @author 芋道源码 + */ +@Slf4j +public class IotGatewayDeviceCoapProtocolIntegrationTest { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 5683; + + // ===================== 网关设备信息(根据实际情况修改,从 iot_device 表查询网关设备) ===================== + private static final String GATEWAY_PRODUCT_KEY = "m6XcS1ZJ3TW8eC0v"; + private static final String GATEWAY_DEVICE_NAME = "sub-ddd"; + private static final String GATEWAY_DEVICE_SECRET = "b3d62c70f8a4495487ed1d35d61ac2b3"; + + /** + * 网关设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 + */ + private static final String GATEWAY_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoibTZYY1MxWkozVFc4ZUMwdiIsImV4cCI6MTc2OTg2NjY3OCwiZGV2aWNlTmFtZSI6InN1Yi1kZGQifQ.nCLSAfHEjXLtTDRXARjOoFqpuo5WfArjFWweUAzrjKU"; + + // ===================== 子设备信息(根据实际情况修改,从 iot_device 表查询子设备) ===================== + private static final String SUB_DEVICE_PRODUCT_KEY = "jAufEMTF1W6wnPhn"; + private static final String SUB_DEVICE_NAME = "chazuo-it"; + private static final String SUB_DEVICE_SECRET = "d46ef9b28ab14238b9c00a3a668032af"; + + @BeforeAll + public static void initCaliforniumConfig() { + // 注册 Californium 配置定义 + CoapConfig.register(); + UdpConfig.register(); + // 创建默认配置 + Configuration.setStandard(Configuration.createStandardWithoutFile()); + } + + // ===================== 认证测试 ===================== + + /** + * 网关设备认证测试:获取网关设备 Token + */ + @Test + @SuppressWarnings("deprecation") + public void testAuth() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT); + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo( + GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME, GATEWAY_DEVICE_SECRET); + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO() + .setClientId(authInfo.getClientId()) + .setUsername(authInfo.getUsername()) + .setPassword(authInfo.getPassword()); + String payload = JsonUtils.toJsonString(authReqDTO); + // 1.2 输出请求 + log.info("[testAuth][请求 URI: {}]", uri); + log.info("[testAuth][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); + // 2.2 输出结果 + log.info("[testAuth][响应码: {}]", response.getCode()); + log.info("[testAuth][响应体: {}]", response.getResponseText()); + log.info("[testAuth][请将返回的 token 复制到 GATEWAY_TOKEN 常量中]"); + } finally { + client.shutdown(); + } + } + + // ===================== 拓扑管理测试 ===================== + + /** + * 添加子设备拓扑关系测试 + *

+ * 网关设备向平台上报需要绑定的子设备信息 + */ + @Test + @SuppressWarnings("deprecation") + public void testTopoAdd() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/add", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建子设备认证信息 + IotDeviceAuthReqDTO subAuthInfo = IotDeviceAuthUtils.getAuthInfo( + SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME, SUB_DEVICE_SECRET); + IotDeviceAuthReqDTO subDeviceAuth = new IotDeviceAuthReqDTO() + .setClientId(subAuthInfo.getClientId()) + .setUsername(subAuthInfo.getUsername()) + .setPassword(subAuthInfo.getPassword()); + // 1.3 构建请求参数 + IotDeviceTopoAddReqDTO params = new IotDeviceTopoAddReqDTO(); + params.setSubDevices(Collections.singletonList(subDeviceAuth)); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.TOPO_ADD.getMethod()) + .put("version", "1.0") + .put("params", params) + .build()); + // 1.4 输出请求 + log.info("[testTopoAdd][请求 URI: {}]", uri); + log.info("[testTopoAdd][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testTopoAdd][响应码: {}]", response.getCode()); + log.info("[testTopoAdd][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + /** + * 删除子设备拓扑关系测试 + *

+ * 网关设备向平台上报需要解绑的子设备信息 + */ + @Test + @SuppressWarnings("deprecation") + public void testTopoDelete() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/delete", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建请求参数 + IotDeviceTopoDeleteReqDTO params = new IotDeviceTopoDeleteReqDTO(); + params.setSubDevices(Collections.singletonList( + new IotDeviceIdentity(SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME))); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.TOPO_DELETE.getMethod()) + .put("version", "1.0") + .put("params", params) + .build()); + // 1.3 输出请求 + log.info("[testTopoDelete][请求 URI: {}]", uri); + log.info("[testTopoDelete][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testTopoDelete][响应码: {}]", response.getCode()); + log.info("[testTopoDelete][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + /** + * 获取子设备拓扑关系测试 + *

+ * 网关设备向平台查询已绑定的子设备列表 + */ + @Test + @SuppressWarnings("deprecation") + public void testTopoGet() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/topo/get", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建请求参数(目前为空,预留扩展) + IotDeviceTopoGetReqDTO params = new IotDeviceTopoGetReqDTO(); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.TOPO_GET.getMethod()) + .put("version", "1.0") + .put("params", params) + .build()); + // 1.3 输出请求 + log.info("[testTopoGet][请求 URI: {}]", uri); + log.info("[testTopoGet][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testTopoGet][响应码: {}]", response.getCode()); + log.info("[testTopoGet][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + // ===================== 子设备注册测试 ===================== + + /** + * 子设备动态注册测试 + *

+ * 网关设备代理子设备进行动态注册,平台返回子设备的 deviceSecret + *

+ * 注意:此接口需要网关 Token 认证 + */ + @Test + @SuppressWarnings("deprecation") + public void testSubDeviceRegister() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/auth/register/sub-device/%s/%s", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建请求参数 + IotSubDeviceRegisterReqDTO subDevice = new IotSubDeviceRegisterReqDTO(); + subDevice.setProductKey(SUB_DEVICE_PRODUCT_KEY); + subDevice.setDeviceName("mougezishebei"); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.SUB_DEVICE_REGISTER.getMethod()) + .put("version", "1.0") + .put("params", Collections.singletonList(subDevice)) + .build()); + // 1.3 输出请求 + log.info("[testSubDeviceRegister][请求 URI: {}]", uri); + log.info("[testSubDeviceRegister][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testSubDeviceRegister][响应码: {}]", response.getCode()); + log.info("[testSubDeviceRegister][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + // ===================== 批量上报测试 ===================== + + /** + * 批量上报属性测试(网关 + 子设备) + *

+ * 网关设备批量上报自身属性、事件,以及子设备的属性、事件 + */ + @Test + @SuppressWarnings("deprecation") + public void testPropertyPackPost() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/property/pack/post", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建【网关设备】自身属性 + Map gatewayProperties = MapUtil.builder() + .put("temperature", 25.5) + .build(); + // 1.3 构建【网关设备】自身事件 + IotDevicePropertyPackPostReqDTO.EventValue gatewayEvent = new IotDevicePropertyPackPostReqDTO.EventValue(); + gatewayEvent.setValue(MapUtil.builder().put("message", "gateway started").build()); + gatewayEvent.setTime(System.currentTimeMillis()); + Map gatewayEvents = MapUtil.builder() + .put("statusReport", gatewayEvent) + .build(); + // 1.4 构建【网关子设备】属性 + Map subDeviceProperties = MapUtil.builder() + .put("power", 100) + .build(); + // 1.5 构建【网关子设备】事件 + IotDevicePropertyPackPostReqDTO.EventValue subDeviceEvent = new IotDevicePropertyPackPostReqDTO.EventValue(); + subDeviceEvent.setValue(MapUtil.builder().put("errorCode", 0).build()); + subDeviceEvent.setTime(System.currentTimeMillis()); + Map subDeviceEvents = MapUtil.builder() + .put("healthCheck", subDeviceEvent) + .build(); + // 1.6 构建子设备数据 + IotDevicePropertyPackPostReqDTO.SubDeviceData subDeviceData = new IotDevicePropertyPackPostReqDTO.SubDeviceData(); + subDeviceData.setIdentity(new IotDeviceIdentity(SUB_DEVICE_PRODUCT_KEY, SUB_DEVICE_NAME)); + subDeviceData.setProperties(subDeviceProperties); + subDeviceData.setEvents(subDeviceEvents); + // 1.7 构建请求参数 + IotDevicePropertyPackPostReqDTO params = new IotDevicePropertyPackPostReqDTO(); + params.setProperties(gatewayProperties); + params.setEvents(gatewayEvents); + params.setSubDevices(List.of(subDeviceData)); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.PROPERTY_PACK_POST.getMethod()) + .put("version", "1.0") + .put("params", params) + .build()); + // 1.8 输出请求 + log.info("[testPropertyPackPost][请求 URI: {}]", uri); + log.info("[testPropertyPackPost][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, GATEWAY_TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testPropertyPackPost][响应码: {}]", response.getCode()); + log.info("[testPropertyPackPost][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + +} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java new file mode 100644 index 0000000..f6d4740 --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/coap/IotGatewaySubDeviceCoapProtocolIntegrationTest.java @@ -0,0 +1,197 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.coap; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.IdUtil; +import cn.iocoder.yudao.framework.common.util.json.JsonUtils; +import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO; +import cn.iocoder.yudao.module.iot.core.enums.IotDeviceMessageMethodEnum; +import cn.iocoder.yudao.module.iot.core.topic.event.IotDeviceEventPostReqDTO; +import cn.iocoder.yudao.module.iot.core.topic.property.IotDevicePropertyPostReqDTO; +import cn.iocoder.yudao.module.iot.core.util.IotDeviceAuthUtils; +import cn.iocoder.yudao.module.iot.gateway.protocol.coap.util.IotCoapUtils; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.californium.core.CoapClient; +import org.eclipse.californium.core.CoapResponse; +import org.eclipse.californium.core.coap.MediaTypeRegistry; +import org.eclipse.californium.core.coap.Option; +import org.eclipse.californium.core.coap.Request; +import org.eclipse.californium.core.config.CoapConfig; +import org.eclipse.californium.elements.config.Configuration; +import org.eclipse.californium.elements.config.UdpConfig; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** + * IoT 网关子设备 CoAP 协议集成测试(手动测试) + * + *

测试场景:子设备(IotProductDeviceTypeEnum 的 SUB 类型)通过网关设备代理上报数据 + * + *

重要说明:子设备无法直接连接平台,所有请求均由网关设备(Gateway)代为转发。 + *

网关设备转发子设备请求时,Token 使用子设备自己的信息。 + * + *

使用步骤: + *

    + *
  1. 启动 yudao-module-iot-gateway 服务(CoAP 端口 5683)
  2. + *
  3. 确保子设备已通过 {@link IotGatewayDeviceCoapProtocolIntegrationTest#testTopoAdd()} 绑定到网关
  4. + *
  5. 运行 {@link #testAuth()} 获取子设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  6. + *
  7. 运行以下测试方法: + *
      + *
    • {@link #testPropertyPost()} - 子设备属性上报(由网关代理转发)
    • + *
    • {@link #testEventPost()} - 子设备事件上报(由网关代理转发)
    • + *
    + *
  8. + *
+ * + * @author 芋道源码 + */ +@Slf4j +public class IotGatewaySubDeviceCoapProtocolIntegrationTest { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 5683; + + // ===================== 网关子设备信息(根据实际情况修改,从 iot_device 表查询子设备) ===================== + private static final String PRODUCT_KEY = "jAufEMTF1W6wnPhn"; + private static final String DEVICE_NAME = "chazuo-it"; + private static final String DEVICE_SECRET = "d46ef9b28ab14238b9c00a3a668032af"; + + /** + * 网关子设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 + */ + private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiakF1ZkVNVEYxVzZ3blBobiIsImV4cCI6MTc2OTk1NDY3OSwiZGV2aWNlTmFtZSI6ImNoYXp1by1pdCJ9.jfbUAoU0xkJl4UvO-NUvcJ6yITPRgUjQ4MKATPuwneg"; + + @BeforeAll + public static void initCaliforniumConfig() { + // 注册 Californium 配置定义 + CoapConfig.register(); + UdpConfig.register(); + // 创建默认配置 + Configuration.setStandard(Configuration.createStandardWithoutFile()); + } + + // ===================== 认证测试 ===================== + + /** + * 子设备认证测试:获取子设备 Token + */ + @Test + @SuppressWarnings("deprecation") + public void testAuth() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/auth", SERVER_HOST, SERVER_PORT); + IotDeviceAuthReqDTO authInfo = IotDeviceAuthUtils.getAuthInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET); + IotDeviceAuthReqDTO authReqDTO = new IotDeviceAuthReqDTO() + .setClientId(authInfo.getClientId()) + .setUsername(authInfo.getUsername()) + .setPassword(authInfo.getPassword()); + String payload = JsonUtils.toJsonString(authReqDTO); + // 1.2 输出请求 + log.info("[testAuth][请求 URI: {}]", uri); + log.info("[testAuth][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + CoapResponse response = client.post(payload, MediaTypeRegistry.APPLICATION_JSON); + // 2.2 输出结果 + log.info("[testAuth][响应码: {}]", response.getCode()); + log.info("[testAuth][响应体: {}]", response.getResponseText()); + log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); + } finally { + client.shutdown(); + } + } + + // ===================== 子设备属性上报测试 ===================== + + /** + * 子设备属性上报测试 + */ + @Test + @SuppressWarnings("deprecation") + public void testPropertyPost() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/property/post", + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.PROPERTY_POST.getMethod()) + .put("version", "1.0") + .put("params", IotDevicePropertyPostReqDTO.of(MapUtil.builder() + .put("power", 100) + .put("status", "online") + .put("temperature", 36.5) + .build())) + .build()); + // 1.2 输出请求 + log.info("[testPropertyPost][子设备属性上报 - 请求实际由 Gateway 代为转发]"); + log.info("[testPropertyPost][请求 URI: {}]", uri); + log.info("[testPropertyPost][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testPropertyPost][响应码: {}]", response.getCode()); + log.info("[testPropertyPost][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + + // ===================== 子设备事件上报测试 ===================== + + /** + * 子设备事件上报测试 + */ + @Test + @SuppressWarnings("deprecation") + public void testEventPost() throws Exception { + // 1.1 构建请求 + String uri = String.format("coap://%s:%d/topic/sys/%s/%s/thing/event/post", + SERVER_HOST, SERVER_PORT, PRODUCT_KEY, DEVICE_NAME); + String payload = JsonUtils.toJsonString(MapUtil.builder() + .put("id", IdUtil.fastSimpleUUID()) + .put("method", IotDeviceMessageMethodEnum.EVENT_POST.getMethod()) + .put("version", "1.0") + .put("params", IotDeviceEventPostReqDTO.of( + "alarm", + MapUtil.builder() + .put("level", "warning") + .put("message", "temperature too high") + .put("threshold", 40) + .put("current", 42) + .build(), + System.currentTimeMillis())) + .build()); + // 1.2 输出请求 + log.info("[testEventPost][子设备事件上报 - 请求实际由 Gateway 代为转发]"); + log.info("[testEventPost][请求 URI: {}]", uri); + log.info("[testEventPost][请求体: {}]", payload); + + // 2.1 发送请求 + CoapClient client = new CoapClient(uri); + try { + Request request = Request.newPost(); + request.setURI(uri); + request.setPayload(payload); + request.getOptions().setContentFormat(MediaTypeRegistry.APPLICATION_JSON); + request.getOptions().addOption(new Option(IotCoapUtils.OPTION_TOKEN, TOKEN)); + + CoapResponse response = client.advanced(request); + // 2.2 输出结果 + log.info("[testEventPost][响应码: {}]", response.getCode()); + log.info("[testEventPost][响应体: {}]", response.getResponseText()); + } finally { + client.shutdown(); + } + } + +} -- libgit2 0.21.4