Commit 87a43b8354c0638130a37a4e9d926aef1db0d608
1 parent
2f9d7603
【功能新增】IoT: 添加脚本引擎模块,支持设备数据解析和命令生成
Showing
22 changed files
with
1589 additions
and
66 deletions
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 | ... | ... |