Commit 697d0e05767d7a90e097db0610461382d5dfbc87

Authored by 云中非
1 parent 24371afe

feat: 自动生成设备编号

... ... @@ -46,10 +46,7 @@ import org.thingsboard.server.service.security.permission.Resource;
46 46
47 47 import java.time.LocalDateTime;
48 48 import java.time.ZoneOffset;
49   -import java.util.HashMap;
50   -import java.util.List;
51   -import java.util.Optional;
52   -import java.util.UUID;
  49 +import java.util.*;
53 50 import java.util.concurrent.ExecutionException;
54 51
55 52 import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.*;
... ... @@ -60,363 +57,371 @@ import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.
60 57 @Api(tags = {"设备管理"})
61 58 @Slf4j
62 59 public class YtDeviceController extends BaseController {
63   - private final YtDeviceService deviceService;
64   - private final DeviceService tbDeviceService;
65   -
66   - @PostMapping
67   - @ApiOperation("创建|编辑")
68   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
69   - public ResponseEntity<DeviceDTO> saveDevice(
70   - @Validated(AddGroup.class) @RequestBody DeviceDTO deviceDTO) throws ThingsboardException, ExecutionException, InterruptedException {
71   - String currentTenantId = getCurrentUser().getCurrentTenantId();
72   - boolean enable = deviceService.validateFormdata(currentTenantId, deviceDTO);
73   - if (!enable) {
74   - ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
75   - }
76   - DeviceDTO newDeviceDTO = null;
77   - boolean isIncludeRelation = false;
78   -
79   - String gatewayId = deviceDTO.getGatewayId();
80   - DeviceDTO gateWayDevice = null;
81   - if (StringUtils.isNotEmpty(gatewayId)) {
82   - gateWayDevice =
83   - deviceService.checkDeviceByTenantIdAndDeviceId(
84   - getCurrentUser().getCurrentTenantId(), gatewayId);
85   -
86   - // 第一步判断该网关设备是否存在于该租户下面
87   - if (null == gateWayDevice) {
88   - throw new YtDataValidationException(
89   - ErrorMessage.DEVICE_NOT_EXISTENCE_IN_TENANT.getMessage());
90   - }
91   - }
  60 + private final YtDeviceService deviceService;
  61 + private final DeviceService tbDeviceService;
  62 +
  63 + @PostMapping
  64 + @ApiOperation("创建|编辑")
  65 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
  66 + public ResponseEntity<DeviceDTO> saveDevice(
  67 + @Validated(AddGroup.class) @RequestBody DeviceDTO deviceDTO) throws ThingsboardException, ExecutionException, InterruptedException {
  68 + String currentTenantId = getCurrentUser().getCurrentTenantId();
  69 + boolean enable = deviceService.validateFormdata(currentTenantId, deviceDTO);
  70 + if (!enable) {
  71 + ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
  72 + }
  73 + DeviceDTO newDeviceDTO = null;
  74 + boolean isIncludeRelation = false;
  75 +
  76 + String gatewayId = deviceDTO.getGatewayId();
  77 + DeviceDTO gateWayDevice = null;
  78 + if (StringUtils.isNotEmpty(gatewayId)) {
  79 + gateWayDevice =
  80 + deviceService.checkDeviceByTenantIdAndDeviceId(
  81 + getCurrentUser().getCurrentTenantId(), gatewayId);
  82 +
  83 + // 第一步判断该网关设备是否存在于该租户下面
  84 + if (null == gateWayDevice) {
  85 + throw new YtDataValidationException(
  86 + ErrorMessage.DEVICE_NOT_EXISTENCE_IN_TENANT.getMessage());
  87 + }
  88 + }
92 89
93   - /**子设备编辑时,TB中已经存在关联关系则值更新设备表信息*/
94   - String selfTbDeviceIdStr = deviceDTO.getTbDeviceId();
95   - if (selfTbDeviceIdStr != null
96   - && deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)
97   - && StringUtils.isNotEmpty(gatewayId)) {
98   -
99   -
100   - // 第二步判断网关子设备是否已关联到网关设备
101   - EntityId entityId = EntityIdFactory.getByTypeAndId("DEVICE", selfTbDeviceIdStr);//gateWayDevice.getTbDeviceId()
102   - List<EntityRelationInfo> list =
103   - relationService.findInfoByTo(getTenantId(), entityId, RelationTypeGroup.COMMON).get();
104   -
105   - for (EntityRelationInfo entityRelationInfo : list) {
106   - if (entityRelationInfo.getTo().getId().equals(selfTbDeviceIdStr)
107   - && entityRelationInfo.getFrom().getId().equals(gatewayId)) {
108   - deviceDTO.setTbDeviceId(entityRelationInfo.getTo().toString());
109   - newDeviceDTO =
110   - deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
111   - isIncludeRelation = true;
112   - break;
113   - }
  90 + /**子设备编辑时,TB中已经存在关联关系则值更新设备表信息*/
  91 + String selfTbDeviceIdStr = deviceDTO.getTbDeviceId();
  92 + if (selfTbDeviceIdStr != null
  93 + && deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)
  94 + && StringUtils.isNotEmpty(gatewayId)) {
  95 +
  96 +
  97 + // 第二步判断网关子设备是否已关联到网关设备
  98 + EntityId entityId = EntityIdFactory.getByTypeAndId("DEVICE", selfTbDeviceIdStr);//gateWayDevice.getTbDeviceId()
  99 + List<EntityRelationInfo> list =
  100 + relationService.findInfoByTo(getTenantId(), entityId, RelationTypeGroup.COMMON).get();
  101 +
  102 + for (EntityRelationInfo entityRelationInfo : list) {
  103 + if (entityRelationInfo.getTo().getId().equals(selfTbDeviceIdStr)
  104 + && entityRelationInfo.getFrom().getId().equals(gatewayId)) {
  105 + deviceDTO.setTbDeviceId(entityRelationInfo.getTo().toString());
  106 + newDeviceDTO =
  107 + deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
  108 + isIncludeRelation = true;
  109 + break;
  110 + }
  111 + }
114 112 }
115   - }
116 113
117 114
118   - /**需要更新设备表和关联关系表*/
119   - if (!isIncludeRelation) {
120   - Device tbDevice = buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(), deviceDTO);
  115 + /**需要更新设备表和关联关系表*/
  116 + if (!isIncludeRelation) {
  117 + Device tbDevice = buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(), deviceDTO);
  118 +
  119 + DeviceId selfTbId = updateTbDevice(tbDevice, deviceDTO.getDeviceToken());
  120 + selfTbDeviceIdStr = selfTbId.getId().toString();
  121 + deviceDTO.setTbDeviceId(selfTbDeviceIdStr);
  122 + newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
  123 +
  124 + if (deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)
  125 + && StringUtils.isNotEmpty(selfTbDeviceIdStr)) {
  126 + // 删除原來的关联关系
  127 + List<DeviceDTO> list =
  128 + deviceService.findGateWayDeviceByTbDeviceId(
  129 + getCurrentUser().getCurrentTenantId(), selfTbDeviceIdStr);
  130 + if (null != list && list.size() > 0) {
  131 + DeviceId form = new DeviceId(UUID.fromString(list.get(0).getTbDeviceId()));
  132 + EntityRelation relation =
  133 + new EntityRelation(
  134 + form, selfTbId, FastIotConstants.Relation.relationType, RelationTypeGroup.COMMON);
  135 + boolean found =
  136 + relationService.deleteRelation(
  137 + getTenantId(),
  138 + form,
  139 + selfTbId,
  140 + FastIotConstants.Relation.relationType,
  141 + RelationTypeGroup.COMMON);
  142 +
  143 + if (!found) {
  144 + throw new ThingsboardException(
  145 + "Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
  146 + }
  147 + sendRelationNotificationMsg(
  148 + getTenantId(), relation, EdgeEventActionType.RELATION_DELETED);
  149 + }
  150 +
  151 + if (gateWayDevice != null) {
  152 + addRelation(getTenantId(), gateWayDevice.getTbDeviceId(), selfTbDeviceIdStr);
  153 + }
  154 + }
  155 + }
  156 + return ResponseEntity.ok(newDeviceDTO);
  157 + }
121 158
122   - DeviceId selfTbId = updateTbDevice(tbDevice, deviceDTO.getDeviceToken());
123   - selfTbDeviceIdStr = selfTbId.getId().toString();
124   - deviceDTO.setTbDeviceId( selfTbDeviceIdStr);
125   - newDeviceDTO = deviceService.insertOrUpdate(getCurrentUser().getCurrentTenantId(), deviceDTO);
  159 + @GetMapping({"sn"})
  160 + @ApiOperation("自动生成设备SN")
  161 + public ResponseEntity<String> generate() {
  162 + String result = deviceService.generateSn();
  163 + return ResponseEntity.ok(result);
  164 + }
126 165
127   - if (deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)
128   - && StringUtils.isNotEmpty(selfTbDeviceIdStr)) {
129   - // 删除原來的关联关系
130   - List<DeviceDTO> list =
131   - deviceService.findGateWayDeviceByTbDeviceId(
132   - getCurrentUser().getCurrentTenantId(), selfTbDeviceIdStr);
133   - if (null != list && list.size() > 0) {
134   - DeviceId form = new DeviceId(UUID.fromString(list.get(0).getTbDeviceId()));
135   - EntityRelation relation =
136   - new EntityRelation(
137   - form, selfTbId, FastIotConstants.Relation.relationType, RelationTypeGroup.COMMON);
138   - boolean found =
139   - relationService.deleteRelation(
140   - getTenantId(),
141   - form,
142   - selfTbId,
143   - FastIotConstants.Relation.relationType,
144   - RelationTypeGroup.COMMON);
145   -
146   - if (!found) {
147   - throw new ThingsboardException(
148   - "Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
149   - }
150   - sendRelationNotificationMsg(
151   - getTenantId(), relation, EdgeEventActionType.RELATION_DELETED);
  166 + private DeviceId updateTbDevice(Device tbDevice, YtCredentialsDto formCredentials)
  167 + throws ThingsboardException {
  168 + Device oldDevice = null;
  169 + boolean created = tbDevice.getId() == null;
  170 + if (!created) {
  171 + oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);
  172 + } else {
  173 + checkEntity(null, tbDevice, Resource.DEVICE);
152 174 }
153 175
154   - if(gateWayDevice != null){
155   - addRelation(getTenantId(), gateWayDevice.getTbDeviceId(), selfTbDeviceIdStr);
  176 + Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, null));
  177 + tbClusterService.onDeviceUpdated(savedDevice, oldDevice);
  178 + DeviceId tbDeviceId = savedDevice.getId();
  179 + try {
  180 + logEntityAction(
  181 + getCurrentUser(),
  182 + savedDevice.getId(),
  183 + savedDevice,
  184 + savedDevice.getCustomerId(),
  185 + created ? ActionType.ADDED : ActionType.UPDATED,
  186 + null);
  187 +
  188 + if (formCredentials != null && formCredentials.getCredentialsType() != null) {
  189 + DeviceCredentials deviceCredentials =
  190 + checkNotNull(
  191 + deviceCredentialsService.findDeviceCredentialsByDeviceId(
  192 + getCurrentUser().getTenantId(), tbDeviceId));
  193 + deviceCredentials.setCredentialsId(formCredentials.getCredentialsId());
  194 + deviceCredentials.setCredentialsType(formCredentials.getCredentialsType());
  195 + deviceCredentials.setCredentialsValue(formCredentials.getCredentialsValue());
  196 +
  197 + DeviceCredentials result =
  198 + checkNotNull(
  199 + deviceCredentialsService.updateDeviceCredentials(
  200 + getCurrentUser().getTenantId(), deviceCredentials));
  201 + tbClusterService.pushMsgToCore(
  202 + new DeviceCredentialsUpdateNotificationMsg(
  203 + getCurrentUser().getTenantId(), deviceCredentials.getDeviceId(), result),
  204 + null);
  205 +
  206 + sendEntityNotificationMsg(
  207 + getTenantId(), tbDeviceId, EdgeEventActionType.CREDENTIALS_UPDATED);
  208 +
  209 + logEntityAction(
  210 + tbDeviceId,
  211 + savedDevice,
  212 + savedDevice.getCustomerId(),
  213 + ActionType.CREDENTIALS_UPDATED,
  214 + null,
  215 + deviceCredentials);
  216 + }
  217 + } catch (ThingsboardException e) {
  218 + log.error("Failed to log entity action", e);
156 219 }
157   - }
158   - }
159   - return ResponseEntity.ok(newDeviceDTO);
160   - }
161   -
162   - private DeviceId updateTbDevice(Device tbDevice, YtCredentialsDto formCredentials)
163   - throws ThingsboardException {
164   - Device oldDevice = null;
165   - boolean created = tbDevice.getId() == null;
166   - if (!created) {
167   - oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);
168   - } else {
169   - checkEntity(null, tbDevice, Resource.DEVICE);
  220 + return tbDeviceId;
170 221 }
171 222
172   - Device savedDevice = checkNotNull(tbDeviceService.saveDeviceWithAccessToken(tbDevice, null));
173   - tbClusterService.onDeviceUpdated(savedDevice, oldDevice);
174   - DeviceId tbDeviceId = savedDevice.getId();
175   - try {
176   - logEntityAction(
177   - getCurrentUser(),
178   - savedDevice.getId(),
179   - savedDevice,
180   - savedDevice.getCustomerId(),
181   - created ? ActionType.ADDED : ActionType.UPDATED,
182   - null);
183   -
184   - if (formCredentials != null && formCredentials.getCredentialsType() != null) {
185   - DeviceCredentials deviceCredentials =
186   - checkNotNull(
187   - deviceCredentialsService.findDeviceCredentialsByDeviceId(
188   - getCurrentUser().getTenantId(), tbDeviceId));
189   - deviceCredentials.setCredentialsId(formCredentials.getCredentialsId());
190   - deviceCredentials.setCredentialsType(formCredentials.getCredentialsType());
191   - deviceCredentials.setCredentialsValue(formCredentials.getCredentialsValue());
192   -
193   - DeviceCredentials result =
194   - checkNotNull(
195   - deviceCredentialsService.updateDeviceCredentials(
196   - getCurrentUser().getTenantId(), deviceCredentials));
197   - tbClusterService.pushMsgToCore(
198   - new DeviceCredentialsUpdateNotificationMsg(
199   - getCurrentUser().getTenantId(), deviceCredentials.getDeviceId(), result),
200   - null);
201   -
202   - sendEntityNotificationMsg(
203   - getTenantId(), tbDeviceId, EdgeEventActionType.CREDENTIALS_UPDATED);
204   -
205   - logEntityAction(
206   - tbDeviceId,
207   - savedDevice,
208   - savedDevice.getCustomerId(),
209   - ActionType.CREDENTIALS_UPDATED,
210   - null,
211   - deviceCredentials);
212   - }
213   - } catch (ThingsboardException e) {
214   - log.error("Failed to log entity action", e);
  223 + @GetMapping("{id}")
  224 + @ApiOperation("详情")
  225 + public ResponseEntity<DeviceDTO> getDevice(@PathVariable("id") String id)
  226 + throws ThingsboardException {
  227 + return ResponseEntity.of(deviceService.getDevice(getCurrentUser().getCurrentTenantId(), id));
215 228 }
216   - return tbDeviceId;
217   - }
218   -
219   - @GetMapping("{id}")
220   - @ApiOperation("详情")
221   - public ResponseEntity<DeviceDTO> getDevice(@PathVariable("id") String id)
222   - throws ThingsboardException {
223   - return ResponseEntity.of(deviceService.getDevice(getCurrentUser().getCurrentTenantId(), id));
224   - }
225   -
226   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
227   - @GetMapping(params = {PAGE_SIZE, PAGE})
228   - @ApiOperation("查询")
229   - public YtPageData<DeviceDTO> pageDevice(
230   - @RequestParam(PAGE_SIZE) int pageSize,
231   - @RequestParam(PAGE) int page,
232   - @RequestParam(value = "name", required = false) String name,
233   - @RequestParam(value = "deviceState", required = false) DeviceState deviceState,
234   - @RequestParam(value = "deviceType", required = false) DeviceTypeEnum deviceType,
235   - @RequestParam(value = "organizationId", required = false) String organizationId,
236   - @RequestParam(value = "alarmStatus", required = false) Integer alarmStatus,
237   - @RequestParam(value = "profileId", required = false) String profileId,
238   - @RequestParam(value = ORDER_FILED, required = false) String orderBy,
239   - @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType)
240   - throws ThingsboardException {
241   - HashMap<String, Object> queryMap = new HashMap<>();
242   - queryMap.put(PAGE_SIZE, pageSize);
243   - queryMap.put(PAGE, page);
244   - queryMap.put(ORDER_FILED, orderBy);
245   - queryMap.put("name", name);
246   - queryMap.put("alarmStatus", alarmStatus);
247   - queryMap.put("profileId", profileId);
248   - if (deviceState != null) {
249   - if(deviceState != DeviceState.INACTIVE){
250   - queryMap.put("deviceState", deviceState == DeviceState.ONLINE);
251   - }else{
252   - queryMap.put("activeState",DeviceState.INACTIVE);
253   - }
  229 +
  230 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  231 + @GetMapping(params = {PAGE_SIZE, PAGE})
  232 + @ApiOperation("查询")
  233 + public YtPageData<DeviceDTO> pageDevice(
  234 + @RequestParam(PAGE_SIZE) int pageSize,
  235 + @RequestParam(PAGE) int page,
  236 + @RequestParam(value = "name", required = false) String name,
  237 + @RequestParam(value = "deviceState", required = false) DeviceState deviceState,
  238 + @RequestParam(value = "deviceType", required = false) DeviceTypeEnum deviceType,
  239 + @RequestParam(value = "organizationId", required = false) String organizationId,
  240 + @RequestParam(value = "alarmStatus", required = false) Integer alarmStatus,
  241 + @RequestParam(value = "profileId", required = false) String profileId,
  242 + @RequestParam(value = ORDER_FILED, required = false) String orderBy,
  243 + @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType)
  244 + throws ThingsboardException {
  245 + HashMap<String, Object> queryMap = new HashMap<>();
  246 + queryMap.put(PAGE_SIZE, pageSize);
  247 + queryMap.put(PAGE, page);
  248 + queryMap.put(ORDER_FILED, orderBy);
  249 + queryMap.put("name", name);
  250 + queryMap.put("alarmStatus", alarmStatus);
  251 + queryMap.put("profileId", profileId);
  252 + if (deviceState != null) {
  253 + if (deviceState != DeviceState.INACTIVE) {
  254 + queryMap.put("deviceState", deviceState == DeviceState.ONLINE);
  255 + } else {
  256 + queryMap.put("activeState", DeviceState.INACTIVE);
  257 + }
  258 + }
  259 + if (deviceType != null) {
  260 + queryMap.put("deviceType", deviceType.name());
  261 + }
  262 + if (!StringUtils.isEmpty(organizationId)) {
  263 + queryMap.put("organizationId", organizationId);
  264 + }
  265 + if (orderType != null) {
  266 + queryMap.put(ORDER_TYPE, orderType.name());
  267 + }
  268 + // 如果当前用户是客户
  269 + if (getCurrentUser().isCustomerUser()) {
  270 + queryMap.put("customerId", getCurrentUser().getCustomerId().toString());
  271 + }
  272 + return deviceService.page(getCurrentUser().getCurrentTenantId(), queryMap);
254 273 }
255   - if (deviceType != null) {
256   - queryMap.put("deviceType", deviceType.name());
  274 +
  275 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  276 + @GetMapping(path = {"/relation"}, params = {PAGE_SIZE, PAGE})
  277 + @ApiOperation("子设备查询")
  278 + public YtPageData<RelationDeviceDTO> pageRelationDevice(
  279 + @RequestParam(PAGE_SIZE) int pageSize,
  280 + @RequestParam(PAGE) int page,
  281 + @RequestParam(value = "name", required = false) String name,
  282 + @RequestParam(value = "deviceState", required = false) DeviceState deviceState,
  283 + @RequestParam(value = "fromId") String fromId,
  284 + @RequestParam(value = ORDER_FILED, required = false) String orderBy,
  285 + @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType) throws ThingsboardException {
  286 + HashMap<String, Object> queryMap = new HashMap<>();
  287 + queryMap.put(PAGE_SIZE, pageSize);
  288 + queryMap.put(PAGE, page);
  289 + queryMap.put(ORDER_FILED, orderBy);
  290 + queryMap.put("name", name);
  291 + queryMap.put("fromId", fromId);
  292 + queryMap.put("tenantId", getCurrentUser().getCurrentTenantId());
  293 + if (deviceState != null) {
  294 + if (deviceState != DeviceState.INACTIVE) {
  295 + queryMap.put("deviceState", deviceState == DeviceState.ONLINE);
  296 + } else {
  297 + queryMap.put("activeState", DeviceState.INACTIVE);
  298 + }
  299 + }
  300 + if (orderType != null) {
  301 + queryMap.put(ORDER_TYPE, orderType.name());
  302 + }
  303 + // 如果当前用户是客户
  304 + if (getCurrentUser().isCustomerUser()) {
  305 + queryMap.put("customerId", getCurrentUser().getCustomerId().toString());
  306 + }
  307 + return deviceService.pageRelation(queryMap);
257 308 }
258   - if (!StringUtils.isEmpty(organizationId)) {
259   - queryMap.put("organizationId", organizationId);
  309 +
  310 + @PostMapping("/import")
  311 + @ApiOperation("导入配置")
  312 + public ResponseEntity<String> importDeviceProfile() {
  313 + // TODO 实现的业务功能
  314 + return ResponseEntity.ok("");
260 315 }
261   - if (orderType != null) {
262   - queryMap.put(ORDER_TYPE, orderType.name());
  316 +
  317 + @PostMapping("/export")
  318 + @ApiOperation("导出")
  319 + public ResponseEntity<String> exportDeviceProfile() {
  320 + // TODO 实现的业务功能
  321 + return ResponseEntity.ok("");
263 322 }
264   - // 如果当前用户是客户
265   - if (getCurrentUser().isCustomerUser()) {
266   - queryMap.put("customerId", getCurrentUser().getCustomerId().toString());
  323 +
  324 + @DeleteMapping
  325 + @ApiOperation("删除")
  326 + public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)
  327 + throws ThingsboardException {
  328 + String currentTenantId = getCurrentUser().getCurrentTenantId();
  329 + List<String> tdIds = deviceService.findTbDeviceId(currentTenantId, deleteDTO.getIds());
  330 + for (String id : tdIds) {
  331 + deleteTbDevice(id);
  332 + }
  333 + deviceService.deleteDevices(currentTenantId, deleteDTO.getIds());
267 334 }
268   - return deviceService.page(getCurrentUser().getCurrentTenantId(), queryMap);
269   - }
270   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
271   - @GetMapping(path = {"/relation"},params = {PAGE_SIZE, PAGE})
272   - @ApiOperation("子设备查询")
273   - public YtPageData<RelationDeviceDTO> pageRelationDevice(
274   - @RequestParam(PAGE_SIZE) int pageSize,
275   - @RequestParam(PAGE) int page,
276   - @RequestParam(value = "name", required = false) String name,
277   - @RequestParam(value = "deviceState", required = false) DeviceState deviceState,
278   - @RequestParam(value = "fromId") String fromId,
279   - @RequestParam(value = ORDER_FILED, required = false) String orderBy,
280   - @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType) throws ThingsboardException {
281   - HashMap<String, Object> queryMap = new HashMap<>();
282   - queryMap.put(PAGE_SIZE, pageSize);
283   - queryMap.put(PAGE, page);
284   - queryMap.put(ORDER_FILED, orderBy);
285   - queryMap.put("name", name);
286   - queryMap.put("fromId", fromId);
287   - queryMap.put("tenantId", getCurrentUser().getCurrentTenantId());
288   - if (deviceState != null) {
289   - if(deviceState != DeviceState.INACTIVE){
290   - queryMap.put("deviceState", deviceState == DeviceState.ONLINE);
291   - }else{
292   - queryMap.put("activeState",DeviceState.INACTIVE);
293   - }
  335 +
  336 + private void deleteTbDevice(String id) throws ThingsboardException {
  337 + DeviceId deviceId = new DeviceId(toUUID(id));
  338 + Device device = checkDeviceId(deviceId, Operation.DELETE);
  339 +
  340 + List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(getTenantId(), deviceId);
  341 +
  342 + tbDeviceService.deleteDevice(getCurrentUser().getTenantId(), deviceId);
  343 +
  344 + tbClusterService.onDeviceDeleted(device, null);
  345 +
  346 + logEntityAction(deviceId, device, device.getCustomerId(), ActionType.DELETED, null, id);
  347 +
  348 + sendDeleteNotificationMsg(getTenantId(), deviceId, relatedEdgeIds);
294 349 }
295   - if (orderType != null) {
296   - queryMap.put(ORDER_TYPE, orderType.name());
  350 +
  351 + @GetMapping("/list/{deviceType}")
  352 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
  353 + @ApiOperation("获取该组织的所有设备")
  354 + public List<DeviceDTO> getGatewayDevices(
  355 + @ApiParam(value = "组织ID") @RequestParam("organizationId") String organizationId,
  356 + @ApiParam(value = "设备类型") @PathVariable("deviceType") DeviceTypeEnum deviceType) {
  357 + return deviceService.findDevicesByDeviceTypeAndOrganizationId(deviceType, organizationId);
297 358 }
298   - // 如果当前用户是客户
299   - if (getCurrentUser().isCustomerUser()) {
300   - queryMap.put("customerId", getCurrentUser().getCustomerId().toString());
  359 +
  360 + @GetMapping("/gateway/{tbDeviceId}")
  361 + @ApiOperation("获取网关设备")
  362 + public DeviceDTO findGateWayDeviceByTbDeviceId(
  363 + @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)
  364 + throws ThingsboardException {
  365 + List<DeviceDTO> list =
  366 + deviceService.findGateWayDeviceByTbDeviceId(
  367 + getCurrentUser().getCurrentTenantId(), tbDeviceId);
  368 + return null != list && list.size() > FastIotConstants.MagicNumber.ZERO
  369 + ? list.get(FastIotConstants.MagicNumber.ZERO)
  370 + : null;
301 371 }
302   - return deviceService.pageRelation(queryMap);
303   - }
304   -
305   - @PostMapping("/import")
306   - @ApiOperation("导入配置")
307   - public ResponseEntity<String> importDeviceProfile() {
308   - // TODO 实现的业务功能
309   - return ResponseEntity.ok("");
310   - }
311   -
312   - @PostMapping("/export")
313   - @ApiOperation("导出")
314   - public ResponseEntity<String> exportDeviceProfile() {
315   - // TODO 实现的业务功能
316   - return ResponseEntity.ok("");
317   - }
318   -
319   - @DeleteMapping
320   - @ApiOperation("删除")
321   - public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)
322   - throws ThingsboardException {
323   - String currentTenantId = getCurrentUser().getCurrentTenantId();
324   - List<String> tdIds = deviceService.findTbDeviceId(currentTenantId, deleteDTO.getIds());
325   - for (String id : tdIds) {
326   - deleteTbDevice(id);
  372 +
  373 + private final ObjectMapper objectMapper;
  374 +
  375 + private Device buildTbDeviceFromDeviceDTO(TenantId tenantId, DeviceDTO deviceDTO) {
  376 + Device tbDevice = new Device();
  377 + String deviceId = deviceDTO.getTbDeviceId();
  378 + if (StringUtils.isNotBlank(deviceId)) {
  379 + DeviceId id = new DeviceId(UUID.fromString(deviceId));
  380 + tbDevice.setId(id);
  381 + }
  382 + ObjectNode additionalInfo = objectMapper.createObjectNode();
  383 + additionalInfo.put(
  384 + "gateway",
  385 + Optional.ofNullable(deviceDTO.getDeviceType())
  386 + .map(deviceType -> deviceType.equals(DeviceTypeEnum.GATEWAY))
  387 + .orElse(false));
  388 + additionalInfo.put(
  389 + "description",
  390 + Optional.ofNullable(deviceDTO.getDeviceInfo())
  391 + .map(deviceInfo -> deviceInfo.get("description"))
  392 + .map(JsonNode::asText)
  393 + .orElse(""));
  394 + additionalInfo.put("overwriteActivityTime", false);
  395 +
  396 + DeviceProfileId deviceProfileId =
  397 + new DeviceProfileId(UUID.fromString(deviceDTO.getProfileId()));
  398 +
  399 + tbDevice.setAdditionalInfo(additionalInfo);
  400 + tbDevice.setCustomerId(null);
  401 + tbDevice.setDeviceProfileId(deviceProfileId);
  402 + tbDevice.setLabel(deviceDTO.getLabel());
  403 + tbDevice.setName(deviceDTO.getName());
  404 + tbDevice.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
  405 + tbDevice.setTenantId(tenantId);
  406 + return tbDevice;
327 407 }
328   - deviceService.deleteDevices(currentTenantId, deleteDTO.getIds());
329   - }
330   -
331   - private void deleteTbDevice(String id) throws ThingsboardException {
332   - DeviceId deviceId = new DeviceId(toUUID(id));
333   - Device device = checkDeviceId(deviceId, Operation.DELETE);
334   -
335   - List<EdgeId> relatedEdgeIds = findRelatedEdgeIds(getTenantId(), deviceId);
336   -
337   - tbDeviceService.deleteDevice(getCurrentUser().getTenantId(), deviceId);
338   -
339   - tbClusterService.onDeviceDeleted(device, null);
340   -
341   - logEntityAction(deviceId, device, device.getCustomerId(), ActionType.DELETED, null, id);
342   -
343   - sendDeleteNotificationMsg(getTenantId(), deviceId, relatedEdgeIds);
344   - }
345   -
346   - @GetMapping("/list/{deviceType}")
347   - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
348   - @ApiOperation("获取该组织的所有设备")
349   - public List<DeviceDTO> getGatewayDevices(
350   - @ApiParam(value = "组织ID") @RequestParam("organizationId") String organizationId,
351   - @ApiParam(value = "设备类型") @PathVariable("deviceType") DeviceTypeEnum deviceType) {
352   - return deviceService.findDevicesByDeviceTypeAndOrganizationId(deviceType, organizationId);
353   - }
354   -
355   - @GetMapping("/gateway/{tbDeviceId}")
356   - @ApiOperation("获取网关设备")
357   - public DeviceDTO findGateWayDeviceByTbDeviceId(
358   - @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)
359   - throws ThingsboardException {
360   - List<DeviceDTO> list =
361   - deviceService.findGateWayDeviceByTbDeviceId(
362   - getCurrentUser().getCurrentTenantId(), tbDeviceId);
363   - return null != list && list.size() > FastIotConstants.MagicNumber.ZERO
364   - ? list.get(FastIotConstants.MagicNumber.ZERO)
365   - : null;
366   - }
367   -
368   - private final ObjectMapper objectMapper;
369   -
370   - private Device buildTbDeviceFromDeviceDTO(TenantId tenantId, DeviceDTO deviceDTO) {
371   - Device tbDevice = new Device();
372   - String deviceId = deviceDTO.getTbDeviceId();
373   - if (StringUtils.isNotBlank(deviceId)) {
374   - DeviceId id = new DeviceId(UUID.fromString(deviceId));
375   - tbDevice.setId(id);
  408 +
  409 + /**
  410 + * 添加关联关系
  411 + *
  412 + * @param tenantId 租户ID
  413 + * @param gateWayTbDeviceId 网关设备Tb的设备ID
  414 + * @param deviceId 设备的tbDeviceId
  415 + */
  416 + private void addRelation(TenantId tenantId, String gateWayTbDeviceId, String deviceId)
  417 + throws ThingsboardException {
  418 + EntityRelation relation = new EntityRelation();
  419 + relation.setFrom(new DeviceId(UUID.fromString(gateWayTbDeviceId)));
  420 + relation.setTypeGroup(RelationTypeGroup.COMMON);
  421 + relation.setTo(new DeviceId(UUID.fromString(deviceId)));
  422 + relation.setType(FastIotConstants.Relation.relationType);
  423 + relationService.saveRelation(tenantId, relation);
  424 + sendRelationNotificationMsg(
  425 + getTenantId(), relation, EdgeEventActionType.RELATION_ADD_OR_UPDATE);
376 426 }
377   - ObjectNode additionalInfo = objectMapper.createObjectNode();
378   - additionalInfo.put(
379   - "gateway",
380   - Optional.ofNullable(deviceDTO.getDeviceType())
381   - .map(deviceType -> deviceType.equals(DeviceTypeEnum.GATEWAY))
382   - .orElse(false));
383   - additionalInfo.put(
384   - "description",
385   - Optional.ofNullable(deviceDTO.getDeviceInfo())
386   - .map(deviceInfo -> deviceInfo.get("description"))
387   - .map(JsonNode::asText)
388   - .orElse(""));
389   - additionalInfo.put("overwriteActivityTime", false);
390   -
391   - DeviceProfileId deviceProfileId =
392   - new DeviceProfileId(UUID.fromString(deviceDTO.getProfileId()));
393   -
394   - tbDevice.setAdditionalInfo(additionalInfo);
395   - tbDevice.setCustomerId(null);
396   - tbDevice.setDeviceProfileId(deviceProfileId);
397   - tbDevice.setLabel(deviceDTO.getLabel());
398   - tbDevice.setName(deviceDTO.getName());
399   - tbDevice.setCreatedTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli());
400   - tbDevice.setTenantId(tenantId);
401   - return tbDevice;
402   - }
403   -
404   - /**
405   - * 添加关联关系
406   - *
407   - * @param tenantId 租户ID
408   - * @param gateWayTbDeviceId 网关设备Tb的设备ID
409   - * @param deviceId 设备的tbDeviceId
410   - */
411   - private void addRelation(TenantId tenantId, String gateWayTbDeviceId, String deviceId)
412   - throws ThingsboardException {
413   - EntityRelation relation = new EntityRelation();
414   - relation.setFrom(new DeviceId(UUID.fromString(gateWayTbDeviceId)));
415   - relation.setTypeGroup(RelationTypeGroup.COMMON);
416   - relation.setTo(new DeviceId(UUID.fromString(deviceId)));
417   - relation.setType(FastIotConstants.Relation.relationType);
418   - relationService.saveRelation(tenantId, relation);
419   - sendRelationNotificationMsg(
420   - getTenantId(), relation, EdgeEventActionType.RELATION_ADD_OR_UPDATE);
421   - }
422 427 }
... ...
... ... @@ -20,7 +20,6 @@ import org.thingsboard.server.common.data.yunteng.dto.OrganizationDTO;
20 20 import org.thingsboard.server.common.data.yunteng.dto.RelationDeviceDTO;
21 21 import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
22 22 import org.thingsboard.server.common.data.yunteng.enums.ScopeEnum;
23   -import org.thingsboard.server.common.data.yunteng.enums.TriggerTypeEnum;
24 23 import org.thingsboard.server.common.data.yunteng.utils.ReflectUtils;
25 24 import org.thingsboard.server.common.data.yunteng.utils.tools.YtPageData;
26 25 import org.thingsboard.server.dao.device.DeviceProfileDao;
... ... @@ -337,4 +336,23 @@ public class YtDeviceServiceImpl extends AbstractBaseService<DeviceMapper, YtDev
337 336 public boolean freshAlarmStatus(EntityId tbDeviceId, Integer created) {
338 337 return baseMapper.freshAlarmStatus(tbDeviceId.getId().toString(), created);
339 338 }
  339 +
  340 +
  341 + @Override
  342 + public String generateSn() {
  343 + StringBuilder snBuilder = new StringBuilder();
  344 + for (int i = 0; i < 2; i++) {
  345 + //生成uuid的hashCode值
  346 + int hashCode = UUID.randomUUID().toString().hashCode();
  347 + //可能为负数
  348 + if (hashCode < 0) {
  349 + hashCode = -hashCode;
  350 + }
  351 + snBuilder.append(hashCode);
  352 +
  353 + }
  354 +
  355 + return snBuilder.substring(0, 16);
  356 + }
  357 +
340 358 }
... ...
... ... @@ -12,78 +12,86 @@ import java.util.Map;
12 12 import java.util.Optional;
13 13 import java.util.Set;
14 14
15   -public interface YtDeviceService extends BaseService<YtDevice>{
16   - DeviceDTO insertOrUpdate(String tenantId, DeviceDTO deviceDTO);
17   -
18   - void deleteDevices(String tenantId, Set<String> ids);
19   -
20   - Optional<DeviceDTO> getDevice(String tenantId, String id);
21   -
22   - YtPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap);
23   -
24   - YtPageData<RelationDeviceDTO> pageRelation(Map<String, Object> queryMap);
25   -
26   - /**
27   - * 验证表单数据有效性
28   - *
29   - * @param ytDevice
30   - */
31   - boolean validateFormdata(String currentTenantId, DeviceDTO ytDevice);
32   -
33   - /**
34   - * 查询所有的设备信息
35   - *
36   - * @param deviceDTO 过滤参数
37   - * @return List<DeviceDTO>
38   - */
39   - List<DeviceDTO> findTbDeviceId(String tenantId, DeviceDTO deviceDTO);
40   -
41   - List<String> findTbDeviceId(String tenantId, Set<String> ids);
42   -
43   - /**
44   - * 通过设备类型和组织ID查询所有的设备
45   - *
46   - * @param deviceType 设备类型
47   - * @param organizationId 组织ID
48   - * @return 设备列表
49   - */
50   - List<DeviceDTO> findDevicesByDeviceTypeAndOrganizationId(
51   - DeviceTypeEnum deviceType, String organizationId);
52   -
53   - /**
54   - * 通过设备ID和租户ID判断该设备是否存在
55   - *
56   - * @param tenantId 租户ID
57   - * @param deviceId 设备ID
58   - * @return 设备
59   - */
60   - DeviceDTO checkDeviceByTenantIdAndDeviceId(String tenantId, String deviceId);
61   -
62   - /**
63   - * 通过网关子设备的TB设备ID查询网关设备信息
64   - *
65   - * @param tbDeviceId 网关子设备的TB设备ID
66   - * @param tenantId 租户ID
67   - * @return 网关设备信息
68   - */
69   - List<DeviceDTO> findGateWayDeviceByTbDeviceId(String tenantId, String tbDeviceId);
70   -
71   - /**
72   - * 通过设备ID和租户ID检查设备是否存在
73   - *
74   - * @param tenantId 租户ID
75   - * @param deviceId 设备ID
76   - * @param isTbDeviceId 是TB设备ID
77   - * @return 设备信息
78   - */
79   - DeviceDTO checkDeviceByTenantIdAndId(String tenantId, String deviceId, boolean isTbDeviceId);
80   -
81   - /**
82   - * 更新设备告警状态
83   - *
84   - * @param tbDeviceId TB设备主键
85   - * @param created 告警状态:0正常,1告警
86   - * @return
87   - */
88   - boolean freshAlarmStatus(EntityId tbDeviceId, Integer created);
  15 +public interface YtDeviceService extends BaseService<YtDevice> {
  16 + DeviceDTO insertOrUpdate(String tenantId, DeviceDTO deviceDTO);
  17 +
  18 + void deleteDevices(String tenantId, Set<String> ids);
  19 +
  20 + Optional<DeviceDTO> getDevice(String tenantId, String id);
  21 +
  22 + YtPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap);
  23 +
  24 + YtPageData<RelationDeviceDTO> pageRelation(Map<String, Object> queryMap);
  25 +
  26 + /**
  27 + * 验证表单数据有效性
  28 + *
  29 + * @param ytDevice
  30 + */
  31 + boolean validateFormdata(String currentTenantId, DeviceDTO ytDevice);
  32 +
  33 + /**
  34 + * 查询所有的设备信息
  35 + *
  36 + * @param deviceDTO 过滤参数
  37 + * @return List<DeviceDTO>
  38 + */
  39 + List<DeviceDTO> findTbDeviceId(String tenantId, DeviceDTO deviceDTO);
  40 +
  41 + List<String> findTbDeviceId(String tenantId, Set<String> ids);
  42 +
  43 + /**
  44 + * 通过设备类型和组织ID查询所有的设备
  45 + *
  46 + * @param deviceType 设备类型
  47 + * @param organizationId 组织ID
  48 + * @return 设备列表
  49 + */
  50 + List<DeviceDTO> findDevicesByDeviceTypeAndOrganizationId(
  51 + DeviceTypeEnum deviceType, String organizationId);
  52 +
  53 + /**
  54 + * 通过设备ID和租户ID判断该设备是否存在
  55 + *
  56 + * @param tenantId 租户ID
  57 + * @param deviceId 设备ID
  58 + * @return 设备
  59 + */
  60 + DeviceDTO checkDeviceByTenantIdAndDeviceId(String tenantId, String deviceId);
  61 +
  62 + /**
  63 + * 通过网关子设备的TB设备ID查询网关设备信息
  64 + *
  65 + * @param tbDeviceId 网关子设备的TB设备ID
  66 + * @param tenantId 租户ID
  67 + * @return 网关设备信息
  68 + */
  69 + List<DeviceDTO> findGateWayDeviceByTbDeviceId(String tenantId, String tbDeviceId);
  70 +
  71 + /**
  72 + * 通过设备ID和租户ID检查设备是否存在
  73 + *
  74 + * @param tenantId 租户ID
  75 + * @param deviceId 设备ID
  76 + * @param isTbDeviceId 是TB设备ID
  77 + * @return 设备信息
  78 + */
  79 + DeviceDTO checkDeviceByTenantIdAndId(String tenantId, String deviceId, boolean isTbDeviceId);
  80 +
  81 + /**
  82 + * 更新设备告警状态
  83 + *
  84 + * @param tbDeviceId TB设备主键
  85 + * @param created 告警状态:0正常,1告警
  86 + * @return
  87 + */
  88 + boolean freshAlarmStatus(EntityId tbDeviceId, Integer created);
  89 +
  90 +
  91 + /**
  92 + * 自动生成设备SN
  93 + *
  94 + * @return
  95 + */
  96 + String generateSn();
89 97 }
... ...