Browse Source

Merge pull request #16617 from thingsboard/feature/lts-4.4/iot-hub-lorawan

IoT Hub: LoRaWAN device packages
pull/16633/head
Viacheslav Klimov 3 weeks ago
committed by GitHub
parent
commit
ab58de7fa6
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 12
      application/src/main/java/org/thingsboard/server/controller/IntegrationController.java
  2. 38
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  3. 18
      application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java
  4. 9
      application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java
  5. 1001
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  6. 154
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  7. 119
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java
  8. 27
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java
  9. 19
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java
  10. 71
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  11. 37
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
  12. 116
      application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java
  13. 32
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  14. 3
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  15. 9
      application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
  16. 10
      application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java
  17. 2
      application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java
  18. 170
      application/src/main/resources/converters/TTI/uplink/js.raw
  19. 20
      application/src/main/resources/converters/TTI/uplink/payload.json
  20. 138
      application/src/main/resources/converters/TTI/uplink/tbel.raw
  21. 169
      application/src/main/resources/converters/TTN/uplink/js.raw
  22. 20
      application/src/main/resources/converters/TTN/uplink/payload.json
  23. 138
      application/src/main/resources/converters/TTN/uplink/tbel.raw
  24. 148
      application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java
  25. 851
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  26. 259
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  27. 51
      application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java
  28. 15
      application/src/test/resources/converters/TTI/uplink/test/default/expected.json
  29. 15
      application/src/test/resources/converters/TTN/uplink/test/default/expected.json
  30. 43
      application/src/test/resources/payload/things_stack_formatter_device_payload.json
  31. 34
      application/src/test/resources/payload/things_stack_manual_device_payload.json
  32. 64
      application/src/test/resources/payload/things_stack_repository_device_payload.json
  33. 77
      application/src/test/resources/payload/tti_custom_decoder_payload.json
  34. 54
      application/src/test/resources/payload/ttn_custom_decoder_payload.json
  35. 15
      common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java
  36. 14
      common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java
  37. 5
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java
  38. 2
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/AbstractUplinkDataConverter.java
  39. 99
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java
  40. 7
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java
  41. 6
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java
  42. 32
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java
  43. 287
      common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java
  44. 16
      common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java
  45. 5
      common/integration/mqtt-integrations/pom.xml
  46. 2
      common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java
  47. 62
      common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java
  48. 50
      common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java
  49. 43
      common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java
  50. 20
      dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java
  51. 11
      dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java
  52. 6
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  53. 6
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  54. 8
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  55. 6
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  56. 8
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  57. 119
      dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java
  58. 34
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  59. 211
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  60. 88
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  61. 1756
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  62. 160
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html
  63. 32
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss
  64. 140
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts
  65. 97
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  66. 2
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts
  67. 33
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html
  68. 65
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss
  69. 79
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts
  70. 128
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  71. 8
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  72. 8
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss
  73. 27
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  74. 55
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  75. 36
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss
  76. 117
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  77. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts
  78. 45
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts
  79. 66
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  80. 81
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  81. 9
      ui-ngx/src/app/shared/models/settings.models.ts
  82. 64
      ui-ngx/src/assets/converters/default-converters-v2-configuration.json
  83. 12
      ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md
  84. 12
      ui-ngx/src/assets/help/en_US/iot-hub/gateway-connection-host.md
  85. 4
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  86. 4
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  87. 4
      ui-ngx/src/assets/locale/locale.constant-da_DK.json
  88. 4
      ui-ngx/src/assets/locale/locale.constant-de_DE.json
  89. 4
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  90. 55
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  91. 4
      ui-ngx/src/assets/locale/locale.constant-es_ES.json
  92. 4
      ui-ngx/src/assets/locale/locale.constant-fr_FR.json
  93. 4
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  94. 4
      ui-ngx/src/assets/locale/locale.constant-it_IT.json
  95. 4
      ui-ngx/src/assets/locale/locale.constant-ja_JP.json
  96. 2
      ui-ngx/src/assets/locale/locale.constant-ka_GE.json
  97. 4
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  98. 2
      ui-ngx/src/assets/locale/locale.constant-lv_LV.json
  99. 4
      ui-ngx/src/assets/locale/locale.constant-nl_NL.json
  100. 4
      ui-ngx/src/assets/locale/locale.constant-no_NO.json

12
application/src/main/java/org/thingsboard/server/controller/IntegrationController.java

@ -144,14 +144,10 @@ public class IntegrationController extends AutoCommitController {
checkEntity(integration.getId(), integration, Resource.INTEGRATION);
if (!integration.isEdgeTemplate()) {
try {
Integration copy = new Integration(integration);
secretConfigurationService.replaceSecretUsages(tenantId, copy.getConfiguration());
integrationManagerService.validateIntegrationConfiguration(copy).get(20, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throwRealCause(e);
}
try {
tbIntegrationService.validateIntegrationConfiguration(tenantId, integration);
} catch (ExecutionException e) {
throwRealCause(e);
}
Integration result = checkNotNull(integrationService.saveIntegration(integration));

38
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -32,10 +32,17 @@ import java.util.UUID;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.device.DeviceConnectivityHostSource;
import org.thingsboard.server.dao.device.DeviceConnectivityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.DevicePackageEntityState;
import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService;
import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest;
import org.thingsboard.server.service.iot_hub.DeviceUpdateResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan;
import org.thingsboard.server.service.iot_hub.InstallPlanResult;
@ -51,6 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController {
private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService;
private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService;
@ -95,6 +103,23 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody
public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody
public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DeviceUpdateRequest request) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/update/{versionId}")
@ResponseBody
@ -153,13 +178,22 @@ public class IotHubController extends BaseController {
iotHubService.deleteInstalledItem(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/keptEntities")
@ResponseBody
public InstalledItemKeptEntities getInstalledItemKeptEntities(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
return iotHubService.findKeptEntities(getTenantId(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/connectivity")
@ResponseBody
public JsonNode getConnectivitySettings(HttpServletRequest request) throws Exception {
checkAllPermissions();
String baseUrl = systemSecurityService.getBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request);
return deviceConnectivityService.getConnectivityInfo(baseUrl);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request);
return deviceConnectivityService.getConnectivityInfo(baseUrl.url(),
baseUrl.fromRequest() ? DeviceConnectivityHostSource.REQUEST : DeviceConnectivityHostSource.BASE_URL);
}
private void checkAllPermissions() throws ThingsboardException {

18
application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java

@ -15,21 +15,27 @@ import org.thingsboard.server.common.data.LibraryConvertersInfo;
import org.thingsboard.server.common.data.converter.ConverterType;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationInfo;
import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.secret.SecretConfigurationService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.converter.ConverterLibraryService;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.integration.IntegrationManagerService;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j
@Service
@ -40,6 +46,8 @@ public class DefaultTbIntegrationService extends AbstractTbEntityService impleme
private final IntegrationService integrationService;
private final ConverterLibraryService converterLibraryService;
private final ConverterService converterService;
private final IntegrationManagerService integrationManagerService;
private final SecretConfigurationService secretConfigurationService;
@Override
public PageData<IntegrationInfo> findTenantIntegrationInfos(TenantId tenantId, PageLink pageLink, boolean isEdgeTemplate) {
@ -94,4 +102,14 @@ public class DefaultTbIntegrationService extends AbstractTbEntityService impleme
return result;
}
@Override
public void validateIntegrationConfiguration(TenantId tenantId, Integration integration) throws ExecutionException, InterruptedException, TimeoutException {
if (integration.isEdgeTemplate()) {
return;
}
Integration copy = new Integration(integration);
secretConfigurationService.replaceSecretUsages(tenantId, copy.getConfiguration());
integrationManagerService.validateIntegrationConfiguration(copy).get(20, TimeUnit.SECONDS);
}
}

9
application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java

@ -5,12 +5,15 @@ package org.thingsboard.server.service.entitiy.integration;
import org.thingsboard.server.common.data.IntegrationConvertersInfo;
import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationInfo;
import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public interface TbIntegrationService {
@ -19,4 +22,10 @@ public interface TbIntegrationService {
PageData<IntegrationInfo> findIntegrationInfosByTenantIdAndEdgeId(TenantId tenantId, EdgeId edgeId, PageLink pageLink);
Map<IntegrationType, IntegrationConvertersInfo> getIntegrationsConvertersInfo(TenantId tenantId);
/**
* The check before an integration is saved: its configuration, with the secrets it uses, is validated by its type.
* An edge template isn't validated. An invalid configuration fails with an {@link ExecutionException}.
*/
void validateIntegrationConfiguration(TenantId tenantId, Integration integration) throws ExecutionException, InterruptedException, TimeoutException;
}

1001
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

File diff suppressed because it is too large

154
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -4,6 +4,7 @@
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
@ -42,6 +44,8 @@ import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemD
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.service.solutions.SolutionService;
import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse;
import org.thingsboard.server.common.data.permission.Operation;
@ -58,6 +62,7 @@ import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.group.EntityGroupService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.rule.RuleChainService;
@ -79,10 +84,12 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -118,6 +125,7 @@ public class DefaultIotHubService implements IotHubService {
private final CalculatedFieldService calculatedFieldService;
private final DeviceProfileService deviceProfileService;
private final DeviceService deviceService;
private final EntityService entityService;
private final TbDeviceService tbDeviceService;
private final SolutionService solutionService;
private final EntityGroupService entityGroupService;
@ -127,6 +135,7 @@ public class DefaultIotHubService implements IotHubService {
private final ConverterService converterService;
private final TbConverterService tbConverterService;
private final ProjectInfo projectInfo;
private final DevicePackageEntities devicePackageEntities;
// Field names of the marketplace version JSON payload. Both the install path and the
// install-plan resolver parse the same shape, so the contract lives here in one place.
@ -410,6 +419,10 @@ public class DefaultIotHubService implements IotHubService {
}
String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) {
// Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService
throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
}
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
// Skip checksum validation for solution templates
@ -454,12 +467,6 @@ public class DefaultIotHubService implements IotHubService {
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
case "DEVICE" -> {
DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor;
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user);
dd.setCreatedEntityIds(null);
dd.setDashboardId(null);
}
case "SOLUTION_TEMPLATE" -> {
SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor;
solutionService.deleteSolution(tenantId, stDescriptor, user);
@ -673,6 +680,8 @@ public class DefaultIotHubService implements IotHubService {
installedItem.setItemName(itemName);
installedItem.setItemType("DEVICE");
installedItem.setVersion(version);
// So that an update can tell whether someone changed an entity since
devicePackageEntities.addChecksums(tenantId, descriptor);
installedItem.setDescriptor(descriptor);
try {
iotHubInstalledItemService.save(tenantId, installedItem);
@ -704,13 +713,35 @@ public class DefaultIotHubService implements IotHubService {
}
}
private void deleteDevicePackageEntities(TenantId tenantId, List<EntityId> createdEntityIds, SecurityUser user) {
/**
* Deletes what a device package created, except the entities another installed device package
* also uses (e.g. an integration it took over with Overwrite): deleting those would break that package,
* and the ones the user had before and the package took as they were (use existing).
* A kept integration loses the metadata entries the package added.
*/
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
DeviceInstalledItemDescriptor descriptor, SecurityUser user) {
List<EntityId> createdEntityIds = descriptor.getCreatedEntityIds();
if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return;
}
Set<UUID> usedExisting = usedExistingIds(descriptor);
List<DeviceInstalledItemDescriptor> otherPackages = new ArrayList<>();
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages);
List<EntityId> reversed = new ArrayList<>(createdEntityIds);
Collections.reverse(reversed);
for (EntityId entityId : reversed) {
if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
continue;
}
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
continue;
}
try {
deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) {
@ -719,6 +750,113 @@ public class DefaultIotHubService implements IotHubService {
}
}
/**
* Removes from the kept integration's metadata the entries the package added, e.g. the profile name its converter
* reads, so that a later package of that model gets the default profile again. An entry another installed package
* also added stays.
*/
private void removeIntegrationMetadata(TenantId tenantId, EntityId entityId, DeviceInstalledItemDescriptor descriptor,
List<DeviceInstalledItemDescriptor> otherPackages) {
if (entityId.getEntityType() != EntityType.INTEGRATION) {
return;
}
Set<String> keys = addedMetadataKeys(descriptor, entityId.getId());
otherPackages.forEach(other -> keys.removeAll(addedMetadataKeys(other, entityId.getId())));
if (keys.isEmpty()) {
return;
}
try {
Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId()));
if (integration == null || !(integration.getConfiguration() != null
&& integration.getConfiguration().get("metadata") instanceof ObjectNode metadata)
|| keys.stream().noneMatch(metadata::has)) {
return;
}
// A copy: the integration read may be the cache's own instance
Integration copy = new Integration(integration);
((ObjectNode) copy.getConfiguration().get("metadata")).remove(keys);
integrationService.saveIntegration(copy);
log.info("[{}] Removed metadata entries {} of the deleted device package from integration {}", tenantId, keys, entityId.getId());
} catch (Exception e) {
log.error("[{}] Failed to remove the deleted device package's metadata entries from integration {}", tenantId, entityId.getId(), e);
}
}
/** The metadata entries the package's steps on the integration added, as its install state records them. */
private static Set<String> addedMetadataKeys(DeviceInstalledItemDescriptor descriptor, UUID integrationId) {
Set<String> keys = new HashSet<>();
if (descriptor.getInstallState() != null) {
descriptor.getInstallState().values().forEach(state -> {
if (state != null && integrationId.toString().equals(state.path("entityOutput").path("id").asText())
&& state.get("metadata") instanceof ObjectNode metadata) {
metadata.fieldNames().forEachRemaining(keys::add);
}
});
}
return keys;
}
/** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */
@Override
public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) {
IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId);
if (installedItem == null) {
throw new IllegalArgumentException("Installed item not found");
}
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Set<UUID> usedExisting = usedExistingIds(dd);
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>());
for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) {
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)));
}
if (usedBy != null) {
usedByItems.addAll(usedBy);
}
if (taken) {
usedExistingCount++;
}
}
}
return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount);
}
/** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */
private static Set<UUID> usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
Set<UUID> ids = new HashSet<>();
if (descriptor.getUsedExistingEntityIds() != null) {
descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId()));
}
return ids;
}
/** The other installed device packages' entities, by id; the packages' descriptors go to {@code otherPackages}. */
private Map<UUID, Set<IotHubInstalledItemId>> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId,
List<DeviceInstalledItemDescriptor> otherPackages) {
Map<UUID, Set<IotHubInstalledItemId>> usedBy = new HashMap<>();
PageLink pageLink = new PageLink(100);
PageData<IotHubInstalledItem> page;
do {
page = iotHubInstalledItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink);
for (IotHubInstalledItem item : page.getData()) {
if (item.getId().equals(installedItemId) || !(item.getDescriptor() instanceof DeviceInstalledItemDescriptor dd)) {
continue;
}
otherPackages.add(dd);
if (dd.getCreatedEntityIds() != null) {
dd.getCreatedEntityIds().forEach(id -> usedBy.computeIfAbsent(id.getId(), k -> new HashSet<>()).add(item.getId()));
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext());
return usedBy;
}
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
switch (entityId.getEntityType()) {
case DEVICE -> {
@ -797,7 +935,7 @@ public class DefaultIotHubService implements IotHubService {
}
}
} else if (descriptor instanceof DeviceInstalledItemDescriptor dd) {
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user);
deleteDevicePackageEntities(tenantId, installedItemId, dd, user);
} else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) {
try {
solutionService.deleteSolution(tenantId, st, user);

119
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java

@ -0,0 +1,119 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway
* and a gateway connector don't have one: an update never changes them.
*/
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class DevicePackageEntities {
static final Set<EntityType> CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD,
EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION);
private final DeviceProfileService deviceProfileService;
private final DashboardService dashboardService;
private final RuleChainService ruleChainService;
private final ConverterService converterService;
private final IntegrationService integrationService;
/** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */
public Snapshot load(TenantId tenantId, EntityId entityId) {
Object entity = switch (entityId.getEntityType()) {
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId);
case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId);
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId);
case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId);
case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId);
default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType());
};
if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) {
return null;
}
Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null;
return new Snapshot(entity, metadata);
}
public String checksum(TenantId tenantId, EntityId entityId) {
Snapshot snapshot = load(tenantId, entityId);
return snapshot != null ? snapshot.checksum() : null;
}
/**
* Adds the checksum of each entity the install state names, so that an update can tell whether someone changed
* it since. Entities the user kept at install are left out: an update never overwrites them.
*/
public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) {
if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) {
return;
}
Map<UUID, EntityId> createdIds = new HashMap<>();
descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id));
descriptor.getInstallState().forEach((stepName, state) -> {
EntityId entityId = entityIdOf(state, createdIds);
if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) {
String checksum = checksum(tenantId, entityId);
if (checksum != null) {
((ObjectNode) state).put("checksum", checksum);
}
}
});
}
/** The package entity an install-state step recorded, with its type from the ids the package created. */
static EntityId entityIdOf(JsonNode state, Map<UUID, EntityId> createdIds) {
JsonNode id = state != null ? state.path("entityOutput").path("id") : null;
if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) {
return null;
}
try {
return createdIds.get(UUID.fromString(id.asText()));
} catch (IllegalArgumentException e) {
return null;
}
}
public record Snapshot(Object entity, Object metadata) {
public Long version() {
return ((HasVersion) entity).getVersion();
}
public String checksum() {
return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity);
}
}
}

27
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java

@ -0,0 +1,27 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.id.EntityId;
/** An entity of an installed device package as an update finds it, before it changes anything. */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DevicePackageEntityState {
private String stepName;
private EntityId entityId;
private boolean exists;
// Sent back with the update, which fails if someone changed the entity in between
private Long version;
// Changed since the package installed or last updated it; null when the install state has no checksum of it
// (installed before checksums were kept)
private Boolean modified;
// Other installed device packages use it, so overwriting it affects them
private boolean shared;
}

19
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java

@ -0,0 +1,19 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
/** Updates an installed device package to another version of its item. */
public interface DevicePackageUpdateService {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId);
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */
DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request);
}

71
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -0,0 +1,71 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* The update of an installed device package as the install wizard planned it: the entity of each install step
* of the new version, already resolved from its template, and what to do with it. The server applies all of it
* in one transaction, together with the new version of the installed item, or nothing.
*/
@Data
public class DeviceUpdateRequest {
private String versionId;
// The version installed when the wizard planned the update; the update fails if the package changed since
private UUID fromVersionId;
// The install method of the new version's steps; the installed one when not set
private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it
private Map<String, JsonNode> installState;
private List<Step> steps;
public enum Action {
// Taken as it is: the new version doesn't change it, or the user kept an entity they had
KEEP,
// Takes the entity from the step
OVERWRITE,
// A new entity: new in this version, deleted since install, or a copy next to one with the same name
CREATE
}
@Data
public static class Step {
private String name;
// The package step's id, which keys its install state; the name when not set
private String id;
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
private String type;
private Action action;
// KEEP and OVERWRITE: the entity
private UUID entityId;
// OVERWRITE: the version the user reviewed; a different one means someone changed the entity since
private Long expectedVersion;
// The user confirmed overwriting an entity of another package or one they didn't install with this package
private boolean confirmed;
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this
// update creates is left for the server, which knows its id only once it is created.
private JsonNode entity;
// DEVICE and GATEWAY: the credentials template, if any
private JsonNode credentials;
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
// they may keep ${<alias>.<property>} of an entity this update creates.
private JsonNode serverAttributes;
private JsonNode sharedAttributes;
// The resolution the install state records for it
private String resolution;
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
// integration, e.g. one the package took as it was; null removes an entry
private JsonNode metadata;
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
private boolean defaultConverter;
}
}

37
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java

@ -0,0 +1,37 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import java.util.Map;
/**
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep
* names the step that failed, if one did.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeviceUpdateResult {
private boolean success;
private String errorMessage;
private String failedStep;
private DeviceInstalledItemDescriptor descriptor;
// By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DeviceUpdateResult(true, null, null, descriptor, outputs);
}
public static DeviceUpdateResult error(String errorMessage, String failedStep) {
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null);
}
}

116
application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java

@ -0,0 +1,116 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.rule.RuleChainMetaData;
import org.thingsboard.server.common.data.rule.RuleNode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* The checksum of an entity as the server stores it, kept in the install state of a device package. A different
* checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name,
* which an update keeps, don't count, nor do the debug settings, which the user turns on without changing what the
* entity does, and whether a profile is the default one, which changes when another profile becomes the default.
*/
final class EntityChecksum {
private static final Set<String> SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId",
"customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources", "debugMode", "debugSettings", "default");
private EntityChecksum() {
}
/** A rule chain is checked with its metadata: pass both. */
static String of(Object... parts) {
StringBuilder canonical = new StringBuilder();
for (Object part : parts) {
JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part);
if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) {
// Device packages on one integration add their entries to its metadata: that is no change to the integration
configuration.remove("metadata");
}
appendCanonical(canonical, node, true);
canonical.append('|');
}
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/**
* What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and
* configuration, and the connections. Node ids, layout and debug settings change without the user changing
* what the rule chain does, e.g. when it is saved again.
*/
private static JsonNode ruleChainContent(RuleChainMetaData metadata) {
ObjectNode content = JacksonUtil.newObjectNode();
ArrayNode nodes = content.putArray("nodes");
if (metadata.getNodes() != null) {
for (RuleNode node : metadata.getNodes()) {
ObjectNode n = nodes.addObject();
n.put("type", node.getType());
n.put("name", node.getName());
n.set("configuration", node.getConfiguration());
n.put("singletonMode", node.isSingletonMode());
n.put("queueName", node.getQueueName());
}
}
content.set("connections", JacksonUtil.valueToTree(metadata.getConnections()));
content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections()));
content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex()));
return content;
}
/** JSON with the keys sorted, so the same entity always gives the same text. */
private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) {
if (node == null || node.isNull() || node.isMissingNode()) {
out.append("null");
} else if (node.isObject()) {
List<String> keys = new ArrayList<>();
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
String key = it.next();
if (!topLevel || !SKIPPED_KEYS.contains(key)) {
keys.add(key);
}
}
keys.sort(null);
out.append('{');
for (int i = 0; i < keys.size(); i++) {
if (i > 0) {
out.append(',');
}
out.append(JacksonUtil.toString(keys.get(i))).append(':');
appendCanonical(out, node.get(keys.get(i)), false);
}
out.append('}');
} else if (node.isArray()) {
out.append('[');
for (int i = 0; i < node.size(); i++) {
if (i > 0) {
out.append(',');
}
appendCanonical(out, node.get(i), false);
}
out.append(']');
} else {
out.append(node.toString());
}
}
}

32
application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java

@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.id.EntityId;
import java.util.List;
/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class InstalledItemKeptEntities {
private List<KeptEntity> entities;
// How many other installed items use at least one of the kept entities
private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class KeptEntity {
private EntityId entityId;
private String name;
}
}

3
application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java

@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -20,6 +21,8 @@ public interface IotHubService {
void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId);
InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId);
InstallPlan resolveInstallPlan(SecurityUser user, String versionId);
InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request);

9
application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java

@ -249,6 +249,11 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
@Override
public String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) {
return resolveBaseUrl(tenantId, customerId, httpServletRequest).url();
}
@Override
public ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) {
String baseUrl = null;
AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general");
@ -262,10 +267,10 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
}
if (StringUtils.isEmpty(baseUrl) && httpServletRequest != null) {
baseUrl = MiscUtils.constructBaseUrl(httpServletRequest);
return new ResolvedBaseUrl(MiscUtils.constructBaseUrl(httpServletRequest), true);
}
return formatBaseUrl(baseUrl);
return new ResolvedBaseUrl(formatBaseUrl(baseUrl), false);
}
@Override

10
application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java

@ -0,0 +1,10 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.security.system;
/**
* Base URL as returned by {@link SystemSecurityService#getBaseUrl}, and whether it was built from
* the request rather than taken from the Base URL in General settings.
*/
public record ResolvedBaseUrl(String url, boolean fromRequest) {
}

2
application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java

@ -33,6 +33,8 @@ public interface SystemSecurityService {
String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest);
ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest);
void logLoginAction(User user, Object authenticationDetails, ActionType actionType, Exception e);
void logLoginAction(User user, Object authenticationDetails, ActionType actionType, String provider, Exception e);

170
application/src/main/resources/converters/TTI/uplink/js.raw

@ -1,111 +1,73 @@
/**
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes.
*
* @param {number[]} input - The raw payload received as an array of bytes.
* @returns {Object} output - The structured output with decoded telemetry and attributes.
*/
function decodePayload(input) {
// Initialize the output object with empty attributes and telemetry for clarity.
var result = { attributes: {}, telemetry: {}};
// Detect input type and normalize to byte array.
var bytes;
if (metadata.payloadFormat == 'JSON') {
// payloadFormat is 'JSON' when The Things Industries payload formatters are configured on the application or device level.
// In that case, decoded_payload is a JSON object produced by your formatter.
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array.
// If your formatter returns pre-decoded values in a different structure,
// update this section to extract the values directly from 'parsed' instead.
var parsed = decodeToJson(input);
if (parsed.bytes == null) {
throw new Error("Payload formatter output does not contain a 'bytes' field. " +
"Update this decoder to match your formatter's output structure.");
}
bytes = parsed.bytes;
} else {
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly.
bytes = input;
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the
// integration writes them from version_ids. Any other device gets LoRaWAN Device.
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as
// attributes, not telemetry: device information and settings.
var values = {};
var attributes = {};
var history = [];
var versionIds = null;
if (metadata.payloadFormat == 'JSON') {
values = decodeToJson(payload);
if (Array.isArray(values.history)) {
values.history.forEach(function (record) {
if (record.timestamp != null) {
var ts = record.timestamp * 1000;
delete record.timestamp;
history.push({ ts: ts, values: record });
}
});
delete values.history;
}
if (Object.prototype.hasOwnProperty.call(values, 'tbVersionIds')) {
versionIds = values.tbVersionIds;
delete values.tbVersionIds;
}
// Decode serial number (SN) from the first 4 bytes of the payload.
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities.
result.attributes.sn = parseBytesToInt(bytes, 0, 4);
// Extract the timestamp from metadata (represented in milliseconds).
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed.
// Initialize an object to store decoded key/value telemetry data.
var values = {};
// Decode battery level from the 5th byte of the payload.
values.battery = parseBytesToInt(bytes, 4, 1);
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100).
values.temperature = parseBytesToInt(bytes, 5, 2) / 100.0;
// Decode saturation from the 8th byte of the payload.
values.saturation = parseBytesToInt(bytes, 7, 1);
// Combine the timestamp with values and add it to the telemetry.
result.telemetry = {
ts: timestamp,
values: values
};
// Return the fully constructed output object.
return result;
// Same logic, less code:
// return {
// attributes: {
// sn: parseBytesToInt(bytes, 0, 4)
// },
// telemetry: {
// ts: convertDateToTimestamp(extractDateFromMetadata()),
// values: {
// battery: parseBytesToInt(bytes, 4, 1),
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// saturation: parseBytesToInt(bytes, 7, 1)
// }
// }
// };
}
var result = decodePayload(payload);
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload;
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'.
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique)
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name.
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name.
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name.
// Return the final result object.
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && typeof versionIds === 'object' && versionIds !== null && !Array.isArray(versionIds)) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
if (brandId != null && modelId != null) {
attributes.brandId = brandId;
attributes.modelId = modelId;
}
}
var profile = 'LoRaWAN Device';
if (brandId != null && modelId != null) {
var model = brandId + '-' + modelId;
profile = model;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + model];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
var attributeKeys = metadata['attributes.' + model];
if (attributeKeys != null && attributeKeys != '') {
attributeKeys.split(',').forEach(function (key) {
key = key.trim();
if (key != '' && values.hasOwnProperty(key)) {
attributes[key] = values[key];
delete values[key];
}
});
}
}
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } };
if (history.length > 0) {
history.push({ ts: metadata.ts, values: values });
result.telemetry = history;
}
if (Object.keys(attributes).length > 0) {
result.attributes = attributes;
}
return result;
/**
* Converts a byte array to a string and parses it as JSON.
*
* @param {number[]} payload - The array of bytes.
* @returns {Object} - The parsed JSON object.
*/
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
/**
* Parse a slice of bytes from an array into an integer (big-endian).
*
* @param {number[]} input - The array of bytes.
* @param {number} offset - The starting index.
* @param {number} length - The number of bytes to convert.
* @returns {number} - The resulting integer.
*/
function parseBytesToInt(input, offset, length) {
var result = 0;
for (var i = offset; i < offset + length; i++) {
result = (result << 8) | (input[i] & 0xFF);
}
return result;
}

20
application/src/main/resources/converters/TTI/uplink/payload.json

@ -14,7 +14,18 @@
"session_key_id": "AYfg8rhha5n+FWx0ZaAprA==",
"f_port": 85,
"f_cnt": 5017,
"frm_payload": "Ae0DM18OTGM=",
"frm_payload": "A2fuAARofAUAAQbLAgd9qAMIfSUACXNmJwt9IAAMfTAA",
"decoded_payload": {
"temperature": 23.8,
"humidity": 62,
"pir": "trigger",
"light_level": 2,
"co2": 936,
"tvoc": 0.37,
"pressure": 1008.6,
"pm2_5": 32,
"pm10": 48
},
"rx_metadata": [{
"gateway_ids": {
"gateway_id": "eui-6A7E111A10000000",
@ -66,6 +77,13 @@
},
"received_at": "2023-05-18T08:25:25.906399073Z",
"consumed_airtime": "0.097536s",
"version_ids": {
"brand_id": "milesight-iot",
"model_id": "am308",
"hardware_version": "1.x",
"firmware_version": "1.x",
"band_id": "EU_863_870"
},
"network_ids": {
"net_id": "000013",
"tenant_id": "tenant",

138
application/src/main/resources/converters/TTI/uplink/tbel.raw

@ -1,79 +1,69 @@
/**
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes.
*
* @param {byte[]} input - The raw payload received as an array of bytes.
* @returns {Object} output - The structured output with decoded telemetry and attributes.
*/
function decodePayload(input) {
// Initialize the output object with empty attributes and telemetry for clarity.
var result = { attributes: {}, telemetry: {}};
// Detect input type and normalize to byte array
var bytes;
if (metadata.payloadFormat == 'JSON') {
// payloadFormat is 'JSON' when The Things Industries payload formatters are configured on the application or device level.
// In that case, decoded_payload is a JSON object produced by your formatter.
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array.
// If your formatter returns pre-decoded values in a different structure,
// update this section to extract the values directly from 'parsed' instead.
var parsed = decodeToJson(input);
if (parsed.bytes == null) {
throw new Error("Payload formatter output does not contain a 'bytes' field. " +
"Update this decoder to match your formatter's output structure.");
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the
// integration writes them from version_ids. Any other device gets LoRaWAN Device.
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as
// attributes, not telemetry: device information and settings.
var values = {};
var attributes = {};
var history = [];
var versionIds = null;
if (metadata.payloadFormat == "JSON") {
values = decodeToJson(payload);
if (values.history instanceof java.util.List) {
foreach (record : values.history) {
if (record.timestamp != null) {
var ts = record.timestamp * 1000;
record.remove("timestamp");
history.add({ ts: ts, values: record });
}
}
bytes = parsed.bytes;
} else {
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly.
bytes = input;
values.remove("history");
}
// Decode serial number (SN) from the first 4 bytes of the payload.
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities.
result.attributes.sn = parseBytesToInt(bytes, 0, 4);
// Extract the timestamp from metadata (represented in milliseconds).
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed.
// Combine the timestamp with decoded values and add it to the telemetry.
result.telemetry = {
ts: timestamp,
values: {
// Decode battery level from the 5th byte of the payload.
battery: parseBytesToInt(bytes, 4, 1),
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100).
temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// Decode saturation from the 8th byte of the payload.
saturation: parseBytesToInt(bytes, 7, 1)
if (values.containsKey("tbVersionIds")) {
versionIds = values.tbVersionIds;
values.remove("tbVersionIds");
}
}
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
if (brandId != null && modelId != null) {
attributes.put("brandId", brandId);
attributes.put("modelId", modelId);
}
}
var profile = "LoRaWAN Device";
if (brandId != null && modelId != null) {
var model = brandId + "-" + modelId;
profile = model;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + model];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
var attributeKeys = metadata["attributes." + model];
if (attributeKeys != null && attributeKeys != "") {
foreach (item : attributeKeys.split(",")) {
var key = item.trim();
if (key != "" && values.containsKey(key)) {
attributes.put(key, values.get(key));
values.remove(key);
}
}
};
// Return the fully constructed output object.
return result;
// Same logic, less code:
// return {
// attributes: {
// sn: parseBytesToInt(bytes, 0, 4)
// },
// telemetry: {
// ts: convertDateToTimestamp(extractDateFromMetadata()),
// values: {
// battery: parseBytesToInt(bytes, 4, 1),
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// saturation: parseBytesToInt(bytes, 7, 1)
// }
// }
// };
}
}
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } };
if (!history.isEmpty()) {
history.add({ ts: metadata.ts, values: values });
result.telemetry = history;
}
if (!attributes.isEmpty()) {
result.attributes = attributes;
}
var result = decodePayload(payload);
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload;
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'.
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique)
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name.
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name.
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name.
// Return the final result object.
return result;

169
application/src/main/resources/converters/TTN/uplink/js.raw

@ -1,110 +1,73 @@
/**
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes.
*
* @param {number[]} input - The raw payload received as an array of bytes.
* @returns {Object} output - The structured output with decoded telemetry and attributes.
*/
function decodePayload(input) {
// Initialize the output object with empty attributes and telemetry for clarity.
var result = { attributes: {}, telemetry: {}};
// Detect input type and normalize to byte array.
var bytes;
if (metadata.payloadFormat == 'JSON') {
// payloadFormat is 'JSON' when The Things Network payload formatters are configured on the application or device level.
// In that case, decoded_payload is a JSON object produced by your formatter.
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array.
// If your formatter returns pre-decoded values in a different structure,
// update this section to extract the values directly from 'parsed' instead.
var parsed = decodeToJson(input);
if (parsed.bytes == null) {
throw new Error("Payload formatter output does not contain a 'bytes' field. " +
"Update this decoder to match your formatter's output structure.");
}
bytes = parsed.bytes;
} else {
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly.
bytes = input;
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the
// integration writes them from version_ids. Any other device gets LoRaWAN Device.
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as
// attributes, not telemetry: device information and settings.
var values = {};
var attributes = {};
var history = [];
var versionIds = null;
if (metadata.payloadFormat == 'JSON') {
values = decodeToJson(payload);
if (Array.isArray(values.history)) {
values.history.forEach(function (record) {
if (record.timestamp != null) {
var ts = record.timestamp * 1000;
delete record.timestamp;
history.push({ ts: ts, values: record });
}
});
delete values.history;
}
if (Object.prototype.hasOwnProperty.call(values, 'tbVersionIds')) {
versionIds = values.tbVersionIds;
delete values.tbVersionIds;
}
// Decode serial number (SN) from the first 4 bytes of the payload.
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities.
result.attributes.sn = parseBytesToInt(bytes, 0, 4);
// Extract the timestamp from metadata (represented in milliseconds).
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed.
// Initialize an object to store decoded key/value telemetry data.
var values = {};
// Decode battery level from the 5th byte of the payload.
values.battery = parseBytesToInt(bytes, 4, 1);
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100).
values.temperature = parseBytesToInt(bytes, 5, 2) / 100.0;
// Decode saturation from the 8th byte of the payload.
values.saturation = parseBytesToInt(bytes, 7, 1);
// Combine the timestamp with values and add it to the telemetry.
result.telemetry = {
ts: timestamp,
values: values
};
// Return the fully constructed output object.
return result;
// Same logic, less code:
// return {
// attributes: {
// sn: parseBytesToInt(bytes, 0, 4)
// },
// telemetry: {
// ts: convertDateToTimestamp(extractDateFromMetadata()),
// values: {
// battery: parseBytesToInt(bytes, 4, 1),
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// saturation: parseBytesToInt(bytes, 7, 1)
// }
// }
// };
}
var result = decodePayload(payload);
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload;
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'.
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique)
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name.
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name.
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name.
// Return the final result object.
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && typeof versionIds === 'object' && versionIds !== null && !Array.isArray(versionIds)) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
if (brandId != null && modelId != null) {
attributes.brandId = brandId;
attributes.modelId = modelId;
}
}
var profile = 'LoRaWAN Device';
if (brandId != null && modelId != null) {
var model = brandId + '-' + modelId;
profile = model;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + model];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
var attributeKeys = metadata['attributes.' + model];
if (attributeKeys != null && attributeKeys != '') {
attributeKeys.split(',').forEach(function (key) {
key = key.trim();
if (key != '' && values.hasOwnProperty(key)) {
attributes[key] = values[key];
delete values[key];
}
});
}
}
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } };
if (history.length > 0) {
history.push({ ts: metadata.ts, values: values });
result.telemetry = history;
}
if (Object.keys(attributes).length > 0) {
result.attributes = attributes;
}
return result;
/**
* Converts a byte array to a string and parses it as JSON.
*
* @param {number[]} payload - The array of bytes.
* @returns {Object} - The parsed JSON object.
*/
function decodeToJson(payload) {
return JSON.parse(String.fromCharCode.apply(String, payload));
}
/**
* Parse a slice of bytes from an array into an integer (big-endian).
*
* @param {number[]} input - The array of bytes.
* @param {number} offset - The starting index.
* @param {number} length - The number of bytes to convert.
* @returns {number} - The resulting integer.
*/
function parseBytesToInt(input, offset, length) {
var result = 0;
for (var i = offset; i < offset + length; i++) {
result = (result << 8) | (input[i] & 0xFF);
}
return result;
}

20
application/src/main/resources/converters/TTN/uplink/payload.json

@ -14,7 +14,18 @@
"session_key_id": "AYfqmb0pc/1uRZv9xUydgQ==",
"f_port": 85,
"f_cnt": 10335,
"frm_payload": "Ae0DM18OTGM=",
"frm_payload": "A2fuAARofAUAAQbLAgd9qAMIfSUACXNmJwt9IAAMfTAA",
"decoded_payload": {
"temperature": 23.8,
"humidity": 62,
"pir": "trigger",
"light_level": 2,
"co2": 936,
"tvoc": 0.37,
"pressure": 1008.6,
"pm2_5": 32,
"pm10": 48
},
"rx_metadata": [{
"gateway_ids": {
"gateway_id": "eui-6a7e111a10000000",
@ -44,6 +55,13 @@
},
"received_at": "2023-05-19T05:33:35.641841782Z",
"consumed_airtime": "0.056576s",
"version_ids": {
"brand_id": "milesight-iot",
"model_id": "am308",
"hardware_version": "1.x",
"firmware_version": "1.x",
"band_id": "EU_863_870"
},
"network_ids": {
"net_id": "000013",
"tenant_id": "ttn",

138
application/src/main/resources/converters/TTN/uplink/tbel.raw

@ -1,79 +1,69 @@
/**
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes.
*
* @param {byte[]} input - The raw payload received as an array of bytes.
* @returns {Object} output - The structured output with decoded telemetry and attributes.
*/
function decodePayload(input) {
// Initialize the output object with empty attributes and telemetry for clarity.
var result = { attributes: {}, telemetry: {}};
// Detect input type and normalize to byte array
var bytes;
if (metadata.payloadFormat == 'JSON') {
// payloadFormat is 'JSON' when The Things Network payload formatters are configured on the application or device level.
// In that case, decoded_payload is a JSON object produced by your formatter.
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array.
// If your formatter returns pre-decoded values in a different structure,
// update this section to extract the values directly from 'parsed' instead.
var parsed = decodeToJson(input);
if (parsed.bytes == null) {
throw new Error("Payload formatter output does not contain a 'bytes' field. " +
"Update this decoder to match your formatter's output structure.");
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>.
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the
// integration writes them from version_ids. Any other device gets LoRaWAN Device.
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as
// attributes, not telemetry: device information and settings.
var values = {};
var attributes = {};
var history = [];
var versionIds = null;
if (metadata.payloadFormat == "JSON") {
values = decodeToJson(payload);
if (values.history instanceof java.util.List) {
foreach (record : values.history) {
if (record.timestamp != null) {
var ts = record.timestamp * 1000;
record.remove("timestamp");
history.add({ ts: ts, values: record });
}
}
bytes = parsed.bytes;
} else {
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly.
bytes = input;
values.remove("history");
}
// Decode serial number (SN) from the first 4 bytes of the payload.
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities.
result.attributes.sn = parseBytesToInt(bytes, 0, 4);
// Extract the timestamp from metadata (represented in milliseconds).
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed.
// Combine the timestamp with decoded values and add it to the telemetry.
result.telemetry = {
ts: timestamp,
values: {
// Decode battery level from the 5th byte of the payload.
battery: parseBytesToInt(bytes, 4, 1),
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100).
temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// Decode saturation from the 8th byte of the payload.
saturation: parseBytesToInt(bytes, 7, 1)
if (values.containsKey("tbVersionIds")) {
versionIds = values.tbVersionIds;
values.remove("tbVersionIds");
}
}
var brandId = metadata.brandId;
var modelId = metadata.modelId;
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) {
brandId = versionIds.brand_id;
modelId = versionIds.model_id;
if (brandId != null && modelId != null) {
attributes.put("brandId", brandId);
attributes.put("modelId", modelId);
}
}
var profile = "LoRaWAN Device";
if (brandId != null && modelId != null) {
var model = brandId + "-" + modelId;
profile = model;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + model];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
var attributeKeys = metadata["attributes." + model];
if (attributeKeys != null && attributeKeys != "") {
foreach (item : attributeKeys.split(",")) {
var key = item.trim();
if (key != "" && values.containsKey(key)) {
attributes.put(key, values.get(key));
values.remove(key);
}
}
};
// Return the fully constructed output object.
return result;
// Same logic, less code:
// return {
// attributes: {
// sn: parseBytesToInt(bytes, 0, 4)
// },
// telemetry: {
// ts: convertDateToTimestamp(extractDateFromMetadata()),
// values: {
// battery: parseBytesToInt(bytes, 4, 1),
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0,
// saturation: parseBytesToInt(bytes, 7, 1)
// }
// }
// };
}
}
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } };
if (!history.isEmpty()) {
history.add({ ts: metadata.ts, values: values });
result.telemetry = history;
}
if (!attributes.isEmpty()) {
result.attributes = attributes;
}
var result = decodePayload(payload);
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload;
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'.
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique)
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name.
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name.
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name.
// Return the final result object.
return result;

148
application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java

@ -51,6 +51,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -81,6 +82,12 @@ public class ConverterControllerTest extends AbstractControllerTest {
private static final String TTN_UPLINK_JSON_DECODER = "converter/ttn_uplink_json_decoder.raw";
private static final String LORIOT_UPLINK_DECODER_RETURN_ARRAY = "converter/loriot_uplink_decoder_array.raw";
private static final String TTN_DECODED_PAYLOAD = "payload/ttn_payload_with_decoded.json";
private static final String TTN_CUSTOM_DECODER_PAYLOAD = "payload/ttn_custom_decoder_payload.json";
private static final String TTI_CUSTOM_DECODER_PAYLOAD = "payload/tti_custom_decoder_payload.json";
private static final String DEFAULT_V2_CONFIGURATION = "ui-ngx/src/assets/converters/default-converters-v2-configuration.json";
private static final String THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD = "payload/things_stack_repository_device_payload.json";
private static final String THINGS_STACK_MANUAL_DEVICE_PAYLOAD = "payload/things_stack_manual_device_payload.json";
private static final String THINGS_STACK_FORMATTER_DEVICE_PAYLOAD = "payload/things_stack_formatter_device_payload.json";
@Before
public void beforeTest() throws Exception {
@ -785,7 +792,134 @@ public class ConverterControllerTest extends AbstractControllerTest {
DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr"));
Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTI, 2);
testDecoder(TTI_UPLINK_DECODER, getDefaultPayload(IntegrationType.TTI), expectedDecodedMessage, converter);
testDecoder(TTI_UPLINK_DECODER, readResource(TTI_CUSTOM_DECODER_PAYLOAD).orElseThrow(), expectedDecodedMessage, converter);
}
private static final String THINGS_STACK_REPOSITORY_DEVICE_RESULT = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," +
"\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560," +
"\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," +
"\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," +
"\"fPort\":85,\"bandwidth\":125000,\"spreadingFactor\":7,\"codeRate\":\"4/5\",\"frequency\":868100000,\"brandId\":\"milesight-iot\",\"modelId\":\"am308\"," +
"\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," +
"\"clusterAddress\":\"eu1.cloud.thethings.network\"}}";
@Test
public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException {
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, Map.of(), THINGS_STACK_REPOSITORY_DEVICE_RESULT);
}
@Test
public void testThingsStackDefaultConvertersTakeProfileNameFromIntegrationMetadata() throws IOException {
String expectedDecodedMessage = THINGS_STACK_REPOSITORY_DEVICE_RESULT.replace("\"profile\":\"milesight-iot-am308\"", "\"profile\":\"AM308\"");
Map<String, String> integrationMetadata = Map.of("profile.milesight-iot-am308", "AM308", "profile.milesight-iot-ws202", "WS202");
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, integrationMetadata, expectedDecodedMessage);
}
@Test
public void testThingsStackDefaultConvertersGiveManualDeviceRawData() throws IOException {
String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"manual-node\",\"profile\":\"LoRaWAN Device\",\"label\":\"manual-node\",\"group\":\"my-app\"," +
"\"telemetry\":{\"ts\":1793181600100,\"values\":{\"fCnt\":3,\"data\":\"Ae0DM18OTGM=\",\"rssi\":-70,\"snr\":7.0}}," +
"\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," +
"\"spreadingFactor\":9,\"frequency\":868300000}}";
testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, Map.of("profile.milesight-iot-am308", "AM308"), expectedDecodedMessage);
}
// temperatureUnit is not ASCII: decoded_payload reaches the decoders as UTF-8, and both must give the same text
private static final String THINGS_STACK_FORMATTER_DEVICE_RESULT = "{\"entityType\":\"DEVICE\",\"name\":\"macro-tracker-1\",\"profile\":\"lansitec-macro-tracker\",\"label\":\"macro-tracker-1\",\"group\":\"my-app\"," +
"\"telemetry\":{\"ts\":1794304800100,\"values\":{\"batteryLevel\":100,\"chargeState\":\"Charging\",\"temperatureUnit\":\"°C\",\"fCnt\":5,\"data\":\"IWQ+Az4AbFA=\",\"rssi\":-70,\"snr\":7.0}}," +
"\"attributes\":{\"brandId\":\"lansitec\",\"modelId\":\"macro-tracker\",\"eui\":\"70B3D57ED006F371\",\"deviceId\":\"macro-tracker-1\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," +
"\"spreadingFactor\":9,\"frequency\":868300000}}";
// A device added without the Repository, whose payload formatter names its model in tbVersionIds: the profile of the
// model, and the brandId and modelId attributes, as a Repository device gets them from version_ids
@Test
public void testThingsStackDefaultConvertersGiveFormatterDeviceTheModelProfileOfItsDecodedPayload() throws IOException {
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD, Map.of(), THINGS_STACK_FORMATTER_DEVICE_RESULT);
}
@Test
public void testThingsStackDefaultConvertersTakeProfileNameOfFormatterDeviceFromIntegrationMetadata() throws IOException {
String expectedDecodedMessage = THINGS_STACK_FORMATTER_DEVICE_RESULT.replace("\"profile\":\"lansitec-macro-tracker\"", "\"profile\":\"Macro tracker\"");
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD, Map.of("profile.lansitec-macro-tracker", "Macro tracker"), expectedDecodedMessage);
}
// version_ids come first: tbVersionIds of a Repository device does not change its profile, and is not telemetry either
@Test
public void testThingsStackDefaultConvertersPreferRepositoryModelToTbVersionIds() throws IOException {
ObjectNode payload = (ObjectNode) JacksonUtil.toJsonNode(readResource(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD).orElseThrow());
((ObjectNode) payload.get("uplink_message").get("decoded_payload"))
.set("tbVersionIds", JacksonUtil.toJsonNode("{\"brand_id\":\"lansitec\",\"model_id\":\"macro-tracker\"}"));
testThingsStackDefaultConvertersOnPayload(payload.toString(), Map.of(), THINGS_STACK_REPOSITORY_DEVICE_RESULT);
}
// tbVersionIds that is not an object (a text, null, a list) names no model, and is not telemetry either
@Test
public void testThingsStackDefaultConvertersIgnoreTbVersionIdsThatIsNotAnObject() throws IOException {
String expectedDecodedMessage = THINGS_STACK_FORMATTER_DEVICE_RESULT.replace("\"profile\":\"lansitec-macro-tracker\"", "\"profile\":\"LoRaWAN Device\"")
.replace("\"brandId\":\"lansitec\",\"modelId\":\"macro-tracker\",", "");
for (String tbVersionIds : List.of("\"lansitec-macro-tracker\"", "null", "[\"lansitec\",\"macro-tracker\"]")) {
ObjectNode payload = (ObjectNode) JacksonUtil.toJsonNode(readResource(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD).orElseThrow());
((ObjectNode) payload.get("uplink_message").get("decoded_payload")).set("tbVersionIds", JacksonUtil.toJsonNode(tbVersionIds));
testThingsStackDefaultConvertersOnPayload(payload.toString(), Map.of(), expectedDecodedMessage);
}
}
// The keys the integration metadata lists for the model are attributes, not telemetry; spaces around them are ignored,
// and a listed key the uplink doesn't have is skipped. The model may come from tbVersionIds
@Test
public void testThingsStackDefaultConvertersSaveTheModelsListedKeysAsAttributes() throws IOException {
String expectedDecodedMessage = THINGS_STACK_FORMATTER_DEVICE_RESULT
.replace("\"chargeState\":\"Charging\",", "")
.replace("\"attributes\":{", "\"attributes\":{\"chargeState\":\"Charging\",");
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD,
Map.of("attributes.lansitec-macro-tracker", " chargeState , firmwareVersionOfTheTracker"), expectedDecodedMessage);
}
// The list is per brand and model, not per profile name: a renamed profile keeps it. History records stay telemetry:
// temperature is in the history record (24.1) and in the latest values (24.5), and only the latest one is an attribute
@Test
public void testThingsStackDefaultConvertersTakeTheListOfARepositoryDeviceByItsModel() throws IOException {
String latestTemperature = "\"temperature\":24.5,";
assertThat(THINGS_STACK_REPOSITORY_DEVICE_RESULT.split(Pattern.quote(latestTemperature), -1)).hasSize(2);
assertThat(THINGS_STACK_REPOSITORY_DEVICE_RESULT).contains("{\"temperature\":24.1,\"co2\":550}");
String expectedDecodedMessage = THINGS_STACK_REPOSITORY_DEVICE_RESULT
.replace("\"profile\":\"milesight-iot-am308\"", "\"profile\":\"AM308\"")
.replace(latestTemperature, "")
.replace("\"attributes\":{", "\"attributes\":{\"temperature\":24.5,");
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD,
Map.of("profile.milesight-iot-am308", "AM308", "attributes.milesight-iot-am308", "temperature"), expectedDecodedMessage);
}
// The list of another model changes nothing
@Test
public void testThingsStackDefaultConvertersIgnoreTheListOfAnotherModel() throws IOException {
testThingsStackDefaultConverters(THINGS_STACK_FORMATTER_DEVICE_PAYLOAD,
Map.of("attributes.lansitec-solar-tracker", "chargeState"), THINGS_STACK_FORMATTER_DEVICE_RESULT);
}
// The TBEL and JS defaults are two copies of one script, so each of them must give this result for TTN and TTI
private void testThingsStackDefaultConverters(String payloadFile, Map<String, String> integrationMetadata, String expectedResult) throws IOException {
testThingsStackDefaultConvertersOnPayload(readResource(payloadFile).orElseThrow(), integrationMetadata, expectedResult);
}
private void testThingsStackDefaultConvertersOnPayload(String payload, Map<String, String> integrationMetadata, String expectedResult) throws IOException {
JsonNode defaultConfigurations = JacksonUtil.toJsonNode(FrontEndSource.read(DEFAULT_V2_CONFIGURATION));
for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) {
Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2);
for (ScriptLanguage scriptLang : ScriptLanguage.values()) {
String decoder = readResource("converters/" + integrationType.getDirectory() + "/uplink/" + scriptLang.name().toLowerCase() + ".raw").orElseThrow();
assertThat(JacksonUtil.toJsonNode(decodeUplink(decoder, scriptLang, payload, "{}", converter, integrationMetadata)))
.as("%s %s", integrationType, scriptLang)
.isEqualTo(JacksonUtil.toJsonNode(expectedResult));
}
}
}
@Test
@ -796,7 +930,7 @@ public class ConverterControllerTest extends AbstractControllerTest {
DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr"));
Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTN, 2);
testDecoder(TTN_UPLINK_DECODER, getDefaultPayload(IntegrationType.TTN), expectedDecodedMessage, converter);
testDecoder(TTN_UPLINK_DECODER, readResource(TTN_CUSTOM_DECODER_PAYLOAD).orElseThrow(), expectedDecodedMessage, converter);
}
@Test
@ -894,11 +1028,16 @@ public class ConverterControllerTest extends AbstractControllerTest {
}
public void testDecoder(String decoderFileName, String payloadExample, String expectedResult, Converter converter) throws IOException {
byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName));
assertThat(decodeUplink(new String(bytes), ScriptLanguage.TBEL, payloadExample, "{}", converter)).isEqualTo(expectedResult);
assertThat(decodeUplink(readResource(decoderFileName).orElseThrow(), ScriptLanguage.TBEL, payloadExample, "{}", converter)).isEqualTo(expectedResult);
}
private String decodeUplink(String decoder, ScriptLanguage scriptLang, String payloadExample, String metadata, Converter converter) {
return decodeUplink(decoder, scriptLang, payloadExample, metadata, converter, Map.of());
}
// integrationMetadata: what the integration adds to the metadata of every uplink, from its configuration
private String decodeUplink(String decoder, ScriptLanguage scriptLang, String payloadExample, String metadata, Converter converter,
Map<String, String> integrationMetadata) {
String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8));
ObjectNode inputParams = JacksonUtil.newObjectNode();
@ -918,6 +1057,7 @@ public class ConverterControllerTest extends AbstractControllerTest {
inputParams.set("payload", unwrapped.get("payload"));
}
inputParams.set("metadata",unwrapped.get("metadata"));
integrationMetadata.forEach(((ObjectNode) inputParams.get("metadata"))::put);
} else {
inputParams.set("payload", new TextNode(base64Payload));
}

851
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -0,0 +1,851 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceCredentialsService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.service.entitiy.TbLogEntityActionService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class DefaultDevicePackageUpdateServiceTest {
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
private final SecurityUser user = mock(SecurityUser.class);
private final UUID itemId = UUID.randomUUID();
private final String versionId = UUID.randomUUID().toString();
private final UUID installedVersionId = UUID.randomUUID();
private final DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID());
private final DashboardId dashboardId = new DashboardId(UUID.randomUUID());
private final DeviceId deviceId = new DeviceId(UUID.randomUUID());
private final IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
@Mock
private IotHubInstalledItemService installedItemService;
@Mock
private IotHubRestClient iotHubRestClient;
@Mock
private DevicePackageEntities packageEntities;
@Mock
private DeviceProfileService deviceProfileService;
@Mock
private DashboardService dashboardService;
@Mock
private DeviceService deviceService;
@Mock
private DeviceCredentialsService deviceCredentialsService;
@Mock
private ConverterService converterService;
@Mock
private IntegrationService integrationService;
@Mock
private TransactionTemplate transactionTemplate;
@Mock
private EntityService entityService;
@Mock
private TbLogEntityActionService logEntityActionService;
@Mock
private TbIntegrationService tbIntegrationService;
@Mock
private SubscriptionService subscriptionService;
@Mock
private TelemetrySubscriptionService telemetryService;
@Mock
private IotHubService iotHubService;
@InjectMocks
private DefaultDevicePackageUpdateService service;
private IotHubInstalledItem installedItem;
// Set when the transaction callback threw, so the transaction would roll back
private final List<RuntimeException> rolledBack = new ArrayList<>();
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(service, "entityService", entityService);
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService);
when(user.getTenantId()).thenReturn(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setSelectedInstallMethod("INTEGRATION_TTN");
descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId));
descriptor.setDashboardId(dashboardId);
// The package created these entities
descriptor.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"),
"Dashboard", stateOf(dashboardId, "created"), "Integration", stateOf(integrationId, "created")));
installedItem = new IotHubInstalledItem();
installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID()));
installedItem.setTenantId(tenantId);
installedItem.setItemId(itemId);
installedItem.setItemType("DEVICE");
installedItem.setVersion("1.0.0");
installedItem.setItemVersionId(installedVersionId);
installedItem.setDescriptor(descriptor);
when(installedItemService.findById(tenantId, installedItem.getId())).thenReturn(installedItem);
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(installedItem);
ObjectNode versionInfo = JacksonUtil.newObjectNode();
versionInfo.put("itemId", itemId.toString());
versionInfo.put("name", "AM308");
versionInfo.put("version", "1.0.1");
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
try {
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null);
} catch (RuntimeException e) {
rolledBack.add(e);
throw e;
}
});
when(packageEntities.checksum(any(), any())).thenReturn("checksum");
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.empty());
Device device = new Device(deviceId);
device.setTenantId(tenantId);
device.setName("AM308");
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>());
}
@Test
void overwritesTheEntitiesAndRecordsTheNewVersionInOneTransaction() {
DeviceProfile profile = profile(3L, "AM308 renamed");
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile);
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0));
Dashboard dashboard = dashboard(7L);
dashboard.setCustomerId(new CustomerId(UUID.randomUUID()));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard);
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")),
keep("AM308", "DEVICE", deviceId),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title"))));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<DeviceProfile> savedProfile = ArgumentCaptor.forClass(DeviceProfile.class);
verify(deviceProfileService).saveDeviceProfile(savedProfile.capture());
// Same id, the name the user gave it, the version they reviewed
assertThat(savedProfile.getValue().getId()).isEqualTo(profileId);
assertThat(savedProfile.getValue().getName()).isEqualTo("AM308 renamed");
assertThat(savedProfile.getValue().getDescription()).isEqualTo("new");
assertThat(savedProfile.getValue().getVersion()).isEqualTo(3L);
ArgumentCaptor<Dashboard> savedDashboard = ArgumentCaptor.forClass(Dashboard.class);
verify(dashboardService).saveDashboard(savedDashboard.capture());
assertThat(savedDashboard.getValue().getCustomerId()).isEqualTo(dashboard.getCustomerId());
verify(installedItemService).save(tenantId, installedItem);
assertThat(installedItem.getVersion()).isEqualTo("1.0.1");
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText())
.isEqualTo(EntityChecksum.of(savedDashboard.getValue()));
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId);
}
@Test
void keptEntity_keepsTheChecksumThePackageLeft() {
// The user changed the dashboard since: its current checksum must not become the package's
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created");
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId));
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@Test
void keptEntityOfAStepWithAnId_keepsItsChecksumUnderTheId() {
// Installed by a version whose step had no id: the entry is under the step's name
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created");
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId);
overview.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview");
}
@Test
void keptEntity_doesNotTakeTheChecksumOfAnotherEntity() {
// The entry under the step's key was recorded for an entity deleted since
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "of-the-deleted-one").put("resolution", "created");
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", UUID.randomUUID().toString()));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse();
}
@Test
void useExistingOfAPackageEntity_staysThePackages() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId);
}
@Test
void useExistingAtInstall_staysUseExisting() {
// At install the user picked their own dashboard: the install adds it to createdEntityIds too
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing");
}
@Test
void overwritingAnEntityUsedAtInstall_needsAConfirmation() {
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void sharedEntityOverwrittenByAnotherPackage_isNotChangedBySomeoneElse() {
Dashboard shared = dashboard(9L);
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null);
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot);
when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0));
// This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one
ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it");
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own));
IotHubInstalledItem other = otherPackage(Map.of("Dashboard", stateOf(dashboardId, "created").put("checksum", snapshot.checksum())));
when(installedItemService.findByTenantId(any(), any(), any(), any()))
.thenReturn(new PageData<>(List.of(installedItem, other), 1, 2, false));
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isFalse();
shared.setConfiguration(JacksonUtil.newObjectNode().put("description", "Changed by hand"));
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isTrue();
}
@Test
void entityOfAStepAVersionDropped_staysThePackages() {
// v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of());
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created");
}
@Test
void entityUsedAtInstall_staysTheUsersAfterAVersionDropsItsStep() {
// Recorded at install; the step is gone from the install state since
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setUsedExistingEntityIds(List.of(dashboardId));
installed.setInstallState(Map.of());
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void entitiesUsedAtInstall_areCarriedIntoTheDescriptor() {
// Installed before the descriptor kept them: the install state has them
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L)));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
}
@Test
void keptIntegration_getsTheStepsMetadataEntries() {
// Taken as it was at install: other packages' entries stay, the step's are merged, a null one is removed
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", stateOf(integrationId, "use-existing")));
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other").put("profile.milesight-iot-am308", "AM308"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setResolution("use-existing");
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge");
entries.putNull("profile.milesight-iot-am308");
step.setMetadata(entries);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.get("profile.other-model").asText()).isEqualTo("Other");
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
assertThat(saved.getValue()).isNotSameAs(current);
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
// The entries the step added, which a delete of the package removes; not the one it removed
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
}
@Test
void integrationOfAStepAVersionDropped_keepsItsMetadataEntries() {
// Taken as it was at install with the package's entries; the new version has no step for it
ObjectNode installed = stateOf(integrationId, "use-existing");
installed.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", installed));
Integration integration = new Integration();
integration.setId(integrationId);
when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getCreatedEntityIds()).contains(integrationId);
// A later delete that keeps the integration removes these entries
assertThat(descriptor.getInstallState().get("TTN").get("metadata"))
.isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
}
@Test
void integrationUsedByAStepNewToThePackage_isListedAsUsedAsItWas() {
// The installed version has no integration step; the new one takes the tenant's integration as it is
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId));
installed.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"),
"Dashboard", stateOf(dashboardId, "created")));
IntegrationId tenantsIntegrationId = new IntegrationId(UUID.randomUUID());
Integration current = new Integration();
current.setId(tenantsIntegrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId);
step.setResolution("use-existing");
step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
// A delete walks createdEntityIds and keeps what usedExistingEntityIds lists, removing only the package's
// entries from it (DefaultIotHubServiceTest#deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas)
assertThat(descriptor.getCreatedEntityIds()).containsOnlyOnce(tenantsIntegrationId);
assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(tenantsIntegrationId);
JsonNode state = descriptor.getInstallState().get("TTN");
assertThat(state.get("resolution").asText()).isEqualTo("use-existing");
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
}
@Test
void keptIntegrationWithTheEntriesItHas_isNotSaved() {
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any());
}
@Test
void twoStepsWithOneKey_areRejected() {
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
first.setId("main-dashboard");
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
second.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void failedStep_rollsBackAndReportsTheStep() {
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308"));
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0));
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
assertThat(rolledBack).hasSize(1);
verify(installedItemService, never()).save(any(), any());
verifyNoInteractions(logEntityActionService);
assertThat(installedItem.getVersion()).isEqualTo("1.0.0");
}
@Test
void entityChangedSinceTheCheck_isAVersionConflict() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@Test
void integrationGetsTheIdOfTheConverterCreatedInTheSameUpdate() throws Exception {
ConverterId converterId = new ConverterId(UUID.randomUUID());
when(converterService.saveConverter(any())).thenAnswer(i -> {
Converter converter = i.getArgument(0);
converter.setId(converterId);
return converter;
});
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
current.setRoutingKey("routing-key");
current.setVersion(2L);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true);
integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")),
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration)));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
assertThat(saved.getValue().getDefaultConverterId()).isEqualTo(converterId);
// The devices keep sending to the same endpoint
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key");
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app");
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key");
}
@Test
void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() {
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter current = new Converter(converterId);
current.setTenantId(tenantId);
current.setName("Uplink data converter for TTN my-app");
current.setVersion(4L);
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current);
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0));
// The package that created the converter records its checksum; one that took it as it was records none
ObjectNode created = JacksonUtil.newObjectNode().put("checksum", "before").put("resolution", "created");
created.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString()));
ObjectNode usedExisting = JacksonUtil.newObjectNode().put("resolution", "use-existing");
usedExisting.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString()));
IotHubInstalledItem creator = otherPackage(Map.of("Uplink", created));
IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting));
when(installedItemService.findByTenantId(any(), any(), any(), any()))
.thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false));
DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setConfirmed(true);
step.setDefaultConverter(true);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink");
assertThat(state.get("defaultConverter").asBoolean()).isTrue();
// The other packages keep what they recorded: check() takes the checksum of any installed package
assertThat(created.get("checksum").asText()).isEqualTo("before");
verify(installedItemService, never()).save(tenantId, creator);
verify(installedItemService, never()).save(tenantId, taker);
}
@Test
void updateOfTheInstalledVersion_keepsTheInstallStateOfTheStepsItLeavesOut() {
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter current = new Converter(converterId);
current.setTenantId(tenantId);
current.setName("Uplink data converter for TTN my-app");
current.setVersion(4L);
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current);
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0));
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
installed.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId, converterId));
installed.setInstallState(Map.of("Integration", stateOf(integrationId, "created"), "uplink", stateOf(converterId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("profileName", "am308"))));
ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0");
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo);
// ThingsBoard's default converter changed: only the converter step is sent
DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setId("uplink");
step.setDefaultConverter(true);
DeviceUpdateRequest request = request(step);
request.setVersionId(installedVersionId.toString());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
ArgumentCaptor<Converter> saved = ArgumentCaptor.forClass(Converter.class);
verify(converterService).saveConverter(saved.capture());
assertThat(state.get("uplink").get("checksum").asText()).isEqualTo(EntityChecksum.of(saved.getValue()));
assertThat(state.get("uplink").get("defaultConverter").asBoolean()).isTrue();
assertThat(state.get("Integration")).isEqualTo(stateOf(integrationId, "created"));
assertThat(state.get("Configuration").get("formValues").get("profileName").asText()).isEqualTo("am308");
verify(integrationService, never()).saveIntegration(any());
assertThat(installedItem.getItemVersionId()).isEqualTo(installedVersionId);
}
@Test
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard");
}
@Test
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
}
@Test
void theDeviceIsNeverOverwritten() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("The device and its credentials don't change on update");
verify(transactionTemplate, never()).execute(any());
}
@Test
void versionOfAnotherItem_isRejected() {
ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString());
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
}
@Test
void anotherUpdateCommittedMeanwhile_failsWithoutChanges() {
// E.g. a second click: it waits for the first one's lock and finds the package on another version
IotHubInstalledItem updated = new IotHubInstalledItem();
updated.setId(installedItem.getId());
updated.setItemVersionId(UUID.fromString(versionId));
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(converterService, never()).saveConverter(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void planOfAnotherInstalledVersion_isRejected() {
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId));
request.setFromVersionId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void integrationsNotInThePlan_areRefused() {
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED))
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Integrations feature is disabled!");
verify(transactionTemplate, never()).execute(any());
}
@Test
void attributesOfAnOverwrittenEntity_areSavedAfterCommit() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"));
step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
verify(telemetryService).saveAttributes(saved.capture());
assertThat(saved.getValue().getEntityId()).isEqualTo(dashboardId);
assertThat(saved.getValue().getScope()).isEqualTo(AttributeScope.SERVER_SCOPE);
assertThat(saved.getValue().getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString());
}
@Test
void checksum_ignoresDebugSettingsAndTheDefaultProfile() {
Converter converter = new Converter();
converter.setName("Uplink");
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {};"));
String installed = EntityChecksum.of(converter);
converter.setDebugMode(true);
converter.setDebugSettings(DebugSettings.all());
assertThat(EntityChecksum.of(converter)).isEqualTo(installed);
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {a: 1};"));
assertThat(EntityChecksum.of(converter)).isNotEqualTo(installed);
DeviceProfile profile = profile(1L, "AM308");
String profileChecksum = EntityChecksum.of(profile);
profile.setDefault(true);
assertThat(EntityChecksum.of(profile)).isEqualTo(profileChecksum);
}
@Test
void checksum_ignoresTheMetadataOfAnIntegration() {
Integration integration = new Integration();
integration.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode().put("host", "eu1.cloud.thethings.network");
configuration.set("metadata", JacksonUtil.newObjectNode());
integration.setConfiguration(configuration);
String installed = EntityChecksum.of(integration);
// Another package on the integration adds its profile name
((ObjectNode) configuration.get("metadata")).put("profile.milesight-iot-am308", "AM308");
assertThat(EntityChecksum.of(integration)).isEqualTo(installed);
assertThat(integration.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue();
configuration.put("host", "nam1.cloud.thethings.network");
assertThat(EntityChecksum.of(integration)).isNotEqualTo(installed);
}
@Test
void userMessage_showsValidationMessagesAndHidesInternalOnes() {
assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached")))
.isEqualTo("Rule chains limit reached");
assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null)))
.contains("Check the update again");
assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]")))
.isEqualTo("Failed to update the device package");
}
@Test
void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() {
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123");
ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}");
ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device));
assertThat(resolved.get("a").asText()).isEqualTo("123");
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}");
}
private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState);
IotHubInstalledItem item = new IotHubInstalledItem();
item.setId(new IotHubInstalledItemId(UUID.randomUUID()));
item.setTenantId(tenantId);
item.setItemType("DEVICE");
item.setDescriptor(descriptor);
return item;
}
private DeviceProfile profile(Long version, String name) {
DeviceProfile profile = new DeviceProfile(profileId);
profile.setTenantId(tenantId);
profile.setName(name);
profile.setVersion(version);
return profile;
}
private Dashboard dashboard(Long version) {
Dashboard dashboard = new Dashboard(dashboardId);
dashboard.setTenantId(tenantId);
dashboard.setTitle("AM308 dashboard");
dashboard.setVersion(version);
return dashboard;
}
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) {
DeviceUpdateRequest request = new DeviceUpdateRequest();
request.setVersionId(versionId);
request.setSteps(List.of(steps));
return request;
}
private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP);
step.setEntityId(id.getId());
return step;
}
private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE);
step.setEntityId(id.getId());
step.setExpectedVersion(version);
step.setEntity(entity);
return step;
}
private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) {
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE);
step.setEntity(entity);
return step;
}
private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) {
DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step();
step.setName(name);
step.setType(type);
step.setAction(action);
return step;
}
private static ObjectNode stateOf(EntityId id, String resolution) {
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", resolution);
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", id.getId().toString()));
return state;
}
}

259
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
@ -7,20 +8,38 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@ -48,6 +67,18 @@ class DefaultIotHubServiceTest {
private IotHubRestClient iotHubRestClient;
@Mock
private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
private DeviceService deviceService;
@Mock
private EntityService entityService;
@Mock
private TbDeviceService tbDeviceService;
@Mock
private DashboardService dashboardService;
@Mock
private TbDashboardService tbDashboardService;
@Mock
private IntegrationService integrationService;
@Spy
@InjectMocks
@ -411,4 +442,230 @@ class DefaultIotHubServiceTest {
assertThat(result.isRolledBack()).isFalse();
assertThat(result.getErrorMessage()).contains("install failed");
}
@Test
void deleteInstalledItem_devicePackage_keepsEntitiesAnotherDevicePackageUses() {
mockTenant();
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(deviceId, sharedDashboardId);
IotHubInstalledItem other = devicePackage(sharedDashboardId);
other.setItemName("Other package");
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
Device device = new Device(deviceId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceService).delete(device, user);
verify(dashboardService, never()).findDashboardById(any(), any());
verify(tbDashboardService, never()).delete(any(), any());
verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
}
@Test
void deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheKeptIntegration() {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(integrationId);
setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
IotHubInstalledItem other = devicePackage(integrationId);
setIntegrationState(other, integrationId, Map.of("profile.lansitec-badge", "Badge"));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
Integration current = integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom",
"profile.lansitec-badge", "Badge", "profile.added-by-user", "Mine"));
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
service.deleteInstalledItem(user, deleted.getId());
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
verify(integrationService, never()).deleteIntegration(any(), any());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge");
assertThat(metadata.get("profile.added-by-user").asText()).isEqualTo("Mine");
// A copy is saved: the integration read may be the cache's own instance
assertThat(current.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue();
}
@Test
void deleteInstalledItem_devicePackage_keepsTheMetadataEntryAnotherPackageAddedToo() {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(integrationId);
setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
IotHubInstalledItem other = devicePackage(integrationId);
setIntegrationState(other, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
service.deleteInstalledItem(user, deleted.getId());
// Nothing is left to remove once the other package's entry is subtracted: the integration isn't even read
verify(integrationService, never()).findIntegrationById(any(), any());
verify(integrationService, never()).saveIntegration(any());
verify(integrationService, never()).deleteIntegration(any(), any());
}
@Test
void deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas() {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(integrationId);
setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(integrationService.findIntegrationById(tenantId, integrationId))
.thenReturn(integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom", "profile.added-by-user", "Mine")));
service.deleteInstalledItem(user, deleted.getId());
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
verify(integrationService, never()).deleteIntegration(any(), any());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
assertThat(metadata.get("profile.added-by-user").asText()).isEqualTo("Mine");
}
@Test
void deleteInstalledItem_devicePackage_leavesTheKeptIntegrationWithoutItsEntriesAsItIs() {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(integrationId);
setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(integrationService.findIntegrationById(tenantId, integrationId))
.thenReturn(integration(integrationId, Map.of("profile.lansitec-badge", "Badge")));
service.deleteInstalledItem(user, deleted.getId());
verify(integrationService, never()).saveIntegration(any());
verify(integrationService, never()).deleteIntegration(any(), any());
}
@Test
void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID());
DeviceProfileId sharedProfileId = new DeviceProfileId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(sharedProfileId, deviceId, sharedDashboardId);
IotHubInstalledItem first = devicePackage(sharedProfileId, sharedDashboardId);
IotHubInstalledItem second = devicePackage(sharedDashboardId);
IotHubInstalledItem unrelated = devicePackage(new DeviceId(UUID.randomUUID()));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false));
when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile"));
when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).containsExactly(
new InstalledItemKeptEntities.KeptEntity(sharedProfileId, "Shared profile"),
new InstalledItemKeptEntities.KeptEntity(sharedDashboardId, "Shared dashboard"));
assertThat(kept.getUsedByItemsCount()).isEqualTo(2);
}
@Test
void deleteInstalledItem_devicePackage_keepsEntitiesTheUserHadBefore() {
mockTenant();
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(deviceId, usersDashboardId);
((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
Device device = new Device(deviceId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceService).delete(device, user);
verify(tbDashboardService, never()).delete(any(), any());
}
@Test
void findKeptEntities_devicePackage_namesTheEntitiesTheUserHadBefore() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(deviceId, usersDashboardId);
((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(usersDashboardId, "My dashboard"));
assertThat(kept.getUsedByItemsCount()).isZero();
assertThat(kept.getUsedExistingCount()).isEqualTo(1);
}
@Test
void findKeptEntities_devicePackageSharingNothing_keepsNothing() {
IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()));
IotHubInstalledItem other = devicePackage(new DeviceId(UUID.randomUUID()));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, other), 1, 2, false));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).isEmpty();
assertThat(kept.getUsedByItemsCount()).isZero();
}
@Test
void updateItemVersion_devicePackage_deletesNothing() {
mockTenant();
IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID()), new DashboardId(UUID.randomUUID()));
installed.setItemType("DEVICE");
when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed);
UpdateItemVersionResult result = service.updateItemVersion(user, installed.getId(), UUID.randomUUID().toString(), true, null);
assertThat(result.isSuccess()).isFalse();
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(tbDashboardService, never()).delete(any(), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
private void setIntegrationState(IotHubInstalledItem item, IntegrationId integrationId, Map<String, String> addedMetadata) {
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", "created");
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", integrationId.getId().toString()));
state.set("metadata", JacksonUtil.valueToTree(addedMetadata));
((DeviceInstalledItemDescriptor) item.getDescriptor()).setInstallState(Map.of("TTN", state));
}
private Integration integration(IntegrationId id, Map<String, String> metadata) {
Integration integration = new Integration(id);
integration.setTenantId(tenantId);
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.valueToTree(metadata));
integration.setConfiguration(configuration);
return integration;
}
private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setDescriptor(descriptor);
return item;
}
}

51
application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java

@ -8,11 +8,14 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
@ -30,6 +33,7 @@ import org.thingsboard.server.service.security.permission.UserPermissionsService
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@ -201,4 +205,51 @@ public class DefaultSystemSecurityServiceTest {
verify(mailService).sendAccountLockoutEmail(eq(tenantId), eq(username), eq(notificationEmail), eq(5));
}
@Test
public void resolveBaseUrlTakesRequestUrlWhenDifferentUrlsAreAllowed() {
givenGeneralSettings("https://tb.example.com", false);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080");
assertThat(baseUrl.fromRequest()).isTrue();
}
@Test
public void resolveBaseUrlTakesSettingsUrlWhenDifferentUrlsAreProhibited() {
givenGeneralSettings("https://tb.example.com", true);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("https://tb.example.com");
assertThat(baseUrl.fromRequest()).isFalse();
}
@Test
public void resolveBaseUrlFallsBackToRequestWhenSettingsUrlIsEmpty() {
givenGeneralSettings("", true);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080");
assertThat(baseUrl.fromRequest()).isTrue();
assertThat(systemSecurityService.getBaseUrl(tenantId, null, request())).isEqualTo(baseUrl.url());
}
private void givenGeneralSettings(String baseUrl, boolean prohibitDifferentUrl) {
AdminSettings generalSettings = new AdminSettings();
generalSettings.setJsonValue(JacksonUtil.newObjectNode()
.put("baseUrl", baseUrl)
.put("prohibitDifferentUrl", prohibitDifferentUrl));
when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general")).thenReturn(generalSettings);
}
private static MockHttpServletRequest request() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme("http");
request.setServerName("192.168.1.10");
request.setServerPort(8080);
return request;
}
}

15
application/src/test/resources/converters/TTI/uplink/test/default/expected.json

@ -1,17 +1,22 @@
{
"entityType": "DEVICE",
"name": "eui-1000000000000001",
"profile": "application-tti-name",
"profile": "milesight-iot-am308",
"telemetry": {
"ts": 1684398325906,
"values": {
"battery": 95,
"temperature": 36.6,
"saturation": 99
"temperature": 23.8,
"humidity": 62,
"pir": "trigger",
"light_level": 2,
"co2": 936,
"tvoc": 0.37,
"pressure": 1008.6,
"pm2_5": 32,
"pm10": 48
}
},
"attributes": {
"sn": 32310067,
"devAddr": "20000001",
"fPort": 85,
"eui": "1000000000000001"

15
application/src/test/resources/converters/TTN/uplink/test/default/expected.json

@ -1,17 +1,22 @@
{
"entityType": "DEVICE",
"name": "eui-1000000000000001",
"profile": "application-tts-name",
"profile": "milesight-iot-am308",
"telemetry": {
"ts": 1684474415641,
"values": {
"battery": 95,
"temperature": 36.6,
"saturation": 99
"temperature": 23.8,
"humidity": 62,
"pir": "trigger",
"light_level": 2,
"co2": 936,
"tvoc": 0.37,
"pressure": 1008.6,
"pm2_5": 32,
"pm10": 48
}
},
"attributes": {
"sn": 32310067,
"devAddr": "20000001",
"fPort": 85,
"eui": "1000000000000001"

43
application/src/test/resources/payload/things_stack_formatter_device_payload.json

@ -0,0 +1,43 @@
{
"end_device_ids": {
"device_id": "macro-tracker-1",
"application_ids": {
"application_id": "my-app"
},
"dev_eui": "70B3D57ED006F371"
},
"received_at": "2026-11-10T10:00:00.123Z",
"uplink_message": {
"f_port": 1,
"f_cnt": 5,
"frm_payload": "IWQ+Az4AbFA=",
"decoded_payload": {
"tbVersionIds": {
"brand_id": "lansitec",
"model_id": "macro-tracker"
},
"batteryLevel": 100,
"chargeState": "Charging",
"temperatureUnit": "°C"
},
"rx_metadata": [
{
"gateway_ids": {
"gateway_id": "ug56"
},
"rssi": -70,
"snr": 7
}
],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 9
}
},
"frequency": "868300000"
},
"received_at": "2026-11-10T10:00:00.100Z"
}
}

34
application/src/test/resources/payload/things_stack_manual_device_payload.json

@ -0,0 +1,34 @@
{
"end_device_ids": {
"device_id": "manual-node",
"application_ids": {
"application_id": "my-app"
},
"dev_eui": "70B3D57ED006F370"
},
"received_at": "2026-10-28T10:00:00.123Z",
"uplink_message": {
"f_port": 1,
"f_cnt": 3,
"frm_payload": "Ae0DM18OTGM=",
"rx_metadata": [
{
"gateway_ids": {
"gateway_id": "ug56"
},
"rssi": -70,
"snr": 7
}
],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 9
}
},
"frequency": "868300000"
},
"received_at": "2026-10-28T10:00:00.100Z"
}
}

64
application/src/test/resources/payload/things_stack_repository_device_payload.json

@ -0,0 +1,64 @@
{
"end_device_ids": {
"device_id": "am308-office",
"application_ids": {
"application_id": "my-app"
},
"dev_eui": "24E124707C481005",
"join_eui": "24E124C0002A0001",
"dev_addr": "260B1234"
},
"received_at": "2026-10-28T10:00:00.123Z",
"uplink_message": {
"f_port": 85,
"f_cnt": 12,
"frm_payload": "AXVk",
"decoded_payload": {
"battery": 95,
"temperature": 24.5,
"co2": 560,
"history": [
{
"timestamp": 1793170000,
"temperature": 24.1,
"co2": 550
}
]
},
"rx_metadata": [
{
"gateway_ids": {
"gateway_id": "ug56"
},
"rssi": -60,
"snr": 9.5,
"channel_index": 2
}
],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 7,
"coding_rate": "4/5"
}
},
"frequency": "868100000"
},
"received_at": "2026-10-28T10:00:00.100Z",
"consumed_airtime": "0.061696s",
"version_ids": {
"brand_id": "milesight-iot",
"model_id": "am308",
"hardware_version": "1.0",
"firmware_version": "1.0",
"band_id": "EU_863_870"
},
"network_ids": {
"net_id": "000013",
"tenant_id": "ttn",
"cluster_id": "eu1",
"cluster_address": "eu1.cloud.thethings.network"
}
}
}

77
application/src/test/resources/payload/tti_custom_decoder_payload.json

@ -0,0 +1,77 @@
{
"end_device_ids": {
"device_id": "eui-1000000000000001",
"application_ids": {
"application_id": "application-tti-name"
},
"dev_eui": "1000000000000001",
"join_eui": "2000000000000001",
"dev_addr": "20000001"
},
"correlation_ids": ["as:up:01H0PZDGB1NW6NAPD815NGHPF6", "gs:conn:01H0FJRSXSYT7VKNYXJ89F95XT", "gs:up:host:01H0FJRSY3MZMGPPFBQ4FZV4T8", "gs:uplink:01H0PZDG4HHGFRTXRTXD4PFTH7", "ns:uplink:01H0PZDG4JZ3BM0K6J89EQK1J7", "rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0PZDG4J02F85RYFPCNSNXCR", "rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0PZDGB081PMP806BJHNHX1A"],
"received_at": "2023-05-18T08:25:26.112483370Z",
"uplink_message": {
"session_key_id": "AYfg8rhha5n+FWx0ZaAprA==",
"f_port": 85,
"f_cnt": 5017,
"frm_payload": "Ae0DM18OTGM=",
"rx_metadata": [{
"gateway_ids": {
"gateway_id": "eui-6A7E111A10000000",
"eui": "6A7E111A10000000"
},
"time": "2023-05-18T08:25:25.885310Z",
"timestamp": 818273765,
"rssi": -24,
"channel_rssi": -24,
"snr": 12,
"frequency_offset": "671",
"uplink_token": "CiIKIAoUZXVpLTZBN0UxMTFBMTAwMDAwMDASCCThJP/+9k6eEOW7l4YDGgwI9cGXowYQ5KPhrwMgiI2rp+jpOA=",
"channel_index": 2,
"received_at": "2023-05-18T08:25:25.869324983Z"
}, {
"gateway_ids": {
"gateway_id": "packetbroker"
},
"packet_broker": {
"message_id": "01H0PZDG4MF9AYSMNY44MAVTDH",
"forwarder_net_id": "000013",
"forwarder_tenant_id": "ttn",
"forwarder_cluster_id": "eu1.cloud.thethings.network",
"forwarder_gateway_eui": "6A7E111A10000000",
"forwarder_gateway_id": "eui-6a7e111a10000000",
"home_network_net_id": "000013",
"home_network_tenant_id": "tenant",
"home_network_cluster_id": "eu1.cloud.thethings.industries"
},
"time": "2023-05-18T08:25:25.885310Z",
"rssi": -24,
"channel_rssi": -24,
"snr": 12,
"frequency_offset": "671",
"uplink_token": "eyJnIjoiWlhsS2FHSkhZMmxQYVVwQ1RWUkpORkl3VGs1VE1XTnBURU5LYkdKdFRXbFBhVXBDVFZSSk5GSXdUazVKYVhkcFlWaFphVTlwU201a01uaGhWVlJvZDFSWFVuRmlSM1JtVFcxT2RVbHBkMmxrUjBadVNXcHZhV05ZY0RKT1IyeExaREpSZVZwR1pIUmpNRXBLVlVoR2RFNVZkR3BWVTBvNUxua3paVVJTWVRaM1lXOU1kbTQwVm5sdmIyWmlPWGN1ZUhCZmVrcElaa3hIWlZadGRVUlFVeTVuYlRaVlZXRXdkakpHV0VKMGJUUjZaMjVXUkVoeGVHRjRaMlJKTlVkS1VsbERhemc1VDNCbk5rVk1iM1JDUkVZM1VWbHdZbEJDTkdOblNqWjBlbkphYUV4MFRVMHhZMVZFTTFac01XdExURUo0YURaMFExTnhhMVJsWWw4eE5FdHlVVXcyZUhsRWFFbEhlakJITXpoTE0xaFdlRzR5VUVjMk4wNUViME5WTkhoTmRrazFZVk5oWkUwd2FXVnFjR294VGtoMFduZHlZMDFxVlVGNmRsbERUazlNY2s5eFdVeFpWMk5XTG1WVFFYVkpNVkptT1U5NWRqUTNhSEoxTUZoalYxRT0iLCJhIjp7ImZuaWQiOiIwMDAwMTMiLCJmdGlkIjoidHRuIiwiZmNpZCI6ImV1MS5jbG91ZC50aGV0aGluZ3MubmV0d29yayJ9fQ==",
"received_at": "2023-05-18T08:25:25.906038642Z"
}],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 7,
"coding_rate": "4/5"
}
},
"frequency": "868500000",
"timestamp": 818273765,
"time": "2023-05-18T08:25:25.885310Z"
},
"received_at": "2023-05-18T08:25:25.906399073Z",
"consumed_airtime": "0.097536s",
"network_ids": {
"net_id": "000013",
"tenant_id": "tenant",
"cluster_id": "eu1",
"cluster_address": "eu1.cloud.thethings.industries",
"tenant_address": "tenant.eu1.cloud.thethings.industries"
}
}
}

54
application/src/test/resources/payload/ttn_custom_decoder_payload.json

@ -0,0 +1,54 @@
{
"end_device_ids": {
"device_id": "eui-1000000000000001",
"application_ids": {
"application_id": "application-tts-name"
},
"dev_eui": "1000000000000001",
"join_eui": "2000000000000001",
"dev_addr": "20000001"
},
"correlation_ids": ["as:up:01H0S7ZJQ9MQPMVY49FT3SE07M", "gs:conn:01H03BQZ9342X3Y86DJ2P704E5", "gs:up:host:01H03BQZ99EGAM52KK1300GFKN", "gs:uplink:01H0S7ZJGS6D9TJSKJN8XNTMAV", "ns:uplink:01H0S7ZJGS9KKD4HTTPKFEMWCV", "rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0S7ZJGSF3M38ZRZVTM38DEC", "rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0S7ZJQ8R2EH5AA269AKM8DX"],
"received_at": "2023-05-19T05:33:35.848446463Z",
"uplink_message": {
"session_key_id": "AYfqmb0pc/1uRZv9xUydgQ==",
"f_port": 85,
"f_cnt": 10335,
"frm_payload": "Ae0DM18OTGM=",
"rx_metadata": [{
"gateway_ids": {
"gateway_id": "eui-6a7e111a10000000",
"eui": "6A7E111A10000000"
},
"time": "2023-05-19T05:33:35.608982Z",
"timestamp": 3893546133,
"rssi": -35,
"channel_rssi": -35,
"snr": 13.2,
"frequency_offset": "69",
"uplink_token": "CiIKIAoUZXVpLTZhN2UxMTFhMTAwMDAwMDASCCThJP/+9k6eEJWZy8AOGgwIr5ScowYQvNbUsQIgiMy8y6jwpwE=",
"channel_index": 3,
"received_at": "2023-05-19T05:33:35.607383681Z"
}],
"settings": {
"data_rate": {
"lora": {
"bandwidth": 125000,
"spreading_factor": 7,
"coding_rate": "4/5"
}
},
"frequency": "867100000",
"timestamp": 3893546133,
"time": "2023-05-19T05:33:35.608982Z"
},
"received_at": "2023-05-19T05:33:35.641841782Z",
"consumed_airtime": "0.056576s",
"network_ids": {
"net_id": "000013",
"tenant_id": "ttn",
"cluster_id": "eu1",
"cluster_address": "eu1.cloud.thethings.network"
}
}
}

15
common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java

@ -0,0 +1,15 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
/**
* Where the host of a transport in the device connectivity info comes from.
*/
public enum DeviceConnectivityHostSource {
/** Set explicitly in the Device connectivity settings. */
DEVICE_CONNECTIVITY,
/** Taken from the Base URL in General settings. */
BASE_URL,
/** Taken from the address of the request. */
REQUEST
}

14
common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java

@ -13,7 +13,19 @@ public interface DeviceConnectivityService {
JsonNode findDevicePublishTelemetryCommands(String baseUrl, Device device) throws URISyntaxException;
JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException;
/**
* Resolved host and port of each enabled transport, with the source of the host.
* A blank port is replaced with the standard port of the protocol.
*/
JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException;
/**
* Same as {@link #getConnectivityInfo(String, DeviceConnectivityHostSource)}, with a base URL
* built from the request.
*/
default JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException {
return getConnectivityInfo(baseUrl, DeviceConnectivityHostSource.REQUEST);
}
Resource getPemCertFile(String protocol);

5
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.common.data.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
@ -14,6 +15,8 @@ import java.util.Map;
public class DeviceInstalledItemDescriptor implements IotHubInstalledItemDescriptor {
private List<EntityId> createdEntityIds;
// Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them
private List<EntityId> usedExistingEntityIds;
private DashboardId dashboardId;
private String selectedInstallMethod;
private Map<String, JsonNode> installState;

2
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/AbstractUplinkDataConverter.java

@ -54,7 +54,7 @@ public abstract class AbstractUplinkDataConverter extends AbstractDataConverter
protected final Map<String, Map<String, String>> currentUpdateOnlyTelemetryPerEntity = new ConcurrentHashMap<>();
protected final Map<String, Map<String, String>> currentUpdateOnlyAttributesPerEntity = new ConcurrentHashMap<>();
private ConverterUnwrapper converterUnwrapper;
protected ConverterUnwrapper converterUnwrapper;
public AbstractUplinkDataConverter(JsInvokeService jsInvokeService, TbelInvokeService tbelInvokeService, LogSettingsComponent logSettings) {
super(jsInvokeService, tbelInvokeService, logSettings);

99
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java

@ -3,15 +3,19 @@
package org.thingsboard.integration.api.converter;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.integration.api.data.UplinkMetaData;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.util.CollectionsUtil;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@ -31,28 +35,36 @@ public final class DedicatedConverterUtil {
}
public static DedicatedUplinkData parseUplinkData(DedicatedConverterConfig config, JsonObject src, UplinkMetaData metadata) {
return parseUplinkData(config, src, metadata, Collections.emptySet());
}
// String values of unwrapperKeys skip the type cast, so devAddr "01020304" stays a string.
public static DedicatedUplinkData parseUplinkData(DedicatedConverterConfig config, JsonObject src, UplinkMetaData metadata, Set<String> unwrapperKeys) {
Map<String, Object> kvMap = new HashMap<>(metadata.getKvMap());
Set<String> telemetryNoCastKeys = new HashSet<>();
Set<String> attributesNoCastKeys = new HashSet<>();
JsonElement telemetry;
if (src.has(TELEMETRY)) {
telemetry = src.get(TELEMETRY);
if (telemetry.isJsonArray()) {
JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry());
if (!telemetryFromMetadata.isEmpty()) {
telemetry.getAsJsonArray().add(telemetryFromMetadata);
}
JsonArray telemetryArray = telemetry.getAsJsonArray();
Set<String> decoderKeys = getTelemetryKeys(telemetryArray);
addMetadataTelemetry(telemetryArray, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys);
// The no-cast keys apply to every array element, so a key the decoder also sends is cast as before.
telemetryNoCastKeys.removeAll(decoderKeys);
} else if (telemetry.isJsonObject()) {
var obj = telemetry.getAsJsonObject();
if (obj.has(VALUES)) {
var values = obj.get(VALUES).getAsJsonObject();
addKvs(values, kvMap, config.getTelemetry());
addKvs(values, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys);
} else {
addKvs(obj, kvMap, config.getTelemetry());
addKvs(obj, kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys);
}
}
} else {
telemetry = addKvs(new JsonObject(), kvMap, config.getTelemetry());
telemetry = addKvs(new JsonObject(), kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys);
}
JsonObject attributes;
@ -62,7 +74,7 @@ public final class DedicatedConverterUtil {
attributes = new JsonObject();
}
addKvs(attributes, kvMap, config.getAttributes());
addKvs(attributes, kvMap, config.getAttributes(), unwrapperKeys, attributesNoCastKeys);
EntityType entityType = getProperty(src, "type", EntityType::valueOf, config::getType);
String entityName = getProperty(src, "name", () -> processTemplate(config.getName(), kvMap));
@ -83,6 +95,8 @@ public final class DedicatedConverterUtil {
.group(group)
.telemetry(telemetry)
.attributes(attributes)
.telemetryNoCastKeys(telemetryNoCastKeys)
.attributesNoCastKeys(attributesNoCastKeys)
.build();
}
@ -101,11 +115,76 @@ public final class DedicatedConverterUtil {
return defaultValue.get();
}
private static JsonObject addKvs(JsonObject kvsObj, Map<String, Object> kvMap, Set<String> keys) {
// The metadata keys join the script's element at the uplink ts, where the script's values win as in an object result.
// Without such an element they get their own one at the uplink ts: an element without ts is saved at the server time.
private static void addMetadataTelemetry(JsonArray telemetry, Map<String, Object> kvMap, Set<String> keys, Set<String> unwrapperKeys, Set<String> noCastKeys) {
Long uplinkTs = getUplinkTs(kvMap);
if (uplinkTs != null) {
for (JsonElement element : telemetry) {
if (element.isJsonObject() && isValuesAtTs(element.getAsJsonObject(), uplinkTs)) {
addKvs(element.getAsJsonObject().getAsJsonObject(VALUES), kvMap, keys, unwrapperKeys, noCastKeys);
return;
}
}
}
JsonObject values = addKvs(new JsonObject(), kvMap, keys, unwrapperKeys, noCastKeys);
if (values.isEmpty()) {
return;
}
if (uplinkTs == null) {
telemetry.add(values);
return;
}
JsonObject element = new JsonObject();
element.addProperty(TS, uplinkTs);
element.add(VALUES, values);
telemetry.add(element);
}
private static boolean isValuesAtTs(JsonObject element, long ts) {
JsonElement elementTs = element.get(TS);
if (!element.has(VALUES) || !element.get(VALUES).isJsonObject() || elementTs == null || !elementTs.isJsonPrimitive()) {
return false;
}
JsonPrimitive primitive = elementTs.getAsJsonPrimitive();
// A script passes a numeric-string metadata ts through unchanged, and the telemetry parser reads it as a long too
return (primitive.isNumber() || (primitive.isString() && StringUtils.isNumeric(primitive.getAsString())))
&& primitive.getAsLong() == ts;
}
private static Long getUplinkTs(Map<String, Object> kvMap) {
Object ts = kvMap.get(TS);
if (ts instanceof Number number) {
return number.longValue();
}
if (ts instanceof String str && StringUtils.isNumeric(str)) {
return Long.parseLong(str);
}
return null;
}
private static Set<String> getTelemetryKeys(JsonArray telemetry) {
Set<String> keys = new HashSet<>();
for (JsonElement element : telemetry) {
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
JsonElement values = obj.get(VALUES);
keys.addAll(values != null && values.isJsonObject() ? values.getAsJsonObject().keySet() : obj.keySet());
}
}
return keys;
}
private static JsonObject addKvs(JsonObject kvsObj, Map<String, Object> kvMap, Set<String> keys, Set<String> unwrapperKeys, Set<String> noCastKeys) {
if (CollectionsUtil.isNotEmpty(keys) && !kvMap.isEmpty()) {
kvMap.entrySet().stream()
.filter(e -> keys.contains(e.getKey()) && !kvsObj.has(e.getKey()))
.forEach(e -> kvsObj.add(e.getKey(), GSON.toJsonTree(e.getValue())));
.forEach(e -> {
kvsObj.add(e.getKey(), GSON.toJsonTree(e.getValue()));
if (e.getValue() instanceof String && unwrapperKeys.contains(e.getKey())) {
noCastKeys.add(e.getKey());
}
});
}
return kvsObj;
}

7
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java

@ -11,6 +11,7 @@ import org.thingsboard.integration.api.util.LogSettingsComponent;
import org.thingsboard.script.api.ScriptInvokeService;
import org.thingsboard.script.api.js.JsInvokeService;
import org.thingsboard.script.api.tbel.TbelInvokeService;
import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.script.ScriptLanguage;
@ -58,7 +59,7 @@ public class DedicatedScriptUplinkDataConverter extends AbstractUplinkDataConver
@Override
protected UplinkData parseUplinkData(JsonObject src, UplinkMetaData metadata) {
DedicatedUplinkData uplinkData = DedicatedConverterUtil.parseUplinkData(config, src, metadata);
DedicatedUplinkData uplinkData = DedicatedConverterUtil.parseUplinkData(config, src, metadata, converterUnwrapper.getKeys());
boolean isAsset = uplinkData.getEntityType() == EntityType.ASSET;
@ -95,13 +96,13 @@ public class DedicatedScriptUplinkDataConverter extends AbstractUplinkDataConver
Map<String, String> currentOnValueTelemetryUpdate = this.currentUpdateOnlyTelemetryPerEntity.getOrDefault(name, new ConcurrentHashMap<>());
Map<String, String> currentOnValueAttributesUpdate = this.currentUpdateOnlyAttributesPerEntity.getOrDefault(name, new ConcurrentHashMap<>());
TransportProtos.PostTelemetryMsg parsedTelemetry = parseTelemetry(uplinkData.getTelemetryJson());
TransportProtos.PostTelemetryMsg parsedTelemetry = JsonConverter.convertToTelemetryProto(uplinkData.getTelemetryJson(), uplinkData.getTelemetryNoCastKeys());
if (!this.updateOnlyKeys.isEmpty()) {
parsedTelemetry = filterTelemetryOnKeyValueUpdateAndUpdateMap(parsedTelemetry, currentOnValueTelemetryUpdate);
}
builder.telemetry(parsedTelemetry);
TransportProtos.PostAttributeMsg parsedAttributes = parseAttributesUpdate(uplinkData.getAttributesJson());
TransportProtos.PostAttributeMsg parsedAttributes = JsonConverter.convertToAttributesProto(uplinkData.getAttributesJson(), uplinkData.getAttributesNoCastKeys());
if (!this.updateOnlyKeys.isEmpty()) {
parsedAttributes = filterAttributeOnKeyValueUpdateAndUpdateMap(parsedAttributes, currentOnValueAttributesUpdate);
}

6
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java

@ -10,6 +10,8 @@ import lombok.Builder;
import lombok.Data;
import org.thingsboard.server.common.data.EntityType;
import java.util.Set;
@Builder
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@ -22,6 +24,10 @@ public class DedicatedUplinkData {
private final String group;
private final JsonElement telemetry;
private final JsonElement attributes;
@JsonIgnore
private final Set<String> telemetryNoCastKeys;
@JsonIgnore
private final Set<String> attributesNoCastKeys;
@JsonRawValue
public String getTelemetry() {

32
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java

@ -13,6 +13,12 @@ import java.util.Map;
public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
// Proto3 JSON writes 64-bit integers as strings, so these numeric fields arrive as "868100000" and are parsed back to numbers.
private static final ImmutableMap<String, String> INT64_KEYS_MAPPING = ImmutableMap.of(
"frequency", "/uplink_message/settings/frequency"
);
// Map 64-bit integer (int64, uint64) fields in INT64_KEYS_MAPPING, not here.
private static final ImmutableMap<String, String> KEYS_MAPPING;
static {
@ -34,7 +40,6 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
.put("spreadingFactor", "/uplink_message/settings/data_rate/lora/spreading_factor")
.put("dataRateIndex", "/uplink_message/settings/data_rate_index")
.put("codeRate", "/uplink_message/settings/coding_rate")
.put("frequency", "/uplink_message/settings/frequency")
.put("timestamp", "/uplink_message/settings/timestamp")
.put("time", "/uplink_message/settings/time")
.put("consumedAirtime", "/uplink_message/consumed_airtime")
@ -58,9 +63,25 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
.put("simulated", "/simulated")
.put("rssi", "")
.put("snr", "")
.put("channel", "")
.putAll(INT64_KEYS_MAPPING)
.build();
}
@Override
protected void addGatewayAdditionalInfo(Map<String, Object> kvMap, JsonNode payloadJson) {
super.addGatewayAdditionalInfo(kvMap, payloadJson);
JsonNode rxMetadata = findByMaxRssi(payloadJson.at(getGatewayInfoPath()));
if (rxMetadata != null && rxMetadata.has("channel_index")) {
kvMap.put("channel", rxMetadata.get("channel_index").asInt());
}
// The Things Stack moved the coding rate from the settings into the LoRa data rate
JsonNode loraCodingRate = payloadJson.at("/uplink_message/settings/data_rate/lora/coding_rate");
if (!kvMap.containsKey("codeRate") && loraCodingRate.isTextual()) {
kvMap.put("codeRate", loraCodingRate.asText());
}
}
@Override
protected String getGatewayInfoPath() {
return "/uplink_message/rx_metadata";
@ -82,6 +103,7 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
@Override
protected void postMapping(Map<String, Object> kvMap) {
INT64_KEYS_MAPPING.keySet().forEach(key -> kvMap.computeIfPresent(key, (k, value) -> value instanceof String str ? parseLong(str, value) : value));
long ts = 0;
if (kvMap.containsKey("uplinkMessageReceivedAt")) {
var uplinkMessageReceivedAtTs = parseDateToTimestamp(kvMap.get("uplinkMessageReceivedAt").toString());
@ -105,6 +127,14 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
kvMap.put("ts", ts);
}
private static Object parseLong(String str, Object defaultValue) {
try {
return Long.parseLong(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
@Override
protected ImmutableMap<String, String> getKeysMapping() {
return KEYS_MAPPING;

287
common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java

@ -2,33 +2,189 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.integration.api.converter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.integration.api.converter.wrapper.ChirpStackConverterUnwrapper;
import org.thingsboard.integration.api.converter.wrapper.ConverterUnwrapper;
import org.thingsboard.integration.api.converter.wrapper.LoriotConverterUnwrapper;
import org.thingsboard.integration.api.converter.wrapper.ThingParkConverterUnwrapper;
import org.thingsboard.integration.api.converter.wrapper.ThingsStackConverterUnwrapper;
import org.thingsboard.integration.api.data.ContentType;
import org.thingsboard.integration.api.data.UplinkData;
import org.thingsboard.integration.api.data.UplinkMetaData;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.gen.transport.TransportProtos;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.DOUBLE_V;
import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.LONG_V;
import static org.thingsboard.server.gen.transport.TransportProtos.KeyValueType.STRING_V;
public class DedicatedScriptUplinkDataConverterTest {
private DedicatedScriptUplinkDataConverter uplinkDataConverter;
private final ConverterUnwrapper thingsStackUnwrapper = new ThingsStackConverterUnwrapper();
@BeforeEach
public void startup() {
uplinkDataConverter = new DedicatedScriptUplinkDataConverter(any(), any(), any());
ReflectionTestUtils.setField(uplinkDataConverter, "converterUnwrapper", thingsStackUnwrapper);
}
@ParameterizedTest
@ValueSource(strings = {"01020304", "01a44d4c"})
public void parseUplinkDataKeepsStringIdentifiersInAttributesTest(String devAddr) throws Exception {
setConfig(Set.of("devAddr", "eui", "fCnt", "rssi", "snr", "frequency"), null);
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrapThingsStack(devAddr));
Map<String, TransportProtos.KeyValueProto> attributes = toMap(uplink.getAttributesUpdate().getKvList());
assertKv(attributes.get("devAddr"), STRING_V, devAddr);
assertKv(attributes.get("eui"), STRING_V, "1000000000000001");
assertKv(attributes.get("fCnt"), LONG_V, 101L);
assertKv(attributes.get("rssi"), LONG_V, -22L);
assertKv(attributes.get("snr"), DOUBLE_V, 11.0);
assertKv(attributes.get("frequency"), LONG_V, 868100000L);
}
@ParameterizedTest
@ValueSource(strings = {"01020304", "01a44d4c"})
public void parseUplinkDataKeepsStringIdentifiersInTelemetryTest(String devAddr) throws Exception {
setConfig(Set.of("eui"), Set.of("devAddr", "fCnt", "rssi", "snr"));
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrapThingsStack(devAddr));
Map<String, TransportProtos.KeyValueProto> telemetry = toMap(uplink.getTelemetry().getTsKvList(0).getKvList());
assertKv(telemetry.get("devAddr"), STRING_V, devAddr);
assertKv(telemetry.get("fCnt"), LONG_V, 101L);
assertKv(telemetry.get("rssi"), LONG_V, -22L);
assertKv(telemetry.get("snr"), DOUBLE_V, 11.0);
assertKv(toMap(uplink.getAttributesUpdate().getKvList()).get("eui"), STRING_V, "1000000000000001");
}
@Test
public void parseUplinkDataKeepsChirpStackStringIdentifiersTest() throws Exception {
setConfig(Set.of("devAddr", "eui", "dr", "frequency"), Set.of("rssi", "snr"));
ObjectNode payload = JacksonUtil.fromString(readPayloadFromFile("ChirpStackPayload.json"), ObjectNode.class);
payload.put("devAddr", "01020304");
((ObjectNode) payload.get("deviceInfo")).put("devEui", "1000000000000001");
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrap(new ChirpStackConverterUnwrapper(), payload));
Map<String, TransportProtos.KeyValueProto> attributes = toMap(uplink.getAttributesUpdate().getKvList());
assertKv(attributes.get("devAddr"), STRING_V, "01020304");
assertKv(attributes.get("eui"), STRING_V, "1000000000000001");
assertKv(attributes.get("dr"), LONG_V, 1L);
assertKv(attributes.get("frequency"), LONG_V, 867100000L);
Map<String, TransportProtos.KeyValueProto> telemetry = toMap(uplink.getTelemetry().getTsKvList(0).getKvList());
assertKv(telemetry.get("rssi"), LONG_V, -22L);
assertKv(telemetry.get("snr"), DOUBLE_V, 10.5);
}
@Test
public void parseUplinkDataKeepsLoriotStringIdentifiersTest() throws Exception {
setConfig(Set.of("eui", "fPort", "frequency", "dr"), Set.of("battery", "rssi"));
ObjectNode payload = JacksonUtil.fromString(readPayloadFromFile("LoriotPayload.json"), ObjectNode.class);
payload.put("EUI", "1000000000000001");
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrap(new LoriotConverterUnwrapper(), payload));
Map<String, TransportProtos.KeyValueProto> attributes = toMap(uplink.getAttributesUpdate().getKvList());
assertKv(attributes.get("eui"), STRING_V, "1000000000000001");
assertKv(attributes.get("fPort"), LONG_V, 80L);
assertKv(attributes.get("frequency"), LONG_V, 868100000L);
assertKv(attributes.get("dr"), STRING_V, "SF12 BW125 4/5");
Map<String, TransportProtos.KeyValueProto> telemetry = toMap(uplink.getTelemetry().getTsKvList(0).getKvList());
assertKv(telemetry.get("battery"), LONG_V, 143L);
assertKv(telemetry.get("rssi"), LONG_V, -49L);
}
@Test
public void parseUplinkDataKeepsThingParkStringIdentifiersTest() throws Exception {
setConfig(Set.of("devAddr", "eui", "lrcid", "fPort", "spreadingFactor", "frequency"), Set.of("rssi", "snr"));
ObjectNode payload = JacksonUtil.fromString(readPayloadFromFile("ThingsParkPayload.json"), ObjectNode.class);
ObjectNode uplinkNode = (ObjectNode) payload.get("DevEUI_uplink");
uplinkNode.put("DevAddr", "01020304");
uplinkNode.put("DevEUI", "1000000000000001");
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrap(new ThingParkConverterUnwrapper(), payload));
Map<String, TransportProtos.KeyValueProto> attributes = toMap(uplink.getAttributesUpdate().getKvList());
assertKv(attributes.get("devAddr"), STRING_V, "01020304");
assertKv(attributes.get("eui"), STRING_V, "1000000000000001");
assertKv(attributes.get("lrcid"), STRING_V, "00000211");
assertKv(attributes.get("fPort"), LONG_V, 1L);
assertKv(attributes.get("spreadingFactor"), LONG_V, 9L);
assertKv(attributes.get("frequency"), DOUBLE_V, 902.5);
Map<String, TransportProtos.KeyValueProto> telemetry = toMap(uplink.getTelemetry().getTsKvList(0).getKvList());
assertKv(telemetry.get("rssi"), DOUBLE_V, -114.0);
assertKv(telemetry.get("snr"), DOUBLE_V, 4.75);
}
@Test
public void parseUplinkDataKeepsNumericIdentifierAsNumberTest() throws Exception {
setConfig(Set.of("devAddr"), null);
ObjectNode payload = JacksonUtil.fromString(readPayloadFromFile("ThingsStackPayload.json"), ObjectNode.class);
UplinkMetaData unwrapped = thingsStackUnwrapper.unwrap(JacksonUtil.writeValueAsBytes(payload), new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond();
UplinkData uplink = uplinkDataConverter.parseUplinkData(new JsonObject(), unwrapped);
assertKv(toMap(uplink.getAttributesUpdate().getKvList()).get("devAddr"), LONG_V, 27000020L);
}
@Test
public void parseUplinkDataCastsDecoderOutputTest() throws Exception {
setConfig(Set.of("devAddr"), null);
JsonObject attributes = new JsonObject();
attributes.addProperty("devAddr", "01020304");
JsonObject uplinkJson = new JsonObject();
uplinkJson.add("attributes", attributes);
UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, unwrapThingsStack("05060708"));
assertKv(toMap(uplink.getAttributesUpdate().getKvList()).get("devAddr"), LONG_V, 1020304L);
}
@Test
public void parseUplinkDataCastsDecoderTelemetryArrayTest() throws Exception {
setConfig(null, Set.of("devAddr"));
JsonObject values = new JsonObject();
values.addProperty("devAddr", "01020304");
JsonObject decoded = new JsonObject();
decoded.addProperty("ts", 1L);
decoded.add("values", values);
JsonArray telemetry = new JsonArray();
telemetry.add(decoded);
JsonObject uplinkJson = new JsonObject();
uplinkJson.add("telemetry", telemetry);
UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, unwrapThingsStack("05060708"));
List<TransportProtos.TsKvListProto> tsKvList = uplink.getTelemetry().getTsKvListList();
assertEquals(2, tsKvList.size());
Map<String, TransportProtos.KeyValueProto> fromDecoder = toMap(tsKvList.stream().filter(tsKv -> tsKv.getTs() == 1L).findFirst().orElseThrow().getKvList());
Map<String, TransportProtos.KeyValueProto> fromMetadata = toMap(tsKvList.stream().filter(tsKv -> tsKv.getTs() != 1L).findFirst().orElseThrow().getKvList());
assertKv(fromDecoder.get("devAddr"), LONG_V, 1020304L);
assertKv(fromMetadata.get("devAddr"), LONG_V, 5060708L);
}
@Test
@ -179,6 +335,100 @@ public class DedicatedScriptUplinkDataConverterTest {
});
}
@Test
public void parseUplinkDataWithTelemetryArraySavesMetadataAtUplinkTsTest() {
DedicatedConverterConfig config = new DedicatedConverterConfig();
config.setType(EntityType.DEVICE);
config.setName("Device ${eui}");
config.setTelemetry(Set.of("rssi"));
ReflectionTestUtils.setField(uplinkDataConverter, "config", config);
long historyTs = 1793170000000L;
long uplinkTs = 1793181600100L;
JsonObject historyValues = new JsonObject();
historyValues.addProperty("temperature", 24.1);
JsonObject history = new JsonObject();
history.addProperty("ts", historyTs);
history.add("values", historyValues);
JsonArray telemetryArray = new JsonArray();
telemetryArray.add(history);
JsonObject uplinkJson = new JsonObject();
uplinkJson.add("telemetry", telemetryArray);
UplinkMetaData uplinkMetaData = new UplinkMetaData(ContentType.JSON, Map.of(
"rssi", "-60",
"eui", "24E124707C481005",
"ts", String.valueOf(uplinkTs)));
UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, uplinkMetaData);
var tsKvLists = uplink.getTelemetry().getTsKvListList();
assertEquals(2, tsKvLists.size());
assertEquals(historyTs, tsKvLists.get(0).getTs());
assertEquals(uplinkTs, tsKvLists.get(1).getTs());
assertEquals("rssi", tsKvLists.get(1).getKv(0).getKey());
}
@Test
public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtUplinkTsTest() {
testMetadataJoinsScriptElementAtUplinkTs(false);
}
@Test
public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtStringUplinkTsTest() {
testMetadataJoinsScriptElementAtUplinkTs(true);
}
private void testMetadataJoinsScriptElementAtUplinkTs(boolean scriptTsAsString) {
DedicatedConverterConfig config = new DedicatedConverterConfig();
config.setType(EntityType.DEVICE);
config.setName("Device ${eui}");
config.setTelemetry(Set.of("rssi", "data"));
ReflectionTestUtils.setField(uplinkDataConverter, "config", config);
long uplinkTs = 1793181600100L;
JsonObject currentValues = new JsonObject();
currentValues.addProperty("temperature", 24.5);
currentValues.addProperty("rssi", -50);
JsonObject current = new JsonObject();
if (scriptTsAsString) {
current.addProperty("ts", String.valueOf(uplinkTs));
} else {
current.addProperty("ts", uplinkTs);
}
current.add("values", currentValues);
JsonArray telemetryArray = new JsonArray();
telemetryArray.add(current);
JsonObject uplinkJson = new JsonObject();
uplinkJson.add("telemetry", telemetryArray);
UplinkMetaData uplinkMetaData = new UplinkMetaData(ContentType.JSON, Map.of(
"rssi", "-60",
"data", "AXVk",
"eui", "24E124707C481005",
"ts", String.valueOf(uplinkTs)));
Map<String, Object> expectedTelemetry = Map.of(
"temperature", 24.5,
"rssi", -50L,
"data", "AXVk"
);
UplinkData uplink = uplinkDataConverter.parseUplinkData(uplinkJson, uplinkMetaData);
var tsKvLists = uplink.getTelemetry().getTsKvListList();
assertEquals(1, tsKvLists.size());
assertEquals(uplinkTs, tsKvLists.get(0).getTs());
assertEquals(expectedTelemetry.size(), tsKvLists.get(0).getKvCount());
tsKvLists.get(0).getKvList().forEach(kv -> assertEquals(expectedTelemetry.get(kv.getKey()), getValue(kv)));
}
@Test
public void parseUplinkDataTest() {
DedicatedConverterConfig config = new DedicatedConverterConfig();
@ -206,6 +456,43 @@ public class DedicatedScriptUplinkDataConverterTest {
assertEquals("BE7A123456789", uplink.getDeviceLabel());
}
private void setConfig(Set<String> attributes, Set<String> telemetry) {
DedicatedConverterConfig config = new DedicatedConverterConfig();
config.setType(EntityType.DEVICE);
config.setName("Device $eui");
config.setAttributes(attributes);
config.setTelemetry(telemetry);
ReflectionTestUtils.setField(uplinkDataConverter, "config", config);
}
private UplinkMetaData unwrapThingsStack(String devAddr) throws Exception {
ObjectNode payload = JacksonUtil.fromString(readPayloadFromFile("ThingsStackPayload.json"), ObjectNode.class);
ObjectNode endDeviceIds = (ObjectNode) payload.get("end_device_ids");
endDeviceIds.put("dev_addr", devAddr);
endDeviceIds.put("dev_eui", "1000000000000001");
((ObjectNode) payload.at("/uplink_message/settings")).put("frequency", "868100000");
return thingsStackUnwrapper.unwrap(JacksonUtil.writeValueAsBytes(payload), new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond();
}
private UplinkMetaData unwrap(ConverterUnwrapper unwrapper, ObjectNode payload) throws Exception {
ReflectionTestUtils.setField(uplinkDataConverter, "converterUnwrapper", unwrapper);
return unwrapper.unwrap(JacksonUtil.writeValueAsBytes(payload), new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond();
}
private Map<String, TransportProtos.KeyValueProto> toMap(List<TransportProtos.KeyValueProto> kvList) {
return kvList.stream().collect(Collectors.toMap(TransportProtos.KeyValueProto::getKey, kv -> kv));
}
private void assertKv(TransportProtos.KeyValueProto kv, TransportProtos.KeyValueType type, Object value) {
assertEquals(type, kv.getType());
assertEquals(value, getValue(kv));
}
private String readPayloadFromFile(String fileName) throws Exception {
var uri = this.getClass().getClassLoader().getResource(fileName).toURI();
return Files.readString(Path.of(uri));
}
private Object getValue(TransportProtos.KeyValueProto kv) {
return switch (kv.getType()) {
case STRING_V -> kv.getStringV();

16
common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java

@ -196,6 +196,22 @@ public class ConverterUnwrapperTest {
assertEquals(ContentType.JSON, result.getSecond().getContentType());
}
@Test
public void thingsStackConverterWrapperTakesCodingRateFromLoraDataRateAndChannelFromStrongestGateway() throws Exception {
ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.TTN).get();
ObjectNode payloadMsg = JacksonUtil.fromString(readPayloadFromFile("ThingsStackPayload.json"), ObjectNode.class);
ObjectNode settings = (ObjectNode) payloadMsg.at("/uplink_message/settings");
settings.remove("coding_rate");
((ObjectNode) settings.at("/data_rate/lora")).put("coding_rate", "4/6");
((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/0")).put("channel_index", 3);
((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/1")).put("channel_index", 5);
Map<String, Object> kvMap = wrapper.unwrap(JacksonUtil.writeValueAsBytes(payloadMsg),
new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond().getKvMap();
assertThat(kvMap).containsEntry("codeRate", "4/6").containsEntry("channel", 3).containsEntry("rssi", -22);
}
@Test
public void thingsParkConverterWrapperTest() throws Exception {
ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.THINGPARK).get();

5
common/integration/mqtt-integrations/pom.xml

@ -70,6 +70,11 @@
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

2
common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java

@ -101,6 +101,8 @@ public class BasicMqttIntegration extends AbstractMqttIntegration<BasicMqttInteg
try {
mqttClientConfiguration = getClientConfiguration(configuration, MqttClientConfiguration.class);
log.debug("mqttClientConfiguration from JSON: {}", mqttClientConfiguration);
// The same setup as a running integration, e.g. TTN expands a region to the full host
setupConfiguration(mqttClientConfiguration);
if (mqttClientConfiguration.getConnectTimeoutSec() > ctx.getIntegrationConnectTimeoutSec() && ctx.getIntegrationConnectTimeoutSec() > 0) {
log.debug("Reduce connection timeout sec down to the limit [{}]", mqttClientConfiguration.getConnectTimeoutSec());
mqttClientConfiguration.setConnectTimeoutSec(ctx.getIntegrationConnectTimeoutSec());

62
common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java

@ -0,0 +1,62 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.integration.mqtt.ttn;
import io.netty.channel.nio.NioEventLoopGroup;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.integration.api.IntegrationContext;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationType;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TtnIntegrationCheckConnectionTest {
private NioEventLoopGroup eventLoopGroup;
private ExecutorService executor;
private IntegrationContext context;
@Before
public void setUp() {
eventLoopGroup = new NioEventLoopGroup(1);
executor = Executors.newSingleThreadExecutor();
context = Mockito.mock(IntegrationContext.class);
Mockito.when(context.getEventLoopGroup()).thenReturn(eventLoopGroup);
Mockito.when(context.getExecutorService()).thenReturn(executor);
Mockito.when(context.getIntegrationConnectTimeoutSec()).thenReturn(1);
Mockito.when(context.getMqttClientRetransmissionMaxAttempts()).thenReturn(1);
Mockito.when(context.getMqttClientRetransmissionInitialDelayMillis()).thenReturn(1000L);
Mockito.when(context.getMqttClientRetransmissionJitterFactor()).thenReturn(0.1);
}
@After
public void tearDown() {
eventLoopGroup.shutdownGracefully();
executor.shutdownNow();
}
// The check runs the same TTN setup as a running integration, which refuses empty credentials
@Test
public void checkRefusesEmptyCredentialsBeforeConnecting() {
Integration integration = new Integration();
integration.setId(new IntegrationId(UUID.randomUUID()));
integration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
integration.setType(IntegrationType.TTN);
integration.setConfiguration(JacksonUtil.toJsonNode("{\"clientConfiguration\":{\"host\":\"eu1\",\"port\":8883,"
+ "\"connectTimeoutSec\":1,\"ssl\":true,\"credentials\":{\"type\":\"basic\",\"username\":\"\",\"password\":\"\"}}}"));
ThingsboardException e = Assert.assertThrows(ThingsboardException.class,
() -> new TtnIntegration().doCheckConnection(integration, context));
Assert.assertTrue(e.getMessage(), e.getMessage().contains("Application Credentials"));
}
}

50
common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java

@ -51,10 +51,12 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Consumer;
@ -70,7 +72,7 @@ public class JsonConverter {
public static PostTelemetryMsg convertToTelemetryProto(JsonElement jsonElement, long ts) throws JsonSyntaxException {
PostTelemetryMsg.Builder builder = PostTelemetryMsg.newBuilder();
convertToTelemetry(jsonElement, ts, null, builder);
convertToTelemetry(jsonElement, ts, null, builder, Collections.emptySet());
return builder.build();
}
@ -78,6 +80,13 @@ public class JsonConverter {
return convertToTelemetryProto(jsonElement, System.currentTimeMillis());
}
// String values of noCastKeys stay strings even when type cast is enabled.
public static PostTelemetryMsg convertToTelemetryProto(JsonElement jsonElement, Set<String> noCastKeys) throws JsonSyntaxException {
PostTelemetryMsg.Builder builder = PostTelemetryMsg.newBuilder();
convertToTelemetry(jsonElement, System.currentTimeMillis(), null, builder, noCastKeys);
return builder.build();
}
public static TbPair<TransportProtos.PostTelemetryMsg, List<GatewayMetadata>> convertToGatewayTelemetry(JsonElement jsonElement, long systemTs) {
List<GatewayMetadata> metadataResult = null;
PostTelemetryMsg.Builder builder = PostTelemetryMsg.newBuilder();
@ -102,7 +111,7 @@ public class JsonConverter {
throw new JsonSyntaxException("Can't parse gateway metadata: " + metadataElem);
}
}
parseObject(systemTs, null, builder, jo);
parseObject(systemTs, null, builder, jo, Collections.emptySet());
} else {
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + je);
}
@ -121,13 +130,13 @@ public class JsonConverter {
return element;
}
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder) {
private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder, Set<String> noCastKeys) {
if (jsonElement.isJsonObject()) {
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject());
parseObject(systemTs, result, builder, jsonElement.getAsJsonObject(), noCastKeys);
} else if (jsonElement.isJsonArray()) {
jsonElement.getAsJsonArray().forEach(je -> {
if (je.isJsonObject()) {
parseObject(systemTs, result, builder, je.getAsJsonObject());
parseObject(systemTs, result, builder, je.getAsJsonObject(), noCastKeys);
} else {
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + je);
}
@ -137,12 +146,12 @@ public class JsonConverter {
}
}
private static void parseObject(long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder, JsonObject jo) {
private static void parseObject(long systemTs, Map<Long, List<KvEntry>> result, PostTelemetryMsg.Builder builder, JsonObject jo, Set<String> noCastKeys) {
try {
if (result != null) {
parseObject(result, systemTs, jo);
} else {
parseObject(builder, systemTs, jo);
parseObject(builder, systemTs, jo, noCastKeys);
}
} catch (Exception e) {
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + jo);
@ -185,9 +194,14 @@ public class JsonConverter {
}
public static PostAttributeMsg convertToAttributesProto(JsonElement jsonObject) throws JsonSyntaxException {
return convertToAttributesProto(jsonObject, Collections.emptySet());
}
// String values of noCastKeys stay strings even when type cast is enabled.
public static PostAttributeMsg convertToAttributesProto(JsonElement jsonObject, Set<String> noCastKeys) throws JsonSyntaxException {
if (jsonObject.isJsonObject()) {
PostAttributeMsg.Builder result = PostAttributeMsg.newBuilder();
List<KeyValueProto> keyValueList = parseProtoValues(jsonObject.getAsJsonObject());
List<KeyValueProto> keyValueList = parseProtoValues(jsonObject.getAsJsonObject(), noCastKeys);
result.addAllKv(keyValueList);
return result.build();
} else {
@ -205,22 +219,22 @@ public class JsonConverter {
return result;
}
private static void parseObject(PostTelemetryMsg.Builder builder, long systemTs, JsonObject jo) {
private static void parseObject(PostTelemetryMsg.Builder builder, long systemTs, JsonObject jo, Set<String> noCastKeys) {
if (jo.has("ts") && jo.has("values")) {
parseWithTs(builder, jo);
parseWithTs(builder, jo, noCastKeys);
} else {
parseWithoutTs(builder, systemTs, jo);
parseWithoutTs(builder, systemTs, jo, noCastKeys);
}
}
private static void parseWithoutTs(PostTelemetryMsg.Builder request, long systemTs, JsonObject jo) {
private static void parseWithoutTs(PostTelemetryMsg.Builder request, long systemTs, JsonObject jo, Set<String> noCastKeys) {
TsKvListProto.Builder builder = TsKvListProto.newBuilder();
builder.setTs(systemTs);
builder.addAllKv(parseProtoValues(jo));
builder.addAllKv(parseProtoValues(jo, noCastKeys));
request.addTsKvList(builder.build());
}
private static void parseWithTs(PostTelemetryMsg.Builder request, JsonObject jo) {
private static void parseWithTs(PostTelemetryMsg.Builder request, JsonObject jo, Set<String> noCastKeys) {
JsonElement tsJsonElement = jo.get("ts");
if (tsJsonElement.isJsonNull()) {
throw new JsonSyntaxException(CAN_T_PARSE_VALUE + "ts is null!");
@ -229,12 +243,12 @@ public class JsonConverter {
} else {
TsKvListProto.Builder builder = TsKvListProto.newBuilder();
builder.setTs(tsJsonElement.getAsLong());
builder.addAllKv(parseProtoValues(jo.get("values").getAsJsonObject()));
builder.addAllKv(parseProtoValues(jo.get("values").getAsJsonObject(), noCastKeys));
request.addTsKvList(builder.build());
}
}
private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject) {
private static List<KeyValueProto> parseProtoValues(JsonObject valuesObject, Set<String> noCastKeys) {
List<KeyValueProto> result = new ArrayList<>();
for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
JsonElement element = valueEntry.getValue();
@ -245,7 +259,7 @@ public class JsonConverter {
String message = String.format("String value length [%d] for key [%s] is greater than maximum allowed [%d]", value.getAsString().length(), valueEntry.getKey(), maxStringValueLength);
throw new JsonSyntaxException(message);
}
if (isTypeCastEnabled && NumberUtils.isParsable(value.getAsString())) {
if (isTypeCastEnabled && !noCastKeys.contains(valueEntry.getKey()) && NumberUtils.isParsable(value.getAsString())) {
try {
result.add(buildNumericKeyValueProto(value, valueEntry.getKey()));
} catch (RuntimeException th) {
@ -669,7 +683,7 @@ public class JsonConverter {
public static Map<Long, List<KvEntry>> convertToTelemetry(JsonElement jsonElement, long systemTs, boolean sorted) throws
JsonSyntaxException {
Map<Long, List<KvEntry>> result = sorted ? new TreeMap<>() : new HashMap<>();
convertToTelemetry(jsonElement, systemTs, result, null);
convertToTelemetry(jsonElement, systemTs, result, null, Collections.emptySet());
return result;
}

43
common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.common.adaptor;
import com.google.gson.JsonParser;
@ -9,6 +10,10 @@ import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.Isolated;
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueProto;
import org.thingsboard.server.gen.transport.TransportProtos.KeyValueType;
import java.util.Set;
@Isolated("JsonConverter static settings being modified")
public class JsonConverterTest {
@ -94,4 +99,40 @@ public class JsonConverterTest {
});
}
@Test
public void testParseAttributesProtoWithNoCastKeys() {
var json = JsonParser.parseString("{\"devAddr\": \"01020304\", \"fCnt\": \"42\", \"rssi\": -110}");
var kvList = JsonConverter.convertToAttributesProto(json, Set.of("devAddr")).getKvList();
assertKv(kvList.get(0), KeyValueType.STRING_V, "01020304");
assertKv(kvList.get(1), KeyValueType.LONG_V, "42");
assertKv(kvList.get(2), KeyValueType.LONG_V, "-110");
}
@Test
public void testParseTelemetryProtoWithNoCastKeys() {
var json = JsonParser.parseString("{\"ts\": 1000, \"values\": {\"eui\": \"1000000000000001\", \"fCnt\": \"42\", \"snr\": 9.5}}");
var tsKvList = JsonConverter.convertToTelemetryProto(json, Set.of("eui")).getTsKvList(0);
Assertions.assertEquals(1000L, tsKvList.getTs());
assertKv(tsKvList.getKv(0), KeyValueType.STRING_V, "1000000000000001");
assertKv(tsKvList.getKv(1), KeyValueType.LONG_V, "42");
assertKv(tsKvList.getKv(2), KeyValueType.DOUBLE_V, "9.5");
}
@Test
public void testParseAttributesProtoCastsNumericStrings() {
var kvList = JsonConverter.convertToAttributesProto(JsonParser.parseString("{\"devAddr\": \"01020304\"}")).getKvList();
assertKv(kvList.get(0), KeyValueType.LONG_V, "1020304");
}
private static void assertKv(KeyValueProto kv, KeyValueType type, String value) {
Assertions.assertEquals(type, kv.getType());
String actual = switch (type) {
case STRING_V -> kv.getStringV();
case LONG_V -> String.valueOf(kv.getLongV());
case DOUBLE_V -> String.valueOf(kv.getDoubleV());
default -> throw new IllegalArgumentException("Unexpected type: " + type);
};
Assertions.assertEquals(value, actual);
}
}

20
dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java

@ -63,6 +63,13 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService
public static final String DEFAULT_DEVICE_TELEMETRY_TOPIC = "v1/devices/me/telemetry";
public static final String HTTP_DEFAULT_PORT = "80";
public static final String HTTPS_DEFAULT_PORT = "443";
private static final Map<String, String> STANDARD_PORTS = Map.of(
HTTP, HTTP_DEFAULT_PORT,
HTTPS, HTTPS_DEFAULT_PORT,
MQTT, "1883",
MQTTS, "8883",
COAP, "5683",
COAPS, "5684");
private final Map<String, Resource> certs = new ConcurrentHashMap<>();
@ -199,17 +206,16 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService
}
@Override
public JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException {
public JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException {
String[] protocols = {HTTP, HTTPS, MQTT, MQTTS, COAP, COAPS};
Map<String, DeviceConnectivityInfo> result = new LinkedHashMap<>();
Map<String, ResolvedDeviceConnectivityInfo> result = new LinkedHashMap<>();
for (String protocol : protocols) {
DeviceConnectivityInfo info = getConnectivity(protocol);
if (info != null && info.isEnabled()) {
DeviceConnectivityInfo resolved = new DeviceConnectivityInfo();
resolved.setEnabled(true);
resolved.setHost(getHost(baseUrl, info, protocol));
resolved.setPort(getPort(info));
result.put(protocol, resolved);
result.put(protocol, new ResolvedDeviceConnectivityInfo(true,
getHost(baseUrl, info, protocol),
StringUtils.isBlank(info.getPort()) ? STANDARD_PORTS.get(protocol) : info.getPort(),
StringUtils.isNotBlank(info.getHost()) ? DeviceConnectivityHostSource.DEVICE_CONNECTIVITY : baseUrlSource));
}
}
return JacksonUtil.valueToTree(result);

11
dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java

@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
/**
* Host and port of an enabled transport as returned by {@link DeviceConnectivityService#getConnectivityInfo},
* with the source of the host. Kept apart from {@link DeviceConnectivityInfo}, which models the stored settings.
*/
public record ResolvedDeviceConnectivityInfo(boolean enabled, String host, String port,
DeviceConnectivityHostSource hostSource) {
}

6
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
@ -19,6 +20,9 @@ public interface IotHubInstalledItemDao extends Dao<IotHubInstalledItem> {
Optional<IotHubInstalledItem> findByTenantIdAndId(TenantId tenantId, IotHubInstalledItemId installedItemId);
// Locks the row until the end of the current transaction
Optional<IotHubInstalledItem> findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId);
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

6
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
@ -19,6 +20,9 @@ public interface IotHubInstalledItemService {
IotHubInstalledItem findById(TenantId tenantId, IotHubInstalledItemId id);
// Locks the item until the end of the current transaction, so concurrent updates of it run one after another
IotHubInstalledItem findByIdForUpdate(TenantId tenantId, IotHubInstalledItemId id);
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

8
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.iot_hub;
import lombok.RequiredArgsConstructor;
@ -37,6 +38,11 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService {
return iotHubInstalledItemDao.findByTenantIdAndId(tenantId, id).orElse(null);
}
@Override
public IotHubInstalledItem findByIdForUpdate(TenantId tenantId, IotHubInstalledItemId id) {
return iotHubInstalledItemDao.findByTenantIdAndIdForUpdate(tenantId, id).orElse(null);
}
@Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES);

6
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.sql.iot_hub;
import org.springframework.data.domain.Page;
@ -21,6 +22,9 @@ interface IotHubInstalledItemRepository extends JpaRepository<IotHubInstalledIte
Optional<IotHubInstalledItemEntity> findByTenantIdAndId(UUID tenantId, UUID id);
@Query(value = "SELECT * FROM iot_hub_installed_item i WHERE i.tenant_id = :tenantId AND i.id = :id FOR UPDATE", nativeQuery = true)
Optional<IotHubInstalledItemEntity> findByTenantIdAndIdForUpdate(@Param("tenantId") UUID tenantId, @Param("id") UUID id);
@Query("SELECT DISTINCT item.itemId FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId")
List<UUID> findInstalledItemIdsByTenantId(@Param("tenantId") UUID tenantId);

8
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.dao.sql.iot_hub;
import lombok.RequiredArgsConstructor;
@ -40,6 +41,11 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao<IotHubInstalledItemEntity
return repository.findByTenantIdAndId(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData);
}
@Override
public Optional<IotHubInstalledItem> findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId) {
return repository.findByTenantIdAndIdForUpdate(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData);
}
@Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
return DaoUtil.toPageData(repository.findByTenantId(

119
dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java

@ -0,0 +1,119 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DeviceConnectivityServiceImplTest {
private static final String BASE_URL = "http://192.168.1.10:8080";
@Mock
private AdminSettingsService adminSettingsService;
@Mock
private DeviceCredentialsService deviceCredentialsService;
@Mock
private DeviceProfileService deviceProfileService;
@InjectMocks
private DeviceConnectivityServiceImpl service;
@Test
void configuredHostIsReportedAsDeviceConnectivity() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
assertThat(mqtt.get("host").asText()).isEqualTo("10.0.0.5");
assertThat(mqtt.get("port").asText()).isEqualTo("1884");
assertThat(mqtt.get("hostSource").asText()).isEqualTo("DEVICE_CONNECTIVITY");
}
@Test
void blankHostTakesBaseUrlAndItsSource() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}""");
JsonNode fromRequest = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
JsonNode fromBaseUrl = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.BASE_URL).get("mqtt");
assertThat(fromRequest.get("host").asText()).isEqualTo("192.168.1.10");
assertThat(fromRequest.get("hostSource").asText()).isEqualTo("REQUEST");
assertThat(fromBaseUrl.get("hostSource").asText()).isEqualTo("BASE_URL");
}
@Test
void blankPortIsReplacedWithStandardPort() throws Exception {
givenConnectivity("""
{"http": {"enabled": true, "host": "", "port": ""},
"https": {"enabled": true, "host": "", "port": ""},
"mqtt": {"enabled": true, "host": "", "port": ""},
"mqtts": {"enabled": true, "host": "", "port": ""},
"coap": {"enabled": true, "host": "", "port": ""},
"coaps": {"enabled": true, "host": "", "port": ""}}""");
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST);
assertThat(info.get("http").get("port").asText()).isEqualTo("80");
assertThat(info.get("https").get("port").asText()).isEqualTo("443");
assertThat(info.get("mqtt").get("port").asText()).isEqualTo("1883");
assertThat(info.get("mqtts").get("port").asText()).isEqualTo("8883");
assertThat(info.get("coap").get("port").asText()).isEqualTo("5683");
assertThat(info.get("coaps").get("port").asText()).isEqualTo("5684");
}
@Test
void disabledProtocolIsLeftOut() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"},
"coap": {"enabled": false, "host": "", "port": "5683"}}""");
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST);
assertThat(info.has("mqtt")).isTrue();
assertThat(info.has("coap")).isFalse();
}
@Test
void responseHasTheFieldsTheUiReads() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
assertThat(mqtt.fieldNames()).toIterable()
.containsExactlyInAnyOrder("enabled", "host", "port", "hostSource");
assertThat(mqtt.get("enabled").asBoolean()).isTrue();
}
@Test
void overloadWithoutSourceReportsRequest() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL).get("mqtt");
assertThat(mqtt.get("host").asText()).isEqualTo("192.168.1.10");
assertThat(mqtt.get("hostSource").asText()).isEqualTo("REQUEST");
}
private void givenConnectivity(String json) {
AdminSettings settings = new AdminSettings();
settings.setJsonValue(JacksonUtil.toJsonNode(json));
when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "connectivity")).thenReturn(settings);
}
}

34
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -13,13 +13,13 @@ import {
MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models';
import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params';
import { InterceptorConfig } from '@core/interceptors/interceptor-config';
import { AppState } from '@core/core.state';
import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { DeviceConnectivitySettings } from '@shared/models/settings.models';
import { ResolvedDeviceConnectivitySettings } from '@shared/models/settings.models';
import { environment as env } from '@env/environment';
export function tbVersionToInt(version: string): number {
@ -170,8 +170,8 @@ export class IotHubApiService {
});
}
public getConnectivitySettings(config?: IotHubRequestConfig): Observable<DeviceConnectivitySettings> {
return this.http.get<DeviceConnectivitySettings>(
public getConnectivitySettings(config?: IotHubRequestConfig): Observable<ResolvedDeviceConnectivitySettings> {
return this.http.get<ResolvedDeviceConnectivitySettings>(
`/api/iot-hub/connectivity`,
{ params: this.buildParams(config) }
);
@ -179,7 +179,7 @@ export class IotHubApiService {
public registerDeviceInstall(
versionId: string,
descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> },
descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> },
config?: IotHubRequestConfig
): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>(
@ -269,6 +269,30 @@ export class IotHubApiService {
);
}
/** The entities of an installed device package as they are now: whether they exist, changed since, or are shared. */
public checkDeviceUpdate(installedItemId: string, config?: IotHubRequestConfig): Observable<DevicePackageEntityState[]> {
return this.http.get<DevicePackageEntityState[]>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate/check`,
{ params: this.buildParams(config) }
);
}
/** Applies a device package update in one transaction: all of it, or nothing. */
public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable<DeviceUpdateResult> {
return this.http.post<DeviceUpdateResult>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`,
request,
{ params: this.buildParams(config) }
);
}
public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> {
return this.http.get<IotHubInstalledItemKeptEntities>(
`/api/iot-hub/installedItems/${installedItemId}/keptEntities`,
{ params: this.buildParams(config) }
);
}
public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> {
return this.http.post<ItemPublishedVersionInfo[]>(
`${this.baseUrl}/api/versions/publishedVersions`,

211
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -49,17 +49,22 @@
}
@case ('form') {
<div class="tb-device-install-form flex flex-col gap-2 p-6">
<div class="tb-device-install-form p-6" [class.tb-device-install-form-checking]="connectionChecking(ws)"
[attr.inert]="connectionChecking(ws) ? '' : null">
<tb-install-form-renderer
[fields]="ws.formFields"
[formGroup]="ws.formGroup"
[resolveImagePath]="resolveImagePathFn"
[reviewMode]="reviewMode">
[reviewMode]="reviewMode"
[newFieldKeys]="ws.newFieldKeys">
</tb-install-form-renderer>
</div>
}
@case ('progress') {
@if (data.update) {
<ng-container *ngTemplateOutlet="updateRows; context: { $implicit: ws }"></ng-container>
} @else {
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) {
@ -143,6 +148,148 @@
}
}
</div>
}
}
}
</div>
</ng-template>
<!-- Update: an entity someone changed since install, which the user can save before the update overwrites it -->
<ng-template #modifiedHint let-ep>
@let hint = textWithLink('iot-hub.device-update-modified');
{{ hint.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ hint.link }}</a>{{ hint.after }}
</ng-template>
<!-- Update: the package's entities and what the update does with them -->
<ng-template #updateRows let-ws>
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) {
<div class="tb-progress-divider"></div>
}
@let plan = updatePlanOf(ep);
@let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name);
@if (ws.reviewing && plan && !plan.confirmed) {
<div class="tb-progress-row tb-progress-row-alert">
<div class="flex min-w-0 flex-1 items-start gap-4">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-warning">warning</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">{{ label }}</span>
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
</span>
}
@if (plan.shared) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@if (plan.modified) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
<ng-container *ngTemplateOutlet="modifiedHint; context: { $implicit: ep }"></ng-container>
</span>
}
</div>
</div>
<div class="flex shrink-0 gap-2">
@if (plan.existing) {
@if (ep.step.type === 'DASHBOARD') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }}
</button>
}
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep)">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
</div>
</div>
} @else if (ep.status === 'error') {
<div class="tb-progress-row tb-progress-row-error">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-error">error</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">{{ label }}</span>
@if (ep.errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ ep.errorMessage }}</span>
}
</div>
<span class="tb-progress-status tb-progress-status-failed">{{ 'iot-hub.device-install-step-error' | translate }}</span>
</div>
} @else {
<div class="tb-progress-row" [class.tb-progress-row-active]="ep.status === 'running'">
<div class="tb-progress-icon">
@switch (ep.status) {
@case ('running') {
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
}
@default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
}
}
</div>
<div class="flex min-w-0 flex-1 flex-col">
<div class="flex min-w-0 items-center gap-2">
<span class="tb-progress-label tb-progress-label-fit"
[class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="!ws.reviewing && (ep.status === 'pending' || ep.status === 'skipped')">{{ label }}</span>
@if (plan?.action === 'create' && plan.resolution !== 'use-existing') {
<span class="tb-progress-new">{{ 'iot-hub.device-update-new' | translate }}</span>
}
</div>
<!-- A confirmed warning stays visible: the status says the conflict is resolved, the hint what happens -->
@if (ws.reviewing && plan?.confirmed) {
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-existing-' + plan.resolution | translate }}</span>
}
@if (plan.shared) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@if (plan.modified) {
<span class="tb-progress-hint">
<ng-container *ngTemplateOutlet="modifiedHint; context: { $implicit: ep }"></ng-container>
</span>
}
}
</div>
<span class="tb-progress-status">
@switch (ep.status) {
@case ('running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
@case ('success') {
<span class="tb-progress-status-done">{{ updateOutcomeOf(plan) | translate }}</span>
}
@case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span>
}
@default {
@if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-no-conflicts' | translate }}</span>
}
}
}
</span>
</div>
}
}
</div>
@ -170,7 +317,14 @@
</div>
} @else {
<div class="tb-device-install-header flex items-center gap-3 py-2 pl-6 pr-2">
<h2 class="tb-device-install-title">{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}</h2>
<h2 class="tb-device-install-title">
@if (data.update) {
{{ 'iot-hub.device-update-title' | translate:{ name: packageInfo?.name || data.item.name } }}
<span class="tb-device-update-version">{{ data.update.fromVersion }} → {{ data.item.version }}</span>
} @else {
{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}
}
</h2>
<button mat-icon-button (click)="cancel()" tabindex="-1">
<mat-icon>close</mat-icon>
</button>
@ -207,7 +361,7 @@
@for (ws of wizardSteps; track ws.label) {
<mat-step [editable]="true"
[completed]="ws.completed"
[completed]="ws.completed && !ws.formGroup?.invalid"
[stepControl]="ws.type === 'form' ? ws.formGroup : null">
<ng-template matStepLabel>{{ ws.label }}</ng-template>
<ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container>
@ -224,9 +378,24 @@
}
</ng-template>
@if (data.update && currentWizardStep?.type === 'progress') {
@let step = currentWizardStep;
@if (hasUpdateError(step)) {
<div class="tb-update-banner tb-update-banner-error">
<mat-icon>error</mat-icon>
<span>{{ step.progressError }}</span>
</div>
} @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) {
<div class="tb-update-banner tb-update-banner-warning">
<mat-icon>warning</mat-icon>
<span>{{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }}</span>
</div>
}
}
<mat-dialog-actions>
@if (!isFirstWizardStep) {
<button mat-stroked-button (click)="previousStep()">{{ 'action.back' | translate }}</button>
<button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isUpdating || currentWizardStep?.checking" (click)="previousStep()">{{ 'action.back' | translate }}</button>
}
<span class="flex-1"></span>
@if (currentWizardStep; as step) {
@ -251,12 +420,38 @@
}
@case ('form') {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-stroked-button color="primary" (click)="nextStep()">
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
<button mat-stroked-button color="primary" [disabled]="connectionChecking(step)" (click)="nextStep()">
@if (connectionChecking(step)) {
<span class="flex items-center gap-2">
<mat-spinner diameter="16"></mat-spinner>
{{ 'iot-hub.checking-connection' | translate }}
</span>
} @else {
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
}
</button>
}
@case ('progress') {
@if (step.progressError) {
@if (data.update && (step.reviewing || step.updating || step.progressError)) {
@if (step.progressError && !step.updating) {
<button mat-button (click)="done()">{{ 'action.close' | translate }}</button>
<button mat-flat-button color="primary" (click)="retryUpdate(step)">
{{ 'iot-hub.device-update-try-again' | translate }}
</button>
} @else if (step.updating) {
<button mat-button disabled>{{ 'action.cancel' | translate }}</button>
<button mat-stroked-button color="primary" disabled>
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
</button>
} @else {
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary"
[disabled]="step.checking || unconfirmedUpdateWarnings(step) > 0"
(click)="runUpdate(step)">
{{ 'action.update' | translate }}
</button>
}
} @else if (step.progressError) {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-flat-button color="primary" (click)="retryEntitySteps(step)">
{{ 'action.retry' | translate }}

88
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss

@ -195,6 +195,10 @@
}
}
.tb-device-install-form-checking {
opacity: 0.6;
}
.tb-progress-divider {
width: 1px;
height: 16px;
@ -219,6 +223,11 @@
flex-wrap: wrap;
gap: 12px;
}
&.tb-progress-row-error {
background: rgba(211, 47, 47, 0.06);
align-items: flex-start;
}
}
.tb-progress-icon {
@ -242,6 +251,10 @@
.tb-progress-warning {
color: #f66716;
}
.tb-progress-error {
color: #c62828;
}
}
.tb-progress-pending-circle {
@ -290,6 +303,36 @@
&.tb-progress-label-pending {
color: rgba(0, 0, 0, 0.54);
}
// Next to a badge instead of taking the whole row
&.tb-progress-label-fit {
flex: 0 1 auto;
}
}
.tb-progress-hint {
font-size: 12px;
line-height: 16px;
letter-spacing: 0.4px;
color: rgba(0, 0, 0, 0.54);
}
.tb-progress-link {
color: #305680;
text-decoration: underline;
cursor: pointer;
}
.tb-progress-new {
flex-shrink: 0;
font-size: 12px;
font-weight: 500;
line-height: 16px;
letter-spacing: 0.4px;
color: #305680;
background: rgba(48, 86, 128, 0.08);
border-radius: 4px;
padding: 2px 8px;
}
.tb-progress-status {
@ -309,6 +352,51 @@
color: rgba(0, 0, 0, 0.54);
}
.tb-progress-status-failed {
color: #c62828;
}
.tb-device-update-version {
margin-left: 8px;
font-size: 14px;
font-weight: 400;
color: rgba(0, 0, 0, 0.54);
}
// Update: above the actions, so the list doesn't move when it goes away
.tb-update-banner {
display: flex;
align-items: center;
gap: 12px;
margin: 0 24px 16px;
padding: 12px 16px;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
line-height: 20px;
mat-icon {
flex-shrink: 0;
font-size: 20px;
width: 20px;
height: 20px;
}
&.tb-update-banner-warning {
background: rgba(246, 103, 22, 0.08);
color: #b5470b;
mat-icon {
color: #f66716;
}
}
&.tb-update-banner-error {
background: rgba(211, 47, 47, 0.06);
color: #c62828;
}
}
.tb-progress-alert-msg {
font-size: 12px;

1756
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

File diff suppressed because it is too large

160
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html

@ -7,37 +7,102 @@
-->
@if (formGroup) {
<form [formGroup]="formGroup" class="tb-install-form flex flex-col gap-4">
@for (field of fields; track field.key; let i = $index) {
<ng-container *ngTemplateOutlet="sectionsTemplate; context: { $implicit: sections }"></ng-container>
@if (advancedSections.length) {
<section class="tb-form-panel stroked no-padding">
<mat-expansion-panel class="tb-settings">
<mat-expansion-panel-header style="padding: 16px">
<mat-panel-title>{{ 'iot-hub.advanced-settings' | translate }}</mat-panel-title>
</mat-expansion-panel-header>
<div class="tb-form-panel no-border no-padding-top">
<ng-container *ngTemplateOutlet="sectionsTemplate; context: { $implicit: advancedSections }"></ng-container>
</div>
</mat-expansion-panel>
</section>
}
@if (shouldRenderGroupHeader(field, i)) {
<h4 class="tb-install-form-group-header">{{ field.group }}</h4>
<ng-template #sectionsTemplate let-sections>
@for (section of sections; track $index) {
@if (section.title) {
<section class="tb-form-panel stroked">
<h3 class="tb-form-panel-title m-0">{{ section.title }}</h3>
<ng-container *ngTemplateOutlet="rowsTemplate; context: { $implicit: section.rows }"></ng-container>
</section>
} @else {
<ng-container *ngTemplateOutlet="rowsTemplate; context: { $implicit: section.rows }"></ng-container>
}
}
</ng-template>
<ng-template #rowsTemplate let-rows>
@for (row of rows; track row.fields[0].key) {
<div class="flex flex-col gap-2">
@if (row.fields.length > 1) {
<div class="flex gap-4">
@for (field of row.fields; track field.key) {
<div class="flex min-w-0 flex-col" [class.flex-1]="!field.width"
[style.flex]="field.width ? '0 1 ' + field.width + 'px' : null">
<ng-container *ngTemplateOutlet="fieldTemplate; context: { $implicit: field, row: row }"></ng-container>
</div>
}
</div>
} @else {
<ng-container *ngTemplateOutlet="fieldTemplate; context: { $implicit: row.fields[0], row: row }"></ng-container>
}
<!-- A field with a help popup shows its hint under the row, next to the popup trigger -->
@for (field of row.fields; track field.key) {
@if (row.hasHintBox && field.helpPopupId) {
<div class="tb-form-hint tb-primary-fill flex items-center justify-between gap-5">
<div class="w-full">{{ helpTextOf(field) }}</div>
<div class="flex shrink-0"
[tb-help-popup]="field.helpPopupId"
hintMode
tb-help-popup-placement="top"
trigger-style="letter-spacing:0.25px; font-size:12px"
[tb-help-popup-style]="{maxWidth: '640px'}"
[trigger-text]="field.helpPopupText"></div>
</div>
}
}
</div>
}
</ng-template>
<ng-template #fieldTemplate let-field let-row="row">
@if (isSecretWidget(field)) {
<!-- secretSupport=true: render Secret picker (handles plaintext + Secret refs internally) -->
<tb-secret-key-input appearance="outline"
[formControlName]="field.key"
[label]="field.label"
[required]="field.required"
[hint]="field.helpText"
[hint]="helpTextOf(field)"
[inputType]="field.type === FormFieldType.PASSWORD ? 'password' : 'text'">
</tb-secret-key-input>
} @else {
<!-- typed widget -->
@switch (field.type) {
@case (FormFieldType.BOOLEAN) {
<mat-checkbox [formControlName]="field.key">{{ field.label }}</mat-checkbox>
<div class="tb-form-row">
<mat-slide-toggle class="mat-slide" [formControlName]="field.key">
@if (helpTextOf(field)) {
<div [tb-hint-tooltip-icon]="helpTextOf(field)">{{ field.label }}</div>
} @else {
{{ field.label }}
}
</mat-slide-toggle>
</div>
}
@case (FormFieldType.SELECT) {
<mat-form-field appearance="outline">
<mat-label>{{ field.label }}</mat-label>
<mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<mat-select [formControlName]="field.key">
@for (opt of field.options; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-select>
@if (field.helpText) {
<mat-hint>{{ field.helpText }}</mat-hint>
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}
@if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error>
@ -45,16 +110,19 @@
</mat-form-field>
}
@case (FormFieldType.STRING_AUTOCOMPLETE) {
<mat-form-field appearance="outline">
<mat-label>{{ field.label }}</mat-label>
<input matInput [formControlName]="field.key" [matAutocomplete]="auto">
<mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" [matAutocomplete]="auto"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
data-lpignore="true" data-1p-ignore data-bwignore>
<mat-autocomplete #auto="matAutocomplete">
@for (opt of field.options; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option>
}
</mat-autocomplete>
@if (field.helpText) {
<mat-hint>{{ field.helpText }}</mat-hint>
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}
@if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error>
@ -62,13 +130,19 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
}
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field>
}
@case (FormFieldType.PASSWORD) {
<mat-form-field appearance="outline">
<mat-label>{{ field.label }}</mat-label>
<mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [type]="passwordVisible[field.key] ? 'text' : 'password'"
[formControlName]="field.key">
[formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
autocomplete="new-password" data-lpignore="true" data-1p-ignore data-bwignore>
<button mat-icon-button matSuffix type="button"
(click)="togglePasswordVisible(field.key)">
<mat-icon>{{ passwordVisible[field.key] ? 'visibility_off' : 'visibility' }}</mat-icon>
@ -81,8 +155,8 @@
<mat-icon>autorenew</mat-icon>
</button>
}
@if (field.helpText) {
<mat-hint>{{ field.helpText }}</mat-hint>
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}
@if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error>
@ -90,14 +164,20 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
}
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field>
}
@case (FormFieldType.INTEGER) {
<mat-form-field appearance="outline">
<mat-label>{{ field.label }}</mat-label>
<input matInput type="number" [formControlName]="field.key">
@if (field.helpText) {
<mat-hint>{{ field.helpText }}</mat-hint>
<mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput type="number" [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
data-lpignore="true" data-1p-ignore data-bwignore>
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}
@if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error>
@ -105,12 +185,18 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
}
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field>
}
@default {
<mat-form-field appearance="outline">
<mat-label>{{ field.label }}</mat-label>
<input matInput [formControlName]="field.key">
<mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
autocomplete="new-username" data-lpignore="true" data-1p-ignore data-bwignore>
@if (field.randomGenerator) {
<button mat-icon-button matSuffix type="button"
[matTooltip]="'iot-hub.generate-random-value' | translate"
@ -119,8 +205,16 @@
<mat-icon>autorenew</mat-icon>
</button>
}
@if (field.helpText) {
<mat-hint>{{ field.helpText }}</mat-hint>
@if (canResetToDefault(field)) {
<button mat-icon-button matSuffix type="button"
[matTooltip]="'action.reset-default' | translate"
matTooltipPosition="above"
(click)="resetToDefault(field)">
<tb-icon>mdi:broom</tb-icon>
</button>
}
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}
@if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error>
@ -128,17 +222,17 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
}
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field>
}
}
}
@if (field.type === FormFieldType.BOOLEAN && field.helpText) {
<div class="tb-install-form-field-help">{{ field.helpText }}</div>
}
@if (field.helpImage) {
<img class="tb-install-form-field-help-image" [src]="imagePath(field.helpImage)" [alt]="field.label">
}
}
</ng-template>
</form>
}

32
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss

@ -5,25 +5,31 @@
display: block;
}
.tb-install-form-group-header {
margin: 16px 0 8px 0;
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.6);
}
.tb-install-form-secret-toggle {
margin-left: 4px;
align-self: center;
}
.tb-install-form-field-help {
font-size: 12px;
color: rgba(0, 0, 0, 0.6);
margin-top: 4px;
}
.tb-install-form-field-help-image {
max-width: 100%;
margin-top: 8px;
}
// Update: a field the installed version didn't have: a thicker outline, a tint and the label in the primary color
:host ::ng-deep .mat-mdc-form-field.tb-install-form-field-new {
.mdc-notched-outline__leading,
.mdc-notched-outline__notch,
.mdc-notched-outline__trailing {
border-color: var(--tb-primary-500);
border-width: 2px;
}
.mat-mdc-text-field-wrapper {
border-radius: 4px;
background: color-mix(in srgb, var(--tb-primary-500) 4%, transparent);
}
.mdc-floating-label,
.mat-mdc-floating-label {
color: var(--tb-primary-500);
font-weight: 500;
}
}

140
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts

@ -2,12 +2,29 @@
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import { FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models';
import { AbstractControl, UntypedFormGroup } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';
import { cleanFormFieldValue, FormFieldDefinition, FormFieldType, pastedPortOf } from '@shared/models/iot-hub/device-package.models';
import { generateSecret } from '@core/utils';
const DEFAULT_RANDOM_SIZE = 20;
/**
* Fields shown on one line. When one of them has a help popup (outside review mode), the row shows
* the field's hint in a box under it, next to the popup trigger, and its fields don't reserve space
* for a hint or an error, so the box sits right under them.
*/
interface FormRow {
fields: FormFieldDefinition[];
hasHintBox: boolean;
}
/** Consecutive rows of one group, shown in a panel with the group as its title; no title for ungrouped fields. */
interface FormSection {
title?: string;
rows: FormRow[];
}
/**
* Reusable form renderer for the device install dialog's SHOW_FORM step. Consumes
* the FormFieldDefinition[] parsed from the package's form.json directly — both
@ -32,21 +49,31 @@ export class InstallFormRendererComponent implements OnChanges {
@Input() resolveImagePath?: (path: string) => string;
/** When true, PASSWORD inputs render unmasked by default (used by review mode). */
@Input() reviewMode = false;
/** Update: the fields the installed version's form didn't have, highlighted as new. */
@Input() newFieldKeys?: Set<string>;
passwordVisible: Record<string, boolean> = {};
// Fields in render order: consecutive fields of a group form a section, and consecutive fields
// with the same `row` share one line
sections: FormSection[] = [];
// The same for the fields of the collapsed Advanced settings panel
advancedSections: FormSection[] = [];
private focusedControl: AbstractControl | null = null;
private keepFocusedError = false;
ngOnChanges(changes: SimpleChanges): void {
if (changes.fields || changes.reviewMode) {
this.passwordVisible = {};
if (this.reviewMode) {
for (const f of this.fields) {
if (f.type === FormFieldType.PASSWORD) {
this.passwordVisible[f.key] = true;
}
}
/**
* A new error shows only after the user leaves the field, so a value is not called wrong while it
* is typed. An error already shown when the user enters the field stays until the value is valid.
*/
readonly errorStateMatcher: ErrorStateMatcher = {
isErrorState: (control, form) => {
if (control && control === this.focusedControl) {
this.keepFocusedError = this.keepFocusedError && control.invalid;
return this.keepFocusedError;
}
return !!control?.invalid && (control.touched || !!form?.submitted);
}
}
};
readonly FormFieldType = FormFieldType;
@ -57,11 +84,47 @@ export class InstallFormRendererComponent implements OnChanges {
return field.secretSupport === true;
}
/** True when the previous field belonged to a different group (for header rendering). */
shouldRenderGroupHeader(field: FormFieldDefinition, index: number): boolean {
if (!field.group) return false;
if (index === 0) return true;
return this.fields[index - 1].group !== field.group;
ngOnChanges(changes: SimpleChanges): void {
// The hint boxes and the unmasked passwords depend on reviewMode too
if (changes.fields || changes.reviewMode) {
const fields = this.fields ?? [];
this.sections = this.buildSections(fields.filter(field => field.section !== 'advanced'));
this.advancedSections = this.buildSections(fields.filter(field => field.section === 'advanced'));
this.passwordVisible = {};
if (this.reviewMode) {
for (const field of fields) {
if (field.type === FormFieldType.PASSWORD) {
this.passwordVisible[field.key] = true;
}
}
}
}
}
private buildSections(fields: FormFieldDefinition[]): FormSection[] {
const sections: FormSection[] = [];
let previous: FormFieldDefinition | undefined;
for (const field of fields) {
if (!previous || field.group !== previous.group) {
sections.push({ title: field.group, rows: [] });
}
const rows = sections[sections.length - 1].rows;
const last = rows[rows.length - 1];
const hasHintBox = !!field.helpPopupId && !this.reviewMode;
if (field.row && last?.fields[0].row === field.row) {
last.fields.push(field);
last.hasHintBox ||= hasHintBox;
} else {
rows.push({ fields: [field], hasHintBox });
}
previous = field;
}
return sections;
}
/** The hint of a field that a defaultValueTemplate fills describes the filled value. */
helpTextOf(field: FormFieldDefinition): string | undefined {
return field.defaultValueTemplate && field.defaultValueTemplateHelpText ? field.defaultValueTemplateHelpText : field.helpText;
}
togglePasswordVisible(key: string): void {
@ -75,11 +138,54 @@ export class InstallFormRendererComponent implements OnChanges {
control.markAsDirty();
}
/** A resettable field the user changed shows a button that puts its defaultValue back. */
canResetToDefault(field: FormFieldDefinition): boolean {
const control = this.formGroup.controls[field.key];
return !!field.resettable && !!control?.enabled && control.value !== (field.defaultValue ?? '');
}
resetToDefault(field: FormFieldDefinition): void {
const control = this.formGroup.controls[field.key];
control.setValue(field.defaultValue ?? '');
control.markAsDirty();
}
onFocus(field: FormFieldDefinition): void {
const control = this.formGroup.controls[field.key];
this.focusedControl = control ?? null;
this.keepFocusedError = !!control?.invalid && control.touched;
}
onBlur(field: FormFieldDefinition): void {
this.focusedControl = null;
const control = this.formGroup.controls[field.key];
const port = pastedPortOf(field, control?.value);
const portControl = field.portField ? this.formGroup.controls[field.portField] : undefined;
if (port !== undefined && portControl) {
portControl.setValue(port);
portControl.markAsDirty();
}
const cleaned = cleanFormFieldValue(field, control?.value);
if (control && cleaned !== control.value) {
control.setValue(cleaned);
}
}
getPatternErrorMessage(field: FormFieldDefinition): string {
return field.validators?.[0]?.message || 'Invalid format';
}
/** True when the field fails a validator other than required and pattern (one the dialog added). */
hasFieldError(field: FormFieldDefinition): boolean {
const errors = this.formGroup.controls[field.key]?.errors;
return !!errors && Object.keys(errors).some(key => key !== 'required' && key !== 'pattern');
}
imagePath(path: string): string {
return this.resolveImagePath ? this.resolveImagePath(path) : path;
}
isNewField(field: FormFieldDefinition): boolean {
return !!this.newFieldKeys?.has(field.key);
}
}

97
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -3,23 +3,29 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable, of, EMPTY } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Observable, of, EMPTY, firstValueFrom, from } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { DialogService } from '@core/services/dialog.service';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem, IotHubInstalledItemKeptEntities } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { ConverterService } from '@core/http/converter.service';
import { Converter } from '@shared/models/converter.models';
import { HasVersion } from '@shared/models/entity.models';
import { EntityId } from '@shared/models/id/entity-id';
import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemDialogResult } from './iot-hub-add-item-dialog.component';
import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component';
import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component';
import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component';
import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component';
import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component';
import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallUpdate } from './device-install-dialog/device-install-dialog.component';
import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component';
import { IotHubBuiltInService } from './iot-hub-built-in.service';
import { isBuiltInItem } from './iot-hub-utils';
import { TbIotHubConverterUpdateDialogComponent, IotHubConverterUpdateDialogData } from './iot-hub-converter-update-dialog.component';
import { DefaultConverterUpdate, loadInstalledDevicePackages } from './iot-hub-default-converter';
/**
* What `openBuiltInOrConfirmInstall` did with a built-in item: 'handled' means nothing is left to do
@ -35,7 +41,9 @@ export class IotHubActionsService {
private dialog: MatDialog,
private dialogService: DialogService,
private translate: TranslateService,
private builtInService: IotHubBuiltInService
private builtInService: IotHubBuiltInService,
private iotHubApiService: IotHubApiService,
private converterService: ConverterService
) {}
openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number,
@ -148,6 +156,9 @@ export class IotHubActionsService {
if (!installedItem) {
return of(false);
}
if (installedItem.itemType === ItemType.DEVICE) {
return this.updateDevice(installedItem, versionId);
}
return this.dialog.open<TbIotHubUpdateDialogComponent, IotHubUpdateDialogData, string | boolean>(TbIotHubUpdateDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
@ -162,16 +173,57 @@ export class IotHubActionsService {
}).afterClosed();
}
/**
* Brings a device package's default converter to ThingsBoard's default converter now, after the user confirms it.
* The dialog opens with what the update check found: whether someone changed the converter, and which other packages use it.
*/
updateDefaultConverter(update: DefaultConverterUpdate): Observable<boolean> {
return from(this.converterUpdateDialogData(update)).pipe(
switchMap(data => this.dialog.open<TbIotHubConverterUpdateDialogComponent, IotHubConverterUpdateDialogData, boolean>(
TbIotHubConverterUpdateDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data
}).afterClosed()),
catchError(() => of(false))
);
}
private async converterUpdateDialogData(update: DefaultConverterUpdate): Promise<IotHubConverterUpdateDialogData> {
const installedItemId = update.installedItem.id.id;
const converterId = update.converter.id.id;
// The converter as it is now, not the table's copy: the dialog downloads it, and the update overwrites only this version
const [states, packages, converter] = await Promise.all([
firstValueFrom(this.iotHubApiService.checkDeviceUpdate(installedItemId)),
loadInstalledDevicePackages(this.iotHubApiService),
firstValueFrom(this.converterService.getConverter(converterId)) as Promise<Converter & HasVersion>
]);
const state = states.find(s => s.stepName === update.stateKey);
// As the server decides what is shared: the converter is one of the entities another package tracks
const usedBy = packages
.filter(item => item.id.id !== installedItemId &&
(item.descriptor as DeviceInstalledItemDescriptor)?.createdEntityIds?.some(id => id.id === converterId))
.map(item => item.itemName);
return { update: { ...update, converter }, version: converter.version ?? state?.version, modified: state?.modified === true, usedBy };
}
deleteItem(installedItem: IotHubInstalledItem): Observable<boolean> {
if (!installedItem) {
return of(false);
}
return this.dialog.open<TbIotHubDeleteDialogComponent, IotHubDeleteDialogData, boolean>(TbIotHubDeleteDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType }
}).afterClosed();
// A device package keeps what other installed packages use: the dialog opens with that already known
const keptEntities$: Observable<IotHubInstalledItemKeptEntities | null> = installedItem.itemType === 'DEVICE' ?
this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) :
of(null);
return keptEntities$.pipe(
switchMap(keptEntities => this.dialog.open<TbIotHubDeleteDialogComponent, IotHubDeleteDialogData, boolean>(TbIotHubDeleteDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType, keptEntities }
}).afterClosed())
);
}
// Reached only for items whose action mode is 'connect', i.e. never for built-in content:
@ -191,9 +243,30 @@ export class IotHubActionsService {
});
}
/**
* A device package is updated by the install wizard of the new version: its steps change what
* the package created in place, so the device and its history stay. When only texts changed,
* the wizard records the new version without opening.
*/
private updateDevice(installedItem: IotHubInstalledItem, versionId: string): Observable<string | boolean> {
return this.iotHubApiService.getVersionInfo(versionId).pipe(
switchMap(item => this.openDeviceInstallDialog(item, {
update: {
installedItemId: installedItem.id.id,
descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor,
fromVersionId: installedItem.itemVersionId,
fromVersion: installedItem.version
}
})),
map(result => result === 'installed' ? 'updated' : result),
// The request has already shown the error
catchError(() => of(false))
);
}
private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
entityGroupId?: string; customerId?: string}): Observable<any> {
entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable<any> {
return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, {
panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'],
disableClose: true,

2
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts

@ -11,6 +11,7 @@ import { TbIotHubAddItemDialogComponent } from './iot-hub-add-item-dialog.compon
import { TbIotHubInstallDialogComponent } from './iot-hub-install-dialog.component';
import { TbIotHubUpdateDialogComponent } from './iot-hub-update-dialog.component';
import { TbIotHubDeleteDialogComponent } from './iot-hub-delete-dialog.component';
import { TbIotHubConverterUpdateDialogComponent } from './iot-hub-converter-update-dialog.component';
import { TbIotHubUnpublishedWarningDialogComponent } from './iot-hub-unpublished-warning-dialog.component';
import { TbDeviceInstallDialogComponent } from './device-install-dialog/device-install-dialog.component';
import { InstallFormRendererComponent } from './device-install-dialog/install-form-renderer/install-form-renderer.component';
@ -27,6 +28,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
@NgModule({
declarations: [
TbIotHubConverterUpdateDialogComponent,
TbIotHubItemDetailDialogComponent,
TbIotHubBrowseComponent,
TbIotHubItemCardComponent,

33
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html

@ -0,0 +1,33 @@
<!--
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
SPDX-License-Identifier: BUSL-1.1
-->
<div class="flex flex-col gap-4 p-6">
<h2 class="tb-converter-update-title">{{ 'iot-hub.converter-update-title' | translate }}</h2>
<p class="tb-converter-update-text">{{ 'iot-hub.device-update-new-default-converter' | translate }}</p>
<div class="tb-converter-update-box flex flex-col gap-2">
<div class="tb-converter-update-name">{{ data.update.converter.name }}</div>
@if (data.usedBy.length) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span>
<ul class="tb-converter-update-packages">
@for (name of data.usedBy; track $index) {
<li>{{ name }}</li>
}
</ul>
}
@if (data.modified) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ modifiedHint.before }}<a class="tb-converter-update-link" href="#" (click)="$event.preventDefault(); downloadCurrent()">{{ modifiedHint.link }}</a>{{ modifiedHint.after }}
</span>
}
</div>
@if (errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ errorMessage }}</span>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">
<button mat-button (click)="cancel()" [disabled]="updating">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary" (click)="update()" [disabled]="updating">{{ 'iot-hub.update' | translate }}</button>
</div>

65
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss

@ -0,0 +1,65 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
:host {
display: block;
max-width: 600px;
}
.tb-converter-update-title {
font-size: 20px;
font-weight: 600;
line-height: 24px;
letter-spacing: 0.1px;
color: rgba(0, 0, 0, 0.87);
margin: 0;
}
.tb-converter-update-text {
font-size: 14px;
line-height: 20px;
letter-spacing: 0.2px;
color: rgba(0, 0, 0, 0.54);
margin: 0;
}
.tb-converter-update-box {
padding: 12px 16px;
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 8px;
}
.tb-converter-update-name {
font-size: 14px;
font-weight: 500;
line-height: 20px;
color: rgba(0, 0, 0, 0.87);
}
.tb-converter-update-packages {
margin: 0;
padding-left: 20px;
font-size: 12px;
line-height: 16px;
color: rgba(0, 0, 0, 0.54);
}
.tb-converter-update-link {
color: #305680;
text-decoration: underline;
cursor: pointer;
}
.tb-progress-alert-msg {
font-size: 12px;
font-weight: 400;
line-height: 16px;
letter-spacing: 0.4px;
&.tb-progress-alert-msg-warning {
color: #f66716;
}
&.tb-progress-alert-msg-error {
color: #dd2c00;
}
}

79
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts

@ -0,0 +1,79 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DefaultConverterUpdate, defaultConverterUpdateRequest } from '@home/components/iot-hub/iot-hub-default-converter';
import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils';
export interface IotHubConverterUpdateDialogData {
update: DefaultConverterUpdate;
// The version of the converter the dialog downloads: the server refuses the update if someone saved the converter since
version?: number;
// Someone changed the converter since a package installed or last updated it
modified: boolean;
// The names of the other installed packages that use the converter
usedBy: string[];
}
/**
* Brings an installed device package's default converter to ThingsBoard's default converter now, without a new version of
* the package. Closes with true once it is updated.
*/
@Component({
selector: 'tb-iot-hub-converter-update-dialog',
standalone: false,
templateUrl: './iot-hub-converter-update-dialog.component.html',
styleUrls: ['./iot-hub-converter-update-dialog.component.scss']
})
export class TbIotHubConverterUpdateDialogComponent extends DialogComponent<TbIotHubConverterUpdateDialogComponent, boolean> {
readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified'));
updating = false;
errorMessage: string | null = null;
constructor(
protected store: Store<AppState>,
protected router: Router,
protected dialogRef: MatDialogRef<TbIotHubConverterUpdateDialogComponent, boolean>,
@Inject(MAT_DIALOG_DATA) public data: IotHubConverterUpdateDialogData,
private iotHubApiService: IotHubApiService,
private translate: TranslateService
) {
super(store, router, dialogRef);
}
downloadCurrent(): void {
downloadEntityJson(this.data.update.converter, this.data.update.converter.name);
}
update(): void {
this.updating = true;
this.errorMessage = null;
this.iotHubApiService.updateDevicePackage(this.data.update.installedItem.id.id,
defaultConverterUpdateRequest(this.data.update, this.data.version), { ignoreErrors: true }).subscribe({
next: result => {
if (result.success) {
this.dialogRef.close(true);
return;
}
// Nothing was changed: the server rolled it back
this.updating = false;
this.errorMessage = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error');
},
error: error => {
this.updating = false;
this.errorMessage = requestFailureMessage(error, this.translate);
}
});
}
cancel(): void {
this.dialogRef.close(false);
}
}

128
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -0,0 +1,128 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
import { firstValueFrom } from 'rxjs';
import { ResourcesService } from '@core/services/resources.service';
import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models';
import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data';
/** An installed device package's default converter that differs from ThingsBoard's default converter now. */
export interface DefaultConverterUpdate {
installedItem: IotHubInstalledItem;
// The key of the converter's step in the package's install state
stateKey: string;
converter: Converter;
defaultConverter: Partial<Converter>;
}
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json';
// The settings of a default converter that decide what it does: the script is compared on its own
const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] =
['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys'];
/**
* The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with
* "default": true installs it. Null when ThingsBoard has no default converter settings for the type.
*/
export const loadDefaultUplinkConverter = async (resourcesService: ResourcesService, integrationType: IntegrationType,
scriptLang: ScriptLanguage, name: string): Promise<Partial<Converter> | null> => {
const configurations = await firstValueFrom(
resourcesService.loadJsonResource<Record<string, ConverterConfigV2>>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL));
const configuration = configurations?.[integrationType];
if (!configuration) {
return null;
}
const script = await firstValueFrom(resourcesService.loadJsonResource<string>(
getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2)));
return {
name,
type: ConverterType.UPLINK,
integrationType,
converterVersion: 2,
edgeTemplate: false,
// As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing
debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 },
configuration: {
...configuration,
scriptLang,
decoder: null,
tbelDecoder: null,
encoder: null,
tbelEncoder: null,
[getTargetField(ConverterType.UPLINK, scriptLang)]: script
},
additionalInfo: { description: '' }
};
};
/** True when the converter does something else than the default one: another script or other settings. */
export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial<Converter>): boolean => {
const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang);
const script = (value: string) => (value ?? '').trimEnd();
return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) ||
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null));
};
/** All installed device packages of the tenant. */
export const loadInstalledDevicePackages = async (iotHubApiService: IotHubApiService): Promise<IotHubInstalledItem[]> => {
const items: IotHubInstalledItem[] = [];
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
items.push(...page.data);
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
return items;
};
/**
* The converters device packages installed themselves as their default converter, not ones they took as they were, of
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version
* may change. The installed items table and the update dialog both decide by it.
*/
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => {
const ids = new Set<string>();
for (const item of await loadInstalledDevicePackages(iotHubApiService)) {
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) {
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') {
ids.add(state.entityOutput.id);
}
}
}
return ids;
};
/**
* The update of the installed version itself that brings its default converter to ThingsBoard's default one. It sends only
* the converter step: the server keeps the other steps, the forms and the integration's metadata as they are.
* expectedVersion is the converter's version the user reviewed.
*/
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => {
const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor;
return {
versionId: update.installedItem.itemVersionId,
fromVersionId: update.installedItem.itemVersionId,
selectedInstallMethod: descriptor.selectedInstallMethod,
installState: {},
steps: [{
name: update.converter.name,
id: update.stateKey,
type: 'UPLINK_CONVERTER',
action: 'OVERWRITE',
entityId: update.converter.id.id,
expectedVersion,
// The user confirmed it in the dialog, which names the other packages it affects
confirmed: true,
resolution: descriptor.installState?.[update.stateKey]?.resolution ?? 'created',
defaultConverter: true,
entity: update.defaultConverter
}]
};
};

8
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html

@ -1,12 +1,16 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<div class="flex flex-col gap-5 p-6">
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-delete-desc">{{ (data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc') | translate }}</p>
<p class="tb-iot-hub-delete-desc">{{ description }}</p>
@if (keptReferences) {
<tb-image-references [references]="keptReferences"></tb-image-references>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>

8
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss

@ -1,5 +1,11 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
:host {
display: block;
max-width: 600px;
}
.tb-iot-hub-delete-title {
font-size: 20px;
font-weight: 600;

27
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -1,18 +1,23 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { IotHubInstalledItem } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
import { ResourceReferences } from '@shared/models/resource.models';
import { EntityId } from '@shared/models/id/entity-id';
export interface IotHubDeleteDialogData {
installedItemId: string;
itemName: string;
itemType?: string;
keptEntities?: IotHubInstalledItemKeptEntities | null;
}
@Component({
@ -23,14 +28,30 @@ export interface IotHubDeleteDialogData {
})
export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDeleteDialogComponent, boolean> {
description: string;
// A device package keeps the entities other installed packages use, and the dialog lists them before the user confirms
keptReferences: ResourceReferences | null = null;
constructor(
protected store: Store<AppState>,
protected router: Router,
protected dialogRef: MatDialogRef<TbIotHubDeleteDialogComponent, boolean>,
@Inject(MAT_DIALOG_DATA) public data: IotHubDeleteDialogData,
private iotHubApiService: IotHubApiService
private iotHubApiService: IotHubApiService,
private translate: TranslateService
) {
super(store, router, dialogRef);
const kept = data.keptEntities;
if (kept?.entities.length) {
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
// Kept because other packages use them, because the user had them before the package, or both
const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' :
!kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used';
this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length });
} else {
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
}
}
confirm(): void {

55
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html

@ -1,7 +1,8 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<div class="tb-installed-table-container flex flex-1 flex-col overflow-hidden rounded-lg">
@ -41,29 +42,26 @@
<th mat-header-cell *matHeaderCellDef>@if (updatesChecked) { {{ 'iot-hub.updates' | translate }} }</th>
<td mat-cell *matCellDef="let item">
@if (updatesChecked) {
@if (getPublishedVersionInfo(item); as pubInfo) {
@if (pubInfo.publishedVersionId !== item.itemVersionId) {
<div class="flex items-center gap-3">
@if (!itemVersion) {
<button class="tb-installed-version-btn" (click)="viewUpdateDetails(pubInfo, item)">
<mat-icon>arrow_upward</mat-icon>
v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
</button>
}
@let pubInfo = getPublishedVersionInfo(item);
@if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) {
<div class="flex items-center gap-3">
@if (!itemVersion) {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
@if (itemVersion) {
{{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }}
} @else {
{{ 'iot-hub.update' | translate }}
}
<mat-icon>arrow_upward</mat-icon>
v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
</button>
</div>
} @else {
<span class="tb-installed-up-to-date">
<mat-icon>check</mat-icon>
{{ 'iot-hub.up-to-date' | translate }}
</span>
}
} @else {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
{{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }}
</button>
}
</div>
} @else if (hasConverterUpdate(item)) {
<!-- Only ThingsBoard's default converter changed: the package has no new version for it -->
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateConverter(item)">
<mat-icon>arrow_upward</mat-icon>
{{ 'iot-hub.new-converter-available' | translate }}
</button>
} @else {
<span class="tb-installed-up-to-date">
<mat-icon>check</mat-icon>
@ -88,9 +86,12 @@
<mat-icon>info_outline</mat-icon>
</button>
}
<button mat-icon-button (click)="openEntity(item)" matTooltip="{{ (item.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.goto-main-dashboard' : 'iot-hub.open-item-type') | translate:{ type: getItemTypeLabel(item.itemType) } }}">
<mat-icon>open_in_new</mat-icon>
</button>
<!-- The tooltip sits on a wrapper: a disabled button shows none -->
<span matTooltip="{{ openLabel(item) }}">
<button mat-icon-button (click)="openEntity(item)" [disabled]="!canOpen(item)">
<mat-icon>open_in_new</mat-icon>
</button>
</span>
<button mat-icon-button (click)="deleteItem(item)" matTooltip="{{ 'iot-hub.remove' | translate }}">
<tb-icon>mdi:trash-can-outline</tb-icon>
</button>
@ -107,9 +108,9 @@
<span>{{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }}</span>
</button>
}
<button mat-menu-item (click)="openEntity(item)">
<button mat-menu-item (click)="openEntity(item)" [disabled]="!canOpen(item)">
<mat-icon>open_in_new</mat-icon>
<span>{{ (item.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.goto-main-dashboard' : 'iot-hub.open-item-type') | translate:{ type: getItemTypeLabel(item.itemType) } }}</span>
<span>{{ openLabel(item) }}</span>
</button>
<button mat-menu-item (click)="deleteItem(item)">
<tb-icon>mdi:trash-can-outline</tb-icon>

36
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
@import "../../../../../scss/constants";
:host {
@ -117,45 +118,20 @@
.tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); }
.tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); }
// "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8
.tb-installed-version-btn {
display: inline-flex;
align-items: center;
gap: 8px;
// "vX.X.X available" and "Update to" buttons: border matches the text color
.tb-installed-update-btn.mat-mdc-outlined-button {
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
color: rgba(0, 0, 0, 0.76);
background: none;
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 4px;
padding: 6px 12px;
cursor: pointer;
font-family: inherit;
height: auto;
--mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color);
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: inherit !important;
--mat-icon-color: currentColor;
}
&:hover {
background: rgba(0, 0, 0, 0.04);
}
}
// "Update" button — Design: same height as available btn, border matches text color
.tb-installed-update-btn.mat-mdc-outlined-button {
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
padding: 6px 12px;
height: auto;
--mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color);
}
// "Up to date" — Design: 14px Medium, #198038, gap-8, py-6

117
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts

@ -27,13 +27,24 @@ import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import {
DeviceInstalledItemDescriptor,
getInstalledItemTarget,
getInstalledItemUrl,
IotHubInstalledItem,
ItemPublishedVersionInfo
} from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { entityTypeTranslations } from '@shared/models/entity-type.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { ConverterService } from '@core/http/converter.service';
import { ResourcesService } from '@core/services/resources.service';
import {
DefaultConverterUpdate,
differsFromDefaultConverter,
loadDefaultUplinkConverter,
loadOwnDefaultConverterIds
} from '@home/components/iot-hub/iot-hub-default-converter';
import { firstValueFrom } from 'rxjs';
@Component({
selector: 'tb-iot-hub-installed-items-table',
@ -66,6 +77,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
isLoading = false;
publishedVersionMap = new Map<string, ItemPublishedVersionInfo>();
// Installed device packages whose default converter differs from ThingsBoard's default converter now
converterUpdates = new Map<string, DefaultConverterUpdate>();
private converterCheckRun = 0;
updatesChecked = false;
isCheckingUpdates = false;
@ -81,7 +95,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
private iotHubActions: IotHubActionsService,
private elementRef: ElementRef,
private zone: NgZone,
private cd: ChangeDetectorRef
private cd: ChangeDetectorRef,
private converterService: ConverterService,
private resourcesService: ResourcesService
) {
this.widgetResize$ = new ResizeObserver(() => {
this.zone.run(() => {
@ -194,6 +210,27 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
});
}
canOpen(item: IotHubInstalledItem): boolean {
return !!getInstalledItemTarget(item?.descriptor);
}
/** Names what Open opens: for a device package, its dashboard, device or integration. */
openLabel(item: IotHubInstalledItem): string {
if (!this.canOpen(item)) {
return this.translate.instant('iot-hub.nothing-to-open');
}
if (item.itemType === 'SOLUTION_TEMPLATE') {
return this.translate.instant('iot-hub.goto-main-dashboard');
}
let type = this.getItemTypeLabel(item.itemType);
const target = item.itemType === 'DEVICE' ? getInstalledItemTarget(item.descriptor) : null;
const typeKey = target && entityTypeTranslations.get(target.entityType)?.type;
if (typeKey) {
type = this.translate.instant(typeKey);
}
return this.translate.instant('iot-hub.open-item-type', { type });
}
openEntity(item: IotHubInstalledItem): void {
const url = getInstalledItemUrl(item?.descriptor);
if (url) {
@ -212,6 +249,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
infos.forEach(info => this.publishedVersionMap.set(info.itemId, info));
this.updatesChecked = true;
this.isCheckingUpdates = false;
void this.checkConverterUpdates();
},
error: () => {
this.isCheckingUpdates = false;
@ -219,16 +257,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
});
}
viewUpdateDetails(publishedInfo: ItemPublishedVersionInfo, installedItem: IotHubInstalledItem): void {
this.iotHubApiService.getVersionInfo(publishedInfo.publishedVersionId, {ignoreLoading: true}).subscribe(versionView => {
this.iotHubActions.openItemDetail(versionView, installedItem).subscribe(result => {
if (result === 'updated' || result === 'deleted') {
this.loadData();
}
});
});
}
updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void {
this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => {
if (result === 'updated') {
@ -237,6 +265,70 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
});
}
hasConverterUpdate(item: IotHubInstalledItem): boolean {
return this.converterUpdates.has(item.id.id);
}
/** Brings the package's default converter to ThingsBoard's default one. Other packages on the converter take it too. */
updateConverter(item: IotHubInstalledItem): void {
const update = this.converterUpdates.get(item.id.id);
if (!update) {
return;
}
this.iotHubActions.updateDefaultConverter(update).subscribe(updated => {
if (updated) {
this.loadData();
}
});
}
/**
* The device packages on this page whose step with "default": true installed a converter that differs from
* ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it.
*/
private async checkConverterUpdates(): Promise<void> {
// A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win
const run = ++this.converterCheckRun;
// The package's default converter of each DEVICE package on the page
const checks: { item: IotHubInstalledItem; stateKey: string; converterId: string }[] = [];
// Over all installed packages, not only this page's, as the update dialog decides
let ownDefaultConverterIds: Set<string> | undefined;
for (const item of this.dataSource) {
const states = item.itemType === 'DEVICE' ? Object.entries((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : [];
for (const [stateKey, state] of states) {
const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined;
if (!id) {
continue;
}
// A converter taken as it was counts only when a package installed it as its default converter
if (state.resolution === 'use-existing') {
ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService);
if (!ownDefaultConverterIds.has(id)) {
continue;
}
}
checks.push({ item, stateKey, converterId: id });
}
}
const changed = await Promise.all(checks.map(async ({ item, stateKey, converterId }): Promise<DefaultConverterUpdate | null> => {
const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true}))
.catch(() => null);
if (!converter) {
return null;
}
const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType,
converter.configuration.scriptLang, converter.name);
return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ?
{ installedItem: item, stateKey, converter, defaultConverter } : null;
}));
if (run !== this.converterCheckRun) {
return;
}
this.converterUpdates = new Map(changed.filter(update => !!update).map(update => [update.installedItem.id.id, update]));
this.cd.markForCheck();
}
getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined {
return this.publishedVersionMap.get(item.itemId);
}
@ -254,6 +346,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
this.dataSource = data.data;
this.totalElements = data.totalElements;
this.isLoading = false;
if (this.updatesChecked && !this.itemVersion) {
void this.checkConverterUpdates();
}
},
error: () => {
this.dataSource = [];

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import {
Component,
ElementRef,
@ -86,11 +87,10 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges {
}
ngOnChanges(changes: SimpleChanges): void {
for (const propName of Object.keys(changes)) {
const change = changes[propName];
if (propName === 'data' && change.currentValue !== change.previousValue) {
this.parsedData = this.parseData(this.data);
}
// A new resolver means the variable values changed, so the same data has to be resolved again.
// Nothing to render until the step's data arrives; a resolver alone would render an empty page
if ((changes.data || changes.onResolveVariable) && this.data != null) {
this.parsedData = this.parseData(this.data);
}
}

45
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts

@ -1,8 +1,10 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { FilterParamInfo, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
export const IOT_HUB_FILTER_GROUPING_THRESHOLD = 11;
export const IOT_HUB_FILTER_POPULAR_LIMIT = 10;
@ -123,3 +125,44 @@ export function resolveIotHubItemImageUrl(item: MpItemVersionView, api: IotHubAp
}
return null;
}
// ThingsBoard error codes whose message is written for the user: validation, permission, not found, limits
const SHOWN_ERROR_CODES = new Set([20, 30, 31, 32, 33, 34, 35, 40, 41]);
const MAX_SHOWN_ERROR_LENGTH = 200;
/** The message as it is when it reads like one written for the user, null for an internal one (a stack trace, a URL, too long). */
export const readableMessage = (message: unknown): string | null =>
typeof message === 'string' && message.trim() && message.length <= MAX_SHOWN_ERROR_LENGTH &&
!/exception|java\.|https?:\/\/|\bat [\w.$]+\(/i.test(message) ? message : null;
/**
* What the user sees for a failed request: ThingsBoard's validation and limit messages as they are,
* anything else (a server error, the network, a bug) as a common message, with the details in the console.
*/
export const requestFailureMessage = (error: any, translate: TranslateService): string => {
const body = error?.error;
const message = SHOWN_ERROR_CODES.has(body?.errorCode) ? readableMessage(body.message) : null;
if (message) {
return message;
}
console.error('Device package request failed', error);
return translate.instant('iot-hub.device-install-unexpected-error');
};
/** A translated text with a link written as <a>…</a>, which the translation may put anywhere in it, split around the link. */
export const splitTextWithLink = (text: string): { before: string; link: string; after: string } => {
const match = /^([\s\S]*)<a>([\s\S]*)<\/a>([\s\S]*)$/.exec(text);
return match ? { before: match[1], link: match[2], after: match[3] } : { before: text, link: '', after: '' };
};
/** Saves an entity as a JSON file named after it. */
export const downloadEntityJson = (entity: any, name: string): void => {
const blob = new Blob([JSON.stringify(entity, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${name.replace(/[^\w\- ]+/g, '_')}.json`;
link.click();
// Revoked right away, the URL may be gone before the download starts
setTimeout(() => URL.revokeObjectURL(url), 0);
};

66
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -110,8 +110,8 @@ export const installMethodLabels = new Map<string, string>(
[InstallMethod.INTEGRATION_TCP, 'TCP Integration'],
[InstallMethod.INTEGRATION_THINGPARK, 'ThingPark Wireless'],
[InstallMethod.INTEGRATION_THINGPARK_ENTERPRISE, 'ThingPark Enterprise'],
[InstallMethod.INTEGRATION_TTI, 'The Things Industries'],
[InstallMethod.INTEGRATION_TTN, 'The Things Stack'],
[InstallMethod.INTEGRATION_TTI, 'The Things Stack Cloud & Enterprise'],
[InstallMethod.INTEGRATION_TTN, 'The Things Stack Sandbox'],
[InstallMethod.INTEGRATION_TUYA, 'Tuya'],
[InstallMethod.INTEGRATION_UDP, 'UDP Integration']
]
@ -215,6 +215,9 @@ export const stepTypeAliasMap: Record<string, string> = {
export interface DeviceInstallStep {
type: InstallStepType;
name: string;
// Optional stable id of the step, unique within the install method: the key of the step's install state,
// so the next version can rename the step. Without it, the name is the key.
id?: string;
file?: string;
template?: string;
serverAttributes?: string;
@ -223,6 +226,10 @@ export interface DeviceInstallStep {
dockerCompose?: string;
// INTEGRATION step references the integration-form.json artifact alongside the template.
form?: string;
// UPLINK_CONVERTER: ThingsBoard's default converter for the method's integration instead of a template
default?: boolean;
// INTEGRATION: entries added to the integration's metadata, which keeps the entries it has
metadata?: Record<string, string>;
}
export interface DevicePackageInfo {
@ -279,9 +286,61 @@ export interface FormFieldDefinition {
// (tb-secret-key-input); false / undefined → render the typed widget.
secretSupport?: boolean;
secretType?: SecretType;
// Consecutive fields with the same group are shown in one panel titled with the group
group?: string;
readOnly?: boolean;
// A STRING field the user changed shows a button that puts defaultValue back
resettable?: boolean;
// Shown inside the empty field; the label then always stays above it
placeholder?: string;
// Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it.
// defaultValue stays the value for ThingsBoard versions that don't know this attribute.
defaultValueTemplate?: string;
// Replaces helpText when defaultValueTemplate fills the field
defaultValueTemplateHelpText?: string;
// 'advanced' puts the field into the collapsed Advanced settings panel below the form
section?: FormFieldSection;
// Next checks the connection of the integration the form configures and stops on a failure
checkConnection?: boolean;
// With checkConnection: the text of the dialog a failed check shows
checkConnectionFailedText?: string;
// A regular expression whose matches are removed from the value when the user leaves the field
// and before the step is committed, e.g. "@ttn$" for an ID copied with its suffix.
// validators check the cleaned value.
cleanupPattern?: string;
// Key of the field that takes the port pasted at the end of this field's value, e.g. "host:8883"
portField?: string;
// Set by the install dialog for the fields it adds, not by packages:
// help popup shown under the field, and the text of its trigger
helpPopupId?: string;
helpPopupText?: string;
// Shown when the field fails a validator the dialog adds (not on required)
errorMessage?: string;
// Consecutive fields with the same row are shown on one line. A field with a width (px) keeps it;
// the other fields of the row share the remaining space.
row?: string;
width?: number;
}
export type FormFieldSection = 'advanced';
const PASTED_PORT_PATTERN = /:(\d{1,5})\/*\s*$/;
/** The value without the port that portField takes, then without the cleanupPattern matches. */
export const cleanFormFieldValue = (field: FormFieldDefinition, value: any): any => {
if (typeof value !== 'string') {
return value;
}
const withoutPort = field.portField ? value.replace(PASTED_PORT_PATTERN, '') : value;
return field.cleanupPattern ? withoutPort.replace(new RegExp(field.cleanupPattern, 'g'), '') : withoutPort;
};
/** The port at the end of the value of a field with portField, e.g. 8883 for "eu1.example.com:8883". */
export const pastedPortOf = (field: FormFieldDefinition, value: any): number | undefined => {
const match = field.portField && typeof value === 'string' ? PASTED_PORT_PATTERN.exec(value) : null;
return match ? Number(match[1]) : undefined;
};
export interface EntityStepOutput {
id: string;
name: string;
@ -296,7 +355,8 @@ export interface EntityStepOutput {
baseUrl?: string;
}
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict';
// skipped: a step of an update that failed, so nothing was changed
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict' | 'skipped';
export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy';

81
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -30,11 +30,65 @@ export interface RuleChainInstalledItemDescriptor {
export interface DeviceInstalledItemDescriptor {
type: 'DEVICE';
createdEntityIds?: { entityType: string; id: string }[];
// Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them
usedExistingEntityIds?: { entityType: string; id: string }[];
dashboardId?: { id: string };
selectedInstallMethod?: string;
installState?: Record<string, any>;
}
/** An entity of an installed device package as the server finds it before an update. */
export interface DevicePackageEntityState {
stepName: string;
entityId: { entityType: string; id: string };
exists: boolean;
version?: number;
// Changed since the package installed or last updated it; null when the server has no checksum of it
modified?: boolean | null;
shared: boolean;
}
/** A step of a device package update, with its entity resolved from the template of the new version. */
export interface DeviceUpdateStep {
name: string;
type: string;
action: 'KEEP' | 'OVERWRITE' | 'CREATE';
entityId?: string;
expectedVersion?: number;
confirmed?: boolean;
entity?: any;
credentials?: any;
// OVERWRITE and CREATE: the attributes the saved entity gets, as at install
serverAttributes?: any;
sharedAttributes?: any;
resolution?: string;
// The package step's id, which keys its install state; the name when not set
id?: string;
// INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry
metadata?: Record<string, string | null>;
// The step takes ThingsBoard's default converter: its install state says so, for the update check
defaultConverter?: boolean;
}
export interface DeviceUpdateRequest {
versionId: string;
// The version installed when the update was planned: the server refuses the update if the package changed since
fromVersionId?: string;
// The install method of the new version's steps
selectedInstallMethod?: string;
installState: Record<string, any>;
steps: DeviceUpdateStep[];
}
/** All of the update was applied, or none of it: failedStep names the step that failed, if one did. */
export interface DeviceUpdateResult {
success: boolean;
errorMessage?: string;
failedStep?: string;
descriptor?: DeviceInstalledItemDescriptor;
outputs?: Record<string, any>;
}
export interface SolutionTemplateInstalledItemDescriptor {
type: 'SOLUTION_TEMPLATE';
createdEntityIds: { entityType: string; id: string }[];
@ -103,6 +157,19 @@ export interface ItemPublishedVersionInfo {
publishedVersion: string;
}
/** An entity that deleting an installed item keeps, because other installed items use it too. */
export interface IotHubKeptEntity {
entityId: { id: string; entityType: string };
name: string;
}
export interface IotHubInstalledItemKeptEntities {
entities: IotHubKeptEntity[];
usedByItemsCount: number;
// Of the kept entities, the ones the user had before and the package took as they were
usedExistingCount: number;
}
export interface IotHubInstalledItem extends BaseData<{id: string}> {
itemId: string;
itemVersionId: string;
@ -112,7 +179,8 @@ export interface IotHubInstalledItem extends BaseData<{id: string}> {
descriptor: IotHubInstalledItemDescriptor;
}
export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor): string | null => {
/** The entity the Open action of an installed item opens, and its URL. */
export const getInstalledItemTarget = (descriptor?: IotHubInstalledItemDescriptor): { url: string; entityType: EntityType } | null => {
if (!descriptor) {
return null;
}
@ -125,10 +193,12 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor):
entityId = descriptor.dashboardId?.id;
entityType = EntityType.DASHBOARD;
} else if (descriptor.createdEntityIds) {
const found = descriptor.createdEntityIds.find(id => id.entityType === EntityType.DEVICE);
// A gateway package (e.g. TTN) creates no device, only a converter and an integration
const found = descriptor.createdEntityIds.find(id => id.entityType === EntityType.DEVICE)
?? descriptor.createdEntityIds.find(id => id.entityType === EntityType.INTEGRATION);
if (found) {
entityId = found.id;
entityType = EntityType.DEVICE;
entityType = found.entityType as EntityType;
}
}
break;
@ -160,7 +230,10 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor):
} else {
url = getEntityDetailsPageURL(entityId, entityType);
}
return url;
return url ? { url, entityType } : null;
}
return null;
}
export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor): string | null =>
getInstalledItemTarget(descriptor)?.url ?? null;

9
ui-ngx/src/app/shared/models/settings.models.ts

@ -85,6 +85,15 @@ export interface DeviceConnectivityInfo {
export type DeviceConnectivitySettings = Record<DeviceConnectivityProtocol, DeviceConnectivityInfo>;
export type DeviceConnectivityHostSource = 'DEVICE_CONNECTIVITY' | 'BASE_URL' | 'REQUEST';
// Connectivity of a transport as resolved for devices, not as stored in the settings
export interface ResolvedDeviceConnectivityInfo extends DeviceConnectivityInfo {
hostSource?: DeviceConnectivityHostSource;
}
export type ResolvedDeviceConnectivitySettings = Partial<Record<DeviceConnectivityProtocol, ResolvedDeviceConnectivityInfo>>;
export enum MailTemplate {
test = 'test',
activation = 'activation',

64
ui-ngx/src/assets/converters/default-converters-v2-configuration.json

@ -143,12 +143,17 @@
},
"TTN": {
"type": "DEVICE",
"name": "Device $eui",
"profile": "$applicationId",
"name": "$deviceId",
"profile": "LoRaWAN Device",
"label": "$deviceId",
"customer": "",
"group": "$applicationId",
"attributes": [
"eui",
"joinEui",
"devAddr",
"deviceId",
"applicationId",
"fPort",
"bandwidth",
"spreadingFactor",
@ -158,23 +163,30 @@
"modelId",
"hardwareVersion",
"firmwareVersion",
"attributes",
"tenantId"
"bandId",
"netId",
"tenantId",
"clusterId",
"clusterAddress",
"attributes"
],
"telemetry": [
"fCnt",
"data",
"decoded",
"latitude",
"longitude",
"altitude",
"rssi",
"snr",
"channel"
"channel",
"consumedAirtime"
],
"updateOnlyKeys": [
"eui",
"joinEui",
"devAddr",
"deviceId",
"applicationId",
"fPort",
"bandwidth",
"spreadingFactor",
@ -184,18 +196,27 @@
"modelId",
"hardwareVersion",
"firmwareVersion",
"attributes",
"tenantId"
"bandId",
"netId",
"tenantId",
"clusterId",
"clusterAddress",
"attributes"
]
},
"TTI": {
"type": "DEVICE",
"name": "Device $eui",
"profile": "$applicationId",
"name": "$deviceId",
"profile": "LoRaWAN Device",
"label": "$deviceId",
"customer": "",
"group": "$applicationId",
"attributes": [
"eui",
"joinEui",
"devAddr",
"deviceId",
"applicationId",
"fPort",
"bandwidth",
"spreadingFactor",
@ -205,23 +226,30 @@
"modelId",
"hardwareVersion",
"firmwareVersion",
"attributes",
"tenantId"
"bandId",
"netId",
"tenantId",
"clusterId",
"clusterAddress",
"attributes"
],
"telemetry": [
"fCnt",
"data",
"decoded",
"latitude",
"longitude",
"altitude",
"rssi",
"snr",
"channel"
"channel",
"consumedAirtime"
],
"updateOnlyKeys": [
"eui",
"joinEui",
"devAddr",
"deviceId",
"applicationId",
"fPort",
"bandwidth",
"spreadingFactor",
@ -231,8 +259,12 @@
"modelId",
"hardwareVersion",
"firmwareVersion",
"attributes",
"tenantId"
"bandId",
"netId",
"tenantId",
"clusterId",
"clusterAddress",
"attributes"
]
}
}

12
ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md

@ -0,0 +1,12 @@
##### Which host should I use?
The device connects to ThingsBoard over MQTT. Enter an address the device can reach from its own network:
* **ThingsBoard on your computer, device on the same Wi-Fi:** your computer's IP in that network, e.g. `192.168.1.10`. Allow the MQTT port (`1883` by default) in its firewall.
* **ThingsBoard reachable from the internet** (it has a public IP or a public domain): use that address, e.g. `tb.mycompany.com` or `203.0.113.15`. The device needs internet access through its Wi-Fi.
* **Device on a local network, ThingsBoard elsewhere:** the server's local IP isn't reachable from there. Use its public domain or IP.
* **MQTT on a separate host:** enter that host. It can differ from the address you open ThingsBoard at in the browser.
Don't use `localhost` or `127.0.0.1`: on the device they mean the device itself.
**Port.** MQTT usually listens on port `1883`. If the transport uses another port, or the port is forwarded (Docker, load balancer), enter the port the device connects to.

12
ui-ngx/src/assets/help/en_US/iot-hub/gateway-connection-host.md

@ -0,0 +1,12 @@
##### Which host should I use?
The gateway runs in Docker and connects to ThingsBoard over MQTT. Enter an address that the machine running the gateway can reach:
* **Gateway on a separate machine in the same network** (e.g. a reComputer next to the equipment): the IP of the ThingsBoard server in that network, e.g. `192.168.1.10`. Allow the MQTT port (`1883` by default) in its firewall.
* **ThingsBoard reachable from the internet** (it has a public IP or a public domain): use that address, e.g. `tb.mycompany.com` or `203.0.113.15`.
* **Gateway on the same machine as ThingsBoard:** `host.docker.internal` (the package's docker-compose maps it to the machine through `extra_hosts`), or the machine's IP in its network.
* **MQTT on a separate host:** enter that host. It can differ from the address you open ThingsBoard at in the browser.
Don't use `localhost` or `127.0.0.1`: depending on the Docker network mode, they mean the gateway container itself or the machine it runs on, not the ThingsBoard server.
**Port.** MQTT usually listens on port `1883`. If the transport uses another port, or the port is forwarded (Docker, load balancer), enter the port the gateway connects to.

4
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

@ -3623,9 +3623,9 @@
"type-aws-kinesis-description": "خدمة للفيديو والبيانات في الوقت الفعلي.",
"type-ibm-watson-iot": "IBM Watson IoT",
"type-ibm-watson-iot-description": "خدمة مُدارة بالكامل على السحابة.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "شبكة LoRaWAN المفتوحة والمركزة.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "برنامج لتشغيل شبكات LoRaWAN الخاصة بنطاق واسع.",
"type-chirpstack": "ChirpStack",
"type-chirpstack-description": "خادم تكوين شبكة LoRaWAN.",

4
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

@ -3048,8 +3048,8 @@
"type-aws-sqs": "AWS SQS",
"type-aws-kinesis": "AWS Kinesis",
"type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community",
"type-tti": "The Things Stack Industries",
"type-ttn": "The Things Stack Sandbox",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-chirpstack": "ChirpStack",
"type-azure-event-hub": "Azure Event Hub",
"type-azure-iot-hub": "Azure IoT Hub",

4
ui-ngx/src/assets/locale/locale.constant-da_DK.json

@ -5693,9 +5693,9 @@
"type-aws-sqs-description": "Fuldadministreret beskedkøtjeneste.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Tjeneste til realtids video- og datastrømme.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Åbent og decentraliseret LoRaWAN-netværk.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software til drift af private LoRaWAN-netværk i stor skala.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-de_DE.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "Vollständig verwalteter Nachrichtenwarteschlangen-Dienst.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Dienst für Echtzeit-Video- und Datenströme.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Offenes und dezentrales LoRaWAN-Netzwerk.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software zum Betrieb privater LoRaWAN-Netzwerke im großen Maßstab.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-el_GR.json

@ -5702,9 +5702,9 @@
"type-aws-sqs-description": "Διαχειριζόμενη υπηρεσία ουράς μηνυμάτων.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Υπηρεσία ροής δεδομένων και βίντεο σε πραγματικό χρόνο.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Ανοιχτό και αποκεντρωμένο δίκτυο LoRaWAN.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Λογισμικό για τη λειτουργία ιδιωτικών δικτύων LoRaWAN σε μεγάλη κλίμακα.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

55
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -5729,9 +5729,9 @@
"type-aws-sqs-description": "Fully managed message queuing service.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Service for real-time video and data streams.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Open and decentralized LoRaWAN network.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software to operate private LoRaWAN networks at scale.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",
@ -6326,6 +6326,11 @@
"type-device-plural": "Devices"
},
"iot-hub": {
"advanced-settings": "Advanced settings",
"back-to-configuration": "Back to configuration",
"checking-connection": "Checking connection…",
"connection-check-failed-title": "Failed to connect to {{method}}",
"connection-check-failed-text": "Check the connection settings, then try again.",
"iot-hub": "IoT Hub",
"generate-random-value": "Generate random value",
"home-title": "ThingsBoard IoT Hub",
@ -6360,7 +6365,7 @@
"items-per-page": "Items per page",
"filter": "Filter",
"clear-filters": "Clear filters",
"available": "Available",
"available": "available",
"items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.",
"items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.",
"items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.",
@ -6440,6 +6445,9 @@
"remove": "Remove",
"remove-confirm-title": "Remove '{{name}}'?",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant",
"remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:",
"remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway",
"select-entity-for-cf": "Select entity for calculated field '{{name}}'",
@ -6486,6 +6494,8 @@
"check-for-updates": "Check for updates",
"updates": "Updates",
"up-to-date": "Up to date",
"new-converter-available": "New converter available",
"converter-update-title": "Update the converter?",
"update": "Update",
"update-to-version": "Update to v {{ version }}",
"update-item-title": "Update Item",
@ -6521,6 +6531,7 @@
"view-item-details": "View item details",
"review-device-instructions": "Review device instructions",
"open-item-type": "Open {{type}}",
"nothing-to-open": "Nothing to open",
"back-to-marketplace": "Back to Marketplace",
"device-install-select-connectivity": "Choose a connection method for your device",
"connection-method": "Connection method",
@ -6544,6 +6555,28 @@
"use-plain-text": "Use plain text",
"device-install-conflict-exists": "{{type}} with this name already exists",
"device-install-use-existing": "Use existing",
"device-install-transport-host-step": "Connection",
"device-install-thingsboard-connection": "ThingsBoard connection",
"device-install-mqtt-host": "MQTT host",
"device-install-mqtt-host-hint": "Host the device connects to over MQTT. It may differ from the address you open ThingsBoard at in the browser.",
"device-install-mqtt-host-request-hint": "Taken from the address you opened ThingsBoard with. Make sure the device can reach it.",
"device-install-mqtt-host-base-url-hint": "Taken from the Base URL in General settings. Make sure the device can reach it.",
"device-install-mqtt-host-loopback-hint": "The MQTT host resolved to {{host}}, which on the device means the device itself. Enter an address the device can reach.",
"device-install-mqtt-host-base-url-loopback-hint": "Taken from the Base URL in General settings, which points to {{host}}. Enter an address the device can reach.",
"device-install-mqtt-host-opened-via-loopback-hint": "ThingsBoard is opened via {{host}}, so enter an address the device can reach.",
"device-install-mqtt-host-configured-hint": "Set by the platform. The device connects to this host.",
"device-install-mqtt-port": "MQTT port",
"device-install-transport-host-error": "Enter a host name or IP address the device can reach (not localhost)",
"device-install-transport-port-error": "Enter a port from 1 to 65535",
"device-install-gateway-mqtt-host-hint": "Host the gateway connects to over MQTT, from the machine it runs on. It may differ from the address you open ThingsBoard at in the browser.",
"device-install-gateway-mqtt-host-request-hint": "Taken from the address you opened ThingsBoard with. Make sure the machine that runs the gateway can reach it.",
"device-install-gateway-mqtt-host-base-url-hint": "Taken from the Base URL in General settings. Make sure the machine that runs the gateway can reach it.",
"device-install-gateway-mqtt-host-loopback-hint": "The MQTT host resolved to {{host}}, which for the gateway means its own container or machine. Enter an address the gateway can reach, or host.docker.internal if it runs on the ThingsBoard machine.",
"device-install-gateway-mqtt-host-base-url-loopback-hint": "Taken from the Base URL in General settings, which points to {{host}}. Enter an address the gateway can reach, or host.docker.internal if it runs on the ThingsBoard machine.",
"device-install-gateway-mqtt-host-opened-via-loopback-hint": "ThingsBoard is opened via {{host}}, so enter an address the gateway can reach, or host.docker.internal if it runs on the ThingsBoard machine.",
"device-install-gateway-mqtt-host-configured-hint": "Set by the platform. The gateway connects to this host.",
"device-install-gateway-transport-host-error": "Enter a host name or IP address the gateway can reach (not localhost)",
"device-install-which-host": "Which host should I use?",
"device-install-overwrite": "Overwrite",
"device-install-create-copy": "Create copy",
"device-install-resolution-created": "Created",
@ -6552,6 +6585,22 @@
"device-install-resolution-create-copy": "Created copy",
"device-install-title": "Connect \"{{name}}\"",
"device-installing-title": "Installing \"{{name}}\"",
"device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update",
"device-update-no-conflicts": "No conflicts",
"device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.",
"device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.",
"device-update-modified": "Has local changes. You can download the current version <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.",
"device-update-existing-use-existing": "Already exists. The existing one will be used.",
"device-update-existing-overwrite": "Already exists. It will be overwritten.",
"device-update-existing-create-copy": "Already exists. A copy will be created.",
"device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update",
"device-update-skipped": "Not changed",
"device-update-updated": "Updated",
"device-update-created": "Created",
"device-update-try-again": "Try again",
"done": "Done",
"in-progress": "In progress",
"item-detail": "IoT Hub item",

4
ui-ngx/src/assets/locale/locale.constant-es_ES.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "Servicio de colas de mensajes totalmente administrado.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Servicio para transmisión de datos y video en tiempo real.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Red LoRaWAN abierta y descentralizada.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software para operar redes LoRaWAN privadas a escala.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-fr_FR.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "Service de gestion de files d’attente de messages.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Service pour le traitement de flux vidéo et de données en temps réel.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Réseau LoRaWAN ouvert et décentralisé.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Logiciel pour exploiter des réseaux LoRaWAN privés à grande échelle.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

@ -5728,9 +5728,9 @@
"type-aws-sqs-description": "पूरी तरह प्रबंधित संदेश क्यूइंग सेवा।",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "रीयल-टाइम वीडियो और डेटा स्ट्रीमों के लिए सेवा।",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "ओपन और डिसेंट्रलाइज़्ड LoRaWAN नेटवर्क।",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "बड़े स्तर पर प्राइवेट LoRaWAN नेटवर्क ऑपरेट करने के लिए सॉफ़्टवेयर।",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-it_IT.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "Servizio di accodamento messaggi completamente gestito.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Servizio per flussi video e dati in tempo reale.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Rete LoRaWAN aperta e decentralizzata.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software per reti private LoRaWAN su larga scala.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-ja_JP.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "完全に管理されたメッセージキューサービス。",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "リアルタイムのビデオおよびデータストリームサービス。",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "オープンで分散型のLoRaWANネットワーク。",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "スケールでプライベートLoRaWANネットワークを運用するためのソフトウェア。",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

2
ui-ngx/src/assets/locale/locale.constant-ka_GE.json

@ -1720,7 +1720,7 @@
"type-aws-sqs": "AWS SQS",
"type-aws-kinesis": "AWS Kinesis",
"type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-azure-event-hub": "ტიპის-აზური-ღონისძიების ცენტრი",
"type-opc-ua": "OPC-UA",
"type-custom": "უჩვეულო",

4
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -5728,9 +5728,9 @@
"type-aws-sqs-description": "Visiškai valdoma žinučių eilių paslauga.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Realaus laiko vaizdo ir duomenų srautų paslauga.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Atviras ir decentralizuotas LoRaWAN tinklas.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Programinė įranga privatiems LoRaWAN tinklams valdyti dideliu mastu.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

2
ui-ngx/src/assets/locale/locale.constant-lv_LV.json

@ -1629,7 +1629,7 @@
"type-mqtt": "MQTT",
"type-aws-iot": "AWS IoT",
"type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-azure-event-hub": "Azure Event Hub",
"type-opc-ua": "OPC-UA",
"opc-ua-application-name": "Aplikācijas nosaukums",

4
ui-ngx/src/assets/locale/locale.constant-nl_NL.json

@ -5691,9 +5691,9 @@
"type-aws-sqs-description": "Volledig beheerde wachtrijdienst.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Dienst voor realtime video- en datastromen.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Open en gedecentraliseerd LoRaWAN-netwerk.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Software om privé LoRaWAN-netwerken op schaal te beheren.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-no_NO.json

@ -5702,9 +5702,9 @@
"type-aws-sqs-description": "Fulladministrert køtjeneste for meldinger.",
"type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Tjeneste for sanntidsvideo og datastrømmer.",
"type-ttn": "The Things Stack Community",
"type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Åpent og desentralisert LoRaWAN-nettverk.",
"type-tti": "The Things Stack Industries",
"type-tti": "The Things Stack Cloud & Enterprise",
"type-tti-description": "Programvare for å drive private LoRaWAN-nettverk i stor skala.",
"type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack",

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save