committed by
GitHub
105 changed files with 7532 additions and 748 deletions
File diff suppressed because it is too large
@ -0,0 +1,119 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.HasVersion; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.DeviceProfileId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.IntegrationId; |
|||
import org.thingsboard.server.common.data.id.RuleChainId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.integration.IntegrationService; |
|||
import org.thingsboard.server.dao.rule.RuleChainService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway |
|||
* and a gateway connector don't have one: an update never changes them. |
|||
*/ |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class DevicePackageEntities { |
|||
|
|||
static final Set<EntityType> CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD, |
|||
EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION); |
|||
|
|||
private final DeviceProfileService deviceProfileService; |
|||
private final DashboardService dashboardService; |
|||
private final RuleChainService ruleChainService; |
|||
private final ConverterService converterService; |
|||
private final IntegrationService integrationService; |
|||
|
|||
/** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */ |
|||
public Snapshot load(TenantId tenantId, EntityId entityId) { |
|||
Object entity = switch (entityId.getEntityType()) { |
|||
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId); |
|||
case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId); |
|||
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId); |
|||
case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId); |
|||
case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId); |
|||
default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType()); |
|||
}; |
|||
if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) { |
|||
return null; |
|||
} |
|||
Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null; |
|||
return new Snapshot(entity, metadata); |
|||
} |
|||
|
|||
public String checksum(TenantId tenantId, EntityId entityId) { |
|||
Snapshot snapshot = load(tenantId, entityId); |
|||
return snapshot != null ? snapshot.checksum() : null; |
|||
} |
|||
|
|||
/** |
|||
* Adds the checksum of each entity the install state names, so that an update can tell whether someone changed |
|||
* it since. Entities the user kept at install are left out: an update never overwrites them. |
|||
*/ |
|||
public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { |
|||
if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) { |
|||
return; |
|||
} |
|||
Map<UUID, EntityId> createdIds = new HashMap<>(); |
|||
descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id)); |
|||
descriptor.getInstallState().forEach((stepName, state) -> { |
|||
EntityId entityId = entityIdOf(state, createdIds); |
|||
if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) { |
|||
String checksum = checksum(tenantId, entityId); |
|||
if (checksum != null) { |
|||
((ObjectNode) state).put("checksum", checksum); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
|
|||
/** The package entity an install-state step recorded, with its type from the ids the package created. */ |
|||
static EntityId entityIdOf(JsonNode state, Map<UUID, EntityId> createdIds) { |
|||
JsonNode id = state != null ? state.path("entityOutput").path("id") : null; |
|||
if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) { |
|||
return null; |
|||
} |
|||
try { |
|||
return createdIds.get(UUID.fromString(id.asText())); |
|||
} catch (IllegalArgumentException e) { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
public record Snapshot(Object entity, Object metadata) { |
|||
|
|||
public Long version() { |
|||
return ((HasVersion) entity).getVersion(); |
|||
} |
|||
|
|||
public String checksum() { |
|||
return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity); |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
|
|||
/** An entity of an installed device package as an update finds it, before it changes anything. */ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DevicePackageEntityState { |
|||
|
|||
private String stepName; |
|||
private EntityId entityId; |
|||
private boolean exists; |
|||
// Sent back with the update, which fails if someone changed the entity in between
|
|||
private Long version; |
|||
// Changed since the package installed or last updated it; null when the install state has no checksum of it
|
|||
// (installed before checksums were kept)
|
|||
private Boolean modified; |
|||
// Other installed device packages use it, so overwriting it affects them
|
|||
private boolean shared; |
|||
|
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** Updates an installed device package to another version of its item. */ |
|||
public interface DevicePackageUpdateService { |
|||
|
|||
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */ |
|||
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId); |
|||
|
|||
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ |
|||
DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); |
|||
|
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.Data; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The update of an installed device package as the install wizard planned it: the entity of each install step |
|||
* of the new version, already resolved from its template, and what to do with it. The server applies all of it |
|||
* in one transaction, together with the new version of the installed item, or nothing. |
|||
*/ |
|||
@Data |
|||
public class DeviceUpdateRequest { |
|||
|
|||
private String versionId; |
|||
// The version installed when the wizard planned the update; the update fails if the package changed since
|
|||
private UUID fromVersionId; |
|||
// The install method of the new version's steps; the installed one when not set
|
|||
private String selectedInstallMethod; |
|||
// The form values of the install state, by step: the server adds the entities to it
|
|||
private Map<String, JsonNode> installState; |
|||
private List<Step> steps; |
|||
|
|||
public enum Action { |
|||
// Taken as it is: the new version doesn't change it, or the user kept an entity they had
|
|||
KEEP, |
|||
// Takes the entity from the step
|
|||
OVERWRITE, |
|||
// A new entity: new in this version, deleted since install, or a copy next to one with the same name
|
|||
CREATE |
|||
} |
|||
|
|||
@Data |
|||
public static class Step { |
|||
private String name; |
|||
// The package step's id, which keys its install state; the name when not set
|
|||
private String id; |
|||
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
|
|||
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
|
|||
private String type; |
|||
private Action action; |
|||
// KEEP and OVERWRITE: the entity
|
|||
private UUID entityId; |
|||
// OVERWRITE: the version the user reviewed; a different one means someone changed the entity since
|
|||
private Long expectedVersion; |
|||
// The user confirmed overwriting an entity of another package or one they didn't install with this package
|
|||
private boolean confirmed; |
|||
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this
|
|||
// update creates is left for the server, which knows its id only once it is created.
|
|||
private JsonNode entity; |
|||
// DEVICE and GATEWAY: the credentials template, if any
|
|||
private JsonNode credentials; |
|||
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
|
|||
// they may keep ${<alias>.<property>} of an entity this update creates.
|
|||
private JsonNode serverAttributes; |
|||
private JsonNode sharedAttributes; |
|||
// The resolution the install state records for it
|
|||
private String resolution; |
|||
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
|
|||
// integration, e.g. one the package took as it was; null removes an entry
|
|||
private JsonNode metadata; |
|||
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
|
|||
private boolean defaultConverter; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,37 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
|
|||
import java.util.Map; |
|||
|
|||
/** |
|||
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep |
|||
* names the step that failed, if one did. |
|||
*/ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DeviceUpdateResult { |
|||
|
|||
private boolean success; |
|||
private String errorMessage; |
|||
private String failedStep; |
|||
private DeviceInstalledItemDescriptor descriptor; |
|||
// By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
|
|||
private Map<String, ObjectNode> outputs; |
|||
|
|||
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { |
|||
return new DeviceUpdateResult(true, null, null, descriptor, outputs); |
|||
} |
|||
|
|||
public static DeviceUpdateResult error(String errorMessage, String failedStep) { |
|||
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,116 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ArrayNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.rule.RuleChainMetaData; |
|||
import org.thingsboard.server.common.data.rule.RuleNode; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.security.MessageDigest; |
|||
import java.security.NoSuchAlgorithmException; |
|||
import java.util.ArrayList; |
|||
import java.util.HexFormat; |
|||
import java.util.Iterator; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* The checksum of an entity as the server stores it, kept in the install state of a device package. A different |
|||
* checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name, |
|||
* which an update keeps, don't count, nor do the debug settings, which the user turns on without changing what the |
|||
* entity does, and whether a profile is the default one, which changes when another profile becomes the default. |
|||
*/ |
|||
final class EntityChecksum { |
|||
|
|||
private static final Set<String> SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId", |
|||
"customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources", "debugMode", "debugSettings", "default"); |
|||
|
|||
private EntityChecksum() { |
|||
} |
|||
|
|||
/** A rule chain is checked with its metadata: pass both. */ |
|||
static String of(Object... parts) { |
|||
StringBuilder canonical = new StringBuilder(); |
|||
for (Object part : parts) { |
|||
JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part); |
|||
if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) { |
|||
// Device packages on one integration add their entries to its metadata: that is no change to the integration
|
|||
configuration.remove("metadata"); |
|||
} |
|||
appendCanonical(canonical, node, true); |
|||
canonical.append('|'); |
|||
} |
|||
try { |
|||
byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8)); |
|||
return HexFormat.of().formatHex(hash); |
|||
} catch (NoSuchAlgorithmException e) { |
|||
throw new IllegalStateException(e); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and |
|||
* configuration, and the connections. Node ids, layout and debug settings change without the user changing |
|||
* what the rule chain does, e.g. when it is saved again. |
|||
*/ |
|||
private static JsonNode ruleChainContent(RuleChainMetaData metadata) { |
|||
ObjectNode content = JacksonUtil.newObjectNode(); |
|||
ArrayNode nodes = content.putArray("nodes"); |
|||
if (metadata.getNodes() != null) { |
|||
for (RuleNode node : metadata.getNodes()) { |
|||
ObjectNode n = nodes.addObject(); |
|||
n.put("type", node.getType()); |
|||
n.put("name", node.getName()); |
|||
n.set("configuration", node.getConfiguration()); |
|||
n.put("singletonMode", node.isSingletonMode()); |
|||
n.put("queueName", node.getQueueName()); |
|||
} |
|||
} |
|||
content.set("connections", JacksonUtil.valueToTree(metadata.getConnections())); |
|||
content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections())); |
|||
content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex())); |
|||
return content; |
|||
} |
|||
|
|||
/** JSON with the keys sorted, so the same entity always gives the same text. */ |
|||
private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) { |
|||
if (node == null || node.isNull() || node.isMissingNode()) { |
|||
out.append("null"); |
|||
} else if (node.isObject()) { |
|||
List<String> keys = new ArrayList<>(); |
|||
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) { |
|||
String key = it.next(); |
|||
if (!topLevel || !SKIPPED_KEYS.contains(key)) { |
|||
keys.add(key); |
|||
} |
|||
} |
|||
keys.sort(null); |
|||
out.append('{'); |
|||
for (int i = 0; i < keys.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
out.append(JacksonUtil.toString(keys.get(i))).append(':'); |
|||
appendCanonical(out, node.get(keys.get(i)), false); |
|||
} |
|||
out.append('}'); |
|||
} else if (node.isArray()) { |
|||
out.append('['); |
|||
for (int i = 0; i < node.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
appendCanonical(out, node.get(i), false); |
|||
} |
|||
out.append(']'); |
|||
} else { |
|||
out.append(node.toString()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class InstalledItemKeptEntities { |
|||
|
|||
private List<KeptEntity> entities; |
|||
// How many other installed items use at least one of the kept entities
|
|||
private int usedByItemsCount; |
|||
// How many of the kept entities the user had before and the package took as they were (use existing)
|
|||
private int usedExistingCount; |
|||
|
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public static class KeptEntity { |
|||
private EntityId entityId; |
|||
private String name; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,10 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.security.system; |
|||
|
|||
/** |
|||
* Base URL as returned by {@link SystemSecurityService#getBaseUrl}, and whether it was built from |
|||
* the request rather than taken from the Base URL in General settings. |
|||
*/ |
|||
public record ResolvedBaseUrl(String url, boolean fromRequest) { |
|||
} |
|||
@ -1,79 +1,69 @@ |
|||
/** |
|||
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes. |
|||
* |
|||
* @param {byte[]} input - The raw payload received as an array of bytes. |
|||
* @returns {Object} output - The structured output with decoded telemetry and attributes. |
|||
*/ |
|||
|
|||
function decodePayload(input) { |
|||
// Initialize the output object with empty attributes and telemetry for clarity. |
|||
var result = { attributes: {}, telemetry: {}}; |
|||
|
|||
// Detect input type and normalize to byte array |
|||
var bytes; |
|||
|
|||
if (metadata.payloadFormat == 'JSON') { |
|||
// payloadFormat is 'JSON' when The Things Industries payload formatters are configured on the application or device level. |
|||
// In that case, decoded_payload is a JSON object produced by your formatter. |
|||
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array. |
|||
// If your formatter returns pre-decoded values in a different structure, |
|||
// update this section to extract the values directly from 'parsed' instead. |
|||
var parsed = decodeToJson(input); |
|||
if (parsed.bytes == null) { |
|||
throw new Error("Payload formatter output does not contain a 'bytes' field. " + |
|||
"Update this decoder to match your formatter's output structure."); |
|||
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload |
|||
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. |
|||
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it, |
|||
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. |
|||
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds |
|||
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the |
|||
// integration writes them from version_ids. Any other device gets LoRaWAN Device. |
|||
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as |
|||
// attributes, not telemetry: device information and settings. |
|||
var values = {}; |
|||
var attributes = {}; |
|||
var history = []; |
|||
var versionIds = null; |
|||
if (metadata.payloadFormat == "JSON") { |
|||
values = decodeToJson(payload); |
|||
if (values.history instanceof java.util.List) { |
|||
foreach (record : values.history) { |
|||
if (record.timestamp != null) { |
|||
var ts = record.timestamp * 1000; |
|||
record.remove("timestamp"); |
|||
history.add({ ts: ts, values: record }); |
|||
} |
|||
} |
|||
bytes = parsed.bytes; |
|||
} else { |
|||
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. |
|||
bytes = input; |
|||
values.remove("history"); |
|||
} |
|||
|
|||
// Decode serial number (SN) from the first 4 bytes of the payload. |
|||
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. |
|||
result.attributes.sn = parseBytesToInt(bytes, 0, 4); |
|||
|
|||
// Extract the timestamp from metadata (represented in milliseconds). |
|||
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. |
|||
|
|||
// Combine the timestamp with decoded values and add it to the telemetry. |
|||
result.telemetry = { |
|||
ts: timestamp, |
|||
values: { |
|||
// Decode battery level from the 5th byte of the payload. |
|||
battery: parseBytesToInt(bytes, 4, 1), |
|||
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100). |
|||
temperature: parseBytesToInt(bytes, 5, 2) / 100.0, |
|||
// Decode saturation from the 8th byte of the payload. |
|||
saturation: parseBytesToInt(bytes, 7, 1) |
|||
if (values.containsKey("tbVersionIds")) { |
|||
versionIds = values.tbVersionIds; |
|||
values.remove("tbVersionIds"); |
|||
} |
|||
} |
|||
var brandId = metadata.brandId; |
|||
var modelId = metadata.modelId; |
|||
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) { |
|||
brandId = versionIds.brand_id; |
|||
modelId = versionIds.model_id; |
|||
if (brandId != null && modelId != null) { |
|||
attributes.put("brandId", brandId); |
|||
attributes.put("modelId", modelId); |
|||
} |
|||
} |
|||
var profile = "LoRaWAN Device"; |
|||
if (brandId != null && modelId != null) { |
|||
var model = brandId + "-" + modelId; |
|||
profile = model; |
|||
// The profile name chosen at install, kept in the integration metadata |
|||
var customProfile = metadata["profile." + model]; |
|||
if (customProfile != null && customProfile != "") { |
|||
profile = customProfile; |
|||
} |
|||
var attributeKeys = metadata["attributes." + model]; |
|||
if (attributeKeys != null && attributeKeys != "") { |
|||
foreach (item : attributeKeys.split(",")) { |
|||
var key = item.trim(); |
|||
if (key != "" && values.containsKey(key)) { |
|||
attributes.put(key, values.get(key)); |
|||
values.remove(key); |
|||
} |
|||
} |
|||
}; |
|||
|
|||
// Return the fully constructed output object. |
|||
return result; |
|||
// Same logic, less code: |
|||
// return { |
|||
// attributes: { |
|||
// sn: parseBytesToInt(bytes, 0, 4) |
|||
// }, |
|||
// telemetry: { |
|||
// ts: convertDateToTimestamp(extractDateFromMetadata()), |
|||
// values: { |
|||
// battery: parseBytesToInt(bytes, 4, 1), |
|||
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0, |
|||
// saturation: parseBytesToInt(bytes, 7, 1) |
|||
// } |
|||
// } |
|||
// }; |
|||
} |
|||
} |
|||
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } }; |
|||
if (!history.isEmpty()) { |
|||
history.add({ ts: metadata.ts, values: values }); |
|||
result.telemetry = history; |
|||
} |
|||
if (!attributes.isEmpty()) { |
|||
result.attributes = attributes; |
|||
} |
|||
|
|||
var result = decodePayload(payload); |
|||
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; |
|||
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. |
|||
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) |
|||
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. |
|||
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. |
|||
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. |
|||
|
|||
// Return the final result object. |
|||
return result; |
|||
|
|||
@ -1,79 +1,69 @@ |
|||
/** |
|||
* Decodes the incoming payload and returns a structured object containing telemetry data and attributes. |
|||
* |
|||
* @param {byte[]} input - The raw payload received as an array of bytes. |
|||
* @returns {Object} output - The structured output with decoded telemetry and attributes. |
|||
*/ |
|||
|
|||
function decodePayload(input) { |
|||
// Initialize the output object with empty attributes and telemetry for clarity. |
|||
var result = { attributes: {}, telemetry: {}}; |
|||
|
|||
// Detect input type and normalize to byte array |
|||
var bytes; |
|||
|
|||
if (metadata.payloadFormat == 'JSON') { |
|||
// payloadFormat is 'JSON' when The Things Network payload formatters are configured on the application or device level. |
|||
// In that case, decoded_payload is a JSON object produced by your formatter. |
|||
// This template assumes the formatter returns { "bytes": [...] } with the raw byte array. |
|||
// If your formatter returns pre-decoded values in a different structure, |
|||
// update this section to extract the values directly from 'parsed' instead. |
|||
var parsed = decodeToJson(input); |
|||
if (parsed.bytes == null) { |
|||
throw new Error("Payload formatter output does not contain a 'bytes' field. " + |
|||
"Update this decoder to match your formatter's output structure."); |
|||
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload |
|||
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. |
|||
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it, |
|||
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. |
|||
// A device that is not in the Repository can name its model in decoded_payload: its payload formatter adds |
|||
// tbVersionIds: { brand_id, model_id }, which is not telemetry; they become the attributes brandId and modelId, as the |
|||
// integration writes them from version_ids. Any other device gets LoRaWAN Device. |
|||
// The keys the integration metadata lists under attributes.<brand_id>-<model_id> (comma-separated) are saved as |
|||
// attributes, not telemetry: device information and settings. |
|||
var values = {}; |
|||
var attributes = {}; |
|||
var history = []; |
|||
var versionIds = null; |
|||
if (metadata.payloadFormat == "JSON") { |
|||
values = decodeToJson(payload); |
|||
if (values.history instanceof java.util.List) { |
|||
foreach (record : values.history) { |
|||
if (record.timestamp != null) { |
|||
var ts = record.timestamp * 1000; |
|||
record.remove("timestamp"); |
|||
history.add({ ts: ts, values: record }); |
|||
} |
|||
} |
|||
bytes = parsed.bytes; |
|||
} else { |
|||
// payloadFormat is 'BINARY' when no payload formatter is configured — raw bytes from frm_payload are passed directly. |
|||
bytes = input; |
|||
values.remove("history"); |
|||
} |
|||
|
|||
// Decode serial number (SN) from the first 4 bytes of the payload. |
|||
// Press '?' icon in the top right corner to learn more about built in helper functions and capabilities. |
|||
result.attributes.sn = parseBytesToInt(bytes, 0, 4); |
|||
|
|||
// Extract the timestamp from metadata (represented in milliseconds). |
|||
var timestamp = metadata.ts; // ts is the timestamp parsed from the incoming message's time, or returns the current time if it cannot be parsed. |
|||
|
|||
// Combine the timestamp with decoded values and add it to the telemetry. |
|||
result.telemetry = { |
|||
ts: timestamp, |
|||
values: { |
|||
// Decode battery level from the 5th byte of the payload. |
|||
battery: parseBytesToInt(bytes, 4, 1), |
|||
// Decode temperature from the 6th and 7th bytes of the payload (divided by 100). |
|||
temperature: parseBytesToInt(bytes, 5, 2) / 100.0, |
|||
// Decode saturation from the 8th byte of the payload. |
|||
saturation: parseBytesToInt(bytes, 7, 1) |
|||
if (values.containsKey("tbVersionIds")) { |
|||
versionIds = values.tbVersionIds; |
|||
values.remove("tbVersionIds"); |
|||
} |
|||
} |
|||
var brandId = metadata.brandId; |
|||
var modelId = metadata.modelId; |
|||
if ((brandId == null || modelId == null) && versionIds instanceof java.util.Map) { |
|||
brandId = versionIds.brand_id; |
|||
modelId = versionIds.model_id; |
|||
if (brandId != null && modelId != null) { |
|||
attributes.put("brandId", brandId); |
|||
attributes.put("modelId", modelId); |
|||
} |
|||
} |
|||
var profile = "LoRaWAN Device"; |
|||
if (brandId != null && modelId != null) { |
|||
var model = brandId + "-" + modelId; |
|||
profile = model; |
|||
// The profile name chosen at install, kept in the integration metadata |
|||
var customProfile = metadata["profile." + model]; |
|||
if (customProfile != null && customProfile != "") { |
|||
profile = customProfile; |
|||
} |
|||
var attributeKeys = metadata["attributes." + model]; |
|||
if (attributeKeys != null && attributeKeys != "") { |
|||
foreach (item : attributeKeys.split(",")) { |
|||
var key = item.trim(); |
|||
if (key != "" && values.containsKey(key)) { |
|||
attributes.put(key, values.get(key)); |
|||
values.remove(key); |
|||
} |
|||
} |
|||
}; |
|||
|
|||
// Return the fully constructed output object. |
|||
return result; |
|||
// Same logic, less code: |
|||
// return { |
|||
// attributes: { |
|||
// sn: parseBytesToInt(bytes, 0, 4) |
|||
// }, |
|||
// telemetry: { |
|||
// ts: convertDateToTimestamp(extractDateFromMetadata()), |
|||
// values: { |
|||
// battery: parseBytesToInt(bytes, 4, 1), |
|||
// temperature: parseBytesToInt(bytes, 5, 2) / 100.0, |
|||
// saturation: parseBytesToInt(bytes, 7, 1) |
|||
// } |
|||
// } |
|||
// }; |
|||
} |
|||
} |
|||
var result = { profile: profile, telemetry: { ts: metadata.ts, values: values } }; |
|||
if (!history.isEmpty()) { |
|||
history.add({ ts: metadata.ts, values: values }); |
|||
result.telemetry = history; |
|||
} |
|||
if (!attributes.isEmpty()) { |
|||
result.attributes = attributes; |
|||
} |
|||
|
|||
var result = decodePayload(payload); |
|||
// Uncomment this code block to overwrite values set in the main configuration window. Useful if you extract device/asset/customer/group names from the payload; |
|||
// result.type = 'DEVICE'; // Entity type allows you to choose type of created entity. Can be 'DEVICE' or 'ASSET'. |
|||
// result.name = 'Temperature Sensor'; // Device or asset name (the value must be unique) |
|||
// result.profile = 'IndustrialSensorProfile'; // Device or asset profile name. |
|||
// result.customer = 'MyCustomer'; // If customer is not null - created entity will be assigned to customer with such name. |
|||
// result.group = 'SensorsGroup'; // If group is not null - created entity will be added to the entity group with such name. |
|||
|
|||
// Return the final result object. |
|||
return result; |
|||
|
|||
@ -0,0 +1,851 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.mockito.junit.jupiter.MockitoSettings; |
|||
import org.mockito.quality.Strictness; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.springframework.transaction.support.TransactionCallback; |
|||
import org.springframework.transaction.support.TransactionTemplate; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.Dashboard; |
|||
import org.thingsboard.server.common.data.Device; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.AttributeScope; |
|||
import org.thingsboard.server.common.data.converter.Converter; |
|||
import org.thingsboard.server.common.data.debug.DebugSettings; |
|||
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
import org.thingsboard.server.common.data.id.DeviceProfileId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.IntegrationId; |
|||
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.page.PageData; |
|||
import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; |
|||
import org.thingsboard.server.common.data.subscription.SubscriptionException; |
|||
import org.thingsboard.rule.engine.api.AttributesSaveRequest; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceCredentialsService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.device.DeviceService; |
|||
import org.thingsboard.server.dao.entity.EntityService; |
|||
import org.thingsboard.server.dao.integration.IntegrationService; |
|||
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; |
|||
import org.thingsboard.server.dao.subscription.PlatformFeature; |
|||
import org.thingsboard.server.dao.subscription.SubscriptionService; |
|||
import org.thingsboard.server.exception.DataValidationException; |
|||
import org.thingsboard.server.service.entitiy.TbLogEntityActionService; |
|||
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.Mockito.doThrow; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoInteractions; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
@MockitoSettings(strictness = Strictness.LENIENT) |
|||
class DefaultDevicePackageUpdateServiceTest { |
|||
|
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
private final SecurityUser user = mock(SecurityUser.class); |
|||
private final UUID itemId = UUID.randomUUID(); |
|||
private final String versionId = UUID.randomUUID().toString(); |
|||
private final UUID installedVersionId = UUID.randomUUID(); |
|||
private final DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); |
|||
private final DashboardId dashboardId = new DashboardId(UUID.randomUUID()); |
|||
private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); |
|||
private final IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); |
|||
|
|||
@Mock |
|||
private IotHubInstalledItemService installedItemService; |
|||
@Mock |
|||
private IotHubRestClient iotHubRestClient; |
|||
@Mock |
|||
private DevicePackageEntities packageEntities; |
|||
@Mock |
|||
private DeviceProfileService deviceProfileService; |
|||
@Mock |
|||
private DashboardService dashboardService; |
|||
@Mock |
|||
private DeviceService deviceService; |
|||
@Mock |
|||
private DeviceCredentialsService deviceCredentialsService; |
|||
@Mock |
|||
private ConverterService converterService; |
|||
@Mock |
|||
private IntegrationService integrationService; |
|||
@Mock |
|||
private TransactionTemplate transactionTemplate; |
|||
@Mock |
|||
private EntityService entityService; |
|||
@Mock |
|||
private TbLogEntityActionService logEntityActionService; |
|||
@Mock |
|||
private TbIntegrationService tbIntegrationService; |
|||
@Mock |
|||
private SubscriptionService subscriptionService; |
|||
@Mock |
|||
private TelemetrySubscriptionService telemetryService; |
|||
@Mock |
|||
private IotHubService iotHubService; |
|||
|
|||
@InjectMocks |
|||
private DefaultDevicePackageUpdateService service; |
|||
|
|||
private IotHubInstalledItem installedItem; |
|||
// Set when the transaction callback threw, so the transaction would roll back
|
|||
private final List<RuntimeException> rolledBack = new ArrayList<>(); |
|||
|
|||
@BeforeEach |
|||
void setUp() { |
|||
ReflectionTestUtils.setField(service, "entityService", entityService); |
|||
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); |
|||
when(user.getTenantId()).thenReturn(tenantId); |
|||
|
|||
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); |
|||
descriptor.setSelectedInstallMethod("INTEGRATION_TTN"); |
|||
descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId)); |
|||
descriptor.setDashboardId(dashboardId); |
|||
// The package created these entities
|
|||
descriptor.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"), |
|||
"Dashboard", stateOf(dashboardId, "created"), "Integration", stateOf(integrationId, "created"))); |
|||
installedItem = new IotHubInstalledItem(); |
|||
installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID())); |
|||
installedItem.setTenantId(tenantId); |
|||
installedItem.setItemId(itemId); |
|||
installedItem.setItemType("DEVICE"); |
|||
installedItem.setVersion("1.0.0"); |
|||
installedItem.setItemVersionId(installedVersionId); |
|||
installedItem.setDescriptor(descriptor); |
|||
when(installedItemService.findById(tenantId, installedItem.getId())).thenReturn(installedItem); |
|||
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(installedItem); |
|||
|
|||
ObjectNode versionInfo = JacksonUtil.newObjectNode(); |
|||
versionInfo.put("itemId", itemId.toString()); |
|||
versionInfo.put("name", "AM308"); |
|||
versionInfo.put("version", "1.0.1"); |
|||
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); |
|||
|
|||
when(transactionTemplate.execute(any())).thenAnswer(invocation -> { |
|||
try { |
|||
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null); |
|||
} catch (RuntimeException e) { |
|||
rolledBack.add(e); |
|||
throw e; |
|||
} |
|||
}); |
|||
when(packageEntities.checksum(any(), any())).thenReturn("checksum"); |
|||
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.empty()); |
|||
Device device = new Device(deviceId); |
|||
device.setTenantId(tenantId); |
|||
device.setName("AM308"); |
|||
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>()); |
|||
} |
|||
|
|||
@Test |
|||
void overwritesTheEntitiesAndRecordsTheNewVersionInOneTransaction() { |
|||
DeviceProfile profile = profile(3L, "AM308 renamed"); |
|||
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile); |
|||
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); |
|||
Dashboard dashboard = dashboard(7L); |
|||
dashboard.setCustomerId(new CustomerId(UUID.randomUUID())); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), |
|||
keep("AM308", "DEVICE", deviceId), |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<DeviceProfile> savedProfile = ArgumentCaptor.forClass(DeviceProfile.class); |
|||
verify(deviceProfileService).saveDeviceProfile(savedProfile.capture()); |
|||
// Same id, the name the user gave it, the version they reviewed
|
|||
assertThat(savedProfile.getValue().getId()).isEqualTo(profileId); |
|||
assertThat(savedProfile.getValue().getName()).isEqualTo("AM308 renamed"); |
|||
assertThat(savedProfile.getValue().getDescription()).isEqualTo("new"); |
|||
assertThat(savedProfile.getValue().getVersion()).isEqualTo(3L); |
|||
ArgumentCaptor<Dashboard> savedDashboard = ArgumentCaptor.forClass(Dashboard.class); |
|||
verify(dashboardService).saveDashboard(savedDashboard.capture()); |
|||
assertThat(savedDashboard.getValue().getCustomerId()).isEqualTo(dashboard.getCustomerId()); |
|||
|
|||
verify(installedItemService).save(tenantId, installedItem); |
|||
assertThat(installedItem.getVersion()).isEqualTo("1.0.1"); |
|||
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
|
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()) |
|||
.isEqualTo(EntityChecksum.of(savedDashboard.getValue())); |
|||
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntity_keepsTheChecksumThePackageLeft() { |
|||
// The user changed the dashboard since: its current checksum must not become the package's
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); |
|||
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed"); |
|||
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK"); |
|||
verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntityOfAStepWithAnId_keepsItsChecksumUnderTheId() { |
|||
// Installed by a version whose step had no id: the entry is under the step's name
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); |
|||
overview.setId("main-dashboard"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed"); |
|||
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview"); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntity_doesNotTakeTheChecksumOfAnotherEntity() { |
|||
// The entry under the step's key was recorded for an entity deleted since
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "of-the-deleted-one").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", UUID.randomUUID().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void useExistingOfAPackageEntity_staysThePackages() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created"); |
|||
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void useExistingAtInstall_staysUseExisting() { |
|||
// At install the user picked their own dashboard: the install adds it to createdEntityIds too
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing"); |
|||
} |
|||
|
|||
@Test |
|||
void overwritingAnEntityUsedAtInstall_needsAConfirmation() { |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void sharedEntityOverwrittenByAnotherPackage_isNotChangedBySomeoneElse() { |
|||
Dashboard shared = dashboard(9L); |
|||
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null); |
|||
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot); |
|||
when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0)); |
|||
// This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one
|
|||
ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it"); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own)); |
|||
IotHubInstalledItem other = otherPackage(Map.of("Dashboard", stateOf(dashboardId, "created").put("checksum", snapshot.checksum()))); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())) |
|||
.thenReturn(new PageData<>(List.of(installedItem, other), 1, 2, false)); |
|||
|
|||
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isFalse(); |
|||
|
|||
shared.setConfiguration(JacksonUtil.newObjectNode().put("description", "Changed by hand")); |
|||
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void entityOfAStepAVersionDropped_staysThePackages() { |
|||
// v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created"); |
|||
} |
|||
|
|||
@Test |
|||
void entityUsedAtInstall_staysTheUsersAfterAVersionDropsItsStep() { |
|||
// Recorded at install; the step is gone from the install state since
|
|||
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
installed.setUsedExistingEntityIds(List.of(dashboardId)); |
|||
installed.setInstallState(Map.of()); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void entitiesUsedAtInstall_areCarriedIntoTheDescriptor() { |
|||
// Installed before the descriptor kept them: the install state has them
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void keptIntegration_getsTheStepsMetadataEntries() { |
|||
// Taken as it was at install: other packages' entries stay, the step's are merged, a null one is removed
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", stateOf(integrationId, "use-existing"))); |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other").put("profile.milesight-iot-am308", "AM308")); |
|||
current.setConfiguration(configuration); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); |
|||
step.setResolution("use-existing"); |
|||
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); |
|||
entries.putNull("profile.milesight-iot-am308"); |
|||
step.setMetadata(entries); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class); |
|||
verify(integrationService).saveIntegration(saved.capture()); |
|||
JsonNode metadata = saved.getValue().getConfiguration().get("metadata"); |
|||
assertThat(metadata.get("profile.other-model").asText()).isEqualTo("Other"); |
|||
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge"); |
|||
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse(); |
|||
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
|
|||
assertThat(saved.getValue()).isNotSameAs(current); |
|||
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse(); |
|||
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN"); |
|||
assertThat(state.get("resolution").asText()).isEqualTo("use-existing"); |
|||
// The entries the step added, which a delete of the package removes; not the one it removed
|
|||
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); |
|||
} |
|||
|
|||
@Test |
|||
void integrationOfAStepAVersionDropped_keepsItsMetadataEntries() { |
|||
// Taken as it was at install with the package's entries; the new version has no step for it
|
|||
ObjectNode installed = stateOf(integrationId, "use-existing"); |
|||
installed.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", installed)); |
|||
Integration integration = new Integration(); |
|||
integration.setId(integrationId); |
|||
when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getCreatedEntityIds()).contains(integrationId); |
|||
// A later delete that keeps the integration removes these entries
|
|||
assertThat(descriptor.getInstallState().get("TTN").get("metadata")) |
|||
.isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); |
|||
} |
|||
|
|||
@Test |
|||
void integrationUsedByAStepNewToThePackage_isListedAsUsedAsItWas() { |
|||
// The installed version has no integration step; the new one takes the tenant's integration as it is
|
|||
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
installed.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId)); |
|||
installed.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"), |
|||
"Dashboard", stateOf(dashboardId, "created"))); |
|||
IntegrationId tenantsIntegrationId = new IntegrationId(UUID.randomUUID()); |
|||
Integration current = new Integration(); |
|||
current.setId(tenantsIntegrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other")); |
|||
current.setConfiguration(configuration); |
|||
when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); |
|||
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); |
|||
step.setResolution("use-existing"); |
|||
step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
// A delete walks createdEntityIds and keeps what usedExistingEntityIds lists, removing only the package's
|
|||
// entries from it (DefaultIotHubServiceTest#deleteInstalledItem_devicePackage_removesItsMetadataEntriesFromTheIntegrationItTookAsItWas)
|
|||
assertThat(descriptor.getCreatedEntityIds()).containsOnlyOnce(tenantsIntegrationId); |
|||
assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(tenantsIntegrationId); |
|||
JsonNode state = descriptor.getInstallState().get("TTN"); |
|||
assertThat(state.get("resolution").asText()).isEqualTo("use-existing"); |
|||
assertThat(state.get("metadata")).isEqualTo(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); |
|||
} |
|||
|
|||
@Test |
|||
void keptIntegrationWithTheEntriesItHas_isNotSaved() { |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); |
|||
current.setConfiguration(configuration); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); |
|||
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
verify(integrationService, never()).saveIntegration(any()); |
|||
} |
|||
|
|||
@Test |
|||
void twoStepsWithOneKey_areRejected() { |
|||
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); |
|||
first.setId("main-dashboard"); |
|||
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); |
|||
second.setId("main-dashboard"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void failedStep_rollsBackAndReportsTheStep() { |
|||
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308")); |
|||
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getFailedStep()).isEqualTo("Dashboard"); |
|||
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); |
|||
assertThat(rolledBack).hasSize(1); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
verifyNoInteractions(logEntityActionService); |
|||
assertThat(installedItem.getVersion()).isEqualTo("1.0.0"); |
|||
} |
|||
|
|||
@Test |
|||
void entityChangedSinceTheCheck_isAVersionConflict() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getFailedStep()).isEqualTo("Dashboard"); |
|||
assertThat(result.getErrorMessage()).contains("Check the update again"); |
|||
verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); |
|||
} |
|||
|
|||
@Test |
|||
void integrationGetsTheIdOfTheConverterCreatedInTheSameUpdate() throws Exception { |
|||
ConverterId converterId = new ConverterId(UUID.randomUUID()); |
|||
when(converterService.saveConverter(any())).thenAnswer(i -> { |
|||
Converter converter = i.getArgument(0); |
|||
converter.setId(converterId); |
|||
return converter; |
|||
}); |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
current.setRoutingKey("routing-key"); |
|||
current.setVersion(2L); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); |
|||
ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); |
|||
integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), |
|||
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class); |
|||
verify(integrationService).saveIntegration(saved.capture()); |
|||
assertThat(saved.getValue().getDefaultConverterId()).isEqualTo(converterId); |
|||
// The devices keep sending to the same endpoint
|
|||
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key"); |
|||
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app"); |
|||
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); |
|||
} |
|||
|
|||
@Test |
|||
void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() { |
|||
ConverterId converterId = new ConverterId(UUID.randomUUID()); |
|||
Converter current = new Converter(converterId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("Uplink data converter for TTN my-app"); |
|||
current.setVersion(4L); |
|||
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current); |
|||
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0)); |
|||
// The package that created the converter records its checksum; one that took it as it was records none
|
|||
ObjectNode created = JacksonUtil.newObjectNode().put("checksum", "before").put("resolution", "created"); |
|||
created.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); |
|||
ObjectNode usedExisting = JacksonUtil.newObjectNode().put("resolution", "use-existing"); |
|||
usedExisting.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); |
|||
IotHubInstalledItem creator = otherPackage(Map.of("Uplink", created)); |
|||
IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())) |
|||
.thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); |
|||
DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, |
|||
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); |
|||
step.setConfirmed(true); |
|||
step.setDefaultConverter(true); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); |
|||
assertThat(state.get("defaultConverter").asBoolean()).isTrue(); |
|||
// The other packages keep what they recorded: check() takes the checksum of any installed package
|
|||
assertThat(created.get("checksum").asText()).isEqualTo("before"); |
|||
verify(installedItemService, never()).save(tenantId, creator); |
|||
verify(installedItemService, never()).save(tenantId, taker); |
|||
} |
|||
|
|||
@Test |
|||
void updateOfTheInstalledVersion_keepsTheInstallStateOfTheStepsItLeavesOut() { |
|||
ConverterId converterId = new ConverterId(UUID.randomUUID()); |
|||
Converter current = new Converter(converterId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("Uplink data converter for TTN my-app"); |
|||
current.setVersion(4L); |
|||
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current); |
|||
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
installed.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId, converterId)); |
|||
installed.setInstallState(Map.of("Integration", stateOf(integrationId, "created"), "uplink", stateOf(converterId, "created"), |
|||
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("profileName", "am308")))); |
|||
ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0"); |
|||
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); |
|||
// ThingsBoard's default converter changed: only the converter step is sent
|
|||
DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, |
|||
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); |
|||
step.setId("uplink"); |
|||
step.setDefaultConverter(true); |
|||
DeviceUpdateRequest request = request(step); |
|||
request.setVersionId(installedVersionId.toString()); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); |
|||
ArgumentCaptor<Converter> saved = ArgumentCaptor.forClass(Converter.class); |
|||
verify(converterService).saveConverter(saved.capture()); |
|||
assertThat(state.get("uplink").get("checksum").asText()).isEqualTo(EntityChecksum.of(saved.getValue())); |
|||
assertThat(state.get("uplink").get("defaultConverter").asBoolean()).isTrue(); |
|||
assertThat(state.get("Integration")).isEqualTo(stateOf(integrationId, "created")); |
|||
assertThat(state.get("Configuration").get("formValues").get("profileName").asText()).isEqualTo("am308"); |
|||
verify(integrationService, never()).saveIntegration(any()); |
|||
assertThat(installedItem.getItemVersionId()).isEqualTo(installedVersionId); |
|||
} |
|||
|
|||
@Test |
|||
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("Dashboard"); |
|||
} |
|||
|
|||
@Test |
|||
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { |
|||
DashboardId foreign = new DashboardId(UUID.randomUUID()); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void theDeviceIsNeverOverwritten() { |
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).isEqualTo("The device and its credentials don't change on update"); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void versionOfAnotherItem_isRejected() { |
|||
ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); |
|||
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void anotherUpdateCommittedMeanwhile_failsWithoutChanges() { |
|||
// E.g. a second click: it waits for the first one's lock and finds the package on another version
|
|||
IotHubInstalledItem updated = new IotHubInstalledItem(); |
|||
updated.setId(installedItem.getId()); |
|||
updated.setItemVersionId(UUID.fromString(versionId)); |
|||
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).contains("Check the update again"); |
|||
verify(converterService, never()).saveConverter(any()); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void planOfAnotherInstalledVersion_isRejected() { |
|||
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); |
|||
request.setFromVersionId(UUID.randomUUID()); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void integrationsNotInThePlan_areRefused() { |
|||
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) |
|||
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).isEqualTo("Integrations feature is disabled!"); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); |
|||
step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); |
|||
verify(telemetryService).saveAttributes(saved.capture()); |
|||
assertThat(saved.getValue().getEntityId()).isEqualTo(dashboardId); |
|||
assertThat(saved.getValue().getScope()).isEqualTo(AttributeScope.SERVER_SCOPE); |
|||
assertThat(saved.getValue().getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); |
|||
} |
|||
|
|||
@Test |
|||
void checksum_ignoresDebugSettingsAndTheDefaultProfile() { |
|||
Converter converter = new Converter(); |
|||
converter.setName("Uplink"); |
|||
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {};")); |
|||
String installed = EntityChecksum.of(converter); |
|||
converter.setDebugMode(true); |
|||
converter.setDebugSettings(DebugSettings.all()); |
|||
assertThat(EntityChecksum.of(converter)).isEqualTo(installed); |
|||
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {a: 1};")); |
|||
assertThat(EntityChecksum.of(converter)).isNotEqualTo(installed); |
|||
|
|||
DeviceProfile profile = profile(1L, "AM308"); |
|||
String profileChecksum = EntityChecksum.of(profile); |
|||
profile.setDefault(true); |
|||
assertThat(EntityChecksum.of(profile)).isEqualTo(profileChecksum); |
|||
} |
|||
|
|||
@Test |
|||
void checksum_ignoresTheMetadataOfAnIntegration() { |
|||
Integration integration = new Integration(); |
|||
integration.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode().put("host", "eu1.cloud.thethings.network"); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode()); |
|||
integration.setConfiguration(configuration); |
|||
String installed = EntityChecksum.of(integration); |
|||
// Another package on the integration adds its profile name
|
|||
((ObjectNode) configuration.get("metadata")).put("profile.milesight-iot-am308", "AM308"); |
|||
assertThat(EntityChecksum.of(integration)).isEqualTo(installed); |
|||
assertThat(integration.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue(); |
|||
configuration.put("host", "nam1.cloud.thethings.network"); |
|||
assertThat(EntityChecksum.of(integration)).isNotEqualTo(installed); |
|||
} |
|||
|
|||
@Test |
|||
void userMessage_showsValidationMessagesAndHidesInternalOnes() { |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) |
|||
.isEqualTo("Rule chains limit reached"); |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) |
|||
.contains("Check the update again"); |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) |
|||
.isEqualTo("Failed to update the device package"); |
|||
} |
|||
|
|||
@Test |
|||
void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() { |
|||
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); |
|||
ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); |
|||
|
|||
ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); |
|||
|
|||
assertThat(resolved.get("a").asText()).isEqualTo("123"); |
|||
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); |
|||
} |
|||
|
|||
private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) { |
|||
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); |
|||
descriptor.setInstallState(installState); |
|||
IotHubInstalledItem item = new IotHubInstalledItem(); |
|||
item.setId(new IotHubInstalledItemId(UUID.randomUUID())); |
|||
item.setTenantId(tenantId); |
|||
item.setItemType("DEVICE"); |
|||
item.setDescriptor(descriptor); |
|||
return item; |
|||
} |
|||
|
|||
private DeviceProfile profile(Long version, String name) { |
|||
DeviceProfile profile = new DeviceProfile(profileId); |
|||
profile.setTenantId(tenantId); |
|||
profile.setName(name); |
|||
profile.setVersion(version); |
|||
return profile; |
|||
} |
|||
|
|||
private Dashboard dashboard(Long version) { |
|||
Dashboard dashboard = new Dashboard(dashboardId); |
|||
dashboard.setTenantId(tenantId); |
|||
dashboard.setTitle("AM308 dashboard"); |
|||
dashboard.setVersion(version); |
|||
return dashboard; |
|||
} |
|||
|
|||
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { |
|||
DeviceUpdateRequest request = new DeviceUpdateRequest(); |
|||
request.setVersionId(versionId); |
|||
request.setSteps(List.of(steps)); |
|||
return request; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); |
|||
step.setEntityId(id.getId()); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); |
|||
step.setEntityId(id.getId()); |
|||
step.setExpectedVersion(version); |
|||
step.setEntity(entity); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); |
|||
step.setEntity(entity); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { |
|||
DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); |
|||
step.setName(name); |
|||
step.setType(type); |
|||
step.setAction(action); |
|||
return step; |
|||
} |
|||
|
|||
|
|||
private static ObjectNode stateOf(EntityId id, String resolution) { |
|||
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", resolution); |
|||
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", id.getId().toString())); |
|||
return state; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,43 @@ |
|||
{ |
|||
"end_device_ids": { |
|||
"device_id": "macro-tracker-1", |
|||
"application_ids": { |
|||
"application_id": "my-app" |
|||
}, |
|||
"dev_eui": "70B3D57ED006F371" |
|||
}, |
|||
"received_at": "2026-11-10T10:00:00.123Z", |
|||
"uplink_message": { |
|||
"f_port": 1, |
|||
"f_cnt": 5, |
|||
"frm_payload": "IWQ+Az4AbFA=", |
|||
"decoded_payload": { |
|||
"tbVersionIds": { |
|||
"brand_id": "lansitec", |
|||
"model_id": "macro-tracker" |
|||
}, |
|||
"batteryLevel": 100, |
|||
"chargeState": "Charging", |
|||
"temperatureUnit": "°C" |
|||
}, |
|||
"rx_metadata": [ |
|||
{ |
|||
"gateway_ids": { |
|||
"gateway_id": "ug56" |
|||
}, |
|||
"rssi": -70, |
|||
"snr": 7 |
|||
} |
|||
], |
|||
"settings": { |
|||
"data_rate": { |
|||
"lora": { |
|||
"bandwidth": 125000, |
|||
"spreading_factor": 9 |
|||
} |
|||
}, |
|||
"frequency": "868300000" |
|||
}, |
|||
"received_at": "2026-11-10T10:00:00.100Z" |
|||
} |
|||
} |
|||
@ -0,0 +1,34 @@ |
|||
{ |
|||
"end_device_ids": { |
|||
"device_id": "manual-node", |
|||
"application_ids": { |
|||
"application_id": "my-app" |
|||
}, |
|||
"dev_eui": "70B3D57ED006F370" |
|||
}, |
|||
"received_at": "2026-10-28T10:00:00.123Z", |
|||
"uplink_message": { |
|||
"f_port": 1, |
|||
"f_cnt": 3, |
|||
"frm_payload": "Ae0DM18OTGM=", |
|||
"rx_metadata": [ |
|||
{ |
|||
"gateway_ids": { |
|||
"gateway_id": "ug56" |
|||
}, |
|||
"rssi": -70, |
|||
"snr": 7 |
|||
} |
|||
], |
|||
"settings": { |
|||
"data_rate": { |
|||
"lora": { |
|||
"bandwidth": 125000, |
|||
"spreading_factor": 9 |
|||
} |
|||
}, |
|||
"frequency": "868300000" |
|||
}, |
|||
"received_at": "2026-10-28T10:00:00.100Z" |
|||
} |
|||
} |
|||
@ -0,0 +1,64 @@ |
|||
{ |
|||
"end_device_ids": { |
|||
"device_id": "am308-office", |
|||
"application_ids": { |
|||
"application_id": "my-app" |
|||
}, |
|||
"dev_eui": "24E124707C481005", |
|||
"join_eui": "24E124C0002A0001", |
|||
"dev_addr": "260B1234" |
|||
}, |
|||
"received_at": "2026-10-28T10:00:00.123Z", |
|||
"uplink_message": { |
|||
"f_port": 85, |
|||
"f_cnt": 12, |
|||
"frm_payload": "AXVk", |
|||
"decoded_payload": { |
|||
"battery": 95, |
|||
"temperature": 24.5, |
|||
"co2": 560, |
|||
"history": [ |
|||
{ |
|||
"timestamp": 1793170000, |
|||
"temperature": 24.1, |
|||
"co2": 550 |
|||
} |
|||
] |
|||
}, |
|||
"rx_metadata": [ |
|||
{ |
|||
"gateway_ids": { |
|||
"gateway_id": "ug56" |
|||
}, |
|||
"rssi": -60, |
|||
"snr": 9.5, |
|||
"channel_index": 2 |
|||
} |
|||
], |
|||
"settings": { |
|||
"data_rate": { |
|||
"lora": { |
|||
"bandwidth": 125000, |
|||
"spreading_factor": 7, |
|||
"coding_rate": "4/5" |
|||
} |
|||
}, |
|||
"frequency": "868100000" |
|||
}, |
|||
"received_at": "2026-10-28T10:00:00.100Z", |
|||
"consumed_airtime": "0.061696s", |
|||
"version_ids": { |
|||
"brand_id": "milesight-iot", |
|||
"model_id": "am308", |
|||
"hardware_version": "1.0", |
|||
"firmware_version": "1.0", |
|||
"band_id": "EU_863_870" |
|||
}, |
|||
"network_ids": { |
|||
"net_id": "000013", |
|||
"tenant_id": "ttn", |
|||
"cluster_id": "eu1", |
|||
"cluster_address": "eu1.cloud.thethings.network" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,77 @@ |
|||
{ |
|||
"end_device_ids": { |
|||
"device_id": "eui-1000000000000001", |
|||
"application_ids": { |
|||
"application_id": "application-tti-name" |
|||
}, |
|||
"dev_eui": "1000000000000001", |
|||
"join_eui": "2000000000000001", |
|||
"dev_addr": "20000001" |
|||
}, |
|||
"correlation_ids": ["as:up:01H0PZDGB1NW6NAPD815NGHPF6", "gs:conn:01H0FJRSXSYT7VKNYXJ89F95XT", "gs:up:host:01H0FJRSY3MZMGPPFBQ4FZV4T8", "gs:uplink:01H0PZDG4HHGFRTXRTXD4PFTH7", "ns:uplink:01H0PZDG4JZ3BM0K6J89EQK1J7", "rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0PZDG4J02F85RYFPCNSNXCR", "rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0PZDGB081PMP806BJHNHX1A"], |
|||
"received_at": "2023-05-18T08:25:26.112483370Z", |
|||
"uplink_message": { |
|||
"session_key_id": "AYfg8rhha5n+FWx0ZaAprA==", |
|||
"f_port": 85, |
|||
"f_cnt": 5017, |
|||
"frm_payload": "Ae0DM18OTGM=", |
|||
"rx_metadata": [{ |
|||
"gateway_ids": { |
|||
"gateway_id": "eui-6A7E111A10000000", |
|||
"eui": "6A7E111A10000000" |
|||
}, |
|||
"time": "2023-05-18T08:25:25.885310Z", |
|||
"timestamp": 818273765, |
|||
"rssi": -24, |
|||
"channel_rssi": -24, |
|||
"snr": 12, |
|||
"frequency_offset": "671", |
|||
"uplink_token": "CiIKIAoUZXVpLTZBN0UxMTFBMTAwMDAwMDASCCThJP/+9k6eEOW7l4YDGgwI9cGXowYQ5KPhrwMgiI2rp+jpOA=", |
|||
"channel_index": 2, |
|||
"received_at": "2023-05-18T08:25:25.869324983Z" |
|||
}, { |
|||
"gateway_ids": { |
|||
"gateway_id": "packetbroker" |
|||
}, |
|||
"packet_broker": { |
|||
"message_id": "01H0PZDG4MF9AYSMNY44MAVTDH", |
|||
"forwarder_net_id": "000013", |
|||
"forwarder_tenant_id": "ttn", |
|||
"forwarder_cluster_id": "eu1.cloud.thethings.network", |
|||
"forwarder_gateway_eui": "6A7E111A10000000", |
|||
"forwarder_gateway_id": "eui-6a7e111a10000000", |
|||
"home_network_net_id": "000013", |
|||
"home_network_tenant_id": "tenant", |
|||
"home_network_cluster_id": "eu1.cloud.thethings.industries" |
|||
}, |
|||
"time": "2023-05-18T08:25:25.885310Z", |
|||
"rssi": -24, |
|||
"channel_rssi": -24, |
|||
"snr": 12, |
|||
"frequency_offset": "671", |
|||
"uplink_token": "eyJnIjoiWlhsS2FHSkhZMmxQYVVwQ1RWUkpORkl3VGs1VE1XTnBURU5LYkdKdFRXbFBhVXBDVFZSSk5GSXdUazVKYVhkcFlWaFphVTlwU201a01uaGhWVlJvZDFSWFVuRmlSM1JtVFcxT2RVbHBkMmxrUjBadVNXcHZhV05ZY0RKT1IyeExaREpSZVZwR1pIUmpNRXBLVlVoR2RFNVZkR3BWVTBvNUxua3paVVJTWVRaM1lXOU1kbTQwVm5sdmIyWmlPWGN1ZUhCZmVrcElaa3hIWlZadGRVUlFVeTVuYlRaVlZXRXdkakpHV0VKMGJUUjZaMjVXUkVoeGVHRjRaMlJKTlVkS1VsbERhemc1VDNCbk5rVk1iM1JDUkVZM1VWbHdZbEJDTkdOblNqWjBlbkphYUV4MFRVMHhZMVZFTTFac01XdExURUo0YURaMFExTnhhMVJsWWw4eE5FdHlVVXcyZUhsRWFFbEhlakJITXpoTE0xaFdlRzR5VUVjMk4wNUViME5WTkhoTmRrazFZVk5oWkUwd2FXVnFjR294VGtoMFduZHlZMDFxVlVGNmRsbERUazlNY2s5eFdVeFpWMk5XTG1WVFFYVkpNVkptT1U5NWRqUTNhSEoxTUZoalYxRT0iLCJhIjp7ImZuaWQiOiIwMDAwMTMiLCJmdGlkIjoidHRuIiwiZmNpZCI6ImV1MS5jbG91ZC50aGV0aGluZ3MubmV0d29yayJ9fQ==", |
|||
"received_at": "2023-05-18T08:25:25.906038642Z" |
|||
}], |
|||
"settings": { |
|||
"data_rate": { |
|||
"lora": { |
|||
"bandwidth": 125000, |
|||
"spreading_factor": 7, |
|||
"coding_rate": "4/5" |
|||
} |
|||
}, |
|||
"frequency": "868500000", |
|||
"timestamp": 818273765, |
|||
"time": "2023-05-18T08:25:25.885310Z" |
|||
}, |
|||
"received_at": "2023-05-18T08:25:25.906399073Z", |
|||
"consumed_airtime": "0.097536s", |
|||
"network_ids": { |
|||
"net_id": "000013", |
|||
"tenant_id": "tenant", |
|||
"cluster_id": "eu1", |
|||
"cluster_address": "eu1.cloud.thethings.industries", |
|||
"tenant_address": "tenant.eu1.cloud.thethings.industries" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,54 @@ |
|||
{ |
|||
"end_device_ids": { |
|||
"device_id": "eui-1000000000000001", |
|||
"application_ids": { |
|||
"application_id": "application-tts-name" |
|||
}, |
|||
"dev_eui": "1000000000000001", |
|||
"join_eui": "2000000000000001", |
|||
"dev_addr": "20000001" |
|||
}, |
|||
"correlation_ids": ["as:up:01H0S7ZJQ9MQPMVY49FT3SE07M", "gs:conn:01H03BQZ9342X3Y86DJ2P704E5", "gs:up:host:01H03BQZ99EGAM52KK1300GFKN", "gs:uplink:01H0S7ZJGS6D9TJSKJN8XNTMAV", "ns:uplink:01H0S7ZJGS9KKD4HTTPKFEMWCV", "rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0S7ZJGSF3M38ZRZVTM38DEC", "rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0S7ZJQ8R2EH5AA269AKM8DX"], |
|||
"received_at": "2023-05-19T05:33:35.848446463Z", |
|||
"uplink_message": { |
|||
"session_key_id": "AYfqmb0pc/1uRZv9xUydgQ==", |
|||
"f_port": 85, |
|||
"f_cnt": 10335, |
|||
"frm_payload": "Ae0DM18OTGM=", |
|||
"rx_metadata": [{ |
|||
"gateway_ids": { |
|||
"gateway_id": "eui-6a7e111a10000000", |
|||
"eui": "6A7E111A10000000" |
|||
}, |
|||
"time": "2023-05-19T05:33:35.608982Z", |
|||
"timestamp": 3893546133, |
|||
"rssi": -35, |
|||
"channel_rssi": -35, |
|||
"snr": 13.2, |
|||
"frequency_offset": "69", |
|||
"uplink_token": "CiIKIAoUZXVpLTZhN2UxMTFhMTAwMDAwMDASCCThJP/+9k6eEJWZy8AOGgwIr5ScowYQvNbUsQIgiMy8y6jwpwE=", |
|||
"channel_index": 3, |
|||
"received_at": "2023-05-19T05:33:35.607383681Z" |
|||
}], |
|||
"settings": { |
|||
"data_rate": { |
|||
"lora": { |
|||
"bandwidth": 125000, |
|||
"spreading_factor": 7, |
|||
"coding_rate": "4/5" |
|||
} |
|||
}, |
|||
"frequency": "867100000", |
|||
"timestamp": 3893546133, |
|||
"time": "2023-05-19T05:33:35.608982Z" |
|||
}, |
|||
"received_at": "2023-05-19T05:33:35.641841782Z", |
|||
"consumed_airtime": "0.056576s", |
|||
"network_ids": { |
|||
"net_id": "000013", |
|||
"tenant_id": "ttn", |
|||
"cluster_id": "eu1", |
|||
"cluster_address": "eu1.cloud.thethings.network" |
|||
} |
|||
} |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.dao.device; |
|||
|
|||
/** |
|||
* Where the host of a transport in the device connectivity info comes from. |
|||
*/ |
|||
public enum DeviceConnectivityHostSource { |
|||
/** Set explicitly in the Device connectivity settings. */ |
|||
DEVICE_CONNECTIVITY, |
|||
/** Taken from the Base URL in General settings. */ |
|||
BASE_URL, |
|||
/** Taken from the address of the request. */ |
|||
REQUEST |
|||
} |
|||
@ -0,0 +1,62 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.integration.mqtt.ttn; |
|||
|
|||
import io.netty.channel.nio.NioEventLoopGroup; |
|||
import org.junit.After; |
|||
import org.junit.Assert; |
|||
import org.junit.Before; |
|||
import org.junit.Test; |
|||
import org.mockito.Mockito; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.integration.api.IntegrationContext; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.IntegrationId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.integration.IntegrationType; |
|||
|
|||
import java.util.UUID; |
|||
import java.util.concurrent.ExecutorService; |
|||
import java.util.concurrent.Executors; |
|||
|
|||
public class TtnIntegrationCheckConnectionTest { |
|||
|
|||
private NioEventLoopGroup eventLoopGroup; |
|||
private ExecutorService executor; |
|||
private IntegrationContext context; |
|||
|
|||
@Before |
|||
public void setUp() { |
|||
eventLoopGroup = new NioEventLoopGroup(1); |
|||
executor = Executors.newSingleThreadExecutor(); |
|||
context = Mockito.mock(IntegrationContext.class); |
|||
Mockito.when(context.getEventLoopGroup()).thenReturn(eventLoopGroup); |
|||
Mockito.when(context.getExecutorService()).thenReturn(executor); |
|||
Mockito.when(context.getIntegrationConnectTimeoutSec()).thenReturn(1); |
|||
Mockito.when(context.getMqttClientRetransmissionMaxAttempts()).thenReturn(1); |
|||
Mockito.when(context.getMqttClientRetransmissionInitialDelayMillis()).thenReturn(1000L); |
|||
Mockito.when(context.getMqttClientRetransmissionJitterFactor()).thenReturn(0.1); |
|||
} |
|||
|
|||
@After |
|||
public void tearDown() { |
|||
eventLoopGroup.shutdownGracefully(); |
|||
executor.shutdownNow(); |
|||
} |
|||
|
|||
// The check runs the same TTN setup as a running integration, which refuses empty credentials
|
|||
@Test |
|||
public void checkRefusesEmptyCredentialsBeforeConnecting() { |
|||
Integration integration = new Integration(); |
|||
integration.setId(new IntegrationId(UUID.randomUUID())); |
|||
integration.setTenantId(TenantId.fromUUID(UUID.randomUUID())); |
|||
integration.setType(IntegrationType.TTN); |
|||
integration.setConfiguration(JacksonUtil.toJsonNode("{\"clientConfiguration\":{\"host\":\"eu1\",\"port\":8883," |
|||
+ "\"connectTimeoutSec\":1,\"ssl\":true,\"credentials\":{\"type\":\"basic\",\"username\":\"\",\"password\":\"\"}}}")); |
|||
|
|||
ThingsboardException e = Assert.assertThrows(ThingsboardException.class, |
|||
() -> new TtnIntegration().doCheckConnection(integration, context)); |
|||
Assert.assertTrue(e.getMessage(), e.getMessage().contains("Application Credentials")); |
|||
} |
|||
} |
|||
@ -0,0 +1,11 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.dao.device; |
|||
|
|||
/** |
|||
* Host and port of an enabled transport as returned by {@link DeviceConnectivityService#getConnectivityInfo}, |
|||
* with the source of the host. Kept apart from {@link DeviceConnectivityInfo}, which models the stored settings. |
|||
*/ |
|||
public record ResolvedDeviceConnectivityInfo(boolean enabled, String host, String port, |
|||
DeviceConnectivityHostSource hostSource) { |
|||
} |
|||
@ -0,0 +1,119 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
package org.thingsboard.server.dao.device; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.AdminSettings; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.dao.settings.AdminSettingsService; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
class DeviceConnectivityServiceImplTest { |
|||
|
|||
private static final String BASE_URL = "http://192.168.1.10:8080"; |
|||
|
|||
@Mock |
|||
private AdminSettingsService adminSettingsService; |
|||
@Mock |
|||
private DeviceCredentialsService deviceCredentialsService; |
|||
@Mock |
|||
private DeviceProfileService deviceProfileService; |
|||
@InjectMocks |
|||
private DeviceConnectivityServiceImpl service; |
|||
|
|||
@Test |
|||
void configuredHostIsReportedAsDeviceConnectivity() throws Exception { |
|||
givenConnectivity(""" |
|||
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}"""); |
|||
|
|||
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); |
|||
|
|||
assertThat(mqtt.get("host").asText()).isEqualTo("10.0.0.5"); |
|||
assertThat(mqtt.get("port").asText()).isEqualTo("1884"); |
|||
assertThat(mqtt.get("hostSource").asText()).isEqualTo("DEVICE_CONNECTIVITY"); |
|||
} |
|||
|
|||
@Test |
|||
void blankHostTakesBaseUrlAndItsSource() throws Exception { |
|||
givenConnectivity(""" |
|||
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}"""); |
|||
|
|||
JsonNode fromRequest = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); |
|||
JsonNode fromBaseUrl = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.BASE_URL).get("mqtt"); |
|||
|
|||
assertThat(fromRequest.get("host").asText()).isEqualTo("192.168.1.10"); |
|||
assertThat(fromRequest.get("hostSource").asText()).isEqualTo("REQUEST"); |
|||
assertThat(fromBaseUrl.get("hostSource").asText()).isEqualTo("BASE_URL"); |
|||
} |
|||
|
|||
@Test |
|||
void blankPortIsReplacedWithStandardPort() throws Exception { |
|||
givenConnectivity(""" |
|||
{"http": {"enabled": true, "host": "", "port": ""}, |
|||
"https": {"enabled": true, "host": "", "port": ""}, |
|||
"mqtt": {"enabled": true, "host": "", "port": ""}, |
|||
"mqtts": {"enabled": true, "host": "", "port": ""}, |
|||
"coap": {"enabled": true, "host": "", "port": ""}, |
|||
"coaps": {"enabled": true, "host": "", "port": ""}}"""); |
|||
|
|||
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST); |
|||
|
|||
assertThat(info.get("http").get("port").asText()).isEqualTo("80"); |
|||
assertThat(info.get("https").get("port").asText()).isEqualTo("443"); |
|||
assertThat(info.get("mqtt").get("port").asText()).isEqualTo("1883"); |
|||
assertThat(info.get("mqtts").get("port").asText()).isEqualTo("8883"); |
|||
assertThat(info.get("coap").get("port").asText()).isEqualTo("5683"); |
|||
assertThat(info.get("coaps").get("port").asText()).isEqualTo("5684"); |
|||
} |
|||
|
|||
@Test |
|||
void disabledProtocolIsLeftOut() throws Exception { |
|||
givenConnectivity(""" |
|||
{"mqtt": {"enabled": true, "host": "", "port": "1883"}, |
|||
"coap": {"enabled": false, "host": "", "port": "5683"}}"""); |
|||
|
|||
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST); |
|||
|
|||
assertThat(info.has("mqtt")).isTrue(); |
|||
assertThat(info.has("coap")).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void responseHasTheFieldsTheUiReads() throws Exception { |
|||
givenConnectivity(""" |
|||
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}"""); |
|||
|
|||
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt"); |
|||
|
|||
assertThat(mqtt.fieldNames()).toIterable() |
|||
.containsExactlyInAnyOrder("enabled", "host", "port", "hostSource"); |
|||
assertThat(mqtt.get("enabled").asBoolean()).isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void overloadWithoutSourceReportsRequest() throws Exception { |
|||
givenConnectivity(""" |
|||
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}"""); |
|||
|
|||
JsonNode mqtt = service.getConnectivityInfo(BASE_URL).get("mqtt"); |
|||
|
|||
assertThat(mqtt.get("host").asText()).isEqualTo("192.168.1.10"); |
|||
assertThat(mqtt.get("hostSource").asText()).isEqualTo("REQUEST"); |
|||
} |
|||
|
|||
private void givenConnectivity(String json) { |
|||
AdminSettings settings = new AdminSettings(); |
|||
settings.setJsonValue(JacksonUtil.toJsonNode(json)); |
|||
when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "connectivity")).thenReturn(settings); |
|||
} |
|||
|
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,33 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<div class="flex flex-col gap-4 p-6"> |
|||
<h2 class="tb-converter-update-title">{{ 'iot-hub.converter-update-title' | translate }}</h2> |
|||
<p class="tb-converter-update-text">{{ 'iot-hub.device-update-new-default-converter' | translate }}</p> |
|||
<div class="tb-converter-update-box flex flex-col gap-2"> |
|||
<div class="tb-converter-update-name">{{ data.update.converter.name }}</div> |
|||
@if (data.usedBy.length) { |
|||
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span> |
|||
<ul class="tb-converter-update-packages"> |
|||
@for (name of data.usedBy; track $index) { |
|||
<li>{{ name }}</li> |
|||
} |
|||
</ul> |
|||
} |
|||
@if (data.modified) { |
|||
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning"> |
|||
{{ modifiedHint.before }}<a class="tb-converter-update-link" href="#" (click)="$event.preventDefault(); downloadCurrent()">{{ modifiedHint.link }}</a>{{ modifiedHint.after }} |
|||
</span> |
|||
} |
|||
</div> |
|||
@if (errorMessage) { |
|||
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ errorMessage }}</span> |
|||
} |
|||
</div> |
|||
<div class="flex items-center justify-end gap-2 p-2"> |
|||
<button mat-button (click)="cancel()" [disabled]="updating">{{ 'action.cancel' | translate }}</button> |
|||
<button mat-flat-button color="primary" (click)="update()" [disabled]="updating">{{ 'iot-hub.update' | translate }}</button> |
|||
</div> |
|||
@ -0,0 +1,65 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: BUSL-1.1 |
|||
:host { |
|||
display: block; |
|||
max-width: 600px; |
|||
} |
|||
|
|||
.tb-converter-update-title { |
|||
font-size: 20px; |
|||
font-weight: 600; |
|||
line-height: 24px; |
|||
letter-spacing: 0.1px; |
|||
color: rgba(0, 0, 0, 0.87); |
|||
margin: 0; |
|||
} |
|||
|
|||
.tb-converter-update-text { |
|||
font-size: 14px; |
|||
line-height: 20px; |
|||
letter-spacing: 0.2px; |
|||
color: rgba(0, 0, 0, 0.54); |
|||
margin: 0; |
|||
} |
|||
|
|||
.tb-converter-update-box { |
|||
padding: 12px 16px; |
|||
border: 1px solid rgba(0, 0, 0, 0.12); |
|||
border-radius: 8px; |
|||
} |
|||
|
|||
.tb-converter-update-name { |
|||
font-size: 14px; |
|||
font-weight: 500; |
|||
line-height: 20px; |
|||
color: rgba(0, 0, 0, 0.87); |
|||
} |
|||
|
|||
.tb-converter-update-packages { |
|||
margin: 0; |
|||
padding-left: 20px; |
|||
font-size: 12px; |
|||
line-height: 16px; |
|||
color: rgba(0, 0, 0, 0.54); |
|||
} |
|||
|
|||
.tb-converter-update-link { |
|||
color: #305680; |
|||
text-decoration: underline; |
|||
cursor: pointer; |
|||
} |
|||
|
|||
.tb-progress-alert-msg { |
|||
font-size: 12px; |
|||
font-weight: 400; |
|||
line-height: 16px; |
|||
letter-spacing: 0.4px; |
|||
|
|||
&.tb-progress-alert-msg-warning { |
|||
color: #f66716; |
|||
} |
|||
|
|||
&.tb-progress-alert-msg-error { |
|||
color: #dd2c00; |
|||
} |
|||
} |
|||
@ -0,0 +1,79 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { Component, Inject } from '@angular/core'; |
|||
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; |
|||
import { Router } from '@angular/router'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { DialogComponent } from '@shared/components/dialog.component'; |
|||
import { IotHubApiService } from '@core/http/iot-hub-api.service'; |
|||
import { DefaultConverterUpdate, defaultConverterUpdateRequest } from '@home/components/iot-hub/iot-hub-default-converter'; |
|||
import { downloadEntityJson, readableMessage, requestFailureMessage, splitTextWithLink } from '@home/components/iot-hub/iot-hub-utils'; |
|||
|
|||
export interface IotHubConverterUpdateDialogData { |
|||
update: DefaultConverterUpdate; |
|||
// The version of the converter the dialog downloads: the server refuses the update if someone saved the converter since
|
|||
version?: number; |
|||
// Someone changed the converter since a package installed or last updated it
|
|||
modified: boolean; |
|||
// The names of the other installed packages that use the converter
|
|||
usedBy: string[]; |
|||
} |
|||
|
|||
/** |
|||
* Brings an installed device package's default converter to ThingsBoard's default converter now, without a new version of |
|||
* the package. Closes with true once it is updated. |
|||
*/ |
|||
@Component({ |
|||
selector: 'tb-iot-hub-converter-update-dialog', |
|||
standalone: false, |
|||
templateUrl: './iot-hub-converter-update-dialog.component.html', |
|||
styleUrls: ['./iot-hub-converter-update-dialog.component.scss'] |
|||
}) |
|||
export class TbIotHubConverterUpdateDialogComponent extends DialogComponent<TbIotHubConverterUpdateDialogComponent, boolean> { |
|||
|
|||
readonly modifiedHint = splitTextWithLink(this.translate.instant('iot-hub.device-update-modified')); |
|||
updating = false; |
|||
errorMessage: string | null = null; |
|||
|
|||
constructor( |
|||
protected store: Store<AppState>, |
|||
protected router: Router, |
|||
protected dialogRef: MatDialogRef<TbIotHubConverterUpdateDialogComponent, boolean>, |
|||
@Inject(MAT_DIALOG_DATA) public data: IotHubConverterUpdateDialogData, |
|||
private iotHubApiService: IotHubApiService, |
|||
private translate: TranslateService |
|||
) { |
|||
super(store, router, dialogRef); |
|||
} |
|||
|
|||
downloadCurrent(): void { |
|||
downloadEntityJson(this.data.update.converter, this.data.update.converter.name); |
|||
} |
|||
|
|||
update(): void { |
|||
this.updating = true; |
|||
this.errorMessage = null; |
|||
this.iotHubApiService.updateDevicePackage(this.data.update.installedItem.id.id, |
|||
defaultConverterUpdateRequest(this.data.update, this.data.version), { ignoreErrors: true }).subscribe({ |
|||
next: result => { |
|||
if (result.success) { |
|||
this.dialogRef.close(true); |
|||
return; |
|||
} |
|||
// Nothing was changed: the server rolled it back
|
|||
this.updating = false; |
|||
this.errorMessage = readableMessage(result.errorMessage) ?? this.translate.instant('iot-hub.device-install-unexpected-error'); |
|||
}, |
|||
error: error => { |
|||
this.updating = false; |
|||
this.errorMessage = requestFailureMessage(error, this.translate); |
|||
} |
|||
}); |
|||
} |
|||
|
|||
cancel(): void { |
|||
this.dialogRef.close(false); |
|||
} |
|||
} |
|||
@ -0,0 +1,128 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { firstValueFrom } from 'rxjs'; |
|||
import { ResourcesService } from '@core/services/resources.service'; |
|||
import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models'; |
|||
import { IntegrationType } from '@shared/models/integration.models'; |
|||
import { ScriptLanguage } from '@shared/models/rule-node.models'; |
|||
import { isEqual } from '@core/utils'; |
|||
import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; |
|||
import { IotHubApiService } from '@core/http/iot-hub-api.service'; |
|||
import { PageLink } from '@shared/models/page/page-link'; |
|||
import { PageData } from '@shared/models/page/page-data'; |
|||
|
|||
/** An installed device package's default converter that differs from ThingsBoard's default converter now. */ |
|||
export interface DefaultConverterUpdate { |
|||
installedItem: IotHubInstalledItem; |
|||
// The key of the converter's step in the package's install state
|
|||
stateKey: string; |
|||
converter: Converter; |
|||
defaultConverter: Partial<Converter>; |
|||
} |
|||
|
|||
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json'; |
|||
|
|||
// The settings of a default converter that decide what it does: the script is compared on its own
|
|||
const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] = |
|||
['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys']; |
|||
|
|||
/** |
|||
* The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with |
|||
* "default": true installs it. Null when ThingsBoard has no default converter settings for the type. |
|||
*/ |
|||
export const loadDefaultUplinkConverter = async (resourcesService: ResourcesService, integrationType: IntegrationType, |
|||
scriptLang: ScriptLanguage, name: string): Promise<Partial<Converter> | null> => { |
|||
const configurations = await firstValueFrom( |
|||
resourcesService.loadJsonResource<Record<string, ConverterConfigV2>>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL)); |
|||
const configuration = configurations?.[integrationType]; |
|||
if (!configuration) { |
|||
return null; |
|||
} |
|||
const script = await firstValueFrom(resourcesService.loadJsonResource<string>( |
|||
getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2))); |
|||
return { |
|||
name, |
|||
type: ConverterType.UPLINK, |
|||
integrationType, |
|||
converterVersion: 2, |
|||
edgeTemplate: false, |
|||
// As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing
|
|||
debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 }, |
|||
configuration: { |
|||
...configuration, |
|||
scriptLang, |
|||
decoder: null, |
|||
tbelDecoder: null, |
|||
encoder: null, |
|||
tbelEncoder: null, |
|||
[getTargetField(ConverterType.UPLINK, scriptLang)]: script |
|||
}, |
|||
additionalInfo: { description: '' } |
|||
}; |
|||
}; |
|||
|
|||
/** True when the converter does something else than the default one: another script or other settings. */ |
|||
export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial<Converter>): boolean => { |
|||
const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang); |
|||
const script = (value: string) => (value ?? '').trimEnd(); |
|||
return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) || |
|||
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); |
|||
}; |
|||
|
|||
/** All installed device packages of the tenant. */ |
|||
export const loadInstalledDevicePackages = async (iotHubApiService: IotHubApiService): Promise<IotHubInstalledItem[]> => { |
|||
const items: IotHubInstalledItem[] = []; |
|||
let pageLink = new PageLink(100); |
|||
let page: PageData<IotHubInstalledItem>; |
|||
do { |
|||
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); |
|||
items.push(...page.data); |
|||
pageLink = pageLink.nextPageLink(); |
|||
} while (page.hasNext); |
|||
return items; |
|||
}; |
|||
|
|||
/** |
|||
* The converters device packages installed themselves as their default converter, not ones they took as they were, of |
|||
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version |
|||
* may change. The installed items table and the update dialog both decide by it. |
|||
*/ |
|||
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => { |
|||
const ids = new Set<string>(); |
|||
for (const item of await loadInstalledDevicePackages(iotHubApiService)) { |
|||
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) { |
|||
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') { |
|||
ids.add(state.entityOutput.id); |
|||
} |
|||
} |
|||
} |
|||
return ids; |
|||
}; |
|||
|
|||
/** |
|||
* The update of the installed version itself that brings its default converter to ThingsBoard's default one. It sends only |
|||
* the converter step: the server keeps the other steps, the forms and the integration's metadata as they are. |
|||
* expectedVersion is the converter's version the user reviewed. |
|||
*/ |
|||
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => { |
|||
const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor; |
|||
return { |
|||
versionId: update.installedItem.itemVersionId, |
|||
fromVersionId: update.installedItem.itemVersionId, |
|||
selectedInstallMethod: descriptor.selectedInstallMethod, |
|||
installState: {}, |
|||
steps: [{ |
|||
name: update.converter.name, |
|||
id: update.stateKey, |
|||
type: 'UPLINK_CONVERTER', |
|||
action: 'OVERWRITE', |
|||
entityId: update.converter.id.id, |
|||
expectedVersion, |
|||
// The user confirmed it in the dialog, which names the other packages it affects
|
|||
confirmed: true, |
|||
resolution: descriptor.installState?.[update.stateKey]?.resolution ?? 'created', |
|||
defaultConverter: true, |
|||
entity: update.defaultConverter |
|||
}] |
|||
}; |
|||
}; |
|||
@ -0,0 +1,12 @@ |
|||
##### Which host should I use? |
|||
|
|||
The device connects to ThingsBoard over MQTT. Enter an address the device can reach from its own network: |
|||
|
|||
* **ThingsBoard on your computer, device on the same Wi-Fi:** your computer's IP in that network, e.g. `192.168.1.10`. Allow the MQTT port (`1883` by default) in its firewall. |
|||
* **ThingsBoard reachable from the internet** (it has a public IP or a public domain): use that address, e.g. `tb.mycompany.com` or `203.0.113.15`. The device needs internet access through its Wi-Fi. |
|||
* **Device on a local network, ThingsBoard elsewhere:** the server's local IP isn't reachable from there. Use its public domain or IP. |
|||
* **MQTT on a separate host:** enter that host. It can differ from the address you open ThingsBoard at in the browser. |
|||
|
|||
Don't use `localhost` or `127.0.0.1`: on the device they mean the device itself. |
|||
|
|||
**Port.** MQTT usually listens on port `1883`. If the transport uses another port, or the port is forwarded (Docker, load balancer), enter the port the device connects to. |
|||
@ -0,0 +1,12 @@ |
|||
##### Which host should I use? |
|||
|
|||
The gateway runs in Docker and connects to ThingsBoard over MQTT. Enter an address that the machine running the gateway can reach: |
|||
|
|||
* **Gateway on a separate machine in the same network** (e.g. a reComputer next to the equipment): the IP of the ThingsBoard server in that network, e.g. `192.168.1.10`. Allow the MQTT port (`1883` by default) in its firewall. |
|||
* **ThingsBoard reachable from the internet** (it has a public IP or a public domain): use that address, e.g. `tb.mycompany.com` or `203.0.113.15`. |
|||
* **Gateway on the same machine as ThingsBoard:** `host.docker.internal` (the package's docker-compose maps it to the machine through `extra_hosts`), or the machine's IP in its network. |
|||
* **MQTT on a separate host:** enter that host. It can differ from the address you open ThingsBoard at in the browser. |
|||
|
|||
Don't use `localhost` or `127.0.0.1`: depending on the Docker network mode, they mean the gateway container itself or the machine it runs on, not the ThingsBoard server. |
|||
|
|||
**Port.** MQTT usually listens on port `1883`. If the transport uses another port, or the port is forwarded (Docker, load balancer), enter the port the gateway connects to. |
|||
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue