🛠 Client MQTT : télémétrie IoT légère sur la Pico W

Raspberry Pi Pico W · avance · Schéma : IMG-pico-w-avance-1-picow-mqtt-client.svg — Pico W publiant des messages MQTT vers un broker heberge sur un NAS via le routeur, abonne vers un dashboard, topics en arborescence capteur/picow dessines en etiquettes

Objectives

MQTT is THE protocol for IoT devices: lightweight (2-byte header), pub/sub, adapted to unstable radio links. The official MQTT client example is located in pico_w/wifi/ of the pico-examples repository (C SDK); in MicroPython, you can speak MQTT without dependencies by constructing packets manually over a TCP socket — excellent for understanding the protocol. You will implement CONNECT + PUBLISH QoS 0, the pattern for all sensor telemetry.

Hardware

Complete code

# mqtt_pub.py — MQTT 3.1.1 minimal (CONNECT + PUBLISH QoS 0) sur socket
import machine, network, socket, time, struct

wlan = network.WLAN; wlan.active(True)
if not wlan.isconnected:
    wlan.connect('my_ssid', 'my_password')
    while not wlan.isconnected:
        machine.idle

def remaining_length(n):            # encodage varint MQTT
    out = b''
    while True:
        b = n % 128; n //= 128
        if n: b |= 0x80
        out += bytes([b])
        if not n: return out

def connect(sock, client_id):
    proto = b'\x00\x04MQTT\x04\x02\x00\x3c'   # level 4, clean session,
    cid = struct.pack('>H', len(client_id)) + client_id.encode  # keepalive 60s
    body = proto + cid
    sock.send(b'\x10' + remaining_length(len(body)) + body)
    return sock.recv(4)             # CONNACK 0x20 0x02 0x00 = accepté

def publish(sock, topic, payload):
    t = struct.pack('>H', len(topic)) + topic.encode
    p = payload.encode if isinstance(payload, str) else payload
    body = t + p
    sock.send(b'\x30' + remaining_length(len(body)) + body)  # QoS 0

s = socket.socket
s.connect(('192.168.1.10', 1883))   # IP de ton broker
print('CONNACK:', connect(s, 'picow-01'))
while True:
    publish(s, 'maison/picow/temperature', '21.5')
    time.sleep(10)
# En C SDK : exemple officiel pico_w/wifi/mqtt (lwIP). En MicroPython, la
# lib umqtt.simple existe aussi dans micropython-lib.
# > 
# n'a pas été vérifiée (hors base documentaire) — le code ci-dessus s'en passe.

Expected verification

CONNACK: b'\\x20\\x02\\x00' (return code 0 = accepted), then on the broker: mosquitto_sub -t 'maison/picow/#' displays a message every 10 s. Wi-Fi disconnections: the socket breaks — restart the connection in a try/except around the loop for real-world behavior.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials