Browse Source

Merge remote-tracking branch 'internal/hotfix-4.4' into fix/group-info-lookup-owner-check-lts-4.4

pull/16844/head
Viacheslav Klimov 3 weeks ago
parent
commit
9182da2d2d
Failed to extract signature
  1. 2
      .gitattributes
  2. 26
      .github/workflows/check-license-headers.yml
  3. 47
      CONTRIBUTING.md
  4. 14
      MAINTAINERS.md
  5. 2
      README.md
  6. 84
      application/pom.xml
  7. 10
      application/src/main/data/json/demo/dashboards/firmware.json
  8. 10
      application/src/main/data/json/demo/dashboards/software.json
  9. 4
      application/src/main/data/json/demo/dashboards/thermostats.json
  10. 4
      application/src/main/data/json/edge/instructions/install/centos/instructions.md
  11. 2
      application/src/main/data/json/edge/instructions/install/docker/instructions.md
  12. 4
      application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md
  13. 6
      application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md
  14. 4
      application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md
  15. 2
      application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md
  16. 6
      application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md
  17. 2
      application/src/main/data/json/system/widget_types/asset_admin_table.json
  18. 4
      application/src/main/data/json/system/widget_types/basic_gpio_control.json
  19. 2
      application/src/main/data/json/system/widget_types/device_admin_table.json
  20. 2
      application/src/main/data/json/system/widget_types/led_indicator.json
  21. 4
      application/src/main/data/json/system/widget_types/raspberry_pi_gpio_control.json
  22. 2
      application/src/main/data/json/system/widget_types/round_switch.json
  23. 2
      application/src/main/data/json/system/widget_types/slide_toggle_control.json
  24. 2
      application/src/main/data/json/system/widget_types/switch_control.json
  25. 6
      application/src/main/data/resources/dashboards/gateways_dashboard.json
  26. 10
      application/src/main/data/resources/js_extensions/gateway-management-extension.js
  27. 10
      application/src/main/data/upgrade/basic/schema_update.sql
  28. 2
      application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql
  29. 5
      application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql
  30. 5
      application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql
  31. 10
      application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql
  32. 21
      application/src/main/java/org/thingsboard/server/actors/app/AppActor.java
  33. 10
      application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleChainActorMessageProcessor.java
  34. 23
      application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleNodeActor.java
  35. 24
      application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleNodeActorMessageProcessor.java
  36. 13
      application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.java
  37. 23
      application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java
  38. 98
      application/src/main/java/org/thingsboard/server/config/SwaggerConfiguration.java
  39. 2
      application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
  40. 23
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  41. 8
      application/src/main/java/org/thingsboard/server/controller/AiDeviceDashboardController.java
  42. 76
      application/src/main/java/org/thingsboard/server/controller/AiModelController.java
  43. 88
      application/src/main/java/org/thingsboard/server/controller/AiResourceController.java
  44. 28
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  45. 12
      application/src/main/java/org/thingsboard/server/controller/AlarmController.java
  46. 448
      application/src/main/java/org/thingsboard/server/controller/ControllerConstants.java
  47. 73
      application/src/main/java/org/thingsboard/server/controller/ConverterController.java
  48. 4
      application/src/main/java/org/thingsboard/server/controller/DeviceController.java
  49. 35
      application/src/main/java/org/thingsboard/server/controller/EdgeController.java
  50. 48
      application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
  51. 26
      application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
  52. 16
      application/src/main/java/org/thingsboard/server/controller/IntegrationController.java
  53. 44
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  54. 20
      application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java
  55. 86
      application/src/main/java/org/thingsboard/server/controller/SignUpController.java
  56. 27
      application/src/main/java/org/thingsboard/server/controller/SystemInfoController.java
  57. 12
      application/src/main/java/org/thingsboard/server/controller/TbResourceController.java
  58. 2
      application/src/main/java/org/thingsboard/server/controller/UserPermissionsController.java
  59. 3
      application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.java
  60. 4
      application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
  61. 14
      application/src/main/java/org/thingsboard/server/service/agent/AgentGrpcService.java
  62. 9
      application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java
  63. 7
      application/src/main/java/org/thingsboard/server/service/agent/config/MergeHostValuesRule.java
  64. 62
      application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java
  65. 79
      application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java
  66. 32
      application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java
  67. 87
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  68. 8
      application/src/main/java/org/thingsboard/server/service/ai/LocalTbAiTokenProvider.java
  69. 47
      application/src/main/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProvider.java
  70. 8
      application/src/main/java/org/thingsboard/server/service/ai/TbAiConfiguration.java
  71. 15
      application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java
  72. 5
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  73. 57
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  74. 2
      application/src/main/java/org/thingsboard/server/service/ai/dashboard/AiDeviceDashboardService.java
  75. 13
      application/src/main/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardService.java
  76. 24
      application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java
  77. 84
      application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java
  78. 7
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  79. 77
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  80. 9
      application/src/main/java/org/thingsboard/server/service/ai/tool/DefaultAiToolService.java
  81. 204
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
  82. 280
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  83. 16
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelExchange.java
  84. 359
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
  85. 14
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
  86. 11
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelUnavailableException.java
  87. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperation.java
  88. 42
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
  89. 339
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  90. 260
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutor.java
  91. 21
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java
  92. 40
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnContext.java
  93. 41
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnLink.java
  94. 14
      application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java
  95. 14
      application/src/main/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldReprocessingService.java
  96. 4
      application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java
  97. 20
      application/src/main/java/org/thingsboard/server/service/converter/ConverterDefaultsService.java
  98. 66
      application/src/main/java/org/thingsboard/server/service/converter/DefaultConverterDefaultsService.java
  99. 6
      application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java
  100. 35
      application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java

2
.gitattributes

@ -0,0 +1,2 @@
# Shipped as committed: its SBOM records the SHA-256 of these exact bytes
application/src/main/data/resources/js_extensions/gateway-management-extension.js -text

26
.github/workflows/check-license-headers.yml

@ -11,19 +11,12 @@ on:
- master - master
- rc - rc
- 'lts-[0-9]+.[0-9]+' - 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
pull_request: pull_request:
branches: branches:
- master - master
- rc - rc
- 'lts-[0-9]+.[0-9]+' - 'lts-[0-9]+.[0-9]+'
- 'license-lts-[0-9]+.[0-9]+'
workflow_dispatch: workflow_dispatch:
inputs:
ce-branch:
description: CE branch to compare against; defaults to the counterpart of the current branch
required: false
type: string
permissions: permissions:
contents: read contents: read
@ -53,27 +46,10 @@ jobs:
java-version: 21 java-version: 21
cache: maven cache: maven
- name: Resolve CE branch
id: ce
env:
PE_BRANCH: ${{ github.base_ref || github.ref_name }}
CE_BRANCH: ${{ inputs.ce-branch }}
run: |
if [[ -z "$CE_BRANCH" ]]; then
case "$PE_BRANCH" in
master|rc) CE_BRANCH="$PE_BRANCH" ;;
lts-*|license-lts-*) CE_BRANCH="${PE_BRANCH#license-}" ;;
*) echo "::error::No CE counterpart is defined for branch $PE_BRANCH"; exit 1 ;;
esac
fi
echo "branch=$CE_BRANCH" >> "$GITHUB_OUTPUT"
- name: Check license headers - name: Check license headers
env:
CE_BRANCH: ${{ steps.ce.outputs.branch }}
run: | run: |
mkdir -p target/license-provenance mkdir -p target/license-provenance
./check-license-headers.sh "${CE_BRANCH}" 2>&1 | tee target/license-provenance/console.log ./check-license-headers.sh 2>&1 | tee target/license-provenance/console.log
- name: Add findings to the job summary - name: Add findings to the job summary
if: failure() && hashFiles('target/license-provenance/console.log') != '' if: failure() && hashFiles('target/license-provenance/console.log') != ''

47
CONTRIBUTING.md

@ -152,8 +152,47 @@ rm ~/.testcontainers.properties
Open a pull request against `master`. Fill out the pull request template, and make sure: Open a pull request against `master`. Fill out the pull request template, and make sure:
- New or changed behavior has test coverage. - New or changed behavior has test coverage.
- `mvn license:format` has been run, so new files carry the correct license header. - `mvn license:format` has been run, so new files carry the correct license header. Do not add
your own copyright or author lines to file headers.
- The change builds cleanly: `mvn -pl <module> -am -DskipTests -Dpkg.skip=true test-compile` at minimum for the modules you touched. - The change builds cleanly: `mvn -pl <module> -am -DskipTests -Dpkg.skip=true test-compile` at minimum for the modules you touched.
- You have signed the Contributor License Agreement (see below).
By contributing, you agree that your contribution is licensed under this project's license (see
[LICENSE](./LICENSE)). ### Pull request titles
The release notes are generated from pull request titles, word for word. Write the title for the
people who read them — users and customers, not reviewers:
- **Describe the change in behavior, as a user sees it.** Name the feature or screen and what now
works differently. Leave out class names, exceptions, library versions and other internals a
user can't relate to; they belong in the description.
- **Use the past tense, starting with a verb** such as `Fixed`, `Added`, `Updated`, `Improved`,
`Removed`, `Renamed` or `Made`. Not `Fix`, `Add` or `Update`.
- **Leave out code-scope prefixes and suffixes** such as `fix(ui):`, ticket keys or branch names
(`(lts-4.3)`). A product-area prefix a user recognizes is fine, followed by the verb:
`IoT Hub: added filtering of the catalogue by the creator's verification status`.
The section an entry appears under (`UI`, `Bug: UI`, `Edge`, …) comes from the pull request's
labels, not its title, so don't repeat the area or the change type in the title. Changes users
don't see — CI, build, a second backport of the same fix — get the `Ignore for release` label
and stay out of the release notes. For anything else, such as docs or refactoring, decide
whether users would want to read about it in the release notes, and add the label if not.
| Instead of | Write |
|----------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| `fix(ui): update moment-timezone to 0.6.5 (tzdata 2026e)` | `Updated UI time zone data to reflect 2026 daylight saving time changes in Canada, Morocco and Moldova` |
| `Warn that updating a solution template recreates everything it installed` | `Added a warning that updating a solution template recreates everything it installed` |
| `Fix empty Provisioning step when navigating the device install wizard via the stepper header` | `Fixed empty Provisioning step when navigating the device install wizard via the stepper header` |
## Contributor License Agreement
Before we can merge your pull request, you need to sign the ThingsBoard
[Contributor License Agreement](https://cla-assistant.io/thingsboard/thingsboard) (CLA). On your
first pull request a bot posts a link: sign in with GitHub and accept the agreement. You sign once,
and it covers all your contributions to this repository, including those made before you signed.
You keep the copyright in your contributions. The CLA grants ThingsBoard, Inc. a license to use and
distribute them, including under this project's license (see [LICENSE](./LICENSE)) and under
commercial licenses.
If you contribute on behalf of your employer, your employer may need to sign the Corporate CLA
instead. Contact info@thingsboard.io.

14
MAINTAINERS.md

@ -0,0 +1,14 @@
# Maintainers
This file lists the maintainers of the ThingsBoard project.
Maintainers review and merge pull requests, triage issues, and drive project releases.
| Name | GitHub | Email |
|---------------------|--------------------------------------------------------|---------------------------|
| Andrii Shvaika | [@ashvayka](https://github.com/ashvayka) | ashvayka@thingsboard.io |
| Igor Kulikov | [@ikulikov](https://github.com/ikulikov) | ikulikov@thingsboard.io |
| Viacheslav Klimov | [@ViacheslavKlimov](https://github.com/ViacheslavKlimov) | vklimov@thingsboard.io |
| Vladyslav Prykhodko | [@vvlladd28](https://github.com/vvlladd28) | vprykhodko@thingsboard.io |
| Sergey Matvienko | [@smatvienko-tb](https://github.com/smatvienko-tb) | smatvienko@thingsboard.io |
For security issues, please follow the process described in [security.md](security.md) instead of contacting maintainers directly.

2
README.md

@ -1,4 +1,4 @@
![banner](https://github.com/user-attachments/assets/25e87623-bc08-429e-9239-abf92800034a) ![banner](https://github.com/user-attachments/assets/526ba5f6-0944-4613-aac4-19a76158aa48)
<div align="center"> <div align="center">

84
application/pom.xml

@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.thingsboard</groupId> <groupId>org.thingsboard</groupId>
<version>4.4.0.2</version> <version>4.4.1-SNAPSHOT</version>
<artifactId>thingsboard</artifactId> <artifactId>thingsboard</artifactId>
</parent> </parent>
<artifactId>application</artifactId> <artifactId>application</artifactId>
@ -27,6 +27,7 @@
<pkg.type>java</pkg.type> <pkg.type>java</pkg.type>
<pkg.process-resources.phase>process-resources</pkg.process-resources.phase> <pkg.process-resources.phase>process-resources</pkg.process-resources.phase>
<pkg.package.phase>package</pkg.package.phase> <pkg.package.phase>package</pkg.package.phase>
<sbom.package.phase>${pkg.package.phase}</sbom.package.phase>
<pkg.name>thingsboard</pkg.name> <pkg.name>thingsboard</pkg.name>
<pkg.win.dist>${project.build.directory}/windows</pkg.win.dist> <pkg.win.dist>${project.build.directory}/windows</pkg.win.dist>
<pkg.copyInstallScripts>true</pkg.copyInstallScripts> <pkg.copyInstallScripts>true</pkg.copyInstallScripts>
@ -577,6 +578,10 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.cyclonedx</groupId>
<artifactId>cyclonedx-maven-plugin</artifactId>
</plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
@ -593,6 +598,83 @@
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<!-- The gateway extension and its SBOM are committed together and must match. The package SBOM
checks it too, but only with -Dsbom.skip=false, which would be at the release. -->
<execution>
<id>check-gateway-extension-sbom</id>
<phase>validate</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<evaluateBeanshell>
<condition><![CDATA[
new String(java.nio.file.Files.readAllBytes(new java.io.File(new java.net.URI("${project.baseUri}src/main/sbom/gateway-management-extension.cdx.json")).toPath()), "UTF-8")
.contains(org.apache.commons.codec.digest.DigestUtils.sha256Hex(java.nio.file.Files.readAllBytes(new java.io.File(new java.net.URI("${project.baseUri}src/main/data/resources/js_extensions/gateway-management-extension.js")).toPath())))
]]></condition>
<message>src/main/sbom/gateway-management-extension.cdx.json does not describe src/main/data/resources/js_extensions/gateway-management-extension.js: it does not contain the SHA-256 of that file. Take both files from the same build in the gateway-management-extensions-dist repository.</message>
</evaluateBeanshell>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.thingsboard</groupId>
<artifactId>sbom-maven-plugin</artifactId>
<executions>
<execution>
<id>merge-ui-sbom</id>
<goals>
<goal>merge</goal>
</goals>
<configuration>
<host>org.thingsboard:ui-ngx</host>
<skip>${skip.ui.build}</skip>
</configuration>
</execution>
<execution>
<id>package-sbom</id>
<configuration>
<components combine.children="append">
<component>
<sbom>${project.basedir}/src/main/sbom/gateway-management-extension.cdx.json</sbom>
<file>${project.build.directory}/data/resources/js_extensions/gateway-management-extension.js</file>
</component>
<component>
<type>data</type>
<name>lwm2m-registry</name>
<description>LwM2M object model XML files from the OMNA LwM2M Registry. Licenses vary per file, mostly BSD-3-Clause.</description>
<supplier>
<name>Open Mobile Alliance</name>
<urls>
<url>https://github.com/OpenMobileAlliance/lwm2m-registry</url>
</urls>
</supplier>
<file>${project.build.directory}/data/lwm2m-registry</file>
</component>
<component>
<type>cryptographic-asset</type>
<name>DigiCert Global Root G2</name>
<description>Root CA certificate for Azure IoT Hub connections.</description>
<supplier>
<name>DigiCert, Inc.</name>
<urls>
<url>https://www.digicert.com</url>
</urls>
</supplier>
<file>${project.build.directory}/data/certs/azure/DigiCertGlobalRootG2.crt.pem</file>
</component>
</components>
</configuration>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.xolstice.maven.plugins</groupId> <groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId> <artifactId>protobuf-maven-plugin</artifactId>

10
application/src/main/data/json/demo/dashboards/firmware.json

@ -279,7 +279,7 @@
"name": "Edit firmware", "name": "Edit firmware",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1142,7 +1142,7 @@
"name": "Edit firmware", "name": "Edit firmware",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1448,7 +1448,7 @@
"name": "Edit firmware", "name": "Edit firmware",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1754,7 +1754,7 @@
"name": "Edit firmware", "name": "Edit firmware",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -2060,7 +2060,7 @@
"name": "Edit firmware", "name": "Edit firmware",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit firmware {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"firmwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n firmwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n firmwareId: vm.entity.firmwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.firmwareId = formValues.firmwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],

10
application/src/main/data/json/demo/dashboards/software.json

@ -279,7 +279,7 @@
"name": "Edit software", "name": "Edit software",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1142,7 +1142,7 @@
"name": "Edit software", "name": "Edit software",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1448,7 +1448,7 @@
"name": "Edit software", "name": "Edit software",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -1754,7 +1754,7 @@
"name": "Edit software", "name": "Edit software",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],
@ -2060,7 +2060,7 @@
"name": "Edit software", "name": "Edit software",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar class=\"flex flex-row\" color=\"primary\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit software {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div *ngIf=\"entity.deviceProfileId\" mat-dialog-content class=\"flex flex-col\">\n <tb-ota-package-autocomplete\n [appearance]=\"'outline'\"\n [useFullEntityId]=\"true\"\n type=\"SOFTWARE\"\n [deviceProfileId]=\"entity.deviceProfileId.id\"\n formControlName=\"softwareId\">\n </tb-ota-package-autocomplete>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": "form {\n min-width: 300px !important;\n}", "customCss": "form {\n min-width: 300px !important;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet entityService = $injector.get(widgetContext.servicesMap.get('entityService'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n\n vm.entityName = entityName;\n vm.entity = {};\n\n vm.editEntityFormGroup = vm.fb.group({\n softwareId: [null]\n });\n\n getEntityInfo();\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n\n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveEntity().subscribe(\n function () {\n // widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n };\n\n\n function getEntityInfo() {\n entityService.getEntity(entityId.entityType, entityId.id).subscribe(\n function (data) {\n vm.entity = data;\n vm.editEntityFormGroup.patchValue({\n softwareId: vm.entity.softwareId\n }, {emitEvent: false});\n }\n );\n }\n\n function saveEntity() {\n const formValues = vm.editEntityFormGroup.value;\n vm.entity.softwareId = formValues.softwareId;\n return deviceService.saveDevice(vm.entity);\n }\n}",
"customResources": [], "customResources": [],

4
application/src/main/data/json/demo/dashboards/thermostats.json

@ -167,7 +167,7 @@
"name": "Add", "name": "Add",
"icon": "add", "icon": "add",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"add-entity-form\">\n <mat-toolbar color=\"primary\">\n <h2>Add thermostat</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" required>\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required')\">\n Thermostat name is required.\n </mat-error>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\n Create\n </button>\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n </div>\n</form>", "customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"add-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Add thermostat</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" required>\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required')\">\n Thermostat name is required.\n </mat-error>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"addEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\n Create\n </button>\n </div>\n</form>",
"customCss": ".add-entity-form{\n width: 300px;\n}\n", "customCss": ".add-entity-form{\n width: 300px;\n}\n",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenAddEntityDialog();\n\nfunction openAddEntityDialog() {\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\n}\n\nfunction AddEntityDialogController(instance) {\n let vm = instance;\n \n vm.addEntityFormGroup = vm.fb.group({\n entityName: ['', [vm.validators.required]],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.addEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n\n vm.save = function() {\n vm.addEntityFormGroup.markAsPristine();\n saveEntityObservable().subscribe(\n function (entity) {\n saveAttributes(entity.id).subscribe(\n function () {\n widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function saveEntityObservable() {\n const formValues = vm.addEntityFormGroup.value;\n let entity = {\n name: formValues.entityName,\n type: \"thermostat\"\n };\n return deviceService.saveDevice(entity);\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.addEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if(attributes[key] !== null) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenAddEntityDialog();\n\nfunction openAddEntityDialog() {\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\n}\n\nfunction AddEntityDialogController(instance) {\n let vm = instance;\n \n vm.addEntityFormGroup = vm.fb.group({\n entityName: ['', [vm.validators.required]],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.addEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.addEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n\n vm.save = function() {\n vm.addEntityFormGroup.markAsPristine();\n saveEntityObservable().subscribe(\n function (entity) {\n saveAttributes(entity.id).subscribe(\n function () {\n widgetContext.updateAliases();\n vm.dialogRef.close(null);\n }\n );\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function saveEntityObservable() {\n const formValues = vm.addEntityFormGroup.value;\n let entity = {\n name: formValues.entityName,\n type: \"thermostat\"\n };\n return deviceService.saveDevice(entity);\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.addEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if(attributes[key] !== null) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}",
"customResources": [], "customResources": [],
@ -187,7 +187,7 @@
"name": "Edit", "name": "Edit",
"icon": "edit", "icon": "edit",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"primary\">\n <h2>Edit thermostat {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" readonly>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n </div>\n</form>", "customHtml": "<form #editEntityForm=\"ngForm\" [formGroup]=\"editEntityFormGroup\"\n (ngSubmit)=\"save()\" class=\"edit-entity-form\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row\">\n <h2>Edit thermostat {{entityName}}</h2>\n <span class=\"flex-1\"></span>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\n </mat-progress-bar>\n <div style=\"height: 4px;\" *ngIf=\"!(isLoading$ | async)\"></div>\n <div mat-dialog-content class=\"flex flex-col\">\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>Thermostat name</mat-label>\n <input matInput formControlName=\"entityName\" readonly>\n </mat-form-field>\n <div formGroupName=\"attributes\" class=\"flex flex-col\">\n <mat-slide-toggle formControlName=\"temperatureAlarmFlag\">\n High temperature alarm\n </mat-slide-toggle>\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>High temperature threshold, °C</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').value\"\n formControlName=\"temperatureAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').hasError('required')\">\n High temperature threshold is required.\n </mat-error>\n </mat-form-field>\n\n <mat-slide-toggle formControlName=\"humidityAlarmFlag\">\n Low humidity alarm\n </mat-slide-toggle>\n\n <mat-form-field class=\"mat-block flex-1\" appearance=\"outline\">\n <mat-label>Low humidity threshold, %</mat-label>\n <input type=\"number\" step=\"any\" matInput\n [required] = \"editEntityFormGroup.get('attributes').get('humidityAlarmFlag').value\"\n formControlName=\"humidityAlarmThreshold\">\n <mat-error *ngIf=\"editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').hasError('required')\">\n Low humidity threshold is required.\n </mat-error>\n </mat-form-field>\n </div>\n </div>\n <div mat-dialog-actions class=\"flex flex-row items-center justify-end\">\n <button mat-button color=\"primary\"\n type=\"button\"\n [disabled]=\"(isLoading$ | async)\"\n (click)=\"cancel()\" cdkFocusInitial>\n Cancel\n </button>\n <button mat-button mat-raised-button color=\"primary\"\n type=\"submit\"\n [disabled]=\"(isLoading$ | async) || editEntityForm.invalid || !editEntityForm.dirty\">\n Save\n </button>\n </div>\n</form>",
"customCss": ".edit-entity-form{\n width: 300px;\n}", "customCss": ".edit-entity-form{\n width: 300px;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId;\n vm.entityName = entityName;\n vm.attributes = {};\n \n vm.editEntityFormGroup = vm.fb.group({\n entityName: [''],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.editEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n \n \n getEntityInfo();\n \n \n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveAttributes(entityId).subscribe(\n function () {\n vm.dialogRef.close(null);\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function getEntityAttributes(attributes) {\n for (var i = 0; i < attributes.length; i++) {\n vm.attributes[attributes[i].key] = attributes[i].value;\n }\n }\n \n function getEntityInfo() {\n attributeService.getEntityAttributes(entityId, 'SERVER_SCOPE').subscribe(\n function (attributes) {\n getEntityAttributes(attributes);\n vm.editEntityFormGroup.patchValue({\n entityName: vm.entityName,\n attributes: vm.attributes\n });\n // if(vm.attributes.temperatureAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n // }\n // if(vm.attributes.humidityAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n // }\n }\n );\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.editEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if (attributes[key] !== vm.attributes[key]) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\n\nopenEditEntityDialog();\n\nfunction openEditEntityDialog() {\n customDialog.customDialog(htmlTemplate, EditEntityDialogController).subscribe();\n}\n\nfunction EditEntityDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId;\n vm.entityName = entityName;\n vm.attributes = {};\n \n vm.editEntityFormGroup = vm.fb.group({\n entityName: [''],\n attributes: vm.fb.group({\n temperatureAlarmFlag: [false],\n temperatureAlarmThreshold: [{value: null, disabled: true}],\n humidityAlarmFlag: [false],\n humidityAlarmThreshold: [{value: null, disabled: true}]\n })\n });\n \n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').disable();\n }\n });\n \n vm.editEntityFormGroup.get('attributes').get('humidityAlarmFlag').valueChanges\n .subscribe(activate => {\n if (activate) {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n } else {\n vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').disable();\n }\n });\n \n \n getEntityInfo();\n \n \n vm.save = function() {\n vm.editEntityFormGroup.markAsPristine();\n saveAttributes(entityId).subscribe(\n function () {\n vm.dialogRef.close(null);\n }\n );\n };\n \n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n \n function getEntityAttributes(attributes) {\n for (var i = 0; i < attributes.length; i++) {\n vm.attributes[attributes[i].key] = attributes[i].value;\n }\n }\n \n function getEntityInfo() {\n attributeService.getEntityAttributes(entityId, 'SERVER_SCOPE').subscribe(\n function (attributes) {\n getEntityAttributes(attributes);\n vm.editEntityFormGroup.patchValue({\n entityName: vm.entityName,\n attributes: vm.attributes\n });\n // if(vm.attributes.temperatureAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('temperatureAlarmThreshold').enable();\n // }\n // if(vm.attributes.humidityAlarmFlag) {\n // vm.editEntityFormGroup.get('attributes').get('humidityAlarmThreshold').enable();\n // }\n }\n );\n }\n \n function saveAttributes(entityId) {\n let attributes = vm.editEntityFormGroup.get('attributes').value;\n let attributesArray = [];\n for (let key in attributes) {\n if (attributes[key] !== vm.attributes[key]) {\n attributesArray.push({key: key, value: attributes[key]});\n }\n }\n if (attributesArray.length > 0) {\n return attributeService.saveEntityAttributes(entityId, \"SERVER_SCOPE\", attributesArray);\n } else {\n return widgetContext.rxjs.of([]);\n }\n }\n}",
"customResources": [], "customResources": [],

4
application/src/main/data/json/edge/instructions/install/centos/instructions.md

@ -116,14 +116,14 @@ sudo systemctl restart postgresql-16.service && psql -U postgres -d postgres -h
Download installation package: Download installation package:
```bash ```bash
wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.rpm wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm
{:copy-code} {:copy-code}
``` ```
Go to the download repository and install ThingsBoard Edge service: Go to the download repository and install ThingsBoard Edge service:
```bash ```bash
sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}pe.rpm sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm
{:copy-code} {:copy-code}
``` ```

2
application/src/main/data/json/edge/instructions/install/docker/instructions.md

@ -24,7 +24,7 @@ Add the following lines to the yml file:
services: services:
mytbedge: mytbedge:
restart: always restart: always
image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}"
ports: ports:
- "8080:8080" - "8080:8080"
- "1883:1883" - "1883:1883"

4
application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md

@ -74,14 +74,14 @@ echo "CREATE DATABASE tb_edge;" | psql -U postgres -d postgres -h 127.0.0.1 -W
Download the installation package: Download the installation package:
```bash ```bash
wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.deb wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb
{:copy-code} {:copy-code}
``` ```
Go to the download repository and install ThingsBoard Edge service: Go to the download repository and install ThingsBoard Edge service:
```bash ```bash
sudo dpkg -i tb-edge-${TB_EDGE_TAG}pe.deb sudo dpkg -i tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb
{:copy-code} {:copy-code}
``` ```

6
application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md

@ -1,14 +1,14 @@
#### Upgrading to ${TB_EDGE_VERSION}EDGEPE #### Upgrading to ${TB_EDGE_VERSION}
ThingsBoard Edge package download: ThingsBoard Edge package download:
```bash ```bash
wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.rpm wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm
{:copy-code} {:copy-code}
``` ```
Install package: Install package:
```bash ```bash
sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}pe.rpm sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.rpm
{:copy-code} {:copy-code}
``` ```

4
application/src/main/data/json/edge/instructions/upgrade/docker/start_service.md

@ -8,11 +8,11 @@ nano docker-compose.yml
services: services:
mytbedge: mytbedge:
restart: always restart: always
image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}"
... ...
``` ```
Make sure your image is set to **tb-edge-pe:${TB_EDGE_VERSION}**. Make sure your image is set to **${TB_EDGE_REPO}:${TB_EDGE_VERSION}**.
Execute the following commands to up this docker compose directly: Execute the following commands to up this docker compose directly:
```bash ```bash

2
application/src/main/data/json/edge/instructions/upgrade/docker/upgrade_db.md

@ -11,7 +11,7 @@ Add the following lines to the yml file:
services: services:
mytbedge: mytbedge:
restart: on-failure restart: on-failure
image: "thingsboard/tb-edge-pe:${TB_EDGE_VERSION}" image: "thingsboard/${TB_EDGE_REPO}:${TB_EDGE_VERSION}"
environment: environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/tb-edge SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/tb-edge
volumes: volumes:

6
application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md

@ -1,13 +1,13 @@
#### Upgrading to ${TB_EDGE_VERSION}EDGEPE #### Upgrading to ${TB_EDGE_VERSION}
ThingsBoard Edge package download: ThingsBoard Edge package download:
```bash ```bash
wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}pe.deb wget https://dist.thingsboard.io/tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb
{:copy-code} {:copy-code}
``` ```
Install package: Install package:
```bash ```bash
sudo dpkg -i tb-edge-${TB_EDGE_TAG}pe.deb sudo dpkg -i tb-edge-${TB_EDGE_TAG}${TB_EDGE_PKG_SUFFIX}.deb
{:copy-code} {:copy-code}
``` ```

2
application/src/main/data/json/system/widget_types/asset_admin_table.json

File diff suppressed because one or more lines are too long

4
application/src/main/data/json/system/widget_types/basic_gpio_control.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/device_admin_table.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/led_indicator.json

@ -11,7 +11,7 @@
"resources": [], "resources": [],
"templateHtml": "<tb-led-indicator [ctx]='ctx'></tb-led-indicator>", "templateHtml": "<tb-led-indicator [ctx]='ctx'></tb-led-indicator>",
"templateCss": "", "templateCss": "",
"controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n", "controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n\nself.typeParameters = function() {\n return {\n displayRpcMessageToast: false\n };\n}\n",
"dataKeySettingsSchema": "{}\n", "dataKeySettingsSchema": "{}\n",
"settingsDirective": "tb-led-indicator-widget-settings", "settingsDirective": "tb-led-indicator-widget-settings",
"defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"title\":\"Led indicator\",\"ledColor\":\"#4caf50\",\"valueAttribute\":\"value\",\"retrieveValueMethod\":\"attribute\",\"parseValueFunction\":\"return data ? true : false;\",\"performCheckStatus\":true,\"checkStatusMethod\":\"checkStatus\"},\"title\":\"Led indicator\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}" "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"title\":\"Led indicator\",\"ledColor\":\"#4caf50\",\"valueAttribute\":\"value\",\"retrieveValueMethod\":\"attribute\",\"parseValueFunction\":\"return data ? true : false;\",\"performCheckStatus\":true,\"checkStatusMethod\":\"checkStatus\"},\"title\":\"Led indicator\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}"

4
application/src/main/data/json/system/widget_types/raspberry_pi_gpio_control.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/round_switch.json

@ -11,7 +11,7 @@
"resources": [], "resources": [],
"templateHtml": "<tb-round-switch [ctx]='ctx'></tb-round-switch>", "templateHtml": "<tb-round-switch [ctx]='ctx'></tb-round-switch>",
"templateCss": "", "templateCss": "",
"controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n", "controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n\nself.typeParameters = function() {\n return {\n displayRpcMessageToast: false\n };\n}\n",
"dataKeySettingsSchema": "{}\n", "dataKeySettingsSchema": "{}\n",
"settingsDirective": "tb-round-switch-widget-settings", "settingsDirective": "tb-round-switch-widget-settings",
"defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"title\":\"Round switch\",\"retrieveValueMethod\":\"rpc\",\"valueKey\":\"value\",\"parseValueFunction\":\"return data ? true : false;\",\"convertValueFunction\":\"return value;\"},\"title\":\"Round switch\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}" "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"title\":\"Round switch\",\"retrieveValueMethod\":\"rpc\",\"valueKey\":\"value\",\"parseValueFunction\":\"return data ? true : false;\",\"convertValueFunction\":\"return value;\"},\"title\":\"Round switch\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}"

2
application/src/main/data/json/system/widget_types/slide_toggle_control.json

@ -11,7 +11,7 @@
"resources": [], "resources": [],
"templateHtml": "<tb-switch [ctx]='ctx' switchType='slide-toggle'></tb-switch>", "templateHtml": "<tb-switch [ctx]='ctx' switchType='slide-toggle'></tb-switch>",
"templateCss": "", "templateCss": "",
"controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n", "controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n\nself.typeParameters = function() {\n return {\n displayRpcMessageToast: false\n };\n}\n",
"dataKeySettingsSchema": "{}\n", "dataKeySettingsSchema": "{}\n",
"settingsDirective": "tb-slide-toggle-widget-settings", "settingsDirective": "tb-slide-toggle-widget-settings",
"defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#ffffff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"title\":\"Slide toggle control\",\"retrieveValueMethod\":\"rpc\",\"valueKey\":\"value\",\"parseValueFunction\":\"return data ? true : false;\",\"convertValueFunction\":\"return value;\",\"requestPersistent\":false,\"labelPosition\":\"after\",\"sliderColor\":\"accent\"},\"title\":\"Slide Toggle Control\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2,\"widgetCss\":\"\",\"noDataDisplayMessage\":\"\"}" "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#ffffff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"title\":\"Slide toggle control\",\"retrieveValueMethod\":\"rpc\",\"valueKey\":\"value\",\"parseValueFunction\":\"return data ? true : false;\",\"convertValueFunction\":\"return value;\",\"requestPersistent\":false,\"labelPosition\":\"after\",\"sliderColor\":\"accent\"},\"title\":\"Slide Toggle Control\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2,\"widgetCss\":\"\",\"noDataDisplayMessage\":\"\"}"

2
application/src/main/data/json/system/widget_types/switch_control.json

@ -11,7 +11,7 @@
"resources": [], "resources": [],
"templateHtml": "<tb-switch [ctx]='ctx'></tb-switch>", "templateHtml": "<tb-switch [ctx]='ctx'></tb-switch>",
"templateCss": "", "templateCss": "",
"controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n", "controllerScript": "self.onInit = function() {\n}\n\nself.onResize = function() {\n}\n\nself.onDestroy = function() {\n}\n\nself.typeParameters = function() {\n return {\n displayRpcMessageToast: false\n };\n}\n",
"dataKeySettingsSchema": "{}\n", "dataKeySettingsSchema": "{}\n",
"settingsDirective": "tb-switch-control-widget-settings", "settingsDirective": "tb-switch-control-widget-settings",
"defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"showOnOffLabels\":true,\"title\":\"Switch control\"},\"title\":\"Switch Control\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}" "defaultConfig": "{\"targetDeviceAliases\":[],\"showTitle\":false,\"backgroundColor\":\"#e6e7e8\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"0px\",\"settings\":{\"requestTimeout\":500,\"initialValue\":false,\"getValueMethod\":\"getValue\",\"setValueMethod\":\"setValue\",\"showOnOffLabels\":true,\"title\":\"Switch control\"},\"title\":\"Switch Control\",\"dropShadow\":true,\"enableFullscreen\":false,\"widgetStyle\":{},\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"actions\":{},\"decimals\":2}"

6
application/src/main/data/resources/dashboards/gateways_dashboard.json

@ -160,7 +160,7 @@
"useShowWidgetActionFunction": null, "useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;", "showWidgetActionFunction": "return true;",
"type": "customPretty", "type": "customPretty",
"customHtml": "<div class=\"container\">\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\" type=\"button\" (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n", "customHtml": "<div class=\"container\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\" type=\"button\" (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}", "customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n",
"customResources": [ "customResources": [
@ -257,7 +257,7 @@
"useShowWidgetActionFunction": null, "useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;", "showWidgetActionFunction": "return true;",
"type": "customPretty", "type": "customPretty",
"customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\r\n (ngSubmit)=\"save($event)\" class=\"add-entity-form\">\r\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\r\n <h2>Add gateway</h2>\r\n <span class=\"flex-1\"></span>\r\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\r\n <mat-icon class=\"material-icons\">close</mat-icon>\r\n </button>\r\n </mat-toolbar>\r\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\r\n </mat-progress-bar>\r\n <div class=\"h-1\" *ngIf=\"!(isLoading$ | async)\"></div>\r\n <div mat-dialog-content class=\"flex flex-col\">\r\n <div class=\"flex flex-row gap-2 flex-wrap\" >\r\n <mat-form-field class=\"w-full sm:w-auto\" appearance=\"outline\">\r\n <mat-label>Name</mat-label>\r\n <input matInput formControlName=\"entityName\" required>\r\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required') || addEntityFormGroup.get('entityName').hasError('pattern')\">\r\n Gateway name is required.\r\n </mat-error>\r\n </mat-form-field>\r\n </div>\r\n <div class=\"flex flex-row gap-2 flex-wrap\">\r\n <tb-entity-subtype-autocomplete\r\n class=\"w-full sm:w-auto\"\r\n formControlName=\"type\"\r\n [required]=\"true\"\r\n [entityType]=\"'DEVICE'\"\r\n appearance=\"outline\"\r\n ></tb-entity-subtype-autocomplete>\r\n </div>\r\n </div>\r\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\r\n <button mat-button color=\"primary\"\r\n type=\"button\"\r\n [disabled]=\"(isLoading$ | async)\"\r\n (click)=\"cancel()\" cdkFocusInitial>\r\n Cancel\r\n </button>\r\n <button mat-button mat-raised-button color=\"primary\"\r\n type=\"submit\"\r\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\r\n Create\r\n </button>\r\n </div>\r\n</form>\r\n", "customHtml": "<form #addEntityForm=\"ngForm\" [formGroup]=\"addEntityFormGroup\"\r\n (ngSubmit)=\"save($event)\" class=\"add-entity-form\">\r\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\r\n <h2>Add gateway</h2>\r\n <span class=\"flex-1\"></span>\r\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\r\n <mat-icon class=\"material-icons\">close</mat-icon>\r\n </button>\r\n </mat-toolbar>\r\n <mat-progress-bar color=\"warn\" mode=\"indeterminate\" *ngIf=\"isLoading$ | async\">\r\n </mat-progress-bar>\r\n <div class=\"h-1\" *ngIf=\"!(isLoading$ | async)\"></div>\r\n <div mat-dialog-content class=\"flex flex-col\">\r\n <div class=\"flex flex-row gap-2 flex-wrap\" >\r\n <mat-form-field class=\"w-full sm:w-auto\" appearance=\"outline\">\r\n <mat-label>Name</mat-label>\r\n <input matInput formControlName=\"entityName\" required>\r\n <mat-error *ngIf=\"addEntityFormGroup.get('entityName').hasError('required') || addEntityFormGroup.get('entityName').hasError('pattern')\">\r\n Gateway name is required.\r\n </mat-error>\r\n </mat-form-field>\r\n </div>\r\n <div class=\"flex flex-row gap-2 flex-wrap\">\r\n <tb-entity-subtype-autocomplete\r\n class=\"w-full sm:w-auto\"\r\n formControlName=\"type\"\r\n [required]=\"true\"\r\n [entityType]=\"'DEVICE'\"\r\n appearance=\"outline\"\r\n ></tb-entity-subtype-autocomplete>\r\n </div>\r\n </div>\r\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\r\n <button mat-button color=\"primary\"\r\n type=\"button\"\r\n [disabled]=\"(isLoading$ | async)\"\r\n (click)=\"cancel()\" cdkFocusInitial>\r\n Cancel\r\n </button>\r\n <button mat-button mat-raised-button color=\"primary\"\r\n type=\"submit\"\r\n [disabled]=\"(isLoading$ | async) || addEntityForm.invalid || !addEntityForm.dirty\">\r\n Create\r\n </button>\r\n </div>\r\n</form>\r\n",
"customCss": ".add-entity-form {\r\n min-width: 400px !important;\r\n}\r\n\r\n.add-entity-form .boolean-value-input {\r\n padding-left: 5px;\r\n}\r\n\r\n.add-entity-form .boolean-value-input .checkbox-label {\r\n margin-bottom: 8px;\r\n color: rgba(0,0,0,0.54);\r\n font-size: 12px;\r\n}\r\n\r\n.relations-list .header {\r\n padding-right: 5px;\r\n padding-bottom: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .header .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n font-size: 12px;\r\n font-weight: 700;\r\n color: rgba(0, 0, 0, .54);\r\n white-space: nowrap;\r\n}\r\n\r\n.relations-list .mat-form-field-infix {\r\n width: auto !important;\r\n}\r\n\r\n.relations-list .body {\r\n padding-right: 5px;\r\n padding-bottom: 15px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .row {\r\n padding-top: 5px;\r\n}\r\n\r\n.relations-list .body .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .md-button {\r\n margin: 0;\r\n}\r\n\r\n", "customCss": ".add-entity-form {\r\n min-width: 400px !important;\r\n}\r\n\r\n.add-entity-form .boolean-value-input {\r\n padding-left: 5px;\r\n}\r\n\r\n.add-entity-form .boolean-value-input .checkbox-label {\r\n margin-bottom: 8px;\r\n color: rgba(0,0,0,0.54);\r\n font-size: 12px;\r\n}\r\n\r\n.relations-list .header {\r\n padding-right: 5px;\r\n padding-bottom: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .header .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n font-size: 12px;\r\n font-weight: 700;\r\n color: rgba(0, 0, 0, .54);\r\n white-space: nowrap;\r\n}\r\n\r\n.relations-list .mat-form-field-infix {\r\n width: auto !important;\r\n}\r\n\r\n.relations-list .body {\r\n padding-right: 5px;\r\n padding-bottom: 15px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .row {\r\n padding-top: 5px;\r\n}\r\n\r\n.relations-list .body .cell {\r\n padding-right: 5px;\r\n padding-left: 5px;\r\n}\r\n\r\n.relations-list .body .md-button {\r\n margin: 0;\r\n}\r\n\r\n",
"customFunction": "let $injector = widgetContext.$scope.$injector;\r\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\r\nlet assetService = $injector.get(widgetContext.servicesMap.get('assetService'));\r\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\r\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\r\nlet entityRelationService = $injector.get(widgetContext.servicesMap.get('entityRelationService'));\r\nlet userSettingsService = $injector.get(widgetContext.servicesMap.get('userSettingsService'));\r\n\r\nopenAddEntityDialog();\r\n\r\nfunction openAddEntityDialog() {\r\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\r\n}\r\n\r\nfunction AddEntityDialogController(instance) {\r\n let vm = instance;\r\n let userSettings;\r\n userSettingsService.loadUserSettings().subscribe(settings=> {\r\n userSettings = settings;\r\n if (!userSettings.createdGatewaysCount) userSettings.createdGatewaysCount = 0;\r\n });\r\n \r\n\r\n vm.addEntityFormGroup = vm.fb.group({\r\n entityName: ['', [vm.validators.required, vm.validators.pattern(/.*\\S.*/)]],\r\n entityType: ['DEVICE'],\r\n entityLabel: [''],\r\n type: ['', [vm.validators.required]],\r\n });\r\n\r\n vm.cancel = function() {\r\n vm.dialogRef.close(null);\r\n };\r\n\r\n\r\n vm.save = function($event) {\r\n vm.addEntityFormGroup.markAsPristine();\r\n saveEntityObservable().subscribe(\r\n function (device) {\r\n widgetContext.updateAliases();\r\n userSettingsService.putUserSettings({ createdGatewaysCount: ++userSettings.createdGatewaysCount }).subscribe(_=>{\r\n });\r\n vm.dialogRef.close(null);\r\n openCommandDialog(device, $event);\r\n }\r\n );\r\n };\r\n \r\n function openCommandDialog(device, $event) {\r\n vm.device = device;\r\n let openCommandAction = widgetContext.actionsApi.getActionDescriptors(\"actionCellButton\").find(action => action.name == \"Launch command\");\r\n setTimeout(() => {\r\n widgetContext.actionsApi.handleWidgetAction($event, openCommandAction, device.id, device.name, {newDevice: true});\r\n });\r\n goToConfigState();\r\n }\r\n\r\n \r\n function goToConfigState() {\r\n const stateParams = {};\r\n stateParams.entityId = vm.device.id;\r\n stateParams.entityName = vm.device.name;\r\n const newStateParams = {\r\n targetEntityParamName: 'default',\r\n new_gateway: {\r\n entityId: vm.device.id,\r\n entityName: vm.device.name\r\n }\r\n }\r\n const params = {...stateParams, ...newStateParams};\r\n widgetContext.stateController.openState('gateway_details', params, false);\r\n }\r\n\r\n function saveEntityObservable() {\r\n const formValues = vm.addEntityFormGroup.value;\r\n let entity = {\r\n name: formValues.entityName.trim(),\r\n type: formValues.type,\r\n label: formValues.entityLabel,\r\n additionalInfo: {\r\n gateway: true\r\n }\r\n };\r\n return deviceService.saveDevice(entity);\r\n }\r\n}\r\n", "customFunction": "let $injector = widgetContext.$scope.$injector;\r\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\r\nlet assetService = $injector.get(widgetContext.servicesMap.get('assetService'));\r\nlet deviceService = $injector.get(widgetContext.servicesMap.get('deviceService'));\r\nlet attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));\r\nlet entityRelationService = $injector.get(widgetContext.servicesMap.get('entityRelationService'));\r\nlet userSettingsService = $injector.get(widgetContext.servicesMap.get('userSettingsService'));\r\n\r\nopenAddEntityDialog();\r\n\r\nfunction openAddEntityDialog() {\r\n customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe();\r\n}\r\n\r\nfunction AddEntityDialogController(instance) {\r\n let vm = instance;\r\n let userSettings;\r\n userSettingsService.loadUserSettings().subscribe(settings=> {\r\n userSettings = settings;\r\n if (!userSettings.createdGatewaysCount) userSettings.createdGatewaysCount = 0;\r\n });\r\n \r\n\r\n vm.addEntityFormGroup = vm.fb.group({\r\n entityName: ['', [vm.validators.required, vm.validators.pattern(/.*\\S.*/)]],\r\n entityType: ['DEVICE'],\r\n entityLabel: [''],\r\n type: ['', [vm.validators.required]],\r\n });\r\n\r\n vm.cancel = function() {\r\n vm.dialogRef.close(null);\r\n };\r\n\r\n\r\n vm.save = function($event) {\r\n vm.addEntityFormGroup.markAsPristine();\r\n saveEntityObservable().subscribe(\r\n function (device) {\r\n widgetContext.updateAliases();\r\n userSettingsService.putUserSettings({ createdGatewaysCount: ++userSettings.createdGatewaysCount }).subscribe(_=>{\r\n });\r\n vm.dialogRef.close(null);\r\n openCommandDialog(device, $event);\r\n }\r\n );\r\n };\r\n \r\n function openCommandDialog(device, $event) {\r\n vm.device = device;\r\n let openCommandAction = widgetContext.actionsApi.getActionDescriptors(\"actionCellButton\").find(action => action.name == \"Launch command\");\r\n setTimeout(() => {\r\n widgetContext.actionsApi.handleWidgetAction($event, openCommandAction, device.id, device.name, {newDevice: true});\r\n });\r\n goToConfigState();\r\n }\r\n\r\n \r\n function goToConfigState() {\r\n const stateParams = {};\r\n stateParams.entityId = vm.device.id;\r\n stateParams.entityName = vm.device.name;\r\n const newStateParams = {\r\n targetEntityParamName: 'default',\r\n new_gateway: {\r\n entityId: vm.device.id,\r\n entityName: vm.device.name\r\n }\r\n }\r\n const params = {...stateParams, ...newStateParams};\r\n widgetContext.stateController.openState('gateway_details', params, false);\r\n }\r\n\r\n function saveEntityObservable() {\r\n const formValues = vm.addEntityFormGroup.value;\r\n let entity = {\r\n name: formValues.entityName.trim(),\r\n type: formValues.type,\r\n label: formValues.entityLabel,\r\n additionalInfo: {\r\n gateway: true\r\n }\r\n };\r\n return deviceService.saveDevice(entity);\r\n }\r\n}\r\n",
"customResources": [], "customResources": [],
@ -1536,7 +1536,7 @@
"useShowWidgetActionFunction": null, "useShowWidgetActionFunction": null,
"showWidgetActionFunction": "return true;", "showWidgetActionFunction": "return true;",
"type": "customPretty", "type": "customPretty",
"customHtml": "<div class=\"container\">\n <mat-toolbar class=\"flex flex-row items-center\" color=\"primary\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\"\n type=\"button\"\n (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n", "customHtml": "<div class=\"container\">\n <mat-toolbar color=\"tb-primary\" class=\"tb-bottom-border flex flex-row items-center\">\n <h2>{{ 'gateway.launch-command' | translate }}</h2>\n <span class=\"flex-1\"></span>\n <div [tb-help]=\"'gatewayInstall'\"></div>\n <button mat-icon-button (click)=\"cancel()\" type=\"button\">\n <mat-icon class=\"material-icons\">close</mat-icon>\n </button>\n </mat-toolbar>\n <tb-gateway-command [deviceId]=\"entityId\"></tb-gateway-command>\n <div mat-dialog-actions class=\"flex flex-row justify-end items-center\">\n <button mat-button color=\"primary\"\n type=\"button\"\n (click)=\"cancel()\" cdkFocusInitial>\n {{ 'action.close' | translate }}\n </button>\n </div>\n</div>\n",
"customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}", "customCss": ".container {\n display: grid;\n grid-template-rows: min-content minmax(auto, 1fr) min-content;\n height: 100%;\n max-height: 100vh;\n width: 600px;\n max-width: 100%;\n}",
"customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n", "customFunction": "let $injector = widgetContext.$scope.$injector;\nlet customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));\n\nopenCommands();\n\nfunction openCommands() {\n customDialog.customDialog(htmlTemplate, CommandsDialogController, {panelClass: \"test\"}).subscribe();\n}\n\nfunction CommandsDialogController(instance) {\n let vm = instance;\n \n vm.entityId = entityId.id;\n\n vm.cancel = function() {\n vm.dialogRef.close(null);\n };\n}\n",
"customResources": [ "customResources": [

10
application/src/main/data/resources/js_extensions/gateway-management-extension.js

File diff suppressed because one or more lines are too long

10
application/src/main/data/upgrade/basic/schema_update.sql

@ -1,10 +0,0 @@
--
-- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
-- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
--
-- Intentionally empty. The offline upgrade path is now fully bean-driven: every schema/data change lives in
-- an LtsMigration bean and its data/upgrade/lts/<version>/schema_update.sql (4.4 baseline DDL is in
-- V4_4_0_0Migration / lts/4.4.0.0/schema_update.sql). This file is kept present only so loadSql does not fail.

2
application/src/main/data/upgrade/lts/4.3.1.4/schema_update.sql

@ -16,7 +16,7 @@ ALTER TABLE alarm_comment DROP CONSTRAINT IF EXISTS fk_alarm_comment_alarm_id;
-- change (nullable, no default), so the ACCESS EXCLUSIVE lock it takes is released as soon as this -- change (nullable, no default), so the ACCESS EXCLUSIVE lock it takes is released as soon as this
-- migration transaction commits. -- migration transaction commits.
-- --
-- The originator_id backfill for pre-existing rows is intentionally NOT done here. LtsMigrationService runs -- The originator_id backfill for pre-existing rows is intentionally NOT done here. MigrationService runs
-- this whole file inside a single transaction, so an in-line UPDATE would hold the ADD COLUMN's -- this whole file inside a single transaction, so an in-line UPDATE would hold the ADD COLUMN's
-- ACCESS EXCLUSIVE lock for the entire backfill -- blocking all reads and writes on entity_alarm while the -- ACCESS EXCLUSIVE lock for the entire backfill -- blocking all reads and writes on entity_alarm while the
-- no-downtime patch path (SystemPatchApplier) runs it on a serving node. Instead the backfill runs after -- no-downtime patch path (SystemPatchApplier) runs it on a serving node. Instead the backfill runs after

5
application/src/main/data/upgrade/lts/4.3.1.6/schema_update.sql

@ -1,6 +1,7 @@
-- --
-- SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -- SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
-- SPDX-License-Identifier: BUSL-1.1 -- SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
-- SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-- --
-- A copy of the tb_cluster block in dao/src/main/resources/sql/schema-entities.sql, because the no-downtime patch -- A copy of the tb_cluster block in dao/src/main/resources/sql/schema-entities.sql, because the no-downtime patch

5
application/src/main/data/upgrade/lts/4.4.0.0/schema_update.sql

@ -14,9 +14,8 @@ ALTER TABLE rule_chain ADD COLUMN IF NOT EXISTS notes varchar(1000000);
-- RULE CHAIN NOTES MIGRATION END -- RULE CHAIN NOTES MIGRATION END
-- PE-only 4.4 baseline DDL below (carried over from basic/schema_update.sql; these columns/index have no -- PE-only 4.4 baseline DDL below (these columns/index have no owning bean of their own). report.* live on
-- owning bean of their own). report.* live on the PE-only report table; job.customer_id is a PE column on the -- the PE-only report table; job.customer_id is a PE column on the shared job table.
-- shared job table.
-- REPORT PUBLIC LINK ADDITION START -- REPORT PUBLIC LINK ADDITION START

10
application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql

@ -0,0 +1,10 @@
--
-- SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
-- SPDX-License-Identifier: BUSL-1.1
--
-- Tenant-scoped paging over calculated fields (WHERE tenant_id = ? ORDER BY id LIMIT ?), issued for every tenant
-- when the calculated field actors initialize, otherwise scans the whole table and sorts on each call.
CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id);
ALTER TABLE ai_model ADD COLUMN IF NOT EXISTS customer_access_enabled BOOLEAN NOT NULL DEFAULT FALSE;

21
application/src/main/java/org/thingsboard/server/actors/app/AppActor.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.actors.app; package org.thingsboard.server.actors.app;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -11,6 +12,7 @@ import org.thingsboard.server.actors.TbActorException;
import org.thingsboard.server.actors.TbActorId; import org.thingsboard.server.actors.TbActorId;
import org.thingsboard.server.actors.TbActorRef; import org.thingsboard.server.actors.TbActorRef;
import org.thingsboard.server.actors.TbEntityActorId; import org.thingsboard.server.actors.TbEntityActorId;
import org.thingsboard.server.actors.TbEntityTypeActorIdPredicate;
import org.thingsboard.server.actors.device.SessionTimeoutCheckMsg; import org.thingsboard.server.actors.device.SessionTimeoutCheckMsg;
import org.thingsboard.server.actors.service.ContextAwareActor; import org.thingsboard.server.actors.service.ContextAwareActor;
import org.thingsboard.server.actors.service.ContextBasedCreator; import org.thingsboard.server.actors.service.ContextBasedCreator;
@ -18,6 +20,7 @@ import org.thingsboard.server.actors.service.DefaultActorService;
import org.thingsboard.server.actors.tenant.TenantActor; import org.thingsboard.server.actors.tenant.TenantActor;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.TenantProfileId; import org.thingsboard.server.common.data.id.TenantProfileId;
import org.thingsboard.server.common.data.page.PageDataIterable; import org.thingsboard.server.common.data.page.PageDataIterable;
@ -27,6 +30,7 @@ import org.thingsboard.server.common.msg.TbActorMsg;
import org.thingsboard.server.common.msg.ToCalculatedFieldSystemMsg; import org.thingsboard.server.common.msg.ToCalculatedFieldSystemMsg;
import org.thingsboard.server.common.msg.aware.TenantAwareMsg; import org.thingsboard.server.common.msg.aware.TenantAwareMsg;
import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg; import org.thingsboard.server.common.msg.queue.QueueToRuleEngineMsg;
import org.thingsboard.server.common.msg.queue.RuleEngineException; import org.thingsboard.server.common.msg.queue.RuleEngineException;
import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.ServiceType;
@ -75,6 +79,8 @@ public class AppActor extends ContextAwareActor {
case APP_INIT_MSG: case APP_INIT_MSG:
break; break;
case PARTITION_CHANGE_MSG: case PARTITION_CHANGE_MSG:
onPartitionChangeMsg((PartitionChangeMsg) msg);
break;
case CF_PARTITIONS_CHANGE_MSG: case CF_PARTITIONS_CHANGE_MSG:
case CF_STATE_PARTITION_RESTORE_MSG: case CF_STATE_PARTITION_RESTORE_MSG:
ctx.broadcastToChildren(msg, true); ctx.broadcastToChildren(msg, true);
@ -202,6 +208,19 @@ public class AppActor extends ContextAwareActor {
}); });
} }
private void onPartitionChangeMsg(PartitionChangeMsg msg) {
if (msg.isForAllTenants()) {
ctx.broadcastToChildren(msg, true);
} else {
ctx.broadcastToChildren(msg, new TbEntityTypeActorIdPredicate(EntityType.TENANT) {
@Override
protected boolean testEntityId(EntityId entityId) {
return super.testEntityId(entityId) && msg.isAffected((TenantId) entityId);
}
}, true);
}
}
private Optional<TbActorRef> getOrCreateTenantActor(TenantId tenantId) { private Optional<TbActorRef> getOrCreateTenantActor(TenantId tenantId) {
if (deletedTenants.contains(tenantId)) { if (deletedTenants.contains(tenantId)) {
return Optional.empty(); return Optional.empty();

10
application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleChainActorMessageProcessor.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.actors.ruleChain; package org.thingsboard.server.actors.ruleChain;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -152,15 +153,18 @@ public class RuleChainActorMessageProcessor extends ComponentMsgProcessor<RuleCh
private TbActorRef createRuleNodeActor(TbActorCtx ctx, RuleNode ruleNode) { private TbActorRef createRuleNodeActor(TbActorCtx ctx, RuleNode ruleNode) {
return ctx.getOrCreateChildActor(new TbEntityActorId(ruleNode.getId()), return ctx.getOrCreateChildActor(new TbEntityActorId(ruleNode.getId()),
() -> DefaultActorService.RULE_DISPATCHER_NAME, () -> DefaultActorService.RULE_DISPATCHER_NAME,
() -> new RuleNodeActor.ActorCreator(systemContext, tenantId, entityId, ruleChainName, ruleNode.getId()), () -> new RuleNodeActor.ActorCreator(systemContext, tenantId, entityId, ruleChainName, ruleNode.getId(), ruleNode),
() -> true); () -> true);
} }
private void initRoutes(RuleChain ruleChain, List<RuleNode> ruleNodeList) { private void initRoutes(RuleChain ruleChain, List<RuleNode> ruleNodeList) {
nodeRoutes.clear(); nodeRoutes.clear();
// Loading the relations of all nodes of the chain in batches instead of one lookup per node;
Map<RuleNodeId, List<EntityRelation>> relationsByNode = service.getRuleNodesRelations(TenantId.SYS_TENANT_ID,
ruleNodeList.stream().map(RuleNode::getId).toList());
// Populating the routes map; // Populating the routes map;
for (RuleNode ruleNode : ruleNodeList) { for (RuleNode ruleNode : ruleNodeList) {
List<EntityRelation> relations = service.getRuleNodeRelations(TenantId.SYS_TENANT_ID, ruleNode.getId()); List<EntityRelation> relations = relationsByNode.getOrDefault(ruleNode.getId(), Collections.emptyList());
log.trace("[{}][{}][{}] Processing rule node relations [{}]", tenantId, entityId, ruleNode.getId(), relations.size()); log.trace("[{}][{}][{}] Processing rule node relations [{}]", tenantId, entityId, ruleNode.getId(), relations.size());
if (relations.isEmpty()) { if (relations.isEmpty()) {
nodeRoutes.put(ruleNode.getId(), Collections.emptyList()); nodeRoutes.put(ruleNode.getId(), Collections.emptyList());

23
application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleNodeActor.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.actors.ruleChain; package org.thingsboard.server.actors.ruleChain;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -12,6 +13,7 @@ import org.thingsboard.server.actors.service.ContextBasedCreator;
import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.RuleNodeId; import org.thingsboard.server.common.data.id.RuleNodeId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.rule.RuleNode;
import org.thingsboard.server.common.msg.TbActorMsg; import org.thingsboard.server.common.msg.TbActorMsg;
import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg; import org.thingsboard.server.common.msg.plugin.ComponentLifecycleMsg;
@ -23,18 +25,25 @@ public class RuleNodeActor extends RuleEngineComponentActor<RuleNodeId, RuleNode
private final String ruleChainName; private final String ruleChainName;
private final RuleChainId ruleChainId; private final RuleChainId ruleChainId;
private final RuleNodeId ruleNodeId; private final RuleNodeId ruleNodeId;
// Rule node already loaded by the parent rule chain actor; null means the processor reads it from the database
private RuleNode preloadedRuleNode;
private RuleNodeActor(ActorSystemContext systemContext, TenantId tenantId, private RuleNodeActor(ActorSystemContext systemContext, TenantId tenantId,
RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId) { RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId, RuleNode preloadedRuleNode) {
super(systemContext, tenantId, ruleNodeId); super(systemContext, tenantId, ruleNodeId);
this.ruleChainName = ruleChainName; this.ruleChainName = ruleChainName;
this.ruleChainId = ruleChainId; this.ruleChainId = ruleChainId;
this.ruleNodeId = ruleNodeId; this.ruleNodeId = ruleNodeId;
this.preloadedRuleNode = preloadedRuleNode;
} }
@Override @Override
protected RuleNodeActorMessageProcessor createProcessor(TbActorCtx ctx) { protected RuleNodeActorMessageProcessor createProcessor(TbActorCtx ctx) {
return new RuleNodeActorMessageProcessor(tenantId, this.ruleChainName, ruleNodeId, systemContext, ctx); RuleNode ruleNode = preloadedRuleNode;
// Use the preloaded node for the first init only: init retries and re-inits after a failed start
// must read the current rule node, which the user may have fixed in the meantime
preloadedRuleNode = null;
return new RuleNodeActorMessageProcessor(tenantId, this.ruleChainName, ruleNodeId, systemContext, ctx, ruleNode);
} }
@Override @Override
@ -99,13 +108,19 @@ public class RuleNodeActor extends RuleEngineComponentActor<RuleNodeId, RuleNode
private final RuleChainId ruleChainId; private final RuleChainId ruleChainId;
private final String ruleChainName; private final String ruleChainName;
private final RuleNodeId ruleNodeId; private final RuleNodeId ruleNodeId;
private final RuleNode ruleNode;
public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId) { public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId) {
this(context, tenantId, ruleChainId, ruleChainName, ruleNodeId, null);
}
public ActorCreator(ActorSystemContext context, TenantId tenantId, RuleChainId ruleChainId, String ruleChainName, RuleNodeId ruleNodeId, RuleNode ruleNode) {
super(context); super(context);
this.tenantId = tenantId; this.tenantId = tenantId;
this.ruleChainId = ruleChainId; this.ruleChainId = ruleChainId;
this.ruleChainName = ruleChainName; this.ruleChainName = ruleChainName;
this.ruleNodeId = ruleNodeId; this.ruleNodeId = ruleNodeId;
this.ruleNode = ruleNode;
} }
@Override @Override
@ -115,7 +130,7 @@ public class RuleNodeActor extends RuleEngineComponentActor<RuleNodeId, RuleNode
@Override @Override
public TbActor createActor() { public TbActor createActor() {
return new RuleNodeActor(context, tenantId, ruleChainId, ruleChainName, ruleNodeId); return new RuleNodeActor(context, tenantId, ruleChainId, ruleChainName, ruleNodeId, ruleNode);
} }
} }

24
application/src/main/java/org/thingsboard/server/actors/ruleChain/RuleNodeActorMessageProcessor.java

@ -42,11 +42,18 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod
RuleNodeActorMessageProcessor(TenantId tenantId, String ruleChainName, RuleNodeActorMessageProcessor(TenantId tenantId, String ruleChainName,
RuleNodeId ruleNodeId, ActorSystemContext systemContext, TbActorCtx selfActor) { RuleNodeId ruleNodeId, ActorSystemContext systemContext, TbActorCtx selfActor) {
this(tenantId, ruleChainName, ruleNodeId, systemContext, selfActor, null);
}
RuleNodeActorMessageProcessor(TenantId tenantId, String ruleChainName,
RuleNodeId ruleNodeId, ActorSystemContext systemContext, TbActorCtx selfActor, RuleNode preloadedRuleNode) {
super(systemContext, tenantId, ruleNodeId); super(systemContext, tenantId, ruleNodeId);
this.apiUsageClient = systemContext.getApiUsageClient(); this.apiUsageClient = systemContext.getApiUsageClient();
this.ruleChainName = ruleChainName; this.ruleChainName = ruleChainName;
this.componentService = systemContext.getComponentService(); this.componentService = systemContext.getComponentService();
RuleNode ruleNode = systemContext.getRuleChainService().findRuleNodeById(tenantId, entityId); // The parent rule chain actor has just loaded this node; reuse it instead of another round trip to the database.
RuleNode ruleNode = preloadedRuleNode != null && ruleNodeId.equals(preloadedRuleNode.getId()) ?
copyOf(preloadedRuleNode) : systemContext.getRuleChainService().findRuleNodeById(tenantId, entityId);
this.info = new RuleNodeInfo(ruleNodeId, ruleChainName, getName(ruleNode)); this.info = new RuleNodeInfo(ruleNodeId, ruleChainName, getName(ruleNode));
replaceSecretUsages(ruleNode); replaceSecretUsages(ruleNode);
this.defaultCtx = new DefaultTbContext(systemContext, ruleChainName, new RuleNodeCtx(tenantId, selfActor, ruleNode)); this.defaultCtx = new DefaultTbContext(systemContext, ruleChainName, new RuleNodeCtx(tenantId, selfActor, ruleNode));
@ -213,6 +220,21 @@ public class RuleNodeActorMessageProcessor extends ComponentMsgProcessor<RuleNod
} }
} }
// Secret substitution modifies the configuration JSON in place, and the RuleNode copy constructor shares it,
// so the configuration is deep-copied to keep the parent rule chain's instance untouched. The copy constructor also
// skips queueName, configurationVersion and debugMode, which are set explicitly to match a node read from the database.
@SuppressWarnings("deprecation")
static RuleNode copyOf(RuleNode ruleNode) {
RuleNode copy = new RuleNode(ruleNode);
copy.setQueueName(ruleNode.getQueueName());
copy.setConfigurationVersion(ruleNode.getConfigurationVersion());
copy.setDebugMode(ruleNode.isDebugMode());
if (ruleNode.getConfiguration() != null) {
copy.setConfiguration(ruleNode.getConfiguration().deepCopy());
}
return copy;
}
private void replaceSecretUsages(RuleNode ruleNode) { private void replaceSecretUsages(RuleNode ruleNode) {
if (componentService.getRuleNodeInfo(ruleNode.getType()).map(info -> info.getAnnotation().hasSecrets()).orElse(false)) { if (componentService.getRuleNodeInfo(ruleNode.getType()).map(info -> info.getAnnotation().hasSecrets()).orElse(false)) {
systemContext.getSecretConfigurationService().replaceSecretUsages(tenantId, ruleNode.getConfiguration()); systemContext.getSecretConfigurationService().replaceSecretUsages(tenantId, ruleNode.getConfiguration());

13
application/src/main/java/org/thingsboard/server/actors/service/DefaultActorService.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.actors.service; package org.thingsboard.server.actors.service;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
@ -19,12 +20,14 @@ import org.thingsboard.server.actors.TbActorSystemSettings;
import org.thingsboard.server.actors.app.AppActor; import org.thingsboard.server.actors.app.AppActor;
import org.thingsboard.server.actors.app.AppInitMsg; import org.thingsboard.server.actors.app.AppInitMsg;
import org.thingsboard.server.actors.stats.StatsActor; import org.thingsboard.server.actors.stats.StatsActor;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.msg.queue.PartitionChangeMsg; import org.thingsboard.server.common.msg.queue.PartitionChangeMsg;
import org.thingsboard.server.common.msg.queue.ServiceType; import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.queue.discovery.TbApplicationEventListener; import org.thingsboard.server.queue.discovery.TbApplicationEventListener;
import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent; import org.thingsboard.server.queue.discovery.event.PartitionChangeEvent;
import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.AfterStartUp;
import java.util.Set;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -119,8 +122,12 @@ public class DefaultActorService extends TbApplicationEventListener<PartitionCha
@Override @Override
protected void onTbApplicationEvent(PartitionChangeEvent event) { protected void onTbApplicationEvent(PartitionChangeEvent event) {
log.info("Received partition change event."); ServiceType serviceType = event.getServiceType();
appActor.tellWithHighPriority(new PartitionChangeMsg(event.getServiceType())); Set<TenantId> affectedTenants = event.getAffectedTenants();
log.info("Received partition change event for {}, affected tenants: {}", serviceType, affectedTenants == null ? "all" : affectedTenants.size());
appActor.tellWithHighPriority(affectedTenants == null ?
PartitionChangeMsg.forAllTenants(serviceType) :
PartitionChangeMsg.forTenants(serviceType, affectedTenants));
} }
@Override @Override

23
application/src/main/java/org/thingsboard/server/actors/tenant/TenantActor.java

@ -199,8 +199,8 @@ public class TenantActor extends RuleChainManagerActor {
private void forwardToCfActor(TenantAwareMsg msg, boolean priority) { private void forwardToCfActor(TenantAwareMsg msg, boolean priority) {
if (cfActor == null) { if (cfActor == null) {
if (msg instanceof CalculatedFieldStateRestoreMsg) { if (msg instanceof CalculatedFieldStateRestoreMsg restoreMsg) {
log.warn("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg); log.warn("[{}] CF Actor is not initialized. Skipping CF state restore: [{}]", tenantId, restoreMsg.getId());
} else { } else {
log.debug("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg); log.debug("[{}] CF Actor is not initialized. ToCalculatedFieldSystemMsg: [{}]", tenantId, msg);
} }
@ -285,7 +285,7 @@ public class TenantActor extends RuleChainManagerActor {
log.info("[{}] Failed to init CF Actor.", tenantId, e); log.info("[{}] Failed to init CF Actor.", tenantId, e);
} }
} }
if (!ruleChainsInitialized) { if (!ruleChainsInitialized && getApiUsageState().isReExecEnabled()) {
log.info("Tenant {} is now managed by this service, initializing rule chains", tenantId); log.info("Tenant {} is now managed by this service, initializing rule chains", tenantId);
initRuleChains(); initRuleChains();
} }
@ -319,12 +319,17 @@ public class TenantActor extends RuleChainManagerActor {
if (entityType.equals(EntityType.API_USAGE_STATE)) { if (entityType.equals(EntityType.API_USAGE_STATE)) {
ApiUsageState old = getApiUsageState(); ApiUsageState old = getApiUsageState();
apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId)); apiUsageState = new ApiUsageState(systemContext.getApiUsageStateService().getApiUsageState(tenantId));
if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) { // Rule chains are initialized only on the rule engine service that manages the tenant, with the same checks
log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId); // (isRuleEngine, isManagedByCurrentService, isReExecEnabled) as in init() and onPartitionChangeMsg()
destroyRuleChains(); if (isRuleEngine) {
} else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()) { if (old.isReExecEnabled() && !apiUsageState.isReExecEnabled()) {
log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId); log.info("[{}] Received API state update. Going to DISABLE Rule Engine execution.", tenantId);
initRuleChains(); destroyRuleChains();
} else if (!old.isReExecEnabled() && apiUsageState.isReExecEnabled()
&& systemContext.getPartitionService().isManagedByCurrentService(tenantId)) {
log.info("[{}] Received API state update. Going to ENABLE Rule Engine execution.", tenantId);
initRuleChains();
}
} }
} }
if (msg.getEntityId().getEntityType() == EntityType.DEVICE && ComponentLifecycleEvent.DELETED == msg.getEvent() && isMyPartition(msg.getEntityId())) { if (msg.getEntityId().getEntityType() == EntityType.DEVICE && ComponentLifecycleEvent.DELETED == msg.getEvent() && isMyPartition(msg.getEntityId())) {

98
application/src/main/java/org/thingsboard/server/config/SwaggerConfiguration.java

@ -37,6 +37,7 @@ import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.OpenApiCustomizer; import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springdoc.core.customizers.OperationCustomizer; import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.customizers.ParameterCustomizer;
import org.springdoc.core.discoverer.SpringDocParameterNameDiscoverer; import org.springdoc.core.discoverer.SpringDocParameterNameDiscoverer;
import org.springdoc.core.models.GroupedOpenApi; import org.springdoc.core.models.GroupedOpenApi;
import org.springdoc.core.properties.SpringDocConfigProperties; import org.springdoc.core.properties.SpringDocConfigProperties;
@ -49,11 +50,14 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.util.ClassUtils;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig; import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.query.AliasEntityType;
import org.thingsboard.server.exception.ThingsboardCredentialsExpiredResponse; import org.thingsboard.server.exception.ThingsboardCredentialsExpiredResponse;
import org.thingsboard.server.exception.ThingsboardErrorResponse; import org.thingsboard.server.exception.ThingsboardErrorResponse;
import org.thingsboard.server.service.security.auth.rest.LoginRequest; import org.thingsboard.server.service.security.auth.rest.LoginRequest;
@ -108,6 +112,7 @@ public class SwaggerConfiguration {
// Keyed by the schema name that swagger-core generates (see resolveSchemaName). // Keyed by the schema name that swagger-core generates (see resolveSchemaName).
private final Map<String, List<String>> schemaPropertyOrders = new ConcurrentHashMap<>(); private final Map<String, List<String>> schemaPropertyOrders = new ConcurrentHashMap<>();
private final Map<String, Set<String>> schemaOwnProps = new ConcurrentHashMap<>(); private final Map<String, Set<String>> schemaOwnProps = new ConcurrentHashMap<>();
private final Map<String, Set<String>> schemaNotRequiredProps = new ConcurrentHashMap<>();
// Tracks schema name → fully-qualified class names to detect collisions. // Tracks schema name → fully-qualified class names to detect collisions.
private final Map<String, Set<String>> schemaNameToClasses = new ConcurrentHashMap<>(); private final Map<String, Set<String>> schemaNameToClasses = new ConcurrentHashMap<>();
@ -269,7 +274,8 @@ public class SwaggerConfiguration {
var requestBody = new RequestBody().description("Refresh token request") var requestBody = new RequestBody().description("Refresh token request")
.content(new Content().addMediaType(APPLICATION_JSON_VALUE, .content(new Content().addMediaType(APPLICATION_JSON_VALUE,
new MediaType().schema(new Schema<JsonNode>().addProperty("refreshToken", new Schema<>().type("string"))))); new MediaType().schema(new Schema<JsonNode>().types(Set.of("object"))
.addProperty("refreshToken", new Schema<>().types(Set.of("string"))))));
operation.requestBody(requestBody); operation.requestBody(requestBody);
@ -291,6 +297,38 @@ public class SwaggerConfiguration {
.build(); .build();
} }
// springdoc infers the parameter type from the Java type only when @Parameter(schema = @Schema(...))
// sets neither type nor implementation; otherwise (e.g. schema = @Schema(minimum = "1")) it falls back
// to "string". Restore integer/int32 or integer/int64 for int and long parameters, keeping the rest of the schema.
@Bean
public ParameterCustomizer integerParameterCustomizer() {
return (parameter, methodParameter) -> {
if (parameter == null || parameter.getSchema() == null) {
return parameter;
}
Schema<?> schema = parameter.getSchema();
boolean isString = "string".equals(schema.getType()) || Set.of("string").equals(schema.getTypes());
String format = integerFormat(methodParameter);
if (isString && format != null && schema.getFormat() == null) {
schema.setType("integer");
schema.setTypes(Set.of("integer"));
schema.setFormat(format);
}
return parameter;
};
}
private static String integerFormat(MethodParameter methodParameter) {
Class<?> type = ClassUtils.resolvePrimitiveIfNecessary(methodParameter.getParameterType());
if (Integer.class.equals(type)) {
return "int32";
}
if (Long.class.equals(type)) {
return "int64";
}
return null;
}
@Bean @Bean
@Lazy(false) @Lazy(false)
ModelConverter mapAwareConverter() { ModelConverter mapAwareConverter() {
@ -349,6 +387,10 @@ public class SwaggerConfiguration {
if (!ownProps.isEmpty()) { if (!ownProps.isEmpty()) {
schemaOwnProps.put(schemaName, ownProps); schemaOwnProps.put(schemaName, ownProps);
} }
Set<String> notRequiredProps = computeNotRequiredPropNames(beanDesc);
if (!notRequiredProps.isEmpty()) {
schemaNotRequiredProps.put(schemaName, notRequiredProps);
}
} catch (Exception e) { } catch (Exception e) {
log.debug("Failed to resolve property order for {}: {}", cls.getName(), e.getMessage()); log.debug("Failed to resolve property order for {}: {}", cls.getName(), e.getMessage());
} }
@ -361,9 +403,11 @@ public class SwaggerConfiguration {
}; };
} }
// The document is OpenAPI 3.1 (see springDocProperties above), which serializes
// Schema.types; a schema built with Schema.type(...) is written without a type.
private void addDefaultSchemas(OpenAPI openAPI) { private void addDefaultSchemas(OpenAPI openAPI) {
Schema<?> errorCodeSchema = new Schema<>() Schema<?> errorCodeSchema = new Schema<>()
.type("integer") .types(Set.of("integer"))
.description("Platform error code") .description("Platform error code")
._enum(Arrays.stream(ThingsboardErrorCode.values()) ._enum(Arrays.stream(ThingsboardErrorCode.values())
.map(ThingsboardErrorCode::getErrorCode) .map(ThingsboardErrorCode::getErrorCode)
@ -374,11 +418,17 @@ public class SwaggerConfiguration {
registerSchema(components, "ThingsboardErrorResponse", ThingsboardErrorResponse.class); registerSchema(components, "ThingsboardErrorResponse", ThingsboardErrorResponse.class);
registerSchema(components, "ThingsboardCredentialsExpiredResponse", ThingsboardCredentialsExpiredResponse.class); registerSchema(components, "ThingsboardCredentialsExpiredResponse", ThingsboardCredentialsExpiredResponse.class);
components.addSchemas("ThingsboardErrorCode", errorCodeSchema); components.addSchemas("ThingsboardErrorCode", errorCodeSchema);
// AliasEntityId.entityType is a plain string, so no schema references AliasEntityType;
// register it to keep the alias names in the spec and in generated clients.
components.addSchemas("AliasEntityType", new Schema<String>()
.types(Set.of("string"))
.description("Alias for an entity of the current user, used as AliasEntityId.entityType")
._enum(Arrays.stream(AliasEntityType.values()).map(Enum::name).toList()));
registerSchema(components, "AiChatModelConfig", AiChatModelConfig.class); registerSchema(components, "AiChatModelConfig", AiChatModelConfig.class);
} }
private static void registerSchema(Components components, String name, Class<?> cls) { private static void registerSchema(Components components, String name, Class<?> cls) {
ResolvedSchema resolved = ModelConverters.getInstance() ResolvedSchema resolved = ModelConverters.getInstance(true)
.readAllAsResolvedSchema(new AnnotatedType().type(cls)); .readAllAsResolvedSchema(new AnnotatedType().type(cls));
components.addSchemas(name, resolved.schema); components.addSchemas(name, resolved.schema);
if (resolved.referencedSchemas != null) { if (resolved.referencedSchemas != null) {
@ -528,6 +578,8 @@ public class SwaggerConfiguration {
deduplicateAllOfProperties(schema, schemas, ownProps); deduplicateAllOfProperties(schema, schemas, ownProps);
}); });
removeNotRequiredProperties(schemas);
// Reorder properties for all component schemas. This runs after all // Reorder properties for all component schemas. This runs after all
// schemas are finalized so it covers schemas the ModelConverter only // schemas are finalized so it covers schemas the ModelConverter only
// saw as a $ref (e.g. interface-based discriminator types like EntityId). // saw as a $ref (e.g. interface-based discriminator types like EntityId).
@ -1112,6 +1164,46 @@ public class SwaggerConfiguration {
return own; return own;
} }
// Honour an explicit @Schema(requiredMode = NOT_REQUIRED): swagger-core skips @NotNull
// for such properties, but still adds the ones with @NotBlank / @NotEmpty to 'required'.
void removeNotRequiredProperties(Map<String, Schema> schemas) {
schemas.forEach((schemaName, schema) -> {
Set<String> notRequiredProps = schemaNotRequiredProps.getOrDefault(schemaName, Set.of());
removeRequiredProperties(schema, notRequiredProps);
});
}
private static Set<String> computeNotRequiredPropNames(com.fasterxml.jackson.databind.BeanDescription beanDesc) {
Set<String> notRequired = new LinkedHashSet<>();
for (var prop : beanDesc.findProperties()) {
var member = prop.getPrimaryMember();
if (member == null) continue;
var schemaAnnotation = member.getAnnotation(io.swagger.v3.oas.annotations.media.Schema.class);
if (schemaAnnotation != null && schemaAnnotation.requiredMode() == io.swagger.v3.oas.annotations.media.Schema.RequiredMode.NOT_REQUIRED) {
notRequired.add(prop.getName());
}
}
return notRequired;
}
private static void removeRequiredProperties(Schema<?> schema, Set<String> notRequiredProps) {
if (notRequiredProps.isEmpty()) {
return;
}
List<Schema> schemas = new ArrayList<>();
schemas.add(schema);
if (schema.getAllOf() != null) {
schemas.addAll(schema.getAllOf());
}
for (Schema<?> s : schemas) {
if (s.getRequired() != null && s.getRequired().stream().anyMatch(notRequiredProps::contains)) {
List<String> required = new ArrayList<>(s.getRequired());
required.removeAll(notRequiredProps);
s.setRequired(required.isEmpty() ? null : required);
}
}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static void reorderSchemaProperties(Schema<?> schema, List<String> propOrder) { private static void reorderSchemaProperties(Schema<?> schema, List<String> propOrder) {
if (schema.getProperties() != null && schema.getProperties().size() > 1) { if (schema.getProperties() != null && schema.getProperties().size() > 1) {

2
application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java

@ -134,7 +134,7 @@ public class ThingsboardSecurityConfiguration {
/** Session bootstrap, exempt for GET only: {@code POST} on the same path creates a custom menu. */ /** Session bootstrap, exempt for GET only: {@code POST} on the same path creates a custom menu. */
public static final String CUSTOM_MENU_ENTRY_POINT = "/api/customMenu"; public static final String CUSTOM_MENU_ENTRY_POINT = "/api/customMenu";
public static final String ALLOWED_PERMISSIONS_ENTRY_POINT = "/api/permissions/allowedPermissions"; public static final String ALLOWED_PERMISSIONS_ENTRY_POINT = "/api/permissions/allowedPermissions";
protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/index.html", "/assets/**", "/static/**", "/api/noauth/**", "/webjars/**", "/api/license/**", "/api/images/public/**", "/api/v2/report/public/**", "/.well-known/**"}; protected static final String[] NON_TOKEN_BASED_AUTH_ENTRY_POINTS = new String[]{"/index.html", "/assets/**", "/static/**", "/api/noauth/**", "/webjars/**", "/api/license/**", "/api/v2/license/**", "/api/images/public/**", "/api/v2/report/public/**", "/.well-known/**"};
/** /**
* API entry points that stay reachable while the setup is incomplete, or while a provisioned instance is * API entry points that stay reachable while the setup is incomplete, or while a provisioned instance is
* locked again at runtime. Only {@link #SETUP_PROTECTED_ENTRY_POINTS} is locked, so the Angular * locked again at runtime. Only {@link #SETUP_PROTECTED_ENTRY_POINTS} is locked, so the Angular

23
application/src/main/java/org/thingsboard/server/controller/AiChatController.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
@ -28,6 +29,7 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiSettings; import org.thingsboard.server.service.ai.TbAiSettings;
import org.thingsboard.server.service.ai.chat.AiChatService; import org.thingsboard.server.service.ai.chat.AiChatService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import java.util.UUID; import java.util.UUID;
@ -43,6 +45,7 @@ class AiChatController extends BaseController {
private final AiChatService aiChatService; private final AiChatService aiChatService;
private final TbAiSettings aiSettings; private final TbAiSettings aiSettings;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping @PostMapping
@ -97,11 +100,27 @@ class AiChatController extends BaseController {
@PathVariable UUID chatId, @PathVariable UUID chatId,
@RequestBody JsonNode request, @RequestBody JsonNode request,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken, @RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage @RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage,
HttpServletRequest httpRequest
) throws ThingsboardException { ) throws ThingsboardException {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return withTraceLogging(chatId, aiChatService.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, user)); String clientOrigin = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest);
return withTraceLogging(chatId, aiChatService.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, clientOrigin, user));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(value = "/{chatId}/resume", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> resumeChat(
@PathVariable UUID chatId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE, required = false) String acceptLanguage,
HttpServletRequest httpRequest
) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
String clientOrigin = systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest);
return withTraceLogging(chatId, aiChatService.resumeChat(chatId, tbAccessToken, acceptLanguage, clientOrigin, user));
} }
private Flux<ServerSentEvent<String>> withTraceLogging(UUID chatId, Flux<ServerSentEvent<String>> events) { private Flux<ServerSentEvent<String>> withTraceLogging(UUID chatId, Flux<ServerSentEvent<String>> events) {

8
application/src/main/java/org/thingsboard/server/controller/AiDeviceDashboardController.java

@ -3,6 +3,7 @@
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
@ -19,6 +20,7 @@ import org.thingsboard.server.dao.service.validator.DashboardDataValidator;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.dashboard.AiDeviceDashboardService; import org.thingsboard.server.service.ai.dashboard.AiDeviceDashboardService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.UUID; import java.util.UUID;
@ -32,20 +34,22 @@ class AiDeviceDashboardController extends BaseController {
private final AiDeviceDashboardService aiDeviceDashboardService; private final AiDeviceDashboardService aiDeviceDashboardService;
private final DashboardDataValidator dashboardDataValidator; private final DashboardDataValidator dashboardDataValidator;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{deviceId}/dashboard") @PostMapping("/{deviceId}/dashboard")
JsonNode generateDashboard( JsonNode generateDashboard(
@PathVariable UUID deviceId, @PathVariable UUID deviceId,
@RequestBody JsonNode request, @RequestBody JsonNode request,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken @RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest
) throws ThingsboardException { ) throws ThingsboardException {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
checkDeviceId(new DeviceId(deviceId), Operation.READ, Operation.READ_ATTRIBUTES, Operation.READ_TELEMETRY); checkDeviceId(new DeviceId(deviceId), Operation.READ, Operation.READ_ATTRIBUTES, Operation.READ_TELEMETRY);
accessControlService.checkPermission(user, Resource.DASHBOARD, Operation.CREATE); accessControlService.checkPermission(user, Resource.DASHBOARD, Operation.CREATE);
dashboardDataValidator.validateMaxDashboardsPerTenant(user.getTenantId()); dashboardDataValidator.validateMaxDashboardsPerTenant(user.getTenantId());
return aiDeviceDashboardService.generateDashboard(deviceId, request, tbAccessToken, user); return aiDeviceDashboardService.generateDashboard(deviceId, request, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
} }
} }

76
application/src/main/java/org/thingsboard/server/controller/AiModelController.java

@ -21,9 +21,12 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResult;
import org.thingsboard.server.common.data.ai.AiModel; import org.thingsboard.server.common.data.ai.AiModel;
import org.thingsboard.server.common.data.ai.AiModelInfo;
import org.thingsboard.server.common.data.ai.dto.TbChatPrompt;
import org.thingsboard.server.common.data.ai.dto.TbChatRequest; import org.thingsboard.server.common.data.ai.dto.TbChatRequest;
import org.thingsboard.server.common.data.ai.dto.TbChatResponse; import org.thingsboard.server.common.data.ai.dto.TbChatResponse;
import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig; import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.AiModelId; import org.thingsboard.server.common.data.id.AiModelId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
@ -32,6 +35,7 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.AiChatModelService; import org.thingsboard.server.service.ai.AiChatModelService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.time.Duration; import java.time.Duration;
import java.util.Optional; import java.util.Optional;
@ -45,6 +49,7 @@ import static org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DE
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH; import static org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH;
@Validated @Validated
@RestController @RestController
@ -115,6 +120,31 @@ class AiModelController extends BaseController {
return aiModelService.findAiModelsByTenantId(user.getTenantId(), pageLink); return aiModelService.findAiModelsByTenantId(user.getTenantId(), pageLink);
} }
@ApiOperation(
value = "Get AI model infos (getAiModelInfos)",
notes = "Returns a page of AI model infos: AI models with the provider credentials removed, so 'configuration.providerConfig' is always null. " +
PAGE_DATA_PARAMETERS + TENANT_AUTHORITY_PARAGRAPH
)
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/infos")
public PageData<AiModelInfo> getAiModelInfos(
@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true)
@RequestParam int pageSize,
@Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true)
@RequestParam int page,
@Parameter(description = AI_MODEL_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch,
@Parameter(description = SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"createdTime", "name", "provider", "modelId"}))
@RequestParam(required = false) String sortProperty,
@Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"}))
@RequestParam(required = false) String sortOrder
) throws ThingsboardException {
var user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.READ);
var pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return aiModelService.findAiModelsByTenantId(user.getTenantId(), pageLink).mapData(AiModelInfo::from);
}
@ApiOperation( @ApiOperation(
value = "Delete AI model by ID (deleteAiModelById)", value = "Delete AI model by ID (deleteAiModelById)",
notes = "Deletes the AI model record by its `id`. " + notes = "Deletes the AI model record by its `id`. " +
@ -152,15 +182,53 @@ class AiModelController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/chat") @PostMapping("/chat")
public DeferredResult<TbChatResponse> sendChatRequest(@Valid @RequestBody TbChatRequest tbChatRequest) throws ThingsboardException { public DeferredResult<TbChatResponse> sendChatRequest(@Valid @RequestBody TbChatRequest tbChatRequest) throws ThingsboardException {
ChatRequest langChainChatRequest = tbChatRequest.toLangChainChatRequest(); return executeChatRequest(tbChatRequest.chatModelConfig(), tbChatRequest.toLangChainChatRequest());
AiChatModelConfig<?> chatModelConfig = tbChatRequest.chatModelConfig(); }
ListenableFuture<TbChatResponse> future = aiChatModelService.sendChatRequestAsync(getTenantId(), chatModelConfig, langChainChatRequest) @ApiOperation(
value = "Send request to a saved AI chat model (sendChatRequestToAiModel)",
notes = "Submits a single prompt - made up of an optional system message and a required user message - to the AI chat model " +
"with the specified `id`, using its saved configuration, and returns either the generated answer or an error envelope. " +
"The user must have the 'INVOKE' permission for AI models, and customer users additionally require the model to have customer access enabled. " +
"Roles that grant all operations, such as the default 'Customer Administrator' role, include 'INVOKE', " +
"so enabling customer access makes the model callable by every customer user with such a role." +
TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH
)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping("/{modelUuid}/chat")
public DeferredResult<TbChatResponse> sendChatRequestToAiModel(
@Parameter(
description = "ID of the AI model record",
required = true,
example = "de7900d4-30e2-11f0-9cd2-0242ac120002"
)
@PathVariable UUID modelUuid,
@Valid @RequestBody TbChatPrompt tbChatPrompt
) throws ThingsboardException {
AiModel model = checkAiModelId(new AiModelId(modelUuid), Operation.INVOKE);
if (!(model.getConfiguration() instanceof AiChatModelConfig<?> chatModelConfig)) {
throw new ThingsboardException("AI model with id [" + modelUuid + "] is not a chat model", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return executeChatRequest(chatModelConfig, tbChatPrompt.toLangChainChatRequest());
}
private DeferredResult<TbChatResponse> executeChatRequest(AiChatModelConfig<?> chatModelConfig, ChatRequest chatRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser();
ListenableFuture<TbChatResponse> future = aiChatModelService.sendChatRequestAsync(user.getTenantId(), chatModelConfig, chatRequest)
.transform(chatResponse -> (TbChatResponse) new TbChatResponse.Success(chatResponse.aiMessage().text()), directExecutor()) .transform(chatResponse -> (TbChatResponse) new TbChatResponse.Success(chatResponse.aiMessage().text()), directExecutor())
.catching(Throwable.class, ex -> new TbChatResponse.Failure(ex.getMessage()), directExecutor()); .catching(Throwable.class, ex -> toFailure(user, ex), directExecutor());
Integer requestTimeoutSeconds = chatModelConfig.timeoutSeconds(); Integer requestTimeoutSeconds = chatModelConfig.timeoutSeconds();
return requestTimeoutSeconds != null ? wrapFuture(future, Duration.ofSeconds(requestTimeoutSeconds).toMillis()) : wrapFuture(future); return requestTimeoutSeconds != null ? wrapFuture(future, Duration.ofSeconds(requestTimeoutSeconds).toMillis()) : wrapFuture(future);
} }
private TbChatResponse.Failure toFailure(SecurityUser user, Throwable ex) {
if (!user.isCustomerUser()) {
return new TbChatResponse.Failure(ex.getMessage());
}
// Provider errors may reveal configuration details that customer users must not see
log.debug("[{}] Chat request of customer user [{}] failed", user.getTenantId(), user.getId(), ex);
return new TbChatResponse.Failure("Failed to get a response from the AI model");
}
} }

88
application/src/main/java/org/thingsboard/server/controller/AiResourceController.java

@ -0,0 +1,88 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.http.CacheControl;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.resource.AiResourceService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.UUID;
@RequiredArgsConstructor
@RestController
@TbCoreComponent
@RequestMapping("/api/ai/resources")
class AiResourceController extends BaseController {
private final AiResourceService aiResourceService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/config")
public JsonNode getAiResourcesConfig() throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
return aiResourceService.getConfig(user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public JsonNode uploadAiResource(@RequestPart("file") MultipartFile file) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiResourceService.upload(file, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/{resourceId}")
public ResponseEntity<byte[]> downloadAiResource(@PathVariable UUID resourceId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
AiResourceService.AiResourceContent content = aiResourceService.download(resourceId, user);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(content.mediaType()))
.header(HttpHeaders.CONTENT_DISPOSITION, disposition(content.name()))
.header("X-Content-Type-Options", "nosniff")
.cacheControl(CacheControl.maxAge(Duration.ofHours(1)).cachePrivate())
.body(content.data());
}
private static String disposition(String name) {
ContentDisposition.Builder builder = ContentDisposition.attachment();
boolean ascii = StandardCharsets.US_ASCII.newEncoder().canEncode(name);
return (ascii ? builder.filename(name) : builder.filename(name, StandardCharsets.UTF_8)).build().toString();
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@DeleteMapping("/{resourceId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteAiResource(@PathVariable UUID resourceId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
aiResourceService.delete(resourceId, user);
}
}

28
application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java

@ -3,7 +3,9 @@
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -21,7 +23,9 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.solution.AiSolutionService; import org.thingsboard.server.service.ai.solution.AiSolutionService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER; import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER;
@ -33,6 +37,7 @@ import static org.thingsboard.server.config.ThingsboardSecurityConfiguration.AUT
public class AiSolutionController extends BaseController { public class AiSolutionController extends BaseController {
private final AiSolutionService aiSolutionService; private final AiSolutionService aiSolutionService;
private final SystemSecurityService systemSecurityService;
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/start") @PostMapping("/start")
@ -58,16 +63,27 @@ public class AiSolutionController extends BaseController {
return aiSolutionService.getSolutions(user); return aiSolutionService.getSolutions(user);
} }
@Deprecated(forRemoval = true)
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/{step}/chat") @PostMapping("/{solutionId}/{step}/chat")
public JsonNode chat(@PathVariable UUID solutionId, public JsonNode chat(@PathVariable UUID solutionId,
@PathVariable SolutionStep step, @PathVariable SolutionStep step,
@RequestBody String message) throws ThingsboardException { @RequestBody String message) throws ThingsboardException {
return sendMessage(solutionId, step, new SolutionChatMessage(message, null));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(value = "/{solutionId}/{step}/messages", consumes = MediaType.APPLICATION_JSON_VALUE)
public JsonNode sendMessage(@PathVariable UUID solutionId,
@PathVariable SolutionStep step,
@RequestBody SolutionChatMessage request) throws ThingsboardException {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.chat(solutionId, step, message, user); return aiSolutionService.chat(solutionId, step, request.message(), request.resources(), user);
} }
record SolutionChatMessage(String message, List<UUID> resources) {}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/create") @PostMapping("/{solutionId}/create")
public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException { public JsonNode createSolution(@PathVariable UUID solutionId) throws ThingsboardException {
@ -97,19 +113,21 @@ public class AiSolutionController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/install") @PostMapping("/{solutionId}/install")
public JsonNode installSolution(@PathVariable UUID solutionId, public JsonNode installSolution(@PathVariable UUID solutionId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken) throws ThingsboardException { @RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.installSolution(solutionId, tbAccessToken, user); return aiSolutionService.installSolution(solutionId, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@DeleteMapping("/{solutionId}/uninstall") @DeleteMapping("/{solutionId}/uninstall")
public JsonNode uninstallSolution(@PathVariable UUID solutionId, public JsonNode uninstallSolution(@PathVariable UUID solutionId,
@RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken) throws ThingsboardException { @RequestHeader(AUTHORIZATION_HEADER) String tbAccessToken,
HttpServletRequest httpRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.uninstallSolution(solutionId, tbAccessToken, user); return aiSolutionService.uninstallSolution(solutionId, tbAccessToken, systemSecurityService.getBaseUrl(user.getTenantId(), user.getCustomerId(), httpRequest), user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")

12
application/src/main/java/org/thingsboard/server/controller/AlarmController.java

@ -191,10 +191,10 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/alarm/{alarmId}/assign/{assigneeId}") @PostMapping(value = "/alarm/{alarmId}/assign/{assigneeId}")
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public Alarm assignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION) public AlarmInfo assignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId, @PathVariable(ALARM_ID) String strAlarmId,
@Parameter(description = ASSIGN_ID_PARAM_DESCRIPTION) @Parameter(description = ASSIGN_ID_PARAM_DESCRIPTION)
@PathVariable(ASSIGNEE_ID) String strAssigneeId @PathVariable(ASSIGNEE_ID) String strAssigneeId
) throws Exception { ) throws Exception {
checkParameter(ALARM_ID, strAlarmId); checkParameter(ALARM_ID, strAlarmId);
checkParameter(ASSIGNEE_ID, strAssigneeId); checkParameter(ASSIGNEE_ID, strAssigneeId);
@ -212,8 +212,8 @@ public class AlarmController extends BaseController {
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@DeleteMapping(value = "/alarm/{alarmId}/assign") @DeleteMapping(value = "/alarm/{alarmId}/assign")
@ResponseStatus(value = HttpStatus.OK) @ResponseStatus(value = HttpStatus.OK)
public Alarm unassignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION) public AlarmInfo unassignAlarm(@Parameter(description = ALARM_ID_PARAM_DESCRIPTION)
@PathVariable(ALARM_ID) String strAlarmId @PathVariable(ALARM_ID) String strAlarmId
) throws Exception { ) throws Exception {
checkParameter(ALARM_ID, strAlarmId); checkParameter(ALARM_ID, strAlarmId);
AlarmId alarmId = new AlarmId(toUUID(strAlarmId)); AlarmId alarmId = new AlarmId(toUUID(strAlarmId));

448
application/src/main/java/org/thingsboard/server/controller/ControllerConstants.java

@ -1833,454 +1833,6 @@ public class ControllerConstants {
"the connectivity fields and other important parameters dependent on the specific integration type. Let's review the configuration object for the MQTT Integration type below. " + "the connectivity fields and other important parameters dependent on the specific integration type. Let's review the configuration object for the MQTT Integration type below. " +
NEW_LINE + INTEGRATION_CONFIGURATION_EXAMPLE + NEW_LINE; NEW_LINE + INTEGRATION_CONFIGURATION_EXAMPLE + NEW_LINE;
// Default converter uplinks messages
static final String DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"end_device_ids\": {\n" +
" \"device_id\": \"eui-1000000000000001\",\n" +
" \"application_ids\": {\n" +
" \"application_id\": \"application-tti-name\"\n" +
" },\n" +
" \"dev_eui\": \"1000000000000001\",\n" +
" \"join_eui\": \"2000000000000001\",\n" +
" \"dev_addr\": \"20000001\"\n" +
" },\n" +
" \"correlation_ids\": [\"as:up:01H0PZDGB1NW6NAPD815NGHPF6\", \"gs:conn:01H0FJRSXSYT7VKNYXJ89F95XT\", \"gs:up:host:01H0FJRSY3MZMGPPFBQ4FZV4T8\", \"gs:uplink:01H0PZDG4HHGFRTXRTXD4PFTH7\", \"ns:uplink:01H0PZDG4JZ3BM0K6J89EQK1J7\", \"rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0PZDG4J02F85RYFPCNSNXCR\", \"rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0PZDGB081PMP806BJHNHX1A\"],\n" +
" \"received_at\": \"2023-05-18T08:25:26.112483370Z\",\n" +
" \"uplink_message\": {\n" +
" \"session_key_id\": \"AYfg8rhha5n+FWx0ZaAprA==\",\n" +
" \"f_port\": 85,\n" +
" \"f_cnt\": 5017,\n" +
" \"frm_payload\": \"Ae0DM18OTGM=\",\n" +
" \"rx_metadata\": [{\n" +
" \"gateway_ids\": {\n" +
" \"gateway_id\": \"eui-6A7E111A10000000\",\n" +
" \"eui\": \"6A7E111A10000000\"\n" +
" },\n" +
" \"time\": \"2023-05-18T08:25:25.885310Z\",\n" +
" \"timestamp\": 818273765,\n" +
" \"rssi\": -24,\n" +
" \"channel_rssi\": -24,\n" +
" \"snr\": 12,\n" +
" \"frequency_offset\": \"671\",\n" +
" \"uplink_token\": \"CiIKIAoUZXVpLTZBN0UxMTFBMTAwMDAwMDASCCThJP/+9k6eEOW7l4YDGgwI9cGXowYQ5KPhrwMgiI2rp+jpOA=\",\n" +
" \"channel_index\": 2,\n" +
" \"received_at\": \"2023-05-18T08:25:25.869324983Z\"\n" +
" }, {\n" +
" \"gateway_ids\": {\n" +
" \"gateway_id\": \"packetbroker\"\n" +
" },\n" +
" \"packet_broker\": {\n" +
" \"message_id\": \"01H0PZDG4MF9AYSMNY44MAVTDH\",\n" +
" \"forwarder_net_id\": \"000013\",\n" +
" \"forwarder_tenant_id\": \"ttn\",\n" +
" \"forwarder_cluster_id\": \"eu1.cloud.thethings.network\",\n" +
" \"forwarder_gateway_eui\": \"6A7E111A10000000\",\n" +
" \"forwarder_gateway_id\": \"eui-6a7e111a10000000\",\n" +
" \"home_network_net_id\": \"000013\",\n" +
" \"home_network_tenant_id\": \"tenant\",\n" +
" \"home_network_cluster_id\": \"eu1.cloud.thethings.industries\"\n" +
" },\n" +
" \"time\": \"2023-05-18T08:25:25.885310Z\",\n" +
" \"rssi\": -24,\n" +
" \"channel_rssi\": -24,\n" +
" \"snr\": 12,\n" +
" \"frequency_offset\": \"671\",\n" +
" \"uplink_token\": \"eyJnIjoiWlhsS2FHSkhZMmxQYVVwQ1RWUkpORkl3VGs1VE1XTnBURU5LYkdKdFRXbFBhVXBDVFZSSk5GSXdUazVKYVhkcFlWaFphVTlwU201a01uaGhWVlJvZDFSWFVuRmlSM1JtVFcxT2RVbHBkMmxrUjBadVNXcHZhV05ZY0RKT1IyeExaREpSZVZwR1pIUmpNRXBLVlVoR2RFNVZkR3BWVTBvNUxua3paVVJTWVRaM1lXOU1kbTQwVm5sdmIyWmlPWGN1ZUhCZmVrcElaa3hIWlZadGRVUlFVeTVuYlRaVlZXRXdkakpHV0VKMGJUUjZaMjVXUkVoeGVHRjRaMlJKTlVkS1VsbERhemc1VDNCbk5rVk1iM1JDUkVZM1VWbHdZbEJDTkdOblNqWjBlbkphYUV4MFRVMHhZMVZFTTFac01XdExURUo0YURaMFExTnhhMVJsWWw4eE5FdHlVVXcyZUhsRWFFbEhlakJITXpoTE0xaFdlRzR5VUVjMk4wNUViME5WTkhoTmRrazFZVk5oWkUwd2FXVnFjR294VGtoMFduZHlZMDFxVlVGNmRsbERUazlNY2s5eFdVeFpWMk5XTG1WVFFYVkpNVkptT1U5NWRqUTNhSEoxTUZoalYxRT0iLCJhIjp7ImZuaWQiOiIwMDAwMTMiLCJmdGlkIjoidHRuIiwiZmNpZCI6ImV1MS5jbG91ZC50aGV0aGluZ3MubmV0d29yayJ9fQ==\",\n" +
" \"received_at\": \"2023-05-18T08:25:25.906038642Z\"\n" +
" }],\n" +
" \"settings\": {\n" +
" \"data_rate\": {\n" +
" \"lora\": {\n" +
" \"bandwidth\": 125000,\n" +
" \"spreading_factor\": 7,\n" +
" \"coding_rate\": \"4/5\"\n" +
" }\n" +
" },\n" +
" \"frequency\": \"868500000\",\n" +
" \"timestamp\": 818273765,\n" +
" \"time\": \"2023-05-18T08:25:25.885310Z\"\n" +
" },\n" +
" \"received_at\": \"2023-05-18T08:25:25.906399073Z\",\n" +
" \"consumed_airtime\": \"0.097536s\",\n" +
" \"network_ids\": {\n" +
" \"net_id\": \"000013\",\n" +
" \"tenant_id\": \"tenant\",\n" +
" \"cluster_id\": \"eu1\",\n" +
" \"cluster_address\": \"eu1.cloud.thethings.industries\",\n" +
" \"tenant_address\": \"tenant.eu1.cloud.thethings.industries\"\n" +
" }\n" +
" }\n" +
"}";
static final String DEFAULT_TTN_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"end_device_ids\": {\n" +
" \"device_id\": \"eui-1000000000000001\",\n" +
" \"application_ids\": {\n" +
" \"application_id\": \"application-tts-name\"\n" +
" },\n" +
" \"dev_eui\": \"1000000000000001\",\n" +
" \"join_eui\": \"2000000000000001\",\n" +
" \"dev_addr\": \"20000001\"\n" +
" },\n" +
" \"correlation_ids\": [\"as:up:01H0S7ZJQ9MQPMVY49FT3SE07M\", \"gs:conn:01H03BQZ9342X3Y86DJ2P704E5\", \"gs:up:host:01H03BQZ99EGAM52KK1300GFKN\", \"gs:uplink:01H0S7ZJGS6D9TJSKJN8XNTMAV\", \"ns:uplink:01H0S7ZJGS9KKD4HTTPKFEMWCV\", \"rpc:/ttn.lorawan.v3.GsNs/HandleUplink:01H0S7ZJGSF3M38ZRZVTM38DEC\", \"rpc:/ttn.lorawan.v3.NsAs/HandleUplink:01H0S7ZJQ8R2EH5AA269AKM8DX\"],\n" +
" \"received_at\": \"2023-05-19T05:33:35.848446463Z\",\n" +
" \"uplink_message\": {\n" +
" \"session_key_id\": \"AYfqmb0pc/1uRZv9xUydgQ==\",\n" +
" \"f_port\": 85,\n" +
" \"f_cnt\": 10335,\n" +
" \"frm_payload\": \"Ae0DM18OTGM=\",\n" +
" \"rx_metadata\": [{\n" +
" \"gateway_ids\": {\n" +
" \"gateway_id\": \"eui-6a7e111a10000000\",\n" +
" \"eui\": \"6A7E111A10000000\"\n" +
" },\n" +
" \"time\": \"2023-05-19T05:33:35.608982Z\",\n" +
" \"timestamp\": 3893546133,\n" +
" \"rssi\": -35,\n" +
" \"channel_rssi\": -35,\n" +
" \"snr\": 13.2,\n" +
" \"frequency_offset\": \"69\",\n" +
" \"uplink_token\": \"CiIKIAoUZXVpLTZhN2UxMTFhMTAwMDAwMDASCCThJP/+9k6eEJWZy8AOGgwIr5ScowYQvNbUsQIgiMy8y6jwpwE=\",\n" +
" \"channel_index\": 3,\n" +
" \"received_at\": \"2023-05-19T05:33:35.607383681Z\"\n" +
" }],\n" +
" \"settings\": {\n" +
" \"data_rate\": {\n" +
" \"lora\": {\n" +
" \"bandwidth\": 125000,\n" +
" \"spreading_factor\": 7,\n" +
" \"coding_rate\": \"4/5\"\n" +
" }\n" +
" },\n" +
" \"frequency\": \"867100000\",\n" +
" \"timestamp\": 3893546133,\n" +
" \"time\": \"2023-05-19T05:33:35.608982Z\"\n" +
" },\n" +
" \"received_at\": \"2023-05-19T05:33:35.641841782Z\",\n" +
" \"consumed_airtime\": \"0.056576s\",\n" +
" \"network_ids\": {\n" +
" \"net_id\": \"000013\",\n" +
" \"tenant_id\": \"ttn\",\n" +
" \"cluster_id\": \"eu1\",\n" +
" \"cluster_address\": \"eu1.cloud.thethings.network\"\n" +
" }\n" +
" }\n" +
"}\n";
static final String DEFAULT_LORIOT_UPLINK_CONVERTER_MESSAGE =
"{\n" +
" \"cmd\": \"rx\",\n" +
" \"seqno\": 3040,\n" +
" \"EUI\": \"1000000000000001\",\n" +
" \"ts\": 1684478801936,\n" +
" \"fcnt\": 2,\n" +
" \"port\": 85,\n" +
" \"freq\": 867500000,\n" +
" \"rssi\": -21,\n" +
" \"snr\": 10,\n" +
" \"toa\": 206,\n" +
" \"dr\": \"SF9 BW125 4/5\",\n" +
" \"ack\": false,\n" +
" \"bat\": 94,\n" +
" \"offline\": false,\n" +
" \"data\": \"01ed03335f0e4c63\"\n" +
"}\n";
static final String DEFAULT_CHIRPSTACK_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"deduplicationId\": \"57433366-50a6-4dc2-8145-2df1bbc70d9e\",\n" +
" \"time\": \"2023-05-22T07:47:05.404859+00:00\",\n" +
" \"deviceInfo\": {\n" +
" \"tenantId\": \"52f14cd4-c6f1-4fbd-8f87-4025e1d49242\",\n" +
" \"tenantName\": \"ChirpStack\",\n" +
" \"applicationId\": \"ca739e26-7b67-4f14-b69e-d568c22a5a75\",\n" +
" \"applicationName\": \"Chirpstack application\",\n" +
" \"deviceProfileId\": \"605d08d4-65f5-4d2c-8a5a-3d2457662f79\",\n" +
" \"deviceProfileName\": \"Chirpstack default device profile\",\n" +
" \"deviceName\": \"Device name\",\n" +
" \"devEui\": \"1000000000000001\",\n" +
" \"tags\": {}\n" +
" },\n" +
" \"devAddr\": \"20000001\",\n" +
" \"adr\": true,\n" +
" \"dr\": 5,\n" +
" \"fCnt\": 4,\n" +
" \"fPort\": 85,\n" +
" \"confirmed\": false,\n" +
" \"data\": \"Ae0DM18OTGM=\",\n" +
" \"rxInfo\": [{\n" +
" \"gatewayId\": \"6a7e111a10000000\",\n" +
" \"uplinkId\": 24022,\n" +
" \"time\": \"2023-05-22T07:47:05.404859+00:00\",\n" +
" \"rssi\": -35,\n" +
" \"snr\": 11.5,\n" +
" \"channel\": 2,\n" +
" \"rfChain\": 1,\n" +
" \"location\": {},\n" +
" \"context\": \"EFwMtA==\",\n" +
" \"metadata\": {\n" +
" \"region_common_name\": \"EU868\",\n" +
" \"region_config_id\": \"eu868\"\n" +
" },\n" +
" \"crcStatus\": \"CRC_OK\"\n" +
" }],\n" +
" \"txInfo\": {\n" +
" \"frequency\": 868500000,\n" +
" \"modulation\": {\n" +
" \"lora\": {\n" +
" \"bandwidth\": 125000,\n" +
" \"spreadingFactor\": 7,\n" +
" \"codeRate\": \"CR_4_5\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
static final String DEFAULT_SIGFOX_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"device\": \"2203961\",\n" +
" \"time\": \"1686298419\",\n" +
" \"data\": \"2502af2102462a\",\n" +
" \"seqNumber\": \"570\",\n" +
" \"deviceTypeId\": \"630ceaea10d051194ec0246e\",\n" +
" \"ack\": \"false\",\n" +
" \"customData#int1\": \"37\",\n" +
" \"customData#int2\": \"2\"\n" +
"}";
static final String DEFAULT_SIGFOX_UPLINK_CONVERTER_METADATA = "{\n" +
" \"Header:accept-encoding\": \"gzip,deflate\",\n" +
" \"Header:content-type\": \"application/json\",\n" +
" \"Header:content-length\": \"243\",\n" +
" \"Header:user-agent\": \"SIGFOX\",\n" +
" \"Header:accept-charset\": \"UTF-8;q=0.9,*;q=0.7\",\n" +
" \"Header:accept-language\": \"en\"" +
"}\n";
static final String DEFAULT_AZURE_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"deviceId\": \"8F4A2C6D\",\n" +
" \"deviceType\": \"Packing machine\",\n" +
" \"temperature\": 25.5,\n" +
" \"pressure\": 1013.25,\n" +
" \"vibration\": {\n" +
" \"x\": 0.02,\n" +
" \"y\": 0.03,\n" +
" \"z\": 0.015\n" +
" },\n" +
" \"location\": {\n" +
" \"latitude\": 37.7749,\n" +
" \"longitude\": -122.4194,\n" +
" \"altitude\": 10\n" +
" },\n" +
" \"timestamp\": \"2023-06-09T10:30:00Z\",\n" +
" \"status\": \"ALARM\",\n" +
" \"alarms\": [\n" +
" {\n" +
" \"type\": \"temperature\",\n" +
" \"severity\": \"high\",\n" +
" \"message\": \"Temperature exceeds threshold.\"\n" +
" },\n" +
" {\n" +
" \"type\": \"vibration\",\n" +
" \"severity\": \"critical\",\n" +
" \"message\": \"Excessive vibration detected.\"\n" +
" }\n" +
" ],\n" +
" \"metadata\": {\n" +
" \"version\": 1,\n" +
" \"batteryLevel\": 100,\n" +
" \"batteryStatus\": \"Charging\",\n" +
" \"manufacturer\": \"Example corporation\"\n" +
" }\n" +
"}";
static final String DEFAULT_AWS_IOT_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"device_id\": \"3G7H1j-9zF\",\n" +
" \"timestamp\": \"2023-06-10T12:00:00Z\",\n" +
" \"sensor_data\": {\n" +
" \"temperature\": 25.3,\n" +
" \"humidity\": 62.8,\n" +
" \"pressure\": 1012.5\n" +
" },\n" +
" \"location\": {\n" +
" \"latitude\": 37.7749,\n" +
" \"longitude\": -122.4194\n" +
" },\n" +
" \"status\": \"active\",\n" +
" \"power_status\": \"on\",\n" +
" \"vibration\": {\n" +
" \"x\": 0.02,\n" +
" \"y\": 0.03,\n" +
" \"z\": 0.01\n" +
" },\n" +
" \"fault_codes\": [100, 204, 301],\n" +
" \"battery_level\": 78.5\n" +
"}\n";
static final String DEFAULT_KNP_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"deviceName\":\"Device A\",\n" +
" \"deviceType\":\"thermostat\",\n" +
" \"customerName\":\"customer\",\n" +
" \"groupName\":\"thermostat devices\",\n" +
" \"attributes\": {\n" +
" \"model\":\"Model A\",\n" +
" \"serialNumber\":\"SN111\"\n" +
" },\n" +
" \"telemetry\": {\n" +
" \"temperature\":42,\n" +
" \"humidity\":80\n" +
" }\n" +
"}\n";
static final String DEFAULT_THINGSPARK_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"DevEUI_uplink\": {\n" +
" \"Time\": \"2024-11-28T21:08:22.138+00:00\",\n" +
" \"DevEUI\": \"1000000000000001\",\n" +
" \"FPort\": 1,\n" +
" \"FCntUp\": 26,\n" +
" \"LostUplinksAS\": 0,\n" +
" \"ADRbit\": 1,\n" +
" \"MType\": 2,\n" +
" \"FCntDn\": 2,\n" +
" \"payload_hex\": \"01ed03335f0e4c63\",\n" +
" \"mic_hex\": \"e7214986\",\n" +
" \"Lrcid\": \"00000211\",\n" +
" \"LrrRSSI\": -114,\n" +
" \"LrrSNR\": 4.75,\n" +
" \"LrrESP\": -115.2547,\n" +
" \"SpFact\": 9,\n" +
" \"SubBand\": \"G0\",\n" +
" \"Channel\": \"LC1\",\n" +
" \"Lrrid\": \"100019D4\",\n" +
" \"Late\": 0,\n" +
" \"LrrLAT\": 32.516357,\n" +
" \"LrrLON\": -106.824348,\n" +
" \"Lrrs\": {\n" +
" \"Lrr\": [{\n" +
" \"Lrrid\": \"100019D4\",\n" +
" \"Chain\": 0,\n" +
" \"LrrRSSI\": -114,\n" +
" \"LrrSNR\": 4.75,\n" +
" \"LrrESP\": -115.2547\n" +
" }]\n" +
" },\n" +
" \"DevLrrCnt\": 1,\n" +
" \"CustomerID\": \"100045194\",\n" +
" \"CustomerData\": {\n" +
" \"loc\": {\n" +
" \"lat\": \"32.592782\",\n" +
" \"lon\": \"-106.927742\"\n" +
" },\n" +
" \"alr\": {\n" +
" \"pro\": \"DL/TBRG\",\n" +
" \"ver\": \"1\"\n" +
" },\n" +
" \"tags\": [\"EnvironSens\", \"RainGauge\", \"CDRRC\"],\n" +
" \"doms\": [],\n" +
" \"name\": \"RainGauge 5483_Test\"\n" +
" },\n" +
" \"BaseStationData\": {\n" +
" \"doms\": [],\n" +
" \"name\": \"iStation US #6_CDRRC_Summerford\"\n" +
" },\n" +
" \"ModelCfg\": \"0\",\n" +
" \"DriverCfg\": {\n" +
" \"mod\": {\n" +
" \"pId\": \"dl\",\n" +
" \"mId\": \"dl-tbrg\",\n" +
" \"ver\": \"1\"\n" +
" },\n" +
" \"app\": {\n" +
" \"pId\": \"dl\",\n" +
" \"mId\": \"dl-tbrg\",\n" +
" \"ver\": \"1\"\n" +
" }\n" +
" },\n" +
" \"InstantPER\": 0,\n" +
" \"MeanPER\": 0.037037,\n" +
" \"DevAddr\": \"00FDA112\",\n" +
" \"TxPower\": 18,\n" +
" \"NbTrans\": 2,\n" +
" \"Frequency\": 902.5,\n" +
" \"DynamicClass\": \"A\"\n" +
" }\n" +
"}";
static final String DEFAULT_TPE_UPLINK_CONVERTER_MESSAGE = "{\n" +
" \"DevEUI_uplink\": {\n" +
" \"Time\": \"2024-11-28T21:08:22.138+00:00\",\n" +
" \"DevEUI\": \"1000000000000001\",\n" +
" \"FPort\": 1,\n" +
" \"FCntUp\": 26,\n" +
" \"LostUplinksAS\": 0,\n" +
" \"ADRbit\": 1,\n" +
" \"MType\": 2,\n" +
" \"FCntDn\": 2,\n" +
" \"payload_hex\": \"01ed03335f0e4c63\",\n" +
" \"mic_hex\": \"e7214986\",\n" +
" \"Lrcid\": \"00000211\",\n" +
" \"LrrRSSI\": -114,\n" +
" \"LrrSNR\": 4.75,\n" +
" \"LrrESP\": -115.2547,\n" +
" \"SpFact\": 9,\n" +
" \"SubBand\": \"G0\",\n" +
" \"Channel\": \"LC1\",\n" +
" \"Lrrid\": \"100019D4\",\n" +
" \"Late\": 0,\n" +
" \"LrrLAT\": 32.516357,\n" +
" \"LrrLON\": -106.824348,\n" +
" \"Lrrs\": {\n" +
" \"Lrr\": [{\n" +
" \"Lrrid\": \"100019D4\",\n" +
" \"Chain\": 0,\n" +
" \"LrrRSSI\": -114,\n" +
" \"LrrSNR\": 4.75,\n" +
" \"LrrESP\": -115.2547\n" +
" }]\n" +
" },\n" +
" \"DevLrrCnt\": 1,\n" +
" \"CustomerID\": \"100045194\",\n" +
" \"CustomerData\": {\n" +
" \"loc\": {\n" +
" \"lat\": \"32.592782\",\n" +
" \"lon\": \"-106.927742\"\n" +
" },\n" +
" \"alr\": {\n" +
" \"pro\": \"DL/TBRG\",\n" +
" \"ver\": \"1\"\n" +
" },\n" +
" \"tags\": [\"EnvironSens\", \"RainGauge\", \"CDRRC\"],\n" +
" \"doms\": [],\n" +
" \"name\": \"RainGauge 5483_Test\"\n" +
" },\n" +
" \"BaseStationData\": {\n" +
" \"doms\": [],\n" +
" \"name\": \"iStation US #6_CDRRC_Summerford\"\n" +
" },\n" +
" \"ModelCfg\": \"0\",\n" +
" \"DriverCfg\": {\n" +
" \"mod\": {\n" +
" \"pId\": \"dl\",\n" +
" \"mId\": \"dl-tbrg\",\n" +
" \"ver\": \"1\"\n" +
" },\n" +
" \"app\": {\n" +
" \"pId\": \"dl\",\n" +
" \"mId\": \"dl-tbrg\",\n" +
" \"ver\": \"1\"\n" +
" }\n" +
" },\n" +
" \"InstantPER\": 0,\n" +
" \"MeanPER\": 0.037037,\n" +
" \"DevAddr\": \"00FDA112\",\n" +
" \"TxPower\": 18,\n" +
" \"NbTrans\": 2,\n" +
" \"Frequency\": 902.5,\n" +
" \"DynamicClass\": \"A\"\n" +
" }\n" +
"}";
// Default converter uplinks messages
static final String REPORT_PARAMS_EXAMPLE = "{\n" + static final String REPORT_PARAMS_EXAMPLE = "{\n" +
" \"type\": \"pdf\",\n" + " \"type\": \"pdf\",\n" +
" \"timezone\": \"Europe/Kiev\",\n" + " \"timezone\": \"Europe/Kiev\",\n" +

73
application/src/main/java/org/thingsboard/server/controller/ConverterController.java

@ -5,7 +5,6 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonParseException; import com.google.gson.JsonParseException;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
@ -63,6 +62,7 @@ import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.event.EventService; import org.thingsboard.server.dao.event.EventService;
import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.converter.ConverterDefaultsService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService; import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
@ -82,17 +82,6 @@ import static org.thingsboard.server.controller.ControllerConstants.CONVERTER_ID
import static org.thingsboard.server.controller.ControllerConstants.CONVERTER_TEXT_SEARCH_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.CONVERTER_TEXT_SEARCH_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.CONVERTER_TYPE_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.CONVERTER_TYPE_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.DEDICATED_CONVERTER_DEFINITION; import static org.thingsboard.server.controller.ControllerConstants.DEDICATED_CONVERTER_DEFINITION;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_AWS_IOT_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_AZURE_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_CHIRPSTACK_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_KNP_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_LORIOT_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_SIGFOX_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_SIGFOX_UPLINK_CONVERTER_METADATA;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_THINGSPARK_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_TPE_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.DEFAULT_TTN_UPLINK_CONVERTER_MESSAGE;
import static org.thingsboard.server.controller.ControllerConstants.INCLUDE_GATEWAY_INFO; import static org.thingsboard.server.controller.ControllerConstants.INCLUDE_GATEWAY_INFO;
import static org.thingsboard.server.controller.ControllerConstants.INTEGRATION_NAME; import static org.thingsboard.server.controller.ControllerConstants.INTEGRATION_NAME;
import static org.thingsboard.server.controller.ControllerConstants.INTEGRATION_NAME_PARAM_DESCRIPTION; import static org.thingsboard.server.controller.ControllerConstants.INTEGRATION_NAME_PARAM_DESCRIPTION;
@ -122,25 +111,7 @@ public class ConverterController extends AutoCommitController {
private final JsInvokeService jsInvokeService; private final JsInvokeService jsInvokeService;
private final Optional<TbelInvokeService> tbelInvokeService; private final Optional<TbelInvokeService> tbelInvokeService;
private final TbConverterService tbConverterService; private final TbConverterService tbConverterService;
private final ConverterDefaultsService converterDefaultsService;
private static final Map<IntegrationType, String> converterDefaultMessages = ImmutableMap.<IntegrationType, String>builder()
.put(IntegrationType.LORIOT, DEFAULT_LORIOT_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.SIGFOX, DEFAULT_SIGFOX_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.TTI, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.TTN, DEFAULT_TTN_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.CHIRPSTACK, DEFAULT_CHIRPSTACK_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.AZURE_IOT_HUB, DEFAULT_AZURE_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.AZURE_EVENT_HUB, DEFAULT_AZURE_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.AZURE_SERVICE_BUS, DEFAULT_AZURE_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.AWS_IOT, DEFAULT_AWS_IOT_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.KPN, DEFAULT_KNP_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.THINGPARK, DEFAULT_THINGSPARK_UPLINK_CONVERTER_MESSAGE)
.put(IntegrationType.TPE, DEFAULT_TPE_UPLINK_CONVERTER_MESSAGE)
.build();
private final static Map<IntegrationType, String> converterDefaultMetadatas = Map.of(
IntegrationType.SIGFOX, DEFAULT_SIGFOX_UPLINK_CONVERTER_METADATA
);
public static final String CONVERTER_ID = "converterId"; public static final String CONVERTER_ID = "converterId";
@ -258,8 +229,9 @@ public class ConverterController extends AutoCommitController {
} }
private JsonNode createDefaultDebugIn(Converter converter, String converterType, String integrationType, String integrationName, Integer converterVersion) throws ThingsboardException { private JsonNode createDefaultDebugIn(Converter converter, String converterType, String integrationType, String integrationName, Integer converterVersion) throws ThingsboardException {
if ((converter == null && !ConverterType.UPLINK.name().equals(converterType)) || boolean isUplink = converter != null ? ConverterType.UPLINK.equals(converter.getType()) : ConverterType.UPLINK.name().equals(converterType);
(converter != null && !ConverterType.UPLINK.equals(converter.getType()))) { boolean isDownlink = converter != null ? ConverterType.DOWNLINK.equals(converter.getType()) : ConverterType.DOWNLINK.name().equals(converterType);
if (!isUplink && !isDownlink) {
return null; return null;
} }
@ -273,6 +245,16 @@ public class ConverterController extends AutoCommitController {
integrationName = targetIntegrationInfo.getSecond(); integrationName = targetIntegrationInfo.getSecond();
} }
if (isDownlink) {
Optional<String> downlinkMetadata = converterDefaultsService.getMetadata(targetIntegrationType, ConverterType.DOWNLINK);
Optional<String> downlinkPayload = converterDefaultsService.getPayload(targetIntegrationType, ConverterType.DOWNLINK);
Optional<String> downlinkMsgType = converterDefaultsService.getDownlinkMsgType(targetIntegrationType);
if (downlinkMetadata.isEmpty() && downlinkPayload.isEmpty() && downlinkMsgType.isEmpty()) {
return null;
}
return createDownlinkDebugIn(integrationName, downlinkMetadata, downlinkPayload, downlinkMsgType);
}
if (converterVersion == null) { if (converterVersion == null) {
converterVersion = converter != null ? converter.getConverterVersion() : null; converterVersion = converter != null ? converter.getConverterVersion() : null;
} }
@ -288,10 +270,9 @@ public class ConverterController extends AutoCommitController {
String inContent; String inContent;
ContentType contentType; ContentType contentType;
inContent = converterDefaultMessages.get(targetIntegrationType); inContent = converterDefaultsService.getPayload(targetIntegrationType, ConverterType.UPLINK).orElse(null);
if (converterDefaultMetadatas.containsKey(targetIntegrationType)) { converterDefaultsService.getMetadata(targetIntegrationType, ConverterType.UPLINK)
metadata.setAll(JacksonUtil.fromString(converterDefaultMetadatas.get(targetIntegrationType), ObjectNode.class)); .ifPresent(defaultMetadata -> metadata.setAll(JacksonUtil.fromString(defaultMetadata, ObjectNode.class)));
}
contentType = ContentType.JSON; contentType = ContentType.JSON;
debugIn.put("inMetadata", JacksonUtil.toString(metadata)); debugIn.put("inMetadata", JacksonUtil.toString(metadata));
@ -301,6 +282,21 @@ public class ConverterController extends AutoCommitController {
return debugIn.isEmpty() ? null : debugIn; return debugIn.isEmpty() ? null : debugIn;
} }
private JsonNode createDownlinkDebugIn(String integrationName, Optional<String> metadata, Optional<String> payload, Optional<String> msgType) {
ObjectNode debugIn = JacksonUtil.newObjectNode();
metadata.ifPresent(value -> debugIn.put("inMetadata", JacksonUtil.toString(JacksonUtil.fromString(value, ObjectNode.class))));
payload.ifPresent(value -> {
debugIn.put("inContent", value);
debugIn.put("inContentType", ContentType.JSON.name());
});
msgType.ifPresent(value -> debugIn.put("inMsgType", value));
ObjectNode integrationMetadata = JacksonUtil.newObjectNode();
integrationMetadata.put(INTEGRATION_NAME, integrationName);
debugIn.put("inIntegrationMetadata", JacksonUtil.toString(integrationMetadata));
return debugIn;
}
private Pair<IntegrationType, String> getTargetIntegrationTypeAndName(Converter converter, String integrationType) throws ThingsboardException { private Pair<IntegrationType, String> getTargetIntegrationTypeAndName(Converter converter, String integrationType) throws ThingsboardException {
IntegrationType targetIntegrationType = null; IntegrationType targetIntegrationType = null;
String targetIntegrationName = ""; String targetIntegrationName = "";
@ -319,7 +315,8 @@ public class ConverterController extends AutoCommitController {
} }
if (targetIntegrationType != null && StringUtils.isBlank(targetIntegrationName)) { if (targetIntegrationType != null && StringUtils.isBlank(targetIntegrationName)) {
targetIntegrationName = "Test " + targetIntegrationType.getDirectory(); targetIntegrationName = converterDefaultsService.getIntegrationName(targetIntegrationType)
.orElse("Test " + targetIntegrationType.getDirectory());
} }
return (targetIntegrationType == null) ? null : Pair.of(targetIntegrationType, targetIntegrationName); return (targetIntegrationType == null) ? null : Pair.of(targetIntegrationType, targetIntegrationName);

4
application/src/main/java/org/thingsboard/server/controller/DeviceController.java

@ -10,7 +10,9 @@ import com.google.common.util.concurrent.MoreExecutors;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import jakarta.annotation.Nullable; import jakarta.annotation.Nullable;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -583,6 +585,8 @@ public class DeviceController extends BaseController {
"In order to enable claiming devices feature a system parameter security.claim.allowClaimingByDefault should be set to true, " + "In order to enable claiming devices feature a system parameter security.claim.allowClaimingByDefault should be set to true, " +
"otherwise a server-side claimingAllowed attribute with the value true is obligatory for provisioned devices. \n" + "otherwise a server-side claimingAllowed attribute with the value true is obligatory for provisioned devices. \n" +
"See official documentation for more details regarding claiming." + CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_CLAIM_CHECK) "See official documentation for more details regarding claiming." + CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_CLAIM_CHECK)
@ApiResponse(responseCode = "200", description = "OK",
content = @Content(schema = @Schema(implementation = ClaimResult.class)))
@PreAuthorize("hasAuthority('CUSTOMER_USER')") @PreAuthorize("hasAuthority('CUSTOMER_USER')")
@RequestMapping(value = "/customer/device/{deviceName}/claim", method = RequestMethod.POST) @RequestMapping(value = "/customer/device/{deviceName}/claim", method = RequestMethod.POST)
@ResponseBody @ResponseBody

35
application/src/main/java/org/thingsboard/server/controller/EdgeController.java

@ -189,6 +189,10 @@ public class EdgeController extends BaseController {
Operation operation = created ? Operation.CREATE : Operation.WRITE; Operation operation = created ? Operation.CREATE : Operation.WRITE;
if (!created) {
checkEdgeId(edge.getId(), Operation.WRITE);
}
if (!entityGroupIds.isEmpty()) { if (!entityGroupIds.isEmpty()) {
for (EntityGroupId entityGroupId : entityGroupIds) { for (EntityGroupId entityGroupId : entityGroupIds) {
accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation, accessControlService.checkPermission(getCurrentUser(), Resource.EDGE, operation,
@ -546,7 +550,7 @@ public class EdgeController extends BaseController {
@PathVariable(ENTITY_GROUP_ID) String strEntityGroupId, @PathVariable(ENTITY_GROUP_ID) String strEntityGroupId,
@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true, schema = @Schema(minimum = "1")) @Parameter(description = PAGE_SIZE_DESCRIPTION, required = true, schema = @Schema(minimum = "1"))
@RequestParam int pageSize, @RequestParam int pageSize,
@Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true, schema = @Schema(minimum = "1")) @Parameter(description = PAGE_NUMBER_DESCRIPTION, required = true, schema = @Schema(minimum = "0"))
@RequestParam int page, @RequestParam int page,
@Parameter(description = EDGE_TEXT_SEARCH_DESCRIPTION) @Parameter(description = EDGE_TEXT_SEARCH_DESCRIPTION)
@RequestParam(required = false) String textSearch, @RequestParam(required = false) String textSearch,
@ -671,6 +675,35 @@ public class EdgeController extends BaseController {
} }
} }
@ApiOperation(value = "Check edge license (checkInstance)",
notes = "Checks license request (V1/V2) from edge service by forwarding request to license portal.")
@PostMapping(value = "/v2/license/checkInstance")
public ResponseEntity<JsonNode> checkInstanceV2(@RequestBody JsonNode request) throws ThingsboardException {
log.debug("Checking instance [{}]", request);
try {
return edgeLicenseService.checkInstanceV2(request);
} catch (Exception e) {
log.error("Error occurred: [{}]", e.getMessage(), e);
throw new ThingsboardException(e, ThingsboardErrorCode.SUBSCRIPTION_VIOLATION);
}
}
@ApiOperation(value = "Activate edge instance (activateInstance)",
notes = "Activates edge license (V1/V2) on license portal.")
@PostMapping(value = "/v2/license/activateInstance", params = {"licenseSecret", "releaseDate", "clusterId"})
public ResponseEntity<JsonNode> activateInstanceV2(@RequestParam String licenseSecret,
@RequestParam String releaseDate,
@RequestParam String clusterId,
@RequestParam(required = false) String protocolVersion) throws ThingsboardException {
log.debug("Activating instance [{}], [{}], [{}], [{}]", licenseSecret, releaseDate, clusterId, protocolVersion);
try {
return edgeLicenseService.activateInstanceV2(licenseSecret, releaseDate, clusterId, protocolVersion);
} catch (Exception e) {
log.error("Error occurred: [{}]", e.getMessage(), e);
throw new ThingsboardException(e, ThingsboardErrorCode.SUBSCRIPTION_VIOLATION);
}
}
private void cleanUpLicenseKey(Edge edge) { private void cleanUpLicenseKey(Edge edge) {
edge.setEdgeLicenseKey(null); edge.setEdgeLicenseKey(null);
} }

48
application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java

@ -57,6 +57,7 @@ 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.common.data.permission.ShareGroupRequest; import org.thingsboard.server.common.data.permission.ShareGroupRequest;
import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.Role;
import org.thingsboard.server.common.data.role.RoleType;
import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.owner.OwnerService; import org.thingsboard.server.dao.owner.OwnerService;
@ -1146,7 +1147,8 @@ public class EntityGroupController extends AutoCommitController {
@ApiOperation(value = "Share the Entity Group (shareEntityGroup)", @ApiOperation(value = "Share the Entity Group (shareEntityGroup)",
notes = "Share the entity group with certain user group based on the provided Share Group Request. " + notes = "Share the entity group with certain user group based on the provided Share Group Request. " +
"The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature." "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. " +
"Each role in 'roleIds' must be a group role readable by the current user, and each of its operations must be granted to the current user for the entity group or its entities."
+ TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK) + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/entityGroup/{entityGroupId}/share") @PostMapping(value = "/entityGroup/{entityGroupId}/share")
@ -1174,14 +1176,18 @@ public class EntityGroupController extends AutoCommitController {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
} }
} else { } else {
userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()); userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()));
checkNotNull(userGroup, "Entity group with id [" + shareGroupRequest.getUserGroupId() + "] is not found");
} }
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup);
List<RoleId> roleIds; List<Role> roles;
if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) {
roleIds = shareGroupRequest.getRoleIds(); roles = new ArrayList<>();
for (RoleId roleId : shareGroupRequest.getRoleIds()) {
Role role = checkRoleId(roleId, Operation.READ);
checkGroupRoleAllowedForShare(role, entityGroup);
roles.add(role);
}
} else { } else {
Role role; Role role;
if (shareGroupRequest.isReadElseWrite()) { if (shareGroupRequest.isReadElseWrite()) {
@ -1189,15 +1195,15 @@ public class EntityGroupController extends AutoCommitController {
} else { } else {
role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId()); role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId());
} }
roleIds = Collections.singletonList(role.getId()); roles = Collections.singletonList(role);
} }
for (RoleId roleId : roleIds) { for (Role role : roles) {
GroupPermission groupPermission = new GroupPermission(); GroupPermission groupPermission = new GroupPermission();
groupPermission.setTenantId(getTenantId()); groupPermission.setTenantId(getTenantId());
groupPermission.setEntityGroupId(entityGroup.getId()); groupPermission.setEntityGroupId(entityGroup.getId());
groupPermission.setEntityGroupType(entityGroup.getType()); groupPermission.setEntityGroupType(entityGroup.getType());
groupPermission.setRoleId(roleId); groupPermission.setRoleId(role.getId());
groupPermission.setUserGroupId(userGroup.getId()); groupPermission.setUserGroupId(userGroup.getId());
GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission)); GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission));
@ -1391,7 +1397,7 @@ public class EntityGroupController extends AutoCommitController {
Edge edge = checkEdgeId(edgeId, Operation.WRITE); Edge edge = checkEdgeId(edgeId, Operation.WRITE);
EntityGroupId entityGroupId = new EntityGroupId(toUUID(strEntityGroupId)); EntityGroupId entityGroupId = new EntityGroupId(toUUID(strEntityGroupId));
checkEntityGroupId(entityGroupId, Operation.READ); checkEntityGroupId(entityGroupId, Operation.WRITE);
EntityType groupType = checkStrEntityGroupType("groupType", strGroupType); EntityType groupType = checkStrEntityGroupType("groupType", strGroupType);
EntityGroup savedEntityGroup = checkNotNull(entityGroupService.assignEntityGroupToEdge(getCurrentUser().getTenantId(), entityGroupId, edgeId, groupType)); EntityGroup savedEntityGroup = checkNotNull(entityGroupService.assignEntityGroupToEdge(getCurrentUser().getTenantId(), entityGroupId, edgeId, groupType));
@ -1506,9 +1512,29 @@ public class EntityGroupController extends AutoCommitController {
} }
} }
private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set<Operation> mergedOperations) throws ThingsboardException { private void checkGroupRoleAllowedForShare(Role role, EntityGroup entityGroup) throws ThingsboardException {
if (role.getType() == RoleType.GENERIC) {
throw new ThingsboardException("Can't assign Generic Role to entity group!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
MergedUserPermissions userPermissions = getCurrentUser().getUserPermissions();
Resource groupResource = Resource.groupResourceFromGroupType(entityGroup.getType());
Resource entityResource = Resource.resourceFromEntityType(entityGroup.getType());
for (Operation operation : toRoleOperations(role)) {
if (!userPermissions.hasGenericPermission(groupResource, operation)
&& !userPermissions.hasGenericPermission(entityResource, operation)
&& !userPermissions.hasGroupPermissions(entityGroup.getId(), operation)) {
throw permissionDenied();
}
}
}
private List<Operation> toRoleOperations(Role role) {
CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class); CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class);
List<Operation> roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType); return JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
}
private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set<Operation> mergedOperations) throws ThingsboardException {
List<Operation> roleOperations = toRoleOperations(role);
if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) { if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) {
GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false)); GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false));
userPermissionsService.onGroupPermissionUpdated(savedGroupPermission); userPermissionsService.onGroupPermissionUpdated(savedGroupPermission);

26
application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java

@ -117,6 +117,7 @@ public class GroupPermissionController extends BaseController {
.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission); .checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission);
} else { } else {
oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE); oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE);
checkGroupPermissionManageable(oldGroupPermission);
} }
if (groupPermission.isPublic()) { if (groupPermission.isPublic()) {
@ -169,17 +170,7 @@ public class GroupPermissionController extends BaseController {
try { try {
GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId)); GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId));
GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE); GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE);
if (groupPermission.isPublic()) { checkGroupPermissionManageable(groupPermission);
throw permissionDenied();
}
checkRoleId(groupPermission.getRoleId(), Operation.READ);
if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
}
if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
}
groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId); groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId);
userPermissionsService.onGroupPermissionDeleted(groupPermission); userPermissionsService.onGroupPermissionDeleted(groupPermission);
@ -257,6 +248,19 @@ public class GroupPermissionController extends BaseController {
return groupPermissions; return groupPermissions;
} }
private void checkGroupPermissionManageable(GroupPermission groupPermission) throws ThingsboardException {
if (groupPermission.isPublic()) {
throw permissionDenied();
}
checkRoleId(groupPermission.getRoleId(), Operation.READ);
if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
}
if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
}
}
private boolean isReadableEntityGroup(GroupPermission groupPermission) { private boolean isReadableEntityGroup(GroupPermission groupPermission) {
EntityGroupId entityGroupId = groupPermission.getEntityGroupId(); EntityGroupId entityGroupId = groupPermission.getEntityGroupId();
if (entityGroupId == null || entityGroupId.isNullUid()) { if (entityGroupId == null || entityGroupId.isNullUid()) {

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

@ -5,7 +5,9 @@ package org.thingsboard.server.controller;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
@ -142,14 +144,10 @@ public class IntegrationController extends AutoCommitController {
checkEntity(integration.getId(), integration, Resource.INTEGRATION); checkEntity(integration.getId(), integration, Resource.INTEGRATION);
if (!integration.isEdgeTemplate()) { try {
try { tbIntegrationService.validateIntegrationConfiguration(tenantId, integration);
Integration copy = new Integration(integration); } catch (ExecutionException e) {
secretConfigurationService.replaceSecretUsages(tenantId, copy.getConfiguration()); throwRealCause(e);
integrationManagerService.validateIntegrationConfiguration(copy).get(20, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throwRealCause(e);
}
} }
Integration result = checkNotNull(integrationService.saveIntegration(integration)); Integration result = checkNotNull(integrationService.saveIntegration(integration));
@ -479,6 +477,8 @@ public class IntegrationController extends AutoCommitController {
notes = "Returns a ZIP containing integration.json, uplink.json, optional downlink.json, " notes = "Returns a ZIP containing integration.json, uplink.json, optional downlink.json, "
+ "and form.json. Sensitive fields are tokenized via @TemplateField annotations on " + "and form.json. Sensitive fields are tokenized via @TemplateField annotations on "
+ "the integration's runtime POJO.") + "the integration's runtime POJO.")
@ApiResponse(responseCode = "200", description = "OK",
content = @Content(mediaType = "application/zip", schema = @Schema(type = "string", format = "binary")))
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/integration/{integrationId}/export-package") @GetMapping("/integration/{integrationId}/export-package")
public ResponseEntity<byte[]> exportIntegrationPackage( public ResponseEntity<byte[]> exportIntegrationPackage(

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

@ -32,10 +32,17 @@ 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.DevicePackageEntityState;
import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService;
import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest;
import org.thingsboard.server.service.iot_hub.DeviceUpdateResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.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;
@ -51,6 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController { public class IotHubController extends BaseController {
private final IotHubService iotHubService; private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService;
private final IotHubInstalledItemService iotHubInstalledItemService; private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService; private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -89,24 +97,27 @@ public class IotHubController extends BaseController {
@ResponseBody @ResponseBody
public InstallItemVersionResult registerDeviceInstall( public InstallItemVersionResult registerDeviceInstall(
@RequestParam String versionId, @RequestParam String versionId,
@RequestParam(required = false) UUID replaceInstalledItemId,
@RequestBody JsonNode body) throws ThingsboardException { @RequestBody JsonNode body) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class);
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor, return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
replaceInstalledItemId != null ? new IotHubInstalledItemId(replaceInstalledItemId) : null);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/device/removeEntities") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody @ResponseBody
public void removeDevicePackageEntities(@PathVariable UUID installedItemId, public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
@RequestParam String versionId,
@RequestParam(required = false) UUID entityGroupId,
@RequestParam(required = false) UUID customerId) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
entityGroupId, customerId); }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody
public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DeviceUpdateRequest request) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@ -167,13 +178,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 {

20
application/src/main/java/org/thingsboard/server/controller/RpcV2Controller.java

@ -13,6 +13,7 @@ import jakarta.annotation.Nullable;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@ -37,6 +38,7 @@ import org.thingsboard.server.common.data.rpc.RpcStatus;
import org.thingsboard.server.common.msg.TbMsg; import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData; import org.thingsboard.server.common.msg.TbMsgMetaData;
import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg; import org.thingsboard.server.common.msg.rpc.RemoveRpcActorMsg;
import org.thingsboard.server.service.rpc.TbRpcService;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.exception.ToErrorResponseEntity; import org.thingsboard.server.exception.ToErrorResponseEntity;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -63,6 +65,9 @@ import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CU
@Slf4j @Slf4j
public class RpcV2Controller extends AbstractRpcController { public class RpcV2Controller extends AbstractRpcController {
@Autowired
private TbRpcService tbRpcService;
private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " + private static final String RPC_REQUEST_DESCRIPTION = "Sends the one-way remote-procedure call (RPC) request to device. " +
"The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " + "The RPC call is A JSON that contains the method name ('method'), parameters ('params') and multiple optional fields. " +
"See example below. We will review the properties of the RPC call one-by-one below. " + "See example below. We will review the properties of the RPC call one-by-one below. " +
@ -155,6 +160,8 @@ public class RpcV2Controller extends AbstractRpcController {
} }
@ApiOperation(value = "Get persistent RPC requests", notes = "Allows to query RPC calls for specific device using pagination." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH) @ApiOperation(value = "Get persistent RPC requests", notes = "Allows to query RPC calls for specific device using pagination." + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@ApiResponse(responseCode = "200", description = "OK",
content = @Content(schema = @Schema(implementation = PageDataRpc.class)))
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/persistent/device/{deviceId}", method = RequestMethod.GET) @RequestMapping(value = "/persistent/device/{deviceId}", method = RequestMethod.GET)
@ResponseBody @ResponseBody
@ -221,13 +228,13 @@ public class RpcV2Controller extends AbstractRpcController {
Rpc rpc = checkRpcId(rpcId); Rpc rpc = checkRpcId(rpcId);
if (rpc != null) { if (rpc != null) {
if (rpc.getStatus().isPushDeleteNotificationToCore()) { if (rpc.getStatus().isIntermediate()) {
RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId()); RemoveRpcActorMsg removeMsg = new RemoveRpcActorMsg(getTenantId(), rpc.getDeviceId(), rpc.getUuidId());
log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc); log.trace("[{}] Forwarding msg {} to queue actor!", rpc.getDeviceId(), rpc);
tbClusterService.pushMsgToCore(removeMsg, null); tbClusterService.pushMsgToCore(removeMsg, null);
} }
rpcService.deleteRpc(getTenantId(), rpcId); tbRpcService.deleteRpc(getTenantId(), rpc);
rpc.setStatus(RpcStatus.DELETED); rpc.setStatus(RpcStatus.DELETED);
TbMsg msg = TbMsg.newMsg() TbMsg msg = TbMsg.newMsg()
@ -239,4 +246,13 @@ public class RpcV2Controller extends AbstractRpcController {
tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null); tbClusterService.pushMsgToRuleEngine(getTenantId(), rpc.getDeviceId(), msg, null);
} }
} }
/**
* Documents the {@code PageData<Rpc>} that {@link #getPersistedRpcByDevice} returns
* through a {@code DeferredResult<ResponseEntity>}. Used only by the OpenAPI spec.
*/
@Schema(name = "PageDataRpc")
private static final class PageDataRpc extends PageData<Rpc> {
}
} }

86
application/src/main/java/org/thingsboard/server/controller/SignUpController.java

@ -2,7 +2,6 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.ServiceAccountCredentials;
@ -34,6 +33,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.rule.engine.api.NotificationCenter; import org.thingsboard.rule.engine.api.NotificationCenter;
@ -117,10 +117,6 @@ public class SignUpController extends BaseController {
private static final String MOBILE_APP_BUNDLE_WAS_NOT_FOUND = "Mobile app bundle was not found"; private static final String MOBILE_APP_BUNDLE_WAS_NOT_FOUND = "Mobile app bundle was not found";
private static final String PRIVACY_POLICY_ACCEPTED = "privacyPolicyAccepted";
private static final String TERMS_OF_USE_ACCEPTED = "termsOfUseAccepted";
private RestTemplate restTemplate; private RestTemplate restTemplate;
@Autowired @Autowired
@ -343,7 +339,7 @@ public class SignUpController extends BaseController {
@ApiOperation(value = "Mobile Login redirect (mobileLogin)", @ApiOperation(value = "Mobile Login redirect (mobileLogin)",
notes = "This method generates redirect to the special link that is handled by mobile application. Useful for email verification flow on mobile app.") notes = "This method generates redirect to the special link that is handled by mobile application. Useful for email verification flow on mobile app.")
@GetMapping(value = "/noauth/login", params = {"pkgName, platform"}) @GetMapping(value = "/noauth/login", params = {"pkgName", "platform"})
public ResponseEntity<String> mobileLogin( public ResponseEntity<String> mobileLogin(
@Parameter(description = "Mobile app package name. Used to identify the application and build the redirect link.", required = true) @Parameter(description = "Mobile app package name. Used to identify the application and build the redirect link.", required = true)
@RequestParam(value = "pkgName") String pkgName, @RequestParam(value = "pkgName") String pkgName,
@ -400,15 +396,18 @@ public class SignUpController extends BaseController {
String encodedPassword = userCredentials.getPassword(); String encodedPassword = userCredentials.getPassword();
UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword); UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword);
User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId()); User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
setPrivacyPolicyAccepted(user); long acceptedTs = System.currentTimeMillis();
setTermsOfUseAccepted(user); user.setPrivacyPolicyAccepted(acceptedTs);
user.setTermsOfUseAccepted(acceptedTs);
user = userService.saveUser(tenantId, user); user = userService.saveUser(tenantId, user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false)); SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false));
String baseUrl = MiscUtils.constructBaseUrl(request); String baseUrl = MiscUtils.constructBaseUrl(request);
String loginUrl; String loginUrl;
if (!StringUtils.isEmpty(pkgName)) { if (!StringUtils.isEmpty(pkgName)) {
loginUrl = String.format("%s/api/noauth/login?pkgName=%s", baseUrl, pkgName); loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login")
.queryParam("pkgName", pkgName).queryParam("platform", platform)
.encode().toUriString();
} else { } else {
loginUrl = String.format("%s/login", baseUrl); loginUrl = String.format("%s/login", baseUrl);
} }
@ -426,23 +425,6 @@ public class SignUpController extends BaseController {
return tokenFactory.createTokenPair(securityUser); return tokenFactory.createTokenPair(securityUser);
} }
private void setPrivacyPolicyAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = JacksonUtil.newObjectNode();
}
((ObjectNode) additionalInfo).put(PRIVACY_POLICY_ACCEPTED, true);
user.setAdditionalInfo(additionalInfo);
}
private boolean isPrivacyPolicyAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(PRIVACY_POLICY_ACCEPTED)) {
return additionalInfo.get(PRIVACY_POLICY_ACCEPTED).asBoolean();
}
return false;
}
@ApiOperation(value = "Check privacy policy (privacyPolicyAccepted)", @ApiOperation(value = "Check privacy policy (privacyPolicyAccepted)",
notes = "Checks that current user accepted the privacy policy.") notes = "Checks that current user accepted the privacy policy.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@ -451,43 +433,23 @@ public class SignUpController extends BaseController {
Boolean privacyPolicyAccepted() throws ThingsboardException { Boolean privacyPolicyAccepted() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId()); User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
return isPrivacyPolicyAccepted(user); return user.isPrivacyPolicyAccepted();
} }
@ApiOperation(value = "Accept privacy policy (acceptPrivacyPolicy)", @ApiOperation(value = "Accept privacy policy (acceptPrivacyPolicy)",
notes = "Accept privacy policy by the current user.") notes = "Accept privacy policy by the current user. " +
"Stores the acceptance flag 'privacyPolicyAccepted' and the acceptance time 'privacyPolicyAcceptedTs' (epoch milliseconds) " +
"in the user's additional info. Repeated acceptance overwrites the stored time.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/signup/acceptPrivacyPolicy") @PostMapping(value = "/signup/acceptPrivacyPolicy")
public JsonNode acceptPrivacyPolicy() throws ThingsboardException { public JwtPair acceptPrivacyPolicy() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId()); User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
setPrivacyPolicyAccepted(user); user.setPrivacyPolicyAccepted();
user = userService.saveUser(securityUser.getTenantId(), user); user = userService.saveUser(securityUser.getTenantId(), user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false)); securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false));
JwtPair tokenPair = tokenFactory.createTokenPair(securityUser); return tokenFactory.createTokenPair(securityUser);
ObjectNode tokenObject = JacksonUtil.newObjectNode();
tokenObject.put("token", tokenPair.getToken());
tokenObject.put("refreshToken", tokenPair.getRefreshToken());
return tokenObject;
}
private void setTermsOfUseAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (!(additionalInfo instanceof ObjectNode)) {
additionalInfo = JacksonUtil.newObjectNode();
}
((ObjectNode) additionalInfo).put(TERMS_OF_USE_ACCEPTED, true);
user.setAdditionalInfo(additionalInfo);
}
private boolean isTermsOfUseAccepted(User user) {
JsonNode additionalInfo = user.getAdditionalInfo();
if (additionalInfo != null && additionalInfo.has(TERMS_OF_USE_ACCEPTED)) {
return additionalInfo.get(TERMS_OF_USE_ACCEPTED).asBoolean();
}
return false;
} }
@ApiOperation(value = "Check Terms Of User (termsOfUseAccepted)", @ApiOperation(value = "Check Terms Of User (termsOfUseAccepted)",
@ -498,26 +460,23 @@ public class SignUpController extends BaseController {
Boolean termsOfUseAccepted() throws ThingsboardException { Boolean termsOfUseAccepted() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId()); User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
return isTermsOfUseAccepted(user); return user.isTermsOfUseAccepted();
} }
@ApiOperation(value = "Accept Terms of Use (acceptTermsOfUse)", @ApiOperation(value = "Accept Terms of Use (acceptTermsOfUse)",
notes = "Accept Terms of Use by the current user.") notes = "Accept Terms of Use by the current user. " +
"Stores the acceptance flag 'termsOfUseAccepted' and the acceptance time 'termsOfUseAcceptedTs' (epoch milliseconds) " +
"in the user's additional info. Repeated acceptance overwrites the stored time.")
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/signup/acceptTermsOfUse") @PostMapping(value = "/signup/acceptTermsOfUse")
public JsonNode acceptTermsOfUse() throws ThingsboardException { public JwtPair acceptTermsOfUse() throws ThingsboardException {
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId()); User user = userService.findUserById(securityUser.getTenantId(), securityUser.getId());
setTermsOfUseAccepted(user); user.setTermsOfUseAccepted();
user = userService.saveUser(securityUser.getTenantId(), user); user = userService.saveUser(securityUser.getTenantId(), user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false)); securityUser = new SecurityUser(user, true, principal, getMergedUserPermissions(user, false));
JwtPair tokenPair = tokenFactory.createTokenPair(securityUser); return tokenFactory.createTokenPair(securityUser);
ObjectNode tokenObject = JacksonUtil.newObjectNode();
tokenObject.put("token", tokenPair.getToken());
tokenObject.put("refreshToken", tokenPair.getRefreshToken());
return tokenObject;
} }
private void validateReCaptcha(String userResponse, String ipAddress, String recaptchaSecretKey) throws ThingsboardException { private void validateReCaptcha(String userResponse, String ipAddress, String recaptchaSecretKey) throws ThingsboardException {
@ -613,6 +572,7 @@ public class SignUpController extends BaseController {
List<GroupPermission> permissions = selfRegistrationParams.getPermissions(); List<GroupPermission> permissions = selfRegistrationParams.getPermissions();
for (GroupPermission permission : permissions) { for (GroupPermission permission : permissions) {
permission.setId(null);
permission.setTenantId(tenantId); permission.setTenantId(tenantId);
permission.setUserGroupId(usersEntityGroup.getId()); permission.setUserGroupId(usersEntityGroup.getId());
if (permission.getEntityGroupId() != null) { if (permission.getEntityGroupId() != null) {

27
application/src/main/java/org/thingsboard/server/controller/SystemInfoController.java

@ -3,7 +3,6 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
@ -21,6 +20,7 @@ import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DashboardInfo;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.SystemParams; import org.thingsboard.server.common.data.SystemParams;
import org.thingsboard.server.common.data.SystemVersionInfo;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
@ -34,6 +34,7 @@ import org.thingsboard.server.common.data.settings.UserSettings;
import org.thingsboard.server.common.data.settings.UserSettingsType; import org.thingsboard.server.common.data.settings.UserSettingsType;
import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration; import org.thingsboard.server.common.data.tenant.profile.DefaultTenantProfileConfiguration;
import org.thingsboard.server.common.msg.edqs.EdqsService; import org.thingsboard.server.common.msg.edqs.EdqsService;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.mobile.QrCodeSettingService; import org.thingsboard.server.dao.mobile.QrCodeSettingService;
import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.dao.subscription.SubscriptionService;
@ -52,7 +53,8 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Hidden import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH;
@RestController @RestController
@TbCoreComponent @TbCoreComponent
@RequestMapping("/api") @RequestMapping("/api")
@ -117,23 +119,26 @@ public class SystemInfoController extends BaseController {
@PostConstruct @PostConstruct
public void init() { public void init() {
JsonNode info = buildInfoObject(); log.info("System build info: {}", JacksonUtil.toString(buildInfoObject()));
log.info("System build info: {}", info);
} }
@ApiOperation(value = "Get platform version (getSystemVersionInfo)",
notes = "Returns the version and edition of the platform build." + SYSTEM_OR_TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/system/info", method = RequestMethod.GET) @RequestMapping(value = "/system/info", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public JsonNode getSystemVersionInfo() { public SystemVersionInfo getSystemVersionInfo() {
return buildInfoObject(); return buildInfoObject();
} }
@Hidden
@RequestMapping(value = "/noauth/system/development", method = RequestMethod.GET) @RequestMapping(value = "/noauth/system/development", method = RequestMethod.GET)
@ResponseBody @ResponseBody
public Boolean isDevelopment() { public Boolean isDevelopment() {
return subscriptionService.isDevelopment(TenantId.SYS_TENANT_ID); return subscriptionService.isDevelopment(TenantId.SYS_TENANT_ID);
} }
@Hidden
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/system/params", method = RequestMethod.GET) @RequestMapping(value = "/system/params", method = RequestMethod.GET)
@ResponseBody @ResponseBody
@ -230,17 +235,11 @@ public class SystemInfoController extends BaseController {
currentUser.getAdditionalInfo().get("defaultDashboardFullscreen").booleanValue()); currentUser.getAdditionalInfo().get("defaultDashboardFullscreen").booleanValue());
} }
private JsonNode buildInfoObject() { private SystemVersionInfo buildInfoObject() {
ObjectNode infoObject = JacksonUtil.newObjectNode();
if (buildProperties != null) { if (buildProperties != null) {
infoObject.put("version", buildProperties.getVersion()); return new SystemVersionInfo(buildProperties.getVersion(), buildProperties.getArtifact(), buildProperties.getName(), "PE");
infoObject.put("artifact", buildProperties.getArtifact());
infoObject.put("name", buildProperties.getName());
} else {
infoObject.put("version", "unknown");
} }
infoObject.put("type", "PE"); return new SystemVersionInfo("unknown", null, null, "PE");
return infoObject;
} }
} }

12
application/src/main/java/org/thingsboard/server/controller/TbResourceController.java

@ -175,8 +175,8 @@ public class TbResourceController extends BaseController {
@ApiOperation(value = "Get resource info (getResourceInfo)", @ApiOperation(value = "Get resource info (getResourceInfo)",
notes = "Get info for the resource with the given type, scope and key. " + notes = "Get info for the resource with the given type, scope and key. " +
RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") @PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@GetMapping(value = "/resource/{resourceType}/{scope}/{key}/info") @GetMapping(value = "/resource/{resourceType}/{scope}/{key}/info")
public TbResourceInfo getResourceInfo(@Parameter(description = "Type of the resource", schema = @Schema(allowableValues = {"lwm2m_model", "jks", "pkcs_12", "js_module", "dashboard"})) public TbResourceInfo getResourceInfo(@Parameter(description = "Type of the resource", schema = @Schema(allowableValues = {"lwm2m_model", "jks", "pkcs_12", "js_module", "dashboard"}))
@PathVariable("resourceType") String resourceTypeStr, @PathVariable("resourceType") String resourceTypeStr,
@ -286,8 +286,9 @@ public class TbResourceController extends BaseController {
@ApiOperation(value = "Get Resource Infos (getResources)", @ApiOperation(value = "Get Resource Infos (getResources)",
notes = "Returns a page of Resource Info objects owned by tenant or sysadmin. " + notes = "Returns a page of Resource Info objects owned by tenant or sysadmin. " +
PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + SYSTEM_OR_TENANT_AUTHORITY_PARAGRAPH) "Customer users may request only 'JS_MODULE' resources, so the 'resourceType' parameter is mandatory for them. " +
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN')") PAGE_DATA_PARAMETERS + RESOURCE_INFO_DESCRIPTION + AVAILABLE_FOR_ANY_AUTHORIZED_USER)
@PreAuthorize("hasAnyAuthority('SYS_ADMIN', 'TENANT_ADMIN', 'CUSTOMER_USER')")
@GetMapping(value = "/resource") @GetMapping(value = "/resource")
public PageData<TbResourceInfo> getResources(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true) public PageData<TbResourceInfo> getResources(@Parameter(description = PAGE_SIZE_DESCRIPTION, required = true)
@RequestParam int pageSize, @RequestParam int pageSize,
@ -322,6 +323,9 @@ public class TbResourceController extends BaseController {
filterResourceTypes.remove(ResourceType.IMAGE); filterResourceTypes.remove(ResourceType.IMAGE);
filterResourceTypes.remove(ResourceType.DASHBOARD); filterResourceTypes.remove(ResourceType.DASHBOARD);
} }
if (getCurrentUser().isCustomerUser() && !filterResourceTypes.equals(Set.of(ResourceType.JS_MODULE))) {
throw permissionDenied();
}
filter.resourceTypes(filterResourceTypes); filter.resourceTypes(filterResourceTypes);
if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) { if (Authority.SYS_ADMIN.equals(getCurrentUser().getAuthority())) {
return checkNotNull(resourceService.findTenantResourcesByTenantId(filter.build(), pageLink)); return checkNotNull(resourceService.findTenantResourcesByTenantId(filter.build(), pageLink));

2
application/src/main/java/org/thingsboard/server/controller/UserPermissionsController.java

@ -70,7 +70,7 @@ public class UserPermissionsController extends BaseController {
@PathVariable(ENTITY_ID) String strEntityId, @PathVariable(ENTITY_ID) String strEntityId,
@Parameter(description = OPERATION_PARAM_DESCRIPTION, required = true, schema = @Schema(allowableValues = {"ALL", "CREATE", "READ", "WRITE", "DELETE", @Parameter(description = OPERATION_PARAM_DESCRIPTION, required = true, schema = @Schema(allowableValues = {"ALL", "CREATE", "READ", "WRITE", "DELETE",
"RPC_CALL", "READ_CREDENTIALS", "WRITE_CREDENTIALS", "READ_ATTRIBUTES", "WRITE_ATTRIBUTES", "READ_TELEMETRY", "WRITE_TELEMETRY","ADD_TO_GROUP", "RPC_CALL", "READ_CREDENTIALS", "WRITE_CREDENTIALS", "READ_ATTRIBUTES", "WRITE_ATTRIBUTES", "READ_TELEMETRY", "WRITE_TELEMETRY","ADD_TO_GROUP",
"REMOVE_FROM_GROUP", "CHANGE_OWNER", "IMPERSONATE", "CLAIM_DEVICES", "SHARE_GROUP", "ASSIGN_TO_TENANT", "READ_CALCULATED_FIELD", "WRITE_CALCULATED_FIELD"})) "REMOVE_FROM_GROUP", "CHANGE_OWNER", "IMPERSONATE", "CLAIM_DEVICES", "SHARE_GROUP", "ASSIGN_TO_TENANT", "READ_CALCULATED_FIELD", "WRITE_CALCULATED_FIELD", "INVOKE"}))
@PathVariable(OPERATION) Operation operation) { @PathVariable(OPERATION) Operation operation) {
EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, strEntityId); EntityId entityId = EntityIdFactory.getByTypeAndId(entityType, strEntityId);
try { try {

3
application/src/main/java/org/thingsboard/server/controller/plugin/TbWebSocketHandler.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.controller.plugin; package org.thingsboard.server.controller.plugin;
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Cache;

4
application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java

@ -114,7 +114,7 @@ public class ThingsboardInstallService {
entityDatabaseSchemaService.createOrUpdateViewsAndFunctions(); entityDatabaseSchemaService.createOrUpdateViewsAndFunctions();
entityDatabaseSchemaService.createOrUpdateDeviceInfoView(persistToTelemetry); entityDatabaseSchemaService.createOrUpdateDeviceInfoView(persistToTelemetry);
} else { } else {
// TODO DON'T FORGET to update SUPPORTED_VERSIONS_FOR_UPGRADE and MIN_CE_VERSION_FOR_UPGRADE in DefaultDatabaseSchemaSettingsService // TODO DON'T FORGET to update SUPPORTED_FAMILIES_FOR_UPGRADE and MIN_CE_VERSION_FOR_UPGRADE in DefaultDatabaseSchemaSettingsService
databaseSchemaVersionService.validateSchemaSettings(); databaseSchemaVersionService.validateSchemaSettings();
// The database's own product marker selects the branch, so a CE database can never be taken // The database's own product marker selects the branch, so a CE database can never be taken
// down the PE path by a missing flag. --fromVersion=CE is still accepted, and now a no-op. // down the PE path by a missing flag. --fromVersion=CE is still accepted, and now a no-op.
@ -131,7 +131,7 @@ public class ThingsboardInstallService {
} }
cacheCleanupService.clearCache(); cacheCleanupService.clearCache();
if (updateFromCE) { if (updateFromCE) {
// The LTS chain references PE-only tables and runs each of its files as a single transaction, // The migration chain references PE-only tables and runs each of its files as a single transaction,
// so a converted CE database must get those tables before the chain rather than after it. // so a converted CE database must get those tables before the chain rather than after it.
entityDatabaseSchemaService.createDatabaseSchema(false); entityDatabaseSchemaService.createDatabaseSchema(false);
} }

14
application/src/main/java/org/thingsboard/server/service/agent/AgentGrpcService.java

@ -285,25 +285,25 @@ public class AgentGrpcService extends AgentRpcServiceGrpc.AgentRpcServiceImplBas
private void resumeEvents(AgentSession session) { private void resumeEvents(AgentSession session) {
var agent = session.getState().getAgent(); var agent = session.getState().getAgent();
scheduleResume(agent.getTenantId(), agent.getId()); scheduleResume(agent.getTenantId(), agent.getId(), session);
} }
private void scheduleResume(TenantId tenantId, AgentId agentId) { private void scheduleResume(TenantId tenantId, AgentId agentId, AgentSession session) {
long maxDelayMs = agentCtx.getReconnectResumeMaxDelayMs(); long maxDelayMs = agentCtx.getReconnectResumeMaxDelayMs();
long delayMs = maxDelayMs > 0 ? ThreadLocalRandom.current().nextLong(maxDelayMs + 1) : 0; long delayMs = maxDelayMs > 0 ? ThreadLocalRandom.current().nextLong(maxDelayMs + 1) : 0;
agentCtx.getReconnectResumeScheduler().schedule(() -> submitResume(tenantId, agentId), delayMs, TimeUnit.MILLISECONDS); agentCtx.getReconnectResumeScheduler().schedule(() -> submitResume(tenantId, agentId, session), delayMs, TimeUnit.MILLISECONDS);
} }
private void submitResume(TenantId tenantId, AgentId agentId) { private void submitResume(TenantId tenantId, AgentId agentId, AgentSession session) {
if (sessions.getByAgentId(agentId) == null) { if (sessions.getByAgentId(agentId) != session) {
log.trace("[{}][{}] Skipping resume-on-reconnect, no active session", tenantId, agentId); log.trace("[{}][{}] Skipping resume-on-reconnect, session is no longer active", tenantId, agentId);
return; return;
} }
try { try {
agentCtx.getAgentEventExecutor().execute(() -> agentEventProcessor.resumeEventsOnReconnect(tenantId, agentId)); agentCtx.getAgentEventExecutor().execute(() -> agentEventProcessor.resumeEventsOnReconnect(tenantId, agentId));
} catch (RejectedExecutionException e) { } catch (RejectedExecutionException e) {
log.warn("[{}][{}] Agent event executor saturated, retrying resume-on-reconnect after delay", tenantId, agentId); log.warn("[{}][{}] Agent event executor saturated, retrying resume-on-reconnect after delay", tenantId, agentId);
scheduleResume(tenantId, agentId); scheduleResume(tenantId, agentId, session);
} }
} }

9
application/src/main/java/org/thingsboard/server/service/agent/compose/ComposeAgentAppCreator.java

@ -9,6 +9,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.RegexUtils; import org.thingsboard.common.util.RegexUtils;
import org.thingsboard.common.util.TbVersionUtils;
import org.thingsboard.server.common.data.agent.Agent; import org.thingsboard.server.common.data.agent.Agent;
import org.thingsboard.server.common.data.agent.AgentAppEventActionType; import org.thingsboard.server.common.data.agent.AgentAppEventActionType;
import org.thingsboard.server.common.data.agent.AgentAppProfileRelationInfo; import org.thingsboard.server.common.data.agent.AgentAppProfileRelationInfo;
@ -24,6 +25,7 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.agent.AgentAppProfileService; import org.thingsboard.server.dao.agent.AgentAppProfileService;
import org.thingsboard.server.dao.agent.AgentAppRelationService; import org.thingsboard.server.dao.agent.AgentAppRelationService;
import org.thingsboard.server.dao.agent.AgentService; import org.thingsboard.server.dao.agent.AgentService;
import org.thingsboard.server.dao.edge.EdgeEditionStyle;
import org.thingsboard.server.gen.agent.v1.ComposeState; import org.thingsboard.server.gen.agent.v1.ComposeState;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.agent.AgentAppProvisioner; import org.thingsboard.server.service.agent.AgentAppProvisioner;
@ -103,6 +105,13 @@ public class ComposeAgentAppCreator {
private AgentAppTemplate resolveTemplate(ComposeInfo composeInfo) { private AgentAppTemplate resolveTemplate(ComposeInfo composeInfo) {
AgentAppTemplate byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion( AgentAppTemplate byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion(
composeInfo.appType(), AgentAppConfigType.DOCKER_COMPOSE, composeInfo.version()); composeInfo.appType(), AgentAppConfigType.DOCKER_COMPOSE, composeInfo.version());
if (byAppType == null && composeInfo.appType() == AgentApplicationType.EDGE && composeInfo.version() != null
&& TbVersionUtils.compare(TbVersionUtils.extractStartingDigits(composeInfo.version()), "4.4") >= 0) {
// from 4.4 the same edge release may be published under both edition styles (e.g. 4.4.0EDGEPE and the CE-style 4.4.0EDGE),
// while its template is registered under one of them only; below 4.4 a CE-style tag is Community Edge and stays GENERIC
byAppType = templateService.findByAppTypeAndConfigTypeAndCurrentVersion(AgentApplicationType.EDGE,
AgentAppConfigType.DOCKER_COMPOSE, EdgeEditionStyle.withVersionSuffix(TbVersionUtils.extractStartingDigits(composeInfo.version())));
}
if (byAppType != null) { if (byAppType != null) {
return byAppType; return byAppType;
} }

7
application/src/main/java/org/thingsboard/server/service/agent/config/MergeHostValuesRule.java

@ -96,11 +96,16 @@ public class MergeHostValuesRule implements AppConfigMergeRule {
log.warn("Skipping gateway host merge: resolveGatewayHost returned blank for baseUrl [{}]", baseUrl); log.warn("Skipping gateway host merge: resolveGatewayHost returned blank for baseUrl [{}]", baseUrl);
return; return;
} }
String port = deviceConnectivityService.resolveGatewayPort();
if (StringUtils.isBlank(port)) {
log.debug("Gateway MQTT port is not configured in connectivity settings, using default [{}]", GATEWAY_DEFAULT_PORT);
port = GATEWAY_DEFAULT_PORT;
}
var imagePattern = AgentApplicationType.GATEWAY.getMainImagePattern(); var imagePattern = AgentApplicationType.GATEWAY.getMainImagePattern();
GatewayEnvSchema schema = GatewayEnvSchema.detect(compose, imagePattern); GatewayEnvSchema schema = GatewayEnvSchema.detect(compose, imagePattern);
Map<String, String> envVars = Map.of( Map<String, String> envVars = Map.of(
schema.getHostKey(), host, schema.getHostKey(), host,
schema.getPortKey(), GATEWAY_DEFAULT_PORT schema.getPortKey(), port
); );
DockerComposeUtils.setEnvVariables(compose, imagePattern, envVars); DockerComposeUtils.setEnvVariables(compose, imagePattern, envVars);
} }

62
application/src/main/java/org/thingsboard/server/service/agent/template/AgentAppTemplateSyncService.java

@ -24,6 +24,7 @@ import org.thingsboard.server.common.data.EdgeUpgradeMessageV2;
import org.thingsboard.server.common.data.agent.AgentApplicationType; import org.thingsboard.server.common.data.agent.AgentApplicationType;
import org.thingsboard.server.common.data.agent.config.AgentAppConfigType; import org.thingsboard.server.common.data.agent.config.AgentAppConfigType;
import org.thingsboard.server.common.data.util.CollectionsUtil; import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.dao.edge.EdgeEditionStyle;
import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry; import org.thingsboard.server.dao.sql.agent.AppTemplateRegistry;
import org.thingsboard.server.queue.util.AfterStartUp; import org.thingsboard.server.queue.util.AfterStartUp;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -39,8 +40,10 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
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.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -68,7 +71,8 @@ public class AgentAppTemplateSyncService {
private static final int APP_TYPE_GROUP_NUM = 1; private static final int APP_TYPE_GROUP_NUM = 1;
private static final int CONFIG_TYPE_GROUP_NUM = 2; private static final int CONFIG_TYPE_GROUP_NUM = 2;
private static final String REPO_KEY = "agent-app-templates"; private static final String REPO_KEY = "agent-app-templates";
private static final String EDGE_IMAGE_VERSION_SUFFIX = "EDGEPE"; // <basePath>/since/<version>/ holds templates that replace the same-named base ones from that platform version on
private static final String SINCE_DIR = "since";
private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration UPDATE_SERVER_CONNECT_TIMEOUT = Duration.ofSeconds(10);
private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30); private static final Duration UPDATE_SERVER_READ_TIMEOUT = Duration.ofSeconds(30);
@ -125,7 +129,7 @@ public class AgentAppTemplateSyncService {
continue; continue;
} }
MaterializationResult result = materializer.materialize( MaterializationResult result = materializer.materialize(
rawTemplate, appType, configType, descriptors, composeLoader()); rawTemplate, appType, configType, descriptors, composeLoader(), folderLister());
if (result.getByVersion().isEmpty()) { if (result.getByVersion().isEmpty()) {
log.warn("Materialized no versions for {}-{} (the version graph is empty or unreachable); " + log.warn("Materialized no versions for {}-{} (the version graph is empty or unreachable); " +
"keeping the previously registered templates", appType, configType); "keeping the previously registered templates", appType, configType);
@ -147,12 +151,47 @@ public class AgentAppTemplateSyncService {
return new RestTemplate(factory); return new RestTemplate(factory);
} }
private List<RepoFile> getTemplateFiles() { /**
return gitSyncService.listFiles(REPO_KEY, basePath, 1, FileType.FILE).stream() * Base templates overridden per file name by {@code since/<version>/} ones, taking the newest folder whose version
* is not above the platform version. Servers older than a {@code since} folder only list the base folder, so the
* templates there are free to rely on newer materialization variables.
*/
List<RepoFile> getTemplateFiles() {
String platform = TbVersionUtils.extractStartingDigits(projectInfo.getProjectVersion());
Map<String, List<RepoFile>> sinceFilesByVersion = listTemplateFiles(basePath + "/" + SINCE_DIR, 2).stream()
.collect(Collectors.groupingBy(AgentAppTemplateSyncService::sinceVersion));
Map<String, RepoFile> byName = new LinkedHashMap<>();
for (String version : VersionFolders.applicableTo(sinceFilesByVersion.keySet(), platform)) {
sinceFilesByVersion.get(version).forEach(file -> byName.putIfAbsent(file.name(), file));
}
listTemplateFiles(basePath, 1).forEach(file -> byName.putIfAbsent(file.name(), file));
return new ArrayList<>(byName.values());
}
// Template files the given number of folders below path
private List<RepoFile> listTemplateFiles(String path, int levels) {
return gitSyncService.listFiles(REPO_KEY, path, depthBelow(path, levels), FileType.FILE).stream()
.filter(file -> RegexUtils.matches(file.name(), TEMPLATE_FILE_PATTERN)) .filter(file -> RegexUtils.matches(file.name(), TEMPLATE_FILE_PATTERN))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
// Name of the folder holding the file, e.g. templates/since/4.4.1/template-EDGE-DOCKER_COMPOSE.json -> 4.4.1
// Tree depth of the entries the given number of folders below path (root entries are at depth 0)
private static int depthBelow(String path, int levels) {
return path.split("/").length - 1 + levels;
}
private static String sinceVersion(RepoFile file) {
String folder = file.path().substring(0, file.path().lastIndexOf('/'));
return folder.substring(folder.lastIndexOf('/') + 1);
}
// Names of the folders directly under a repo path, cached per template since every version lists the same folders
private Function<String, List<String>> folderLister() {
Map<String, List<String>> cache = new HashMap<>();
return path -> cache.computeIfAbsent(path, p -> gitSyncService.listFiles(REPO_KEY, p, depthBelow(p, 1), FileType.DIRECTORY)
.stream().map(RepoFile::name).toList());
}
private Function<String, JsonNode> composeLoader() { private Function<String, JsonNode> composeLoader() {
// Returns null when the file is absent so the materializer can probe more/less specific // Returns null when the file is absent so the materializer can probe more/less specific
// version subfolders (e.g. compose/edge/4.3/4.3.1 before compose/edge/4.3) and pick the closest match. // version subfolders (e.g. compose/edge/4.3/4.3.1 before compose/edge/4.3) and pick the closest match.
@ -169,8 +208,8 @@ public class AgentAppTemplateSyncService {
private List<AppVersionDescriptor> resolveDescriptors(AgentApplicationType appType) { private List<AppVersionDescriptor> resolveDescriptors(AgentApplicationType appType) {
return switch (appType) { return switch (appType) {
case EDGE -> appendVersionSuffix(filterCurrentlySupportedVersions( case EDGE -> appendEdgeVersionSuffix(filterCurrentlySupportedVersions(
filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType)), EDGE_IMAGE_VERSION_SUFFIX); filterVersionsWithoutTemplates(edgeDescriptors(), minSupportedEdgeVersion, appType)));
case GATEWAY -> filterVersionsWithoutTemplates( case GATEWAY -> filterVersionsWithoutTemplates(
buildDescriptors(gatewayVersionGraph(), "gatewayVersions", "nextGatewayVersion", false), buildDescriptors(gatewayVersionGraph(), "gatewayVersions", "nextGatewayVersion", false),
minSupportedGatewayVersion, appType); minSupportedGatewayVersion, appType);
@ -178,18 +217,23 @@ public class AgentAppTemplateSyncService {
}; };
} }
static List<AppVersionDescriptor> appendVersionSuffix(List<AppVersionDescriptor> descriptors, String suffix) { // edge image tags carry an edition suffix that depends on the version itself (e.g. 4.4.0EDGEPE vs 4.4.1EDGE)
static List<AppVersionDescriptor> appendEdgeVersionSuffix(List<AppVersionDescriptor> descriptors) {
if (CollectionsUtil.isEmpty(descriptors)) { if (CollectionsUtil.isEmpty(descriptors)) {
return descriptors; return descriptors;
} }
return descriptors.stream() return descriptors.stream()
.map(d -> new AppVersionDescriptor( .map(d -> new AppVersionDescriptor(
d.getVersion() + suffix, withEdgeVersionSuffix(d.getVersion()),
d.getNextVersion() == null ? null : d.getNextVersion() + suffix, withEdgeVersionSuffix(d.getNextVersion()),
d.isRequiresUpdateDb())) d.isRequiresUpdateDb()))
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
private static String withEdgeVersionSuffix(String version) {
return version == null ? null : EdgeEditionStyle.withVersionSuffix(version);
}
List<AppVersionDescriptor> filterCurrentlySupportedVersions(List<AppVersionDescriptor> descriptors) { List<AppVersionDescriptor> filterCurrentlySupportedVersions(List<AppVersionDescriptor> descriptors) {
if (CollectionsUtil.isEmpty(descriptors)) { if (CollectionsUtil.isEmpty(descriptors)) {
return descriptors; return descriptors;

79
application/src/main/java/org/thingsboard/server/service/agent/template/AppTemplateMaterializer.java

@ -17,9 +17,8 @@ import org.thingsboard.server.common.data.agent.step.ComposeTypeChoiceStep;
import org.thingsboard.server.common.data.agent.template.AgentAppTemplate; import org.thingsboard.server.common.data.agent.template.AgentAppTemplate;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.agent.StepLinkedListUtils; import org.thingsboard.server.dao.agent.StepLinkedListUtils;
import org.thingsboard.server.dao.edge.EdgeEditionStyle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -69,7 +68,8 @@ public class AppTemplateMaterializer {
AgentApplicationType appType, AgentApplicationType appType,
AgentAppConfigType configType, AgentAppConfigType configType,
List<AppVersionDescriptor> descriptors, List<AppVersionDescriptor> descriptors,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
Map<String, AgentAppTemplate> byVersion = new LinkedHashMap<>(); Map<String, AgentAppTemplate> byVersion = new LinkedHashMap<>();
AgentAppTemplate latest = null; AgentAppTemplate latest = null;
@ -81,7 +81,7 @@ public class AppTemplateMaterializer {
try { try {
Map<String, Object> vars = buildVars(d); Map<String, Object> vars = buildVars(d);
AgentAppTemplate template = materializeOne(rawTemplate, appType, configType, AgentAppTemplate template = materializeOne(rawTemplate, appType, configType,
d.getVersion(), d.getNextVersion(), vars, composeLoader); d.getVersion(), d.getNextVersion(), vars, composeLoader, folderLister);
byVersion.put(d.getVersion(), template); byVersion.put(d.getVersion(), template);
if (d.getNextVersion() == null) { if (d.getNextVersion() == null) {
latest = template; latest = template;
@ -115,7 +115,8 @@ public class AppTemplateMaterializer {
String version, String version,
String nextVersion, String nextVersion,
Map<String, Object> vars, Map<String, Object> vars,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
JsonNode substituted = TemplateVarSubstitutor.substitute(rawTemplate, vars); JsonNode substituted = TemplateVarSubstitutor.substitute(rawTemplate, vars);
AgentAppTemplate template = JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER AgentAppTemplate template = JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_JSON_MAPPER
@ -127,7 +128,7 @@ public class AppTemplateMaterializer {
template.setCurrentVersion(version); template.setCurrentVersion(version);
template.setNextVersion(nextVersion); template.setNextVersion(nextVersion);
resolveComposeTemplates(template.getStartSteps(), vars, composeLoader); resolveComposeTemplates(template.getStartSteps(), vars, composeLoader, folderLister);
Predicate<AgentAppStep> disabled = step -> Predicate<AgentAppStep> disabled = step ->
step.getCondition() != null && !truthy(vars.get(step.getCondition())); step.getCondition() != null && !truthy(vars.get(step.getCondition()));
@ -140,7 +141,8 @@ public class AppTemplateMaterializer {
} }
private void resolveComposeTemplates(List<AgentAppStep> steps, Map<String, Object> vars, private void resolveComposeTemplates(List<AgentAppStep> steps, Map<String, Object> vars,
Function<String, JsonNode> composeLoader) { Function<String, JsonNode> composeLoader,
Function<String, List<String>> folderLister) {
if (steps == null) { if (steps == null) {
return; return;
} }
@ -154,7 +156,7 @@ public class AppTemplateMaterializer {
if (value != null && value.isTextual()) { if (value != null && value.isTextual()) {
String path = value.asText(); String path = value.asText();
if (path.endsWith(".yml") || path.endsWith(".yaml")) { if (path.endsWith(".yml") || path.endsWith(".yaml")) {
JsonNode compose = loadMostSpecificCompose(path, vars, composeLoader); JsonNode compose = loadMostSpecificCompose(path, vars, composeLoader, folderLister);
resolved.put(entry.getKey(), TemplateVarSubstitutor.substitute(compose, vars)); resolved.put(entry.getKey(), TemplateVarSubstitutor.substitute(compose, vars));
continue; continue;
} }
@ -166,13 +168,15 @@ public class AppTemplateMaterializer {
} }
/** /**
* Load the compose body for {@code path}, preferring the most specific version subfolder that actually exists in * Load the compose body for {@code path}, taking the file from the newest version folder that has it. For version
* the repo. For version {@code 4.3.1.2} with a base {@code composeLine} of {@code 4.3}, this tries * {@code 4.4.2} and {@code compose/edge/4.4/kafka.yml} with folders {@code 4.3, 4.4, 4.4.1} under
* {@code compose/edge/4.3/4.3.1/4.3.1.2/…}, then {@code …/4.3/4.3.1/…}, then the base {@code …/4.3/…}. Falls through * {@code compose/edge}, this tries {@code compose/edge/4.4.1/kafka.yml}, then {@code compose/edge/4.4/kafka.yml},
* to an error (so the version is skipped, as before) only when no candidate exists. * then {@code compose/edge/4.3/kafka.yml}. Falls through to an error (so the version is skipped) only when no
* candidate exists.
*/ */
private JsonNode loadMostSpecificCompose(String path, Map<String, Object> vars, Function<String, JsonNode> composeLoader) { private JsonNode loadMostSpecificCompose(String path, Map<String, Object> vars, Function<String, JsonNode> composeLoader,
List<String> candidates = composePathCandidates(path, vars); Function<String, List<String>> folderLister) {
List<String> candidates = composePathCandidates(path, vars, folderLister);
for (String candidate : candidates) { for (String candidate : candidates) {
JsonNode compose = composeLoader.apply(candidate); JsonNode compose = composeLoader.apply(candidate);
if (compose != null) { if (compose != null) {
@ -183,38 +187,26 @@ public class AppTemplateMaterializer {
} }
/** /**
* Candidate compose paths, most specific first, obtained by expanding the {@code composeLine} folder segment into * Candidate compose paths, newest first: the {@code composeLine} folder of {@code path} is swapped for each sibling
* progressively deeper version subfolders (e.g. {@code 4.3} -> {@code 4.3/4.3.1} -> {@code 4.3/4.3.1/4.3.1.2}). * version folder that applies to the version (see {@link VersionFolders}). Paths without a {@code composeLine}
* folder (e.g. {@code compose/generic/default/...}) are used as-is.
*/ */
private List<String> composePathCandidates(String path, Map<String, Object> vars) { static List<String> composePathCandidates(String path, Map<String, Object> vars, Function<String, List<String>> folderLister) {
Object lineObj = vars.get("composeLine"); Object line = vars.get("composeLine");
Object versionObj = vars.get("version"); Object version = vars.get("version");
if (lineObj == null || versionObj == null) { String lineFolder = "/" + line + "/";
return List.of(path); if (line == null || version == null || !path.contains(lineFolder)) {
}
String line = lineObj.toString();
String[] parts = TbVersionUtils.extractStartingDigits(versionObj.toString()).split("\\.");
int baseFolderDepth = line.split("\\.").length;
// Dotted prefixes from the composeLine depth up to the full numeric version, e.g. ["4.3","4.3.1","4.3.1.2"].
List<String> dottedPrefixes = new ArrayList<>();
for (int i = baseFolderDepth; i <= parts.length; i++) {
dottedPrefixes.add(String.join(".", Arrays.copyOfRange(parts, 0, i)));
}
// Guard: version must share the composeLine prefix; otherwise just use the base path.
if (dottedPrefixes.isEmpty() || !dottedPrefixes.get(0).equals(line)) {
return List.of(path); return List.of(path);
} }
String parent = path.substring(0, path.indexOf(lineFolder));
String file = path.substring(path.indexOf(lineFolder) + lineFolder.length());
List<String> folders = VersionFolders.applicableTo(folderLister.apply(parent),
TbVersionUtils.extractStartingDigits(version.toString()));
return folders.isEmpty() ? List.of(path) : folders.stream().map(folder -> parent + "/" + folder + "/" + file).toList();
}
List<String> candidates = new ArrayList<>(); private static String edgeRepo(String version) {
for (int depth = dottedPrefixes.size(); depth >= 1; depth--) { return version == null ? null : EdgeEditionStyle.getEdgeEditionStyle(version).getDockerRepo();
String nestedLine = String.join("/", dottedPrefixes.subList(0, depth));
candidates.add(line.equals(nestedLine)
? path
: path.replaceFirst("/" + Pattern.quote(line) + "/",
"/" + Matcher.quoteReplacement(nestedLine) + "/"));
}
return candidates;
} }
private Map<String, Object> buildVars(AppVersionDescriptor d) { private Map<String, Object> buildVars(AppVersionDescriptor d) {
@ -226,6 +218,9 @@ public class AppTemplateMaterializer {
vars.put("nextVersion", d.getNextVersion()); vars.put("nextVersion", d.getNextVersion());
vars.put("nextEdgeVersion", d.getNextVersion()); vars.put("nextEdgeVersion", d.getNextVersion());
vars.put("nextGatewayVersion", d.getNextVersion()); vars.put("nextGatewayVersion", d.getNextVersion());
// edge image repo per version, as CE-style versions are published under tb-edge instead of tb-edge-pe
vars.put("edgeRepo", edgeRepo(d.getVersion()));
vars.put("nextEdgeRepo", edgeRepo(d.getNextVersion()));
vars.put("composeLine", composeLine(d.getVersion())); vars.put("composeLine", composeLine(d.getVersion()));
vars.put("requiresUpdateDb", d.isRequiresUpdateDb()); vars.put("requiresUpdateDb", d.isRequiresUpdateDb());
return vars; return vars;

32
application/src/main/java/org/thingsboard/server/service/agent/template/VersionFolders.java

@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.agent.template;
import org.thingsboard.common.util.TbVersionUtils;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
/**
* Version-named folders of the templates repo (e.g. {@code templates/since/4.4.1}, {@code compose/edge/4.4}): a
* folder applies to its own version and every later one, until a newer folder exists.
*/
final class VersionFolders {
private static final Pattern VERSION = Pattern.compile("\\d+(\\.\\d+)*");
private VersionFolders() {
}
/**
* The folder names that are plain versions not above {@code version}, newest first; other names are ignored.
*/
static List<String> applicableTo(Collection<String> folders, String version) {
return folders.stream()
.filter(folder -> VERSION.matcher(folder).matches())
.filter(folder -> TbVersionUtils.compare(folder, version) <= 0)
.sorted((a, b) -> TbVersionUtils.compare(b, a))
.toList();
}
}

87
application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java

@ -6,11 +6,9 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.codec.ServerSentEvent; import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClientRequestException; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo; import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
@ -21,8 +19,13 @@ import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.stats.TbApiUsageReportClient; import org.thingsboard.server.common.stats.TbApiUsageReportClient;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
import org.thingsboard.server.service.ai.transport.TbAiChannelUnavailableException;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.apiusage.TbApiUsageStateService; import org.thingsboard.server.service.apiusage.TbApiUsageStateService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks; import reactor.core.publisher.Sinks;
@ -41,8 +44,8 @@ class DefaultTbAiService implements TbAiService {
private final TbApiUsageStateService apiUsageStateService; private final TbApiUsageStateService apiUsageStateService;
private final TbApiUsageReportClient apiUsageReportClient; private final TbApiUsageReportClient apiUsageReportClient;
private final Optional<TbAiTokenProvider> tokenProvider; private final Optional<TbAiTokenProvider> tokenProvider;
private final TbAiClient tbAiClient;
private final TbAiSettings aiSettings; private final TbAiSettings aiSettings;
private final TbAiOperations operations;
@Override @Override
public JsonNode process(TbAiCall<TbAiResponse> call, SecurityUser user, boolean checkCredits) { public JsonNode process(TbAiCall<TbAiResponse> call, SecurityUser user, boolean checkCredits) {
@ -50,19 +53,23 @@ class DefaultTbAiService implements TbAiService {
if (checkCredits) { if (checkCredits) {
checkApiUsage(user); checkApiUsage(user);
} }
TbAiResponse response = call.apply(tbAiClient, createTokenProvider(user)); TbAiResponse response = call.apply(createCheckedTokenProvider(user));
return processResponse(response, user); return processResponse(response, user);
} }
@Override @Override
public Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> call, SecurityUser user) { public Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> call, SecurityUser user,
TbAiTurnLink link, boolean checkCredits) {
checkEnabled(); checkEnabled();
checkApiUsage(user); if (checkCredits) {
checkApiUsage(user);
}
TbAiClient.TokenProvider tokenProvider = createCheckedTokenProvider(user);
return Flux.defer(() -> { return Flux.defer(() -> {
// Eager subscribe so client cancel does not drop the trailing creditsUsed event. // Eager subscribe so client cancel does not drop the trailing creditsUsed event.
Sinks.Many<ServerSentEvent<String>> clientSink = Sinks.many().unicast().onBackpressureBuffer(); Sinks.Many<ServerSentEvent<String>> clientSink = Sinks.many().unicast().onBackpressureBuffer();
call.apply(tbAiClient, createTokenProvider(user)) call.apply(tokenProvider)
.timeout(Duration.ofSeconds(aiSettings.getSseInactivityTimeoutSeconds())) .timeout(Duration.ofSeconds(aiSettings.getSseInactivityTimeoutSeconds()))
.subscribe( .subscribe(
event -> { event -> {
@ -82,7 +89,8 @@ class DefaultTbAiService implements TbAiService {
clientSink::tryEmitComplete clientSink::tryEmitComplete
); );
return clientSink.asFlux(); Flux<ServerSentEvent<String>> client = clientSink.asFlux();
return link != null ? client.doOnCancel(link::clientLeft) : client;
}); });
} }
@ -98,7 +106,7 @@ class DefaultTbAiService implements TbAiService {
} }
try { try {
return JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_AND_ENUMS_JSON_MAPPER.treeToValue( return JacksonUtil.IGNORE_UNKNOWN_PROPERTIES_AND_ENUMS_JSON_MAPPER.treeToValue(
process(TbAiClient::getApiUsageInfo, user, false), ApiUsageInfo.class); process(tokenProvider -> operations.execute(new TbAiOperation(ChannelProtocol.USAGE_GET, null), user, tokenProvider), user, false), ApiUsageInfo.class);
} catch (Exception e) { } catch (Exception e) {
log.warn("[{}][{}] Couldn't get AI API usage info", user.getTenantId(), user.getId(), e); log.warn("[{}][{}] Couldn't get AI API usage info", user.getTenantId(), user.getId(), e);
return new ApiUsageInfo(Map.of(), 0); return new ApiUsageInfo(Map.of(), 0);
@ -111,8 +119,14 @@ class DefaultTbAiService implements TbAiService {
} }
} }
private TbAiClient.TokenProvider createTokenProvider(SecurityUser user) { /**
* Reads the token before the call reaches the channel pool, so a token the user may not have (e.g. AI is not in the
* subscription plan) fails the call with its own error rather than as a channel that cannot be opened, and is
* checked on every call rather than only when a channel opens.
*/
private TbAiClient.TokenProvider createCheckedTokenProvider(SecurityUser user) {
TbAiTokenProvider provider = tokenProvider.orElseThrow(() -> new ThingsboardRuntimeException("AI feature is not available", ThingsboardErrorCode.BAD_REQUEST_PARAMS)); TbAiTokenProvider provider = tokenProvider.orElseThrow(() -> new ThingsboardRuntimeException("AI feature is not available", ThingsboardErrorCode.BAD_REQUEST_PARAMS));
provider.getToken(user);
return TbAiTokenProviderFactory.userScoped(provider, user); return TbAiTokenProviderFactory.userScoped(provider, user);
} }
@ -139,43 +153,10 @@ class DefaultTbAiService implements TbAiService {
private static String toUserFriendlyMessage(Throwable e) { private static String toUserFriendlyMessage(Throwable e) {
if (e instanceof TimeoutException) { if (e instanceof TimeoutException) {
return "Request timed out"; return "Request timed out";
} else if (e instanceof WebClientRequestException) { } else if (e instanceof TbAiChannelUnavailableException) {
return "Service unavailable";
} else if (e instanceof WebClientResponseException wcre) {
return toUserFriendlyMessage(wcre);
}
return "Internal error";
}
private static String toUserFriendlyMessage(WebClientResponseException wcre) {
var status = HttpStatus.resolve(wcre.getStatusCode().value());
if (status == null) {
return "Internal error";
}
if (status == HttpStatus.UNAUTHORIZED || status == HttpStatus.FORBIDDEN) {
return status.getReasonPhrase();
}
String errorMessage = null;
try {
JsonNode errorResponse = JacksonUtil.toJsonNode(wcre.getResponseBodyAsString());
if (errorResponse.hasNonNull("message")) {
errorMessage = errorResponse.get("message").asText();
}
} catch (IllegalArgumentException ignored) {}
if (errorMessage != null) {
return errorMessage;
}
// fallback
if (status.is4xxClientError()) {
return "Invalid request";
}
if (status.is5xxServerError()) {
return "Service unavailable"; return "Service unavailable";
} else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) {
return e.getMessage();
} }
return "Internal error"; return "Internal error";
} }
@ -185,10 +166,20 @@ class DefaultTbAiService implements TbAiService {
if (response.isSuccess()) { if (response.isSuccess()) {
return response.getValue(); return response.getValue();
} else { } else {
throw new ThingsboardRuntimeException(response.getError(), ThingsboardErrorCode.GENERAL); throw new ThingsboardRuntimeException(response.getError(), toErrorCode(response.getStatus()));
} }
} }
static ThingsboardErrorCode toErrorCode(int status) {
return switch (status) {
case 400, 413, 415, 422 -> ThingsboardErrorCode.BAD_REQUEST_PARAMS;
case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND;
case 409 -> ThingsboardErrorCode.VERSION_CONFLICT;
case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS;
default -> ThingsboardErrorCode.GENERAL;
};
}
private void checkApiUsage(SecurityUser user) { private void checkApiUsage(SecurityUser user) {
if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) { if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) {
throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS);

8
application/src/main/java/org/thingsboard/server/service/ai/LocalTbAiTokenProvider.java

@ -37,7 +37,7 @@ import java.util.concurrent.TimeUnit;
@Component @Component
@TbCoreComponent @TbCoreComponent
@ConditionalOnExpression("'${TB_AI_JWT_SIGNING_KEY:}' != ''") @ConditionalOnExpression("'${ai.jwt.signing_key:}' != ''")
class LocalTbAiTokenProvider implements TbAiTokenProvider { class LocalTbAiTokenProvider implements TbAiTokenProvider {
private final TbAiTokenFactory tokenFactory; private final TbAiTokenFactory tokenFactory;
@ -47,9 +47,9 @@ class LocalTbAiTokenProvider implements TbAiTokenProvider {
// AI-related settings are read directly from environment variables, not yaml properties: they are // AI-related settings are read directly from environment variables, not yaml properties: they are
// managed-service settings, not operator-tunable configuration. // managed-service settings, not operator-tunable configuration.
public LocalTbAiTokenProvider(@Value("${TB_AI_JWT_ISSUER:local}") String issuer, public LocalTbAiTokenProvider(@Value("${ai.jwt.issuer:local}") String issuer,
@Value("${TB_AI_JWT_SIGNING_KEY}") String signingKey, @Value("${ai.jwt.signing_key}") String signingKey,
@Value("${TB_AI_JWT_EXPIRATION_TIME_MINUTES:60}") int expirationTimeMinutes, @Value("${ai.jwt.expiration_time_minutes:60}") int expirationTimeMinutes,
@Value("${cache.tbAiAccessTokens.timeToLiveInMinutes:60}") int cacheTtlMinutes, @Value("${cache.tbAiAccessTokens.timeToLiveInMinutes:60}") int cacheTtlMinutes,
@Value("${cache.tbAiAccessTokens.maxSize:20000}") int cacheMaxSize, @Value("${cache.tbAiAccessTokens.maxSize:20000}") int cacheMaxSize,
SystemSecurityService systemSecurityService, SystemSecurityService systemSecurityService,

47
application/src/main/java/org/thingsboard/server/service/ai/OnPremiseTbAiTokenProvider.java

@ -2,46 +2,30 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai; package org.thingsboard.server.service.ai;
import org.springframework.beans.factory.annotation.Value; import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
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;
import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.net.URI;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.function.Supplier; import java.util.function.Supplier;
// The handshake carries no Origin: the origin TB AI uses comes from the channel's hello and start frames.
@Component @Component
@TbCoreComponent @TbCoreComponent
@ConditionalOnExpression("'${TB_AI_JWT_SIGNING_KEY:}' == ''") @RequiredArgsConstructor
@ConditionalOnExpression("'${ai.jwt.signing_key:}' == ''")
class OnPremiseTbAiTokenProvider implements TbAiTokenProvider { class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
private final SubscriptionService subscriptionService; private final SubscriptionService subscriptionService;
private final SystemSecurityService systemSecurityService;
private final ProjectInfo projectInfo;
private final String coreBaseUrl;
OnPremiseTbAiTokenProvider(SubscriptionService subscriptionService,
SystemSecurityService systemSecurityService,
ProjectInfo projectInfo,
@Value("${TB_CORE_BASE_URL:}") String coreBaseUrl) {
this.subscriptionService = subscriptionService;
this.systemSecurityService = systemSecurityService;
this.projectInfo = projectInfo;
this.coreBaseUrl = coreBaseUrl;
}
@Override @Override
public String getToken(SecurityUser user) { public String getToken(SecurityUser user) {
@ -50,8 +34,7 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
@Override @Override
public Map<String, String> getAdditionalInfo(SecurityUser user) { public Map<String, String> getAdditionalInfo(SecurityUser user) {
String origin = StringUtils.isNotEmpty(coreBaseUrl) ? coreBaseUrl : resolveOrigin(user); return additionalInfo(user.getUuidId(), user.getTenantId());
return additionalInfo(user.getUuidId(), user.getTenantId(), origin);
} }
@Override @Override
@ -66,11 +49,7 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
@Override @Override
public Map<String, String> getAdditionalInfo(TenantId tenantId, UserId userId) { public Map<String, String> getAdditionalInfo(TenantId tenantId, UserId userId) {
// Background deletion tasks only need the Origin header to be present; the AI service never calls back return additionalInfo(userId.getId(), tenantId);
// to ThingsBoard for a delete. Skip TB_CORE_BASE_URL and the white-labeling chain (the tenant may already
// be gone by the time the task runs) and take the system-level general settings base URL instead.
String origin = systemSecurityService.getBaseUrl(tenantId, null, null);
return additionalInfo(userId.getId(), tenantId, origin);
} }
private String requireAiToken(Supplier<RuntimeException> onMissingToken) { private String requireAiToken(Supplier<RuntimeException> onMissingToken) {
@ -81,20 +60,10 @@ class OnPremiseTbAiTokenProvider implements TbAiTokenProvider {
return token; return token;
} }
private String resolveOrigin(SecurityUser user) { private Map<String, String> additionalInfo(UUID userId, TenantId tenantId) {
String origin = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null);
if ("localhost".equals(URI.create(origin).getHost())) {
throw new ThingsboardRuntimeException("Please configure the base URL under Login white labeling or General settings at the sysadmin level", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return origin;
}
private Map<String, String> additionalInfo(UUID userId, TenantId tenantId, String origin) {
return Map.of( return Map.of(
TbAiHeaders.USER_ID, userId.toString(), TbAiHeaders.USER_ID, userId.toString(),
TbAiHeaders.TENANT_ID, tenantId.getId().toString(), TbAiHeaders.TENANT_ID, tenantId.getId().toString()
TbAiHeaders.TB_VERSION, projectInfo.getProjectVersion(),
HttpHeaders.ORIGIN, origin
); );
} }

8
application/src/main/java/org/thingsboard/server/service/ai/TbAiConfiguration.java

@ -5,18 +5,16 @@ package org.thingsboard.server.service.ai;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@Configuration(proxyBeanMethods = false) @Configuration(proxyBeanMethods = false)
@TbCoreComponent @TbCoreComponent
class TbAiConfiguration { class TbAiConfiguration {
// TB_AI_BASE_URL is read directly from an environment variable, not a yaml property: it is a
// managed-service setting, not operator-tunable configuration.
@Bean @Bean
TbAiClient tbAiClient(@Value("${TB_AI_BASE_URL:https://ai.thingsboard.cloud}") String baseUrl) { TbAiChannelClient tbAiChannelClient(@Value("${ai.base_url:https://ai.thingsboard.cloud}") String baseUrl) {
return new TbAiClient(baseUrl); return new TbAiChannelClient(baseUrl);
} }
} }

15
application/src/main/java/org/thingsboard/server/service/ai/TbAiService.java

@ -7,6 +7,7 @@ import org.springframework.http.codec.ServerSentEvent;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.data.usage.ApiUsageInfo; import org.thingsboard.ai.common.data.usage.ApiUsageInfo;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import java.util.UUID; import java.util.UUID;
@ -19,7 +20,17 @@ public interface TbAiService {
JsonNode process(TbAiCall<TbAiClient.TbAiResponse> action, SecurityUser user, boolean checkCredits); JsonNode process(TbAiCall<TbAiClient.TbAiResponse> action, SecurityUser user, boolean checkCredits);
Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user); default Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user) {
return processStream(chatId, action, user, null, true);
}
/**
* Streams a chat turn to the browser. {@code link}, when given, is told when the browser stops listening, which
* ThingsBoard itself never does before the turn ends. {@code checkCredits} is false for following a turn that has
* already been paid for.
*/
Flux<ServerSentEvent<String>> processStream(UUID chatId, TbAiCall<Flux<ServerSentEvent<String>>> action, SecurityUser user,
TbAiTurnLink link, boolean checkCredits);
boolean isEnabled(); boolean isEnabled();
@ -28,7 +39,7 @@ public interface TbAiService {
@FunctionalInterface @FunctionalInterface
interface TbAiCall<T> { interface TbAiCall<T> {
T apply(TbAiClient client, TbAiClient.TokenProvider tokenProvider); T apply(TbAiClient.TokenProvider tokenProvider);
} }

5
application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java

@ -22,7 +22,10 @@ public interface AiChatService {
void deleteChat(UUID chatId, SecurityUser user); void deleteChat(UUID chatId, SecurityUser user);
Flux<ServerSentEvent<String>> sendChatMessage( Flux<ServerSentEvent<String>> sendChatMessage(
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, SecurityUser user UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
); );
Flux<ServerSentEvent<String>> resumeChat(UUID chatId, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user);
} }

57
application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java

@ -6,8 +6,16 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.http.codec.ServerSentEvent; import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTransport;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.ai.transport.TbAiTurnLink;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
@ -18,50 +26,61 @@ import java.util.UUID;
@RequiredArgsConstructor @RequiredArgsConstructor
class DefaultAiChatService implements AiChatService { class DefaultAiChatService implements AiChatService {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport;
private final TbAiOperations operations;
@Override @Override
public JsonNode createChat(JsonNode request, SecurityUser user) { public JsonNode createChat(JsonNode request, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.createChat(request, tokenProvider); new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public void updateChat(UUID chatId, JsonNode request, SecurityUser user) { public void updateChat(UUID chatId, JsonNode request, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> { tbAiService.process(tokenProvider -> operations.execute(
return client.updateChat(chatId, request, tokenProvider); new TbAiOperation(ChannelProtocol.CHAT_UPDATE, new ChatOperationRequest(chatId, request)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode listChats(SecurityUser user) { public JsonNode listChats(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.listChats(tokenProvider); new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode getChatMessages(UUID chatId, SecurityUser user) { public JsonNode getChatMessages(UUID chatId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.getChatMessages(chatId, tokenProvider); new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public void deleteChat(UUID chatId, SecurityUser user) { public void deleteChat(UUID chatId, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> { tbAiService.process(tokenProvider -> operations.execute(
return client.deleteChat(chatId, tokenProvider); new TbAiOperation(ChannelProtocol.CHAT_DELETE, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public Flux<ServerSentEvent<String>> sendChatMessage( public Flux<ServerSentEvent<String>> sendChatMessage(
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, SecurityUser user UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user
) { ) {
return tbAiService.processStream(chatId, (client, tokenProvider) -> { var link = new TbAiTurnLink();
return client.sendChatMessage(chatId, request, tbAccessToken, acceptLanguage, tokenProvider); return tbAiService.processStream(chatId, tokenProvider -> {
}, user); var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
return tbAiTransport.sendChatMessage(chatId, request, context, link);
}, user, link, true);
}
@Override
public Flux<ServerSentEvent<String>> resumeChat(UUID chatId, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user) {
var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
return tbAiTransport.resumeChat(chatId, context, link);
}, user, link, false);
} }
} }

2
application/src/main/java/org/thingsboard/server/service/ai/dashboard/AiDeviceDashboardService.java

@ -9,6 +9,6 @@ import java.util.UUID;
public interface AiDeviceDashboardService { public interface AiDeviceDashboardService {
JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, SecurityUser user); JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, String clientOrigin, SecurityUser user);
} }

13
application/src/main/java/org/thingsboard/server/service/ai/dashboard/DefaultAiDeviceDashboardService.java

@ -6,7 +6,12 @@ import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.DashboardOperationRequest;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID; import java.util.UUID;
@ -17,11 +22,13 @@ import java.util.UUID;
class DefaultAiDeviceDashboardService implements AiDeviceDashboardService { class DefaultAiDeviceDashboardService implements AiDeviceDashboardService {
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override @Override
public JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, SecurityUser user) { public JsonNode generateDashboard(UUID deviceId, JsonNode request, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> return tbAiService.process(tokenProvider -> operations.execute(
client.generateDashboard(deviceId, request, tbAccessToken, tokenProvider), user); new TbAiOperation(ChannelProtocol.DASHBOARD_GENERATE, new DashboardOperationRequest(deviceId, request)),
new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user);
} }
} }

24
application/src/main/java/org/thingsboard/server/service/ai/resource/AiResourceService.java

@ -0,0 +1,24 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.resource;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
public interface AiResourceService {
JsonNode getConfig(SecurityUser user);
JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException;
AiResourceContent download(UUID resourceId, SecurityUser user);
void delete(UUID resourceId, SecurityUser user);
record AiResourceContent(String name, String mediaType, byte[] data) {}
}

84
application/src/main/java/org/thingsboard/server/service/ai/resource/DefaultAiResourceService.java

@ -0,0 +1,84 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.resource;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ResourceOperationRequest;
import org.thingsboard.ai.common.channel.ResourceUploadRequest;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
@Service
@TbCoreComponent
@RequiredArgsConstructor
class DefaultAiResourceService implements AiResourceService {
private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override
public JsonNode getConfig(SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_CONFIG, null), user, tokenProvider), user, false);
}
@Override
public JsonNode upload(MultipartFile file, SecurityUser user) throws ThingsboardException {
if (file == null || file.isEmpty()) {
throw new ThingsboardException("The file is empty", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
long maxSize = getConfig(user).path("maxSize").asLong(0);
if (maxSize > 0 && file.getSize() > maxSize) {
throw new ThingsboardException("The file is too large: " + file.getOriginalFilename(), ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
String data;
try {
data = base64(file);
} catch (IOException e) {
throw new ThingsboardException("Failed to read the file", e, ThingsboardErrorCode.GENERAL);
}
var request = new ResourceUploadRequest(file.getOriginalFilename(), file.getContentType(), data);
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_UPLOAD, request), user, tokenProvider), user, false);
}
private static String base64(MultipartFile file) throws IOException {
var encoded = new ByteArrayOutputStream((int) Math.min(Integer.MAX_VALUE - 8, (file.getSize() + 2) / 3 * 4));
try (InputStream in = file.getInputStream(); OutputStream encoder = Base64.getEncoder().wrap(encoded)) {
in.transferTo(encoder);
}
return encoded.toString(StandardCharsets.ISO_8859_1);
}
@Override
public AiResourceContent download(UUID resourceId, SecurityUser user) {
JsonNode content = tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_GET, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
return new AiResourceContent(content.path("name").asText(), content.path("mediaType").asText(),
Base64.getDecoder().decode(content.path("data").asText()));
}
@Override
public void delete(UUID resourceId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.RESOURCE_DELETE, new ResourceOperationRequest(resourceId)), user, tokenProvider), user, false);
}
}

7
application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java

@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID; import java.util.UUID;
public interface AiSolutionService { public interface AiSolutionService {
@ -16,7 +17,7 @@ public interface AiSolutionService {
JsonNode getSolutions(SecurityUser user); JsonNode getSolutions(SecurityUser user);
JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user); JsonNode chat(UUID solutionId, SolutionStep step, String message, List<UUID> resources, SecurityUser user);
JsonNode createSolution(UUID solutionId, SecurityUser user); JsonNode createSolution(UUID solutionId, SecurityUser user);
@ -24,9 +25,9 @@ public interface AiSolutionService {
void clearStep(UUID solutionId, SolutionStep step, SecurityUser user); void clearStep(UUID solutionId, SolutionStep step, SecurityUser user);
JsonNode installSolution(UUID solutionId, String tbAccessToken, SecurityUser user); JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, SecurityUser user); JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
void deleteSolution(UUID solutionId, SecurityUser user); void deleteSolution(UUID solutionId, SecurityUser user);

77
application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java

@ -4,12 +4,25 @@ package org.thingsboard.server.service.ai.solution;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.ai.transport.TbAiTurnContext;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID; import java.util.UUID;
@Service @Service
@ -18,75 +31,73 @@ import java.util.UUID;
public class DefaultAiSolutionService implements AiSolutionService { public class DefaultAiSolutionService implements AiSolutionService {
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override @Override
public JsonNode startNew(SecurityUser user) { public JsonNode startNew(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.startNewSolution(tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode getSolution(UUID solutionId, SecurityUser user) { public JsonNode getSolution(UUID solutionId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.getSolution(solutionId, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_GET, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode getSolutions(SecurityUser user) { public JsonNode getSolutions(SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.getSolutions(tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_LIST, null), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode chat(UUID solutionId, SolutionStep step, String message, SecurityUser user) { public JsonNode chat(UUID solutionId, SolutionStep step, String message, List<UUID> resources, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { String text = StringUtils.defaultString(message);
return client.sendSolutionMessage(solutionId, step, message, tokenProvider); List<UUID> attached = CollectionsUtil.isEmpty(resources) ? null : resources;
}, user); if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
} }
@Override @Override
public JsonNode createSolution(UUID solutionId, SecurityUser user) { public JsonNode createSolution(UUID solutionId, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.createSolution(solutionId, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_CREATE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user);
}, user);
} }
@Override @Override
public JsonNode updateData(UUID solutionId, String dataKey, JsonNode value, SecurityUser user) { public JsonNode updateData(UUID solutionId, String dataKey, JsonNode value, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.updateData(solutionId, dataKey, value, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_DATA_UPDATE, new SolutionDataRequest(solutionId, dataKey, value)), user, tokenProvider), user);
}, user);
} }
@Override @Override
public void clearStep(UUID solutionId, SolutionStep step, SecurityUser user) { public void clearStep(UUID solutionId, SolutionStep step, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> { tbAiService.process(tokenProvider -> operations.execute(
return client.clearStep(solutionId, step, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false);
}, user, false);
} }
@Override @Override
public JsonNode installSolution(UUID solutionId, String tbAccessToken, SecurityUser user) { public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.installSolution(solutionId, tbAccessToken, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_INSTALL, new SolutionOperationRequest(solutionId)),
}, user, false); new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user, false);
} }
@Override @Override
public JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, SecurityUser user) { public JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.uninstallSolution(solutionId, tbAccessToken, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_UNINSTALL, new SolutionOperationRequest(solutionId)),
}, user, false); new TbAiTurnContext(user, tbAccessToken, null, tokenProvider, clientOrigin)), user, false);
} }
@Override @Override
public void deleteSolution(UUID solutionId, SecurityUser user) { public void deleteSolution(UUID solutionId, SecurityUser user) {
tbAiService.process((client, tokenProvider) -> { tbAiService.process(tokenProvider -> operations.execute(
return client.deleteSolution(solutionId, tokenProvider); new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}, user, false);
} }
} }

9
application/src/main/java/org/thingsboard/server/service/ai/tool/DefaultAiToolService.java

@ -5,8 +5,11 @@ package org.thingsboard.server.service.ai.tool;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
@Service @Service
@ -15,12 +18,12 @@ import org.thingsboard.server.service.security.model.SecurityUser;
class DefaultAiToolService implements AiToolService { class DefaultAiToolService implements AiToolService {
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiOperations operations;
@Override @Override
public JsonNode resolveToolApproval(JsonNode decision, SecurityUser user) { public JsonNode resolveToolApproval(JsonNode decision, SecurityUser user) {
return tbAiService.process((client, tokenProvider) -> { return tbAiService.process(tokenProvider -> operations.execute(
return client.resolveToolApproval(decision, tokenProvider); new TbAiOperation(ChannelProtocol.TOOL_APPROVAL_RESOLVE, decision), user, tokenProvider), user, false);
}, user, false);
} }
} }

204
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java

@ -0,0 +1,204 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.OperationResult;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Runs one operation on a pooled channel and waits for its {@code operation.result}. An operation the channel did not
* start (a {@code draining} or {@code too_many_operations} refusal, or a 1001 close before any frame for it: TB AI
* closes with 1001 only when nothing runs on the connection) is retried once on a new channel; any other failure after
* it was sent is an error, so an operation never runs twice. That includes
* {@link ChannelProtocol#CLOSE_EXCHANGES_ABORTED}, the close of a connection whose running operations were aborted.
*/
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
class ChannelTbAiOperations {
static final Duration OPERATION_TIMEOUT = Duration.ofMinutes(30);
private final TbAiChannelPool pool;
private final TbAiRequestExecutor requestExecutor;
TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) {
boolean fresh = false;
for (int attempt = 1; ; attempt++) {
TbAiPooledConnection connection = acquire(context, fresh);
var call = new OperationCall(operation, context, connection);
try {
return call.run();
} catch (NotStartedException e) {
if (attempt >= 2) {
log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage());
return failure("Service unavailable");
}
log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage());
fresh = true;
}
}
}
private TbAiPooledConnection acquire(TbAiTurnContext context, boolean fresh) {
try {
return pool.acquire(context, fresh).get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new TbAiChannelUnavailableException("Interrupted while opening the AI channel", e);
} catch (TimeoutException e) {
throw new TbAiChannelUnavailableException("Timed out opening the AI channel", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof RuntimeException runtime) {
throw runtime;
}
throw new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(e), e);
}
}
static TbAiResponse failure(String message) {
return TbAiResponse.builder().success(false).error(message).build();
}
static TbAiResponse toResponse(OperationResult result) {
TbAiResponse response;
if (result.isSuccess()) {
response = TbAiResponse.builder().success(true).status(result.status()).value(result.body()).build();
} else {
JsonNode message = result.body() != null ? result.body().get("message") : null;
String error = message != null && message.isTextual() ? message.asText() : reasonPhrase(result.status());
response = TbAiResponse.builder().success(false).status(result.status()).error(error).build();
}
response.setCreditsUsed(result.creditsUsed());
return response;
}
private static String reasonPhrase(int status) {
HttpStatus resolved = HttpStatus.resolve(status);
return resolved != null ? resolved.getReasonPhrase() : "Internal error";
}
private static final class NotStartedException extends RuntimeException {
NotStartedException(String message) {
super(message, null, false, false);
}
}
private final class OperationCall implements TbAiChannelExchange {
private final TbAiOperation operation;
private final TbAiTurnContext context;
private final TbAiPooledConnection connection;
private final CompletableFuture<TbAiResponse> result = new CompletableFuture<>();
private final AtomicBoolean finished = new AtomicBoolean();
private volatile boolean frameSeen;
private volatile String op;
private OperationCall(TbAiOperation operation, TbAiTurnContext context, TbAiPooledConnection connection) {
this.operation = operation;
this.context = context;
this.connection = connection;
}
TbAiResponse run() {
ChannelFrame start = ChannelFrame.request(operation.type(), connection.codec().toPayload(operation.payload()))
.withOrigin(context.clientOrigin());
op = start.id();
try {
connection.start(this, start);
} catch (ChannelException e) {
finish();
throw new NotStartedException("channel closed before the operation was sent");
}
try {
return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return failure("Request interrupted");
} catch (TimeoutException e) {
return failure("Request timed out");
} catch (ExecutionException e) {
if (e.getCause() instanceof NotStartedException notStarted) {
throw notStarted;
}
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e));
return failure("Service unavailable");
} finally {
finish();
}
}
@Override
public void onFrame(TbAiPooledConnection frameConnection, ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.TB_REQUEST -> {
frameSeen = true;
requestExecutor.serve(frameConnection.session(), frame, frameConnection.codec(), context, frameConnection.maxFrameBytes());
}
case ChannelProtocol.OPERATION_RESULT -> result.complete(toResponse(
frameConnection.codec().fromPayload(frame.payload(), OperationResult.class)));
case ChannelProtocol.ERROR -> onError(frameConnection, frame);
default -> {
frameSeen = true;
log.debug("Ignoring AI channel frame '{}' during operation '{}'", frame.type(), operation.type());
}
}
} catch (ChannelException e) {
result.completeExceptionally(e);
}
}
@Override
public void onClose(int code, String reason) {
if (!frameSeen && code == ChannelProtocol.CLOSE_GOING_AWAY) {
result.completeExceptionally(new NotStartedException("channel closed [" + code + "] " + reason));
} else {
result.completeExceptionally(new ChannelException("AI channel closed [" + code + "] " + reason));
}
}
private void onError(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChannelError error = frameConnection.codec().fromPayload(frame.payload(), ChannelError.class);
if (ChannelError.DRAINING.equals(error.code())) {
frameConnection.retire();
result.completeExceptionally(new NotStartedException(error.message()));
} else if (ChannelError.TOO_MANY_OPERATIONS.equals(error.code())) {
result.completeExceptionally(new NotStartedException(error.message()));
} else {
log.warn("AI channel error during operation '{}' {}: {}", operation.type(), error.code(), error.message());
result.completeExceptionally(new CompletionException(new ChannelException(error.message())));
}
}
private void finish() {
if (finished.compareAndSet(false, true)) {
connection.finish(op, System.nanoTime());
}
}
}
}

280
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java

@ -0,0 +1,280 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatEventPayload;
import org.thingsboard.ai.common.channel.ChatTurnRequest;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.queue.util.TbCoreComponent;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import java.util.UUID;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or
* closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails
* the turn with "Service unavailable".
*/
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
class ChannelTbAiTransport implements TbAiTransport {
private static final String HEARTBEAT = "heartbeat";
private final TbAiChannelPool pool;
private final TbAiRequestExecutor requestExecutor;
@Override
public Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link) {
return turn(ChannelProtocol.CHAT_SEND, chatId, request, context, link);
}
@Override
public Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link) {
return turn(ChannelProtocol.CHAT_RESUME, chatId, null, context, link);
}
private Flux<ServerSentEvent<String>> turn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link) {
return Flux.create(sink -> {
var turn = new ChannelTurn(type, chatId, request, context, sink);
sink.onDispose(turn::abandon);
if (link != null) {
link.onClientLeft(turn::detach);
}
turn.start(false);
});
}
private static ServerSentEvent<String> errorEvent(String message) {
return ServerSentEvent.<String>builder()
.event("error")
.data(JacksonUtil.toString(JacksonUtil.newObjectNode().put("message", message)))
.build();
}
private final class ChannelTurn implements TbAiChannelExchange {
private final String type;
private final UUID chatId;
private final JsonNode request;
private final TbAiTurnContext context;
private final FluxSink<ServerSentEvent<String>> sink;
private final AtomicBoolean finished = new AtomicBoolean();
private volatile TbAiPooledConnection connection;
private volatile String op;
private volatile boolean frameSeen;
private volatile boolean retried;
private volatile boolean detached;
private ChannelTurn(String type, UUID chatId, JsonNode request, TbAiTurnContext context, FluxSink<ServerSentEvent<String>> sink) {
this.type = type;
this.chatId = chatId;
this.request = request;
this.context = context;
this.sink = sink;
}
void start(boolean fresh) {
pool.acquire(context, fresh).whenComplete((acquired, error) -> {
if (error != null) {
connectFailed(error instanceof CompletionException && error.getCause() != null ? error.getCause() : error);
} else {
attach(acquired);
}
});
}
void abandon() {
if (finished.get()) {
return;
}
TbAiPooledConnection current = connection;
if (current != null) {
try {
current.send(new ChannelFrame(ChannelProtocol.CANCEL, null, null, null, op));
} catch (ChannelException e) {
log.debug("[{}] Failed to cancel the AI turn: {}", chatId, e.getMessage());
}
}
end(null);
}
void detach() {
detached = true;
sendDetach();
}
private void sendDetach() {
TbAiPooledConnection current = connection;
if (finished.get() || current == null || !current.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) {
return;
}
try {
current.send(new ChannelFrame(ChannelProtocol.CHAT_DETACH, null, null, null, op));
} catch (ChannelException e) {
log.debug("[{}] Failed to detach from the AI turn: {}", chatId, e.getMessage());
}
}
@Override
public void onFrame(TbAiPooledConnection frameConnection, ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.CHAT_EVENT -> {
frameSeen = true;
onChatEvent(frameConnection, frame);
}
case ChannelProtocol.TB_REQUEST -> {
frameSeen = true;
requestExecutor.serve(frameConnection.session(), frame, frameConnection.codec(), context, frameConnection.maxFrameBytes());
}
case ChannelProtocol.TURN_END -> end(null);
case ChannelProtocol.ERROR -> onError(frameConnection, frame);
default -> log.debug("[{}] Ignoring AI channel frame '{}'", chatId, frame.type());
}
} catch (ChannelException e) {
log.warn("[{}] Malformed AI channel frame '{}': {}", chatId, frame.type(), e.getMessage());
end(errorEvent("Internal error"));
}
}
@Override
public void onClose(int code, String reason) {
if (finished.get()) {
return;
}
if (!frameSeen && code == ChannelProtocol.CLOSE_GOING_AWAY && retry()) {
return;
}
if (!frameSeen) {
fail(new TbAiChannelUnavailableException("AI channel closed before the turn started [" + code + "] " + reason, null));
} else if (code == ChannelProtocol.CLOSE_NORMAL) {
end(null);
} else {
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason);
end(errorEvent("Service unavailable"));
}
}
private void connectFailed(Throwable error) {
if (error instanceof TbAiChannelRejectedException rejected) {
end(errorEvent(rejected.getMessage()));
} else if (error instanceof TbAiChannelUnavailableException unavailable) {
fail(unavailable);
} else {
fail(new TbAiChannelUnavailableException("Cannot open the AI channel: " + error.getMessage(), error));
}
}
private void attach(TbAiPooledConnection acquired) {
if (sink.isCancelled() || finished.get()) {
acquired.unreserve(System.nanoTime());
return;
}
if (ChannelProtocol.CHAT_RESUME.equals(type) && !acquired.supports(ChannelProtocol.TURN_RESUME_CAPABILITY)) {
acquired.unreserve(System.nanoTime());
end(null);
return;
}
ChannelFrame start = ChannelFrame.request(type,
acquired.codec().toPayload(new ChatTurnRequest(chatId, request, context.acceptLanguage())))
.withOrigin(context.clientOrigin());
op = start.id();
connection = acquired;
try {
acquired.start(this, start);
if (detached) {
sendDetach();
}
} catch (ChannelException e) {
connection = null;
acquired.finish(op, System.nanoTime());
if (!retry()) {
fail(new TbAiChannelUnavailableException("AI channel closed before the turn started", e));
}
}
}
private void onChatEvent(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChatEventPayload event = frameConnection.codec().fromPayload(frame.payload(), ChatEventPayload.class);
if (HEARTBEAT.equals(event.name())) {
sink.next(ServerSentEvent.<String>builder().comment(HEARTBEAT).build());
return;
}
sink.next(ServerSentEvent.<String>builder()
.event(event.name())
.data(event.data() != null ? event.data().toString() : null)
.build());
}
private void onError(TbAiPooledConnection frameConnection, ChannelFrame frame) {
ChannelError error = frameConnection.codec().fromPayload(frame.payload(), ChannelError.class);
boolean notStarted = ChannelError.DRAINING.equals(error.code()) || ChannelError.TOO_MANY_OPERATIONS.equals(error.code());
if (ChannelError.DRAINING.equals(error.code())) {
frameConnection.retire();
}
if (notStarted && !frameSeen) {
release();
if (retry()) {
return;
}
fail(new TbAiChannelUnavailableException("AI channel refused the turn: " + error.message(), null));
return;
}
log.warn("[{}] AI channel error {}: {}", chatId, error.code(), error.message());
end(errorEvent("Internal error"));
}
private boolean retry() {
if (retried || finished.get()) {
return false;
}
retried = true;
log.debug("[{}] AI turn was not started, retrying on a new channel", chatId);
connection = null;
start(true);
return true;
}
private void fail(RuntimeException error) {
if (finished.compareAndSet(false, true)) {
release();
sink.error(error);
}
}
private void end(ServerSentEvent<String> lastEvent) {
if (finished.compareAndSet(false, true)) {
release();
if (lastEvent != null) {
sink.next(lastEvent);
}
sink.complete();
}
}
private void release() {
TbAiPooledConnection current = connection;
if (current != null) {
connection = null;
current.finish(op, System.nanoTime());
}
}
}
}

16
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelExchange.java

@ -0,0 +1,16 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.thingsboard.ai.common.channel.ChannelFrame;
/**
* One chat turn or operation on a pooled channel. Callbacks run on the channel's I/O thread and must not block.
*/
interface TbAiChannelExchange {
void onFrame(TbAiPooledConnection connection, ChannelFrame frame);
void onClose(int code, String reason);
}

359
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java

@ -0,0 +1,359 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.common.util.ThingsBoardThreadFactory;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.install.ProjectInfo;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.LongSupplier;
/**
* Channels to TB AI on this tb-core node, one per user in the common case: each call carries its own client origin.
* <ul>
* <li>Calls of one user share a channel; concurrent first calls share one handshake.</li>
* <li>At most {@code maxConnections} pooled channels per node. When full, the least recently used idle channel is
* closed; if none is idle the call gets a transient channel that closes after it, so a full pool never delays or
* refuses a call.</li>
* <li>One sweeper closes channels idle for {@code idleTimeout} and retires channels older than {@code maxAge}, which
* bounds how long a revoked token or changed subscription keeps working on an open channel.</li>
* <li>Background calls (housekeeper deletions) always use transient channels.</li>
* <li>After {@link #shutdown} no channel opens, so a call refused by the shutdown is not retried on a new one.</li>
* </ul>
*/
@Slf4j
@Component
@TbCoreComponent
class TbAiChannelPool {
record PoolKey(TenantId tenantId, UserId userId) {}
private static final Duration SWEEP_INTERVAL = Duration.ofSeconds(5);
private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(15);
private static final int MAX_ACQUIRE_ATTEMPTS = 3;
private final TbAiChannelClient channelClient;
private final String tbVersion;
private final int maxConnections;
private final int maxOperationsPerConnection;
private final long idleTimeoutNanos;
private final long maxAgeNanos;
private final LongSupplier nanoClock;
private final ConcurrentMap<PoolKey, Group> groups = new ConcurrentHashMap<>();
private final AtomicInteger pooledConnections = new AtomicInteger();
private final ScheduledExecutorService sweeper;
private volatile boolean shutdown;
@Autowired
TbAiChannelPool(TbAiChannelClient channelClient,
ProjectInfo projectInfo,
@Value("${ai.channel.pool.max_connections:2000}") int maxConnections,
@Value("${ai.channel.pool.max_operations_per_connection:20}") int maxOperationsPerConnection,
@Value("${ai.channel.pool.idle_timeout_seconds:60}") long idleTimeoutSeconds,
@Value("${ai.channel.pool.max_age_minutes:10}") long maxAgeMinutes) {
this(channelClient, projectInfo.getProjectVersion(), maxConnections, maxOperationsPerConnection,
Duration.ofSeconds(idleTimeoutSeconds), Duration.ofMinutes(maxAgeMinutes), System::nanoTime, true);
}
TbAiChannelPool(TbAiChannelClient channelClient, String tbVersion, int maxConnections, int maxOperationsPerConnection,
Duration idleTimeout, Duration maxAge, LongSupplier nanoClock, boolean startSweeper) {
this.channelClient = channelClient;
this.tbVersion = tbVersion;
this.maxConnections = maxConnections;
this.maxOperationsPerConnection = maxOperationsPerConnection;
this.idleTimeoutNanos = idleTimeout.toNanos();
this.maxAgeNanos = maxAge.toNanos();
this.nanoClock = nanoClock;
if (startSweeper) {
this.sweeper = Executors.newSingleThreadScheduledExecutor(ThingsBoardThreadFactory.forName("tb-ai-channel-pool"));
this.sweeper.scheduleWithFixedDelay(this::sweep, SWEEP_INTERVAL.toMillis(), SWEEP_INTERVAL.toMillis(), TimeUnit.MILLISECONDS);
} else {
this.sweeper = null;
}
}
/**
* A channel with one slot reserved for the caller, who must give it back through
* {@link TbAiPooledConnection#finish} or {@link TbAiPooledConnection#unreserve}. {@code fresh} skips the open
* channels, for a retry after a channel refused the call. Fails with {@link TbAiChannelUnavailableException} or
* {@link TbAiChannelRejectedException}.
*/
CompletableFuture<TbAiPooledConnection> acquire(TbAiTurnContext context, boolean fresh) {
return acquire(context, fresh, 1);
}
private CompletableFuture<TbAiPooledConnection> acquire(TbAiTurnContext context, boolean fresh, int attempt) {
if (shutdown) {
return CompletableFuture.failedFuture(new TbAiChannelUnavailableException("Server is shutting down", null));
}
if (context.isBackground()) {
return connect(context, null, false);
}
PoolKey key = new PoolKey(context.tenantId(), context.userId());
CompletableFuture<TbAiPooledConnection> pending = null;
if (!fresh) {
Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) {
long now = nanoClock.getAsLong();
for (int i = group.connections.size() - 1; i >= 0; i--) {
TbAiPooledConnection connection = group.connections.get(i);
if (connection.tryReserve(now)) {
return CompletableFuture.completedFuture(connection);
}
}
pending = group.connecting;
}
}
if (pending != null) {
return pending.thenCompose(connection -> connection.tryReserve(nanoClock.getAsLong())
? CompletableFuture.completedFuture(connection)
: retryAcquire(context, attempt));
}
boolean pooled = tryTakePoolSlot() || (evictIdleConnection() && tryTakePoolSlot());
if (!pooled) {
log.debug("[{}] AI channel pool is full ({}), using a transient channel", key, maxConnections);
return connect(context, key, false);
}
Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) {
if (!fresh) {
CompletableFuture<TbAiPooledConnection> started = group.connecting;
if (started != null) {
pooledConnections.decrementAndGet();
return started.thenCompose(connection -> connection.tryReserve(nanoClock.getAsLong())
? CompletableFuture.completedFuture(connection)
: retryAcquire(context, attempt));
}
}
CompletableFuture<TbAiPooledConnection> ready = connect(context, key, true);
group.connecting = ready;
ready.whenComplete((connection, error) -> {
synchronized (group) {
if (group.connecting == ready) {
group.connecting = null;
}
// A channel closed right after hello has already left the pool (removed() then found nothing).
if (connection != null && !connection.isRemoved()) {
group.connections.add(connection);
}
}
});
return ready;
}
}
private CompletableFuture<TbAiPooledConnection> retryAcquire(TbAiTurnContext context, int attempt) {
if (attempt >= MAX_ACQUIRE_ATTEMPTS) {
return CompletableFuture.failedFuture(new TbAiChannelUnavailableException("No AI channel with free capacity", null));
}
return acquire(context, true, attempt + 1);
}
/**
* Opens a channel; its hello carries the opening call's origin, which TB AI uses for start frames without one. One
* timer bounds the whole handshake: when it fires the connection leaves the pool at once, and a WebSocket upgrade
* that completes later is closed as soon as its session arrives (see {@link TbAiPooledConnection#opened}).
*/
private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) {
var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled,
maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong());
channelClient.connect(handshakeTokenProvider(context), connection)
.subscribeOn(Schedulers.boundedElastic())
.subscribe(connection::opened, error -> connection.failed(toConnectError(error)));
return connection.ready()
.orTimeout(CONNECT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)
.whenComplete((ready, error) -> {
if (error != null) {
connection.failed(error);
}
})
.exceptionallyCompose(error -> CompletableFuture.failedFuture(unwrap(error)));
}
void release(TbAiPooledConnection connection) {
if (connection.releasePoolSlot()) {
pooledConnections.decrementAndGet();
}
}
/**
* Called once when a channel closes or fails to open.
*/
void removed(TbAiPooledConnection connection) {
Group group = connection.key() != null ? groups.get(connection.key()) : null;
if (group != null) {
synchronized (group) {
group.connections.remove(connection);
}
}
release(connection);
}
int pooledConnections() {
return pooledConnections.get();
}
void sweep() {
try {
long now = nanoClock.getAsLong();
int closed = 0;
for (Map.Entry<PoolKey, Group> entry : groups.entrySet()) {
List<TbAiPooledConnection> snapshot;
synchronized (entry.getValue()) {
snapshot = new ArrayList<>(entry.getValue().connections);
}
for (TbAiPooledConnection connection : snapshot) {
if (connection.sweep(now, idleTimeoutNanos, maxAgeNanos)) {
closed++;
}
}
groups.computeIfPresent(entry.getKey(), (key, group) -> {
synchronized (group) {
return group.connections.isEmpty() && group.connecting == null ? null : group;
}
});
}
if (closed > 0 || log.isTraceEnabled()) {
log.debug("AI channel pool: {} pooled channel(s), {} user(s), {} closed as idle or aged",
pooledConnections.get(), groups.size(), closed);
}
} catch (Exception e) {
log.warn("Failed to sweep the AI channel pool", e);
}
}
@PreDestroy
void shutdown() {
shutdown = true;
if (sweeper != null) {
sweeper.shutdownNow();
}
groups.values().forEach(group -> {
List<TbAiPooledConnection> snapshot;
synchronized (group) {
snapshot = new ArrayList<>(group.connections);
}
snapshot.forEach(connection -> connection.close(ChannelProtocol.CLOSE_GOING_AWAY, "Server is shutting down"));
});
}
private boolean tryTakePoolSlot() {
while (true) {
int current = pooledConnections.get();
if (current >= maxConnections) {
return false;
}
if (pooledConnections.compareAndSet(current, current + 1)) {
return true;
}
}
}
private boolean evictIdleConnection() {
TbAiPooledConnection oldest = null;
long oldestUse = Long.MAX_VALUE;
for (Group group : groups.values()) {
synchronized (group) {
for (TbAiPooledConnection connection : group.connections) {
if (connection.isIdle() && connection.lastUsedNanos() < oldestUse) {
oldest = connection;
oldestUse = connection.lastUsedNanos();
}
}
}
}
if (oldest == null || !oldest.evictIfIdle()) {
return false;
}
// Free the evicted channel's slot now rather than when its close is reported, so the caller can take it.
release(oldest);
return true;
}
private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) {
TbAiClient.TokenProvider delegate = context.tokenProvider();
String acceptLanguage = context.acceptLanguage();
return new TbAiClient.TokenProvider() {
@Override
public String getToken() {
return delegate.getToken();
}
@Override
public Map<String, String> getAdditionalInfo() {
var headers = new HashMap<>(delegate.getAdditionalInfo());
headers.put(TbAiHeaders.TB_VERSION, tbVersion);
if (acceptLanguage != null && !acceptLanguage.isBlank()) {
headers.put(HttpHeaders.ACCEPT_LANGUAGE, acceptLanguage);
}
return headers;
}
};
}
private static Throwable toConnectError(Throwable error) {
for (Throwable cause : ExceptionUtils.getThrowableList(error)) {
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) {
int status = handshake.response().status().code();
if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) {
return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase());
}
}
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {
return cause;
}
}
return new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(error), error);
}
private static Throwable unwrap(Throwable error) {
Throwable cause = error;
while ((cause instanceof java.util.concurrent.CompletionException || cause instanceof java.util.concurrent.ExecutionException)
&& cause.getCause() != null) {
cause = cause.getCause();
}
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {
return cause;
}
if (cause instanceof java.util.concurrent.TimeoutException) {
return new TbAiChannelUnavailableException("AI channel handshake timed out", cause);
}
return new TbAiChannelUnavailableException("Cannot open the AI channel: " + ExceptionUtils.getRootCauseMessage(cause), cause);
}
private static final class Group {
private final List<TbAiPooledConnection> connections = new ArrayList<>();
private CompletableFuture<TbAiPooledConnection> connecting;
}
}

14
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java

@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user.
*/
public class TbAiChannelRejectedException extends RuntimeException {
public TbAiChannelRejectedException(String reason) {
super(reason);
}
}

11
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelUnavailableException.java

@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
public class TbAiChannelUnavailableException extends RuntimeException {
public TbAiChannelUnavailableException(String message, Throwable cause) {
super(message, cause);
}
}

8
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperation.java

@ -0,0 +1,8 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* A typed channel operation: its frame type (a {@code ChannelProtocol} constant) and its request payload DTO, or null.
*/
public record TbAiOperation(String type, Object payload) {}

42
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java

@ -0,0 +1,42 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService;
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class TbAiOperations {
private final ChannelTbAiOperations channelOperations;
private final SystemSecurityService systemSecurityService;
/**
* For a call made on the user's behalf with no browser request at hand and no callback into ThingsBoard.
*/
public TbAiResponse execute(TbAiOperation operation, SecurityUser user, TbAiClient.TokenProvider tokenProvider) {
String clientOrigin = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), null);
return execute(operation, new TbAiTurnContext(user, null, null, tokenProvider, clientOrigin));
}
public TbAiResponse execute(TbAiOperation operation, TbAiTurnContext context) {
try {
return channelOperations.execute(operation, context);
} catch (TbAiChannelUnavailableException e) {
log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage());
return ChannelTbAiOperations.failure("Service unavailable");
} catch (TbAiChannelRejectedException e) {
return ChannelTbAiOperations.failure(e.getMessage());
}
}
}

339
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java

@ -0,0 +1,339 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelFrameListener;
import org.thingsboard.ai.common.channel.ChannelHello;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* One WebSocket to TB AI, shared by the turns and operations of one user. Capacity is reserved before an exchange
* starts ({@link #tryReserve}) and released when it ends ({@link #finish}); a retiring connection takes no new work
* and closes once its last exchange ends. Exchanges are told apart by their op, the id of their start frame.
* <p>
* Lock order: the pool's group lock may be held while calling into a connection, never the reverse, and a connection
* never closes its session while holding its own lock.
*/
@Slf4j
final class TbAiPooledConnection implements ChannelFrameListener {
// Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell
// before using it that this ThingsBoard understands it.
static final List<String> CLIENT_CAPABILITIES = List.of();
private final TbAiChannelPool.PoolKey key;
private final String origin;
private final boolean pooled;
private final int maxOperations;
private final ChannelFrameCodec codec;
private final TbAiChannelPool pool;
private final long createdNanos;
private final CompletableFuture<TbAiPooledConnection> ready = new CompletableFuture<>();
private final Map<String, TbAiChannelExchange> exchanges = new ConcurrentHashMap<>();
private final AtomicBoolean removed = new AtomicBoolean();
private final AtomicBoolean poolSlotHeld;
private final Object lock = new Object();
private int reserved;
private boolean retiring;
private long lastUsedNanos;
private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
private volatile List<String> serverCapabilities = List.of();
/**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
* take its place.
*/
TbAiPooledConnection(TbAiChannelPool.PoolKey key, String origin, boolean pooled, int maxOperations,
ChannelFrameCodec codec, TbAiChannelPool pool, long nowNanos) {
this.key = key;
this.origin = origin;
this.pooled = pooled;
this.maxOperations = maxOperations;
this.codec = codec;
this.pool = pool;
this.createdNanos = nowNanos;
this.lastUsedNanos = nowNanos;
this.reserved = 1;
this.retiring = !pooled;
this.poolSlotHeld = new AtomicBoolean(pooled);
}
/**
* True exactly once for a pooled connection, when it gives its place in the pool's connection count back.
*/
boolean releasePoolSlot() {
return poolSlotHeld.compareAndSet(true, false);
}
boolean isRemoved() {
return removed.get();
}
TbAiChannelPool.PoolKey key() {
return key;
}
boolean isPooled() {
return pooled;
}
int maxFrameBytes() {
return maxFrameBytes;
}
ChannelSession session() {
return session;
}
ChannelFrameCodec codec() {
return codec;
}
CompletableFuture<TbAiPooledConnection> ready() {
return ready;
}
/**
* Whether TB AI listed {@code capability} in its hello. Frames a capability adds must not be sent without it: an
* older TB AI closes the connection on a frame type it does not know.
*/
boolean supports(String capability) {
return serverCapabilities.contains(capability);
}
/**
* The session arrived. If the handshake already failed (the connect timed out), the session is closed: it is
* stored first and {@link #failed} closes whatever is stored after failing {@code ready}, so one of the two always
* sees the other and the channel never stays open outside the pool.
*/
void opened(ChannelSession openedSession) {
session = openedSession;
if (ready.isDone()) {
close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
return;
}
try {
openedSession.send(ChannelFrame.of(ChannelProtocol.HELLO, codec.toPayload(
new ChannelHello(ChannelProtocol.VERSION, CLIENT_CAPABILITIES, origin, null))));
} catch (ChannelException e) {
ready.completeExceptionally(new TbAiChannelUnavailableException("Cannot send hello: " + e.getMessage(), e));
}
}
/**
* The handshake failed or timed out: the connection leaves the pool now and its session, if it has one or gets
* one later, is closed.
*/
void failed(Throwable error) {
ready.completeExceptionally(error);
markRemoved();
close(ChannelProtocol.CLOSE_NORMAL, "Handshake failed");
}
boolean tryReserve(long nowNanos) {
synchronized (lock) {
if (retiring || session == null || !session.isOpen() || reserved >= maxOperations) {
return false;
}
reserved++;
lastUsedNanos = nowNanos;
return true;
}
}
/**
* Starts an exchange on a reserved slot; its op is the id of {@code startFrame}.
*/
void start(TbAiChannelExchange exchange, ChannelFrame startFrame) {
exchanges.put(startFrame.id(), exchange);
try {
session.send(startFrame);
} catch (ChannelException e) {
exchanges.remove(startFrame.id());
throw e;
}
}
void send(ChannelFrame frame) {
session.send(frame);
}
/**
* Ends the exchange started with {@code op} and gives back its reservation; frames for it that still arrive are
* dropped.
*/
void finish(String op, long nowNanos) {
exchanges.remove(op);
unreserve(nowNanos);
}
/**
* Gives back a reservation that never started an exchange.
*/
void unreserve(long nowNanos) {
boolean close;
synchronized (lock) {
reserved = Math.max(0, reserved - 1);
lastUsedNanos = nowNanos;
close = retiring && reserved == 0;
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Done");
}
}
void retire() {
boolean close;
synchronized (lock) {
retiring = true;
close = reserved == 0;
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Retired");
}
}
/**
* Closes the connection when it has been idle for {@code idleNanos} or is older than {@code maxAgeNanos}; an old
* connection still in use stops taking work and closes after its last exchange.
*/
boolean sweep(long nowNanos, long idleNanos, long maxAgeNanos) {
boolean close = false;
synchronized (lock) {
boolean aged = nowNanos - createdNanos >= maxAgeNanos;
if (reserved == 0 && (aged || nowNanos - lastUsedNanos >= idleNanos)) {
retiring = true;
close = true;
} else if (aged) {
retiring = true;
}
}
if (close) {
close(ChannelProtocol.CLOSE_NORMAL, "Idle");
}
return close;
}
/**
* Closes the connection if nothing runs on it, to make room in a full pool.
*/
boolean evictIfIdle() {
synchronized (lock) {
if (reserved != 0 || retiring) {
return false;
}
retiring = true;
}
close(ChannelProtocol.CLOSE_NORMAL, "Evicted");
return true;
}
long lastUsedNanos() {
synchronized (lock) {
return lastUsedNanos;
}
}
boolean isIdle() {
synchronized (lock) {
return reserved == 0 && !retiring;
}
}
void close(int code, String reason) {
ChannelSession current = session;
if (current != null && current.isOpen()) {
current.close(code, reason);
}
}
@Override
public void onFrame(ChannelSession frameSession, ChannelFrame frame) {
if (!ready.isDone()) {
onHandshakeFrame(frame);
return;
}
if (frame.op() == null) {
onConnectionFrame(frame);
return;
}
TbAiChannelExchange exchange = exchanges.get(frame.op());
if (exchange == null) {
log.debug("[{}] Dropping AI channel frame '{}' for finished operation '{}'", key, frame.type(), frame.op());
return;
}
exchange.onFrame(this, frame);
}
@Override
public void onClose(ChannelSession closedSession, int code, String reason) {
synchronized (lock) {
retiring = true;
}
ready.completeExceptionally(new TbAiChannelUnavailableException(
"AI channel closed before hello [" + code + "] " + reason, null));
markRemoved();
List<TbAiChannelExchange> running = List.copyOf(exchanges.values());
exchanges.clear();
running.forEach(exchange -> exchange.onClose(code, reason));
}
private void onHandshakeFrame(ChannelFrame frame) {
try {
switch (frame.type()) {
case ChannelProtocol.HELLO -> {
ChannelHello hello = codec.fromPayload(frame.payload(), ChannelHello.class);
if (hello.maxFrameBytes() != null && hello.maxFrameBytes() > 0 && hello.maxFrameBytes() < Integer.MAX_VALUE) {
maxFrameBytes = hello.maxFrameBytes().intValue();
}
if (hello.capabilities() != null) {
serverCapabilities = List.copyOf(hello.capabilities());
}
ready.complete(this);
}
case ChannelProtocol.ERROR -> {
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class);
ready.completeExceptionally(new TbAiChannelUnavailableException("AI channel refused: " + error.message(), null));
close(ChannelProtocol.CLOSE_NORMAL, "Error received");
}
default -> log.debug("[{}] Ignoring AI channel frame '{}' before hello", key, frame.type());
}
} catch (ChannelException e) {
ready.completeExceptionally(new TbAiChannelUnavailableException("Malformed AI channel hello: " + e.getMessage(), e));
close(ChannelProtocol.CLOSE_PROTOCOL_ERROR, e.getMessage());
}
}
private void onConnectionFrame(ChannelFrame frame) {
if (ChannelProtocol.ERROR.equals(frame.type())) {
ChannelError error = codec.fromPayload(frame.payload(), ChannelError.class);
log.warn("[{}] AI channel error {}: {}", key, error.code(), error.message());
close(ChannelProtocol.CLOSE_NORMAL, "Error received");
} else {
log.debug("[{}] Ignoring AI channel frame '{}' without op", key, frame.type());
}
}
private void markRemoved() {
if (removed.compareAndSet(false, true)) {
pool.removed(this);
}
}
}

260
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiRequestExecutor.java

@ -0,0 +1,260 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBufferLimitException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.thingsboard.ai.common.channel.ChannelBodies;
import org.thingsboard.ai.common.channel.ChannelError;
import org.thingsboard.ai.common.channel.ChannelException;
import org.thingsboard.ai.common.channel.ChannelFrame;
import org.thingsboard.ai.common.channel.ChannelFrameCodec;
import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChannelSession;
import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.channel.TbHttpRequest;
import org.thingsboard.ai.common.channel.TbHttpResponse;
import org.thingsboard.server.config.ThingsboardSecurityConfiguration;
import org.thingsboard.server.queue.util.TbCoreComponent;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import javax.net.ssl.SSLException;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
@Slf4j
@Component
@TbCoreComponent
public class TbAiRequestExecutor {
static final String INVALID_REQUEST = "invalid_request";
static final String REQUEST_FAILED = "request_failed";
static final String TIMEOUT = "timeout";
static final String TOO_LARGE = "too_large";
private static final String API_PREFIX = "/api/";
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(35);
private static final Set<HttpMethod> ALLOWED_METHODS = Set.of(
HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE);
private static final Set<String> DROPPED_REQUEST_HEADERS = Set.of(
"host", "authorization", "x-authorization", "cookie", "connection", "content-length", "transfer-encoding",
"x-forwarded-host", "x-forwarded-proto", "x-forwarded-port", "x-forwarded-for");
private static final Set<String> DROPPED_RESPONSE_HEADERS = Set.of(
"set-cookie", "content-length", "transfer-encoding", "connection");
private static final String X_FORWARDED_HOST = "X-Forwarded-Host";
private static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
private static final String X_FORWARDED_PORT = "X-Forwarded-Port";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";
private final String baseUrl;
private final WebClient webClient;
@Autowired
public TbAiRequestExecutor(@Value("${server.address:0.0.0.0}") String address,
@Value("${server.port:8080}") int port,
@Value("${server.ssl.enabled:false}") boolean sslEnabled) {
this(loopbackUrl(address, port, sslEnabled), sslEnabled ? insecureLoopbackSslContext() : null);
}
TbAiRequestExecutor(String baseUrl, SslContext sslContext) {
this.baseUrl = baseUrl;
HttpClient httpClient = sslContext != null
? HttpClient.create().secure(spec -> spec.sslContext(sslContext))
: HttpClient.create();
this.webClient = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES))
.build();
}
public Mono<ChannelFrame> execute(ChannelFrame frame, ChannelFrameCodec codec, TbAiTurnContext context, int maxBodyBytes) {
TbHttpRequest request;
try {
request = codec.fromPayload(frame.payload(), TbHttpRequest.class);
} catch (RuntimeException e) {
return Mono.just(error(frame, codec, INVALID_REQUEST, "Malformed tb.request payload"));
}
String invalidReason = context.tbAccessToken() == null
? "ThingsBoard access is not available for this operation"
: validate(request);
if (invalidReason != null) {
log.warn("[{}][{}] Rejected AI request {} {}: {}", context.tenantId(), context.userId(),
request.method(), request.path(), invalidReason);
return Mono.just(error(frame, codec, INVALID_REQUEST, invalidReason));
}
Duration timeout = request.timeoutMs() != null && request.timeoutMs() > 0 ? Duration.ofMillis(request.timeoutMs()) : DEFAULT_TIMEOUT;
String query = StringUtils.isEmpty(request.query()) ? "" : "?" + request.query();
byte[] body = ChannelBodies.decode(request.body(), request.bodyEncoding());
WebClient.RequestBodySpec spec = webClient.method(HttpMethod.valueOf(request.method().toUpperCase(Locale.ROOT)))
.uri(URI.create(baseUrl + request.path() + query))
.headers(headers -> {
copyRequestHeaders(request.headers(), headers);
forwardedHeaders(context).forEach(headers::set);
headers.set(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, context.tbAccessToken());
});
WebClient.RequestHeadersSpec<?> withBody = body.length > 0 ? spec.bodyValue(body) : spec;
return withBody.exchangeToMono(response -> response.bodyToMono(byte[].class)
.defaultIfEmpty(new byte[0])
.map(responseBody -> {
if (responseBody.length > maxBodyBytes) {
throw new DataBufferLimitException("Response body of " + responseBody.length + " bytes exceeds " + maxBodyBytes);
}
HttpHeaders responseHeaders = response.headers().asHttpHeaders();
String encoding = ChannelBodies.encoding(responseHeaders.getFirst(HttpHeaders.CONTENT_TYPE));
var reply = new TbHttpResponse(response.statusCode().value(), responseHeaders(responseHeaders),
ChannelBodies.encode(responseBody, encoding), encoding);
return ChannelFrame.reply(ChannelProtocol.TB_RESPONSE, frame, codec.toPayload(reply));
}))
.timeout(timeout)
.onErrorResume(e -> Mono.just(failure(frame, codec, request, e)));
}
public void serve(ChannelSession session, ChannelFrame frame, ChannelFrameCodec codec, TbAiTurnContext context, int maxBodyBytes) {
execute(frame, codec, context, maxBodyBytes).subscribe(reply -> {
try {
session.send(reply);
} catch (ChannelException e) {
log.debug("Dropped '{}' reply: {}", reply.type(), e.getMessage());
}
});
}
static String validate(TbHttpRequest request) {
if (request.method() == null || !ALLOWED_METHODS.contains(HttpMethod.valueOf(request.method().toUpperCase(Locale.ROOT)))) {
return "Method is not allowed: " + request.method();
}
String path = request.path();
if (path == null || !path.startsWith(API_PREFIX)) {
return "Path must start with " + API_PREFIX;
}
URI uri;
try {
uri = URI.create("http://loopback" + path);
} catch (IllegalArgumentException e) {
return "Path is not a valid URI path";
}
if (uri.getRawQuery() != null || uri.getRawFragment() != null || !uri.normalize().getRawPath().equals(path)
|| path.contains("//")) {
return "Path must be a normalized relative path";
}
if (request.query() != null) {
try {
URI withQuery = URI.create("http://loopback" + path + "?" + request.query());
if (withQuery.getRawFragment() != null) {
return "Query must not contain a fragment";
}
} catch (IllegalArgumentException e) {
return "Query is not a valid URI query";
}
}
return null;
}
/**
* Makes the loopback request look as if it came through the user's {@code clientOrigin} from the user's address,
* so ThingsBoard builds URLs (device connectivity commands) and records addresses as for the user's own request.
* The browser request's X-Forwarded-* headers cannot be copied: the forwarded-header filter consumes them.
*/
static Map<String, String> forwardedHeaders(TbAiTurnContext context) {
var headers = new LinkedHashMap<String, String>();
URI origin = parseOrigin(context.clientOrigin());
if (origin != null) {
String scheme = origin.getScheme().toLowerCase(Locale.ROOT);
int port = origin.getPort() != -1 ? origin.getPort() : "https".equals(scheme) ? 443 : 80;
headers.put(X_FORWARDED_PROTO, scheme);
headers.put(X_FORWARDED_HOST, origin.getHost());
headers.put(X_FORWARDED_PORT, String.valueOf(port));
}
if (context.user() != null && StringUtils.isNotBlank(context.user().getClientAddress())) {
headers.put(X_FORWARDED_FOR, context.user().getClientAddress());
}
return headers;
}
private static URI parseOrigin(String clientOrigin) {
if (StringUtils.isBlank(clientOrigin)) {
return null;
}
try {
URI uri = URI.create(clientOrigin.trim());
String scheme = uri.getScheme();
if (uri.getHost() == null || !("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme))) {
return null;
}
return uri;
} catch (IllegalArgumentException e) {
return null;
}
}
private static void copyRequestHeaders(Map<String, List<String>> source, HttpHeaders target) {
if (source == null) {
return;
}
source.forEach((name, values) -> {
if (!DROPPED_REQUEST_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
target.put(name, values);
}
});
}
private static Map<String, List<String>> responseHeaders(HttpHeaders headers) {
var result = new LinkedHashMap<String, List<String>>();
headers.forEach((name, values) -> {
if (!DROPPED_RESPONSE_HEADERS.contains(name.toLowerCase(Locale.ROOT))) {
result.put(name, List.copyOf(values));
}
});
return result;
}
private static ChannelFrame failure(ChannelFrame frame, ChannelFrameCodec codec, TbHttpRequest request, Throwable e) {
if (e instanceof TimeoutException) {
return error(frame, codec, TIMEOUT, "ThingsBoard did not answer " + request.method() + " " + request.path() + " in time");
}
if (e instanceof DataBufferLimitException) {
return error(frame, codec, TOO_LARGE, "Response is larger than the channel frame limit");
}
log.warn("AI request {} {} failed: {}", request.method(), request.path(), e.getMessage());
return error(frame, codec, REQUEST_FAILED, "ThingsBoard request failed");
}
private static ChannelFrame error(ChannelFrame frame, ChannelFrameCodec codec, String code, String message) {
return ChannelFrame.reply(ChannelProtocol.ERROR, frame, codec.toPayload(new ChannelError(code, message)));
}
private static String loopbackUrl(String address, int port, boolean sslEnabled) {
String host = StringUtils.isBlank(address) || "0.0.0.0".equals(address) || "::".equals(address) ? "127.0.0.1" : address;
if (host.contains(":") && !host.startsWith("[")) {
host = "[" + host + "]";
}
return (sslEnabled ? "https" : "http") + "://" + host + ":" + port;
}
private static SslContext insecureLoopbackSslContext() {
try {
return SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} catch (SSLException e) {
throw new IllegalStateException("Failed to create the loopback SSL context", e);
}
}
}

21
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTransport.java

@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.codec.ServerSentEvent;
import reactor.core.publisher.Flux;
import java.util.UUID;
public interface TbAiTransport {
Flux<ServerSentEvent<String>> sendChatMessage(UUID chatId, JsonNode request, TbAiTurnContext context, TbAiTurnLink link);
/**
* Follows the turn running in the chat: a {@code turnResumed} event, every event of the turn so far, then the live
* ones. Completes at once when no turn is running or when TB AI cannot resume turns.
*/
Flux<ServerSentEvent<String>> resumeChat(UUID chatId, TbAiTurnContext context, TbAiTurnLink link);
}

40
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnContext.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.service.security.model.SecurityUser;
/**
* Everything one TB AI call needs on the TB side. {@code user} is null for background work (housekeeper deletions);
* {@code tbAccessToken} is null for calls during which TB AI never calls ThingsBoard back. {@code clientOrigin} is the
* ThingsBoard base URL the user reached for this call: TB AI shows it to the user (device connectivity commands) and
* audits it, and the calls back into ThingsBoard are forwarded as if made through it.
*/
public record TbAiTurnContext(
TenantId tenantId,
UserId userId,
SecurityUser user,
String tbAccessToken,
String acceptLanguage,
TbAiClient.TokenProvider tokenProvider,
String clientOrigin
) {
public TbAiTurnContext(SecurityUser user, String tbAccessToken, String acceptLanguage,
TbAiClient.TokenProvider tokenProvider, String clientOrigin) {
this(user.getTenantId(), user.getId(), user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);
}
public static TbAiTurnContext background(TenantId tenantId, UserId userId, TbAiClient.TokenProvider tokenProvider,
String clientOrigin) {
return new TbAiTurnContext(tenantId, userId, null, null, null, tokenProvider, clientOrigin);
}
public boolean isBackground() {
return user == null;
}
}

41
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiTurnLink.java

@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport;
/**
* Connects the browser end of an AI chat stream to its turn on TB AI. ThingsBoard keeps listening to a turn after the
* browser leaves (the turn bills its credits at its end), so leaving is reported separately: TB AI then knows nobody
* follows the turn, and a pending approval expires soon instead of waiting its full timeout for a user who left.
*/
public final class TbAiTurnLink {
private final Object lock = new Object();
private Runnable onClientLeft;
private boolean clientLeft;
public void onClientLeft(Runnable listener) {
boolean leftAlready;
synchronized (lock) {
onClientLeft = listener;
leftAlready = clientLeft;
}
if (leftAlready) {
listener.run();
}
}
public void clientLeft() {
Runnable listener;
synchronized (lock) {
if (clientLeft) {
return;
}
clientLeft = true;
listener = onClientLeft;
}
if (listener != null) {
listener.run();
}
}
}

14
application/src/main/java/org/thingsboard/server/service/cf/AbstractCalculatedFieldProcessingService.java

@ -72,6 +72,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -494,13 +495,20 @@ public abstract class AbstractCalculatedFieldProcessingService {
callback.onFailure(new IllegalArgumentException("Only TimeSeriesImmediateOutputStrategy is supported.")); callback.onFailure(new IllegalArgumentException("Only TimeSeriesImmediateOutputStrategy is supported."));
} else { } else {
TimeseriesSaveRequest.Strategy strategy = new TimeseriesSaveRequest.Strategy(tsOutputStrategy.isSaveTimeSeries(), tsOutputStrategy.isSaveLatest(), tsOutputStrategy.isSendWsUpdate(), tsOutputStrategy.isProcessCfs()); TimeseriesSaveRequest.Strategy strategy = new TimeseriesSaveRequest.Strategy(tsOutputStrategy.isSaveTimeSeries(), tsOutputStrategy.isSaveLatest(), tsOutputStrategy.isSendWsUpdate(), tsOutputStrategy.isProcessCfs());
saveTimeSeriesInternal(tenantId, entityId, jsonResult, tsOutputStrategy.getTtl(), cfIds, ts, strategy, callback); saveTimeSeriesInternal(tenantId, entityId, jsonResult, resolveTtl(tenantId, tsOutputStrategy.getTtl()), cfIds, ts, strategy, callback);
} }
} }
protected void saveReprocessingTimeSeriesResult(TenantId tenantId, EntityId entityId, JsonElement jsonResult, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) { protected void saveReprocessingTimeSeriesResult(TenantId tenantId, EntityId entityId, JsonElement jsonResult, long ttl, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) {
log.trace("[{}][{}] Saving CF reprocessing result: {}", tenantId, entityId, jsonResult); log.trace("[{}][{}] Saving CF reprocessing result: {}", tenantId, entityId, jsonResult);
saveTimeSeriesInternal(tenantId, entityId, jsonResult, null, null, ts, strategy, callback); saveTimeSeriesInternal(tenantId, entityId, jsonResult, resolveTtl(tenantId, ttl), null, ts, strategy, callback);
}
private long resolveTtl(TenantId tenantId, long ttl) {
if (ttl == 0L) {
return TimeUnit.DAYS.toSeconds(apiLimitService.getLimit(tenantId, DefaultTenantProfileConfiguration::getDefaultStorageTtlDays));
}
return ttl;
} }
private void saveTimeSeriesInternal(TenantId tenantId, EntityId entityId, JsonElement jsonResult, Long ttl, List<CalculatedFieldId> cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) { private void saveTimeSeriesInternal(TenantId tenantId, EntityId entityId, JsonElement jsonResult, Long ttl, List<CalculatedFieldId> cfIds, long ts, TimeseriesSaveRequest.Strategy strategy, TbCallback callback) {

14
application/src/main/java/org/thingsboard/server/service/cf/DefaultCalculatedFieldReprocessingService.java

@ -20,6 +20,8 @@ import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import org.thingsboard.server.common.data.cf.configuration.Argument; import org.thingsboard.server.common.data.cf.configuration.Argument;
import org.thingsboard.server.common.data.cf.configuration.ArgumentType; import org.thingsboard.server.common.data.cf.configuration.ArgumentType;
import org.thingsboard.server.common.data.cf.configuration.OutputType; import org.thingsboard.server.common.data.cf.configuration.OutputType;
import org.thingsboard.server.common.data.cf.configuration.TimeSeriesImmediateOutputStrategy;
import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput;
import org.thingsboard.server.common.data.cf.configuration.aggregation.RelatedEntitiesAggregationCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.RelatedEntitiesAggregationCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.aggregation.single.EntityAggregationCalculatedFieldConfiguration; import org.thingsboard.server.common.data.cf.configuration.aggregation.single.EntityAggregationCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.aggregation.single.interval.AggInterval; import org.thingsboard.server.common.data.cf.configuration.aggregation.single.interval.AggInterval;
@ -255,17 +257,25 @@ public class DefaultCalculatedFieldReprocessingService extends AbstractCalculate
private Future<Void> saveResult(CFReprocessingCtx ctx, CalculatedFieldResult calculatedFieldResult, long ts, Strategy strategy) { private Future<Void> saveResult(CFReprocessingCtx ctx, CalculatedFieldResult calculatedFieldResult, long ts, Strategy strategy) {
SettableFuture<Void> future = SettableFuture.create(); SettableFuture<Void> future = SettableFuture.create();
long ttl = getOutputTtl(ctx.getCfCtx());
if (calculatedFieldResult instanceof PropagationCalculatedFieldResult propagationResult) { if (calculatedFieldResult instanceof PropagationCalculatedFieldResult propagationResult) {
TbCallback rootCallback = TbCallback.wrap(future); TbCallback rootCallback = TbCallback.wrap(future);
handlePropagationResults(propagationResult, rootCallback, handlePropagationResults(propagationResult, rootCallback,
(entityId, res, cb) -> (entityId, res, cb) ->
saveReprocessingTimeSeriesResult(ctx.getTenantId(), entityId, res.toJsonElement(), ts, strategy, cb)); saveReprocessingTimeSeriesResult(ctx.getTenantId(), entityId, res.toJsonElement(), ttl, ts, strategy, cb));
} else { } else {
saveReprocessingTimeSeriesResult(ctx.getTenantId(), ctx.getEntityId(), calculatedFieldResult.toJsonElement(), ts, strategy, TbCallback.wrap(future)); saveReprocessingTimeSeriesResult(ctx.getTenantId(), ctx.getEntityId(), calculatedFieldResult.toJsonElement(), ttl, ts, strategy, TbCallback.wrap(future));
} }
return future; return future;
} }
private long getOutputTtl(CalculatedFieldCtx cfCtx) {
if (cfCtx.getOutput() instanceof TimeSeriesOutput tsOutput && tsOutput.getStrategy() instanceof TimeSeriesImmediateOutputStrategy tsStrategy) {
return tsStrategy.getTtl();
}
return 0L;
}
private CFReprocessingCtx buildCtx(TenantId tenantId, EntityId entityId, private CFReprocessingCtx buildCtx(TenantId tenantId, EntityId entityId,
CalculatedFieldCtx cfCtx, CalculatedFieldState state) { CalculatedFieldCtx cfCtx, CalculatedFieldState state) {
if (CalculatedFieldType.RELATED_ENTITIES_AGGREGATION.equals(cfCtx.getCfType())) { if (CalculatedFieldType.RELATED_ENTITIES_AGGREGATION.equals(cfCtx.getCfType())) {

4
application/src/main/java/org/thingsboard/server/service/cf/ctx/state/alarm/AlarmRuleState.java

@ -4,6 +4,8 @@ package org.thingsboard.server.service.cf.ctx.state.alarm;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.KvUtil; import org.thingsboard.common.util.KvUtil;
@ -38,6 +40,8 @@ public class AlarmRuleState {
private final AlarmSeverity severity; private final AlarmSeverity severity;
private AlarmRule alarmRule; private AlarmRule alarmRule;
@ToString.Exclude
@EqualsAndHashCode.Exclude
private AlarmCalculatedFieldState state; private AlarmCalculatedFieldState state;
private AlarmCondition condition; private AlarmCondition condition;

20
application/src/main/java/org/thingsboard/server/service/converter/ConverterDefaultsService.java

@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.converter;
import org.thingsboard.server.common.data.converter.ConverterType;
import org.thingsboard.server.common.data.integration.IntegrationType;
import java.util.Optional;
public interface ConverterDefaultsService {
Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType);
Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType);
Optional<String> getIntegrationName(IntegrationType integrationType);
Optional<String> getDownlinkMsgType(IntegrationType integrationType);
}

66
application/src/main/java/org/thingsboard/server/service/converter/DefaultConverterDefaultsService.java

@ -0,0 +1,66 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.converter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.converter.ConverterType;
import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
@TbCoreComponent
@Service
@Slf4j
public class DefaultConverterDefaultsService implements ConverterDefaultsService {
private static final String CONVERTERS_DIR = "converters";
private static final String PAYLOAD_FILE = "payload.json";
private static final String METADATA_FILE = "metadata.json";
private static final String INTEGRATION_FILE = "integration.json";
private static final String MSG_TYPE_FILE = "msgType.txt";
@Override
public Optional<String> getPayload(IntegrationType integrationType, ConverterType converterType) {
return getFileContent(integrationType, converterType.getDirectory() + "/" + PAYLOAD_FILE);
}
@Override
public Optional<String> getMetadata(IntegrationType integrationType, ConverterType converterType) {
return getFileContent(integrationType, converterType.getDirectory() + "/" + METADATA_FILE);
}
@Override
public Optional<String> getIntegrationName(IntegrationType integrationType) {
return getFileContent(integrationType, INTEGRATION_FILE)
.map(content -> JacksonUtil.toJsonNode(content).get("name").asText());
}
@Override
public Optional<String> getDownlinkMsgType(IntegrationType integrationType) {
return getFileContent(integrationType, ConverterType.DOWNLINK.getDirectory() + "/" + MSG_TYPE_FILE)
.map(String::trim);
}
private Optional<String> getFileContent(IntegrationType integrationType, String relativePath) {
if (integrationType.getDirectory() == null) {
return Optional.empty();
}
String path = String.join("/", CONVERTERS_DIR, integrationType.getDirectory(), relativePath);
try (InputStream in = getClass().getClassLoader().getResourceAsStream(path)) {
if (in == null) {
return Optional.empty();
}
return Optional.of(new String(in.readAllBytes(), StandardCharsets.UTF_8));
} catch (IOException e) {
log.warn("Failed to read converter defaults file {}", path, e);
return Optional.empty();
}
}
}

6
application/src/main/java/org/thingsboard/server/service/device/DeviceBulkImportService.java

@ -11,6 +11,7 @@ import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.DeviceProfileProvisionType; import org.thingsboard.server.common.data.DeviceProfileProvisionType;
@ -89,7 +90,10 @@ public class DeviceBulkImportService extends AbstractBulkImportService<Device> {
additionalInfo.set("description", new TextNode(value)); additionalInfo.set("description", new TextNode(value));
break; break;
case IS_GATEWAY: case IS_GATEWAY:
additionalInfo.set("gateway", BooleanNode.valueOf(Boolean.parseBoolean(value))); additionalInfo.set(DataConstants.GATEWAY_PARAMETER, BooleanNode.valueOf(Boolean.parseBoolean(value)));
break;
case OVERWRITE_ACTIVITY_TIME:
additionalInfo.set(DataConstants.OVERWRITE_ACTIVITY_TIME_PARAMETER, BooleanNode.valueOf(Boolean.parseBoolean(value)));
break; break;
} }
device.setAdditionalInfo(additionalInfo); device.setAdditionalInfo(additionalInfo);

35
application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java

@ -66,7 +66,7 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
new HttpEntity<>(request, headers), JsonNode.class); new HttpEntity<>(request, headers), JsonNode.class);
log.trace("checkInstance response: {}", response); log.trace("checkInstance response: {}", response);
// removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections
return new ResponseEntity<JsonNode>(response.getBody(), response.getStatusCode()); return new ResponseEntity<>(response.getBody(), response.getStatusCode());
} }
@Override @Override
@ -80,7 +80,38 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
null, JsonNode.class, params); null, JsonNode.class, params);
log.trace("activateInstance response: {}", response); log.trace("activateInstance response: {}", response);
// removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections // removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections
return new ResponseEntity<JsonNode>(response.getBody(), response.getStatusCode()); return new ResponseEntity<>(response.getBody(), response.getStatusCode());
}
@Override
public ResponseEntity<JsonNode> checkInstanceV2(JsonNode request) {
log.trace("checkInstance V2 [{}]", request);
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<JsonNode> response = this.restTemplate.postForEntity(
EDGE_LICENSE_SERVER_ENDPOINT + "/api/v2/license/checkInstance",
new HttpEntity<>(request, headers), JsonNode.class);
log.trace("checkInstance V2 response: {}", response);
// removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections
return new ResponseEntity<>(response.getBody(), response.getStatusCode());
}
@Override
public ResponseEntity<JsonNode> activateInstanceV2(String edgeLicenseSecret, String releaseDate, String clusterId, String protocolVersion) {
log.trace("activateInstance V2 [{}][{}][{}]", releaseDate, clusterId, protocolVersion);
Map<String, String> params = new HashMap<>();
params.put("licenseSecret", edgeLicenseSecret);
params.put("releaseDate", releaseDate);
params.put("clusterId", clusterId);
String url = EDGE_LICENSE_SERVER_ENDPOINT + "/api/v2/license/activateInstance?licenseSecret={licenseSecret}&releaseDate={releaseDate}&clusterId={clusterId}";
if (protocolVersion != null) {
params.put("protocolVersion", protocolVersion);
url += "&protocolVersion={protocolVersion}";
}
ResponseEntity<JsonNode> response = this.restTemplate.postForEntity(url, null, JsonNode.class, params);
log.trace("activateInstance V2 response: {}", response);
// removing headers from response of the license server, because it might be a conflict with the proxy from we are accepting incoming connections
return new ResponseEntity<>(response.getBody(), response.getStatusCode());
} }
private RestTemplate initRestTemplate() { private RestTemplate initRestTemplate() {

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save