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
+ * 用于直连设备/网关的一型一密动态注册,不需要认证
+ *
+ * @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/IotDirectDeviceCoapProtocolIntegrationTest.java
index 5856ced..b8f9126 100644
--- 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/IotDirectDeviceCoapProtocolIntegrationTest.java
@@ -3,7 +3,12 @@ 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;
@@ -18,35 +23,40 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
- * IoT 网关 CoAP 协议集成测试(手动测试)
+ * IoT 直连设备 CoAP 协议集成测试(手动测试)
+ *
+ * 测试场景:直连设备(IotProductDeviceTypeEnum 的 DIRECT 类型)通过 CoAP 协议直接连接平台
*
* 使用步骤:
*
+ * 使用产品密钥(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 协议管理子设备拓扑关系
+ *
+ * 使用步骤:
+ *
+ * 网关设备向平台上报需要绑定的子设备信息
+ */
+ @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 测试场景:子设备(IotProductDeviceTypeEnum 的 SUB 类型)通过网关设备代理上报数据
+ *
+ * 重要说明:子设备无法直接连接平台,所有请求均由网关设备(Gateway)代为转发。
+ * 网关设备转发子设备请求时,Token 使用子设备自己的信息。
+ *
+ * 使用步骤:
+ *
*
*
* @author 芋道源码
*/
@Slf4j
-public class IotCoapProtocolIntegrationTest {
+public class IotDirectDeviceCoapProtocolIntegrationTest {
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 5683;
- // 设备信息(根据实际情况修改 PRODUCT_KEY、DEVICE_NAME、PASSWORD)
+ // ===================== 直连设备信息(根据实际情况修改,从 iot_device 表查询子设备) =====================
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;
+ private static final String DEVICE_SECRET = "0baa4c2ecc104ae1a26b4070c218bdf3";
/**
- * 设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里
+ * 直连设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里
*/
- private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTMwNTA1NSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.mf3MEATCn5bp6cXgULunZjs8d00RGUxj96JEz0hMS7k";
+ private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTk5MjgxOSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.UHLCXsoGNsKbtJcbTV3n1psp03G75hVcVpV4wwd39r4";
@BeforeAll
public static void initCaliforniumConfig() {
@@ -57,26 +67,30 @@ public class IotCoapProtocolIntegrationTest {
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);
- String payload = JsonUtils.toJsonString(MapUtil.builder()
- .put("clientId", CLIENT_ID)
- .put("username", USERNAME)
- .put("password", PASSWORD)
- .build());
-
+ 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 {
- log.info("[testAuth][请求 URI: {}]", uri);
- log.info("[testAuth][请求体: {}]", payload);
-
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 常量中]");
@@ -85,24 +99,32 @@ public class IotCoapProtocolIntegrationTest {
}
}
+ // ===================== 直连设备属性上报测试 =====================
+
/**
* 属性上报测试
*/
@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", MapUtil.builder()
+ .put("params", IotDevicePropertyPostReqDTO.of(MapUtil.
+ *
+ *
+ *
+ *
+ * @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();
+ }
+ }
+
+ // ===================== 拓扑管理测试 =====================
+
+ /**
+ * 添加子设备拓扑关系测试
+ *
+ *
+ *
+ *
+ *
+ * @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.
+ *
+ *