Prepare ThingsBoard Request Subflow
Setting I/O nodes and environmental variables
When creating a subflow user needs to define input node and one or more output nodes, so the messages can pass through our custom implementation. In the top bar there are configuration options enabling us to do that.
Environmental variables can be added to the subflow using the edit properties window, where user can also change the name of the subflow. Environmental variables can be used to make subflow configurable (make subflow reusable in different configurations). For example user can specify environmental variable named addID which is of type boolean and build custom implementation of the code based on this environmental variable where subflow outputs JS object which does or doesnt include ID based on selected option when deploying the subflow.
Inside the subflow environmental variables are accessible with: env.get(’);
Prerequisites
This subflow assumes that you are working with specific type of object, we have predefined for all our examples. This is the said structure:
{
"id": 1,
"timestamp": 2021-04-19T00:00:00Z,
"data": {
"measurement1": 0.35,
"measurement2": 1.91
}
}
If your message object has a structure without nested objects you dont need to use this subflow.
Setting function node for HTTP Request body generation
Function Node is powerful Node-RED node which enables us to add our Custom Javascript code to Node-RED without the need to make custom nodes.
This function Node implements Javascript code moves nested properties to the first level Javascript object, this is done using for-loop and typeof method to find the type of property:
for (let key in inputObject) {
if (typeof inputObject[key] !== 'object') {
outputObject[key] = inputObject[key];
} else {
let dataObject = inputObject[key];
for (let key in dataObject) {
outputObject[key] = dataObject[key];
}
}
}
Sending data to ThingsBoard is done over the HTTP Requests. With the previous for-loop we constructed message body, which should be javascript object, another object needs to be constructed for succesful request which is header, headers can be passed inside the HTTP Request node inside the msg.headers property.