Commit 1400e985f59159b81dac71ae4baee69e396a7b42

Authored by 杨鸣坤
1 parent 119aca6c

设备同步

@@ -91,7 +91,18 @@ public class ThingsboardSecurityConfiguration { @@ -91,7 +91,18 @@ public class ThingsboardSecurityConfiguration {
91 91
92 @Value("${file.storage.local.staticUrl}") 92 @Value("${file.storage.local.staticUrl}")
93 private String ossStaticUrl; 93 private String ossStaticUrl;
94 - public static final String[] YT_NOT_AUTH_API = new String[]{"/api/yt/auth/code/login","/api/yt/third/bind","/api/yt/third/login/*","/api/yt/third/login/id/*", "/api/yt/third/authorize","/api/yt/platform/get","/api/yt/app_design/get", "/api/yt/noauth/**","/api/index/hook/**"}; 94 + public static final String[] YT_NOT_AUTH_API = new String[]{
  95 + "/api/yt/auth/code/login",
  96 + "/api/yt/third/bind",
  97 + "/api/yt/third/login/*",
  98 + "/api/yt/third/login/id/*",
  99 + "/api/yt/third/authorize",
  100 + "/api/yt/platform/get",
  101 + "/api/yt/app_design/get",
  102 + "/api/yt/noauth/**",
  103 + "/api/index/hook/**",
  104 + "/api/yt/deviceSync/**"
  105 + };
95 106
96 public static final String PUBLIC_LOGIN_ENTRY_POINT = "/api/auth/login/public"; 107 public static final String PUBLIC_LOGIN_ENTRY_POINT = "/api/auth/login/public";
97 public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token"; 108 public static final String TOKEN_REFRESH_ENTRY_POINT = "/api/auth/token";
@@ -57,540 +57,545 @@ import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant. @@ -57,540 +57,545 @@ import static org.thingsboard.server.common.data.yunteng.constant.QueryConstant.
57 @Api(tags = {"设备管理"}) 57 @Api(tags = {"设备管理"})
58 @Slf4j 58 @Slf4j
59 public class TkDeviceController extends BaseController { 59 public class TkDeviceController extends BaseController {
60 - private final TkDeviceService tkdeviceService;  
61 - private final TkDeviceProfileService ytDeviceProfileService;  
62 - private final TkAlarmInfoService tkAlarmInfoService ;  
63 - private final TbAlarmService tbAlarmService;  
64 - private final TbDeviceService tbDeviceService;  
65 - private final TbEntityRelationService tbEntityRelationService;  
66 - private final TkOrganizationService organizationService;  
67 - private final CacheUtils cacheUtils;  
68 - private final TkVideoChannelService tkVideoChannelService;  
69 - private final TkVideoService tkVideoService;  
70 - @PostMapping("/batch/update")  
71 - @ApiOperation("批量修改设备")  
72 - @PreAuthorize(  
73 - "@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:post','api:yt:device:update'})")  
74 - public ResponseEntity<String> batchUpdateDevice(  
75 - @Validated(AddGroup.class) @RequestBody List<DeviceDTO> deviceDTO,String orgId) {  
76 - deviceDTO.forEach(i ->{  
77 - i.setOrganizationId(orgId); 60 + private final TkDeviceService tkdeviceService;
  61 + private final TkDeviceProfileService ytDeviceProfileService;
  62 + private final TkAlarmInfoService tkAlarmInfoService;
  63 + private final TbAlarmService tbAlarmService;
  64 + private final TbDeviceService tbDeviceService;
  65 + private final TbEntityRelationService tbEntityRelationService;
  66 + private final TkOrganizationService organizationService;
  67 + private final CacheUtils cacheUtils;
  68 + private final TkVideoChannelService tkVideoChannelService;
  69 + private final TkVideoService tkVideoService;
  70 +
  71 + @PostMapping("/batch/update")
  72 + @ApiOperation("批量修改设备")
  73 + @PreAuthorize(
  74 + "@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:post','api:yt:device:update'})")
  75 + public ResponseEntity<String> batchUpdateDevice(
  76 + @Validated(AddGroup.class) @RequestBody List<DeviceDTO> deviceDTO, String orgId) {
  77 + deviceDTO.forEach(i -> {
  78 + i.setOrganizationId(orgId);
  79 + try {
  80 + saveDevice(i);
  81 + } catch (Exception e) {
  82 + e.printStackTrace();
  83 + }
  84 + });
  85 + return ResponseEntity.ok(MessageUtils.message("update.success"));
  86 + }
  87 +
  88 + @PostMapping
  89 + @ApiOperation("创建|编辑")
  90 + @PreAuthorize(
  91 + "@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:post','api:yt:device:update'})")
  92 + public ResponseEntity<DeviceDTO> saveDevice(
  93 + @Validated(AddGroup.class) @RequestBody DeviceDTO deviceDTO)
  94 + throws ThingsboardException, ExecutionException, InterruptedException {
  95 + return saveDeviceInterface(deviceDTO);
  96 + }
  97 +
  98 + public ResponseEntity<DeviceDTO> saveDeviceInterface(DeviceDTO deviceDTO) throws ThingsboardException, ExecutionException, InterruptedException {
  99 + tkdeviceService.validateFormData(getCurrentUser().getTenantId(), deviceDTO);
  100 +
  101 + /** 网关是否有效 */
  102 + String gatewayId = deviceDTO.getGatewayId();
  103 + Device gateWay = null;
  104 + if (StringUtils.isNotEmpty(gatewayId)) {
  105 + gateWay = checkDeviceId(DeviceId.fromString(gatewayId), Operation.READ);
  106 + if (null == gateWay) {
  107 + throw new TkDataValidationException(
  108 + MessageUtils.message(ErrorMessage.DEVICE_NOT_EXISTENCE_IN_TENANT.getI18nCode()));
  109 + }
  110 + }
  111 +
  112 + boolean created = null == deviceDTO.getId();
  113 + Device savedDevice = null;
78 try { 114 try {
79 - saveDevice(i); 115 + /**
  116 + * 子设备编辑业务逻辑: 设备地址码必须同时设置到附加信息字段内。 1、新增或编辑网关和直连设备 2、新增网关子设备 3、编辑网关子设备时,关联关系已存在(未切换网关)
  117 + * 4、编辑网关子设备时,关联关系不存在(切换网关) 5、编辑网关子设备时,修改其它设备信息,例如:设备名称等。
  118 + */
  119 + Device tbDevice = tkdeviceService.buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(), deviceDTO);
  120 + savedDevice = updateTbDevice(tbDevice, deviceDTO.getDeviceToken(), created);
  121 +
  122 +
  123 + if (deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)
  124 + && gatewayId != null) {
  125 + boolean relationNotMatched = true;
  126 +
  127 + DeviceId slaveId = savedDevice.getId();
  128 + List<EntityRelationInfo> relations =
  129 + relationService.findInfoByTo(getTenantId(), slaveId, RelationTypeGroup.COMMON).get();
  130 +
  131 + for (EntityRelationInfo relationInfo : relations) {
  132 + if (!FastIotConstants.Relation.relationType.equals(relationInfo.getType())) {
  133 + continue;
  134 + }
  135 + if (relationInfo.getFrom().equals(gateWay.getId())) {
  136 + relationNotMatched = false;
  137 + } else {
  138 + relationService.deleteRelation(getTenantId(), relationInfo);
  139 + }
  140 + }
  141 +
  142 + if (relationNotMatched) {
  143 + addRelation(getTenantId(), gateWay.getId(), slaveId);
  144 + }
  145 + }
80 } catch (Exception e) { 146 } catch (Exception e) {
81 - e.printStackTrace(); 147 + throw new TkDataValidationException(e.getMessage());
  148 +
82 } 149 }
83 - });  
84 - return ResponseEntity.ok(MessageUtils.message("update.success"));  
85 - }  
86 -  
87 - @PostMapping  
88 - @ApiOperation("创建|编辑")  
89 - @PreAuthorize(  
90 - "@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:post','api:yt:device:update'})")  
91 - public ResponseEntity<DeviceDTO> saveDevice(  
92 - @Validated(AddGroup.class) @RequestBody DeviceDTO deviceDTO)  
93 - throws ThingsboardException, ExecutionException, InterruptedException {  
94 - tkdeviceService.validateFormData(getCurrentUser().getTenantId(), deviceDTO);  
95 -  
96 - /** 网关是否有效 */  
97 - String gatewayId = deviceDTO.getGatewayId();  
98 - Device gateWay = null;  
99 - if (StringUtils.isNotEmpty(gatewayId)) {  
100 - gateWay = checkDeviceId(DeviceId.fromString(gatewayId), Operation.READ);  
101 - if (null == gateWay) {  
102 - throw new TkDataValidationException(  
103 - MessageUtils.message(ErrorMessage.DEVICE_NOT_EXISTENCE_IN_TENANT.getI18nCode()));  
104 - } 150 + CopyUtils.copyProperties(savedDevice, deviceDTO);
  151 + return ResponseEntity.ok(deviceDTO);
105 } 152 }
106 153
107 - boolean created = null ==deviceDTO.getId();  
108 - Device savedDevice = null;  
109 - try {  
110 - /**  
111 - * 子设备编辑业务逻辑: 设备地址码必须同时设置到附加信息字段内。 1、新增或编辑网关和直连设备 2、新增网关子设备 3、编辑网关子设备时,关联关系已存在(未切换网关)  
112 - * 4、编辑网关子设备时,关联关系不存在(切换网关) 5、编辑网关子设备时,修改其它设备信息,例如:设备名称等。  
113 - */  
114 - Device tbDevice = tkdeviceService.buildTbDeviceFromDeviceDTO(getCurrentUser().getTenantId(), deviceDTO);  
115 - savedDevice = updateTbDevice(tbDevice, deviceDTO.getDeviceToken(), created);  
116 -  
117 -  
118 - if (deviceDTO.getDeviceType().equals(DeviceTypeEnum.SENSOR)  
119 - && gatewayId != null) {  
120 - boolean relationNotMatched = true;  
121 -  
122 - DeviceId slaveId = savedDevice.getId();  
123 - List<EntityRelationInfo> relations =  
124 - relationService.findInfoByTo(getTenantId(), slaveId, RelationTypeGroup.COMMON).get();  
125 -  
126 - for (EntityRelationInfo relationInfo : relations) {  
127 - if (!FastIotConstants.Relation.relationType.equals(relationInfo.getType())) {  
128 - continue;  
129 - }  
130 - if (relationInfo.getFrom().equals(gateWay.getId())) {  
131 - relationNotMatched = false;  
132 - } else {  
133 - relationService.deleteRelation(getTenantId(), relationInfo);  
134 - } 154 + @GetMapping({"sn"})
  155 + @ApiOperation("自动生成设备SN")
  156 + public ResponseEntity<String> generate() {
  157 + String result = tkdeviceService.generateSn();
  158 + return ResponseEntity.ok(result);
  159 + }
  160 +
  161 +
  162 + public Device updateTbDevice(
  163 + Device tbDevice, TkCredentialsDto formCredentials, boolean created)
  164 + throws Exception {
  165 + Device oldDevice = null;
  166 + if (!created) {
  167 + oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);
  168 + Optional.ofNullable(oldDevice).ifPresent(db -> {
  169 + if (!db.getDeviceProfileId().equals(tbDevice.getDeviceProfileId())) {
  170 + //更改了产品,需将原产品的缓存置为无效
  171 + cacheUtils.invalidate(FastIotConstants.CacheConfigKey.SCENE_REACT, tbDevice.getTenantId().toString() + "," + db.getDeviceProfileId().toString());
  172 + }
  173 + if (null != db.getDeviceInfo()) {
  174 + Optional.ofNullable(db.getDeviceInfo().get(FastIotConstants.DeviceAdditional.SIP)).ifPresent(sip -> {
  175 + ObjectNode additional = (ObjectNode) tbDevice.getDeviceInfo();
  176 + additional.set(FastIotConstants.DeviceAdditional.SIP, sip);
  177 + });
  178 + }
  179 + });
  180 + } else {
  181 + tbDevice.setAlarmStatus(0);
  182 + checkEntity(null, tbDevice, Resource.DEVICE);
  183 + }
  184 +
  185 + Device savedDevice = tbDeviceService.save(tbDevice, oldDevice, null, getCurrentUser());
  186 + DeviceId tbDeviceId = savedDevice.getId();
  187 + DeviceCredentials deviceCredentials;
  188 + if (formCredentials != null && formCredentials.getCredentialsType() != null) {
  189 + 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 + checkNotNull(deviceCredentials);
  198 + Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS);
  199 + tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser());
  200 + }
  201 + //如果是网关设备,且网关修改了其组织
  202 + if (oldDevice != null && savedDevice.getDeviceType().equals(DeviceTypeEnum.GATEWAY) && !oldDevice.getOrganizationId().equals(savedDevice.getOrganizationId())) {
  203 + updateSensorDeviceOrganization(savedDevice.getTenantId(), savedDevice.getId(), savedDevice.getOrganizationId());
135 } 204 }
  205 + return savedDevice;
  206 + }
136 207
137 - if (relationNotMatched) {  
138 - addRelation(getTenantId(), gateWay.getId(), slaveId); 208 + private void updateSensorDeviceOrganization(TenantId tenantId, DeviceId gatewayId, String newOrganizationId) throws ThingsboardException {
  209 + //查询新组织下的所有组织
  210 + List<String> allOrganization = organizationService.organizationAllIds(tenantId.toString(), newOrganizationId);
  211 + SecurityUser loginUser = getCurrentUser();
  212 + //网关子设备没在该网关新组织下,则同步更新为网关的新组织
  213 + if (null != allOrganization && !allOrganization.isEmpty()) {
  214 + List<Device> list = tkdeviceService.findDevicesByGatewaySwitchOrgId(tenantId, newOrganizationId, gatewayId);
  215 + if (!list.isEmpty()) {
  216 + list.forEach(obj -> {
  217 + Device newObj = new Device(obj);
  218 + newObj.setOrganizationId(newOrganizationId);
  219 + try {
  220 + tbDeviceService.save(newObj, obj, null, loginUser);
  221 + } catch (Exception e) {
  222 + throw new RuntimeException(e);
  223 + }
  224 + });
  225 + }
139 } 226 }
140 - }  
141 - } catch (Exception e) {  
142 - throw new TkDataValidationException(e.getMessage()); 227 + }
143 228
  229 + @GetMapping("{id}")
  230 + @ApiOperation("详情")
  231 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN','CUSTOMER_USER'},{'api:yt:device:get'})")
  232 + public ResponseEntity<DeviceDTO> getDevice(@PathVariable("id") String id)
  233 + throws ThingsboardException {
  234 + return ResponseEntity.of(tkdeviceService.getDevice(getCurrentUser().getTenantId().getId(), UUID.fromString(id)));
144 } 235 }
145 - CopyUtils.copyProperties(savedDevice,deviceDTO);  
146 - return ResponseEntity.ok(deviceDTO);  
147 - }  
148 -  
149 - @GetMapping({"sn"})  
150 - @ApiOperation("自动生成设备SN")  
151 - public ResponseEntity<String> generate() {  
152 - String result = tkdeviceService.generateSn();  
153 - return ResponseEntity.ok(result);  
154 - }  
155 -  
156 -  
157 - public Device updateTbDevice(  
158 - Device tbDevice, TkCredentialsDto formCredentials, boolean created)  
159 - throws Exception {  
160 - Device oldDevice = null;  
161 - if (!created) {  
162 - oldDevice = checkDeviceId(tbDevice.getId(), Operation.WRITE);  
163 - Optional.ofNullable(oldDevice).ifPresent(db->{  
164 - if(!db.getDeviceProfileId().equals(tbDevice.getDeviceProfileId())){  
165 - //更改了产品,需将原产品的缓存置为无效  
166 - cacheUtils.invalidate(FastIotConstants.CacheConfigKey.SCENE_REACT,tbDevice.getTenantId().toString()+","+db.getDeviceProfileId().toString()); 236 +
  237 + @GetMapping("/public/{id}")
  238 + @ApiOperation("Public客户调用公开设备详情")
  239 + @PreAuthorize("hasAnyAuthority('CUSTOMER_USER')")
  240 + public ResponseEntity<DeviceDTO> getPublicDevice(@PathVariable("id") String id)
  241 + throws ThingsboardException {
  242 + return ResponseEntity.of(tkdeviceService.getDevice(getCurrentUser().getTenantId().getId(), UUID.fromString(id)));
  243 + }
  244 +
  245 +
  246 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER','OPENAPI_USER')")
  247 + @PostMapping(path = {"/page"})
  248 + @ApiOperation("查询")
  249 + public TkPageData<DeviceDTO> getPage(
  250 + @RequestBody Map<String, Object> queryMap)
  251 + throws ThingsboardException {
  252 + return pageDevice((Integer) queryMap.get("pageSize"), (Integer) queryMap.get("page"), queryMap);
  253 + }
  254 +
  255 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER','OPENAPI_USER')")
  256 + @PostMapping(params = {PAGE_SIZE, PAGE})
  257 + @ApiOperation("查询")
  258 + public TkPageData<DeviceDTO> pageDevice(
  259 + @RequestParam(PAGE_SIZE) int pageSize,
  260 + @RequestParam(PAGE) int page,
  261 + @RequestBody Map<String, Object> queryMap)
  262 + throws ThingsboardException {
  263 + queryMap.put(PAGE, page);
  264 + queryMap.put(PAGE_SIZE, pageSize);
  265 + // 如果当前用户是客户
  266 + if (getCurrentUser().isCustomerUser()) {
  267 + queryMap.put("customerId", getCurrentUser().getCustomerId().getId());
  268 + }
  269 + //如果当前用户是普通租户或者openapi用戶
  270 + if (getCurrentUser().isPtCommonTenant() || getCurrentUser().isOpenApiUser()) {
  271 + List<String> organizationIds = commonTenantOrganizationAllIds();
  272 + if (null != organizationIds && organizationIds.size() > 0) {
  273 + queryMap.put("organizationIds", organizationIds);
  274 + }
  275 + }
  276 + DeviceState deviceState =
  277 + null != queryMap.get("deviceState")
  278 + && StringUtils.isNotEmpty(queryMap.get("deviceState").toString())
  279 + ? DeviceState.valueOf(queryMap.get("deviceState").toString())
  280 + : null;
  281 + if (deviceState != null) {
  282 + queryMap.put("deviceState", deviceState.name());
167 } 283 }
168 - if(null !=db.getDeviceInfo()){  
169 - Optional.ofNullable(db.getDeviceInfo().get(FastIotConstants.DeviceAdditional.SIP)).ifPresent(sip ->{  
170 - ObjectNode additional = (ObjectNode) tbDevice.getDeviceInfo();  
171 - additional.set(FastIotConstants.DeviceAdditional.SIP,sip);  
172 - }); 284 + queryMap.put("userId", getCurrentUser().getId().toString());
  285 + return tkdeviceService.page(getCurrentUser().getCurrentTenantId(), queryMap);
  286 + }
  287 +
  288 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  289 + @GetMapping(
  290 + path = {"/relation"},
  291 + params = {PAGE_SIZE, PAGE})
  292 + @ApiOperation("子设备查询")
  293 + public TkPageData<RelationDeviceDTO> pageRelationDevice(
  294 + @RequestParam(PAGE_SIZE) int pageSize,
  295 + @RequestParam(PAGE) int page,
  296 + @RequestParam(value = "name", required = false) String name,
  297 + @RequestParam(value = "deviceState", required = false) DeviceState deviceState,
  298 + @RequestParam(value = "fromId") String fromId,
  299 + @RequestParam(value = ORDER_FILED, required = false) String orderBy,
  300 + @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType)
  301 + throws ThingsboardException {
  302 + HashMap<String, Object> queryMap = new HashMap<>();
  303 + queryMap.put(PAGE_SIZE, pageSize);
  304 + queryMap.put(PAGE, page);
  305 + queryMap.put(ORDER_FILED, orderBy);
  306 + queryMap.put("name", name);
  307 + queryMap.put("fromId", UUID.fromString(fromId));
  308 + queryMap.put("tenantId", UUID.fromString(getCurrentUser().getCurrentTenantId()));
  309 + if (deviceState != null) {
  310 + queryMap.put("deviceState", deviceState.name());
  311 + }
  312 + if (orderType != null) {
  313 + queryMap.put(ORDER_TYPE, orderType.name());
  314 + }
  315 + // 如果当前用户是客户
  316 + if (getCurrentUser().isCustomerUser()) {
  317 + queryMap.put("customerId", getCurrentUser().getCustomerId().getId());
173 } 318 }
174 - });  
175 - } else {  
176 - tbDevice.setAlarmStatus(0);  
177 - checkEntity(null, tbDevice, Resource.DEVICE); 319 + //如果当前用户是普通租户
  320 + if (getCurrentUser().isPtCommonTenant()) {
  321 + List<String> organizationIds = commonTenantOrganizationAllIds();
  322 + if (null != organizationIds && organizationIds.size() > 0) {
  323 + queryMap.put("organizationIds", organizationIds);
  324 + }
  325 + }
  326 + return tkdeviceService.pageRelation(queryMap);
  327 + }
  328 +
  329 + @PostMapping("/import")
  330 + @ApiOperation("导入配置")
  331 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:import'})")
  332 + public ResponseEntity<String> importDeviceProfile() {
  333 + // TODO 实现的业务功能
  334 + return ResponseEntity.ok("");
178 } 335 }
179 336
180 - Device savedDevice = tbDeviceService.save(tbDevice, oldDevice, null, getCurrentUser());  
181 - DeviceId tbDeviceId = savedDevice.getId();  
182 - DeviceCredentials deviceCredentials;  
183 - if (formCredentials != null && formCredentials.getCredentialsType() != null) {  
184 - deviceCredentials =  
185 - checkNotNull(  
186 - deviceCredentialsService.findDeviceCredentialsByDeviceId(  
187 - getCurrentUser().getTenantId(), tbDeviceId));  
188 - deviceCredentials.setCredentialsId(formCredentials.getCredentialsId());  
189 - deviceCredentials.setCredentialsType(formCredentials.getCredentialsType());  
190 - deviceCredentials.setCredentialsValue(formCredentials.getCredentialsValue());  
191 -  
192 - checkNotNull(deviceCredentials);  
193 - Device device = checkDeviceId(deviceCredentials.getDeviceId(), Operation.WRITE_CREDENTIALS);  
194 - tbDeviceService.updateDeviceCredentials(device, deviceCredentials, getCurrentUser());  
195 - }  
196 - //如果是网关设备,且网关修改了其组织  
197 - if(oldDevice !=null && savedDevice.getDeviceType().equals(DeviceTypeEnum.GATEWAY) && !oldDevice.getOrganizationId().equals(savedDevice.getOrganizationId())){  
198 - updateSensorDeviceOrganization(savedDevice.getTenantId(),savedDevice.getId(),savedDevice.getOrganizationId());  
199 - }  
200 - return savedDevice;  
201 - }  
202 - private void updateSensorDeviceOrganization(TenantId tenantId,DeviceId gatewayId,String newOrganizationId) throws ThingsboardException {  
203 - //查询新组织下的所有组织  
204 - List<String> allOrganization = organizationService.organizationAllIds(tenantId.toString(),newOrganizationId);  
205 - SecurityUser loginUser = getCurrentUser();  
206 - //网关子设备没在该网关新组织下,则同步更新为网关的新组织  
207 - if(null != allOrganization && !allOrganization.isEmpty()){  
208 - List<Device> list = tkdeviceService.findDevicesByGatewaySwitchOrgId(tenantId,newOrganizationId,gatewayId);  
209 - if(!list.isEmpty()){  
210 - list.forEach(obj->{  
211 - Device newObj = new Device(obj);  
212 - newObj.setOrganizationId(newOrganizationId);  
213 - try {  
214 - tbDeviceService.save(newObj, obj, null, loginUser);  
215 - } catch (Exception e) {  
216 - throw new RuntimeException(e);  
217 - } 337 + @PostMapping("/export")
  338 + @ApiOperation("导出")
  339 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:export'})")
  340 + public ResponseEntity<String> exportDeviceProfile() {
  341 + // TODO 实现的业务功能
  342 + return ResponseEntity.ok("");
  343 + }
  344 +
  345 + @DeleteMapping
  346 + @ApiOperation("删除")
  347 + @Transactional
  348 + @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:delete'})")
  349 + public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)
  350 + throws ThingsboardException {
  351 + String currentTenantId = getCurrentUser().getCurrentTenantId();
  352 + List<String> tbIds = tkdeviceService.findTbDeviceIdAndCheckForDelete(currentTenantId, deleteDTO.getIds());
  353 + if (null != tbIds) {
  354 + for (String id : tbIds) {
  355 + deleteTbDevice(UUID.fromString(id));
  356 + deleteAlarm(id);
  357 + }
  358 + tkVideoChannelService.clearDeviceChannelByDeviceIds(currentTenantId, tbIds);
  359 + tkVideoService.deleteGBT28181VideosByDeviceIds(currentTenantId, tbIds);
  360 + }
  361 + }
  362 +
  363 + private void deleteAlarm(String id) throws ThingsboardException {
  364 + //根据设备的tbId查询当前设备的所有告警
  365 + List<String> alarmIds = tkAlarmInfoService.getByTbDeviceId(getTenantId().toString(), id);
  366 + if (alarmIds.isEmpty()) {
  367 + return;
  368 + }
  369 + alarmIds.forEach(strAlarmId -> {
  370 + //此处参考AlarmController中的deleteAlarm方法
  371 + try {
  372 + AlarmId alarmId = new AlarmId(toUUID(strAlarmId));
  373 + Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);
  374 + tbAlarmService.delete(alarm, getCurrentUser());
  375 + } catch (Exception e) {
  376 + e.printStackTrace();
  377 + }
218 }); 378 });
219 - }  
220 } 379 }
221 - }  
222 -  
223 - @GetMapping("{id}")  
224 - @ApiOperation("详情")  
225 - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN','CUSTOMER_USER'},{'api:yt:device:get'})")  
226 - public ResponseEntity<DeviceDTO> getDevice(@PathVariable("id") String id)  
227 - throws ThingsboardException {  
228 - return ResponseEntity.of(tkdeviceService.getDevice(getCurrentUser().getTenantId().getId(), UUID.fromString(id)));  
229 - }  
230 -  
231 - @GetMapping("/public/{id}")  
232 - @ApiOperation("Public客户调用公开设备详情")  
233 - @PreAuthorize("hasAnyAuthority('CUSTOMER_USER')")  
234 - public ResponseEntity<DeviceDTO> getPublicDevice(@PathVariable("id") String id)  
235 - throws ThingsboardException {  
236 - return ResponseEntity.of(tkdeviceService.getDevice(getCurrentUser().getTenantId().getId(), UUID.fromString(id)));  
237 - }  
238 -  
239 -  
240 -  
241 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER','OPENAPI_USER')")  
242 - @PostMapping(path = {"/page"})  
243 - @ApiOperation("查询")  
244 - public TkPageData<DeviceDTO> getPage(  
245 - @RequestBody Map<String, Object> queryMap)  
246 - throws ThingsboardException {  
247 - return pageDevice((Integer) queryMap.get("pageSize"),(Integer) queryMap.get("page"),queryMap);  
248 - }  
249 -  
250 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER','OPENAPI_USER')")  
251 - @PostMapping(params = {PAGE_SIZE, PAGE})  
252 - @ApiOperation("查询")  
253 - public TkPageData<DeviceDTO> pageDevice(  
254 - @RequestParam(PAGE_SIZE) int pageSize,  
255 - @RequestParam(PAGE) int page,  
256 - @RequestBody Map<String, Object> queryMap)  
257 - throws ThingsboardException {  
258 - queryMap.put(PAGE, page);  
259 - queryMap.put(PAGE_SIZE, pageSize);  
260 - // 如果当前用户是客户  
261 - if (getCurrentUser().isCustomerUser()) {  
262 - queryMap.put("customerId", getCurrentUser().getCustomerId().getId()); 380 +
  381 + private void deleteTbDevice(UUID id) throws ThingsboardException {
  382 + DeviceId deviceId = new DeviceId(id);
  383 +
  384 + Device device = checkDeviceId(deviceId, Operation.DELETE);
  385 +
  386 + tbDeviceService.delete(device, getCurrentUser());
263 } 387 }
264 - //如果当前用户是普通租户或者openapi用戶  
265 - if (getCurrentUser().isPtCommonTenant()||getCurrentUser().isOpenApiUser()) {  
266 - List<String> organizationIds =commonTenantOrganizationAllIds();  
267 - if(null!=organizationIds&&organizationIds.size()>0){  
268 - queryMap.put("organizationIds", organizationIds);  
269 - } 388 +
  389 + @GetMapping("/list")
  390 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  391 + @ApiOperation("获取满足条件的所有设备")
  392 + public List<DeviceDTO> getDevices(
  393 + @ApiParam(value = "设备类型") @RequestParam(value = "deviceType", required = false) DeviceTypeEnum deviceType,
  394 + @ApiParam(value = "组织ID") @RequestParam(value = "organizationId", required = false) String organizationId,
  395 + @ApiParam(value = "设备标签") @RequestParam(value = "deviceLabel", required = false) String deviceLabel,
  396 + @ApiParam(value = "设备配置ID") @RequestParam(value = "deviceProfileId", required = false) String deviceProfileId,
  397 + @ApiParam(value = "传输协议类型") @RequestParam(value = "transportType", required = false) TransportTypeEnum transportType,
  398 + @ApiParam(value = "是否场景联动调用,是true") @RequestParam(value = "isSceneLinkage", required = false) Boolean isSceneLinkage,
  399 + @ApiParam(value = "是否边缘分配设备调用,是true") @RequestParam(value = "isEdgeDistribution", required = false) Boolean isEdgeDistribution,
  400 + @ApiParam(value = "edgeId") @RequestParam(value = "edgeId", required = false) String edgeId,
  401 + @ApiParam(value = "排除边端设备是true") @RequestParam(value = "isExcludeEdge", required = false) Boolean isExcludeEdge,
  402 + @ApiParam(value = "排除云端设备是true") @RequestParam(value = "isExcludeCloud", required = false) Boolean isExcludeCloud
  403 + )
  404 + throws ThingsboardException {
  405 + if (isExcludeEdge == null) {
  406 + isExcludeEdge = false;
  407 + }
  408 + if (isExcludeCloud == null) {
  409 + isExcludeCloud = false;
  410 + }
  411 + return tkdeviceService.findDevicesByDeviceTypeAndOrganizationId(
  412 + deviceType,
  413 + getCurrentUser().getTenantId().getId(),
  414 + organizationId,
  415 + deviceLabel,
  416 + StringUtils.isEmpty(deviceProfileId) ? null : UUID.fromString(deviceProfileId),
  417 + transportType,
  418 + isSceneLinkage,
  419 + isEdgeDistribution,
  420 + StringUtils.isEmpty(edgeId) ? null : UUID.fromString(edgeId),
  421 + isExcludeEdge,
  422 + isExcludeCloud
  423 + );
270 } 424 }
271 - DeviceState deviceState =  
272 - null != queryMap.get("deviceState")  
273 - && StringUtils.isNotEmpty(queryMap.get("deviceState").toString())  
274 - ? DeviceState.valueOf(queryMap.get("deviceState").toString())  
275 - : null;  
276 - if (deviceState != null) {  
277 - queryMap.put("deviceState", deviceState.name()); 425 +
  426 +
  427 + @PostMapping("/getListByDeviceProfileIds")
  428 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  429 + @ApiOperation("获取多种产品下的设备")
  430 + public List<DeviceDTO> getListByDeviceProfileIds(
  431 + @RequestBody(required = false) List<UUID> deviceProfileIds,
  432 + String organizationId)
  433 + throws ThingsboardException {
  434 + if (deviceProfileIds == null || deviceProfileIds.isEmpty()) {
  435 + throw new TkDataValidationException(MessageUtils.message(ErrorMessage.GET_DEVICE_LIST_ERROR.getI18nCode()));
  436 + }
  437 + return tkdeviceService.findDevicesByOrganizationIds(
  438 + getCurrentUser().getTenantId().getId(),
  439 + organizationId,
  440 + deviceProfileIds);
278 } 441 }
279 - queryMap.put("userId", getCurrentUser().getId().toString());  
280 - return tkdeviceService.page(getCurrentUser().getCurrentTenantId(), queryMap);  
281 - }  
282 -  
283 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
284 - @GetMapping(  
285 - path = {"/relation"},  
286 - params = {PAGE_SIZE, PAGE})  
287 - @ApiOperation("子设备查询")  
288 - public TkPageData<RelationDeviceDTO> pageRelationDevice(  
289 - @RequestParam(PAGE_SIZE) int pageSize,  
290 - @RequestParam(PAGE) int page,  
291 - @RequestParam(value = "name", required = false) String name,  
292 - @RequestParam(value = "deviceState", required = false) DeviceState deviceState,  
293 - @RequestParam(value = "fromId") String fromId,  
294 - @RequestParam(value = ORDER_FILED, required = false) String orderBy,  
295 - @RequestParam(value = ORDER_TYPE, required = false) OrderTypeEnum orderType)  
296 - throws ThingsboardException {  
297 - HashMap<String, Object> queryMap = new HashMap<>();  
298 - queryMap.put(PAGE_SIZE, pageSize);  
299 - queryMap.put(PAGE, page);  
300 - queryMap.put(ORDER_FILED, orderBy);  
301 - queryMap.put("name", name);  
302 - queryMap.put("fromId", UUID.fromString(fromId));  
303 - queryMap.put("tenantId", UUID.fromString(getCurrentUser().getCurrentTenantId()));  
304 - if (deviceState != null) {  
305 - queryMap.put("deviceState", deviceState.name()); 442 +
  443 + @GetMapping("/gateway/list")
  444 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  445 + @ApiOperation("获取满足条件的所有设备")
  446 + public List<DeviceDTO> getGatewayDevices(
  447 + @ApiParam(value = "组织ID")
  448 + String organizationId,
  449 + @ApiParam(value = "网关id")
  450 + String gatewayId,
  451 + @ApiParam(value = "传输类型") @RequestParam(value = "transportType", required = false)
  452 + DeviceTransportType transportType)
  453 + throws ThingsboardException {
  454 + List<String> orgIds = null;
  455 + if (getCurrentUser().isPtCommonTenant()) {
  456 + orgIds = commonTenantOrganizationAllIds();
  457 + }
  458 + return tkdeviceService.findDevicesByTransportTypeAndOrganizationId(
  459 + getCurrentUser().getTenantId().getId(), orgIds, organizationId, transportType, gatewayId);
306 } 460 }
307 - if (orderType != null) {  
308 - queryMap.put(ORDER_TYPE, orderType.name()); 461 +
  462 + @GetMapping("/list/master/{organizationId}")
  463 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  464 + @ApiOperation("主设备列表")
  465 + public List<SelectItemDTO> getMasterDevices(
  466 + @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,
  467 + @ApiParam(value = "设备配置ID") @RequestParam(value = "deviceProfileId", required = false)
  468 + String deviceProfileId)
  469 + throws ThingsboardException {
  470 + return tkdeviceService.findMasterDevices(
  471 + getCurrentUser().getTenantId().getId(),
  472 + getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,
  473 + organizationId,
  474 + UUID.fromString(deviceProfileId));
309 } 475 }
310 - // 如果当前用户是客户  
311 - if (getCurrentUser().isCustomerUser()) {  
312 - queryMap.put("customerId", getCurrentUser().getCustomerId().getId()); 476 +
  477 + @GetMapping("/list/slave/{organizationId}")
  478 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  479 + @ApiOperation("从设备列表")
  480 + public List<SelectItemDTO> getSlaveDevices(
  481 + @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,
  482 + @ApiParam(value = "主设备ID") @RequestParam(value = "masterId", required = false)
  483 + String masterId)
  484 + throws ThingsboardException {
  485 + return tkdeviceService.findSlaveDevices(
  486 + UUID.fromString(masterId),
  487 + getCurrentUser().getTenantId().getId(),
  488 + getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,
  489 + organizationId);
313 } 490 }
314 - //如果当前用户是普通租户  
315 - if (getCurrentUser().isPtCommonTenant()) {  
316 - List<String> organizationIds =commonTenantOrganizationAllIds();  
317 - if(null!=organizationIds&&organizationIds.size()>0){  
318 - queryMap.put("organizationIds", organizationIds);  
319 - } 491 +
  492 + @GetMapping("/keys/{organizationId}")
  493 + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")
  494 + @ApiOperation("设备遥测指标名称")
  495 + public List<String> listKeys(
  496 + @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,
  497 + @ApiParam(value = "设备ID") @RequestParam(value = "deviceIds", required = false)
  498 + List<UUID> deviceIds)
  499 + throws ThingsboardException {
  500 + return tkdeviceService.findDeviceKeys(
  501 + getCurrentUser().getTenantId().getId(),
  502 + getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,
  503 + organizationId,
  504 + deviceIds);
320 } 505 }
321 - return tkdeviceService.pageRelation(queryMap);  
322 - }  
323 -  
324 - @PostMapping("/import")  
325 - @ApiOperation("导入配置")  
326 - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:import'})")  
327 - public ResponseEntity<String> importDeviceProfile() {  
328 - // TODO 实现的业务功能  
329 - return ResponseEntity.ok("");  
330 - }  
331 -  
332 - @PostMapping("/export")  
333 - @ApiOperation("导出")  
334 - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:export'})")  
335 - public ResponseEntity<String> exportDeviceProfile() {  
336 - // TODO 实现的业务功能  
337 - return ResponseEntity.ok("");  
338 - }  
339 -  
340 - @DeleteMapping  
341 - @ApiOperation("删除")  
342 - @Transactional  
343 - @PreAuthorize("@check.checkPermissions({'TENANT_ADMIN'},{'api:yt:device:delete'})")  
344 - public void deleteDevices(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)  
345 - throws ThingsboardException {  
346 - String currentTenantId = getCurrentUser().getCurrentTenantId();  
347 - List<String> tbIds = tkdeviceService.findTbDeviceIdAndCheckForDelete(currentTenantId, deleteDTO.getIds());  
348 - if(null !=tbIds){  
349 - for (String id : tbIds) {  
350 - deleteTbDevice(UUID.fromString(id));  
351 - deleteAlarm(id);  
352 - }  
353 - tkVideoChannelService.clearDeviceChannelByDeviceIds(currentTenantId,tbIds);  
354 - tkVideoService.deleteGBT28181VideosByDeviceIds(currentTenantId,tbIds); 506 +
  507 + @GetMapping("/gateway/{tbDeviceId}")
  508 + @ApiOperation("获取网关设备")
  509 + public DeviceDTO findGateWayDeviceByTbDeviceId(
  510 + @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)
  511 + throws ThingsboardException {
  512 + List<DeviceDTO> list =
  513 + tkdeviceService.findGateWayDeviceByTbDeviceId(
  514 + getCurrentUser().getTenantId().getId(), UUID.fromString(tbDeviceId));
  515 + return null != list && list.size() > FastIotConstants.MagicNumber.ZERO
  516 + ? list.get(FastIotConstants.MagicNumber.ZERO)
  517 + : null;
355 } 518 }
356 - }  
357 -  
358 - private void deleteAlarm(String id) throws ThingsboardException {  
359 - //根据设备的tbId查询当前设备的所有告警  
360 - List<String> alarmIds = tkAlarmInfoService.getByTbDeviceId(getTenantId().toString(),id);  
361 - if(alarmIds.isEmpty()){  
362 - return;  
363 - }  
364 - alarmIds.forEach(strAlarmId -> {  
365 - //此处参考AlarmController中的deleteAlarm方法  
366 - try {  
367 - AlarmId alarmId = new AlarmId(toUUID(strAlarmId));  
368 - Alarm alarm = checkAlarmId(alarmId, Operation.WRITE);  
369 - tbAlarmService.delete(alarm, getCurrentUser());  
370 - } catch (Exception e) {  
371 - e.printStackTrace();  
372 - }  
373 - });  
374 - }  
375 - private void deleteTbDevice(UUID id) throws ThingsboardException {  
376 - DeviceId deviceId = new DeviceId(id);  
377 -  
378 - Device device = checkDeviceId(deviceId, Operation.DELETE);  
379 -  
380 - tbDeviceService.delete(device, getCurrentUser());  
381 - }  
382 -  
383 - @GetMapping("/list")  
384 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
385 - @ApiOperation("获取满足条件的所有设备")  
386 - public List<DeviceDTO> getDevices(  
387 - @ApiParam(value = "设备类型") @RequestParam(value = "deviceType", required = false) DeviceTypeEnum deviceType,  
388 - @ApiParam(value = "组织ID") @RequestParam(value = "organizationId", required = false) String organizationId,  
389 - @ApiParam(value = "设备标签") @RequestParam(value = "deviceLabel", required = false) String deviceLabel,  
390 - @ApiParam(value = "设备配置ID") @RequestParam(value = "deviceProfileId", required = false) String deviceProfileId,  
391 - @ApiParam(value = "传输协议类型") @RequestParam(value = "transportType", required = false) TransportTypeEnum transportType,  
392 - @ApiParam(value = "是否场景联动调用,是true") @RequestParam(value = "isSceneLinkage", required = false) Boolean isSceneLinkage,  
393 - @ApiParam(value = "是否边缘分配设备调用,是true") @RequestParam(value = "isEdgeDistribution", required = false) Boolean isEdgeDistribution,  
394 - @ApiParam(value = "edgeId") @RequestParam(value = "edgeId", required = false) String edgeId,  
395 - @ApiParam(value = "排除边端设备是true") @RequestParam(value = "isExcludeEdge", required = false) Boolean isExcludeEdge,  
396 - @ApiParam(value = "排除云端设备是true") @RequestParam(value = "isExcludeCloud", required = false) Boolean isExcludeCloud  
397 - )  
398 - throws ThingsboardException {  
399 - if (isExcludeEdge == null) {  
400 - isExcludeEdge = false; 519 +
  520 + @GetMapping("/get_subset/{tbDeviceId}")
  521 + @ApiOperation("获取网关子设备信息")
  522 + public DeviceDTO getSubsetDeviceByTbDeviceId(
  523 + @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)
  524 + throws ThingsboardException {
  525 + return tkdeviceService.getSubsetDeviceByTbDeviceId(
  526 + getCurrentUser().getCurrentTenantId(), tbDeviceId);
401 } 527 }
402 - if (isExcludeCloud == null) {  
403 - isExcludeCloud = false; 528 +
  529 + @GetMapping("/device/relation")
  530 + public String getDeviceRelation(
  531 + @ApiParam(value = "网关子设备:true 非网关子设备:false") @RequestParam(value = "isSlave") boolean isSlave,
  532 + @ApiParam(value = "设备ID") @RequestParam(value = "deviceId") String deviceId) {
  533 + return tkdeviceService.getDeviceRelation(isSlave, UUID.fromString(deviceId));
404 } 534 }
405 - return tkdeviceService.findDevicesByDeviceTypeAndOrganizationId(  
406 - deviceType,  
407 - getCurrentUser().getTenantId().getId(),  
408 - organizationId,  
409 - deviceLabel,  
410 - StringUtils.isEmpty(deviceProfileId) ? null : UUID.fromString(deviceProfileId),  
411 - transportType,  
412 - isSceneLinkage,  
413 - isEdgeDistribution,  
414 - StringUtils.isEmpty(edgeId) ? null : UUID.fromString(edgeId),  
415 - isExcludeEdge,  
416 - isExcludeCloud  
417 - );  
418 - }  
419 -  
420 -  
421 - @PostMapping("/getListByDeviceProfileIds")  
422 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
423 - @ApiOperation("获取多种产品下的设备")  
424 - public List<DeviceDTO> getListByDeviceProfileIds(  
425 - @RequestBody (required = false)List<UUID> deviceProfileIds,  
426 - String organizationId)  
427 - throws ThingsboardException {  
428 - if(deviceProfileIds==null||deviceProfileIds.isEmpty()){  
429 - throw new TkDataValidationException(MessageUtils.message(ErrorMessage.GET_DEVICE_LIST_ERROR.getI18nCode())); 535 +
  536 +
  537 + /**
  538 + * 添加关联关系
  539 + *
  540 + * @param tenantId 租户ID
  541 + * @param gateWayTbDeviceId 网关设备Tb的设备ID
  542 + * @param deviceId 设备的tbDeviceId
  543 + */
  544 + private void addRelation(TenantId tenantId, DeviceId gateWayTbDeviceId, DeviceId deviceId)
  545 + throws ThingsboardException {
  546 + EntityRelation relation = new EntityRelation();
  547 + relation.setFrom(gateWayTbDeviceId);
  548 + relation.setTypeGroup(RelationTypeGroup.COMMON);
  549 + relation.setTo(deviceId);
  550 + relation.setType(FastIotConstants.Relation.relationType);
  551 + checkCanCreateRelation(relation.getTo());
  552 + if (relation.getTypeGroup() == null) {
  553 + relation.setTypeGroup(RelationTypeGroup.COMMON);
  554 + }
  555 +
  556 + tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser());
430 } 557 }
431 - return tkdeviceService.findDevicesByOrganizationIds(  
432 - getCurrentUser().getTenantId().getId(),  
433 - organizationId,  
434 - deviceProfileIds);  
435 - }  
436 -  
437 - @GetMapping("/gateway/list")  
438 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
439 - @ApiOperation("获取满足条件的所有设备")  
440 - public List<DeviceDTO> getGatewayDevices(  
441 - @ApiParam(value = "组织ID")  
442 - String organizationId,  
443 - @ApiParam(value = "网关id")  
444 - String gatewayId,  
445 - @ApiParam(value = "传输类型") @RequestParam(value = "transportType", required = false)  
446 - DeviceTransportType transportType)  
447 - throws ThingsboardException {  
448 - List<String> orgIds = null;  
449 - if(getCurrentUser().isPtCommonTenant()){  
450 - orgIds= commonTenantOrganizationAllIds(); 558 +
  559 + @GetMapping({"used/{id}"})
  560 + @ApiOperation("设备是否被占用")
  561 + public ResponseResult<Boolean> otherUsing(@PathVariable("id") String deviceId)
  562 + throws ThingsboardException {
  563 + String str = tkdeviceService.otherUsing(deviceId, getCurrentUser().getCurrentTenantId());
  564 + ResponseResult result = ResponseResult.success(StringUtils.isEmpty(str) ? true : false);
  565 + result.setMessage(str);
  566 + return result;
451 } 567 }
452 - return tkdeviceService.findDevicesByTransportTypeAndOrganizationId(  
453 - getCurrentUser().getTenantId().getId(), orgIds,organizationId, transportType,gatewayId);  
454 - }  
455 -  
456 - @GetMapping("/list/master/{organizationId}")  
457 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
458 - @ApiOperation("主设备列表")  
459 - public List<SelectItemDTO> getMasterDevices(  
460 - @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,  
461 - @ApiParam(value = "设备配置ID") @RequestParam(value = "deviceProfileId", required = false)  
462 - String deviceProfileId)  
463 - throws ThingsboardException {  
464 - return tkdeviceService.findMasterDevices(  
465 - getCurrentUser().getTenantId().getId(),  
466 - getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,  
467 - organizationId,  
468 - UUID.fromString(deviceProfileId));  
469 - }  
470 -  
471 - @GetMapping("/list/slave/{organizationId}")  
472 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
473 - @ApiOperation("从设备列表")  
474 - public List<SelectItemDTO> getSlaveDevices(  
475 - @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,  
476 - @ApiParam(value = "主设备ID") @RequestParam(value = "masterId", required = false)  
477 - String masterId)  
478 - throws ThingsboardException {  
479 - return tkdeviceService.findSlaveDevices(  
480 - UUID.fromString(masterId),  
481 - getCurrentUser().getTenantId().getId(),  
482 - getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,  
483 - organizationId);  
484 - }  
485 -  
486 - @GetMapping("/keys/{organizationId}")  
487 - @PreAuthorize("hasAnyAuthority('TENANT_ADMIN','CUSTOMER_USER')")  
488 - @ApiOperation("设备遥测指标名称")  
489 - public List<String> listKeys(  
490 - @ApiParam(value = "组织ID") @PathVariable("organizationId") String organizationId,  
491 - @ApiParam(value = "设备ID") @RequestParam(value = "deviceIds", required = false)  
492 - List<UUID> deviceIds)  
493 - throws ThingsboardException {  
494 - return tkdeviceService.findDeviceKeys(  
495 - getCurrentUser().getTenantId().getId(),  
496 - getCurrentUser().isCustomerUser() ? getCurrentUser().getCustomerId().getId() : null,  
497 - organizationId,  
498 - deviceIds);  
499 - }  
500 -  
501 - @GetMapping("/gateway/{tbDeviceId}")  
502 - @ApiOperation("获取网关设备")  
503 - public DeviceDTO findGateWayDeviceByTbDeviceId(  
504 - @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)  
505 - throws ThingsboardException {  
506 - List<DeviceDTO> list =  
507 - tkdeviceService.findGateWayDeviceByTbDeviceId(  
508 - getCurrentUser().getTenantId().getId(), UUID.fromString(tbDeviceId));  
509 - return null != list && list.size() > FastIotConstants.MagicNumber.ZERO  
510 - ? list.get(FastIotConstants.MagicNumber.ZERO)  
511 - : null;  
512 - }  
513 -  
514 - @GetMapping("/get_subset/{tbDeviceId}")  
515 - @ApiOperation("获取网关子设备信息")  
516 - public DeviceDTO getSubsetDeviceByTbDeviceId(  
517 - @ApiParam(value = "tb设备Id") @PathVariable("tbDeviceId") String tbDeviceId)  
518 - throws ThingsboardException {  
519 - return tkdeviceService.getSubsetDeviceByTbDeviceId(  
520 - getCurrentUser().getCurrentTenantId(), tbDeviceId);  
521 - }  
522 -  
523 - @GetMapping("/device/relation")  
524 - public String getDeviceRelation(  
525 - @ApiParam(value = "网关子设备:true 非网关子设备:false") @RequestParam(value = "isSlave") boolean isSlave,  
526 - @ApiParam(value = "设备ID") @RequestParam(value = "deviceId") String deviceId) {  
527 - return tkdeviceService.getDeviceRelation(isSlave, UUID.fromString(deviceId));  
528 - }  
529 -  
530 -  
531 -  
532 - /**  
533 - * 添加关联关系  
534 - *  
535 - * @param tenantId 租户ID  
536 - * @param gateWayTbDeviceId 网关设备Tb的设备ID  
537 - * @param deviceId 设备的tbDeviceId  
538 - */  
539 - private void addRelation(TenantId tenantId, DeviceId gateWayTbDeviceId, DeviceId deviceId)  
540 - throws ThingsboardException {  
541 - EntityRelation relation = new EntityRelation();  
542 - relation.setFrom(gateWayTbDeviceId);  
543 - relation.setTypeGroup(RelationTypeGroup.COMMON);  
544 - relation.setTo(deviceId);  
545 - relation.setType(FastIotConstants.Relation.relationType);  
546 - checkCanCreateRelation(relation.getTo());  
547 - if (relation.getTypeGroup() == null) {  
548 - relation.setTypeGroup(RelationTypeGroup.COMMON); 568 +
  569 + @GetMapping({"/attributes/{deviceProfileId}"})
  570 + @ApiOperation("获取设备的属性")
  571 + public ResponseEntity<JsonNode> getDeviceAttributes(
  572 + @PathVariable("deviceProfileId") String deviceProfileId,
  573 + @RequestParam(value = "dataType", required = false) DataTypeEnum dataType)
  574 + throws ThingsboardException {
  575 + String tenantId = getCurrentUser().getCurrentTenantId();
  576 + DeviceProfileDTO dto = ytDeviceProfileService.findDeviceProfileById(tenantId, deviceProfileId);
  577 + if (null == dto) {
  578 + throw new TkDataValidationException(MessageUtils.message(ErrorMessage.INVALID_PARAMETER.getI18nCode()));
  579 + }
  580 + return ResponseEntity.ok(
  581 + tkdeviceService.getDeviceAttributes(deviceProfileId, tenantId, dataType));
549 } 582 }
550 583
551 - tbEntityRelationService.save(getTenantId(), getCurrentUser().getCustomerId(), relation, getCurrentUser());  
552 - }  
553 -  
554 - @GetMapping({"used/{id}"})  
555 - @ApiOperation("设备是否被占用")  
556 - public ResponseResult<Boolean> otherUsing(@PathVariable("id") String deviceId)  
557 - throws ThingsboardException {  
558 - String str = tkdeviceService.otherUsing(deviceId, getCurrentUser().getCurrentTenantId());  
559 - ResponseResult result = ResponseResult.success(StringUtils.isEmpty(str) ? true : false);  
560 - result.setMessage(str);  
561 - return result;  
562 - }  
563 -  
564 - @GetMapping({"/attributes/{deviceProfileId}"})  
565 - @ApiOperation("获取设备的属性")  
566 - public ResponseEntity<JsonNode> getDeviceAttributes(  
567 - @PathVariable("deviceProfileId") String deviceProfileId,  
568 - @RequestParam(value = "dataType", required = false) DataTypeEnum dataType)  
569 - throws ThingsboardException {  
570 - String tenantId = getCurrentUser().getCurrentTenantId();  
571 - DeviceProfileDTO dto = ytDeviceProfileService.findDeviceProfileById(tenantId, deviceProfileId);  
572 - if (null == dto) {  
573 - throw new TkDataValidationException(MessageUtils.message(ErrorMessage.INVALID_PARAMETER.getI18nCode())); 584 + @PostMapping("get/devices")
  585 + @ApiOperation("通过设备ID列表获取设备信息")
  586 + public ResponseResult<List<DeviceDTO>> findDeviceInfoByTbDeviceIds(
  587 + @RequestBody List<String> tbDeviceIds) throws ThingsboardException {
  588 + return ResponseResult.success(
  589 + tkdeviceService.findDeviceInfoByTbDeviceIds(
  590 + tbDeviceIds, getCurrentUser().getCurrentTenantId()));
574 } 591 }
575 - return ResponseEntity.ok(  
576 - tkdeviceService.getDeviceAttributes(deviceProfileId, tenantId, dataType));  
577 - }  
578 -  
579 - @PostMapping("get/devices")  
580 - @ApiOperation("通过设备ID列表获取设备信息")  
581 - public ResponseResult<List<DeviceDTO>> findDeviceInfoByTbDeviceIds(  
582 - @RequestBody List<String> tbDeviceIds) throws ThingsboardException {  
583 - return ResponseResult.success(  
584 - tkdeviceService.findDeviceInfoByTbDeviceIds(  
585 - tbDeviceIds, getCurrentUser().getCurrentTenantId()));  
586 - }  
587 -  
588 - private void checkCanCreateRelation(EntityId entityId) throws ThingsboardException {  
589 - SecurityUser currentUser = getCurrentUser();  
590 - var isTenantAdminAndRelateToSelf = currentUser.isTenantAdmin() && currentUser.getTenantId().equals(entityId);  
591 - if (!isTenantAdminAndRelateToSelf) {  
592 - checkEntityId(entityId, Operation.WRITE); 592 +
  593 + private void checkCanCreateRelation(EntityId entityId) throws ThingsboardException {
  594 + SecurityUser currentUser = getCurrentUser();
  595 + var isTenantAdminAndRelateToSelf = currentUser.isTenantAdmin() && currentUser.getTenantId().equals(entityId);
  596 + if (!isTenantAdminAndRelateToSelf) {
  597 + checkEntityId(entityId, Operation.WRITE);
  598 + }
593 } 599 }
594 - }  
595 600
596 } 601 }
  1 +package org.thingsboard.server.controller.yunteng;
  2 +
  3 +import com.fasterxml.jackson.databind.ObjectMapper;
  4 +import com.fasterxml.jackson.databind.node.ObjectNode;
  5 +import com.google.common.collect.Lists;
  6 +import io.swagger.annotations.Api;
  7 +import lombok.RequiredArgsConstructor;
  8 +import lombok.extern.slf4j.Slf4j;
  9 +import org.apache.commons.collections4.CollectionUtils;
  10 +import org.apache.http.Consts;
  11 +import org.apache.http.HttpEntity;
  12 +import org.apache.http.client.methods.CloseableHttpResponse;
  13 +import org.apache.http.client.methods.HttpPost;
  14 +import org.apache.http.entity.ContentType;
  15 +import org.apache.http.entity.StringEntity;
  16 +import org.apache.http.impl.client.CloseableHttpClient;
  17 +import org.apache.http.impl.client.HttpClients;
  18 +import org.apache.http.message.BasicHeader;
  19 +import org.springframework.http.HttpStatus;
  20 +import org.springframework.http.ResponseEntity;
  21 +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  22 +import org.springframework.security.core.context.SecurityContext;
  23 +import org.springframework.security.core.context.SecurityContextHolder;
  24 +import org.springframework.web.bind.annotation.RequestBody;
  25 +import org.springframework.web.bind.annotation.RequestMapping;
  26 +import org.springframework.web.bind.annotation.RequestMethod;
  27 +import org.springframework.web.bind.annotation.RestController;
  28 +import org.thingsboard.server.common.data.Device;
  29 +import org.thingsboard.server.common.data.User;
  30 +import org.thingsboard.server.common.data.id.DeviceId;
  31 +import org.thingsboard.server.common.data.id.TenantId;
  32 +import org.thingsboard.server.common.data.id.UserId;
  33 +import org.thingsboard.server.common.data.security.DeviceCredentialsType;
  34 +import org.thingsboard.server.common.data.security.model.JwtToken;
  35 +import org.thingsboard.server.common.data.yunteng.core.exception.TkDataValidationException;
  36 +import org.thingsboard.server.common.data.yunteng.dto.DeviceDTO;
  37 +import org.thingsboard.server.common.data.yunteng.dto.TkCredentialsDto;
  38 +import org.thingsboard.server.common.data.yunteng.dto.UserDTO;
  39 +import org.thingsboard.server.common.data.yunteng.enums.DeviceState;
  40 +import org.thingsboard.server.common.data.yunteng.enums.DeviceTypeEnum;
  41 +import org.thingsboard.server.controller.BaseController;
  42 +import org.thingsboard.server.dao.device.DeviceService;
  43 +import org.thingsboard.server.dao.user.UserService;
  44 +import org.thingsboard.server.dao.yunteng.entities.SysUserEntity;
  45 +import org.thingsboard.server.dao.yunteng.service.TkDeviceService;
  46 +import org.thingsboard.server.dao.yunteng.service.TkUserService;
  47 +import org.thingsboard.server.queue.util.TbCoreComponent;
  48 +import org.thingsboard.server.service.security.auth.JwtAuthenticationToken;
  49 +import org.thingsboard.server.service.security.auth.jwt.JwtAuthenticationProvider;
  50 +import org.thingsboard.server.service.security.model.SecurityUser;
  51 +import org.thingsboard.server.service.security.model.UserPrincipal;
  52 +import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
  53 +import org.thingsboard.server.service.security.model.token.RawAccessJwtToken;
  54 +
  55 +import java.io.ByteArrayOutputStream;
  56 +import java.io.IOException;
  57 +import java.io.InputStream;
  58 +import java.util.HashMap;
  59 +import java.util.List;
  60 +import java.util.Map;
  61 +import java.util.UUID;
  62 +
  63 +@Api(tags = "数据对接")
  64 +@RestController
  65 +@TbCoreComponent
  66 +@RequestMapping("api/yt/deviceSync")
  67 +@RequiredArgsConstructor
  68 +@Slf4j
  69 +public class TkDeviceSyncController extends BaseController {
  70 + private final TkDeviceController deviceController;
  71 + private final UserService userService;
  72 + private final JwtTokenFactory tokenFactory;
  73 + private final TkUserService tkUserService;
  74 + private final JwtAuthenticationProvider accessTokenAuthenticationProvider;
  75 + private final TkDeviceService tkDeviceService;
  76 +
  77 +
  78 + @RequestMapping(value = "device", method = RequestMethod.POST)
  79 + public ResponseEntity<DeviceDTO> syncDevice(@RequestBody ObjectNode objectNode) throws Exception {
  80 + if (objectNode == null) {
  81 + throw new TkDataValidationException("设备信息为空");
  82 + }
  83 +
  84 + if (objectNode.isObject()) {
  85 + List<String> fieldNames = Lists.newArrayList(objectNode.fieldNames());
  86 + if (CollectionUtils.isEmpty(fieldNames)) {
  87 + throw new TkDataValidationException("设备信息为空");
  88 + }
  89 +
  90 + DeviceDTO deviceDTO = new DeviceDTO();
  91 + Map<String, Object> statusMap = new HashMap<>();
  92 + StringBuffer dtuSn = new StringBuffer();
  93 + fieldNames.forEach(fieldName -> {
  94 + deviceDTO.setTransportType("DEFAULT");
  95 + var child = objectNode.get(fieldName);
  96 + if (child.isContainerNode()) {
  97 +
  98 + } else if (child.isTextual()) {
  99 + String text = child.asText();
  100 + if (fieldName.equals("deviceId")) {
  101 + text = text.replaceAll("-", "");
  102 + deviceDTO.setTbDeviceId(text);
  103 + deviceDTO.setSn(text);
  104 + TkCredentialsDto deviceToken = new TkCredentialsDto(UUID.randomUUID());
  105 + deviceToken.setCredentialsType(DeviceCredentialsType.ACCESS_TOKEN);
  106 + deviceToken.setCredentialsId(text);
  107 + deviceDTO.setDeviceToken(deviceToken);
  108 + statusMap.put("dtuSn", text);
  109 + dtuSn.append(text);
  110 + } else if (fieldName.equals("deviceProfileId")) {
  111 + deviceDTO.setDeviceProfileId("91cbfd70-da18-11ef-a247-0f9acb050a20"); // todo ymk 需要修改为配置
  112 + deviceDTO.setProfileId("91cbfd70-da18-11ef-a247-0f9acb050a20"); // todo ymk 需要修改为配置
  113 + } else if (fieldName.equals("deviceName")) {
  114 + deviceDTO.setName(text);
  115 + }
  116 + } else {
  117 + statusMap.put(fieldName, child.asText());
  118 + }
  119 + });
  120 +
  121 +
  122 + try {
  123 + String token = createAuthResult();
  124 + deviceDTO.setOrganizationId("9b4e32c7-5ccf-467a-a24d-6c22a12155d6"); // todo ymk 需要修改为配置
  125 + deviceDTO.setDeviceType(DeviceTypeEnum.DIRECT_CONNECTION); // todo ymk 需要根据实际情况填值
  126 + DeviceDTO oldDeviceDto = tkDeviceService.getDeviceByDeviceName(getCurrentUser().getTenantId().getId(), deviceDTO.getName());
  127 + if (oldDeviceDto != null) {
  128 + deviceDTO.setId(oldDeviceDto.getId());
  129 + deviceDTO.setDeviceToken(null);
  130 + }
  131 +
  132 + ResponseEntity<DeviceDTO> deviceDTOResponseEntity = deviceController.saveDeviceInterface(deviceDTO);
  133 + if (deviceDTOResponseEntity.getStatusCode() == HttpStatus.OK) {
  134 + BasicHeader qxAuthorization = new BasicHeader("X-Authorization", "Bearer " + token);
  135 + String qxDeviceInfoDetailUrlStr = "http://10.9.0.205:8080/api/v1/" + dtuSn + "/telemetry";
  136 + HttpPost qxDeviceInfoDetailPost = new HttpPost(qxDeviceInfoDetailUrlStr);
  137 + qxDeviceInfoDetailPost.addHeader(qxAuthorization);
  138 + ObjectMapper objectMapper = new ObjectMapper();
  139 + String syncDeviceInfoDetail = sendPost(qxDeviceInfoDetailPost, objectMapper.writeValueAsString(statusMap));
  140 + }
  141 + } catch (Exception e) {
  142 + log.error("sync device occur error!");
  143 + e.printStackTrace();
  144 + }
  145 + } else if (objectNode.isArray()) {
  146 +
  147 + }
  148 +
  149 +
  150 + return null;
  151 + }
  152 +
  153 + private String createAuthResult() throws Exception {
  154 + UserDTO userDTO = tkUserService.findUserInfoById("d3ff02fd-02ad-4d3e-a197-dc2632ddffe9");
  155 + UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.PUBLIC_ID, userDTO.getId());
  156 + User user = userService.findUserById(new TenantId(UUID.fromString(userDTO.getTenantId())), new UserId(UUID.fromString(userDTO.getTbUser())));
  157 + SecurityUser securityUser = new SecurityUser(user, true, principal);
  158 + JwtToken jwtToken = tokenFactory.createAccessJwtToken(securityUser);
  159 + SecurityContext context = SecurityContextHolder.createEmptyContext();
  160 + context.setAuthentication(accessTokenAuthenticationProvider.authenticate(new JwtAuthenticationToken(getRawJwtToken(jwtToken))));
  161 + SecurityContextHolder.setContext(context);
  162 + return jwtToken.getToken();
  163 + }
  164 +
  165 + private RawAccessJwtToken getRawJwtToken(JwtToken token) {
  166 + return new RawAccessJwtToken(token.getToken());
  167 + }
  168 +
  169 + private String sendPost(HttpPost httpPost, String jsonData) {
  170 + CloseableHttpClient httpClient = HttpClients.createDefault();
  171 + StringEntity entity = new StringEntity(jsonData, ContentType.create("application/json", Consts.UTF_8));
  172 + httpPost.setEntity(entity);
  173 + String result = null;
  174 + try {
  175 + CloseableHttpResponse execute = httpClient.execute(httpPost);
  176 + HttpEntity res = execute.getEntity();
  177 + InputStream is = res.getContent();
  178 + int len;
  179 + byte[] buf = new byte[128];
  180 + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  181 + while ((len = is.read(buf)) != -1) {
  182 + byteArrayOutputStream.write(buf, 0, len);
  183 + }
  184 + result = byteArrayOutputStream.toString();
  185 + } catch (IOException e) {
  186 + e.printStackTrace();
  187 + }
  188 + return result;
  189 + }
  190 +}
@@ -9,6 +9,7 @@ import com.google.common.util.concurrent.Futures; @@ -9,6 +9,7 @@ import com.google.common.util.concurrent.Futures;
9 import com.google.common.util.concurrent.ListenableFuture; 9 import com.google.common.util.concurrent.ListenableFuture;
10 import lombok.RequiredArgsConstructor; 10 import lombok.RequiredArgsConstructor;
11 import lombok.extern.slf4j.Slf4j; 11 import lombok.extern.slf4j.Slf4j;
  12 +import org.apache.commons.collections4.CollectionUtils;
12 import org.apache.commons.lang3.StringUtils; 13 import org.apache.commons.lang3.StringUtils;
13 import org.jetbrains.annotations.Nullable; 14 import org.jetbrains.annotations.Nullable;
14 import org.springframework.cache.annotation.CacheEvict; 15 import org.springframework.cache.annotation.CacheEvict;
@@ -193,7 +194,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -193,7 +194,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
193 new LambdaQueryWrapper<TkDeviceEntity>() 194 new LambdaQueryWrapper<TkDeviceEntity>()
194 .eq(TkDeviceEntity::getTenantId, currentTenantId.getId()) 195 .eq(TkDeviceEntity::getTenantId, currentTenantId.getId())
195 .eq(TkDeviceEntity::getGatewayId, UUID.fromString(gateWayId)) 196 .eq(TkDeviceEntity::getGatewayId, UUID.fromString(gateWayId))
196 - .ne(!insert, TkDeviceEntity::getId, null==deviceDTO.getId()?null:UUID.fromString(deviceDTO.getId()))); 197 + .ne(!insert, TkDeviceEntity::getId, null == deviceDTO.getId() ? null : UUID.fromString(deviceDTO.getId())));
197 if (null != entities && !entities.isEmpty()) { 198 if (null != entities && !entities.isEmpty()) {
198 for (TkDeviceEntity entity : entities) { 199 for (TkDeviceEntity entity : entities) {
199 if (Objects.equals(deviceDTO.getCode(), entity.getCode())) { 200 if (Objects.equals(deviceDTO.getCode(), entity.getCode())) {
@@ -325,7 +326,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -325,7 +326,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
325 String deviceLabel, 326 String deviceLabel,
326 UUID deviceProfileId, 327 UUID deviceProfileId,
327 TransportTypeEnum transportTypeEnum, 328 TransportTypeEnum transportTypeEnum,
328 - Boolean isSceneLinkage, 329 + Boolean isSceneLinkage,
329 Boolean isEdgeDistribution, 330 Boolean isEdgeDistribution,
330 UUID edgeId, 331 UUID edgeId,
331 Boolean isExcludeEdge, 332 Boolean isExcludeEdge,
@@ -337,8 +338,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -337,8 +338,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
337 338
338 List<TkDeviceEntity> listEntity = baseMapper.findDevicesByDeviceTypeAndOrganizationId(orgIds, 339 List<TkDeviceEntity> listEntity = baseMapper.findDevicesByDeviceTypeAndOrganizationId(orgIds,
339 deviceType == null ? null : deviceType.name(), 340 deviceType == null ? null : deviceType.name(),
340 - deviceLabel, deviceProfileId, transportTypeEnum,isSceneLinkage,isEdgeDistribution,edgeId,isExcludeEdge,isExcludeCloud);  
341 - return listEntity.stream().map(entity -> { 341 + deviceLabel, deviceProfileId, transportTypeEnum, isSceneLinkage, isEdgeDistribution, edgeId, isExcludeEdge, isExcludeCloud);
  342 + return listEntity.stream().map(entity -> {
342 return CopyUtils.copyAndReturn(entity, new DeviceDTO()); 343 return CopyUtils.copyAndReturn(entity, new DeviceDTO());
343 } 344 }
344 ).collect(Collectors.toList()); 345 ).collect(Collectors.toList());
@@ -377,10 +378,10 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -377,10 +378,10 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
377 throw new TkDataValidationException(MessageUtils.message(ErrorMessage.ORGANIZATION_NOT_EXTIED.getI18nCode())); 378 throw new TkDataValidationException(MessageUtils.message(ErrorMessage.ORGANIZATION_NOT_EXTIED.getI18nCode()));
378 } 379 }
379 List<String> deviceProfileIds = null; 380 List<String> deviceProfileIds = null;
380 - if(null!= gatewayId){  
381 - TkDeviceEntity gateWay = baseMapper.selectById(UUID.fromString(gatewayId)); 381 + if (null != gatewayId) {
  382 + TkDeviceEntity gateWay = baseMapper.selectById(UUID.fromString(gatewayId));
382 TkDeviceProfileEntity gateWayDeviceProfile = tkProfileMapper.selectById(gateWay.getDeviceProfileId()); 383 TkDeviceProfileEntity gateWayDeviceProfile = tkProfileMapper.selectById(gateWay.getDeviceProfileId());
383 - transportType =gateWayDeviceProfile.getTransportType(); 384 + transportType = gateWayDeviceProfile.getTransportType();
384 } 385 }
385 if (null != transportType) { 386 if (null != transportType) {
386 deviceProfileIds = tkProfileMapper.getDeviceProfileIds(tenantId, transportType); 387 deviceProfileIds = tkProfileMapper.getDeviceProfileIds(tenantId, transportType);
@@ -417,8 +418,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -417,8 +418,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
417 @Override 418 @Override
418 public List<DeviceDTO> findGateWayDeviceByTbDeviceId(UUID tenantId, UUID tbDeviceId) { 419 public List<DeviceDTO> findGateWayDeviceByTbDeviceId(UUID tenantId, UUID tbDeviceId) {
419 checkDeviceByTenantIdAndId(tenantId, tbDeviceId, true); 420 checkDeviceByTenantIdAndId(tenantId, tbDeviceId, true);
420 - List<TkDeviceEntity> listEntity =baseMapper.findGateWayDeviceByTbDeviceId(tbDeviceId);  
421 - return listEntity.stream().map(entity -> { 421 + List<TkDeviceEntity> listEntity = baseMapper.findGateWayDeviceByTbDeviceId(tbDeviceId);
  422 + return listEntity.stream().map(entity -> {
422 return CopyUtils.copyAndReturn(entity, new DeviceDTO()); 423 return CopyUtils.copyAndReturn(entity, new DeviceDTO());
423 } 424 }
424 ).collect(Collectors.toList()); 425 ).collect(Collectors.toList());
@@ -445,8 +446,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -445,8 +446,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
445 446
446 447
447 @Override 448 @Override
448 - public Optional<DeviceDTO> getDevice(UUID tenantId, UUID id) {  
449 - TkDeviceEntity deviceEntity = baseMapper.selectDetail(tenantId, id); 449 + public Optional<DeviceDTO> getDevice(UUID tenantId, UUID id) {
  450 + TkDeviceEntity deviceEntity = baseMapper.selectDetail(tenantId, id);
450 DeviceDTO device = 451 DeviceDTO device =
451 CopyUtils.copyAndReturn(deviceEntity, new DeviceDTO()); 452 CopyUtils.copyAndReturn(deviceEntity, new DeviceDTO());
452 // 转换为 Instant 453 // 转换为 Instant
@@ -466,8 +467,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -466,8 +467,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
466 device.getId(), 467 device.getId(),
467 CollectEnum.DEVICE_COLLECT.name()); 468 CollectEnum.DEVICE_COLLECT.name());
468 device.setIsCollect(entiy == null ? 0 : 1); 469 device.setIsCollect(entiy == null ? 0 : 1);
469 - }catch (Exception e){  
470 - log.error(e.getMessage(),e); 470 + } catch (Exception e) {
  471 + log.error(e.getMessage(), e);
471 } 472 }
472 473
473 device.setOrganizationDTO(organizationService.findOrganizationById(device.getOrganizationId(), tenantId.toString())); 474 device.setOrganizationDTO(organizationService.findOrganizationById(device.getOrganizationId(), tenantId.toString()));
@@ -477,8 +478,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -477,8 +478,8 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
477 @Override 478 @Override
478 public TkPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap) { 479 public TkPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap) {
479 List<String> idList = (List<String>) queryMap.get("deviceProfileIds"); 480 List<String> idList = (List<String>) queryMap.get("deviceProfileIds");
480 - if(null!=idList){  
481 - queryMap.put("deviceProfileIds",idList.stream().map(item -> UUID.fromString(item)).collect(Collectors.toList())); 481 + if (null != idList) {
  482 + queryMap.put("deviceProfileIds", idList.stream().map(item -> UUID.fromString(item)).collect(Collectors.toList()));
482 } 483 }
483 queryMap.put("tenantId", UUID.fromString(tenantId)); 484 queryMap.put("tenantId", UUID.fromString(tenantId));
484 String organizationId = (String) queryMap.get("organizationId"); 485 String organizationId = (String) queryMap.get("organizationId");
@@ -573,6 +574,21 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -573,6 +574,21 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
573 } 574 }
574 575
575 @Override 576 @Override
  577 + public DeviceDTO getDeviceByDeviceName(UUID tenantId, String deviceName) {
  578 + List<TkDeviceEntity> deviceList =
  579 + baseMapper.selectList(
  580 + new QueryWrapper<TkDeviceEntity>()
  581 + .lambda()
  582 + .eq(true, TkDeviceEntity::getTenantId, tenantId)
  583 + .eq(TkDeviceEntity::getName, deviceName));
  584 + if (CollectionUtils.isNotEmpty(deviceList)) {
  585 + return deviceList.get(0).getDTO(DeviceDTO.class);
  586 + }
  587 +
  588 + return null;
  589 + }
  590 +
  591 + @Override
576 public boolean freshAlarmStatus(EntityId tbDeviceId, Integer created) { 592 public boolean freshAlarmStatus(EntityId tbDeviceId, Integer created) {
577 return baseMapper.freshAlarmStatus(tbDeviceId.getId(), created); 593 return baseMapper.freshAlarmStatus(tbDeviceId.getId(), created);
578 } 594 }
@@ -764,11 +780,11 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -764,11 +780,11 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
764 if (null == tenantId || null == tbDeviceId) { 780 if (null == tenantId || null == tbDeviceId) {
765 throw new TkDataValidationException(MessageUtils.message(ErrorMessage.INVALID_PARAMETER.getI18nCode())); 781 throw new TkDataValidationException(MessageUtils.message(ErrorMessage.INVALID_PARAMETER.getI18nCode()));
766 } 782 }
767 - TkDeviceEntity entity=baseMapper.findDeviceInfo(tenantId, tbDeviceId);  
768 - if(entity==null){ 783 + TkDeviceEntity entity = baseMapper.findDeviceInfo(tenantId, tbDeviceId);
  784 + if (entity == null) {
769 return null; 785 return null;
770 } 786 }
771 - return CopyUtils.copyAndReturn(entity,new DeviceDTO()); 787 + return CopyUtils.copyAndReturn(entity, new DeviceDTO());
772 } 788 }
773 789
774 790
@@ -875,7 +891,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -875,7 +891,7 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
875 .selectList( 891 .selectList(
876 new LambdaQueryWrapper<TkDeviceEntity>() 892 new LambdaQueryWrapper<TkDeviceEntity>()
877 .eq(TkDeviceEntity::getTenantId, UUID.fromString(tenantId)) 893 .eq(TkDeviceEntity::getTenantId, UUID.fromString(tenantId))
878 - .in(TkDeviceEntity::getTbDeviceId, tbDeviceIds.stream().map(id ->UUID.fromString(id)).collect(Collectors.toList()))) 894 + .in(TkDeviceEntity::getTbDeviceId, tbDeviceIds.stream().map(id -> UUID.fromString(id)).collect(Collectors.toList())))
879 .stream() 895 .stream()
880 .map(entity -> entity.getDTO(DeviceDTO.class)) 896 .map(entity -> entity.getDTO(DeviceDTO.class))
881 .collect(Collectors.toList()); 897 .collect(Collectors.toList());
@@ -887,15 +903,15 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD @@ -887,15 +903,15 @@ public class TkDeviceServiceImpl extends AbstractTbBaseService<DeviceMapper, TkD
887 UUID tbDeviceId = null; 903 UUID tbDeviceId = null;
888 try { 904 try {
889 tbDeviceId = UUID.fromString(nameOrTbDeviceId); 905 tbDeviceId = UUID.fromString(nameOrTbDeviceId);
890 - }catch (Exception e){ 906 + } catch (Exception e) {
891 907
892 } 908 }
893 TkDeviceEntity entity = 909 TkDeviceEntity entity =
894 baseMapper.selectOne(new LambdaQueryWrapper<TkDeviceEntity>() 910 baseMapper.selectOne(new LambdaQueryWrapper<TkDeviceEntity>()
895 .eq(TkDeviceEntity::getTenantId, UUID.fromString(tenantId)) 911 .eq(TkDeviceEntity::getTenantId, UUID.fromString(tenantId))
896 - .eq(TkDeviceEntity::getGatewayId,UUID.fromString(gateWayId))  
897 - .eq(TkDeviceEntity::getName, nameOrTbDeviceId).or().eq(null!=tbDeviceId,TkDeviceEntity::getTbDeviceId,tbDeviceId));  
898 - return Optional.ofNullable(entity).map(obj->obj.getDTO(DeviceDTO.class)).orElse(null); 912 + .eq(TkDeviceEntity::getGatewayId, UUID.fromString(gateWayId))
  913 + .eq(TkDeviceEntity::getName, nameOrTbDeviceId).or().eq(null != tbDeviceId, TkDeviceEntity::getTbDeviceId, tbDeviceId));
  914 + return Optional.ofNullable(entity).map(obj -> obj.getDTO(DeviceDTO.class)).orElse(null);
899 } 915 }
900 916
901 @Override 917 @Override
@@ -24,265 +24,278 @@ import java.util.*; @@ -24,265 +24,278 @@ import java.util.*;
24 24
25 public interface TkDeviceService extends TbBaseService<TkDeviceEntity> { 25 public interface TkDeviceService extends TbBaseService<TkDeviceEntity> {
26 26
27 - Device buildTbDeviceFromDeviceDTO(TenantId tenantId, DeviceDTO deviceDTO);  
28 - /**  
29 - *  
30 - * 更新设备扩展信息  
31 - * @param tenantId 租户ID  
32 - * @param deviceId Tb设备ID  
33 - * @param key 扩展信息字段名  
34 - * @param val 扩展信息字段值  
35 - * @return  
36 - */  
37 - DeviceDTO updateDeviceInfo(UUID tenantId,UUID deviceId,String key, JsonNode val);  
38 -  
39 -  
40 -  
41 - Optional<DeviceDTO> getDevice(UUID tenantId, UUID id) ;  
42 -  
43 - TkPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap);  
44 -  
45 - TkPageData<RelationDeviceDTO> pageRelation(Map<String, Object> queryMap);  
46 -  
47 - /** 验证表单数据有效性 */  
48 - void validateFormData(TenantId currentTenantId, DeviceDTO ytDevice);  
49 -  
50 - /**  
51 - * 查询所有的设备信息  
52 - *  
53 - * @return List<DeviceDTO>  
54 - */  
55 - boolean deviceNameUsed(UUID tenantId, String deviceName, String deviceId);  
56 -  
57 - /**  
58 - * 设备删除前的检查  
59 - * @param tenantId 租户ID  
60 - * @param ids 删除的设备ID集合  
61 - * @return TB的设备ID集合  
62 - */  
63 - List<String> findTbDeviceIdAndCheckForDelete(String tenantId, Set<String> ids);  
64 -  
65 - /**  
66 - * 通过设备类型和组织ID查询所有的设备  
67 - *  
68 - * @param deviceType 设备类型  
69 - * @param organizationId 组织ID  
70 - * @param isSceneLinkage 是否场景联动调用 用于过滤边缘设备  
71 - * @param isEdgeDistribution 是否分配边缘调用 用于过滤场景联动已使用设备  
72 - * @param edgeId 是否分配边缘调用 用于过滤已分配给此边端的设备  
73 - * @return 设备列表  
74 - */  
75 - List<DeviceDTO> findDevicesByDeviceTypeAndOrganizationId(  
76 - DeviceTypeEnum deviceType,  
77 - UUID tenantId,  
78 - String organizationId,  
79 - String deviceLabel,  
80 - UUID deviceProfileId,  
81 - TransportTypeEnum transportTypeEnum,  
82 - Boolean isSceneLinkage,  
83 - Boolean isEdgeDistribution,  
84 - UUID edgeId,Boolean excludeEdge,Boolean isExcludeCloud);  
85 -  
86 -  
87 - List<DeviceDTO> findDevicesByOrganizationIds(  
88 - UUID tenantId,  
89 - String organizationId,  
90 - List<UUID> deviceProfileIds);  
91 -  
92 - /**  
93 - * 网关切换组织后,需要刷新组织信息的网关子设备  
94 - * @param tenantId 租户ID  
95 - * @param organizationId 网关设备的组织ID  
96 - * @param gatewayId  
97 - * @return  
98 - */  
99 - List<Device> findDevicesByGatewaySwitchOrgId(TenantId tenantId, String organizationId, DeviceId gatewayId);  
100 -  
101 - List<DeviceDTO> findDevicesByTransportTypeAndOrganizationId(  
102 - UUID tenantId ,List<String> orgIds ,String organizationId, DeviceTransportType transportType, String gatewayId);  
103 - /**  
104 - * 通过设备ID和租户ID判断该设备是否存在  
105 - *  
106 - * @param tenantId 租户ID  
107 - * @param deviceId 设备ID  
108 - * @return 设备  
109 - */  
110 - DeviceDTO checkDeviceByTenantIdAndDeviceId(UUID tenantId, UUID deviceId);  
111 -  
112 - /**  
113 - * 通过网关子设备的TB设备ID查询网关设备信息  
114 - *  
115 - * @param tbDeviceId 网关子设备的TB设备ID  
116 - * @param tenantId 租户ID  
117 - * @return 网关设备信息  
118 - */  
119 - List<DeviceDTO> findGateWayDeviceByTbDeviceId(UUID tenantId, UUID tbDeviceId);  
120 -  
121 - /**  
122 - * 通过设备ID和租户ID检查设备是否存在  
123 - *  
124 - * @param tenantId 租户ID  
125 - * @param deviceId 设备ID  
126 - * @param isTbDeviceId 是TB设备ID  
127 - * @return 设备信息  
128 - */  
129 - DeviceDTO checkDeviceByTenantIdAndId(UUID tenantId, UUID deviceId, boolean isTbDeviceId);  
130 -  
131 - /**  
132 - * 更新设备告警状态  
133 - *  
134 - * @param tbDeviceId TB设备主键  
135 - * @param created 告警状态:0正常,1告警  
136 - * @return true成功 false失败  
137 - */  
138 - boolean freshAlarmStatus(EntityId tbDeviceId, Integer created);  
139 -  
140 - /**  
141 - * 自动生成设备SN  
142 - *  
143 - * @return 设备SN  
144 - */  
145 - String generateSn();  
146 -  
147 - /**  
148 - * 设备是否被其它资源使用,例如:场景联动  
149 - *  
150 - * @param deviceId 平台设备ID  
151 - * @param tenantId 租户ID  
152 - * @return 场景联动ID  
153 - */  
154 - String otherUsing(String deviceId, String tenantId);  
155 - /**  
156 - * 主设备信息  
157 - *  
158 - * @param tenantId 租户ID  
159 - * @param organizationId 组织ID  
160 - * @return 设备列表  
161 - */  
162 - List<SelectItemDTO> findMasterDevices(  
163 - UUID tenantId, UUID customerId, String organizationId, UUID deviceProfileId);  
164 -  
165 - /**  
166 - * 从设备信息  
167 - *  
168 - * @param masterId 主设备ID  
169 - * @param tenantId 租户ID  
170 - * @param organizationId 组织ID  
171 - * @return 设备列表  
172 - */  
173 - List<SelectItemDTO> findSlaveDevices(  
174 - UUID masterId, UUID tenantId, UUID customerId, String organizationId);  
175 -  
176 - /**  
177 - * TCP协议传输时,获取网关设备的从设备  
178 - *  
179 - * @param tenantId 租户ID  
180 - * @param masterId 网关设备的TB_ID  
181 - * @param deviceCode 网关子设备的标识符,例如:485协议的从设备地址码  
182 - * @return 从设备信息  
183 - */  
184 - TkDeviceEntity findSlaveDevice(UUID tenantId, UUID masterId, String deviceCode);  
185 -  
186 - /**  
187 - * 设备遥测数据指标名称  
188 - *  
189 - * @param tenantId 租户ID  
190 - * @param customerId 客户ID  
191 - * @param organizationId 组织ID  
192 - * @param deviceIds 设备ID  
193 - * @return 遥测属性列表  
194 - */  
195 - List<String> findDeviceKeys(  
196 - UUID tenantId, UUID customerId, String organizationId, List<UUID> deviceIds);  
197 -  
198 -  
199 -  
200 - /**  
201 - * 通过设备ids查询设备信息列表  
202 - *  
203 - * @param tenantId 租户ID  
204 - * @param ids 设备IDS  
205 - * @return 设备信息列表  
206 - */  
207 - List<DeviceDTO> findDevicesInfoByIds(UUID tenantId, Set<UUID> ids);  
208 -  
209 - /**  
210 - * 通过tb设备ID获取平台设备信息  
211 - *  
212 - * @param tenantId 租户ID  
213 - * @param tbDeviceId tb设备ID  
214 - * @return 设备信息  
215 - */  
216 - DeviceDTO getSubsetDeviceByTbDeviceId(String tenantId, String tbDeviceId);  
217 -  
218 - /**  
219 - * 通过设备配置ID获取属性  
220 - *  
221 - * @param deviceProfileId 平台设备配置ID  
222 - * @param tenantId 租户ID  
223 - * @param dataType 数据属性  
224 - * @return 属性信息de  
225 - */  
226 - JsonNode getDeviceAttributes(String deviceProfileId, String tenantId, DataTypeEnum dataType);  
227 -  
228 - String getDeviceRelation(boolean isSlave,UUID deviceId);  
229 -  
230 - DeviceDTO findDeviceInfoByTbDeviceId(UUID tenantId,UUID tbDeviceId);  
231 -  
232 -  
233 - /**  
234 - * 根据组织和产品ID查询对应的设备  
235 - * @param tenantId 租户ID  
236 - * @param organizationId 组织ID  
237 - * @param map 组织设备关系列表  
238 - * @return 需要接收RPC控制的网关设备或直连设备的ID  
239 - */  
240 - List<String> getDevicesByOrganizationIdAndProjectId(String tenantId, String organizationId, Map<String, List<String>> map);  
241 -  
242 - /**  
243 - * 根据tbDeviceProfileId查询所有的组织与设备关系  
244 - * @param tenantId 租户ID  
245 - * @param deviceProfileId 或 tk_device_profile id 设备配置ID  
246 - * @return 组织ID作为key,设备ID列表作为value  
247 - */  
248 - Map<String, List<String>> getDeviceIdsByDeviceProfileId(String tenantId, String deviceProfileId);  
249 -  
250 - ListenableFuture<List<DeviceDTO>> findDeviceListByDeviceProfileId(String deviceProfileId,String tenantId,String organizationId);  
251 -  
252 - /**  
253 - * 通过设备配置ID查询所有的tbDeviceId  
254 - * @param deviceProfileId 设备配置ID  
255 - * @param tenantId 租户ID  
256 - * @return id集合  
257 - */  
258 - List<String> findTbDeviceIdsByDeviceProfileId(String deviceProfileId,String tenantId,String organizationId);  
259 -  
260 - /**  
261 - * 根据TB设备ID列表获取设备信息  
262 - * @param tbDeviceIds id列表  
263 - * @param tenantId 租户ID  
264 - * @return 设备列表  
265 - */  
266 - List<DeviceDTO> findDeviceInfoByTbDeviceIds(List<String> tbDeviceIds,String tenantId);  
267 -  
268 -  
269 - /**  
270 - * 根据租户ID和设备名称或设备ID查询该设备的信息  
271 - * @param tenantId 租户ID  
272 - * @param nameOrTbDeviceId 设备名称或TBDeviceId  
273 - * @param gateWayId Tb网关ID  
274 - * @return TBDeviceId  
275 - */  
276 - DeviceDTO getDeviceByDeviceNameOrIdAndGateWayId(String tenantId, String nameOrTbDeviceId, String gateWayId);  
277 -  
278 - /**  
279 - * 修改设备的产品ID(profileId)  
280 - * @param tenantId 租户ID  
281 - * @param tbDeviceId TB设备ID  
282 - * @param tbDeviceProfileId TB产品ID  
283 - * @return true成功 false失败  
284 - */  
285 - boolean updateDeviceProfileByTbDeviceId(UUID tenantId,UUID tbDeviceId,UUID tbDeviceProfileId);  
286 -  
287 - String usedBySceneLinkage(String tenantId, String tbDeviceId); 27 + Device buildTbDeviceFromDeviceDTO(TenantId tenantId, DeviceDTO deviceDTO);
  28 +
  29 + /**
  30 + * 更新设备扩展信息
  31 + *
  32 + * @param tenantId 租户ID
  33 + * @param deviceId Tb设备ID
  34 + * @param key 扩展信息字段名
  35 + * @param val 扩展信息字段值
  36 + * @return
  37 + */
  38 + DeviceDTO updateDeviceInfo(UUID tenantId, UUID deviceId, String key, JsonNode val);
  39 +
  40 +
  41 + Optional<DeviceDTO> getDevice(UUID tenantId, UUID id);
  42 +
  43 + TkPageData<DeviceDTO> page(String tenantId, Map<String, Object> queryMap);
  44 +
  45 + TkPageData<RelationDeviceDTO> pageRelation(Map<String, Object> queryMap);
  46 +
  47 + /**
  48 + * 验证表单数据有效性
  49 + */
  50 + void validateFormData(TenantId currentTenantId, DeviceDTO ytDevice);
  51 +
  52 + /**
  53 + * 查询所有的设备信息
  54 + *
  55 + * @return List<DeviceDTO>
  56 + */
  57 + boolean deviceNameUsed(UUID tenantId, String deviceName, String deviceId);
  58 +
  59 + DeviceDTO getDeviceByDeviceName(UUID tenantId, String deviceName);
  60 +
  61 + /**
  62 + * 设备删除前的检查
  63 + *
  64 + * @param tenantId 租户ID
  65 + * @param ids 删除的设备ID集合
  66 + * @return TB的设备ID集合
  67 + */
  68 + List<String> findTbDeviceIdAndCheckForDelete(String tenantId, Set<String> ids);
  69 +
  70 + /**
  71 + * 通过设备类型和组织ID查询所有的设备
  72 + *
  73 + * @param deviceType 设备类型
  74 + * @param organizationId 组织ID
  75 + * @param isSceneLinkage 是否场景联动调用 用于过滤边缘设备
  76 + * @param isEdgeDistribution 是否分配边缘调用 用于过滤场景联动已使用设备
  77 + * @param edgeId 是否分配边缘调用 用于过滤已分配给此边端的设备
  78 + * @return 设备列表
  79 + */
  80 + List<DeviceDTO> findDevicesByDeviceTypeAndOrganizationId(
  81 + DeviceTypeEnum deviceType,
  82 + UUID tenantId,
  83 + String organizationId,
  84 + String deviceLabel,
  85 + UUID deviceProfileId,
  86 + TransportTypeEnum transportTypeEnum,
  87 + Boolean isSceneLinkage,
  88 + Boolean isEdgeDistribution,
  89 + UUID edgeId, Boolean excludeEdge, Boolean isExcludeCloud);
  90 +
  91 +
  92 + List<DeviceDTO> findDevicesByOrganizationIds(
  93 + UUID tenantId,
  94 + String organizationId,
  95 + List<UUID> deviceProfileIds);
  96 +
  97 + /**
  98 + * 网关切换组织后,需要刷新组织信息的网关子设备
  99 + *
  100 + * @param tenantId 租户ID
  101 + * @param organizationId 网关设备的组织ID
  102 + * @param gatewayId
  103 + * @return
  104 + */
  105 + List<Device> findDevicesByGatewaySwitchOrgId(TenantId tenantId, String organizationId, DeviceId gatewayId);
  106 +
  107 + List<DeviceDTO> findDevicesByTransportTypeAndOrganizationId(
  108 + UUID tenantId, List<String> orgIds, String organizationId, DeviceTransportType transportType, String gatewayId);
  109 +
  110 + /**
  111 + * 通过设备ID和租户ID判断该设备是否存在
  112 + *
  113 + * @param tenantId 租户ID
  114 + * @param deviceId 设备ID
  115 + * @return 设备
  116 + */
  117 + DeviceDTO checkDeviceByTenantIdAndDeviceId(UUID tenantId, UUID deviceId);
  118 +
  119 + /**
  120 + * 通过网关子设备的TB设备ID查询网关设备信息
  121 + *
  122 + * @param tbDeviceId 网关子设备的TB设备ID
  123 + * @param tenantId 租户ID
  124 + * @return 网关设备信息
  125 + */
  126 + List<DeviceDTO> findGateWayDeviceByTbDeviceId(UUID tenantId, UUID tbDeviceId);
  127 +
  128 + /**
  129 + * 通过设备ID和租户ID检查设备是否存在
  130 + *
  131 + * @param tenantId 租户ID
  132 + * @param deviceId 设备ID
  133 + * @param isTbDeviceId 是TB设备ID
  134 + * @return 设备信息
  135 + */
  136 + DeviceDTO checkDeviceByTenantIdAndId(UUID tenantId, UUID deviceId, boolean isTbDeviceId);
  137 +
  138 + /**
  139 + * 更新设备告警状态
  140 + *
  141 + * @param tbDeviceId TB设备主键
  142 + * @param created 告警状态:0正常,1告警
  143 + * @return true成功 false失败
  144 + */
  145 + boolean freshAlarmStatus(EntityId tbDeviceId, Integer created);
  146 +
  147 + /**
  148 + * 自动生成设备SN
  149 + *
  150 + * @return 设备SN
  151 + */
  152 + String generateSn();
  153 +
  154 + /**
  155 + * 设备是否被其它资源使用,例如:场景联动
  156 + *
  157 + * @param deviceId 平台设备ID
  158 + * @param tenantId 租户ID
  159 + * @return 场景联动ID
  160 + */
  161 + String otherUsing(String deviceId, String tenantId);
  162 +
  163 + /**
  164 + * 主设备信息
  165 + *
  166 + * @param tenantId 租户ID
  167 + * @param organizationId 组织ID
  168 + * @return 设备列表
  169 + */
  170 + List<SelectItemDTO> findMasterDevices(
  171 + UUID tenantId, UUID customerId, String organizationId, UUID deviceProfileId);
  172 +
  173 + /**
  174 + * 从设备信息
  175 + *
  176 + * @param masterId 主设备ID
  177 + * @param tenantId 租户ID
  178 + * @param organizationId 组织ID
  179 + * @return 设备列表
  180 + */
  181 + List<SelectItemDTO> findSlaveDevices(
  182 + UUID masterId, UUID tenantId, UUID customerId, String organizationId);
  183 +
  184 + /**
  185 + * TCP协议传输时,获取网关设备的从设备
  186 + *
  187 + * @param tenantId 租户ID
  188 + * @param masterId 网关设备的TB_ID
  189 + * @param deviceCode 网关子设备的标识符,例如:485协议的从设备地址码
  190 + * @return 从设备信息
  191 + */
  192 + TkDeviceEntity findSlaveDevice(UUID tenantId, UUID masterId, String deviceCode);
  193 +
  194 + /**
  195 + * 设备遥测数据指标名称
  196 + *
  197 + * @param tenantId 租户ID
  198 + * @param customerId 客户ID
  199 + * @param organizationId 组织ID
  200 + * @param deviceIds 设备ID
  201 + * @return 遥测属性列表
  202 + */
  203 + List<String> findDeviceKeys(
  204 + UUID tenantId, UUID customerId, String organizationId, List<UUID> deviceIds);
  205 +
  206 +
  207 + /**
  208 + * 通过设备ids查询设备信息列表
  209 + *
  210 + * @param tenantId 租户ID
  211 + * @param ids 设备IDS
  212 + * @return 设备信息列表
  213 + */
  214 + List<DeviceDTO> findDevicesInfoByIds(UUID tenantId, Set<UUID> ids);
  215 +
  216 + /**
  217 + * 通过tb设备ID获取平台设备信息
  218 + *
  219 + * @param tenantId 租户ID
  220 + * @param tbDeviceId tb设备ID
  221 + * @return 设备信息
  222 + */
  223 + DeviceDTO getSubsetDeviceByTbDeviceId(String tenantId, String tbDeviceId);
  224 +
  225 + /**
  226 + * 通过设备配置ID获取属性
  227 + *
  228 + * @param deviceProfileId 平台设备配置ID
  229 + * @param tenantId 租户ID
  230 + * @param dataType 数据属性
  231 + * @return 属性信息de
  232 + */
  233 + JsonNode getDeviceAttributes(String deviceProfileId, String tenantId, DataTypeEnum dataType);
  234 +
  235 + String getDeviceRelation(boolean isSlave, UUID deviceId);
  236 +
  237 + DeviceDTO findDeviceInfoByTbDeviceId(UUID tenantId, UUID tbDeviceId);
  238 +
  239 +
  240 + /**
  241 + * 根据组织和产品ID查询对应的设备
  242 + *
  243 + * @param tenantId 租户ID
  244 + * @param organizationId 组织ID
  245 + * @param map 组织设备关系列表
  246 + * @return 需要接收RPC控制的网关设备或直连设备的ID
  247 + */
  248 + List<String> getDevicesByOrganizationIdAndProjectId(String tenantId, String organizationId, Map<String, List<String>> map);
  249 +
  250 + /**
  251 + * 根据tbDeviceProfileId查询所有的组织与设备关系
  252 + *
  253 + * @param tenantId 租户ID
  254 + * @param deviceProfileId 或 tk_device_profile id 设备配置ID
  255 + * @return 组织ID作为key, 设备ID列表作为value
  256 + */
  257 + Map<String, List<String>> getDeviceIdsByDeviceProfileId(String tenantId, String deviceProfileId);
  258 +
  259 + ListenableFuture<List<DeviceDTO>> findDeviceListByDeviceProfileId(String deviceProfileId, String tenantId, String organizationId);
  260 +
  261 + /**
  262 + * 通过设备配置ID查询所有的tbDeviceId
  263 + *
  264 + * @param deviceProfileId 设备配置ID
  265 + * @param tenantId 租户ID
  266 + * @return id集合
  267 + */
  268 + List<String> findTbDeviceIdsByDeviceProfileId(String deviceProfileId, String tenantId, String organizationId);
  269 +
  270 + /**
  271 + * 根据TB设备ID列表获取设备信息
  272 + *
  273 + * @param tbDeviceIds id列表
  274 + * @param tenantId 租户ID
  275 + * @return 设备列表
  276 + */
  277 + List<DeviceDTO> findDeviceInfoByTbDeviceIds(List<String> tbDeviceIds, String tenantId);
  278 +
  279 +
  280 + /**
  281 + * 根据租户ID和设备名称或设备ID查询该设备的信息
  282 + *
  283 + * @param tenantId 租户ID
  284 + * @param nameOrTbDeviceId 设备名称或TBDeviceId
  285 + * @param gateWayId Tb网关ID
  286 + * @return TBDeviceId
  287 + */
  288 + DeviceDTO getDeviceByDeviceNameOrIdAndGateWayId(String tenantId, String nameOrTbDeviceId, String gateWayId);
  289 +
  290 + /**
  291 + * 修改设备的产品ID(profileId)
  292 + *
  293 + * @param tenantId 租户ID
  294 + * @param tbDeviceId TB设备ID
  295 + * @param tbDeviceProfileId TB产品ID
  296 + * @return true成功 false失败
  297 + */
  298 + boolean updateDeviceProfileByTbDeviceId(UUID tenantId, UUID tbDeviceId, UUID tbDeviceProfileId);
  299 +
  300 + String usedBySceneLinkage(String tenantId, String tbDeviceId);
288 } 301 }