The TRB140 is an ultra-small, lightweight, and energy-efficient IoT device with mission-critical LTE Cat 4 and Gigabit Ethernet connectivity options. Its Linux environment offers a high degree of customization.
This gateway is perfect for projects and applications where a single device must be upgraded with reliable and secure internet connectivity.
In this guide, the TRB polls humidity and temperature data from a Modbus server and then sends the data to Ubidots via HTTP.
This guide should also work for other Teltonika routers and gateways that support the Mobdus protocol, such as:
|
Follow steps 1 through 4 from the following guide in order to learn how to set up the hardware, access it via Ethernet and configure the Modbus service on your device. Once completed, come back here.
1. Set up the Data to Server service
The next step is to configure sending the data retrieved from the Modbus server to Ubidots.
Go to Ubidots → Devices → Functions and create a new UbiFunction.
Give it any name that you find appropriate.
Set the method to POST.
Set the runtime to Python 3.11 Lite.
Set the Ubidots token.
In the code section, paste the following:
import requests
import time
import ast
import json
# Base url to perform request to Ubidots API
BASE_URL = "https://industrial.api.ubidots.com"
REQUESTS_FUNCTIONS = {"get": requests.get, "post": requests.post}
# If you changed the data configuration name to other
# than the one used in the article, set this variable to that name
DATA_CONFIGURATION_NAME: str = 'ModbusServerDataHTTP'
def main(args):
# Print args for debug
print(args)
# Get the payload containing the data of our interest
data: dict = args[DATA_CONFIGURATION_NAME]
# Build the device label using the server name and its ip address
device_label: str = data['server_name'].replace('_', '-') + '-' + data['ip'].replace('.', '-')
# Get the variable's name
variable_label: str = data['name']
# Divide the value by 10 according to the device's datasheet. Adjust this accordingly
value: int = int(data['data']) / 10
# Get the Ubidots token
token: str = args.get('token', None)
if token is None:
print("[ERROR] Please configure you Ubidots token for this Ubifunction or define it within it.")
return {"status": "error"}
if not data:
print("No data")
return {"error" : "No data present in the payload"}
payload: dict = {variable_label : value}
req = update_device(device_label, payload, token)
print("[INFO] Request result:")
print(req.text)
return {"status": "Ok", "result": req.json()}
def update_device(device, payload, token):
"""
updates a variable with a single dot
"""
url = "{}/api/v1.6/devices/{}".format(BASE_URL, device)
headers = {"X-Auth-Token": token, "Content-Type": "application/json"}
req = create_request(url, headers, payload, attempts=5, request_type="post")
return req
def create_request(url, headers, data, attempts, request_type):
"""
Function to create a request to the server
"""
request_func = REQUESTS_FUNCTIONS.get(request_type)
kwargs = {"url": url, "headers": headers}
if request_type == "post":
kwargs["json"] = data
try:
req = request_func(**kwargs)
print("[INFO] Request result: {}".format(req.text))
status_code = req.status_code
time.sleep(1)
while status_code >= 400 and attempts < 5:
req = request_func(**kwargs)
print("[INFO] Request result: {}".format(req.text))
status_code = req.status_code
attempts += 1
time.sleep(1)
return req
except Exception as e:
print("[ERROR] There was an error with the request, details:")
print(e)
return None
Click on the "save & deploy" button to save the UbiFunction. After this, make sure to copy the function's HTTPS endpoint URL:
Go back to the TRB140's web configuration interface and go to Services → Data to Server.
If you are coming straight from the previous guide, make sure to disable the MQTT connection created before, just to make sure that the data is sent via HTTP.
After that, under the ADD NEW INSTANCE section, write a NEW COLLECTION NAME, and then click on the "ADD" button:
Once you do that, the DATA CONFIGURATION screen will pop-up with an empty configuration. Edit it to set the following configuration:
Fill the "name" field with any name that helps you identify this configuration. One thing to take into account is that the payload that you'll receive on Ubidots is under the payload/<data-configuration-name> key. For example, if you name this configuration ModbusServerData, then the data arriving on Ubidots will be under Payload → modbusserverdata.ame, different than the one used for the previous MQTT connection. In this guide, the name used was ModbusServerDataHTTP.
In the "type" field, choose Modbus. This will select the data source to be the Modbus server data.
In "format type", select JSON. This is so that the received data on Ubidots is a JSON and not a JSON-formatted string.
Make sure to enable the "send as object" option.
Leave the other settings unchanged.
Scroll down until you find the button to keep going with the configuration and click on it:
In the next configuration page, make sure to turn on the "enable" button next to GENERAL SETTINGS and leave the format type set to JSON.
You can set the data publishing period by going to the ADVANCED SETTINGS tab. Here, the "period" option allows you to select the data sending interval in seconds. Once done, click on the "next" button.
Once the SERVER CONFIGURATION is displayed, set the following configuration:
Select the "type" to HTTP.
In the "server address" field, set the function's HTTPS endpoint URL obtained before.
In the HTTP headers section, add the following headers:
Header | Value |
Content-type | application/json |
X-Auth-Token | Your Ubidots account token |
Then, click on the "SAVE & APPLY" button.
2. Checking the received data on Ubidots
Upon completing the steps above, you'll be able to see data being received on your device on Ubidots through the UbiFunction: