TCP Integration
TCP Integration receives data from devices that send it over a TCP connection and converts the payload into ThingsBoard telemetry and attributes. It also supports downlink: the Edge can send a message back over the same connection.
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 TCP integration service. Port 10560 must be open for incoming connections there.
- The
echocommand andnetcat(nc) to simulate a device.
The example device SN-002 sends temperature and humidity readings to port 10560. Pick the payload format that matches your device:
SN-002,default,temperature,25.7\r\nSN-002,default,humidity,69[{"deviceName": "SN-002", "deviceType": "default", "temperature": 25.7, "humidity": 69}]\x30\x30\x30\x30\x11\x53\x4e\x2d\x30\x30\x32\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x00\x00\x00| Bytes | Hex | Value | Description |
|---|---|---|---|
| 0-3 | \x30\x30\x30\x30 |
none | Dummy prefix (skipped) |
| 4 | \x11 |
17 | Payload length in bytes |
| 5-10 | \x53\x4e\x2d\x30\x30\x32 |
SN-002 |
Device name |
| 11-17 | \x64\x65\x66\x61\x75\x6c\x74 |
default |
Device type |
| 18-21 | \x32\x35\x2e\x37 |
25.7 |
Temperature |
| 22-24 | \x00\x00\x00 |
none | Dummy suffix (ignored) |
Create converter templates
Section titled “Create converter templates”Converter templates are created on the server. The uplink converter decodes the TCP 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 TCP as the Integration type, and enter the name
TCP 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, "").split(',');var telemetryKey = payloadArray[2];var telemetryValue = payloadArray[3];var telemetryPayload = {};telemetryPayload[telemetryKey] = telemetryValue;var 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))}};function decodeToString(payload) {return String.fromCharCode.apply(String, payload);}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 TCP as the Integration type, and enter the name
TCP 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 TCP as the Integration type. Keep the name
TCP integrationor enter your own. Click Next. -
On the Uplink data converter step, select Select existing, choose
TCP uplink converter, and click Next. -
On the Downlink data converter step, select Select existing, choose
TCP downlink converter, and click Next. -
On the Connection step, keep Port at
10560. Under Handler Configuration, select the handler for your payload format and fill in its fields:Field Value Handler Configuration TEXT Max Frame Length (in bytes) 128Strip delimiter enabled (removes the newline from the payload) Message separator type System line separator Field Value Handler Configuration JSON Field Value Handler Configuration BINARY (the default) Max Frame Length (in bytes) 128Length Field Offset 4(the length byte\x11is at position 4, after the four dummy bytes)Length Field Length 1(one byte holds the length)Length Adjustment (the compensation value to add to the value of the length field) 0Number of first bytes to strip out from the decoded frame 5(the four dummy bytes plus the length byte) -
Execute remotely is enabled and cannot be turned off, because TCP 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 socket settings on the Connection step keep their defaults:
| Setting | Description |
|---|---|
| Max number of pending connects on the socket | Queue length for incoming connection requests. New connections are refused when the queue is full. |
| Size of the buffer for inbound socket (in KB) | Socket receive buffer size. |
| Size of the buffer for outbound socket (in KB) | Socket send buffer size. |
| Enable sending of keep-alive messages on connection-oriented sockets | Sends periodic keep-alive probes to check that the connection is still alive. |
| Forces a socket to send the data without buffering (disable Nagle’s buffering algorithm) | Sends data immediately instead of buffering it. |
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
TCP integration, and click Assign. -
Log in to the Edge and go to Integrations > Integrations. The TCP integration is listed there.
Install and run the remote TCP integration
Section titled “Install and run the remote TCP 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 10560:10560 \-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 10560:10560Publishes port 10560 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 port 10560.
Send an uplink message
Section titled “Send an uplink message”-
Send a test message with
echoandnc. Pick the command for your payload format:One message:
Terminal window echo -e 'SN-002,default,temperature,25.7' | nc -q0 127.0.0.1 10560Several messages in one connection, separated by a newline:
Terminal window echo -e 'SN-002,default,temperature,25.7\nSN-002,default,humidity,69' | nc -q1 -w1 127.0.0.1 10560Terminal window echo -e -n '{"deviceName": "SN-002", "deviceType": "default", "temperature": 25.7, "humidity": 69}' | nc -q1 -w1 127.0.0.1 10560Terminal window echo -e -n '\x30\x30\x30\x30\x11\x53\x4e\x2d\x30\x30\x32\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x00\x00\x00' | nc -q1 -w1 127.0.0.1 10560 -
On the Edge, go to Integrations > Integrations, open the TCP integration, and select the Events tab. An Uplink event with status OK appears.
-
The device SN-002 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
TCP 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
TCP 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 over an open TCP connection of the device. In the test below, nc keeps the connection open and prints the response.
-
On the Edge, go to Devices & assets > Devices, open SN-002, 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.
-
Send an uplink message again, this time keeping the connection open (without
-q0):Terminal window echo -e 'SN-002,default,temperature,25.7' | nc 127.0.0.1 10560Several messages:
Terminal window echo -e 'SN-002,default,temperature,25.7\nSN-002,default,humidity,69' | nc -w60 127.0.0.1 10560Terminal window echo -e -n '{"deviceName": "SN-002", "deviceType": "default", "temperature": 25.7, "humidity": 69}' | nc -w60 127.0.0.1 10560Terminal window echo -e -n '\x30\x30\x30\x30\x11\x53\x4e\x2d\x30\x30\x32\x64\x65\x66\x61\x75\x6c\x74\x32\x35\x2e\x37\x00\x00\x00' | nc -w60 127.0.0.1 10560The terminal prints the response from the Edge:
{"firmware":"v1.0"}
Was this helpful?