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

This commit is contained in:
YunaiV
2026-01-26 12:44:03 +08:00
parent 572a3d1051
commit 136da4eb50
6 changed files with 813 additions and 48 deletions

View File

@@ -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;

View File

@@ -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 协议的【设备动态注册】处理器
* <p>
* 用于直连设备/网关的一型一密动态注册,不需要认证
*
* @author 芋道源码
* @see <a href="https://help.aliyun.com/zh/iot/user-guide/unique-certificate-per-product-verification">阿里云 - 一型一密</a>
* @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<String, Object> 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<IotDeviceRegisterRespDTO> 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, "服务器内部错误");
}
}
}

View File

@@ -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
* <p>
* 用于直连设备/网关的一型一密动态注册,不需要认证
*
* @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);
}
}

View File

@@ -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 协议集成测试(手动测试)
*
* <p>测试场景直连设备IotProductDeviceTypeEnum 的 DIRECT 类型)通过 CoAP 协议直接连接平台
*
* <p>使用步骤:
* <ol>
* <li>启动 yudao-module-iot-gateway 服务CoAP 端口 5683</li>
* <li>运行 {@link #testDeviceRegister()} 测试直连设备动态注册(一型一密)</li>
* <li>运行 {@link #testAuth()} 获取设备 token将返回的 token 粘贴到 {@link #TOKEN} 常量</li>
* <li>运行以下测试方法:
* <ul>
* <li>{@link #testPropertyPost()} - 设备属性上报</li>
* <li>{@link #testEventPost()} - 设备事件上报</li>
* </ul>
* </li>
* </ol>
*
* @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.<String, Object>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.<String, Object>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();
}
}
// ===================== 动态注册测试 =====================
/**
* 直连设备动态注册测试(一型一密)
* <p>
* 使用产品密钥productSecret验证身份成功后返回设备密钥deviceSecret
* <p>
* 注意:此接口不需要 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();
}
}
}

View File

@@ -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 协议集成测试(手动测试)
*
* <p>测试场景网关设备IotProductDeviceTypeEnum 的 GATEWAY 类型)通过 CoAP 协议管理子设备拓扑关系
*
* <p>使用步骤:
* <ol>
* <li>启动 yudao-module-iot-gateway 服务CoAP 端口 5683</li>
* <li>运行 {@link #testAuth()} 获取网关设备 token将返回的 token 粘贴到 {@link #GATEWAY_TOKEN} 常量</li>
* <li>运行以下测试方法:
* <ul>
* <li>{@link #testTopoAdd()} - 添加子设备拓扑关系</li>
* <li>{@link #testTopoDelete()} - 删除子设备拓扑关系</li>
* <li>{@link #testTopoGet()} - 获取子设备拓扑关系</li>
* <li>{@link #testSubDeviceRegister()} - 子设备动态注册</li>
* <li>{@link #testPropertyPackPost()} - 批量上报属性(网关 + 子设备)</li>
* </ul>
* </li>
* </ol>
*
* @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();
}
}
// ===================== 拓扑管理测试 =====================
/**
* 添加子设备拓扑关系测试
* <p>
* 网关设备向平台上报需要绑定的子设备信息
*/
@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();
}
}
/**
* 删除子设备拓扑关系测试
* <p>
* 网关设备向平台上报需要解绑的子设备信息
*/
@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();
}
}
/**
* 获取子设备拓扑关系测试
* <p>
* 网关设备向平台查询已绑定的子设备列表
*/
@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();
}
}
// ===================== 子设备注册测试 =====================
/**
* 子设备动态注册测试
* <p>
* 网关设备代理子设备进行动态注册,平台返回子设备的 deviceSecret
* <p>
* 注意:此接口需要网关 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();
}
}
// ===================== 批量上报测试 =====================
/**
* 批量上报属性测试(网关 + 子设备)
* <p>
* 网关设备批量上报自身属性、事件,以及子设备的属性、事件
*/
@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<String, Object> gatewayProperties = MapUtil.<String, Object>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<String, IotDevicePropertyPackPostReqDTO.EventValue> gatewayEvents = MapUtil.<String, IotDevicePropertyPackPostReqDTO.EventValue>builder()
.put("statusReport", gatewayEvent)
.build();
// 1.4 构建【网关子设备】属性
Map<String, Object> subDeviceProperties = MapUtil.<String, Object>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<String, IotDevicePropertyPackPostReqDTO.EventValue> subDeviceEvents = MapUtil.<String, IotDevicePropertyPackPostReqDTO.EventValue>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();
}
}
}

View File

@@ -3,7 +3,11 @@ 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;
@@ -18,35 +22,43 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* IoT 网关 CoAP 协议集成测试手动测试
* IoT 网关子设备 CoAP 协议集成测试手动测试
*
* <p>测试场景子设备IotProductDeviceTypeEnum SUB 类型通过网关设备代理上报数据
*
* <p><b>重要说明子设备无法直接连接平台所有请求均由网关设备Gateway代为转发</b>
* <p>网关设备转发子设备请求时Token 使用子设备自己的信息
*
* <p>使用步骤
* <ol>
* <li>启动 yudao-module-iot-gateway 服务CoAP 端口 5683</li>
* <li>运行 {@link #testAuth()} 获取 token将返回的 token 粘贴到 {@link #TOKEN} 常量</li>
* <li>运行 {@link #testPropertyPost()} 测试属性上报或运行 {@link #testEventPost()} 测试事件上报</li>
* <li>确保子设备已通过 {@link IotGatewayDeviceCoapProtocolIntegrationTest#testTopoAdd()} 绑定到网关</li>
* <li>运行 {@link #testAuth()} 获取子设备 token将返回的 token 粘贴到 {@link #TOKEN} 常量</li>
* <li>运行以下测试方法
* <ul>
* <li>{@link #testPropertyPost()} - 子设备属性上报由网关代理转发</li>
* <li>{@link #testEventPost()} - 子设备事件上报由网关代理转发</li>
* </ul>
* </li>
* </ol>
*
* @author 芋道源码
*/
@Slf4j
public class IotCoapProtocolIntegrationTest {
public class IotGatewaySubDeviceCoapProtocolIntegrationTest {
private static final String SERVER_HOST = "127.0.0.1";
private static final int SERVER_PORT = 5683;
// 设备信息根据实际情况修改 PRODUCT_KEYDEVICE_NAMEPASSWORD
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;
// ===================== 网关子设备信息根据实际情况修改 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()} 方法获取后粘贴到这里
* 网关子设备 Token {@link #testAuth()} 方法获取后粘贴到这里
*/
private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTMwNTA1NSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.mf3MEATCn5bp6cXgULunZjs8d00RGUxj96JEz0hMS7k";
private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiakF1ZkVNVEYxVzZ3blBobiIsImV4cCI6MTc2OTk1NDY3OSwiZGV2aWNlTmFtZSI6ImNoYXp1by1pdCJ9.jfbUAoU0xkJl4UvO-NUvcJ6yITPRgUjQ4MKATPuwneg";
@BeforeAll
public static void initCaliforniumConfig() {
@@ -57,26 +69,31 @@ public class IotCoapProtocolIntegrationTest {
Configuration.setStandard(Configuration.createStandardWithoutFile());
}
// ===================== 认证测试 =====================
/**
* 认证测试获取设备 Token
* 子设备认证测试获取设备 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 +102,33 @@ 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("width", 1)
.put("height", "2")
.build())
.put("params", IotDevicePropertyPostReqDTO.of(MapUtil.<String, Object>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();
@@ -111,11 +137,8 @@ public class IotCoapProtocolIntegrationTest {
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);
// 2.2 输出结果
log.info("[testPropertyPost][响应码: {}]", response.getCode());
log.info("[testPropertyPost][响应体: {}]", response.getResponseText());
} finally {
@@ -123,29 +146,37 @@ public class IotCoapProtocolIntegrationTest {
}
}
// ===================== 子设备事件上报测试 =====================
/**
* 事件上报测试
* 子设备事件上报测试
*/
@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", MapUtil.builder()
.put("identifier", "eat")
.put("value", MapUtil.builder()
.put("width", 1)
.put("height", "2")
.put("oneThree", "3")
.build())
.put("time", System.currentTimeMillis())
.build())
.put("params", IotDeviceEventPostReqDTO.of(
"alarm",
MapUtil.<String, Object>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();
@@ -154,11 +185,8 @@ public class IotCoapProtocolIntegrationTest {
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);
// 2.2 输出结果
log.info("[testEventPost][响应码: {}]", response.getCode());
log.info("[testEventPost][响应体: {}]", response.getResponseText());
} finally {