diff --git a/application/src/main/java/org/thingsboard/server/controller/IntegrationController.java b/application/src/main/java/org/thingsboard/server/controller/IntegrationController.java index 298e4fe6ec..2a7ce581af 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IntegrationController.java +++ b/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)); diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index f3d32fedc8..b6d01d3342 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/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 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 { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java index f578321567..879da5cf47 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java +++ b/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 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); + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java index 9bd0f08877..ba32fc4d9c 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java +++ b/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 findIntegrationInfosByTenantIdAndEdgeId(TenantId tenantId, EdgeId edgeId, PageLink pageLink); Map 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; } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java new file mode 100644 index 0000000000..1becc88cf4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java @@ -0,0 +1,1001 @@ +// 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 com.fasterxml.jackson.databind.node.TextNode; +import com.google.gson.JsonParser; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.rule.engine.api.AttributesSaveRequest; +import org.thingsboard.server.common.adaptor.JsonConverter; +import org.thingsboard.server.common.data.AttributeScope; +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.HasName; +import org.thingsboard.server.common.data.HasTenantId; +import org.thingsboard.server.common.data.HasVersion; +import org.thingsboard.server.common.data.audit.ActionType; +import org.thingsboard.server.common.data.converter.Converter; +import org.thingsboard.server.common.data.converter.ConverterType; +import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.exception.ThingsboardException; +import org.thingsboard.server.common.data.id.ConverterId; +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.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.DeviceInstalledItemDescriptor; +import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; +import org.thingsboard.server.common.data.kv.AttributeKvEntry; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.page.PageLink; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.common.data.security.DeviceCredentials; +import org.thingsboard.server.common.data.security.DeviceCredentialsType; +import org.thingsboard.server.common.data.subscription.SubscriptionException; +import org.thingsboard.server.dao.attributes.AttributesService; +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.rule.RuleChainService; +import org.thingsboard.server.dao.subscription.PlatformFeature; +import org.thingsboard.server.dao.subscription.SubscriptionService; +import org.thingsboard.server.exception.DataValidationException; +import org.thingsboard.server.exception.EntitiesLimitExceededException; +import org.thingsboard.server.queue.util.TbCoreComponent; +import org.thingsboard.server.service.entitiy.AbstractTbEntityService; +import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.rule.TbRuleChainService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Applies an update of an installed device package in one transaction. The install wizard resolves the templates + * of the new version (the same way it installs them) and sends the entity of each step; this service checks the + * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a + * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a + * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, + * are written after commit too. + */ +@Service +@TbCoreComponent +@Slf4j +@RequiredArgsConstructor +public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { + + // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} + private static final Map STEP_ALIASES = Map.of( + "DEVICE_PROFILE", "deviceProfile", + "DEVICE", "device", + "GATEWAY", "gateway", + "DASHBOARD", "dashboard", + "RULE_CHAIN", "ruleChain", + "UPLINK_CONVERTER", "uplinkConverter", + "DOWNLINK_CONVERTER", "downlinkConverter", + "INTEGRATION", "integration"); + private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); + private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + + private final IotHubInstalledItemService installedItemService; + private final IotHubRestClient iotHubRestClient; + private final IotHubService iotHubService; + private final DevicePackageEntities packageEntities; + private final DeviceProfileService deviceProfileService; + private final DeviceService deviceService; + private final DeviceCredentialsService deviceCredentialsService; + private final DashboardService dashboardService; + private final RuleChainService ruleChainService; + private final TbRuleChainService tbRuleChainService; + private final ConverterService converterService; + private final IntegrationService integrationService; + private final TbIntegrationService tbIntegrationService; + private final SubscriptionService subscriptionService; + private final AttributesService attributesService; + private final TelemetrySubscriptionService telemetryService; + private final TransactionTemplate transactionTemplate; + + @Override + public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { + TenantId tenantId = user.getTenantId(); + DeviceInstalledItemDescriptor descriptor = findDevicePackage(tenantId, installedItemId).descriptor(); + Set sharedIds = new HashSet<>(); + iotHubService.findKeptEntities(tenantId, installedItemId).getEntities().forEach(e -> sharedIds.add(e.getEntityId().getId())); + Map createdIds = createdIds(descriptor); + Map> recordedChecksums = recordedChecksums(tenantId); + + List states = new ArrayList<>(); + if (descriptor.getInstallState() == null) { + return states; + } + descriptor.getInstallState().forEach((stepName, state) -> { + EntityId entityId = DevicePackageEntities.entityIdOf(state, createdIds); + if (entityId == null || !DevicePackageEntities.CHECKSUM_TYPES.contains(entityId.getEntityType())) { + return; + } + DevicePackageEntities.Snapshot snapshot = packageEntities.load(tenantId, entityId); + JsonNode storedChecksum = state.get("checksum"); + // Changed by someone else only when no installed package recorded the current checksum: an update of another + // package that shares the entity, e.g. a converter, records it only in its own row + Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null : + !storedChecksum.asText().equals(snapshot.checksum()) + && !recordedChecksums.getOrDefault(entityId.getId(), Set.of()).contains(snapshot.checksum()); + states.add(new DevicePackageEntityState(stepName, entityId, snapshot != null, + snapshot != null ? snapshot.version() : null, modified, sharedIds.contains(entityId.getId()))); + }); + return states; + } + + @Override + public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + Applied applied; + try { + DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { + throw new IllegalArgumentException("The version belongs to another item"); + } + validatePlan(devicePackage, request); + checkFeatures(tenantId, request); + validateIntegrations(tenantId, request); + applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + } catch (StepFailure e) { + log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause()); + return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName); + } catch (RestClientException e) { + log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); + return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + } catch (Exception e) { + log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); + return DeviceUpdateResult.error(userMessage(e), null); + } + afterCommit(user, tenantId, applied); + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + } + + private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { + IotHubInstalledItem installedItem = installedItemService.findById(tenantId, installedItemId); + if (installedItem == null || !"DEVICE".equals(installedItem.getItemType()) + || !(installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor)) { + throw new IllegalArgumentException("Installed device package not found"); + } + return new DevicePackage(installedItem, descriptor); + } + + /** + * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * whose credentials the firmware uses, are never changed. + */ + private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + if (request.getSteps() == null || request.getSteps().isEmpty()) { + throw new IllegalArgumentException("The update has no steps"); + } + Set ownedIds = ownedIds(devicePackage.descriptor()); + Set stateKeys = new HashSet<>(); + for (DeviceUpdateRequest.Step step : request.getSteps()) { + if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { + throw new IllegalArgumentException("Invalid update step: " + step.getName()); + } + // The key of the step's install state + if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) { + throw new IllegalArgumentException("Duplicate update step: " + step.getName()); + } + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + switch (step.getAction()) { + case KEEP, OVERWRITE -> { + if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { + throw new IllegalArgumentException("No entity for update step: " + step.getName()); + } + boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + && !"GATEWAY_CONNECTOR".equals(step.getType())) { + throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); + } + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + throw new IllegalArgumentException("The device and its credentials don't change on update"); + } + } + case CREATE -> { + } + } + if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + } + } + } + + /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ + private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { + boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP + && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); + if (savesIntegrations) { + subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); + } + } + + /** The configuration of an integration is checked by a remote call, so before the transaction. */ + private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { + for (DeviceUpdateRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + continue; + } + ObjectNode body = step.getEntity().deepCopy(); + // Converters this update creates have no id yet; the configuration doesn't depend on them + body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); + Integration integration = JacksonUtil.treeToValue(body, Integration.class); + integration.setTenantId(tenantId); + try { + tbIntegrationService.validateIntegrationConfiguration(tenantId, integration); + } catch (ExecutionException e) { + // What the integration reports, e.g. wrong credentials, is what the user has to fix + Throwable cause = e.getCause() != null ? e.getCause() : e; + throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause)); + } catch (TimeoutException e) { + throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration")); + } + } + } + + private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { + IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); + DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + Set ownedIds = ownedIds(previous); + Map aliasOutputs = new HashMap<>(); + Map outputs = new LinkedHashMap<>(); + Map installState = new LinkedHashMap<>(); + if (request.getInstallState() != null) { + request.getInstallState().forEach((key, value) -> { + if (value != null && value.has("formValues")) { + installState.put(key, JacksonUtil.newObjectNode().set("formValues", value.get("formValues"))); + } + }); + } + List stepEntityIds = new ArrayList<>(); + Map usedExistingIds = usedExistingIds(previous); + List saved = new ArrayList<>(); + List connectorSteps = new ArrayList<>(); + List attributes = new ArrayList<>(); + DashboardId dashboardId = null; + + for (DeviceUpdateRequest.Step step : request.getSteps()) { + try { + if ("GATEWAY_CONNECTOR".equals(step.getType())) { + // A connector lives in the gateway's attributes, which aren't transactional: saved after commit + if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); + } + continue; + } + JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; + StepResult result = applyStep(tenantId, step, entity); + ObjectNode output = result.output(); + aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); + outputs.put(step.getName(), output); + ObjectNode state = JacksonUtil.newObjectNode(); + state.set("entityOutput", output); + // The package's own entity stays the package's, whatever the request says, so later versions update it + boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); + String resolution = step.getResolution() == null || (owned && "use-existing".equals(step.getResolution())) ? "created" : step.getResolution(); + state.put("resolution", resolution); + // A kept entity keeps the checksum of what the package left: the current one would take the + // user's changes for the package's, and the next update would overwrite them without a warning + String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); + if (checksum != null) { + state.put("checksum", checksum); + } + if (step.isDefaultConverter()) { + state.put("defaultConverter", true); + } + ObjectNode metadata = addedMetadata(step.getMetadata()); + if (metadata != null) { + state.set("metadata", metadata); + } + installState.put(step.getId() != null ? step.getId() : step.getName(), state); + // As at install, an entity used as it was is listed too, so a delete removes the metadata entries the + // package added to it; usedExistingEntityIds keeps it the user's + if (!stepEntityIds.contains(result.entityId())) { + stepEntityIds.add(result.entityId()); + } + if ("use-existing".equals(resolution)) { + usedExistingIds.putIfAbsent(result.entityId().getId(), result.entityId()); + } + if (result.entityId() instanceof DashboardId id) { + dashboardId = id; + } + if (result.saved() != null) { + saved.add(result.saved()); + } + if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { + // As at install, the step's attributes go with the entity it saved; written after commit + attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); + } + } catch (StepFailure e) { + throw e; + } catch (Exception e) { + throw new StepFailure(step.getName(), e); + } + } + + // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps + // it changes: the other steps and the forms keep their install state + if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { + previous.getInstallState().forEach((key, value) -> { + if (value instanceof ObjectNode state) { + installState.putIfAbsent(key, state); + } + }); + } + + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + // The new version may not offer the method the package was installed with + descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod()); + descriptor.setCreatedEntityIds(createdEntityIds(tenantId, previous, stepEntityIds)); + // Carried over like createdEntityIds, so an entity the user chose to use stays theirs after a version drops its step + Set tracked = createdIds(descriptor).keySet(); + descriptor.setUsedExistingEntityIds(usedExistingIds.values().stream().filter(id -> tracked.contains(id.getId())).toList()); + descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous)); + Map state = new LinkedHashMap<>(installState); + carryMetadataStates(previous, tracked, state); + descriptor.setInstallState(state); + + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(descriptor); + installedItemService.save(tenantId, installedItem); + // Resolved once every entity is saved: attributes may refer to a later step's entity + List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), + resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); + return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); + } + + /** The checksums the installed device packages recorded, by entity. */ + private Map> recordedChecksums(TenantId tenantId) { + Map> checksums = new HashMap<>(); + PageLink pageLink = new PageLink(100); + PageData page; + do { + page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); + for (IotHubInstalledItem item : page.getData()) { + if (item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor && descriptor.getInstallState() != null) { + descriptor.getInstallState().values().forEach(state -> { + UUID id = toUuid(state.path("entityOutput").path("id").asText()); + JsonNode checksum = state.get("checksum"); + if (id != null && checksum != null && checksum.isTextual()) { + checksums.computeIfAbsent(id, k -> new HashSet<>()).add(checksum.asText()); + } + }); + } + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + return checksums; + } + + private static UUID toUuid(String id) { + try { + return UUID.fromString(id); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then + * fails: the plan was made for the version installed before. Without it both would create the new entities. + */ + private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { + IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); + UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); + if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) + || !Objects.equals(devicePackage.installedItem().getItemVersionId(), installedItem.getItemVersionId())) { + throw new IllegalArgumentException("The package was updated meanwhile. Check the update again."); + } + return installedItem; + } + + private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + return switch (step.getType()) { + case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); + case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); + case "INTEGRATION" -> saveIntegration(tenantId, step, entity); + default -> throw new IllegalArgumentException("Unsupported step type: " + step.getType()); + }; + } + + private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; + DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); + profile.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(profile, id, current, step); + // The tenant's default profile stays the default one + profile.setDefault(current.isDefault()); + } else { + profile.setId(null); + profile.setVersion(null); + } + DeviceProfile result = deviceProfileService.saveDeviceProfile(profile); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; + Device device; + boolean created = false; + if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + Device template = JacksonUtil.treeToValue(entity, Device.class); + template.setTenantId(tenantId); + template.setId(null); + template.setVersion(null); + device = deviceService.saveDevice(template); + created = true; + } else { + Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; + device = existing(tenantId, current, step); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + // Another device the user chose to overwrite; the package's own device never changes + Device template = JacksonUtil.treeToValue(entity, Device.class); + template.setTenantId(tenantId); + prepareOverwrite(template, id, current, step); + device = deviceService.saveDevice(template); + created = true; + } + } + DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); + if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + credentials = applyCredentials(tenantId, credentials, step.getCredentials()); + } + ObjectNode output = output(device.getId(), device.getName()); + if (credentials != null) { + output.put("token", credentials.getCredentialsId()); + } + if ("GATEWAY".equals(step.getType())) { + output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); + } + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + return new StepResult(device.getId(), output, null, saved); + } + + private DeviceCredentials applyCredentials(TenantId tenantId, DeviceCredentials credentials, JsonNode template) { + JsonNode type = template.get("credentialsType"); + if (type != null && type.isTextual()) { + credentials.setCredentialsType(DeviceCredentialsType.valueOf(type.asText())); + } + JsonNode value = template.get("credentialsValue"); + if (value != null && !value.isNull()) { + credentials.setCredentialsValue(value.isTextual() ? value.asText() : value.toString()); + } + JsonNode credentialsId = template.get("credentialsId"); + if (credentialsId != null && credentialsId.isTextual()) { + credentials.setCredentialsId(credentialsId.asText()); + } + return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); + } + + private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; + Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getTitle()); + } + Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); + dashboard.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(dashboard, id, current, step); + // The dashboard keeps its owner and the customers it is assigned to + if (dashboard.getCustomerId() == null) { + dashboard.setCustomerId(current.getCustomerId()); + } + dashboard.setAssignedCustomers(current.getAssignedCustomers()); + } else { + dashboard.setId(null); + dashboard.setVersion(null); + } + Dashboard result = dashboardService.saveDashboard(dashboard); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); + } + + private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; + RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; + RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); + ruleChain.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(ruleChain, id, current, step); + // A rule chain the tenant made its root one stays the root + ruleChain.setRoot(current.isRoot()); + } else { + ruleChain.setId(null); + ruleChain.setVersion(null); + ruleChain.setRoot(false); + } + RuleChain result = ruleChainService.saveRuleChain(ruleChain); + if (entity.has("metadata") && entity.get("metadata").isObject()) { + RuleChainMetaData metadata = JacksonUtil.treeToValue(entity.get("metadata"), RuleChainMetaData.class); + metadata.setRuleChainId(result.getId()); + metadata.setVersion(result.getVersion()); + if (!ruleChainService.saveRuleChainMetaData(tenantId, metadata, tbRuleChainService::updateRuleNodeConfiguration).isSuccess()) { + throw new IllegalStateException("Failed to save the rule chain metadata"); + } + result = ruleChainService.findRuleChainById(tenantId, result.getId()); + } + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; + Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + return kept(id, current.getName()); + } + Converter converter = JacksonUtil.treeToValue(entity, Converter.class); + converter.setTenantId(tenantId); + converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(converter, id, current, step); + } else { + converter.setId(null); + converter.setVersion(null); + } + Converter result = converterService.saveConverter(converter); + return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); + } + + private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; + Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; + if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + existing(tenantId, current, step); + Integration merged = withMergedMetadata(current, step.getMetadata()); + if (merged != null) { + Integration result = integrationService.saveIntegration(merged); + return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); + } + return new StepResult(id, integrationOutput(current), null, null); + } + Integration integration = JacksonUtil.treeToValue(entity, Integration.class); + integration.setTenantId(tenantId); + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + existing(tenantId, current, step); + prepareOverwrite(integration, id, current, step); + // The devices keep sending to the same endpoint + integration.setRoutingKey(current.getRoutingKey()); + } else { + integration.setId(null); + integration.setVersion(null); + if (integration.getRoutingKey() == null) { + integration.setRoutingKey(UUID.randomUUID().toString()); + } + } + Integration result = integrationService.saveIntegration(integration); + return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); + } + + /** + * Carries over the state of an integration the package still tracks but this version has no step for, with the + * entries the package added to its metadata: a delete that keeps the integration removes them. + */ + private static void carryMetadataStates(DeviceInstalledItemDescriptor previous, Set tracked, Map state) { + if (previous.getInstallState() == null) { + return; + } + Set recorded = new HashSet<>(); + state.values().forEach(s -> { + UUID id = toUuid(s.path("entityOutput").path("id").asText()); + if (id != null) { + recorded.add(id); + } + }); + previous.getInstallState().forEach((key, previousState) -> { + UUID id = previousState != null ? toUuid(previousState.path("entityOutput").path("id").asText()) : null; + if (id != null && tracked.contains(id) && !recorded.contains(id) && previousState.has("metadata") && !state.containsKey(key)) { + state.put(key, previousState.deepCopy()); + } + }); + } + + /** The entries the step adds to the integration's metadata, which a delete of the package removes; null when none. */ + private static ObjectNode addedMetadata(JsonNode entries) { + if (entries == null || !entries.isObject()) { + return null; + } + ObjectNode added = JacksonUtil.newObjectNode(); + entries.fields().forEachRemaining(entry -> { + if (entry.getValue() != null && !entry.getValue().isNull()) { + added.put(entry.getKey(), entry.getValue().asText()); + } + }); + return added.isEmpty() ? null : added; + } + + /** + * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. + * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + */ + private static Integration withMergedMetadata(Integration integration, JsonNode entries) { + if (entries == null || !entries.isObject() || entries.isEmpty()) { + return null; + } + Integration copy = new Integration(integration); + ObjectNode configuration = copy.getConfiguration() instanceof ObjectNode current ? current : JacksonUtil.newObjectNode(); + JsonNode before = configuration.get("metadata"); + ObjectNode metadata = before instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode(); + entries.fields().forEachRemaining(entry -> { + if (entry.getValue() == null || entry.getValue().isNull()) { + metadata.remove(entry.getKey()); + } else { + metadata.put(entry.getKey(), entry.getValue().asText()); + } + }); + if (metadata.equals(before) || (metadata.isEmpty() && before == null)) { + return null; + } + configuration.set("metadata", metadata); + copy.setConfiguration(configuration); + return copy; + } + + + /** + * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the + * user reviewed makes the save fail if someone changed the entity since. + */ + private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + switch (entity) { + case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } + case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } + case Dashboard d -> { d.setId((DashboardId) id); d.setTitle(((Dashboard) current).getTitle()); } + case RuleChain r -> { r.setId((RuleChainId) id); r.setName(((RuleChain) current).getName()); } + case Converter c -> { c.setId((ConverterId) id); c.setName(((Converter) current).getName()); } + case Integration i -> { i.setId((IntegrationId) id); i.setName(((Integration) current).getName()); } + default -> throw new IllegalArgumentException("Unsupported entity: " + entity.getClass().getSimpleName()); + } + Long currentVersion = ((HasVersion) current).getVersion(); + if (step.getExpectedVersion() != null && !step.getExpectedVersion().equals(currentVersion)) { + throw new EntityVersionMismatchException(id.getEntityType(), null); + } + ((HasVersion) entity).setVersion(currentVersion); + } + + private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { + throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + } + return current; + } + + private StepResult kept(EntityId id, String name) { + return new StepResult(id, output(id, name), null, null); + } + + /** The checksum the installed version recorded for the entity, under whichever step it was installed with. */ + private static String previousChecksum(DeviceInstalledItemDescriptor previous, UUID entityId) { + if (previous.getInstallState() == null || entityId == null) { + return null; + } + for (JsonNode state : previous.getInstallState().values()) { + JsonNode checksum = state.get("checksum"); + if (entityId.toString().equals(state.path("entityOutput").path("id").asText()) && checksum != null && checksum.isTextual()) { + return checksum.asText(); + } + } + return null; + } + + /** + * The checksum is of the entity the save returned: a profile or an integration read back by id inside the + * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with + * its metadata, which isn't cached. + */ + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + } + + private static ObjectNode output(EntityId id, String name) { + ObjectNode output = JacksonUtil.newObjectNode(); + output.put("id", id.getId().toString()); + output.put("name", name); + return output; + } + + /** With what the install instructions resolve: ${integration.routingKey}, ${integration.httpEndpoint}, ${integration.baseUrl}. */ + private static ObjectNode integrationOutput(Integration integration) { + ObjectNode output = output(integration.getId(), integration.getName()); + output.put("routingKey", integration.getRoutingKey()); + JsonNode configuration = integration.getConfiguration() != null ? integration.getConfiguration() : JacksonUtil.newObjectNode(); + JsonNode client = configuration.path("clientConfiguration"); + putText(output, "httpEndpoint", client.path("httpEndpoint"), configuration.path("httpEndpoint")); + putText(output, "baseUrl", client.path("baseUrl"), configuration.path("baseUrl")); + return output; + } + + private static void putText(ObjectNode output, String key, JsonNode first, JsonNode second) { + JsonNode value = first.isTextual() ? first : second; + if (value.isTextual()) { + output.put(key, value.asText()); + } + } + + /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { + if (node == null) { + return null; + } + if (node.isTextual()) { + String text = node.asText(); + Matcher matcher = ENTITY_PLACEHOLDER.matcher(text); + StringBuilder resolved = new StringBuilder(); + boolean changed = false; + while (matcher.find()) { + ObjectNode output = aliasOutputs.get(matcher.group(1)); + JsonNode value = output != null ? output.get(matcher.group(2)) : null; + String replacement = value != null && !value.isNull() ? value.asText() : matcher.group(); + changed |= value != null && !value.isNull(); + matcher.appendReplacement(resolved, Matcher.quoteReplacement(replacement)); + } + matcher.appendTail(resolved); + return changed ? TextNode.valueOf(resolved.toString()) : node; + } + if (node.isObject()) { + ObjectNode copy = JacksonUtil.newObjectNode(); + for (Iterator> it = node.fields(); it.hasNext(); ) { + Map.Entry field = it.next(); + copy.set(field.getKey(), resolvePlaceholders(field.getValue(), aliasOutputs)); + } + return copy; + } + if (node.isArray()) { + ArrayNode copy = JacksonUtil.newArrayNode(); + node.forEach(item -> copy.add(resolvePlaceholders(item, aliasOutputs))); + return copy; + } + return node; + } + + /** + * The ids the package tracks: the entities of this version's steps, and those of the installed version this one + * no longer uses, so deleting the package still deletes them. Entities deleted since are dropped. + */ + private List createdEntityIds(TenantId tenantId, DeviceInstalledItemDescriptor previous, List stepEntityIds) { + List ids = new ArrayList<>(stepEntityIds); + Set known = new HashSet<>(); + ids.forEach(id -> known.add(id.getId())); + if (previous.getCreatedEntityIds() != null) { + for (EntityId id : previous.getCreatedEntityIds()) { + if (known.add(id.getId()) && entityService.fetchEntity(tenantId, id).isPresent()) { + ids.add(id); + } + } + } + return ids; + } + + private DashboardId existingDashboard(TenantId tenantId, DeviceInstalledItemDescriptor previous) { + DashboardId id = previous.getDashboardId(); + return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; + } + + /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { + for (SavedEntity saved : applied.saved()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); + if (saved.id().getEntityType() != EntityType.DEVICE) { + autoCommit(user, saved.id()); + } + } catch (Exception e) { + log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + } + } + for (StepAttributes step : applied.attributes()) { + try { + saveAttributes(tenantId, step.entityId(), AttributeScope.SERVER_SCOPE, step.server()); + saveAttributes(tenantId, step.entityId(), AttributeScope.SHARED_SCOPE, step.shared()); + } catch (Exception e) { + log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); + } + } + for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { + try { + saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); + } catch (Exception e) { + log.warn("[{}] Failed to save the gateway connector of device package step [{}]", tenantId, step.getName(), e); + } + } + } + + private void saveConnector(TenantId tenantId, ObjectNode gateway, JsonNode connector) throws Exception { + if (gateway == null || connector == null || !connector.has("name")) { + return; + } + DeviceId gatewayId = new DeviceId(UUID.fromString(gateway.get("id").asText())); + String name = connector.get("name").asText(); + List active = new ArrayList<>(); + for (AttributeKvEntry entry : attributesService.find(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, List.of("active_connectors")).get()) { + JsonNode value = JacksonUtil.toJsonNode(entry.getValueAsString()); + if (value != null && value.isArray()) { + value.forEach(v -> active.add(v.asText())); + } + } + if (!active.contains(name)) { + active.add(name); + } + ObjectNode attributes = JacksonUtil.newObjectNode(); + attributes.set("active_connectors", JacksonUtil.valueToTree(active)); + attributes.set(name, connector); + saveAttributes(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, attributes); + } + + private void saveAttributes(TenantId tenantId, EntityId entityId, AttributeScope scope, JsonNode attributes) { + if (attributes == null || !attributes.isObject() || attributes.isEmpty()) { + return; + } + List entries = JsonConverter.convertToAttributes(JsonParser.parseString(attributes.toString())); + telemetryService.saveAttributes(AttributesSaveRequest.builder() + .tenantId(tenantId) + .entityId(entityId) + .scope(scope) + .entries(entries) + .build()); + } + + /** + * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database + * error, as a common message, with the details in the log. + */ + static String userMessage(Throwable e) { + if (e instanceof EntityVersionMismatchException) { + return "Someone changed it while you were reviewing the update. Check the update again."; + } + if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException + || e instanceof SubscriptionException) { + return e.getMessage(); + } + if (e instanceof ThingsboardException te && te.getErrorCode() != ThingsboardErrorCode.GENERAL) { + return te.getMessage(); + } + return UNEXPECTED_ERROR; + } + + private static boolean isKnownType(String type) { + return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type)); + } + + /** + * The entities the package owns: those it created, not the ones the user chose to use as they were. The install adds + * those to createdEntityIds too, so they are subtracted; an entity of a step a later version dropped stays owned. + */ + private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) { + Set ids = new HashSet<>(createdIds(descriptor).keySet()); + ids.removeAll(usedExistingIds(descriptor).keySet()); + return ids; + } + + /** + * The entities the user chose to use as they were. An install made before the descriptor kept them has them only in + * its install state, which the first update carries over into the descriptor. + */ + private static Map usedExistingIds(DeviceInstalledItemDescriptor descriptor) { + Map ids = new LinkedHashMap<>(); + if (descriptor.getUsedExistingEntityIds() != null) { + descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id)); + return ids; + } + Map createdIds = createdIds(descriptor); + if (descriptor.getInstallState() != null) { + descriptor.getInstallState().values().forEach(state -> { + UUID id = toUuid(state.path("entityOutput").path("id").asText()); + if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) { + ids.put(id, createdIds.get(id)); + } + }); + } + return ids; + } + + private static Map createdIds(DeviceInstalledItemDescriptor descriptor) { + Map ids = new HashMap<>(); + if (descriptor.getCreatedEntityIds() != null) { + descriptor.getCreatedEntityIds().forEach(id -> ids.put(id.getId(), id)); + } + return ids; + } + + private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { + DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + if (entity != null) { + copy.setEntity(entity); + } + return copy; + } + + private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { + } + + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { + } + + private record SavedEntity(EntityId id, Object entity, boolean created) { + } + + private record StepAttributes(String stepName, EntityId entityId, JsonNode server, JsonNode shared) { + } + + private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, + List connectorSteps, List attributes, + Map aliasOutputs) { + } + + /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ + private static class StepFailure extends RuntimeException { + + private final String stepName; + + StepFailure(String stepName, Throwable cause) { + super(cause.getMessage(), cause); + this.stepName = stepName; + } + + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 06ef375109..c071bc61b6 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/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 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 createdEntityIds = descriptor.getCreatedEntityIds(); if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } + Set usedExisting = usedExistingIds(descriptor); + List otherPackages = new ArrayList<>(); + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages); List 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 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 otherPackages) { + if (entityId.getEntityType() != EntityType.INTEGRATION) { + return; + } + Set 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 addedMetadataKeys(DeviceInstalledItemDescriptor descriptor, UUID integrationId) { + Set 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 kept = new ArrayList<>(); + Set usedByItems = new HashSet<>(); + int usedExistingCount = 0; + if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { + Set usedExisting = usedExistingIds(dd); + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); + for (EntityId entityId : dd.getCreatedEntityIds()) { + Set 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 usedExistingIds(DeviceInstalledItemDescriptor descriptor) { + Set 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> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId, + List otherPackages) { + Map> usedBy = new HashMap<>(); + PageLink pageLink = new PageLink(100); + PageData 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); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java new file mode 100644 index 0000000000..18c7540a2b --- /dev/null +++ b/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 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 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 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); + } + + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java new file mode 100644 index 0000000000..92e7b93ce2 --- /dev/null +++ b/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; + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java new file mode 100644 index 0000000000..5688056c98 --- /dev/null +++ b/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 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); + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java new file mode 100644 index 0000000000..13a9c2937e --- /dev/null +++ b/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 installState; + private List 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. ${.} 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 ${.} 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; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java new file mode 100644 index 0000000000..c229f42cff --- /dev/null +++ b/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 outputs; + + public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map 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); + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java new file mode 100644 index 0000000000..58a41b9d20 --- /dev/null +++ b/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 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 keys = new ArrayList<>(); + for (Iterator 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()); + } + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java new file mode 100644 index 0000000000..ad517c5327 --- /dev/null +++ b/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 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; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index b934344e91..e1d0cd666b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/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); diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java index 57ada98db3..5a582026fd 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java +++ b/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 diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java b/application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java new file mode 100644 index 0000000000..33b7c49e47 --- /dev/null +++ b/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) { +} diff --git a/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java b/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java index df462aaf77..d1394bf280 100644 --- a/application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java +++ b/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); diff --git a/application/src/main/resources/converters/TTI/uplink/js.raw b/application/src/main/resources/converters/TTI/uplink/js.raw index 10f09c96ad..9cc99a41a9 100644 --- a/application/src/main/resources/converters/TTI/uplink/js.raw +++ b/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 -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. +// 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.- (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; -} - diff --git a/application/src/main/resources/converters/TTI/uplink/payload.json b/application/src/main/resources/converters/TTI/uplink/payload.json index afe0ab6311..db2c29c4cb 100644 --- a/application/src/main/resources/converters/TTI/uplink/payload.json +++ b/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", diff --git a/application/src/main/resources/converters/TTI/uplink/tbel.raw b/application/src/main/resources/converters/TTI/uplink/tbel.raw index 3dd4a8fb48..ff5744a55e 100644 --- a/application/src/main/resources/converters/TTI/uplink/tbel.raw +++ b/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 -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. +// 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.- (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; diff --git a/application/src/main/resources/converters/TTN/uplink/js.raw b/application/src/main/resources/converters/TTN/uplink/js.raw index 478c26140a..9cc99a41a9 100644 --- a/application/src/main/resources/converters/TTN/uplink/js.raw +++ b/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 -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. +// 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.- (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; -} diff --git a/application/src/main/resources/converters/TTN/uplink/payload.json b/application/src/main/resources/converters/TTN/uplink/payload.json index e9d39a3070..b6e8b80b29 100644 --- a/application/src/main/resources/converters/TTN/uplink/payload.json +++ b/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", diff --git a/application/src/main/resources/converters/TTN/uplink/tbel.raw b/application/src/main/resources/converters/TTN/uplink/tbel.raw index 12f302274d..ff5744a55e 100644 --- a/application/src/main/resources/converters/TTN/uplink/tbel.raw +++ b/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 -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. +// 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.- (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; diff --git a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java index 7dbb04f21f..9e3615532f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/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 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 integrationMetadata, String expectedResult) throws IOException { + testThingsStackDefaultConvertersOnPayload(readResource(payloadFile).orElseThrow(), integrationMetadata, expectedResult); + } + + private void testThingsStackDefaultConvertersOnPayload(String payload, Map 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 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)); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java new file mode 100644 index 0000000000..9c30892737 --- /dev/null +++ b/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 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.>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 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 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 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 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 state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); + ArgumentCaptor 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 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 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; + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 2f1a0ada5b..a20a609a15 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/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 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 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 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 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; + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java b/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java index 8ffd947991..9a46775ede 100644 --- a/application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java +++ b/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; + } + } diff --git a/application/src/test/resources/converters/TTI/uplink/test/default/expected.json b/application/src/test/resources/converters/TTI/uplink/test/default/expected.json index 34264b8cb7..5ac20bca97 100644 --- a/application/src/test/resources/converters/TTI/uplink/test/default/expected.json +++ b/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" diff --git a/application/src/test/resources/converters/TTN/uplink/test/default/expected.json b/application/src/test/resources/converters/TTN/uplink/test/default/expected.json index de65e80a57..aba17ca611 100644 --- a/application/src/test/resources/converters/TTN/uplink/test/default/expected.json +++ b/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" diff --git a/application/src/test/resources/payload/things_stack_formatter_device_payload.json b/application/src/test/resources/payload/things_stack_formatter_device_payload.json new file mode 100644 index 0000000000..adcf82b996 --- /dev/null +++ b/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" + } +} diff --git a/application/src/test/resources/payload/things_stack_manual_device_payload.json b/application/src/test/resources/payload/things_stack_manual_device_payload.json new file mode 100644 index 0000000000..b8d810a8ea --- /dev/null +++ b/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" + } +} diff --git a/application/src/test/resources/payload/things_stack_repository_device_payload.json b/application/src/test/resources/payload/things_stack_repository_device_payload.json new file mode 100644 index 0000000000..430f685aab --- /dev/null +++ b/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" + } + } +} diff --git a/application/src/test/resources/payload/tti_custom_decoder_payload.json b/application/src/test/resources/payload/tti_custom_decoder_payload.json new file mode 100644 index 0000000000..afe0ab6311 --- /dev/null +++ b/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" + } + } +} \ No newline at end of file diff --git a/application/src/test/resources/payload/ttn_custom_decoder_payload.json b/application/src/test/resources/payload/ttn_custom_decoder_payload.json new file mode 100644 index 0000000000..e9d39a3070 --- /dev/null +++ b/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" + } + } +} diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java new file mode 100644 index 0000000000..4091794979 --- /dev/null +++ b/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 +} diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java index 4bd0ab255d..48da435d32 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java +++ b/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); diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java b/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java index c7f5583291..269eafd106 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java +++ b/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 createdEntityIds; + // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them + private List usedExistingEntityIds; private DashboardId dashboardId; private String selectedInstallMethod; private Map installState; diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/AbstractUplinkDataConverter.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/AbstractUplinkDataConverter.java index 599c431468..b0f981f181 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/AbstractUplinkDataConverter.java +++ b/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> currentUpdateOnlyTelemetryPerEntity = new ConcurrentHashMap<>(); protected final Map> currentUpdateOnlyAttributesPerEntity = new ConcurrentHashMap<>(); - private ConverterUnwrapper converterUnwrapper; + protected ConverterUnwrapper converterUnwrapper; public AbstractUplinkDataConverter(JsInvokeService jsInvokeService, TbelInvokeService tbelInvokeService, LogSettingsComponent logSettings) { super(jsInvokeService, tbelInvokeService, logSettings); diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java index 0d270db56d..a944217d1d 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedConverterUtil.java +++ b/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 unwrapperKeys) { Map kvMap = new HashMap<>(metadata.getKvMap()); + Set telemetryNoCastKeys = new HashSet<>(); + Set 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 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 kvMap, Set 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 kvMap, Set keys, Set unwrapperKeys, Set 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 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 getTelemetryKeys(JsonArray telemetry) { + Set 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 kvMap, Set keys, Set unwrapperKeys, Set 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; } diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java index 8098512b21..7f99ff891f 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverter.java +++ b/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 currentOnValueTelemetryUpdate = this.currentUpdateOnlyTelemetryPerEntity.getOrDefault(name, new ConcurrentHashMap<>()); Map 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); } diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java index be46b58539..f0fe325bc6 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/DedicatedUplinkData.java +++ b/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 telemetryNoCastKeys; + @JsonIgnore + private final Set attributesNoCastKeys; @JsonRawValue public String getTelemetry() { diff --git a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java b/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java index b7d0f67211..f9cf07a5bf 100644 --- a/common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java +++ b/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 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 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 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 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 getKeysMapping() { return KEYS_MAPPING; diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java index 155b9ac6c8..15ea42a432 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/DedicatedScriptUplinkDataConverterTest.java +++ b/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 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 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 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 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 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 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 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 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 tsKvList = uplink.getTelemetry().getTsKvListList(); + assertEquals(2, tsKvList.size()); + Map fromDecoder = toMap(tsKvList.stream().filter(tsKv -> tsKv.getTs() == 1L).findFirst().orElseThrow().getKvList()); + Map 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 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 attributes, Set 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 toMap(List 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(); diff --git a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java b/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java index c3c154ad2f..7463b97003 100644 --- a/common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java +++ b/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 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(); diff --git a/common/integration/mqtt-integrations/pom.xml b/common/integration/mqtt-integrations/pom.xml index 89b3025891..b3d3a1dcb0 100644 --- a/common/integration/mqtt-integrations/pom.xml +++ b/common/integration/mqtt-integrations/pom.xml @@ -70,6 +70,11 @@ 4.13.2 test + + org.mockito + mockito-core + test + diff --git a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java index f82aabcb56..33020d91cf 100644 --- a/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java +++ b/common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java @@ -101,6 +101,8 @@ public class BasicMqttIntegration extends AbstractMqttIntegration ctx.getIntegrationConnectTimeoutSec() && ctx.getIntegrationConnectTimeoutSec() > 0) { log.debug("Reduce connection timeout sec down to the limit [{}]", mqttClientConfiguration.getConnectTimeoutSec()); mqttClientConfiguration.setConnectTimeoutSec(ctx.getIntegrationConnectTimeoutSec()); diff --git a/common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java b/common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java new file mode 100644 index 0000000000..2270fa22e6 --- /dev/null +++ b/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")); + } +} diff --git a/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java b/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java index f70769dd80..cecb4fb4ed 100644 --- a/common/proto/src/main/java/org/thingsboard/server/common/adaptor/JsonConverter.java +++ b/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 noCastKeys) throws JsonSyntaxException { + PostTelemetryMsg.Builder builder = PostTelemetryMsg.newBuilder(); + convertToTelemetry(jsonElement, System.currentTimeMillis(), null, builder, noCastKeys); + return builder.build(); + } + public static TbPair> convertToGatewayTelemetry(JsonElement jsonElement, long systemTs) { List 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> result, PostTelemetryMsg.Builder builder) { + private static void convertToTelemetry(JsonElement jsonElement, long systemTs, Map> result, PostTelemetryMsg.Builder builder, Set 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> result, PostTelemetryMsg.Builder builder, JsonObject jo) { + private static void parseObject(long systemTs, Map> result, PostTelemetryMsg.Builder builder, JsonObject jo, Set 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 noCastKeys) throws JsonSyntaxException { if (jsonObject.isJsonObject()) { PostAttributeMsg.Builder result = PostAttributeMsg.newBuilder(); - List keyValueList = parseProtoValues(jsonObject.getAsJsonObject()); + List 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 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 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 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 parseProtoValues(JsonObject valuesObject) { + private static List parseProtoValues(JsonObject valuesObject, Set noCastKeys) { List result = new ArrayList<>(); for (Entry 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> convertToTelemetry(JsonElement jsonElement, long systemTs, boolean sorted) throws JsonSyntaxException { Map> result = sorted ? new TreeMap<>() : new HashMap<>(); - convertToTelemetry(jsonElement, systemTs, result, null); + convertToTelemetry(jsonElement, systemTs, result, null, Collections.emptySet()); return result; } diff --git a/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java b/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java index 3729ad3d39..a06f47494c 100644 --- a/common/proto/src/test/java/org/thingsboard/server/common/adaptor/JsonConverterTest.java +++ b/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); + } + } diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java index 8cb6d64c00..50ae0fcd43 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java +++ b/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 STANDARD_PORTS = Map.of( + HTTP, HTTP_DEFAULT_PORT, + HTTPS, HTTPS_DEFAULT_PORT, + MQTT, "1883", + MQTTS, "8883", + COAP, "5683", + COAPS, "5684"); private final Map 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 result = new LinkedHashMap<>(); + Map 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); diff --git a/dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java b/dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java new file mode 100644 index 0000000000..64325ce821 --- /dev/null +++ b/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) { +} diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java index 236f5a7587..b99cf18981 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java +++ b/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 { Optional findByTenantIdAndId(TenantId tenantId, IotHubInstalledItemId installedItemId); + // Locks the row until the end of the current transaction + Optional findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId); + PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java index 5067eac572..072506dfca 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java +++ b/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 findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink); List findInstalledItemIdsByTenantId(TenantId tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java index bf86162b86..d69060cd94 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java +++ b/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 findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java index 21d0dc89c9..693166b7e0 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java +++ b/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 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 findByTenantIdAndIdForUpdate(@Param("tenantId") UUID tenantId, @Param("id") UUID id); + @Query("SELECT DISTINCT item.itemId FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId") List findInstalledItemIdsByTenantId(@Param("tenantId") UUID tenantId); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java index c1b0c5fbb3..d07d8f5dd4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java +++ b/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 findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId) { + return repository.findByTenantIdAndIdForUpdate(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData); + } + @Override public PageData findByTenantId(TenantId tenantId, List itemTypes, UUID itemId, PageLink pageLink) { return DaoUtil.toPageData(repository.findByTenantId( diff --git a/dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java b/dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java new file mode 100644 index 0000000000..2a91a14654 --- /dev/null +++ b/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); + } + +} diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 439976d6c5..fa040e8632 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/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 { - return this.http.get( + public getConnectivitySettings(config?: IotHubRequestConfig): Observable { + return this.http.get( `/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 }, + descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, config?: IotHubRequestConfig ): Observable { return this.http.post( @@ -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 { + return this.http.get( + `/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 { + return this.http.post( + `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, + request, + { params: this.buildParams(config) } + ); + } + + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { + return this.http.get( + `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, + { params: this.buildParams(config) } + ); + } + public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable { return this.http.post( `${this.baseUrl}/api/versions/publishedVersions`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 3bc2fbcbd4..695df118b5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -49,17 +49,22 @@ } @case ('form') { -
+
+ [reviewMode]="reviewMode" + [newFieldKeys]="ws.newFieldKeys">
} @case ('progress') { + @if (data.update) { + + } @else {
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) { @if (i > 0) { @@ -143,6 +148,148 @@ } }
+ } + } + } +
+ + + + + @let hint = textWithLink('iot-hub.device-update-modified'); + {{ hint.before }}{{ hint.link }}{{ hint.after }} + + + + +
+ @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @if (i > 0) { +
+ } + @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) { +
+
+
+ warning +
+
+ {{ label }} + @if (plan.newDefaultConverter) { + {{ 'iot-hub.device-update-new-default-converter' | translate }} + } + @if (plan.existing) { + + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + + } + @if (plan.shared) { + {{ 'iot-hub.device-update-shared' | translate }} + } + @if (plan.modified) { + + + + } +
+
+
+ @if (plan.existing) { + @if (ep.step.type === 'DASHBOARD') { + + } @else { + + } + + } @else { + + } +
+
+ } @else if (ep.status === 'error') { +
+
+ error +
+
+ {{ label }} + @if (ep.errorMessage) { + {{ ep.errorMessage }} + } +
+ {{ 'iot-hub.device-install-step-error' | translate }} +
+ } @else { +
+
+ @switch (ep.status) { + @case ('running') { + + } + @case ('success') { + check_circle + } + @default { +
{{ i + 1 }}
+ } + } +
+
+
+ {{ label }} + @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + {{ 'iot-hub.device-update-new' | translate }} + } +
+ + @if (ws.reviewing && plan?.confirmed) { + @if (plan.newDefaultConverter) { + {{ 'iot-hub.device-update-new-default-converter' | translate }} + } + @if (plan.existing) { + {{ 'iot-hub.device-update-existing-' + plan.resolution | translate }} + } + @if (plan.shared) { + {{ 'iot-hub.device-update-shared' | translate }} + } + @if (plan.modified) { + + + + } + } +
+ + @switch (ep.status) { + @case ('running') { + {{ 'iot-hub.in-progress' | translate }} + } + @case ('success') { + {{ updateOutcomeOf(plan) | translate }} + } + @case ('skipped') { + {{ 'iot-hub.device-update-skipped' | translate }} + } + @default { + @if (ws.reviewing && plan) { + {{ 'iot-hub.device-update-no-conflicts' | translate }} + } + } + } + +
} }
@@ -170,7 +317,14 @@ } @else {
-

{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}

+

+ @if (data.update) { + {{ 'iot-hub.device-update-title' | translate:{ name: packageInfo?.name || data.item.name } }} + {{ data.update.fromVersion }} → {{ data.item.version }} + } @else { + {{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }} + } +

@@ -207,7 +361,7 @@ @for (ws of wizardSteps; track ws.label) { {{ ws.label }} @@ -224,9 +378,24 @@ } + @if (data.update && currentWizardStep?.type === 'progress') { + @let step = currentWizardStep; + @if (hasUpdateError(step)) { +
+ error + {{ step.progressError }} +
+ } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { +
+ warning + {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} +
+ } + } + @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -251,12 +420,38 @@ } @case ('form') { - } @case ('progress') { - @if (step.progressError) { + @if (data.update && (step.reviewing || step.updating || step.progressError)) { + @if (step.progressError && !step.updating) { + + + } @else if (step.updating) { + + + } @else { + + + } + } @else if (step.progressError) { } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -90,14 +164,20 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @case (FormFieldType.INTEGER) { - - {{ field.label }} - - @if (field.helpText) { - {{ field.helpText }} + + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} + + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -105,12 +185,18 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @default { - - {{ field.label }} - + + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} + @if (field.randomGenerator) { } - @if (field.helpText) { - {{ field.helpText }} + @if (canResetToDefault(field)) { + + } + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -128,17 +222,17 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } } } - @if (field.type === FormFieldType.BOOLEAN && field.helpText) { -
{{ field.helpText }}
- } @if (field.helpImage) { } - } + } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss index 960c886f7b..492e9be76d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss +++ b/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; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts index 4e4c813ae7..5c2b03d162 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts +++ b/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; passwordVisible: Record = {}; + // 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); + } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index a3ad857308..46fed1fbae 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/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, { 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 { + return from(this.converterUpdateDialogData(update)).pipe( + switchMap(data => this.dialog.open( + TbIotHubConverterUpdateDialogComponent, { + panelClass: ['tb-dialog'], + disableClose: true, + autoFocus: false, + data + }).afterClosed()), + catchError(() => of(false)) + ); + } + + private async converterUpdateDialogData(update: DefaultConverterUpdate): Promise { + 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 + ]); + 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 { if (!installedItem) { return of(false); } - return this.dialog.open(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 = 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, { + 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 { + 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 { + entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], disableClose: true, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index ea754e42f9..99a2676c90 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/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, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html new file mode 100644 index 0000000000..936eaf624a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html @@ -0,0 +1,33 @@ + +
+

{{ 'iot-hub.converter-update-title' | translate }}

+

{{ 'iot-hub.device-update-new-default-converter' | translate }}

+
+
{{ data.update.converter.name }}
+ @if (data.usedBy.length) { + {{ 'iot-hub.device-update-shared' | translate }} +
    + @for (name of data.usedBy; track $index) { +
  • {{ name }}
  • + } +
+ } + @if (data.modified) { + + {{ modifiedHint.before }}{{ modifiedHint.link }}{{ modifiedHint.after }} + + } +
+ @if (errorMessage) { + {{ errorMessage }} + } +
+
+ + +
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss new file mode 100644 index 0000000000..ae19cef879 --- /dev/null +++ b/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; + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts new file mode 100644 index 0000000000..3db43abe6f --- /dev/null +++ b/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 { + + readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified')); + updating = false; + errorMessage: string | null = null; + + constructor( + protected store: Store, + protected router: Router, + protected dialogRef: MatDialogRef, + @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); + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts new file mode 100644 index 0000000000..0a6f970e21 --- /dev/null +++ b/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; +} + +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 | null> => { + const configurations = await firstValueFrom( + resourcesService.loadJsonResource>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL)); + const configuration = configurations?.[integrationType]; + if (!configuration) { + return null; + } + const script = await firstValueFrom(resourcesService.loadJsonResource( + 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): 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 => { + const items: IotHubInstalledItem[] = []; + let pageLink = new PageLink(100); + let page: PageData; + 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> => { + const ids = new Set(); + 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 + }] + }; +}; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html index 3270cfd641..3de67878aa 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html @@ -1,12 +1,16 @@

{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}

-

{{ (data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc') | translate }}

+

{{ description }}

+ @if (keptReferences) { + + }
diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss index 86ad80c197..63fa684164 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss +++ b/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; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts index 4447dc8a23..08ae924eb6 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts +++ b/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 { + 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, protected router: Router, protected dialogRef: MatDialogRef, @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 { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index f4885183cd..bc550bd817 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html @@ -1,7 +1,8 @@
@@ -41,29 +42,26 @@ @if (updatesChecked) { {{ 'iot-hub.updates' | translate }} } @if (updatesChecked) { - @if (getPublishedVersionInfo(item); as pubInfo) { - @if (pubInfo.publishedVersionId !== item.itemVersionId) { -
- @if (!itemVersion) { - - } + @let pubInfo = getPublishedVersionInfo(item); + @if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) { +
+ @if (!itemVersion) { -
- } @else { - - check - {{ 'iot-hub.up-to-date' | translate }} - - } + } @else { + + } +
+ } @else if (hasConverterUpdate(item)) { + + } @else { check @@ -88,9 +86,12 @@ info_outline } - + + + + @@ -107,9 +108,9 @@ {{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }} } -