Browse Source

feat(iot-hub): device install form for LoRaWAN packages

- The device install form shows placeholders, templated defaults, an
  Advanced section and a ThingsBoard connection section with the MQTT host
  and port, cleans pasted values, shows errors after the user leaves a field
  and does not let the browser autofill ThingsBoard credentials.
- A field marked by the package checks the integration connection.
- The TTN and TTI install methods are named The Things Stack Sandbox and
  The Things Stack Cloud.
- The TTN converter metadata includes the coding rate and the gateway channel.
- Deleting or updating a device package keeps the integrations, converters
  and other entities that another installed device package uses, and the
  delete dialog names them before the user confirms.
- The Open button of an installed item names what it opens.
pull/16455/head
dshvaika 1 month ago
parent
commit
db7795eecb
  1. 16
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 62
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  3. 30
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  4. 3
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  5. 9
      application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
  6. 10
      application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java
  7. 2
      application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java
  8. 94
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  9. 51
      application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java
  10. 15
      common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java
  11. 14
      common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java
  12. 15
      common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java
  13. 16
      common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java
  14. 5
      common/integration/mqtt-integrations/pom.xml
  15. 2
      common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java
  16. 62
      common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java
  17. 20
      dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java
  18. 11
      dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java
  19. 119
      dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java
  20. 15
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  21. 42
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  22. 17
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  23. 453
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  24. 136
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html
  25. 7
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss
  26. 126
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts
  27. 26
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  28. 5
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  29. 8
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss
  30. 27
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  31. 16
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  32. 23
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  33. 12
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts
  34. 36
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  35. 25
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  36. 9
      ui-ngx/src/app/shared/models/settings.models.ts
  37. 12
      ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md
  38. 4
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  39. 4
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  40. 4
      ui-ngx/src/assets/locale/locale.constant-da_DK.json
  41. 4
      ui-ngx/src/assets/locale/locale.constant-de_DE.json
  42. 4
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  43. 34
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  44. 4
      ui-ngx/src/assets/locale/locale.constant-es_ES.json
  45. 4
      ui-ngx/src/assets/locale/locale.constant-fr_FR.json
  46. 4
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  47. 4
      ui-ngx/src/assets/locale/locale.constant-it_IT.json
  48. 4
      ui-ngx/src/assets/locale/locale.constant-ja_JP.json
  49. 2
      ui-ngx/src/assets/locale/locale.constant-ka_GE.json
  50. 4
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  51. 2
      ui-ngx/src/assets/locale/locale.constant-lv_LV.json
  52. 4
      ui-ngx/src/assets/locale/locale.constant-nl_NL.json
  53. 4
      ui-ngx/src/assets/locale/locale.constant-no_NO.json
  54. 4
      ui-ngx/src/assets/locale/locale.constant-pl_PL.json
  55. 4
      ui-ngx/src/assets/locale/locale.constant-pt_BR.json
  56. 4
      ui-ngx/src/assets/locale/locale.constant-tr_TR.json
  57. 4
      ui-ngx/src/assets/locale/locale.constant-uk_UA.json
  58. 4
      ui-ngx/src/assets/locale/locale.constant-zh_CN.json

16
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -32,10 +32,13 @@ import java.util.UUID;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.dao.device.DeviceConnectivityHostSource;
import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.device.DeviceConnectivityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan; import org.thingsboard.server.service.iot_hub.InstallPlan;
import org.thingsboard.server.service.iot_hub.InstallPlanResult; import org.thingsboard.server.service.iot_hub.InstallPlanResult;
@ -153,13 +156,22 @@ public class IotHubController extends BaseController {
iotHubService.deleteInstalledItem(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); iotHubService.deleteInstalledItem(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/keptEntities")
@ResponseBody
public InstalledItemKeptEntities getInstalledItemKeptEntities(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
return iotHubService.findKeptEntities(getTenantId(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/connectivity") @GetMapping("/connectivity")
@ResponseBody @ResponseBody
public JsonNode getConnectivitySettings(HttpServletRequest request) throws Exception { public JsonNode getConnectivitySettings(HttpServletRequest request) throws Exception {
checkAllPermissions(); checkAllPermissions();
String baseUrl = systemSecurityService.getBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request); ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(getTenantId(), getCurrentUser().getCustomerId(), request);
return deviceConnectivityService.getConnectivityInfo(baseUrl); return deviceConnectivityService.getConnectivityInfo(baseUrl.url(),
baseUrl.fromRequest() ? DeviceConnectivityHostSource.REQUEST : DeviceConnectivityHostSource.BASE_URL);
} }
private void checkAllPermissions() throws ThingsboardException { private void checkAllPermissions() throws ThingsboardException {

62
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -42,6 +42,8 @@ import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemD
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.service.solutions.SolutionService; import org.thingsboard.server.service.solutions.SolutionService;
import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse; import org.thingsboard.server.service.solutions.data.solution.SolutionInstallResponse;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
@ -58,6 +60,7 @@ import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.group.EntityGroupService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.rule.RuleChainService; import org.thingsboard.server.dao.rule.RuleChainService;
@ -79,10 +82,12 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.HexFormat; import java.util.HexFormat;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -118,6 +123,7 @@ public class DefaultIotHubService implements IotHubService {
private final CalculatedFieldService calculatedFieldService; private final CalculatedFieldService calculatedFieldService;
private final DeviceProfileService deviceProfileService; private final DeviceProfileService deviceProfileService;
private final DeviceService deviceService; private final DeviceService deviceService;
private final EntityService entityService;
private final TbDeviceService tbDeviceService; private final TbDeviceService tbDeviceService;
private final SolutionService solutionService; private final SolutionService solutionService;
private final EntityGroupService entityGroupService; private final EntityGroupService entityGroupService;
@ -456,7 +462,7 @@ public class DefaultIotHubService implements IotHubService {
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
case "DEVICE" -> { case "DEVICE" -> {
DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor; DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor;
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user);
dd.setCreatedEntityIds(null); dd.setCreatedEntityIds(null);
dd.setDashboardId(null); dd.setDashboardId(null);
} }
@ -704,13 +710,24 @@ public class DefaultIotHubService implements IotHubService {
} }
} }
private void deleteDevicePackageEntities(TenantId tenantId, List<EntityId> createdEntityIds, SecurityUser user) { /**
* Deletes what a device package created, except the entities another installed device package
* also uses (e.g. an integration it took over with Overwrite): deleting those would break that package.
*/
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
List<EntityId> createdEntityIds, SecurityUser user) {
if (createdEntityIds == null || createdEntityIds.isEmpty()) { if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return; return;
} }
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId);
List<EntityId> reversed = new ArrayList<>(createdEntityIds); List<EntityId> reversed = new ArrayList<>(createdEntityIds);
Collections.reverse(reversed); Collections.reverse(reversed);
for (EntityId entityId : reversed) { for (EntityId entityId : reversed) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
continue;
}
try { try {
deleteDevicePackageEntity(tenantId, entityId, user); deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) { } catch (Exception e) {
@ -719,6 +736,45 @@ public class DefaultIotHubService implements IotHubService {
} }
} }
/** The delete dialog shows these before the user confirms, so they must match what {@link #deleteDevicePackageEntities} keeps. */
@Override
public InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId) {
IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId);
if (installedItem == null) {
throw new IllegalArgumentException("Installed item not found");
}
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId);
for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) {
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)));
usedByItems.addAll(usedBy);
}
}
}
return new InstalledItemKeptEntities(kept, usedByItems.size());
}
private Map<UUID, Set<IotHubInstalledItemId>> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) {
Map<UUID, Set<IotHubInstalledItemId>> usedBy = new HashMap<>();
PageLink pageLink = new PageLink(100);
PageData<IotHubInstalledItem> page;
do {
page = iotHubInstalledItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink);
for (IotHubInstalledItem item : page.getData()) {
if (!item.getId().equals(installedItemId)
&& item.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
dd.getCreatedEntityIds().forEach(id -> usedBy.computeIfAbsent(id.getId(), k -> new HashSet<>()).add(item.getId()));
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext());
return usedBy;
}
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
switch (entityId.getEntityType()) { switch (entityId.getEntityType()) {
case DEVICE -> { case DEVICE -> {
@ -797,7 +853,7 @@ public class DefaultIotHubService implements IotHubService {
} }
} }
} else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) {
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user); deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user);
} else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) { } else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) {
try { try {
solutionService.deleteSolution(tenantId, st, user); solutionService.deleteSolution(tenantId, st, user);

30
application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java

@ -0,0 +1,30 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.id.EntityId;
import java.util.List;
/** What deleting an installed item keeps, because other installed items use it too. */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class InstalledItemKeptEntities {
private List<KeptEntity> entities;
// How many other installed items use at least one of the kept entities
private int usedByItemsCount;
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class KeptEntity {
private EntityId entityId;
private String name;
}
}

3
application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java

@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
@ -20,6 +21,8 @@ public interface IotHubService {
void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId);
InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId);
InstallPlan resolveInstallPlan(SecurityUser user, String versionId); InstallPlan resolveInstallPlan(SecurityUser user, String versionId);
InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request); InstallPlanResult installPlan(SecurityUser user, InstallPlan plan, JsonNode data, HttpServletRequest request);

9
application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java

@ -249,6 +249,11 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
@Override @Override
public String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) { public String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) {
return resolveBaseUrl(tenantId, customerId, httpServletRequest).url();
}
@Override
public ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest) {
String baseUrl = null; String baseUrl = null;
AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general"); AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general");
@ -262,10 +267,10 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
} }
if (StringUtils.isEmpty(baseUrl) && httpServletRequest != null) { if (StringUtils.isEmpty(baseUrl) && httpServletRequest != null) {
baseUrl = MiscUtils.constructBaseUrl(httpServletRequest); return new ResolvedBaseUrl(MiscUtils.constructBaseUrl(httpServletRequest), true);
} }
return formatBaseUrl(baseUrl); return new ResolvedBaseUrl(formatBaseUrl(baseUrl), false);
} }
@Override @Override

10
application/src/main/java/org/thingsboard/server/service/security/system/ResolvedBaseUrl.java

@ -0,0 +1,10 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.security.system;
/**
* Base URL as returned by {@link SystemSecurityService#getBaseUrl}, and whether it was built from
* the request rather than taken from the Base URL in General settings.
*/
public record ResolvedBaseUrl(String url, boolean fromRequest) {
}

2
application/src/main/java/org/thingsboard/server/service/security/system/SystemSecurityService.java

@ -33,6 +33,8 @@ public interface SystemSecurityService {
String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest); String getBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest);
ResolvedBaseUrl resolveBaseUrl(TenantId tenantId, CustomerId customerId, HttpServletRequest httpServletRequest);
void logLoginAction(User user, Object authenticationDetails, ActionType actionType, Exception e); void logLoginAction(User user, Object authenticationDetails, ActionType actionType, Exception e);
void logLoginAction(User user, Object authenticationDetails, ActionType actionType, String provider, Exception e); void logLoginAction(User user, Object authenticationDetails, ActionType actionType, String provider, Exception e);

94
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub; package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
@ -13,14 +14,27 @@ import org.mockito.Mock;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -48,6 +62,16 @@ class DefaultIotHubServiceTest {
private IotHubRestClient iotHubRestClient; private IotHubRestClient iotHubRestClient;
@Mock @Mock
private IotHubInstalledItemService iotHubInstalledItemService; private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
private DeviceService deviceService;
@Mock
private EntityService entityService;
@Mock
private TbDeviceService tbDeviceService;
@Mock
private DashboardService dashboardService;
@Mock
private TbDashboardService tbDashboardService;
@Spy @Spy
@InjectMocks @InjectMocks
@ -411,4 +435,72 @@ class DefaultIotHubServiceTest {
assertThat(result.isRolledBack()).isFalse(); assertThat(result.isRolledBack()).isFalse();
assertThat(result.getErrorMessage()).contains("install failed"); assertThat(result.getErrorMessage()).contains("install failed");
} }
@Test
void deleteInstalledItem_devicePackage_keepsEntitiesAnotherDevicePackageUses() {
mockTenant();
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(deviceId, sharedDashboardId);
IotHubInstalledItem other = devicePackage(sharedDashboardId);
other.setItemName("Other package");
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
Device device = new Device(deviceId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceService).delete(device, user);
verify(dashboardService, never()).findDashboardById(any(), any());
verify(tbDashboardService, never()).delete(any(), any());
verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
}
@Test
void findKeptEntities_devicePackage_namesTheSharedEntitiesAndCountsTheOtherPackages() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId sharedDashboardId = new DashboardId(UUID.randomUUID());
DeviceProfileId sharedProfileId = new DeviceProfileId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(sharedProfileId, deviceId, sharedDashboardId);
IotHubInstalledItem first = devicePackage(sharedProfileId, sharedDashboardId);
IotHubInstalledItem second = devicePackage(sharedDashboardId);
IotHubInstalledItem unrelated = devicePackage(new DeviceId(UUID.randomUUID()));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false));
when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile"));
when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).containsExactly(
new InstalledItemKeptEntities.KeptEntity(sharedProfileId, "Shared profile"),
new InstalledItemKeptEntities.KeptEntity(sharedDashboardId, "Shared dashboard"));
assertThat(kept.getUsedByItemsCount()).isEqualTo(2);
}
@Test
void findKeptEntities_devicePackageSharingNothing_keepsNothing() {
IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()));
IotHubInstalledItem other = devicePackage(new DeviceId(UUID.randomUUID()));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, other), 1, 2, false));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).isEmpty();
assertThat(kept.getUsedByItemsCount()).isZero();
}
private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setDescriptor(descriptor);
return item;
}
} }

51
application/src/test/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityServiceTest.java

@ -8,11 +8,14 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException; import org.springframework.security.authentication.LockedException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
@ -30,6 +33,7 @@ import org.thingsboard.server.service.security.permission.UserPermissionsService
import java.util.UUID; import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
@ -201,4 +205,51 @@ public class DefaultSystemSecurityServiceTest {
verify(mailService).sendAccountLockoutEmail(eq(tenantId), eq(username), eq(notificationEmail), eq(5)); verify(mailService).sendAccountLockoutEmail(eq(tenantId), eq(username), eq(notificationEmail), eq(5));
} }
@Test
public void resolveBaseUrlTakesRequestUrlWhenDifferentUrlsAreAllowed() {
givenGeneralSettings("https://tb.example.com", false);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080");
assertThat(baseUrl.fromRequest()).isTrue();
}
@Test
public void resolveBaseUrlTakesSettingsUrlWhenDifferentUrlsAreProhibited() {
givenGeneralSettings("https://tb.example.com", true);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("https://tb.example.com");
assertThat(baseUrl.fromRequest()).isFalse();
}
@Test
public void resolveBaseUrlFallsBackToRequestWhenSettingsUrlIsEmpty() {
givenGeneralSettings("", true);
ResolvedBaseUrl baseUrl = systemSecurityService.resolveBaseUrl(tenantId, null, request());
assertThat(baseUrl.url()).isEqualTo("http://192.168.1.10:8080");
assertThat(baseUrl.fromRequest()).isTrue();
assertThat(systemSecurityService.getBaseUrl(tenantId, null, request())).isEqualTo(baseUrl.url());
}
private void givenGeneralSettings(String baseUrl, boolean prohibitDifferentUrl) {
AdminSettings generalSettings = new AdminSettings();
generalSettings.setJsonValue(JacksonUtil.newObjectNode()
.put("baseUrl", baseUrl)
.put("prohibitDifferentUrl", prohibitDifferentUrl));
when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general")).thenReturn(generalSettings);
}
private static MockHttpServletRequest request() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setScheme("http");
request.setServerName("192.168.1.10");
request.setServerPort(8080);
return request;
}
} }

15
common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityHostSource.java

@ -0,0 +1,15 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
/**
* Where the host of a transport in the device connectivity info comes from.
*/
public enum DeviceConnectivityHostSource {
/** Set explicitly in the Device connectivity settings. */
DEVICE_CONNECTIVITY,
/** Taken from the Base URL in General settings. */
BASE_URL,
/** Taken from the address of the request. */
REQUEST
}

14
common/dao-api/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityService.java

@ -13,7 +13,19 @@ public interface DeviceConnectivityService {
JsonNode findDevicePublishTelemetryCommands(String baseUrl, Device device) throws URISyntaxException; JsonNode findDevicePublishTelemetryCommands(String baseUrl, Device device) throws URISyntaxException;
JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException; /**
* Resolved host and port of each enabled transport, with the source of the host.
* A blank port is replaced with the standard port of the protocol.
*/
JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException;
/**
* Same as {@link #getConnectivityInfo(String, DeviceConnectivityHostSource)}, with a base URL
* built from the request.
*/
default JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException {
return getConnectivityInfo(baseUrl, DeviceConnectivityHostSource.REQUEST);
}
Resource getPemCertFile(String protocol); Resource getPemCertFile(String protocol);

15
common/integration/integration-api/src/main/java/org/thingsboard/integration/api/converter/wrapper/ThingsStackConverterUnwrapper.java

@ -58,9 +58,24 @@ public class ThingsStackConverterUnwrapper extends AbstractConverterUnwrapper {
.put("simulated", "/simulated") .put("simulated", "/simulated")
.put("rssi", "") .put("rssi", "")
.put("snr", "") .put("snr", "")
.put("channel", "")
.build(); .build();
} }
@Override
protected void addGatewayAdditionalInfo(Map<String, Object> kvMap, JsonNode payloadJson) {
super.addGatewayAdditionalInfo(kvMap, payloadJson);
JsonNode rxMetadata = findByMaxRssi(payloadJson.at(getGatewayInfoPath()));
if (rxMetadata != null && rxMetadata.has("channel_index")) {
kvMap.put("channel", rxMetadata.get("channel_index").asInt());
}
// The Things Stack moved the coding rate from the settings into the LoRa data rate
JsonNode loraCodingRate = payloadJson.at("/uplink_message/settings/data_rate/lora/coding_rate");
if (!kvMap.containsKey("codeRate") && loraCodingRate.isTextual()) {
kvMap.put("codeRate", loraCodingRate.asText());
}
}
@Override @Override
protected String getGatewayInfoPath() { protected String getGatewayInfoPath() {
return "/uplink_message/rx_metadata"; return "/uplink_message/rx_metadata";

16
common/integration/integration-api/src/test/java/org/thingsboard/integration/api/converter/wrapper/ConverterUnwrapperTest.java

@ -196,6 +196,22 @@ public class ConverterUnwrapperTest {
assertEquals(ContentType.JSON, result.getSecond().getContentType()); assertEquals(ContentType.JSON, result.getSecond().getContentType());
} }
@Test
public void thingsStackConverterWrapperTakesCodingRateFromLoraDataRateAndChannelFromStrongestGateway() throws Exception {
ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.TTN).get();
ObjectNode payloadMsg = JacksonUtil.fromString(readPayloadFromFile("ThingsStackPayload.json"), ObjectNode.class);
ObjectNode settings = (ObjectNode) payloadMsg.at("/uplink_message/settings");
settings.remove("coding_rate");
((ObjectNode) settings.at("/data_rate/lora")).put("coding_rate", "4/6");
((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/0")).put("channel_index", 3);
((ObjectNode) payloadMsg.at("/uplink_message/rx_metadata/1")).put("channel_index", 5);
Map<String, Object> kvMap = wrapper.unwrap(JacksonUtil.writeValueAsBytes(payloadMsg),
new UplinkMetaData<>(ContentType.JSON, Map.of())).getSecond().getKvMap();
assertThat(kvMap).containsEntry("codeRate", "4/6").containsEntry("channel", 3).containsEntry("rssi", -22);
}
@Test @Test
public void thingsParkConverterWrapperTest() throws Exception { public void thingsParkConverterWrapperTest() throws Exception {
ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.THINGPARK).get(); ConverterUnwrapper wrapper = ConverterUnwrapperFactory.getUnwrapper(IntegrationType.THINGPARK).get();

5
common/integration/mqtt-integrations/pom.xml

@ -70,6 +70,11 @@
<version>4.13.2</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

2
common/integration/mqtt-integrations/src/main/java/org/thingsboard/integration/mqtt/basic/BasicMqttIntegration.java

@ -101,6 +101,8 @@ public class BasicMqttIntegration extends AbstractMqttIntegration<BasicMqttInteg
try { try {
mqttClientConfiguration = getClientConfiguration(configuration, MqttClientConfiguration.class); mqttClientConfiguration = getClientConfiguration(configuration, MqttClientConfiguration.class);
log.debug("mqttClientConfiguration from JSON: {}", mqttClientConfiguration); log.debug("mqttClientConfiguration from JSON: {}", mqttClientConfiguration);
// The same setup as a running integration, e.g. TTN expands a region to the full host
setupConfiguration(mqttClientConfiguration);
if (mqttClientConfiguration.getConnectTimeoutSec() > ctx.getIntegrationConnectTimeoutSec() && ctx.getIntegrationConnectTimeoutSec() > 0) { if (mqttClientConfiguration.getConnectTimeoutSec() > ctx.getIntegrationConnectTimeoutSec() && ctx.getIntegrationConnectTimeoutSec() > 0) {
log.debug("Reduce connection timeout sec down to the limit [{}]", mqttClientConfiguration.getConnectTimeoutSec()); log.debug("Reduce connection timeout sec down to the limit [{}]", mqttClientConfiguration.getConnectTimeoutSec());
mqttClientConfiguration.setConnectTimeoutSec(ctx.getIntegrationConnectTimeoutSec()); mqttClientConfiguration.setConnectTimeoutSec(ctx.getIntegrationConnectTimeoutSec());

62
common/integration/mqtt-integrations/src/test/java/org/thingsboard/integration/mqtt/ttn/TtnIntegrationCheckConnectionTest.java

@ -0,0 +1,62 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.integration.mqtt.ttn;
import io.netty.channel.nio.NioEventLoopGroup;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.integration.api.IntegrationContext;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationType;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TtnIntegrationCheckConnectionTest {
private NioEventLoopGroup eventLoopGroup;
private ExecutorService executor;
private IntegrationContext context;
@Before
public void setUp() {
eventLoopGroup = new NioEventLoopGroup(1);
executor = Executors.newSingleThreadExecutor();
context = Mockito.mock(IntegrationContext.class);
Mockito.when(context.getEventLoopGroup()).thenReturn(eventLoopGroup);
Mockito.when(context.getExecutorService()).thenReturn(executor);
Mockito.when(context.getIntegrationConnectTimeoutSec()).thenReturn(1);
Mockito.when(context.getMqttClientRetransmissionMaxAttempts()).thenReturn(1);
Mockito.when(context.getMqttClientRetransmissionInitialDelayMillis()).thenReturn(1000L);
Mockito.when(context.getMqttClientRetransmissionJitterFactor()).thenReturn(0.1);
}
@After
public void tearDown() {
eventLoopGroup.shutdownGracefully();
executor.shutdownNow();
}
// The check runs the same TTN setup as a running integration, which refuses empty credentials
@Test
public void checkRefusesEmptyCredentialsBeforeConnecting() {
Integration integration = new Integration();
integration.setId(new IntegrationId(UUID.randomUUID()));
integration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
integration.setType(IntegrationType.TTN);
integration.setConfiguration(JacksonUtil.toJsonNode("{\"clientConfiguration\":{\"host\":\"eu1\",\"port\":8883,"
+ "\"connectTimeoutSec\":1,\"ssl\":true,\"credentials\":{\"type\":\"basic\",\"username\":\"\",\"password\":\"\"}}}"));
ThingsboardException e = Assert.assertThrows(ThingsboardException.class,
() -> new TtnIntegration().doCheckConnection(integration, context));
Assert.assertTrue(e.getMessage(), e.getMessage().contains("Application Credentials"));
}
}

20
dao/src/main/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImpl.java

@ -63,6 +63,13 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService
public static final String DEFAULT_DEVICE_TELEMETRY_TOPIC = "v1/devices/me/telemetry"; public static final String DEFAULT_DEVICE_TELEMETRY_TOPIC = "v1/devices/me/telemetry";
public static final String HTTP_DEFAULT_PORT = "80"; public static final String HTTP_DEFAULT_PORT = "80";
public static final String HTTPS_DEFAULT_PORT = "443"; public static final String HTTPS_DEFAULT_PORT = "443";
private static final Map<String, String> STANDARD_PORTS = Map.of(
HTTP, HTTP_DEFAULT_PORT,
HTTPS, HTTPS_DEFAULT_PORT,
MQTT, "1883",
MQTTS, "8883",
COAP, "5683",
COAPS, "5684");
private final Map<String, Resource> certs = new ConcurrentHashMap<>(); private final Map<String, Resource> certs = new ConcurrentHashMap<>();
@ -199,17 +206,16 @@ public class DeviceConnectivityServiceImpl implements DeviceConnectivityService
} }
@Override @Override
public JsonNode getConnectivityInfo(String baseUrl) throws URISyntaxException { public JsonNode getConnectivityInfo(String baseUrl, DeviceConnectivityHostSource baseUrlSource) throws URISyntaxException {
String[] protocols = {HTTP, HTTPS, MQTT, MQTTS, COAP, COAPS}; String[] protocols = {HTTP, HTTPS, MQTT, MQTTS, COAP, COAPS};
Map<String, DeviceConnectivityInfo> result = new LinkedHashMap<>(); Map<String, ResolvedDeviceConnectivityInfo> result = new LinkedHashMap<>();
for (String protocol : protocols) { for (String protocol : protocols) {
DeviceConnectivityInfo info = getConnectivity(protocol); DeviceConnectivityInfo info = getConnectivity(protocol);
if (info != null && info.isEnabled()) { if (info != null && info.isEnabled()) {
DeviceConnectivityInfo resolved = new DeviceConnectivityInfo(); result.put(protocol, new ResolvedDeviceConnectivityInfo(true,
resolved.setEnabled(true); getHost(baseUrl, info, protocol),
resolved.setHost(getHost(baseUrl, info, protocol)); StringUtils.isBlank(info.getPort()) ? STANDARD_PORTS.get(protocol) : info.getPort(),
resolved.setPort(getPort(info)); StringUtils.isNotBlank(info.getHost()) ? DeviceConnectivityHostSource.DEVICE_CONNECTIVITY : baseUrlSource));
result.put(protocol, resolved);
} }
} }
return JacksonUtil.valueToTree(result); return JacksonUtil.valueToTree(result);

11
dao/src/main/java/org/thingsboard/server/dao/device/ResolvedDeviceConnectivityInfo.java

@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
/**
* Host and port of an enabled transport as returned by {@link DeviceConnectivityService#getConnectivityInfo},
* with the source of the host. Kept apart from {@link DeviceConnectivityInfo}, which models the stored settings.
*/
public record ResolvedDeviceConnectivityInfo(boolean enabled, String host, String port,
DeviceConnectivityHostSource hostSource) {
}

119
dao/src/test/java/org/thingsboard/server/dao/device/DeviceConnectivityServiceImplTest.java

@ -0,0 +1,119 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.dao.device;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class DeviceConnectivityServiceImplTest {
private static final String BASE_URL = "http://192.168.1.10:8080";
@Mock
private AdminSettingsService adminSettingsService;
@Mock
private DeviceCredentialsService deviceCredentialsService;
@Mock
private DeviceProfileService deviceProfileService;
@InjectMocks
private DeviceConnectivityServiceImpl service;
@Test
void configuredHostIsReportedAsDeviceConnectivity() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
assertThat(mqtt.get("host").asText()).isEqualTo("10.0.0.5");
assertThat(mqtt.get("port").asText()).isEqualTo("1884");
assertThat(mqtt.get("hostSource").asText()).isEqualTo("DEVICE_CONNECTIVITY");
}
@Test
void blankHostTakesBaseUrlAndItsSource() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}""");
JsonNode fromRequest = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
JsonNode fromBaseUrl = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.BASE_URL).get("mqtt");
assertThat(fromRequest.get("host").asText()).isEqualTo("192.168.1.10");
assertThat(fromRequest.get("hostSource").asText()).isEqualTo("REQUEST");
assertThat(fromBaseUrl.get("hostSource").asText()).isEqualTo("BASE_URL");
}
@Test
void blankPortIsReplacedWithStandardPort() throws Exception {
givenConnectivity("""
{"http": {"enabled": true, "host": "", "port": ""},
"https": {"enabled": true, "host": "", "port": ""},
"mqtt": {"enabled": true, "host": "", "port": ""},
"mqtts": {"enabled": true, "host": "", "port": ""},
"coap": {"enabled": true, "host": "", "port": ""},
"coaps": {"enabled": true, "host": "", "port": ""}}""");
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST);
assertThat(info.get("http").get("port").asText()).isEqualTo("80");
assertThat(info.get("https").get("port").asText()).isEqualTo("443");
assertThat(info.get("mqtt").get("port").asText()).isEqualTo("1883");
assertThat(info.get("mqtts").get("port").asText()).isEqualTo("8883");
assertThat(info.get("coap").get("port").asText()).isEqualTo("5683");
assertThat(info.get("coaps").get("port").asText()).isEqualTo("5684");
}
@Test
void disabledProtocolIsLeftOut() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"},
"coap": {"enabled": false, "host": "", "port": "5683"}}""");
JsonNode info = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST);
assertThat(info.has("mqtt")).isTrue();
assertThat(info.has("coap")).isFalse();
}
@Test
void responseHasTheFieldsTheUiReads() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "10.0.0.5", "port": "1884"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL, DeviceConnectivityHostSource.REQUEST).get("mqtt");
assertThat(mqtt.fieldNames()).toIterable()
.containsExactlyInAnyOrder("enabled", "host", "port", "hostSource");
assertThat(mqtt.get("enabled").asBoolean()).isTrue();
}
@Test
void overloadWithoutSourceReportsRequest() throws Exception {
givenConnectivity("""
{"mqtt": {"enabled": true, "host": "", "port": "1883"}}""");
JsonNode mqtt = service.getConnectivityInfo(BASE_URL).get("mqtt");
assertThat(mqtt.get("host").asText()).isEqualTo("192.168.1.10");
assertThat(mqtt.get("hostSource").asText()).isEqualTo("REQUEST");
}
private void givenConnectivity(String json) {
AdminSettings settings = new AdminSettings();
settings.setJsonValue(JacksonUtil.toJsonNode(json));
when(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "connectivity")).thenReturn(settings);
}
}

15
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -13,13 +13,13 @@ import {
MpItemVersionView MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models'; } from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models';
import { IotHubInstalledItem, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params';
import { InterceptorConfig } from '@core/interceptors/interceptor-config'; import { InterceptorConfig } from '@core/interceptors/interceptor-config';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { getCurrentAuthState } from '@core/auth/auth.selectors'; import { getCurrentAuthState } from '@core/auth/auth.selectors';
import { DeviceConnectivitySettings } from '@shared/models/settings.models'; import { ResolvedDeviceConnectivitySettings } from '@shared/models/settings.models';
import { environment as env } from '@env/environment'; import { environment as env } from '@env/environment';
export function tbVersionToInt(version: string): number { export function tbVersionToInt(version: string): number {
@ -170,8 +170,8 @@ export class IotHubApiService {
}); });
} }
public getConnectivitySettings(config?: IotHubRequestConfig): Observable<DeviceConnectivitySettings> { public getConnectivitySettings(config?: IotHubRequestConfig): Observable<ResolvedDeviceConnectivitySettings> {
return this.http.get<DeviceConnectivitySettings>( return this.http.get<ResolvedDeviceConnectivitySettings>(
`/api/iot-hub/connectivity`, `/api/iot-hub/connectivity`,
{ params: this.buildParams(config) } { params: this.buildParams(config) }
); );
@ -269,6 +269,13 @@ export class IotHubApiService {
); );
} }
public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> {
return this.http.get<IotHubInstalledItemKeptEntities>(
`/api/iot-hub/installedItems/${installedItemId}/keptEntities`,
{ params: this.buildParams(config) }
);
}
public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> { public getItemsPublishedVersions(itemIds: string[], config?: IotHubRequestConfig): Observable<ItemPublishedVersionInfo[]> {
return this.http.post<ItemPublishedVersionInfo[]>( return this.http.post<ItemPublishedVersionInfo[]>(
`${this.baseUrl}/api/versions/publishedVersions`, `${this.baseUrl}/api/versions/publishedVersions`,

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

@ -49,13 +49,43 @@
} }
@case ('form') { @case ('form') {
<div class="tb-device-install-form flex flex-col gap-2 p-6"> <div class="tb-device-install-form p-6">
<tb-install-form-renderer <tb-install-form-renderer
[fields]="ws.formFields" [fields]="ws.formFields"
[formGroup]="ws.formGroup" [formGroup]="ws.formGroup"
[resolveImagePath]="resolveImagePathFn" [resolveImagePath]="resolveImagePathFn"
[reviewMode]="reviewMode"> [reviewMode]="reviewMode"
[checkConnectionTemplate]="connectionCheckOf(ws) && hasCheckConnectionField(ws) ? checkConnectionTpl : null">
</tb-install-form-renderer> </tb-install-form-renderer>
<ng-template #checkConnectionTpl>
<div class="flex items-center gap-4">
<button mat-stroked-button color="primary" type="button"
[disabled]="connectionCheckResult(ws) === 'checking'"
(click)="checkConnection(ws)">
{{ 'iot-hub.check-connection' | translate }}
</button>
@switch (connectionCheckMessage(ws)) {
@case ('checking') {
<mat-spinner diameter="20"></mat-spinner>
}
@case ('success') {
<span class="tb-connection-check-result flex items-center gap-2">
<mat-icon>check_circle</mat-icon>
{{ 'iot-hub.connection-check-success' | translate }}
</span>
}
@case ('error') {
<span class="tb-connection-check-result tb-connection-check-error flex items-center gap-2">
<mat-icon>error</mat-icon>
{{ 'iot-hub.connection-check-failed' | translate }}
</span>
}
}
</div>
</ng-template>
@if (connectionCheckOf(ws) && !hasCheckConnectionField(ws)) {
<ng-container *ngTemplateOutlet="checkConnectionTpl"></ng-container>
}
</div> </div>
} }
@ -207,7 +237,7 @@
@for (ws of wizardSteps; track ws.label) { @for (ws of wizardSteps; track ws.label) {
<mat-step [editable]="true" <mat-step [editable]="true"
[completed]="ws.completed" [completed]="ws.completed && !ws.formGroup?.invalid"
[stepControl]="ws.type === 'form' ? ws.formGroup : null"> [stepControl]="ws.type === 'form' ? ws.formGroup : null">
<ng-template matStepLabel>{{ ws.label }}</ng-template> <ng-template matStepLabel>{{ ws.label }}</ng-template>
<ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container> <ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container>
@ -252,7 +282,11 @@
@case ('form') { @case ('form') {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container> <ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-stroked-button color="primary" (click)="nextStep()"> <button mat-stroked-button color="primary" (click)="nextStep()">
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}} @if (continueAnyway) {
{{ 'iot-hub.continue-anyway' | translate }}
} @else {
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
}
</button> </button>
} }
@case ('progress') { @case ('progress') {

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

@ -195,6 +195,23 @@
} }
} }
.tb-connection-check-result {
font-size: 14px;
color: #198038;
mat-icon {
color: #198038;
}
&.tb-connection-check-error {
color: #dd2c00;
mat-icon {
color: #dd2c00;
}
}
}
.tb-progress-divider { .tb-progress-divider {
width: 1px; width: 1px;
height: 16px; height: 16px;

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

@ -7,10 +7,10 @@ import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component'; import { DialogComponent } from '@shared/components/dialog.component';
import { UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { AbstractControl, UntypedFormControl, UntypedFormGroup, ValidationErrors, Validators } from '@angular/forms';
import { MatStepper } from '@angular/material/stepper'; import { MatStepper } from '@angular/material/stepper';
import { StepperSelectionEvent } from '@angular/cdk/stepper'; import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom, Subscription } from 'rxjs';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { PageLink } from '@shared/models/page/page-link'; import { PageLink } from '@shared/models/page/page-link';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
@ -29,6 +29,7 @@ import { IntegrationService } from '@core/http/integration.service';
import { Converter, ConverterType } from '@shared/models/converter.models'; import { Converter, ConverterType } from '@shared/models/converter.models';
import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service'; import { AiDashboardGenerationService } from '@home/components/ai/ai-dashboard-generation.service';
import { import {
cleanFormFieldValue,
DeviceInstallStep, DeviceInstallStep,
DevicePackageInfo, DevicePackageInfo,
ENTITY_STEP_TYPES, ENTITY_STEP_TYPES,
@ -38,10 +39,16 @@ import {
FormFieldType, FormFieldType,
installMethodIcons as INSTALL_METHOD_ICONS, installMethodIcons as INSTALL_METHOD_ICONS,
installMethodLabels as INSTALL_METHOD_LABELS, installMethodLabels as INSTALL_METHOD_LABELS,
InstallMethod,
InstallStepType, InstallStepType,
stepTypeAliasMap stepTypeAliasMap
} from '@shared/models/iot-hub/device-package.models'; } from '@shared/models/iot-hub/device-package.models';
import { mergeMap } from 'rxjs/operators'; import { mergeMap } from 'rxjs/operators';
import {
DeviceConnectivityHostSource,
DeviceConnectivityProtocol,
ResolvedDeviceConnectivityInfo
} from '@shared/models/settings.models';
export interface DeviceInstallDialogData { export interface DeviceInstallDialogData {
item: MpItemVersionView; item: MpItemVersionView;
@ -63,15 +70,127 @@ export interface WizardStep {
markdown?: string; markdown?: string;
// Form // Form
formFields?: FormFieldDefinition[]; formFields?: FormFieldDefinition[];
// Fields the dialog adds on top of the package's form file
extraFormFields?: FormFieldDefinition[];
// Key of the step's form values in the install state; the label when not set
stateKey?: string;
formGroup?: UntypedFormGroup; formGroup?: UntypedFormGroup;
// Connection check of the integration the form configures; null when the form configures none
connectionCheck?: ConnectionCheck | null;
// Progress // Progress
entitySteps?: EntityStepProgress[]; entitySteps?: EntityStepProgress[];
progressError?: string; progressError?: string;
progressDone?: boolean; progressDone?: boolean;
} }
export interface ConnectionCheck {
// The INTEGRATION step template that the form values fill
template: string;
status: 'idle' | 'checking' | 'success' | 'error';
// The values the status is for, as JSON: only the fields the integration template uses
checkedValues?: string;
// The result shows next to the button for a few seconds after the check
resultVisible?: boolean;
resultTimer?: ReturnType<typeof setTimeout>;
}
const ENTITY_STEP_MIN_DELAY = 2000; const ENTITY_STEP_MIN_DELAY = 2000;
const CONNECTION_CHECK_RESULT_MS = 5000;
const DEFAULT_RANDOM_SIZE = 20; const DEFAULT_RANDOM_SIZE = 20;
const TRANSPORT_HOST_FIELD_KEY = 'tbTransportHost';
const TRANSPORT_PORT_FIELD_KEY = 'tbTransportPort';
// Not the translated label, so review mode finds the values in any UI language
const TRANSPORT_STEP_STATE_KEY = 'tbTransportConnection';
/**
* A transport whose ${<protocol>.host} / ${<protocol>.port} the install form lets the user check,
* with the translation keys of its fields. The wording is per transport (the label, the hints and
* the help popup name the protocol and its default port), so each entry brings its own keys.
*/
interface HostFieldTransport {
protocol: DeviceConnectivityProtocol;
hostLabel: string;
portLabel: string;
// Hint by the source of the host; REQUEST is used when the source is unknown
hostHints: Partial<Record<DeviceConnectivityHostSource, string>> & { REQUEST: string };
// Hint by the source of a host that resolved to a loopback address; loopbackHint when there is none
loopbackHints: Partial<Record<DeviceConnectivityHostSource, string>>;
loopbackHint: string;
// Review mode: the stored value is shown without its source
reviewHostHint: string;
// Host set in Device connectivity: the fields are read-only
configuredHint: string;
hostError: string;
portError: string;
helpPopupId: string;
helpPopupText: string;
}
// Install methods whose packages get the transport fields. Other methods use the host differently
// (a ChirpStack package builds the ThingsBoard URL from it, a gateway puts it into docker-compose)
// and keep the resolved value until they are handled separately.
const HOST_FIELD_TRANSPORTS = new Map<string, HostFieldTransport>([
[InstallMethod.DIRECT_MQTT, {
protocol: 'mqtt',
hostLabel: 'iot-hub.device-install-mqtt-host',
portLabel: 'iot-hub.device-install-mqtt-port',
hostHints: {
REQUEST: 'iot-hub.device-install-mqtt-host-request-hint',
BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-hint'
},
loopbackHints: {
REQUEST: 'iot-hub.device-install-mqtt-host-opened-via-loopback-hint',
BASE_URL: 'iot-hub.device-install-mqtt-host-base-url-loopback-hint'
},
loopbackHint: 'iot-hub.device-install-mqtt-host-loopback-hint',
reviewHostHint: 'iot-hub.device-install-mqtt-host-hint',
configuredHint: 'iot-hub.device-install-mqtt-host-configured-hint',
hostError: 'iot-hub.device-install-transport-host-error',
portError: 'iot-hub.device-install-transport-port-error',
helpPopupId: 'iot-hub/device-connection-host',
helpPopupText: 'iot-hub.device-install-which-host'
}]
]);
/**
* Reduces what a user may paste (a URL, host:port, [IPv6]:port) to the bare host: the port is
* a separate setting, and the scheme or path would end up in the firmware as part of the host.
*/
const toBareHost = (value: string): string => {
const hostPort = value.trim().replace(/^[a-z][a-z\d+.-]*:\/\//i, '').replace(/[/?#].*$/, '');
const bracketed = hostPort.match(/^\[([^\]]*)](:\d*)?$/);
if (bracketed) {
return bracketed[1];
}
// A bare IPv6 address has several colons; a single one separates the port.
const parts = hostPort.split(':');
return parts.length === 2 ? parts[0] : hostPort;
};
// localhost, 127.0.0.0/8, ::1 and 0.0.0.0: a device can't reach the server at any of them.
// Unlike DeviceConnectivityUtil.isLocalhost this doesn't resolve hostnames, and it also
// rejects 0.0.0.0, which isn't a loopback address but is just as unreachable.
// Takes a bare host (see toBareHost).
const isLoopbackHost = (host: string): boolean => {
const h = host.toLowerCase();
return h === 'localhost' || h === '::1' || h === '0.0.0.0' || /^127(\.\d{1,3}){3}$/.test(h);
};
// Host name, IPv4 or IPv6 characters only: the value goes into C string literals and JSON templates.
const HOST_PATTERN = /^[a-z\d._:-]+$/i;
const transportHostValidator = (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
const host = toBareHost(control.value);
return !HOST_PATTERN.test(host) || isLoopbackHost(host) ? { transportHost: true } : null;
};
const isValidPort = (port: number): boolean => Number.isInteger(port) && port >= 1 && port <= 65535;
const transportPortValidator = (control: AbstractControl): ValidationErrors | null =>
control.value === null || control.value === '' || isValidPort(Number(control.value)) ? null : { transportPort: true };
@Component({ @Component({
selector: 'tb-device-install-dialog', selector: 'tb-device-install-dialog',
@ -108,15 +227,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// Variable resolution state // Variable resolution state
formValues: Record<string, any> = {}; formValues: Record<string, any> = {};
private formTemplateSubscriptions: Subscription[] = [];
entityOutputs = new Map<string, EntityStepOutput>(); entityOutputs = new Map<string, EntityStepOutput>();
transportVars: Record<string, string> = {}; transportVars: Record<string, string> = {};
// Routing key pre-allocated for the in-flight INTEGRATION step so ${routingKey} // Routing key pre-allocated for the in-flight INTEGRATION step so ${routingKey}
// placeholders (e.g. inside clientConfiguration.httpEndpoint emitted by the // placeholders (e.g. inside clientConfiguration.httpEndpoint emitted by the
// export pipeline) substitute to the value we'll save. // export pipeline) substitute to the value we'll save.
private pendingRoutingKey: string | undefined; private pendingRoutingKey: string | undefined;
// protocol → where the server took its host from
private transportHostSources: Partial<Record<DeviceConnectivityProtocol, DeviceConnectivityHostSource>> = {};
// form-field key → declared type. Used by resolveTemplateJson() to emit BOOLEAN/INTEGER // form-field key → declared type. Used by resolveTemplateJson() to emit BOOLEAN/INTEGER
// placeholders as raw JSON values instead of quoted strings. // placeholders as raw JSON values instead of quoted strings.
private fieldTypes = new Map<string, FormFieldType>(); private fieldTypes = new Map<string, FormFieldType>();
// Transport whose ${<protocol>.host} the transport host field overrides
private hostFieldProtocol: DeviceConnectivityProtocol | null = null;
gatewayDockerComposeContent: string | null = null; gatewayDockerComposeContent: string | null = null;
resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this); resolveMarkdownVariable: (key: string) => string | undefined = this._resolveMarkdownVariable.bind(this);
@ -175,10 +299,11 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
try { try {
const connectivity = await firstValueFrom(this.iotHubApiService.getConnectivitySettings({ ignoreErrors: true })); const connectivity = await firstValueFrom(this.iotHubApiService.getConnectivitySettings({ ignoreErrors: true }));
if (connectivity) { if (connectivity) {
for (const [protocol, info] of Object.entries(connectivity)) { for (const [protocol, info] of Object.entries(connectivity) as [DeviceConnectivityProtocol, ResolvedDeviceConnectivityInfo][]) {
if (info) { if (info) {
this.transportVars[`${protocol}.host`] = info.host || ''; this.transportVars[`${protocol}.host`] = info.host || '';
this.transportVars[`${protocol}.port`] = String(info.port || ''); this.transportVars[`${protocol}.port`] = String(info.port || '');
this.transportHostSources[protocol] = info.hostSource;
} }
} }
} }
@ -191,6 +316,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.selectedInstallMethod = this.data.selectedInstallMethod; this.selectedInstallMethod = this.data.selectedInstallMethod;
this.restoreInstallState(this.data.installState); this.restoreInstallState(this.data.installState);
this.startWizard(); this.startWizard();
// After startWizard: the transport fields it adds take part in resolving the file
this.resolveGatewayDockerCompose();
} else if (this.availableInstallMethods.length === 1) { } else if (this.availableInstallMethods.length === 1) {
// Single method: skip the selector and start the wizard. // Single method: skip the selector and start the wizard.
this.selectedInstallMethod = this.availableInstallMethods[0]; this.selectedInstallMethod = this.availableInstallMethods[0];
@ -205,6 +332,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} }
ngOnDestroy() { ngOnDestroy() {
this.formTemplateSubscriptions.forEach(subscription => subscription.unsubscribe());
this.wizardSteps?.forEach(ws => clearTimeout(ws.connectionCheck?.resultTimer));
for (const url of this.zipImages.values()) { for (const url of this.zipImages.values()) {
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} }
@ -299,7 +428,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} }
} }
nextStep(): void { async nextStep(): Promise<void> {
const step = this.currentWizardStep; const step = this.currentWizardStep;
if (!step) { if (!step) {
return; return;
@ -308,6 +437,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
step.formGroup.markAllAsTouched(); step.formGroup.markAllAsTouched();
return; return;
} }
// Checks the connection unless these values were already checked; after a failed check,
// Next continues anyway.
const check = this.connectionCheckOf(step);
if (check && check.checkedValues !== this.checkedValuesOf(step, check)) {
if (check.status === 'checking' || !(await this.checkConnection(step))) {
return;
}
}
if (this.isLastWizardStep) { if (this.isLastWizardStep) {
this.done(); this.done();
return; return;
@ -317,19 +454,146 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.stepper.next(); this.stepper.next();
} }
connectionCheckOf(ws: WizardStep): ConnectionCheck | undefined {
if (this.reviewMode || ws.type !== 'form' || !ws.formFields) {
return undefined;
}
if (ws.connectionCheck === undefined) {
const template = this.findIntegrationTemplate(ws);
ws.connectionCheck = template ? { template, status: 'idle' } : null;
}
return ws.connectionCheck ?? undefined;
}
/** True when the package puts the Check connection button under one of its fields. */
hasCheckConnectionField(ws: WizardStep): boolean {
return !!ws.formFields?.some(field => field.checkConnection);
}
/** The result of the last check, while the form still has the values it checked. */
connectionCheckResult(ws: WizardStep): ConnectionCheck['status'] | undefined {
const check = this.connectionCheckOf(ws);
if (!check || check.status === 'idle') {
return undefined;
}
if (check.status === 'checking' || check.checkedValues === this.checkedValuesOf(ws, check)) {
return check.status;
}
return undefined;
}
async checkConnection(ws: WizardStep): Promise<boolean> {
const check = this.connectionCheckOf(ws);
if (!check) {
return true;
}
if (ws.formGroup.invalid) {
ws.formGroup.markAllAsTouched();
return false;
}
this.cleanFormStep(ws);
const values = ws.formGroup.getRawValue();
check.status = 'checking';
this.cdr.detectChanges();
const committedValues = this.formValues;
let body: any;
try {
// The integration is built the way Provisioning builds it, from the values not committed yet
this.formValues = { ...committedValues, ...values };
body = this.resolveTemplateJson(this.zipFiles.get(check.template));
} finally {
this.formValues = committedValues;
}
// The check requires a routing key; Provisioning adds one the same way
if (!body.routingKey) body.routingKey = this.generateUuid();
if (!body.configuration) body.configuration = {};
if (body.configuration.metadata == null) body.configuration.metadata = {};
try {
await firstValueFrom(this.integrationService.checkIntegrationConnection(body, { ignoreErrors: true }));
check.status = 'success';
} catch {
check.status = 'error';
}
check.checkedValues = this.checkedValuesOf(ws, check);
check.resultVisible = true;
clearTimeout(check.resultTimer);
check.resultTimer = setTimeout(() => {
check.resultVisible = false;
this.cdr.detectChanges();
}, CONNECTION_CHECK_RESULT_MS);
this.cdr.detectChanges();
return check.status === 'success';
}
/** What shows next to the button: the spinner while checking, then the result for a few seconds. */
connectionCheckMessage(ws: WizardStep): ConnectionCheck['status'] | undefined {
const check = this.connectionCheckOf(ws);
if (check?.status === 'checking') {
return 'checking';
}
return check?.resultVisible && check.checkedValues === this.checkedValuesOf(ws, check) ? check.status : undefined;
}
/** True when the last check of the current values failed, so Next continues anyway. */
get continueAnyway(): boolean {
const step = this.currentWizardStep;
return !!step && this.connectionCheckResult(step) === 'error';
}
/**
* The values of the connection fields: the ones the integration template puts into its configuration
* (host, port, credentials), not e.g. its name. Other fields don't reset the check result.
*/
private checkedValuesOf(ws: WizardStep, check: ConnectionCheck): string {
const content = this.zipFiles.get(check.template) ?? '';
const configurationStart = content.indexOf('"configuration"');
const template = configurationStart >= 0 ? content.substring(configurationStart) : content;
const values = this.cleanedFormValues(ws);
const used = ws.formFields
.filter(field => template.includes(`\${${field.key}}`))
.map(field => [field.key, values[field.key]]);
return JSON.stringify(used);
}
private findIntegrationTemplate(ws: WizardStep): string | undefined {
for (const step of this.wizardSteps.flatMap(w => w.rawSteps)) {
if (step.type !== InstallStepType.INTEGRATION || !step.template) {
continue;
}
const content = this.zipFiles.get(step.template) ?? '';
if (ws.formFields.some(field => content.includes(`\${${field.key}}`))) {
return step.template;
}
}
return undefined;
}
onStepSelectionChange(event: StepperSelectionEvent): void { onStepSelectionChange(event: StepperSelectionEvent): void {
if (event.selectedIndex <= event.previouslySelectedIndex) { if (event.selectedIndex <= event.previouslySelectedIndex) {
return; return;
} }
// Forward moves can come from the stepper header, which bypasses nextStep(), // Forward moves can come from the stepper header, which bypasses nextStep(),
// so commit every step being passed over here. // so commit every step being passed over here.
let formValuesChanged = false;
for (let i = event.previouslySelectedIndex; i < event.selectedIndex; i++) { for (let i = event.previouslySelectedIndex; i < event.selectedIndex; i++) {
const ws = this.wizardSteps[i]; const ws = this.wizardSteps[i];
if (ws.type === 'form') { if (ws.type === 'form') {
// Keep the bare host, so the stored state and the form after Back show what the device gets
const hostControl = ws.formGroup.get(TRANSPORT_HOST_FIELD_KEY);
if (hostControl?.enabled && hostControl.value) {
hostControl.setValue(toBareHost(hostControl.value), { emitEvent: false });
}
this.cleanFormStep(ws);
Object.assign(this.formValues, ws.formGroup.getRawValue()); Object.assign(this.formValues, ws.formGroup.getRawValue());
formValuesChanged = true;
} }
ws.completed = true; ws.completed = true;
} }
if (formValuesChanged) {
// Instruction steps stay rendered, and their markdown only changes when the resolver does:
// after Back and a corrected value, they would otherwise keep showing the old one.
this.resolveMarkdownVariable = this._resolveMarkdownVariable.bind(this);
}
this.onStepActivated(this.wizardSteps[event.selectedIndex]); this.onStepActivated(this.wizardSteps[event.selectedIndex]);
} }
@ -498,6 +762,18 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (key in this.formValues) { if (key in this.formValues) {
return String(this.formValues[key]); return String(this.formValues[key]);
} }
if (this.hostFieldProtocol && key === `${this.hostFieldProtocol}.host`) {
const host = toBareHost(String(this.formValues[TRANSPORT_HOST_FIELD_KEY] ?? ''));
if (host) {
return host;
}
}
if (this.hostFieldProtocol && key === `${this.hostFieldProtocol}.port`) {
const port = this.formValues[TRANSPORT_PORT_FIELD_KEY];
if (port !== undefined && port !== null && port !== '') {
return String(port);
}
}
if (key in this.transportVars) { if (key in this.transportVars) {
return this.transportVars[key]; return this.transportVars[key];
} }
@ -599,7 +875,9 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} }
} }
} }
// Resolve gateway docker-compose if available }
private resolveGatewayDockerCompose(): void {
const gatewayStep = (this.packageInfo.installSteps[this.selectedInstallMethod] || []).find(s => s.type === 'GATEWAY'); const gatewayStep = (this.packageInfo.installSteps[this.selectedInstallMethod] || []).find(s => s.type === 'GATEWAY');
if (gatewayStep?.dockerCompose) { if (gatewayStep?.dockerCompose) {
const raw = this.zipFiles.get(gatewayStep.dockerCompose); const raw = this.zipFiles.get(gatewayStep.dockerCompose);
@ -665,6 +943,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private appendInstallSteps(): void { private appendInstallSteps(): void {
const rawSteps = this.packageInfo.installSteps[this.selectedInstallMethod] || []; const rawSteps = this.packageInfo.installSteps[this.selectedInstallMethod] || [];
const firstInstallStep = this.wizardSteps.length;
let i = 0; let i = 0;
while (i < rawSteps.length) { while (i < rawSteps.length) {
const step = rawSteps[i]; const step = rawSteps[i];
@ -702,6 +981,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
i++; i++;
} }
} }
this.addTransportFields(firstInstallStep);
// Initialize form groups // Initialize form groups
for (const ws of this.wizardSteps) { for (const ws of this.wizardSteps) {
if (ws.type === 'form' && !ws.formGroup) { if (ws.type === 'form' && !ws.formGroup) {
@ -710,12 +990,101 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
} }
} }
/**
* Packages write ${<protocol>.host} and ${<protocol>.port} into sketches and templates. Show them
* in the last form before the host is first used. When the system administrator set the host in
* Device connectivity, they are read-only. Otherwise the user can correct them — and must, when
* the host resolved to localhost, which on the device is the device itself.
*/
private addTransportFields(fromIndex: number): void {
this.hostFieldProtocol = null;
const transport = HOST_FIELD_TRANSPORTS.get(this.selectedInstallMethod);
const protocol = transport?.protocol;
const resolvedHost = protocol ? this.transportVars[`${protocol}.host`] : undefined;
if (resolvedHost === undefined) {
return;
}
const steps = this.wizardSteps.slice(fromIndex);
const firstUse = steps.findIndex(ws => this.usesVariable(ws, `${protocol}.host`));
if (firstUse < 0) {
return;
}
const loopback = !resolvedHost || isLoopbackHost(resolvedHost);
const hostSource = this.transportHostSources[protocol];
const readOnly = hostSource === 'DEVICE_CONNECTIVITY' && !loopback;
let formStep = steps.slice(0, firstUse).reverse().find(ws => ws.type === 'form');
if (!formStep) {
formStep = {
type: 'form',
label: this.translate.instant('iot-hub.device-install-transport-host-step'),
stateKey: TRANSPORT_STEP_STATE_KEY,
rawSteps: [],
completed: this.reviewMode
};
this.wizardSteps.splice(fromIndex + firstUse, 0, formStep);
}
let hostHint: string;
if (readOnly) {
hostHint = transport.configuredHint;
} else if (this.reviewMode) {
hostHint = transport.reviewHostHint;
} else if (loopback) {
hostHint = (hostSource && transport.loopbackHints[hostSource]) || transport.loopbackHint;
} else {
hostHint = (hostSource && transport.hostHints[hostSource]) || transport.hostHints.REQUEST;
}
const helpPopupId = readOnly ? undefined : transport.helpPopupId;
const group = this.translate.instant('iot-hub.device-install-thingsboard-connection');
formStep.extraFormFields = [{
key: TRANSPORT_HOST_FIELD_KEY,
label: this.translate.instant(transport.hostLabel),
type: FormFieldType.STRING,
defaultValue: loopback ? '' : resolvedHost,
required: true,
readOnly,
helpText: this.translate.instant(hostHint, { host: resolvedHost }),
// Shown on the transportHost error of transportHostValidator
errorMessage: this.translate.instant(transport.hostError),
helpPopupId,
helpPopupText: helpPopupId ? this.translate.instant(transport.helpPopupText) : undefined,
group,
row: TRANSPORT_HOST_FIELD_KEY
}];
if (steps.some(ws => this.usesVariable(ws, `${protocol}.port`))) {
const resolvedPort = Number(this.transportVars[`${protocol}.port`]);
formStep.extraFormFields.push({
key: TRANSPORT_PORT_FIELD_KEY,
label: this.translate.instant(transport.portLabel),
type: FormFieldType.INTEGER,
defaultValue: isValidPort(resolvedPort) ? resolvedPort : '',
required: true,
readOnly,
// Shown on the transportPort error of transportPortValidator
errorMessage: this.translate.instant(transport.portError),
group,
row: TRANSPORT_HOST_FIELD_KEY,
width: 200
});
}
this.hostFieldProtocol = protocol;
}
private usesVariable(ws: WizardStep, key: string): boolean {
const placeholder = `\${${key}}`;
return ws.rawSteps.some(step =>
[step.file, step.template, step.serverAttributes, step.sharedAttributes, step.credentials, step.dockerCompose]
.some(file => file && this.zipFiles.get(file)?.includes(placeholder)));
}
private initFormStep(ws: WizardStep): void { private initFormStep(ws: WizardStep): void {
const formJson = this.zipFiles.get(ws.rawSteps[0].file) || '[]'; const formJson = (ws.rawSteps[0] && this.zipFiles.get(ws.rawSteps[0].file)) || '[]';
ws.formFields = JSON.parse(formJson) as FormFieldDefinition[]; // These are for the fields the dialog adds; a package can't set them
const packageFields = (JSON.parse(formJson) as FormFieldDefinition[])
.map(({ helpPopupId, helpPopupText, errorMessage, ...field }) => field);
ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])];
const controls: Record<string, UntypedFormControl> = {}; const controls: Record<string, UntypedFormControl> = {};
// In review mode, use stored values; otherwise use defaults // In review mode, use stored values; otherwise use defaults
const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues;
for (const field of ws.formFields) { for (const field of ws.formFields) {
this.fieldTypes.set(field.key, field.type); this.fieldTypes.set(field.key, field.type);
const validators = []; const validators = [];
@ -723,16 +1092,78 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
validators.push(Validators.required); validators.push(Validators.required);
} }
if (field.validators?.length > 0) { if (field.validators?.length > 0) {
validators.push(Validators.pattern(field.validators[0].pattern)); const pattern = Validators.pattern(field.validators[0].pattern);
validators.push((control: AbstractControl) =>
pattern({ value: cleanFormFieldValue(field, control.value) } as AbstractControl));
}
if (field.key === TRANSPORT_HOST_FIELD_KEY) {
validators.push(transportHostValidator);
} else if (field.key === TRANSPORT_PORT_FIELD_KEY) {
validators.push(transportPortValidator);
} }
const initialValue = this.resolveInitialFieldValue(field, storedValues?.[field.key]); const initialValue = this.resolveInitialFieldValue(field, storedValues?.[field.key]);
controls[field.key] = new UntypedFormControl(initialValue, validators); controls[field.key] = new UntypedFormControl({ value: initialValue, disabled: !!field.readOnly }, validators);
} }
ws.formGroup = new UntypedFormGroup(controls); ws.formGroup = new UntypedFormGroup(controls);
if (this.reviewMode) { if (this.reviewMode) {
ws.formGroup.disable(); ws.formGroup.disable();
ws.completed = true; ws.completed = true;
} else {
this.applyDefaultValueTemplates(ws, storedValues);
}
}
/**
* Keeps each field with a defaultValueTemplate filled from the other fields until the user edits it.
* A template with an empty field gives an empty value, so the placeholder shows instead.
*/
private applyDefaultValueTemplates(ws: WizardStep, storedValues: Record<string, any> | undefined): void {
const templated = ws.formFields.filter(field => field.defaultValueTemplate && storedValues?.[field.key] === undefined);
if (!templated.length) {
return;
}
const update = () => {
for (const field of templated) {
const control = ws.formGroup.controls[field.key];
if (!control.dirty) {
control.setValue(this.renderFormTemplate(field.defaultValueTemplate, this.cleanedFormValues(ws)), { emitEvent: false });
}
}
};
update();
this.formTemplateSubscriptions.push(ws.formGroup.valueChanges.subscribe(update));
}
/** Applies each field's cleanupPattern to its control, so the stored values are the cleaned ones. */
private cleanFormStep(ws: WizardStep): void {
for (const field of ws.formFields) {
const control = ws.formGroup.controls[field.key];
const cleaned = cleanFormFieldValue(field, control?.value);
if (control?.enabled && cleaned !== control.value) {
control.setValue(cleaned, { emitEvent: false });
}
}
}
private cleanedFormValues(ws: WizardStep): Record<string, any> {
const values = ws.formGroup.getRawValue();
for (const field of ws.formFields) {
values[field.key] = cleanFormFieldValue(field, values[field.key]);
} }
return values;
}
private renderFormTemplate(template: string, values: Record<string, any>): string {
let missing = false;
const result = template.replace(/\$\{([^}]+)}/g, (_, key: string) => {
const value = values[key];
if (value === undefined || value === null || value === '') {
missing = true;
return '';
}
return String(value);
});
return missing ? '' : result;
} }
private resolveInitialFieldValue(field: FormFieldDefinition, storedValue: any): any { private resolveInitialFieldValue(field: FormFieldDefinition, storedValue: any): any {
@ -1252,7 +1683,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const state: Record<string, any> = {}; const state: Record<string, any> = {};
for (const ws of this.wizardSteps) { for (const ws of this.wizardSteps) {
if (ws.type === 'form' && ws.formGroup) { if (ws.type === 'form' && ws.formGroup) {
state[ws.label] = { formValues: ws.formGroup.getRawValue() }; state[ws.stateKey ?? ws.label] = { formValues: ws.formGroup.getRawValue() };
} else if (ws.type === 'progress' && ws.entitySteps) { } else if (ws.type === 'progress' && ws.entitySteps) {
for (const ep of ws.entitySteps) { for (const ep of ws.entitySteps) {
if (ep.status === 'success' && ep.entityOutput) { if (ep.status === 'success' && ep.entityOutput) {

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

@ -7,19 +7,78 @@
--> -->
@if (formGroup) { @if (formGroup) {
<form [formGroup]="formGroup" class="tb-install-form flex flex-col gap-4"> <form [formGroup]="formGroup" class="tb-install-form flex flex-col gap-4">
@for (field of fields; track field.key; let i = $index) { <ng-container *ngTemplateOutlet="sectionsTemplate; context: { $implicit: sections }"></ng-container>
@if (advancedSections.length) {
<section class="tb-form-panel stroked no-padding">
<mat-expansion-panel class="tb-settings">
<mat-expansion-panel-header style="padding: 16px">
<mat-panel-title>{{ 'iot-hub.advanced-settings' | translate }}</mat-panel-title>
</mat-expansion-panel-header>
<div class="tb-form-panel no-border no-padding-top">
<ng-container *ngTemplateOutlet="sectionsTemplate; context: { $implicit: advancedSections }"></ng-container>
</div>
</mat-expansion-panel>
</section>
}
<ng-template #sectionsTemplate let-sections>
@for (section of sections; track $index) {
@if (section.title) {
<section class="tb-form-panel stroked">
<h3 class="tb-form-panel-title m-0">{{ section.title }}</h3>
<ng-container *ngTemplateOutlet="rowsTemplate; context: { $implicit: section.rows }"></ng-container>
</section>
} @else {
<ng-container *ngTemplateOutlet="rowsTemplate; context: { $implicit: section.rows }"></ng-container>
}
}
</ng-template>
@if (shouldRenderGroupHeader(field, i)) { <ng-template #rowsTemplate let-rows>
<h4 class="tb-install-form-group-header">{{ field.group }}</h4> @for (row of rows; track row.fields[0].key) {
<div class="flex flex-col gap-2">
@if (row.fields.length > 1) {
<div class="flex gap-4">
@for (field of row.fields; track field.key) {
<div class="flex min-w-0 flex-col" [class.flex-1]="!field.width"
[style.flex]="field.width ? '0 1 ' + field.width + 'px' : null">
<ng-container *ngTemplateOutlet="fieldTemplate; context: { $implicit: field }"></ng-container>
</div>
}
</div>
} @else {
<ng-container *ngTemplateOutlet="fieldTemplate; context: { $implicit: row.fields[0] }"></ng-container>
}
<!-- A field with a help popup shows its hint under the row, next to the popup trigger -->
@for (field of row.fields; track field.key) {
@if (hasHintBox(field)) {
<div class="tb-form-hint tb-primary-fill flex items-center justify-between gap-5">
<div class="w-full">{{ helpTextOf(field) }}</div>
<div class="flex shrink-0"
[tb-help-popup]="field.helpPopupId"
hintMode
tb-help-popup-placement="top"
trigger-style="letter-spacing:0.25px; font-size:12px"
[tb-help-popup-style]="{maxWidth: '640px'}"
[trigger-text]="field.helpPopupText"></div>
</div>
}
}
@if (checkConnectionTemplate && hasCheckConnectionField(row.fields)) {
<ng-container *ngTemplateOutlet="checkConnectionTemplate"></ng-container>
}
</div>
} }
</ng-template>
<ng-template #fieldTemplate let-field>
@if (isSecretWidget(field)) { @if (isSecretWidget(field)) {
<!-- secretSupport=true: render Secret picker (handles plaintext + Secret refs internally) --> <!-- secretSupport=true: render Secret picker (handles plaintext + Secret refs internally) -->
<tb-secret-key-input appearance="outline" <tb-secret-key-input appearance="outline"
[formControlName]="field.key" [formControlName]="field.key"
[label]="field.label" [label]="field.label"
[required]="field.required" [required]="field.required"
[hint]="field.helpText" [hint]="helpTextOf(field)"
[inputType]="field.type === FormFieldType.PASSWORD ? 'password' : 'text'"> [inputType]="field.type === FormFieldType.PASSWORD ? 'password' : 'text'">
</tb-secret-key-input> </tb-secret-key-input>
} @else { } @else {
@ -29,15 +88,16 @@
<mat-checkbox [formControlName]="field.key">{{ field.label }}</mat-checkbox> <mat-checkbox [formControlName]="field.key">{{ field.label }}</mat-checkbox>
} }
@case (FormFieldType.SELECT) { @case (FormFieldType.SELECT) {
<mat-form-field appearance="outline"> <mat-form-field appearance="outline" [subscriptSizing]="isInHintBoxRow(field) ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}</mat-label>
<mat-select [formControlName]="field.key"> <mat-select [formControlName]="field.key">
@for (opt of field.options; track opt.value) { @for (opt of field.options; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option> <mat-option [value]="opt.value">{{ opt.label }}</mat-option>
} }
</mat-select> </mat-select>
@if (field.helpText) { @if (helpTextOf(field) && !hasHintBox(field)) {
<mat-hint>{{ field.helpText }}</mat-hint> <mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }
@if (formGroup.controls[field.key]?.hasError('required')) { @if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error> <mat-error>{{ field.label + ' is required' }}</mat-error>
@ -45,16 +105,19 @@
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.STRING_AUTOCOMPLETE) { @case (FormFieldType.STRING_AUTOCOMPLETE) {
<mat-form-field appearance="outline"> <mat-form-field appearance="outline" [subscriptSizing]="isInHintBoxRow(field) ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}</mat-label>
<input matInput [formControlName]="field.key" [matAutocomplete]="auto"> <input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" [matAutocomplete]="auto"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
data-lpignore="true" data-1p-ignore data-bwignore>
<mat-autocomplete #auto="matAutocomplete"> <mat-autocomplete #auto="matAutocomplete">
@for (opt of field.options; track opt.value) { @for (opt of field.options; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option> <mat-option [value]="opt.value">{{ opt.label }}</mat-option>
} }
</mat-autocomplete> </mat-autocomplete>
@if (field.helpText) { @if (helpTextOf(field) && !hasHintBox(field)) {
<mat-hint>{{ field.helpText }}</mat-hint> <mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }
@if (formGroup.controls[field.key]?.hasError('required')) { @if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error> <mat-error>{{ field.label + ' is required' }}</mat-error>
@ -62,13 +125,19 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) { @if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error> <mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
} }
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.PASSWORD) { @case (FormFieldType.PASSWORD) {
<mat-form-field appearance="outline"> <mat-form-field appearance="outline" [subscriptSizing]="isInHintBoxRow(field) ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}</mat-label>
<input matInput [type]="passwordVisible[field.key] ? 'text' : 'password'" <input matInput [type]="passwordVisible[field.key] ? 'text' : 'password'"
[formControlName]="field.key"> [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
autocomplete="new-password" data-lpignore="true" data-1p-ignore data-bwignore>
<button mat-icon-button matSuffix type="button" <button mat-icon-button matSuffix type="button"
(click)="togglePasswordVisible(field.key)"> (click)="togglePasswordVisible(field.key)">
<mat-icon>{{ passwordVisible[field.key] ? 'visibility_off' : 'visibility' }}</mat-icon> <mat-icon>{{ passwordVisible[field.key] ? 'visibility_off' : 'visibility' }}</mat-icon>
@ -81,8 +150,8 @@
<mat-icon>autorenew</mat-icon> <mat-icon>autorenew</mat-icon>
</button> </button>
} }
@if (field.helpText) { @if (helpTextOf(field) && !hasHintBox(field)) {
<mat-hint>{{ field.helpText }}</mat-hint> <mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }
@if (formGroup.controls[field.key]?.hasError('required')) { @if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error> <mat-error>{{ field.label + ' is required' }}</mat-error>
@ -90,14 +159,20 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) { @if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error> <mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
} }
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.INTEGER) { @case (FormFieldType.INTEGER) {
<mat-form-field appearance="outline"> <mat-form-field appearance="outline" [subscriptSizing]="isInHintBoxRow(field) ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}</mat-label>
<input matInput type="number" [formControlName]="field.key"> <input matInput type="number" [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
@if (field.helpText) { [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
<mat-hint>{{ field.helpText }}</mat-hint> data-lpignore="true" data-1p-ignore data-bwignore>
@if (helpTextOf(field) && !hasHintBox(field)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }
@if (formGroup.controls[field.key]?.hasError('required')) { @if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error> <mat-error>{{ field.label + ' is required' }}</mat-error>
@ -105,12 +180,18 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) { @if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error> <mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
} }
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field> </mat-form-field>
} }
@default { @default {
<mat-form-field appearance="outline"> <mat-form-field appearance="outline" [subscriptSizing]="isInHintBoxRow(field) ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}</mat-label>
<input matInput [formControlName]="field.key"> <input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
autocomplete="new-username" data-lpignore="true" data-1p-ignore data-bwignore>
@if (field.randomGenerator) { @if (field.randomGenerator) {
<button mat-icon-button matSuffix type="button" <button mat-icon-button matSuffix type="button"
[matTooltip]="'iot-hub.generate-random-value' | translate" [matTooltip]="'iot-hub.generate-random-value' | translate"
@ -119,8 +200,8 @@
<mat-icon>autorenew</mat-icon> <mat-icon>autorenew</mat-icon>
</button> </button>
} }
@if (field.helpText) { @if (helpTextOf(field) && !hasHintBox(field)) {
<mat-hint>{{ field.helpText }}</mat-hint> <mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }
@if (formGroup.controls[field.key]?.hasError('required')) { @if (formGroup.controls[field.key]?.hasError('required')) {
<mat-error>{{ field.label + ' is required' }}</mat-error> <mat-error>{{ field.label + ' is required' }}</mat-error>
@ -128,17 +209,20 @@
@if (formGroup.controls[field.key]?.hasError('pattern')) { @if (formGroup.controls[field.key]?.hasError('pattern')) {
<mat-error>{{ getPatternErrorMessage(field) }}</mat-error> <mat-error>{{ getPatternErrorMessage(field) }}</mat-error>
} }
@if (field.errorMessage && hasFieldError(field)) {
<mat-error>{{ field.errorMessage }}</mat-error>
}
</mat-form-field> </mat-form-field>
} }
} }
} }
@if (field.type === FormFieldType.BOOLEAN && field.helpText) { @if (field.type === FormFieldType.BOOLEAN && helpTextOf(field)) {
<div class="tb-install-form-field-help">{{ field.helpText }}</div> <div class="tb-install-form-field-help">{{ helpTextOf(field) }}</div>
} }
@if (field.helpImage) { @if (field.helpImage) {
<img class="tb-install-form-field-help-image" [src]="imagePath(field.helpImage)" [alt]="field.label"> <img class="tb-install-form-field-help-image" [src]="imagePath(field.helpImage)" [alt]="field.label">
} }
} </ng-template>
</form> </form>
} }

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

@ -5,13 +5,6 @@
display: block; display: block;
} }
.tb-install-form-group-header {
margin: 16px 0 8px 0;
font-size: 14px;
font-weight: 600;
color: rgba(0, 0, 0, 0.6);
}
.tb-install-form-secret-toggle { .tb-install-form-secret-toggle {
margin-left: 4px; margin-left: 4px;
align-self: center; align-self: center;

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

@ -1,13 +1,25 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; import { Component, Input, OnChanges, SimpleChanges, TemplateRef } from '@angular/core';
import { UntypedFormGroup } from '@angular/forms'; import { AbstractControl, UntypedFormGroup } from '@angular/forms';
import { FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models'; import { ErrorStateMatcher } from '@angular/material/core';
import { cleanFormFieldValue, FormFieldDefinition, FormFieldType } from '@shared/models/iot-hub/device-package.models';
import { generateSecret } from '@core/utils'; import { generateSecret } from '@core/utils';
const DEFAULT_RANDOM_SIZE = 20; const DEFAULT_RANDOM_SIZE = 20;
/** Fields shown on one line. */
interface FormRow {
fields: FormFieldDefinition[];
}
/** Consecutive rows of one group, shown in a panel with the group as its title; no title for ungrouped fields. */
interface FormSection {
title?: string;
rows: FormRow[];
}
/** /**
* Reusable form renderer for the device install dialog's SHOW_FORM step. Consumes * Reusable form renderer for the device install dialog's SHOW_FORM step. Consumes
* the FormFieldDefinition[] parsed from the package's form.json directly — both * the FormFieldDefinition[] parsed from the package's form.json directly — both
@ -32,10 +44,49 @@ export class InstallFormRendererComponent implements OnChanges {
@Input() resolveImagePath?: (path: string) => string; @Input() resolveImagePath?: (path: string) => string;
/** When true, PASSWORD inputs render unmasked by default (used by review mode). */ /** When true, PASSWORD inputs render unmasked by default (used by review mode). */
@Input() reviewMode = false; @Input() reviewMode = false;
/** Rendered under the field marked with checkConnection; the dialog supplies it. */
@Input() checkConnectionTemplate?: TemplateRef<unknown> | null;
passwordVisible: Record<string, boolean> = {}; passwordVisible: Record<string, boolean> = {};
// Fields in render order: consecutive fields of a group form a section, and consecutive fields
// with the same `row` share one line
sections: FormSection[] = [];
// The same for the fields of the collapsed Advanced settings panel
advancedSections: FormSection[] = [];
private rowOf = new Map<string, FormRow>();
private focusedControl: AbstractControl | null = null;
private keepFocusedError = false;
/**
* A new error shows only after the user leaves the field, so a value is not called wrong while it
* is typed. An error already shown when the user enters the field stays until the value is valid.
*/
readonly errorStateMatcher: ErrorStateMatcher = {
isErrorState: (control, form) => {
if (control && control === this.focusedControl) {
this.keepFocusedError = this.keepFocusedError && control.invalid;
return this.keepFocusedError;
}
return !!control?.invalid && (control.touched || !!form?.submitted);
}
};
readonly FormFieldType = FormFieldType;
/** Render this field via the Secret picker widget (tb-secret-key-input). The picker
* itself accepts both plaintext and Secret references, so secretSupport=true means
* "this field MAY hold a Secret reference and the picker UI should be shown". */
isSecretWidget(field: FormFieldDefinition): boolean {
return field.secretSupport === true;
}
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
if (changes.fields) {
this.rowOf.clear();
const fields = this.fields ?? [];
this.sections = this.buildSections(fields.filter(field => field.section !== 'advanced'));
this.advancedSections = this.buildSections(fields.filter(field => field.section === 'advanced'));
}
if (changes.fields || changes.reviewMode) { if (changes.fields || changes.reviewMode) {
this.passwordVisible = {}; this.passwordVisible = {};
if (this.reviewMode) { if (this.reviewMode) {
@ -48,20 +99,33 @@ export class InstallFormRendererComponent implements OnChanges {
} }
} }
readonly FormFieldType = FormFieldType; private buildSections(fields: FormFieldDefinition[]): FormSection[] {
const sections: FormSection[] = [];
let previous: FormFieldDefinition | undefined;
for (const field of fields) {
if (!previous || field.group !== previous.group) {
sections.push({ title: field.group, rows: [] });
}
const rows = sections[sections.length - 1].rows;
const last = rows[rows.length - 1];
if (field.row && last?.fields[0].row === field.row) {
last.fields.push(field);
} else {
rows.push({ fields: [field] });
}
this.rowOf.set(field.key, rows[rows.length - 1]);
previous = field;
}
return sections;
}
/** Render this field via the Secret picker widget (tb-secret-key-input). The picker hasCheckConnectionField(fields: FormFieldDefinition[]): boolean {
* itself accepts both plaintext and Secret references, so secretSupport=true means return fields.some(field => field.checkConnection);
* "this field MAY hold a Secret reference and the picker UI should be shown". */
isSecretWidget(field: FormFieldDefinition): boolean {
return field.secretSupport === true;
} }
/** True when the previous field belonged to a different group (for header rendering). */ /** The hint of a field that a defaultValueTemplate fills describes the filled value. */
shouldRenderGroupHeader(field: FormFieldDefinition, index: number): boolean { helpTextOf(field: FormFieldDefinition): string | undefined {
if (!field.group) return false; return field.defaultValueTemplate && field.defaultValueTemplateHelpText ? field.defaultValueTemplateHelpText : field.helpText;
if (index === 0) return true;
return this.fields[index - 1].group !== field.group;
} }
togglePasswordVisible(key: string): void { togglePasswordVisible(key: string): void {
@ -75,10 +139,44 @@ export class InstallFormRendererComponent implements OnChanges {
control.markAsDirty(); control.markAsDirty();
} }
onFocus(field: FormFieldDefinition): void {
const control = this.formGroup.controls[field.key];
this.focusedControl = control ?? null;
this.keepFocusedError = !!control?.invalid && control.touched;
}
onBlur(field: FormFieldDefinition): void {
this.focusedControl = null;
const control = this.formGroup.controls[field.key];
const cleaned = cleanFormFieldValue(field, control?.value);
if (control && cleaned !== control.value) {
control.setValue(cleaned);
}
}
getPatternErrorMessage(field: FormFieldDefinition): string { getPatternErrorMessage(field: FormFieldDefinition): string {
return field.validators?.[0]?.message || 'Invalid format'; return field.validators?.[0]?.message || 'Invalid format';
} }
/** Fields with a help popup show their hint in a box under the row, with the popup trigger. */
hasHintBox(field: FormFieldDefinition): boolean {
return !!field.helpPopupId && !this.reviewMode;
}
/**
* True for the fields of a row that has a hint box. They don't reserve space for a hint or an
* error, so the box sits right under them.
*/
isInHintBoxRow(field: FormFieldDefinition): boolean {
return !!this.rowOf.get(field.key)?.fields.some(f => this.hasHintBox(f));
}
/** True when the field fails a validator other than required and pattern (one the dialog added). */
hasFieldError(field: FormFieldDefinition): boolean {
const errors = this.formGroup.controls[field.key]?.errors;
return !!errors && Object.keys(errors).some(key => key !== 'required' && key !== 'pattern');
}
imagePath(path: string): string { imagePath(path: string): string {
return this.resolveImagePath ? this.resolveImagePath(path) : path; return this.resolveImagePath ? this.resolveImagePath(path) : path;
} }

26
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -4,12 +4,13 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog'; import { MatDialog } from '@angular/material/dialog';
import { Observable, of, EMPTY } from 'rxjs'; import { Observable, of, EMPTY } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'; import { catchError, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core'; import { TranslateService } from '@ngx-translate/core';
import { DialogService } from '@core/services/dialog.service'; import { DialogService } from '@core/services/dialog.service';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { DeviceInstalledItemDescriptor, IotHubInstalledItem, IotHubInstalledItemKeptEntities } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { EntityId } from '@shared/models/id/entity-id'; import { EntityId } from '@shared/models/id/entity-id';
import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemDialogResult } from './iot-hub-add-item-dialog.component'; import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemDialogResult } from './iot-hub-add-item-dialog.component';
import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component'; import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component';
@ -35,7 +36,8 @@ export class IotHubActionsService {
private dialog: MatDialog, private dialog: MatDialog,
private dialogService: DialogService, private dialogService: DialogService,
private translate: TranslateService, private translate: TranslateService,
private builtInService: IotHubBuiltInService private builtInService: IotHubBuiltInService,
private iotHubApiService: IotHubApiService
) {} ) {}
openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number,
@ -166,12 +168,18 @@ export class IotHubActionsService {
if (!installedItem) { if (!installedItem) {
return of(false); return of(false);
} }
return this.dialog.open<TbIotHubDeleteDialogComponent, IotHubDeleteDialogData, boolean>(TbIotHubDeleteDialogComponent, { // A device package keeps what other installed packages use: the dialog opens with that already known
panelClass: ['tb-dialog'], const keptEntities$: Observable<IotHubInstalledItemKeptEntities | null> = installedItem.itemType === 'DEVICE' ?
disableClose: true, this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) :
autoFocus: false, of(null);
data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType } return keptEntities$.pipe(
}).afterClosed(); switchMap(keptEntities => this.dialog.open<TbIotHubDeleteDialogComponent, IotHubDeleteDialogData, boolean>(TbIotHubDeleteDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data: { installedItemId: installedItem.id.id, itemName: installedItem.itemName, itemType: installedItem.itemType, keptEntities }
}).afterClosed())
);
} }
// Reached only for items whose action mode is 'connect', i.e. never for built-in content: // Reached only for items whose action mode is 'connect', i.e. never for built-in content:

5
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html

@ -1,12 +1,13 @@
<!-- <!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0 SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
--> -->
<div class="flex flex-col gap-5 p-6"> <div class="flex flex-col gap-5 p-6">
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2> <h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-delete-desc">{{ (data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc') | translate }}</p> <p class="tb-iot-hub-delete-desc">{{ description }}</p>
</div> </div>
<div class="flex items-center justify-end gap-2 p-2"> <div class="flex items-center justify-end gap-2 p-2">
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button> <button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>

8
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss

@ -1,5 +1,11 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
:host {
display: block;
max-width: 600px;
}
.tb-iot-hub-delete-title { .tb-iot-hub-delete-title {
font-size: 20px; font-size: 20px;
font-weight: 600; font-weight: 600;

27
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -1,18 +1,21 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Inject } from '@angular/core'; import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router'; import { Router } from '@angular/router';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state'; import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component'; import { DialogComponent } from '@shared/components/dialog.component';
import { IotHubInstalledItem } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
export interface IotHubDeleteDialogData { export interface IotHubDeleteDialogData {
installedItemId: string; installedItemId: string;
itemName: string; itemName: string;
itemType?: string; itemType?: string;
keptEntities?: IotHubInstalledItemKeptEntities | null;
} }
@Component({ @Component({
@ -23,14 +26,19 @@ export interface IotHubDeleteDialogData {
}) })
export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDeleteDialogComponent, boolean> { export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDeleteDialogComponent, boolean> {
description: string;
constructor( constructor(
protected store: Store<AppState>, protected store: Store<AppState>,
protected router: Router, protected router: Router,
protected dialogRef: MatDialogRef<TbIotHubDeleteDialogComponent, boolean>, protected dialogRef: MatDialogRef<TbIotHubDeleteDialogComponent, boolean>,
@Inject(MAT_DIALOG_DATA) public data: IotHubDeleteDialogData, @Inject(MAT_DIALOG_DATA) public data: IotHubDeleteDialogData,
private iotHubApiService: IotHubApiService private iotHubApiService: IotHubApiService,
private translate: TranslateService
) { ) {
super(store, router, dialogRef); super(store, router, dialogRef);
this.description = data.keptEntities?.entities.length ? this.describeKeptEntities(data.keptEntities) :
this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
} }
confirm(): void { confirm(): void {
@ -44,4 +52,17 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
cancel(): void { cancel(): void {
this.dialogRef.close(false); this.dialogRef.close(false);
} }
/** A device package keeps the entities other installed packages use, and the description names them before the user confirms. */
private describeKeptEntities(kept: IotHubInstalledItemKeptEntities): string {
const names = kept.entities.map(entity => {
const key = `iot-hub.remove-kept-entity.${entity.entityId.entityType}`;
const named = this.translate.instant(key, { name: entity.name });
return named === key ? `'${entity.name}'` : named;
});
const entities = names.length === 1 ? names[0] :
this.translate.instant('iot-hub.remove-kept-entities', { first: names.slice(0, -1).join(', '), last: names[names.length - 1] });
return this.translate.instant('iot-hub.remove-desc-kept',
{ entities, count: kept.usedByItemsCount, kept: kept.entities.length });
}
} }

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

@ -1,7 +1,8 @@
<!-- <!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-License-Identifier: Apache-2.0 SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
--> -->
<div class="tb-installed-table-container flex flex-1 flex-col overflow-hidden rounded-lg"> <div class="tb-installed-table-container flex flex-1 flex-col overflow-hidden rounded-lg">
@ -88,9 +89,12 @@
<mat-icon>info_outline</mat-icon> <mat-icon>info_outline</mat-icon>
</button> </button>
} }
<button mat-icon-button (click)="openEntity(item)" matTooltip="{{ (item.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.goto-main-dashboard' : 'iot-hub.open-item-type') | translate:{ type: getItemTypeLabel(item.itemType) } }}"> <!-- The tooltip sits on a wrapper: a disabled button shows none -->
<mat-icon>open_in_new</mat-icon> <span matTooltip="{{ openLabel(item) }}">
</button> <button mat-icon-button (click)="openEntity(item)" [disabled]="!canOpen(item)">
<mat-icon>open_in_new</mat-icon>
</button>
</span>
<button mat-icon-button (click)="deleteItem(item)" matTooltip="{{ 'iot-hub.remove' | translate }}"> <button mat-icon-button (click)="deleteItem(item)" matTooltip="{{ 'iot-hub.remove' | translate }}">
<tb-icon>mdi:trash-can-outline</tb-icon> <tb-icon>mdi:trash-can-outline</tb-icon>
</button> </button>
@ -107,9 +111,9 @@
<span>{{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }}</span> <span>{{ (item.itemType === 'DEVICE' ? 'iot-hub.review-device-instructions' : 'iot-hub.view-item-details') | translate }}</span>
</button> </button>
} }
<button mat-menu-item (click)="openEntity(item)"> <button mat-menu-item (click)="openEntity(item)" [disabled]="!canOpen(item)">
<mat-icon>open_in_new</mat-icon> <mat-icon>open_in_new</mat-icon>
<span>{{ (item.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.goto-main-dashboard' : 'iot-hub.open-item-type') | translate:{ type: getItemTypeLabel(item.itemType) } }}</span> <span>{{ openLabel(item) }}</span>
</button> </button>
<button mat-menu-item (click)="deleteItem(item)"> <button mat-menu-item (click)="deleteItem(item)">
<tb-icon>mdi:trash-can-outline</tb-icon> <tb-icon>mdi:trash-can-outline</tb-icon>

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

@ -27,10 +27,12 @@ import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { Direction, SortOrder } from '@shared/models/page/sort-order';
import { import {
DeviceInstalledItemDescriptor, DeviceInstalledItemDescriptor,
getInstalledItemTarget,
getInstalledItemUrl, getInstalledItemUrl,
IotHubInstalledItem, IotHubInstalledItem,
ItemPublishedVersionInfo ItemPublishedVersionInfo
} from '@shared/models/iot-hub/iot-hub-installed-item.models'; } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { entityTypeTranslations } from '@shared/models/entity-type.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
@ -194,6 +196,27 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
}); });
} }
canOpen(item: IotHubInstalledItem): boolean {
return !!getInstalledItemTarget(item?.descriptor);
}
/** Names what Open opens: for a device package, its dashboard, device or integration. */
openLabel(item: IotHubInstalledItem): string {
if (!this.canOpen(item)) {
return this.translate.instant('iot-hub.nothing-to-open');
}
if (item.itemType === 'SOLUTION_TEMPLATE') {
return this.translate.instant('iot-hub.goto-main-dashboard');
}
let type = this.getItemTypeLabel(item.itemType);
const target = item.itemType === 'DEVICE' ? getInstalledItemTarget(item.descriptor) : null;
const typeKey = target && entityTypeTranslations.get(target.entityType)?.type;
if (typeKey) {
type = this.translate.instant(typeKey);
}
return this.translate.instant('iot-hub.open-item-type', { type });
}
openEntity(item: IotHubInstalledItem): void { openEntity(item: IotHubInstalledItem): void {
const url = getInstalledItemUrl(item?.descriptor); const url = getInstalledItemUrl(item?.descriptor);
if (url) { if (url) {

12
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.component.ts

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { import {
Component, Component,
ElementRef, ElementRef,
@ -86,11 +87,10 @@ export class TbIotHubMarkdownComponent implements OnInit, OnChanges {
} }
ngOnChanges(changes: SimpleChanges): void { ngOnChanges(changes: SimpleChanges): void {
for (const propName of Object.keys(changes)) { // A new resolver means the variable values changed, so the same data has to be resolved again.
const change = changes[propName]; // Nothing to render until the step's data arrives; a resolver alone would render an empty page
if (propName === 'data' && change.currentValue !== change.previousValue) { if ((changes.data || changes.onResolveVariable) && this.data != null) {
this.parsedData = this.parseData(this.data); this.parsedData = this.parseData(this.data);
}
} }
} }

36
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -110,8 +110,8 @@ export const installMethodLabels = new Map<string, string>(
[InstallMethod.INTEGRATION_TCP, 'TCP Integration'], [InstallMethod.INTEGRATION_TCP, 'TCP Integration'],
[InstallMethod.INTEGRATION_THINGPARK, 'ThingPark Wireless'], [InstallMethod.INTEGRATION_THINGPARK, 'ThingPark Wireless'],
[InstallMethod.INTEGRATION_THINGPARK_ENTERPRISE, 'ThingPark Enterprise'], [InstallMethod.INTEGRATION_THINGPARK_ENTERPRISE, 'ThingPark Enterprise'],
[InstallMethod.INTEGRATION_TTI, 'The Things Industries'], [InstallMethod.INTEGRATION_TTI, 'The Things Stack Cloud'],
[InstallMethod.INTEGRATION_TTN, 'The Things Stack'], [InstallMethod.INTEGRATION_TTN, 'The Things Stack Sandbox'],
[InstallMethod.INTEGRATION_TUYA, 'Tuya'], [InstallMethod.INTEGRATION_TUYA, 'Tuya'],
[InstallMethod.INTEGRATION_UDP, 'UDP Integration'] [InstallMethod.INTEGRATION_UDP, 'UDP Integration']
] ]
@ -279,9 +279,41 @@ export interface FormFieldDefinition {
// (tb-secret-key-input); false / undefined → render the typed widget. // (tb-secret-key-input); false / undefined → render the typed widget.
secretSupport?: boolean; secretSupport?: boolean;
secretType?: SecretType; secretType?: SecretType;
// Fields with the same group get one header above the first of them
group?: string; group?: string;
readOnly?: boolean;
// Shown inside the empty field; the label then always stays above it
placeholder?: string;
// Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it.
// defaultValue stays the value for ThingsBoard versions that don't know this attribute.
defaultValueTemplate?: string;
// Replaces helpText when defaultValueTemplate fills the field
defaultValueTemplateHelpText?: string;
// 'advanced' puts the field into the collapsed Advanced settings panel below the form
section?: FormFieldSection;
// Shows the Check connection button of the integration the form configures under this field
checkConnection?: boolean;
// A regular expression whose matches are removed from the value when the user leaves the field
// and before the step is committed, e.g. "@ttn$" for an ID copied with its suffix.
// validators check the cleaned value.
cleanupPattern?: string;
// Set by the install dialog for the fields it adds, not by packages:
// help popup shown under the field, and the text of its trigger
helpPopupId?: string;
helpPopupText?: string;
// Shown when the field fails a validator the dialog adds (not on required)
errorMessage?: string;
// Consecutive fields with the same row are shown on one line. A field with a width (px) keeps it;
// the other fields of the row share the remaining space.
row?: string;
width?: number;
} }
export type FormFieldSection = 'advanced';
export const cleanFormFieldValue = (field: FormFieldDefinition, value: any): any =>
field.cleanupPattern && typeof value === 'string' ? value.replace(new RegExp(field.cleanupPattern, 'g'), '') : value;
export interface EntityStepOutput { export interface EntityStepOutput {
id: string; id: string;
name: string; name: string;

25
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -103,6 +103,17 @@ export interface ItemPublishedVersionInfo {
publishedVersion: string; publishedVersion: string;
} }
/** An entity that deleting an installed item keeps, because other installed items use it too. */
export interface IotHubKeptEntity {
entityId: { id: string; entityType: string };
name: string;
}
export interface IotHubInstalledItemKeptEntities {
entities: IotHubKeptEntity[];
usedByItemsCount: number;
}
export interface IotHubInstalledItem extends BaseData<{id: string}> { export interface IotHubInstalledItem extends BaseData<{id: string}> {
itemId: string; itemId: string;
itemVersionId: string; itemVersionId: string;
@ -112,7 +123,8 @@ export interface IotHubInstalledItem extends BaseData<{id: string}> {
descriptor: IotHubInstalledItemDescriptor; descriptor: IotHubInstalledItemDescriptor;
} }
export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor): string | null => { /** The entity the Open action of an installed item opens, and its URL. */
export const getInstalledItemTarget = (descriptor?: IotHubInstalledItemDescriptor): { url: string; entityType: EntityType } | null => {
if (!descriptor) { if (!descriptor) {
return null; return null;
} }
@ -125,10 +137,12 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor):
entityId = descriptor.dashboardId?.id; entityId = descriptor.dashboardId?.id;
entityType = EntityType.DASHBOARD; entityType = EntityType.DASHBOARD;
} else if (descriptor.createdEntityIds) { } else if (descriptor.createdEntityIds) {
const found = descriptor.createdEntityIds.find(id => id.entityType === EntityType.DEVICE); // A gateway package (e.g. TTN) creates no device, only a converter and an integration
const found = descriptor.createdEntityIds.find(id => id.entityType === EntityType.DEVICE)
?? descriptor.createdEntityIds.find(id => id.entityType === EntityType.INTEGRATION);
if (found) { if (found) {
entityId = found.id; entityId = found.id;
entityType = EntityType.DEVICE; entityType = found.entityType as EntityType;
} }
} }
break; break;
@ -160,7 +174,10 @@ export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor):
} else { } else {
url = getEntityDetailsPageURL(entityId, entityType); url = getEntityDetailsPageURL(entityId, entityType);
} }
return url; return url ? { url, entityType } : null;
} }
return null; return null;
} }
export const getInstalledItemUrl = (descriptor?: IotHubInstalledItemDescriptor): string | null =>
getInstalledItemTarget(descriptor)?.url ?? null;

9
ui-ngx/src/app/shared/models/settings.models.ts

@ -85,6 +85,15 @@ export interface DeviceConnectivityInfo {
export type DeviceConnectivitySettings = Record<DeviceConnectivityProtocol, DeviceConnectivityInfo>; export type DeviceConnectivitySettings = Record<DeviceConnectivityProtocol, DeviceConnectivityInfo>;
export type DeviceConnectivityHostSource = 'DEVICE_CONNECTIVITY' | 'BASE_URL' | 'REQUEST';
// Connectivity of a transport as resolved for devices, not as stored in the settings
export interface ResolvedDeviceConnectivityInfo extends DeviceConnectivityInfo {
hostSource?: DeviceConnectivityHostSource;
}
export type ResolvedDeviceConnectivitySettings = Partial<Record<DeviceConnectivityProtocol, ResolvedDeviceConnectivityInfo>>;
export enum MailTemplate { export enum MailTemplate {
test = 'test', test = 'test',
activation = 'activation', activation = 'activation',

12
ui-ngx/src/assets/help/en_US/iot-hub/device-connection-host.md

@ -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.

4
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

@ -3624,9 +3624,9 @@
"type-aws-kinesis-description": "خدمة للفيديو والبيانات في الوقت الفعلي.", "type-aws-kinesis-description": "خدمة للفيديو والبيانات في الوقت الفعلي.",
"type-ibm-watson-iot": "IBM Watson IoT", "type-ibm-watson-iot": "IBM Watson IoT",
"type-ibm-watson-iot-description": "خدمة مُدارة بالكامل على السحابة.", "type-ibm-watson-iot-description": "خدمة مُدارة بالكامل على السحابة.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "شبكة LoRaWAN المفتوحة والمركزة.", "type-ttn-description": "شبكة LoRaWAN المفتوحة والمركزة.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "برنامج لتشغيل شبكات LoRaWAN الخاصة بنطاق واسع.", "type-tti-description": "برنامج لتشغيل شبكات LoRaWAN الخاصة بنطاق واسع.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "خادم تكوين شبكة LoRaWAN.", "type-chirpstack-description": "خادم تكوين شبكة LoRaWAN.",

4
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

@ -3049,8 +3049,8 @@
"type-aws-sqs": "AWS SQS", "type-aws-sqs": "AWS SQS",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-ibm-watson-iot": "IBM Watson IoT", "type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-azure-event-hub": "Azure Event Hub", "type-azure-event-hub": "Azure Event Hub",
"type-azure-iot-hub": "Azure IoT Hub", "type-azure-iot-hub": "Azure IoT Hub",

4
ui-ngx/src/assets/locale/locale.constant-da_DK.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "Fuldadministreret meddelelseskøtjeneste.", "type-aws-sqs-description": "Fuldadministreret meddelelseskøtjeneste.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Tjeneste til realtids video- og datastrømme.", "type-aws-kinesis-description": "Tjeneste til realtids video- og datastrømme.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Åbent og decentraliseret LoRaWAN-netværk.", "type-ttn-description": "Åbent og decentraliseret LoRaWAN-netværk.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software til drift af private LoRaWAN-netværk i stor skala.", "type-tti-description": "Software til drift af private LoRaWAN-netværk i stor skala.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN-netværkskonfigurationstjeneste.", "type-chirpstack-description": "LoRaWAN-netværkskonfigurationstjeneste.",

4
ui-ngx/src/assets/locale/locale.constant-de_DE.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Vollständig verwalteter Nachrichtenwarteschlangen-Dienst.", "type-aws-sqs-description": "Vollständig verwalteter Nachrichtenwarteschlangen-Dienst.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Dienst für Echtzeit-Video- und Datenströme.", "type-aws-kinesis-description": "Dienst für Echtzeit-Video- und Datenströme.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Offenes und dezentrales LoRaWAN-Netzwerk.", "type-ttn-description": "Offenes und dezentrales LoRaWAN-Netzwerk.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software zum Betrieb privater LoRaWAN-Netzwerke im großen Maßstab.", "type-tti-description": "Software zum Betrieb privater LoRaWAN-Netzwerke im großen Maßstab.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-el_GR.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "Διαχειριζόμενη υπηρεσία ουράς μηνυμάτων.", "type-aws-sqs-description": "Διαχειριζόμενη υπηρεσία ουράς μηνυμάτων.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Υπηρεσία ροής δεδομένων και βίντεο σε πραγματικό χρόνο.", "type-aws-kinesis-description": "Υπηρεσία ροής δεδομένων και βίντεο σε πραγματικό χρόνο.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Ανοιχτό και αποκεντρωμένο δίκτυο LoRaWAN.", "type-ttn-description": "Ανοιχτό και αποκεντρωμένο δίκτυο LoRaWAN.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Λογισμικό για ιδιωτικά δίκτυα LoRaWAN.", "type-tti-description": "Λογισμικό για ιδιωτικά δίκτυα LoRaWAN.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "Διακομιστής διαμόρφωσης δικτύου LoRaWAN.", "type-chirpstack-description": "Διακομιστής διαμόρφωσης δικτύου LoRaWAN.",

34
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -5692,9 +5692,9 @@
"type-aws-sqs-description": "Fully managed message queuing service.", "type-aws-sqs-description": "Fully managed message queuing service.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Service for real-time video and data streams.", "type-aws-kinesis-description": "Service for real-time video and data streams.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Open and decentralized LoRaWAN network.", "type-ttn-description": "Open and decentralized LoRaWAN network.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software to operate private LoRaWAN networks at scale.", "type-tti-description": "Software to operate private LoRaWAN networks at scale.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
@ -6286,6 +6286,11 @@
"type-device-plural": "Devices" "type-device-plural": "Devices"
}, },
"iot-hub": { "iot-hub": {
"advanced-settings": "Advanced settings",
"check-connection": "Check connection",
"connection-check-success": "Connected.",
"connection-check-failed": "Could not connect. Check the connection settings and the credentials.",
"continue-anyway": "Continue anyway",
"iot-hub": "IoT Hub", "iot-hub": "IoT Hub",
"generate-random-value": "Generate random value", "generate-random-value": "Generate random value",
"home-title": "ThingsBoard IoT Hub", "home-title": "ThingsBoard IoT Hub",
@ -6400,6 +6405,16 @@
"remove": "Remove", "remove": "Remove",
"remove-confirm-title": "Remove '{{name}}'?", "remove-confirm-title": "Remove '{{name}}'?",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant",
"remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant, except {entities}. { count, plural, =1 {1 other installed package uses} other {# other installed packages use} } { kept, plural, =1 {it} other {them} }.",
"remove-kept-entities": "{{first}} and {{last}}",
"remove-kept-entity": {
"CONVERTER": "data converter '{{name}}'",
"DASHBOARD": "dashboard '{{name}}'",
"DEVICE": "device '{{name}}'",
"DEVICE_PROFILE": "device profile '{{name}}'",
"INTEGRATION": "integration '{{name}}'",
"RULE_CHAIN": "rule chain '{{name}}'"
},
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway", "remove-anyway": "Remove anyway",
"select-entity-for-cf": "Select entity for calculated field '{{name}}'", "select-entity-for-cf": "Select entity for calculated field '{{name}}'",
@ -6481,6 +6496,7 @@
"view-item-details": "View item details", "view-item-details": "View item details",
"review-device-instructions": "Review device instructions", "review-device-instructions": "Review device instructions",
"open-item-type": "Open {{type}}", "open-item-type": "Open {{type}}",
"nothing-to-open": "Nothing to open",
"back-to-marketplace": "Back to Marketplace", "back-to-marketplace": "Back to Marketplace",
"device-install-select-connectivity": "Choose a connection method for your device", "device-install-select-connectivity": "Choose a connection method for your device",
"connection-method": "Connection method", "connection-method": "Connection method",
@ -6504,6 +6520,20 @@
"use-plain-text": "Use plain text", "use-plain-text": "Use plain text",
"device-install-conflict-exists": "{{type}} with this name already exists", "device-install-conflict-exists": "{{type}} with this name already exists",
"device-install-use-existing": "Use existing", "device-install-use-existing": "Use existing",
"device-install-transport-host-step": "Connection",
"device-install-thingsboard-connection": "ThingsBoard connection",
"device-install-mqtt-host": "MQTT host",
"device-install-mqtt-host-hint": "Host the device connects to over MQTT. It may differ from the address you open ThingsBoard at in the browser.",
"device-install-mqtt-host-request-hint": "Taken from the address you opened ThingsBoard with. Make sure the device can reach it.",
"device-install-mqtt-host-base-url-hint": "Taken from the Base URL in General settings. Make sure the device can reach it.",
"device-install-mqtt-host-loopback-hint": "The MQTT host resolved to {{host}}, which on the device means the device itself. Enter an address the device can reach.",
"device-install-mqtt-host-base-url-loopback-hint": "Taken from the Base URL in General settings, which points to {{host}}. Enter an address the device can reach.",
"device-install-mqtt-host-opened-via-loopback-hint": "ThingsBoard is opened via {{host}}, so enter an address the device can reach.",
"device-install-mqtt-host-configured-hint": "Set by the platform. The device connects to this host.",
"device-install-mqtt-port": "MQTT port",
"device-install-transport-host-error": "Enter a host name or IP address the device can reach (not localhost)",
"device-install-transport-port-error": "Enter a port from 1 to 65535",
"device-install-which-host": "Which host should I use?",
"device-install-overwrite": "Overwrite", "device-install-overwrite": "Overwrite",
"device-install-create-copy": "Create copy", "device-install-create-copy": "Create copy",
"device-install-resolution-created": "Created", "device-install-resolution-created": "Created",

4
ui-ngx/src/assets/locale/locale.constant-es_ES.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Servicio de colas de mensajes totalmente administrado.", "type-aws-sqs-description": "Servicio de colas de mensajes totalmente administrado.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Servicio para transmisión de datos y video en tiempo real.", "type-aws-kinesis-description": "Servicio para transmisión de datos y video en tiempo real.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Red LoRaWAN abierta y descentralizada.", "type-ttn-description": "Red LoRaWAN abierta y descentralizada.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software para operar redes LoRaWAN privadas a escala.", "type-tti-description": "Software para operar redes LoRaWAN privadas a escala.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-fr_FR.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Service de gestion de files d’attente de messages.", "type-aws-sqs-description": "Service de gestion de files d’attente de messages.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Service pour le traitement de flux vidéo et de données en temps réel.", "type-aws-kinesis-description": "Service pour le traitement de flux vidéo et de données en temps réel.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Réseau LoRaWAN ouvert et décentralisé.", "type-ttn-description": "Réseau LoRaWAN ouvert et décentralisé.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Logiciel pour exploiter des réseaux LoRaWAN privés à grande échelle.", "type-tti-description": "Logiciel pour exploiter des réseaux LoRaWAN privés à grande échelle.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

@ -4852,9 +4852,9 @@
"type-aws-sqs-description": "पूरी तरह प्रबंधित मैसेज क्यूइंग सेवा.", "type-aws-sqs-description": "पूरी तरह प्रबंधित मैसेज क्यूइंग सेवा.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "रीयल-टाइम वीडियो और डेटा स्ट्रीम्स के लिए सेवा.", "type-aws-kinesis-description": "रीयल-टाइम वीडियो और डेटा स्ट्रीम्स के लिए सेवा.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "ओपन और डिसेंट्रलाइज़्ड LoRaWAN नेटवर्क.", "type-ttn-description": "ओपन और डिसेंट्रलाइज़्ड LoRaWAN नेटवर्क.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "बड़े स्तर पर प्राइवेट LoRaWAN नेटवर्क ऑपरेट करने के लिए सॉफ़्टवेयर.", "type-tti-description": "बड़े स्तर पर प्राइवेट LoRaWAN नेटवर्क ऑपरेट करने के लिए सॉफ़्टवेयर.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN नेटवर्क कॉन्फ़िगरेशन सर्वर.", "type-chirpstack-description": "LoRaWAN नेटवर्क कॉन्फ़िगरेशन सर्वर.",

4
ui-ngx/src/assets/locale/locale.constant-it_IT.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Servizio di accodamento messaggi completamente gestito.", "type-aws-sqs-description": "Servizio di accodamento messaggi completamente gestito.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Servizio per flussi video e dati in tempo reale.", "type-aws-kinesis-description": "Servizio per flussi video e dati in tempo reale.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Rete LoRaWAN aperta e decentralizzata.", "type-ttn-description": "Rete LoRaWAN aperta e decentralizzata.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software per reti private LoRaWAN su larga scala.", "type-tti-description": "Software per reti private LoRaWAN su larga scala.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-ja_JP.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "完全に管理されたメッセージキューサービス。", "type-aws-sqs-description": "完全に管理されたメッセージキューサービス。",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "リアルタイムのビデオおよびデータストリームサービス。", "type-aws-kinesis-description": "リアルタイムのビデオおよびデータストリームサービス。",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "オープンで分散型のLoRaWANネットワーク。", "type-ttn-description": "オープンで分散型のLoRaWANネットワーク。",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "スケールでプライベートLoRaWANネットワークを運用するためのソフトウェア。", "type-tti-description": "スケールでプライベートLoRaWANネットワークを運用するためのソフトウェア。",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWANネットワーク構成サーバー。", "type-chirpstack-description": "LoRaWANネットワーク構成サーバー。",

2
ui-ngx/src/assets/locale/locale.constant-ka_GE.json

@ -1720,7 +1720,7 @@
"type-aws-sqs": "AWS SQS", "type-aws-sqs": "AWS SQS",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-ibm-watson-iot": "IBM Watson IoT", "type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-azure-event-hub": "ტიპის-აზური-ღონისძიების ცენტრი", "type-azure-event-hub": "ტიპის-აზური-ღონისძიების ცენტრი",
"type-opc-ua": "OPC-UA", "type-opc-ua": "OPC-UA",
"type-custom": "უჩვეულო", "type-custom": "უჩვეულო",

4
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -4339,9 +4339,9 @@
"type-aws-sqs-description": "Pilnai valdoma eilių paslauga.", "type-aws-sqs-description": "Pilnai valdoma eilių paslauga.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Realaus laiko vaizdo ir duomenų srautai.", "type-aws-kinesis-description": "Realaus laiko vaizdo ir duomenų srautai.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Atviras ir decentralizuotas LoRaWAN tinklas.", "type-ttn-description": "Atviras ir decentralizuotas LoRaWAN tinklas.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Programinė įranga privačioms LoRaWAN tinklams masteliuoti.", "type-tti-description": "Programinė įranga privačioms LoRaWAN tinklams masteliuoti.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN tinklo konfigūravimo serveris.", "type-chirpstack-description": "LoRaWAN tinklo konfigūravimo serveris.",

2
ui-ngx/src/assets/locale/locale.constant-lv_LV.json

@ -1629,7 +1629,7 @@
"type-mqtt": "MQTT", "type-mqtt": "MQTT",
"type-aws-iot": "AWS IoT", "type-aws-iot": "AWS IoT",
"type-ibm-watson-iot": "IBM Watson IoT", "type-ibm-watson-iot": "IBM Watson IoT",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-azure-event-hub": "Azure Event Hub", "type-azure-event-hub": "Azure Event Hub",
"type-opc-ua": "OPC-UA", "type-opc-ua": "OPC-UA",
"opc-ua-application-name": "Aplikācijas nosaukums", "opc-ua-application-name": "Aplikācijas nosaukums",

4
ui-ngx/src/assets/locale/locale.constant-nl_NL.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "Volledig beheerde wachtrijdienst.", "type-aws-sqs-description": "Volledig beheerde wachtrijdienst.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Dienst voor realtime video- en datastromen.", "type-aws-kinesis-description": "Dienst voor realtime video- en datastromen.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Open en gedecentraliseerd LoRaWAN-netwerk.", "type-ttn-description": "Open en gedecentraliseerd LoRaWAN-netwerk.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software om privé LoRaWAN-netwerken op schaal te beheren.", "type-tti-description": "Software om privé LoRaWAN-netwerken op schaal te beheren.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN-netwerkconfiguratieserver.", "type-chirpstack-description": "LoRaWAN-netwerkconfiguratieserver.",

4
ui-ngx/src/assets/locale/locale.constant-no_NO.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "Fulladministrert køtjeneste for meldinger.", "type-aws-sqs-description": "Fulladministrert køtjeneste for meldinger.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Tjeneste for sanntidsvideo og datastrømmer.", "type-aws-kinesis-description": "Tjeneste for sanntidsvideo og datastrømmer.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Åpent og desentralisert LoRaWAN-nettverk.", "type-ttn-description": "Åpent og desentralisert LoRaWAN-nettverk.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Programvare for å drive private LoRaWAN-nettverk i stor skala.", "type-tti-description": "Programvare for å drive private LoRaWAN-nettverk i stor skala.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "Konfigurasjonsserver for LoRaWAN-nettverk.", "type-chirpstack-description": "Konfigurasjonsserver for LoRaWAN-nettverk.",

4
ui-ngx/src/assets/locale/locale.constant-pl_PL.json

@ -3541,9 +3541,9 @@
"type-aws-kinesis-description": "Usługa strumieni wideo i danych w czasie rzeczywistym.", "type-aws-kinesis-description": "Usługa strumieni wideo i danych w czasie rzeczywistym.",
"type-ibm-watson-iot": "IBM Watson IoT", "type-ibm-watson-iot": "IBM Watson IoT",
"type-ibm-watson-iot-description": "W pełni zarządzana usługa hostowana w chmurze.", "type-ibm-watson-iot-description": "W pełni zarządzana usługa hostowana w chmurze.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Otwarta i zdecentralizowana sieć LoRaWAN.", "type-ttn-description": "Otwarta i zdecentralizowana sieć LoRaWAN.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Oprogramowanie do obsługi prywatnych sieci LoRaWAN na dużą skalę.", "type-tti-description": "Oprogramowanie do obsługi prywatnych sieci LoRaWAN na dużą skalę.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "Serwer konfiguracji sieci LoRaWAN.", "type-chirpstack-description": "Serwer konfiguracji sieci LoRaWAN.",

4
ui-ngx/src/assets/locale/locale.constant-pt_BR.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Serviço de filas de mensagens totalmente gerenciado.", "type-aws-sqs-description": "Serviço de filas de mensagens totalmente gerenciado.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Serviço para streams de vídeo e dados em tempo real.", "type-aws-kinesis-description": "Serviço para streams de vídeo e dados em tempo real.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Rede LoRaWAN aberta e descentralizada.", "type-ttn-description": "Rede LoRaWAN aberta e descentralizada.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Software para operar redes LoRaWAN privadas em escala.", "type-tti-description": "Software para operar redes LoRaWAN privadas em escala.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-tr_TR.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "Tam yönetilen mesaj kuyruğa alma hizmeti.", "type-aws-sqs-description": "Tam yönetilen mesaj kuyruğa alma hizmeti.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Gerçek zamanlı video ve veri akış hizmeti.", "type-aws-kinesis-description": "Gerçek zamanlı video ve veri akış hizmeti.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Açık ve merkeziyetsiz LoRaWAN ağı.", "type-ttn-description": "Açık ve merkeziyetsiz LoRaWAN ağı.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Ölçeklenebilir özel LoRaWAN ağlarını çalıştırmak için yazılım.", "type-tti-description": "Ölçeklenebilir özel LoRaWAN ağlarını çalıştırmak için yazılım.",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN ağı yapılandırma sunucusu.", "type-chirpstack-description": "LoRaWAN ağı yapılandırma sunucusu.",

4
ui-ngx/src/assets/locale/locale.constant-uk_UA.json

@ -5690,9 +5690,9 @@
"type-aws-sqs-description": "Повністю керований сервіс черг повідомлень.", "type-aws-sqs-description": "Повністю керований сервіс черг повідомлень.",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "Сервіс для потоків відео та даних у реальному часі.", "type-aws-kinesis-description": "Сервіс для потоків відео та даних у реальному часі.",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "Відкрита та децентралізована мережа LoRaWAN.", "type-ttn-description": "Відкрита та децентралізована мережа LoRaWAN.",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "Програмне забезпечення для масштабованої експлуатації приватних мереж LoRaWAN.", "type-tti-description": "Програмне забезпечення для масштабованої експлуатації приватних мереж LoRaWAN.",
"type-things-stack": "The Things Stack", "type-things-stack": "The Things Stack",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",

4
ui-ngx/src/assets/locale/locale.constant-zh_CN.json

@ -4851,9 +4851,9 @@
"type-aws-sqs-description": "完全托管的消息队列服务。", "type-aws-sqs-description": "完全托管的消息队列服务。",
"type-aws-kinesis": "AWS Kinesis", "type-aws-kinesis": "AWS Kinesis",
"type-aws-kinesis-description": "实时视频和数据流服务。", "type-aws-kinesis-description": "实时视频和数据流服务。",
"type-ttn": "The Things Stack Community", "type-ttn": "The Things Stack Sandbox",
"type-ttn-description": "开放去中心化的 LoRaWAN 网络。", "type-ttn-description": "开放去中心化的 LoRaWAN 网络。",
"type-tti": "The Things Stack Industries", "type-tti": "The Things Stack Cloud",
"type-tti-description": "用于大规模运营私有 LoRaWAN 网络的软件。", "type-tti-description": "用于大规模运营私有 LoRaWAN 网络的软件。",
"type-chirpstack": "ChirpStack", "type-chirpstack": "ChirpStack",
"type-chirpstack-description": "LoRaWAN 网络配置服务器。", "type-chirpstack-description": "LoRaWAN 网络配置服务器。",

Loading…
Cancel
Save