Commit 4a67c19c4f0460dcdd979f4c6c4397c86d34176e

Authored by 云中非
1 parent f555aa40

refactor: 设备管理

1.平台设备整合TB业务逻辑
@@ -318,7 +318,7 @@ public abstract class BaseController { @@ -318,7 +318,7 @@ public abstract class BaseController {
318 } 318 }
319 } 319 }
320 320
321 - <T> T checkNotNull(T reference) throws ThingsboardException { 321 + public <T> T checkNotNull(T reference) throws ThingsboardException {
322 return checkNotNull(reference, "Requested item wasn't found!"); 322 return checkNotNull(reference, "Requested item wasn't found!");
323 } 323 }
324 324
@@ -532,7 +532,7 @@ public abstract class BaseController { @@ -532,7 +532,7 @@ public abstract class BaseController {
532 } 532 }
533 } 533 }
534 534
535 - Device checkDeviceId(DeviceId deviceId, Operation operation) throws ThingsboardException { 535 + public Device checkDeviceId(DeviceId deviceId, Operation operation) throws ThingsboardException {
536 try { 536 try {
537 validateId(deviceId, "Incorrect deviceId " + deviceId); 537 validateId(deviceId, "Incorrect deviceId " + deviceId);
538 Device device = deviceService.findDeviceById(getCurrentUser().getTenantId(), deviceId); 538 Device device = deviceService.findDeviceById(getCurrentUser().getTenantId(), deviceId);
1 package org.thingsboard.server.controller.yunteng; 1 package org.thingsboard.server.controller.yunteng;
2 2
3 import io.jsonwebtoken.*; 3 import io.jsonwebtoken.*;
  4 +import io.swagger.annotations.Api;
4 import lombok.RequiredArgsConstructor; 5 import lombok.RequiredArgsConstructor;
5 import lombok.extern.slf4j.Slf4j; 6 import lombok.extern.slf4j.Slf4j;
6 import org.springframework.security.authentication.BadCredentialsException; 7 import org.springframework.security.authentication.BadCredentialsException;
@@ -26,6 +27,7 @@ import java.net.InetAddress; @@ -26,6 +27,7 @@ import java.net.InetAddress;
26 @RequestMapping("/api/yt/notice") 27 @RequestMapping("/api/yt/notice")
27 @RequiredArgsConstructor 28 @RequiredArgsConstructor
28 @Slf4j 29 @Slf4j
  30 +@Api(tags = {"告警通知"})
29 public class YtAlarmNoticeController { 31 public class YtAlarmNoticeController {
30 32
31 private final YtNoticeService service; 33 private final YtNoticeService service;
1 package org.thingsboard.server.controller.yunteng; 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 import lombok.RequiredArgsConstructor; 7 import lombok.RequiredArgsConstructor;
  8 +import lombok.extern.slf4j.Slf4j;
4 import org.apache.commons.lang3.StringUtils; 9 import org.apache.commons.lang3.StringUtils;
5 import org.springframework.http.HttpStatus; 10 import org.springframework.http.HttpStatus;
6 import org.springframework.http.ResponseEntity; 11 import org.springframework.http.ResponseEntity;
7 import org.springframework.validation.annotation.Validated; 12 import org.springframework.validation.annotation.Validated;
8 import org.springframework.web.bind.annotation.*; 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 import org.thingsboard.server.common.data.exception.ThingsboardException; 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.TenantId;
11 import org.thingsboard.server.common.data.yunteng.common.AddGroup; 20 import org.thingsboard.server.common.data.yunteng.common.AddGroup;
12 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup; 21 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup;
13 import org.thingsboard.server.common.data.yunteng.core.exception.FastIotException; 22 import org.thingsboard.server.common.data.yunteng.core.exception.FastIotException;
@@ -18,33 +27,61 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum; @@ -18,33 +27,61 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
18 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum; 27 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum;
19 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData; 28 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
20 import org.thingsboard.server.controller.BaseController; 29 import org.thingsboard.server.controller.BaseController;
  30 +import org.thingsboard.server.dao.device.DeviceService;
21 import org.thingsboard.server.dao.yunteng.service.YtDeviceService; 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;
22 34
23 -import java.net.URI; 35 +import java.time.LocalDateTime;
  36 +import java.time.ZoneOffset;
24 import java.util.HashMap; 37 import java.util.HashMap;
25 import java.util.Optional; 38 import java.util.Optional;
  39 +import java.util.UUID;
26 40
27 import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.*; 41 import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.*;
28 42
29 @RestController 43 @RestController
30 @RequiredArgsConstructor 44 @RequiredArgsConstructor
31 @RequestMapping("api/yt/device") 45 @RequestMapping("api/yt/device")
  46 +@Api(tags = {"设备管理"})
  47 +@Slf4j
32 public class YtDeviceController extends BaseController { 48 public class YtDeviceController extends BaseController {
33 private final YtDeviceService deviceService; 49 private final YtDeviceService deviceService;
  50 + private final DeviceService tbDeviceService;
34 51
35 @PostMapping 52 @PostMapping
36 public ResponseEntity<DeviceDTO> saveDevice(@Validated(AddGroup.class)@RequestBody DeviceDTO deviceDTO) 53 public ResponseEntity<DeviceDTO> saveDevice(@Validated(AddGroup.class)@RequestBody DeviceDTO deviceDTO)
37 throws FastIotException, ThingsboardException { 54 throws FastIotException, ThingsboardException {
  55 + boolean enable = deviceService.validateFormdata(deviceDTO);
  56 + if(!enable){
  57 + ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
  58 + }
  59 +
  60 + Device tbDevice = buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(),deviceDTO);
  61 + Device oldDevice = null;
  62 + boolean created = tbDevice.getId() == null;
  63 + if (!created) {
  64 + oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);
  65 + } else {
  66 + checkEntity(null, tbDevice, Resource.DEVICE);
  67 + }
  68 +
  69 + Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, deviceDTO.getDeviceToken()));
  70 + tbClusterService.onDeviceUpdated(savedDevice, oldDevice);
  71 + try {
  72 + logEntityAction(getCurrentUser(), savedDevice.getId(), savedDevice,
  73 + savedDevice.getCustomerId(),
  74 + created ? ActionType.ADDED : ActionType.UPDATED, null);
  75 + } catch (ThingsboardException e) {
  76 + log.error("Failed to log entity action", e);
  77 + }
  78 +
  79 + deviceDTO.setTbDeviceId(savedDevice.getId().getId().toString());
38 DeviceDTO newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO); 80 DeviceDTO newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
39 return Optional.ofNullable(newDeviceDTO) 81 return Optional.ofNullable(newDeviceDTO)
40 .map( 82 .map(
41 dto -> { 83 dto -> {
42 - URI location =  
43 - ServletUriComponentsBuilder.fromCurrentRequest()  
44 - .path("/{id}")  
45 - .buildAndExpand(newDeviceDTO.getId())  
46 - .toUri();  
47 - return ResponseEntity.created(location).body(newDeviceDTO); 84 + return ResponseEntity.ok(newDeviceDTO);
48 }) 85 })
49 .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build()); 86 .orElse(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build());
50 } 87 }
@@ -88,4 +125,37 @@ public class YtDeviceController extends BaseController { @@ -88,4 +125,37 @@ public class YtDeviceController extends BaseController {
88 public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException { 125 public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) throws ThingsboardException {
89 deviceService.deleteDevices(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds()); 126 deviceService.deleteDevices(getCurrentUser().getCurrentTenantId(), deleteDTO.getIds());
90 } 127 }
  128 +
  129 +
  130 + private final ObjectMapper objectMapper;
  131 + private Device buildTbDeviceFromDeviceDTO(TenantId tenantId,DeviceDTO deviceDTO) {
  132 + Device tbDevice = new Device();
  133 + String deviceId = deviceDTO.getTbDeviceId();
  134 + if (StringUtils.isNotBlank(deviceId)) {
  135 + DeviceId id = new DeviceId(UUID.fromString(deviceId));
  136 + tbDevice.setId(id);
  137 + }
  138 + ObjectNode additionalInfo = objectMapper.createObjectNode();
  139 + additionalInfo.put("gateway",Optional.ofNullable(deviceDTO.getDeviceType())
  140 + .map(deviceType -> deviceType.equals(DeviceTypeEnum.GATEWAY))
  141 + .orElse(false));
  142 + additionalInfo.put("description",Optional.ofNullable(deviceDTO.getDeviceInfo())
  143 + .map(deviceInfo -> deviceInfo.get("description"))
  144 + .map(JsonNode::asText)
  145 + .orElse(""));
  146 + additionalInfo.put("overwriteActivityTime",false);
  147 +
  148 +
  149 + DeviceProfileId deviceProfileId = new DeviceProfileId(UUID.fromString(deviceDTO.getProfileId()));
  150 +
  151 +
  152 + tbDevice.setAdditionalInfo(additionalInfo);
  153 + tbDevice.setCustomerId(null);
  154 + tbDevice.setDeviceProfileId(deviceProfileId);
  155 + tbDevice.setLabel(deviceDTO.getLabel());
  156 + tbDevice.setName(deviceDTO.getName());
  157 + tbDevice.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
  158 + tbDevice.setTenantId(tenantId);
  159 + return tbDevice;
  160 + }
91 } 161 }
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.constant.ModelConstants;  
9 -import org.thingsboard.server.common.data.yunteng.enums.TransportTypeEnum;  
10 -  
11 -@Data  
12 -@EqualsAndHashCode(callSuper = true)  
13 -@TableName(ModelConstants.Table.IOTFS_DEVICE_PROFILE_TABLE_NAME)  
14 -public class YtDeviceProfile extends TenantBaseEntity {  
15 - private String name;  
16 - private String description;  
17 - /** 转换脚本:TCP才会使用 */  
18 - private String convertJs;  
19 -  
20 - private TransportTypeEnum transportType;  
21 - /** TB的设备配置文件 */  
22 - @TableField(updateStrategy = FieldStrategy.IGNORED)  
23 - private String tbProfileId;  
24 -}  
@@ -9,6 +9,9 @@ import lombok.extern.slf4j.Slf4j; @@ -9,6 +9,9 @@ import lombok.extern.slf4j.Slf4j;
9 import org.apache.commons.lang3.StringUtils; 9 import org.apache.commons.lang3.StringUtils;
10 import org.springframework.stereotype.Service; 10 import org.springframework.stereotype.Service;
11 import org.springframework.transaction.annotation.Transactional; 11 import org.springframework.transaction.annotation.Transactional;
  12 +import org.thingsboard.server.common.data.DeviceProfile;
  13 +import org.thingsboard.server.common.data.id.TenantId;
  14 +import org.thingsboard.server.common.data.security.DeviceCredentials;
12 import org.thingsboard.server.common.data.yunteng.constant.FastIotConstants; 15 import org.thingsboard.server.common.data.yunteng.constant.FastIotConstants;
13 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants; 16 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
14 import org.thingsboard.server.common.data.yunteng.core.exception.DataValidationException; 17 import org.thingsboard.server.common.data.yunteng.core.exception.DataValidationException;
@@ -19,11 +22,11 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceState; @@ -19,11 +22,11 @@ import org.thingsboard.server.common.data.yunteng.enums.DeviceState;
19 import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum; 22 import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
20 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils; 23 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
21 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData; 24 import org.thingsboard.server.common.data.yunteng.utils.tools.PageData;
  25 +import org.thingsboard.server.dao.device.DeviceCredentialsDao;
  26 +import org.thingsboard.server.dao.device.DeviceProfileDao;
22 import org.thingsboard.server.dao.yunteng.entities.Organization; 27 import org.thingsboard.server.dao.yunteng.entities.Organization;
23 import org.thingsboard.server.dao.yunteng.entities.YtDevice; 28 import org.thingsboard.server.dao.yunteng.entities.YtDevice;
24 -import org.thingsboard.server.dao.yunteng.entities.YtDeviceProfile;  
25 import org.thingsboard.server.dao.yunteng.mapper.DeviceMapper; 29 import org.thingsboard.server.dao.yunteng.mapper.DeviceMapper;
26 -import org.thingsboard.server.dao.yunteng.mapper.DeviceProfileMapper;  
27 import org.thingsboard.server.dao.yunteng.mapper.OrganizationMapper; 30 import org.thingsboard.server.dao.yunteng.mapper.OrganizationMapper;
28 import org.thingsboard.server.dao.yunteng.service.AbstractBaseService; 31 import org.thingsboard.server.dao.yunteng.service.AbstractBaseService;
29 import org.thingsboard.server.dao.yunteng.service.YtDeviceService; 32 import org.thingsboard.server.dao.yunteng.service.YtDeviceService;
@@ -40,77 +43,28 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -40,77 +43,28 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
40 // private final TBConfig tbConfig; 43 // private final TBConfig tbConfig;
41 // private final TBConnectService tbConnectService; 44 // private final TBConnectService tbConnectService;
42 // private final TbDBService tbDBService; 45 // private final TbDBService tbDBService;
43 - private final DeviceProfileMapper deviceProfileMapper;  
44 - private final OrganizationMapper organizationMapper; 46 + private final DeviceProfileDao deviceProfileDao;
  47 + private final DeviceCredentialsDao deviceCredentialsDao;
  48 +
45 49
  50 + private final OrganizationMapper organizationMapper;
46 @Override 51 @Override
47 // @Transactional 52 // @Transactional
48 // 事务会导致 tbDBService 多数据源失效 53 // 事务会导致 tbDBService 多数据源失效
49 public DeviceDTO insertOrUpdate(String tenantId,DeviceDTO deviceDTO) { 54 public DeviceDTO insertOrUpdate(String tenantId,DeviceDTO deviceDTO) {
  55 +
50 if (StringUtils.isBlank(deviceDTO.getId())) { 56 if (StringUtils.isBlank(deviceDTO.getId())) {
51 - return insert(tenantId,deviceDTO); 57 + return insert(deviceDTO);
52 } else { 58 } else {
53 return update(tenantId,deviceDTO); 59 return update(tenantId,deviceDTO);
54 } 60 }
55 } 61 }
56 62
57 private DeviceDTO update(String tenantId,DeviceDTO deviceDTO) { 63 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 DataValidationException("设备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 - }*/ 64 +
  65 + validateUpdate(deviceDTO);
  66 +
  67 + YtDevice device = new YtDevice();
114 deviceDTO.copyToEntity( 68 deviceDTO.copyToEntity(
115 device, 69 device,
116 ModelConstants.TablePropertyMapping.ACTIVE_TIME, 70 ModelConstants.TablePropertyMapping.ACTIVE_TIME,
@@ -126,22 +80,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -126,22 +80,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
126 return device.getDTO(DeviceDTO.class); 80 return device.getDTO(DeviceDTO.class);
127 } 81 }
128 82
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 -// } 83 +
145 84
146 private void validateUpdate(DeviceDTO deviceDTO) { 85 private void validateUpdate(DeviceDTO deviceDTO) {
147 if (StringUtils.isAllBlank(deviceDTO.getName())) { 86 if (StringUtils.isAllBlank(deviceDTO.getName())) {
@@ -188,16 +127,19 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -188,16 +127,19 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
188 return changed; 127 return changed;
189 } 128 }
190 129
191 - private void validateDeviceDTO(String tenantId,DeviceDTO deviceDTO, boolean insert) { 130 + @Override
  131 + public boolean validateFormdata(DeviceDTO deviceDTO) {
  132 + boolean insert = StringUtils.isBlank(deviceDTO.getId());
  133 + String tenantId = deviceDTO.getTenantId();
192 if (StringUtils.isBlank(deviceDTO.getName())) { 134 if (StringUtils.isBlank(deviceDTO.getName())) {
193 - throw new DataValidationException("device name cannot be black"); 135 + throw new DataValidationException("device name cannot be blank");
194 } 136 }
195 // validate IOT DB 137 // validate IOT DB
196 if (StringUtils.isBlank(deviceDTO.getProfileId())) { 138 if (StringUtils.isBlank(deviceDTO.getProfileId())) {
197 - throw new DataValidationException("device profile cannot be black"); 139 + throw new DataValidationException("device profile cannot be blank");
198 } 140 }
199 if (StringUtils.isBlank(deviceDTO.getDeviceToken()) && !insert) { 141 if (StringUtils.isBlank(deviceDTO.getDeviceToken()) && !insert) {
200 - throw new DataValidationException("device token cannot be black"); 142 + throw new DataValidationException("device token cannot be blank");
201 } 143 }
202 // 验证设备名称是否已经存在 如果此处直接使用deviceDTO 将有误 144 // 验证设备名称是否已经存在 如果此处直接使用deviceDTO 将有误
203 if (insert) { 145 if (insert) {
@@ -206,68 +148,59 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -206,68 +148,59 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
206 if (findDeviceInfo(tenantId,check).size() > 0) { 148 if (findDeviceInfo(tenantId,check).size() > 0) {
207 throw new DataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage()); 149 throw new DataValidationException(ErrorMessage.NAME_ALREADY_EXISTS.getMessage());
208 } 150 }
  151 +
  152 + if (StringUtils.isNotBlank(deviceDTO.getDeviceToken())) {
  153 + List<YtDevice> devices =
  154 + baseMapper.selectList(
  155 + new QueryWrapper<YtDevice>()
  156 + .lambda()
  157 + .eq(YtDevice::getDeviceToken, deviceDTO.getDeviceToken()));
  158 + if (!devices.isEmpty()) {
  159 + throw new DataValidationException("设备Device Token已经存在!");
  160 + }
  161 + }
  162 + }else{
  163 + YtDevice device = baseMapper.selectById(deviceDTO.getId());
  164 + if (!device.getTenantId().equals(tenantId)) {
  165 + return false;
  166 + }
209 } 167 }
210 // 验证数据profileId的正确性 168 // 验证数据profileId的正确性
211 - YtDeviceProfile deviceProfile = deviceProfileMapper.selectById(deviceDTO.getProfileId()); 169 + TenantId tenant = new TenantId(UUID.fromString(tenantId));
  170 + DeviceProfile deviceProfile = deviceProfileDao.findById(tenant,UUID.fromString(deviceDTO.getProfileId()));
212 Organization organization = organizationMapper.selectById(deviceDTO.getOrganizationId()); 171 Organization organization = organizationMapper.selectById(deviceDTO.getOrganizationId());
213 if (null == deviceProfile || null == organization) { 172 if (null == deviceProfile || null == organization) {
214 throw new DataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage()); 173 throw new DataValidationException(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)) { 174 + } else if (!organization.getTenantId().equals(tenantId)) {
221 throw new DataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage()); 175 throw new DataValidationException(ErrorMessage.TENANT_MISMATCHING.getMessage());
222 } 176 }
  177 + return true;
223 } 178 }
224 179
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 DataValidationException("设备Device Token已经存在!");  
235 - }  
236 - } 180 +
  181 +
  182 +
  183 + private DeviceDTO insert(DeviceDTO deviceDTO) {
  184 +
237 YtDevice device = new YtDevice(); 185 YtDevice device = new YtDevice();
238 deviceDTO.copyToEntity( 186 deviceDTO.copyToEntity(
239 device, 187 device,
240 ModelConstants.TablePropertyMapping.ACTIVE_TIME, 188 ModelConstants.TablePropertyMapping.ACTIVE_TIME,
241 ModelConstants.TablePropertyMapping.DEVICE_STATE, 189 ModelConstants.TablePropertyMapping.DEVICE_STATE,
242 - ModelConstants.TablePropertyMapping.TB_DEVICE_ID,  
243 - ModelConstants.TablePropertyMapping.TENANT_CODE,  
244 ModelConstants.TablePropertyMapping.CREATOR, 190 ModelConstants.TablePropertyMapping.CREATOR,
245 ModelConstants.TablePropertyMapping.UPDATER, 191 ModelConstants.TablePropertyMapping.UPDATER,
246 ModelConstants.TablePropertyMapping.CREATE_TIME, 192 ModelConstants.TablePropertyMapping.CREATE_TIME,
247 ModelConstants.TablePropertyMapping.UPDATE, 193 ModelConstants.TablePropertyMapping.UPDATE,
248 ModelConstants.TablePropertyMapping.UPDATE_TIME); 194 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 -// } 195 +
  196 + // 判断插入的DTO是否设置了deviceToken,如果不存在,获取Tb的deviceToken存入DB
  197 + if (StringUtils.isAllBlank(device.getDeviceToken())) {
  198 + TenantId tenantId = new TenantId(UUID.fromString(deviceDTO.getTenantId()));
  199 + UUID credentialsId = UUID.fromString(deviceDTO.getTbDeviceId());
  200 + DeviceCredentials deviceTokenFromDB = deviceCredentialsDao.findById(tenantId,credentialsId);
  201 + device.setDeviceToken(deviceTokenFromDB.getCredentialsId());
  202 + }
  203 +
271 device.setAlarmStatus(0); 204 device.setAlarmStatus(0);
272 /** 默认待激活状态 */ 205 /** 默认待激活状态 */
273 device.setDeviceState(DeviceState.INACTIVE); 206 device.setDeviceState(DeviceState.INACTIVE);
@@ -275,40 +208,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -275,40 +208,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
275 return device.getDTO(DeviceDTO.class); 208 return device.getDTO(DeviceDTO.class);
276 } 209 }
277 210
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 -// } 211 +
312 212
313 @Override 213 @Override
314 @Transactional 214 @Transactional
@@ -375,7 +275,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev @@ -375,7 +275,7 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
375 YtDevice::getDeviceToken, 275 YtDevice::getDeviceToken,
376 deviceDTO.getDeviceToken()) 276 deviceDTO.getDeviceToken())
377 .eq(true, YtDevice::getTenantId, tenantId) 277 .eq(true, YtDevice::getTenantId, tenantId)
378 - .like( 278 + .eq(
379 StringUtils.isNotBlank(deviceDTO.getName()), 279 StringUtils.isNotBlank(deviceDTO.getName()),
380 YtDevice::getName, 280 YtDevice::getName,
381 deviceDTO.getName())); 281 deviceDTO.getName()));
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 -}  
@@ -15,6 +15,7 @@ import org.apache.ibatis.session.SqlSession; @@ -15,6 +15,7 @@ import org.apache.ibatis.session.SqlSession;
15 import org.mybatis.spring.SqlSessionUtils; 15 import org.mybatis.spring.SqlSessionUtils;
16 import org.springframework.beans.factory.annotation.Autowired; 16 import org.springframework.beans.factory.annotation.Autowired;
17 import org.springframework.transaction.annotation.Transactional; 17 import org.springframework.transaction.annotation.Transactional;
  18 +import org.thingsboard.server.cluster.TbClusterService;
18 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants; 19 import org.thingsboard.server.common.data.yunteng.constant.ModelConstants;
19 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum; 20 import org.thingsboard.server.common.data.yunteng.enums.OrderTypeEnum;
20 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils; 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,7 +33,7 @@ public abstract class AbstractBaseService<M extends BaseMapper<T>, T extends Bas
32 implements BaseService<T> { 33 implements BaseService<T> {
33 34
34 @Autowired protected M baseMapper; 35 @Autowired protected M baseMapper;
35 - 36 + @Autowired protected TbClusterService tbClusterService;
36 @Override 37 @Override
37 public List<T> findAllByTenant(String tenantId) { 38 public List<T> findAllByTenant(String tenantId) {
38 QueryWrapper<T> wrapper = new QueryWrapper<>(); 39 QueryWrapper<T> wrapper = new QueryWrapper<>();
@@ -136,4 +137,6 @@ public abstract class AbstractBaseService<M extends BaseMapper<T>, T extends Bas @@ -136,4 +137,6 @@ public abstract class AbstractBaseService<M extends BaseMapper<T>, T extends Bas
136 return (Class<T>) 137 return (Class<T>)
137 ReflectionKit.getSuperClassGenericType(getClass(), 1); 138 ReflectionKit.getSuperClassGenericType(getClass(), 1);
138 } 139 }
  140 +
  141 +
139 } 142 }
@@ -18,6 +18,12 @@ public interface YtDeviceService { @@ -18,6 +18,12 @@ public interface YtDeviceService {
18 PageData<DeviceDTO> page(String tenantId,Map<String, Object> queryMap); 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 * @param deviceDTO 过滤参数 28 * @param deviceDTO 过滤参数
23 * @return List<DeviceDTO> 29 * @return List<DeviceDTO>
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,description,transport_type,tb_profile_id,tenant_id,create_time,update_time,creator,updater FROM  
21 - iotfs_device_profile  
22 - <where>  
23 - <if test="id !=null and id!=''">  
24 - AND id = #{id}  
25 - </if>  
26 - </where>  
27 - </select>  
28 -</mapper>