Skip to content

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.

  • How to install and configure the paho-mqtt Python 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
RequirementDetails
PythonVersion 3.8 or later
pipPython package manager (included with Python)
SiliconWit IO AccountFree IoT platform account
A registered deviceCreated from the SiliconWit IO dashboard

You will need the following credentials from your SiliconWit IO dashboard after registering a device:

CredentialExampleDescription
Device IDAbCdEfGhIjUnique 10-character identifier (used as MQTT username)
Access Tokenyour_access_token_hereMQTT password
Publish Topicd/{device_id}/tTopic for sending sensor data (d = device, t = telemetry)

Keep your access token secure. Never share it publicly or commit it to version control.

Open a terminal and install the paho-mqtt library using pip:

Terminal window
pip install paho-mqtt

Verify the installation:

Terminal window
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 │
└─────────────────────────────────────────────────────────┘

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 certificates
client.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

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 = 8883
DEVICE_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)

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 json
import 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))
FieldTypeDescription
temperaturefloatTemperature reading in degrees Celsius
humidityfloatRelative humidity percentage

You can add any additional fields. SiliconWit IO automatically detects and displays new data fields on the dashboard.

Create a file called mqtt_client.py with the following complete code:

import ssl
import json
import time
import random
import paho.mqtt.client as mqtt
# ========== SILICONWIT IO MQTT CONFIGURATION ==========
MQTT_BROKER = "mqtt.siliconwit.io"
MQTT_PORT = 8883
DEVICE_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:

Terminal window
python mqtt_client.py

You 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 successfully
  1. Log in to your SiliconWit IO dashboard.
  2. Navigate to your registered device.
  3. You should see the temperature and humidity values updating every 10 seconds.
  4. SiliconWit IO automatically displays charts and a data table for each field.
SymptomCauseSolution
Connection refusedWrong broker address or portVerify MQTT_BROKER and MQTT_PORT (8883 for TLS).
SSL: CERTIFICATE_VERIFY_FAILEDSystem CA certificates missing or outdatedRun pip install certifi and update your OS certificates.
Connection failed with code: 5Invalid credentialsVerify DEVICE_ID and ACCESS_TOKEN match your SiliconWit IO dashboard.
Connection timed outFirewall blocking port 8883Check that outbound port 8883 is allowed on your network.
Connection failed with code: 4Bad username or password formatEnsure Device ID is used as both client ID and username.
SymptomCauseSolution
on_publish never firesClient not connectedCheck client.is_connected() before publishing.
Data not appearing on dashboardWrong topic formatTopic must be d/{device_id}/t with the actual device ID.
Payload rejectedInvalid JSONValidate your JSON with json.loads(payload) before publishing.
SymptomCauseSolution
ModuleNotFoundError: pahopaho-mqtt not installedRun pip install paho-mqtt.
AttributeError: CallbackAPIVersionOld paho-mqtt versionRun pip install --upgrade paho-mqtt (need v2.0+).
Script exits immediatelyException not caughtCheck the terminal output for error messages.

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.