UDP Integration
UDP Integration receives data from devices that send it over UDP and converts the payload into ThingsBoard telemetry and attributes. It also supports downlink: the Edge can send a message back through the same UDP socket.
Prerequisites
Section titled “Prerequisites”- A ThingsBoard server with tenant administrator access. The templates are created there.
- A ThingsBoard Edge instance connected to the server.
- Docker on the machine that will run the UDP integration service. UDP port 11560 must be open for incoming packets there.
- The
echocommand andnetcat(nc) to simulate a device.
The example device SN-001 sends temperature and humidity readings to port 11560. Pick the payload format that matches your device:
SN-001,default,temperature,25.7,humidity,69[{"deviceName": "SN-001", "deviceType": "default", "temperature": 25.7, "humidity": 69}]\x53\x4e\x2d\x30\x30\x31\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x36\x39| Bytes | Hex | Value | Description |
|---|---|---|---|
| 0-5 | \x53\x4e\x2d\x30\x30\x31 |
SN-001 |
Device name |
| 6-12 | \x64\x65\x66\x61\x75\x6c\x74 |
default |
Device type |
| 13-16 | \x32\x35\x2e\x37 |
25.7 |
Temperature |
| 17-18 | \x36\x39 |
69 |
Humidity |
534e2d30303164656661756c7432352e373639Each pair of hex digits is one byte:
| Bytes | Hex | Value | Description |
|---|---|---|---|
| 0-5 | 534e2d303031 |
SN-001 |
Device name |
| 6-12 | 64656661756c74 |
default |
Device type |
| 13-16 | 32352e37 |
25.7 |
Temperature |
| 17-18 | 3639 |
69 |
Humidity |
Create converter templates
Section titled “Create converter templates”Converter templates are created on the server. The uplink converter decodes the UDP payload into telemetry and attributes. The downlink converter encodes messages from the rule engine, for example shared attribute updates, into the message sent back to the device.
Uplink converter
Section titled “Uplink converter”-
On the server, go to Edge management > Templates and open the Converter tab. Click Add data converter and select Create new converter.
-
Set Converter type to Uplink, select UDP as the Integration type, and enter the name
UDP uplink converter. -
In Main decoding configuration, select JS, paste the script for your payload format, and click Add.
/** Decoder **/// decode payload to stringvar strArray = decodeToString(payload);var payloadArray = strArray.replace(/\"/g, "").replace(/\s/g, "").replace(/\\n/g, "").split(',');var telemetryPayload = {};for (var i = 2; i < payloadArray.length; i = i + 2) {var telemetryKey = payloadArray[i];var telemetryValue = parseFloat(payloadArray[i + 1]);telemetryPayload[telemetryKey] = telemetryValue;}// Result object with device attributes/telemetry datavar result = {deviceName: payloadArray[0],deviceType: payloadArray[1],telemetry: telemetryPayload,attributes: {}};function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}return result;/** Decoder **/// decode payload to JSONvar data = decodeToJson(payload);var result = {deviceName: data.deviceName,deviceType: data.deviceType,attributes: {},telemetry: {temperature: data.temperature,humidity: data.humidity}};function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}function decodeToJson(payload) {var str = decodeToString(payload);return JSON.parse(str);}return result;/** Decoder **/// decode payload to stringvar payloadStr = decodeToString(payload);var deviceName = payloadStr.substring(0, 6);var deviceType = payloadStr.substring(6, 13);var result = {deviceName: deviceName,deviceType: deviceType,attributes: {},telemetry: {temperature: parseFloat(payloadStr.substring(13, 17)),humidity: parseFloat(payloadStr.substring(17, 19))}};function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}return result;/** Decoder **/// decode payload to JSON — HEX handler wraps the hex string in a reports structurevar data = decodeToJson(payload).reports[0].value;var result = {deviceName: hexToString(data.substring(0, 12)),deviceType: hexToString(data.substring(12, 26)),telemetry: {temperature: parseFloat(hexToString(data.substring(26, 34))),humidity: parseFloat(hexToString(data.substring(34, 38))),}};function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}function hexToString(hex) {var str = '';for (var i = 0; i < hex.length; i += 2) {var notNullValue = parseInt(hex.substr(i, 2), 16);if (notNullValue) {str += String.fromCharCode(notNullValue);}}return str;}function decodeToJson(payload) {var str = decodeToString(payload);return JSON.parse(str);}return result;
To change a converter later, open it on the Converter tab, click the pencil icon, edit the script, and click the checkmark icon. The change is pushed to every Edge that uses it.
Downlink converter
Section titled “Downlink converter”-
On the Converter tab, click Add data converter and select Create new converter.
-
Set Converter type to Downlink, select UDP as the Integration type, and enter the name
UDP downlink converter. -
In Main encoding configuration, select JS, paste the following script, and click Add:
// Encode downlink data from incoming Rule Engine message// msg - JSON message payload// msgType - e.g. 'ATTRIBUTES_UPDATED', 'POST_TELEMETRY_REQUEST'// metadata - key/value pairs with message metadata// integrationMetadata - key/value pairs defined in the Integrationvar result = {// downlink data content type: JSON, TEXT or BINARY (base64 format)contentType: "JSON",// downlink datadata: JSON.stringify(msg),// Optional metadata object presented in key/value formatmetadata: {}};return result;
Create integration template
Section titled “Create integration template”-
On the server, go to Edge management > Templates, open the Integration tab, and click Add integration.
-
On the Basic settings step, select UDP as the Integration type. Keep the name
UDP integrationor enter your own. Click Next. -
On the Uplink data converter step, select Select existing, choose
UDP uplink converter, and click Next. -
On the Downlink data converter step, select Select existing, choose
UDP downlink converter, and click Next. -
On the Connection step, keep Port at
11560(or enter another free port). Under Handler Configuration, select the handler for your payload format:Field Value Handler Configuration TEXT Charset Name UTF-8(the default)Field Value Handler Configuration JSON Field Value Handler Configuration BINARY (the default) Field Value Handler Configuration HEX -
Execute remotely is enabled and cannot be turned off, because UDP Integration runs only as a remote service. Copy the Integration key and Integration secret shown under it. You need them to start the service.
-
Click Add.
The other settings on the Connection step keep their defaults:
| Setting | Description |
|---|---|
| Size of the buffer for inbound socket (in KB) | Socket receive buffer size. |
| Cache Size | Maximum number of cached UDP sessions. |
| Cache time to live in minutes | How long a UDP session stays in the cache. |
| Enable broadcast - integration will accepts broadcast address packets | Accepts packets sent to the broadcast address. |
Assign the integration to the Edge
Section titled “Assign the integration to the Edge”-
On the server, go to Edge management > Edges and click the Edge. On the Details tab, click Manage integrations.
-
Click Assign to edge (+), select
UDP integration, and click Assign. -
Log in to the Edge and go to Integrations > Integrations. The UDP integration is listed there.
Install and run the remote UDP integration
Section titled “Install and run the remote UDP integration”The remote service connects to the Edge through the integration RPC port, 9090 by default (INTEGRATIONS_RPC_PORT in tb-edge.yml), and identifies itself with the Integration key and Integration secret of the template. See also Remote integrations.
-
Pull the image:
Terminal window docker pull thingsboard/tb-tcp-udp-integration:4.4.0.2 -
Create a directory for the logs:
Terminal window mkdir -p ~/.tb-pe-tcp-udp-integration-logs && sudo chown -R 799:799 ~/.tb-pe-tcp-udp-integration-logs -
Start the service. Replace the placeholders with your values:
Terminal window docker run -it -p 11560:11560/udp \-v ~/.tb-pe-tcp-udp-integration-logs:/var/log/tb-tcp-udp-integration \-e "RPC_HOST=mytbedge" \-e "RPC_PORT=9090" \-e "INTEGRATION_ROUTING_KEY=YOUR_ROUTING_KEY" \-e "INTEGRATION_SECRET=YOUR_SECRET" \--name my-tb-pe-tcp-udp-integration \--network NETWORK_NAME \--restart always \thingsboard/tb-tcp-udp-integration:4.4.0.2Parameter Description mytbedgeHostname of the Edge service 9090Integration RPC port of the Edge -p 11560:11560/udpPublishes UDP port 11560 of the container on the host YOUR_ROUTING_KEYIntegration key of the template YOUR_SECRETIntegration secret of the template NETWORK_NAMEDocker network of the Edge container. Find it with docker network ls.
To detach from the container without stopping it, press Ctrl+p then Ctrl+q. Useful commands:
docker attach my-tb-pe-tcp-udp-integration # reattach to the logsdocker stop my-tb-pe-tcp-udp-integrationdocker start my-tb-pe-tcp-udp-integrationOnce the service is running, it listens on UDP port 11560.
Send an uplink message
Section titled “Send an uplink message”-
Send a test message with
echoandnc. Pick the command for your payload format:Terminal window echo -e 'SN-001,default,temperature,25.7,humidity,69' | nc -w5 -u 127.0.0.1 11560Terminal window echo -e -n '{"deviceName": "SN-001", "deviceType": "default", "temperature": 25.7, "humidity": 69}' | nc -w60 -u 127.0.0.1 11560Terminal window echo -e -n '\x53\x4e\x2d\x30\x30\x31\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x36\x39' | nc -w5 -u 127.0.0.1 11560Terminal window echo -e -n '534e2d30303164656661756c7432352e373639' | xxd -r -p | nc -w5 -u 127.0.0.1 11560 -
On the Edge, go to Integrations > Integrations, open the UDP integration, and select the Events tab. An Uplink event with status OK appears.
-
The device SN-001 is created automatically. On the Edge, go to Devices & assets > Devices, open it, and select the Latest telemetry tab to see the received values.
-
To see how the converter processed the message, go to Integrations > Data converters, open
UDP uplink converter, and select the Events tab. Click the three dots in the In column to see the raw payload, or in the Out column to see the decoded result.
Configure the rule chain for downlinks
Section titled “Configure the rule chain for downlinks”To send messages from the rule engine to the integration, add an integration downlink node to the root rule chain of the Edge.
-
On the Edge, go to Data processing > Rule chains and open Edge Root Rule Chain.
-
In the node search field, type
integration downlinkand drag the integration downlink node onto the canvas. -
Enter a name, select
UDP integrationin the Integration field, and click Add. -
Connect the message type switch node to the new node and select the Attributes Updated link label.
-
Click the checkmark icon to save the rule chain.
Send a downlink message
Section titled “Send a downlink message”The integration sends the downlink to the address the device last sent a packet from, as long as its UDP session is still cached. In the test below, nc sends the uplink and then waits 120 seconds for the response.
-
Send an uplink message with
-q120, so thatnckeeps waiting for the response:Terminal window echo -e 'SN-001,default,temperature,25.7,humidity,69' | nc -q120 -u 127.0.0.1 11560Terminal window echo -e -n '{"deviceName": "SN-001", "deviceType": "default", "temperature": 25.7, "humidity": 69}' | nc -q120 -u 127.0.0.1 11560Terminal window echo -e -n '\x53\x4e\x2d\x30\x30\x31\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x36\x39' | nc -q120 -u 127.0.0.1 11560Terminal window echo -e -n '534e2d30303164656661756c7432352e373639' | xxd -r -p | nc -q120 -u 127.0.0.1 11560 -
Within these 120 seconds, on the Edge, go to Devices & assets > Devices, open SN-001, and select the Attributes tab. Select the Shared attributes scope, click +, enter the key
firmwareand the valuev1.0, and click Add. -
Open the Events tab of the integration. A Downlink event with status OK appears.
-
The terminal prints the response from the Edge:
{"firmware":"v1.0"}
Was this helpful?