Getting Started with Python Industrial IoT Platform
Hello everyone! Today I want to share with you the basics of developing an industrial IoT platform using Python. An industrial IoT platform is an essential infrastructure that connects industrial devices, collects data, and analyzes data. With Python, we can quickly build a lightweight industrial IoT platform. Let’s start our learning today!
1. Basics of MQTT Communication
First, we need to implement device communication. MQTT is the most commonly used communication protocol in IoT, and we will use the paho-mqtt library in Python to implement it:
import paho.mqtt.client as mqtt
# Create MQTT client
client = mqtt.Client()
# Connection callback
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
client.subscribe("device/+/data") # Subscribe to all device data topics
# Message callback
def on_message(client, userdata, msg):
print(f"Received message Topic: {msg.topic} Data: {msg.payload}")
client.on_connect = on_connect
client.on_message = on_message
# Connect to MQTT server
client.connect("localhost", 1883, 60)
client.loop_forever()
2. Data Collection and Storage
After collecting device data, we need to store it in a database. Here we demonstrate using SQLite:
import sqlite3
import json
def save_device_data(device_id, data):
conn = sqlite3.connect('iot.db')
c = conn.cursor()
# Create data table
c.execute('''CREATE TABLE IF NOT EXISTS device_data
(id INTEGER PRIMARY KEY AUTOINCREMENT,
device_id TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
data TEXT)''')
# Insert data
c.execute("INSERT INTO device_data (device_id, data) VALUES (?, ?)",
(device_id, json.dumps(data)))
conn.commit()
conn.close()
3. Data Analysis and Processing
Perform real-time analysis and processing of the collected data:
import pandas as pd
import numpy as np
def analyze_device_data(device_id):
conn = sqlite3.connect('iot.db')
# Read device data
df = pd.read_sql_query(
"SELECT * FROM device_data WHERE device_id=?",
conn,
params=[device_id]
)
# Calculate statistics
data = json.loads(df['data'].iloc[-1])
temperature = data.get('temperature')
# Simple anomaly detection
if temperature > 80:
send_alert(device_id, "Temperature too high!")
conn.close()
4. Web API Interface
Use the Flask framework to provide a Web API:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/api/devices', methods=['GET'])
def get_devices():
# Get the list of all devices
return jsonify({
'devices': [
{'id': 'device1', 'name': 'Device 1'},
{'id': 'device2', 'name': 'Device 2'}
]
})
@app.route('/api/device/<device_id>/data', methods=['GET'])
def get_device_data(device_id):
# Get historical data of the device
conn = sqlite3.connect('iot.db')
cursor = conn.cursor()
cursor.execute(
"SELECT * FROM device_data WHERE device_id=? ORDER BY timestamp DESC LIMIT 100",
[device_id]
)
data = cursor.fetchall()
conn.close()
return jsonify({'data': data})
if __name__ == '__main__':
app.run(debug=True)</device_id>
Tips:
-
In actual projects, it is recommended to use more powerful databases like MySQL or MongoDB.
-
Production environments need to add authentication and security protection.
-
You can use asyncio for asynchronous processing to improve performance.
Today we learned the basics of building an industrial IoT platform using Python, including MQTT communication, data collection and storage, analysis and processing, and Web API development. These are all core components of an industrial IoT platform.
Friends, today’s journey of learning Python ends here! Remember to practice these codes, and you can also try adding new features. Feel free to ask me any questions in the comments. I wish you all happy learning and continuous improvement in Python!
Click to read the full article and learn more.