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 380f372ea7..db5dc64379 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; @@ -286,6 +288,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()) { @@ -314,6 +318,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(resolution)) { stepEntityIds.add(result.entityId()); @@ -348,12 +358,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 0d6bed9f0f..7b02a966fa 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 @@ -349,6 +352,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()); @@ -457,6 +494,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"))) @@ -478,6 +531,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 fc1718b108..77fef10a5e 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)) }; @@ -2093,6 +2146,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 { @@ -2358,12 +2462,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent !isEqual( this.resolvePackageFile(this.zipFiles, step[file], this.formValues), this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues) @@ -2433,6 +2540,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.",