Commit 6993586c45c1236377c5aa76476cf1b8f09a8e4a

Authored by xp.Huang
2 parents 4275e0cd 85cba202

Merge branch 'ljl1207' into 'master'

refactor: 设备管理

See merge request huang/thingsboard3.3.2!5
Showing 18 changed files with 523 additions and 571 deletions
... ... @@ -319,7 +319,7 @@ public abstract class BaseController {
319 319 }
320 320 }
321 321
322   - <T> T checkNotNull(T reference) throws ThingsboardException {
  322 + public <T> T checkNotNull(T reference) throws ThingsboardException {
323 323 return checkNotNull(reference, "Requested item wasn't found!");
324 324 }
325 325
... ... @@ -533,7 +533,7 @@ public abstract class BaseController {
533 533 }
534 534 }
535 535
536   - Device checkDeviceId(DeviceId deviceId, Operation operation) throws ThingsboardException {
  536 + public Device checkDeviceId(DeviceId deviceId, Operation operation) throws ThingsboardException {
537 537 try {
538 538 validateId(deviceId, "Incorrect deviceId " + deviceId);
539 539 Device device = deviceService.findDeviceById(getCurrentUser().getTenantId(), deviceId);
... ...
... ... @@ -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 1 package org.thingsboard.server.controller.yunteng;
2 2
3 3 import io.jsonwebtoken.*;
  4 +import io.swagger.annotations.Api;
4 5 import lombok.RequiredArgsConstructor;
5 6 import lombok.extern.slf4j.Slf4j;
6 7 import org.springframework.security.authentication.BadCredentialsException;
... ... @@ -26,6 +27,7 @@ import java.net.InetAddress;
26 27 @RequestMapping("/api/yt/notice")
27 28 @RequiredArgsConstructor
28 29 @Slf4j
  30 +@Api(tags = {"告警通知"})
29 31 public class YtAlarmNoticeController {
30 32
31 33 private final YtNoticeService service;
... ...
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   -}
1 1 package org.thingsboard.server.controller.yunteng;
2 2
  3 +import com.fasterxml.jackson.databind.JsonNode;
  4 +import com.fasterxml.jackson.databind.ObjectMapper;
  5 +import com.fasterxml.jackson.databind.node.ObjectNode;
  6 +import io.swagger.annotations.Api;
3 7 import lombok.RequiredArgsConstructor;
  8 +import lombok.extern.slf4j.Slf4j;
4 9 import org.apache.commons.lang3.StringUtils;
5 10 import org.springframework.http.HttpStatus;
6 11 import org.springframework.http.ResponseEntity;
7 12 import org.springframework.validation.annotation.Validated;
8 13 import org.springframework.web.bind.annotation.*;
9   -import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
  14 +import org.thingsboard.server.common.data.Device;
  15 +import org.thingsboard.server.common.data.audit.ActionType;
10 16 import org.thingsboard.server.common.data.exception.ThingsboardException;
  17 +import org.thingsboard.server.common.data.id.DeviceId;
  18 +import org.thingsboard.server.common.data.id.DeviceProfileId;
  19 +import org.thingsboard.server.common.data.id.EdgeId;
  20 +import org.thingsboard.server.common.data.id.TenantId;
11 21 import org.thingsboard.server.common.data.yunteng.common.AddGroup;
12 22 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup;
13 23 import org.thingsboard.server.common.data.yunteng.dto.DeleteDTO;
... ... @@ -17,37 +27,71 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
17 27 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum;
18 28 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
19 29 import org.thingsboard.server.controller.BaseController;
  30 +import org.thingsboard.server.dao.device.DeviceService;
20 31 import org.thingsboard.server.dao.yunteng.service.YtDeviceService;
  32 +import org.thingsboard.server.service.security.permission.Operation;
  33 +import org.thingsboard.server.service.security.permission.Resource;
21 34
22   -import java.net.URI;
  35 +import java.time.LocalDateTime;
  36 +import java.time.ZoneOffset;
23 37 import java.util.HashMap;
  38 +import java.util.List;
24 39 import java.util.Optional;
  40 +import java.util.UUID;
25 41
26 42 import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.*;
27 43
28 44 @RestController
29 45 @RequiredArgsConstructor
30 46 @RequestMapping("api/yt/device")
  47 +@Api(tags = {"设备管理"})
  48 +@Slf4j
31 49 public class YtDeviceController extends BaseController {
32 50 private final YtDeviceService deviceService;
  51 + private final DeviceService tbDeviceService;
33 52
34 53 @PostMapping
35 54 public ResponseEntity<DeviceDTO> saveDevice(@Validated(AddGroup.class)@RequestBody DeviceDTO deviceDTO)
36 55 throws ThingsboardException {
  56 + boolean enable = deviceService.validateFormdata(deviceDTO);
  57 + if(!enable){
  58 + ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
  59 + }
  60 +
  61 + Device tbDevice = buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(),deviceDTO);
  62 + Device savedDevice = updateTbDevice(tbDevice,deviceDTO.getDeviceToken());
  63 +
  64 + deviceDTO.setTbDeviceId(savedDevice.getId().getId().toString());
37 65 DeviceDTO newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
38 66 return Optional.ofNullable(newDeviceDTO)
39 67 .map(
40 68 dto -> {
41   - URI location =
42   - ServletUriComponentsBuilder.fromCurrentRequest()
43   - .path("/{id}")
44   - .buildAndExpand(newDeviceDTO.getId())
45   - .toUri();
46   - return ResponseEntity.created(location).body(newDeviceDTO);
  69 + return ResponseEntity.ok(newDeviceDTO);
47 70 })
48 71 .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
49 72 }
50 73
  74 + private Device updateTbDevice( Device tbDevice,String deviceToken) throws ThingsboardException {
  75 + Device oldDevice = null;
  76 + boolean created = tbDevice.getId() == null;
  77 + if (!created) {
  78 + oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);
  79 + } else {
  80 + checkEntity(null, tbDevice, Resource.DEVICE);
  81 + }
  82 +
  83 + Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, deviceToken));
  84 + tbClusterService.onDeviceUpdated(savedDevice, oldDevice);
  85 + try {
  86 + logEntityAction(getCurrentUser(), savedDevice.getId(), savedDevice,
  87 + savedDevice.getCustomerId(),
  88 + created ? ActionType.ADDED : ActionType.UPDATED, null);
  89 + } catch (ThingsboardException e) {
  90 + log.error("Failed to log entity action", e);
  91 + }
  92 + return savedDevice;
  93 + }
  94 +
51 95 @GetMapping("{id}")
52 96 public ResponseEntity<DeviceDTO> getDevice(@PathVariable("id") String id) throws ThingsboardException {
53 97 return ResponseEntity.of(deviceService.getDevice(getCurrentUser().getCurrentTenantId(), id));
... ... @@ -85,6 +129,62 @@ public class YtDeviceController extends BaseController {
85 129
86 130 @DeleteMapping
87 131 public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException {
88   - 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);
  155 + }
  156 +
  157 +
  158 + private final ObjectMapper objectMapper;
  159 + private Device buildTbDeviceFromDeviceDTO(TenantId tenantId,DeviceDTO deviceDTO) {
  160 + Device tbDevice = new Device();
  161 + String deviceId = deviceDTO.getTbDeviceId();
  162 + if (StringUtils.isNotBlank(deviceId)) {
  163 + DeviceId id = new DeviceId(UUID.fromString(deviceId));
  164 + tbDevice.setId(id);
  165 + }
  166 + ObjectNode additionalInfo = objectMapper.createObjectNode();
  167 + additionalInfo.put("gateway",Optional.ofNullable(deviceDTO.getDeviceType())
  168 + .map(deviceType -> deviceType.equals(DeviceTypeEnum.GATEWAY))
  169 + .orElse(false));
  170 + additionalInfo.put("description",Optional.ofNullable(deviceDTO.getDeviceInfo())
  171 + .map(deviceInfo -> deviceInfo.get("description"))
  172 + .map(JsonNode::asText)
  173 + .orElse(""));
  174 + additionalInfo.put("overwriteActivityTime",false);
  175 +
  176 +
  177 +
  178 + DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.fromString(deviceDTO.getDeviceProfile().getTbProfileId()));
  179 +
  180 +
  181 + tbDevice.setAdditionalInfo(additionalInfo);
  182 + tbDevice.setCustomerId(null);
  183 + tbDevice.setDeviceProfileId(deviceProfileId);
  184 + tbDevice.setLabel(deviceDTO.getLabel());
  185 + tbDevice.setName(deviceDTO.getName());
  186 + tbDevice.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
  187 + tbDevice.setTenantId(tenantId);
  188 + return tbDevice;
89 189 }
90 190 }
... ...
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;
... ...
... ... @@ -5,16 +5,17 @@ import com.baomidou.mybatisplus.annotation.TableField;
5 5 import com.baomidou.mybatisplus.annotation.TableName;
6 6 import lombok.Data;
7 7 import lombok.EqualsAndHashCode;
8   -import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
9 8 import org.thingsboard.server.common.data.yunteng.enums.TransportTypeEnum;
  9 +import org.thingsboard.server.dao.model.ModelConstants;
10 10
11 11 @Data
12 12 @EqualsAndHashCode(callSuper = true)
13   -@TableName(ModelConstants.Table.IOTFS_DEVICE_PROFILE_TABLE_NAME)
  13 +@TableName(ModelConstants.DEVICE_PROFILE_COLUMN_FAMILY_NAME)
14 14 public class YtDeviceProfile extends TenantBaseEntity {
15 15 private String name;
16 16 private String description;
17 17 /** 转换脚本:TCP才会使用 */
  18 + @Deprecated
18 19 private String convertJs;
19 20
20 21 private TransportTypeEnum transportType;
... ...
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,6 +9,8 @@ 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.id.TenantId;
  13 +import org.thingsboard.server.common.data.security.DeviceCredentials;
12 14 import org.thingsboard.server.common.data.yunteng.constant.FastIotConstants;
13 15 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
14 16 import org.thingsboard.server.common.data.yunteng.core.exception.YtDataValidationException;
... ... @@ -19,6 +21,8 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceState;
19 21 import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
20 22 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
21 23 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
  24 +import org.thingsboard.server.dao.device.DeviceCredentialsDao;
  25 +import org.thingsboard.server.dao.device.DeviceProfileDao;
22 26 import org.thingsboard.server.dao.yunteng.entities.Organization;
23 27 import org.thingsboard.server.dao.yunteng.entities.YtDevice;
24 28 import org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile;
... ... @@ -40,77 +44,29 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
40 44 // private final TBConfig tbConfig;
41 45 // private final TBConnectService tbConnectService;
42 46 // private final TbDBService tbDBService;
43   - private final DeviceProfileMapper deviceProfileMapper;
44   - private final OrganizationMapper organizationMapper;
  47 + private final DeviceProfileDao deviceProfileDao;
  48 + private final DeviceCredentialsDao deviceCredentialsDao;
45 49
  50 +
  51 + private final OrganizationMapper ytOrganizationMapper;
  52 + private final DeviceProfileMapper ytDeviceProfileMapper;
46 53 @Override
47 54 // @Transactional
48 55 // 事务会导致 tbDBService 多数据源失效
49 56 public DeviceDTO insertOrUpdate(String tenantId,DeviceDTO deviceDTO) {
  57 +
50 58 if (StringUtils.isBlank(deviceDTO.getId())) {
51   - return insert(tenantId,deviceDTO);
  59 + return insert(deviceDTO);
52 60 } else {
53 61 return update(tenantId,deviceDTO);
54 62 }
55 63 }
56 64
57 65 private DeviceDTO update(String tenantId,DeviceDTO deviceDTO) {
58   - YtDevice device = baseMapper.selectById(deviceDTO.getId());
59   - if (!device.getTenantId().equals(tenantId)) {
60   - return null;
61   - }
62   - validateDeviceDTO(tenantId,deviceDTO, false);
63   - List<YtDevice> devices =
64   - baseMapper.selectList(
65   - new QueryWrapper<YtDevice>()
66   - .lambda()
67   -// .eq(YtDevice::getDeviceToken, deviceDTO.getDeviceToken())
68   - );
69   - if (!devices.isEmpty()) {
70   - // 如果device token已经存在,那么必定只有一个,不会有多个
71   - YtDevice deviceExistWithSameToken = devices.get(0);
72   - if (!deviceExistWithSameToken.getId().equals(deviceDTO.getId())) {
73   - throw new YtDataValidationException("设备Device Token已经存在!");
74   - }
75   - }
76   - // 首先update tb, 需要更新的字段有
77   - // name, tbDeviceProfileId, label, isGateway, deviceToken
78   - /*if (tbConfig.isEnabled()) {
79   - validateUpdate(deviceDTO);
80   - deviceDTO.setTbDeviceId(device.getTbDeviceId());
81   - // 判断name, tbDeviceProfileId, label, isGateway是否有更新
82   - boolean changed = detectDeviceChange(deviceDTO, device);
83   - if (changed) {
84   - Device tbDevice = buildTbDeviceFromDeviceDTO(deviceDTO);
85   - try {
86   - tbConnectService.saveDevice(tbDevice, deviceDTO.getDeviceToken()).get();
87   - } catch (InterruptedException | ExecutionException e) {
88   - log.error("update device to tb error:{}", e.getMessage());
89   - throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
90   - }
91   - }
92   - // update deviceToken
93   - if (!deviceDTO.getDeviceToken().equals(device.getDeviceToken())) {
94   - CredentialEntity credentialEntity =
95   - tbDBService.findDeviceCredentialsByDeviceId(deviceDTO.getTbDeviceId());
96   - if (credentialEntity == null) {
97   - log.error("tb 无此设备信息->tbDeviceId[{}]", deviceDTO.getTbDeviceId());
98   - throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR.setMessage("tb 无此设备信息"));
99   - }
100   - credentialEntity.setCredentialsId(deviceDTO.getDeviceToken());
101   - TBCredential tbCredential = buildTBCredential(credentialEntity);
102   - try {
103   - TBCredential newTbCredentials = tbConnectService.saveDeviceCredential(tbCredential).get();
104   - if (newTbCredentials == null) {
105   - throw new FastIotException(
106   - ErrorMessage.CONNECT_TO_TB_ERROR.setMessage("update tb credentials error"));
107   - }
108   - } catch (InterruptedException | ExecutionException e) {
109   - log.error("update device to tb error:{}", e.getMessage());
110   - throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
111   - }
112   - }
113   - }*/
  66 +
  67 + validateUpdate(deviceDTO);
  68 +
  69 + YtDevice device = new YtDevice();
114 70 deviceDTO.copyToEntity(
115 71 device,
116 72 ModelConstants.TablePropertyMapping.ACTIVE_TIME,
... ... @@ -126,22 +82,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
126 82 return device.getDTO(DeviceDTO.class);
127 83 }
128 84
129   -// private TBCredential buildTBCredential(CredentialEntity credentialEntity) {
130   -// Assert.notNull(credentialEntity, "credentialEntity cannot be null");
131   -// TBCredential tbCredential = new TBCredential();
132   -// tbCredential.setCredentialsId(credentialEntity.getCredentialsId());
133   -// tbCredential.setCredentialsType(credentialEntity.getCredentialsType());
134   -// tbCredential.setCreateTime(credentialEntity.getCreatedTime());
135   -// tbCredential.setCredentialsValue(credentialEntity.getCredentialsValue());
136   -// Id deviceId = new Id();
137   -// deviceId.setEntityType(EntityType.DEVICE);
138   -// deviceId.setId(credentialEntity.getDeviceId());
139   -// tbCredential.setDeviceId(deviceId);
140   -// Id id = new Id();
141   -// id.setId(credentialEntity.getId());
142   -// tbCredential.setId(id);
143   -// return tbCredential;
144   -// }
  85 +
145 86
146 87 private void validateUpdate(DeviceDTO deviceDTO) {
147 88 if (StringUtils.isAllBlank(deviceDTO.getName())) {
... ... @@ -188,86 +129,79 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
188 129 return changed;
189 130 }
190 131
191   - private void validateDeviceDTO(String tenantId,DeviceDTO deviceDTO, boolean insert) {
  132 + @Override
  133 + public boolean validateFormdata(DeviceDTO deviceDTO) {
  134 + boolean insert = StringUtils.isBlank(deviceDTO.getId());
  135 + String tenantId = deviceDTO.getTenantId();
192 136 if (StringUtils.isBlank(deviceDTO.getName())) {
193   - throw new YtDataValidationException("device name cannot be black");
  137 + throw new YtDataValidationException("device name cannot be blank");
194 138 }
195 139 // validate IOT DB
196 140 if (StringUtils.isBlank(deviceDTO.getProfileId())) {
197   - throw new YtDataValidationException("device profile cannot be black");
  141 + throw new YtDataValidationException("device profile cannot be blank");
198 142 }
199 143 if (StringUtils.isBlank(deviceDTO.getDeviceToken()) && !insert) {
200   - throw new YtDataValidationException("device token cannot be black");
  144 + throw new YtDataValidationException("device token cannot be blank");
201 145 }
202 146 // 验证设备名称是否已经存在 如果此处直接使用deviceDTO 将有误
203 147 if (insert) {
204 148 DeviceDTO check = new DeviceDTO();
205 149 check.setName(deviceDTO.getName());
206   - if (findDeviceInfo(tenantId,check).size() > 0) {
  150 + if (findTbDeviceId(tenantId,check).size() > 0) {
207 151 throw new YtDataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
208 152 }
  153 +
  154 + if (StringUtils.isNotBlank(deviceDTO.getDeviceToken())) {
  155 + List<YtDevice> devices =
  156 + baseMapper.selectList(
  157 + new QueryWrapper<YtDevice>()
  158 + .lambda()
  159 + .eq(YtDevice::getDeviceToken, deviceDTO.getDeviceToken()));
  160 + if (!devices.isEmpty()) {
  161 + throw new YtDataValidationException("设备Device Token已经存在!");
  162 + }
  163 + }
  164 + }else{
  165 + YtDevice device = baseMapper.selectById(deviceDTO.getId());
  166 + if (!device.getTenantId().equals(tenantId)) {
  167 + return false;
  168 + }
209 169 }
210 170 // 验证数据profileId的正确性
211   - YtDeviceProfile deviceProfile = deviceProfileMapper.selectById(deviceDTO.getProfileId());
212   - Organization organization = organizationMapper.selectById(deviceDTO.getOrganizationId());
  171 + YtDeviceProfile deviceProfile = ytDeviceProfileMapper.selectById(deviceDTO.getProfileId());
  172 + Organization organization = ytOrganizationMapper.selectById(deviceDTO.getOrganizationId());
213 173 if (null == deviceProfile || null == organization) {
214 174 throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
215   -// } else if (StringUtils.isEmpty(deviceProfile.getTbProfileId())) {
216   -// throw new DataValidationException("tb_device profile is nonexistent");
217   - } else if (!deviceProfile
218   - .getTenantId()
219   - .equals(tenantId)
220   - || !organization.getTenantId().equals(tenantId)) {
  175 + } else if (!organization.getTenantId().equals(tenantId)) {
221 176 throw new YtDataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage());
222 177 }
  178 + return true;
223 179 }
224 180
225   - private DeviceDTO insert(String tenantId,DeviceDTO deviceDTO) {
226   - validateDeviceDTO(tenantId,deviceDTO, true);
227   - if (StringUtils.isNotBlank(deviceDTO.getDeviceToken())) {
228   - List<YtDevice> devices =
229   - baseMapper.selectList(
230   - new QueryWrapper<YtDevice>()
231   - .lambda()
232   - .eq(YtDevice::getDeviceToken, deviceDTO.getDeviceToken()));
233   - if (!devices.isEmpty()) {
234   - throw new YtDataValidationException("设备Device Token已经存在!");
235   - }
236   - }
  181 +
  182 +
  183 +
  184 + private DeviceDTO insert(DeviceDTO deviceDTO) {
  185 +
237 186 YtDevice device = new YtDevice();
238 187 deviceDTO.copyToEntity(
239 188 device,
240 189 ModelConstants.TablePropertyMapping.ACTIVE_TIME,
241 190 ModelConstants.TablePropertyMapping.DEVICE_STATE,
242   - ModelConstants.TablePropertyMapping.TB_DEVICE_ID,
243   - ModelConstants.TablePropertyMapping.TENANT_CODE,
244 191 ModelConstants.TablePropertyMapping.CREATOR,
245 192 ModelConstants.TablePropertyMapping.UPDATER,
246 193 ModelConstants.TablePropertyMapping.CREATE_TIME,
247 194 ModelConstants.TablePropertyMapping.UPDATE,
248 195 ModelConstants.TablePropertyMapping.UPDATE_TIME);
249   - device.setTenantId(tenantId);
250   - // First insert into TB
251   -// if (tbConfig.isEnabled()) {
252   -// Device tbDevice = buildTbDeviceFromDeviceDTO(deviceDTO);
253   -// try {
254   -// Device insertedTbDevice =
255   -// tbConnectService.saveDevice(tbDevice, deviceDTO.getDeviceToken()).get();
256   -// if (insertedTbDevice == null) {
257   -// throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
258   -// }
259   -// // 判断插入的DTO是否设置了deviceToken,如果不存在,获取Tb的deviceToken存入DB
260   -// if (StringUtils.isAllBlank(device.getDeviceToken())) {
261   -// String deviceTokenFromDB =
262   -// tbDBService.getDeviceTokenFromDB(insertedTbDevice.getId().getId());
263   -// device.setDeviceToken(deviceTokenFromDB);
264   -// }
265   -// device.setTbDeviceId(insertedTbDevice.getId().getId());
266   -// } catch (InterruptedException | ExecutionException e) {
267   -// log.error("insert device into tb error:{}", e.getMessage());
268   -// throw new FastIotException(ErrorMessage.CONNECT_TO_TB_ERROR);
269   -// }
270   -// }
  196 +
  197 + // 判断插入的DTO是否设置了deviceToken,如果不存在,获取Tb的deviceToken存入DB
  198 + if (StringUtils.isAllBlank(device.getDeviceToken())) {
  199 + TenantId tenantId = new TenantId(UUID.fromString(deviceDTO.getTenantId()));
  200 + UUID credentialsId = UUID.fromString(deviceDTO.getTbDeviceId());
  201 + DeviceCredentials deviceTokenFromDB = deviceCredentialsDao.findById(tenantId,credentialsId);
  202 + device.setDeviceToken(deviceTokenFromDB.getCredentialsId());
  203 + }
  204 +
271 205 device.setAlarmStatus(0);
272 206 /** 默认待激活状态 */
273 207 device.setDeviceState(DeviceState.INACTIVE);
... ... @@ -275,40 +209,20 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
275 209 return device.getDTO(DeviceDTO.class);
276 210 }
277 211
278   -// private Device buildTbDeviceFromDeviceDTO(DeviceDTO deviceDTO) {
279   -// Device tbDevice = new Device();
280   -// if (StringUtils.isNotBlank(deviceDTO.getTbDeviceId())) {
281   -// Id id = new Id();
282   -// id.setId(deviceDTO.getTbDeviceId());
283   -// id.setEntityType(EntityType.DEVICE);
284   -// tbDevice.setId(id);
285   -// }
286   -// Device.AdditionalInfo additionalInfo = new Device.AdditionalInfo();
287   -// additionalInfo.setGateway(
288   -// Optional.ofNullable(deviceDTO.getDeviceType())
289   -// .map(deviceType -> deviceType.equals(DeviceTypeEnum.GATEWAY))
290   -// .orElse(false));
291   -//
292   -// additionalInfo.setDescription(
293   -// Optional.ofNullable(deviceDTO.getDeviceInfo())
294   -// .map(deviceInfo -> deviceInfo.get("description"))
295   -// .map(JsonNode::asText)
296   -// .orElse(""));
297   -// additionalInfo.setOverwriteActivityTime(false);
298   -//
299   -// Id deviceProfileId = new Id();
300   -// deviceProfileId.setEntityType(EntityType.DEVICE_PROFILE);
301   -// DeviceProfile deviceProfile = deviceProfileMapper.selectById(deviceDTO.getProfileId());
302   -// deviceProfileId.setId(deviceProfile != null ? deviceProfile.getTbProfileId() : null);
303   -//
304   -// tbDevice.setAdditionalInfo(additionalInfo);
305   -// tbDevice.setCustomerId(null);
306   -// tbDevice.setDeviceProfileId(deviceProfileId);
307   -// tbDevice.setLabel(deviceDTO.getLabel());
308   -// tbDevice.setName(deviceDTO.getName());
309   -// tbDevice.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
310   -// return tbDevice;
311   -// }
  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);
  219 +
  220 + List<String> tbDeviceIds =
  221 + baseMapper.selectList(queryWrapper).stream()
  222 + .map(YtDevice::getTbDeviceId)
  223 + .collect(Collectors.toList());
  224 + return tbDeviceIds;
  225 + }
312 226
313 227 @Override
314 228 @Transactional
... ... @@ -319,15 +233,8 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
319 233 .eq(YtDevice::getTenantId, tenantId)
320 234 .in(YtDevice::getId, ids);
321 235
322   - List<String> tbDeviceIds =
323   - baseMapper.selectList(queryWrapper).stream()
324   - .map(YtDevice::getTbDeviceId)
325   - .collect(Collectors.toList());
326 236 baseMapper.delete(queryWrapper);
327   - // 忽略删除进度,也不管是否删除了
328   -/* if (tbConfig.isEnabled()) {
329   - tbDeviceIds.forEach(tbConnectService::deleteDevice);
330   - }*/
  237 +
331 238 }
332 239
333 240 @Override
... ... @@ -350,7 +257,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
350 257 organizationIds.add(organizationId);
351 258 // 查询该组织的所有子类
352 259 List<OrganizationDTO> organizationDTOS =
353   - organizationMapper.findOrganizationTreeList(
  260 + ytOrganizationMapper.findOrganizationTreeList(
354 261 tenantId, organizationIds);
355 262 List<String> queryOrganizationIds = new ArrayList<>();
356 263 organizationDTOS.forEach(
... ... @@ -365,7 +272,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
365 272 }
366 273
367 274 @Override
368   - public List<DeviceDTO> findDeviceInfo(String tenantId,DeviceDTO deviceDTO) {
  275 + public List<DeviceDTO> findTbDeviceId(String tenantId, DeviceDTO deviceDTO) {
369 276 List<YtDevice> deviceList =
370 277 baseMapper.selectList(
371 278 new QueryWrapper<YtDevice>()
... ... @@ -375,7 +282,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
375 282 YtDevice::getDeviceToken,
376 283 deviceDTO.getDeviceToken())
377 284 .eq(true, YtDevice::getTenantId, tenantId)
378   - .like(
  285 + .eq(
379 286 StringUtils.isNotBlank(deviceDTO.getName()),
380 287 YtDevice::getName,
381 288 deviceDTO.getName()));
... ...
... ... @@ -15,6 +15,7 @@ import org.apache.ibatis.session.SqlSession;
15 15 import org.mybatis.spring.SqlSessionUtils;
16 16 import org.springframework.beans.factory.annotation.Autowired;
17 17 import org.springframework.transaction.annotation.Transactional;
  18 +import org.thingsboard.server.cluster.TbClusterService;
18 19 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
19 20 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum;
20 21 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
... ... @@ -32,7 +33,7 @@ public abstract class AbstractBaseService<M extends BaseMapper<T>, T extends Bas
32 33 implements BaseService<T> {
33 34
34 35 @Autowired protected M baseMapper;
35   -
  36 + @Autowired protected TbClusterService tbClusterService;
36 37 @Override
37 38 public List<T> findAllByTenant(String tenantId) {
38 39 QueryWrapper<T> wrapper = new QueryWrapper<>();
... ... @@ -136,4 +137,6 @@ public abstract class AbstractBaseService<M extends BaseMapper<T>, T extends Bas
136 137 return (Class<T>)
137 138 ReflectionKit.getSuperClassGenericType(getClass(), 1);
138 139 }
  140 +
  141 +
139 142 }
... ...
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 }
... ...
... ... @@ -18,9 +18,17 @@ public interface YtDeviceService {
18 18 PageData<DeviceDTO> page(String tenantId,Map<String, Object> queryMap);
19 19
20 20 /**
  21 + * 验证表单数据有效性
  22 + * @param ytDevice
  23 + * @return
  24 + */
  25 + boolean validateFormdata(DeviceDTO ytDevice);
  26 + /**
21 27 * 查询所有的设备信息
22 28 * @param deviceDTO 过滤参数
23 29 * @return List<DeviceDTO>
24 30 */
25   - 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);
26 34 }
... ...
... ... @@ -5,7 +5,7 @@
5 5 <resultMap type="org.thingsboard.server.common.data.yunteng.dto.DeviceProfileDTO" id="deviceProfileMap">
6 6 <result property="id" column="id"/>
7 7 <result property="name" column="name"/>
8   - <result property="convertJs" column="convert_js"/>
  8 +<!-- <result property="convertJs" column="convert_js"/>-->
9 9 <result property="description" column="description"/>
10 10 <result property="transportType" column="transport_type" typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
11 11 <result property="tbProfileId" column="tb_profile_id"/>
... ... @@ -17,7 +17,8 @@
17 17 </resultMap>
18 18 <select id="getDeviceProfileInfo" resultMap="deviceProfileMap">
19 19 SELECT id,name
20   - ,convert_js,description,transport_type,tb_profile_id,tenant_id,create_time,update_time,creator,updater FROM
  20 +-- ,convert_js
  21 + ,description,transport_type,tb_profile_id,tenant_id,create_time,update_time,creator,updater FROM
21 22 iotfs_device_profile
22 23 <where>
23 24 <if test="id !=null and id!=''">
... ...