Commit 195c4c9becaeaed52530af6fdec55a4dd9c7a8fd

Authored by 黄 x
1 parent 889e4ec4

fix: add Configuration Center thumbnail and device script return id

... ... @@ -59,205 +59,207 @@ import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.
59 59 @RequestMapping("api/yt/js")
60 60 @Api(tags = {"设备数据解析脚本管理"})
61 61 public class YtDeviceScriptController extends BaseController {
62   - private final YtDeviceScriptService scriptService;
63   - private final YtDeviceProfileService ytDeviceProfileService;
64   - private final YtScriptInvokeService jsEngine;
65   - private static final JsonParser parser = new JsonParser();
66   -
67   - private static final ObjectMapper objectMapper = new ObjectMapper();
68   -
69   - @PostMapping()
70   - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:js:post','api:yt:js:update'})")
71   - @ApiOperation("创建 | 编辑")
72   - public ResponseEntity<YtDeviceScriptDTO> saveJavaScript(
73   - @RequestBody YtDeviceScriptDTO scriptDTO) throws ThingsboardException {
74   - String id = scriptDTO.getId();
75   - boolean created = StringUtils.isBlank(id);
76   - String tenantId = getCurrentUser().getCurrentTenantId();
77   - scriptDTO.setTenantId(tenantId);
78   - scriptService.validateFormdata(scriptDTO,created);
79   - /**
80   - * 业务流程
81   - * 1/3.编辑时同步刷新相关的设备配置
82   - * 2/3.处理TB业务逻辑
83   - * 3/3.处理业务平台的业务逻辑
84   - */
85   - if(!created){
86   - List<DeviceProfileDTO> usedProfiles =ytDeviceProfileService.findDeviceProfile(tenantId,id);
87   - for(DeviceProfileDTO profile:usedProfiles){
88   - DeviceProfile tbDeviceProfile = buildTbDeviceProfileFromDeviceProfileDTO(profile,scriptDTO.getTenantId(),scriptDTO.getConvertJs());
89   - updateTbDeviceProfile(tbDeviceProfile);
90   - }
91   -
92   - }
93   -
94   -
95   - String creator = getCurrentUser().getCurrentUserId();
96   - scriptDTO.setCreator(creator);
97   - scriptDTO.setUpdater(creator);
98   - scriptService.insertOrUpdate(scriptDTO);
99   -
100   - return ResponseEntity.ok(scriptDTO);
  62 + private static final JsonParser parser = new JsonParser();
  63 + private static final ObjectMapper objectMapper = new ObjectMapper();
  64 + private final YtDeviceScriptService scriptService;
  65 + private final YtDeviceProfileService ytDeviceProfileService;
  66 + private final YtScriptInvokeService jsEngine;
  67 +
  68 + @PostMapping()
  69 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:js:post','api:yt:js:update'})")
  70 + @ApiOperation("创建 | 编辑")
  71 + public ResponseEntity<YtDeviceScriptDTO> saveJavaScript(@RequestBody YtDeviceScriptDTO scriptDTO)
  72 + throws ThingsboardException {
  73 + String id = scriptDTO.getId();
  74 + boolean created = StringUtils.isBlank(id);
  75 + String tenantId = getCurrentUser().getCurrentTenantId();
  76 + scriptDTO.setTenantId(tenantId);
  77 + scriptService.validateFormdata(scriptDTO, created);
  78 + /** 业务流程 1/3.编辑时同步刷新相关的设备配置 2/3.处理TB业务逻辑 3/3.处理业务平台的业务逻辑 */
  79 + if (!created) {
  80 + List<DeviceProfileDTO> usedProfiles = ytDeviceProfileService.findDeviceProfile(tenantId, id);
  81 + for (DeviceProfileDTO profile : usedProfiles) {
  82 + DeviceProfile tbDeviceProfile =
  83 + buildTbDeviceProfileFromDeviceProfileDTO(
  84 + profile, scriptDTO.getTenantId(), scriptDTO.getConvertJs());
  85 + updateTbDeviceProfile(tbDeviceProfile);
  86 + }
101 87 }
102 88
103   - /**
104   - * 更新thingsboard的设备配置信息
105   - *
106   - * @param deviceProfile 设备配置
107   - * @throws ThingsboardException
108   - */
109   - private DeviceProfile updateTbDeviceProfile(DeviceProfile deviceProfile) throws ThingsboardException {
110   - boolean isFirmwareChanged = false;
111   - boolean isSoftwareChanged = false;
112   -
113   - DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(getTenantId(), deviceProfile.getId());
114   - if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
115   - isFirmwareChanged = true;
116   - }
117   - if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
118   - isSoftwareChanged = true;
119   - }
120   - if (FastIotConstants.ASSERT_DEFAULT_NAME.equals(oldDeviceProfile.getName()) && !Objects.equals(deviceProfile.getName(), oldDeviceProfile.getName())) {
121   - throw new YtDataValidationException(ErrorMessage.ASSERT_DEFAULT_NAME_NO_CHANGED.getMessage());
122   - }
123   -
124   - DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
125   -
126   - tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
127   - tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), savedDeviceProfile.getId(), ComponentLifecycleEvent.UPDATED);
128   -
129   - logEntityAction(savedDeviceProfile.getId(), savedDeviceProfile,
130   - null,ActionType.UPDATED, null);
131   -
132   - otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
133   -
134   - sendEntityNotificationMsg(getTenantId(), savedDeviceProfile.getId(),EdgeEventActionType.UPDATED);
135   - return savedDeviceProfile;
  89 + String creator = getCurrentUser().getCurrentUserId();
  90 + scriptDTO.setCreator(creator);
  91 + scriptDTO.setUpdater(creator);
  92 + return ResponseEntity.ok(scriptService.insertOrUpdate(scriptDTO));
  93 + }
  94 +
  95 + /**
  96 + * 更新thingsboard的设备配置信息
  97 + *
  98 + * @param deviceProfile 设备配置
  99 + * @throws ThingsboardException
  100 + */
  101 + private DeviceProfile updateTbDeviceProfile(DeviceProfile deviceProfile)
  102 + throws ThingsboardException {
  103 + boolean isFirmwareChanged = false;
  104 + boolean isSoftwareChanged = false;
  105 +
  106 + DeviceProfile oldDeviceProfile =
  107 + deviceProfileService.findDeviceProfileById(getTenantId(), deviceProfile.getId());
  108 + if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
  109 + isFirmwareChanged = true;
136 110 }
137   -
138   - @GetMapping("{id}")
139   - @ApiOperation("详情")
140   -// @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:deviceProfile:get'})")
141   - public ResponseEntity<YtDeviceScriptDTO> getDevice(@PathVariable("id") String id) throws ThingsboardException {
142   - return ResponseEntity.of(scriptService.getDeviceScript(getCurrentUser().getCurrentTenantId(), id));
  111 + if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
  112 + isSoftwareChanged = true;
143 113 }
144   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
145   - @GetMapping(params = {PAGE_SIZE, PAGE})
146   - @ApiOperation("分页查询")
147   - public YtPageData<YtDeviceScriptDTO> pageDeviceProfile(
148   - @RequestParam(PAGE_SIZE) int pageSize,
149   - @RequestParam(PAGE) int page,
150   - @RequestParam(value = "name", required = false) String name,
151   - @RequestParam(value = "transportType", required = false) String transportType,
152   - @RequestParam(value = ORDER_FILED, required = false) String orderFiled,
153   - @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType) throws ThingsboardException {
154   -
155   - return scriptService.page(page, pageSize, orderFiled, orderType, getCurrentUser().getCurrentTenantId());
  114 + if (FastIotConstants.ASSERT_DEFAULT_NAME.equals(oldDeviceProfile.getName())
  115 + && !Objects.equals(deviceProfile.getName(), oldDeviceProfile.getName())) {
  116 + throw new YtDataValidationException(ErrorMessage.ASSERT_DEFAULT_NAME_NO_CHANGED.getMessage());
156 117 }
157 118
158   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
159   - @GetMapping("/me/list")
160   - @ApiOperation("选项列表")
161   - public ResponseEntity listDeviceProfile() throws ThingsboardException {
162   - List<YtDeviceScriptDTO> results = scriptService.findDeviceScript(getCurrentUser().getCurrentTenantId());
163   - return ResponseEntity.ok(results);
  119 + DeviceProfile savedDeviceProfile =
  120 + checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
  121 +
  122 + tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
  123 + tbClusterService.broadcastEntityStateChangeEvent(
  124 + deviceProfile.getTenantId(), savedDeviceProfile.getId(), ComponentLifecycleEvent.UPDATED);
  125 +
  126 + logEntityAction(savedDeviceProfile.getId(), savedDeviceProfile, null, ActionType.UPDATED, null);
  127 +
  128 + otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
  129 +
  130 + sendEntityNotificationMsg(
  131 + getTenantId(), savedDeviceProfile.getId(), EdgeEventActionType.UPDATED);
  132 + return savedDeviceProfile;
  133 + }
  134 +
  135 + @GetMapping("{id}")
  136 + @ApiOperation("详情")
  137 + // @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:deviceProfile:get'})")
  138 + public ResponseEntity<YtDeviceScriptDTO> getDevice(@PathVariable("id") String id)
  139 + throws ThingsboardException {
  140 + return ResponseEntity.of(
  141 + scriptService.getDeviceScript(getCurrentUser().getCurrentTenantId(), id));
  142 + }
  143 +
  144 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
  145 + @GetMapping(params = {PAGE_SIZE, PAGE})
  146 + @ApiOperation("分页查询")
  147 + public YtPageData<YtDeviceScriptDTO> pageDeviceProfile(
  148 + @RequestParam(PAGE_SIZE) int pageSize,
  149 + @RequestParam(PAGE) int page,
  150 + @RequestParam(value = "name", required = false) String name,
  151 + @RequestParam(value = "transportType", required = false) String transportType,
  152 + @RequestParam(value = ORDER_FILED, required = false) String orderFiled,
  153 + @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType)
  154 + throws ThingsboardException {
  155 +
  156 + return scriptService.page(
  157 + page, pageSize, orderFiled, orderType, getCurrentUser().getCurrentTenantId());
  158 + }
  159 +
  160 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
  161 + @GetMapping("/me/list")
  162 + @ApiOperation("选项列表")
  163 + public ResponseEntity listDeviceProfile() throws ThingsboardException {
  164 + List<YtDeviceScriptDTO> results =
  165 + scriptService.findDeviceScript(getCurrentUser().getCurrentTenantId());
  166 + return ResponseEntity.ok(results);
  167 + }
  168 +
  169 + @DeleteMapping
  170 + @ApiOperation("删除")
  171 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:deviceProfile:delete'})")
  172 + public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)
  173 + throws ThingsboardException {
  174 + scriptService.deleteScriptes(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
  175 + }
  176 +
  177 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
  178 + @PostMapping("/test")
  179 + @ApiOperation("测试脚本执行结果")
  180 + public ResponseEntity<JsonNode> test(@RequestBody JsonNode inputParams)
  181 + throws ThingsboardException {
  182 + try {
  183 + String script = inputParams.get("script").asText();
  184 + String jsParam = inputParams.get("params").asText();
  185 +
  186 + String output = "";
  187 + String errorText = "";
  188 + ScriptEngine engine = null;
  189 + try {
  190 + UUID scriptId = jsEngine.eval(YtScriptType.TCP_TRANSPORT_SCRIPT, script).get();
  191 + ListenableFuture<String> result =
  192 + Futures.transformAsync(
  193 + jsEngine.invokeFunction(scriptId, jsParam),
  194 + o -> {
  195 + try {
  196 + JsonElement json = parser.parse(o.toString());
  197 + return Futures.immediateFuture(json.toString());
  198 + } catch (Exception e) {
  199 + return Futures.immediateFailedFuture(e);
  200 + }
  201 + },
  202 + MoreExecutors.directExecutor());
  203 +
  204 + output = result.get(20, TimeUnit.SECONDS);
  205 + } catch (Exception e) {
  206 + errorText = e.getMessage();
  207 + } finally {
  208 + if (engine != null) {
  209 + engine.destroy();
  210 + }
  211 + }
  212 + ObjectNode result = objectMapper.createObjectNode();
  213 + result.put("output", output);
  214 + result.put("error", errorText);
  215 + return ResponseEntity.ok(result);
  216 + } catch (Exception e) {
  217 + throw handleException(e);
164 218 }
165   -
166   - @DeleteMapping
167   - @ApiOperation("删除")
168   - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:deviceProfile:delete'})")
169   - public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException {
170   - scriptService.deleteScriptes(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
  219 + }
  220 +
  221 + /**
  222 + * 构造调用TBDeviceProfile需要的参数
  223 + *
  224 + * @param deviceProfileDTO 页面接收的参数
  225 + * @return 封装好的TBDeviceProfile
  226 + */
  227 + private DeviceProfile buildTbDeviceProfileFromDeviceProfileDTO(
  228 + DeviceProfileDTO deviceProfileDTO, String scriptId, String scriptText) {
  229 + DeviceProfile tbDeviceProfile = new DeviceProfile();
  230 + if (StringUtils.isNotBlank(deviceProfileDTO.getId())) {
  231 + UUID profileId = UUID.fromString(deviceProfileDTO.getId());
  232 + tbDeviceProfile.setId(new DeviceProfileId(profileId));
  233 + tbDeviceProfile.setCreatedTime(
  234 + deviceProfileDTO.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
  235 + } else {
  236 + tbDeviceProfile.setCreatedTime(
  237 + LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
171 238 }
172   -
173   -
174   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
175   - @PostMapping("/test")
176   - @ApiOperation("测试脚本执行结果")
177   - public ResponseEntity<JsonNode> test(@RequestBody JsonNode inputParams) throws ThingsboardException {
178   - try {
179   - String script = inputParams.get("script").asText();
180   - String jsParam = inputParams.get("params").asText();
181   -
182   -
183   - String output = "";
184   - String errorText = "";
185   - ScriptEngine engine = null;
186   - try {
187   - UUID scriptId = jsEngine.eval(YtScriptType.TCP_TRANSPORT_SCRIPT, script).get();
188   - ListenableFuture<String> result = Futures.transformAsync(jsEngine.invokeFunction(scriptId, jsParam),
189   - o -> {
190   - try {
191   - JsonElement json = parser.parse(o.toString());
192   - return Futures.immediateFuture(json.toString());
193   - } catch (Exception e) {
194   - return Futures.immediateFailedFuture(e);
195   - }
196   - }, MoreExecutors.directExecutor());
197   -
198   - output =result.get(20, TimeUnit.SECONDS);
199   - } catch (Exception e) {
200   - errorText = e.getMessage();
201   - } finally {
202   - if (engine != null) {
203   - engine.destroy();
204   - }
205   - }
206   - ObjectNode result = objectMapper.createObjectNode();
207   - result.put("output", output);
208   - result.put("error", errorText);
209   - return ResponseEntity.ok(result);
210   - } catch (Exception e) {
211   - throw handleException(e);
212   - }
213   -
214   -
  239 + tbDeviceProfile.setName(deviceProfileDTO.getName());
  240 + tbDeviceProfile.setImage(deviceProfileDTO.getImage());
  241 + tbDeviceProfile.setDescription(deviceProfileDTO.getDescription());
  242 + tbDeviceProfile.setType(DeviceProfileType.DEFAULT);
  243 + UUID tenantId = UUID.fromString(deviceProfileDTO.getTenantId());
  244 + tbDeviceProfile.setTenantId(TenantId.fromUUID(tenantId));
  245 + tbDeviceProfile.setDefault(deviceProfileDTO.isDefault());
  246 +
  247 + // 获取当前租户的默认规则链
  248 + if (StringUtils.isNotBlank(deviceProfileDTO.getDefaultRuleChainId())) {
  249 + UUID chainId = UUID.fromString(deviceProfileDTO.getDefaultRuleChainId());
  250 + tbDeviceProfile.setDefaultRuleChainId(new RuleChainId(chainId));
215 251 }
216 252
  253 + tbDeviceProfile.setDefaultQueueName(ServiceQueue.MAIN);
  254 + tbDeviceProfile.setProvisionType(DeviceProfileProvisionType.DISABLED);
217 255
  256 + // 传输类型默认都是Default
  257 + String transportType = deviceProfileDTO.getTransportType();
  258 + tbDeviceProfile.setTransportType(DeviceTransportType.valueOf(transportType));
218 259
219   -
220   -
221   - /**
222   - * 构造调用TBDeviceProfile需要的参数
223   - *
224   - * @param deviceProfileDTO 页面接收的参数
225   - * @return 封装好的TBDeviceProfile
226   - */
227   - private DeviceProfile buildTbDeviceProfileFromDeviceProfileDTO(DeviceProfileDTO deviceProfileDTO,String scriptId,String scriptText) {
228   - DeviceProfile tbDeviceProfile = new DeviceProfile();
229   - if (StringUtils.isNotBlank(deviceProfileDTO.getId())) {
230   - UUID profileId = UUID.fromString(deviceProfileDTO.getId());
231   - tbDeviceProfile.setId(new DeviceProfileId(profileId));
232   - tbDeviceProfile.setCreatedTime(deviceProfileDTO.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
233   - }else{
234   - tbDeviceProfile.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
235   - }
236   - tbDeviceProfile.setName(deviceProfileDTO.getName());
237   - tbDeviceProfile.setImage(deviceProfileDTO.getImage());
238   - tbDeviceProfile.setDescription(deviceProfileDTO.getDescription());
239   - tbDeviceProfile.setType(DeviceProfileType.DEFAULT);
240   - UUID tenantId = UUID.fromString(deviceProfileDTO.getTenantId());
241   - tbDeviceProfile.setTenantId(TenantId.fromUUID(tenantId));
242   - tbDeviceProfile.setDefault(deviceProfileDTO.isDefault());
243   -
244   - // 获取当前租户的默认规则链
245   - if (StringUtils.isNotBlank(deviceProfileDTO.getDefaultRuleChainId())) {
246   - UUID chainId = UUID.fromString(deviceProfileDTO.getDefaultRuleChainId());
247   - tbDeviceProfile.setDefaultRuleChainId(new RuleChainId(chainId));
248   - }
249   -
250   - tbDeviceProfile.setDefaultQueueName(ServiceQueue.MAIN);
251   - tbDeviceProfile.setProvisionType(DeviceProfileProvisionType.DISABLED);
252   -
253   -
254   - // 传输类型默认都是Default
255   - String transportType = deviceProfileDTO.getTransportType();
256   - tbDeviceProfile.setTransportType(DeviceTransportType.valueOf(transportType));
257   -
258   -
259   - deviceProfileDTO.setScriptId(scriptId);
260   - tbDeviceProfile.setProfileData(buildDeviceProfileData(transportType,deviceProfileDTO.getProfileData(),scriptText));
261   - return tbDeviceProfile;
262   - }
  260 + deviceProfileDTO.setScriptId(scriptId);
  261 + tbDeviceProfile.setProfileData(
  262 + buildDeviceProfileData(transportType, deviceProfileDTO.getProfileData(), scriptText));
  263 + return tbDeviceProfile;
  264 + }
263 265 }
... ...
... ... @@ -32,5 +32,8 @@ public class ConfigurationCenterDTO extends TenantDTO {
32 32 groups = {UpdateGroup.class, AddGroup.class})
33 33 private String platform;
34 34
  35 + @ApiModelProperty(value = "组态缩略图")
  36 + private String thumbnail;
  37 +
35 38 private OrganizationDTO organizationDTO;
36 39 }
... ...
... ... @@ -14,4 +14,5 @@ public class ConfigurationCenter extends TenantBaseEntity {
14 14 private String remark;
15 15 private String organizationId;
16 16 private String platform;
  17 + private String thumbnail;
17 18 }
... ...
... ... @@ -13,6 +13,7 @@
13 13 <result property="creator" column="creator"/>
14 14 <result property="tenantId" column="tenant_id"/>
15 15 <result property="updater" column="updater"/>
  16 + <result property="thumbnail" column="thumbnail"/>
16 17 <association property="organizationDTO"
17 18 javaType="org.thingsboard.server.common.data.yunteng.dto.OrganizationDTO">
18 19 <result property="name" column="organization_name"/>
... ... @@ -29,7 +30,7 @@
29 30 </resultMap>
30 31
31 32 <sql id="columns">
32   - a.id,a.name,a.platform,a.organization_id,a.remark,a.update_time,a.create_time,a.creator,a.tenant_id,a.updater,io.name AS organization_name
  33 + a.id,a.name,a.platform,a.organization_id,a.thumbnail, a.remark,a.update_time,a.create_time,a.creator,a.tenant_id,a.updater,io.name AS organization_name
33 34 </sql>
34 35 <select id="getConfigurationCenterPage" resultMap="configurationCenterMap">
35 36 SELECT
... ... @@ -56,7 +57,7 @@
56 57 </select>
57 58
58 59 <select id="getConfigurationInfoById" resultMap="configurationInfoMap">
59   - SELECT icc.id,icc.name,icc.platform,icct.id AS content_id,icct.content FROM iotfs_configuration_center icc LEFT JOIN
  60 + SELECT icc.id,icc.name,icc.platform,icc.thumbnail,icct.id AS content_id,icct.content FROM iotfs_configuration_center icc LEFT JOIN
60 61 iotfs_configuration_content icct ON icc.id = icct.configuration_id
61 62 WHERE icc.id = #{id} AND icc.tenant_id = #{tenantId}
62 63 </select>
... ...