From db7795eecb331e8105dbde1ac29d37e4f33de67b Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 27 Oct 2026 14:57:45 +0200 Subject: [PATCH 01/66] feat(iot-hub): device install form for LoRaWAN packages - The device install form shows placeholders, templated defaults, an Advanced section and a ThingsBoard connection section with the MQTT host and port, cleans pasted values, shows errors after the user leaves a field and does not let the browser autofill ThingsBoard credentials. - A field marked by the package checks the integration connection. - The TTN and TTI install methods are named The Things Stack Sandbox and The Things Stack Cloud. - The TTN converter metadata includes the coding rate and the gateway channel. - Deleting or updating a device package keeps the integrations, converters and other entities that another installed device package uses, and the delete dialog names them before the user confirms. - The Open button of an installed item names what it opens. --- .../server/controller/IotHubController.java | 16 +- .../service/iot_hub/DefaultIotHubService.java | 62 ++- .../iot_hub/InstalledItemKeptEntities.java | 30 ++ .../server/service/iot_hub/IotHubService.java | 3 + .../system/DefaultSystemSecurityService.java | 9 +- .../security/system/ResolvedBaseUrl.java | 10 + .../system/SystemSecurityService.java | 2 + .../iot_hub/DefaultIotHubServiceTest.java | 94 +++- .../DefaultSystemSecurityServiceTest.java | 51 ++ .../device/DeviceConnectivityHostSource.java | 15 + .../dao/device/DeviceConnectivityService.java | 14 +- .../ThingsStackConverterUnwrapper.java | 15 + .../wrapper/ConverterUnwrapperTest.java | 16 + common/integration/mqtt-integrations/pom.xml | 5 + .../mqtt/basic/BasicMqttIntegration.java | 2 + .../TtnIntegrationCheckConnectionTest.java | 62 +++ .../device/DeviceConnectivityServiceImpl.java | 20 +- .../ResolvedDeviceConnectivityInfo.java | 11 + .../DeviceConnectivityServiceImplTest.java | 119 +++++ .../src/app/core/http/iot-hub-api.service.ts | 15 +- .../device-install-dialog.component.html | 42 +- .../device-install-dialog.component.scss | 17 + .../device-install-dialog.component.ts | 453 +++++++++++++++++- .../install-form-renderer.component.html | 136 +++++- .../install-form-renderer.component.scss | 7 - .../install-form-renderer.component.ts | 126 ++++- .../iot-hub/iot-hub-actions.service.ts | 26 +- .../iot-hub-delete-dialog.component.html | 5 +- .../iot-hub-delete-dialog.component.scss | 8 +- .../iot-hub-delete-dialog.component.ts | 27 +- ...t-hub-installed-items-table.component.html | 16 +- ...iot-hub-installed-items-table.component.ts | 23 + .../iot-hub/iot-hub-markdown.component.ts | 12 +- .../models/iot-hub/device-package.models.ts | 36 +- .../iot-hub/iot-hub-installed-item.models.ts | 25 +- .../src/app/shared/models/settings.models.ts | 9 + .../en_US/iot-hub/device-connection-host.md | 12 + .../assets/locale/locale.constant-ar_AE.json | 4 +- .../assets/locale/locale.constant-ca_ES.json | 4 +- .../assets/locale/locale.constant-da_DK.json | 4 +- .../assets/locale/locale.constant-de_DE.json | 4 +- .../assets/locale/locale.constant-el_GR.json | 4 +- .../assets/locale/locale.constant-en_US.json | 34 +- .../assets/locale/locale.constant-es_ES.json | 4 +- .../assets/locale/locale.constant-fr_FR.json | 4 +- .../assets/locale/locale.constant-hi_IN.json | 4 +- .../assets/locale/locale.constant-it_IT.json | 4 +- .../assets/locale/locale.constant-ja_JP.json | 4 +- .../assets/locale/locale.constant-ka_GE.json | 2 +- .../assets/locale/locale.constant-lt_LT.json | 4 +- .../assets/locale/locale.constant-lv_LV.json | 2 +- .../assets/locale/locale.constant-nl_NL.json | 4 +- .../assets/locale/locale.constant-no_NO.json | 4 +- .../assets/locale/locale.constant-pl_PL.json | 4 +- .../assets/locale/locale.constant-pt_BR.json | 4 +- .../assets/locale/locale.constant-tr_TR.json | 4 +- .../assets/locale/locale.constant-uk_UA.json | 4 +- .../assets/locale/locale.constant-zh_CN.json | 4 +- 58 files changed, 1506 insertions(+), 155 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java create mode 100644 application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java create mode 100644 common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java create mode 100644 common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java create mode 100644 dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java create mode 100644 dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java create mode 100644 ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md 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..1645505c00 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,13 @@ 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.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; @@ -153,13 +156,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/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 06ef375109..a3cf0599fa 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 @@ -42,6 +42,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 +60,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 +82,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 +123,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; @@ -456,7 +462,7 @@ public class DefaultIotHubService implements IotHubService { case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); case "DEVICE" -> { DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor; - deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); + deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); dd.setCreatedEntityIds(null); dd.setDashboardId(null); } @@ -704,13 +710,24 @@ 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. + */ + private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, + List createdEntityIds, SecurityUser user) { if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); List reversed = new ArrayList<>(createdEntityIds); Collections.reverse(reversed); for (EntityId entityId : reversed) { + Set usedBy = usedByOtherPackages.get(entityId.getId()); + if (usedBy != null) { + log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); + continue; + } try { deleteDevicePackageEntity(tenantId, entityId, user); } catch (Exception e) { @@ -719,6 +736,45 @@ public class DefaultIotHubService implements IotHubService { } } + /** 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<>(); + if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); + for (EntityId entityId : dd.getCreatedEntityIds()) { + Set usedBy = usedByOtherPackages.get(entityId.getId()); + if (usedBy != null) { + kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); + usedByItems.addAll(usedBy); + } + } + } + return new InstalledItemKeptEntities(kept, usedByItems.size()); + } + + private Map> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { + 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 && 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 +853,7 @@ public class DefaultIotHubService implements IotHubService { } } } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { - deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); + deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), 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/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java new file mode 100644 index 0000000000..021cfe5be5 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java @@ -0,0 +1,30 @@ +// 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, because other installed items use it too. */ +@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; + + @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/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..0f0068872c 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; @@ -13,14 +14,27 @@ 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.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +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.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.Optional; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -48,6 +62,16 @@ 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; @Spy @InjectMocks @@ -411,4 +435,72 @@ 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 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 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(); + } + + 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/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/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..c26ecaffd3 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 @@ -58,9 +58,24 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper { .put("simulated", "/simulated") .put("rssi", "") .put("snr", "") + .put("channel", "") .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"; 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/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/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..49da0f4e6a 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 { 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) } ); @@ -269,6 +269,13 @@ export class IotHubApiService { ); } + 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..8f36545817 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,13 +49,43 @@ } @case ('form') { -
+
+ [reviewMode]="reviewMode" + [checkConnectionTemplate]="connectionCheckOf(ws) && hasCheckConnectionField(ws) ? checkConnectionTpl : null"> + +
+ + @switch (connectionCheckMessage(ws)) { + @case ('checking') { + + } + @case ('success') { + + check_circle + {{ 'iot-hub.connection-check-success' | translate }} + + } + @case ('error') { + + error + {{ 'iot-hub.connection-check-failed' | translate }} + + } + } +
+
+ @if (connectionCheckOf(ws) && !hasCheckConnectionField(ws)) { + + }
} @@ -207,7 +237,7 @@ @for (ws of wizardSteps; track ws.label) { {{ ws.label }} @@ -252,7 +282,11 @@ @case ('form') { } @case ('progress') { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss index 9ab0b87e94..c57e41aebd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss @@ -195,6 +195,23 @@ } } +.tb-connection-check-result { + font-size: 14px; + color: #198038; + + mat-icon { + color: #198038; + } + + &.tb-connection-check-error { + color: #dd2c00; + + mat-icon { + color: #dd2c00; + } + } +} + .tb-progress-divider { width: 1px; height: 16px; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ee4a325742..9b265718b4 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -7,10 +7,10 @@ import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { DialogComponent } from '@shared/components/dialog.component'; -import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; +import { AbstractControl, UntypedFormControl, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms'; import { MatStepper } from '@angular/material/stepper'; import { StepperSelectionEvent } from '@angular/cdk/stepper'; -import { firstValueFrom } from 'rxjs'; +import { firstValueFrom, Subscription } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -29,6 +29,7 @@ import { IntegrationService } from '@core/http/integration.service'; import { Converter, ConverterType } from '@shared/models/converter.models'; import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service'; import { + cleanFormFieldValue, DeviceInstallStep, DevicePackageInfo, ENTITY_STEP_TYPES, @@ -38,10 +39,16 @@ import { FormFieldType, installMethodIcons as INSTALL_METHOD_ICONS, installMethodLabels as INSTALL_METHOD_LABELS, + InstallMethod, InstallStepType, stepTypeAliasMap } from '@shared/models/iot-hub/device-package.models'; import { mergeMap } from 'rxjs/operators'; +import { + DeviceConnectivityHostSource, + DeviceConnectivityProtocol, + ResolvedDeviceConnectivityInfo +} from '@shared/models/settings.models'; export interface DeviceInstallDialogData { item: MpItemVersionView; @@ -63,15 +70,127 @@ export interface WizardStep { markdown?: string; // Form formFields?: FormFieldDefinition[]; + // Fields the dialog adds on top of the package's form file + extraFormFields?: FormFieldDefinition[]; + // Key of the step's form values in the install state; the label when not set + stateKey?: string; formGroup?: UntypedFormGroup; + // Connection check of the integration the form configures; null when the form configures none + connectionCheck?: ConnectionCheck | null; // Progress entitySteps?: EntityStepProgress[]; progressError?: string; progressDone?: boolean; } +export interface ConnectionCheck { + // The INTEGRATION step template that the form values fill + template: string; + status: 'idle' | 'checking' | 'success' | 'error'; + // The values the status is for, as JSON: only the fields the integration template uses + checkedValues?: string; + // The result shows next to the button for a few seconds after the check + resultVisible?: boolean; + resultTimer?: ReturnType; +} + const ENTITY_STEP_MIN_DELAY = 2000; +const CONNECTION_CHECK_RESULT_MS = 5000; const DEFAULT_RANDOM_SIZE = 20; +const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost'; +const TRANSPORT_PORT_FIELD_KEY = 'tbTransportPort'; +// Not the translated label, so review mode finds the values in any UI language +const TRANSPORT_STEP_STATE_KEY = 'tbTransportConnection'; + +/** + * A transport whose ${.host} / ${.port} the install form lets the user check, + * with the translation keys of its fields. The wording is per transport (the label, the hints and + * the help popup name the protocol and its default port), so each entry brings its own keys. + */ +interface HostFieldTransport { + protocol: DeviceConnectivityProtocol; + hostLabel: string; + portLabel: string; + // Hint by the source of the host; REQUEST is used when the source is unknown + hostHints: Partial> & { REQUEST: string }; + // Hint by the source of a host that resolved to a loopback address; loopbackHint when there is none + loopbackHints: Partial>; + loopbackHint: string; + // Review mode: the stored value is shown without its source + reviewHostHint: string; + // Host set in Device connectivity: the fields are read-only + configuredHint: string; + hostError: string; + portError: string; + helpPopupId: string; + helpPopupText: string; +} + +// Install methods whose packages get the transport fields. Other methods use the host differently +// (a ChirpStack package builds the ThingsBoard URL from it, a gateway puts it into docker-compose) +// and keep the resolved value until they are handled separately. +const HOST_FIELD_TRANSPORTS = new Map([ + [InstallMethod.DIRECT_MQTT, { + protocol: 'mqtt', + hostLabel: 'iot-hub.device-install-mqtt-host', + portLabel: 'iot-hub.device-install-mqtt-port', + hostHints: { + REQUEST: 'iot-hub.device-install-mqtt-host-request-hint', + BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-hint' + }, + loopbackHints: { + REQUEST: 'iot-hub.device-install-mqtt-host-opened-via-loopback-hint', + BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-loopback-hint' + }, + loopbackHint: 'iot-hub.device-install-mqtt-host-loopback-hint', + reviewHostHint: 'iot-hub.device-install-mqtt-host-hint', + configuredHint: 'iot-hub.device-install-mqtt-host-configured-hint', + hostError: 'iot-hub.device-install-transport-host-error', + portError: 'iot-hub.device-install-transport-port-error', + helpPopupId: 'iot-hub/device-connection-host', + helpPopupText: 'iot-hub.device-install-which-host' + }] +]); + +/** + * Reduces what a user may paste (a URL, host:port, [IPv6]:port) to the bare host: the port is + * a separate setting, and the scheme or path would end up in the firmware as part of the host. + */ +const toBareHost = (value: string): string => { + const hostPort = value.trim().replace(/^[a-z][a-z\d+.-]*:\/\//i, '').replace(/[/?#].*$/, ''); + const bracketed = hostPort.match(/^\[([^\]]*)](:\d*)?$/); + if (bracketed) { + return bracketed[1]; + } + // A bare IPv6 address has several colons; a single one separates the port. + const parts = hostPort.split(':'); + return parts.length === 2 ? parts[0] : hostPort; +}; + +// localhost, 127.0.0.0/8, ::1 and 0.0.0.0: a device can't reach the server at any of them. +// Unlike DeviceConnectivityUtil.isLocalhost this doesn't resolve hostnames, and it also +// rejects 0.0.0.0, which isn't a loopback address but is just as unreachable. +// Takes a bare host (see toBareHost). +const isLoopbackHost = (host: string): boolean => { + const h = host.toLowerCase(); + return h === 'localhost' || h === '::1' || h === '0.0.0.0' || /^127(\.\d{1,3}){3}$/.test(h); +}; + +// Host name, IPv4 or IPv6 characters only: the value goes into C string literals and JSON templates. +const HOST_PATTERN = /^[a-z\d._:-]+$/i; + +const transportHostValidator = (control: AbstractControl): ValidationErrors | null => { + if (!control.value) { + return null; + } + const host = toBareHost(control.value); + return !HOST_PATTERN.test(host) || isLoopbackHost(host) ? { transportHost: true } : null; +}; + +const isValidPort = (port: number): boolean => Number.isInteger(port) && port >= 1 && port <= 65535; + +const transportPortValidator = (control: AbstractControl): ValidationErrors | null => + control.value === null || control.value === '' || isValidPort(Number(control.value)) ? null : { transportPort: true }; @Component({ selector: 'tb-device-install-dialog', @@ -108,15 +227,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; + private formTemplateSubscriptions: Subscription[] = []; entityOutputs = new Map(); transportVars: Record = {}; // Routing key pre-allocated for the in-flight INTEGRATION step so ${routingKey} // placeholders (e.g. inside clientConfiguration.httpEndpoint emitted by the // export pipeline) substitute to the value we'll save. private pendingRoutingKey: string | undefined; + // protocol → where the server took its host from + private transportHostSources: Partial> = {}; // form-field key → declared type. Used by resolveTemplateJson() to emit BOOLEAN/INTEGER // placeholders as raw JSON values instead of quoted strings. private fieldTypes = new Map(); + // Transport whose ${.host} the transport host field overrides + private hostFieldProtocol: DeviceConnectivityProtocol | null = null; gatewayDockerComposeContent: string | null = null; resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this); @@ -175,10 +299,11 @@ export class TbDeviceInstallDialogComponent extends DialogComponent subscription.unsubscribe()); + this.wizardSteps?.forEach(ws => clearTimeout(ws.connectionCheck?.resultTimer)); for (const url of this.zipImages.values()) { URL.revokeObjectURL(url); } @@ -299,7 +428,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { const step = this.currentWizardStep; if (!step) { return; @@ -308,6 +437,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.checkConnection); + } + + /** The result of the last check, while the form still has the values it checked. */ + connectionCheckResult(ws: WizardStep): ConnectionCheck['status'] | undefined { + const check = this.connectionCheckOf(ws); + if (!check || check.status === 'idle') { + return undefined; + } + if (check.status === 'checking' || check.checkedValues === this.checkedValuesOf(ws, check)) { + return check.status; + } + return undefined; + } + + async checkConnection(ws: WizardStep): Promise { + const check = this.connectionCheckOf(ws); + if (!check) { + return true; + } + if (ws.formGroup.invalid) { + ws.formGroup.markAllAsTouched(); + return false; + } + this.cleanFormStep(ws); + const values = ws.formGroup.getRawValue(); + check.status = 'checking'; + this.cdr.detectChanges(); + const committedValues = this.formValues; + let body: any; + try { + // The integration is built the way Provisioning builds it, from the values not committed yet + this.formValues = { ...committedValues, ...values }; + body = this.resolveTemplateJson(this.zipFiles.get(check.template)); + } finally { + this.formValues = committedValues; + } + // The check requires a routing key; Provisioning adds one the same way + if (!body.routingKey) body.routingKey = this.generateUuid(); + if (!body.configuration) body.configuration = {}; + if (body.configuration.metadata == null) body.configuration.metadata = {}; + try { + await firstValueFrom(this.integrationService.checkIntegrationConnection(body, { ignoreErrors: true })); + check.status = 'success'; + } catch { + check.status = 'error'; + } + check.checkedValues = this.checkedValuesOf(ws, check); + check.resultVisible = true; + clearTimeout(check.resultTimer); + check.resultTimer = setTimeout(() => { + check.resultVisible = false; + this.cdr.detectChanges(); + }, CONNECTION_CHECK_RESULT_MS); + this.cdr.detectChanges(); + return check.status === 'success'; + } + + /** What shows next to the button: the spinner while checking, then the result for a few seconds. */ + connectionCheckMessage(ws: WizardStep): ConnectionCheck['status'] | undefined { + const check = this.connectionCheckOf(ws); + if (check?.status === 'checking') { + return 'checking'; + } + return check?.resultVisible && check.checkedValues === this.checkedValuesOf(ws, check) ? check.status : undefined; + } + + /** True when the last check of the current values failed, so Next continues anyway. */ + get continueAnyway(): boolean { + const step = this.currentWizardStep; + return !!step && this.connectionCheckResult(step) === 'error'; + } + + /** + * The values of the connection fields: the ones the integration template puts into its configuration + * (host, port, credentials), not e.g. its name. Other fields don't reset the check result. + */ + private checkedValuesOf(ws: WizardStep, check: ConnectionCheck): string { + const content = this.zipFiles.get(check.template) ?? ''; + const configurationStart = content.indexOf('"configuration"'); + const template = configurationStart >= 0 ? content.substring(configurationStart) : content; + const values = this.cleanedFormValues(ws); + const used = ws.formFields + .filter(field => template.includes(`\${${field.key}}`)) + .map(field => [field.key, values[field.key]]); + return JSON.stringify(used); + } + + private findIntegrationTemplate(ws: WizardStep): string | undefined { + for (const step of this.wizardSteps.flatMap(w => w.rawSteps)) { + if (step.type !== InstallStepType.INTEGRATION || !step.template) { + continue; + } + const content = this.zipFiles.get(step.template) ?? ''; + if (ws.formFields.some(field => content.includes(`\${${field.key}}`))) { + return step.template; + } + } + return undefined; + } + onStepSelectionChange(event: StepperSelectionEvent): void { if (event.selectedIndex <= event.previouslySelectedIndex) { return; } // Forward moves can come from the stepper header, which bypasses nextStep(), // so commit every step being passed over here. + let formValuesChanged = false; for (let i = event.previouslySelectedIndex; i < event.selectedIndex; i++) { const ws = this.wizardSteps[i]; if (ws.type === 'form') { + // Keep the bare host, so the stored state and the form after Back show what the device gets + const hostControl = ws.formGroup.get(TRANSPORT_HOST_FIELD_KEY); + if (hostControl?.enabled && hostControl.value) { + hostControl.setValue(toBareHost(hostControl.value), { emitEvent: false }); + } + this.cleanFormStep(ws); Object.assign(this.formValues, ws.formGroup.getRawValue()); + formValuesChanged = true; } ws.completed = true; } + if (formValuesChanged) { + // Instruction steps stay rendered, and their markdown only changes when the resolver does: + // after Back and a corrected value, they would otherwise keep showing the old one. + this.resolveMarkdownVariable = this._resolveMarkdownVariable.bind(this); + } this.onStepActivated(this.wizardSteps[event.selectedIndex]); } @@ -498,6 +762,18 @@ export class TbDeviceInstallDialogComponent extends DialogComponent s.type === 'GATEWAY'); if (gatewayStep?.dockerCompose) { const raw = this.zipFiles.get(gatewayStep.dockerCompose); @@ -665,6 +943,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent.host} and ${.port} into sketches and templates. Show them + * in the last form before the host is first used. When the system administrator set the host in + * Device connectivity, they are read-only. Otherwise the user can correct them — and must, when + * the host resolved to localhost, which on the device is the device itself. + */ + private addTransportFields(fromIndex: number): void { + this.hostFieldProtocol = null; + const transport = HOST_FIELD_TRANSPORTS.get(this.selectedInstallMethod); + const protocol = transport?.protocol; + const resolvedHost = protocol ? this.transportVars[`${protocol}.host`] : undefined; + if (resolvedHost === undefined) { + return; + } + const steps = this.wizardSteps.slice(fromIndex); + const firstUse = steps.findIndex(ws => this.usesVariable(ws, `${protocol}.host`)); + if (firstUse < 0) { + return; + } + const loopback = !resolvedHost || isLoopbackHost(resolvedHost); + const hostSource = this.transportHostSources[protocol]; + const readOnly = hostSource === 'DEVICE_CONNECTIVITY' && !loopback; + let formStep = steps.slice(0, firstUse).reverse().find(ws => ws.type === 'form'); + if (!formStep) { + formStep = { + type: 'form', + label: this.translate.instant('iot-hub.device-install-transport-host-step'), + stateKey: TRANSPORT_STEP_STATE_KEY, + rawSteps: [], + completed: this.reviewMode + }; + this.wizardSteps.splice(fromIndex + firstUse, 0, formStep); + } + let hostHint: string; + if (readOnly) { + hostHint = transport.configuredHint; + } else if (this.reviewMode) { + hostHint = transport.reviewHostHint; + } else if (loopback) { + hostHint = (hostSource && transport.loopbackHints[hostSource]) || transport.loopbackHint; + } else { + hostHint = (hostSource && transport.hostHints[hostSource]) || transport.hostHints.REQUEST; + } + const helpPopupId = readOnly ? undefined : transport.helpPopupId; + const group = this.translate.instant('iot-hub.device-install-thingsboard-connection'); + formStep.extraFormFields = [{ + key: TRANSPORT_HOST_FIELD_KEY, + label: this.translate.instant(transport.hostLabel), + type: FormFieldType.STRING, + defaultValue: loopback ? '' : resolvedHost, + required: true, + readOnly, + helpText: this.translate.instant(hostHint, { host: resolvedHost }), + // Shown on the transportHost error of transportHostValidator + errorMessage: this.translate.instant(transport.hostError), + helpPopupId, + helpPopupText: helpPopupId ? this.translate.instant(transport.helpPopupText) : undefined, + group, + row: TRANSPORT_HOST_FIELD_KEY + }]; + if (steps.some(ws => this.usesVariable(ws, `${protocol}.port`))) { + const resolvedPort = Number(this.transportVars[`${protocol}.port`]); + formStep.extraFormFields.push({ + key: TRANSPORT_PORT_FIELD_KEY, + label: this.translate.instant(transport.portLabel), + type: FormFieldType.INTEGER, + defaultValue: isValidPort(resolvedPort) ? resolvedPort : '', + required: true, + readOnly, + // Shown on the transportPort error of transportPortValidator + errorMessage: this.translate.instant(transport.portError), + group, + row: TRANSPORT_HOST_FIELD_KEY, + width: 200 + }); + } + this.hostFieldProtocol = protocol; + } + + private usesVariable(ws: WizardStep, key: string): boolean { + const placeholder = `\${${key}}`; + return ws.rawSteps.some(step => + [step.file, step.template, step.serverAttributes, step.sharedAttributes, step.credentials, step.dockerCompose] + .some(file => file && this.zipFiles.get(file)?.includes(placeholder))); + } + private initFormStep(ws: WizardStep): void { - const formJson = this.zipFiles.get(ws.rawSteps[0].file) || '[]'; - ws.formFields = JSON.parse(formJson) as FormFieldDefinition[]; + const formJson = (ws.rawSteps[0] && this.zipFiles.get(ws.rawSteps[0].file)) || '[]'; + // These are for the fields the dialog adds; a package can't set them + const packageFields = (JSON.parse(formJson) as FormFieldDefinition[]) + .map(({ helpPopupId, helpPopupText, errorMessage, ...field }) => field); + ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; + const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -723,16 +1092,78 @@ export class TbDeviceInstallDialogComponent extends DialogComponent 0) { - validators.push(Validators.pattern(field.validators[0].pattern)); + const pattern = Validators.pattern(field.validators[0].pattern); + validators.push((control: AbstractControl) => + pattern({ value: cleanFormFieldValue(field, control.value) } as AbstractControl)); + } + if (field.key === TRANSPORT_HOST_FIELD_KEY) { + validators.push(transportHostValidator); + } else if (field.key === TRANSPORT_PORT_FIELD_KEY) { + validators.push(transportPortValidator); } const initialValue = this.resolveInitialFieldValue(field, storedValues?.[field.key]); - controls[field.key] = new UntypedFormControl(initialValue, validators); + controls[field.key] = new UntypedFormControl({ value: initialValue, disabled: !!field.readOnly }, validators); } ws.formGroup = new UntypedFormGroup(controls); if (this.reviewMode) { ws.formGroup.disable(); ws.completed = true; + } else { + this.applyDefaultValueTemplates(ws, storedValues); + } + } + + /** + * Keeps each field with a defaultValueTemplate filled from the other fields until the user edits it. + * A template with an empty field gives an empty value, so the placeholder shows instead. + */ + private applyDefaultValueTemplates(ws: WizardStep, storedValues: Record | undefined): void { + const templated = ws.formFields.filter(field => field.defaultValueTemplate && storedValues?.[field.key] === undefined); + if (!templated.length) { + return; + } + const update = () => { + for (const field of templated) { + const control = ws.formGroup.controls[field.key]; + if (!control.dirty) { + control.setValue(this.renderFormTemplate(field.defaultValueTemplate, this.cleanedFormValues(ws)), { emitEvent: false }); + } + } + }; + update(); + this.formTemplateSubscriptions.push(ws.formGroup.valueChanges.subscribe(update)); + } + + /** Applies each field's cleanupPattern to its control, so the stored values are the cleaned ones. */ + private cleanFormStep(ws: WizardStep): void { + for (const field of ws.formFields) { + const control = ws.formGroup.controls[field.key]; + const cleaned = cleanFormFieldValue(field, control?.value); + if (control?.enabled && cleaned !== control.value) { + control.setValue(cleaned, { emitEvent: false }); + } + } + } + + private cleanedFormValues(ws: WizardStep): Record { + const values = ws.formGroup.getRawValue(); + for (const field of ws.formFields) { + values[field.key] = cleanFormFieldValue(field, values[field.key]); } + return values; + } + + private renderFormTemplate(template: string, values: Record): string { + let missing = false; + const result = template.replace(/\$\{([^}]+)}/g, (_, key: string) => { + const value = values[key]; + if (value === undefined || value === null || value === '') { + missing = true; + return ''; + } + return String(value); + }); + return missing ? '' : result; } private resolveInitialFieldValue(field: FormFieldDefinition, storedValue: any): any { @@ -1252,7 +1683,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; for (const ws of this.wizardSteps) { if (ws.type === 'form' && ws.formGroup) { - state[ws.label] = { formValues: ws.formGroup.getRawValue() }; + state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() }; } else if (ws.type === 'progress' && ws.entitySteps) { for (const ep of ws.entitySteps) { if (ep.status === 'success' && ep.entityOutput) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index cdd06ae7b2..b7d1b7a978 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -7,19 +7,78 @@ --> @if (formGroup) {
- @for (field of fields; track field.key; let i = $index) { + + @if (advancedSections.length) { +
+ + + {{ 'iot-hub.advanced-settings' | translate }} + +
+ +
+
+
+ } + + + @for (section of sections; track $index) { + @if (section.title) { +
+

{{ section.title }}

+ +
+ } @else { + + } + } +
- @if (shouldRenderGroupHeader(field, i)) { -

{{ field.group }}

+ + @for (row of rows; track row.fields[0].key) { +
+ @if (row.fields.length > 1) { +
+ @for (field of row.fields; track field.key) { +
+ +
+ } +
+ } @else { + + } + + @for (field of row.fields; track field.key) { + @if (hasHintBox(field)) { +
+
{{ helpTextOf(field) }}
+
+
+ } + } + @if (checkConnectionTemplate && hasCheckConnectionField(row.fields)) { + + } +
} +
+ @if (isSecretWidget(field)) { } @else { @@ -29,15 +88,16 @@ {{ field.label }} } @case (FormFieldType.SELECT) { - + {{ field.label }} @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -45,16 +105,19 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - + {{ field.label }} - + @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -62,13 +125,19 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @case (FormFieldType.PASSWORD) { - + {{ field.label }} + [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" + [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" + autocomplete="new-password" data-lpignore="true" data-1p-ignore data-bwignore> } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -90,14 +159,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 }} + + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -105,12 +180,18 @@ @if (formGroup.controls[field.key]?.hasError('pattern')) { {{ getPatternErrorMessage(field) }} } + @if (field.errorMessage && hasFieldError(field)) { + {{ field.errorMessage }} + } } @default { - + {{ field.label }} - + @if (field.randomGenerator) { } - @if (field.helpText) { - {{ field.helpText }} + @if (helpTextOf(field) && !hasHintBox(field)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -128,17 +209,20 @@ @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.type === FormFieldType.BOOLEAN && helpTextOf(field)) { +
{{ helpTextOf(field) }}
} @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..9acd239c18 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,13 +5,6 @@ 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; 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..fedef617df 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 @@ -1,13 +1,25 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // 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 { Component, Input, OnChanges, SimpleChanges, TemplateRef } from '@angular/core'; +import { AbstractControl, UntypedFormGroup } from '@angular/forms'; +import { ErrorStateMatcher } from '@angular/material/core'; +import { cleanFormFieldValue, FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models'; import { generateSecret } from '@core/utils'; const DEFAULT_RANDOM_SIZE = 20; +/** Fields shown on one line. */ +interface FormRow { + fields: FormFieldDefinition[]; +} + +/** 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,10 +44,49 @@ 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; + /** Rendered under the field marked with checkConnection; the dialog supplies it. */ + @Input() checkConnectionTemplate?: TemplateRef | null; 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 rowOf = new Map(); + private focusedControl: AbstractControl | null = null; + private keepFocusedError = false; + + /** + * 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; + + /** Render this field via the Secret picker widget (tb-secret-key-input). The picker + * itself accepts both plaintext and Secret references, so secretSupport=true means + * "this field MAY hold a Secret reference and the picker UI should be shown". */ + isSecretWidget(field: FormFieldDefinition): boolean { + return field.secretSupport === true; + } ngOnChanges(changes: SimpleChanges): void { + if (changes.fields) { + this.rowOf.clear(); + const fields = this.fields ?? []; + this.sections = this.buildSections(fields.filter(field => field.section !== 'advanced')); + this.advancedSections = this.buildSections(fields.filter(field => field.section === 'advanced')); + } if (changes.fields || changes.reviewMode) { this.passwordVisible = {}; if (this.reviewMode) { @@ -48,20 +99,33 @@ export class InstallFormRendererComponent implements OnChanges { } } - readonly FormFieldType = FormFieldType; + 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]; + if (field.row && last?.fields[0].row === field.row) { + last.fields.push(field); + } else { + rows.push({ fields: [field] }); + } + this.rowOf.set(field.key, rows[rows.length - 1]); + previous = field; + } + return sections; + } - /** Render this field via the Secret picker widget (tb-secret-key-input). The picker - * itself accepts both plaintext and Secret references, so secretSupport=true means - * "this field MAY hold a Secret reference and the picker UI should be shown". */ - isSecretWidget(field: FormFieldDefinition): boolean { - return field.secretSupport === true; + hasCheckConnectionField(fields: FormFieldDefinition[]): boolean { + return fields.some(field => field.checkConnection); } - /** 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; + /** 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,10 +139,44 @@ export class InstallFormRendererComponent implements OnChanges { 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 cleaned = cleanFormFieldValue(field, control?.value); + if (control && cleaned !== control.value) { + control.setValue(cleaned); + } + } + getPatternErrorMessage(field: FormFieldDefinition): string { return field.validators?.[0]?.message || 'Invalid format'; } + /** Fields with a help popup show their hint in a box under the row, with the popup trigger. */ + hasHintBox(field: FormFieldDefinition): boolean { + return !!field.helpPopupId && !this.reviewMode; + } + + /** + * True for the fields of a row that has a hint box. They don't reserve space for a hint or an + * error, so the box sits right under them. + */ + isInHintBoxRow(field: FormFieldDefinition): boolean { + return !!this.rowOf.get(field.key)?.fields.some(f => this.hasHintBox(f)); + } + + /** 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; } 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..b04932040d 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 @@ -4,12 +4,13 @@ import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of, EMPTY } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; +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 { 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'; @@ -35,7 +36,8 @@ export class IotHubActionsService { private dialog: MatDialog, private dialogService: DialogService, private translate: TranslateService, - private builtInService: IotHubBuiltInService + private builtInService: IotHubBuiltInService, + private iotHubApiService: IotHubApiService ) {} openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, @@ -166,12 +168,18 @@ export class IotHubActionsService { 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: 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..60eb673a23 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,13 @@

{{ '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 }}

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..56a9c82543 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,21 @@ // 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'; export interface IotHubDeleteDialogData { installedItemId: string; itemName: string; itemType?: string; + keptEntities?: IotHubInstalledItemKeptEntities | null; } @Component({ @@ -23,14 +26,19 @@ export interface IotHubDeleteDialogData { }) export class TbIotHubDeleteDialogComponent extends DialogComponent { + description: string; + 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); + this.description = data.keptEntities?.entities.length ? this.describeKeptEntities(data.keptEntities) : + this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); } confirm(): void { @@ -44,4 +52,17 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent { + const key = `iot-hub.remove-kept-entity.${entity.entityId.entityType}`; + const named = this.translate.instant(key, { name: entity.name }); + return named === key ? `'${entity.name}'` : named; + }); + const entities = names.length === 1 ? names[0] : + this.translate.instant('iot-hub.remove-kept-entities', { first: names.slice(0, -1).join(', '), last: names[names.length - 1] }); + return this.translate.instant('iot-hub.remove-desc-kept', + { entities, count: kept.usedByItemsCount, kept: kept.entities.length }); + } } 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..ab41384640 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 @@
@@ -88,9 +89,12 @@ info_outline } - + + + + @@ -107,9 +111,9 @@ {{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }} } -
} @else { - + } @for (field of row.fields; track field.key) { - @if (hasHintBox(field)) { + @if (row.hasHintBox && field.helpPopupId) {
{{ helpTextOf(field) }}
- + @if (isSecretWidget(field)) { {{ field.label }} } @case (FormFieldType.SELECT) { - {{ field.label }} @@ -96,7 +96,7 @@ {{ opt.label }} } - @if (helpTextOf(field) && !hasHintBox(field)) { + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { @@ -105,7 +105,7 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }} {{ opt.label }} } - @if (helpTextOf(field) && !hasHintBox(field)) { + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { @@ -131,7 +131,7 @@ } @case (FormFieldType.PASSWORD) { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !hasHintBox(field)) { + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { @@ -165,13 +165,13 @@ } @case (FormFieldType.INTEGER) { - {{ field.label }} - @if (helpTextOf(field) && !hasHintBox(field)) { + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { @@ -186,7 +186,7 @@ } @default { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !hasHintBox(field)) { + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { 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 fedef617df..e1c525c770 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 @@ -9,9 +9,14 @@ import { generateSecret } from '@core/utils'; const DEFAULT_RANDOM_SIZE = 20; -/** Fields shown on one line. */ +/** + * 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. */ @@ -53,7 +58,6 @@ export class InstallFormRendererComponent implements OnChanges { sections: FormSection[] = []; // The same for the fields of the collapsed Advanced settings panel advancedSections: FormSection[] = []; - private rowOf = new Map(); private focusedControl: AbstractControl | null = null; private keepFocusedError = false; @@ -81,8 +85,8 @@ export class InstallFormRendererComponent implements OnChanges { } ngOnChanges(changes: SimpleChanges): void { - if (changes.fields) { - this.rowOf.clear(); + // The hint boxes 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')); @@ -108,12 +112,13 @@ export class InstallFormRendererComponent implements OnChanges { } 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] }); + rows.push({ fields: [field], hasHintBox }); } - this.rowOf.set(field.key, rows[rows.length - 1]); previous = field; } return sections; @@ -158,19 +163,6 @@ export class InstallFormRendererComponent implements OnChanges { return field.validators?.[0]?.message || 'Invalid format'; } - /** Fields with a help popup show their hint in a box under the row, with the popup trigger. */ - hasHintBox(field: FormFieldDefinition): boolean { - return !!field.helpPopupId && !this.reviewMode; - } - - /** - * True for the fields of a row that has a hint box. They don't reserve space for a hint or an - * error, so the box sits right under them. - */ - isInHintBoxRow(field: FormFieldDefinition): boolean { - return !!this.rowOf.get(field.key)?.fields.some(f => this.hasHintBox(f)); - } - /** 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; diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index d45e5d1964..a717d97a0d 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -279,7 +279,7 @@ export interface FormFieldDefinition { // (tb-secret-key-input); false / undefined → render the typed widget. secretSupport?: boolean; secretType?: SecretType; - // Fields with the same group get one header above the first of them + // Consecutive fields with the same group are shown in one panel titled with the group group?: string; readOnly?: boolean; // Shown inside the empty field; the label then always stays above it From e662441d252adf11127c4c663634870049392483 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 26 Oct 2026 12:50:26 +0200 Subject: [PATCH 04/66] refactor(iot-hub): build the form rows and the unmasked passwords in one ngOnChanges block (cherry picked from commit ce741cf2deee263628c33cecad84dd669a4d6709) --- .../install-form-renderer.component.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) 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 e1c525c770..e1c73ecafa 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 @@ -85,18 +85,16 @@ export class InstallFormRendererComponent implements OnChanges { } ngOnChanges(changes: SimpleChanges): void { - // The hint boxes depend on reviewMode too + // 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')); - } - 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; + for (const field of fields) { + if (field.type === FormFieldType.PASSWORD) { + this.passwordVisible[field.key] = true; } } } From 41143a17564961e9bfb59806481874075b0062b3 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 27 Oct 2026 18:56:19 +0200 Subject: [PATCH 05/66] feat(iot-hub): the device install form checks the connection on Next, splits a pasted port and shows toggles - A form field with checkConnection makes Next: Provisioning check the integration connection. The form waits while it runs, and a failed check opens an alert titled with the install method that shows the field's checkConnectionFailedText (or a general text) and keeps the user on the form. The separate Check connection button is gone. - A field with portField moves a port pasted at the end of its value into the named field. - BOOLEAN fields render as a slide toggle in a form row, with the help text in the hint icon. --- .../device-install-dialog.component.html | 46 +++--------- .../device-install-dialog.component.scss | 17 +---- .../device-install-dialog.component.ts | 73 ++++++++----------- .../install-form-renderer.component.html | 16 ++-- .../install-form-renderer.component.scss | 6 -- .../install-form-renderer.component.ts | 16 ++-- .../models/iot-hub/device-package.models.ts | 26 ++++++- 7 files changed, 81 insertions(+), 119 deletions(-) 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 8f36545817..11499fe154 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,43 +49,14 @@ } @case ('form') { -
+
+ [reviewMode]="reviewMode"> - -
- - @switch (connectionCheckMessage(ws)) { - @case ('checking') { - - } - @case ('success') { - - check_circle - {{ 'iot-hub.connection-check-success' | translate }} - - } - @case ('error') { - - error - {{ 'iot-hub.connection-check-failed' | translate }} - - } - } -
-
- @if (connectionCheckOf(ws) && !hasCheckConnectionField(ws)) { - - }
} @@ -256,7 +227,7 @@ @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -281,9 +252,12 @@ } @case ('form') { -
} } - @if (checkConnectionTemplate && hasCheckConnectionField(row.fields)) { - - }
} @@ -85,7 +82,15 @@ @switch (field.type) { @case (FormFieldType.BOOLEAN) { - {{ field.label }} +
+ + @if (helpTextOf(field)) { +
{{ field.label }}
+ } @else { + {{ field.label }} + } +
+
} @case (FormFieldType.SELECT) { {{ helpTextOf(field) }}
- } @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 9acd239c18..f99f29ebca 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 @@ -10,12 +10,6 @@ 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; 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 e1c73ecafa..6965009871 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 @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { Component, Input, OnChanges, SimpleChanges, TemplateRef } from '@angular/core'; +import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, UntypedFormGroup } from '@angular/forms'; import { ErrorStateMatcher } from '@angular/material/core'; -import { cleanFormFieldValue, FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models'; +import { cleanFormFieldValue, FormFieldDefinition, FormFieldType, pastedPortOf } from '@shared/models/iot-hub/device-package.models'; import { generateSecret } from '@core/utils'; const DEFAULT_RANDOM_SIZE = 20; @@ -49,8 +49,6 @@ 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; - /** Rendered under the field marked with checkConnection; the dialog supplies it. */ - @Input() checkConnectionTemplate?: TemplateRef | null; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields @@ -122,10 +120,6 @@ export class InstallFormRendererComponent implements OnChanges { return sections; } - hasCheckConnectionField(fields: FormFieldDefinition[]): boolean { - return fields.some(field => field.checkConnection); - } - /** 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; @@ -151,6 +145,12 @@ export class InstallFormRendererComponent implements OnChanges { 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); diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index a717d97a0d..b707ac353d 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -110,7 +110,7 @@ export const installMethodLabels = new Map( [InstallMethod.INTEGRATION_TCP, 'TCP Integration'], [InstallMethod.INTEGRATION_THINGPARK, 'ThingPark Wireless'], [InstallMethod.INTEGRATION_THINGPARK_ENTERPRISE, 'ThingPark Enterprise'], - [InstallMethod.INTEGRATION_TTI, 'The Things Stack Cloud'], + [InstallMethod.INTEGRATION_TTI, 'The Things Stack Cloud & Enterprise'], [InstallMethod.INTEGRATION_TTN, 'The Things Stack Sandbox'], [InstallMethod.INTEGRATION_TUYA, 'Tuya'], [InstallMethod.INTEGRATION_UDP, 'UDP Integration'] @@ -291,12 +291,16 @@ export interface FormFieldDefinition { defaultValueTemplateHelpText?: string; // 'advanced' puts the field into the collapsed Advanced settings panel below the form section?: FormFieldSection; - // Shows the Check connection button of the integration the form configures under this field + // Next checks the connection of the integration the form configures and stops on a failure checkConnection?: boolean; + // With checkConnection: the text of the dialog a failed check shows + checkConnectionFailedText?: string; // A regular expression whose matches are removed from the value when the user leaves the field // and before the step is committed, e.g. "@ttn$" for an ID copied with its suffix. // validators check the cleaned value. cleanupPattern?: string; + // Key of the field that takes the port pasted at the end of this field's value, e.g. "host:8883" + portField?: string; // Set by the install dialog for the fields it adds, not by packages: // help popup shown under the field, and the text of its trigger helpPopupId?: string; @@ -311,8 +315,22 @@ export interface FormFieldDefinition { export type FormFieldSection = 'advanced'; -export const cleanFormFieldValue = (field: FormFieldDefinition, value: any): any => - field.cleanupPattern && typeof value === 'string' ? value.replace(new RegExp(field.cleanupPattern, 'g'), '') : value; +const PASTED_PORT_PATTERN = /:(\d{1,5})\/*\s*$/; + +/** The value without the port that portField takes, then without the cleanupPattern matches. */ +export const cleanFormFieldValue = (field: FormFieldDefinition, value: any): any => { + if (typeof value !== 'string') { + return value; + } + const withoutPort = field.portField ? value.replace(PASTED_PORT_PATTERN, '') : value; + return field.cleanupPattern ? withoutPort.replace(new RegExp(field.cleanupPattern, 'g'), '') : withoutPort; +}; + +/** The port at the end of the value of a field with portField, e.g. 8883 for "eu1.example.com:8883". */ +export const pastedPortOf = (field: FormFieldDefinition, value: any): number | undefined => { + const match = field.portField && typeof value === 'string' ? PASTED_PORT_PATTERN.exec(value) : null; + return match ? Number(match[1]) : undefined; +}; export interface EntityStepOutput { id: string; From 082fc3205844035c90e8ed0fbfd07cad7d20276b Mon Sep 17 00:00:00 2001 From: dshvaika Date: Tue, 27 Oct 2026 18:56:19 +0200 Subject: [PATCH 06/66] feat(iot-hub): name the TTI install method and integration type The Things Stack Cloud & Enterprise --- ui-ngx/src/assets/locale/locale.constant-ar_AE.json | 2 +- ui-ngx/src/assets/locale/locale.constant-ca_ES.json | 2 +- ui-ngx/src/assets/locale/locale.constant-da_DK.json | 2 +- ui-ngx/src/assets/locale/locale.constant-de_DE.json | 2 +- ui-ngx/src/assets/locale/locale.constant-el_GR.json | 2 +- ui-ngx/src/assets/locale/locale.constant-en_US.json | 10 +++++----- ui-ngx/src/assets/locale/locale.constant-es_ES.json | 2 +- ui-ngx/src/assets/locale/locale.constant-fr_FR.json | 2 +- ui-ngx/src/assets/locale/locale.constant-hi_IN.json | 2 +- ui-ngx/src/assets/locale/locale.constant-it_IT.json | 2 +- ui-ngx/src/assets/locale/locale.constant-ja_JP.json | 2 +- ui-ngx/src/assets/locale/locale.constant-lt_LT.json | 2 +- ui-ngx/src/assets/locale/locale.constant-nl_NL.json | 2 +- ui-ngx/src/assets/locale/locale.constant-no_NO.json | 2 +- ui-ngx/src/assets/locale/locale.constant-pl_PL.json | 2 +- ui-ngx/src/assets/locale/locale.constant-pt_BR.json | 2 +- ui-ngx/src/assets/locale/locale.constant-tr_TR.json | 2 +- ui-ngx/src/assets/locale/locale.constant-uk_UA.json | 2 +- ui-ngx/src/assets/locale/locale.constant-zh_CN.json | 2 +- 19 files changed, 23 insertions(+), 23 deletions(-) diff --git a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json index 238062e445..9b25b862d7 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ar_AE.json +++ b/ui-ngx/src/assets/locale/locale.constant-ar_AE.json @@ -3626,7 +3626,7 @@ "type-ibm-watson-iot-description": "خدمة مُدارة بالكامل على السحابة.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "شبكة LoRaWAN المفتوحة والمركزة.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "برنامج لتشغيل شبكات LoRaWAN الخاصة بنطاق واسع.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "خادم تكوين شبكة LoRaWAN.", diff --git a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json index 2f6d4040d9..75557d2ed8 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ca_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-ca_ES.json @@ -3050,7 +3050,7 @@ "type-aws-kinesis": "AWS Kinesis", "type-ibm-watson-iot": "IBM Watson IoT", "type-ttn": "The Things Stack Sandbox", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-chirpstack": "ChirpStack", "type-azure-event-hub": "Azure Event Hub", "type-azure-iot-hub": "Azure IoT Hub", diff --git a/ui-ngx/src/assets/locale/locale.constant-da_DK.json b/ui-ngx/src/assets/locale/locale.constant-da_DK.json index b3c53700be..2fb93d0171 100644 --- a/ui-ngx/src/assets/locale/locale.constant-da_DK.json +++ b/ui-ngx/src/assets/locale/locale.constant-da_DK.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "Tjeneste til realtids video- og datastrømme.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Åbent og decentraliseret LoRaWAN-netværk.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software til drift af private LoRaWAN-netværk i stor skala.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN-netværkskonfigurationstjeneste.", diff --git a/ui-ngx/src/assets/locale/locale.constant-de_DE.json b/ui-ngx/src/assets/locale/locale.constant-de_DE.json index 3db3ab6800..0be24c2909 100644 --- a/ui-ngx/src/assets/locale/locale.constant-de_DE.json +++ b/ui-ngx/src/assets/locale/locale.constant-de_DE.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Dienst für Echtzeit-Video- und Datenströme.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Offenes und dezentrales LoRaWAN-Netzwerk.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software zum Betrieb privater LoRaWAN-Netzwerke im großen Maßstab.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-el_GR.json b/ui-ngx/src/assets/locale/locale.constant-el_GR.json index fbea64bf30..928afe9da8 100644 --- a/ui-ngx/src/assets/locale/locale.constant-el_GR.json +++ b/ui-ngx/src/assets/locale/locale.constant-el_GR.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "Υπηρεσία ροής δεδομένων και βίντεο σε πραγματικό χρόνο.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Ανοιχτό και αποκεντρωμένο δίκτυο LoRaWAN.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Λογισμικό για ιδιωτικά δίκτυα LoRaWAN.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "Διακομιστής διαμόρφωσης δικτύου LoRaWAN.", diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 19822cadae..0e0b2c893c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -5694,7 +5694,7 @@ "type-aws-kinesis-description": "Service for real-time video and data streams.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Open and decentralized LoRaWAN network.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software to operate private LoRaWAN networks at scale.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", @@ -6287,10 +6287,10 @@ }, "iot-hub": { "advanced-settings": "Advanced settings", - "check-connection": "Check connection", - "connection-check-success": "Connected.", - "connection-check-failed": "Could not connect. Check the connection settings and the credentials.", - "continue-anyway": "Continue anyway", + "back-to-configuration": "Back to configuration", + "checking-connection": "Checking connection…", + "connection-check-failed-title": "Failed to connect to {{method}}", + "connection-check-failed-text": "Check the connection settings, then try again.", "iot-hub": "IoT Hub", "generate-random-value": "Generate random value", "home-title": "ThingsBoard IoT Hub", diff --git a/ui-ngx/src/assets/locale/locale.constant-es_ES.json b/ui-ngx/src/assets/locale/locale.constant-es_ES.json index 1f94ccd579..341bdfa40e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-es_ES.json +++ b/ui-ngx/src/assets/locale/locale.constant-es_ES.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Servicio para transmisión de datos y video en tiempo real.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Red LoRaWAN abierta y descentralizada.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software para operar redes LoRaWAN privadas a escala.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json index 4185c7d673..4fd4b3e797 100644 --- a/ui-ngx/src/assets/locale/locale.constant-fr_FR.json +++ b/ui-ngx/src/assets/locale/locale.constant-fr_FR.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Service pour le traitement de flux vidéo et de données en temps réel.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Réseau LoRaWAN ouvert et décentralisé.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Logiciel pour exploiter des réseaux LoRaWAN privés à grande échelle.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json index 7cb1ee68e0..2b3d37af18 100644 --- a/ui-ngx/src/assets/locale/locale.constant-hi_IN.json +++ b/ui-ngx/src/assets/locale/locale.constant-hi_IN.json @@ -4854,7 +4854,7 @@ "type-aws-kinesis-description": "रीयल-टाइम वीडियो और डेटा स्ट्रीम्स के लिए सेवा.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "ओपन और डिसेंट्रलाइज़्ड LoRaWAN नेटवर्क.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "बड़े स्तर पर प्राइवेट LoRaWAN नेटवर्क ऑपरेट करने के लिए सॉफ़्टवेयर.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN नेटवर्क कॉन्फ़िगरेशन सर्वर.", diff --git a/ui-ngx/src/assets/locale/locale.constant-it_IT.json b/ui-ngx/src/assets/locale/locale.constant-it_IT.json index 09376d0cec..d89c64c08f 100644 --- a/ui-ngx/src/assets/locale/locale.constant-it_IT.json +++ b/ui-ngx/src/assets/locale/locale.constant-it_IT.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Servizio per flussi video e dati in tempo reale.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Rete LoRaWAN aperta e decentralizzata.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software per reti private LoRaWAN su larga scala.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json index 569d17f7a5..1cc5650d1d 100644 --- a/ui-ngx/src/assets/locale/locale.constant-ja_JP.json +++ b/ui-ngx/src/assets/locale/locale.constant-ja_JP.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "リアルタイムのビデオおよびデータストリームサービス。", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "オープンで分散型のLoRaWANネットワーク。", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "スケールでプライベートLoRaWANネットワークを運用するためのソフトウェア。", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWANネットワーク構成サーバー。", diff --git a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json index b13f82cd5c..3bdf99f170 100644 --- a/ui-ngx/src/assets/locale/locale.constant-lt_LT.json +++ b/ui-ngx/src/assets/locale/locale.constant-lt_LT.json @@ -4341,7 +4341,7 @@ "type-aws-kinesis-description": "Realaus laiko vaizdo ir duomenų srautai.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Atviras ir decentralizuotas LoRaWAN tinklas.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Programinė įranga privačioms LoRaWAN tinklams masteliuoti.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN tinklo konfigūravimo serveris.", diff --git a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json index 53150314c1..9c32ca6fcc 100644 --- a/ui-ngx/src/assets/locale/locale.constant-nl_NL.json +++ b/ui-ngx/src/assets/locale/locale.constant-nl_NL.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "Dienst voor realtime video- en datastromen.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Open en gedecentraliseerd LoRaWAN-netwerk.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software om privé LoRaWAN-netwerken op schaal te beheren.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN-netwerkconfiguratieserver.", diff --git a/ui-ngx/src/assets/locale/locale.constant-no_NO.json b/ui-ngx/src/assets/locale/locale.constant-no_NO.json index ff10d16752..3d5a817173 100644 --- a/ui-ngx/src/assets/locale/locale.constant-no_NO.json +++ b/ui-ngx/src/assets/locale/locale.constant-no_NO.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "Tjeneste for sanntidsvideo og datastrømmer.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Åpent og desentralisert LoRaWAN-nettverk.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Programvare for å drive private LoRaWAN-nettverk i stor skala.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "Konfigurasjonsserver for LoRaWAN-nettverk.", diff --git a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json index ddae826d81..be600a572c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pl_PL.json +++ b/ui-ngx/src/assets/locale/locale.constant-pl_PL.json @@ -3543,7 +3543,7 @@ "type-ibm-watson-iot-description": "W pełni zarządzana usługa hostowana w chmurze.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Otwarta i zdecentralizowana sieć LoRaWAN.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Oprogramowanie do obsługi prywatnych sieci LoRaWAN na dużą skalę.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "Serwer konfiguracji sieci LoRaWAN.", diff --git a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json index a39b81493a..352563c216 100644 --- a/ui-ngx/src/assets/locale/locale.constant-pt_BR.json +++ b/ui-ngx/src/assets/locale/locale.constant-pt_BR.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Serviço para streams de vídeo e dados em tempo real.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Rede LoRaWAN aberta e descentralizada.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Software para operar redes LoRaWAN privadas em escala.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json index 5174a42982..11af893b7c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-tr_TR.json +++ b/ui-ngx/src/assets/locale/locale.constant-tr_TR.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "Gerçek zamanlı video ve veri akış hizmeti.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Açık ve merkeziyetsiz LoRaWAN ağı.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Ölçeklenebilir özel LoRaWAN ağlarını çalıştırmak için yazılım.", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN ağı yapılandırma sunucusu.", diff --git a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json index a44b237554..73aa65c360 100644 --- a/ui-ngx/src/assets/locale/locale.constant-uk_UA.json +++ b/ui-ngx/src/assets/locale/locale.constant-uk_UA.json @@ -5692,7 +5692,7 @@ "type-aws-kinesis-description": "Сервіс для потоків відео та даних у реальному часі.", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "Відкрита та децентралізована мережа LoRaWAN.", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "Програмне забезпечення для масштабованої експлуатації приватних мереж LoRaWAN.", "type-things-stack": "The Things Stack", "type-chirpstack": "ChirpStack", diff --git a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json index ced59136bb..2583e70fc1 100644 --- a/ui-ngx/src/assets/locale/locale.constant-zh_CN.json +++ b/ui-ngx/src/assets/locale/locale.constant-zh_CN.json @@ -4853,7 +4853,7 @@ "type-aws-kinesis-description": "实时视频和数据流服务。", "type-ttn": "The Things Stack Sandbox", "type-ttn-description": "开放去中心化的 LoRaWAN 网络。", - "type-tti": "The Things Stack Cloud", + "type-tti": "The Things Stack Cloud & Enterprise", "type-tti-description": "用于大规模运营私有 LoRaWAN 网络的软件。", "type-chirpstack": "ChirpStack", "type-chirpstack-description": "LoRaWAN 网络配置服务器。", From d53982905a1f2e2a4c76274e3e9af2bb5543092b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 12:58:29 +0200 Subject: [PATCH 07/66] fix(iot-hub): update a device package in place instead of deleting its entities Updating an installed device package deleted everything the package created, the device included, so its telemetry and attributes were lost, and nothing was installed again. Now the update opens the install wizard of the new version over the installed package. It keeps the install method and the form values, finds the entities by the ids in the install state (so a renamed profile is still found), keeps the device and gateway as they are (id, credentials, history) and overwrites the device profile, converters, integration, dashboard and rule chain with the new templates under their current names. The installed item then takes the new version through registerDeviceUpdate. The server no longer updates a device package by itself. PROD-9096 --- .../server/controller/IotHubController.java | 4 + .../service/iot_hub/DefaultIotHubService.java | 45 ++++- .../server/service/iot_hub/IotHubService.java | 2 + .../iot_hub/DefaultIotHubServiceTest.java | 55 ++++++ .../src/app/core/http/iot-hub-api.service.ts | 7 +- .../device-install-dialog.component.ts | 166 +++++++++++++++--- .../iot-hub/iot-hub-actions.service.ts | 20 ++- 7 files changed, 265 insertions(+), 34 deletions(-) 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 1645505c00..e5388bd28b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -92,9 +92,13 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, + @RequestParam(required = false) UUID installedItemId, @RequestBody JsonNode body) throws ThingsboardException { checkAllPermissions(); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); + if (installedItemId != null) { + return iotHubService.registerDeviceUpdate(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, descriptor); + } return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } 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 a3cf0599fa..6f0f9db86f 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 @@ -416,6 +416,10 @@ public class DefaultIotHubService implements IotHubService { } String itemType = installedItem.getItemType(); + if ("DEVICE".equals(itemType)) { + // The install wizard of the new version changes the package's entities in place, see registerDeviceUpdate + 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 @@ -460,12 +464,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, installedItemId, dd.getCreatedEntityIds(), user); - dd.setCreatedEntityIds(null); - dd.setDashboardId(null); - } case "SOLUTION_TEMPLATE" -> { SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor; solutionService.deleteSolution(tenantId, stDescriptor, user); @@ -710,6 +708,41 @@ public class DefaultIotHubService implements IotHubService { } } + @Override + public InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, + DeviceInstalledItemDescriptor descriptor) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Registering device package update of {} to version: {}", tenantId, installedItemId, versionId); + + try { + IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); + if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())) { + throw new IllegalArgumentException("Installed device package not found"); + } + + JsonNode versionInfo = iotHubRestClient.getVersionInfo(versionId); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + if (!installedItem.getItemId().toString().equals(versionInfo.get("itemId").asText())) { + throw new IllegalArgumentException("The version belongs to another item"); + } + + // The wizard has already changed the entities in place: a failure here must not delete them + installedItem.setItemVersionId(UUID.fromString(versionId)); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(descriptor); + iotHubInstalledItemService.save(tenantId, installedItem); + log.info("[{}] Registered device package update: {} (version {})", tenantId, installedItem.getItemName(), installedItem.getVersion()); + + return InstallItemVersionResult.success(descriptor); + } catch (Exception e) { + log.error("[{}] Failed to register device package update of {} to version: {}", tenantId, installedItemId, versionId, e); + return InstallItemVersionResult.error(e.getMessage()); + } + } + /** * 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. 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 e1d0cd666b..3a3fd372b0 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 @@ -19,6 +19,8 @@ public interface IotHubService { InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor); + InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, DeviceInstalledItemDescriptor descriptor); + void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); 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 0f0068872c..cf4f25bfd7 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 @@ -495,6 +495,61 @@ class DefaultIotHubServiceTest { 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()); + } + + @Test + void registerDeviceUpdate_keepsTheInstalledItemAndRecordsTheNewVersion() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem installed = devicePackage(deviceId); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + installed.setVersion("1.0"); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, installed.getItemId().toString(), "DEVICE", "AM308", "1.1")); + DeviceInstalledItemDescriptor updated = new DeviceInstalledItemDescriptor(); + updated.setCreatedEntityIds(List.of(deviceId)); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, updated); + + assertThat(result.isSuccess()).isTrue(); + verify(iotHubInstalledItemService).save(tenantId, installed); + assertThat(installed.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(installed.getVersion()).isEqualTo("1.1"); + assertThat(installed.getDescriptor()).isSameAs(updated); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + } + + @Test + void registerDeviceUpdate_versionOfAnotherItem_isRejected() { + mockTenant(); + IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID())); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Other", "1.0")); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, new DeviceInstalledItemDescriptor()); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); 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 49da0f4e6a..639127e075 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 @@ -180,10 +180,13 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig + config?: IotHubRequestConfig, + // Set for an update: the installed item takes the version and the descriptor + installedItemId?: string ): Observable { + const installedItemParam = installedItemId ? `&installedItemId=${installedItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, + `/api/iot-hub/device/register?versionId=${versionId}${installedItemParam}`, { type: 'DEVICE', ...descriptor }, { params: this.buildParams(config) } ); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 0f2a99df36..ea37b3bbe5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -14,6 +14,7 @@ import { firstValueFrom, Subscription } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { DeviceProfileService } from '@core/http/device-profile.service'; import { DeviceService } from '@core/http/device.service'; @@ -57,6 +58,17 @@ export interface DeviceInstallDialogData { installState?: Record; entityGroupId?: string; customerId?: string; + // Set when the wizard updates an installed package to the item version + update?: DeviceInstallUpdate; +} + +/** + * The installed package an update changes. The steps of the new version change the entities + * the package created in place, so the device keeps its id, credentials and history. + */ +export interface DeviceInstallUpdate { + installedItemId: string; + descriptor: DeviceInstalledItemDescriptor; } export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress'; @@ -318,6 +330,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field); ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; - // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; + // In review mode, use stored values; an update starts from the values of the installed version; otherwise use defaults + const storedState = this.reviewMode ? this.data.installState : this.data.update?.descriptor.installState; + const storedValues = storedState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -1250,17 +1259,26 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + /** keepName: the entity keeps its current name instead of the template's, e.g. a device profile the user renamed. */ + private async overwriteEntity(step: DeviceInstallStep, existing: EntityStepOutput, keepName = false): Promise { const raw = this.zipFiles.get(step.template); if (!raw) throw new Error(`Template file not found: ${step.template}`); // Overwriting an existing integration reuses its routingKey, so resolve @@ -1563,6 +1583,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (step.type !== InstallStepType.DEVICE && step.type !== InstallStepType.GATEWAY) { + return existing; + } + const creds = await firstValueFrom(this.deviceService.getDeviceCredentials(existing.id, false, {ignoreErrors: true})); + const output: EntityStepOutput = { ...existing, token: creds.credentialsId }; + if (step.type === InstallStepType.GATEWAY) { + output.dockerComposeUrl = `/api/device-connectivity/gateway-launch/${output.id}/docker-compose/download`; + // As createEntity does: the docker-compose template resolves ${gateway.token} + this.entityOutputs.set('gateway', output); + if (step.dockerCompose) { + const dcRaw = this.zipFiles.get(step.dockerCompose); + if (dcRaw) this.gatewayDockerComposeContent = this.resolveVariables(dcRaw); + } + } + return output; + } + + /** + * Update: the entity the installed version created for this step. It is found by the id kept in + * the install state, not by name, so an entity the user renamed is still found. Null when this + * is not an update, when the installed version had no such step, or when the entity was deleted since. + */ + private async findPreviousEntity(step: DeviceInstallStep): Promise { + const installState = this.data.update?.descriptor.installState; + // A connector lives in the gateway's attributes: its step runs again over the same gateway + if (!installState || step.type === InstallStepType.GATEWAY_CONNECTOR) { + return null; + } + const id: string = (installState[step.name] || installState[this.resolveVariables(step.name)])?.entityOutput?.id; + if (!id) { + return null; + } + const config = {ignoreErrors: true}; + try { + switch (step.type) { + case InstallStepType.DEVICE_PROFILE: { + const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); + return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; + } + case InstallStepType.DEVICE: { + const device = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: device.name, url: `/entities/devices/all/${id}` }; + } + case InstallStepType.GATEWAY: { + const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: gateway.name, url: '/entities/gateways' }; + } + case InstallStepType.DASHBOARD: { + const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); + return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; + } + case InstallStepType.RULE_CHAIN: { + const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); + return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; + } + case InstallStepType.UPLINK_CONVERTER: + case InstallStepType.DOWNLINK_CONVERTER: { + const converter = await firstValueFrom(this.converterService.getConverter(id, config)); + const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; + return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; + } + case InstallStepType.INTEGRATION: { + const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); + return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; + } + default: + return null; + } + } catch (_e) { + // Deleted since: the step creates it again + return null; + } + } + + /** + * Update: a device or gateway is kept as it is, so its credentials, which the firmware uses, don't change. + * Other entities take the new version's template and keep their id and current name. + */ + private updatePreviousEntity(step: DeviceInstallStep, previous: EntityStepOutput): Promise { + if (step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + return this.useExistingEntity(step, previous); + } + return this.overwriteEntity(step, previous, true); + } + private async preCheckEntity(step: DeviceInstallStep): Promise { const raw = this.zipFiles.get(step.template); if (!raw) return null; @@ -1711,6 +1822,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousId.id)) { + ids.push(previousId); + } + } return ids; } 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 b04932040d..fb5c9125d0 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 @@ -17,7 +17,7 @@ import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubIt 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'; @@ -150,6 +150,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, @@ -199,9 +202,22 @@ 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. + */ + 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 } + })), + map(result => result === 'installed' ? 'updated' : result) + ); + } + 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, From 12deaf57287f78cadc2ac47aed9a5a523a7d66e3 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 13:41:41 +0200 Subject: [PATCH 08/66] fix(iot-hub): keep what the user chose at install when updating a device package - An entity the user took with "Use existing" at install is kept as it is on update instead of being overwritten with the package's template. - Only a 404 counts as "deleted since"; any other failure to load a previous entity fails the step, so a transient error can't create a second device with new credentials. - A rejected update registration (success=false) is shown on the step and can be retried instead of closing as updated. - An overwritten dashboard keeps its owner. - Ids of entities deleted since are no longer re-tracked. - The transport fields take the current Device connectivity settings. - A version without a dashboard step keeps the installed dashboardId. - A failed version lookup on update no longer errors unhandled. PROD-9096 --- .../device-install-dialog.component.ts | 141 +++++++++++------- .../iot-hub/iot-hub-actions.service.ts | 4 +- 2 files changed, 93 insertions(+), 52 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ea37b3bbe5..3daae22f31 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -66,6 +66,12 @@ export interface DeviceInstallDialogData { * The installed package an update changes. The steps of the new version change the entities * the package created in place, so the device keeps its id, credentials and history. */ +/** Update: an entity the installed version has for a step, and whether the user kept it as it was at install. */ +interface PreviousEntity { + output: EntityStepOutput; + useExisting: boolean; +} + export interface DeviceInstallUpdate { installedItemId: string; descriptor: DeviceInstalledItemDescriptor; @@ -236,6 +242,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); // Variable resolution state formValues: Record = {}; @@ -1093,8 +1101,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field); ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; - // In review mode, use stored values; an update starts from the values of the installed version; otherwise use defaults - const storedState = this.reviewMode ? this.data.installState : this.data.update?.descriptor.installState; + // In review mode, use stored values; an update starts from the values of the installed version, + // except the transport fields, which take the current Device connectivity settings; otherwise use defaults + const storedState = this.reviewMode ? this.data.installState : + ws.stateKey !== TRANSPORT_STEP_STATE_KEY ? this.data.update?.descriptor.installState : undefined; const storedValues = storedState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); @@ -1265,7 +1275,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousDashboardId) ? { entityType: 'DASHBOARD', id: previousDashboardId } : undefined); + const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, { createdEntityIds, dashboardId, selectedInstallMethod: this.selectedInstallMethod, installState: this.buildInstallState() }, @@ -1310,10 +1324,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + private async findPreviousEntity(step: DeviceInstallStep): Promise { const installState = this.data.update?.descriptor.installState; // A connector lives in the gateway's attributes: its step runs again over the same gateway if (!installState || step.type === InstallStepType.GATEWAY_CONNECTOR) { return null; } - const id: string = (installState[step.name] || installState[this.resolveVariables(step.name)])?.entityOutput?.id; + const stored = installState[step.name] || installState[this.resolveVariables(step.name)]; + const id: string = stored?.entityOutput?.id; if (!id) { return null; } - const config = {ignoreErrors: true}; try { - switch (step.type) { - case InstallStepType.DEVICE_PROFILE: { - const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); - return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; - } - case InstallStepType.DEVICE: { - const device = await firstValueFrom(this.deviceService.getDevice(id, config)); - return { id, name: device.name, url: `/entities/devices/all/${id}` }; - } - case InstallStepType.GATEWAY: { - const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); - return { id, name: gateway.name, url: '/entities/gateways' }; - } - case InstallStepType.DASHBOARD: { - const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); - return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; - } - case InstallStepType.RULE_CHAIN: { - const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); - return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; - } - case InstallStepType.UPLINK_CONVERTER: - case InstallStepType.DOWNLINK_CONVERTER: { - const converter = await firstValueFrom(this.converterService.getConverter(id, config)); - const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; - return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; - } - case InstallStepType.INTEGRATION: { - const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); - return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; - } - default: - return null; + const output = await this.loadPreviousEntity(step, id); + // The user chose to keep an entity they already had: the update doesn't overwrite it either + return output ? { output, useExisting: stored.resolution === 'use-existing' } : null; + } catch (e: any) { + if (e?.status === 404) { + // Deleted since: the step creates it again, and the package no longer tracks the old id + this.deletedPreviousIds.add(id); + return null; } - } catch (_e) { - // Deleted since: the step creates it again - return null; + throw e; + } + } + + private async loadPreviousEntity(step: DeviceInstallStep, id: string): Promise { + const config = {ignoreErrors: true}; + switch (step.type) { + case InstallStepType.DEVICE_PROFILE: { + const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); + return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; + } + case InstallStepType.DEVICE: { + const device = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: device.name, url: `/entities/devices/all/${id}` }; + } + case InstallStepType.GATEWAY: { + const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: gateway.name, url: '/entities/gateways' }; + } + case InstallStepType.DASHBOARD: { + const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); + return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; + } + case InstallStepType.RULE_CHAIN: { + const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); + return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; + } + case InstallStepType.UPLINK_CONVERTER: + case InstallStepType.DOWNLINK_CONVERTER: { + const converter = await firstValueFrom(this.converterService.getConverter(id, config)); + const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; + return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; + } + case InstallStepType.INTEGRATION: { + const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); + return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; + } + default: + return null; } } @@ -1753,11 +1792,11 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { - return this.useExistingEntity(step, previous); + private updatePreviousEntity(step: DeviceInstallStep, previous: PreviousEntity): Promise { + if (previous.useExisting || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + return this.useExistingEntity(step, previous.output); } - return this.overwriteEntity(step, previous, true); + return this.overwriteEntity(step, previous.output, true); } private async preCheckEntity(step: DeviceInstallStep): Promise { @@ -1825,7 +1864,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousId.id)) { + if (!this.deletedPreviousIds.has(previousId.id) && !ids.some(id => id.id === previousId.id)) { ids.push(previousId); } } 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 fb5c9125d0..4c6fa566e8 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 @@ -211,7 +211,9 @@ export class IotHubActionsService { switchMap(item => this.openDeviceInstallDialog(item, { update: { installedItemId: installedItem.id.id, descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor } })), - map(result => result === 'installed' ? 'updated' : result) + map(result => result === 'installed' ? 'updated' : result), + // The request has already shown the error + catchError(() => of(false)) ); } From 7351515978fee4a807bcc52907c472ef25496a56 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 14:03:06 +0200 Subject: [PATCH 09/66] fix(iot-hub): keep entities other packages use and report a failed registration on device update - Entities other installed device packages use are kept as they are on update, as deleting the package already does, instead of being overwritten with this package's templates. - A version without a dashboard step keeps the installed dashboard only if it still exists; a deleted one is no longer tracked. - On update, Close reports the update as done only once the new version is registered. - A kept integration keeps httpEndpoint and baseUrl for the instructions. - The gateway output and docker-compose resolution are in one helper. PROD-9096 --- .../device-install-dialog.component.ts | 116 ++++++++++++------ 1 file changed, 79 insertions(+), 37 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 3daae22f31..c400003c26 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -62,16 +62,19 @@ export interface DeviceInstallDialogData { update?: DeviceInstallUpdate; } -/** - * The installed package an update changes. The steps of the new version change the entities - * the package created in place, so the device keeps its id, credentials and history. - */ -/** Update: an entity the installed version has for a step, and whether the user kept it as it was at install. */ +/** Update: an entity the installed version has for a step. */ interface PreviousEntity { output: EntityStepOutput; - useExisting: boolean; + // Taken as it is instead of overwritten: the user kept it at install, or another installed package uses it + keepAsIs: boolean; + // What the install state records for it, so that the next update decides again + resolution: string; } +/** + * The installed package an update changes. The steps of the new version change the entities + * the package created in place, so the device keeps its id, credentials and history. + */ export interface DeviceInstallUpdate { installedItemId: string; descriptor: DeviceInstalledItemDescriptor; @@ -244,6 +247,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); + // Update: ids of the package's entities that other installed device packages use, loaded once + private sharedEntityIds: Promise> | null = null; // Variable resolution state formValues: Record = {}; @@ -666,7 +671,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousDashboardId) ? { entityType: 'DASHBOARD', id: previousDashboardId } : undefined); const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, @@ -1390,15 +1392,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent> { + if (!this.sharedEntityIds) { + this.sharedEntityIds = firstValueFrom( + this.iotHubApiService.getInstalledItemKeptEntities(this.data.update.installedItemId, {ignoreLoading: true}) + ).then(kept => new Set(kept.entities.map(e => e.entityId.id))); + // A failed request is asked again on retry instead of being remembered + this.sharedEntityIds.catch(() => this.sharedEntityIds = null); + } + return this.sharedEntityIds; + } + private async loadPreviousEntity(step: DeviceInstallStep, id: string): Promise { const config = {ignoreErrors: true}; switch (step.type) { @@ -1780,8 +1801,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (previous.useExisting || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + if (previous.keepAsIs || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { return this.useExistingEntity(step, previous.output); } return this.overwriteEntity(step, previous.output, true); @@ -1871,6 +1892,27 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const previousDashboardId = this.data.update?.descriptor.dashboardId?.id; + if (!previousDashboardId || this.deletedPreviousIds.has(previousDashboardId)) { + return undefined; + } + try { + await firstValueFrom(this.dashboardService.getDashboardInfo(previousDashboardId, {ignoreErrors: true})); + return { entityType: 'DASHBOARD', id: previousDashboardId }; + } catch (e: any) { + if (e?.status === 404) { + this.deletedPreviousIds.add(previousDashboardId); + return undefined; + } + throw e; + } + } + private findCreatedDashboardId(): { entityType: string; id: string } | undefined { for (const ws of this.wizardSteps) { if (ws.type === 'progress' && ws.entitySteps) { From 76d619ff6e80cc6debb2b7b3c7093b597f04d9e8 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 18:12:38 +0200 Subject: [PATCH 10/66] IoT Hub: list the entities a device package removal keeps with the references component The remove dialog named the kept converter, integration and other entities inside one sentence, which was hard to read. It now says how many other installed packages use them and lists them with tb-image-references, one per row, each linking to the entity. --- .../iot-hub-delete-dialog.component.html | 3 ++ .../iot-hub-delete-dialog.component.ts | 28 +++++++++---------- .../assets/locale/locale.constant-en_US.json | 11 +------- 3 files changed, 17 insertions(+), 25 deletions(-) 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 60eb673a23..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 @@ -8,6 +8,9 @@

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

{{ description }}

+ @if (keptReferences) { + + }
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 56a9c82543..81d13800d3 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 @@ -10,6 +10,8 @@ import { DialogComponent } from '@shared/components/dialog.component'; 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; @@ -28,6 +30,9 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent, protected router: Router, @@ -37,8 +42,14 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); + this.description = this.translate.instant('iot-hub.remove-desc-kept', + { 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 { @@ -52,17 +63,4 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent { - const key = `iot-hub.remove-kept-entity.${entity.entityId.entityType}`; - const named = this.translate.instant(key, { name: entity.name }); - return named === key ? `'${entity.name}'` : named; - }); - const entities = names.length === 1 ? names[0] : - this.translate.instant('iot-hub.remove-kept-entities', { first: names.slice(0, -1).join(', '), last: names[names.length - 1] }); - return this.translate.instant('iot-hub.remove-desc-kept', - { entities, count: kept.usedByItemsCount, kept: kept.entities.length }); - } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 0e0b2c893c..030dcad4f8 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6405,16 +6405,7 @@ "remove": "Remove", "remove-confirm-title": "Remove '{{name}}'?", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", - "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant, except {entities}. { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } { kept, plural, =1 {it} other {them} }.", - "remove-kept-entities": "{{first}} and {{last}}", - "remove-kept-entity": { - "CONVERTER": "data converter '{{name}}'", - "DASHBOARD": "dashboard '{{name}}'", - "DEVICE": "device '{{name}}'", - "DEVICE_PROFILE": "device profile '{{name}}'", - "INTEGRATION": "integration '{{name}}'", - "RULE_CHAIN": "rule chain '{{name}}'" - }, + "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", "select-entity-for-cf": "Select entity for calculated field '{{name}}'", From 598f4704a94b9da12294af5225ad4b255554e9be Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 18:44:25 +0200 Subject: [PATCH 11/66] TTN and TTI default uplink converter: the IoT Hub LoRaWAN converter A new TTN or TTI integration now starts with the converter the IoT Hub LoRaWAN packages install. A device registered from the LoRaWAN Device Repository gets the profile - and its decoded values as telemetry, with a Milesight-style history list kept at each record's time. Any other device gets the LoRaWAN Device profile and its raw payload as data. The device is named by its end device ID and added to a group named after the application. The TBEL and JS defaults are the same script. ConverterControllerTest runs both through the real default v2 configuration for TTN and TTI, so ui-ngx now also copies that configuration to the classpath. --- .../controller/ConverterControllerTest.java | 73 ++++++---- .../things_stack_manual_device_payload.json | 34 +++++ ...hings_stack_repository_device_payload.json | 64 +++++++++ ui-ngx/pom.xml | 1 + .../default-converters-v2-configuration.json | 64 ++++++--- .../src/assets/converters/js-tti-decoder.raw | 134 ++++-------------- .../src/assets/converters/js-ttn-decoder.raw | 133 ++++------------- .../assets/converters/tbel-tti-decoder.raw | 104 ++++---------- .../assets/converters/tbel-ttn-decoder.raw | 104 ++++---------- 9 files changed, 309 insertions(+), 402 deletions(-) create mode 100644 application/src/test/resources/payload/things_stack_manual_device_payload.json create mode 100644 application/src/test/resources/payload/things_stack_repository_device_payload.json 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 e51e796f11..0d99594197 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -32,6 +32,7 @@ import org.thingsboard.server.common.data.integration.Integration; 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.common.data.script.ScriptLanguage; import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.dao.service.DaoSqlTest; @@ -89,13 +90,14 @@ public class ConverterControllerTest extends AbstractControllerTest { private static final String THINGPARK_UPLINK_DECODER = "converter/thingpark_uplink_decoder.raw"; private static final String DEFAULT_TPE_UPLINK_DECODER = "converters/tbel-tpe-decoder.raw"; private static final String TPE_UPLINK_DECODER = "converter/tpe_uplink_decoder.raw"; - private static final String DEFAULT_TTI_UPLINK_DECODER = "converters/tbel-tti-decoder.raw"; private static final String TTI_UPLINK_DECODER = "converter/tti_uplink_decoder.raw"; - private static final String DEFAULT_TTN_UPLINK_DECODER = "converters/tbel-ttn-decoder.raw"; private static final String TTN_UPLINK_DECODER = "converter/ttn_uplink_decoder.raw"; 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 DEFAULT_V2_CONFIGURATION = "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"; @Before public void beforeTest() throws Exception { @@ -673,17 +675,6 @@ public class ConverterControllerTest extends AbstractControllerTest { } } - @Test - public void testTTIDefaultDecoder() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"application-tti-name\"," + - "\"telemetry\":{\"ts\":1684398325906,\"values\":{\"battery\":95,\"temperature\":36.6,\"saturation\":99}},\"attributes\":{\"sn\":32310067,\"devAddr\":\"20000001\",\"fPort\":85,\"eui\":\"1000000000000001\"}}"; - - DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr")); - Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTI, 2); - - testDecoder(DEFAULT_TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); - } - @Test public void testTTINotDefaultDecoder() throws IOException { String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"IndustrialSensorProfile\",\"customer\":\"MyCustomer\",\"group\":\"SensorsGroup\"," + @@ -696,14 +687,45 @@ public class ConverterControllerTest extends AbstractControllerTest { } @Test - public void testTTNDefaultDecoder() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"eui-1000000000000001\",\"profile\":\"application-tts-name\"," + - "\"telemetry\":{\"ts\":1684474415641,\"values\":{\"battery\":95,\"temperature\":36.6,\"saturation\":99}},\"attributes\":{\"sn\":32310067,\"devAddr\":\"20000001\",\"fPort\":85,\"eui\":\"1000000000000001\"}}"; + public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { + String expectedDecodedMessage = "{\"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\"}}"; - DedicatedConverterConfig config = createDedicatedConverterConfig(EntityType.DEVICE, "eui-$eui", "$applicationId", Set.of("eui", "fPort", "devAddr")); - Converter converter = createConverter(JacksonUtil.valueToTree(config), IntegrationType.TTN, 2); + testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, expectedDecodedMessage); + } - testDecoder(DEFAULT_TTN_UPLINK_DECODER, DEFAULT_TTN_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); + @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, expectedDecodedMessage); + } + + // 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, String expectedResult) throws IOException { + JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); + String payload = readResource(payloadFile); + for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { + Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); + for (ScriptLanguage scriptLang : ScriptLanguage.values()) { + String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; + assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang))) + .as("%s %s", integrationType, scriptLang) + .isEqualTo(JacksonUtil.toJsonNode(expectedResult)); + } + } + } + + private String readResource(String name) throws IOException { + return new String(IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(name)), StandardCharsets.UTF_8); } @Test @@ -870,6 +892,10 @@ public class ConverterControllerTest extends AbstractControllerTest { } public void testDecoder(String decoderFileName, String payloadExample, String expectedResult, Converter converter) throws IOException { + assertThat(decode(decoderFileName, payloadExample, converter, ScriptLanguage.TBEL)).isEqualTo(expectedResult); + } + + private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException { byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName)); String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8)); @@ -895,14 +921,11 @@ public class ConverterControllerTest extends AbstractControllerTest { inputParams.set("payload", new TextNode(base64Payload)); } - JsonNode response = doPost("/api/converter/testUpLink?scriptLang=TBEL", inputParams, JsonNode.class); - String output; + JsonNode response = doPost("/api/converter/testUpLink?scriptLang=" + scriptLang, inputParams, JsonNode.class); if (converter != null && converter.getConverterVersion() == 2) { - output = response.get("outputMsg").toString(); - } else { - output = response.get("output").asText(); + return response.get("outputMsg").toString(); } - assertThat(output).isEqualTo(expectedResult); + return response.get("output").asText(); } public DedicatedConverterConfig createDedicatedConverterConfig(EntityType type, String name, String profile, Set attributes) { 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/ui-ngx/pom.xml b/ui-ngx/pom.xml index ac1b07c92c..d41acf2057 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -96,6 +96,7 @@ src/assets/converters **/*.raw + default-converters-v2-configuration.json diff --git a/ui-ngx/src/assets/converters/default-converters-v2-configuration.json b/ui-ngx/src/assets/converters/default-converters-v2-configuration.json index 547095527d..4ee2d652cc 100644 --- a/ui-ngx/src/assets/converters/default-converters-v2-configuration.json +++ b/ui-ngx/src/assets/converters/default-converters-v2-configuration.json @@ -143,12 +143,17 @@ }, "TTN": { "type": "DEVICE", - "name": "Device $eui", - "profile": "$applicationId", + "name": "$deviceId", + "profile": "LoRaWAN Device", "label": "$deviceId", + "customer": "", + "group": "$applicationId", "attributes": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -158,23 +163,30 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ], "telemetry": [ "fCnt", "data", - "decoded", "latitude", "longitude", "altitude", "rssi", "snr", - "channel" + "channel", + "consumedAirtime" ], "updateOnlyKeys": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -184,18 +196,27 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ] }, "TTI": { "type": "DEVICE", - "name": "Device $eui", - "profile": "$applicationId", + "name": "$deviceId", + "profile": "LoRaWAN Device", "label": "$deviceId", + "customer": "", + "group": "$applicationId", "attributes": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -205,23 +226,30 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ], "telemetry": [ "fCnt", "data", - "decoded", "latitude", "longitude", "altitude", "rssi", "snr", - "channel" + "channel", + "consumedAirtime" ], "updateOnlyKeys": [ "eui", + "joinEui", "devAddr", + "deviceId", + "applicationId", "fPort", "bandwidth", "spreadingFactor", @@ -231,8 +259,12 @@ "modelId", "hardwareVersion", "firmwareVersion", - "attributes", - "tenantId" + "bandId", + "netId", + "tenantId", + "clusterId", + "clusterAddress", + "attributes" ] } } diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index 10f09c96ad..5cb10f8db1 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -1,111 +1,35 @@ -/** - * 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. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +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; } - - // 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 profile = 'LoRaWAN Device'; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + '-' + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == 'milesight-iot-am308') { +// profile = 'AM308'; +// } +if (history.length == 0) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.push({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; -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; - -/** - * 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/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index 478c26140a..5cb10f8db1 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -1,110 +1,35 @@ -/** - * 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. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +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; } - - // 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 profile = 'LoRaWAN Device'; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + '-' + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == 'milesight-iot-am308') { +// profile = 'AM308'; +// } +if (history.length == 0) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.push({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; -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; - -/** - * 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/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 3dd4a8fb48..09c75b5aed 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -1,79 +1,31 @@ -/** - * 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. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +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) - } - }; - - // 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. -return result; +var profile = "LoRaWAN Device"; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + "-" + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == "milesight-iot-am308") { +// profile = "AM308"; +// } +if (history.isEmpty()) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.add({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 12f302274d..09c75b5aed 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -1,79 +1,31 @@ -/** - * 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. Any other device gets LoRaWAN Device. +var values = {}; +var history = []; +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) - } - }; - - // 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. -return result; +var profile = "LoRaWAN Device"; +if (metadata.brandId != null && metadata.modelId != null) { + profile = metadata.brandId + "-" + metadata.modelId; +} +// To give a model its own profile name, map it here, for example: +// if (profile == "milesight-iot-am308") { +// profile = "AM308"; +// } +if (history.isEmpty()) { + return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; +} +history.add({ ts: metadata.ts, values: values }); +return { profile: profile, telemetry: history }; From 2aa823766c19837eb9803894c147b2203bff4ebc Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:06:12 +0200 Subject: [PATCH 12/66] Dedicated converter: save metadata telemetry at the uplink time when the script returns a telemetry array The metadata telemetry keys went into a separate array element without ts, so they were saved at the server time, while the script's own values were saved at the uplink time. The element now takes ts from the metadata, the same ts the script reads and the one an object result already uses for these keys. --- .../controller/ConverterControllerTest.java | 2 +- .../api/converter/DedicatedConverterUtil.java | 20 +++++++++- ...edicatedScriptUplinkDataConverterTest.java | 37 +++++++++++++++++++ 3 files changed, 57 insertions(+), 2 deletions(-) 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 0d99594197..2a56e51460 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -690,7 +690,7 @@ public class ConverterControllerTest extends AbstractControllerTest { public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { String expectedDecodedMessage = "{\"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\"}]," + + "{\"ts\":1793181600100,\"values\":{\"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\"," + 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..c8052005f6 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 @@ -40,7 +40,7 @@ public final class DedicatedConverterUtil { if (telemetry.isJsonArray()) { JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry()); if (!telemetryFromMetadata.isEmpty()) { - telemetry.getAsJsonArray().add(telemetryFromMetadata); + telemetry.getAsJsonArray().add(withUplinkTs(telemetryFromMetadata, kvMap)); } } else if (telemetry.isJsonObject()) { var obj = telemetry.getAsJsonObject(); @@ -101,6 +101,24 @@ public final class DedicatedConverterUtil { return defaultValue.get(); } + // An array element without ts is saved at the server time, so the metadata element takes the uplink time when it is known + private static JsonObject withUplinkTs(JsonObject values, Map kvMap) { + Object ts = kvMap.get(TS); + Long uplinkTs = null; + if (ts instanceof Number number) { + uplinkTs = number.longValue(); + } else if (ts instanceof String str && StringUtils.isNumeric(str)) { + uplinkTs = Long.parseLong(str); + } + if (uplinkTs == null) { + return values; + } + JsonObject element = new JsonObject(); + element.addProperty(TS, uplinkTs); + element.add(VALUES, values); + return element; + } + private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys) { if (CollectionsUtil.isNotEmpty(keys) && !kvMap.isEmpty()) { kvMap.entrySet().stream() 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..f764751813 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 @@ -179,6 +179,43 @@ 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 parseUplinkDataTest() { DedicatedConverterConfig config = new DedicatedConverterConfig(); From 17278ce2d9ee11cd721955e0d356994bbf8757ff Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:14:43 +0200 Subject: [PATCH 13/66] Dedicated converter: metadata telemetry joins the script's array element at the uplink ts With its own element at the uplink ts, a metadata key also returned by the script overwrote the script's value. The metadata keys now go into the script's element at that ts, only where the script has no value, as for an object result. Without such an element they keep their own element at the uplink ts. --- .../controller/ConverterControllerTest.java | 4 +- .../api/converter/DedicatedConverterUtil.java | 52 ++++++++++++++----- ...edicatedScriptUplinkDataConverterTest.java | 44 ++++++++++++++++ 3 files changed, 84 insertions(+), 16 deletions(-) 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 2a56e51460..8ab6727c04 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -689,8 +689,8 @@ public class ConverterControllerTest extends AbstractControllerTest { @Test public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { String expectedDecodedMessage = "{\"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}}," + - "{\"ts\":1793181600100,\"values\":{\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + + "\"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\"," + 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 c8052005f6..f23d60a2a3 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,6 +3,7 @@ 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 org.thingsboard.common.util.JacksonUtil; @@ -38,10 +39,7 @@ public final class DedicatedConverterUtil { telemetry = src.get(TELEMETRY); if (telemetry.isJsonArray()) { - JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry()); - if (!telemetryFromMetadata.isEmpty()) { - telemetry.getAsJsonArray().add(withUplinkTs(telemetryFromMetadata, kvMap)); - } + addMetadataTelemetry(telemetry.getAsJsonArray(), kvMap, config.getTelemetry()); } else if (telemetry.isJsonObject()) { var obj = telemetry.getAsJsonObject(); if (obj.has(VALUES)) { @@ -101,22 +99,48 @@ public final class DedicatedConverterUtil { return defaultValue.get(); } - // An array element without ts is saved at the server time, so the metadata element takes the uplink time when it is known - private static JsonObject withUplinkTs(JsonObject values, Map kvMap) { - Object ts = kvMap.get(TS); - Long uplinkTs = null; - if (ts instanceof Number number) { - uplinkTs = number.longValue(); - } else if (ts instanceof String str && StringUtils.isNumeric(str)) { - uplinkTs = Long.parseLong(str); + // 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) { + 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); + return; + } + } + } + JsonObject values = addKvs(new JsonObject(), kvMap, keys); + if (values.isEmpty()) { + return; } if (uplinkTs == null) { - return values; + telemetry.add(values); + return; } JsonObject element = new JsonObject(); element.addProperty(TS, uplinkTs); element.add(VALUES, values); - return element; + telemetry.add(element); + } + + private static boolean isValuesAtTs(JsonObject element, long ts) { + JsonElement elementTs = element.get(TS); + return element.has(VALUES) && element.get(VALUES).isJsonObject() + && elementTs != null && elementTs.isJsonPrimitive() && elementTs.getAsJsonPrimitive().isNumber() + && elementTs.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 JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set keys) { 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 f764751813..5ee41eda4e 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 @@ -216,6 +216,50 @@ public class DedicatedScriptUplinkDataConverterTest { assertEquals("rssi", tsKvLists.get(1).getKv(0).getKey()); } + @Test + public void parseUplinkDataWithTelemetryArrayAddsMetadataToScriptElementAtUplinkTsTest() { + 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(); + 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(); From 198e87211c39cfc2f203b45df323b5f79a59c909 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Wed, 28 Oct 2026 19:37:06 +0200 Subject: [PATCH 14/66] Dedicated converter: a numeric-string ts in a script element counts as the uplink ts A script passes a numeric-string metadata ts through unchanged, and the telemetry parser reads it as a long, so the metadata keys must join that element too. --- .../api/converter/DedicatedConverterUtil.java | 11 ++++++++--- .../DedicatedScriptUplinkDataConverterTest.java | 15 ++++++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) 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 f23d60a2a3..3af0d78e72 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 @@ -6,6 +6,7 @@ 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; @@ -127,9 +128,13 @@ public final class DedicatedConverterUtil { private static boolean isValuesAtTs(JsonObject element, long ts) { JsonElement elementTs = element.get(TS); - return element.has(VALUES) && element.get(VALUES).isJsonObject() - && elementTs != null && elementTs.isJsonPrimitive() && elementTs.getAsJsonPrimitive().isNumber() - && elementTs.getAsLong() == 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) { 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 5ee41eda4e..6349a9334a 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 @@ -218,6 +218,15 @@ public class DedicatedScriptUplinkDataConverterTest { @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}"); @@ -230,7 +239,11 @@ public class DedicatedScriptUplinkDataConverterTest { currentValues.addProperty("temperature", 24.5); currentValues.addProperty("rssi", -50); JsonObject current = new JsonObject(); - current.addProperty("ts", uplinkTs); + if (scriptTsAsString) { + current.addProperty("ts", String.valueOf(uplinkTs)); + } else { + current.addProperty("ts", uplinkTs); + } current.add("values", currentValues); JsonArray telemetryArray = new JsonArray(); From 15a7222f2567e689a8182f01a368a052a81a4eb1 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 29 Oct 2026 13:51:36 +0200 Subject: [PATCH 15/66] fix(iot-hub): apply a device package update in one transaction on the server The wizard no longer saves the entities itself and reverts them from snapshots on a failure. It plans the update and the server applies it. - POST /api/iot-hub/installedItems/{id}/deviceUpdate takes the entity of each step, resolved from the new version's template, and saves all of them with the new version of the installed item in one transaction. Any failure rolls everything back. The audit log, version control and attributes are written after commit. - The server checks the plan: only the package's entities or confirmed conflicts are overwritten, the device and its credentials never change, and an entity changed since the check fails the update (version). - GET .../deviceUpdate/check reports for each entity whether it still exists, is shared with other packages, or was changed since install, by a checksum the server keeps in the install state at install and on update. Packages installed before keep the comparison with the template. - An entity changed since install is overwritten only after a warning, with a link to download its current version. A shared one shows the shared warning. - Only texts changed: the version is recorded without the wizard. - Try again checks the update again. Errors show validation messages and a common message for anything else. --- .../server/controller/IotHubController.java | 26 +- .../DefaultDevicePackageUpdateService.java | 789 +++++++++++++++++ .../service/iot_hub/DefaultIotHubService.java | 40 +- .../iot_hub/DevicePackageEntities.java | 119 +++ .../iot_hub/DevicePackageEntityState.java | 27 + .../iot_hub/DevicePackageUpdateService.java | 19 + .../service/iot_hub/DeviceUpdateRequest.java | 61 ++ .../service/iot_hub/DeviceUpdateResult.java | 37 + .../service/iot_hub/EntityChecksum.java | 110 +++ .../server/service/iot_hub/IotHubService.java | 2 - ...DefaultDevicePackageUpdateServiceTest.java | 376 ++++++++ .../iot_hub/DefaultIotHubServiceTest.java | 40 - .../src/app/core/http/iot-hub-api.service.ts | 26 +- .../device-install-dialog.component.html | 186 +++- .../device-install-dialog.component.scss | 84 ++ .../device-install-dialog.component.ts | 808 +++++++++++++++--- .../iot-hub/iot-hub-actions.service.ts | 10 +- .../models/iot-hub/device-package.models.ts | 3 +- .../iot-hub/iot-hub-installed-item.models.ts | 43 + .../assets/locale/locale.constant-en_US.json | 14 + 20 files changed, 2591 insertions(+), 229 deletions(-) create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java create mode 100644 application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java create mode 100644 application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java 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 e5388bd28b..b6d01d3342 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -38,6 +38,10 @@ 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; @@ -54,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; @@ -92,16 +97,29 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, - @RequestParam(required = false) UUID installedItemId, @RequestBody JsonNode body) throws ThingsboardException { checkAllPermissions(); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); - if (installedItemId != null) { - return iotHubService.registerDeviceUpdate(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, descriptor); - } 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 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..1e6d3f776d --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java @@ -0,0 +1,789 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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.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.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.secret.SecretConfigurationService; +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.integration.IntegrationManagerService; +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.Set; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +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 int INTEGRATION_VALIDATION_TIMEOUT_SEC = 20; + 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 IntegrationManagerService integrationManagerService; + private final SecretConfigurationService secretConfigurationService; + 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); + + 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"); + Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null : + !storedChecksum.asText().equals(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); + 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 = createdIds(devicePackage.descriptor()).keySet(); + for (DeviceUpdateRequest.Step step : request.getSteps()) { + if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { + throw new IllegalArgumentException("Invalid 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()); + } + } + } + + /** 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); + if (integration.isEdgeTemplate()) { + continue; + } + try { + secretConfigurationService.replaceSecretUsages(tenantId, integration.getConfiguration()); + integrationManagerService.validateIntegrationConfiguration(integration).get(INTEGRATION_VALIDATION_TIMEOUT_SEC, TimeUnit.SECONDS); + } 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) { + DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + 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<>(); + List saved = new ArrayList<>(); + List afterCommitSteps = 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) { + DeviceUpdateRequest.Step resolved = copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs)); + afterCommitSteps.add(resolved); + } + 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); + state.put("resolution", step.getResolution() != null ? step.getResolution() : "created"); + // 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.getName()) : result.checksum(); + if (checksum != null) { + state.put("checksum", checksum); + } + installState.put(step.getName(), state); + if (!"use-existing".equals(step.getResolution())) { + stepEntityIds.add(result.entityId()); + } + if (result.entityId() instanceof DashboardId id) { + dashboardId = id; + } + if (result.saved() != null) { + saved.add(result.saved()); + } + if (step.getAction() == DeviceUpdateRequest.Action.CREATE && ("DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()))) { + // Its attributes are saved after commit, once the device exists + DeviceUpdateRequest.Step created = copyWithEntity(step, null); + created.setEntityId(result.entityId().getId()); + afterCommitSteps.add(created); + } + } catch (StepFailure e) { + throw e; + } catch (Exception e) { + throw new StepFailure(step.getName(), e); + } + } + + 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)); + descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous)); + Map state = new LinkedHashMap<>(installState); + descriptor.setInstallState(state); + + IotHubInstalledItem installedItem = devicePackage.installedItem(); + 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); + return new Applied(descriptor, outputs, saved, afterCommitSteps, aliasOutputs); + } + + 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); + 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)); + } + + /** + * 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); + } + + private static String previousChecksum(DeviceInstalledItemDescriptor previous, String stepName) { + JsonNode checksum = previous.getInstallState() != null && previous.getInstallState().get(stepName) != null ? + previous.getInstallState().get(stepName).get("checksum") : null; + return checksum != null && checksum.isTextual() ? checksum.asText() : 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 (DeviceUpdateRequest.Step step : applied.afterCommitSteps()) { + try { + if ("GATEWAY_CONNECTOR".equals(step.getType())) { + saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); + } else { + DeviceId deviceId = new DeviceId(step.getEntityId()); + saveAttributes(tenantId, deviceId, AttributeScope.SERVER_SCOPE, step.getServerAttributes()); + saveAttributes(tenantId, deviceId, AttributeScope.SHARED_SCOPE, step.getSharedAttributes()); + } + } catch (Exception e) { + log.warn("[{}] Failed to save the attributes 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) { + 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)); + } + + 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 Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, + List afterCommitSteps, 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 6f0f9db86f..dcc569b481 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 @@ -133,6 +133,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. @@ -417,7 +418,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // The install wizard of the new version changes the package's entities in place, see registerDeviceUpdate + // 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(); @@ -677,6 +678,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); @@ -708,41 +711,6 @@ public class DefaultIotHubService implements IotHubService { } } - @Override - public InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, - DeviceInstalledItemDescriptor descriptor) { - TenantId tenantId = user.getTenantId(); - log.info("[{}] Registering device package update of {} to version: {}", tenantId, installedItemId, versionId); - - try { - IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); - if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())) { - throw new IllegalArgumentException("Installed device package not found"); - } - - JsonNode versionInfo = iotHubRestClient.getVersionInfo(versionId); - if (versionInfo == null) { - throw new IllegalArgumentException("Failed to get version info from IoT Hub"); - } - if (!installedItem.getItemId().toString().equals(versionInfo.get("itemId").asText())) { - throw new IllegalArgumentException("The version belongs to another item"); - } - - // The wizard has already changed the entities in place: a failure here must not delete them - installedItem.setItemVersionId(UUID.fromString(versionId)); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - iotHubInstalledItemService.save(tenantId, installedItem); - log.info("[{}] Registered device package update: {} (version {})", tenantId, installedItem.getItemName(), installedItem.getVersion()); - - return InstallItemVersionResult.success(descriptor); - } catch (Exception e) { - log.error("[{}] Failed to register device package update of {} to version: {}", tenantId, installedItemId, versionId, e); - return InstallItemVersionResult.error(e.getMessage()); - } - } - /** * 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. 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..37cc999822 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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..005727da77 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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..25a0cdb6ef --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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..6e47841e91 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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 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; + // 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; + // DEVICE and GATEWAY created by this update: attributes, saved after the transaction + private JsonNode serverAttributes; + private JsonNode sharedAttributes; + // The resolution the install state records for it + private String resolution; + } + +} 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..da73d5de80 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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..898a222f05 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java @@ -0,0 +1,110 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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.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. + */ +final class EntityChecksum { + + private static final Set SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId", + "customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources"); + + 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); + 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/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index 3a3fd372b0..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 @@ -19,8 +19,6 @@ public interface IotHubService { InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor); - InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, DeviceInstalledItemDescriptor descriptor); - void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); 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..736e6c790d --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java @@ -0,0 +1,376 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.iot_hub; + +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.converter.Converter; +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.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.exception.DataValidationException; +import org.thingsboard.server.service.entitiy.TbLogEntityActionService; +import org.thingsboard.server.service.security.model.SecurityUser; + +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.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 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; + + @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); + descriptor.setInstallState(Map.of()); + installedItem = new IotHubInstalledItem(); + installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID())); + installedItem.setTenantId(tenantId); + installedItem.setItemId(itemId); + installedItem.setItemType("DEVICE"); + installedItem.setVersion("1.0.0"); + installedItem.setDescriptor(descriptor); + when(installedItemService.findById(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); + } + + @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 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 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 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 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; + } + +} 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 cf4f25bfd7..8cc1848797 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 @@ -510,46 +510,6 @@ class DefaultIotHubServiceTest { verify(iotHubInstalledItemService, never()).save(any(), any()); } - @Test - void registerDeviceUpdate_keepsTheInstalledItemAndRecordsTheNewVersion() { - mockTenant(); - DeviceId deviceId = new DeviceId(UUID.randomUUID()); - IotHubInstalledItem installed = devicePackage(deviceId); - installed.setItemType("DEVICE"); - installed.setItemId(UUID.randomUUID()); - installed.setVersion("1.0"); - when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); - String versionId = UUID.randomUUID().toString(); - when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, installed.getItemId().toString(), "DEVICE", "AM308", "1.1")); - DeviceInstalledItemDescriptor updated = new DeviceInstalledItemDescriptor(); - updated.setCreatedEntityIds(List.of(deviceId)); - - InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, updated); - - assertThat(result.isSuccess()).isTrue(); - verify(iotHubInstalledItemService).save(tenantId, installed); - assertThat(installed.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); - assertThat(installed.getVersion()).isEqualTo("1.1"); - assertThat(installed.getDescriptor()).isSameAs(updated); - verify(tbDeviceService, never()).delete(any(Device.class), any()); - } - - @Test - void registerDeviceUpdate_versionOfAnotherItem_isRejected() { - mockTenant(); - IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID())); - installed.setItemType("DEVICE"); - installed.setItemId(UUID.randomUUID()); - when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); - String versionId = UUID.randomUUID().toString(); - when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Other", "1.0")); - - InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, new DeviceInstalledItemDescriptor()); - - assertThat(result.isSuccess()).isFalse(); - verify(iotHubInstalledItemService, never()).save(any(), any()); - } - private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); 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 639127e075..1bf462ce35 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,7 +13,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { IotHubInstalledItem, IotHubInstalledItemKeptEntities, 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'; @@ -180,13 +180,10 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig, - // Set for an update: the installed item takes the version and the descriptor - installedItemId?: string + config?: IotHubRequestConfig ): Observable { - const installedItemParam = installedItemId ? `&installedItemId=${installedItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}${installedItemParam}`, + `/api/iot-hub/device/register?versionId=${versionId}`, { type: 'DEVICE', ...descriptor }, { params: this.buildParams(config) } ); @@ -272,6 +269,23 @@ 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`, 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 11499fe154..d13e0221d9 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 @@ -61,6 +61,9 @@ } @case ('progress') { + @if (data.update) { + + } @else {
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) { @if (i > 0) { @@ -144,6 +147,142 @@ } }
+ } + } + } +
+ + + + + {{ 'iot-hub.device-update-modified' | translate }} + {{ 'iot-hub.device-update-here' | translate }}. + + + + +
+ @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.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.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') { + {{ 'iot-hub.done' | translate }} + } + @case ('skipped') { + {{ 'iot-hub.device-update-skipped' | translate }} + } + @default { + @if (ws.reviewing && plan) { + {{ 'iot-hub.device-update-no-conflicts' | translate }} + } + } + } + +
} }
@@ -171,7 +310,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 } }} + } +

@@ -225,9 +371,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) { @@ -264,7 +425,26 @@ } @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) {
} @@ -270,7 +271,7 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ 'iot-hub.done' | translate }} + {{ updateOutcomeOf(plan) | translate }} } @case ('skipped') { {{ 'iot-hub.device-update-skipped' | translate }} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 39e97081c4..34b25e66c5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -200,6 +200,8 @@ export interface WizardStep { extraFormFields?: FormFieldDefinition[]; // Key of the step's form values in the install state; the label when not set stateKey?: string; + // Update: the keys of the form's fields the installed version didn't have + newFieldKeys?: Set; formGroup?: UntypedFormGroup; // Connection check of the integration the form configures; null when the form configures none connectionCheck?: ConnectionCheck | null; @@ -1230,6 +1232,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent…, which the translation may put anywhere in it, split around the link. */ + /** Update: what the update did with the entity of a row, once it succeeded. */ + updateOutcomeOf(plan: EntityStepPlan | undefined): string { + if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') { + return 'iot-hub.device-update-not-changed'; + } + return plan.action === 'overwrite' || plan.resolution === 'overwrite' ? 'iot-hub.device-update-updated' : 'iot-hub.device-update-created'; + } + textWithLink(key: string): { before: string; link: string; after: string } { const text: string = this.translate.instant(key); const match = /^([\s\S]*)([\s\S]*)<\/a>([\s\S]*)$/.exec(text); @@ -2295,6 +2306,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent s.type === step.type && (s.id && step.id ? s.id === step.id : s.name === step.name)); } + /** Update: the fields of a form step the installed version's form didn't have; all of them for a new form step. */ + private newFieldKeysOf(step: DeviceInstallStep, fields: FormFieldDefinition[]): Set { + if (!this.previousPackageInfo) { + return new Set(); + } + const previousStep = this.findPreviousStep(step); + let previousKeys = new Set(); + try { + const previousForm = previousStep ? JSON.parse(this.previousFiles.get(previousStep.file) || '[]') as FormFieldDefinition[] : []; + previousKeys = new Set(previousForm.map(field => field.key)); + } catch { + return new Set(); + } + return new Set(fields.map(field => field.key).filter(key => !previousKeys.has(key))); + } + /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ private stateKeysOf(step: DeviceInstallStep): string[] { return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)]; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index a94a41cff0..ab1314f65d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -36,7 +36,10 @@ @for (row of rows; track row.fields[0].key) { -
+
+ @if (isNewRow(row)) { + {{ 'iot-hub.device-update-new' | translate }} + } @if (row.fields.length > 1) {
@for (field of row.fields; track field.key) { 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 f99f29ebca..10711348cc 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 @@ -14,3 +14,23 @@ max-width: 100%; margin-top: 8px; } + +// Update: a field the installed version didn't have +.tb-install-form-row-new { + padding: 8px 12px; + border-left: 3px solid #305680; + border-radius: 4px; + background: rgba(48, 86, 128, 0.04); +} + +.tb-install-form-new { + align-self: flex-start; + font-size: 12px; + font-weight: 500; + line-height: 16px; + letter-spacing: 0.4px; + color: #305680; + background: rgba(48, 86, 128, 0.08); + border-radius: 4px; + padding: 2px 8px; +} 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 6965009871..4633a41afd 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 @@ -49,6 +49,8 @@ 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 @@ -170,4 +172,8 @@ export class InstallFormRendererComponent implements OnChanges { imagePath(path: string): string { return this.resolveImagePath ? this.resolveImagePath(path) : path; } + + isNewRow(row: { fields: FormFieldDefinition[] }): boolean { + return !!this.newFieldKeys?.size && row.fields.some(field => this.newFieldKeys.has(field.key)); + } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 7e587600c9..36c91f24ab 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6538,13 +6538,16 @@ "device-update-no-conflicts": "No conflicts", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", - "device-update-modified": "Changed by someone else. You can download the current version here.", + "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", "device-update-existing-use-existing": "Already exists. The existing one will be used.", "device-update-existing-overwrite": "Already exists. It will be overwritten.", "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", + "device-update-not-changed": "Not changed", + "device-update-updated": "Updated", + "device-update-created": "Created", "device-update-try-again": "Try again", "done": "Done", "in-progress": "In progress", From 109c13a5e2f64c6612b0502c008cae7b3f7d2677 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:15:10 +0200 Subject: [PATCH 20/66] feat(iot-hub): mark a new form field by its outline, label and hint; show Done for kept entities --- .../device-install-dialog.component.html | 3 +- .../device-install-dialog.component.ts | 2 +- .../install-form-renderer.component.html | 60 +++++++++++++------ .../install-form-renderer.component.scss | 28 ++++----- .../install-form-renderer.component.ts | 6 +- .../assets/locale/locale.constant-en_US.json | 2 +- 6 files changed, 62 insertions(+), 39 deletions(-) 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 7fb651678e..964a50bd0d 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 @@ -56,7 +56,8 @@ [formGroup]="ws.formGroup" [resolveImagePath]="resolveImagePathFn" [reviewMode]="reviewMode" - [newFieldKeys]="ws.newFieldKeys"> + [newFieldKeys]="ws.newFieldKeys" + [newFieldHint]="'iot-hub.device-update-new-field' | translate: { version: data.item.version }">
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 34b25e66c5..ca88fa519e 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -1946,7 +1946,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent @for (row of rows; track row.fields[0].key) { -
- @if (isNewRow(row)) { - {{ 'iot-hub.device-update-new' | translate }} - } +
@if (row.fields.length > 1) {
@for (field of row.fields; track field.key) { @@ -96,7 +93,7 @@
} @case (FormFieldType.SELECT) { - {{ field.label }} @@ -104,8 +101,13 @@ {{ opt.label }} } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -113,7 +115,7 @@ } @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }} {{ opt.label }} } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -139,7 +146,7 @@ } @case (FormFieldType.PASSWORD) { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -173,14 +185,19 @@ } @case (FormFieldType.INTEGER) { - {{ field.label }} - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -194,7 +211,7 @@ } @default { - {{ field.label }} autorenew } - @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { - {{ helpTextOf(field) }} + @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { + + @if (isNewField(field)) { + {{ newFieldHint }} + } + {{ helpTextOf(field) }} + } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} 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 10711348cc..b19765a280 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 @@ -15,22 +15,20 @@ margin-top: 8px; } -// Update: a field the installed version didn't have -.tb-install-form-row-new { - padding: 8px 12px; - border-left: 3px solid #305680; - border-radius: 4px; - background: rgba(48, 86, 128, 0.04); +// Update: a field the installed version didn't have: outline, label and hint 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); + } + .mdc-floating-label, + .mat-mdc-floating-label { + color: var(--tb-primary-500); + } } -.tb-install-form-new { - align-self: flex-start; - font-size: 12px; +.tb-install-form-new-hint { + color: var(--tb-primary-500); font-weight: 500; - line-height: 16px; - letter-spacing: 0.4px; - color: #305680; - background: rgba(48, 86, 128, 0.08); - border-radius: 4px; - padding: 2px 8px; } 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 4633a41afd..16a1298ae2 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 @@ -51,6 +51,8 @@ export class InstallFormRendererComponent implements OnChanges { @Input() reviewMode = false; /** Update: the fields the installed version's form didn't have, highlighted as new. */ @Input() newFieldKeys?: Set; + /** Update: the text the hint of a new field starts with. */ + @Input() newFieldHint = ''; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields @@ -173,7 +175,7 @@ export class InstallFormRendererComponent implements OnChanges { return this.resolveImagePath ? this.resolveImagePath(path) : path; } - isNewRow(row: { fields: FormFieldDefinition[] }): boolean { - return !!this.newFieldKeys?.size && row.fields.some(field => this.newFieldKeys.has(field.key)); + isNewField(field: FormFieldDefinition): boolean { + return !!this.newFieldKeys?.has(field.key); } } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 36c91f24ab..78db1e922c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6545,7 +6545,7 @@ "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", - "device-update-not-changed": "Not changed", + "device-update-new-field": "New in {{version}}.", "device-update-updated": "Updated", "device-update-created": "Created", "device-update-try-again": "Try again", From 25692d6ab0faca2c22ad4cb9030907c0cb5798ba Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:24:57 +0200 Subject: [PATCH 21/66] feat(iot-hub): mark a new form field by a primary outline and a New label --- .../device-install-dialog.component.html | 3 +- .../install-form-renderer.component.html | 55 +++++-------------- .../install-form-renderer.component.scss | 13 +++-- .../install-form-renderer.component.ts | 2 - .../assets/locale/locale.constant-en_US.json | 1 - 5 files changed, 23 insertions(+), 51 deletions(-) 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 964a50bd0d..7fb651678e 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 @@ -56,8 +56,7 @@ [formGroup]="ws.formGroup" [resolveImagePath]="resolveImagePathFn" [reviewMode]="reviewMode" - [newFieldKeys]="ws.newFieldKeys" - [newFieldHint]="'iot-hub.device-update-new-field' | translate: { version: data.item.version }"> + [newFieldKeys]="ws.newFieldKeys">
} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html index f8fd99411e..965f6ffefe 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html @@ -95,19 +95,14 @@ @case (FormFieldType.SELECT) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @for (opt of field.options; track opt.value) { {{ opt.label }} } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -117,7 +112,7 @@ @case (FormFieldType.STRING_AUTOCOMPLETE) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -126,13 +121,8 @@ {{ opt.label }} } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -148,7 +138,7 @@ @case (FormFieldType.PASSWORD) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} autorenew } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -187,17 +172,12 @@ @case (FormFieldType.INTEGER) { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} @@ -213,7 +193,7 @@ @default { - {{ field.label }} + {{ field.label }}@if (isNewField(field)) { · {{ 'iot-hub.device-update-new' | translate }}} @@ -225,13 +205,8 @@ autorenew } - @if ((helpTextOf(field) || isNewField(field)) && !(row.hasHintBox && field.helpPopupId)) { - - @if (isNewField(field)) { - {{ newFieldHint }} - } - {{ helpTextOf(field) }} - + @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { + {{ helpTextOf(field) }} } @if (formGroup.controls[field.key]?.hasError('required')) { {{ field.label + ' is required' }} 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 b19765a280..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 @@ -15,20 +15,21 @@ margin-top: 8px; } -// Update: a field the installed version didn't have: outline, label and hint in the primary color +// 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; } } - -.tb-install-form-new-hint { - 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 16a1298ae2..a87c734094 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 @@ -51,8 +51,6 @@ export class InstallFormRendererComponent implements OnChanges { @Input() reviewMode = false; /** Update: the fields the installed version's form didn't have, highlighted as new. */ @Input() newFieldKeys?: Set; - /** Update: the text the hint of a new field starts with. */ - @Input() newFieldHint = ''; passwordVisible: Record = {}; // Fields in render order: consecutive fields of a group form a section, and consecutive fields diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 78db1e922c..4d52160b91 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6545,7 +6545,6 @@ "device-update-existing-create-copy": "Already exists. A copy will be created.", "device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update", "device-update-skipped": "Not changed", - "device-update-new-field": "New in {{version}}.", "device-update-updated": "Updated", "device-update-created": "Created", "device-update-try-again": "Try again", From 83ab5ec8147d8b12d77c11c1e7935bf0c01258d9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:28:30 +0200 Subject: [PATCH 22/66] feat(iot-hub): installed items offer an update through the new version's details --- .../iot-hub-installed-items-table.component.html | 12 +++++------- .../iot-hub-installed-items-table.component.scss | 6 +++--- 2 files changed, 8 insertions(+), 10 deletions(-) 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 ab41384640..8e4d9b57c5 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 @@ -45,19 +45,17 @@ @if (getPublishedVersionInfo(item); as pubInfo) { @if (pubInfo.publishedVersionId !== item.itemVersionId) {
+ @if (!itemVersion) { - } - + + }
} @else { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index 9f304d2751..7d511670b9 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -126,9 +126,9 @@ font-weight: 500; line-height: 20px; letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); + color: var(--tb-primary-500); background: none; - border: 1px solid rgba(0, 0, 0, 0.12); + border: 1px solid var(--tb-primary-500); border-radius: 4px; padding: 6px 12px; cursor: pointer; @@ -143,7 +143,7 @@ } &:hover { - background: rgba(0, 0, 0, 0.04); + background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); } } From f410611ed690d3a877e9dfb05283b1e7f770f216 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:28:46 +0200 Subject: [PATCH 23/66] fix(iot-hub): lowercase available after the version --- ui-ngx/src/assets/locale/locale.constant-en_US.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 4d52160b91..eb84ed9a84 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6325,7 +6325,7 @@ "items-per-page": "Items per page", "filter": "Filter", "clear-filters": "Clear filters", - "available": "Available", + "available": "available", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", "items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.", "items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.", From a25a4563933fbe6e7d30e8e8695e1f13d0900563 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:32:02 +0200 Subject: [PATCH 24/66] fix(iot-hub): keep the update button red --- ...t-hub-installed-items-table.component.html | 2 +- ...t-hub-installed-items-table.component.scss | 32 +------------------ 2 files changed, 2 insertions(+), 32 deletions(-) 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 8e4d9b57c5..6926a0ba41 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 @@ -47,7 +47,7 @@
@if (!itemVersion) { - diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index 7d511670b9..e390164cd5 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -117,37 +117,7 @@ .tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); } .tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); } -// "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8 -.tb-installed-version-btn { - display: inline-flex; - align-items: center; - gap: 8px; - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: var(--tb-primary-500); - background: none; - border: 1px solid var(--tb-primary-500); - border-radius: 4px; - padding: 6px 12px; - cursor: pointer; - font-family: inherit; - - mat-icon { - font-size: 18px; - width: 18px; - height: 18px; - color: inherit !important; - --mat-icon-color: currentColor; - } - - &:hover { - background: color-mix(in srgb, var(--tb-primary-500) 8%, transparent); - } -} - -// "Update" button — Design: same height as available btn, border matches text color +// "vX.X.X available" and "Update to" buttons: border matches the text color .tb-installed-update-btn.mat-mdc-outlined-button { font-size: 14px; font-weight: 500; From cd95b67b8c931b1a1ebe57845c783526cff43656 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 09:34:42 +0200 Subject: [PATCH 25/66] feat(iot-hub): the available version button opens the update --- .../iot-hub-installed-items-table.component.html | 3 +-- .../iot-hub-installed-items-table.component.scss | 5 +++++ .../iot-hub/iot-hub-installed-items-table.component.ts | 10 ---------- 3 files changed, 6 insertions(+), 12 deletions(-) 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 6926a0ba41..08195cac7a 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 @@ -45,9 +45,8 @@ @if (getPublishedVersionInfo(item); as pubInfo) { @if (pubInfo.publishedVersionId !== item.itemVersionId) {
- @if (!itemVersion) { - diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss index e390164cd5..e943f76f46 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss @@ -126,6 +126,11 @@ padding: 6px 12px; height: auto; --mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color); + + mat-icon { + color: inherit !important; + --mat-icon-color: currentColor; + } } // "Up to date" — Design: 14px Medium, #198038, gap-8, py-6 diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 0e332b9d45..27a2215c48 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -242,16 +242,6 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } - viewUpdateDetails(publishedInfo: ItemPublishedVersionInfo, installedItem: IotHubInstalledItem): void { - this.iotHubApiService.getVersionInfo(publishedInfo.publishedVersionId, {ignoreLoading: true}).subscribe(versionView => { - this.iotHubActions.openItemDetail(versionView, installedItem).subscribe(result => { - if (result === 'updated' || result === 'deleted') { - this.loadData(); - } - }); - }); - } - updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { if (result === 'updated') { From 341fd5d3cd247bf4adaf3b22cb0a361b6a9a8149 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Mon, 2 Nov 2026 10:20:01 +0200 Subject: [PATCH 26/66] feat(iot-hub): a device package step takes the default converter, a new default converter shows as an update, and the profile name is set at install - UPLINK_CONVERTER step with "default": true and no template: the wizard builds the converter ThingsBoard creates for a new integration of the method's type (INTEGRATION_TTN: TTN) from the UI assets, and installs, overwrites and updates it like a template of the package. - Installed items: a device package whose default converter differs from ThingsBoard's default converter now shows "New converter available". It opens the update of the installed version, which brings the converter to the default one. A package that took another package's converter overwrites it with the shared-entity warning. - After an update overwrites an entity, the other packages that recorded its checksum record the new one. - INTEGRATION step "metadata": its entries are added to the integration's metadata at create, overwrite, use existing and update; the entries the integration has stay. An entry that maps a name to itself (profile.: ) isn't added. The checksum of an integration leaves out its metadata. - The default TTN and TTI converters take the profile name from the integration metadata entry profile.- when there is one. - Form field "resettable": a field the user changed shows a button that puts its default value back. --- .../DefaultDevicePackageUpdateService.java | 53 +++++++ .../service/iot_hub/DeviceUpdateRequest.java | 2 + .../service/iot_hub/EntityChecksum.java | 5 + .../controller/ConverterControllerTest.java | 29 +++- ...DefaultDevicePackageUpdateServiceTest.java | 64 ++++++++ .../device-install-dialog.component.html | 6 + .../device-install-dialog.component.ts | 138 ++++++++++++++++-- .../install-form-renderer.component.html | 8 + .../install-form-renderer.component.ts | 12 ++ .../iot-hub/iot-hub-default-converter.ts | 57 ++++++++ ...t-hub-installed-items-table.component.html | 40 ++--- ...iot-hub-installed-items-table.component.ts | 52 ++++++- .../models/iot-hub/device-package.models.ts | 6 + .../iot-hub/iot-hub-installed-item.models.ts | 2 + .../src/assets/converters/js-tti-decoder.raw | 12 +- .../src/assets/converters/js-ttn-decoder.raw | 12 +- .../assets/converters/tbel-tti-decoder.raw | 12 +- .../assets/converters/tbel-ttn-decoder.raw | 12 +- .../assets/locale/locale.constant-en_US.json | 2 + 19 files changed, 465 insertions(+), 59 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts 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 index 6b8445d16e..1f452c3792 100644 --- 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 @@ -42,6 +42,8 @@ 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; @@ -285,6 +287,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List saved = new ArrayList<>(); List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); + // The checksums of the entities this update overwrote, which other packages may record too + Map overwrittenChecksums = new HashMap<>(); DashboardId dashboardId = null; for (DeviceUpdateRequest.Step step : request.getSteps()) { @@ -310,6 +314,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (checksum != null) { state.put("checksum", checksum); } + if (step.isDefaultConverter()) { + state.put("defaultConverter", true); + } + if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && result.checksum() != null) { + overwrittenChecksums.put(result.entityId().getId(), result.checksum()); + } installState.put(step.getId() != null ? step.getId() : step.getName(), state); if (!"use-existing".equals(step.getResolution())) { stepEntityIds.add(result.entityId()); @@ -344,12 +354,55 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i installedItem.setVersion(versionInfo.get("version").asText()); installedItem.setDescriptor(descriptor); installedItemService.save(tenantId, installedItem); + refreshChecksumsOfOtherPackages(tenantId, installedItem.getId(), overwrittenChecksums); // 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); } + /** + * Another package that recorded the checksum of an entity this update overwrote, e.g. a shared converter, records the + * new one: the update was confirmed for all packages using the entity, so their next update sees no change by someone else. + */ + private void refreshChecksumsOfOtherPackages(TenantId tenantId, IotHubInstalledItemId installedItemId, Map checksums) { + if (checksums.isEmpty()) { + return; + } + PageLink pageLink = new PageLink(100); + PageData page; + do { + page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); + for (IotHubInstalledItem item : page.getData()) { + if (!item.getId().equals(installedItemId) && item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor + && descriptor.getInstallState() != null && refreshChecksums(descriptor.getInstallState(), checksums)) { + installedItemService.save(tenantId, item); + } + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext()); + } + + private static boolean refreshChecksums(Map installState, Map checksums) { + boolean changed = false; + for (JsonNode state : installState.values()) { + String checksum = checksums.get(toUuid(state.path("entityOutput").path("id").asText())); + if (checksum != null && state.has("checksum") && state instanceof ObjectNode objectState) { + objectState.put("checksum", checksum); + changed = true; + } + } + return changed; + } + + 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. 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 index 28118ed018..c3f2f90f89 100644 --- 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 @@ -61,6 +61,8 @@ public class DeviceUpdateRequest { private JsonNode sharedAttributes; // The resolution the install state records for it private String resolution; + // 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/EntityChecksum.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java index 4cd2f25d02..1f8c8887e5 100644 --- 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 @@ -6,6 +6,7 @@ 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; @@ -37,6 +38,10 @@ final class EntityChecksum { 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('|'); } 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 8ab6727c04..023397bf0b 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -686,9 +686,7 @@ public class ConverterControllerTest extends AbstractControllerTest { testDecoder(TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); } - @Test - public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException { - String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," + + 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\"," + @@ -696,7 +694,17 @@ public class ConverterControllerTest extends AbstractControllerTest { "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + "\"clusterAddress\":\"eu1.cloud.thethings.network\"}}"; - testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, expectedDecodedMessage); + @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 @@ -706,18 +714,18 @@ public class ConverterControllerTest extends AbstractControllerTest { "\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," + "\"spreadingFactor\":9,\"frequency\":\"868300000\"}}"; - testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, expectedDecodedMessage); + testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, Map.of("profile.milesight-iot-am308", "AM308"), expectedDecodedMessage); } // 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, String expectedResult) throws IOException { + private void testThingsStackDefaultConverters(String payloadFile, Map integrationMetadata, String expectedResult) throws IOException { JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); String payload = readResource(payloadFile); for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); for (ScriptLanguage scriptLang : ScriptLanguage.values()) { String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; - assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang))) + assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang, integrationMetadata))) .as("%s %s", integrationType, scriptLang) .isEqualTo(JacksonUtil.toJsonNode(expectedResult)); } @@ -896,6 +904,12 @@ public class ConverterControllerTest extends AbstractControllerTest { } private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException { + return decode(decoderFileName, payloadExample, converter, scriptLang, Map.of()); + } + + // integrationMetadata: what the integration adds to the metadata of every uplink, from its configuration + private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang, + Map integrationMetadata) throws IOException { byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName)); String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8)); @@ -917,6 +931,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 index 6fbf49587c..e0281891aa 100644 --- 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 @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 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; @@ -34,6 +35,7 @@ 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; @@ -165,6 +167,7 @@ class DefaultDevicePackageUpdateServiceTest { device.setTenantId(tenantId); device.setName("AM308"); when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); + when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>()); } @Test @@ -335,6 +338,40 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); } + @Test + void overwrittenSharedConverter_isRecordedAsDefaultAndOtherPackagesTakeItsChecksum() { + 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(); + assertThat(created.get("checksum").asText()).isEqualTo(state.get("checksum").asText()); + assertThat(usedExisting.has("checksum")).isFalse(); + verify(installedItemService).save(tenantId, creator); + verify(installedItemService, never()).save(tenantId, taker); + } + @Test void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); @@ -443,6 +480,22 @@ class DefaultDevicePackageUpdateServiceTest { 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"))) @@ -464,6 +517,17 @@ class DefaultDevicePackageUpdateServiceTest { 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); 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 7fb651678e..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 @@ -177,6 +177,9 @@
{{ 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) } }} @@ -252,6 +255,9 @@
@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 }} } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ca88fa519e..e515186140 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -35,6 +35,11 @@ import { IntegrationService } from '@core/http/integration.service'; import { DialogService } from '@core/services/dialog.service'; import { Converter, ConverterType } from '@shared/models/converter.models'; import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service'; +import { ResourcesService } from '@core/services/resources.service'; +import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { ScriptLanguage } from '@shared/models/rule-node.models'; +import { IntegrationType } from '@shared/models/integration.models'; +import { differsFromDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; import { cleanFormFieldValue, DeviceInstallStep, @@ -98,6 +103,8 @@ interface EntityStepPlan { version?: number; // Modified: the entity as the check found it, which the user can download before it is overwritten current?: any; + // A step with "default": true whose converter differs from ThingsBoard's default converter now + newDefaultConverter?: boolean; } /** @@ -225,6 +232,8 @@ export interface ConnectionCheck { } const ENTITY_STEP_MIN_DELAY = 2000; +// Where the wizard keeps the converter it builds for a step with "default": true, as if the package had that file +const DEFAULT_CONVERTER_PATH = 'tb-default-converter/'; const DEFAULT_RANDOM_SIZE = 20; const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost'; const TRANSPORT_PORT_FIELD_KEY = 'tbTransportPort'; @@ -359,6 +368,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); private previousPackageInfo: DevicePackageInfo | null = null; private entityPlans = new WeakMap(); + // Update: for each step with "default": true, whether its converter differs from ThingsBoard's default one now + private defaultConverterChanges = new Map(); // Variable resolution state formValues: Record = {}; @@ -397,7 +408,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.packageInfo.installSteps[ct]?.length > 0 ); @@ -440,6 +453,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (step.type === InstallStepType.INTEGRATION && step.metadata) { + return this.addStepMetadata(step, existing); + } if (step.type !== InstallStepType.DEVICE && step.type !== InstallStepType.GATEWAY) { return existing; } @@ -1814,6 +1833,35 @@ export class TbDeviceInstallDialogComponent extends DialogComponent: does when the + * user kept the default profile name, isn't added. + */ + private withStepMetadata(step: DeviceInstallStep, metadata: Record | null | undefined): Record { + const merged = { ...(metadata ?? {}) }; + for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) { + const key = this.resolveVariables(rawKey); + const value = this.resolveVariables(String(rawValue ?? '')); + if (value && !value.includes('${') && value !== key.substring(key.indexOf('.') + 1)) { + merged[key] = value; + } + } + return merged; + } + + /** An integration taken as it is still gets the step's metadata: the package's converter reads it. */ + private async addStepMetadata(step: DeviceInstallStep, existing: EntityStepOutput): Promise { + const integration = await firstValueFrom(this.integrationService.getIntegration(existing.id, {ignoreErrors: true})); + const metadata = this.withStepMetadata(step, integration.configuration?.metadata); + if (isEqual(metadata, integration.configuration?.metadata ?? {})) { + return existing; + } + integration.configuration = { ...integration.configuration, metadata }; + const result = await firstValueFrom(this.integrationService.saveIntegration(integration, {ignoreErrors: true})); + return this.buildIntegrationOutput(result); + } + /** Stores the gateway output early, so the custom docker-compose template, if any, resolves ${gateway.token} etc. */ private setGatewayOutput(step: DeviceInstallStep, output: EntityStepOutput): void { this.entityOutputs.set('gateway', output); @@ -2001,7 +2049,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { for (const ep of ws.entitySteps) { const plan = this.entityPlans.get(ep); const alias = stepTypeAliasMap[ep.step.type]; @@ -2068,16 +2116,21 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.buildUpdateStep(ws, ep.step, this.entityPlans.get(ep))); + const steps: DeviceUpdateStep[] = []; + for (const ep of ws.entitySteps) { + steps.push(await this.buildUpdateStep(ws, ep.step, this.entityPlans.get(ep))); + } + return steps; } - private buildUpdateStep(ws: WizardStep, step: DeviceInstallStep, plan: EntityStepPlan): DeviceUpdateStep { + private async buildUpdateStep(ws: WizardStep, step: DeviceInstallStep, plan: EntityStepPlan): Promise { const base: DeviceUpdateStep = { name: step.name, id: step.id, type: step.type, action: 'KEEP', - resolution: plan.previous?.resolution ?? plan.resolution ?? 'created' + resolution: plan.previous?.resolution ?? plan.resolution ?? 'created', + defaultConverter: step.default || undefined }; if (step.type === InstallStepType.GATEWAY_CONNECTOR) { return plan.action === 'keep' ? base : { ...base, action: 'OVERWRITE', entity: this.resolveTemplateJson(this.zipFiles.get(step.template)) }; @@ -2090,6 +2143,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const scriptLang = getCurrentAuthState(this.store).tbelEnabled ? ScriptLanguage.TBEL : ScriptLanguage.JS; + for (const [method, steps] of Object.entries(this.packageInfo.installSteps ?? {})) { + for (const step of steps) { + if (step.type !== InstallStepType.UPLINK_CONVERTER || !step.default) { + continue; + } + const integrationType = method.replace(/^INTEGRATION_/, '') as IntegrationType; + const converter = await loadDefaultUplinkConverter(this.resourcesService, integrationType, scriptLang, step.name); + if (!converter) { + throw new Error(`ThingsBoard has no default converter for ${integrationType}`); + } + step.template = `${DEFAULT_CONVERTER_PATH}${integrationType}.json`; + this.zipFiles.set(step.template, JSON.stringify(converter)); + } + } + } + + /** + * Update: ThingsBoard's default converter changes with ThingsBoard, not with the package, so a step with "default": true + * changed when the package's converter differs from the default one now. A converter the user changed differs too: + * the update shows that someone changed it. + */ + private async checkDefaultConverters(): Promise { + this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + try { + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { + const id = step.default ? this.storedStateOf(step)?.state?.entityOutput?.id : undefined; + const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true})).catch(() => null) : null; + if (converter) { + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + this.defaultConverterChanges.set(step, !!defaultConverter && differsFromDefaultConverter(converter, defaultConverter)); + } + } + } finally { + this.formValues = {}; + this.entityOutputs.clear(); + } + } + /** Update: loads the installed version. Without it, every form and entity of the new version counts as changed. */ private async loadPreviousVersion(): Promise { try { @@ -2343,12 +2447,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual( this.resolvePackageFile(this.zipFiles, step[file], this.formValues), this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues) @@ -2418,6 +2525,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponentautorenew } + @if (canResetToDefault(field)) { + + } @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { {{ helpTextOf(field) }} } 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 a87c734094..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 @@ -138,6 +138,18 @@ 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; 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..b90a362da3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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'; + +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)); +}; 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 08195cac7a..db7ad21423 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 @@ -42,26 +42,26 @@ @if (updatesChecked) { {{ 'iot-hub.updates' | translate }} } @if (updatesChecked) { - @if (getPublishedVersionInfo(item); as pubInfo) { - @if (pubInfo.publishedVersionId !== item.itemVersionId) { -
- @if (!itemVersion) { - - } @else { - - } -
- } @else { - - check - {{ 'iot-hub.up-to-date' | translate }} - - } + @let pubInfo = getPublishedVersionInfo(item); + @if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) { +
+ @if (!itemVersion) { + + } @else { + + } +
+ } @else if (hasConverterUpdate(item)) { + + } @else { check diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 27a2215c48..765f563898 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -36,6 +36,10 @@ import { entityTypeTranslations } from '@shared/models/entity-type.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { ConverterService } from '@core/http/converter.service'; +import { ResourcesService } from '@core/services/resources.service'; +import { differsFromDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { firstValueFrom } from 'rxjs'; @Component({ selector: 'tb-iot-hub-installed-items-table', @@ -68,6 +72,8 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, isLoading = false; publishedVersionMap = new Map(); + // Installed device packages whose default converter differs from ThingsBoard's default converter now + converterUpdates = new Set(); updatesChecked = false; isCheckingUpdates = false; @@ -83,7 +89,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private iotHubActions: IotHubActionsService, private elementRef: ElementRef, private zone: NgZone, - private cd: ChangeDetectorRef + private cd: ChangeDetectorRef, + private converterService: ConverterService, + private resourcesService: ResourcesService ) { this.widgetResize$ = new ResizeObserver(() => { this.zone.run(() => { @@ -235,6 +243,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); this.updatesChecked = true; this.isCheckingUpdates = false; + void this.checkConverterUpdates(); }, error: () => { this.isCheckingUpdates = false; @@ -250,6 +259,44 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, }); } + hasConverterUpdate(item: IotHubInstalledItem): boolean { + return this.converterUpdates.has(item.id.id); + } + + /** The update to the installed version itself brings the converter to ThingsBoard's default one. */ + updateConverter(item: IotHubInstalledItem): void { + this.iotHubActions.updateItem(item, item.version, item.itemVersionId).subscribe(result => { + if (result === 'updated') { + this.loadData(); + } + }); + } + + /** + * The device packages on this page whose step with "default": true installed a converter that differs from + * ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it. + */ + private async checkConverterUpdates(): Promise { + const updates = new Set(); + for (const item of this.dataSource) { + const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; + for (const state of states) { + const id = state?.defaultConverter ? state.entityOutput?.id : undefined; + const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) + .catch(() => null) : null; + if (converter) { + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + if (defaultConverter && differsFromDefaultConverter(converter, defaultConverter)) { + updates.add(item.id.id); + } + } + } + } + this.converterUpdates = updates; + this.cd.markForCheck(); + } + getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { return this.publishedVersionMap.get(item.itemId); } @@ -267,6 +314,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, this.dataSource = data.data; this.totalElements = data.totalElements; this.isLoading = false; + if (this.updatesChecked && !this.itemVersion) { + void this.checkConverterUpdates(); + } }, error: () => { this.dataSource = []; diff --git a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts index 62e38c0541..088f787440 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts @@ -226,6 +226,10 @@ export interface DeviceInstallStep { dockerCompose?: string; // INTEGRATION step references the integration-form.json artifact alongside the template. form?: string; + // UPLINK_CONVERTER: ThingsBoard's default converter for the method's integration instead of a template + default?: boolean; + // INTEGRATION: entries added to the integration's metadata, which keeps the entries it has + metadata?: Record; } export interface DevicePackageInfo { @@ -285,6 +289,8 @@ export interface FormFieldDefinition { // Consecutive fields with the same group are shown in one panel titled with the group group?: string; readOnly?: boolean; + // A STRING field the user changed shows a button that puts defaultValue back + resettable?: boolean; // Shown inside the empty field; the label then always stays above it placeholder?: string; // Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it. diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index fbdd9867c3..494605caf4 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -62,6 +62,8 @@ export interface DeviceUpdateStep { resolution?: string; // The package step's id, which keys its install state; the name when not set id?: string; + // The step takes ThingsBoard's default converter: its install state says so, for the update check + defaultConverter?: boolean; } export interface DeviceUpdateRequest { diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index 5cb10f8db1..ee4314679b 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -1,6 +1,7 @@ // 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. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == 'JSON') { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') { var profile = 'LoRaWAN Device'; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + '-' + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata['profile.' + profile]; + if (customProfile != null && customProfile != '') { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == 'milesight-iot-am308') { -// profile = 'AM308'; -// } if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index 5cb10f8db1..ee4314679b 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -1,6 +1,7 @@ // 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. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == 'JSON') { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') { var profile = 'LoRaWAN Device'; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + '-' + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata['profile.' + profile]; + if (customProfile != null && customProfile != '') { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == 'milesight-iot-am308') { -// profile = 'AM308'; -// } if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 09c75b5aed..1cfef4546d 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -1,6 +1,7 @@ // 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. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == "JSON") { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") { var profile = "LoRaWAN Device"; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + "-" + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata["profile." + profile]; + if (customProfile != null && customProfile != "") { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == "milesight-iot-am308") { -// profile = "AM308"; -// } if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 09c75b5aed..1cfef4546d 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -1,6 +1,7 @@ // 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. Any other device gets LoRaWAN Device. +// Such a device gets the profile -, so all devices of one model share it, +// or the name the integration metadata gives it under profile.-. Any other device gets LoRaWAN Device. var values = {}; var history = []; if (metadata.payloadFormat == "JSON") { @@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") { var profile = "LoRaWAN Device"; if (metadata.brandId != null && metadata.modelId != null) { profile = metadata.brandId + "-" + metadata.modelId; + // The profile name chosen at install, kept in the integration metadata + var customProfile = metadata["profile." + profile]; + if (customProfile != null && customProfile != "") { + profile = customProfile; + } } -// To give a model its own profile name, map it here, for example: -// if (profile == "milesight-iot-am308") { -// profile = "AM308"; -// } if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index eb84ed9a84..68a0906635 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6452,6 +6452,7 @@ "check-for-updates": "Check for updates", "updates": "Updates", "up-to-date": "Up to date", + "new-converter-available": "New converter available", "update": "Update", "update-to-version": "Update to v {{ version }}", "update-item-title": "Update Item", @@ -6538,6 +6539,7 @@ "device-update-no-conflicts": "No conflicts", "device-update-new": "New", "device-update-shared": "Used by other packages. The update affects them.", + "device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.", "device-update-modified": "Has local changes. You can download the current version here.", "device-install-unexpected-error": "Something went wrong. Try again.", "device-update-existing-use-existing": "Already exists. The existing one will be used.", From 4bfa5d91153ae83dd9c7f4faede9f4a7593cdf0f Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 10:20:54 +0200 Subject: [PATCH 27/66] fix(iot-hub): keep the package's own entity on use-existing, find a step that gained an id by its name --- .../device-install-dialog.component.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ca88fa519e..327590d41c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2086,7 +2086,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } + /** Update: true when the entity is one the installed package created. */ + private isPackageEntity(id: string): boolean { + return !!this.data.update?.descriptor.createdEntityIds?.some(created => created.id === id); + } + /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ private stateKeysOf(step: DeviceInstallStep): string[] { return step.id ? [step.id] : [step.name, this.resolveVariables(step.name)]; } - /** Update: the install state of a step of the new version, under the key of the installed step it replaces. */ + /** + * Update: the install state of a step of the new version, under the key of the installed step it replaces. + * Without the installed version's steps (e.g. it can't be downloaded any more), a step that has gained an id + * is also looked up under its own name, which the installed version keyed it by. + */ private storedStateOf(step: DeviceInstallStep): { key: string; state: any } | undefined { const installState = this.data.update?.descriptor.installState ?? {}; const previousStep = this.findPreviousStep(step); const keys = [...(previousStep ? this.stateKeysOf(previousStep) : []), ...this.stateKeysOf(step)]; + if (!previousStep && step.id) { + keys.push(step.name, this.resolveVariables(step.name)); + } const key = keys.find(k => k && installState[k]); return key ? { key, state: installState[key] } : undefined; } From f536a08e21117c49ba42e7dac70dfc80c5675bd7 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 10:45:51 +0200 Subject: [PATCH 28/66] fix(iot-hub): the server keeps the package's own entities, the name fallback only without the installed version --- .../iot_hub/DefaultDevicePackageUpdateService.java | 10 +++++++--- .../DefaultDevicePackageUpdateServiceTest.java | 14 ++++++++++++++ .../device-install-dialog.component.ts | 2 +- 3 files changed, 22 insertions(+), 4 deletions(-) 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 index 6b8445d16e..380f372ea7 100644 --- 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 @@ -271,6 +271,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + Set ownedIds = createdIds(previous).keySet(); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); Map installState = new LinkedHashMap<>(); @@ -303,7 +304,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i outputs.put(step.getName(), output); ObjectNode state = JacksonUtil.newObjectNode(); state.set("entityOutput", output); - state.put("resolution", step.getResolution() != null ? step.getResolution() : "created"); + // 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(); @@ -311,7 +315,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("checksum", checksum); } installState.put(step.getId() != null ? step.getId() : step.getName(), state); - if (!"use-existing".equals(step.getResolution())) { + if (!"use-existing".equals(resolution)) { stepEntityIds.add(result.entityId()); } if (result.entityId() instanceof DashboardId id) { @@ -320,7 +324,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) { + 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())); } 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 index 6fbf49587c..0d6bed9f0f 100644 --- 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 @@ -256,6 +256,20 @@ class DefaultDevicePackageUpdateServiceTest { 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 twoStepsWithOneKey_areRejected() { DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 327590d41c..fc1718b108 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2344,7 +2344,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent k && installState[k]); From 464147b6f7eda98484ac6721784ba689a695dd29 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:04:41 +0200 Subject: [PATCH 29/66] fix(iot-hub): a package owns the entities its install state records, except use-existing ones --- .../DefaultDevicePackageUpdateService.java | 24 +++++++++++- ...DefaultDevicePackageUpdateServiceTest.java | 37 ++++++++++++++++++- .../device-install-dialog.component.ts | 8 +++- 3 files changed, 64 insertions(+), 5 deletions(-) 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 index db5dc64379..5ab98c932e 100644 --- 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 @@ -204,7 +204,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (request.getSteps() == null || request.getSteps().isEmpty()) { throw new IllegalArgumentException("The update has no steps"); } - Set ownedIds = createdIds(devicePackage.descriptor()).keySet(); + 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())) { @@ -273,7 +273,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); - Set ownedIds = createdIds(previous).keySet(); + Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); Map installState = new LinkedHashMap<>(); @@ -840,6 +840,26 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type)); } + /** + * The entities the package owns: those its install state records, except the ones the user chose to use as they + * were. Not createdEntityIds: the install adds the use-existing ones to it too. + */ + private static Set ownedIds(DeviceInstalledItemDescriptor descriptor) { + Set ids = new HashSet<>(); + if (descriptor.getInstallState() != null) { + descriptor.getInstallState().values().forEach(state -> { + JsonNode id = state.path("entityOutput").path("id"); + if (id.isTextual() && !"use-existing".equals(state.path("resolution").asText())) { + try { + ids.add(UUID.fromString(id.asText())); + } catch (IllegalArgumentException ignored) { + } + } + }); + } + return ids; + } + private static Map createdIds(DeviceInstalledItemDescriptor descriptor) { Map ids = new HashMap<>(); if (descriptor.getCreatedEntityIds() != null) { 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 index 7b02a966fa..06d0109b82 100644 --- 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 @@ -135,7 +135,9 @@ class DefaultDevicePackageUpdateServiceTest { descriptor.setSelectedInstallMethod("INTEGRATION_TTN"); descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId)); descriptor.setDashboardId(dashboardId); - descriptor.setInstallState(Map.of()); + // 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); @@ -273,6 +275,32 @@ class DefaultDevicePackageUpdateServiceTest { 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 twoStepsWithOneKey_areRejected() { DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); @@ -593,4 +621,11 @@ class DefaultDevicePackageUpdateServiceTest { 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/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 77fef10a5e..5085d7fc96 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -2429,9 +2429,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } - /** Update: true when the entity is one the installed package created. */ + /** + * Update: true when the entity is one the installed package owns: its install state records it, and not as one + * the user chose to use as it was. Not createdEntityIds: the install adds the use-existing ones to it too. + */ private isPackageEntity(id: string): boolean { - return !!this.data.update?.descriptor.createdEntityIds?.some(created => created.id === id); + return Object.values(this.data.update?.descriptor.installState ?? {}) + .some(state => state?.entityOutput?.id === id && state.resolution !== 'use-existing'); } /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ From 50eff0dd15667da9e07eafa2086d7bce9052e6d9 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:37:10 +0200 Subject: [PATCH 30/66] fix(iot-hub): keep the used-existing ids, check shared entities against every package's checksums, fix the default converter review --- .../DefaultDevicePackageUpdateService.java | 82 +++++++++--------- ...DefaultDevicePackageUpdateServiceTest.java | 71 +++++++++++++++- .../DeviceInstalledItemDescriptor.java | 2 + .../src/app/core/http/iot-hub-api.service.ts | 2 +- .../device-install-dialog.component.ts | 84 ++++++++++++++++--- .../iot-hub/iot-hub-default-converter.ts | 9 ++ ...iot-hub-installed-items-table.component.ts | 8 +- .../iot-hub/iot-hub-installed-item.models.ts | 2 + 8 files changed, 203 insertions(+), 57 deletions(-) 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 index 5ab98c932e..c8dd0e69f8 100644 --- 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 @@ -137,6 +137,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i 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) { @@ -149,8 +150,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } 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()); + !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()))); }); @@ -285,11 +289,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }); } List stepEntityIds = new ArrayList<>(); + Map usedExistingIds = usedExistingIds(previous); List saved = new ArrayList<>(); List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); // The checksums of the entities this update overwrote, which other packages may record too - Map overwrittenChecksums = new HashMap<>(); DashboardId dashboardId = null; for (DeviceUpdateRequest.Step step : request.getSteps()) { @@ -321,12 +325,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (step.isDefaultConverter()) { state.put("defaultConverter", true); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && result.checksum() != null) { - overwrittenChecksums.put(result.entityId().getId(), result.checksum()); - } installState.put(step.getId() != null ? step.getId() : step.getName(), state); if (!"use-existing".equals(resolution)) { stepEntityIds.add(result.entityId()); + } else { + usedExistingIds.putIfAbsent(result.entityId().getId(), result.entityId()); } if (result.entityId() instanceof DashboardId id) { dashboardId = id; @@ -349,6 +352,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // 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); descriptor.setInstallState(state); @@ -358,45 +364,33 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i installedItem.setVersion(versionInfo.get("version").asText()); installedItem.setDescriptor(descriptor); installedItemService.save(tenantId, installedItem); - refreshChecksumsOfOtherPackages(tenantId, installedItem.getId(), overwrittenChecksums); // 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); } - /** - * Another package that recorded the checksum of an entity this update overwrote, e.g. a shared converter, records the - * new one: the update was confirmed for all packages using the entity, so their next update sees no change by someone else. - */ - private void refreshChecksumsOfOtherPackages(TenantId tenantId, IotHubInstalledItemId installedItemId, Map checksums) { - if (checksums.isEmpty()) { - return; - } + /** 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.getId().equals(installedItemId) && item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor - && descriptor.getInstallState() != null && refreshChecksums(descriptor.getInstallState(), checksums)) { - installedItemService.save(tenantId, item); + 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()); - } - - private static boolean refreshChecksums(Map installState, Map checksums) { - boolean changed = false; - for (JsonNode state : installState.values()) { - String checksum = checksums.get(toUuid(state.path("entityOutput").path("id").asText())); - if (checksum != null && state.has("checksum") && state instanceof ObjectNode objectState) { - objectState.put("checksum", checksum); - changed = true; - } - } - return changed; + return checksums; } private static UUID toUuid(String id) { @@ -841,19 +835,31 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The entities the package owns: those its install state records, except the ones the user chose to use as they - * were. Not createdEntityIds: the install adds the use-existing ones to it too. + * 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<>(); + 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 -> { - JsonNode id = state.path("entityOutput").path("id"); - if (id.isTextual() && !"use-existing".equals(state.path("resolution").asText())) { - try { - ids.add(UUID.fromString(id.asText())); - } catch (IllegalArgumentException ignored) { - } + 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)); } }); } 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 index 06d0109b82..2f7e4f57b0 100644 --- 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 @@ -117,6 +117,8 @@ class DefaultDevicePackageUpdateServiceTest { private SubscriptionService subscriptionService; @Mock private TelemetrySubscriptionService telemetryService; + @Mock + private IotHubService iotHubService; @InjectMocks private DefaultDevicePackageUpdateService service; @@ -301,6 +303,67 @@ class DefaultDevicePackageUpdateServiceTest { 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)); + // 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 twoStepsWithOneKey_areRejected() { DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); @@ -381,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest { } @Test - void overwrittenSharedConverter_isRecordedAsDefaultAndOtherPackagesTakeItsChecksum() { + void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() { ConverterId converterId = new ConverterId(UUID.randomUUID()); Converter current = new Converter(converterId); current.setTenantId(tenantId); @@ -408,9 +471,9 @@ class DefaultDevicePackageUpdateServiceTest { assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); assertThat(state.get("defaultConverter").asBoolean()).isTrue(); - assertThat(created.get("checksum").asText()).isEqualTo(state.get("checksum").asText()); - assertThat(usedExisting.has("checksum")).isFalse(); - verify(installedItemService).save(tenantId, creator); + // 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); } 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..25734fae2d 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 @@ -14,6 +14,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/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 1bf462ce35..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 @@ -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( diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 5085d7fc96..195e5e0e3b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -18,7 +18,8 @@ import { DeviceInstalledItemDescriptor, DevicePackageEntityState, DeviceUpdateResult, - DeviceUpdateStep + DeviceUpdateStep, + IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { DeviceProfileService } from '@core/http/device-profile.service'; @@ -39,7 +40,8 @@ import { ResourcesService } from '@core/services/resources.service'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { ScriptLanguage } from '@shared/models/rule-node.models'; import { IntegrationType } from '@shared/models/integration.models'; -import { differsFromDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { PageData } from '@shared/models/page/page-data'; import { cleanFormFieldValue, DeviceInstallStep, @@ -1462,7 +1464,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent: does when the - * user kept the default profile name, isn't added. + * user kept the default profile name, isn't added, and an earlier value of it is removed: the name is the default again. */ private withStepMetadata(step: DeviceInstallStep, metadata: Record | null | undefined): Record { const merged = { ...(metadata ?? {}) }; for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) { const key = this.resolveVariables(rawKey); const value = this.resolveVariables(String(rawValue ?? '')); - if (value && !value.includes('${') && value !== key.substring(key.indexOf('.') + 1)) { + if (!value || value.includes('${')) { + continue; + } + if (value === key.substring(key.indexOf('.') + 1)) { + delete merged[key]; + } else { merged[key] = value; } } @@ -2282,7 +2290,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent null) : null; if (converter) { const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, @@ -2348,7 +2361,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -2429,13 +2442,30 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } + /** True when a device package installed the converter itself, as its default converter. */ + private async isInstalledDefaultConverter(id: string): Promise { + let pageLink = new PageLink(100); + let page: PageData; + do { + page = await firstValueFrom(this.iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); + if (page.data.some(item => isOwnDefaultConverter(item, id))) { + return true; + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext); + return false; + } + /** - * Update: true when the entity is one the installed package owns: its install state records it, and not as one - * the user chose to use as it was. Not createdEntityIds: the install adds the use-existing ones to it too. + * Update: true when the entity is one the installed package owns: it created it, not the user chose to use it as it was. + * The same rule as the server's: createdEntityIds without usedExistingEntityIds, which an install made before the + * descriptor kept them has only in its install state. */ private isPackageEntity(id: string): boolean { - return Object.values(this.data.update?.descriptor.installState ?? {}) - .some(state => state?.entityOutput?.id === id && state.resolution !== 'use-existing'); + const descriptor = this.data.update?.descriptor; + const usedExisting = descriptor?.usedExistingEntityIds?.some(used => used.id === id) ?? + Object.values(descriptor?.installState ?? {}).some(state => state?.entityOutput?.id === id && state.resolution === 'use-existing'); + return !!descriptor?.createdEntityIds?.some(created => created.id === id) && !usedExisting; } /** The keys the install state may keep a step under: its id, or else its name, as written or resolved. */ @@ -2478,7 +2508,23 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual( this.resolvePackageFile(this.zipFiles, step[file], this.formValues), this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues) - )); + )) || !isEqual( + // An INTEGRATION step's metadata entries, which the package's converter reads, are written when it is overwritten + this.resolveStepMetadata(step.metadata, this.formValues), + this.resolveStepMetadata(previousStep.metadata, previousFormValues) + ); + } + + /** The metadata entries of a step, resolved with the given form values. */ + private resolveStepMetadata(metadata: Record | undefined, formValues: Record): Record { + const committedValues = this.formValues; + this.formValues = formValues; + try { + return Object.fromEntries(Object.entries(metadata ?? {}) + .map(([key, value]) => [this.resolveVariables(key), this.resolveVariables(String(value ?? ''))])); + } finally { + this.formValues = committedValues; + } } /** Update: the form values the installed version was installed with. */ @@ -2708,6 +2754,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); }; + +/** + * True when the device package installed the converter itself as its default converter, not one it took as it was: + * only such a converter is ThingsBoard's default one, which a new ThingsBoard version may change. + */ +export const isOwnDefaultConverter = (item: IotHubInstalledItem, converterId: string): boolean => + item.itemType === 'DEVICE' && Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) + .some(state => state?.defaultConverter && state.entityOutput?.id === converterId && state.resolution !== 'use-existing'); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 765f563898..d4cf0d4df0 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -38,7 +38,7 @@ import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/ import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { ConverterService } from '@core/http/converter.service'; import { ResourcesService } from '@core/services/resources.service'; -import { differsFromDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; import { firstValueFrom } from 'rxjs'; @Component({ @@ -281,7 +281,11 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, for (const item of this.dataSource) { const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; for (const state of states) { - const id = state?.defaultConverter ? state.entityOutput?.id : undefined; + let id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; + // A converter taken as it was counts only when a package installed it as its default converter + if (id && state.resolution === 'use-existing' && !this.dataSource.some(other => isOwnDefaultConverter(other, id))) { + id = undefined; + } const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) .catch(() => null) : null; if (converter) { diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 494605caf4..eb4776d107 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -30,6 +30,8 @@ export interface RuleChainInstalledItemDescriptor { export interface DeviceInstalledItemDescriptor { type: 'DEVICE'; createdEntityIds?: { entityType: string; id: string }[]; + // Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them + usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { id: string }; selectedInstallMethod?: string; installState?: Record; From 31dda2cf4153452fc722290c5a595b13fd447240 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:51:31 +0200 Subject: [PATCH 31/66] fix(iot-hub): a kept integration gets the step's metadata entries, one lookup of the packages' own default converters --- .../DefaultDevicePackageUpdateService.java | 27 ++++++ .../service/iot_hub/DeviceUpdateRequest.java | 3 + ...DefaultDevicePackageUpdateServiceTest.java | 51 +++++++++++ .../device-install-dialog.component.ts | 89 ++++++++++--------- .../iot-hub/iot-hub-default-converter.ts | 28 ++++-- ...iot-hub-installed-items-table.component.ts | 11 ++- .../iot-hub/iot-hub-installed-item.models.ts | 2 + 7 files changed, 159 insertions(+), 52 deletions(-) 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 index c8dd0e69f8..399e46f6ac 100644 --- 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 @@ -587,6 +587,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { existing(tenantId, current, step); + if (mergeMetadata(current, step.getMetadata())) { + Integration result = integrationService.saveIntegration(current); + return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); + } return new StepResult(id, integrationOutput(current), null, null); } Integration integration = JacksonUtil.treeToValue(entity, Integration.class); @@ -607,6 +611,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); } + /** Merges the step's metadata entries into the integration's; true when that changed it. */ + private static boolean mergeMetadata(Integration integration, JsonNode entries) { + if (entries == null || !entries.isObject() || entries.isEmpty()) { + return false; + } + ObjectNode configuration = integration.getConfiguration() != null && integration.getConfiguration().isObject() ? + (ObjectNode) integration.getConfiguration() : JacksonUtil.newObjectNode(); + ObjectNode metadata = configuration.get("metadata") 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(configuration.get("metadata")) || (metadata.isEmpty() && configuration.get("metadata") == null)) { + return false; + } + configuration.set("metadata", metadata); + integration.setConfiguration(configuration); + return true; + } + /** * 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. 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 index c3f2f90f89..b8f31cef32 100644 --- 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 @@ -61,6 +61,9 @@ public class DeviceUpdateRequest { 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/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java index 2f7e4f57b0..76bad73451 100644 --- 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 @@ -364,6 +364,57 @@ class DefaultDevicePackageUpdateServiceTest { 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(); + assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText()) + .isEqualTo("use-existing"); + } + + @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); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 195e5e0e3b..f049ee97b8 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -18,8 +18,7 @@ import { DeviceInstalledItemDescriptor, DevicePackageEntityState, DeviceUpdateResult, - DeviceUpdateStep, - IotHubInstalledItem + DeviceUpdateStep } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { DeviceProfileService } from '@core/http/device-profile.service'; @@ -40,8 +39,7 @@ import { ResourcesService } from '@core/services/resources.service'; import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { ScriptLanguage } from '@shared/models/rule-node.models'; import { IntegrationType } from '@shared/models/integration.models'; -import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; -import { PageData } from '@shared/models/page/page-data'; +import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; import { cleanFormFieldValue, DeviceInstallStep, @@ -1843,13 +1841,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent | null | undefined): Record { const merged = { ...(metadata ?? {}) }; - for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) { - const key = this.resolveVariables(rawKey); - const value = this.resolveVariables(String(rawValue ?? '')); - if (!value || value.includes('${')) { - continue; - } - if (value === key.substring(key.indexOf('.') + 1)) { + for (const [key, value] of Object.entries(this.stepMetadataEntries(step))) { + if (value === null) { delete merged[key]; } else { merged[key] = value; @@ -1858,6 +1851,34 @@ export class TbDeviceInstallDialogComponent extends DialogComponent | undefined { + this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + try { + return this.integrationMetadataOf(step); + } finally { + this.formValues = {}; + this.entityOutputs.clear(); + } + } + + private integrationMetadataOf(step: DeviceInstallStep): Record | undefined { + return step.type === InstallStepType.INTEGRATION && step.metadata ? this.stepMetadataEntries(step) : undefined; + } + + /** The INTEGRATION step's metadata entries, resolved: null for a self-mapping, whose earlier value is removed. */ + private stepMetadataEntries(step: DeviceInstallStep): Record { + const entries: Record = {}; + for (const [rawKey, rawValue] of Object.entries(step.metadata ?? {})) { + const key = this.resolveVariables(rawKey); + const value = this.resolveVariables(String(rawValue ?? '')); + if (value && !value.includes('${')) { + entries[key] = value === key.substring(key.indexOf('.') + 1) ? null : value; + } + } + return entries; + } + /** An integration taken as it is still gets the step's metadata: the package's converter reads it. */ private async addStepMetadata(step: DeviceInstallStep, existing: EntityStepOutput): Promise { const integration = await firstValueFrom(this.integrationService.getIntegration(existing.id, {ignoreErrors: true})); @@ -2138,7 +2159,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { this.restoreInstallState(this.data.update.descriptor.installState ?? {}); + let ownDefaultConverterIds: Set | undefined; try { for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { const stored = step.default ? this.storedStateOf(step)?.state : undefined; let id: string = stored?.entityOutput?.id; // A converter taken as it was may be any converter with that name: only another package's default one is checked - if (id && stored.resolution === 'use-existing' && !(await this.isInstalledDefaultConverter(id))) { - id = undefined; + if (id && stored.resolution === 'use-existing') { + ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService); + if (!ownDefaultConverterIds.has(id)) { + id = undefined; + } } const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true})).catch(() => null) : null; if (converter) { @@ -2361,7 +2388,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -2442,19 +2470,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field.key).filter(key => !previousKeys.has(key))); } - /** True when a device package installed the converter itself, as its default converter. */ - private async isInstalledDefaultConverter(id: string): Promise { - let pageLink = new PageLink(100); - let page: PageData; - do { - page = await firstValueFrom(this.iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); - if (page.data.some(item => isOwnDefaultConverter(item, id))) { - return true; - } - pageLink = pageLink.nextPageLink(); - } while (page.hasNext); - return false; - } + /** * Update: true when the entity is one the installed package owns: it created it, not the user chose to use it as it was. @@ -2508,24 +2524,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual( this.resolvePackageFile(this.zipFiles, step[file], this.formValues), this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues) - )) || !isEqual( - // An INTEGRATION step's metadata entries, which the package's converter reads, are written when it is overwritten - this.resolveStepMetadata(step.metadata, this.formValues), - this.resolveStepMetadata(previousStep.metadata, previousFormValues) - ); + )); } - /** The metadata entries of a step, resolved with the given form values. */ - private resolveStepMetadata(metadata: Record | undefined, formValues: Record): Record { - const committedValues = this.formValues; - this.formValues = formValues; - try { - return Object.fromEntries(Object.entries(metadata ?? {}) - .map(([key, value]) => [this.resolveVariables(key), this.resolveVariables(String(value ?? ''))])); - } finally { - this.formValues = committedValues; - } - } /** Update: the form values the installed version was installed with. */ private previousFormValues(): Record { 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 index 6af1073b93..68aeb0f832 100644 --- 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 @@ -7,6 +7,9 @@ import { IntegrationType } from '@shared/models/integration.models'; import { ScriptLanguage } from '@shared/models/rule-node.models'; import { isEqual } from '@core/utils'; import { DeviceInstalledItemDescriptor, 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'; const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json'; @@ -58,9 +61,24 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert }; /** - * True when the device package installed the converter itself as its default converter, not one it took as it was: - * only such a converter is ThingsBoard's default one, which a new ThingsBoard version may change. + * 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 isOwnDefaultConverter = (item: IotHubInstalledItem, converterId: string): boolean => - item.itemType === 'DEVICE' && Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) - .some(state => state?.defaultConverter && state.entityOutput?.id === converterId && state.resolution !== 'use-existing'); +export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise> => { + const ids = new Set(); + let pageLink = new PageLink(100); + let page: PageData; + do { + page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); + for (const item of page.data) { + 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); + } + } + } + pageLink = pageLink.nextPageLink(); + } while (page.hasNext); + return ids; +}; diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index d4cf0d4df0..a99fc65a66 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -38,7 +38,7 @@ import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/ import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { ConverterService } from '@core/http/converter.service'; import { ResourcesService } from '@core/services/resources.service'; -import { differsFromDefaultConverter, isOwnDefaultConverter, loadDefaultUplinkConverter } from '@home/components/iot-hub/iot-hub-default-converter'; +import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; import { firstValueFrom } from 'rxjs'; @Component({ @@ -278,13 +278,18 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, */ private async checkConverterUpdates(): Promise { const updates = new Set(); + // Over all installed packages, not only this page's, as the update dialog decides + let ownDefaultConverterIds: Set | undefined; for (const item of this.dataSource) { const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; for (const state of states) { let id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; // A converter taken as it was counts only when a package installed it as its default converter - if (id && state.resolution === 'use-existing' && !this.dataSource.some(other => isOwnDefaultConverter(other, id))) { - id = undefined; + if (id && state.resolution === 'use-existing') { + ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService); + if (!ownDefaultConverterIds.has(id)) { + id = undefined; + } } const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) .catch(() => null) : null; diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index eb4776d107..882c97f9c5 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -64,6 +64,8 @@ export interface DeviceUpdateStep { resolution?: string; // The package step's id, which keys its install state; the name when not set id?: string; + // INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry + metadata?: Record; // The step takes ThingsBoard's default converter: its install state says so, for the update check defaultConverter?: boolean; } From de40a36f125de4600887274018e31f8f8c589e71 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:53:41 +0200 Subject: [PATCH 32/66] fix(iot-hub): a kept integration gets the step's metadata, one default converter lookup, uninstall keeps use-existing entities --- .../service/iot_hub/DefaultIotHubService.java | 34 ++++++++++++++--- .../iot_hub/InstalledItemKeptEntities.java | 4 +- ...DefaultDevicePackageUpdateServiceTest.java | 2 +- .../iot_hub/DefaultIotHubServiceTest.java | 37 +++++++++++++++++++ .../iot-hub-delete-dialog.component.ts | 6 ++- .../iot-hub/iot-hub-installed-item.models.ts | 2 + .../assets/locale/locale.constant-en_US.json | 2 + 7 files changed, 78 insertions(+), 9 deletions(-) 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 dcc569b481..6968cbd00f 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 @@ -713,17 +713,24 @@ public class DefaultIotHubService implements IotHubService { /** * 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. + * 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). */ private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, - List createdEntityIds, SecurityUser user) { + DeviceInstalledItemDescriptor descriptor, SecurityUser user) { + List createdEntityIds = descriptor.getCreatedEntityIds(); if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; } + Set usedExisting = usedExistingIds(descriptor); Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); 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()); + continue; + } Set usedBy = usedByOtherPackages.get(entityId.getId()); if (usedBy != null) { log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); @@ -746,17 +753,34 @@ public class DefaultIotHubService implements IotHubService { } 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); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); - if (usedBy != null) { + 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()); + 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; } private Map> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -854,7 +878,7 @@ public class DefaultIotHubService implements IotHubService { } } } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { - deleteDevicePackageEntities(tenantId, installedItemId, 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/InstalledItemKeptEntities.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java index 021cfe5be5..ad517c5327 100644 --- 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 @@ -9,7 +9,7 @@ import org.thingsboard.server.common.data.id.EntityId; import java.util.List; -/** What deleting an installed item keeps, because other installed items use it too. */ +/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ @Data @NoArgsConstructor @AllArgsConstructor @@ -18,6 +18,8 @@ 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 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 index 76bad73451..316732253c 100644 --- 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 @@ -308,7 +308,7 @@ class DefaultDevicePackageUpdateServiceTest { 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)); + 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)); 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 8cc1848797..938c816ed7 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 @@ -481,6 +481,43 @@ class DefaultIotHubServiceTest { 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())); 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 81d13800d3..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 @@ -45,8 +45,10 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent ({ id: entity.entityId as EntityId, name: entity.name })); - this.description = this.translate.instant('iot-hub.remove-desc-kept', - { count: kept.usedByItemsCount, kept: kept.entities.length }); + // 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'); } diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index 882c97f9c5..2ca0603a37 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -166,6 +166,8 @@ export interface IotHubKeptEntity { export interface IotHubInstalledItemKeptEntities { entities: IotHubKeptEntity[]; usedByItemsCount: number; + // Of the kept entities, the ones the user had before and the package took as they were + usedExistingCount: number; } export interface IotHubInstalledItem extends BaseData<{id: string}> { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index 68a0906635..ca933a9b36 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6405,6 +6405,8 @@ "remove": "Remove", "remove-confirm-title": "Remove '{{name}}'?", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", + "remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:", + "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity} other {entities} } will not be removed, because you had them before the package was installed or { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } them:", "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From f2d4872688e0a1f91b524885867b3f00603b4e99 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 12:08:30 +0200 Subject: [PATCH 33/66] fix(iot-hub): merge metadata into a copy of the integration, lock the metadata fields on update, plural of the kept text --- .../DefaultDevicePackageUpdateService.java | 30 +++++++++++-------- ...DefaultDevicePackageUpdateServiceTest.java | 3 ++ .../device-install-dialog.component.ts | 20 +++++++++++++ .../assets/locale/locale.constant-en_US.json | 2 +- 4 files changed, 42 insertions(+), 13 deletions(-) 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 index 399e46f6ac..2bbed29280 100644 --- 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 @@ -587,8 +587,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { existing(tenantId, current, step); - if (mergeMetadata(current, step.getMetadata())) { - Integration result = integrationService.saveIntegration(current); + 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); @@ -611,14 +612,18 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); } - /** Merges the step's metadata entries into the integration's; true when that changed it. */ - private static boolean mergeMetadata(Integration integration, JsonNode entries) { + /** + * 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 false; + return null; } - ObjectNode configuration = integration.getConfiguration() != null && integration.getConfiguration().isObject() ? - (ObjectNode) integration.getConfiguration() : JacksonUtil.newObjectNode(); - ObjectNode metadata = configuration.get("metadata") instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode(); + 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()); @@ -626,14 +631,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i metadata.put(entry.getKey(), entry.getValue().asText()); } }); - if (metadata.equals(configuration.get("metadata")) || (metadata.isEmpty() && configuration.get("metadata") == null)) { - return false; + if (metadata.equals(before) || (metadata.isEmpty() && before == null)) { + return null; } configuration.set("metadata", metadata); - integration.setConfiguration(configuration); - return true; + 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. 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 index 316732253c..062eabf80f 100644 --- 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 @@ -392,6 +392,9 @@ class DefaultDevicePackageUpdateServiceTest { 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(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText()) .isEqualTo("use-existing"); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index f049ee97b8..ca92919b5b 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -1247,6 +1247,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent locked.has(field.key) ? { ...field, readOnly: true, resettable: false } : field); } for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); @@ -1862,6 +1866,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const keys = new Set(); + for (const step of this.packageInfo.installSteps[this.selectedInstallMethod] ?? []) { + if (step.type !== InstallStepType.INTEGRATION) { + continue; + } + for (const [key, value] of Object.entries(step.metadata ?? {})) { + for (const match of `${key} ${value ?? ''}`.matchAll(/\$\{([^}.]+)}/g)) { + keys.add(match[1]); + } + } + } + return keys; + } + private integrationMetadataOf(step: DeviceInstallStep): Record | undefined { return step.type === InstallStepType.INTEGRATION && step.metadata ? this.stepMetadataEntries(step) : undefined; } diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index ca933a9b36..598b051e0e 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -6406,7 +6406,7 @@ "remove-confirm-title": "Remove '{{name}}'?", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", "remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:", - "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity} other {entities} } will not be removed, because you had them before the package was installed or { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } them:", + "remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-anyway": "Remove anyway", From 4f0151542fbfb30c9a37df4063293d4ac0bcc027 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 12:33:46 +0200 Subject: [PATCH 34/66] fix(iot-hub): check the update again after any way back, check default converters in parallel and keep the latest run --- .../device-install-dialog.component.ts | 20 ++++++--- ...iot-hub-installed-items-table.component.ts | 41 ++++++++++++------- 2 files changed, 41 insertions(+), 20 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index ca92919b5b..54dfc3e218 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -555,6 +555,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.resetUpdatePlan(ws)); + } return; } // Forward moves can come from the stepper header, which bypasses nextStep(), diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index a99fc65a66..2677ec1cbe 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -74,6 +74,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, publishedVersionMap = new Map(); // Installed device packages whose default converter differs from ThingsBoard's default converter now converterUpdates = new Set(); + private converterCheckRun = 0; updatesChecked = false; isCheckingUpdates = false; @@ -277,35 +278,47 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, * ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it. */ private async checkConverterUpdates(): Promise { - const updates = new Set(); + // A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win + const run = ++this.converterCheckRun; + // The package's default converter of each DEVICE package on the page + const checks: { itemId: string; converterId: string }[] = []; // Over all installed packages, not only this page's, as the update dialog decides let ownDefaultConverterIds: Set | undefined; for (const item of this.dataSource) { const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : []; for (const state of states) { - let id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; + const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined; + if (!id) { + continue; + } // A converter taken as it was counts only when a package installed it as its default converter - if (id && state.resolution === 'use-existing') { + if (state.resolution === 'use-existing') { ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService); if (!ownDefaultConverterIds.has(id)) { - id = undefined; - } - } - const converter = id ? await firstValueFrom(this.converterService.getConverter(id, {ignoreErrors: true, ignoreLoading: true})) - .catch(() => null) : null; - if (converter) { - const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, - converter.configuration.scriptLang, converter.name); - if (defaultConverter && differsFromDefaultConverter(converter, defaultConverter)) { - updates.add(item.id.id); + continue; } } + checks.push({ itemId: item.id.id, converterId: id }); } } - this.converterUpdates = updates; + const changed = await Promise.all(checks.map(async ({ itemId, converterId }) => { + const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true})) + .catch(() => null); + if (!converter) { + return null; + } + const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType, + converter.configuration.scriptLang, converter.name); + return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ? itemId : null; + })); + if (run !== this.converterCheckRun) { + return; + } + this.converterUpdates = new Set(changed.filter(itemId => !!itemId)); this.cd.markForCheck(); } + getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { return this.publishedVersionMap.get(item.itemId); } From af75897c2530f388cf5178b22d7b08c4ba4ff599 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 13:37:39 +0200 Subject: [PATCH 35/66] fix(iot-hub): drop the result of an update check the user went back from --- .../device-install-dialog.component.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 54dfc3e218..9f79cbb59d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -370,6 +370,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent(); // Update: for each step with "default": true, whether its converter differs from ThingsBoard's default one now private defaultConverterChanges = new Map(); + // Update: the check of the update in progress; a way back meanwhile starts a new one, which drops this one's result + private updateCheckRun = 0; // Variable resolution state formValues: Record = {}; @@ -557,7 +559,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + const run = ++this.updateCheckRun; // Templates refer to the package's entities, e.g. ${deviceProfile.id}: until the steps run, the installed ones this.restoreInstallState(this.data.update.descriptor.installState ?? {}, false); ws.entitySteps = ws.rawSteps.map(s => ({ @@ -2600,9 +2608,16 @@ export class TbDeviceInstallDialogComponent extends DialogComponent [state.stepName, state])); const plans = await Promise.all(ws.entitySteps.map(ep => this.planEntityStep(ep))); + if (run !== this.updateCheckRun) { + // The user went back meanwhile: the plan is of the form values before + return; + } ws.entitySteps.forEach((ep, i) => this.entityPlans.set(ep, plans[i])); this.overwriteReferencesToCreated(ws); } catch (e: any) { + if (run !== this.updateCheckRun) { + return; + } ws.progressError = this.failureMessage(e); } ws.checking = false; From 7420039a55962b7f30b81f53bb15d0a8e9654a7b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 11:20:28 +0200 Subject: [PATCH 36/66] feat(iot-hub): the default TTN/TTI converter decodes Lansitec devices from the LoRaWAN Device Repository The Lansitec codecs wrap everything in bytes, give numbers as strings with units and get some fields wrong. The default converter unwraps them, names the keys as the Lansitec datasheets do, decodes the wrong fields from the raw bytes, and writes the Register message as attributes. The JS default reads the payload as UTF-8. --- .../src/assets/converters/js-tti-decoder.raw | 425 +++++++++++++++++- .../src/assets/converters/js-ttn-decoder.raw | 425 +++++++++++++++++- .../assets/converters/tbel-tti-decoder.raw | 378 +++++++++++++++- .../assets/converters/tbel-ttn-decoder.raw | 378 +++++++++++++++- 4 files changed, 1600 insertions(+), 6 deletions(-) diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index ee4314679b..ca1d911e66 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -2,11 +2,428 @@ // 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.-. Any other device gets LoRaWAN Device. + +// Lansitec: the LoRaWAN Device Repository codecs wrap everything in "bytes", write numbers as strings with units +// ("85%", "-67dBm") and get some fields wrong. Key names follow the Lansitec datasheets where there are any: +// Bluetooth Gateway DataSheet 2.27, Badge Tracker DataSheet v5.30, Temperature Humidity Sensor DataSheet 1.26. +// The wrong fields are decoded from the raw bytes (metadata.data). Remove a fix when the Repository fixes the codec. +var LANSITEC_UNITS = ['dBm', 'dB', '%', 'V', 'sec', 'min', 's', '℃', 'level', ' meter']; + +var LANSITEC_GATEWAYS = ['compact-bluetooth-gateway', 'indoor-bluetooth-gateway', 'macro-bluetooth-gateway', 'solar-bluetooth-gateway']; + +// Codec key -> datasheet name, per model group. '-' drops the key. +// +// Bluetooth Gateway DataSheet 2.27, 4.4.1 Registration: ADR, Mode (current working LoRaWAN frequency sub-band plan), +// LoRaWAN frequency band, Power (LoRa TX power, dBm), Continuously BLE receiving, DR (LoRaWAN Uplink Data Rate), +// PRI (Position report interval), HB (Heartbeat interval), Bluetooth receiving duration. +// 4.4.2 Heartbeat: RSSI and SNR (LoRa), VER (Firmware version). VOL, SNR and CHGSTAT come from the raw bytes. +// number is the count of reported devices: the beacons list has them. The beacons come from the raw bytes too. +var LANSITEC_GATEWAY_KEYS = { + adr: 'adr', mode: 'mode', LoRaWANband: 'loraWanFrequencyBand', LoRaTxpower: 'loraTxPower', + ContinuousReceive: 'continuousBleReceiving', dr: 'dataRate', pos: 'positionReportInterval', + hb: 'heartbeatInterval', BLEReceivingDuration: 'bluetoothReceivingDuration', + rssi: 'loraRssi', snr: '-', ver: 'deviceFirmwareVersion', vol: '-', chgstate: '-', number: '-' +}; + +// Badge Tracker DataSheet v5.30, 5.1 Registration: ADR, LoRa TX power, DR, GNSSEN (GNSS enable status), +// POSMODE (Positioning report mode), BLEPRI (Bluetooth Position Report Interval). The codec reads it without the +// GNSSPRI field, so heartbeat, version, CFMMSG, HBCOUNT and fall detection come from the raw bytes. +// 5.2 Heartbeat: Battery (percentage), RSSI (LoRa), GNSSSTATE (Status of the GNSS module), CHGSTATE (Status of +// battery charging). SNR and VIBSTATE come from the raw bytes. +// 5.3 GNSS Position: longitude, latitude and time come from the raw bytes. +// 5.4 Beacon: bytes 1-5 are RFU, the codec reads byte 1 as Vibstate. 5.5 Alarm: 0x01 SOS, 0x02 Fall Detection. +var LANSITEC_BADGE_KEYS = { + ADR: 'adr', 'Lora Txpower': 'loraTxPower', DR: 'dataRate', GNSSEN: 'gnssEnabled', + 'Position mode': 'positioningReportMode', 'Position period': 'bluetoothPositionReportInterval', + 'Heartbeat period': '-', 'Firmware version': '-', CFMMSG: '-', HBCOUNT: '-', 'Fall threshold': '-', + 'Battery level': 'batteryLevel', RSSI: 'loraRssi', SNR: '-', 'GPS state': 'gnssState', + 'Move state': '-', 'Charge state': 'chargeState', + Longitude: '-', Latitude: '-', Time: '-', Length: '-', Vibstate: '-', 'Alarm type': 'alarm' +}; + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.1 Register: ADR, MODE (current working scheme), SMODE (data +// scheme supported), POWER (configured transmit power, dBm), DR, REPTIND (report H&T if the value is the same; +// the codec gives "false" for 0 = always report), TH (period of temperature and humidity report), CRC. +// 2.2.2 Periodical temperature and humidity: VER is the version of the message type, not the firmware; +// VOL (battery left, %), RSSI (downlink, detected by the sensor). SNR, temperature and humidity come from the raw bytes. +var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = { + adr: 'adr', mode: 'mode', smode: 'smode', LoraTxpower: 'loraTxPower', dr: 'dataRate', repting: 'reptind', + th: 'temperatureHumidityReportPeriod', crc: '-', + ver: '-', vol: 'batteryLevel', rssi: 'loraRssi', snr: '-', temperature: '-', humidity: '-' +}; + +// Without a datasheet only these keys are renamed: the integration writes rssi, snr and firmwareVersion itself. +// chgstate: the SocketSync gateway has the compact gateway codec byte for byte, which reads CHGSTAT 0x50 as +// "Not charging" (Bluetooth Gateway DataSheet 2.27, 4.4.2), so it is dropped. number is its count of reported +// devices: the beacons list has them. +var LANSITEC_CLASH_KEYS = { + rssi: 'loraRssi', RSSI: 'loraRssi', snr: 'loraSnr', SNR: 'loraSnr', + firmwareVersion: 'deviceFirmwareVersion', 'Firmware version': 'deviceFirmwareVersion', + type: '-', 'Message type': '-', chgstate: '-', number: '-' +}; + +// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi... +var LANSITEC_BEACON_PREFIXES = ['devicetype1', 'devicetype2', 'devicetype3', 'device', 'dev', 'pos', 'asset']; +var LANSITEC_BEACON_FIELDS = ['data', 'major', 'minor', 'rssi', 'id']; + +function lansitecEndsWith(s, end) { + return s.length >= end.length && s.substring(s.length - end.length) == end; +} + +// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes. +function lansitecNumber(v) { + if (typeof v != 'string') { + return v; + } + for (var i = 0; i < LANSITEC_UNITS.length; i++) { + var u = LANSITEC_UNITS[i]; + if (lansitecEndsWith(v, u)) { + var n = v.substring(0, v.length - u.length).trim(); + if (/^-?[0-9]+(\.[0-9]+)?$/.test(n)) { + return u == 'min' ? parseFloat(n) * 60 : parseFloat(n); + } + } + } + return v; +} + +function lansitecLowerStart(part) { + var n = 0; + while (n < part.length && part.charAt(n) != part.charAt(n).toLowerCase()) { + n = n + 1; + } + if (n == part.length) { + return part.toLowerCase(); + } + if (n > 1) { + return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1); + } + return part.substring(0, 1).toLowerCase() + part.substring(1); +} + +function lansitecCamelCase(key) { + var parts = key.split(/[ .]+/); + var result = lansitecLowerStart(parts[0]); + for (var i = 1; i < parts.length; i++) { + var part = lansitecLowerStart(parts[i]); + result = result + part.substring(0, 1).toUpperCase() + part.substring(1); + } + return result; +} + +function lansitecBeaconKey(key) { + var k = key.toLowerCase().replace('.', ''); + for (var i = 0; i < LANSITEC_BEACON_PREFIXES.length; i++) { + var p = LANSITEC_BEACON_PREFIXES[i]; + if (k.indexOf(p) == 0) { + var rest = k.substring(p.length); + for (var j = 0; j < LANSITEC_BEACON_FIELDS.length; j++) { + var f = LANSITEC_BEACON_FIELDS[j]; + if (lansitecEndsWith(rest, f) && /^[0-9]+$/.test(rest.substring(0, rest.length - f.length))) { + return { group: p, index: rest.substring(0, rest.length - f.length), field: f }; + } + if (rest.indexOf(f) == 0 && /^[0-9]+$/.test(rest.substring(f.length))) { + return { group: p, index: rest.substring(f.length), field: f }; + } + } + } + } + return null; +} + +function lansitecKeyTable(model) { + if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { + return LANSITEC_GATEWAY_KEYS; + } + if (model == 'badge-tracker') { + return LANSITEC_BADGE_KEYS; + } + if (model == 'temperature-humidity-sensor') { + return LANSITEC_TEMPERATURE_HUMIDITY_KEYS; + } + return null; +} + +function lansitecValues(raw, model) { + var table = lansitecKeyTable(model); + var values = {}; + var beacons = {}; + Object.keys(raw).forEach(function (key) { + var value = raw[key]; + var b = lansitecBeaconKey(key); + if (b != null) { + var id = b.group + b.index; + if (beacons[id] == null) { + beacons[id] = { order: parseInt(b.index, 10) }; + } + if (b.field == 'rssi') { + beacons[id].rssi = lansitecNumber(value); + } else if (b.field == 'data' || b.field == 'major' || b.field == 'minor') { + beacons[id][b.field] = value; + } + } else if (table == null && key == 'time' && typeof value == 'string') { + // Container tracker and helmet sensor, no datasheet: their codecs add 8 hours to the GNSS time and wrap + // it in quotes, as the badge tracker codec does with the UTC time of DataSheet v5.30, 5.3. + values.gnssTime = new Date(value.replace(/"/g, '')).getTime() - 8 * 60 * 60 * 1000; + } else if (table != null && table.hasOwnProperty(key)) { + if (table[key] != '-') { + values[table[key]] = lansitecNumber(value); + } + } else if (LANSITEC_CLASH_KEYS.hasOwnProperty(key)) { + if (LANSITEC_CLASH_KEYS[key] != '-') { + values[LANSITEC_CLASH_KEYS[key]] = lansitecNumber(value); + } + } else { + values[lansitecCamelCase(key)] = lansitecNumber(value); + } + }); + if (Object.keys(beacons).length > 0) { + values.beacons = lansitecBeaconList(beacons); + } + return values; +} + +function lansitecBeaconList(beacons) { + var list = []; + var ids = Object.keys(beacons); + for (var i = 1; i <= ids.length; i++) { + ids.forEach(function (id) { + var b = beacons[id]; + if (b.order == i) { + var item = {}; + if (b.data != null) { + item.data = b.data; + } + if (b.major != null) { + item.major = b.major; + item.minor = b.minor; + } + item.rssi = b.rssi; + list.push(item); + } + }); + } + // The gateway codec reads the data of every device after the first at a 5-byte step, so it is right only + // for 4-byte data (DataSheet 4.4.4 examples): with longer data only the first device is kept. The gateways + // with a datasheet get their beacons from the raw bytes instead; this is for the SocketSync gateway. + if (list.length > 1 && list[0].data != null && list[0].data.length != 8) { + return [list[0]]; + } + return list; +} + +// Decoded from the raw bytes by the datasheet where the codec gets it wrong. +function lansitecRawValues(values, b, model) { + var type = (b[0] >> 4) & 0x0F; + if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { + lansitecGatewayRawValues(values, b, model, type); + } else if (model == 'badge-tracker') { + lansitecBadgeRawValues(values, b, type); + } else if (model == 'temperature-humidity-sensor' && type == 2) { + lansitecTemperatureHumidityRawValues(values, b); + } +} + +function lansitecBase64ToBytes(input) { + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var bytes = []; + var bits = 0; + var count = 0; + for (var i = 0; i < input.length; i++) { + var c = chars.indexOf(input.charAt(i)); + if (c < 0) { + continue; + } + bits = (bits << 6) | c; + count = count + 6; + if (count >= 8) { + count = count - 8; + bytes.push((bits >> count) & 0xFF); + } + } + return bytes; +} + +function lansitecHex(b, from, to) { + var digits = '0123456789ABCDEF'; + var hex = ''; + for (var i = from; i < to; i++) { + hex = hex + digits.charAt((b[i] >> 4) & 0x0F) + digits.charAt(b[i] & 0x0F); + } + return hex; +} + +function lansitecUint(b, offset, length) { + var v = 0; + for (var i = 0; i < length; i++) { + v = v * 256 + b[offset + i]; + } + return v; +} + +// IEEE 754 single precision, big-endian, rounded to 6 decimals (about 0.1 m) as in the TBEL converter. +function lansitecFloat(b, offset) { + var bits = lansitecUint(b, offset, 4); + var exponent = Math.floor(bits / 8388608) % 256; + var mantissa = bits % 8388608; + var value = exponent == 0 ? mantissa * Math.pow(2, -149) : (1 + mantissa / 8388608) * Math.pow(2, exponent - 127); + value = Math.round(value * 1000000) / 1000000; + return bits >= 2147483648 ? -value : value; +} + +// SNR, unit 0.01 dB, -3000 to 3000: signed. The codecs read it unsigned. +function lansitecSnr(b, offset) { + var v = lansitecUint(b, offset, 2); + if (v > 32767) { + v = v - 65536; + } + return v / 100; +} + +// Bluetooth Gateway DataSheet 2.27. +function lansitecGatewayRawValues(values, b, model, type) { + if (type == 1 && b.length >= 9) { + // 4.4.1: Network reconnection interval, unit 5 minutes. The codec does not decode it. + values.networkReconnectionInterval = b[8] * 300; + } else if (type == 2 && b.length >= 8) { + // 4.4.2: VOL is the battery voltage (VOL x 0.01 + 1.5 V) on the macro gateway and the battery level (%) on + // the others. The codec decides by the value (<= 100 is %), not by the model. + if (model == 'macro-bluetooth-gateway') { + values.batteryVoltage = (b[1] + 150) / 100; + } else { + values.batteryLevel = b[1]; + } + values.loraSnr = lansitecSnr(b, 3); + // CHGSTAT: 0x00 Not charging, 0x50 Charging, 0x60 Charging completed on the compact and solar gateway, + // always 0x00 on the macro and indoor gateway. The codec reads the low half of the byte. + if (model == 'compact-bluetooth-gateway' || model == 'solar-bluetooth-gateway') { + if (b[7] == 0x00) { + values.chargeState = 'Not charging'; + } else if (b[7] == 0x50) { + values.chargeState = 'Charging'; + } else if (b[7] == 0x60) { + values.chargeState = 'Charging completed'; + } + } + } else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) { + delete values.beacons; + var beacons = lansitecGatewayBeacons(b, type); + if (beacons != null) { + values.beacons = beacons; + } + } +} + +// 4.4.4-4.4.6: Device Type 1, 2 and 3 messages: Type (bits 3-0: number of devices), then Data (1-31 bytes) and +// RSSI (value - 256, dBm) of each device. Data length is not in the message: it is set by the device report rule +// of the type (4.4.3), so all devices of one message have the same length. The codec reads every device after +// the first at a 5-byte step. +// 4.4.7: Multi-Device Type message: Device Type ID before the data of each device. The data length can differ per +// type, and the message does not say it: decoded only when all devices fit the same length. +function lansitecGatewayBeacons(b, type) { + var count = b[0] & 0x0F; + if (count == 0 || (b.length - 1) % count != 0) { + return null; + } + var step = (b.length - 1) / count; + var head = type == 0xE ? 1 : 0; + var dataLength = step - head - 1; + if (dataLength < 1) { + return null; + } + var list = []; + for (var i = 0; i < count; i++) { + var start = 1 + i * step; + var deviceType = type - 7; + if (type == 0xE) { + deviceType = b[start]; + if (deviceType < 1 || deviceType > 3) { + return null; + } + } + list.push({ + deviceType: deviceType, + data: lansitecHex(b, start + head, start + head + dataLength), + rssi: b[start + step - 1] - 256 + }); + } + return list; +} + +// Badge Tracker DataSheet v5.30. +function lansitecBadgeRawValues(values, b, type) { + if (type == 1 && b.length == 14) { + // 5.1, 14 bytes: Type, SMODE, Power, Config, BLEPRI (2), GNSSPRI (2), Heartbeat, Version (2), CFMMSG, HBCOUNT, Fall. + // BLEEN (Config bit 0) is not decoded: the field table says BLE enable status and that GNSSEN or BLEEN must + // be enabled, but the example (Config 32) has both 0 and calls bit 0 reserved. + values.gnssPositionReportInterval = lansitecUint(b, 6, 2) * 5; + values.heartbeatInterval = b[8] * 30; + // Version 0x0525 is V5.25. + var major = lansitecHex(b, 9, 10); + if (major.charAt(0) == '0') { + major = major.substring(1); + } + values.deviceFirmwareVersion = 'V' + major + '.' + lansitecHex(b, 10, 11); + values.cfmmsg = b[11]; + values.hbcount = b[12]; + // Fall detection threshold, unit 0.5 m, 0 means off. + values.fallDetectionThreshold = b[13] * 0.5; + } else if (type == 2 && b.length >= 6) { + // 5.2: the SNR field is there since firmware 0x0501. The SNREN bit (Type bits 3-0) is not used: the + // datasheet example 20 64 3E 033E 00 60 00 has SNREN 0 and the SNR 8.3 dB. + values.loraSnr = lansitecSnr(b, 3); + // VIBSTATE: moving state 0-9, 0 means no moving, 9 high acceleration. The codec turns only 0 and 1 into text. + values.movingState = b[5] & 0x0F; + } else if (type == 3 && b.length >= 13) { + // 5.3: Flag (Type bits 3-0) 0x1 means GNSS positioning failed. Longitude and latitude are IEEE 754 floats + // (the codec divides the mantissa by 0x7fffff instead of 2^23), time is UTC seconds (the codec adds 8 hours). + if ((b[0] & 0x0F) == 0) { + values.longitude = lansitecFloat(b, 1); + values.latitude = lansitecFloat(b, 5); + values.gnssTime = lansitecUint(b, 9, 4) * 1000; + } + } +} + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.2: VER (Type bits 3-0) 1 means the SNR field is there, 0 means +// it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. +// TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. +function lansitecTemperatureHumidityRawValues(values, b) { + var offset = 3; + if ((b[0] & 0x0F) == 1) { + values.loraSnr = lansitecSnr(b, 3); + offset = 5; + } + if (b.length < offset + 3) { + return; + } + var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100; + if ((b[offset] & 0x80) != 0) { + temperature = -temperature; + } + values.temperature = Math.round(temperature * 100) / 100; + values.humidity = b[offset + 2]; +} + var values = {}; +var attributes = {}; var history = []; if (metadata.payloadFormat == 'JSON') { values = decodeToJson(payload); - if (Array.isArray(values.history)) { + if (metadata.brandId == 'lansitec' && values.bytes != null) { + // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. + var raw = values.bytes; + values = lansitecValues(raw, metadata.modelId); + if (metadata.data != null) { + lansitecRawValues(values, lansitecBase64ToBytes(metadata.data), metadata.modelId); + } + // Register is sent after join and holds the device settings: they are attributes, not telemetry. + var messageType = raw.type != null ? raw.type : raw['Message type']; + if (messageType == 'Register') { + attributes = values; + values = {}; + } + } else if (Array.isArray(values.history)) { values.history.forEach(function (record) { if (record.timestamp != null) { var ts = record.timestamp * 1000; @@ -26,12 +443,16 @@ if (metadata.brandId != null && metadata.modelId != null) { profile = customProfile; } } +if (Object.keys(attributes).length > 0) { + return { profile: profile, attributes: attributes }; +} if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } history.push({ ts: metadata.ts, values: values }); return { profile: profile, telemetry: history }; +// The payload is UTF-8: a codec value can have a unit like ℃. function decodeToJson(payload) { - return JSON.parse(String.fromCharCode.apply(String, payload)); + return JSON.parse(decodeURIComponent(escape(String.fromCharCode.apply(String, payload)))); } diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index ee4314679b..ca1d911e66 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -2,11 +2,428 @@ // 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.-. Any other device gets LoRaWAN Device. + +// Lansitec: the LoRaWAN Device Repository codecs wrap everything in "bytes", write numbers as strings with units +// ("85%", "-67dBm") and get some fields wrong. Key names follow the Lansitec datasheets where there are any: +// Bluetooth Gateway DataSheet 2.27, Badge Tracker DataSheet v5.30, Temperature Humidity Sensor DataSheet 1.26. +// The wrong fields are decoded from the raw bytes (metadata.data). Remove a fix when the Repository fixes the codec. +var LANSITEC_UNITS = ['dBm', 'dB', '%', 'V', 'sec', 'min', 's', '℃', 'level', ' meter']; + +var LANSITEC_GATEWAYS = ['compact-bluetooth-gateway', 'indoor-bluetooth-gateway', 'macro-bluetooth-gateway', 'solar-bluetooth-gateway']; + +// Codec key -> datasheet name, per model group. '-' drops the key. +// +// Bluetooth Gateway DataSheet 2.27, 4.4.1 Registration: ADR, Mode (current working LoRaWAN frequency sub-band plan), +// LoRaWAN frequency band, Power (LoRa TX power, dBm), Continuously BLE receiving, DR (LoRaWAN Uplink Data Rate), +// PRI (Position report interval), HB (Heartbeat interval), Bluetooth receiving duration. +// 4.4.2 Heartbeat: RSSI and SNR (LoRa), VER (Firmware version). VOL, SNR and CHGSTAT come from the raw bytes. +// number is the count of reported devices: the beacons list has them. The beacons come from the raw bytes too. +var LANSITEC_GATEWAY_KEYS = { + adr: 'adr', mode: 'mode', LoRaWANband: 'loraWanFrequencyBand', LoRaTxpower: 'loraTxPower', + ContinuousReceive: 'continuousBleReceiving', dr: 'dataRate', pos: 'positionReportInterval', + hb: 'heartbeatInterval', BLEReceivingDuration: 'bluetoothReceivingDuration', + rssi: 'loraRssi', snr: '-', ver: 'deviceFirmwareVersion', vol: '-', chgstate: '-', number: '-' +}; + +// Badge Tracker DataSheet v5.30, 5.1 Registration: ADR, LoRa TX power, DR, GNSSEN (GNSS enable status), +// POSMODE (Positioning report mode), BLEPRI (Bluetooth Position Report Interval). The codec reads it without the +// GNSSPRI field, so heartbeat, version, CFMMSG, HBCOUNT and fall detection come from the raw bytes. +// 5.2 Heartbeat: Battery (percentage), RSSI (LoRa), GNSSSTATE (Status of the GNSS module), CHGSTATE (Status of +// battery charging). SNR and VIBSTATE come from the raw bytes. +// 5.3 GNSS Position: longitude, latitude and time come from the raw bytes. +// 5.4 Beacon: bytes 1-5 are RFU, the codec reads byte 1 as Vibstate. 5.5 Alarm: 0x01 SOS, 0x02 Fall Detection. +var LANSITEC_BADGE_KEYS = { + ADR: 'adr', 'Lora Txpower': 'loraTxPower', DR: 'dataRate', GNSSEN: 'gnssEnabled', + 'Position mode': 'positioningReportMode', 'Position period': 'bluetoothPositionReportInterval', + 'Heartbeat period': '-', 'Firmware version': '-', CFMMSG: '-', HBCOUNT: '-', 'Fall threshold': '-', + 'Battery level': 'batteryLevel', RSSI: 'loraRssi', SNR: '-', 'GPS state': 'gnssState', + 'Move state': '-', 'Charge state': 'chargeState', + Longitude: '-', Latitude: '-', Time: '-', Length: '-', Vibstate: '-', 'Alarm type': 'alarm' +}; + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.1 Register: ADR, MODE (current working scheme), SMODE (data +// scheme supported), POWER (configured transmit power, dBm), DR, REPTIND (report H&T if the value is the same; +// the codec gives "false" for 0 = always report), TH (period of temperature and humidity report), CRC. +// 2.2.2 Periodical temperature and humidity: VER is the version of the message type, not the firmware; +// VOL (battery left, %), RSSI (downlink, detected by the sensor). SNR, temperature and humidity come from the raw bytes. +var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = { + adr: 'adr', mode: 'mode', smode: 'smode', LoraTxpower: 'loraTxPower', dr: 'dataRate', repting: 'reptind', + th: 'temperatureHumidityReportPeriod', crc: '-', + ver: '-', vol: 'batteryLevel', rssi: 'loraRssi', snr: '-', temperature: '-', humidity: '-' +}; + +// Without a datasheet only these keys are renamed: the integration writes rssi, snr and firmwareVersion itself. +// chgstate: the SocketSync gateway has the compact gateway codec byte for byte, which reads CHGSTAT 0x50 as +// "Not charging" (Bluetooth Gateway DataSheet 2.27, 4.4.2), so it is dropped. number is its count of reported +// devices: the beacons list has them. +var LANSITEC_CLASH_KEYS = { + rssi: 'loraRssi', RSSI: 'loraRssi', snr: 'loraSnr', SNR: 'loraSnr', + firmwareVersion: 'deviceFirmwareVersion', 'Firmware version': 'deviceFirmwareVersion', + type: '-', 'Message type': '-', chgstate: '-', number: '-' +}; + +// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi... +var LANSITEC_BEACON_PREFIXES = ['devicetype1', 'devicetype2', 'devicetype3', 'device', 'dev', 'pos', 'asset']; +var LANSITEC_BEACON_FIELDS = ['data', 'major', 'minor', 'rssi', 'id']; + +function lansitecEndsWith(s, end) { + return s.length >= end.length && s.substring(s.length - end.length) == end; +} + +// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes. +function lansitecNumber(v) { + if (typeof v != 'string') { + return v; + } + for (var i = 0; i < LANSITEC_UNITS.length; i++) { + var u = LANSITEC_UNITS[i]; + if (lansitecEndsWith(v, u)) { + var n = v.substring(0, v.length - u.length).trim(); + if (/^-?[0-9]+(\.[0-9]+)?$/.test(n)) { + return u == 'min' ? parseFloat(n) * 60 : parseFloat(n); + } + } + } + return v; +} + +function lansitecLowerStart(part) { + var n = 0; + while (n < part.length && part.charAt(n) != part.charAt(n).toLowerCase()) { + n = n + 1; + } + if (n == part.length) { + return part.toLowerCase(); + } + if (n > 1) { + return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1); + } + return part.substring(0, 1).toLowerCase() + part.substring(1); +} + +function lansitecCamelCase(key) { + var parts = key.split(/[ .]+/); + var result = lansitecLowerStart(parts[0]); + for (var i = 1; i < parts.length; i++) { + var part = lansitecLowerStart(parts[i]); + result = result + part.substring(0, 1).toUpperCase() + part.substring(1); + } + return result; +} + +function lansitecBeaconKey(key) { + var k = key.toLowerCase().replace('.', ''); + for (var i = 0; i < LANSITEC_BEACON_PREFIXES.length; i++) { + var p = LANSITEC_BEACON_PREFIXES[i]; + if (k.indexOf(p) == 0) { + var rest = k.substring(p.length); + for (var j = 0; j < LANSITEC_BEACON_FIELDS.length; j++) { + var f = LANSITEC_BEACON_FIELDS[j]; + if (lansitecEndsWith(rest, f) && /^[0-9]+$/.test(rest.substring(0, rest.length - f.length))) { + return { group: p, index: rest.substring(0, rest.length - f.length), field: f }; + } + if (rest.indexOf(f) == 0 && /^[0-9]+$/.test(rest.substring(f.length))) { + return { group: p, index: rest.substring(f.length), field: f }; + } + } + } + } + return null; +} + +function lansitecKeyTable(model) { + if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { + return LANSITEC_GATEWAY_KEYS; + } + if (model == 'badge-tracker') { + return LANSITEC_BADGE_KEYS; + } + if (model == 'temperature-humidity-sensor') { + return LANSITEC_TEMPERATURE_HUMIDITY_KEYS; + } + return null; +} + +function lansitecValues(raw, model) { + var table = lansitecKeyTable(model); + var values = {}; + var beacons = {}; + Object.keys(raw).forEach(function (key) { + var value = raw[key]; + var b = lansitecBeaconKey(key); + if (b != null) { + var id = b.group + b.index; + if (beacons[id] == null) { + beacons[id] = { order: parseInt(b.index, 10) }; + } + if (b.field == 'rssi') { + beacons[id].rssi = lansitecNumber(value); + } else if (b.field == 'data' || b.field == 'major' || b.field == 'minor') { + beacons[id][b.field] = value; + } + } else if (table == null && key == 'time' && typeof value == 'string') { + // Container tracker and helmet sensor, no datasheet: their codecs add 8 hours to the GNSS time and wrap + // it in quotes, as the badge tracker codec does with the UTC time of DataSheet v5.30, 5.3. + values.gnssTime = new Date(value.replace(/"/g, '')).getTime() - 8 * 60 * 60 * 1000; + } else if (table != null && table.hasOwnProperty(key)) { + if (table[key] != '-') { + values[table[key]] = lansitecNumber(value); + } + } else if (LANSITEC_CLASH_KEYS.hasOwnProperty(key)) { + if (LANSITEC_CLASH_KEYS[key] != '-') { + values[LANSITEC_CLASH_KEYS[key]] = lansitecNumber(value); + } + } else { + values[lansitecCamelCase(key)] = lansitecNumber(value); + } + }); + if (Object.keys(beacons).length > 0) { + values.beacons = lansitecBeaconList(beacons); + } + return values; +} + +function lansitecBeaconList(beacons) { + var list = []; + var ids = Object.keys(beacons); + for (var i = 1; i <= ids.length; i++) { + ids.forEach(function (id) { + var b = beacons[id]; + if (b.order == i) { + var item = {}; + if (b.data != null) { + item.data = b.data; + } + if (b.major != null) { + item.major = b.major; + item.minor = b.minor; + } + item.rssi = b.rssi; + list.push(item); + } + }); + } + // The gateway codec reads the data of every device after the first at a 5-byte step, so it is right only + // for 4-byte data (DataSheet 4.4.4 examples): with longer data only the first device is kept. The gateways + // with a datasheet get their beacons from the raw bytes instead; this is for the SocketSync gateway. + if (list.length > 1 && list[0].data != null && list[0].data.length != 8) { + return [list[0]]; + } + return list; +} + +// Decoded from the raw bytes by the datasheet where the codec gets it wrong. +function lansitecRawValues(values, b, model) { + var type = (b[0] >> 4) & 0x0F; + if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { + lansitecGatewayRawValues(values, b, model, type); + } else if (model == 'badge-tracker') { + lansitecBadgeRawValues(values, b, type); + } else if (model == 'temperature-humidity-sensor' && type == 2) { + lansitecTemperatureHumidityRawValues(values, b); + } +} + +function lansitecBase64ToBytes(input) { + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var bytes = []; + var bits = 0; + var count = 0; + for (var i = 0; i < input.length; i++) { + var c = chars.indexOf(input.charAt(i)); + if (c < 0) { + continue; + } + bits = (bits << 6) | c; + count = count + 6; + if (count >= 8) { + count = count - 8; + bytes.push((bits >> count) & 0xFF); + } + } + return bytes; +} + +function lansitecHex(b, from, to) { + var digits = '0123456789ABCDEF'; + var hex = ''; + for (var i = from; i < to; i++) { + hex = hex + digits.charAt((b[i] >> 4) & 0x0F) + digits.charAt(b[i] & 0x0F); + } + return hex; +} + +function lansitecUint(b, offset, length) { + var v = 0; + for (var i = 0; i < length; i++) { + v = v * 256 + b[offset + i]; + } + return v; +} + +// IEEE 754 single precision, big-endian, rounded to 6 decimals (about 0.1 m) as in the TBEL converter. +function lansitecFloat(b, offset) { + var bits = lansitecUint(b, offset, 4); + var exponent = Math.floor(bits / 8388608) % 256; + var mantissa = bits % 8388608; + var value = exponent == 0 ? mantissa * Math.pow(2, -149) : (1 + mantissa / 8388608) * Math.pow(2, exponent - 127); + value = Math.round(value * 1000000) / 1000000; + return bits >= 2147483648 ? -value : value; +} + +// SNR, unit 0.01 dB, -3000 to 3000: signed. The codecs read it unsigned. +function lansitecSnr(b, offset) { + var v = lansitecUint(b, offset, 2); + if (v > 32767) { + v = v - 65536; + } + return v / 100; +} + +// Bluetooth Gateway DataSheet 2.27. +function lansitecGatewayRawValues(values, b, model, type) { + if (type == 1 && b.length >= 9) { + // 4.4.1: Network reconnection interval, unit 5 minutes. The codec does not decode it. + values.networkReconnectionInterval = b[8] * 300; + } else if (type == 2 && b.length >= 8) { + // 4.4.2: VOL is the battery voltage (VOL x 0.01 + 1.5 V) on the macro gateway and the battery level (%) on + // the others. The codec decides by the value (<= 100 is %), not by the model. + if (model == 'macro-bluetooth-gateway') { + values.batteryVoltage = (b[1] + 150) / 100; + } else { + values.batteryLevel = b[1]; + } + values.loraSnr = lansitecSnr(b, 3); + // CHGSTAT: 0x00 Not charging, 0x50 Charging, 0x60 Charging completed on the compact and solar gateway, + // always 0x00 on the macro and indoor gateway. The codec reads the low half of the byte. + if (model == 'compact-bluetooth-gateway' || model == 'solar-bluetooth-gateway') { + if (b[7] == 0x00) { + values.chargeState = 'Not charging'; + } else if (b[7] == 0x50) { + values.chargeState = 'Charging'; + } else if (b[7] == 0x60) { + values.chargeState = 'Charging completed'; + } + } + } else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) { + delete values.beacons; + var beacons = lansitecGatewayBeacons(b, type); + if (beacons != null) { + values.beacons = beacons; + } + } +} + +// 4.4.4-4.4.6: Device Type 1, 2 and 3 messages: Type (bits 3-0: number of devices), then Data (1-31 bytes) and +// RSSI (value - 256, dBm) of each device. Data length is not in the message: it is set by the device report rule +// of the type (4.4.3), so all devices of one message have the same length. The codec reads every device after +// the first at a 5-byte step. +// 4.4.7: Multi-Device Type message: Device Type ID before the data of each device. The data length can differ per +// type, and the message does not say it: decoded only when all devices fit the same length. +function lansitecGatewayBeacons(b, type) { + var count = b[0] & 0x0F; + if (count == 0 || (b.length - 1) % count != 0) { + return null; + } + var step = (b.length - 1) / count; + var head = type == 0xE ? 1 : 0; + var dataLength = step - head - 1; + if (dataLength < 1) { + return null; + } + var list = []; + for (var i = 0; i < count; i++) { + var start = 1 + i * step; + var deviceType = type - 7; + if (type == 0xE) { + deviceType = b[start]; + if (deviceType < 1 || deviceType > 3) { + return null; + } + } + list.push({ + deviceType: deviceType, + data: lansitecHex(b, start + head, start + head + dataLength), + rssi: b[start + step - 1] - 256 + }); + } + return list; +} + +// Badge Tracker DataSheet v5.30. +function lansitecBadgeRawValues(values, b, type) { + if (type == 1 && b.length == 14) { + // 5.1, 14 bytes: Type, SMODE, Power, Config, BLEPRI (2), GNSSPRI (2), Heartbeat, Version (2), CFMMSG, HBCOUNT, Fall. + // BLEEN (Config bit 0) is not decoded: the field table says BLE enable status and that GNSSEN or BLEEN must + // be enabled, but the example (Config 32) has both 0 and calls bit 0 reserved. + values.gnssPositionReportInterval = lansitecUint(b, 6, 2) * 5; + values.heartbeatInterval = b[8] * 30; + // Version 0x0525 is V5.25. + var major = lansitecHex(b, 9, 10); + if (major.charAt(0) == '0') { + major = major.substring(1); + } + values.deviceFirmwareVersion = 'V' + major + '.' + lansitecHex(b, 10, 11); + values.cfmmsg = b[11]; + values.hbcount = b[12]; + // Fall detection threshold, unit 0.5 m, 0 means off. + values.fallDetectionThreshold = b[13] * 0.5; + } else if (type == 2 && b.length >= 6) { + // 5.2: the SNR field is there since firmware 0x0501. The SNREN bit (Type bits 3-0) is not used: the + // datasheet example 20 64 3E 033E 00 60 00 has SNREN 0 and the SNR 8.3 dB. + values.loraSnr = lansitecSnr(b, 3); + // VIBSTATE: moving state 0-9, 0 means no moving, 9 high acceleration. The codec turns only 0 and 1 into text. + values.movingState = b[5] & 0x0F; + } else if (type == 3 && b.length >= 13) { + // 5.3: Flag (Type bits 3-0) 0x1 means GNSS positioning failed. Longitude and latitude are IEEE 754 floats + // (the codec divides the mantissa by 0x7fffff instead of 2^23), time is UTC seconds (the codec adds 8 hours). + if ((b[0] & 0x0F) == 0) { + values.longitude = lansitecFloat(b, 1); + values.latitude = lansitecFloat(b, 5); + values.gnssTime = lansitecUint(b, 9, 4) * 1000; + } + } +} + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.2: VER (Type bits 3-0) 1 means the SNR field is there, 0 means +// it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. +// TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. +function lansitecTemperatureHumidityRawValues(values, b) { + var offset = 3; + if ((b[0] & 0x0F) == 1) { + values.loraSnr = lansitecSnr(b, 3); + offset = 5; + } + if (b.length < offset + 3) { + return; + } + var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100; + if ((b[offset] & 0x80) != 0) { + temperature = -temperature; + } + values.temperature = Math.round(temperature * 100) / 100; + values.humidity = b[offset + 2]; +} + var values = {}; +var attributes = {}; var history = []; if (metadata.payloadFormat == 'JSON') { values = decodeToJson(payload); - if (Array.isArray(values.history)) { + if (metadata.brandId == 'lansitec' && values.bytes != null) { + // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. + var raw = values.bytes; + values = lansitecValues(raw, metadata.modelId); + if (metadata.data != null) { + lansitecRawValues(values, lansitecBase64ToBytes(metadata.data), metadata.modelId); + } + // Register is sent after join and holds the device settings: they are attributes, not telemetry. + var messageType = raw.type != null ? raw.type : raw['Message type']; + if (messageType == 'Register') { + attributes = values; + values = {}; + } + } else if (Array.isArray(values.history)) { values.history.forEach(function (record) { if (record.timestamp != null) { var ts = record.timestamp * 1000; @@ -26,12 +443,16 @@ if (metadata.brandId != null && metadata.modelId != null) { profile = customProfile; } } +if (Object.keys(attributes).length > 0) { + return { profile: profile, attributes: attributes }; +} if (history.length == 0) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } history.push({ ts: metadata.ts, values: values }); return { profile: profile, telemetry: history }; +// The payload is UTF-8: a codec value can have a unit like ℃. function decodeToJson(payload) { - return JSON.parse(String.fromCharCode.apply(String, payload)); + return JSON.parse(decodeURIComponent(escape(String.fromCharCode.apply(String, payload)))); } diff --git a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 1cfef4546d..2e675de454 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -2,11 +2,384 @@ // 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.-. Any other device gets LoRaWAN Device. + +// Lansitec: the LoRaWAN Device Repository codecs wrap everything in "bytes", write numbers as strings with units +// ("85%", "-67dBm") and get some fields wrong. Key names follow the Lansitec datasheets where there are any: +// Bluetooth Gateway DataSheet 2.27, Badge Tracker DataSheet v5.30, Temperature Humidity Sensor DataSheet 1.26. +// The wrong fields are decoded from the raw bytes (metadata.data). Remove a fix when the Repository fixes the codec. +var LANSITEC_UNITS = ["dBm", "dB", "%", "V", "sec", "min", "s", "℃", "level", " meter"]; + +var LANSITEC_GATEWAYS = ["compact-bluetooth-gateway", "indoor-bluetooth-gateway", "macro-bluetooth-gateway", "solar-bluetooth-gateway"]; + +// Codec key -> datasheet name, per model group. "-" drops the key. +// +// Bluetooth Gateway DataSheet 2.27, 4.4.1 Registration: ADR, Mode (current working LoRaWAN frequency sub-band plan), +// LoRaWAN frequency band, Power (LoRa TX power, dBm), Continuously BLE receiving, DR (LoRaWAN Uplink Data Rate), +// PRI (Position report interval), HB (Heartbeat interval), Bluetooth receiving duration. +// 4.4.2 Heartbeat: RSSI and SNR (LoRa), VER (Firmware version). VOL, SNR and CHGSTAT come from the raw bytes. +// number is the count of reported devices: the beacons list has them. The beacons come from the raw bytes too. +var LANSITEC_GATEWAY_KEYS = { + adr: "adr", mode: "mode", LoRaWANband: "loraWanFrequencyBand", LoRaTxpower: "loraTxPower", + ContinuousReceive: "continuousBleReceiving", dr: "dataRate", pos: "positionReportInterval", + hb: "heartbeatInterval", BLEReceivingDuration: "bluetoothReceivingDuration", + rssi: "loraRssi", snr: "-", ver: "deviceFirmwareVersion", vol: "-", chgstate: "-", number: "-" +}; + +// Badge Tracker DataSheet v5.30, 5.1 Registration: ADR, LoRa TX power, DR, GNSSEN (GNSS enable status), +// POSMODE (Positioning report mode), BLEPRI (Bluetooth Position Report Interval). The codec reads it without the +// GNSSPRI field, so heartbeat, version, CFMMSG, HBCOUNT and fall detection come from the raw bytes. +// 5.2 Heartbeat: Battery (percentage), RSSI (LoRa), GNSSSTATE (Status of the GNSS module), CHGSTATE (Status of +// battery charging). SNR and VIBSTATE come from the raw bytes. +// 5.3 GNSS Position: longitude, latitude and time come from the raw bytes. +// 5.4 Beacon: bytes 1-5 are RFU, the codec reads byte 1 as Vibstate. 5.5 Alarm: 0x01 SOS, 0x02 Fall Detection. +var LANSITEC_BADGE_KEYS = { + ADR: "adr", "Lora Txpower": "loraTxPower", DR: "dataRate", GNSSEN: "gnssEnabled", + "Position mode": "positioningReportMode", "Position period": "bluetoothPositionReportInterval", + "Heartbeat period": "-", "Firmware version": "-", CFMMSG: "-", HBCOUNT: "-", "Fall threshold": "-", + "Battery level": "batteryLevel", RSSI: "loraRssi", SNR: "-", "GPS state": "gnssState", + "Move state": "-", "Charge state": "chargeState", + Longitude: "-", Latitude: "-", Time: "-", Length: "-", Vibstate: "-", "Alarm type": "alarm" +}; + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.1 Register: ADR, MODE (current working scheme), SMODE (data +// scheme supported), POWER (configured transmit power, dBm), DR, REPTIND (report H&T if the value is the same; +// the codec gives "false" for 0 = always report), TH (period of temperature and humidity report), CRC. +// 2.2.2 Periodical temperature and humidity: VER is the version of the message type, not the firmware; +// VOL (battery left, %), RSSI (downlink, detected by the sensor). SNR, temperature and humidity come from the raw bytes. +var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = { + adr: "adr", mode: "mode", smode: "smode", LoraTxpower: "loraTxPower", dr: "dataRate", repting: "reptind", + th: "temperatureHumidityReportPeriod", crc: "-", + ver: "-", vol: "batteryLevel", rssi: "loraRssi", snr: "-", temperature: "-", humidity: "-" +}; + +// Without a datasheet only these keys are renamed: the integration writes rssi, snr and firmwareVersion itself. +// chgstate: the SocketSync gateway has the compact gateway codec byte for byte, which reads CHGSTAT 0x50 as +// "Not charging" (Bluetooth Gateway DataSheet 2.27, 4.4.2), so it is dropped. number is its count of reported +// devices: the beacons list has them. +var LANSITEC_CLASH_KEYS = { + rssi: "loraRssi", RSSI: "loraRssi", snr: "loraSnr", SNR: "loraSnr", + firmwareVersion: "deviceFirmwareVersion", "Firmware version": "deviceFirmwareVersion", + type: "-", "Message type": "-", chgstate: "-", number: "-" +}; + +// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes. +function lansitecNumber(v) { + if (!(v instanceof String)) { + return v; + } + foreach (u : LANSITEC_UNITS) { + if (v.endsWith(u)) { + var n = v.substring(0, v.length() - u.length()).trim(); + if (n.matches("-?[0-9]+(\\.[0-9]+)?")) { + return u == "min" ? parseDouble(n) * 60 : parseDouble(n); + } + } + } + return v; +} + +function lansitecLowerStart(part) { + var n = 0; + while (n < part.length() && part.substring(n, n + 1) != part.substring(n, n + 1).toLowerCase()) { + n = n + 1; + } + if (n == part.length()) { + return part.toLowerCase(); + } + if (n > 1) { + return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1); + } + return part.substring(0, 1).toLowerCase() + part.substring(1); +} + +function lansitecCamelCase(key) { + var parts = key.split("[ .]+"); + var result = lansitecLowerStart(parts[0]); + for (var i = 1; i < parts.length; i++) { + var part = lansitecLowerStart(parts[i]); + result = result + part.substring(0, 1).toUpperCase() + part.substring(1); + } + return result; +} + +// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi... +var LANSITEC_BEACON_PREFIXES = ["devicetype1", "devicetype2", "devicetype3", "device", "dev", "pos", "asset"]; +var LANSITEC_BEACON_FIELDS = ["data", "major", "minor", "rssi", "id"]; + +function lansitecBeaconKey(key) { + var k = key.toLowerCase().replace(".", ""); + foreach (p : LANSITEC_BEACON_PREFIXES) { + if (k.startsWith(p)) { + var rest = k.substring(p.length()); + foreach (f : LANSITEC_BEACON_FIELDS) { + if (rest.endsWith(f) && rest.substring(0, rest.length() - f.length()).matches("[0-9]+")) { + return { group: p, index: rest.substring(0, rest.length() - f.length()), field: f }; + } + if (rest.startsWith(f) && rest.substring(f.length()).matches("[0-9]+")) { + return { group: p, index: rest.substring(f.length()), field: f }; + } + } + } + } + return null; +} + +function lansitecKeyTable(model) { + if (LANSITEC_GATEWAYS.contains(model)) { + return LANSITEC_GATEWAY_KEYS; + } + if (model == "badge-tracker") { + return LANSITEC_BADGE_KEYS; + } + if (model == "temperature-humidity-sensor") { + return LANSITEC_TEMPERATURE_HUMIDITY_KEYS; + } + return null; +} + +function lansitecValues(raw, model) { + var table = lansitecKeyTable(model); + var values = {}; + var beacons = {}; + foreach (key : raw.keySet()) { + var value = raw[key]; + var b = lansitecBeaconKey(key); + if (b != null) { + var id = b.group + b.index; + if (beacons[id] == null) { + beacons[id] = { order: parseInt(b.index) }; + } + if (b.field == "rssi") { + beacons[id].rssi = lansitecNumber(value); + } else if (b.field == "data" || b.field == "major" || b.field == "minor") { + beacons[id][b.field] = value; + } + } else if (table == null && key == "time" && value instanceof String) { + // Container tracker and helmet sensor, no datasheet: their codecs add 8 hours to the GNSS time and wrap + // it in quotes, as the badge tracker codec does with the UTC time of DataSheet v5.30, 5.3. + var gnssDate = new Date(value.replace("\"", "")); + values.gnssTime = gnssDate.getTime() - 8 * 60 * 60 * 1000; + } else if (table != null && table.containsKey(key)) { + var tableName = table[key]; + if (tableName != "-") { + values[tableName] = lansitecNumber(value); + } + } else if (LANSITEC_CLASH_KEYS.containsKey(key)) { + var clashName = LANSITEC_CLASH_KEYS[key]; + if (clashName != "-") { + values[clashName] = lansitecNumber(value); + } + } else { + var codecName = lansitecCamelCase(key); + values[codecName] = lansitecNumber(value); + } + } + if (!beacons.isEmpty()) { + values.beacons = lansitecBeaconList(beacons); + } + return values; +} + +function lansitecBeaconList(beacons) { + var list = []; + for (var i = 1; i <= beacons.size(); i++) { + foreach (id : beacons.keySet()) { + var b = beacons[id]; + if (b.order == i) { + var item = {}; + if (b.data != null) { + item.data = b.data; + } + if (b.major != null) { + item.major = b.major; + item.minor = b.minor; + } + item.rssi = b.rssi; + list.add(item); + } + } + } + // The gateway codec reads the data of every device after the first at a 5-byte step, so it is right only + // for 4-byte data (DataSheet 4.4.4 examples): with longer data only the first device is kept. The gateways + // with a datasheet get their beacons from the raw bytes instead; this is for the SocketSync gateway. + if (list.size() > 1 && list[0].data != null && list[0].data.length() != 8) { + var first = []; + first.add(list[0]); + return first; + } + return list; +} + +// Decoded from the raw bytes by the datasheet where the codec gets it wrong. +function lansitecRawValues(values, b, model) { + var type = (b[0] >> 4) & 0x0F; + if (LANSITEC_GATEWAYS.contains(model)) { + lansitecGatewayRawValues(values, b, model, type); + } else if (model == "badge-tracker") { + lansitecBadgeRawValues(values, b, type); + } else if (model == "temperature-humidity-sensor" && type == 2) { + lansitecTemperatureHumidityRawValues(values, b); + } +} + +// SNR, unit 0.01 dB, -3000 to 3000: signed. The codecs read it unsigned. +function lansitecSnr(b, offset) { + var v = parseBytesToInt(b, offset, 2, true); + if (v > 32767) { + v = v - 65536; + } + return v / 100.0; +} + +// Bluetooth Gateway DataSheet 2.27. +function lansitecGatewayRawValues(values, b, model, type) { + if (type == 1 && b.length >= 9) { + // 4.4.1: Network reconnection interval, unit 5 minutes. The codec does not decode it. + values.networkReconnectionInterval = (b[8] & 0xFF) * 300; + } else if (type == 2 && b.length >= 8) { + // 4.4.2: VOL is the battery voltage (VOL x 0.01 + 1.5 V) on the macro gateway and the battery level (%) on + // the others. The codec decides by the value (<= 100 is %), not by the model. + if (model == "macro-bluetooth-gateway") { + values.batteryVoltage = ((b[1] & 0xFF) + 150) / 100.0; + } else { + values.batteryLevel = b[1] & 0xFF; + } + values.loraSnr = lansitecSnr(b, 3); + // CHGSTAT: 0x00 Not charging, 0x50 Charging, 0x60 Charging completed on the compact and solar gateway, + // always 0x00 on the macro and indoor gateway. The codec reads the low half of the byte. + if (model == "compact-bluetooth-gateway" || model == "solar-bluetooth-gateway") { + var charge = b[7] & 0xFF; + if (charge == 0x00) { + values.chargeState = "Not charging"; + } else if (charge == 0x50) { + values.chargeState = "Charging"; + } else if (charge == 0x60) { + values.chargeState = "Charging completed"; + } + } + } else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) { + values.remove("beacons"); + var beacons = lansitecGatewayBeacons(b, type); + if (beacons != null) { + values.beacons = beacons; + } + } +} + +// 4.4.4-4.4.6: Device Type 1, 2 and 3 messages: Type (bits 3-0: number of devices), then Data (1-31 bytes) and +// RSSI (value - 256, dBm) of each device. Data length is not in the message: it is set by the device report rule +// of the type (4.4.3), so all devices of one message have the same length. The codec reads every device after +// the first at a 5-byte step. +// 4.4.7: Multi-Device Type message: Device Type ID before the data of each device. The data length can differ per +// type, and the message does not say it: decoded only when all devices fit the same length. +function lansitecGatewayBeacons(b, type) { + var count = b[0] & 0x0F; + if (count == 0 || (b.length - 1) % count != 0) { + return null; + } + // TBEL division gives a Double: array indexes need an int. + var step = ((b.length - 1) / count).intValue(); + var head = type == 0xE ? 1 : 0; + var dataLength = step - head - 1; + if (dataLength < 1) { + return null; + } + var hex = bytesToHex(b); + var list = []; + for (var i = 0; i < count; i++) { + var start = 1 + i * step; + var deviceType = type - 7; + if (type == 0xE) { + deviceType = b[start] & 0xFF; + if (deviceType < 1 || deviceType > 3) { + return null; + } + } + var item = {}; + item.deviceType = deviceType; + item.data = hex.substring(2 * (start + head), 2 * (start + head + dataLength)); + item.rssi = (b[start + step - 1] & 0xFF) - 256; + list.add(item); + } + return list; +} + +// Badge Tracker DataSheet v5.30. +function lansitecBadgeRawValues(values, b, type) { + if (type == 1 && b.length == 14) { + // 5.1, 14 bytes: Type, SMODE, Power, Config, BLEPRI (2), GNSSPRI (2), Heartbeat, Version (2), CFMMSG, HBCOUNT, Fall. + // BLEEN (Config bit 0) is not decoded: the field table says BLE enable status and that GNSSEN or BLEEN must + // be enabled, but the example (Config 32) has both 0 and calls bit 0 reserved. + values.gnssPositionReportInterval = parseBytesToInt(b, 6, 2, true) * 5; + values.heartbeatInterval = (b[8] & 0xFF) * 30; + // Version 0x0525 is V5.25. + var version = bytesToHex(b).substring(18, 22); + var major = version.substring(0, 2); + if (major.startsWith("0")) { + major = major.substring(1); + } + values.deviceFirmwareVersion = "V" + major + "." + version.substring(2); + values.cfmmsg = b[11] & 0xFF; + values.hbcount = b[12] & 0xFF; + // Fall detection threshold, unit 0.5 m, 0 means off. + values.fallDetectionThreshold = (b[13] & 0xFF) * 0.5; + } else if (type == 2 && b.length >= 6) { + // 5.2: the SNR field is there since firmware 0x0501. The SNREN bit (Type bits 3-0) is not used: the + // datasheet example 20 64 3E 033E 00 60 00 has SNREN 0 and the SNR 8.3 dB. + values.loraSnr = lansitecSnr(b, 3); + // VIBSTATE: moving state 0-9, 0 means no moving, 9 high acceleration. The codec turns only 0 and 1 into text. + values.movingState = b[5] & 0x0F; + } else if (type == 3 && b.length >= 13) { + // 5.3: Flag (Type bits 3-0) 0x1 means GNSS positioning failed. Longitude and latitude are IEEE 754 floats + // (the codec divides the mantissa by 0x7fffff instead of 2^23), time is UTC seconds (the codec adds 8 hours). + // Rounded to 6 decimals (about 0.1 m), as a double: the float has no more precision. + if ((b[0] & 0x0F) == 0) { + values.longitude = toFixed(parseBytesToFloat(b, 1, 4, true) * 1.0, 6); + values.latitude = toFixed(parseBytesToFloat(b, 5, 4, true) * 1.0, 6); + values.gnssTime = parseBytesToLong(b, 9, 4, true) * 1000; + } + } +} + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.2: VER (Type bits 3-0) 1 means the SNR field is there, 0 means +// it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. +// TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. +function lansitecTemperatureHumidityRawValues(values, b) { + var offset = 3; + if ((b[0] & 0x0F) == 1) { + values.loraSnr = lansitecSnr(b, 3); + offset = 5; + } + if (b.length < offset + 3) { + return; + } + var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0; + if ((b[offset] & 0x80) != 0) { + temperature = -temperature; + } + values.temperature = toFixed(temperature, 2); + values.humidity = b[offset + 2] & 0xFF; +} + var values = {}; +var attributes = {}; var history = []; if (metadata.payloadFormat == "JSON") { values = decodeToJson(payload); - if (values.history instanceof java.util.List) { + if (metadata.brandId == "lansitec" && values.bytes != null) { + // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. + var raw = values.bytes; + values = lansitecValues(raw, metadata.modelId); + if (metadata.data != null) { + lansitecRawValues(values, base64ToBytes(metadata.data), metadata.modelId); + } + // Register is sent after join and holds the device settings: they are attributes, not telemetry. + var messageType = raw.type != null ? raw.type : raw["Message type"]; + if (messageType == "Register") { + attributes = values; + values = {}; + } + } else if (values.history instanceof java.util.List) { foreach (record : values.history) { if (record.timestamp != null) { var ts = record.timestamp * 1000; @@ -26,6 +399,9 @@ if (metadata.brandId != null && metadata.modelId != null) { profile = customProfile; } } +if (!attributes.isEmpty()) { + return { profile: profile, attributes: attributes }; +} if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 1cfef4546d..2e675de454 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -2,11 +2,384 @@ // 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.-. Any other device gets LoRaWAN Device. + +// Lansitec: the LoRaWAN Device Repository codecs wrap everything in "bytes", write numbers as strings with units +// ("85%", "-67dBm") and get some fields wrong. Key names follow the Lansitec datasheets where there are any: +// Bluetooth Gateway DataSheet 2.27, Badge Tracker DataSheet v5.30, Temperature Humidity Sensor DataSheet 1.26. +// The wrong fields are decoded from the raw bytes (metadata.data). Remove a fix when the Repository fixes the codec. +var LANSITEC_UNITS = ["dBm", "dB", "%", "V", "sec", "min", "s", "℃", "level", " meter"]; + +var LANSITEC_GATEWAYS = ["compact-bluetooth-gateway", "indoor-bluetooth-gateway", "macro-bluetooth-gateway", "solar-bluetooth-gateway"]; + +// Codec key -> datasheet name, per model group. "-" drops the key. +// +// Bluetooth Gateway DataSheet 2.27, 4.4.1 Registration: ADR, Mode (current working LoRaWAN frequency sub-band plan), +// LoRaWAN frequency band, Power (LoRa TX power, dBm), Continuously BLE receiving, DR (LoRaWAN Uplink Data Rate), +// PRI (Position report interval), HB (Heartbeat interval), Bluetooth receiving duration. +// 4.4.2 Heartbeat: RSSI and SNR (LoRa), VER (Firmware version). VOL, SNR and CHGSTAT come from the raw bytes. +// number is the count of reported devices: the beacons list has them. The beacons come from the raw bytes too. +var LANSITEC_GATEWAY_KEYS = { + adr: "adr", mode: "mode", LoRaWANband: "loraWanFrequencyBand", LoRaTxpower: "loraTxPower", + ContinuousReceive: "continuousBleReceiving", dr: "dataRate", pos: "positionReportInterval", + hb: "heartbeatInterval", BLEReceivingDuration: "bluetoothReceivingDuration", + rssi: "loraRssi", snr: "-", ver: "deviceFirmwareVersion", vol: "-", chgstate: "-", number: "-" +}; + +// Badge Tracker DataSheet v5.30, 5.1 Registration: ADR, LoRa TX power, DR, GNSSEN (GNSS enable status), +// POSMODE (Positioning report mode), BLEPRI (Bluetooth Position Report Interval). The codec reads it without the +// GNSSPRI field, so heartbeat, version, CFMMSG, HBCOUNT and fall detection come from the raw bytes. +// 5.2 Heartbeat: Battery (percentage), RSSI (LoRa), GNSSSTATE (Status of the GNSS module), CHGSTATE (Status of +// battery charging). SNR and VIBSTATE come from the raw bytes. +// 5.3 GNSS Position: longitude, latitude and time come from the raw bytes. +// 5.4 Beacon: bytes 1-5 are RFU, the codec reads byte 1 as Vibstate. 5.5 Alarm: 0x01 SOS, 0x02 Fall Detection. +var LANSITEC_BADGE_KEYS = { + ADR: "adr", "Lora Txpower": "loraTxPower", DR: "dataRate", GNSSEN: "gnssEnabled", + "Position mode": "positioningReportMode", "Position period": "bluetoothPositionReportInterval", + "Heartbeat period": "-", "Firmware version": "-", CFMMSG: "-", HBCOUNT: "-", "Fall threshold": "-", + "Battery level": "batteryLevel", RSSI: "loraRssi", SNR: "-", "GPS state": "gnssState", + "Move state": "-", "Charge state": "chargeState", + Longitude: "-", Latitude: "-", Time: "-", Length: "-", Vibstate: "-", "Alarm type": "alarm" +}; + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.1 Register: ADR, MODE (current working scheme), SMODE (data +// scheme supported), POWER (configured transmit power, dBm), DR, REPTIND (report H&T if the value is the same; +// the codec gives "false" for 0 = always report), TH (period of temperature and humidity report), CRC. +// 2.2.2 Periodical temperature and humidity: VER is the version of the message type, not the firmware; +// VOL (battery left, %), RSSI (downlink, detected by the sensor). SNR, temperature and humidity come from the raw bytes. +var LANSITEC_TEMPERATURE_HUMIDITY_KEYS = { + adr: "adr", mode: "mode", smode: "smode", LoraTxpower: "loraTxPower", dr: "dataRate", repting: "reptind", + th: "temperatureHumidityReportPeriod", crc: "-", + ver: "-", vol: "batteryLevel", rssi: "loraRssi", snr: "-", temperature: "-", humidity: "-" +}; + +// Without a datasheet only these keys are renamed: the integration writes rssi, snr and firmwareVersion itself. +// chgstate: the SocketSync gateway has the compact gateway codec byte for byte, which reads CHGSTAT 0x50 as +// "Not charging" (Bluetooth Gateway DataSheet 2.27, 4.4.2), so it is dropped. number is its count of reported +// devices: the beacons list has them. +var LANSITEC_CLASH_KEYS = { + rssi: "loraRssi", RSSI: "loraRssi", snr: "loraSnr", SNR: "loraSnr", + firmwareVersion: "deviceFirmwareVersion", "Firmware version": "deviceFirmwareVersion", + type: "-", "Message type": "-", chgstate: "-", number: "-" +}; + +// Strips the unit. Periods become seconds: the codecs give most of them in seconds, a few in minutes. +function lansitecNumber(v) { + if (!(v instanceof String)) { + return v; + } + foreach (u : LANSITEC_UNITS) { + if (v.endsWith(u)) { + var n = v.substring(0, v.length() - u.length()).trim(); + if (n.matches("-?[0-9]+(\\.[0-9]+)?")) { + return u == "min" ? parseDouble(n) * 60 : parseDouble(n); + } + } + } + return v; +} + +function lansitecLowerStart(part) { + var n = 0; + while (n < part.length() && part.substring(n, n + 1) != part.substring(n, n + 1).toLowerCase()) { + n = n + 1; + } + if (n == part.length()) { + return part.toLowerCase(); + } + if (n > 1) { + return part.substring(0, n - 1).toLowerCase() + part.substring(n - 1); + } + return part.substring(0, 1).toLowerCase() + part.substring(1); +} + +function lansitecCamelCase(key) { + var parts = key.split("[ .]+"); + var result = lansitecLowerStart(parts[0]); + for (var i = 1; i < parts.length; i++) { + var part = lansitecLowerStart(parts[i]); + result = result + part.substring(0, 1).toUpperCase() + part.substring(1); + } + return result; +} + +// Beacon keys: Devicetype1data1, Device1data, dev1major, dev1.major, pos1minor, asset1rssi... +var LANSITEC_BEACON_PREFIXES = ["devicetype1", "devicetype2", "devicetype3", "device", "dev", "pos", "asset"]; +var LANSITEC_BEACON_FIELDS = ["data", "major", "minor", "rssi", "id"]; + +function lansitecBeaconKey(key) { + var k = key.toLowerCase().replace(".", ""); + foreach (p : LANSITEC_BEACON_PREFIXES) { + if (k.startsWith(p)) { + var rest = k.substring(p.length()); + foreach (f : LANSITEC_BEACON_FIELDS) { + if (rest.endsWith(f) && rest.substring(0, rest.length() - f.length()).matches("[0-9]+")) { + return { group: p, index: rest.substring(0, rest.length() - f.length()), field: f }; + } + if (rest.startsWith(f) && rest.substring(f.length()).matches("[0-9]+")) { + return { group: p, index: rest.substring(f.length()), field: f }; + } + } + } + } + return null; +} + +function lansitecKeyTable(model) { + if (LANSITEC_GATEWAYS.contains(model)) { + return LANSITEC_GATEWAY_KEYS; + } + if (model == "badge-tracker") { + return LANSITEC_BADGE_KEYS; + } + if (model == "temperature-humidity-sensor") { + return LANSITEC_TEMPERATURE_HUMIDITY_KEYS; + } + return null; +} + +function lansitecValues(raw, model) { + var table = lansitecKeyTable(model); + var values = {}; + var beacons = {}; + foreach (key : raw.keySet()) { + var value = raw[key]; + var b = lansitecBeaconKey(key); + if (b != null) { + var id = b.group + b.index; + if (beacons[id] == null) { + beacons[id] = { order: parseInt(b.index) }; + } + if (b.field == "rssi") { + beacons[id].rssi = lansitecNumber(value); + } else if (b.field == "data" || b.field == "major" || b.field == "minor") { + beacons[id][b.field] = value; + } + } else if (table == null && key == "time" && value instanceof String) { + // Container tracker and helmet sensor, no datasheet: their codecs add 8 hours to the GNSS time and wrap + // it in quotes, as the badge tracker codec does with the UTC time of DataSheet v5.30, 5.3. + var gnssDate = new Date(value.replace("\"", "")); + values.gnssTime = gnssDate.getTime() - 8 * 60 * 60 * 1000; + } else if (table != null && table.containsKey(key)) { + var tableName = table[key]; + if (tableName != "-") { + values[tableName] = lansitecNumber(value); + } + } else if (LANSITEC_CLASH_KEYS.containsKey(key)) { + var clashName = LANSITEC_CLASH_KEYS[key]; + if (clashName != "-") { + values[clashName] = lansitecNumber(value); + } + } else { + var codecName = lansitecCamelCase(key); + values[codecName] = lansitecNumber(value); + } + } + if (!beacons.isEmpty()) { + values.beacons = lansitecBeaconList(beacons); + } + return values; +} + +function lansitecBeaconList(beacons) { + var list = []; + for (var i = 1; i <= beacons.size(); i++) { + foreach (id : beacons.keySet()) { + var b = beacons[id]; + if (b.order == i) { + var item = {}; + if (b.data != null) { + item.data = b.data; + } + if (b.major != null) { + item.major = b.major; + item.minor = b.minor; + } + item.rssi = b.rssi; + list.add(item); + } + } + } + // The gateway codec reads the data of every device after the first at a 5-byte step, so it is right only + // for 4-byte data (DataSheet 4.4.4 examples): with longer data only the first device is kept. The gateways + // with a datasheet get their beacons from the raw bytes instead; this is for the SocketSync gateway. + if (list.size() > 1 && list[0].data != null && list[0].data.length() != 8) { + var first = []; + first.add(list[0]); + return first; + } + return list; +} + +// Decoded from the raw bytes by the datasheet where the codec gets it wrong. +function lansitecRawValues(values, b, model) { + var type = (b[0] >> 4) & 0x0F; + if (LANSITEC_GATEWAYS.contains(model)) { + lansitecGatewayRawValues(values, b, model, type); + } else if (model == "badge-tracker") { + lansitecBadgeRawValues(values, b, type); + } else if (model == "temperature-humidity-sensor" && type == 2) { + lansitecTemperatureHumidityRawValues(values, b); + } +} + +// SNR, unit 0.01 dB, -3000 to 3000: signed. The codecs read it unsigned. +function lansitecSnr(b, offset) { + var v = parseBytesToInt(b, offset, 2, true); + if (v > 32767) { + v = v - 65536; + } + return v / 100.0; +} + +// Bluetooth Gateway DataSheet 2.27. +function lansitecGatewayRawValues(values, b, model, type) { + if (type == 1 && b.length >= 9) { + // 4.4.1: Network reconnection interval, unit 5 minutes. The codec does not decode it. + values.networkReconnectionInterval = (b[8] & 0xFF) * 300; + } else if (type == 2 && b.length >= 8) { + // 4.4.2: VOL is the battery voltage (VOL x 0.01 + 1.5 V) on the macro gateway and the battery level (%) on + // the others. The codec decides by the value (<= 100 is %), not by the model. + if (model == "macro-bluetooth-gateway") { + values.batteryVoltage = ((b[1] & 0xFF) + 150) / 100.0; + } else { + values.batteryLevel = b[1] & 0xFF; + } + values.loraSnr = lansitecSnr(b, 3); + // CHGSTAT: 0x00 Not charging, 0x50 Charging, 0x60 Charging completed on the compact and solar gateway, + // always 0x00 on the macro and indoor gateway. The codec reads the low half of the byte. + if (model == "compact-bluetooth-gateway" || model == "solar-bluetooth-gateway") { + var charge = b[7] & 0xFF; + if (charge == 0x00) { + values.chargeState = "Not charging"; + } else if (charge == 0x50) { + values.chargeState = "Charging"; + } else if (charge == 0x60) { + values.chargeState = "Charging completed"; + } + } + } else if (type == 0x8 || type == 0x9 || type == 0xA || type == 0xE) { + values.remove("beacons"); + var beacons = lansitecGatewayBeacons(b, type); + if (beacons != null) { + values.beacons = beacons; + } + } +} + +// 4.4.4-4.4.6: Device Type 1, 2 and 3 messages: Type (bits 3-0: number of devices), then Data (1-31 bytes) and +// RSSI (value - 256, dBm) of each device. Data length is not in the message: it is set by the device report rule +// of the type (4.4.3), so all devices of one message have the same length. The codec reads every device after +// the first at a 5-byte step. +// 4.4.7: Multi-Device Type message: Device Type ID before the data of each device. The data length can differ per +// type, and the message does not say it: decoded only when all devices fit the same length. +function lansitecGatewayBeacons(b, type) { + var count = b[0] & 0x0F; + if (count == 0 || (b.length - 1) % count != 0) { + return null; + } + // TBEL division gives a Double: array indexes need an int. + var step = ((b.length - 1) / count).intValue(); + var head = type == 0xE ? 1 : 0; + var dataLength = step - head - 1; + if (dataLength < 1) { + return null; + } + var hex = bytesToHex(b); + var list = []; + for (var i = 0; i < count; i++) { + var start = 1 + i * step; + var deviceType = type - 7; + if (type == 0xE) { + deviceType = b[start] & 0xFF; + if (deviceType < 1 || deviceType > 3) { + return null; + } + } + var item = {}; + item.deviceType = deviceType; + item.data = hex.substring(2 * (start + head), 2 * (start + head + dataLength)); + item.rssi = (b[start + step - 1] & 0xFF) - 256; + list.add(item); + } + return list; +} + +// Badge Tracker DataSheet v5.30. +function lansitecBadgeRawValues(values, b, type) { + if (type == 1 && b.length == 14) { + // 5.1, 14 bytes: Type, SMODE, Power, Config, BLEPRI (2), GNSSPRI (2), Heartbeat, Version (2), CFMMSG, HBCOUNT, Fall. + // BLEEN (Config bit 0) is not decoded: the field table says BLE enable status and that GNSSEN or BLEEN must + // be enabled, but the example (Config 32) has both 0 and calls bit 0 reserved. + values.gnssPositionReportInterval = parseBytesToInt(b, 6, 2, true) * 5; + values.heartbeatInterval = (b[8] & 0xFF) * 30; + // Version 0x0525 is V5.25. + var version = bytesToHex(b).substring(18, 22); + var major = version.substring(0, 2); + if (major.startsWith("0")) { + major = major.substring(1); + } + values.deviceFirmwareVersion = "V" + major + "." + version.substring(2); + values.cfmmsg = b[11] & 0xFF; + values.hbcount = b[12] & 0xFF; + // Fall detection threshold, unit 0.5 m, 0 means off. + values.fallDetectionThreshold = (b[13] & 0xFF) * 0.5; + } else if (type == 2 && b.length >= 6) { + // 5.2: the SNR field is there since firmware 0x0501. The SNREN bit (Type bits 3-0) is not used: the + // datasheet example 20 64 3E 033E 00 60 00 has SNREN 0 and the SNR 8.3 dB. + values.loraSnr = lansitecSnr(b, 3); + // VIBSTATE: moving state 0-9, 0 means no moving, 9 high acceleration. The codec turns only 0 and 1 into text. + values.movingState = b[5] & 0x0F; + } else if (type == 3 && b.length >= 13) { + // 5.3: Flag (Type bits 3-0) 0x1 means GNSS positioning failed. Longitude and latitude are IEEE 754 floats + // (the codec divides the mantissa by 0x7fffff instead of 2^23), time is UTC seconds (the codec adds 8 hours). + // Rounded to 6 decimals (about 0.1 m), as a double: the float has no more precision. + if ((b[0] & 0x0F) == 0) { + values.longitude = toFixed(parseBytesToFloat(b, 1, 4, true) * 1.0, 6); + values.latitude = toFixed(parseBytesToFloat(b, 5, 4, true) * 1.0, 6); + values.gnssTime = parseBytesToLong(b, 9, 4, true) * 1000; + } + } +} + +// Temperature Humidity Sensor DataSheet 1.26, 2.2.2: VER (Type bits 3-0) 1 means the SNR field is there, 0 means +// it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. +// TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. +function lansitecTemperatureHumidityRawValues(values, b) { + var offset = 3; + if ((b[0] & 0x0F) == 1) { + values.loraSnr = lansitecSnr(b, 3); + offset = 5; + } + if (b.length < offset + 3) { + return; + } + var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0; + if ((b[offset] & 0x80) != 0) { + temperature = -temperature; + } + values.temperature = toFixed(temperature, 2); + values.humidity = b[offset + 2] & 0xFF; +} + var values = {}; +var attributes = {}; var history = []; if (metadata.payloadFormat == "JSON") { values = decodeToJson(payload); - if (values.history instanceof java.util.List) { + if (metadata.brandId == "lansitec" && values.bytes != null) { + // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. + var raw = values.bytes; + values = lansitecValues(raw, metadata.modelId); + if (metadata.data != null) { + lansitecRawValues(values, base64ToBytes(metadata.data), metadata.modelId); + } + // Register is sent after join and holds the device settings: they are attributes, not telemetry. + var messageType = raw.type != null ? raw.type : raw["Message type"]; + if (messageType == "Register") { + attributes = values; + values = {}; + } + } else if (values.history instanceof java.util.List) { foreach (record : values.history) { if (record.timestamp != null) { var ts = record.timestamp * 1000; @@ -26,6 +399,9 @@ if (metadata.brandId != null && metadata.modelId != null) { profile = customProfile; } } +if (!attributes.isEmpty()) { + return { profile: profile, attributes: attributes }; +} if (history.isEmpty()) { return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; } From e57c5167f9fd6af225664e07490e93920060a226 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 12:38:43 +0200 Subject: [PATCH 37/66] fix(iot-hub): the JS default TTN/TTI converter takes the payload as UTF-8 bytes or as characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nashorn passes the payload as characters, so decoding it again as UTF-8 failed on a unit like ℃ and the uplink was lost. Tested with simulated TTN uplinks of the Lansitec datasheet examples, TBEL and JS give the same values. --- ui-ngx/src/assets/converters/js-tti-decoder.raw | 10 ++++++++-- ui-ngx/src/assets/converters/js-ttn-decoder.raw | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index ca1d911e66..cc7223254c 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -452,7 +452,13 @@ if (history.length == 0) { history.push({ ts: metadata.ts, values: values }); return { profile: profile, telemetry: history }; -// The payload is UTF-8: a codec value can have a unit like ℃. +// A codec value can have a unit like ℃. Where the payload comes as UTF-8 bytes, they are decoded; where it already +// comes as characters, the decoding fails and the text is taken as it is. function decodeToJson(payload) { - return JSON.parse(decodeURIComponent(escape(String.fromCharCode.apply(String, payload)))); + var text = String.fromCharCode.apply(String, payload); + try { + text = decodeURIComponent(escape(text)); + } catch (e) { + } + return JSON.parse(text); } diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index ca1d911e66..cc7223254c 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -452,7 +452,13 @@ if (history.length == 0) { history.push({ ts: metadata.ts, values: values }); return { profile: profile, telemetry: history }; -// The payload is UTF-8: a codec value can have a unit like ℃. +// A codec value can have a unit like ℃. Where the payload comes as UTF-8 bytes, they are decoded; where it already +// comes as characters, the decoding fails and the text is taken as it is. function decodeToJson(payload) { - return JSON.parse(decodeURIComponent(escape(String.fromCharCode.apply(String, payload)))); + var text = String.fromCharCode.apply(String, payload); + try { + text = decodeURIComponent(escape(text)); + } catch (e) { + } + return JSON.parse(text); } From b26409cae1cc133555b3afed6e684106e8e97b4d Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 13:50:06 +0200 Subject: [PATCH 38/66] test(iot-hub): the default TTN/TTI converters decode Lansitec devices, on 20 uplinks The Things Stack sent (TBEL and JS, TTN and TTI) --- .../controller/ConverterControllerTest.java | 66 + .../things_stack_lansitec_uplinks.json | 1444 +++++++++++++++++ 2 files changed, 1510 insertions(+) create mode 100644 application/src/test/resources/payload/things_stack_lansitec_uplinks.json 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 023397bf0b..317508490f 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -4,6 +4,7 @@ package org.thingsboard.server.controller; import com.fasterxml.jackson.core.type.TypeReference; 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.common.collect.Streams; @@ -40,6 +41,7 @@ import org.thingsboard.server.exception.DataValidationException; import java.io.IOException; import java.io.InputStream; +import java.math.RoundingMode; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; @@ -98,6 +100,7 @@ public class ConverterControllerTest extends AbstractControllerTest { private static final String DEFAULT_V2_CONFIGURATION = "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_LANSITEC_UPLINKS = "payload/things_stack_lansitec_uplinks.json"; @Before public void beforeTest() throws Exception { @@ -732,6 +735,69 @@ public class ConverterControllerTest extends AbstractControllerTest { } } + // Uplinks of Lansitec devices registered from the LoRaWAN Device Repository, as The Things Stack sent them + // (Simulate uplink), and the keys the default converters decode from them. The keys the integration adds to + // every uplink (rssi, fCnt...) are not listed. TBEL gives integers as doubles, so numbers are compared by value. + private static final Set THINGS_STACK_UPLINK_KEYS = Set.of("fCnt", "data", "rssi", "snr", "channel", "consumedAirtime"); + + @Test + public void testThingsStackDefaultConvertersDecodeLansitecDevices() throws IOException { + JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); + JsonNode cases = JacksonUtil.toJsonNode(readResource(THINGS_STACK_LANSITEC_UPLINKS)); + for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { + Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); + for (ScriptLanguage scriptLang : ScriptLanguage.values()) { + String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; + for (JsonNode testCase : cases) { + String description = integrationType + " " + scriptLang + " " + testCase.get("name").asText(); + JsonNode result = JacksonUtil.toJsonNode(decode(decoderFileName, testCase.get("uplink").toString(), converter, scriptLang, Map.of())); + JsonNode decoded = testCase.get("decoded"); + assertThat(result.get("profile")).as(description).isEqualTo(decoded.get("profile")); + + JsonNode telemetry = result.get("telemetry"); + if (telemetry != null && telemetry.isArray()) { + telemetry = telemetry.get(telemetry.size() - 1); + } + JsonNode telemetryValues = telemetry != null && telemetry.has("values") ? telemetry.get("values") : JacksonUtil.newObjectNode(); + ObjectNode lansitecTelemetry = JacksonUtil.newObjectNode(); + telemetryValues.fields().forEachRemaining(e -> { + if (!THINGS_STACK_UPLINK_KEYS.contains(e.getKey())) { + lansitecTelemetry.set(e.getKey(), e.getValue()); + } + }); + assertThat(numbersByValue(lansitecTelemetry)).as(description + " telemetry") + .isEqualTo(numbersByValue(decoded.has("telemetry") ? decoded.get("telemetry") : JacksonUtil.newObjectNode())); + + if (decoded.has("attributes")) { + ObjectNode attributes = JacksonUtil.newObjectNode(); + decoded.get("attributes").fieldNames().forEachRemaining(key -> attributes.set(key, result.get("attributes").get(key))); + assertThat(numbersByValue(attributes)).as(description + " attributes").isEqualTo(numbersByValue(decoded.get("attributes"))); + } + } + } + } + } + + private static JsonNode numbersByValue(JsonNode node) { + if (node == null) { + return null; + } + if (node.isNumber()) { + return JacksonUtil.toJsonNode(node.decimalValue().setScale(6, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString()); + } + if (node.isObject()) { + ObjectNode copy = JacksonUtil.newObjectNode(); + node.fields().forEachRemaining(e -> copy.set(e.getKey(), numbersByValue(e.getValue()))); + return copy; + } + if (node.isArray()) { + ArrayNode copy = JacksonUtil.newArrayNode(); + node.forEach(item -> copy.add(numbersByValue(item))); + return copy; + } + return node; + } + private String readResource(String name) throws IOException { return new String(IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(name)), StandardCharsets.UTF_8); } diff --git a/application/src/test/resources/payload/things_stack_lansitec_uplinks.json b/application/src/test/resources/payload/things_stack_lansitec_uplinks.json new file mode 100644 index 0000000000..5b1aefd85f --- /dev/null +++ b/application/src/test/resources/payload/things_stack_lansitec_uplinks.json @@ -0,0 +1,1444 @@ +[ + { + "name": "gw Registration 4.4.1", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DWZKQC3A6CWMNE64WPEVRC", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:96427a37-7461-40d0-94f4-6e3ea7f275e5" + ], + "received_at": "2026-11-02T10:30:49.835523566Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "FiCgMAA8eAsG", + "decoded_payload": { + "bytes": { + "BLEReceivingDuration": "11sec", + "ContinuousReceive": "Continuous Bluetooth receiving is disabled", + "LoRaTxpower": "20dBm", + "LoRaWANband": "EU868", + "adr": "OFF", + "dr": "DR3", + "hb": "3600sec", + "mode": "EU868", + "pos": "300sec", + "type": "Register" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "attributes": { + "bluetoothReceivingDuration": 11.0, + "continuousBleReceiving": "Continuous Bluetooth receiving is disabled", + "loraTxPower": 20.0, + "loraWanFrequencyBand": "EU868", + "adr": "OFF", + "dataRate": "DR3", + "heartbeatInterval": 3600.0, + "mode": "EU868", + "positionReportInterval": 300.0, + "networkReconnectionInterval": 1800 + } + } + }, + { + "name": "gw Heartbeat 4.4.2 macro", + "uplink": { + "end_device_ids": { + "device_id": "lt-macro-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0002", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DWZT8XP0N2W84G07Q2MMCH", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:1af83ff0-c875-48b0-b388-dc2e2742ef61" + ], + "received_at": "2026-11-02T10:30:56.540968417Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "Ics+Az4AbAA=", + "decoded_payload": { + "bytes": { + "chgstate": "Not charging", + "rssi": "-62dBm", + "snr": "8.3dB", + "type": "Heartbeat", + "ver": "VER108", + "vol": "3.5300000000000002V" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "macro-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.10", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-macro-bluetooth-gateway", + "telemetry": { + "loraRssi": -62.0, + "deviceFirmwareVersion": "VER108", + "batteryVoltage": 3.53, + "loraSnr": 8.3 + } + } + }, + { + "name": "gw Heartbeat CHGSTAT 0x50 (built)", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX00PFS05VHZX420SK9SRW", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:4a7e0719-1b7b-4322-b00f-9619d3c1988b" + ], + "received_at": "2026-11-02T10:31:03.118765152Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IWQ+Az4AbFA=", + "decoded_payload": { + "bytes": { + "chgstate": "Not charging", + "rssi": "-62dBm", + "snr": "8.3dB", + "type": "Heartbeat", + "ver": "VER108", + "vol": "100%" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "telemetry": { + "loraRssi": -62.0, + "deviceFirmwareVersion": "VER108", + "batteryLevel": 100, + "loraSnr": 8.3, + "chargeState": "Charging" + } + } + }, + { + "name": "gw Heartbeat CHGSTAT 0x60, SNR -5.00 (built)", + "uplink": { + "end_device_ids": { + "device_id": "lt-solar-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0003", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX074N1N81HG0PPEWKCC4W", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:08bbcae0-1d84-49ae-af6c-384da48f8212" + ], + "received_at": "2026-11-02T10:31:09.716547098Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IWQ+/gwAbGA=", + "decoded_payload": { + "bytes": { + "chgstate": "Not charging", + "rssi": "-62dBm", + "snr": "650.36dB", + "type": "Heartbeat", + "ver": "VER108", + "vol": "100%" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "solar-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.10", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-solar-bluetooth-gateway", + "telemetry": { + "loraRssi": -62.0, + "deviceFirmwareVersion": "VER108", + "batteryLevel": 100, + "loraSnr": -5.0, + "chargeState": "Charging completed" + } + } + }, + { + "name": "gw Device Type 1 4.4.4 ex1", + "uplink": { + "end_device_ids": { + "device_id": "lt-indoor-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0001", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX0DHGSWGSMJN6M8JJQM4Q", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:3ff688da-df1b-4138-ac08-7d4e01ce8695" + ], + "received_at": "2026-11-02T10:31:16.271874839Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "gwYaTAACFaq7swYaTAACFaq8tAYaTAACFaq9tQ==", + "decoded_payload": { + "bytes": { + "Devicetype1data1": "061A4C000215AABB", + "Devicetype1data2": "15AABBB3061A4C00", + "Devicetype1data3": "1A4C000215AABCB4", + "Devicetype1rssi1": "-77dBm", + "Devicetype1rssi2": "-76dBm", + "Devicetype1rssi3": "-75dBm", + "number": 3, + "type": "Device Type 1 Message" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "indoor-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-indoor-bluetooth-gateway", + "telemetry": { + "beacons": [ + { + "deviceType": 1, + "data": "061A4C000215AABB", + "rssi": -77 + }, + { + "deviceType": 1, + "data": "061A4C000215AABC", + "rssi": -76 + }, + { + "deviceType": 1, + "data": "061A4C000215AABD", + "rssi": -75 + } + ] + } + } + }, + { + "name": "gw Device Type 1 4.4.4 ex2", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX0KYNGRQ053WBK9XC1SP2", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:d999fd28-8d4f-401c-9b7f-95c694d99f72" + ], + "received_at": "2026-11-02T10:31:22.835827277Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "gmSCFpgmU0wCFaq8tGSCFpgmVAYaFaq9tQ==", + "decoded_payload": { + "bytes": { + "Devicetype1data1": "6482169826534C0215AABC", + "Devicetype1data2": "534C0215AABCB464821698", + "Devicetype1rssi1": "-76dBm", + "Devicetype1rssi2": "-75dBm", + "number": 2, + "type": "Device Type 1 Message" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "telemetry": { + "beacons": [ + { + "deviceType": 1, + "data": "6482169826534C0215AABC", + "rssi": -76 + }, + { + "deviceType": 1, + "data": "648216982654061A15AABD", + "rssi": -75 + } + ] + } + } + }, + { + "name": "gw Device Type 2 4.4.5 ex2", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX0TBEF65ED7NRWQ4YFTRQ", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:7f4ac774-4027-4962-a213-e526da66fd38" + ], + "received_at": "2026-11-02T10:31:29.389983893Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "kpgmU0FNLTEwMDAxs5gmVEFNLTEwMDAytA==", + "decoded_payload": { + "bytes": { + "Devicetype2data1": "982653414D2D3130303031", + "Devicetype2data2": "2D3130303031B398265441", + "Devicetype2rssi1": "-77dBm", + "Devicetype2rssi2": "-76dBm", + "number": 2, + "type": "Device Type 2 Message" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "telemetry": { + "beacons": [ + { + "deviceType": 2, + "data": "982653414D2D3130303031", + "rssi": -77 + }, + { + "deviceType": 2, + "data": "982654414D2D3130303032", + "rssi": -76 + } + ] + } + } + }, + { + "name": "gw Device Type 3 4.4.6 ex1", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX10R67RVM4X2QAMR9C8JG", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:68655884-9942-4270-9536-700ee6b20dcf" + ], + "received_at": "2026-11-02T10:31:35.941440062Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "ogAQAwrCABADC8Q=", + "decoded_payload": { + "bytes": { + "Devicetype3data1": "0010030A", + "Devicetype3data2": "0010030B", + "Devicetype3rssi1": "-62dBm", + "Devicetype3rssi2": "-60dBm", + "number": 2, + "type": "Device Type 3 Message" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "telemetry": { + "beacons": [ + { + "deviceType": 3, + "data": "0010030A", + "rssi": -62 + }, + { + "deviceType": 3, + "data": "0010030B", + "rssi": -60 + } + ] + } + } + }, + { + "name": "gw Multi 4.4.7 (mixed lengths)", + "uplink": { + "end_device_ids": { + "device_id": "lt-compact-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0000", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX174RG6ZG5ZKAHAZTRVG9", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:1aff5046-26ee-42eb-9dfb-d58dafa63116" + ], + "received_at": "2026-11-02T10:31:42.487961636Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "4wEGGkwAAhWqu7MDQU0tMTAwMDGxAgAQAwvF", + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "compact-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-compact-bluetooth-gateway", + "telemetry": {} + } + }, + { + "name": "badge Registration 5.1", + "uplink": { + "end_device_ids": { + "device_id": "lt-badge-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0007", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX1DGR31039JQYY9Y2XQ8V", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:224ac913-2b83-4efa-8b16-93b3f4fe7a16" + ], + "received_at": "2026-11-02T10:31:49.014979356Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "EACgMgA8AWh4BSUCBQQ=", + "decoded_payload": { + "bytes": { + "ADR": "OFF", + "CFMMSG": "1 Confirmed every 5 Heartbeat", + "DR": "DR3", + "Fall threshold": "1 meter", + "Firmware version": "V68.78", + "GNSSEN": "Disable", + "HBCOUNT": "Disconnect Judgement 37", + "Heartbeat period": "30sec", + "Lora Txpower": "20dBm", + "Message type": "Register", + "Position mode": "Autonomous", + "Position period": "300sec" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "badge-tracker", + "hardware_version": "1.0", + "firmware_version": "5.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-badge-tracker", + "attributes": { + "adr": "OFF", + "dataRate": "DR3", + "gnssEnabled": "Disable", + "loraTxPower": 20.0, + "positioningReportMode": "Autonomous", + "bluetoothPositionReportInterval": 300.0, + "gnssPositionReportInterval": 1800, + "heartbeatInterval": 3600, + "deviceFirmwareVersion": "V5.25", + "cfmmsg": 2, + "hbcount": 5, + "fallDetectionThreshold": 2.0 + } + } + }, + { + "name": "badge Heartbeat 5.2", + "uplink": { + "end_device_ids": { + "device_id": "lt-badge-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0007", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX1KWZBE1ANRSZWHFSKQ89", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:29eb6310-c010-4972-897c-d743a41f1d8d" + ], + "received_at": "2026-11-02T10:31:55.550797518Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IGQ+Az4AYAA=", + "decoded_payload": { + "bytes": { + "Battery level": "100%", + "Charge state": "Charge complete", + "GPS state": "GPS OFF", + "Message type": "Heartbeat", + "Move state": "No Move", + "RSSI": "-62dBm", + "SNR": "8.3dB" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "badge-tracker", + "hardware_version": "1.0", + "firmware_version": "5.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-badge-tracker", + "telemetry": { + "batteryLevel": 100.0, + "chargeState": "Charge complete", + "gnssState": "GPS OFF", + "loraRssi": -62.0, + "loraSnr": 8.3, + "movingState": 0 + } + } + }, + { + "name": "badge GNSS 5.3", + "uplink": { + "end_device_ids": { + "device_id": "lt-badge-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0007", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX1T9GTJ0BFJRK0D53EHQA", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:bd62cb24-c5cb-4732-a997-c5b6af5a2e47" + ], + "received_at": "2026-11-02T10:32:02.096017163Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "MELtisRB/84uZXLoqA==", + "decoded_payload": { + "bytes": { + "Latitude": 31.975675579986046, + "Longitude": 118.77103314054408, + "Message type": "GNSSPosition", + "Time": "\"2023-12-08T17:58:00.000Z\"" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "badge-tracker", + "hardware_version": "1.0", + "firmware_version": "5.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-badge-tracker", + "telemetry": { + "longitude": 118.771027, + "latitude": 31.975674, + "gnssTime": 1702029480000 + } + } + }, + { + "name": "badge GNSS flag failed (built)", + "uplink": { + "end_device_ids": { + "device_id": "lt-badge-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0007", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX20NZAK3HTDSA9K12Z4Z6", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:b498fb1f-8894-4ba9-b17c-07c7d0f4018f" + ], + "received_at": "2026-11-02T10:32:08.639160535Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "MULtisRB/84uZXLoqA==", + "decoded_payload": { + "bytes": { + "Latitude": 31.975675579986046, + "Longitude": 118.77103314054408, + "Message type": "GNSSPosition", + "Time": "\"2023-12-08T17:58:00.000Z\"" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "badge-tracker", + "hardware_version": "1.0", + "firmware_version": "5.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-badge-tracker", + "telemetry": {} + } + }, + { + "name": "temp-hum VER1 -5.00 dB, -12.34 C, 56 % (built)", + "uplink": { + "end_device_ids": { + "device_id": "lt-temperature-humidity-sensor", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A000A", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX2756RP8VNV5W4TED20QV", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:2f27538b-a738-43f7-b251-82e5b814d2f2" + ], + "received_at": "2026-11-02T10:32:15.269594659Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IWQ+/gyMIjgSNA==", + "decoded_payload": { + "bytes": { + "crc": 4660, + "humidity": "56%", + "rssi": "-62dBm", + "snr": 650.36, + "temperature": "-12.34℃", + "type": "Heartbeat", + "ver": 1, + "vol": "100%" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "temperature-humidity-sensor", + "hardware_version": "1.0", + "firmware_version": "1.01", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-temperature-humidity-sensor", + "telemetry": { + "loraRssi": -62.0, + "batteryLevel": 100.0, + "loraSnr": -5.0, + "temperature": -12.34, + "humidity": 56 + } + } + }, + { + "name": "temp-hum VER0 21.05 C, 40 % (built)", + "uplink": { + "end_device_ids": { + "device_id": "lt-temperature-humidity-sensor", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A000A", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX2DHP1PVMSN9XXTFX6G9E", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:d92a9e40-19fc-4d8a-bbed-db57a3285281" + ], + "received_at": "2026-11-02T10:32:21.813476822Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IGQ+FQUoEjQ=", + "decoded_payload": { + "bytes": { + "crc": 0, + "humidity": "52%", + "rssi": "-62dBm", + "snr": 53.81, + "temperature": "40.18℃", + "type": "Heartbeat", + "ver": 0, + "vol": "100%" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "temperature-humidity-sensor", + "hardware_version": "1.0", + "firmware_version": "1.01", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-temperature-humidity-sensor", + "telemetry": { + "loraRssi": -62.0, + "batteryLevel": 100.0, + "temperature": 21.05, + "humidity": 40 + } + } + }, + { + "name": "container Heartbeat (built from the codec)", + "uplink": { + "end_device_ids": { + "device_id": "lt-container-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0008", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX2KYHR69G9SQHNPG7VJ0N", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:e36b265c-edf1-4c2b-8162-4e475b776185" + ], + "received_at": "2026-11-02T10:32:28.369063597Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "Ics+Az4yABkADA==", + "decoded_payload": { + "bytes": { + "gpsstate": "located", + "movement": "60sec", + "rssi": "-62dBm", + "snr": "8.3dB", + "snrinc": "SNR field included ", + "temperature": "25℃", + "type": "Heartbeat", + "vibstate": "2level", + "vol": "3.5300000000000002V" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "container-tracker", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-container-tracker", + "telemetry": { + "gpsstate": "located", + "movement": 60.0, + "loraRssi": -62.0, + "loraSnr": 8.3, + "snrinc": "SNR field included ", + "temperature": 25.0, + "vibstate": 2.0, + "vol": 3.5300000000000002 + } + } + }, + { + "name": "container GNSS (badge 5.3 bytes)", + "uplink": { + "end_device_ids": { + "device_id": "lt-container-tracker", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0008", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX2TBAJT5T5EE3615Y9MAW", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:b64cce74-6708-4423-aa37-eca108e9f585" + ], + "received_at": "2026-11-02T10:32:34.922307414Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "MELtisRB/84uZXLoqA==", + "decoded_payload": { + "bytes": { + "latitude": 31.975675579986046, + "longitude": 118.77103314054408, + "time": "\"2023-12-08T17:58:00.000Z\"", + "type": "GNSSPosition" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "container-tracker", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-container-tracker", + "telemetry": { + "latitude": 31.975675579986046, + "longitude": 118.77103314054408, + "gnssTime": 1702029480000 + } + } + }, + { + "name": "helmet Heartbeat (built from the codec)", + "uplink": { + "end_device_ids": { + "device_id": "lt-helmet-sensor", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0009", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX30QBDSZ7MN6T27M5X0A3", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:177c9fb1-a5aa-40a5-a324-ace0f58979b7" + ], + "received_at": "2026-11-02T10:32:41.450805906Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IWQ+Az4BAQIEIA==", + "decoded_payload": { + "bytes": { + "batteryPercentage": "100%", + "bleState": 1, + "chargeTime": "60s", + "gpsState": 1, + "moveState": "2 Move", + "rssi": "-62dBm", + "snr": "8.3dB", + "type": "Heartbeat", + "wearTime": "120s" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "helmet-sensor", + "hardware_version": "1.0", + "firmware_version": "0.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-helmet-sensor", + "telemetry": { + "batteryPercentage": 100.0, + "bleState": 1, + "chargeTime": 60.0, + "gpsState": 1, + "moveState": "2 Move", + "loraRssi": -62.0, + "loraSnr": 8.3, + "wearTime": 120.0 + } + } + }, + { + "name": "helmet GNSS (built from the codec)", + "uplink": { + "end_device_ids": { + "device_id": "lt-helmet-sensor", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0009", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX373VN3K38B2H5WR86Z6H", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:ed54ebed-8df4-46eb-a656-5769e3c37be8" + ], + "received_at": "2026-11-02T10:32:47.994303232Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "MQABhqBC7YrEQf/OLmVy6Kg=", + "decoded_payload": { + "bytes": { + "gpsState": "gps location success", + "latitude": 31.975675579986046, + "longitude": 118.77103314054408, + "pressure": 100000, + "time": "\"2023-12-08T17:58:00.000Z\"", + "type": "GNSSPosition", + "wearState": "wear" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "helmet-sensor", + "hardware_version": "1.0", + "firmware_version": "0.25", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-helmet-sensor", + "telemetry": { + "gpsState": "gps location success", + "latitude": 31.975675579986046, + "longitude": 118.77103314054408, + "pressure": 100000, + "gnssTime": 1702029480000, + "wearState": "wear" + } + } + }, + { + "name": "socketsync Heartbeat 0x50", + "uplink": { + "end_device_ids": { + "device_id": "lt-socket-sync-bluetooth-gateway", + "application_ids": { + "application_id": "ansitec-test" + }, + "dev_eui": "70B3D57ED01A0004", + "join_eui": "0000000000000000" + }, + "correlation_ids": [ + "as:up:01M6DX3DFWNQE3WSG9JNFTAG7B", + "rpc:/ttn.lorawan.v3.AppAs/SimulateUplink:ec26c3c1-e861-4d65-b6e7-1206e538a5c7" + ], + "received_at": "2026-11-02T10:32:54.523762899Z", + "uplink_message": { + "f_port": 1, + "frm_payload": "IWQ+Az4AbFA=", + "decoded_payload": { + "bytes": { + "chgstate": "Not charging", + "rssi": "-62dBm", + "snr": "8.3dB", + "type": "Heartbeat", + "ver": "VER108", + "vol": "100%" + } + }, + "rx_metadata": [ + { + "gateway_ids": { + "gateway_id": "test" + }, + "rssi": -42, + "channel_rssi": -42, + "snr": 4.2 + } + ], + "settings": { + "data_rate": { + "lora": { + "bandwidth": 125000, + "spreading_factor": 7, + "coding_rate": "4/5" + } + }, + "frequency": "868100000" + }, + "version_ids": { + "brand_id": "lansitec", + "model_id": "socket-sync-bluetooth-gateway", + "hardware_version": "1.0", + "firmware_version": "1.0", + "band_id": "EU_863_870" + } + }, + "simulated": true + }, + "decoded": { + "profile": "lansitec-socket-sync-bluetooth-gateway", + "telemetry": { + "loraRssi": -62.0, + "loraSnr": 8.3, + "ver": "VER108", + "vol": 100.0 + } + } + } +] From 846c022d9d6c6967839509fa7ac60d6c105623b4 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Mon, 2 Nov 2026 14:04:13 +0200 Subject: [PATCH 39/66] fix(iot-hub): a Lansitec frame too short for its message or bytes that are not an object no longer drop the uplink; the Lansitec test also checks the attributes --- .../controller/ConverterControllerTest.java | 103 +++++++++++++----- .../src/assets/converters/js-tti-decoder.raw | 14 ++- .../src/assets/converters/js-ttn-decoder.raw | 14 ++- .../assets/converters/tbel-tti-decoder.raw | 14 ++- .../assets/converters/tbel-ttn-decoder.raw | 14 ++- 5 files changed, 108 insertions(+), 51 deletions(-) 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 317508490f..56a9237097 100644 --- a/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java +++ b/application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java @@ -737,47 +737,96 @@ public class ConverterControllerTest extends AbstractControllerTest { // Uplinks of Lansitec devices registered from the LoRaWAN Device Repository, as The Things Stack sent them // (Simulate uplink), and the keys the default converters decode from them. The keys the integration adds to - // every uplink (rssi, fCnt...) are not listed. TBEL gives integers as doubles, so numbers are compared by value. + // every uplink (rssi, fCnt, eui...) are not listed. TBEL gives integers as doubles, so numbers are compared by value. private static final Set THINGS_STACK_UPLINK_KEYS = Set.of("fCnt", "data", "rssi", "snr", "channel", "consumedAirtime"); + private static final Set THINGS_STACK_ATTRIBUTE_KEYS = Set.of("eui", "joinEui", "devAddr", "deviceId", "applicationId", "fPort", + "bandwidth", "spreadingFactor", "codeRate", "frequency", "brandId", "modelId", "hardwareVersion", "firmwareVersion", "bandId", + "netId", "tenantId", "clusterId", "clusterAddress"); @Test public void testThingsStackDefaultConvertersDecodeLansitecDevices() throws IOException { - JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); JsonNode cases = JacksonUtil.toJsonNode(readResource(THINGS_STACK_LANSITEC_UPLINKS)); + forEachThingsStackDefaultConverter((description, decoder) -> { + for (JsonNode testCase : cases) { + String caseDescription = description + " " + testCase.get("name").asText(); + JsonNode result = decoder.apply(testCase.get("uplink")); + JsonNode decoded = testCase.get("decoded"); + assertThat(result.get("profile")).as(caseDescription).isEqualTo(decoded.get("profile")); + assertThat(numbersByValue(withoutKeys(telemetryValues(result), THINGS_STACK_UPLINK_KEYS))).as(caseDescription + " telemetry") + .isEqualTo(numbersByValue(decoded.has("telemetry") ? decoded.get("telemetry") : JacksonUtil.newObjectNode())); + assertThat(numbersByValue(withoutKeys(result.get("attributes"), THINGS_STACK_ATTRIBUTE_KEYS))).as(caseDescription + " attributes") + .isEqualTo(numbersByValue(decoded.has("attributes") ? decoded.get("attributes") : JacksonUtil.newObjectNode())); + } + }); + } + + // A frame too short for its message type, and bytes that are not an object: the uplink is still converted + @Test + public void testThingsStackDefaultConvertersKeepMalformedLansitecUplinks() throws IOException { + JsonNode temperatureHumidity = null; + for (JsonNode testCase : JacksonUtil.toJsonNode(readResource(THINGS_STACK_LANSITEC_UPLINKS))) { + if (testCase.get("name").asText().startsWith("temp-hum VER1")) { + temperatureHumidity = testCase.get("uplink"); + } + } + ObjectNode shortFrame = temperatureHumidity.deepCopy(); + ((ObjectNode) shortFrame.get("uplink_message")).put("frm_payload", "IQ=="); + ObjectNode bytesList = temperatureHumidity.deepCopy(); + ((ObjectNode) bytesList.get("uplink_message").get("decoded_payload")).set("bytes", JacksonUtil.toJsonNode("[33, 100]")); + + forEachThingsStackDefaultConverter((description, decoder) -> { + JsonNode result = decoder.apply(shortFrame); + assertThat(result.get("profile").asText()).as(description + " short frame").isEqualTo("lansitec-temperature-humidity-sensor"); + assertThat(telemetryValues(result).has("loraSnr")).as(description + " short frame").isFalse(); + + result = decoder.apply(bytesList); + assertThat(result.get("profile").asText()).as(description + " bytes list").isEqualTo("lansitec-temperature-humidity-sensor"); + assertThat(numbersByValue(telemetryValues(result).get("bytes"))).as(description + " bytes list") + .isEqualTo(numbersByValue(JacksonUtil.toJsonNode("[33, 100]"))); + }); + } + + private interface ThingsStackDecoderCheck { + void check(String description, java.util.function.Function decoder) throws IOException; + } + + private void forEachThingsStackDefaultConverter(ThingsStackDecoderCheck check) throws IOException { + JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(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 decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; - for (JsonNode testCase : cases) { - String description = integrationType + " " + scriptLang + " " + testCase.get("name").asText(); - JsonNode result = JacksonUtil.toJsonNode(decode(decoderFileName, testCase.get("uplink").toString(), converter, scriptLang, Map.of())); - JsonNode decoded = testCase.get("decoded"); - assertThat(result.get("profile")).as(description).isEqualTo(decoded.get("profile")); - - JsonNode telemetry = result.get("telemetry"); - if (telemetry != null && telemetry.isArray()) { - telemetry = telemetry.get(telemetry.size() - 1); - } - JsonNode telemetryValues = telemetry != null && telemetry.has("values") ? telemetry.get("values") : JacksonUtil.newObjectNode(); - ObjectNode lansitecTelemetry = JacksonUtil.newObjectNode(); - telemetryValues.fields().forEachRemaining(e -> { - if (!THINGS_STACK_UPLINK_KEYS.contains(e.getKey())) { - lansitecTelemetry.set(e.getKey(), e.getValue()); - } - }); - assertThat(numbersByValue(lansitecTelemetry)).as(description + " telemetry") - .isEqualTo(numbersByValue(decoded.has("telemetry") ? decoded.get("telemetry") : JacksonUtil.newObjectNode())); - - if (decoded.has("attributes")) { - ObjectNode attributes = JacksonUtil.newObjectNode(); - decoded.get("attributes").fieldNames().forEachRemaining(key -> attributes.set(key, result.get("attributes").get(key))); - assertThat(numbersByValue(attributes)).as(description + " attributes").isEqualTo(numbersByValue(decoded.get("attributes"))); + check.check(integrationType + " " + scriptLang, uplink -> { + try { + return JacksonUtil.toJsonNode(decode(decoderFileName, uplink.toString(), converter, scriptLang, Map.of())); + } catch (IOException e) { + throw new RuntimeException(e); } - } + }); } } } + private static JsonNode telemetryValues(JsonNode result) { + JsonNode telemetry = result.get("telemetry"); + if (telemetry != null && telemetry.isArray()) { + telemetry = telemetry.get(telemetry.size() - 1); + } + return telemetry != null && telemetry.has("values") ? telemetry.get("values") : JacksonUtil.newObjectNode(); + } + + private static ObjectNode withoutKeys(JsonNode node, Set keys) { + ObjectNode copy = JacksonUtil.newObjectNode(); + if (node != null) { + node.fields().forEachRemaining(e -> { + if (!keys.contains(e.getKey())) { + copy.set(e.getKey(), e.getValue()); + } + }); + } + return copy; + } + private static JsonNode numbersByValue(JsonNode node) { if (node == null) { return null; diff --git a/ui-ngx/src/assets/converters/js-tti-decoder.raw b/ui-ngx/src/assets/converters/js-tti-decoder.raw index cc7223254c..e3257d7c4b 100644 --- a/ui-ngx/src/assets/converters/js-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/js-tti-decoder.raw @@ -214,6 +214,9 @@ function lansitecBeaconList(beacons) { // Decoded from the raw bytes by the datasheet where the codec gets it wrong. function lansitecRawValues(values, b, model) { + if (b.length == 0) { + return; + } var type = (b[0] >> 4) & 0x0F; if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { lansitecGatewayRawValues(values, b, model, type); @@ -389,14 +392,13 @@ function lansitecBadgeRawValues(values, b, type) { // it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. // TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. function lansitecTemperatureHumidityRawValues(values, b) { - var offset = 3; - if ((b[0] & 0x0F) == 1) { - values.loraSnr = lansitecSnr(b, 3); - offset = 5; - } + var offset = (b[0] & 0x0F) == 1 ? 5 : 3; if (b.length < offset + 3) { return; } + if (offset == 5) { + values.loraSnr = lansitecSnr(b, 3); + } var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100; if ((b[offset] & 0x80) != 0) { temperature = -temperature; @@ -410,7 +412,7 @@ var attributes = {}; var history = []; if (metadata.payloadFormat == 'JSON') { values = decodeToJson(payload); - if (metadata.brandId == 'lansitec' && values.bytes != null) { + if (metadata.brandId == 'lansitec' && values.bytes != null && typeof values.bytes === 'object' && !Array.isArray(values.bytes)) { // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. var raw = values.bytes; values = lansitecValues(raw, metadata.modelId); diff --git a/ui-ngx/src/assets/converters/js-ttn-decoder.raw b/ui-ngx/src/assets/converters/js-ttn-decoder.raw index cc7223254c..e3257d7c4b 100644 --- a/ui-ngx/src/assets/converters/js-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/js-ttn-decoder.raw @@ -214,6 +214,9 @@ function lansitecBeaconList(beacons) { // Decoded from the raw bytes by the datasheet where the codec gets it wrong. function lansitecRawValues(values, b, model) { + if (b.length == 0) { + return; + } var type = (b[0] >> 4) & 0x0F; if (LANSITEC_GATEWAYS.indexOf(model) >= 0) { lansitecGatewayRawValues(values, b, model, type); @@ -389,14 +392,13 @@ function lansitecBadgeRawValues(values, b, type) { // it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. // TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. function lansitecTemperatureHumidityRawValues(values, b) { - var offset = 3; - if ((b[0] & 0x0F) == 1) { - values.loraSnr = lansitecSnr(b, 3); - offset = 5; - } + var offset = (b[0] & 0x0F) == 1 ? 5 : 3; if (b.length < offset + 3) { return; } + if (offset == 5) { + values.loraSnr = lansitecSnr(b, 3); + } var temperature = (b[offset] & 0x7F) + b[offset + 1] / 100; if ((b[offset] & 0x80) != 0) { temperature = -temperature; @@ -410,7 +412,7 @@ var attributes = {}; var history = []; if (metadata.payloadFormat == 'JSON') { values = decodeToJson(payload); - if (metadata.brandId == 'lansitec' && values.bytes != null) { + if (metadata.brandId == 'lansitec' && values.bytes != null && typeof values.bytes === 'object' && !Array.isArray(values.bytes)) { // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. var raw = values.bytes; values = lansitecValues(raw, metadata.modelId); diff --git a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw index 2e675de454..6052f41f4a 100644 --- a/ui-ngx/src/assets/converters/tbel-tti-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-tti-decoder.raw @@ -212,6 +212,9 @@ function lansitecBeaconList(beacons) { // Decoded from the raw bytes by the datasheet where the codec gets it wrong. function lansitecRawValues(values, b, model) { + if (b.length == 0) { + return; + } var type = (b[0] >> 4) & 0x0F; if (LANSITEC_GATEWAYS.contains(model)) { lansitecGatewayRawValues(values, b, model, type); @@ -345,14 +348,13 @@ function lansitecBadgeRawValues(values, b, type) { // it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. // TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. function lansitecTemperatureHumidityRawValues(values, b) { - var offset = 3; - if ((b[0] & 0x0F) == 1) { - values.loraSnr = lansitecSnr(b, 3); - offset = 5; - } + var offset = (b[0] & 0x0F) == 1 ? 5 : 3; if (b.length < offset + 3) { return; } + if (offset == 5) { + values.loraSnr = lansitecSnr(b, 3); + } var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0; if ((b[offset] & 0x80) != 0) { temperature = -temperature; @@ -366,7 +368,7 @@ var attributes = {}; var history = []; if (metadata.payloadFormat == "JSON") { values = decodeToJson(payload); - if (metadata.brandId == "lansitec" && values.bytes != null) { + if (metadata.brandId == "lansitec" && isMap(values.bytes)) { // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. var raw = values.bytes; values = lansitecValues(raw, metadata.modelId); diff --git a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw index 2e675de454..6052f41f4a 100644 --- a/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw +++ b/ui-ngx/src/assets/converters/tbel-ttn-decoder.raw @@ -212,6 +212,9 @@ function lansitecBeaconList(beacons) { // Decoded from the raw bytes by the datasheet where the codec gets it wrong. function lansitecRawValues(values, b, model) { + if (b.length == 0) { + return; + } var type = (b[0] >> 4) & 0x0F; if (LANSITEC_GATEWAYS.contains(model)) { lansitecGatewayRawValues(values, b, model, type); @@ -345,14 +348,13 @@ function lansitecBadgeRawValues(values, b, type) { // it is not and the message is 8 bytes. The codec always reads the SNR, so with VER 0 the next fields are shifted. // TEMP_INT bit 7 is the sign, TEMP_FRA the hundredths. function lansitecTemperatureHumidityRawValues(values, b) { - var offset = 3; - if ((b[0] & 0x0F) == 1) { - values.loraSnr = lansitecSnr(b, 3); - offset = 5; - } + var offset = (b[0] & 0x0F) == 1 ? 5 : 3; if (b.length < offset + 3) { return; } + if (offset == 5) { + values.loraSnr = lansitecSnr(b, 3); + } var temperature = (b[offset] & 0x7F) + (b[offset + 1] & 0xFF) / 100.0; if ((b[offset] & 0x80) != 0) { temperature = -temperature; @@ -366,7 +368,7 @@ var attributes = {}; var history = []; if (metadata.payloadFormat == "JSON") { values = decodeToJson(payload); - if (metadata.brandId == "lansitec" && values.bytes != null) { + if (metadata.brandId == "lansitec" && isMap(values.bytes)) { // The Lansitec codecs put everything in "bytes" and get some fields wrong: see the Lansitec block above. var raw = values.bytes; values = lansitecValues(raw, metadata.modelId); From 6cfe0e0bf4288af0bcce60558c909c9b9cdb41f2 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Mon, 2 Nov 2026 15:21:51 +0200 Subject: [PATCH 40/66] Typed LoRaWAN uplink converters keep string identifiers as strings Values that the network server sends as JSON strings and that the typed converter adds from the unwrapped event (devAddr, eui, joinEui, netId, hardwareVersion, ...) skip the numeric type cast, so devAddr "01020304" stays "01020304". Numbers from the event (fCnt, rssi, snr, ...) and the decoder output are cast as before. JsonConverter gets convertToTelemetryProto/convertToAttributesProto overloads with a set of no-cast keys; the existing methods do not change. PROD-9057 Co-Authored-By: Claude --- .../AbstractUplinkDataConverter.java | 2 +- .../api/converter/DedicatedConverterUtil.java | 30 ++++-- .../DedicatedScriptUplinkDataConverter.java | 7 +- .../api/converter/DedicatedUplinkData.java | 6 ++ ...edicatedScriptUplinkDataConverterTest.java | 100 ++++++++++++++++++ .../server/common/adaptor/JsonConverter.java | 50 +++++---- .../common/adaptor/JsonConverterTest.java | 40 +++++++ 7 files changed, 206 insertions(+), 29 deletions(-) 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..ae3ccf23c3 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 @@ -11,7 +11,9 @@ 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,14 +33,21 @@ 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()); + JsonObject telemetryFromMetadata = addKvs(new JsonObject(), kvMap, config.getTelemetry(), unwrapperKeys, telemetryNoCastKeys); if (!telemetryFromMetadata.isEmpty()) { telemetry.getAsJsonArray().add(telemetryFromMetadata); } @@ -46,13 +55,13 @@ public final class DedicatedConverterUtil { 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 +71,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 +92,8 @@ public final class DedicatedConverterUtil { .group(group) .telemetry(telemetry) .attributes(attributes) + .telemetryNoCastKeys(telemetryNoCastKeys) + .attributesNoCastKeys(attributesNoCastKeys) .build(); } @@ -101,11 +112,16 @@ public final class DedicatedConverterUtil { return defaultValue.get(); } - private static JsonObject addKvs(JsonObject kvsObj, Map kvMap, Set 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/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..60a41cae3b 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,102 @@ // 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.ConverterUnwrapper; +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"), 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); + } + + @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 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 @@ -206,6 +275,37 @@ 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"); + return thingsStackUnwrapper.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/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..13f49c785e 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 @@ -9,6 +9,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 +98,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); + } + } From d9e1f62204660bedaa99884143467e65b780a555 Mon Sep 17 00:00:00 2001 From: dshvaika Date: Mon, 2 Nov 2026 15:47:18 +0200 Subject: [PATCH 41/66] IoT Hub device package delete removes its entries from a kept integration's metadata A device package's install state records, per INTEGRATION step, the metadata entries the step added to the integration (e.g. profile.milesight-iot-am308 -> the chosen profile name), both at install (UI) and on update (server). When the package is deleted and its integration is kept, because other installed packages use it or the package took it as it was, those entries are removed from the integration's configuration.metadata. Entries another installed package also recorded stay, and the integration is not saved when none of the package's entries is present. The integration checksum already leaves metadata out, so the remaining packages don't see the integration as changed. Co-Authored-By: Claude --- .../DefaultDevicePackageUpdateService.java | 19 +++- .../service/iot_hub/DefaultIotHubService.java | 67 ++++++++++++-- ...DefaultDevicePackageUpdateServiceTest.java | 6 +- .../iot_hub/DefaultIotHubServiceTest.java | 88 +++++++++++++++++++ .../device-install-dialog.component.ts | 9 +- 5 files changed, 180 insertions(+), 9 deletions(-) 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 index 2bbed29280..159014bdcd 100644 --- 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 @@ -293,7 +293,6 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List saved = new ArrayList<>(); List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); - // The checksums of the entities this update overwrote, which other packages may record too DashboardId dashboardId = null; for (DeviceUpdateRequest.Step step : request.getSteps()) { @@ -325,6 +324,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i 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); if (!"use-existing".equals(resolution)) { stepEntityIds.add(result.entityId()); @@ -612,6 +615,20 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); } + /** 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. 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 6968cbd00f..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; @@ -715,6 +717,7 @@ public class DefaultIotHubService implements IotHubService { * 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) { @@ -723,17 +726,20 @@ public class DefaultIotHubService implements IotHubService { return; } Set usedExisting = usedExistingIds(descriptor); - Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); + 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 { @@ -744,6 +750,52 @@ 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) { @@ -756,7 +808,7 @@ public class DefaultIotHubService implements IotHubService { int usedExistingCount = 0; if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { Set usedExisting = usedExistingIds(dd); - Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); + Map> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); for (EntityId entityId : dd.getCreatedEntityIds()) { Set usedBy = usedByOtherPackages.get(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId()); @@ -783,15 +835,20 @@ public class DefaultIotHubService implements IotHubService { return ids; } - private Map> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { + /** 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 && dd.getCreatedEntityIds() != null) { + 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())); } } 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 index 062eabf80f..57b11a2076 100644 --- 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 @@ -395,8 +395,10 @@ class DefaultDevicePackageUpdateServiceTest { // 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(); - assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText()) - .isEqualTo("use-existing"); + 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 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 938c816ed7..e8264499c3 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 @@ -8,6 +8,7 @@ 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; @@ -19,8 +20,10 @@ 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; @@ -28,12 +31,14 @@ 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; @@ -72,6 +77,8 @@ class DefaultIotHubServiceTest { private DashboardService dashboardService; @Mock private TbDashboardService tbDashboardService; + @Mock + private IntegrationService integrationService; @Spy @InjectMocks @@ -458,6 +465,71 @@ class DefaultIotHubServiceTest { 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()); + + verify(integrationService, never()).saveIntegration(any()); + verify(integrationService, never()).deleteIntegration(any(), any()); + } + + @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()); @@ -547,6 +619,22 @@ class DefaultIotHubServiceTest { 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)); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 9f79cbb59d..a75ed31fd8 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -1901,6 +1901,12 @@ export class TbDeviceInstallDialogComponent extends DialogComponent | undefined { + const entries = Object.entries(this.integrationMetadataOf(step) ?? {}).filter(([, value]) => value !== null); + return entries.length ? Object.fromEntries(entries) : undefined; + } + /** The INTEGRATION step's metadata entries, resolved: null for a self-mapping, whose earlier value is removed. */ private stepMetadataEntries(step: DeviceInstallStep): Record { const entries: Record = {}; @@ -2789,8 +2795,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent Date: Mon, 2 Nov 2026 15:54:34 +0200 Subject: [PATCH 42/66] IoT Hub: a confirm dialog updates a device package's default converter "New converter available" in Installed items opens "Update the converter?" instead of the version update wizard. The dialog names the converter and, from the update check, either warns that someone changed it (with a download of the current one) or lists the other installed packages that use it. Update sends only the converter step, built from ThingsBoard's default converter now, through the device package update. An update to the installed version itself keeps the install state of the steps and forms it leaves out, so the integration and its metadata stay as they are. The wizard's error message, text-with-link and JSON download helpers move to iot-hub-utils, and the installed device packages loader to iot-hub-default-converter, for both to use. Co-Authored-By: Claude --- .../DefaultDevicePackageUpdateService.java | 10 +++ ...DefaultDevicePackageUpdateServiceTest.java | 47 +++++++++++ .../device-install-dialog.component.ts | 36 +-------- .../iot-hub/iot-hub-actions.service.ts | 37 ++++++++- .../iot-hub/iot-hub-components.module.ts | 2 + ...hub-converter-update-dialog.component.html | 32 ++++++++ ...hub-converter-update-dialog.component.scss | 65 +++++++++++++++ ...t-hub-converter-update-dialog.component.ts | 79 +++++++++++++++++++ .../iot-hub/iot-hub-default-converter.ts | 68 +++++++++++++--- ...t-hub-installed-items-table.component.html | 2 +- ...iot-hub-installed-items-table.component.ts | 34 +++++--- .../home/components/iot-hub/iot-hub-utils.ts | 42 ++++++++++ .../assets/locale/locale.constant-en_US.json | 2 + 13 files changed, 398 insertions(+), 58 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.scss create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.ts 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 index 2bbed29280..06151fe139 100644 --- 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 @@ -348,6 +348,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } + // 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()); 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 index 062eabf80f..a3c7e7ca28 100644 --- 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 @@ -531,6 +531,53 @@ class DefaultDevicePackageUpdateServiceTest { 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()); diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 9f79cbb59d..29dca9d171 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -40,6 +40,7 @@ import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { ScriptLanguage } from '@shared/models/rule-node.models'; import { IntegrationType } from '@shared/models/integration.models'; import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter'; +import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils'; import { cleanFormFieldValue, DeviceInstallStep, @@ -119,15 +120,6 @@ export interface DeviceInstallUpdate { fromVersion: string; } -// ThingsBoard error codes whose message is written for the user: validation, permission, not found, limits -const SHOWN_ERROR_CODES = new Set([20, 30, 31, 32, 33, 34, 35, 40, 41]); -const MAX_SHOWN_ERROR_LENGTH = 200; - -/** The message as it is when it reads like one written for the user, null for an internal one (a stack trace, a URL, too long). */ -const readableMessage = (message: unknown): string | null => - typeof message === 'string' && message.trim() && message.length <= MAX_SHOWN_ERROR_LENGTH && - !/exception|java\.|https?:\/\/|\bat [\w.$]+\(/i.test(message) ? message : null; - // Fields the server sets, or that the update keeps as they are: they don't count as changes the user made. // Nor do the debug settings, which change nothing the entity does, and whether a profile is the default one. const SERVER_SET_KEYS = new Set(['id', 'name', 'title', 'routingKey', 'version', 'createdTime', 'tenantId', 'customerId', @@ -2014,18 +2006,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent…, which the translation may put anywhere in it, split around the link. */ /** Update: what the update did with the entity of a row, once it succeeded. */ updateOutcomeOf(plan: EntityStepPlan | undefined): string { if (!plan || plan.action === 'keep' || plan.resolution === 'use-existing') { @@ -2064,9 +2045,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent([\s\S]*)<\/a>([\s\S]*)$/.exec(text); - return match ? { before: match[1], link: match[2], after: match[3] } : { before: text, link: '', after: '' }; + return splitTextWithLink(this.translate.instant(key)); } /** Update: saves the entity the user changed, as it is before the update overwrites it, to a JSON file. */ @@ -2075,14 +2054,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent URL.revokeObjectURL(url), 0); + downloadEntityJson(current, ep.resolvedName || ep.step.name); } /** 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 f1d358426f..8dd87b637f 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,7 +3,7 @@ // 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 { 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'; @@ -21,6 +21,8 @@ import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallU 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 @@ -167,6 +169,39 @@ 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; + const [states, packages] = await Promise.all([ + firstValueFrom(this.iotHubApiService.checkDeviceUpdate(installedItemId)), + loadInstalledDevicePackages(this.iotHubApiService) + ]); + 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, version: state?.version, modified: state?.modified === true, usedBy }; + } + deleteItem(installedItem: IotHubInstalledItem): Observable { if (!installedItem) { return of(false); 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..a629614e50 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-converter-update-dialog.component.html @@ -0,0 +1,32 @@ + +
+

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

+

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

+
+
{{ data.update.converter.name }}
+ @if (data.modified) { + + {{ modifiedHint.before }}{{ modifiedHint.link }}{{ modifiedHint.after }} + + } @else if (data.usedBy.length) { + {{ 'iot-hub.device-update-shared' | translate }} +
    + @for (name of data.usedBy; track $index) { +
  • {{ name }}
  • + } +
+ } +
+ @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..2d54d12bba --- /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 The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +: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..a6736965a4 --- /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 The ThingsBoard Authors +// SPDX-License-Identifier: Apache-2.0 +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 converter's version the update check found: 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.converter-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 index 68aeb0f832..acbd246df8 100644 --- 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 @@ -6,11 +6,20 @@ import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetT import { IntegrationType } from '@shared/models/integration.models'; import { ScriptLanguage } from '@shared/models/rule-node.models'; import { isEqual } from '@core/utils'; -import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +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 @@ -60,6 +69,19 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert 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 @@ -67,18 +89,40 @@ export const differsFromDefaultConverter = (converter: Converter, defaultConvert */ export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise> => { const ids = new Set(); - let pageLink = new PageLink(100); - let page: PageData; - do { - page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); - for (const item of page.data) { - 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); - } + 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); } } - pageLink = pageLink.nextPageLink(); - } while (page.hasNext); + } 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-installed-items-table.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html index db7ad21423..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 @@ -57,7 +57,7 @@ }
} @else if (hasConverterUpdate(item)) { - +