### Start ThingsBoard Edge Service Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Starts the ThingsBoard Edge service using the system's service manager. ```bash sudo service tb-edge start ``` -------------------------------- ### Install Prerequisites (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Installs necessary tools like nano and wget, and the EPEL repository for RHEL/CentOS 7. ```bash sudo yum install -y nano wget && sudo yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm ``` -------------------------------- ### Install and Configure PostgreSQL for ThingsBoard Edge Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Installs PostgreSQL 16, starts the service, sets the superuser password, and creates the 'tb_edge' database required for ThingsBoard Edge. ```bash # Automated repository configuration: sudo apt install -y postgresql-common sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh # install and launch the postgresql service: sudo apt update sudo apt -y install postgresql-16 sudo service postgresql start ``` ```bash sudo -u postgres psql -c "\password" ``` ```bash echo "CREATE DATABASE tb_edge;" | psql -U postgres -d postgres -h 127.0.0.1 -W ``` -------------------------------- ### Run ThingsBoard Edge Installation Script Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Executes the installation script for ThingsBoard Edge after the service has been downloaded and configured. ```bash sudo /usr/share/tb-edge/bin/install/install.sh ``` -------------------------------- ### Install Java 17 OpenJDK (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Installs OpenJDK 17, configures it as the default Java version, and verifies the installation. ```bash sudo dnf install -y java-17-openjdk ``` ```bash sudo update-alternatives --config java ``` ```bash java -version ``` -------------------------------- ### Install PostgreSQL for CentOS/RHEL 9 (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Installs the PostgreSQL repository RPM for CentOS/RHEL 9. ```bash sudo dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm ``` -------------------------------- ### Download and Install ThingsBoard Edge Service Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Downloads the ThingsBoard Edge installation package (.deb file) using wget and then installs the service using dpkg. ```bash wget https://github.com/thingsboard/thingsboard-edge/releases/download/v${TB_EDGE_TAG}/tb-edge-${TB_EDGE_TAG}.deb ``` ```bash sudo dpkg -i tb-edge-${TB_EDGE_TAG}.deb ``` -------------------------------- ### Install PostgreSQL for CentOS/RHEL 8 (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Installs the PostgreSQL repository RPM for CentOS/RHEL 8. ```bash sudo sudo dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm ``` -------------------------------- ### Initialize and Configure PostgreSQL (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Disables the default PostgreSQL module, installs PostgreSQL 16, initializes the database, enables the service, sets the PostgreSQL user password, configures MD5 authentication, and restarts the service. ```bash sudo dnf -qy module disable postgresql && \ sudo dnf -y install postgresql16 postgresql16-server postgresql16-contrib && \ sudo /usr/pgsql-16/bin/postgresql-16-setup initdb && \ sudo systemctl enable --now postgresql-16 ``` ```bash sudo -u postgres psql -c "\password" ``` ```bash sudo sed -i 's/^host\s\+all\s\+all\s\+127\.0\.0\.1\/32\s\+ident/host all all 127.0.0.1/32 md5/' /var/lib/pgsql/16/data/pg_hba.conf ``` ```bash sudo systemctl restart postgresql-16.service && psql -U postgres -d postgres -h 127.0.0.1 -W -c "CREATE DATABASE tb_edge;" ``` -------------------------------- ### Download and Install ThingsBoard Edge (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/centos/instructions.md Downloads the ThingsBoard Edge RPM package for the specified version and installs it on the system. ```bash wget https://github.com/thingsboard/thingsboard-edge/releases/download/v${TB_EDGE_TAG}/tb-edge-${TB_EDGE_TAG}.rpm ``` ```bash sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}.rpm ``` -------------------------------- ### Start ThingsBoard Container (Shell) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/tb/README.md This command starts a previously stopped ThingsBoard Docker container named 'mytb'. The container will resume its operation with the existing data. ```shell docker start mytb ``` -------------------------------- ### Install Java 17 (OpenJDK) on Ubuntu Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Installs OpenJDK 17, which is required for ThingsBoard service. It also includes commands to set Java 17 as the default and verify the installation. ```bash sudo apt update && sudo apt install openjdk-17-jdk ``` ```bash sudo update-alternatives --config java ``` ```bash java -version ``` -------------------------------- ### Install ThingsBoard Edge Package Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md Installs the downloaded ThingsBoard Edge .deb package using the `dpkg` command. This requires superuser privileges (`sudo`) and assumes the package file is in the current directory. ```bash sudo dpkg -i tb-edge-${TB_EDGE_TAG}.deb ``` -------------------------------- ### Time-Series Widget Example with Chart.js Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/widget_js_fn.md Shows an example of using the Chart.js library to create time-series visualizations within a ThingsBoard widget. This illustrates how to leverage popular charting libraries for data representation. ```JavaScript tb-help-popup="widget/editor/examples/ext_timeseries_example" ``` -------------------------------- ### Device Authentication: MQTT Basic Auth Source: https://context7.com/guoruilv/thingsboard/llms.txt Python code snippet for setting up MQTT client authentication using basic username and password credentials. This example is a starting point and requires further implementation for connecting and publishing messages. ```python import paho.mqtt.client as mqtt import json ``` -------------------------------- ### Start and Monitor ThingsBoard Edge Service Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/docker/instructions.md Initiates the ThingsBoard Edge service using Docker Compose in detached mode and continuously displays the logs for the `mytbedge` service. This command allows for immediate feedback on the service's startup process and any potential issues. ```bash docker compose up -d && docker compose logs -f mytbedge ``` -------------------------------- ### Optional: Configure PostgreSQL Connection for ThingsBoard Edge Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Appends PostgreSQL connection details to the ThingsBoard Edge configuration file if custom datasources or credentials are used. Remember to replace placeholder password. ```bash sudo sh -c 'cat <> /etc/tb-edge/conf/tb-edge.conf export SPRING_DATASOURCE_URL=jdbc:postgresql://localhost:5432/tb_edge export SPRING_DATASOURCE_USERNAME=postgres export SPRING_DATASOURCE_PASSWORD= EOL' ``` -------------------------------- ### Install ThingsBoard Edge RPM Package Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/upgrade/centos/instructions.md Installs the downloaded ThingsBoard Edge RPM package using the rpm command. This requires root privileges (sudo). Ensure the RPM file name matches the downloaded package. ```bash sudo rpm -Uvh tb-edge-${TB_EDGE_TAG}.rpm ``` -------------------------------- ### Latest Values Widget Example with gauge.js Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/widget_js_fn.md Demonstrates how to use the gauge.js library within a ThingsBoard widget to display the latest values. This example highlights the integration of external JavaScript libraries for custom widget functionalities. ```JavaScript tb-help-popup="widget/editor/examples/ext_latest_values_example" ``` -------------------------------- ### JSON Message Examples for Fields Templatization Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/originator_attributes_node_fields_templatization.md These JSON examples illustrate the structure of messages before and after processing by a script node, demonstrating how the 'keyToFetch' metadata field is populated based on different conditions. It shows how dynamic attribute fetching is initiated. ```json { "msg": { "temperature": 26.5, "humidity": 75.2, "soilMoisture": 28.9, "windSpeed": 8.2, "windDirection": "NNE" }, "metadata": { "deviceType": "default", "deviceName": "SN-001", "ts": "1685379440000", "keyToFetch": "lastIrrigationTime" } } ``` ```json { "msg": { "temperature": 26.5, "humidity": 75.2, "soilMoisture": 32.5, "windSpeed": 10.4, "windDirection": "NNE" }, "metadata": { "deviceType": "default", "deviceName": "SN-001", "ts": "1685379440000", "keyToFetch": "lastWindSpeedAlarmTime" } } ``` ```json { "msg": { "temperature": 26.5, "humidity": 75.2, "soilMoisture": 28.9, "windSpeed": 8.2, "windDirection": "NNE" }, "metadata": { "deviceType": "default", "deviceName": "SN-001", "ts": "1685379440000", "keyToFetch": "lastIrrigationTime", "ss_lastIrrigationTime": "1685369440000" } } ``` ```json { "msg": { "temperature": 26.5, "humidity": 75.2, "soilMoisture": 32.5, "windSpeed": 10.4, "windDirection": "NNE" }, "metadata": { "deviceType": "default", "deviceName": "MM-001", "ts": "1685379440000", "keyToFetch": "lastWindSpeedAlarmTime", "ss_lastWindSpeedAlarmTime": "1685359440000" } } ``` -------------------------------- ### Download ThingsBoard Edge Package Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/upgrade/ubuntu/instructions.md Downloads the ThingsBoard Edge .deb package from the specified GitHub release URL. This command requires `wget` to be installed and assumes the `TB_EDGE_TAG` variable is set. ```bash wget https://github.com/thingsboard/thingsboard-edge/releases/download/v${TB_EDGE_TAG}/tb-edge-${TB_EDGE_TAG}.deb ``` -------------------------------- ### Configure ThingsBoard Edge with Cloud Connection Details Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Appends essential cloud connection parameters to the ThingsBoard Edge configuration file (/etc/tb-edge/conf/tb-edge.conf). This includes routing keys, secrets, host, port, and SSL settings. ```bash sudo sh -c 'cat <> /etc/tb-edge/conf/tb-edge.conf export CLOUD_ROUTING_KEY=${CLOUD_ROUTING_KEY} export CLOUD_ROUTING_SECRET=${CLOUD_ROUTING_SECRET} export CLOUD_RPC_HOST=${BASE_URL} export CLOUD_RPC_PORT=${CLOUD_RPC_PORT} export CLOUD_RPC_SSL_ENABLED=${CLOUD_RPC_SSL_ENABLED} EOL' ``` -------------------------------- ### Templating Examples with JSON Data Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/rule_node.md Demonstrates how to use template parameters, including nested JSON data, for notification content. The example shows a JSON input and the resulting transformed text. ```json { "building_1": { "temperature": 24 } } ``` ```text Building 1: temperature is ${building_1.temperature} ``` ```text Building 1: temperature is 24 ``` -------------------------------- ### To Email Node Configuration Example Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/to_email_node_fields_templatization.md This example shows the configuration of a 'to email' rule node in ThingsBoard. It utilizes fields templatization to dynamically populate the 'to', 'cc', 'subject', and 'body' fields of an email based on message metadata, such as primary user and subscribers. ```json { "msg": { "temperature": 32 }, "metadata": { "deviceType": "Thermostat", "deviceName": "TH-001", "ts": "1685379440000", "primaryUser": "john.doe@example.com", "subscribers": "mike.johnson@example.io,sarah.smith@example.org,emily.davis@example.co" } } ``` -------------------------------- ### Incoming Message Example (Temperature Sensor) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/customer_attributes_node_fields_templatization.md An example of an incoming message from a temperature sensor, including the message payload and metadata. The 'deviceType' in the metadata is crucial for dynamic attribute fetching. ```json { "msg": { "temperature": 32 }, "metadata": { "deviceType": "temperature", "deviceName": "TH-001", "ts": "1685379440000" } } ``` -------------------------------- ### Alarm Notification Template Example (Text) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/alarm_comment.md Demonstrates a simple text-based template for alarm notifications, showing how to insert alarm type and action using templatization parameters. This example uses basic parameters without any modifiers. ```text Alarm '${alarmType}' - comment ${action} ``` -------------------------------- ### Notification Template Example Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/entities_limit_increase_request.md This example demonstrates how to use templatization parameters within a notification template. It shows how to insert dynamic data like user email and entity type, and how to modify the case of the inserted text using suffixes like ':lowerCase'. ```text ${userEmail} has reached the maximum number of ${entityType:lowerCase}s allowed and is requesting an increase to the ${entityType:lowerCase} limit. ``` -------------------------------- ### Markdown: Create Headers Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/widget_js_markdown_pattern.md Demonstrates how to create Markdown headers using the '#' character. The number of '#' characters determines the header level (e.g., '#' for h1, '######' for h6). This is useful for structuring content within Markdown cards. ```markdown ###### Markdown/HTML card ``` -------------------------------- ### Dynamic Timeseries Data Fetching with Event-Based Templatization Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/originator_telemetry_node_fields_templatization.md This example demonstrates how to dynamically fetch timeseries data based on a device's event type ('motion' or 'parked'). It uses a script node to populate metadata fields (keyToFetch1, keyToFetch2, etc.) with the appropriate telemetry keys. The rule node configuration then uses these metadata fields to query the latest telemetry readings within a specified time range. The output message includes the original message data and the fetched telemetry values, formatted as JSON strings. ```json { "msg": { "latitude": "40.730610", "longitude": "-73.935242", "event": "motion" }, "metadata": { "deviceName": "GPS-001", "deviceType": "GPS Tracker", "ts": "1685479440000", "keyToFetch1": "speed", "keyToFetch2": "direction", "keyToFetch3": "acceleration" } } ``` ```json { "msg": { "latitude": "40.730610", "longitude": "-73.935242", "event": "parked" }, "metadata": { "deviceName": "GPS-001", "deviceType": "GPS Tracker", "ts": "1685379440000", "keyToFetch1": "parkedLocation", "keyToFetch2": "parkedDuration", "keyToFetch3": "parkedTime" } } ``` ```json { "msg": { "latitude": "40.730610", "longitude": "-73.935242", "event": "motion" }, "metadata": { "deviceName": "GPS-001", "deviceType": "GPS Tracker", "ts": "1685479440000", "keyToFetch1": "speed", "keyToFetch2": "direction", "keyToFetch3": "acceleration", "speed": "[{\"ts\":1685476840000,\"value\":5.2},{\"ts\":1685477840000,\"value\":15.7},{\"ts\":1685478840000,\"value\":30.2}]", "direction": "[{\"ts\":1685476840000,\"value\":\"N\"},{\"ts\":1685477840000,\"value\":\"NE\"},{\"ts\":1685478840000,\"value\":\"N\"}]", "acceleration": "[{\"ts\":1685476840000,\"value\":2.2},{\"ts\":1685477840000,\"value\":2.4},{\"ts\":1685478840000,\"value\":2.5}]", "fuelLevel": "[{\"ts\":1685476840000,\"value\":61.5},{\"ts\":1685477840000,\"value\":57.4},{\"ts\":1685478840000,\"value\":55.6}]", "batteryLevel": "[{\"ts\":1685476840000,\"value\":88.1},{\"ts\":1685477840000,\"value\":87.8},{\"ts\":1685478840000,\"value\":87.2}]" } } ``` ```json { "msg": { "latitude": "40.730610", "longitude": "-73.935242", "event": "parked" }, "metadata": { "deviceName": "GPS-001", "deviceType": "GPS Tracker", "ts": "1685379440000", "keyToFetch1": "parkedLocation", "keyToFetch2": "parkedDuration", "keyToFetch3": "parkedTime" } } ``` -------------------------------- ### Stop ThingsBoard Container (Shell) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/tb/README.md This command gracefully stops a running ThingsBoard Docker container named 'mytb'. The container's state and data are preserved for future starts. ```shell docker stop mytb ``` -------------------------------- ### Execute MQTT RPC from Server (Shell Script) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/examples/rpc_widget.md A shell script to initiate an RPC connection from the server to a device using MQTT. It requires the mqtt client library to be installed and a device access token to be configured. This script facilitates sending commands to devices. ```bash #!/bin/bash # Replace with your device access token ACCESS_TOKEN="YOUR_DEVICE_ACCESS_TOKEN" # MQTT broker details (default ThingsBoard MQTT broker) # If you are using a different MQTT broker, please update the mqtt client parameters accordingly. MQTT_BROKER="mqtt.thingsboard.cloud" MQTT_PORT="1883" # Install mqtt client library if not already installed # Check your system's package manager for instructions (e.g., apt, yum, brew) # Example for npm: # npm install -g mqtt # Start the MQTT client and subscribe to RPC request topic # The '0' in the topic is a QoS level, which can be adjusted if needed. mqtt --host "${MQTT_BROKER}" --port ${MQTT_PORT} --username "${ACCESS_TOKEN}" --clientId "thingsboard-rpc-client-$(openssl rand -hex 4)" --loop --subscribe "v1/devices/me/rpc/request/0" --prettyPrint --logLevel "info" ``` -------------------------------- ### Device Provisioning Source: https://context7.com/guoruilv/thingsboard/llms.txt Automate device provisioning by generating credentials. ```APIDOC ## Device Provisioning Automatic device provisioning with credentials generation. ### Method POST ### Endpoint `/api/v1/provision` ### Parameters #### Request Body - **deviceName** (string) - The name of the device to provision. - **provisionDeviceKey** (string) - The provisioning device key from the device profile. - **provisionDeviceSecret** (string) - The provisioning device secret from the device profile. - **credentialsType** (string, Optional) - The type of credentials to generate (e.g., "ACCESS_TOKEN"). If not provided, an access token is typically generated. - **token** (string, Optional) - A custom access token to be used if `credentialsType` is "ACCESS_TOKEN". ### Request Example **With specified credentials type and token:** ```bash curl -X POST "https://thingsboard.example.com/api/v1/provision" \ -H "Content-Type: application/json" \ -d '{ "deviceName": "Sensor_12345", "provisionDeviceKey": "provision_key_from_profile", "provisionDeviceSecret": "provision_secret_from_profile", "credentialsType": "ACCESS_TOKEN", "token": "custom_access_token_123" }' ``` **For auto-generated token provisioning:** ```bash curl -X POST "https://thingsboard.example.com/api/v1/provision" \ -H "Content-Type: application/json" \ -d '{ "deviceName": "Sensor_54321", "provisionDeviceKey": "provision_key", "provisionDeviceSecret": "provision_secret" }' ``` ### Response #### Success Response (200 OK) - **status** (string) - The provisioning status (e.g., "SUCCESS"). - **credentialsType** (string) - The type of credentials generated (e.g., "ACCESS_TOKEN"). - **credentialsValue** (string) - The generated credential value (e.g., the access token). - **provisionDeviceStatus** (string) - The status of the provisioned device (e.g., "PROVISIONED"). #### Response Example ```json { "status": "SUCCESS", "credentialsType": "ACCESS_TOKEN", "credentialsValue": "custom_access_token_123", "provisionDeviceStatus": "PROVISIONED" } ``` **Response for auto-generated token:** ```json { "status": "SUCCESS", "credentialsType": "ACCESS_TOKEN", "credentialsValue": "auto_generated_token_xyz789", "provisionDeviceStatus": "PROVISIONED" } ``` ``` -------------------------------- ### MQTT Basic Authentication Example Source: https://context7.com/guoruilv/thingsboard/llms.txt Connects to ThingsBoard using MQTT with basic username and password authentication. It publishes telemetry data upon successful connection. Requires the 'paho-mqtt' library. Dependencies: 'paho-mqtt', 'json'. ```python import paho.mqtt.client as mqtt import json THINGSBOARD_HOST = 'thingsboard.example.com' THINGSBOARD_PORT = 1883 CLIENT_ID = 'device-client-id' USERNAME = 'device_username' PASSWORD = 'device_password' def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected with MQTT basic auth") telemetry = {"temperature": 26.5, "humidity": 87} client.publish('v1/devices/me/telemetry', json.dumps(telemetry)) else: print(f"Connection failed with code {rc}") client = mqtt.Client(client_id=CLIENT_ID) client.username_pw_set(username=USERNAME, password=PASSWORD) client.on_connect = on_connect try: client.connect(THINGSBOARD_HOST, THINGSBOARD_PORT, 60) client.loop_forever() except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Relative OPC-UA Path Expression Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/lib/gateway/timeseries-path_fn.md A relative path specifies the address relative to a predefined starting point in the OPC-UA server's namespace. This example demonstrates accessing a 'Temperature' node by first defining the 'Device Node expression' and then the relative expression. ```text Root\.Objects\.TempSensor ``` ```text ${Temperature} ``` -------------------------------- ### Optional: Update ThingsBoard Edge Bind Ports Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/install/ubuntu/instructions.md Updates the ThingsBoard Edge configuration file to change default bind ports (HTTP, MQTT, CoAP) to avoid conflicts if running on the same machine as ThingsBoard Server. Also disables LWM2M and SNMP. ```bash sudo sh -c 'cat <> /etc/tb-edge/conf/tb-edge.conf export HTTP_BIND_PORT=18080 export MQTT_BIND_PORT=11883 export COAP_BIND_PORT=15683 export LWM2M_ENABLED=false export SNMP_ENABLED=false EOL' ``` -------------------------------- ### Run ThingsBoard Migration Tool (Java) Source: https://github.com/guoruilv/thingsboard/blob/master/tools/src/main/java/org/thingsboard/client/tools/migrator/README.md This command executes the ThingsBoard migration tool, converting PostgreSQL dumps into SSTables for Cassandra. It requires the paths to the dumped files and the output directories for different SSTable types. The '-castEnable' flag controls whether casting is enabled. ```java java -jar ./tools-3.2.2-SNAPSHOT-jar-with-dependencies.jar \ -telemetryFrom /home/user/dump/ts_kv_all.dmp \ -relatedEntities /home/user/dump/related_entities.dmp \ -latestOut /home/user/migration/ts_latest \ -tsOut /home/user/migration/ts \ -partitionsOut /home/user/migration/ts_partition \ -castEnable false ``` -------------------------------- ### Format Alarm Start Time using JavaScript Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/lib/alarm/cell_content_fn.md This JavaScript code formats the alarm start time using the provided date/time pattern. It takes the alarm start time as input and uses the widget context's date transformation utility to return a formatted string. If no start time is provided, it returns an empty string. ```javascript var startTime = value; return startTime ? ctx.date.transform(startTime, 'yyyy-MM-dd HH:mm:ss') : ''; ``` -------------------------------- ### Build Migration Tool (Maven) Source: https://github.com/guoruilv/thingsboard/blob/master/tools/src/main/java/org/thingsboard/client/tools/migrator/README.md This snippet shows how to build the ThingsBoard migration tool using Maven. It compiles the code and creates a single JAR file with all dependencies, ready for execution. The generated JAR will be located in the 'target' directory. ```bash cd tools mvn clean compile assembly:single ``` -------------------------------- ### Run Black Box Tests with Maven (Valkey Standalone) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Executes black box tests (excluding UI tests) from the msa/black-box-tests directory using Maven. This configuration uses Valkey standalone as the database. ```bash mvn clean install -DblackBoxTests.skip=false ``` -------------------------------- ### Incoming Message Example (Humidity Sensor) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/customer_attributes_node_fields_templatization.md An example of an incoming message from a humidity sensor, including the message payload and metadata. The 'deviceType' in the metadata is used to fetch corresponding threshold attributes. ```json { "msg": { "humidity": 77 }, "metadata": { "deviceType": "humidity", "deviceName": "HM-001", "ts": "1685379440000" } } ``` -------------------------------- ### Create Data Directory and Set Permissions (Shell) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/tb/README.md This command creates a directory to store ThingsBoard data and sets the correct ownership for the Docker container. It requires sudo permissions to execute. ```shell mkdir -p ~/.mytb-data && sudo chown -R 799:799 ~/.mytb-data ``` -------------------------------- ### Handle MQTT RPC from Server (JavaScript) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/examples/rpc_widget.md A JavaScript client to handle RPC requests sent from the ThingsBoard server. This script connects to the MQTT broker using a device access token and listens for incoming RPC commands. It includes logic to process requests and send back responses. ```javascript const mqtt = require('mqtt'); // Replace with your device access token const ACCESS_TOKEN = 'YOUR_DEVICE_ACCESS_TOKEN'; // MQTT broker details (default ThingsBoard MQTT broker) // If you are using a different MQTT broker, please update the mqtt client parameters accordingly. const MQTT_BROKER = 'mqtt.thingsboard.cloud'; const MQTT_PORT = 1883; const client = mqtt.connect(`mqtt://${MQTT_BROKER}:${MQTT_PORT}`, { username: ACCESS_TOKEN, clientId: `thingsboard-rpc-client-${Math.random().toString(16).substr(2, 8)}` }); const rpcRequestTopic = 'v1/devices/me/rpc/request/0'; const rpcResponseTopic = 'v1/devices/me/rpc/response'; client.on('connect', () => { console.log('Connected to ThingsBoard MQTT broker'); client.subscribe(rpcRequestTopic, (err) => { if (!err) { console.log(`Subscribed to topic: ${rpcRequestTopic}`); } else { console.error('Subscription error:', err); } }); }); client.on('message', (topic, message) => { console.log(`Received message on topic ${topic}: ${message.toString()}`); try { const rpcRequest = JSON.parse(message.toString()); console.log('RPC Request:', rpcRequest); if (rpcRequest.method && rpcRequest.params) { // Handle the RPC request here // For example, call a function based on the method and params const method = rpcRequest.method; const params = rpcRequest.params; const requestId = rpcRequest.id; // Simulate processing the request console.log(`Processing RPC method: ${method} with params: ${JSON.stringify(params)}`); // Simulate a response (e.g., success) const rpcResponse = { id: requestId, result: `Method ${method} executed successfully with params: ${JSON.stringify(params)}` }; client.publish(rpcResponseTopic, JSON.stringify(rpcResponse), (err) => { if (err) { console.error('Failed to publish RPC response:', err); } else { console.log('Published RPC response:', rpcResponse); } }); } else { console.error('Invalid RPC request format'); } } catch (e) { console.error('Error parsing message:', e); } }); client.on('error', (err) => { console.error('Connection error:', err); client.end(); }); client.on('close', () => { console.log('Connection closed'); }); // Graceful shutdown process.on('SIGINT', () => { console.log('Disconnecting...'); client.end(); }); ``` -------------------------------- ### Alarm Notification Template Example with Modifier (Text) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/alarm_comment.md Illustrates a text-based template for alarm notifications that utilizes a templatization parameter with a modifier. This example shows how to capitalize the alarm severity for a more descriptive notification. ```text Alarm '${alarmType}' (${alarmSeverity:capitalize}) was commented ``` -------------------------------- ### Device Authentication: Access Token (HTTP & MQTT) Source: https://context7.com/guoruilv/thingsboard/llms.txt Examples for authenticating devices with ThingsBoard using an access token. It shows how to send telemetry data via HTTP POST request and how to connect and publish data using MQTT with the access token as the username. The password field should be left empty for MQTT authentication. ```bash # HTTP Authentication curl -X POST "https://thingsboard.example.com/api/v1/ACCESS_TOKEN_HERE/telemetry" \ -H "Content-Type: application/json" \ -d '{"temperature": 25.5}' ``` ```python # MQTT Authentication (Python) import paho.mqtt.client as mqtt client = mqtt.Client() client.username_pw_set('ACCESS_TOKEN_HERE') # Token as username, password empty client.connect('thingsboard.example.com', 1883, 60) # Publish telemetry client.publish('v1/devices/me/telemetry', '{"temperature": 25.5}') ``` -------------------------------- ### Example Merged Time Series Output Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/calculated-field/expression_fn.md An example JSON output demonstrating the structure of merged time series data after analysis, indicating identified issues with timestamps and associated values. ```json [ { "ts": 1741613833843, "values": { "issue": { "temperature": -3.12, "defrostState": false } } }, { "ts": 1741613923848, "values": { "issue": { "temperature": -4.16, "defrostState": false } } } ] ``` -------------------------------- ### Specific Time Schedule Format Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/alarm-rule/alarm_rule_schedule_format.md Configures a schedule to be active during specific days and times within a week. It allows defining days of the week, start and end times in milliseconds from the start of the day, and a timezone. The 'type' field can be omitted. ```json { "type": "SPECIFIC_TIME", "daysOfWeek": [ 2, 4 ], "endsOn": 0, "startsOn": 0, "timezone": "Europe/Kiev" } ``` -------------------------------- ### Device Provisioning via REST API Source: https://context7.com/guoruilv/thingsboard/llms.txt Demonstrates how to provision new devices to ThingsBoard using the REST API. Supports provisioning with explicit credentials or auto-generating credentials. Requires 'curl' or a similar HTTP client. The endpoint is accessible without authentication for provisioning. ```bash # POST /api/v1/provision # No authentication required for provisioning endpoint curl -X POST "https://thingsboard.example.com/api/v1/provision" \ -H "Content-Type: application/json" \ -d '{ "deviceName": "Sensor_12345", "provisionDeviceKey": "provision_key_from_profile", "provisionDeviceSecret": "provision_secret_from_profile", "credentialsType": "ACCESS_TOKEN", "token": "custom_access_token_123" }' # Response (200 OK): # { # "status": "SUCCESS", # "credentialsType": "ACCESS_TOKEN", # "credentialsValue": "custom_access_token_123", # "provisionDeviceStatus": "PROVISIONED" # } # Auto-generated token provisioning: curl -X POST "https://thingsboard.example.com/api/v1/provision" \ -H "Content-Type: application/json" \ -d '{ "deviceName": "Sensor_54321", "provisionDeviceKey": "provision_key", "provisionDeviceSecret": "provision_secret" }' # Response includes auto-generated token: # { # "status": "SUCCESS", # "credentialsType": "ACCESS_TOKEN", # "credentialsValue": "auto_generated_token_xyz789", # "provisionDeviceStatus": "PROVISIONED" # } ``` -------------------------------- ### Build ThingsBoard Docker Images with Maven Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Builds local Docker images for ThingsBoard microservices. Ensure you are in the directory containing the main pom.xml. This command skips tests and builds images. ```bash mvn clean install -Ddockerfile.skip=false ``` -------------------------------- ### JavaScript Post-Processing Function Examples Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/config/datakey_postprocess_fn.md A collection of JavaScript examples demonstrating different data post-processing techniques for telemetry data. These functions take the current and previous data points, along with their timestamps, to transform or filter the data. ```javascript return value * 10; ``` ```javascript return Math.round(value); ``` ```javascript if (prevOrigValue) { return (value - prevOrigValue) / prevOrigValue; } else { return 0; } ``` ```javascript if (value) { return moment(value).format("DD/MM/YYYY HH:mm:ss"); } return ''; ``` ```javascript if (value === 0) { return null; } else { return value; } ``` ```javascript return value ? '
Temperature: '+value+' °C
' : ''; ``` -------------------------------- ### Verify Docker Images Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Lists all local Docker images. After building, verify that the expected ThingsBoard microservice images are present in the REPOSITORY column. ```bash docker image ls ``` -------------------------------- ### Get Location from Entity Attributes (JavaScript) Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/action/mobile_get_location_fn.md A JavaScript function that retrieves latitude and longitude from entity attributes. It handles cases where entityId is available and returns an Observable or a default array. Dependencies include widgetContext's attributeService and rxjs. ```javascript return getLocationFromEntityAttributes(); function getLocationFromEntityAttributes() { if (entityId) { return widgetContext.attributeService.getEntityAttributes(entityId, 'SERVER_SCOPE', ['latitude', 'longitude']) .pipe(widgetContext.rxjs .map(function(attributeData) { var res = [0,0]; if (attributeData && attributeData.length === 2) { res[0] = attributeData.filter(function (data) { return data.key === 'latitude'})[0].value; res[1] = attributeData.filter(function (data) { return data.key === 'longitude'})[0].value; } return res; } ) ); } else { return [0,0]; } } ``` -------------------------------- ### Run Black Box Tests with Maven (Valkey Standalone TLS) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Executes black box tests (excluding UI tests) with Valkey standalone and TLS enabled. This command ensures secure communication with the database. ```bash mvn clean install -DblackBoxTests.skip=false -DblackBoxTests.redisSsl=true ``` -------------------------------- ### Example AI Output for Freezer Alarm Analysis Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/ai_node_prompt_settings.md This is an example of the structured JSON output an AI might generate after analyzing a 'High Temperature' alarm for an IoT freezer unit. It includes a human-readable summary and a recommended action for an operator. ```json { "summary": "Critical high temperature alert on freezer unit Freezer-B7. The current temperature is -5°C, which is significantly above the required threshold of -18°C.", "action": "Dispatch technician immediately to inspect the unit's cooling system and ensure the door is properly sealed. Investigate for potential power issues." } ``` -------------------------------- ### Create Docker Volume for Windows (Shell) Source: https://github.com/guoruilv/thingsboard/blob/master/msa/tb/README.md For Windows users, this command creates a Docker-managed volume to store ThingsBoard data instead of using a host directory. This is recommended for better compatibility on Windows. ```shell docker volume create mytb-data ``` -------------------------------- ### Alarm Assignment Notification Template Example 2 Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/alarm_assignment.md This example illustrates a more detailed alarm assignment notification template. It includes the alarm type, alarm severity (capitalized), and a descriptive message about the assignment. The parameter names are enclosed in `${...}`. ```text Alarm '${alarmType}' (${alarmSeverity:capitalize}) was assigned to user ``` -------------------------------- ### Markdown: Create Lists Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/widget/editor/widget_js_markdown_pattern.md Shows how to create unordered lists using the '-' character. Nested lists can be created by indenting with tabs. This pattern is used for organizing information in a structured, readable format within ThingsBoard. ```markdown - Element 1 - Element 2 - Element 2.1 - Element 2.2 - Element 3 ``` -------------------------------- ### Alarm Assignment Notification Template Example 1 Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/notification/alarm_assignment.md This example demonstrates a simple alarm assignment notification template. It shows how to include the alarm type and the action performed, with the action being converted to uppercase. The parameter names are enclosed in `${...}`. ```text Alarm '${alarmType}' - ${action:upperCase} ``` -------------------------------- ### Configure Maven for Local UI Test Execution Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Sets up Maven and IDE configurations to run a specific black-box UI test manually against a locally built UI. This involves adding the module to pom.xml and configuring VM options in the IDE. ```xml org.thingsboard thingsboard-black-box-tests ${thingsboard.version} ``` -------------------------------- ### Example AI Output for Pump Bearing Wear Analysis Source: https://github.com/guoruilv/thingsboard/blob/master/ui-ngx/src/assets/help/en_US/rulenode/ai_node_prompt_settings.md This JSON output is an example of what an AI might generate when analyzing data from a 'Pump-103' indicating potential bearing wear. It includes a summary with specific metrics and a recommendation for inspection and replacement. ```json { "type": "Bearing Wear", "severity": "CRITICAL", "details": { "summary": "Pump-103 showed a vibration spike from 4.2 to 8.0 mm/s with continued elevated levels (6.2–7.2 mm/s), along with a temperature spike to 86 °C and recurrent 84 °C. With acoustics only in the WARNING band (~17–18%), this pattern indicates bearing wear; inspect and replace the bearing promptly to prevent failure." } } ``` -------------------------------- ### Check Available Disk Space (Bash) Source: https://github.com/guoruilv/thingsboard/blob/master/application/src/main/data/json/edge/instructions/upgrade/upgrade_preparing.md This command checks the free disk space on the root filesystem ('/'). It requires sudo privileges. Ensure sufficient free space is available for the database backup. ```bash df -h / ``` -------------------------------- ### Run All Tests (Black-box and UI) with Maven Source: https://github.com/guoruilv/thingsboard/blob/master/msa/black-box-tests/README.md Executes all available tests, including both black-box and UI tests. This provides a comprehensive test run. ```bash mvn clean install -DblackBoxTests.skip=false -Dsuite=all ```