IoT Libraries Available for Python
What this domain tests
CWIIP checks that you can name the right Python library for a task and write correct client code with it: connection setup, TLS, callbacks, reconnection and cleanup. Questions often hinge on what a library does not do for you.
Protocol clients
- MQTT:
paho-mqtt.Client(client_id, clean_session=True);connect(host, 1883, keepalive);loop_start()for a background thread orloop_forever()to block;tls_set(ca_certs=...)before connecting;publish(topic, payload, qos, retain);subscribe(topic, qos). Useaiomqttorasyncio-mqttfor async applications. - CoAP:
aiocoap(asyncio-based) orCoAPthonfor request/response and Observe. - HTTP:
requestsfor synchronous calls,httpxoraiohttpfor async. - Industrial:
pymodbus(Modbus TCP/RTU),asyncuaorpython-opcua(OPC UA),bacpypes(BACnet). - Serial and buses:
pyserial,smbus2for I2C.
Hardware and cloud
gpiozero,RPi.GPIO, and AdafruitBlinka(board,busio,digitalio) with CircuitPython device libraries for sensors.- Cloud SDKs: AWS IoT Device SDK v2 (
awsiotsdk),azure-iot-device,google-cloud-iot. They wrap MQTT plus device identity and shadow/twin features. - Data:
sqlite3(stdlib),psycopg2/psycopg,pymongo,influxdb-client. Validation and crypto:pydantic,cryptography.
Callback discipline
- The paho signature is
on_connect(client, userdata, flags, rc)in 1.x; MQTT 5 clients add a properties argument. Always checkrc == 0. loop_start()reconnects automatically, but subscriptions are not restored for a clean session - resubscribe insideon_connect.- Keep
on_messagefast. Blocking work (database writes, HTTP calls) must be handed to a queue or worker thread. Never callloop_forever()inside a callback.
Worked example
import paho.mqtt.client as mqtt
TOPIC = "site/17/telemetry"
def on_connect(client, userdata, flags, rc):
if rc == 0:
client.subscribe(TOPIC, qos=1)
def on_message(client, userdata, msg):
print(msg.topic, msg.payload.decode())
c = mqtt.Client("gw-17")
c.tls_set(ca_certs="/etc/ssl/ca.pem")
c.on_connect = on_connect
c.on_message = on_message
c.connect("broker.example", 8883, 60)
c.loop_start()
Resubscribing in on_connect is the key line: after any reconnect, a clean-session client has no subscriptions and would otherwise go silent.
Traps
- Assuming the library resubscribes automatically.
- Blocking inside
on_message, stalling keepalives. - Using port 1883 after enabling
tls_set. - Mixing paho 1.x and 2.x callback signatures (
CallbackAPIVersion). - Assuming
loop_forever()returns.