Python MQTT Client for SiliconWit IO
In this tutorial, you will learn how to build a Python MQTT client that sends sensor telemetry data (temperature and humidity) to the SiliconWit IO IoT platform. The client connects to the SiliconWit IO MQTT broker over a secure TLS connection on port 8883 and publishes JSON-formatted data at regular intervals.
Python is an excellent choice for IoT gateways, edge devices, and rapid prototyping. This tutorial works on any system that runs Python — Linux, macOS, Windows, or single-board computers like the Raspberry Pi.
What You Will Learn
Section titled “What You Will Learn”- How to install and configure the
paho-mqttPython library - How to establish a secure TLS connection to the SiliconWit IO MQTT broker
- How to authenticate using your device credentials
- How to publish JSON telemetry data on a schedule
- How to handle connection errors and automatic reconnection
Prerequisites
Section titled “Prerequisites”| Requirement | Details |
|---|---|
| Python | Version 3.8 or later |
| pip | Python package manager (included with Python) |
| SiliconWit IO Account | Free IoT platform account |
| A registered device | Created from the SiliconWit IO dashboard |
You will need the following credentials from your SiliconWit IO dashboard after registering a device:
| Credential | Example | Description |
|---|---|---|
| Device ID | AbCdEfGhIj | Unique 10-character identifier (used as MQTT username) |
| Access Token | your_access_token_here | MQTT password |
| Publish Topic | d/{device_id}/t | Topic for sending sensor data (d = device, t = telemetry) |
Keep your access token secure. Never share it publicly or commit it to version control.
Step 1: Install paho-mqtt
Section titled “Step 1: Install paho-mqtt”Open a terminal and install the paho-mqtt library using pip:
pip install paho-mqttVerify the installation:
python -c "import paho.mqtt.client as mqtt; print(mqtt.__version__)"If you are using a virtual environment (recommended), activate it before running pip install. For example:
python -m venv venv && source venv/bin/activate.
Step 2: Understand the Connection Architecture
Section titled “Step 2: Understand the Connection Architecture”The Python client connects directly to the SiliconWit IO MQTT broker over TLS:
┌─────────────────────────────────────────────────────────┐│ SiliconWit IO Cloud ││ ││ Dashboard <--> MQTT Broker (TLS on port 8883) ││ | ││ Telemetry Topic ││ d/{device_id}/t │└────────────────────┬────────────────────────────────────┘ │ │ TLS 1.2 (port 8883) │┌────────────────────┴────────────────────────────────────┐│ Python Client (paho-mqtt) ││ ││ - Connects with TLS ││ - Authenticates with device_id + access_token ││ - Publishes JSON telemetry every 10 seconds │└─────────────────────────────────────────────────────────┘Step 3: Set Up TLS for Secure Connection
Section titled “Step 3: Set Up TLS for Secure Connection”The SiliconWit IO MQTT broker requires TLS encryption on port 8883. The paho-mqtt library supports TLS natively through Python’s built-in ssl module. No additional certificates need to be downloaded — the client uses your system’s default trusted CA certificates.
import ssl
# TLS configuration uses the system's default CA certificatesclient.tls_set(tls_version=ssl.PROTOCOL_TLS_CLIENT)This single line configures the client to:
- Use TLS 1.2 or later
- Verify the server certificate against your system’s trusted CA store
- Encrypt all traffic between your client and the broker
Step 4: Connect and Authenticate
Section titled “Step 4: Connect and Authenticate”SiliconWit IO uses your Device ID as the MQTT username and your Access Token as the password. The Device ID also serves as the MQTT client ID.
MQTT_BROKER = "mqtt.siliconwit.io"MQTT_PORT = 8883DEVICE_ID = "YOUR_DEVICE_ID"ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"
client.username_pw_set(DEVICE_ID, ACCESS_TOKEN)client.connect(MQTT_BROKER, MQTT_PORT, keepalive=60)Step 5: Publish JSON Telemetry
Section titled “Step 5: Publish JSON Telemetry”The telemetry payload is a JSON object containing your sensor readings. SiliconWit IO accepts any valid JSON structure, so you can include whatever fields your application needs.
import jsonimport random
payload = { "temperature": round(random.uniform(20.0, 35.0), 1), "humidity": round(random.uniform(30.0, 80.0), 1)}
topic = f"d/{DEVICE_ID}/t"client.publish(topic, json.dumps(payload))| Field | Type | Description |
|---|---|---|
temperature | float | Temperature reading in degrees Celsius |
humidity | float | Relative humidity percentage |
You can add any additional fields. SiliconWit IO automatically detects and displays new data fields on the dashboard.
Step 6: Full Code
Section titled “Step 6: Full Code”Create a file called mqtt_client.py with the following complete code:
import sslimport jsonimport timeimport randomimport paho.mqtt.client as mqtt
# ========== SILICONWIT IO MQTT CONFIGURATION ==========MQTT_BROKER = "mqtt.siliconwit.io"MQTT_PORT = 8883DEVICE_ID = "YOUR_DEVICE_ID"ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"PUBLISH_TOPIC = f"d/{DEVICE_ID}/t"
# ========== TIMING ==========TELEMETRY_INTERVAL = 10 # seconds
# ========== CALLBACKS ==========def on_connect(client, userdata, flags, reason_code, properties): if reason_code == 0: print(f"[MQTT] Connected to SiliconWit IO") else: print(f"[MQTT] Connection failed with code: {reason_code}")
def on_disconnect(client, userdata, flags, reason_code, properties): print(f"[MQTT] Disconnected (code: {reason_code}). Reconnecting...")
def on_publish(client, userdata, mid, reason_code, properties): print(f"[MQTT] Message {mid} published successfully")
# ========== SENSOR SIMULATION ==========def read_sensors(): """ Simulate sensor readings. Replace this function with actual sensor code for real hardware. """ return { "temperature": round(random.uniform(20.0, 35.0), 1), "humidity": round(random.uniform(30.0, 80.0), 1), }
# ========== MAIN ==========def main(): print("=== Python MQTT Client -> SiliconWit IO ===\n")
# Create MQTT client (API v2) client = mqtt.Client( callback_api_version=mqtt.CallbackAPIVersion.VERSION2, client_id=DEVICE_ID, protocol=mqtt.MQTTv311, )
# Set authentication client.username_pw_set(DEVICE_ID, ACCESS_TOKEN)
# Configure TLS client.tls_set(tls_version=ssl.PROTOCOL_TLS_CLIENT)
# Set callbacks client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_publish = on_publish
# Enable automatic reconnection client.reconnect_delay_set(min_delay=1, max_delay=60)
# Connect to broker print(f"[MQTT] Connecting to {MQTT_BROKER}:{MQTT_PORT}...") try: client.connect(MQTT_BROKER, MQTT_PORT, keepalive=60) except Exception as e: print(f"[ERROR] Connection failed: {e}") return
# Start the network loop in a background thread client.loop_start()
try: while True: if client.is_connected(): # Read sensor data sensor_data = read_sensors()
# Publish telemetry payload = json.dumps(sensor_data) result = client.publish(PUBLISH_TOPIC, payload, qos=1) print(f"[TELEMETRY] Sent: {payload}") else: print("[MQTT] Waiting for connection...")
time.sleep(TELEMETRY_INTERVAL)
except KeyboardInterrupt: print("\n[INFO] Shutting down...") finally: client.loop_stop() client.disconnect() print("[INFO] Disconnected. Goodbye.")
if __name__ == "__main__": main()Run the script:
python mqtt_client.pyYou should see output similar to:
=== Python MQTT Client -> SiliconWit IO ===
[MQTT] Connecting to mqtt.siliconwit.io:8883...[MQTT] Connected to SiliconWit IO[TELEMETRY] Sent: {"temperature": 24.3, "humidity": 55.7}[MQTT] Message 1 published successfully[TELEMETRY] Sent: {"temperature": 28.1, "humidity": 42.9}[MQTT] Message 2 published successfullyStep 7: View Data on SiliconWit IO
Section titled “Step 7: View Data on SiliconWit IO”- Log in to your SiliconWit IO dashboard.
- Navigate to your registered device.
- You should see the temperature and humidity values updating every 10 seconds.
- SiliconWit IO automatically displays charts and a data table for each field.
Troubleshooting
Section titled “Troubleshooting”Connection Issues
Section titled “Connection Issues”| Symptom | Cause | Solution |
|---|---|---|
Connection refused | Wrong broker address or port | Verify MQTT_BROKER and MQTT_PORT (8883 for TLS). |
SSL: CERTIFICATE_VERIFY_FAILED | System CA certificates missing or outdated | Run pip install certifi and update your OS certificates. |
Connection failed with code: 5 | Invalid credentials | Verify DEVICE_ID and ACCESS_TOKEN match your SiliconWit IO dashboard. |
Connection timed out | Firewall blocking port 8883 | Check that outbound port 8883 is allowed on your network. |
Connection failed with code: 4 | Bad username or password format | Ensure Device ID is used as both client ID and username. |
Publishing Issues
Section titled “Publishing Issues”| Symptom | Cause | Solution |
|---|---|---|
on_publish never fires | Client not connected | Check client.is_connected() before publishing. |
| Data not appearing on dashboard | Wrong topic format | Topic must be d/{device_id}/t with the actual device ID. |
| Payload rejected | Invalid JSON | Validate your JSON with json.loads(payload) before publishing. |
Environment Issues
Section titled “Environment Issues”| Symptom | Cause | Solution |
|---|---|---|
ModuleNotFoundError: paho | paho-mqtt not installed | Run pip install paho-mqtt. |
AttributeError: CallbackAPIVersion | Old paho-mqtt version | Run pip install --upgrade paho-mqtt (need v2.0+). |
| Script exits immediately | Exception not caught | Check the terminal output for error messages. |
Summary
Section titled “Summary”In this tutorial, you built a Python MQTT client that:
- Connects securely to the SiliconWit IO MQTT broker over TLS on port 8883
- Authenticates using your Device ID and Access Token
- Publishes JSON telemetry data (temperature and humidity) at regular intervals
- Handles automatic reconnection if the connection drops
- Uses the paho-mqtt v2 API with proper callbacks
This pattern can be extended to read data from real sensors, forward data from serial devices, or act as an IoT gateway aggregating data from multiple sources. Replace the read_sensors() function with your actual sensor reading code to move from simulation to production.