Commit 85cba202f9102d411df48201e44f39fdf1a7aa8c

Authored by 云中非
1 parent c9c6d769

refactor: 迁移代码

1.合并设备管理
2.合并设备配置
... ... @@ -15,6 +15,7 @@
15 15 */
16 16 package org.thingsboard.server.controller;
17 17
  18 +import io.swagger.annotations.Api;
18 19 import io.swagger.annotations.ApiOperation;
19 20 import io.swagger.annotations.ApiParam;
20 21 import lombok.extern.slf4j.Slf4j;
... ... @@ -186,62 +187,6 @@ public class DeviceProfileController extends BaseController {
186 187 }
187 188 }
188 189
189   - @ApiOperation(value = "Create Or Update Device Profile (saveDeviceProfile)",
190   - notes = "Create or update the Device Profile. When creating device profile, platform generates device profile id as " + UUID_WIKI_LINK +
191   - "The newly created device profile id will be present in the response. " +
192   - "Specify existing device profile id to update the device profile. " +
193   - "Referencing non-existing device profile Id will cause 'Not Found' error. " + NEW_LINE +
194   - "Device profile name is unique in the scope of tenant. Only one 'default' device profile may exist in scope of tenant." + DEVICE_PROFILE_DATA +
195   - TENANT_AUTHORITY_PARAGRAPH,
196   - produces = "application/json",
197   - consumes = "application/json")
198   - @PreAuthorize("hasAuthority('TENANT_ADMIN')")
199   - @RequestMapping(value = "/deviceProfile", method = RequestMethod.POST)
200   - @ResponseBody
201   - public DeviceProfile saveDeviceProfile(
202   - @ApiParam(value = "A JSON value representing the device profile.")
203   - @RequestBody DeviceProfile deviceProfile) throws ThingsboardException {
204   - try {
205   - boolean created = deviceProfile.getId() == null;
206   - deviceProfile.setTenantId(getTenantId());
207   -
208   - checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE);
209   -
210   - boolean isFirmwareChanged = false;
211   - boolean isSoftwareChanged = false;
212   -
213   - if (!created) {
214   - DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(getTenantId(), deviceProfile.getId());
215   - if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
216   - isFirmwareChanged = true;
217   - }
218   - if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
219   - isSoftwareChanged = true;
220   - }
221   - }
222   -
223   - DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
224   -
225   - tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
226   - tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), savedDeviceProfile.getId(),
227   - created ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
228   -
229   - logEntityAction(savedDeviceProfile.getId(), savedDeviceProfile,
230   - null,
231   - created ? ActionType.ADDED : ActionType.UPDATED, null);
232   -
233   - otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
234   -
235   - sendEntityNotificationMsg(getTenantId(), savedDeviceProfile.getId(),
236   - deviceProfile.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
237   - return savedDeviceProfile;
238   - } catch (Exception e) {
239   - logEntityAction(emptyId(EntityType.DEVICE_PROFILE), deviceProfile,
240   - null, deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
241   - throw handleException(e);
242   - }
243   - }
244   -
245 190 @ApiOperation(value = "Delete device profile (deleteDeviceProfile)",
246 191 notes = "Deletes the device profile. Referencing non-existing device profile Id will cause an error. " +
247 192 "Can't delete the device profile if it is referenced by existing devices." + TENANT_AUTHORITY_PARAGRAPH,
... ... @@ -337,6 +282,62 @@ public class DeviceProfileController extends BaseController {
337 282 }
338 283 }
339 284
  285 + @ApiOperation(value = "Create Or Update Device Profile (saveDeviceProfile)",
  286 + notes = "Create or update the Device Profile. When creating device profile, platform generates device profile id as " + UUID_WIKI_LINK +
  287 + "The newly created device profile id will be present in the response. " +
  288 + "Specify existing device profile id to update the device profile. " +
  289 + "Referencing non-existing device profile Id will cause 'Not Found' error. " + NEW_LINE +
  290 + "Device profile name is unique in the scope of tenant. Only one 'default' device profile may exist in scope of tenant." + DEVICE_PROFILE_DATA +
  291 + TENANT_AUTHORITY_PARAGRAPH,
  292 + produces = "application/json",
  293 + consumes = "application/json")
  294 + @PreAuthorize("hasAuthority('TENANT_ADMIN')")
  295 + @RequestMapping(value = "/deviceProfile", method = RequestMethod.POST)
  296 + @ResponseBody
  297 + public DeviceProfile saveDeviceProfile(
  298 + @ApiParam(value = "A JSON value representing the device profile.")
  299 + @RequestBody DeviceProfile deviceProfile) throws ThingsboardException {
  300 + try {
  301 + boolean created = deviceProfile.getId() == null;
  302 + deviceProfile.setTenantId(getTenantId());
  303 +
  304 + checkEntity(deviceProfile.getId(), deviceProfile, Resource.DEVICE_PROFILE);
  305 +
  306 + boolean isFirmwareChanged = false;
  307 + boolean isSoftwareChanged = false;
  308 +
  309 + if (!created) {
  310 + DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(getTenantId(), deviceProfile.getId());
  311 + if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
  312 + isFirmwareChanged = true;
  313 + }
  314 + if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
  315 + isSoftwareChanged = true;
  316 + }
  317 + }
  318 +
  319 + DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
  320 +
  321 + tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
  322 + tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), savedDeviceProfile.getId(),
  323 + created ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
  324 +
  325 + logEntityAction(savedDeviceProfile.getId(), savedDeviceProfile,
  326 + null,
  327 + created ? ActionType.ADDED : ActionType.UPDATED, null);
  328 +
  329 + otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
  330 +
  331 + sendEntityNotificationMsg(getTenantId(), savedDeviceProfile.getId(),
  332 + deviceProfile.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
  333 + return savedDeviceProfile;
  334 + } catch (Exception e) {
  335 + logEntityAction(emptyId(EntityType.DEVICE_PROFILE), deviceProfile,
  336 + null, deviceProfile.getId() == null ? ActionType.ADDED : ActionType.UPDATED, e);
  337 + throw handleException(e);
  338 + }
  339 + }
  340 +
340 341 @ApiOperation(value = "Get Device Profiles for transport type (getDeviceProfileInfos)",
341 342 notes = "Returns a page of devices profile info objects owned by tenant. " +
342 343 PAGE_DATA_PARAMETERS + DEVICE_PROFILE_INFO_DESCRIPTION + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH,
... ...
1   -package org.thingsboard.server.controller.yunteng;
2   -
3   -import lombok.RequiredArgsConstructor;
4   -import org.springframework.http.ResponseEntity;
5   -import org.springframework.web.bind.annotation.*;
6   -import org.thingsboard.server.common.data.exception.ThingsboardException;
7   -import org.thingsboard.server.common.data.yunteng.dto.AlarmProfileDTO;
8   -import org.thingsboard.server.common.data.yunteng.dto.DeleteDTO;
9   -import org.thingsboard.server.controller.BaseController;
10   -import org.thingsboard.server.dao.yunteng.service.YtAlarmProfileService;
11   -
12   -@RestController
13   -@RequestMapping("/api/yt/alarmProfile")
14   -@RequiredArgsConstructor
15   -public class YtAlarmProfileController extends BaseController {
16   - private final YtAlarmProfileService alarmProfileService;
17   -
18   - @PostMapping
19   - public ResponseEntity<AlarmProfileDTO> saveAlarmProfile(
20   - @RequestBody AlarmProfileDTO alarmProfileDTO) throws ThingsboardException {
21   - return ResponseEntity.ok(alarmProfileService.saveOrUpdateAlarmProfile(getCurrentUser().getCurrentTenantId(), alarmProfileDTO));
22   - }
23   -
24   - @DeleteMapping
25   - public ResponseEntity<Boolean> deleteAlarmProfile(
26   - @RequestBody DeleteDTO deleteDTO) {
27   - return ResponseEntity.ok(alarmProfileService.deleteAlarmProfile(deleteDTO.getIds()));
28   - }
29   -}
... ... @@ -16,10 +16,10 @@ import org.thingsboard.server.common.data.audit.ActionType;
16 16 import org.thingsboard.server.common.data.exception.ThingsboardException;
17 17 import org.thingsboard.server.common.data.id.DeviceId;
18 18 import org.thingsboard.server.common.data.id.DeviceProfileId;
  19 +import org.thingsboard.server.common.data.id.EdgeId;
19 20 import org.thingsboard.server.common.data.id.TenantId;
20 21 import org.thingsboard.server.common.data.yunteng.common.AddGroup;
21 22 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup;
22   -import org.thingsboard.server.common.data.yunteng.core.exception.FastIotException;
23 23 import org.thingsboard.server.common.data.yunteng.dto.DeleteDTO;
24 24 import org.thingsboard.server.common.data.yunteng.dto.DeviceDTO;
25 25 import org.thingsboard.server.common.data.yunteng.enums.DeviceState;
... ... @@ -35,6 +35,7 @@ import org.thingsboard.server.service.security.permission.Resource;
35 35 import java.time.LocalDateTime;
36 36 import java.time.ZoneOffset;
37 37 import java.util.HashMap;
  38 +import java.util.List;
38 39 import java.util.Optional;
39 40 import java.util.UUID;
40 41
... ... @@ -51,13 +52,26 @@ public class YtDeviceController extends BaseController {
51 52
52 53 @PostMapping
53 54 public ResponseEntity<DeviceDTO> saveDevice(@Validated(AddGroup.class)@RequestBody DeviceDTO deviceDTO)
54   - throws FastIotException, ThingsboardException {
  55 + throws ThingsboardException {
55 56 boolean enable = deviceService.validateFormdata(deviceDTO);
56 57 if(!enable){
57 58 ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
58 59 }
59 60
60 61 Device tbDevice = buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(),deviceDTO);
  62 + Device savedDevice = updateTbDevice(tbDevice,deviceDTO.getDeviceToken());
  63 +
  64 + deviceDTO.setTbDeviceId(savedDevice.getId().getId().toString());
  65 + DeviceDTO newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
  66 + return Optional.ofNullable(newDeviceDTO)
  67 + .map(
  68 + dto -> {
  69 + return ResponseEntity.ok(newDeviceDTO);
  70 + })
  71 + .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
  72 + }
  73 +
  74 + private Device updateTbDevice( Device tbDevice,String deviceToken) throws ThingsboardException {
61 75 Device oldDevice = null;
62 76 boolean created = tbDevice.getId() == null;
63 77 if (!created) {
... ... @@ -66,7 +80,7 @@ public class YtDeviceController extends BaseController {
66 80 checkEntity(null, tbDevice, Resource.DEVICE);
67 81 }
68 82
69   - Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, deviceDTO.getDeviceToken()));
  83 + Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, deviceToken));
70 84 tbClusterService.onDeviceUpdated(savedDevice, oldDevice);
71 85 try {
72 86 logEntityAction(getCurrentUser(), savedDevice.getId(), savedDevice,
... ... @@ -75,15 +89,7 @@ public class YtDeviceController extends BaseController {
75 89 } catch (ThingsboardException e) {
76 90 log.error("Failed to log entity action", e);
77 91 }
78   -
79   - deviceDTO.setTbDeviceId(savedDevice.getId().getId().toString());
80   - DeviceDTO newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
81   - return Optional.ofNullable(newDeviceDTO)
82   - .map(
83   - dto -> {
84   - return ResponseEntity.ok(newDeviceDTO);
85   - })
86   - .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
  92 + return savedDevice;
87 93 }
88 94
89 95 @GetMapping("{id}")
... ... @@ -123,7 +129,29 @@ public class YtDeviceController extends BaseController {
123 129
124 130 @DeleteMapping
125 131 public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException {
126   - deviceService.deleteDevices(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
  132 + String currentTenantId = getCurrentUser().getCurrentTenantId();
  133 + List<String> tdIds = deviceService.findTbDeviceId(currentTenantId, deleteDTO.getIds());
  134 + for(String id:tdIds){
  135 + deleteTbDevice(id);
  136 + }
  137 + deviceService.deleteDevices(currentTenantId, deleteDTO.getIds());
  138 + }
  139 +
  140 + private void deleteTbDevice(String id) throws ThingsboardException {
  141 + DeviceId deviceId = new DeviceId(toUUID(id));
  142 + Device device = checkDeviceId(deviceId, Operation.DELETE);
  143 +
  144 + List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(getTenantId(), deviceId);
  145 +
  146 + tbDeviceService.deleteDevice(getCurrentUser().getTenantId(), deviceId);
  147 +
  148 + tbClusterService.onDeviceDeleted(device, null);
  149 +
  150 + logEntityAction(deviceId, device,
  151 + device.getCustomerId(),
  152 + ActionType.DELETED, null, id);
  153 +
  154 + sendDeleteNotificationMsg(getTenantId(), deviceId, relatedEdgeIds);
127 155 }
128 156
129 157
... ... @@ -146,7 +174,8 @@ public class YtDeviceController extends BaseController {
146 174 additionalInfo.put("overwriteActivityTime",false);
147 175
148 176
149   - DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.fromString(deviceDTO.getProfileId()));
  177 +
  178 + DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.fromString(deviceDTO.getDeviceProfile().getTbProfileId()));
150 179
151 180
152 181 tbDevice.setAdditionalInfo(additionalInfo);
... ...
1 1 package org.thingsboard.server.controller.yunteng;
2 2
  3 +import io.swagger.annotations.Api;
3 4 import lombok.RequiredArgsConstructor;
  5 +import org.apache.commons.lang3.StringUtils;
4 6 import org.springframework.http.HttpStatus;
5 7 import org.springframework.http.ResponseEntity;
6 8 import org.springframework.security.access.prepost.PreAuthorize;
7 9 import org.springframework.validation.annotation.Validated;
8 10 import org.springframework.web.bind.annotation.*;
9 11 import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  12 +import org.thingsboard.common.util.JacksonUtil;
  13 +import org.thingsboard.server.common.data.DeviceProfile;
  14 +import org.thingsboard.server.common.data.DeviceProfileProvisionType;
  15 +import org.thingsboard.server.common.data.DeviceProfileType;
  16 +import org.thingsboard.server.common.data.DeviceTransportType;
  17 +import org.thingsboard.server.common.data.audit.ActionType;
  18 +import org.thingsboard.server.common.data.device.profile.*;
  19 +import org.thingsboard.server.common.data.edge.EdgeEventActionType;
10 20 import org.thingsboard.server.common.data.exception.ThingsboardException;
  21 +import org.thingsboard.server.common.data.id.DeviceProfileId;
  22 +import org.thingsboard.server.common.data.id.TenantId;
  23 +import org.thingsboard.server.common.data.plugin.ComponentLifecycleEvent;
11 24 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup;
12 25 import org.thingsboard.server.common.data.yunteng.dto.DeleteDTO;
13 26 import org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO;
14 27 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum;
15 28 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
  29 +import org.thingsboard.server.common.msg.queue.ServiceQueue;
16 30 import org.thingsboard.server.controller.BaseController;
17 31 import org.thingsboard.server.dao.yunteng.service.YtDeviceProfileService;
  32 +import org.thingsboard.server.service.security.permission.Operation;
18 33
19 34 import java.net.URI;
20   -import java.util.HashMap;
21   -import java.util.List;
22   -import java.util.Optional;
  35 +import java.time.LocalDateTime;
  36 +import java.time.ZoneOffset;
  37 +import java.util.*;
23 38
24 39 import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.*;
25 40
26 41 @RestController
27 42 @RequiredArgsConstructor
28 43 @RequestMapping("api/yt/deviceProfile")
  44 +@Api(tags = {"设备配置"})
29 45 public class YtDeviceProfileController extends BaseController {
30   - private final YtDeviceProfileService deviceProfileService;
  46 + private final YtDeviceProfileService ytDeviceProfileService;
31 47
32 48 @PostMapping
33   - @PreAuthorize("hasRole('ROLE_TENANT_ADMIN')")
  49 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
34 50 public ResponseEntity<DeviceProfileDTO> saveDeviceProfile(
35 51 @RequestBody DeviceProfileDTO deviceProfileDTO) throws ThingsboardException {
36   - DeviceProfileDTO newDeviceProfileDTO = deviceProfileService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceProfileDTO);
  52 +
  53 + boolean created = deviceProfileDTO.getId() == null;
  54 +
  55 + /**
  56 + * 业务流程
  57 + * 1/3.验证业务平台中表单数据的合法性
  58 + * 2/3.处理TB业务逻辑
  59 + * 3/3.处理业务平台的业务逻辑
  60 + */
  61 + //TODO 1/3.验证业务平台中表单数据的合法性
  62 +
  63 + //TODO 2/3.处理TB业务逻辑
  64 + deviceProfileDTO.setTenantId(getCurrentUser().getCurrentTenantId());
  65 + DeviceProfile tbDeviceProfile = buildTbDeviceProfileFromDeviceProfileDTO(deviceProfileDTO);
  66 + DeviceProfile savedDeviceProfile = updateTbDeviceProfile(tbDeviceProfile,created);
  67 +
  68 +
  69 + //TODO 3/3.处理业务平台的业务逻辑
  70 +
  71 + DeviceProfileDTO newDeviceProfileDTO = ytDeviceProfileService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceProfileDTO);
37 72 return Optional.ofNullable(newDeviceProfileDTO)
38 73 .map(
39 74 dto -> {
... ... @@ -47,9 +82,45 @@ public class YtDeviceProfileController extends BaseController {
47 82 .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
48 83 }
49 84
  85 + /**
  86 + * 更新thingsboard的设备配置信息
  87 + * @param deviceProfile 设备配置
  88 + * @param created 新建设备
  89 + * @throws ThingsboardException
  90 + */
  91 + private DeviceProfile updateTbDeviceProfile(DeviceProfile deviceProfile,boolean created) throws ThingsboardException {
  92 + boolean isFirmwareChanged = false;
  93 + boolean isSoftwareChanged = false;
  94 + if (!created) {
  95 + DeviceProfile oldDeviceProfile = deviceProfileService.findDeviceProfileById(getTenantId(), deviceProfile.getId());
  96 + if (!Objects.equals(deviceProfile.getFirmwareId(), oldDeviceProfile.getFirmwareId())) {
  97 + isFirmwareChanged = true;
  98 + }
  99 + if (!Objects.equals(deviceProfile.getSoftwareId(), oldDeviceProfile.getSoftwareId())) {
  100 + isSoftwareChanged = true;
  101 + }
  102 + }
  103 +
  104 + DeviceProfile savedDeviceProfile = checkNotNull(deviceProfileService.saveDeviceProfile(deviceProfile));
  105 +
  106 + tbClusterService.onDeviceProfileChange(savedDeviceProfile, null);
  107 + tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), savedDeviceProfile.getId(),
  108 + created ? ComponentLifecycleEvent.CREATED : ComponentLifecycleEvent.UPDATED);
  109 +
  110 + logEntityAction(savedDeviceProfile.getId(), savedDeviceProfile,
  111 + null,
  112 + created ? ActionType.ADDED : ActionType.UPDATED, null);
  113 +
  114 + otaPackageStateService.update(savedDeviceProfile, isFirmwareChanged, isSoftwareChanged);
  115 +
  116 + sendEntityNotificationMsg(getTenantId(), savedDeviceProfile.getId(),
  117 + deviceProfile.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
  118 + return savedDeviceProfile;
  119 + }
  120 +
50 121 @GetMapping("{id}")
51 122 public ResponseEntity<DeviceProfileDTO> getDevice(@PathVariable("id") String id) throws ThingsboardException {
52   - return ResponseEntity.of(deviceProfileService.getDeviceProfile(getCurrentUser().getCurrentTenantId(), id));
  123 + return ResponseEntity.of(ytDeviceProfileService.getDeviceProfile(getCurrentUser().getCurrentTenantId(), id));
53 124 }
54 125
55 126 @GetMapping(params = {PAGE_SIZE, PAGE})
... ... @@ -69,18 +140,72 @@ public class YtDeviceProfileController extends BaseController {
69 140 if (orderType != null) {
70 141 queryMap.put(ORDER_TYPE, orderType.name());
71 142 }
72   - return deviceProfileService.page(getCurrentUser().getCurrentTenantId(), queryMap);
  143 + return ytDeviceProfileService.page(getCurrentUser().getCurrentTenantId(), queryMap);
73 144 }
74 145
75 146 @DeleteMapping
76 147 public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException {
77   - deviceProfileService.deleteDeviceProfiles(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
  148 + for(String id:deleteDTO.getIds()){
  149 + deleteTbDeviceProfile(id);
  150 + }
  151 + ytDeviceProfileService.deleteDeviceProfiles(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
  152 + }
  153 +
  154 + private void deleteTbDeviceProfile(String strDeviceProfileId) throws ThingsboardException {
  155 + DeviceProfileId deviceProfileId = new DeviceProfileId(toUUID(strDeviceProfileId));
  156 + DeviceProfile deviceProfile = checkDeviceProfileId(deviceProfileId, Operation.DELETE);
  157 + deviceProfileService.deleteDeviceProfile(getTenantId(), deviceProfileId);
  158 +
  159 + tbClusterService.onDeviceProfileDelete(deviceProfile, null);
  160 + tbClusterService.broadcastEntityStateChangeEvent(deviceProfile.getTenantId(), deviceProfile.getId(), ComponentLifecycleEvent.DELETED);
  161 +
  162 + logEntityAction(deviceProfileId, deviceProfile,
  163 + null,
  164 + ActionType.DELETED, null, deviceProfileId);
  165 +
  166 + sendEntityNotificationMsg(getTenantId(), deviceProfile.getId(), EdgeEventActionType.DELETED);
78 167 }
79 168
80 169 @GetMapping("/me")
81 170 public ResponseEntity<List<DeviceProfileDTO>> findCurrentTenantDeviceProfiles() throws ThingsboardException {
82   - DeviceProfileDTO deviceProfileDTO = new DeviceProfileDTO();
83   - deviceProfileDTO.setTenantId(getCurrentUser().getCurrentTenantId());
84   - return ResponseEntity.ok(deviceProfileService.findDeviceProfile(getCurrentUser().getCurrentTenantId(), deviceProfileDTO));
  171 +
  172 + return ResponseEntity.ok(ytDeviceProfileService.findDeviceProfile(getCurrentUser().getCurrentTenantId()));
  173 + }
  174 +
  175 + /**
  176 + * 构造调用TBDeviceProfile需要的参数
  177 + *
  178 + * @param deviceProfileDTO 页面接收的参数
  179 + * @return 封装好的TBDeviceProfile
  180 + */
  181 + private DeviceProfile buildTbDeviceProfileFromDeviceProfileDTO(DeviceProfileDTO deviceProfileDTO) {
  182 + DeviceProfile tbDeviceProfile = new DeviceProfile();
  183 + if (StringUtils.isNotBlank(deviceProfileDTO.getId())) {
  184 + UUID profileId = UUID.fromString(deviceProfileDTO.getId());
  185 + tbDeviceProfile.setId(new DeviceProfileId(profileId));
  186 + }
  187 + tbDeviceProfile.setName(deviceProfileDTO.getName());
  188 + tbDeviceProfile.setType(DeviceProfileType.DEFAULT);
  189 + UUID tenantId = UUID.fromString(deviceProfileDTO.getTenantId());
  190 + tbDeviceProfile.setTenantId(new TenantId(tenantId));
  191 + // 传输类型默认都是Default
  192 + tbDeviceProfile.setTransportType(DeviceTransportType.DEFAULT);
  193 + // 获取当前租户的默认规则链
  194 +// tbDeviceProfile.setDefaultRuleChainId(new RuleChainId(getCurrentUserDefaultRuleChains()));
  195 + tbDeviceProfile.setDefaultQueueName(ServiceQueue.MAIN);
  196 + tbDeviceProfile.setProvisionType(DeviceProfileProvisionType.DISABLED);
  197 + tbDeviceProfile.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
  198 + DeviceProfileData deviceProfileData = new DeviceProfileData();
  199 + deviceProfileData.setConfiguration(new DefaultDeviceProfileConfiguration());
  200 + deviceProfileData.setProvisionConfiguration(new DisabledDeviceProfileProvisionConfiguration(null));
  201 + deviceProfileData.setTransportConfiguration(new DefaultDeviceProfileTransportConfiguration());
  202 + if (null != deviceProfileDTO.getAlarms()) {
  203 + List<DeviceProfileAlarm> list = new ArrayList<>();
  204 + DeviceProfileAlarm deviceProfileAlarm = JacksonUtil.convertValue(deviceProfileDTO.getAlarms(),DeviceProfileAlarm.class);
  205 + list.add(deviceProfileAlarm);
  206 + deviceProfileData.setAlarms(list);
  207 + }
  208 + tbDeviceProfile.setProfileData(deviceProfileData);
  209 + return tbDeviceProfile;
85 210 }
86 211 }
... ...
... ... @@ -43,7 +43,7 @@ public class DeviceProfileInfo extends EntityInfo {
43 43
44 44 @JsonCreator
45 45 public DeviceProfileInfo(@JsonProperty("id") EntityId id,
46   - @JsonProperty("name") String name,
  46 + @JsonProperty("name") String name ,
47 47 @JsonProperty("image") String image,
48 48 @JsonProperty("defaultDashboardId") DashboardId defaultDashboardId,
49 49 @JsonProperty("type") DeviceProfileType type,
... ...
... ... @@ -25,6 +25,7 @@ public class DeviceProfileDTO extends TenantDTO {
25 25 @NotEmpty(message = "传输协议不能为空或者二空字符串")
26 26 private DeviceTransportType transportType;
27 27 /** TB的设备配置文件 */
  28 + @Deprecated
28 29 private String tbProfileId;
29 30
30 31 private JsonNode alarms;
... ...
  1 +package org.thingsboard.server.dao.yunteng.entities;
  2 +
  3 +import com.baomidou.mybatisplus.annotation.FieldStrategy;
  4 +import com.baomidou.mybatisplus.annotation.TableField;
  5 +import com.baomidou.mybatisplus.annotation.TableName;
  6 +import lombok.Data;
  7 +import lombok.EqualsAndHashCode;
  8 +import org.thingsboard.server.common.data.yunteng.enums.TransportTypeEnum;
  9 +import org.thingsboard.server.dao.model.ModelConstants;
  10 +
  11 +@Data
  12 +@EqualsAndHashCode(callSuper = true)
  13 +@TableName(ModelConstants.DEVICE_PROFILE_COLUMN_FAMILY_NAME)
  14 +public class YtDeviceProfile extends TenantBaseEntity {
  15 + private String name;
  16 + private String description;
  17 + /** 转换脚本:TCP才会使用 */
  18 + @Deprecated
  19 + private String convertJs;
  20 +
  21 + private TransportTypeEnum transportType;
  22 + /** TB的设备配置文件 */
  23 + @TableField(updateStrategy = FieldStrategy.IGNORED)
  24 + private String tbProfileId;
  25 +}
... ...
1   -package org.thingsboard.server.dao.yunteng.impl;
2   -
3   -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4   -import lombok.RequiredArgsConstructor;
5   -import lombok.extern.slf4j.Slf4j;
6   -import org.apache.commons.lang3.StringUtils;
7   -import org.springframework.stereotype.Service;
8   -import org.springframework.transaction.annotation.Transactional;
9   -import org.thingsboard.server.common.data.yunteng.core.exception.YtDataValidationException;
10   -import org.thingsboard.server.common.data.yunteng.core.message.ErrorMessage;
11   -import org.thingsboard.server.common.data.yunteng.dto.AlarmProfileDTO;
12   -import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
13   -import org.thingsboard.server.dao.yunteng.entities.AlarmProfile;
14   -import org.thingsboard.server.dao.yunteng.mapper.AlarmProfileMapper;
15   -import org.thingsboard.server.dao.yunteng.service.AbstractBaseService;
16   -import org.thingsboard.server.dao.yunteng.service.YtAlarmProfileService;
17   -
18   -import java.util.List;
19   -import java.util.Optional;
20   -import java.util.Set;
21   -
22   -@Service
23   -@RequiredArgsConstructor
24   -@Slf4j
25   -public class YtAlarmProfileServiceImpl extends AbstractBaseService<AlarmProfileMapper, AlarmProfile>
26   - implements YtAlarmProfileService {
27   -
28   - @Override
29   - @Transactional
30   - public AlarmProfileDTO saveOrUpdateAlarmProfile(String tenantId,AlarmProfileDTO alarmProfileDTO) {
31   - AlarmProfile alarmProfile = new AlarmProfile();
32   - alarmProfileDTO.copyToEntity(alarmProfile);
33   - if (StringUtils.isEmpty(alarmProfileDTO.getId())) {
34   - alarmProfile.setTenantId(tenantId);
35   - baseMapper.insert(alarmProfile);
36   - } else {
37   - baseMapper.updateById(alarmProfile);
38   - }
39   - alarmProfile.copyToDTO(alarmProfileDTO);
40   - return alarmProfileDTO;
41   - }
42   -
43   - @Override
44   - @Transactional
45   - public boolean deleteAlarmProfile(Set<String> ids) {
46   - return baseMapper.deleteBatchIds(ids) > 0;
47   - }
48   -
49   - @Override
50   - public AlarmProfileDTO findAlarmProfileByDeviceProfileId(String tenantId,String deviceProfileId) {
51   - if (StringUtils.isEmpty(deviceProfileId)) {
52   - throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
53   - }
54   - List<AlarmProfile> alarmProfileList =
55   - baseMapper.selectList(
56   - new QueryWrapper<AlarmProfile>()
57   - .lambda()
58   - .eq(AlarmProfile::getDeviceProfileId, deviceProfileId)
59   - .eq(AlarmProfile::getTenantId, tenantId));
60   - return Optional.ofNullable(alarmProfileList)
61   - .filter(alarmProfiles -> alarmProfiles.size() > 0)
62   - .map(
63   - alarmProfiles ->
64   - ReflectUtils.sourceToTarget(alarmProfileList, AlarmProfileDTO.class).get(0))
65   - .orElse(null);
66   - }
67   -}
... ... @@ -28,7 +28,7 @@ public class YtCommonServiceImpl implements YtCommonService {
28 28 DeviceDTO deviceDTO = new DeviceDTO();
29 29 deviceDTO.setDeviceToken(deviceToken);
30 30 //检查数据库是否已存在对应的DeviceToken
31   - if(deviceService.findDeviceInfo(tenantId,deviceDTO).size()>0){
  31 + if(deviceService.findTbDeviceId(tenantId,deviceDTO).size()>0){
32 32 generateDeviceToken(tenantId);
33 33 }
34 34 return deviceToken;
... ...
1 1 package org.thingsboard.server.dao.yunteng.impl;
2 2
  3 +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
3 4 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
4 5 import com.baomidou.mybatisplus.core.metadata.IPage;
5 6 import lombok.RequiredArgsConstructor;
6 7 import lombok.extern.slf4j.Slf4j;
7 8 import org.apache.commons.lang3.StringUtils;
  9 +import org.jetbrains.annotations.NotNull;
  10 +import org.springframework.beans.BeanUtils;
8 11 import org.springframework.stereotype.Service;
9 12 import org.springframework.transaction.annotation.Transactional;
  13 +import org.thingsboard.server.common.data.DeviceProfile;
  14 +import org.thingsboard.server.common.data.id.TenantId;
  15 +import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
10 16 import org.thingsboard.server.common.data.yunteng.core.cache.CacheUtils;
11 17 import org.thingsboard.server.common.data.yunteng.core.exception.YtDataValidationException;
12 18 import org.thingsboard.server.common.data.yunteng.core.message.ErrorMessage;
... ... @@ -15,12 +21,14 @@ import org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO;
15 21 import org.thingsboard.server.common.data.yunteng.enums.TransportTypeEnum;
16 22 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
17 23 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
  24 +import org.thingsboard.server.dao.device.DeviceProfileDao;
  25 +import org.thingsboard.server.dao.yunteng.entities.AlarmProfile;
18 26 import org.thingsboard.server.dao.yunteng.entities.YtDevice;
19 27 import org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile;
  28 +import org.thingsboard.server.dao.yunteng.mapper.AlarmProfileMapper;
20 29 import org.thingsboard.server.dao.yunteng.mapper.DeviceMapper;
21 30 import org.thingsboard.server.dao.yunteng.mapper.DeviceProfileMapper;
22 31 import org.thingsboard.server.dao.yunteng.service.AbstractBaseService;
23   -import org.thingsboard.server.dao.yunteng.service.YtAlarmProfileService;
24 32 import org.thingsboard.server.dao.yunteng.service.YtDeviceProfileService;
25 33
26 34 import java.util.*;
... ... @@ -29,13 +37,15 @@ import java.util.*;
29 37 @RequiredArgsConstructor
30 38 @Slf4j
31 39 public class YtDeviceProfileServiceImpl
32   - extends AbstractBaseService<DeviceProfileMapper, org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile>
33   - implements YtDeviceProfileService {
  40 + extends AbstractBaseService<DeviceProfileMapper, YtDeviceProfile>
  41 + implements YtDeviceProfileService {
34 42
35 43 private final DeviceMapper deviceMapper;
36   - private final YtAlarmProfileService alarmProfileService;
  44 + private final AlarmProfileMapper alarmProfileMapper;
37 45 private final CacheUtils cacheUtils;
38 46
  47 + private final DeviceProfileDao deviceProfileDao;
  48 +
39 49 @Override
40 50 @Transactional
41 51 public DeviceProfileDTO insertOrUpdate(String tenantId,DeviceProfileDTO deviceProfileDTO) {
... ... @@ -47,40 +57,80 @@ public class YtDeviceProfileServiceImpl
47 57 }
48 58
49 59 private DeviceProfileDTO update(String tenantId,DeviceProfileDTO deviceProfileDTO) {
50   - YtDeviceProfile deviceProfile = baseMapper.selectById(deviceProfileDTO.getId());
51   - if (!deviceProfile.getTenantId().equals(tenantId)) {
52   - return null;
53   - }
54   - deviceProfileDTO.copyToEntity(deviceProfile);
  60 +
55 61 // 如果原来不是TCP或者更新也不是TCP 那就需要check
56   - if (!deviceProfile.getTransportType().equals(TransportTypeEnum.TCP)
57   - || !deviceProfileDTO.getTransportType().equals(TransportTypeEnum.TCP)) {
58   - checkDeviceProfile(deviceProfileDTO, deviceProfile);
  62 +// if (!deviceProfile.getTransportType().equals(TransportTypeEnum.TCP)
  63 +// || !deviceProfileDTO.getTransportType().equals(TransportTypeEnum.TCP)) {
  64 +// checkDeviceProfile(deviceProfileDTO, deviceProfile);
  65 +// }
  66 + LambdaQueryWrapper<AlarmProfile> filter = new QueryWrapper<AlarmProfile>().lambda()
  67 + .eq(AlarmProfile::getTenantId,deviceProfileDTO.getTenantId())
  68 + .eq(AlarmProfile::getDeviceProfileId,deviceProfileDTO.getId());
  69 + List<AlarmProfile> oldAlarms = alarmProfileMapper.selectList(filter);
  70 + List<String> oldIds = new ArrayList<>();
  71 + for(AlarmProfile item: oldAlarms){
  72 + oldIds.add(item.getId());
59 73 }
60   - baseMapper.updateById(deviceProfile);
  74 +
  75 +
  76 +
61 77 Optional.ofNullable(deviceProfileDTO.getAlarmProfile())
62   - .filter(alarmProfileDTO -> StringUtils.isNotBlank(alarmProfileDTO.getId()))
63   - .map(alarmProfileDTO -> alarmProfileService.saveOrUpdateAlarmProfile(tenantId,alarmProfileDTO));
64   - return deviceProfile.getDTO(DeviceProfileDTO.class);
  78 +// .filter(alarmProfileDTO -> StringUtils.isNotBlank(alarmProfileDTO.getId()))
  79 + .ifPresent(alarmProfileDTO -> {
  80 + AlarmProfile alarmProfile = buildAlarmDto2Entity(deviceProfileDTO.getId(), deviceProfileDTO.getTenantId(), alarmProfileDTO);
  81 + String alarmId = alarmProfileDTO.getId();
  82 + if(StringUtils.isNotBlank(alarmId)){
  83 + alarmProfileMapper.updateById(alarmProfile);
  84 + oldIds.remove(alarmId);
  85 + }{
  86 + alarmProfileMapper.insert(alarmProfile);
  87 + }
  88 + });
  89 + Optional.ofNullable(oldIds).ifPresent(item->alarmProfileMapper.deleteBatchIds(item));
  90 + return deviceProfileDTO;
65 91 }
66 92
67   - private DeviceProfileDTO insert(String tenantId,DeviceProfileDTO deviceProfileDTO) {
68   - YtDeviceProfile deviceProfile = new YtDeviceProfile();
69   - // 判断数据库是否已存在名字相同的设备配置
70   - if (findDeviceProfile(tenantId,deviceProfileDTO).size() > 0) {
71   - throw new YtDataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
72   - }
73   - deviceProfileDTO.copyToEntity(deviceProfile);
74   - deviceProfile.setTenantId(tenantId);
75   - saveOrUpdateTBDeviceProfile(deviceProfileDTO, deviceProfile);
76   - baseMapper.insert(deviceProfile);
  93 + private DeviceProfileDTO insert(String deviceProfileId,DeviceProfileDTO deviceProfileDTO) {
77 94 Optional.ofNullable(deviceProfileDTO.getAlarmProfile())
78 95 .map(
79 96 alarmProfileDTO -> {
80   - alarmProfileDTO.setDeviceProfileId(deviceProfile.getId());
81   - return alarmProfileService.saveOrUpdateAlarmProfile(tenantId,alarmProfileDTO);
  97 + AlarmProfile alarmProfile = buildAlarmDto2Entity(deviceProfileId, deviceProfileDTO.getTenantId(), alarmProfileDTO);
  98 + alarmProfileMapper.insert(alarmProfile);
  99 + alarmProfile.copyToDTO(alarmProfileDTO);
  100 + return alarmProfileDTO;
82 101 });
83   - return deviceProfile.getDTO(DeviceProfileDTO.class);
  102 + return deviceProfileDTO;
  103 + }
  104 +
  105 + @NotNull
  106 + private AlarmProfile buildAlarmDto2Entity(String deviceProfileId, String tenantId, AlarmProfileDTO alarmProfileDTO) {
  107 + alarmProfileDTO.setDeviceProfileId(deviceProfileId);
  108 + alarmProfileDTO.setTenantId(tenantId);
  109 + AlarmProfile alarmProfile = new AlarmProfile();
  110 + alarmProfileDTO.copyToEntity(alarmProfile, ModelConstants.TablePropertyMapping.UPDATE_TIME,
  111 + ModelConstants.TablePropertyMapping.UPDATER);
  112 + return alarmProfile;
  113 + }
  114 +
  115 + @Override
  116 + public boolean validateFormdata(DeviceProfileDTO ytDeviceProfileDTO) {
  117 + TenantId tenantId = new TenantId(UUID.fromString(ytDeviceProfileDTO.getTenantId()));
  118 + if(StringUtils.isBlank(ytDeviceProfileDTO.getId())){
  119 + // 判断数据库是否已存在名字相同的设备配置
  120 +
  121 + DeviceProfile profile = deviceProfileDao.findByName(tenantId, ytDeviceProfileDTO.getName());
  122 + if (profile != null) {
  123 + throw new YtDataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
  124 + }
  125 + }else{
  126 + UUID profileId = UUID.fromString(ytDeviceProfileDTO.getId());
  127 + DeviceProfile profile = deviceProfileDao.findById(tenantId, profileId);
  128 + if (profile == null) {
  129 + throw new YtDataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage());
  130 + }
  131 + }
  132 +
  133 + return false;
84 134 }
85 135
86 136 @Override
... ... @@ -93,43 +143,29 @@ public class YtDeviceProfileServiceImpl
93 143 throw new YtDataValidationException("有设备使用待删除配置,请先删除设备或者修改设备配置");
94 144 }
95 145 // TODO check if ids bind to iotfs_key_value_mapping
96   - // 删除本地时,先删除TB的DeviceProfile
97   - for (String id : ids) {
98   - YtDeviceProfile deviceProfile = baseMapper.selectById(id);
99   -// if (!tbConnectService.deleteDeviceProfile(deviceProfile.getTbProfileId()).get()) {
100   -// log.error("delete TBProfile error {}", deviceProfile.getTbProfileId());
101   -// throw new FastIotException(ErrorMessage.INVALID_PARAMETER);
102   -// }
103   - // 删除设备配置同时需要删除对应的告警配置
104   - AlarmProfileDTO alarmProfileDTO = alarmProfileService.findAlarmProfileByDeviceProfileId(tenantId,id);
105   - Optional.ofNullable(alarmProfileDTO)
106   - .filter(alarm -> StringUtils.isNotBlank(alarm.getId()))
107   - .map(
108   - alarm -> {
109   - Set<String> alarmList = new HashSet<>();
110   - alarmList.add(alarm.getId());
111   - return alarmProfileService.deleteAlarmProfile(alarmList);
112   - });
  146 + List<UUID> deletedIds = new ArrayList<>();
  147 + for(String id:ids){
  148 + deletedIds.add(UUID.fromString(id));
  149 + LambdaQueryWrapper filter = new QueryWrapper<AlarmProfile>()
  150 + .lambda()
  151 + .eq(AlarmProfile::getTenantId, tenantId)
  152 + .in(AlarmProfile::getDeviceProfileId, id);
  153 + alarmProfileMapper.delete(filter);
113 154 }
114   - baseMapper.delete(
115   - new QueryWrapper<YtDeviceProfile>()
116   - .lambda()
117   - .eq(YtDeviceProfile::getTenantId, tenantId)
118   - .in(YtDeviceProfile::getId, ids));
  155 + deviceProfileDao.removeAllByIds(deletedIds);
  156 +
119 157 }
120 158
121 159 @Override
122 160 public Optional<DeviceProfileDTO> getDeviceProfile(String tenantId,String id) {
123   - return Optional.ofNullable(
124   - baseMapper.selectOne(
125   - new QueryWrapper<YtDeviceProfile>()
126   - .lambda()
127   - .eq(
128   - YtDeviceProfile::getTenantId,
129   - tenantId)
130   - .eq(YtDeviceProfile::getId, id)))
131   - .map(deviceProfile -> deviceProfile.getDTO(DeviceProfileDTO.class));
132   - }
  161 + TenantId tenant = new TenantId(UUID.fromString(tenantId));
  162 + DeviceProfile profile = deviceProfileDao.findById(tenant,UUID.fromString(id));
  163 + return Optional.ofNullable(profile).map(entity ->{
  164 + DeviceProfileDTO result = new DeviceProfileDTO();
  165 + BeanUtils.copyProperties(entity,result);
  166 + return result;
  167 + });
  168 + }
133 169
134 170 @Override
135 171 public PageData<DeviceProfileDTO> page(String tenantId,Map<String, Object> queryMap) {
... ... @@ -156,139 +192,20 @@ public class YtDeviceProfileServiceImpl
156 192 return getPageData(deviceIPage, DeviceProfileDTO.class);
157 193 }
158 194
159   - @Override
160   - public List<DeviceProfileDTO> findDeviceProfile(String tenantId,DeviceProfileDTO deviceProfileDTO) {
161   - List<YtDeviceProfile> deviceProfileList =
162   - baseMapper.selectList(
163   - new QueryWrapper<YtDeviceProfile>()
164   - .lambda()
165   - .eq(YtDeviceProfile::getTenantId, tenantId)
166   - .like(
167   - StringUtils.isNotBlank(deviceProfileDTO.getName()),
168   - YtDeviceProfile::getName,
169   - deviceProfileDTO.getName()));
170   - return ReflectUtils.sourceToTarget(deviceProfileList, DeviceProfileDTO.class);
171   - }
172 195
173   - /**
174   - * 构造调用TBDeviceProfile需要的参数
175   - *
176   - * @param deviceProfileDTO 页面接收的参数
177   - * @return 封装好的TBDeviceProfile
178 196
179   - private TBDeviceProfile buildTbDeviceProfileFromDeviceProfileDTO(
180   - DeviceProfileDTO deviceProfileDTO) {
181   - TBDeviceProfile tbDeviceProfile = new TBDeviceProfile();
182   - if (StringUtils.isNotBlank(deviceProfileDTO.getId())) {
183   - List<DeviceProfileDTO> deviceProfile = baseMapper.getDeviceProfileInfo(deviceProfileDTO);
184   - tbDeviceProfile.setId(
185   - new Id(EntityType.DEVICE_PROFILE, deviceProfile.get(0).getTbProfileId()));
186   - }
187   - tbDeviceProfile.setName(deviceProfileDTO.getName());
188   - // 传输类型默认都是Default
189   - tbDeviceProfile.setTransportType(TransportTypeEnum.DEFAULT.name());
190   - // 获取当前租户的默认规则链
191   - tbDeviceProfile.setDefaultRuleChainId(
192   - new Id(EntityType.RULE_CHAIN, getCurrentUserDefaultRuleChains()));
193   - tbDeviceProfile.setDefaultQueueName(TbConnectConstant.RuleEngine.MAIN);
194   - tbDeviceProfile.setProvisionType(ProvisionTypeEnum.DISABLED.name());
195   - tbDeviceProfile.setCreatedTime(
196   - LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
197   - TBDeviceProfile.DeviceProfileData deviceProfileData = new TBDeviceProfile.DeviceProfileData();
198   - deviceProfileData.setConfiguration(new TBDeviceProfile.DeviceProfileConfiguration());
199   - deviceProfileData.setProvisionConfiguration(
200   - new TBDeviceProfile.DeviceProfileProvisionConfiguration());
201   - deviceProfileData.setTransportConfiguration(
202   - new TBDeviceProfile.DeviceProfileTransportConfiguration());
203   - if (null != deviceProfileDTO.getAlarms()) {
204   - List<TBDeviceProfile.DeviceProfileAlarm> list = new ArrayList<>();
205   - TBDeviceProfile.DeviceProfileAlarm deviceProfileAlarm = JacksonUtil.convertValue(deviceProfileDTO.getAlarms(),TBDeviceProfile.DeviceProfileAlarm.class);
206   - list.add(deviceProfileAlarm);
207   - deviceProfileData.setAlarms(list);
208   - }
209   - tbDeviceProfile.setProfileData(deviceProfileData);
210   - return tbDeviceProfile;
211   - } */
212 197
213   - /**
214   - * 检查设备配置然后进行相应的操作
215   - *
216   - * @param target 用户新选择的配置
217   - * @param source 用户以前选择的配置
218   - */
219   - private void checkDeviceProfile(DeviceProfileDTO target, YtDeviceProfile source) {
220   - // 原来是TCP => Default、MQTT或其他 需要新增TB设备配置文件
221   - if (source.getTransportType().equals(TransportTypeEnum.TCP)
222   - && !target.getTransportType().equals(TransportTypeEnum.TCP)) {
223   - saveOrUpdateTBDeviceProfile(target, source);
224   - }
225   - if (!source.getTransportType().equals(TransportTypeEnum.TCP)) {
226   - // 原来不是TCP => 更新值或者更换TB设备配置文件
227   - if (!target.getTransportType().equals(TransportTypeEnum.TCP)) {
228   - // 目标不是TCP则进行修改名称
229   - saveOrUpdateTBDeviceProfile(target, source);
230   - } else {
231   - // 目标是TCP则删除原来的TBDeviceProfile
232   -// tbConnectService.deleteDeviceProfile(source.getTbProfileId());
233   - source.setTbProfileId(null);
234   - }
235   - }
236   - }
237 198
238   - /**
239   - * 调用TB保存设备配置
240   - *
241   - * @param target 用户新选择的配置
242   - * @param source 用户以前选择的配置
243   - */
244   - private void saveOrUpdateTBDeviceProfile(DeviceProfileDTO target, YtDeviceProfile source) {
245   -// if (tbConfig.isEnabled()) {
246   -// try {
247   -// TBDeviceProfile tbDeviceProfile = buildTbDeviceProfileFromDeviceProfileDTO(target);
248   -// tbDeviceProfile = tbConnectService.saveOrUpdateDeviceProfile(tbDeviceProfile).get();
249   -// if (null == tbDeviceProfile) {
250   -// throw new FastIotException(ErrorMessage.INVALID_PARAMETER);
251   -// }
252   -// source.setTbProfileId(tbDeviceProfile.getId().getId());
253   -// } catch (ExecutionException | InterruptedException e) {
254   -// log.error("create TBDeviceProfile error {}", e.getMessage());
255   -// throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
256   -// }
257   -// }
258   - }
259 199
260   - private String getCurrentUserDefaultRuleChains() {
261   - String defaultId;
262   -// Optional<String> result =
263   -// cacheUtils
264   -// .get(
265   -// FastIotConstants.CacheConfigKey.DEFAULT_RULE_CHAIN,
266   -// SecurityContext.getCurrentUser().getTenantId());
267   -// if (null != result && result.isPresent()) {
268   -// return result.get();
269   -// }
270   -// try {
271   -// if (tbConfig.isEnabled()) {
272   -// TBPageData tbPageData = tbConnectService.getRuleChains(10, 0).get();
273   -// if (null == tbPageData || null == tbPageData.getData()) {
274   -// throw new FastIotException(ErrorMessage.NONE_DEFAULT_RULE_CHAIN);
275   -// }
276   -// TBPageData convert = new TBPageData().getPageData(tbPageData,TBRuleChain.class);
277   -// List<TBRuleChain> data = (List<TBRuleChain>) convert.getData();
278   -// for (TBRuleChain tbRuleChain : data) {
279   -// if (tbRuleChain.isRoot()) {
280   -// defaultId = tbRuleChain.getId().getId();
281   -// cacheUtils.put(
282   -// FastIotConstants.CacheConfigKey.DEFAULT_RULE_CHAIN,
283   -// SecurityContext.getCurrentUser().getTenantId(),
284   -// defaultId);
285   -// return defaultId;
286   -// }
287   -// }
288   -// }
289   -// } catch (ExecutionException | InterruptedException e) {
290   -// throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
291   -// }
292   - return null;
  200 +
  201 +
  202 +
  203 +
  204 +
  205 + @Override
  206 + public List<DeviceProfileDTO> findDeviceProfile(String tenantId) {
  207 + UUID profileId = UUID.fromString(tenantId);
  208 + List<DeviceProfile> profile =deviceProfileDao.find(new TenantId(profileId));
  209 + return ReflectUtils.sourceToTarget(profile,DeviceProfileDTO.class);
293 210 }
294 211 }
... ...
... ... @@ -9,12 +9,11 @@ import lombok.extern.slf4j.Slf4j;
9 9 import org.apache.commons.lang3.StringUtils;
10 10 import org.springframework.stereotype.Service;
11 11 import org.springframework.transaction.annotation.Transactional;
12   -import org.thingsboard.server.common.data.DeviceProfile;
13 12 import org.thingsboard.server.common.data.id.TenantId;
14 13 import org.thingsboard.server.common.data.security.DeviceCredentials;
15 14 import org.thingsboard.server.common.data.yunteng.constant.FastIotConstants;
16 15 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
17   -import org.thingsboard.server.common.data.yunteng.core.exception.DataValidationException;
  16 +import org.thingsboard.server.common.data.yunteng.core.exception.YtDataValidationException;
18 17 import org.thingsboard.server.common.data.yunteng.core.message.ErrorMessage;
19 18 import org.thingsboard.server.common.data.yunteng.dto.DeviceDTO;
20 19 import org.thingsboard.server.common.data.yunteng.dto.OrganizationDTO;
... ... @@ -26,7 +25,9 @@ import org.thingsboard.server.dao.device.DeviceCredentialsDao;
26 25 import org.thingsboard.server.dao.device.DeviceProfileDao;
27 26 import org.thingsboard.server.dao.yunteng.entities.Organization;
28 27 import org.thingsboard.server.dao.yunteng.entities.YtDevice;
  28 +import org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile;
29 29 import org.thingsboard.server.dao.yunteng.mapper.DeviceMapper;
  30 +import org.thingsboard.server.dao.yunteng.mapper.DeviceProfileMapper;
30 31 import org.thingsboard.server.dao.yunteng.mapper.OrganizationMapper;
31 32 import org.thingsboard.server.dao.yunteng.service.AbstractBaseService;
32 33 import org.thingsboard.server.dao.yunteng.service.YtDeviceService;
... ... @@ -47,7 +48,8 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
47 48 private final DeviceCredentialsDao deviceCredentialsDao;
48 49
49 50
50   - private final OrganizationMapper organizationMapper;
  51 + private final OrganizationMapper ytOrganizationMapper;
  52 + private final DeviceProfileMapper ytDeviceProfileMapper;
51 53 @Override
52 54 // @Transactional
53 55 // 事务会导致 tbDBService 多数据源失效
... ... @@ -84,7 +86,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
84 86
85 87 private void validateUpdate(DeviceDTO deviceDTO) {
86 88 if (StringUtils.isAllBlank(deviceDTO.getName())) {
87   - throw new DataValidationException("device name must be specific");
  89 + throw new YtDataValidationException("device name must be specific");
88 90 }
89 91 }
90 92
... ... @@ -132,21 +134,21 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
132 134 boolean insert = StringUtils.isBlank(deviceDTO.getId());
133 135 String tenantId = deviceDTO.getTenantId();
134 136 if (StringUtils.isBlank(deviceDTO.getName())) {
135   - throw new DataValidationException("device name cannot be blank");
  137 + throw new YtDataValidationException("device name cannot be blank");
136 138 }
137 139 // validate IOT DB
138 140 if (StringUtils.isBlank(deviceDTO.getProfileId())) {
139   - throw new DataValidationException("device profile cannot be blank");
  141 + throw new YtDataValidationException("device profile cannot be blank");
140 142 }
141 143 if (StringUtils.isBlank(deviceDTO.getDeviceToken()) && !insert) {
142   - throw new DataValidationException("device token cannot be blank");
  144 + throw new YtDataValidationException("device token cannot be blank");
143 145 }
144 146 // 验证设备名称是否已经存在 如果此处直接使用deviceDTO 将有误
145 147 if (insert) {
146 148 DeviceDTO check = new DeviceDTO();
147 149 check.setName(deviceDTO.getName());
148   - if (findDeviceInfo(tenantId,check).size() > 0) {
149   - throw new DataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
  150 + if (findTbDeviceId(tenantId,check).size() > 0) {
  151 + throw new YtDataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
150 152 }
151 153
152 154 if (StringUtils.isNotBlank(deviceDTO.getDeviceToken())) {
... ... @@ -156,7 +158,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
156 158 .lambda()
157 159 .eq(YtDevice::getDeviceToken, deviceDTO.getDeviceToken()));
158 160 if (!devices.isEmpty()) {
159   - throw new DataValidationException("设备Device Token已经存在!");
  161 + throw new YtDataValidationException("设备Device Token已经存在!");
160 162 }
161 163 }
162 164 }else{
... ... @@ -166,13 +168,12 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
166 168 }
167 169 }
168 170 // 验证数据profileId的正确性
169   - TenantId tenant = new TenantId(UUID.fromString(tenantId));
170   - DeviceProfile deviceProfile = deviceProfileDao.findById(tenant,UUID.fromString(deviceDTO.getProfileId()));
171   - Organization organization = organizationMapper.selectById(deviceDTO.getOrganizationId());
  171 + YtDeviceProfile deviceProfile = ytDeviceProfileMapper.selectById(deviceDTO.getProfileId());
  172 + Organization organization = ytOrganizationMapper.selectById(deviceDTO.getOrganizationId());
172 173 if (null == deviceProfile || null == organization) {
173   - throw new DataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
  174 + throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
174 175 } else if (!organization.getTenantId().equals(tenantId)) {
175   - throw new DataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage());
  176 + throw new YtDataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage());
176 177 }
177 178 return true;
178 179 }
... ... @@ -208,7 +209,20 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
208 209 return device.getDTO(DeviceDTO.class);
209 210 }
210 211
  212 + @Override
  213 + public List<String> findTbDeviceId(String tenantId, Set<String> ids) {
  214 + LambdaQueryWrapper<YtDevice> queryWrapper =
  215 + new QueryWrapper<YtDevice>()
  216 + .lambda()
  217 + .eq(YtDevice::getTenantId, tenantId)
  218 + .in(YtDevice::getId, ids);
211 219
  220 + List<String> tbDeviceIds =
  221 + baseMapper.selectList(queryWrapper).stream()
  222 + .map(YtDevice::getTbDeviceId)
  223 + .collect(Collectors.toList());
  224 + return tbDeviceIds;
  225 + }
212 226
213 227 @Override
214 228 @Transactional
... ... @@ -219,15 +233,8 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
219 233 .eq(YtDevice::getTenantId, tenantId)
220 234 .in(YtDevice::getId, ids);
221 235
222   - List<String> tbDeviceIds =
223   - baseMapper.selectList(queryWrapper).stream()
224   - .map(YtDevice::getTbDeviceId)
225   - .collect(Collectors.toList());
226 236 baseMapper.delete(queryWrapper);
227   - // 忽略删除进度,也不管是否删除了
228   -/* if (tbConfig.isEnabled()) {
229   - tbDeviceIds.forEach(tbConnectService::deleteDevice);
230   - }*/
  237 +
231 238 }
232 239
233 240 @Override
... ... @@ -250,7 +257,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
250 257 organizationIds.add(organizationId);
251 258 // 查询该组织的所有子类
252 259 List<OrganizationDTO> organizationDTOS =
253   - organizationMapper.findOrganizationTreeList(
  260 + ytOrganizationMapper.findOrganizationTreeList(
254 261 tenantId, organizationIds);
255 262 List<String> queryOrganizationIds = new ArrayList<>();
256 263 organizationDTOS.forEach(
... ... @@ -265,7 +272,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
265 272 }
266 273
267 274 @Override
268   - public List<DeviceDTO> findDeviceInfo(String tenantId,DeviceDTO deviceDTO) {
  275 + public List<DeviceDTO> findTbDeviceId(String tenantId, DeviceDTO deviceDTO) {
269 276 List<YtDevice> deviceList =
270 277 baseMapper.selectList(
271 278 new QueryWrapper<YtDevice>()
... ...
  1 +package org.thingsboard.server.dao.yunteng.mapper;
  2 +
  3 +
  4 +import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  5 +import org.apache.ibatis.annotations.Mapper;
  6 +import org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO;
  7 +import org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile;
  8 +
  9 +import java.util.List;
  10 +
  11 +@Mapper
  12 +public interface DeviceProfileMapper extends BaseMapper<YtDeviceProfile> {
  13 +
  14 + List<DeviceProfileDTO> getDeviceProfileInfo(DeviceProfileDTO deviceProfileDTO);
  15 +}
... ...
1   -package org.thingsboard.server.dao.yunteng.service;
2   -
3   -import org.thingsboard.server.common.data.yunteng.dto.AlarmProfileDTO;
4   -
5   -import java.util.Set;
6   -
7   -public interface YtAlarmProfileService {
8   - /**
9   - * 保存告警设置
10   - * @param alarmProfileDTO 告警设置相关信息
11   - * @return AlarmProfileDTO
12   - */
13   - AlarmProfileDTO saveOrUpdateAlarmProfile(String tenantId,AlarmProfileDTO alarmProfileDTO);
14   -
15   - /**
16   - * 删除告警配置
17   - * @param ids 删除的ids
18   - * @return 删除结果:true 成功 false 失败
19   - */
20   - boolean deleteAlarmProfile(Set<String> ids);
21   -
22   - /**
23   - * 根据设备配置ID查询告警配置信息
24   - * @param deviceProfileId 设备配置ID
25   - * @return 告警配置信息
26   - */
27   - AlarmProfileDTO findAlarmProfileByDeviceProfileId(String tenantId,String deviceProfileId);
28   -}
1 1 package org.thingsboard.server.dao.yunteng.service;
2 2
  3 +import org.thingsboard.server.common.data.yunteng.dto.DeviceDTO;
3 4 import org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO;
4 5 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
5 6
... ... @@ -17,5 +18,14 @@ public interface YtDeviceProfileService {
17 18
18 19 PageData<DeviceProfileDTO> page(String tenantId, Map<String, Object> queryMap);
19 20
20   - List<DeviceProfileDTO> findDeviceProfile(String tenantId,DeviceProfileDTO deviceProfileDTO);
  21 + List<DeviceProfileDTO> findDeviceProfile(String tenantId);
  22 +
  23 +
  24 +
  25 + /**
  26 + * 验证表单数据有效性
  27 + * @param ytDeviceProfileDTO
  28 + * @return
  29 + */
  30 + boolean validateFormdata(DeviceProfileDTO ytDeviceProfileDTO);
21 31 }
... ...
... ... @@ -28,5 +28,7 @@ public interface YtDeviceService {
28 28 * @param deviceDTO 过滤参数
29 29 * @return List<DeviceDTO>
30 30 */
31   - List<DeviceDTO> findDeviceInfo(String tenantId,DeviceDTO deviceDTO);
  31 + List<DeviceDTO> findTbDeviceId(String tenantId, DeviceDTO deviceDTO);
  32 +
  33 + List<String> findTbDeviceId(String tenantId, Set<String> ids);
32 34 }
... ...
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3 +
  4 +<mapper namespace="org.thingsboard.server.dao.yunteng.mapper.DeviceProfileMapper">
  5 + <resultMap type="org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO" id="deviceProfileMap">
  6 + <result property="id" column="id"/>
  7 + <result property="name" column="name"/>
  8 +<!-- <result property="convertJs" column="convert_js"/>-->
  9 + <result property="description" column="description"/>
  10 + <result property="transportType" column="transport_type" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
  11 + <result property="tbProfileId" column="tb_profile_id"/>
  12 + <result property="tenantId" column="tenant_id"/>
  13 + <result property="createTime" column="create_time"/>
  14 + <result property="updateTime" column="update_time"/>
  15 + <result property="creator" column="creator"/>
  16 + <result property="updater" column="updater"/>
  17 + </resultMap>
  18 + <select id="getDeviceProfileInfo" resultMap="deviceProfileMap">
  19 + SELECT id,name
  20 +-- ,convert_js
  21 + ,description,transport_type,tb_profile_id,tenant_id,create_time,update_time,creator,updater FROM
  22 + iotfs_device_profile
  23 + <where>
  24 + <if test="id !=null and id!=''">
  25 + AND id = #{id}
  26 + </if>
  27 + </where>
  28 + </select>
  29 +</mapper>
... ...