diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/IotDeviceController.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/IotDeviceController.java index deb8cf3..18553a7 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/IotDeviceController.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/IotDeviceController.java @@ -64,7 +64,7 @@ public class IotDeviceController { @Operation(summary = "绑定子设备到网关") @PreAuthorize("@ss.hasPermission('iot:device:update')") public CommonResult bindDeviceGateway(@Valid @RequestBody IotDeviceBindGatewayReqVO reqVO) { - deviceService.bindDeviceGateway(reqVO.getIds(), reqVO.getGatewayId()); + deviceService.bindDeviceGateway(reqVO.getSubIds(), reqVO.getGatewayId()); return success(true); } @@ -72,7 +72,7 @@ public class IotDeviceController { @Operation(summary = "解绑子设备与网关") @PreAuthorize("@ss.hasPermission('iot:device:update')") public CommonResult unbindDeviceGateway(@Valid @RequestBody IotDeviceUnbindGatewayReqVO reqVO) { - deviceService.unbindDeviceGateway(reqVO.getIds(), reqVO.getGatewayId()); + deviceService.unbindDeviceGateway(reqVO.getSubIds(), reqVO.getGatewayId()); return success(true); } diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceBindGatewayReqVO.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceBindGatewayReqVO.java index be122d8..dbfa523 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceBindGatewayReqVO.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceBindGatewayReqVO.java @@ -13,7 +13,7 @@ public class IotDeviceBindGatewayReqVO { @Schema(description = "子设备编号列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "1,2,3") @NotEmpty(message = "子设备编号列表不能为空") - private Set ids; + private Set subIds; @Schema(description = "网关设备编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "10") @NotNull(message = "网关设备编号不能为空") diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceUnbindGatewayReqVO.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceUnbindGatewayReqVO.java index e198193..f51d659 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceUnbindGatewayReqVO.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/device/vo/device/IotDeviceUnbindGatewayReqVO.java @@ -13,7 +13,7 @@ public class IotDeviceUnbindGatewayReqVO { @Schema(description = "子设备编号列表", requiredMode = Schema.RequiredMode.REQUIRED, example = "1,2,3") @NotEmpty(message = "子设备编号列表不能为空") - private Set ids; + private Set subIds; @Schema(description = "网关设备编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") @NotNull(message = "网关设备编号不能为空") diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceService.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceService.java index e69ebc2..717376f 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceService.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceService.java @@ -297,18 +297,18 @@ public interface IotDeviceService { /** * 绑定子设备到网关 * - * @param ids 子设备编号列表 + * @param subIds 子设备编号列表 * @param gatewayId 网关设备编号 */ - void bindDeviceGateway(Collection ids, Long gatewayId); + void bindDeviceGateway(Collection subIds, Long gatewayId); /** * 解绑子设备与网关 * - * @param ids 子设备编号列表 + * @param subIds 子设备编号列表 * @param gatewayId 网关设备编号 */ - void unbindDeviceGateway(Collection ids, Long gatewayId); + void unbindDeviceGateway(Collection subIds, Long gatewayId); /** * 获取未绑定网关的子设备分页 diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceServiceImpl.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceServiceImpl.java index cfdfafa..fc6b5ee 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceServiceImpl.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/IotDeviceServiceImpl.java @@ -518,13 +518,6 @@ public class IotDeviceServiceImpl implements IotDeviceService { log.error("[authDevice][设备({}/{}) 密码不正确]", productKey, deviceName); return false; } - - // 3. 校验子设备拓扑关系:子设备必须先绑定到某网关才能认证上线 - if (IotProductDeviceTypeEnum.isGatewaySub(device.getDeviceType()) - && device.getGatewayId() == null) { - log.warn("[authDevice][子设备({}/{}) 未绑定到任何网关,认证失败]", productKey, deviceName); - return false; - } return true; } @@ -577,14 +570,14 @@ public class IotDeviceServiceImpl implements IotDeviceService { @Override @Transactional(rollbackFor = Exception.class) - public void bindDeviceGateway(Collection ids, Long gatewayId) { - if (CollUtil.isEmpty(ids)) { + public void bindDeviceGateway(Collection subIds, Long gatewayId) { + if (CollUtil.isEmpty(subIds)) { return; } // 1.1 校验网关设备存在且类型正确 validateGatewayDeviceExists(gatewayId); // 1.2 校验每个设备是否可绑定 - List devices = deviceMapper.selectByIds(ids); + List devices = deviceMapper.selectByIds(subIds); for (IotDeviceDO device : devices) { checkSubDeviceCanBind(device, gatewayId); } @@ -613,13 +606,13 @@ public class IotDeviceServiceImpl implements IotDeviceService { @Override @Transactional(rollbackFor = Exception.class) - public void unbindDeviceGateway(Collection ids, Long gatewayId) { + public void unbindDeviceGateway(Collection subIds, Long gatewayId) { // 1. 校验设备存在 - if (CollUtil.isEmpty(ids)) { + if (CollUtil.isEmpty(subIds)) { return; } - List devices = deviceMapper.selectByIds(ids); - devices.removeIf(device -> device.getGatewayId() == null); + List devices = deviceMapper.selectByIds(subIds); + devices.removeIf(device -> ObjUtil.notEqual(device.getGatewayId(), gatewayId)); if (CollUtil.isEmpty(devices)) { return; } diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageService.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageService.java index 4a300df..e28f489 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageService.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageService.java @@ -7,7 +7,6 @@ import cn.iocoder.yudao.module.iot.controller.admin.statistics.vo.IotStatisticsD import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage; import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceDO; import cn.iocoder.yudao.module.iot.dal.dataobject.device.IotDeviceMessageDO; -import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import javax.annotation.Nullable; @@ -75,7 +74,7 @@ public interface IotDeviceMessageService { */ List getDeviceMessageListByRequestIdsAndReply( @NotNull(message = "设备编号不能为空") Long deviceId, - @NotEmpty(message = "请求编号不能为空") List requestIds, + List requestIds, Boolean reply); /** diff --git a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageServiceImpl.java b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageServiceImpl.java index 0fc1e25..24a5bb9 100644 --- a/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageServiceImpl.java +++ b/yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/device/message/IotDeviceMessageServiceImpl.java @@ -1,6 +1,7 @@ package cn.iocoder.yudao.module.iot.service.device.message; import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.collection.ListUtil; import cn.hutool.core.date.LocalDateTimeUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.map.MapUtil; @@ -103,7 +104,6 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { return sendDeviceMessage(message, device); } - // TODO @芋艿:针对连接网关的设备,是不是 productKey、deviceName 需要调整下; @Override public IotDeviceMessage sendDeviceMessage(IotDeviceMessage message, IotDeviceDO device) { return sendDeviceMessage(message, device, null); @@ -273,7 +273,8 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { log.warn("[handlePackMessage][子设备({}/{}) 不存在]", identity.getProductKey(), identity.getDeviceName()); continue; } - sendDevicePackData(subDevice, packMessage.getServerId(), subDeviceData.getProperties(), subDeviceData.getEvents()); + // 特殊:子设备不需要指定 serverId,因为子设备实际可能连接在不同的 gateway-server 上,导致 serverId 不同 + sendDevicePackData(subDevice, null, subDeviceData.getProperties(), subDeviceData.getEvents()); } catch (Exception ex) { log.error("[handlePackMessage][子设备({}/{}) 数据处理失败]", subDeviceData.getIdentity().getProductKey(), subDeviceData.getIdentity().getDeviceName(), ex); @@ -335,9 +336,10 @@ public class IotDeviceMessageServiceImpl implements IotDeviceMessageService { } @Override - public List getDeviceMessageListByRequestIdsAndReply(Long deviceId, - List requestIds, - Boolean reply) { + public List getDeviceMessageListByRequestIdsAndReply(Long deviceId, List requestIds, Boolean reply) { + if (CollUtil.isEmpty(requestIds)) { + return ListUtil.of(); + } return deviceMessageMapper.selectListByRequestIdsAndReply(deviceId, requestIds, reply); } diff --git a/yudao-module-iot/yudao-module-iot-core/src/main/java/cn/iocoder/yudao/module/iot/core/util/IotDeviceAuthUtils.java b/yudao-module-iot/yudao-module-iot-core/src/main/java/cn/iocoder/yudao/module/iot/core/util/IotDeviceAuthUtils.java index ee2c917..9ee953e 100644 --- a/yudao-module-iot/yudao-module-iot-core/src/main/java/cn/iocoder/yudao/module/iot/core/util/IotDeviceAuthUtils.java +++ b/yudao-module-iot/yudao-module-iot-core/src/main/java/cn/iocoder/yudao/module/iot/core/util/IotDeviceAuthUtils.java @@ -72,7 +72,7 @@ public class IotDeviceAuthUtils { .digestHex(content); } - public static String buildContent(String clientId, String productKey, String deviceName, String deviceSecret) { + private static String buildContent(String clientId, String productKey, String deviceName, String deviceSecret) { return "clientId" + clientId + "deviceName" + deviceName + "deviceSecret" + deviceSecret + diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotDirectDeviceHttpProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotDirectDeviceHttpProtocolIntegrationTest.java index dba9e64..70e4114 100644 --- a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotDirectDeviceHttpProtocolIntegrationTest.java +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotDirectDeviceHttpProtocolIntegrationTest.java @@ -21,9 +21,14 @@ import org.junit.jupiter.api.Test; * *

使用步骤: *

    - *
  1. 启动 yudao-module-iot-gateway 服务(HTTP 端口 8082)
  2. - *
  3. 运行 {@link #testAuth()} 获取 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  4. - *
  5. 运行 {@link #testPropertyPost()} 测试属性上报,或运行 {@link #testEventPost()} 测试事件上报
  6. + *
  7. 启动 yudao-module-iot-gateway 服务(HTTP 端口 8092)
  8. + *
  9. 运行 {@link #testAuth()} 获取设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  10. + *
  11. 运行以下测试方法: + *
      + *
    • {@link #testPropertyPost()} - 设备属性上报
    • + *
    • {@link #testEventPost()} - 设备事件上报
    • + *
    + *
  12. *
* * @author 芋道源码 @@ -35,16 +40,18 @@ public class IotDirectDeviceHttpProtocolIntegrationTest { private static final String SERVER_HOST = "127.0.0.1"; private static final int SERVER_PORT = 8092; - // 设备信息(根据实际情况修改 PRODUCT_KEY、DEVICE_NAME、DEVICE_SECRET,从 iot_device 表查询) + // ===================== 直连设备信息(根据实际情况修改,从 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()} 方法获取后,粘贴到这里 + * 直连设备 Token:从 {@link #testAuth()} 方法获取后,粘贴到这里 */ private static final String TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcm9kdWN0S2V5IjoiNGF5bVpnT1RPT0NyREtSVCIsImV4cCI6MTc2OTMwNTA1NSwiZGV2aWNlTmFtZSI6InNtYWxsIn0.mf3MEATCn5bp6cXgULunZjs8d00RGUxj96JEz0hMS7k"; + // ===================== 认证测试 ===================== + /** * 认证测试:获取设备 Token */ @@ -69,6 +76,8 @@ public class IotDirectDeviceHttpProtocolIntegrationTest { log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); } + // ===================== 直连设备属性上报测试 ===================== + /** * 属性上报测试 */ @@ -101,6 +110,8 @@ public class IotDirectDeviceHttpProtocolIntegrationTest { } } + // ===================== 直连设备事件上报测试 ===================== + /** * 事件上报测试 */ diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewayDeviceHttpProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewayDeviceHttpProtocolIntegrationTest.java new file mode 100644 index 0000000..e431bfb --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewayDeviceHttpProtocolIntegrationTest.java @@ -0,0 +1,308 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.http; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.http.HttpResponse; +import cn.hutool.http.HttpUtil; +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 lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + + +/** + * IoT 网关设备 HTTP 协议集成测试(手动测试) + * + *

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

使用步骤: + *

    + *
  1. 启动 yudao-module-iot-gateway 服务(HTTP 端口 8092)
  2. + *
  3. 运行 {@link #testAuth()} 获取网关设备 token,将返回的 token 粘贴到 {@link #GATEWAY_TOKEN} 常量
  4. + *
  5. 运行以下测试方法: + *
      + *
    • {@link #testTopoAdd()} - 添加子设备拓扑关系
    • + *
    • {@link #testTopoDelete()} - 删除子设备拓扑关系
    • + *
    • {@link #testTopoGet()} - 获取子设备拓扑关系
    • + *
    • {@link #testSubDeviceRegister()} - 子设备动态注册
    • + *
    • {@link #testPropertyPackPost()} - 批量上报属性(网关 + 子设备)
    • + *
    + *
  6. + *
+ * + * @author 芋道源码 + */ +@Slf4j +@SuppressWarnings("HttpUrlsUsage") +public class IotGatewayDeviceHttpProtocolIntegrationTest { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 8092; + + // ===================== 网关设备信息(根据实际情况修改,从 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"; + + // ===================== 认证测试 ===================== + + /** + * 网关设备认证测试:获取网关设备 Token + */ + @Test + public void testAuth() { + // 1.1 构建请求 + String url = String.format("http://%s:%d/auth", SERVER_HOST, SERVER_PORT); + IotDeviceAuthUtils.AuthInfo 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][请求 URL: {}]", url); + log.info("[testAuth][请求体: {}]", payload); + + // 2.1 发送请求 + String response = HttpUtil.post(url, payload); + // 2.2 输出结果 + log.info("[testAuth][响应体: {}]", response); + log.info("[testAuth][请将返回的 token 复制到 GATEWAY_TOKEN 常量中]"); + } + + // ===================== 拓扑管理测试 ===================== + + // TODO @芋艿:待测试 + + /** + * 添加子设备拓扑关系测试 + *

+ * 网关设备向平台上报需要绑定的子设备信息 + */ + @Test + public void testTopoAdd() { + // 1.1 构建请求 + String url = String.format("http://%s:%d/topic/sys/%s/%s/thing/topo/add", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建子设备认证信息 + IotDeviceAuthUtils.AuthInfo 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][请求 URL: {}]", url); + log.info("[testTopoAdd][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", GATEWAY_TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testTopoAdd][响应体: {}]", httpResponse.body()); + } + } + + /** + * 删除子设备拓扑关系测试 + *

+ * 网关设备向平台上报需要解绑的子设备信息 + */ + @Test + public void testTopoDelete() { + // 1.1 构建请求 + String url = String.format("http://%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][请求 URL: {}]", url); + log.info("[testTopoDelete][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", GATEWAY_TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testTopoDelete][响应体: {}]", httpResponse.body()); + } + } + + /** + * 获取子设备拓扑关系测试 + *

+ * 网关设备向平台查询已绑定的子设备列表 + */ + @Test + public void testTopoGet() { + // 1.1 构建请求 + String url = String.format("http://%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][请求 URL: {}]", url); + log.info("[testTopoGet][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", GATEWAY_TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testTopoGet][响应体: {}]", httpResponse.body()); + } + } + + // ===================== 子设备注册测试 ===================== + + // TODO @芋艿:待测试 + + /** + * 子设备动态注册测试 + *

+ * 网关设备代理子设备进行动态注册,平台返回子设备的 deviceSecret + */ + @Test + public void testSubDeviceRegister() { + // 1.1 构建请求 + String url = String.format("http://%s:%d/topic/sys/%s/%s/thing/sub/register", + SERVER_HOST, SERVER_PORT, GATEWAY_PRODUCT_KEY, GATEWAY_DEVICE_NAME); + // 1.2 构建请求参数 + IotSubDeviceRegisterReqDTO subDevice = new IotSubDeviceRegisterReqDTO(); + subDevice.setProductKey(SUB_DEVICE_PRODUCT_KEY); + subDevice.setDeviceName(SUB_DEVICE_NAME); + 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][请求 URL: {}]", url); + log.info("[testSubDeviceRegister][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", GATEWAY_TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testSubDeviceRegister][响应体: {}]", httpResponse.body()); + } + } + + // ===================== 批量上报测试 ===================== + + /** + * 批量上报属性测试(网关 + 子设备) + *

+ * 网关设备批量上报自身属性、事件,以及子设备的属性、事件 + */ + @Test + public void testPropertyPackPost() { + // 1.1 构建请求 + String url = String.format("http://%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][请求 URL: {}]", url); + log.info("[testPropertyPackPost][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", GATEWAY_TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testPropertyPackPost][响应体: {}]", httpResponse.body()); + } + } + +} diff --git a/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewaySubDeviceHttpProtocolIntegrationTest.java b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewaySubDeviceHttpProtocolIntegrationTest.java new file mode 100644 index 0000000..1428d8e --- /dev/null +++ b/yudao-module-iot/yudao-module-iot-gateway/src/test/java/cn/iocoder/yudao/module/iot/gateway/protocol/http/IotGatewaySubDeviceHttpProtocolIntegrationTest.java @@ -0,0 +1,159 @@ +package cn.iocoder.yudao.module.iot.gateway.protocol.http; + +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.http.HttpResponse; +import cn.hutool.http.HttpUtil; +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 lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + + +/** + * IoT 网关子设备 HTTP 协议集成测试(手动测试) + * + *

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

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

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

使用步骤: + *

    + *
  1. 启动 yudao-module-iot-gateway 服务(HTTP 端口 8092)
  2. + *
  3. 确保子设备已通过 {@link IotGatewayDeviceHttpProtocolIntegrationTest#testTopoAdd()} 绑定到网关
  4. + *
  5. 运行 {@link #testAuth()} 获取子设备 token,将返回的 token 粘贴到 {@link #TOKEN} 常量
  6. + *
  7. 运行以下测试方法: + *
      + *
    • {@link #testPropertyPost()} - 子设备属性上报(由网关代理转发)
    • + *
    • {@link #testEventPost()} - 子设备事件上报(由网关代理转发)
    • + *
    + *
  8. + *
+ * + * @author 芋道源码 + */ +@Slf4j +@SuppressWarnings("HttpUrlsUsage") +public class IotGatewaySubDeviceHttpProtocolIntegrationTest { + + private static final String SERVER_HOST = "127.0.0.1"; + private static final int SERVER_PORT = 8092; + + // ===================== 网关子设备信息(根据实际情况修改,从 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.eyJwcm9kdWN0S2V5IjoiakF1ZkVNVEYxVzZ3blBobiIsImV4cCI6MTc2OTg3MTI3NCwiZGV2aWNlTmFtZSI6ImNoYXp1by1pdCJ9.99sAlRalzMU3CqRlGStDzCwWSBJq6u3PJw48JQ3NpzQ"; + + // ===================== 认证测试 ===================== + + /** + * 子设备认证测试:获取子设备 Token + */ + @Test + public void testAuth() { + // 1.1 构建请求 + String url = String.format("http://%s:%d/auth", SERVER_HOST, SERVER_PORT); + IotDeviceAuthUtils.AuthInfo 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][请求 URL: {}]", url); + log.info("[testAuth][请求体: {}]", payload); + + // 2.1 发送请求 + String response = HttpUtil.post(url, payload); + // 2.2 输出结果 + log.info("[testAuth][响应体: {}]", response); + log.info("[testAuth][请将返回的 token 复制到 TOKEN 常量中]"); + } + + // ===================== 子设备属性上报测试 ===================== + + /** + * 子设备属性上报测试 + */ + @Test + public void testPropertyPost() { + // 1.1 构建请求 + String url = String.format("http://%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][请求 URL: {}]", url); + log.info("[testPropertyPost][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testPropertyPost][响应体: {}]", httpResponse.body()); + } + } + + // ===================== 子设备事件上报测试 ===================== + + /** + * 子设备事件上报测试 + */ + @Test + public void testEventPost() { + // 1.1 构建请求 + String url = String.format("http://%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][请求 URL: {}]", url); + log.info("[testEventPost][请求体: {}]", payload); + + // 2.1 发送请求 + try (HttpResponse httpResponse = HttpUtil.createPost(url) + .header("Authorization", TOKEN) + .body(payload) + .execute()) { + // 2.2 输出结果 + log.info("[testEventPost][响应体: {}]", httpResponse.body()); + } + } + +}