Skip to main content
All CollectionsConnect your Devices
Send data from embedded Linux devices using Python
Send data from embedded Linux devices using Python

A simple command-line client to reuse in your Linux device

Sergio M avatar
Written by Sergio M
Updated over 3 months ago

In the world of the Internet of Things (IoT), Linux has emerged as a popular operating system for IoT devices. Its popularity can be attributed to Linux's flexibility, robustness, open-source nature, and a rich set of tools, libraries, and utilities that make it ideal for IoT solutions. One such utility is Python, a powerful, easy-to-learn, and widely-used programming language.

Python, with its vast selection of libraries, simplifies the task of data collection, processing, and transmission. It enables IoT devices to communicate with cloud platforms and send data for further analysis and visualization.

A wide array of industrial IoT devices and gateways are now powered by Linux, opening up new opportunities for leveraging the potential of these devices. Some of these include:

  1. Robustel: Their R3000 LG and R2000 Dual industrial routers are powered by Linux and provide secure and reliable connectivity.

  2. NCD.io: NCD.io offers the PR55-17B Industrial IoT Linux Wireless Gateway which is capable of high-performance data aggregation.

  3. Advantech: The company offers a range of Linux-based devices, including the ECU-1000 series of industrial IoT gateways.

  4. Red Lion: Their Sixnet® series RTUs (Remote Terminal Units) and IndustrialPro® SN-6000 cellular routers come with robust Linux platforms.

  5. Revolution Pi: The Revolution Pi series, based on the Raspberry Pi platform, are open-source, modular, and industrial-grade PLCs running on Linux.

  6. OWASYS: Known for their advanced Linux-based embedded devices like owa5X IoT Gateways.

Given the proliferation of these Linux-based IoT devices, we have created a Python script that can send data from these devices to the Ubidots platform. The data can be sent over HTTP or MQTT, two widely used IoT protocols.

Python Script

From the Command Line:

  1. Install Required Libraries: If not already installed, install the necessary Python libraries using pip:

    pip install paho-mqtt
    pip install requests

  2. Create Python file: Create a file called ubidots_send.py and enter the following script:

import sys
import requests
import json
from paho.mqtt import client as mqtt_client

def send_http(payload, device_label, token):
url = f"https://industrial.api.ubidots.com/api/v1.6/devices/{device_label}"
headers = {"X-Auth-Token": token, "Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=payload)
print(response.text)

def send_mqtt(payload, device_label, token):
broker = 'industrial.api.ubidots.com'
port = 1883
topic = f"/v1.6/devices/{device_label}"

client_id = token
username = token
password = ''

def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)

client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client

def publish(client):
msg = json.dumps(payload)
result = client.publish(topic, msg)
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")

client = connect_mqtt()
publish(client)

def main():
args = sys.argv
if len(args) != 5:
print("Usage: python script.py payload device_label token protocol")
return

# In this line, you should replace the variables below, with the ones expected according to your application:
payload = dict(zip(
["engine_rpm", "oil_level", "oil_temperature", "fuel_level", "engine_temperature", "ambient_temperature", "runtime", "estimated_fuel_efficiency", "lat", "lng"],
map(float, args[1].split(','))
))
device_label = args[2]
token = args[3]
protocol = args[4]

if protocol == "http":
send_http(payload, device_label, token)
elif protocol == "mqtt":
send_mqtt(payload, device_label, token)
else:
print("Invalid protocol. Use 'http' or 'mqtt'")

if __name__ == "__main__":
main()

3. Prepare Your Data: In the following line, replace the variables below, with the ones expected according to your application:

payload = dict(zip(["engine_rpm", "oil_level", "oil_temperature", "fuel_level", "engine_temperature", "ambient_temperature", "runtime", "estimated_fuel_efficiency", "lat", "lng"], map(float, args[1].split(','))))

4. Run the Script: Run the script from the terminal, passing the required arguments: payload, Ubidots device-label, Ubidots token, and the desired protocol. Use the following command, replacing the placeholders with your actual data:

python ubidots_send.py "1000,50,80,75,100,20,300,15,40.712776,-74.005974" my-device my-token http

For example:

python ubidots_send.py "1000,50,80,75,100,20,300,15,40.712776,-74.005974" my-device BBFF-UMrU5BPuGAltESk8UyHJXVkhTSudQ4 mqtt 

Results

After running the command, the following response is expected:

python ubidots_send.py "1000,50,80,75,100,20,300,15,40.712776,-74.005974" my-device BBFF-UMrU5BPuGAltESk8UyHJXVkhTSudQ4 mqtt 

Send `{"engine_rpm": 1000.0, "oil_level": 50.0, "oil_temperature": 80.0, "fuel_level": 75.0, "engine_temperature": 100.0, "ambient_temperature": 20.0, "runtime": 300.0, "estimated_fuel_efficiency": 15.0, "lat": 40.712776, "lng": -74.005974}` to topic `/v1.6/devices/my-device`

...and then the data can be seen in your Ubidots account:

Others found useful...

Did this answer your question?