Commit e3e3a00fba7e6827528d3235c6ea76dd07a6381d
Merge remote-tracking branch 'yudao/feature/iot' into iot
Showing
47 changed files
with
2534 additions
and
75 deletions
yudao-module-iot/yudao-module-iot-api/src/main/java/cn/iocoder/yudao/module/iot/enums/ErrorCodeConstants.java
| ... | ... | @@ -75,4 +75,7 @@ public interface ErrorCodeConstants { |
| 75 | 75 | // ========== IoT 规则场景(场景联动) 1-050-011-000 ========== |
| 76 | 76 | ErrorCode RULE_SCENE_NOT_EXISTS = new ErrorCode(1_050_011_000, "IoT 规则场景(场景联动)不存在"); |
| 77 | 77 | |
| 78 | + // ========== IoT 产品脚本信息 1-050-012-000 ========== | |
| 79 | + ErrorCode PRODUCT_SCRIPT_NOT_EXISTS = new ErrorCode(1_050_012_000, "IoT 产品脚本信息不存在"); | |
| 80 | + | |
| 78 | 81 | } |
| 79 | 82 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-api/src/main/java/cn/iocoder/yudao/module/iot/enums/product/IotProductScriptLanguageEnum.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.enums.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.core.ArrayValuable; | |
| 4 | +import lombok.AllArgsConstructor; | |
| 5 | +import lombok.Getter; | |
| 6 | + | |
| 7 | +import java.util.Arrays; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * IoT 产品脚本语言枚举 | |
| 11 | + * | |
| 12 | + * @author 芋道源码 | |
| 13 | + */ | |
| 14 | +@Getter | |
| 15 | +@AllArgsConstructor | |
| 16 | +public enum IotProductScriptLanguageEnum implements ArrayValuable<String> { | |
| 17 | + | |
| 18 | + JAVASCRIPT("javascript", "JavaScript"), | |
| 19 | + JAVA("java", "Java"), | |
| 20 | + PYTHON("python", "Python"), | |
| 21 | + ; | |
| 22 | + | |
| 23 | + public static final String[] ARRAYS = Arrays.stream(values()).map(IotProductScriptLanguageEnum::getCode) | |
| 24 | + .toArray(String[]::new); | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * 编码 | |
| 28 | + */ | |
| 29 | + private final String code; | |
| 30 | + /** | |
| 31 | + * 名称 | |
| 32 | + */ | |
| 33 | + private final String name; | |
| 34 | + | |
| 35 | + @Override | |
| 36 | + public String[] array() { | |
| 37 | + return ARRAYS; | |
| 38 | + } | |
| 39 | + | |
| 40 | + public static IotProductScriptLanguageEnum getByCode(String code) { | |
| 41 | + return Arrays.stream(values()) | |
| 42 | + .filter(type -> type.getCode().equals(code)) | |
| 43 | + .findFirst() | |
| 44 | + .orElse(null); | |
| 45 | + } | |
| 46 | +} | |
| 0 | 47 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-api/src/main/java/cn/iocoder/yudao/module/iot/enums/product/IotProductScriptStatusEnum.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.enums.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.core.ArrayValuable; | |
| 4 | +import lombok.AllArgsConstructor; | |
| 5 | +import lombok.Getter; | |
| 6 | + | |
| 7 | +import java.util.Arrays; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * IoT 产品脚本状态枚举 | |
| 11 | + * | |
| 12 | + * @author 芋道源码 | |
| 13 | + */ | |
| 14 | +@Getter | |
| 15 | +@AllArgsConstructor | |
| 16 | +public enum IotProductScriptStatusEnum implements ArrayValuable<Integer> { | |
| 17 | + | |
| 18 | + ENABLE(0, "启用"), | |
| 19 | + DISABLE(1, "禁用"), | |
| 20 | + ; | |
| 21 | + | |
| 22 | + public static final Integer[] ARRAYS = Arrays.stream(values()).map(IotProductScriptStatusEnum::getStatus) | |
| 23 | + .toArray(Integer[]::new); | |
| 24 | + | |
| 25 | + /** | |
| 26 | + * 状态值 | |
| 27 | + */ | |
| 28 | + private final Integer status; | |
| 29 | + /** | |
| 30 | + * 状态名 | |
| 31 | + */ | |
| 32 | + private final String name; | |
| 33 | + | |
| 34 | + @Override | |
| 35 | + public Integer[] array() { | |
| 36 | + return ARRAYS; | |
| 37 | + } | |
| 38 | + | |
| 39 | + public static IotProductScriptStatusEnum getByStatus(Integer status) { | |
| 40 | + return Arrays.stream(values()) | |
| 41 | + .filter(type -> type.getStatus().equals(status)) | |
| 42 | + .findFirst() | |
| 43 | + .orElse(null); | |
| 44 | + } | |
| 45 | + | |
| 46 | + public static boolean isEnable(Integer status) { | |
| 47 | + return ENABLE.getStatus().equals(status); | |
| 48 | + } | |
| 49 | + | |
| 50 | + public static boolean isDisable(Integer status) { | |
| 51 | + return DISABLE.getStatus().equals(status); | |
| 52 | + } | |
| 53 | +} | |
| 0 | 54 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-api/src/main/java/cn/iocoder/yudao/module/iot/enums/product/IotProductScriptTypeEnum.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.enums.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.core.ArrayValuable; | |
| 4 | +import lombok.AllArgsConstructor; | |
| 5 | +import lombok.Getter; | |
| 6 | + | |
| 7 | +import java.util.Arrays; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * IoT 产品脚本类型枚举 | |
| 11 | + * | |
| 12 | + * @author 芋道源码 | |
| 13 | + */ | |
| 14 | +@Getter | |
| 15 | +@AllArgsConstructor | |
| 16 | +public enum IotProductScriptTypeEnum implements ArrayValuable<Integer> { | |
| 17 | + | |
| 18 | + PROPERTY_PARSER(1, "property_parser", "属性解析"), | |
| 19 | + EVENT_PARSER(2, "event_parser", "事件解析"), | |
| 20 | + COMMAND_ENCODER(3, "command_encoder", "命令编码"), | |
| 21 | + ; | |
| 22 | + | |
| 23 | + public static final Integer[] ARRAYS = Arrays.stream(values()).map(IotProductScriptTypeEnum::getCode) | |
| 24 | + .toArray(Integer[]::new); | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * 编码 | |
| 28 | + */ | |
| 29 | + private final Integer code; | |
| 30 | + /** | |
| 31 | + * 类型 | |
| 32 | + */ | |
| 33 | + private final String type; | |
| 34 | + /** | |
| 35 | + * 名称 | |
| 36 | + */ | |
| 37 | + private final String name; | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + public Integer[] array() { | |
| 41 | + return ARRAYS; | |
| 42 | + } | |
| 43 | + | |
| 44 | + public static IotProductScriptTypeEnum getByCode(Integer code) { | |
| 45 | + return Arrays.stream(values()) | |
| 46 | + .filter(type -> type.getCode().equals(code)) | |
| 47 | + .findFirst() | |
| 48 | + .orElse(null); | |
| 49 | + } | |
| 50 | +} | |
| 0 | 51 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/pom.xml
| ... | ... | @@ -69,6 +69,13 @@ |
| 69 | 69 | <artifactId>yudao-spring-boot-starter-excel</artifactId> |
| 70 | 70 | </dependency> |
| 71 | 71 | |
| 72 | + <!-- 脚本插件相关 --> | |
| 73 | + <dependency> | |
| 74 | + <groupId>cn.iocoder.boot</groupId> | |
| 75 | + <artifactId>yudao-module-iot-plugin-script</artifactId> | |
| 76 | + <version>${revision}</version> | |
| 77 | + </dependency> | |
| 78 | + | |
| 72 | 79 | <!-- 消息队列相关 --> |
| 73 | 80 | <dependency> |
| 74 | 81 | <groupId>org.apache.rocketmq</groupId> |
| ... | ... | @@ -87,7 +94,7 @@ |
| 87 | 94 | </dependency> |
| 88 | 95 | |
| 89 | 96 | <dependency> |
| 90 | - <groupId>org.pf4j</groupId> <!-- PF4J:内置插件机制 --> | |
| 97 | + <groupId>org.pf4j</groupId> <!-- PF4J:内置插件机制 --> | |
| 91 | 98 | <artifactId>pf4j-spring</artifactId> |
| 92 | 99 | </dependency> |
| 93 | 100 | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/IotProductScriptController.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.pojo.CommonResult; | |
| 4 | +import cn.iocoder.yudao.framework.common.pojo.PageResult; | |
| 5 | +import cn.iocoder.yudao.framework.common.util.object.BeanUtils; | |
| 6 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.*; | |
| 7 | +import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductScriptDO; | |
| 8 | +import cn.iocoder.yudao.module.iot.service.product.IotProductScriptService; | |
| 9 | +import io.swagger.v3.oas.annotations.Operation; | |
| 10 | +import io.swagger.v3.oas.annotations.Parameter; | |
| 11 | +import io.swagger.v3.oas.annotations.tags.Tag; | |
| 12 | +import jakarta.annotation.Resource; | |
| 13 | +import jakarta.validation.Valid; | |
| 14 | +import org.springframework.security.access.prepost.PreAuthorize; | |
| 15 | +import org.springframework.validation.annotation.Validated; | |
| 16 | +import org.springframework.web.bind.annotation.*; | |
| 17 | + | |
| 18 | +import java.util.List; | |
| 19 | + | |
| 20 | +import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; | |
| 21 | + | |
| 22 | +@Tag(name = "管理后台 - IoT 产品脚本信息") | |
| 23 | +@RestController | |
| 24 | +@RequestMapping("/iot/product-script") | |
| 25 | +@Validated | |
| 26 | +public class IotProductScriptController { | |
| 27 | + | |
| 28 | + @Resource | |
| 29 | + private IotProductScriptService productScriptService; | |
| 30 | + | |
| 31 | + @PostMapping("/create") | |
| 32 | + @Operation(summary = "创建产品脚本") | |
| 33 | + @PreAuthorize("@ss.hasPermission('iot:product-script:create')") | |
| 34 | + public CommonResult<Long> createProductScript(@Valid @RequestBody IotProductScriptSaveReqVO createReqVO) { | |
| 35 | + return success(productScriptService.createProductScript(createReqVO)); | |
| 36 | + } | |
| 37 | + | |
| 38 | + @PutMapping("/update") | |
| 39 | + @Operation(summary = "更新产品脚本") | |
| 40 | + @PreAuthorize("@ss.hasPermission('iot:product-script:update')") | |
| 41 | + public CommonResult<Boolean> updateProductScript(@Valid @RequestBody IotProductScriptSaveReqVO updateReqVO) { | |
| 42 | + productScriptService.updateProductScript(updateReqVO); | |
| 43 | + return success(true); | |
| 44 | + } | |
| 45 | + | |
| 46 | + @DeleteMapping("/delete") | |
| 47 | + @Operation(summary = "删除产品脚本") | |
| 48 | + @Parameter(name = "id", description = "编号", required = true) | |
| 49 | + @PreAuthorize("@ss.hasPermission('iot:product-script:delete')") | |
| 50 | + public CommonResult<Boolean> deleteProductScript(@RequestParam("id") Long id) { | |
| 51 | + productScriptService.deleteProductScript(id); | |
| 52 | + return success(true); | |
| 53 | + } | |
| 54 | + | |
| 55 | + @GetMapping("/get") | |
| 56 | + @Operation(summary = "获得产品脚本详情") | |
| 57 | + @Parameter(name = "id", description = "编号", required = true, example = "1024") | |
| 58 | + @PreAuthorize("@ss.hasPermission('iot:product-script:query')") | |
| 59 | + public CommonResult<IotProductScriptRespVO> getProductScript(@RequestParam("id") Long id) { | |
| 60 | + IotProductScriptDO productScript = productScriptService.getProductScript(id); | |
| 61 | + return success(BeanUtils.toBean(productScript, IotProductScriptRespVO.class)); | |
| 62 | + } | |
| 63 | + | |
| 64 | + @GetMapping("/list-by-product") | |
| 65 | + @Operation(summary = "获得产品的脚本列表") | |
| 66 | + @Parameter(name = "productId", description = "产品编号", required = true, example = "1024") | |
| 67 | + @PreAuthorize("@ss.hasPermission('iot:product-script:query')") | |
| 68 | + public CommonResult<List<IotProductScriptRespVO>> getProductScriptListByProductId( | |
| 69 | + @RequestParam("productId") Long productId) { | |
| 70 | + List<IotProductScriptDO> list = productScriptService.getProductScriptListByProductId(productId); | |
| 71 | + return success(BeanUtils.toBean(list, IotProductScriptRespVO.class)); | |
| 72 | + } | |
| 73 | + | |
| 74 | + @GetMapping("/page") | |
| 75 | + @Operation(summary = "获得产品脚本分页") | |
| 76 | + @PreAuthorize("@ss.hasPermission('iot:product-script:query')") | |
| 77 | + public CommonResult<PageResult<IotProductScriptRespVO>> getProductScriptPage( | |
| 78 | + @Valid IotProductScriptPageReqVO pageReqVO) { | |
| 79 | + PageResult<IotProductScriptDO> pageResult = productScriptService.getProductScriptPage(pageReqVO); | |
| 80 | + return success(BeanUtils.toBean(pageResult, IotProductScriptRespVO.class)); | |
| 81 | + } | |
| 82 | + | |
| 83 | + @PostMapping("/test") | |
| 84 | + @Operation(summary = "测试产品脚本") | |
| 85 | + @PreAuthorize("@ss.hasPermission('iot:product-script:test')") | |
| 86 | + public CommonResult<IotProductScriptTestRespVO> testProductScript( | |
| 87 | + @Valid @RequestBody IotProductScriptTestReqVO testReqVO) { | |
| 88 | + return success(productScriptService.testProductScript(testReqVO)); | |
| 89 | + } | |
| 90 | + | |
| 91 | + @PutMapping("/update-status") | |
| 92 | + @Operation(summary = "更新产品脚本状态") | |
| 93 | + @PreAuthorize("@ss.hasPermission('iot:product-script:update')") | |
| 94 | + public CommonResult<Boolean> updateProductScriptStatus( | |
| 95 | + @Valid @RequestBody IotProductScriptUpdateStatusReqVO updateStatusReqVO) { | |
| 96 | + productScriptService.updateProductScriptStatus(updateStatusReqVO.getId(), updateStatusReqVO.getStatus()); | |
| 97 | + return success(true); | |
| 98 | + } | |
| 99 | +} | |
| 0 | 100 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptPageReqVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.pojo.PageParam; | |
| 4 | +import cn.iocoder.yudao.framework.common.validation.InEnum; | |
| 5 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptLanguageEnum; | |
| 6 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptStatusEnum; | |
| 7 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptTypeEnum; | |
| 8 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 9 | +import lombok.Data; | |
| 10 | +import lombok.EqualsAndHashCode; | |
| 11 | +import lombok.ToString; | |
| 12 | +import org.springframework.format.annotation.DateTimeFormat; | |
| 13 | + | |
| 14 | +import java.time.LocalDateTime; | |
| 15 | + | |
| 16 | +import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND; | |
| 17 | + | |
| 18 | +@Schema(description = "管理后台 - IoT 产品脚本信息分页 Request VO") | |
| 19 | +@Data | |
| 20 | +@EqualsAndHashCode(callSuper = true) | |
| 21 | +@ToString(callSuper = true) | |
| 22 | +public class IotProductScriptPageReqVO extends PageParam { | |
| 23 | + | |
| 24 | + @Schema(description = "产品ID", example = "28277") | |
| 25 | + private Long productId; | |
| 26 | + | |
| 27 | + @Schema(description = "产品唯一标识符") | |
| 28 | + private String productKey; | |
| 29 | + | |
| 30 | + @Schema(description = "脚本类型", example = "1") | |
| 31 | + @InEnum(IotProductScriptTypeEnum.class) | |
| 32 | + private Integer scriptType; | |
| 33 | + | |
| 34 | + @Schema(description = "脚本语言") | |
| 35 | + @InEnum(IotProductScriptLanguageEnum.class) | |
| 36 | + private String scriptLanguage; | |
| 37 | + | |
| 38 | + @Schema(description = "状态", example = "0") | |
| 39 | + @InEnum(IotProductScriptStatusEnum.class) | |
| 40 | + private Integer status; | |
| 41 | + | |
| 42 | + @Schema(description = "备注说明", example = "你说的对") | |
| 43 | + private String remark; | |
| 44 | + | |
| 45 | + @Schema(description = "最后测试时间") | |
| 46 | + @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) | |
| 47 | + private LocalDateTime[] lastTestTime; | |
| 48 | + | |
| 49 | + @Schema(description = "创建时间") | |
| 50 | + @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) | |
| 51 | + private LocalDateTime[] createTime; | |
| 52 | + | |
| 53 | +} | |
| 0 | 54 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptRespVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; | |
| 4 | +import com.alibaba.excel.annotation.ExcelProperty; | |
| 5 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 6 | +import lombok.Data; | |
| 7 | + | |
| 8 | +import java.time.LocalDateTime; | |
| 9 | + | |
| 10 | +@Schema(description = "管理后台 - IoT 产品脚本信息 Response VO") | |
| 11 | +@Data | |
| 12 | +@ExcelIgnoreUnannotated | |
| 13 | +public class IotProductScriptRespVO { | |
| 14 | + | |
| 15 | + @Schema(description = "主键", requiredMode = Schema.RequiredMode.REQUIRED, example = "26565") | |
| 16 | + @ExcelProperty("主键") | |
| 17 | + private Long id; | |
| 18 | + | |
| 19 | + @Schema(description = "产品ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "28277") | |
| 20 | + @ExcelProperty("产品ID") | |
| 21 | + private Long productId; | |
| 22 | + | |
| 23 | + @Schema(description = "产品唯一标识符", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 24 | + @ExcelProperty("产品唯一标识符") | |
| 25 | + private String productKey; | |
| 26 | + | |
| 27 | + @Schema(description = "脚本类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") | |
| 28 | + @ExcelProperty("脚本类型") | |
| 29 | + private Integer scriptType; | |
| 30 | + | |
| 31 | + @Schema(description = "脚本内容", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 32 | + @ExcelProperty("脚本内容") | |
| 33 | + private String scriptContent; | |
| 34 | + | |
| 35 | + @Schema(description = "脚本语言", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 36 | + @ExcelProperty("脚本语言") | |
| 37 | + private String scriptLanguage; | |
| 38 | + | |
| 39 | + @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "0") | |
| 40 | + @ExcelProperty("状态") | |
| 41 | + private Integer status; | |
| 42 | + | |
| 43 | + @Schema(description = "备注说明", example = "你说的对") | |
| 44 | + @ExcelProperty("备注说明") | |
| 45 | + private String remark; | |
| 46 | + | |
| 47 | + @Schema(description = "最后测试时间") | |
| 48 | + @ExcelProperty("最后测试时间") | |
| 49 | + private LocalDateTime lastTestTime; | |
| 50 | + | |
| 51 | + @Schema(description = "最后测试结果(0=失败 1=成功)") | |
| 52 | + @ExcelProperty("最后测试结果(0=失败 1=成功)") | |
| 53 | + private Integer lastTestResult; | |
| 54 | + | |
| 55 | + @Schema(description = "脚本版本号", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 56 | + @ExcelProperty("脚本版本号") | |
| 57 | + private Integer version; | |
| 58 | + | |
| 59 | + @Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 60 | + @ExcelProperty("创建时间") | |
| 61 | + private LocalDateTime createTime; | |
| 62 | + | |
| 63 | +} | |
| 0 | 64 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptSaveReqVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.validation.InEnum; | |
| 4 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptLanguageEnum; | |
| 5 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptStatusEnum; | |
| 6 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptTypeEnum; | |
| 7 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 8 | +import jakarta.validation.constraints.NotEmpty; | |
| 9 | +import jakarta.validation.constraints.NotNull; | |
| 10 | +import lombok.Data; | |
| 11 | + | |
| 12 | +@Schema(description = "管理后台 - IoT 产品脚本信息新增/修改 Request VO") | |
| 13 | +@Data | |
| 14 | +public class IotProductScriptSaveReqVO { | |
| 15 | + | |
| 16 | + @Schema(description = "主键", requiredMode = Schema.RequiredMode.REQUIRED, example = "26565") | |
| 17 | + private Long id; | |
| 18 | + | |
| 19 | + @Schema(description = "产品ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "28277") | |
| 20 | + @NotNull(message = "产品ID不能为空") | |
| 21 | + private Long productId; | |
| 22 | + | |
| 23 | + @Schema(description = "产品唯一标识符", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 24 | + @NotEmpty(message = "产品唯一标识符不能为空") | |
| 25 | + private String productKey; | |
| 26 | + | |
| 27 | + @Schema(description = "脚本类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") | |
| 28 | + @NotNull(message = "脚本类型不能为空") | |
| 29 | + @InEnum(IotProductScriptTypeEnum.class) | |
| 30 | + private Integer scriptType; | |
| 31 | + | |
| 32 | + @Schema(description = "脚本内容", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 33 | + @NotEmpty(message = "脚本内容不能为空") | |
| 34 | + private String scriptContent; | |
| 35 | + | |
| 36 | + @Schema(description = "脚本语言", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 37 | + @NotEmpty(message = "脚本语言不能为空") | |
| 38 | + @InEnum(IotProductScriptLanguageEnum.class) | |
| 39 | + private String scriptLanguage; | |
| 40 | + | |
| 41 | + @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "0") | |
| 42 | + @NotNull(message = "状态不能为空") | |
| 43 | + @InEnum(IotProductScriptStatusEnum.class) | |
| 44 | + private Integer status; | |
| 45 | + | |
| 46 | + @Schema(description = "备注说明", example = "你说的对") | |
| 47 | + private String remark; | |
| 48 | + | |
| 49 | +} | |
| 0 | 50 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptTestReqVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.validation.InEnum; | |
| 4 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptTypeEnum; | |
| 5 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 6 | +import jakarta.validation.constraints.NotEmpty; | |
| 7 | +import jakarta.validation.constraints.NotNull; | |
| 8 | +import lombok.Data; | |
| 9 | + | |
| 10 | +@Schema(description = "管理后台 - IoT 产品脚本测试 Request VO") | |
| 11 | +@Data | |
| 12 | +public class IotProductScriptTestReqVO { | |
| 13 | + | |
| 14 | + @Schema(description = "脚本ID,如果已保存脚本则传入", example = "1024") | |
| 15 | + private Long id; | |
| 16 | + | |
| 17 | + @Schema(description = "产品ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "2048") | |
| 18 | + @NotNull(message = "产品ID不能为空") | |
| 19 | + private Long productId; | |
| 20 | + | |
| 21 | + @Schema(description = "脚本类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1") | |
| 22 | + @NotNull(message = "脚本类型不能为空") | |
| 23 | + @InEnum(value = IotProductScriptTypeEnum.class) | |
| 24 | + private Integer scriptType; | |
| 25 | + | |
| 26 | + @Schema(description = "脚本内容", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 27 | + @NotEmpty(message = "脚本内容不能为空") | |
| 28 | + private String scriptContent; | |
| 29 | + | |
| 30 | + @Schema(description = "脚本语言", requiredMode = Schema.RequiredMode.REQUIRED, example = "javascript") | |
| 31 | + @NotEmpty(message = "脚本语言不能为空") | |
| 32 | + private String scriptLanguage; | |
| 33 | + | |
| 34 | + @Schema(description = "测试输入数据", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 35 | + @NotEmpty(message = "测试输入数据不能为空") | |
| 36 | + private String testInput; | |
| 37 | + | |
| 38 | +} | |
| 0 | 39 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptTestRespVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 4 | +import lombok.Data; | |
| 5 | + | |
| 6 | +@Schema(description = "管理后台 - IoT 产品脚本测试 Response VO") | |
| 7 | +@Data | |
| 8 | +public class IotProductScriptTestRespVO { | |
| 9 | + | |
| 10 | + @Schema(description = "测试是否成功", requiredMode = Schema.RequiredMode.REQUIRED) | |
| 11 | + private Boolean success; | |
| 12 | + | |
| 13 | + @Schema(description = "测试结果输出") | |
| 14 | + private Object output; | |
| 15 | + | |
| 16 | + @Schema(description = "错误消息,失败时返回") | |
| 17 | + private String errorMessage; | |
| 18 | + | |
| 19 | + @Schema(description = "执行耗时(毫秒)") | |
| 20 | + private Long executionTimeMs; | |
| 21 | + | |
| 22 | + // 静态工厂方法 - 成功 | |
| 23 | + public static IotProductScriptTestRespVO success(Object output, Long executionTimeMs) { | |
| 24 | + IotProductScriptTestRespVO respVO = new IotProductScriptTestRespVO(); | |
| 25 | + respVO.setSuccess(true); | |
| 26 | + respVO.setOutput(output); | |
| 27 | + respVO.setExecutionTimeMs(executionTimeMs); | |
| 28 | + return respVO; | |
| 29 | + } | |
| 30 | + | |
| 31 | + // 静态工厂方法 - 失败 | |
| 32 | + public static IotProductScriptTestRespVO error(String errorMessage, Long executionTimeMs) { | |
| 33 | + IotProductScriptTestRespVO respVO = new IotProductScriptTestRespVO(); | |
| 34 | + respVO.setSuccess(false); | |
| 35 | + respVO.setErrorMessage(errorMessage); | |
| 36 | + respVO.setExecutionTimeMs(executionTimeMs); | |
| 37 | + return respVO; | |
| 38 | + } | |
| 39 | +} | |
| 0 | 40 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/product/vo/script/IotProductScriptUpdateStatusReqVO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.controller.admin.product.vo.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.validation.InEnum; | |
| 4 | +import cn.iocoder.yudao.module.iot.enums.product.IotProductScriptStatusEnum; | |
| 5 | +import io.swagger.v3.oas.annotations.media.Schema; | |
| 6 | +import jakarta.validation.constraints.NotNull; | |
| 7 | +import lombok.Data; | |
| 8 | + | |
| 9 | +@Schema(description = "管理后台 - IoT 产品脚本状态更新 Request VO") | |
| 10 | +@Data | |
| 11 | +public class IotProductScriptUpdateStatusReqVO { | |
| 12 | + | |
| 13 | + @Schema(description = "脚本ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024") | |
| 14 | + @NotNull(message = "脚本ID不能为空") | |
| 15 | + private Long id; | |
| 16 | + | |
| 17 | + @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "0") | |
| 18 | + @NotNull(message = "状态不能为空") | |
| 19 | + @InEnum(IotProductScriptStatusEnum.class) | |
| 20 | + private Integer status; | |
| 21 | + | |
| 22 | +} | |
| 0 | 23 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/IotRuleSceneController.java
| ... | ... | @@ -20,6 +20,7 @@ import org.springframework.web.bind.annotation.*; |
| 20 | 20 | |
| 21 | 21 | import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; |
| 22 | 22 | |
| 23 | +// TODO @芋艿:规则场景 要不要,统一改成 场景联动 | |
| 23 | 24 | @Tag(name = "管理后台 - IoT 规则场景") |
| 24 | 25 | @RestController |
| 25 | 26 | @RequestMapping("/iot/rule-scene") | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/IotRuleScenePageReqVO.java
| 1 | 1 | package cn.iocoder.yudao.module.iot.controller.admin.rule.vo.scene; |
| 2 | 2 | |
| 3 | +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; | |
| 3 | 4 | import cn.iocoder.yudao.framework.common.pojo.PageParam; |
| 5 | +import cn.iocoder.yudao.framework.common.validation.InEnum; | |
| 4 | 6 | import io.swagger.v3.oas.annotations.media.Schema; |
| 5 | 7 | import lombok.Data; |
| 6 | 8 | import lombok.EqualsAndHashCode; |
| ... | ... | @@ -24,6 +26,7 @@ public class IotRuleScenePageReqVO extends PageParam { |
| 24 | 26 | private String description; |
| 25 | 27 | |
| 26 | 28 | @Schema(description = "场景状态", example = "1") |
| 29 | + @InEnum(CommonStatusEnum.class) | |
| 27 | 30 | private Integer status; |
| 28 | 31 | |
| 29 | 32 | @Schema(description = "创建时间") | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/config/IotRuleSceneActionConfig.java
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/config/IotRuleSceneActionDeviceControl.java
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/config/IotRuleSceneTriggerCondition.java
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/config/IotRuleSceneTriggerConditionParameter.java
| ... | ... | @@ -4,6 +4,7 @@ import cn.iocoder.yudao.module.iot.dal.dataobject.thingmodel.IotThingModelDO; |
| 4 | 4 | import cn.iocoder.yudao.module.iot.enums.rule.IotRuleSceneTriggerConditionParameterOperatorEnum; |
| 5 | 5 | import lombok.Data; |
| 6 | 6 | |
| 7 | +// TODO @puhui999:这个要不内嵌到 IoTRuleSceneDO 里面? | |
| 7 | 8 | /** |
| 8 | 9 | * 触发条件参数 |
| 9 | 10 | * | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/rule/vo/scene/config/IotRuleSceneTriggerConfig.java
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/controller/admin/thingmodel/IotThingModelController.java
| ... | ... | @@ -61,15 +61,15 @@ public class IotThingModelController { |
| 61 | 61 | return success(BeanUtils.toBean(thingModel, IotThingModelRespVO.class)); |
| 62 | 62 | } |
| 63 | 63 | |
| 64 | + // TODO @puhui999:要不叫 get-tsl,去掉 product-id;后续,把 | |
| 64 | 65 | @GetMapping("/tsl-by-product-id") |
| 65 | 66 | @Operation(summary = "获得产品物模型 TSL") |
| 66 | - @Parameter(name = "productId", description = "产品ID", required = true, example = "1024") | |
| 67 | + @Parameter(name = "productId", description = "产品 ID", required = true, example = "1024") | |
| 67 | 68 | @PreAuthorize("@ss.hasPermission('iot:thing-model:query')") |
| 68 | 69 | public CommonResult<IotThingModelTSLRespVO> getThingModelTslByProductId(@RequestParam("productId") Long productId) { |
| 69 | 70 | return success(thingModelService.getThingModelTslByProductId(productId)); |
| 70 | 71 | } |
| 71 | 72 | |
| 72 | - // TODO @puhui @super:getThingModelListByProductId 和 getThingModelListByProductId 可以融合么? | |
| 73 | 73 | @GetMapping("/list") |
| 74 | 74 | @Operation(summary = "获得产品物模型列表") |
| 75 | 75 | @PreAuthorize("@ss.hasPermission('iot:thing-model:query')") | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/dal/dataobject/product/IotProductScriptDO.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.dal.dataobject.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO; | |
| 4 | +import com.baomidou.mybatisplus.annotation.KeySequence; | |
| 5 | +import com.baomidou.mybatisplus.annotation.TableId; | |
| 6 | +import com.baomidou.mybatisplus.annotation.TableName; | |
| 7 | +import lombok.*; | |
| 8 | + | |
| 9 | +import java.time.LocalDateTime; | |
| 10 | + | |
| 11 | +/** | |
| 12 | + * IoT 产品脚本信息 DO | |
| 13 | + * | |
| 14 | + * @author 芋道源码 | |
| 15 | + */ | |
| 16 | +@TableName("iot_product_script") | |
| 17 | +@KeySequence("iot_product_script_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。 | |
| 18 | +@Data | |
| 19 | +@EqualsAndHashCode(callSuper = true) | |
| 20 | +@ToString(callSuper = true) | |
| 21 | +@Builder | |
| 22 | +@NoArgsConstructor | |
| 23 | +@AllArgsConstructor | |
| 24 | +public class IotProductScriptDO extends BaseDO { | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * 主键 | |
| 28 | + */ | |
| 29 | + @TableId | |
| 30 | + private Long id; | |
| 31 | + /** | |
| 32 | + * 产品ID | |
| 33 | + */ | |
| 34 | + private Long productId; | |
| 35 | + /** | |
| 36 | + * 产品唯一标识符 | |
| 37 | + */ | |
| 38 | + private String productKey; | |
| 39 | + /** | |
| 40 | + * 脚本类型(property_parser=属性解析,event_parser=事件解析,command_encoder=命令编码) | |
| 41 | + */ | |
| 42 | + private String scriptType; | |
| 43 | + /** | |
| 44 | + * 脚本内容 | |
| 45 | + */ | |
| 46 | + private String scriptContent; | |
| 47 | + /** | |
| 48 | + * 脚本语言 | |
| 49 | + */ | |
| 50 | + private String scriptLanguage; | |
| 51 | + /** | |
| 52 | + * 状态(0=禁用 1=启用) | |
| 53 | + */ | |
| 54 | + private Integer status; | |
| 55 | + /** | |
| 56 | + * 备注说明 | |
| 57 | + */ | |
| 58 | + private String remark; | |
| 59 | + /** | |
| 60 | + * 最后测试时间 | |
| 61 | + */ | |
| 62 | + private LocalDateTime lastTestTime; | |
| 63 | + /** | |
| 64 | + * 最后测试结果(0=失败 1=成功) | |
| 65 | + */ | |
| 66 | + private Integer lastTestResult; | |
| 67 | + /** | |
| 68 | + * 脚本版本号 | |
| 69 | + */ | |
| 70 | + private Integer version; | |
| 71 | + | |
| 72 | +} | |
| 0 | 73 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/dal/mysql/product/IotProductScriptMapper.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.dal.mysql.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.pojo.PageResult; | |
| 4 | +import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; | |
| 5 | +import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; | |
| 6 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptPageReqVO; | |
| 7 | +import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductScriptDO; | |
| 8 | +import org.apache.ibatis.annotations.Mapper; | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * IoT 产品脚本信息 Mapper | |
| 12 | + * | |
| 13 | + * @author 芋道源码 | |
| 14 | + */ | |
| 15 | +@Mapper | |
| 16 | +public interface IotProductScriptMapper extends BaseMapperX<IotProductScriptDO> { | |
| 17 | + | |
| 18 | + default PageResult<IotProductScriptDO> selectPage(IotProductScriptPageReqVO reqVO) { | |
| 19 | + return selectPage(reqVO, new LambdaQueryWrapperX<IotProductScriptDO>() | |
| 20 | + .eqIfPresent(IotProductScriptDO::getProductId, reqVO.getProductId()) | |
| 21 | + .eqIfPresent(IotProductScriptDO::getProductKey, reqVO.getProductKey()) | |
| 22 | + .eqIfPresent(IotProductScriptDO::getScriptType, reqVO.getScriptType()) | |
| 23 | + .eqIfPresent(IotProductScriptDO::getScriptLanguage, reqVO.getScriptLanguage()) | |
| 24 | + .eqIfPresent(IotProductScriptDO::getStatus, reqVO.getStatus()) | |
| 25 | + .eqIfPresent(IotProductScriptDO::getRemark, reqVO.getRemark()) | |
| 26 | + .betweenIfPresent(IotProductScriptDO::getLastTestTime, reqVO.getLastTestTime()) | |
| 27 | + .betweenIfPresent(IotProductScriptDO::getCreateTime, reqVO.getCreateTime()) | |
| 28 | + .orderByDesc(IotProductScriptDO::getId)); | |
| 29 | + } | |
| 30 | + | |
| 31 | +} | |
| 0 | 32 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/product/IotProductScriptService.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.service.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.pojo.PageResult; | |
| 4 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptPageReqVO; | |
| 5 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptSaveReqVO; | |
| 6 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptTestReqVO; | |
| 7 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptTestRespVO; | |
| 8 | +import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductScriptDO; | |
| 9 | +import jakarta.validation.Valid; | |
| 10 | + | |
| 11 | +import java.util.List; | |
| 12 | + | |
| 13 | +/** | |
| 14 | + * IoT 产品脚本信息 Service 接口 | |
| 15 | + * | |
| 16 | + * @author 芋道源码 | |
| 17 | + */ | |
| 18 | +public interface IotProductScriptService { | |
| 19 | + | |
| 20 | + /** | |
| 21 | + * 创建IoT 产品脚本信息 | |
| 22 | + * | |
| 23 | + * @param createReqVO 创建信息 | |
| 24 | + * @return 编号 | |
| 25 | + */ | |
| 26 | + Long createProductScript(@Valid IotProductScriptSaveReqVO createReqVO); | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * 更新IoT 产品脚本信息 | |
| 30 | + * | |
| 31 | + * @param updateReqVO 更新信息 | |
| 32 | + */ | |
| 33 | + void updateProductScript(@Valid IotProductScriptSaveReqVO updateReqVO); | |
| 34 | + | |
| 35 | + /** | |
| 36 | + * 删除IoT 产品脚本信息 | |
| 37 | + * | |
| 38 | + * @param id 编号 | |
| 39 | + */ | |
| 40 | + void deleteProductScript(Long id); | |
| 41 | + | |
| 42 | + /** | |
| 43 | + * 获得IoT 产品脚本信息 | |
| 44 | + * | |
| 45 | + * @param id 编号 | |
| 46 | + * @return IoT 产品脚本信息 | |
| 47 | + */ | |
| 48 | + IotProductScriptDO getProductScript(Long id); | |
| 49 | + | |
| 50 | + /** | |
| 51 | + * 获得IoT 产品脚本信息分页 | |
| 52 | + * | |
| 53 | + * @param pageReqVO 分页查询 | |
| 54 | + * @return IoT 产品脚本信息分页 | |
| 55 | + */ | |
| 56 | + PageResult<IotProductScriptDO> getProductScriptPage(IotProductScriptPageReqVO pageReqVO); | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * 获取产品的脚本列表 | |
| 60 | + * | |
| 61 | + * @param productId 产品ID | |
| 62 | + * @return 脚本列表 | |
| 63 | + */ | |
| 64 | + List<IotProductScriptDO> getProductScriptListByProductId(Long productId); | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * 测试产品脚本 | |
| 68 | + * | |
| 69 | + * @param testReqVO 测试请求 | |
| 70 | + * @return 测试结果 | |
| 71 | + */ | |
| 72 | + IotProductScriptTestRespVO testProductScript(@Valid IotProductScriptTestReqVO testReqVO); | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * 更新产品脚本状态 | |
| 76 | + * | |
| 77 | + * @param id 脚本ID | |
| 78 | + * @param status 状态 | |
| 79 | + */ | |
| 80 | + void updateProductScriptStatus(Long id, Integer status); | |
| 81 | + | |
| 82 | +} | |
| 0 | 83 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/product/IotProductScriptServiceImpl.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.service.product; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.framework.common.pojo.PageResult; | |
| 4 | +import cn.iocoder.yudao.framework.common.util.object.BeanUtils; | |
| 5 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptPageReqVO; | |
| 6 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptSaveReqVO; | |
| 7 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptTestReqVO; | |
| 8 | +import cn.iocoder.yudao.module.iot.controller.admin.product.vo.script.IotProductScriptTestRespVO; | |
| 9 | +import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductDO; | |
| 10 | +import cn.iocoder.yudao.module.iot.dal.dataobject.product.IotProductScriptDO; | |
| 11 | +import cn.iocoder.yudao.module.iot.dal.mysql.product.IotProductScriptMapper; | |
| 12 | +import cn.iocoder.yudao.module.iot.plugin.script.context.PluginScriptContext; | |
| 13 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptService; | |
| 14 | +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; | |
| 15 | +import jakarta.annotation.Resource; | |
| 16 | +import lombok.extern.slf4j.Slf4j; | |
| 17 | +import org.springframework.stereotype.Service; | |
| 18 | +import org.springframework.validation.annotation.Validated; | |
| 19 | + | |
| 20 | +import java.time.LocalDateTime; | |
| 21 | +import java.util.HashMap; | |
| 22 | +import java.util.List; | |
| 23 | +import java.util.Map; | |
| 24 | + | |
| 25 | +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; | |
| 26 | +import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.PRODUCT_NOT_EXISTS; | |
| 27 | +import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.PRODUCT_SCRIPT_NOT_EXISTS; | |
| 28 | + | |
| 29 | +/** | |
| 30 | + * IoT 产品脚本信息 Service 实现类 | |
| 31 | + * | |
| 32 | + * @author 芋道源码 | |
| 33 | + */ | |
| 34 | +@Service | |
| 35 | +@Validated | |
| 36 | +@Slf4j | |
| 37 | +public class IotProductScriptServiceImpl implements IotProductScriptService { | |
| 38 | + | |
| 39 | + @Resource | |
| 40 | + private IotProductScriptMapper productScriptMapper; | |
| 41 | + | |
| 42 | + @Resource | |
| 43 | + private IotProductService productService; | |
| 44 | + | |
| 45 | + @Resource | |
| 46 | + private ScriptService scriptService; | |
| 47 | + | |
| 48 | + @Override | |
| 49 | + public Long createProductScript(IotProductScriptSaveReqVO createReqVO) { | |
| 50 | + // 验证产品是否存在 | |
| 51 | + validateProductExists(createReqVO.getProductId()); | |
| 52 | + | |
| 53 | + // 插入 | |
| 54 | + IotProductScriptDO productScript = BeanUtils.toBean(createReqVO, IotProductScriptDO.class); | |
| 55 | + // 初始化版本为1 | |
| 56 | + productScript.setVersion(1); | |
| 57 | + // 初始化测试相关字段 | |
| 58 | + productScript.setLastTestResult(null); | |
| 59 | + productScript.setLastTestTime(null); | |
| 60 | + productScriptMapper.insert(productScript); | |
| 61 | + // 返回 | |
| 62 | + return productScript.getId(); | |
| 63 | + } | |
| 64 | + | |
| 65 | + @Override | |
| 66 | + public void updateProductScript(IotProductScriptSaveReqVO updateReqVO) { | |
| 67 | + // 校验存在 | |
| 68 | + validateProductScriptExists(updateReqVO.getId()); | |
| 69 | + | |
| 70 | + // 获取旧的记录,保留版本号和测试信息 | |
| 71 | + IotProductScriptDO oldScript = getProductScript(updateReqVO.getId()); | |
| 72 | + | |
| 73 | + // 更新 | |
| 74 | + IotProductScriptDO updateObj = BeanUtils.toBean(updateReqVO, IotProductScriptDO.class); | |
| 75 | + // 更新版本号 | |
| 76 | + updateObj.setVersion(oldScript.getVersion() + 1); | |
| 77 | + // 保留测试相关信息 | |
| 78 | + updateObj.setLastTestTime(oldScript.getLastTestTime()); | |
| 79 | + updateObj.setLastTestResult(oldScript.getLastTestResult()); | |
| 80 | + productScriptMapper.updateById(updateObj); | |
| 81 | + } | |
| 82 | + | |
| 83 | + @Override | |
| 84 | + public void deleteProductScript(Long id) { | |
| 85 | + // 校验存在 | |
| 86 | + validateProductScriptExists(id); | |
| 87 | + // 删除 | |
| 88 | + productScriptMapper.deleteById(id); | |
| 89 | + } | |
| 90 | + | |
| 91 | + private void validateProductScriptExists(Long id) { | |
| 92 | + if (productScriptMapper.selectById(id) == null) { | |
| 93 | + throw exception(PRODUCT_SCRIPT_NOT_EXISTS); | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 97 | + private void validateProductExists(Long productId) { | |
| 98 | + IotProductDO product = productService.getProduct(productId); | |
| 99 | + if (product == null) { | |
| 100 | + throw exception(PRODUCT_NOT_EXISTS); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + @Override | |
| 105 | + public IotProductScriptDO getProductScript(Long id) { | |
| 106 | + return productScriptMapper.selectById(id); | |
| 107 | + } | |
| 108 | + | |
| 109 | + @Override | |
| 110 | + public PageResult<IotProductScriptDO> getProductScriptPage(IotProductScriptPageReqVO pageReqVO) { | |
| 111 | + return productScriptMapper.selectPage(pageReqVO); | |
| 112 | + } | |
| 113 | + | |
| 114 | + @Override | |
| 115 | + public List<IotProductScriptDO> getProductScriptListByProductId(Long productId) { | |
| 116 | + return productScriptMapper.selectList(new LambdaQueryWrapper<IotProductScriptDO>() | |
| 117 | + .eq(IotProductScriptDO::getProductId, productId) | |
| 118 | + .orderByDesc(IotProductScriptDO::getId)); | |
| 119 | + } | |
| 120 | + | |
| 121 | + @Override | |
| 122 | + public IotProductScriptTestRespVO testProductScript(IotProductScriptTestReqVO testReqVO) { | |
| 123 | + long startTime = System.currentTimeMillis(); | |
| 124 | + | |
| 125 | + try { | |
| 126 | + // 验证产品是否存在 | |
| 127 | + validateProductExists(testReqVO.getProductId()); | |
| 128 | + | |
| 129 | + // 根据ID获取已保存的脚本(如果有) | |
| 130 | + IotProductScriptDO existingScript = null; | |
| 131 | + if (testReqVO.getId() != null) { | |
| 132 | + existingScript = getProductScript(testReqVO.getId()); | |
| 133 | + } | |
| 134 | + | |
| 135 | + // 创建测试上下文 | |
| 136 | + PluginScriptContext context = new PluginScriptContext(); | |
| 137 | + IotProductDO product = productService.getProduct(testReqVO.getProductId()); | |
| 138 | + | |
| 139 | + // 设置设备上下文(使用产品信息,没有具体设备) | |
| 140 | + context.withDeviceContext(product.getProductKey(), null); | |
| 141 | + | |
| 142 | + // 设置输入参数 | |
| 143 | + Map<String, Object> params = new HashMap<>(); | |
| 144 | + params.put("input", testReqVO.getTestInput()); | |
| 145 | + params.put("productKey", product.getProductKey()); | |
| 146 | + params.put("scriptType", testReqVO.getScriptType()); | |
| 147 | + | |
| 148 | + // 根据脚本类型设置特定参数 | |
| 149 | + switch (testReqVO.getScriptType()) { | |
| 150 | + case 1: // PROPERTY_PARSER | |
| 151 | + params.put("method", "property"); | |
| 152 | + break; | |
| 153 | + case 2: // EVENT_PARSER | |
| 154 | + params.put("method", "event"); | |
| 155 | + params.put("identifier", "default"); | |
| 156 | + break; | |
| 157 | + case 3: // COMMAND_ENCODER | |
| 158 | + params.put("method", "command"); | |
| 159 | + break; | |
| 160 | + default: | |
| 161 | + // 默认不添加额外参数 | |
| 162 | + } | |
| 163 | + | |
| 164 | + // 添加所有参数到上下文 | |
| 165 | + for (Map.Entry<String, Object> entry : params.entrySet()) { | |
| 166 | + context.setParameter(entry.getKey(), entry.getValue()); | |
| 167 | + } | |
| 168 | + | |
| 169 | + // 执行脚本 | |
| 170 | + Object result = scriptService.executeScript( | |
| 171 | + testReqVO.getScriptLanguage(), | |
| 172 | + testReqVO.getScriptContent(), | |
| 173 | + context); | |
| 174 | + | |
| 175 | + // 更新测试结果(如果是已保存的脚本) | |
| 176 | + if (existingScript != null) { | |
| 177 | + IotProductScriptDO updateObj = new IotProductScriptDO(); | |
| 178 | + updateObj.setId(existingScript.getId()); | |
| 179 | + updateObj.setLastTestTime(LocalDateTime.now()); | |
| 180 | + updateObj.setLastTestResult(1); // 1表示成功 | |
| 181 | + productScriptMapper.updateById(updateObj); | |
| 182 | + } | |
| 183 | + | |
| 184 | + long executionTime = System.currentTimeMillis() - startTime; | |
| 185 | + return IotProductScriptTestRespVO.success(result, executionTime); | |
| 186 | + | |
| 187 | + } catch (Exception e) { | |
| 188 | + log.error("[testProductScript][测试脚本异常]", e); | |
| 189 | + | |
| 190 | + // 如果是已保存的脚本,更新测试失败状态 | |
| 191 | + if (testReqVO.getId() != null) { | |
| 192 | + try { | |
| 193 | + IotProductScriptDO updateObj = new IotProductScriptDO(); | |
| 194 | + updateObj.setId(testReqVO.getId()); | |
| 195 | + updateObj.setLastTestTime(LocalDateTime.now()); | |
| 196 | + updateObj.setLastTestResult(0); // 0表示失败 | |
| 197 | + productScriptMapper.updateById(updateObj); | |
| 198 | + } catch (Exception ex) { | |
| 199 | + log.error("[testProductScript][更新脚本测试结果异常]", ex); | |
| 200 | + } | |
| 201 | + } | |
| 202 | + | |
| 203 | + long executionTime = System.currentTimeMillis() - startTime; | |
| 204 | + return IotProductScriptTestRespVO.error(e.getMessage(), executionTime); | |
| 205 | + } | |
| 206 | + } | |
| 207 | + | |
| 208 | + @Override | |
| 209 | + public void updateProductScriptStatus(Long id, Integer status) { | |
| 210 | + // 校验存在 | |
| 211 | + validateProductScriptExists(id); | |
| 212 | + | |
| 213 | + // 更新状态 | |
| 214 | + IotProductScriptDO updateObj = new IotProductScriptDO(); | |
| 215 | + updateObj.setId(id); | |
| 216 | + updateObj.setStatus(status); | |
| 217 | + productScriptMapper.updateById(updateObj); | |
| 218 | + } | |
| 219 | +} | |
| 0 | 220 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-biz/src/main/java/cn/iocoder/yudao/module/iot/service/thingmodel/IotThingModelServiceImpl.java
| ... | ... | @@ -151,26 +151,27 @@ public class IotThingModelServiceImpl implements IotThingModelService { |
| 151 | 151 | return thingModelMapper.selectList(reqVO); |
| 152 | 152 | } |
| 153 | 153 | |
| 154 | + // TODO @puhui999:这个转换,放在 controller 貌似也行? | |
| 154 | 155 | @Override |
| 155 | 156 | public IotThingModelTSLRespVO getThingModelTslByProductId(Long productId) { |
| 156 | 157 | IotThingModelTSLRespVO tslRespVO = new IotThingModelTSLRespVO(); |
| 157 | 158 | // 1. 获得产品所有物模型定义 |
| 158 | - List<IotThingModelDO> thingModelList = thingModelMapper.selectListByProductId(productId); | |
| 159 | - if (CollUtil.isEmpty(thingModelList)) { | |
| 159 | + List<IotThingModelDO> thingModels = thingModelMapper.selectListByProductId(productId); | |
| 160 | + if (CollUtil.isEmpty(thingModels)) { | |
| 160 | 161 | return tslRespVO; |
| 161 | 162 | } |
| 162 | 163 | |
| 163 | 164 | // 2.1 设置公共部分参数 |
| 164 | - IotThingModelDO thingModel = thingModelList.get(0); | |
| 165 | + IotThingModelDO thingModel = thingModels.get(0); | |
| 165 | 166 | tslRespVO.setProductId(thingModel.getProductId()).setProductKey(thingModel.getProductKey()); |
| 166 | 167 | // 2.2 处理属性列表 |
| 167 | - tslRespVO.setProperties(convertList(filterList(thingModelList, item -> | |
| 168 | + tslRespVO.setProperties(convertList(filterList(thingModels, item -> | |
| 168 | 169 | ObjUtil.equal(IotThingModelTypeEnum.PROPERTY.getType(), item.getType())), IotThingModelDO::getProperty)); |
| 169 | 170 | // 2.3 处理服务列表 |
| 170 | - tslRespVO.setServices(convertList(filterList(thingModelList, item -> | |
| 171 | + tslRespVO.setServices(convertList(filterList(thingModels, item -> | |
| 171 | 172 | ObjUtil.equal(IotThingModelTypeEnum.SERVICE.getType(), item.getType())), IotThingModelDO::getService)); |
| 172 | 173 | // 2.4 处理事件列表 |
| 173 | - tslRespVO.setEvents(convertList(filterList(thingModelList, item -> | |
| 174 | + tslRespVO.setEvents(convertList(filterList(thingModels, item -> | |
| 174 | 175 | ObjUtil.equal(IotThingModelTypeEnum.EVENT.getType(), item.getType())), IotThingModelDO::getEvent)); |
| 175 | 176 | return tslRespVO; |
| 176 | 177 | } | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/pom.xml
| ... | ... | @@ -9,6 +9,7 @@ |
| 9 | 9 | </parent> |
| 10 | 10 | <modules> |
| 11 | 11 | <module>yudao-module-iot-plugin-common</module> |
| 12 | + <module>yudao-module-iot-plugin-script</module> | |
| 12 | 13 | <module>yudao-module-iot-plugin-http</module> |
| 13 | 14 | <module>yudao-module-iot-plugin-mqtt</module> |
| 14 | 15 | <module>yudao-module-iot-plugin-emqx</module> | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/pom.xml
| ... | ... | @@ -94,34 +94,34 @@ |
| 94 | 94 | </archive> |
| 95 | 95 | </configuration> |
| 96 | 96 | </plugin> |
| 97 | -<!-- <plugin>--> | |
| 98 | -<!-- <groupId>org.apache.maven.plugins</groupId>--> | |
| 99 | -<!-- <artifactId>maven-shade-plugin</artifactId>--> | |
| 100 | -<!-- <version>3.6.0</version>--> | |
| 101 | -<!-- <executions>--> | |
| 102 | -<!-- <execution>--> | |
| 103 | -<!-- <phase>package</phase>--> | |
| 104 | -<!-- <goals>--> | |
| 105 | -<!-- <goal>shade</goal>--> | |
| 106 | -<!-- </goals>--> | |
| 107 | -<!-- <configuration>--> | |
| 108 | -<!-- <minimizeJar>true</minimizeJar>--> | |
| 109 | -<!-- </configuration>--> | |
| 110 | -<!-- </execution>--> | |
| 111 | -<!-- </executions>--> | |
| 112 | -<!-- <configuration>--> | |
| 113 | -<!-- <archive>--> | |
| 114 | -<!-- <manifestEntries>--> | |
| 115 | -<!-- <Plugin-Id>${plugin.id}</Plugin-Id>--> | |
| 116 | -<!-- <Plugin-Class>${plugin.class}</Plugin-Class>--> | |
| 117 | -<!-- <Plugin-Version>${plugin.version}</Plugin-Version>--> | |
| 118 | -<!-- <Plugin-Provider>${plugin.provider}</Plugin-Provider>--> | |
| 119 | -<!-- <Plugin-Description>${plugin.description}</Plugin-Description>--> | |
| 120 | -<!-- <Plugin-Dependencies>${plugin.dependencies}</Plugin-Dependencies>--> | |
| 121 | -<!-- </manifestEntries>--> | |
| 122 | -<!-- </archive>--> | |
| 123 | -<!-- </configuration>--> | |
| 124 | -<!-- </plugin>--> | |
| 97 | + <!-- <plugin>--> | |
| 98 | + <!-- <groupId>org.apache.maven.plugins</groupId>--> | |
| 99 | + <!-- <artifactId>maven-shade-plugin</artifactId>--> | |
| 100 | + <!-- <version>3.6.0</version>--> | |
| 101 | + <!-- <executions>--> | |
| 102 | + <!-- <execution>--> | |
| 103 | + <!-- <phase>package</phase>--> | |
| 104 | + <!-- <goals>--> | |
| 105 | + <!-- <goal>shade</goal>--> | |
| 106 | + <!-- </goals>--> | |
| 107 | + <!-- <configuration>--> | |
| 108 | + <!-- <minimizeJar>true</minimizeJar>--> | |
| 109 | + <!-- </configuration>--> | |
| 110 | + <!-- </execution>--> | |
| 111 | + <!-- </executions>--> | |
| 112 | + <!-- <configuration>--> | |
| 113 | + <!-- <archive>--> | |
| 114 | + <!-- <manifestEntries>--> | |
| 115 | + <!-- <Plugin-Id>${plugin.id}</Plugin-Id>--> | |
| 116 | + <!-- <Plugin-Class>${plugin.class}</Plugin-Class>--> | |
| 117 | + <!-- <Plugin-Version>${plugin.version}</Plugin-Version>--> | |
| 118 | + <!-- <Plugin-Provider>${plugin.provider}</Plugin-Provider>--> | |
| 119 | + <!-- <Plugin-Description>${plugin.description}</Plugin-Description>--> | |
| 120 | + <!-- <Plugin-Dependencies>${plugin.dependencies}</Plugin-Dependencies>--> | |
| 121 | + <!-- </manifestEntries>--> | |
| 122 | + <!-- </archive>--> | |
| 123 | + <!-- </configuration>--> | |
| 124 | + <!-- </plugin>--> | |
| 125 | 125 | |
| 126 | 126 | <!-- 独立模式 --> |
| 127 | 127 | <plugin> |
| ... | ... | @@ -161,5 +161,12 @@ |
| 161 | 161 | <groupId>io.vertx</groupId> |
| 162 | 162 | <artifactId>vertx-web</artifactId> |
| 163 | 163 | </dependency> |
| 164 | + | |
| 165 | + <!-- 添加脚本引擎模块依赖 --> | |
| 166 | + <dependency> | |
| 167 | + <groupId>cn.iocoder.boot</groupId> | |
| 168 | + <artifactId>yudao-module-iot-plugin-script</artifactId> | |
| 169 | + <version>${revision}</version> | |
| 170 | + </dependency> | |
| 164 | 171 | </dependencies> |
| 165 | 172 | </project> |
| 166 | 173 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/src/main/java/cn/iocoder/yudao/module/iot/plugin/http/IotHttpPluginApplication.java
| ... | ... | @@ -9,7 +9,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 9 | 9 | * 独立运行入口 |
| 10 | 10 | */ |
| 11 | 11 | @Slf4j |
| 12 | -@SpringBootApplication | |
| 12 | +@SpringBootApplication(scanBasePackages = { | |
| 13 | + // common 的包 | |
| 14 | + "cn.iocoder.yudao.module.iot.plugin.common", | |
| 15 | + // http 的包 | |
| 16 | + "cn.iocoder.yudao.module.iot.plugin.http", | |
| 17 | + // script 的包 | |
| 18 | + "cn.iocoder.yudao.module.iot.plugin.script" | |
| 19 | +}) | |
| 13 | 20 | public class IotHttpPluginApplication { |
| 14 | 21 | |
| 15 | 22 | public static void main(String[] args) { | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/src/main/java/cn/iocoder/yudao/module/iot/plugin/http/config/IotPluginHttpAutoConfiguration.java
| ... | ... | @@ -5,6 +5,7 @@ import cn.iocoder.yudao.module.iot.plugin.common.downstream.IotDeviceDownstreamH |
| 5 | 5 | import cn.iocoder.yudao.module.iot.plugin.http.downstream.IotDeviceDownstreamHandlerImpl; |
| 6 | 6 | import cn.iocoder.yudao.module.iot.plugin.http.upstream.IotDeviceUpstreamServer; |
| 7 | 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; |
| 8 | +import org.springframework.context.ApplicationContext; | |
| 8 | 9 | import org.springframework.context.annotation.Bean; |
| 9 | 10 | import org.springframework.context.annotation.Configuration; |
| 10 | 11 | |
| ... | ... | @@ -19,8 +20,9 @@ public class IotPluginHttpAutoConfiguration { |
| 19 | 20 | |
| 20 | 21 | @Bean(initMethod = "start", destroyMethod = "stop") |
| 21 | 22 | public IotDeviceUpstreamServer deviceUpstreamServer(IotDeviceUpstreamApi deviceUpstreamApi, |
| 22 | - IotPluginHttpProperties properties) { | |
| 23 | - return new IotDeviceUpstreamServer(properties, deviceUpstreamApi); | |
| 23 | + IotPluginHttpProperties properties, | |
| 24 | + ApplicationContext applicationContext) { | |
| 25 | + return new IotDeviceUpstreamServer(properties, deviceUpstreamApi, applicationContext); | |
| 24 | 26 | } |
| 25 | 27 | |
| 26 | 28 | @Bean | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/src/main/java/cn/iocoder/yudao/module/iot/plugin/http/script/HttpScriptService.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.http.script; | |
| 2 | + | |
| 3 | +import cn.hutool.core.util.StrUtil; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.context.PluginScriptContext; | |
| 5 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptService; | |
| 6 | +import io.vertx.core.json.JsonObject; | |
| 7 | +import lombok.RequiredArgsConstructor; | |
| 8 | +import lombok.extern.slf4j.Slf4j; | |
| 9 | +import org.springframework.stereotype.Service; | |
| 10 | + | |
| 11 | +import java.util.HashMap; | |
| 12 | +import java.util.Map; | |
| 13 | +import java.util.concurrent.ConcurrentHashMap; | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * HTTP协议脚本处理服务 | |
| 17 | + * 用于管理和执行设备数据解析脚本 | |
| 18 | + * | |
| 19 | + * @author haohao | |
| 20 | + */ | |
| 21 | +@Service | |
| 22 | +@RequiredArgsConstructor | |
| 23 | +@Slf4j | |
| 24 | +public class HttpScriptService { | |
| 25 | + | |
| 26 | + private final ScriptService scriptService; | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * 脚本缓存,按产品Key缓存脚本内容 | |
| 30 | + */ | |
| 31 | + private final Map<String, String> scriptCache = new ConcurrentHashMap<>(); | |
| 32 | + | |
| 33 | + /** | |
| 34 | + * 解析设备属性数据 | |
| 35 | + * | |
| 36 | + * @param productKey 产品Key | |
| 37 | + * @param deviceName 设备名称 | |
| 38 | + * @param payload 设备上报的原始数据 | |
| 39 | + * @return 解析后的属性数据 | |
| 40 | + */ | |
| 41 | + @SuppressWarnings("unchecked") | |
| 42 | + public Map<String, Object> parsePropertyData(String productKey, String deviceName, JsonObject payload) { | |
| 43 | + // 如果没有脚本,直接返回原始数据 | |
| 44 | + String script = getScriptByProductKey(productKey); | |
| 45 | + if (StrUtil.isBlank(script)) { | |
| 46 | + if (payload != null && payload.containsKey("params")) { | |
| 47 | + return payload.getJsonObject("params").getMap(); | |
| 48 | + } | |
| 49 | + return new HashMap<>(); | |
| 50 | + } | |
| 51 | + | |
| 52 | + try { | |
| 53 | + // 创建脚本上下文 | |
| 54 | + PluginScriptContext context = new PluginScriptContext(); | |
| 55 | + context.withDeviceContext(productKey + ":" + deviceName, null); | |
| 56 | + context.withParameter("payload", payload.toString()); | |
| 57 | + context.withParameter("method", "property"); | |
| 58 | + | |
| 59 | + // 执行脚本 | |
| 60 | + Object result = scriptService.executeJavaScript(script, context); | |
| 61 | + log.debug("[parsePropertyData][产品:{} 设备:{} 原始数据:{} 解析结果:{}]", | |
| 62 | + productKey, deviceName, payload, result); | |
| 63 | + | |
| 64 | + // 处理结果 | |
| 65 | + if (result instanceof Map) { | |
| 66 | + return (Map<String, Object>) result; | |
| 67 | + } else if (result instanceof String) { | |
| 68 | + try { | |
| 69 | + return new JsonObject((String) result).getMap(); | |
| 70 | + } catch (Exception e) { | |
| 71 | + log.warn("[parsePropertyData][脚本返回的字符串不是有效的JSON] result:{}", result); | |
| 72 | + } | |
| 73 | + } | |
| 74 | + } catch (Exception e) { | |
| 75 | + log.error("[parsePropertyData][执行脚本解析属性数据异常] productKey:{} deviceName:{}", | |
| 76 | + productKey, deviceName, e); | |
| 77 | + } | |
| 78 | + | |
| 79 | + // 解析失败,返回空数据 | |
| 80 | + return new HashMap<>(); | |
| 81 | + } | |
| 82 | + | |
| 83 | + /** | |
| 84 | + * 解析设备事件数据 | |
| 85 | + * | |
| 86 | + * @param productKey 产品Key | |
| 87 | + * @param deviceName 设备名称 | |
| 88 | + * @param identifier 事件标识符 | |
| 89 | + * @param payload 设备上报的原始数据 | |
| 90 | + * @return 解析后的事件数据 | |
| 91 | + */ | |
| 92 | + @SuppressWarnings("unchecked") | |
| 93 | + public Map<String, Object> parseEventData(String productKey, String deviceName, String identifier, | |
| 94 | + JsonObject payload) { | |
| 95 | + // 如果没有脚本,直接返回原始数据 | |
| 96 | + String script = getScriptByProductKey(productKey); | |
| 97 | + if (StrUtil.isBlank(script)) { | |
| 98 | + if (payload != null && payload.containsKey("params")) { | |
| 99 | + return payload.getJsonObject("params").getMap(); | |
| 100 | + } | |
| 101 | + return new HashMap<>(); | |
| 102 | + } | |
| 103 | + | |
| 104 | + try { | |
| 105 | + // 创建脚本上下文 | |
| 106 | + PluginScriptContext context = new PluginScriptContext(); | |
| 107 | + context.withDeviceContext(productKey + ":" + deviceName, null); | |
| 108 | + context.withParameter("payload", payload.toString()); | |
| 109 | + context.withParameter("method", "event"); | |
| 110 | + context.withParameter("identifier", identifier); | |
| 111 | + | |
| 112 | + // 执行脚本 | |
| 113 | + Object result = scriptService.executeJavaScript(script, context); | |
| 114 | + log.debug("[parseEventData][产品:{} 设备:{} 事件:{} 原始数据:{} 解析结果:{}]", | |
| 115 | + productKey, deviceName, identifier, payload, result); | |
| 116 | + | |
| 117 | + // 处理结果 | |
| 118 | + if (result instanceof Map) { | |
| 119 | + return (Map<String, Object>) result; | |
| 120 | + } else if (result instanceof String) { | |
| 121 | + try { | |
| 122 | + return new JsonObject((String) result).getMap(); | |
| 123 | + } catch (Exception e) { | |
| 124 | + log.warn("[parseEventData][脚本返回的字符串不是有效的JSON] result:{}", result); | |
| 125 | + } | |
| 126 | + } | |
| 127 | + } catch (Exception e) { | |
| 128 | + log.error("[parseEventData][执行脚本解析事件数据异常] productKey:{} deviceName:{} identifier:{}", | |
| 129 | + productKey, deviceName, identifier, e); | |
| 130 | + } | |
| 131 | + | |
| 132 | + // 解析失败,返回空数据 | |
| 133 | + return new HashMap<>(); | |
| 134 | + } | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * 根据产品Key获取脚本 | |
| 138 | + * | |
| 139 | + * @param productKey 产品Key | |
| 140 | + * @return 脚本内容 | |
| 141 | + */ | |
| 142 | + private String getScriptByProductKey(String productKey) { | |
| 143 | + // 从缓存中获取脚本 | |
| 144 | + String script = scriptCache.get(productKey); | |
| 145 | + if (script != null) { | |
| 146 | + return script; | |
| 147 | + } | |
| 148 | + | |
| 149 | + // TODO: 实际应用中,这里应从数据库或配置中心获取产品对应的脚本 | |
| 150 | + // 此处仅为示例,提供一个默认脚本 | |
| 151 | + if ("example_product".equals(productKey)) { | |
| 152 | + script = "/**\n" + | |
| 153 | + " * 设备数据解析脚本示例\n" + | |
| 154 | + " * @param payload 设备上报的原始数据\n" + | |
| 155 | + " * @param method 方法类型:property(属性)或event(事件)\n" + | |
| 156 | + " * @param identifier 事件标识符(仅当method为event时有值)\n" + | |
| 157 | + " * @return 解析后的数据\n" + | |
| 158 | + " */\n" + | |
| 159 | + "function parse() {\n" + | |
| 160 | + " // 解析JSON数据\n" + | |
| 161 | + " var data = JSON.parse(payload);\n" + | |
| 162 | + " var result = {};\n" + | |
| 163 | + " \n" + | |
| 164 | + " // 根据方法类型处理\n" + | |
| 165 | + " if (method === 'property') {\n" + | |
| 166 | + " // 属性数据解析\n" + | |
| 167 | + " if (data.params) {\n" + | |
| 168 | + " // 直接返回params中的数据\n" + | |
| 169 | + " return data.params;\n" + | |
| 170 | + " }\n" + | |
| 171 | + " } else if (method === 'event') {\n" + | |
| 172 | + " // 事件数据解析\n" + | |
| 173 | + " if (data.params) {\n" + | |
| 174 | + " return data.params;\n" + | |
| 175 | + " }\n" + | |
| 176 | + " }\n" + | |
| 177 | + " \n" + | |
| 178 | + " return result;\n" + | |
| 179 | + "}\n" + | |
| 180 | + "\n" + | |
| 181 | + "// 执行解析\n" + | |
| 182 | + "parse();"; | |
| 183 | + | |
| 184 | + // 缓存脚本 | |
| 185 | + scriptCache.put(productKey, script); | |
| 186 | + } | |
| 187 | + | |
| 188 | + return script; | |
| 189 | + } | |
| 190 | + | |
| 191 | + /** | |
| 192 | + * 设置产品解析脚本 | |
| 193 | + * | |
| 194 | + * @param productKey 产品Key | |
| 195 | + * @param script 脚本内容 | |
| 196 | + */ | |
| 197 | + public void setScript(String productKey, String script) { | |
| 198 | + if (StrUtil.isNotBlank(productKey) && StrUtil.isNotBlank(script)) { | |
| 199 | + // 验证脚本是否有效 | |
| 200 | + if (scriptService.validateScript("js", script)) { | |
| 201 | + scriptCache.put(productKey, script); | |
| 202 | + log.info("[setScript][设置产品:{}的解析脚本成功]", productKey); | |
| 203 | + } else { | |
| 204 | + log.warn("[setScript][脚本验证失败,不更新缓存] productKey:{}", productKey); | |
| 205 | + } | |
| 206 | + } | |
| 207 | + } | |
| 208 | + | |
| 209 | + /** | |
| 210 | + * 清除产品解析脚本 | |
| 211 | + * | |
| 212 | + * @param productKey 产品Key | |
| 213 | + */ | |
| 214 | + public void clearScript(String productKey) { | |
| 215 | + if (StrUtil.isNotBlank(productKey)) { | |
| 216 | + scriptCache.remove(productKey); | |
| 217 | + log.info("[clearScript][清除产品:{}的解析脚本]", productKey); | |
| 218 | + } | |
| 219 | + } | |
| 220 | + | |
| 221 | + /** | |
| 222 | + * 清除所有脚本缓存 | |
| 223 | + */ | |
| 224 | + public void clearAllScripts() { | |
| 225 | + scriptCache.clear(); | |
| 226 | + log.info("[clearAllScripts][清除所有脚本缓存]"); | |
| 227 | + } | |
| 228 | +} | |
| 0 | 229 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/src/main/java/cn/iocoder/yudao/module/iot/plugin/http/upstream/IotDeviceUpstreamServer.java
| ... | ... | @@ -8,6 +8,7 @@ import io.vertx.core.http.HttpServer; |
| 8 | 8 | import io.vertx.ext.web.Router; |
| 9 | 9 | import io.vertx.ext.web.handler.BodyHandler; |
| 10 | 10 | import lombok.extern.slf4j.Slf4j; |
| 11 | +import org.springframework.context.ApplicationContext; | |
| 11 | 12 | |
| 12 | 13 | /** |
| 13 | 14 | * IoT 设备下行服务端,接收来自 device 设备的请求,转发给 server 服务器 |
| ... | ... | @@ -24,7 +25,8 @@ public class IotDeviceUpstreamServer { |
| 24 | 25 | private final IotPluginHttpProperties properties; |
| 25 | 26 | |
| 26 | 27 | public IotDeviceUpstreamServer(IotPluginHttpProperties properties, |
| 27 | - IotDeviceUpstreamApi deviceUpstreamApi) { | |
| 28 | + IotDeviceUpstreamApi deviceUpstreamApi, | |
| 29 | + ApplicationContext applicationContext) { | |
| 28 | 30 | this.properties = properties; |
| 29 | 31 | // 创建 Vertx 实例 |
| 30 | 32 | this.vertx = Vertx.vertx(); |
| ... | ... | @@ -33,7 +35,8 @@ public class IotDeviceUpstreamServer { |
| 33 | 35 | router.route().handler(BodyHandler.create()); // 处理 Body |
| 34 | 36 | |
| 35 | 37 | // 使用统一的 Handler 处理所有上行请求 |
| 36 | - IotDeviceUpstreamVertxHandler upstreamHandler = new IotDeviceUpstreamVertxHandler(deviceUpstreamApi); | |
| 38 | + IotDeviceUpstreamVertxHandler upstreamHandler = new IotDeviceUpstreamVertxHandler(deviceUpstreamApi, | |
| 39 | + applicationContext); | |
| 37 | 40 | router.post(IotDeviceUpstreamVertxHandler.PROPERTY_PATH).handler(upstreamHandler); |
| 38 | 41 | router.post(IotDeviceUpstreamVertxHandler.EVENT_PATH).handler(upstreamHandler); |
| 39 | 42 | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-http/src/main/java/cn/iocoder/yudao/module/iot/plugin/http/upstream/router/IotDeviceUpstreamVertxHandler.java
| ... | ... | @@ -10,11 +10,12 @@ import cn.iocoder.yudao.module.iot.api.device.dto.control.upstream.IotDeviceStat |
| 10 | 10 | import cn.iocoder.yudao.module.iot.enums.device.IotDeviceStateEnum; |
| 11 | 11 | import cn.iocoder.yudao.module.iot.plugin.common.pojo.IotStandardResponse; |
| 12 | 12 | import cn.iocoder.yudao.module.iot.plugin.common.util.IotPluginCommonUtils; |
| 13 | +import cn.iocoder.yudao.module.iot.plugin.http.script.HttpScriptService; | |
| 13 | 14 | import io.vertx.core.Handler; |
| 14 | 15 | import io.vertx.core.json.JsonObject; |
| 15 | 16 | import io.vertx.ext.web.RoutingContext; |
| 16 | -import lombok.RequiredArgsConstructor; | |
| 17 | 17 | import lombok.extern.slf4j.Slf4j; |
| 18 | +import org.springframework.context.ApplicationContext; | |
| 18 | 19 | |
| 19 | 20 | import java.time.LocalDateTime; |
| 20 | 21 | import java.util.HashMap; |
| ... | ... | @@ -30,11 +31,9 @@ import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeC |
| 30 | 31 | * |
| 31 | 32 | * @author haohao |
| 32 | 33 | */ |
| 33 | -@RequiredArgsConstructor | |
| 34 | 34 | @Slf4j |
| 35 | 35 | public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 36 | 36 | |
| 37 | - // TODO @haohao:要不要类似 IotDeviceConfigSetVertxHandler 写的,把这些 PATH、METHOD 之类的抽走 | |
| 38 | 37 | /** |
| 39 | 38 | * 属性上报路径 |
| 40 | 39 | */ |
| ... | ... | @@ -49,8 +48,14 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 49 | 48 | private static final String EVENT_METHOD_SUFFIX = ".post"; |
| 50 | 49 | |
| 51 | 50 | private final IotDeviceUpstreamApi deviceUpstreamApi; |
| 51 | + private final HttpScriptService scriptService; | |
| 52 | + | |
| 53 | + public IotDeviceUpstreamVertxHandler(IotDeviceUpstreamApi deviceUpstreamApi, | |
| 54 | + ApplicationContext applicationContext) { | |
| 55 | + this.deviceUpstreamApi = deviceUpstreamApi; | |
| 56 | + this.scriptService = applicationContext.getBean(HttpScriptService.class); | |
| 57 | + } | |
| 52 | 58 | |
| 53 | - // TODO @haohao:要不要分成多个 Handler?每个只解决一个问题哈。 | |
| 54 | 59 | @Override |
| 55 | 60 | public void handle(RoutingContext routingContext) { |
| 56 | 61 | String path = routingContext.request().path(); |
| ... | ... | @@ -68,7 +73,8 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 68 | 73 | String method; |
| 69 | 74 | if (path.matches(".*/thing/event/property/post")) { |
| 70 | 75 | // 处理属性上报 |
| 71 | - IotDevicePropertyReportReqDTO reportReqDTO = parsePropertyReportRequest(productKey, deviceName, requestId, body); | |
| 76 | + IotDevicePropertyReportReqDTO reportReqDTO = parsePropertyReportRequest(productKey, deviceName, | |
| 77 | + requestId, body); | |
| 72 | 78 | |
| 73 | 79 | // 设备上线 |
| 74 | 80 | updateDeviceState(reportReqDTO.getProductKey(), reportReqDTO.getDeviceName()); |
| ... | ... | @@ -79,7 +85,8 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 79 | 85 | } else if (path.matches(".*/thing/event/.+/post")) { |
| 80 | 86 | // 处理事件上报 |
| 81 | 87 | String identifier = routingContext.pathParam("identifier"); |
| 82 | - IotDeviceEventReportReqDTO reportReqDTO = parseEventReportRequest(productKey, deviceName, identifier, requestId, body); | |
| 88 | + IotDeviceEventReportReqDTO reportReqDTO = parseEventReportRequest(productKey, deviceName, identifier, | |
| 89 | + requestId, body); | |
| 83 | 90 | |
| 84 | 91 | // 设备上线 |
| 85 | 92 | updateDeviceState(reportReqDTO.getProductKey(), reportReqDTO.getDeviceName()); |
| ... | ... | @@ -89,7 +96,8 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 89 | 96 | method = EVENT_METHOD_PREFIX + identifier + EVENT_METHOD_SUFFIX; |
| 90 | 97 | } else { |
| 91 | 98 | // 不支持的请求路径 |
| 92 | - IotStandardResponse errorResponse = IotStandardResponse.error(requestId, "unknown", BAD_REQUEST.getCode(), "不支持的请求路径"); | |
| 99 | + IotStandardResponse errorResponse = IotStandardResponse.error(requestId, "unknown", | |
| 100 | + BAD_REQUEST.getCode(), "不支持的请求路径"); | |
| 93 | 101 | IotPluginCommonUtils.writeJsonResponse(routingContext, errorResponse); |
| 94 | 102 | return; |
| 95 | 103 | } |
| ... | ... | @@ -108,7 +116,8 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 108 | 116 | : EVENT_METHOD_PREFIX + (routingContext.pathParams().containsKey("identifier") |
| 109 | 117 | ? routingContext.pathParam("identifier") |
| 110 | 118 | : "unknown") + EVENT_METHOD_SUFFIX; |
| 111 | - IotStandardResponse errorResponse = IotStandardResponse.error(requestId, method, INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg()); | |
| 119 | + IotStandardResponse errorResponse = IotStandardResponse.error(requestId, method, | |
| 120 | + INTERNAL_SERVER_ERROR.getCode(), INTERNAL_SERVER_ERROR.getMsg()); | |
| 112 | 121 | IotPluginCommonUtils.writeJsonResponse(routingContext, errorResponse); |
| 113 | 122 | } |
| 114 | 123 | } |
| ... | ... | @@ -121,7 +130,8 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 121 | 130 | */ |
| 122 | 131 | private void updateDeviceState(String productKey, String deviceName) { |
| 123 | 132 | deviceUpstreamApi.updateDeviceState(((IotDeviceStateUpdateReqDTO) new IotDeviceStateUpdateReqDTO() |
| 124 | - .setRequestId(IdUtil.fastSimpleUUID()).setProcessId(IotPluginCommonUtils.getProcessId()).setReportTime(LocalDateTime.now()) | |
| 133 | + .setRequestId(IdUtil.fastSimpleUUID()).setProcessId(IotPluginCommonUtils.getProcessId()) | |
| 134 | + .setReportTime(LocalDateTime.now()) | |
| 125 | 135 | .setProductKey(productKey).setDeviceName(deviceName)).setState(IotDeviceStateEnum.ONLINE.getState())); |
| 126 | 136 | } |
| 127 | 137 | |
| ... | ... | @@ -134,22 +144,29 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 134 | 144 | * @param body 请求体 |
| 135 | 145 | * @return 属性上报请求 DTO |
| 136 | 146 | */ |
| 137 | - @SuppressWarnings("unchecked") | |
| 138 | - private IotDevicePropertyReportReqDTO parsePropertyReportRequest(String productKey, String deviceName, String requestId, JsonObject body) { | |
| 139 | - // 按照标准 JSON 格式处理属性数据 | |
| 140 | - Map<String, Object> properties = new HashMap<>(); | |
| 141 | - Map<String, Object> params = body.getJsonObject("params") != null ? body.getJsonObject("params").getMap() : null; | |
| 142 | - if (params != null) { | |
| 143 | - // 将标准格式的 params 转换为平台需要的 properties 格式 | |
| 144 | - for (Map.Entry<String, Object> entry : params.entrySet()) { | |
| 145 | - String key = entry.getKey(); | |
| 146 | - Object valueObj = entry.getValue(); | |
| 147 | - // 如果是复杂结构(包含 value 和 time) | |
| 148 | - if (valueObj instanceof Map) { | |
| 149 | - Map<String, Object> valueMap = (Map<String, Object>) valueObj; | |
| 150 | - properties.put(key, valueMap.getOrDefault("value", valueObj)); | |
| 151 | - } else { | |
| 152 | - properties.put(key, valueObj); | |
| 147 | + private IotDevicePropertyReportReqDTO parsePropertyReportRequest(String productKey, String deviceName, | |
| 148 | + String requestId, JsonObject body) { | |
| 149 | + // 使用脚本解析数据 | |
| 150 | + Map<String, Object> properties = scriptService.parsePropertyData(productKey, deviceName, body); | |
| 151 | + | |
| 152 | + // 如果脚本解析结果为空,使用默认解析逻辑 | |
| 153 | + if (properties.isEmpty()) { | |
| 154 | + properties = new HashMap<>(); | |
| 155 | + Map<String, Object> params = body.getJsonObject("params") != null ? body.getJsonObject("params").getMap() | |
| 156 | + : null; | |
| 157 | + if (params != null) { | |
| 158 | + // 将标准格式的 params 转换为平台需要的 properties 格式 | |
| 159 | + for (Map.Entry<String, Object> entry : params.entrySet()) { | |
| 160 | + String key = entry.getKey(); | |
| 161 | + Object valueObj = entry.getValue(); | |
| 162 | + // 如果是复杂结构(包含 value 和 time) | |
| 163 | + if (valueObj instanceof Map) { | |
| 164 | + @SuppressWarnings("unchecked") | |
| 165 | + Map<String, Object> valueMap = (Map<String, Object>) valueObj; | |
| 166 | + properties.put(key, valueMap.getOrDefault("value", valueObj)); | |
| 167 | + } else { | |
| 168 | + properties.put(key, valueObj); | |
| 169 | + } | |
| 153 | 170 | } |
| 154 | 171 | } |
| 155 | 172 | } |
| ... | ... | @@ -170,14 +187,19 @@ public class IotDeviceUpstreamVertxHandler implements Handler<RoutingContext> { |
| 170 | 187 | * @param body 请求体 |
| 171 | 188 | * @return 事件上报请求 DTO |
| 172 | 189 | */ |
| 173 | - private IotDeviceEventReportReqDTO parseEventReportRequest(String productKey, String deviceName, String identifier, String requestId, JsonObject body) { | |
| 174 | - // 按照标准 JSON 格式处理事件参数 | |
| 175 | - Map<String, Object> params; | |
| 176 | - if (body.containsKey("params")) { | |
| 177 | - params = body.getJsonObject("params").getMap(); | |
| 178 | - } else { | |
| 179 | - // 兼容旧格式 | |
| 180 | - params = new HashMap<>(); | |
| 190 | + private IotDeviceEventReportReqDTO parseEventReportRequest(String productKey, String deviceName, String identifier, | |
| 191 | + String requestId, JsonObject body) { | |
| 192 | + // 使用脚本解析事件数据 | |
| 193 | + Map<String, Object> params = scriptService.parseEventData(productKey, deviceName, identifier, body); | |
| 194 | + | |
| 195 | + // 如果脚本解析结果为空,使用默认解析逻辑 | |
| 196 | + if (params.isEmpty()) { | |
| 197 | + if (body.containsKey("params")) { | |
| 198 | + params = body.getJsonObject("params").getMap(); | |
| 199 | + } else { | |
| 200 | + // 兼容旧格式 | |
| 201 | + params = new HashMap<>(); | |
| 202 | + } | |
| 181 | 203 | } |
| 182 | 204 | |
| 183 | 205 | // 构建事件上报请求 DTO | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/pom.xml
0 → 100644
| 1 | +<?xml version="1.0" encoding="UTF-8"?> | |
| 2 | +<project xmlns="http://maven.apache.org/POM/4.0.0" | |
| 3 | + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
| 4 | + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
| 5 | + <parent> | |
| 6 | + <artifactId>yudao-module-iot-plugins</artifactId> | |
| 7 | + <groupId>cn.iocoder.boot</groupId> | |
| 8 | + <version>${revision}</version> | |
| 9 | + </parent> | |
| 10 | + <modelVersion>4.0.0</modelVersion> | |
| 11 | + | |
| 12 | + <artifactId>yudao-module-iot-plugin-script</artifactId> | |
| 13 | + <packaging>jar</packaging> | |
| 14 | + | |
| 15 | + <name>${project.artifactId}</name> | |
| 16 | + <description>IoT 插件脚本模块,提供JS引擎解析等功能</description> | |
| 17 | + | |
| 18 | + <dependencies> | |
| 19 | + <!-- 引入公共模块 --> | |
| 20 | + <dependency> | |
| 21 | + <groupId>cn.iocoder.boot</groupId> | |
| 22 | + <artifactId>yudao-module-iot-plugin-common</artifactId> | |
| 23 | + <version>${revision}</version> | |
| 24 | + </dependency> | |
| 25 | + | |
| 26 | + <!-- Spring相关依赖 --> | |
| 27 | + <dependency> | |
| 28 | + <groupId>org.springframework</groupId> | |
| 29 | + <artifactId>spring-context</artifactId> | |
| 30 | + </dependency> | |
| 31 | + | |
| 32 | + <!-- 工具类相关 --> | |
| 33 | + <dependency> | |
| 34 | + <groupId>cn.hutool</groupId> | |
| 35 | + <artifactId>hutool-all</artifactId> | |
| 36 | + </dependency> | |
| 37 | + <dependency> | |
| 38 | + <groupId>org.projectlombok</groupId> | |
| 39 | + <artifactId>lombok</artifactId> | |
| 40 | + <optional>true</optional> | |
| 41 | + </dependency> | |
| 42 | + <dependency> | |
| 43 | + <groupId>org.slf4j</groupId> | |
| 44 | + <artifactId>slf4j-api</artifactId> | |
| 45 | + </dependency> | |
| 46 | + | |
| 47 | + <!-- JavaScript 引擎 - 使用标准JSR-223实现 --> | |
| 48 | + <dependency> | |
| 49 | + <groupId>org.openjdk.nashorn</groupId> | |
| 50 | + <artifactId>nashorn-core</artifactId> | |
| 51 | + <version>15.4</version> | |
| 52 | + </dependency> | |
| 53 | + | |
| 54 | + <!-- 测试相关 --> | |
| 55 | + <dependency> | |
| 56 | + <groupId>org.springframework.boot</groupId> | |
| 57 | + <artifactId>spring-boot-starter-test</artifactId> | |
| 58 | + <scope>test</scope> | |
| 59 | + </dependency> | |
| 60 | + </dependencies> | |
| 61 | +</project> | |
| 0 | 62 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/ScriptExample.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.context.PluginScriptContext; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptService; | |
| 5 | +import org.slf4j.Logger; | |
| 6 | +import org.slf4j.LoggerFactory; | |
| 7 | +import org.springframework.beans.factory.annotation.Autowired; | |
| 8 | +import org.springframework.stereotype.Component; | |
| 9 | + | |
| 10 | +import java.util.HashMap; | |
| 11 | +import java.util.Map; | |
| 12 | + | |
| 13 | +/** | |
| 14 | + * 脚本使用示例类 | |
| 15 | + */ | |
| 16 | +@Component | |
| 17 | +public class ScriptExample { | |
| 18 | + private static final Logger logger = LoggerFactory.getLogger(ScriptExample.class); | |
| 19 | + | |
| 20 | + @Autowired | |
| 21 | + private ScriptService scriptService; | |
| 22 | + | |
| 23 | + /** | |
| 24 | + * 示例:执行简单的JavaScript脚本 | |
| 25 | + */ | |
| 26 | + public void executeSimpleScript() { | |
| 27 | + String script = "var result = a + b; result;"; | |
| 28 | + | |
| 29 | + Map<String, Object> params = new HashMap<>(); | |
| 30 | + params.put("a", 10); | |
| 31 | + params.put("b", 20); | |
| 32 | + | |
| 33 | + Object result = scriptService.executeJavaScript(script, params); | |
| 34 | + logger.info("脚本执行结果: {}", result); | |
| 35 | + } | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * 示例:使用脚本处理设备数据 | |
| 39 | + * | |
| 40 | + * @param deviceId 设备ID | |
| 41 | + * @param payload 设备原始数据 | |
| 42 | + * @return 处理后的数据 | |
| 43 | + */ | |
| 44 | + @SuppressWarnings("unchecked") | |
| 45 | + public Map<String, Object> processDeviceData(String deviceId, String payload) { | |
| 46 | + // 设备数据处理脚本 | |
| 47 | + String script = "function process() {\n" + | |
| 48 | + " var data = JSON.parse(payload);\n" + | |
| 49 | + " var result = {};\n" + | |
| 50 | + " // 提取温度信息\n" + | |
| 51 | + " if (data.temp) {\n" + | |
| 52 | + " result.temperature = data.temp;\n" + | |
| 53 | + " }\n" + | |
| 54 | + " // 提取湿度信息\n" + | |
| 55 | + " if (data.hum) {\n" + | |
| 56 | + " result.humidity = data.hum;\n" + | |
| 57 | + " }\n" + | |
| 58 | + " // 计算额外信息\n" + | |
| 59 | + " if (data.temp && data.temp > 30) {\n" + | |
| 60 | + " result.alert = true;\n" + | |
| 61 | + " result.alertMessage = '温度过高警告';\n" + | |
| 62 | + " }\n" + | |
| 63 | + " return result;\n" + | |
| 64 | + "}\n" + | |
| 65 | + "process();"; | |
| 66 | + | |
| 67 | + // 创建脚本上下文 | |
| 68 | + PluginScriptContext context = new PluginScriptContext(); | |
| 69 | + context.withDeviceContext(deviceId, null); | |
| 70 | + context.withParameter("payload", payload); | |
| 71 | + | |
| 72 | + try { | |
| 73 | + Object result = scriptService.executeJavaScript(script, context); | |
| 74 | + if (result != null) { | |
| 75 | + // 处理结果 | |
| 76 | + logger.info("设备数据处理结果: {}", result); | |
| 77 | + | |
| 78 | + // 安全地将结果转换为Map | |
| 79 | + if (result instanceof Map) { | |
| 80 | + return (Map<String, Object>) result; | |
| 81 | + } else { | |
| 82 | + logger.warn("脚本返回结果类型不是Map: {}", result.getClass().getName()); | |
| 83 | + } | |
| 84 | + } | |
| 85 | + } catch (Exception e) { | |
| 86 | + logger.error("处理设备数据失败: {}", e.getMessage()); | |
| 87 | + } | |
| 88 | + | |
| 89 | + return new HashMap<>(); | |
| 90 | + } | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * 示例:生成设备命令 | |
| 94 | + * | |
| 95 | + * @param deviceId 设备ID | |
| 96 | + * @param command 命令名称 | |
| 97 | + * @param params 命令参数 | |
| 98 | + * @return 格式化的命令字符串 | |
| 99 | + */ | |
| 100 | + public String generateDeviceCommand(String deviceId, String command, Map<String, Object> params) { | |
| 101 | + // 命令生成脚本 | |
| 102 | + String script = "function generateCommand(cmd, params) {\n" + | |
| 103 | + " var result = { 'cmd': cmd };\n" + | |
| 104 | + " if (params) {\n" + | |
| 105 | + " result.params = params;\n" + | |
| 106 | + " }\n" + | |
| 107 | + " result.timestamp = new Date().getTime();\n" + | |
| 108 | + " result.deviceId = deviceId;\n" + | |
| 109 | + " return JSON.stringify(result);\n" + | |
| 110 | + "}\n" + | |
| 111 | + "generateCommand(command, commandParams);"; | |
| 112 | + | |
| 113 | + // 创建脚本上下文 | |
| 114 | + PluginScriptContext context = new PluginScriptContext(); | |
| 115 | + context.setParameter("deviceId", deviceId); | |
| 116 | + context.setParameter("command", command); | |
| 117 | + context.setParameter("commandParams", params); | |
| 118 | + | |
| 119 | + try { | |
| 120 | + Object result = scriptService.executeJavaScript(script, context); | |
| 121 | + if (result instanceof String) { | |
| 122 | + return (String) result; | |
| 123 | + } else if (result != null) { | |
| 124 | + logger.warn("脚本返回结果类型不是String: {}", result.getClass().getName()); | |
| 125 | + } | |
| 126 | + } catch (Exception e) { | |
| 127 | + logger.error("生成设备命令失败: {}", e.getMessage()); | |
| 128 | + } | |
| 129 | + | |
| 130 | + return null; | |
| 131 | + } | |
| 132 | +} | |
| 0 | 133 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/config/ScriptConfiguration.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.config; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.engine.ScriptEngineFactory; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptService; | |
| 5 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptServiceImpl; | |
| 6 | +import org.springframework.context.annotation.Bean; | |
| 7 | +import org.springframework.context.annotation.Configuration; | |
| 8 | + | |
| 9 | +/** | |
| 10 | + * 脚本模块配置类 | |
| 11 | + */ | |
| 12 | +@Configuration | |
| 13 | +public class ScriptConfiguration { | |
| 14 | + | |
| 15 | + /** | |
| 16 | + * 创建脚本引擎工厂 | |
| 17 | + * | |
| 18 | + * @return 脚本引擎工厂 | |
| 19 | + */ | |
| 20 | + @Bean | |
| 21 | + public ScriptEngineFactory scriptEngineFactory() { | |
| 22 | + return new ScriptEngineFactory(); | |
| 23 | + } | |
| 24 | + | |
| 25 | + /** | |
| 26 | + * 创建脚本服务 | |
| 27 | + * | |
| 28 | + * @param engineFactory 脚本引擎工厂 | |
| 29 | + * @return 脚本服务 | |
| 30 | + */ | |
| 31 | + @Bean | |
| 32 | + public ScriptService scriptService(ScriptEngineFactory engineFactory) { | |
| 33 | + ScriptServiceImpl service = new ScriptServiceImpl(); | |
| 34 | + // 如果有其他配置可以在这里设置 | |
| 35 | + return service; | |
| 36 | + } | |
| 37 | +} | |
| 0 | 38 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/context/PluginScriptContext.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.context; | |
| 2 | + | |
| 3 | +import java.util.HashMap; | |
| 4 | +import java.util.Map; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * 插件脚本上下文,提供插件执行脚本的上下文环境 | |
| 8 | + */ | |
| 9 | +public class PluginScriptContext implements ScriptContext { | |
| 10 | + | |
| 11 | + /** | |
| 12 | + * 上下文参数 | |
| 13 | + */ | |
| 14 | + private final Map<String, Object> parameters = new HashMap<>(); | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * 上下文函数 | |
| 18 | + */ | |
| 19 | + private final Map<String, Object> functions = new HashMap<>(); | |
| 20 | + | |
| 21 | + /** | |
| 22 | + * 日志函数接口 | |
| 23 | + */ | |
| 24 | + public interface LogFunction { | |
| 25 | + void log(String message); | |
| 26 | + } | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * 构建插件脚本上下文 | |
| 30 | + */ | |
| 31 | + public PluginScriptContext() { | |
| 32 | + // 初始化上下文,注册一些基础函数 | |
| 33 | + LogFunction logFunction = message -> System.out.println("[Plugin Script] " + message); | |
| 34 | + registerFunction("log", logFunction); | |
| 35 | + } | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * 构建插件脚本上下文 | |
| 39 | + * | |
| 40 | + * @param parameters 初始参数 | |
| 41 | + */ | |
| 42 | + public PluginScriptContext(Map<String, Object> parameters) { | |
| 43 | + this(); | |
| 44 | + if (parameters != null) { | |
| 45 | + this.parameters.putAll(parameters); | |
| 46 | + } | |
| 47 | + } | |
| 48 | + | |
| 49 | + @Override | |
| 50 | + public Map<String, Object> getParameters() { | |
| 51 | + return parameters; | |
| 52 | + } | |
| 53 | + | |
| 54 | + @Override | |
| 55 | + public Map<String, Object> getFunctions() { | |
| 56 | + return functions; | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Override | |
| 60 | + public void setParameter(String key, Object value) { | |
| 61 | + parameters.put(key, value); | |
| 62 | + } | |
| 63 | + | |
| 64 | + @Override | |
| 65 | + public Object getParameter(String key) { | |
| 66 | + return parameters.get(key); | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Override | |
| 70 | + public void registerFunction(String name, Object function) { | |
| 71 | + functions.put(name, function); | |
| 72 | + } | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * 批量设置参数 | |
| 76 | + * | |
| 77 | + * @param params 参数Map | |
| 78 | + * @return 当前上下文对象 | |
| 79 | + */ | |
| 80 | + public PluginScriptContext withParameters(Map<String, Object> params) { | |
| 81 | + if (params != null) { | |
| 82 | + parameters.putAll(params); | |
| 83 | + } | |
| 84 | + return this; | |
| 85 | + } | |
| 86 | + | |
| 87 | + /** | |
| 88 | + * 添加设备相关的上下文参数 | |
| 89 | + * | |
| 90 | + * @param deviceId 设备ID | |
| 91 | + * @param deviceData 设备数据 | |
| 92 | + * @return 当前上下文对象 | |
| 93 | + */ | |
| 94 | + public PluginScriptContext withDeviceContext(String deviceId, Map<String, Object> deviceData) { | |
| 95 | + parameters.put("deviceId", deviceId); | |
| 96 | + parameters.put("deviceData", deviceData); | |
| 97 | + return this; | |
| 98 | + } | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * 添加消息相关的上下文参数 | |
| 102 | + * | |
| 103 | + * @param topic 消息主题 | |
| 104 | + * @param payload 消息内容 | |
| 105 | + * @return 当前上下文对象 | |
| 106 | + */ | |
| 107 | + public PluginScriptContext withMessageContext(String topic, Object payload) { | |
| 108 | + parameters.put("topic", topic); | |
| 109 | + parameters.put("payload", payload); | |
| 110 | + return this; | |
| 111 | + } | |
| 112 | + | |
| 113 | + /** | |
| 114 | + * 设置单个参数 | |
| 115 | + * | |
| 116 | + * @param key 参数名 | |
| 117 | + * @param value 参数值 | |
| 118 | + * @return 当前上下文对象 | |
| 119 | + */ | |
| 120 | + public PluginScriptContext withParameter(String key, Object value) { | |
| 121 | + parameters.put(key, value); | |
| 122 | + return this; | |
| 123 | + } | |
| 124 | +} | |
| 0 | 125 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/context/ScriptContext.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.context; | |
| 2 | + | |
| 3 | +import java.util.Map; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * 脚本上下文接口,定义脚本执行所需的上下文环境 | |
| 7 | + */ | |
| 8 | +public interface ScriptContext { | |
| 9 | + | |
| 10 | + /** | |
| 11 | + * 获取上下文参数 | |
| 12 | + * | |
| 13 | + * @return 上下文参数 | |
| 14 | + */ | |
| 15 | + Map<String, Object> getParameters(); | |
| 16 | + | |
| 17 | + /** | |
| 18 | + * 获取上下文函数 | |
| 19 | + * | |
| 20 | + * @return 上下文函数 | |
| 21 | + */ | |
| 22 | + Map<String, Object> getFunctions(); | |
| 23 | + | |
| 24 | + /** | |
| 25 | + * 设置上下文参数 | |
| 26 | + * | |
| 27 | + * @param key 参数名 | |
| 28 | + * @param value 参数值 | |
| 29 | + */ | |
| 30 | + void setParameter(String key, Object value); | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * 获取上下文参数 | |
| 34 | + * | |
| 35 | + * @param key 参数名 | |
| 36 | + * @return 参数值 | |
| 37 | + */ | |
| 38 | + Object getParameter(String key); | |
| 39 | + | |
| 40 | + /** | |
| 41 | + * 注册函数 | |
| 42 | + * | |
| 43 | + * @param name 函数名称 | |
| 44 | + * @param function 函数对象 | |
| 45 | + */ | |
| 46 | + void registerFunction(String name, Object function); | |
| 47 | +} | |
| 0 | 48 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/engine/AbstractScriptEngine.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.engine; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.context.ScriptContext; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.sandbox.ScriptSandbox; | |
| 5 | + | |
| 6 | +import java.util.Map; | |
| 7 | + | |
| 8 | +/** | |
| 9 | + * 抽象脚本引擎基类,定义脚本引擎的基本功能 | |
| 10 | + */ | |
| 11 | +public abstract class AbstractScriptEngine { | |
| 12 | + | |
| 13 | + protected ScriptSandbox sandbox; | |
| 14 | + | |
| 15 | + /** | |
| 16 | + * 初始化脚本引擎 | |
| 17 | + */ | |
| 18 | + public abstract void init(); | |
| 19 | + | |
| 20 | + /** | |
| 21 | + * 执行脚本 | |
| 22 | + * | |
| 23 | + * @param script 脚本内容 | |
| 24 | + * @param context 脚本上下文 | |
| 25 | + * @return 脚本执行结果 | |
| 26 | + */ | |
| 27 | + public abstract Object execute(String script, ScriptContext context); | |
| 28 | + | |
| 29 | + /** | |
| 30 | + * 执行脚本 | |
| 31 | + * | |
| 32 | + * @param script 脚本内容 | |
| 33 | + * @param params 脚本参数 | |
| 34 | + * @return 脚本执行结果 | |
| 35 | + */ | |
| 36 | + public abstract Object execute(String script, Map<String, Object> params); | |
| 37 | + | |
| 38 | + /** | |
| 39 | + * 销毁脚本引擎,释放资源 | |
| 40 | + */ | |
| 41 | + public abstract void destroy(); | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * 设置脚本沙箱 | |
| 45 | + * | |
| 46 | + * @param sandbox 脚本沙箱 | |
| 47 | + */ | |
| 48 | + public void setSandbox(ScriptSandbox sandbox) { | |
| 49 | + this.sandbox = sandbox; | |
| 50 | + } | |
| 51 | +} | |
| 0 | 52 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/engine/JsScriptEngine.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.engine; | |
| 2 | + | |
| 3 | +import cn.hutool.core.map.MapUtil; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.context.ScriptContext; | |
| 5 | +import cn.iocoder.yudao.module.iot.plugin.script.sandbox.JsSandbox; | |
| 6 | +import cn.iocoder.yudao.module.iot.plugin.script.util.ScriptUtils; | |
| 7 | +import org.slf4j.Logger; | |
| 8 | +import org.slf4j.LoggerFactory; | |
| 9 | + | |
| 10 | +import javax.script.*; | |
| 11 | +import java.util.Map; | |
| 12 | +import java.util.concurrent.Callable; | |
| 13 | +import java.util.concurrent.ConcurrentHashMap; | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * JavaScript脚本引擎实现 | |
| 17 | + * 使用JSR-223 Nashorn脚本引擎 | |
| 18 | + */ | |
| 19 | +public class JsScriptEngine extends AbstractScriptEngine { | |
| 20 | + private static final Logger logger = LoggerFactory.getLogger(JsScriptEngine.class); | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * 默认脚本执行超时时间(毫秒) | |
| 24 | + */ | |
| 25 | + private static final long DEFAULT_TIMEOUT_MS = 5000; | |
| 26 | + | |
| 27 | + /** | |
| 28 | + * JavaScript引擎名称 | |
| 29 | + */ | |
| 30 | + private static final String JS_ENGINE_NAME = "nashorn"; | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * 脚本引擎管理器 | |
| 34 | + */ | |
| 35 | + private ScriptEngineManager engineManager; | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * 脚本引擎实例 | |
| 39 | + */ | |
| 40 | + private ScriptEngine engine; | |
| 41 | + | |
| 42 | + /** | |
| 43 | + * 脚本缓存 | |
| 44 | + */ | |
| 45 | + private final Map<String, Object> cachedScripts = new ConcurrentHashMap<>(); | |
| 46 | + | |
| 47 | + @Override | |
| 48 | + public void init() { | |
| 49 | + logger.info("初始化JavaScript脚本引擎"); | |
| 50 | + | |
| 51 | + // 创建脚本引擎管理器 | |
| 52 | + engineManager = new ScriptEngineManager(); | |
| 53 | + | |
| 54 | + // 获取JavaScript引擎 | |
| 55 | + engine = engineManager.getEngineByName(JS_ENGINE_NAME); | |
| 56 | + if (engine == null) { | |
| 57 | + logger.error("无法创建JavaScript引擎,尝试使用JavaScript名称获取"); | |
| 58 | + engine = engineManager.getEngineByName("JavaScript"); | |
| 59 | + } | |
| 60 | + | |
| 61 | + if (engine == null) { | |
| 62 | + throw new IllegalStateException("无法创建JavaScript引擎,请检查环境配置"); | |
| 63 | + } | |
| 64 | + | |
| 65 | + logger.info("成功创建JavaScript引擎: {}", engine.getClass().getName()); | |
| 66 | + | |
| 67 | + // 默认使用JS沙箱 | |
| 68 | + if (sandbox == null) { | |
| 69 | + setSandbox(new JsSandbox()); | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + @Override | |
| 74 | + public Object execute(String script, ScriptContext context) { | |
| 75 | + if (engine == null) { | |
| 76 | + init(); | |
| 77 | + } | |
| 78 | + | |
| 79 | + // 创建可超时执行的任务 | |
| 80 | + Callable<Object> task = () -> { | |
| 81 | + try { | |
| 82 | + // 创建脚本绑定 | |
| 83 | + Bindings bindings = new SimpleBindings(); | |
| 84 | + if (context != null) { | |
| 85 | + // 添加上下文参数 | |
| 86 | + Map<String, Object> contextParams = context.getParameters(); | |
| 87 | + if (MapUtil.isNotEmpty(contextParams)) { | |
| 88 | + bindings.putAll(contextParams); | |
| 89 | + } | |
| 90 | + | |
| 91 | + // 添加上下文函数 | |
| 92 | + bindings.putAll(context.getFunctions()); | |
| 93 | + } | |
| 94 | + | |
| 95 | + // 应用沙箱限制 | |
| 96 | + if (sandbox != null) { | |
| 97 | + sandbox.applySandbox(engine, script); | |
| 98 | + } | |
| 99 | + | |
| 100 | + // 执行脚本 | |
| 101 | + return engine.eval(script, bindings); | |
| 102 | + } catch (ScriptException e) { | |
| 103 | + logger.error("执行JavaScript脚本异常: {}", e.getMessage()); | |
| 104 | + throw new RuntimeException("脚本执行异常: " + e.getMessage(), e); | |
| 105 | + } | |
| 106 | + }; | |
| 107 | + | |
| 108 | + try { | |
| 109 | + // 使用超时执行器执行脚本 | |
| 110 | + return ScriptUtils.executeWithTimeout(task, DEFAULT_TIMEOUT_MS); | |
| 111 | + } catch (Exception e) { | |
| 112 | + logger.error("执行JavaScript脚本错误: {}", e.getMessage()); | |
| 113 | + throw new RuntimeException("脚本执行失败: " + e.getMessage(), e); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + | |
| 117 | + @Override | |
| 118 | + public Object execute(String script, Map<String, Object> params) { | |
| 119 | + if (engine == null) { | |
| 120 | + init(); | |
| 121 | + } | |
| 122 | + | |
| 123 | + // 创建可超时执行的任务 | |
| 124 | + Callable<Object> task = () -> { | |
| 125 | + try { | |
| 126 | + // 创建脚本绑定 | |
| 127 | + Bindings bindings = new SimpleBindings(); | |
| 128 | + if (MapUtil.isNotEmpty(params)) { | |
| 129 | + bindings.putAll(params); | |
| 130 | + } | |
| 131 | + | |
| 132 | + // 应用沙箱限制 | |
| 133 | + if (sandbox != null) { | |
| 134 | + sandbox.applySandbox(engine, script); | |
| 135 | + } | |
| 136 | + | |
| 137 | + // 执行脚本 | |
| 138 | + return engine.eval(script, bindings); | |
| 139 | + } catch (ScriptException e) { | |
| 140 | + logger.error("执行JavaScript脚本异常: {}", e.getMessage()); | |
| 141 | + throw new RuntimeException("脚本执行异常: " + e.getMessage(), e); | |
| 142 | + } | |
| 143 | + }; | |
| 144 | + | |
| 145 | + try { | |
| 146 | + // 使用超时执行器执行脚本 | |
| 147 | + return ScriptUtils.executeWithTimeout(task, DEFAULT_TIMEOUT_MS); | |
| 148 | + } catch (Exception e) { | |
| 149 | + logger.error("执行JavaScript脚本错误: {}", e.getMessage()); | |
| 150 | + throw new RuntimeException("脚本执行失败: " + e.getMessage(), e); | |
| 151 | + } | |
| 152 | + } | |
| 153 | + | |
| 154 | + @Override | |
| 155 | + public void destroy() { | |
| 156 | + logger.info("销毁JavaScript脚本引擎"); | |
| 157 | + cachedScripts.clear(); | |
| 158 | + engine = null; | |
| 159 | + engineManager = null; | |
| 160 | + } | |
| 161 | +} | |
| 0 | 162 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/engine/ScriptEngineFactory.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.engine; | |
| 2 | + | |
| 3 | +import org.slf4j.Logger; | |
| 4 | +import org.slf4j.LoggerFactory; | |
| 5 | +import org.springframework.stereotype.Component; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * 脚本引擎工厂,用于创建不同类型的脚本引擎 | |
| 9 | + */ | |
| 10 | +@Component | |
| 11 | +public class ScriptEngineFactory { | |
| 12 | + private static final Logger logger = LoggerFactory.getLogger(ScriptEngineFactory.class); | |
| 13 | + | |
| 14 | + /** | |
| 15 | + * 创建JavaScript脚本引擎 | |
| 16 | + * | |
| 17 | + * @return JavaScript脚本引擎 | |
| 18 | + */ | |
| 19 | + public JsScriptEngine createJsEngine() { | |
| 20 | + logger.debug("创建JavaScript脚本引擎"); | |
| 21 | + return new JsScriptEngine(); | |
| 22 | + } | |
| 23 | + | |
| 24 | + /** | |
| 25 | + * 根据脚本类型创建对应的脚本引擎 | |
| 26 | + * | |
| 27 | + * @param scriptType 脚本类型 | |
| 28 | + * @return 脚本引擎 | |
| 29 | + */ | |
| 30 | + public AbstractScriptEngine createEngine(String scriptType) { | |
| 31 | + if (scriptType == null || scriptType.isEmpty()) { | |
| 32 | + throw new IllegalArgumentException("脚本类型不能为空"); | |
| 33 | + } | |
| 34 | + | |
| 35 | + switch (scriptType.toLowerCase()) { | |
| 36 | + case "js": | |
| 37 | + case "javascript": | |
| 38 | + return createJsEngine(); | |
| 39 | + // 可以在这里添加其他类型的脚本引擎 | |
| 40 | + default: | |
| 41 | + throw new IllegalArgumentException("不支持的脚本类型: " + scriptType); | |
| 42 | + } | |
| 43 | + } | |
| 44 | +} | |
| 0 | 45 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/sandbox/JsSandbox.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.sandbox; | |
| 2 | + | |
| 3 | +import org.slf4j.Logger; | |
| 4 | +import org.slf4j.LoggerFactory; | |
| 5 | + | |
| 6 | +import javax.script.ScriptEngine; | |
| 7 | +import java.util.Arrays; | |
| 8 | +import java.util.HashSet; | |
| 9 | +import java.util.Set; | |
| 10 | +import java.util.regex.Pattern; | |
| 11 | + | |
| 12 | +/** | |
| 13 | + * JavaScript脚本沙箱,限制脚本的执行权限 | |
| 14 | + */ | |
| 15 | +public class JsSandbox implements ScriptSandbox { | |
| 16 | + private static final Logger logger = LoggerFactory.getLogger(JsSandbox.class); | |
| 17 | + | |
| 18 | + /** | |
| 19 | + * 禁止使用的关键字 | |
| 20 | + */ | |
| 21 | + private static final Set<String> FORBIDDEN_KEYWORDS = new HashSet<>(Arrays.asList( | |
| 22 | + "java.lang.System", "java.io", "java.nio", "java.net", "javax.net", | |
| 23 | + "java.security", "java.lang.reflect", "eval(", "Function(", "setTimeout", | |
| 24 | + "setInterval", "exec(", "execSync")); | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * 正则表达式匹配禁止的关键字 | |
| 28 | + */ | |
| 29 | + private static final Pattern FORBIDDEN_PATTERN = Pattern.compile( | |
| 30 | + "(?:import\\s+\\{\\s*.*\\s*\\}\\s+from)|" + | |
| 31 | + "(?:require\\s*\\()|" + | |
| 32 | + "(?:process\\.)|" + | |
| 33 | + "(?:globalThis\\.)|" + | |
| 34 | + "(?:\\bfs\\.)|" + | |
| 35 | + "(?:\\bchild_process\\b)|" + | |
| 36 | + "(?:\\bwindow\\b)"); | |
| 37 | + | |
| 38 | + /** | |
| 39 | + * 脚本执行超时时间(毫秒) | |
| 40 | + */ | |
| 41 | + private static final long SCRIPT_TIMEOUT_MS = 5000; | |
| 42 | + | |
| 43 | + @Override | |
| 44 | + public void applySandbox(Object engineContext, String script) { | |
| 45 | + if (!(engineContext instanceof ScriptEngine)) { | |
| 46 | + throw new IllegalArgumentException("引擎上下文类型不正确,无法应用JavaScript沙箱"); | |
| 47 | + } | |
| 48 | + | |
| 49 | + ScriptEngine engine = (ScriptEngine) engineContext; | |
| 50 | + | |
| 51 | + // 在Nashorn引擎中,可以通过以下方式设置安全限制 | |
| 52 | + try { | |
| 53 | + // 设置严格模式 | |
| 54 | + String securityPrefix = "'use strict';\n"; | |
| 55 | + | |
| 56 | + // 禁用Java.type等访问系统资源的功能 | |
| 57 | + engine.eval("var Java = undefined;"); | |
| 58 | + engine.eval("var JavaImporter = undefined;"); | |
| 59 | + engine.eval("var Packages = undefined;"); | |
| 60 | + | |
| 61 | + // 增强安全控制可以在这里添加 | |
| 62 | + logger.debug("已应用JavaScript安全沙箱限制"); | |
| 63 | + | |
| 64 | + } catch (Exception e) { | |
| 65 | + logger.warn("应用JavaScript沙箱限制失败: {}", e.getMessage()); | |
| 66 | + } | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Override | |
| 70 | + public boolean validateScript(String script) { | |
| 71 | + if (script == null || script.isEmpty()) { | |
| 72 | + return false; | |
| 73 | + } | |
| 74 | + | |
| 75 | + // 检查禁止的关键字 | |
| 76 | + for (String keyword : FORBIDDEN_KEYWORDS) { | |
| 77 | + if (script.contains(keyword)) { | |
| 78 | + logger.warn("脚本包含禁止使用的关键字: {}", keyword); | |
| 79 | + return false; | |
| 80 | + } | |
| 81 | + } | |
| 82 | + | |
| 83 | + // 使用正则表达式检查更复杂的模式 | |
| 84 | + if (FORBIDDEN_PATTERN.matcher(script).find()) { | |
| 85 | + logger.warn("脚本包含禁止使用的模式"); | |
| 86 | + return false; | |
| 87 | + } | |
| 88 | + | |
| 89 | + // 脚本长度限制 | |
| 90 | + if (script.length() > 1024 * 100) { // 限制100KB | |
| 91 | + logger.warn("脚本太大,超过了限制"); | |
| 92 | + return false; | |
| 93 | + } | |
| 94 | + | |
| 95 | + return true; | |
| 96 | + } | |
| 97 | +} | |
| 0 | 98 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/sandbox/ScriptSandbox.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.sandbox; | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * 脚本沙箱接口,提供脚本执行的安全限制 | |
| 5 | + */ | |
| 6 | +public interface ScriptSandbox { | |
| 7 | + | |
| 8 | + /** | |
| 9 | + * 应用沙箱限制到脚本执行环境 | |
| 10 | + * | |
| 11 | + * @param engineContext 引擎上下文 | |
| 12 | + * @param script 要执行的脚本内容 | |
| 13 | + */ | |
| 14 | + void applySandbox(Object engineContext, String script); | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * 检查脚本是否符合安全规则 | |
| 18 | + * | |
| 19 | + * @param script 要检查的脚本内容 | |
| 20 | + * @return 是否安全 | |
| 21 | + */ | |
| 22 | + boolean validateScript(String script); | |
| 23 | +} | |
| 0 | 24 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/service/ScriptService.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.service; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.context.ScriptContext; | |
| 4 | + | |
| 5 | +import java.util.Map; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * 脚本服务接口,定义脚本执行的核心功能 | |
| 9 | + */ | |
| 10 | +public interface ScriptService { | |
| 11 | + | |
| 12 | + /** | |
| 13 | + * 执行脚本 | |
| 14 | + * | |
| 15 | + * @param scriptType 脚本类型(如js、groovy等) | |
| 16 | + * @param script 脚本内容 | |
| 17 | + * @param context 脚本上下文 | |
| 18 | + * @return 脚本执行结果 | |
| 19 | + */ | |
| 20 | + Object executeScript(String scriptType, String script, ScriptContext context); | |
| 21 | + | |
| 22 | + /** | |
| 23 | + * 执行脚本 | |
| 24 | + * | |
| 25 | + * @param scriptType 脚本类型(如js、groovy等) | |
| 26 | + * @param script 脚本内容 | |
| 27 | + * @param params 脚本参数 | |
| 28 | + * @return 脚本执行结果 | |
| 29 | + */ | |
| 30 | + Object executeScript(String scriptType, String script, Map<String, Object> params); | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * 执行JavaScript脚本 | |
| 34 | + * | |
| 35 | + * @param script 脚本内容 | |
| 36 | + * @param context 脚本上下文 | |
| 37 | + * @return 脚本执行结果 | |
| 38 | + */ | |
| 39 | + Object executeJavaScript(String script, ScriptContext context); | |
| 40 | + | |
| 41 | + /** | |
| 42 | + * 执行JavaScript脚本 | |
| 43 | + * | |
| 44 | + * @param script 脚本内容 | |
| 45 | + * @param params 脚本参数 | |
| 46 | + * @return 脚本执行结果 | |
| 47 | + */ | |
| 48 | + Object executeJavaScript(String script, Map<String, Object> params); | |
| 49 | + | |
| 50 | + /** | |
| 51 | + * 验证脚本内容是否安全 | |
| 52 | + * | |
| 53 | + * @param scriptType 脚本类型 | |
| 54 | + * @param script 脚本内容 | |
| 55 | + * @return 脚本是否安全 | |
| 56 | + */ | |
| 57 | + boolean validateScript(String scriptType, String script); | |
| 58 | +} | |
| 0 | 59 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/service/ScriptServiceImpl.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.service; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.context.PluginScriptContext; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.context.ScriptContext; | |
| 5 | +import cn.iocoder.yudao.module.iot.plugin.script.engine.AbstractScriptEngine; | |
| 6 | +import cn.iocoder.yudao.module.iot.plugin.script.engine.ScriptEngineFactory; | |
| 7 | +import cn.iocoder.yudao.module.iot.plugin.script.sandbox.JsSandbox; | |
| 8 | +import cn.iocoder.yudao.module.iot.plugin.script.sandbox.ScriptSandbox; | |
| 9 | +import org.slf4j.Logger; | |
| 10 | +import org.slf4j.LoggerFactory; | |
| 11 | +import org.springframework.beans.factory.annotation.Autowired; | |
| 12 | +import org.springframework.stereotype.Service; | |
| 13 | + | |
| 14 | +import javax.annotation.PostConstruct; | |
| 15 | +import javax.annotation.PreDestroy; | |
| 16 | +import java.util.Map; | |
| 17 | +import java.util.concurrent.ConcurrentHashMap; | |
| 18 | + | |
| 19 | +/** | |
| 20 | + * 脚本服务实现类 | |
| 21 | + */ | |
| 22 | +@Service | |
| 23 | +public class ScriptServiceImpl implements ScriptService { | |
| 24 | + private static final Logger logger = LoggerFactory.getLogger(ScriptServiceImpl.class); | |
| 25 | + | |
| 26 | + @Autowired | |
| 27 | + private ScriptEngineFactory engineFactory; | |
| 28 | + | |
| 29 | + /** | |
| 30 | + * 脚本引擎缓存,避免重复创建 | |
| 31 | + */ | |
| 32 | + private final Map<String, AbstractScriptEngine> engineCache = new ConcurrentHashMap<>(); | |
| 33 | + | |
| 34 | + /** | |
| 35 | + * 脚本沙箱缓存 | |
| 36 | + */ | |
| 37 | + private final Map<String, ScriptSandbox> sandboxCache = new ConcurrentHashMap<>(); | |
| 38 | + | |
| 39 | + @PostConstruct | |
| 40 | + public void init() { | |
| 41 | + // 初始化常用的脚本引擎和沙箱 | |
| 42 | + getEngine("js"); | |
| 43 | + sandboxCache.put("js", new JsSandbox()); | |
| 44 | + } | |
| 45 | + | |
| 46 | + @PreDestroy | |
| 47 | + public void destroy() { | |
| 48 | + // 销毁所有引擎 | |
| 49 | + for (AbstractScriptEngine engine : engineCache.values()) { | |
| 50 | + try { | |
| 51 | + engine.destroy(); | |
| 52 | + } catch (Exception e) { | |
| 53 | + logger.error("销毁脚本引擎失败", e); | |
| 54 | + } | |
| 55 | + } | |
| 56 | + engineCache.clear(); | |
| 57 | + sandboxCache.clear(); | |
| 58 | + } | |
| 59 | + | |
| 60 | + @Override | |
| 61 | + public Object executeScript(String scriptType, String script, ScriptContext context) { | |
| 62 | + if (scriptType == null || script == null) { | |
| 63 | + throw new IllegalArgumentException("脚本类型和内容不能为空"); | |
| 64 | + } | |
| 65 | + | |
| 66 | + // 获取脚本引擎 | |
| 67 | + AbstractScriptEngine engine = getEngine(scriptType); | |
| 68 | + | |
| 69 | + // 验证脚本是否安全 | |
| 70 | + if (!validateScript(scriptType, script)) { | |
| 71 | + throw new SecurityException("脚本包含不安全的代码,无法执行"); | |
| 72 | + } | |
| 73 | + | |
| 74 | + try { | |
| 75 | + // 执行脚本 | |
| 76 | + return engine.execute(script, context); | |
| 77 | + } catch (Exception e) { | |
| 78 | + logger.error("执行脚本失败: {}", e.getMessage()); | |
| 79 | + throw new RuntimeException("执行脚本失败: " + e.getMessage(), e); | |
| 80 | + } | |
| 81 | + } | |
| 82 | + | |
| 83 | + @Override | |
| 84 | + public Object executeScript(String scriptType, String script, Map<String, Object> params) { | |
| 85 | + // 创建默认上下文 | |
| 86 | + ScriptContext context = new PluginScriptContext(params); | |
| 87 | + return executeScript(scriptType, script, context); | |
| 88 | + } | |
| 89 | + | |
| 90 | + @Override | |
| 91 | + public Object executeJavaScript(String script, ScriptContext context) { | |
| 92 | + return executeScript("js", script, context); | |
| 93 | + } | |
| 94 | + | |
| 95 | + @Override | |
| 96 | + public Object executeJavaScript(String script, Map<String, Object> params) { | |
| 97 | + return executeScript("js", script, params); | |
| 98 | + } | |
| 99 | + | |
| 100 | + @Override | |
| 101 | + public boolean validateScript(String scriptType, String script) { | |
| 102 | + ScriptSandbox sandbox = sandboxCache.get(scriptType.toLowerCase()); | |
| 103 | + if (sandbox == null) { | |
| 104 | + logger.warn("找不到脚本类型[{}]对应的沙箱,使用默认JS沙箱", scriptType); | |
| 105 | + sandbox = new JsSandbox(); | |
| 106 | + sandboxCache.put(scriptType.toLowerCase(), sandbox); | |
| 107 | + } | |
| 108 | + return sandbox.validateScript(script); | |
| 109 | + } | |
| 110 | + | |
| 111 | + /** | |
| 112 | + * 获取脚本引擎,如果不存在则创建 | |
| 113 | + * | |
| 114 | + * @param scriptType 脚本类型 | |
| 115 | + * @return 脚本引擎 | |
| 116 | + */ | |
| 117 | + private AbstractScriptEngine getEngine(String scriptType) { | |
| 118 | + return engineCache.computeIfAbsent(scriptType.toLowerCase(), type -> { | |
| 119 | + AbstractScriptEngine engine = engineFactory.createEngine(type); | |
| 120 | + engine.init(); | |
| 121 | + return engine; | |
| 122 | + }); | |
| 123 | + } | |
| 124 | +} | |
| 0 | 125 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/java/cn/iocoder/yudao/module/iot/plugin/script/util/ScriptUtils.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script.util; | |
| 2 | + | |
| 3 | +import cn.hutool.json.JSONUtil; | |
| 4 | +import org.slf4j.Logger; | |
| 5 | +import org.slf4j.LoggerFactory; | |
| 6 | + | |
| 7 | +import java.util.Map; | |
| 8 | +import java.util.concurrent.*; | |
| 9 | + | |
| 10 | +/** | |
| 11 | + * 脚本工具类,提供执行脚本的辅助方法 | |
| 12 | + */ | |
| 13 | +public class ScriptUtils { | |
| 14 | + private static final Logger logger = LoggerFactory.getLogger(ScriptUtils.class); | |
| 15 | + | |
| 16 | + /** | |
| 17 | + * 默认脚本执行超时时间(毫秒) | |
| 18 | + */ | |
| 19 | + private static final long DEFAULT_TIMEOUT_MS = 3000; | |
| 20 | + | |
| 21 | + /** | |
| 22 | + * 脚本执行线程池 | |
| 23 | + */ | |
| 24 | + private static final ExecutorService SCRIPT_EXECUTOR = new ThreadPoolExecutor( | |
| 25 | + 2, 10, 60L, TimeUnit.SECONDS, | |
| 26 | + new LinkedBlockingQueue<>(100), | |
| 27 | + r -> new Thread(r, "script-executor-" + r.hashCode()), | |
| 28 | + new ThreadPoolExecutor.CallerRunsPolicy()); | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * 带超时的执行任务 | |
| 32 | + * | |
| 33 | + * @param task 任务 | |
| 34 | + * @param timeoutMs 超时时间(毫秒) | |
| 35 | + * @param <T> 返回类型 | |
| 36 | + * @return 任务结果 | |
| 37 | + * @throws RuntimeException 执行异常 | |
| 38 | + */ | |
| 39 | + public static <T> T executeWithTimeout(Callable<T> task, long timeoutMs) { | |
| 40 | + Future<T> future = SCRIPT_EXECUTOR.submit(task); | |
| 41 | + try { | |
| 42 | + return future.get(timeoutMs, TimeUnit.MILLISECONDS); | |
| 43 | + } catch (TimeoutException e) { | |
| 44 | + future.cancel(true); | |
| 45 | + throw new RuntimeException("脚本执行超时,已终止"); | |
| 46 | + } catch (InterruptedException e) { | |
| 47 | + Thread.currentThread().interrupt(); | |
| 48 | + throw new RuntimeException("脚本执行被中断"); | |
| 49 | + } catch (ExecutionException e) { | |
| 50 | + throw new RuntimeException("脚本执行失败: " + e.getCause().getMessage(), e.getCause()); | |
| 51 | + } | |
| 52 | + } | |
| 53 | + | |
| 54 | + /** | |
| 55 | + * 带默认超时的执行任务 | |
| 56 | + * | |
| 57 | + * @param task 任务 | |
| 58 | + * @param <T> 返回类型 | |
| 59 | + * @return 任务结果 | |
| 60 | + * @throws RuntimeException 执行异常 | |
| 61 | + */ | |
| 62 | + public static <T> T executeWithTimeout(Callable<T> task) { | |
| 63 | + return executeWithTimeout(task, DEFAULT_TIMEOUT_MS); | |
| 64 | + } | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * 关闭工具类的线程池 | |
| 68 | + */ | |
| 69 | + public static void shutdown() { | |
| 70 | + SCRIPT_EXECUTOR.shutdown(); | |
| 71 | + try { | |
| 72 | + if (!SCRIPT_EXECUTOR.awaitTermination(10, TimeUnit.SECONDS)) { | |
| 73 | + SCRIPT_EXECUTOR.shutdownNow(); | |
| 74 | + } | |
| 75 | + } catch (InterruptedException e) { | |
| 76 | + SCRIPT_EXECUTOR.shutdownNow(); | |
| 77 | + Thread.currentThread().interrupt(); | |
| 78 | + } | |
| 79 | + } | |
| 80 | + | |
| 81 | + /** | |
| 82 | + * 将JSON字符串转换为Map | |
| 83 | + * | |
| 84 | + * @param json JSON字符串 | |
| 85 | + * @return Map对象,转换失败则返回null | |
| 86 | + */ | |
| 87 | + @SuppressWarnings("unchecked") | |
| 88 | + public static Map<String, Object> parseJson(String json) { | |
| 89 | + try { | |
| 90 | + // 使用hutool的JSONUtil工具类解析JSON | |
| 91 | + return JSONUtil.toBean(json, Map.class); | |
| 92 | + } catch (Exception e) { | |
| 93 | + logger.error("解析JSON失败: {}", e.getMessage()); | |
| 94 | + return null; | |
| 95 | + } | |
| 96 | + } | |
| 97 | + | |
| 98 | + /** | |
| 99 | + * 尝试将对象转换为整数 | |
| 100 | + * | |
| 101 | + * @param obj 需要转换的对象 | |
| 102 | + * @return 转换后的整数,如果无法转换则返回null | |
| 103 | + */ | |
| 104 | + public static Integer toInteger(Object obj) { | |
| 105 | + if (obj == null) { | |
| 106 | + return null; | |
| 107 | + } | |
| 108 | + | |
| 109 | + if (obj instanceof Integer) { | |
| 110 | + return (Integer) obj; | |
| 111 | + } else if (obj instanceof Number) { | |
| 112 | + return ((Number) obj).intValue(); | |
| 113 | + } else if (obj instanceof String) { | |
| 114 | + try { | |
| 115 | + return Integer.parseInt((String) obj); | |
| 116 | + } catch (NumberFormatException e) { | |
| 117 | + logger.debug("无法将字符串转换为整数: {}", obj); | |
| 118 | + return null; | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + logger.debug("无法将对象转换为整数: {}", obj.getClass().getName()); | |
| 123 | + return null; | |
| 124 | + } | |
| 125 | + | |
| 126 | + /** | |
| 127 | + * 尝试将对象转换为双精度浮点数 | |
| 128 | + * | |
| 129 | + * @param obj 需要转换的对象 | |
| 130 | + * @return 转换后的双精度浮点数,如果无法转换则返回null | |
| 131 | + */ | |
| 132 | + public static Double toDouble(Object obj) { | |
| 133 | + if (obj == null) { | |
| 134 | + return null; | |
| 135 | + } | |
| 136 | + | |
| 137 | + if (obj instanceof Double) { | |
| 138 | + return (Double) obj; | |
| 139 | + } else if (obj instanceof Number) { | |
| 140 | + return ((Number) obj).doubleValue(); | |
| 141 | + } else if (obj instanceof String) { | |
| 142 | + try { | |
| 143 | + return Double.parseDouble((String) obj); | |
| 144 | + } catch (NumberFormatException e) { | |
| 145 | + logger.debug("无法将字符串转换为双精度浮点数: {}", obj); | |
| 146 | + return null; | |
| 147 | + } | |
| 148 | + } | |
| 149 | + | |
| 150 | + logger.debug("无法将对象转换为双精度浮点数: {}", obj.getClass().getName()); | |
| 151 | + return null; | |
| 152 | + } | |
| 153 | + | |
| 154 | + /** | |
| 155 | + * 比较两个数值是否相等,忽略其具体类型 | |
| 156 | + * | |
| 157 | + * @param a 第一个数值 | |
| 158 | + * @param b 第二个数值 | |
| 159 | + * @return 如果两个数值相等则返回true,否则返回false | |
| 160 | + */ | |
| 161 | + public static boolean numbersEqual(Number a, Number b) { | |
| 162 | + if (a == null || b == null) { | |
| 163 | + return a == b; | |
| 164 | + } | |
| 165 | + | |
| 166 | + return Math.abs(a.doubleValue() - b.doubleValue()) < 0.0000001; | |
| 167 | + } | |
| 168 | +} | |
| 0 | 169 | \ No newline at end of file | ... | ... |
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
0 → 100644
yudao-module-iot/yudao-module-iot-plugins/yudao-module-iot-plugin-script/src/test/java/cn/iocoder/yudao/module/iot/plugin/script/ScriptServiceTest.java
0 → 100644
| 1 | +package cn.iocoder.yudao.module.iot.plugin.script; | |
| 2 | + | |
| 3 | +import cn.iocoder.yudao.module.iot.plugin.script.context.PluginScriptContext; | |
| 4 | +import cn.iocoder.yudao.module.iot.plugin.script.engine.ScriptEngineFactory; | |
| 5 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptService; | |
| 6 | +import cn.iocoder.yudao.module.iot.plugin.script.service.ScriptServiceImpl; | |
| 7 | +import org.junit.jupiter.api.BeforeEach; | |
| 8 | +import org.junit.jupiter.api.Test; | |
| 9 | + | |
| 10 | +import java.util.HashMap; | |
| 11 | +import java.util.Map; | |
| 12 | + | |
| 13 | +import static org.junit.jupiter.api.Assertions.*; | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * 脚本服务单元测试 | |
| 17 | + */ | |
| 18 | +class ScriptServiceTest { | |
| 19 | + | |
| 20 | + private ScriptService scriptService; | |
| 21 | + | |
| 22 | + @BeforeEach | |
| 23 | + void setUp() { | |
| 24 | + ScriptEngineFactory engineFactory = new ScriptEngineFactory(); | |
| 25 | + ScriptServiceImpl service = new ScriptServiceImpl(); | |
| 26 | + | |
| 27 | + // 使用反射设置engineFactory | |
| 28 | + try { | |
| 29 | + java.lang.reflect.Field field = ScriptServiceImpl.class.getDeclaredField("engineFactory"); | |
| 30 | + field.setAccessible(true); | |
| 31 | + field.set(service, engineFactory); | |
| 32 | + } catch (Exception e) { | |
| 33 | + throw new RuntimeException("设置测试依赖失败", e); | |
| 34 | + } | |
| 35 | + | |
| 36 | + service.init(); // 手动调用初始化方法 | |
| 37 | + this.scriptService = service; | |
| 38 | + } | |
| 39 | + | |
| 40 | + @Test | |
| 41 | + void testExecuteSimpleScript() { | |
| 42 | + // 准备 | |
| 43 | + String script = "var result = a + b; result;"; | |
| 44 | + Map<String, Object> params = new HashMap<>(); | |
| 45 | + params.put("a", 10); | |
| 46 | + params.put("b", 20); | |
| 47 | + | |
| 48 | + // 执行 | |
| 49 | + Object result = scriptService.executeJavaScript(script, params); | |
| 50 | + | |
| 51 | + // 验证 - 使用delta比较,允许浮点数和整数比较 | |
| 52 | + assertEquals(30.0, ((Number) result).doubleValue(), 0.001); | |
| 53 | + } | |
| 54 | + | |
| 55 | + @Test | |
| 56 | + void testExecuteObjectResult() { | |
| 57 | + // 准备 | |
| 58 | + String script = "var obj = { name: 'test', value: 123 }; obj;"; | |
| 59 | + | |
| 60 | + // 执行 | |
| 61 | + Object result = scriptService.executeJavaScript(script, new HashMap<>()); | |
| 62 | + | |
| 63 | + // 验证 | |
| 64 | + assertNotNull(result); | |
| 65 | + assertTrue(result instanceof Map); | |
| 66 | + | |
| 67 | + @SuppressWarnings("unchecked") | |
| 68 | + Map<String, Object> map = (Map<String, Object>) result; | |
| 69 | + assertEquals("test", map.get("name")); | |
| 70 | + | |
| 71 | + // 对于数值,先转换为double再比较 | |
| 72 | + assertEquals(123.0, ((Number) map.get("value")).doubleValue(), 0.001); | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test | |
| 76 | + void testExecuteWithContext() { | |
| 77 | + // 准备 | |
| 78 | + String script = "var message = 'Hello, ' + name + '!'; message;"; | |
| 79 | + PluginScriptContext context = new PluginScriptContext(); | |
| 80 | + context.setParameter("name", "World"); | |
| 81 | + | |
| 82 | + // 执行 | |
| 83 | + Object result = scriptService.executeJavaScript(script, context); | |
| 84 | + | |
| 85 | + // 验证 | |
| 86 | + assertEquals("Hello, World!", result); | |
| 87 | + } | |
| 88 | + | |
| 89 | + @Test | |
| 90 | + void testScriptWithFunction() { | |
| 91 | + // 准备 | |
| 92 | + String script = "function add(x, y) { return x + y; } add(a, b);"; | |
| 93 | + Map<String, Object> params = new HashMap<>(); | |
| 94 | + params.put("a", 15); | |
| 95 | + params.put("b", 25); | |
| 96 | + | |
| 97 | + // 执行 | |
| 98 | + Object result = scriptService.executeJavaScript(script, params); | |
| 99 | + | |
| 100 | + // 验证 - 使用delta比较,允许浮点数和整数比较 | |
| 101 | + assertEquals(40.0, ((Number) result).doubleValue(), 0.001); | |
| 102 | + } | |
| 103 | + | |
| 104 | + @Test | |
| 105 | + void testExecuteInvalidScript() { | |
| 106 | + // 准备 | |
| 107 | + String script = "invalid syntax"; | |
| 108 | + | |
| 109 | + // 执行和验证 | |
| 110 | + assertThrows(RuntimeException.class, () -> { | |
| 111 | + scriptService.executeJavaScript(script, new HashMap<>()); | |
| 112 | + }); | |
| 113 | + } | |
| 114 | + | |
| 115 | + @Test | |
| 116 | + void testScriptTimeout() { | |
| 117 | + // 准备 - 一个无限循环的脚本 | |
| 118 | + String script = "while(true) { }"; | |
| 119 | + | |
| 120 | + // 执行和验证 | |
| 121 | + assertThrows(RuntimeException.class, () -> { | |
| 122 | + scriptService.executeJavaScript(script, new HashMap<>()); | |
| 123 | + }); | |
| 124 | + } | |
| 125 | +} | |
| 0 | 126 | \ No newline at end of file | ... | ... |