Browse Source

Merge branch 'feature/lts-4.4/iot-hub-lorawan-converter-profile' into fix/iot-hub-device-update-in-place-lts-4.4

pull/16466/head
dpinkevych 1 month ago
parent
commit
e73d452d57
Failed to extract signature
  1. 53
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  2. 2
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  3. 5
      application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java
  4. 29
      application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java
  5. 64
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  6. 6
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  7. 138
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  8. 8
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html
  9. 12
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts
  10. 57
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  11. 40
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  12. 52
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  13. 6
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  14. 2
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  15. 12
      ui-ngx/src/assets/converters/js-tti-decoder.raw
  16. 12
      ui-ngx/src/assets/converters/js-ttn-decoder.raw
  17. 12
      ui-ngx/src/assets/converters/tbel-tti-decoder.raw
  18. 12
      ui-ngx/src/assets/converters/tbel-ttn-decoder.raw
  19. 2
      ui-ngx/src/assets/locale/locale.constant-en_US.json

53
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<SavedEntity> saved = new ArrayList<>();
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>();
List<StepAttributes> attributes = new ArrayList<>();
// The checksums of the entities this update overwrote, which other packages may record too
Map<UUID, String> 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<StepAttributes> 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<UUID, String> checksums) {
if (checksums.isEmpty()) {
return;
}
PageLink pageLink = new PageLink(100);
PageData<IotHubInstalledItem> 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<String, JsonNode> installState, Map<UUID, String> 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.

2
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;
}
}

5
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('|');
}

29
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<String, String> 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<String, String> 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<String, String> 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));
}

64
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<String, JsonNode> installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState);
IotHubInstalledItem item = new IotHubInstalledItem();
item.setId(new IotHubInstalledItemId(UUID.randomUUID()));
item.setTenantId(tenantId);
item.setItemType("DEVICE");
item.setDescriptor(descriptor);
return item;
}
private DeviceProfile profile(Long version, String name) {
DeviceProfile profile = new DeviceProfile(profileId);
profile.setTenantId(tenantId);

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

@ -177,6 +177,9 @@
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">{{ label }}</span>
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
@ -252,6 +255,9 @@
</div>
<!-- A confirmed warning stays visible: the status says the conflict is resolved, the hint what happens -->
@if (ws.reviewing && plan?.confirmed) {
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-existing-' + plan.resolution | translate }}</span>
}

138
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<TbDeviceInst
private previousFiles = new Map<string, string>();
private previousPackageInfo: DevicePackageInfo | null = null;
private entityPlans = new WeakMap<EntityStepProgress, EntityStepPlan>();
// Update: for each step with "default": true, whether its converter differs from ThingsBoard's default one now
private defaultConverterChanges = new Map<DeviceInstallStep, boolean>();
// Variable resolution state
formValues: Record<string, any> = {};
@ -397,7 +408,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private integrationService: IntegrationService,
private aiDashboardGenerationService: AiDashboardGenerationService,
private dialogService: DialogService,
private translate: TranslateService
private translate: TranslateService,
private resourcesService: ResourcesService
) {
super(store, router, dialogRef);
}
@ -407,6 +419,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
try {
await this.loadPackageFiles(this.data.item.id as string, this.zipFiles, this.zipImages);
this.packageInfo = JSON.parse(this.zipFiles.get('device-info.json'));
await this.addDefaultConverters();
this.availableInstallMethods = this.packageInfo.installMethods.filter(
ct => this.packageInfo.installSteps[ct]?.length > 0
);
@ -440,6 +453,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// Update: the package keeps the method it was installed with
this.selectedInstallMethod = this.data.update.descriptor.selectedInstallMethod;
await this.loadPreviousVersion();
await this.checkDefaultConverters();
if (this.isTextOnlyUpdate() && await this.registerTextOnlyUpdate()) {
return;
}
@ -1588,7 +1602,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!body.routingKey) body.routingKey = this.pendingRoutingKey;
if (!body.configuration) body.configuration = {};
if (body.configuration.metadata == null) body.configuration.metadata = {};
body.configuration.metadata = this.withStepMetadata(step, body.configuration.metadata);
const result = await firstValueFrom(
this.integrationService.saveIntegration(body, { ignoreErrors: true })
@ -1785,7 +1799,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
body.id = { id: existing.id, entityType: 'INTEGRATION' };
body.routingKey = this.pendingRoutingKey;
if (!body.configuration) body.configuration = {};
if (body.configuration.metadata == null) body.configuration.metadata = {};
const current = await firstValueFrom(this.integrationService.getIntegration(existing.id, {ignoreErrors: true}));
body.configuration.metadata = this.withStepMetadata(step,
{ ...current?.configuration?.metadata, ...body.configuration.metadata });
const result = await firstValueFrom(
this.integrationService.saveIntegration(body, { ignoreErrors: true })
@ -1802,6 +1818,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/** A device or gateway taken as it is: the token comes from its current credentials. */
private async useExistingEntity(step: DeviceInstallStep, existing: EntityStepOutput): Promise<EntityStepOutput> {
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<TbDeviceInst
return output;
}
/**
* The integration's metadata with the INTEGRATION step's entries added. The entries it has stay, so the packages on
* one integration keep each other's. An entry that maps a name to itself, as profile.<name>: <name> does when the
* user kept the default profile name, isn't added.
*/
private withStepMetadata(step: DeviceInstallStep, metadata: Record<string, string> | null | undefined): Record<string, string> {
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<EntityStepOutput> {
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<TbDeviceInst
fromVersionId: this.data.update.fromVersionId,
selectedInstallMethod: this.selectedInstallMethod,
installState: this.buildFormState(),
steps: this.buildUpdateSteps(ws)
steps: await this.buildUpdateSteps(ws)
}, { ignoreLoading: true, ignoreErrors: true }));
} catch (e: any) {
result = { success: false, errorMessage: this.failureMessage(e) };
@ -2053,7 +2101,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
/** Update: the steps the server applies, each with its entity resolved from the template of the new version. */
private buildUpdateSteps(ws: WizardStep): DeviceUpdateStep[] {
private async buildUpdateSteps(ws: WizardStep): Promise<DeviceUpdateStep[]> {
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<TbDeviceInst
this.entityOutputs.delete(alias);
}
}
return ws.entitySteps.map(ep => 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<DeviceUpdateStep> {
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<TbDeviceInst
}
const overwritten = plan.action === 'overwrite' ? plan.previous.output : plan.resolution === 'overwrite' ? plan.existing : null;
const entity = this.buildEntityBody(ws, step, overwritten);
if (step.type === InstallStepType.INTEGRATION) {
// An overwritten integration keeps the metadata it has, e.g. other packages' profile names
const current = overwritten ?
await firstValueFrom(this.integrationService.getIntegration(overwritten.id, {ignoreErrors: true})) : null;
entity.configuration.metadata = this.withStepMetadata(step, { ...current?.configuration?.metadata, ...entity.configuration.metadata });
}
// As at install, the entity gets the step's attributes
const attributes = {
serverAttributes: this.resolvePackageFile(this.zipFiles, step.serverAttributes, this.formValues),
@ -2192,6 +2251,51 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
}
/**
* A converter step with "default": true takes the converter ThingsBoard creates for a new integration of the method's
* type (INTEGRATION_TTN: TTN). It becomes the step's template, so it installs, overwrites and updates like a file of the package.
*/
private async addDefaultConverters(): Promise<void> {
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<void> {
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<void> {
try {
@ -2358,12 +2462,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
/** Update: true when the new version's files give the entity something else than the installed version's gave it. */
private entityStepChanged(step: DeviceInstallStep): boolean {
if (this.defaultConverterChanges.has(step)) {
return this.defaultConverterChanges.get(step);
}
const previousStep = this.findPreviousStep(step);
if (!previousStep) {
return true;
}
const previousFormValues = this.previousFormValues();
const files: (keyof DeviceInstallStep)[] = ['template', 'serverAttributes', 'sharedAttributes', 'credentials'];
const files: ('template' | 'serverAttributes' | 'sharedAttributes' | 'credentials')[] = ['template', 'serverAttributes', 'sharedAttributes', 'credentials'];
return files.some(file => !isEqual(
this.resolvePackageFile(this.zipFiles, step[file], this.formValues),
this.resolvePackageFile(this.previousFiles, previousStep[file], previousFormValues)
@ -2433,6 +2540,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (previous) {
// Its current name: the user may have renamed it
ep.resolvedName = previous.output.name;
const newDefaultConverter = this.defaultConverterChanges.get(step);
// The default converter of a package that took another package's converter is that package's: the update
// of either brings it to ThingsBoard's default, which changes it for both
if (previous.useExisting && newDefaultConverter) {
const current = await this.loadEntitySnapshot(step, previous.output.id);
return { action: 'overwrite', previous, shared: true, confirmed: false, version: current.version, newDefaultConverter };
}
// The device and its credentials, which the firmware uses, never change on update
if (previous.useExisting || step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) {
return { action: 'keep', previous, confirmed: true };
@ -2451,7 +2565,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
action: 'overwrite', previous, shared: previous.shared, modified: modified && !previous.shared,
confirmed: !previous.shared && !modified,
version,
current: modified && !previous.shared ? current : undefined
current: modified && !previous.shared ? current : undefined,
newDefaultConverter
};
}
// New in this version, or deleted since: created as at install, with the same name conflict check
@ -2580,7 +2695,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} else if (ws.type === 'progress' && ws.entitySteps) {
for (const ep of ws.entitySteps) {
if (ep.status === 'success' && ep.entityOutput) {
state[ep.step.id ?? ep.step.name] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created' };
state[ep.step.id ?? ep.step.name] = { entityOutput: ep.entityOutput, resolution: ep.resolution || 'created',
...(ep.step.default ? { defaultConverter: true } : {}) };
}
}
}

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

@ -205,6 +205,14 @@
<mat-icon>autorenew</mat-icon>
</button>
}
@if (canResetToDefault(field)) {
<button mat-icon-button matSuffix type="button"
[matTooltip]="'action.reset-default' | translate"
matTooltipPosition="above"
(click)="resetToDefault(field)">
<tb-icon>mdi:broom</tb-icon>
</button>
}
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
}

12
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;

57
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<Partial<Converter> | null> => {
const configurations = await firstValueFrom(
resourcesService.loadJsonResource<Record<string, ConverterConfigV2>>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL));
const configuration = configurations?.[integrationType];
if (!configuration) {
return null;
}
const script = await firstValueFrom(resourcesService.loadJsonResource<string>(
getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2)));
return {
name,
type: ConverterType.UPLINK,
integrationType,
converterVersion: 2,
edgeTemplate: false,
// As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing
debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 },
configuration: {
...configuration,
scriptLang,
decoder: null,
tbelDecoder: null,
encoder: null,
tbelEncoder: null,
[getTargetField(ConverterType.UPLINK, scriptLang)]: script
},
additionalInfo: { description: '' }
};
};
/** True when the converter does something else than the default one: another script or other settings. */
export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial<Converter>): boolean => {
const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang);
const script = (value: string) => (value ?? '').trimEnd();
return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) ||
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null));
};

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

@ -42,26 +42,26 @@
<th mat-header-cell *matHeaderCellDef>@if (updatesChecked) { {{ 'iot-hub.updates' | translate }} }</th>
<td mat-cell *matCellDef="let item">
@if (updatesChecked) {
@if (getPublishedVersionInfo(item); as pubInfo) {
@if (pubInfo.publishedVersionId !== item.itemVersionId) {
<div class="flex items-center gap-3">
@if (!itemVersion) {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
<mat-icon>arrow_upward</mat-icon>
v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
</button>
} @else {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
{{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }}
</button>
}
</div>
} @else {
<span class="tb-installed-up-to-date">
<mat-icon>check</mat-icon>
{{ 'iot-hub.up-to-date' | translate }}
</span>
}
@let pubInfo = getPublishedVersionInfo(item);
@if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) {
<div class="flex items-center gap-3">
@if (!itemVersion) {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
<mat-icon>arrow_upward</mat-icon>
v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
</button>
} @else {
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
{{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }}
</button>
}
</div>
} @else if (hasConverterUpdate(item)) {
<!-- The update of the same version: only ThingsBoard's default converter changed -->
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateConverter(item)">
<mat-icon>arrow_upward</mat-icon>
{{ 'iot-hub.new-converter-available' | translate }}
</button>
} @else {
<span class="tb-installed-up-to-date">
<mat-icon>check</mat-icon>

52
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<string, ItemPublishedVersionInfo>();
// Installed device packages whose default converter differs from ThingsBoard's default converter now
converterUpdates = new Set<string>();
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<void> {
const updates = new Set<string>();
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 = [];

6
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<string, string>;
}
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.

2
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 {

12
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 <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. 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 } };
}

12
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 <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. 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 } };
}

12
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 <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. 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 } };
}

12
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 <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. 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 } };
}

2
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 <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.",
"device-update-existing-use-existing": "Already exists. The existing one will be used.",

Loading…
Cancel
Save