Skip to content
You Start with one site
Amounts in Start with one site
IoT & AIoT · Course

Send a reading from your laptop first

Lesson 3 of 9 Beginner 12 min read
Found this useful?

You flash your first firmware, open the dashboard, and nothing arrives. Is it the wiring? The Wi-Fi password? The certificate? The token? The topic? Five things can be wrong at once, and the board tells you almost nothing. This lesson removes most of them before you touch any hardware: you send a reading from your laptop first, and you watch the whole path work.

#MQTT #Python #TLS

Why start on the laptop

A laptop has a keyboard, a screen, clear error messages and a working internet connection. A microcontroller has none of these. If the laptop can publish with your credentials, then the broker, the account, the token, the topic and the JSON are all proven. When the board later fails, the fault is in the board's part: its Wi-Fi, its clock, its certificate or its wiring. You have cut the search in half before you start.

Your broker or ours. The script works with any MQTT broker. The worked example is siliconwit.io, our monitoring service, because it needs no server of your own. No account yet? siliconwit.io/try gives you a real device with broker credentials, with no sign-up, for about 30 minutes: enough to run this lesson's script. Create a free account to keep it and its history. For anything that must last, use a free account from the start. On a broker you run, such as Mosquitto, only the host, port, username and password change; the section near the end shows how.

Step 1: Get a device and its credentials

On siliconwit.io, open Add Device, choose Define my own device, and give it two fields named temperature (unit °C) and humidity (unit %). Leave the data interval at 10 seconds for now. When you confirm, you get the two values the script needs: the Device ID (it looks like SWD-XXXXXX) and the Access Token. You can see the token again later on the device's Settings tab.

Field names are the JSON keys your program sends. They are lowercase letters, numbers and underscores. A key that matches no field is not stored, so "Temperature" or "temp" would be silently ignored.

Step 2: Install the MQTT library

The script uses paho-mqtt, the common open-source MQTT client for Python. It needs version 2.0 or newer, because version 2 changed how callbacks are written.

Terminal window
python3 -m pip install "paho-mqtt>=2.0"
python3 -c "import paho.mqtt; print(paho.mqtt.__version__)" # 2.0 or newer

Step 3: The script

Save this as send_reading.py, put your Device ID and Access Token in the two marked lines, and leave everything else as it is. The readings are made up (about 22 °C and 50%), because the point today is the path, not the sensor.

# send_reading.py: send a reading every 10 seconds, the way a device would
import json
import random
import time
import paho.mqtt.client as mqtt
HOST = "mqtt.siliconwit.io" # your own broker: its address
PORT = 8883 # MQTT over TLS
DEVICE_ID = "SWD-XXXXXX" # your Device ID: the client ID and the username
TOKEN = "your-access-token" # your Access Token: the password
EVERY_S = 10 # the device's Data Interval, in seconds
def on_connect(client, userdata, flags, reason_code, properties):
print("connect:", reason_code) # "Success", or the reason it was refused
def on_disconnect(client, userdata, flags, reason_code, properties):
print("disconnected:", reason_code)
client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,
client_id=DEVICE_ID, protocol=mqtt.MQTTv311)
client.username_pw_set(DEVICE_ID, TOKEN)
client.tls_set() # encrypt, and check the broker's certificate
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.connect(HOST, PORT, keepalive=60)
client.loop_start() # a background thread keeps the connection alive
topic = f"d/{DEVICE_ID}/t"
try:
while True:
reading = {
"temperature": round(22.0 + random.uniform(-0.5, 0.5), 1),
"humidity": round(50.0 + random.uniform(-2.0, 2.0), 1),
}
info = client.publish(topic, json.dumps(reading), qos=1)
print(topic, json.dumps(reading), "queued" if info.rc == 0 else f"not sent (rc {info.rc})")
time.sleep(EVERY_S)
except KeyboardInterrupt:
pass
client.loop_stop()
client.disconnect()

Read it in four parts:

  • The settings at the top are the same five facts every device needs: host, port, Device ID, token, and how often to send. Nothing else in the script is specific to one broker.
  • mqtt.Client(...) uses the Device ID as the client ID, as the platform asks. username_pw_set gives the Device ID as the username and the token as the password.
  • tls_set() turns on encryption and checks the broker's certificate against the trusted roots your computer already has. The broker's certificate comes from Let's Encrypt, which every current operating system trusts.
  • loop_start() starts a background thread that keeps the connection alive, sends a ping when nothing else is sent for the 60 second keep-alive, and reconnects by itself if the link drops. Your main loop only builds and publishes readings.

Step 4: Run it and watch

Run python3 send_reading.py. Within a second or two you should see something like this:

connect: Success
d/SWD-XXXXXX/t {"temperature": 22.2, "humidity": 49.2} queued
d/SWD-XXXXXX/t {"temperature": 22.1, "humidity": 49.9} queued
d/SWD-XXXXXX/t {"temperature": 22.5, "humidity": 49.8} queued

Now open the device on siliconwit.io. The latest reading appears and updates every 10 seconds; the chart on the Insights tab grows a point each time. Press Ctrl+C to stop the script. After three missed intervals, and never sooner than 5 minutes, the device shows as not reporting. Start the script again and it comes back. You have just watched the oversight from the first lesson work, from both sides.

"queued" is not "stored". publish() returns as soon as the message is handed to the library. With QoS 1 the library then waits for the broker to confirm it, and sends it again if no confirmation comes. Only the dashboard tells you the platform kept it. That is why you always check both ends.

When it does not work

The script prints the reason the broker gives, so most faults name themselves:

What you seeWhat it meansWhat to do
connect: Not authorizedThe broker refused the login.Copy the Device ID and token again, with no spaces. Check the device is not paused. If you regenerated the token, the old one stopped working at once.
not sent (rc 4) on every lineThe client is not connected (4 means "no connection").Look for a connect line above it. If there is none, the connection never opened.
CERTIFICATE_VERIFY_FAILEDYour computer could not check the broker's certificate.Check the host name is exactly mqtt.siliconwit.io and your computer's clock is right. On an old system, update its root certificates.
A timeout, and no connect line at allPort 8883 is blocked on this network.Some office and school networks block it. Try a phone hotspot to confirm.
Connects, publishes, but the dashboard is emptyThe topic or the field names do not match.The topic must be d/ + your exact Device ID + /t. The keys must be your field names, in lowercase.
Worked example

You change EVERY_S to 4, but the device's data interval is still 10 seconds. You run the script for one minute. How many readings does the platform keep?

Show the worked solution, 3 steps
  1. What you send

    One reading every 4 seconds is 60 / 4 = 15 readings a minute. ✅

  2. What the platform accepts

    It keeps a reading only when at least 10 seconds have passed since the last one it kept. With readings at 0, 4, 8, 12, 16, 20 ... seconds, it keeps those at 0, 12, 24, 36 and 48: 5 readings. ✅

  3. The lesson

    Ten of the fifteen messages were sent for nothing, and the readings you kept are 12 seconds apart, not 10. Match EVERY_S to the data interval, or change the interval on the device's Settings tab. ✅

On a broker you run

The same script talks to your own Mosquitto. Change the host and port, and tell tls_set which certificate authority signed your broker's certificate. For a first test on your own network you can use port 1883 with no TLS, but only on a network you trust, and never with a password you use anywhere else.

HOST = "192.168.1.20" # the computer that runs Mosquitto
PORT = 8883 # or 1883 for a first test with no TLS
client.tls_set(ca_certs="ca.crt") # the CA that signed your broker's certificate
# (with port 1883, delete the tls_set line)
# and watch it arrive, on the broker's computer:
# mosquitto_sub -h localhost -t 'd/#' -v

On your own broker you also choose the username, the password and the topic. Keeping the d/<id>/t pattern costs nothing and means the same device code works on both.

Common mistakes

  • The laptop and the board running at the same time with the same Device ID. The client ID must be unique, so the broker closes the first connection when the second one connects. Each keeps reconnecting and throwing the other off. Stop the script before you power the board.
  • A list of readings in one message. Send one JSON object per reading. An array is not split into separate readings.
  • Publishing to another topic. On siliconwit.io a device may publish only to its own topics. A publish anywhere else closes the connection.
  • The token in a file you share. If the script goes to a shared folder or a public repository, so does the token. Anyone with it can publish as your device. If that happens, regenerate the token on the Settings tab.
Your turn: the missing field

Your fields are temperature and humidity. A classmate's script sends {"temp": 22.4, "humidity": 50.1}. The device shows as reporting. What appears on the dashboard, and why?

Show the answer, 2 steps
  1. What is stored

    Humidity is stored and charted, because humidity is a field. temp matches no field, so it is not stored. The temperature chart stays empty. ✅

  2. Why it is easy to miss

    The connection works, a reading arrives, and the device shows as reporting. Only one chart is quiet. When one value is missing and the others are fine, check the key names first. ✅

Check yourself

Question 1

Why send the first reading from a laptop and not from the board?

Question 2

The script prints connect: Not authorized. What is the most likely cause?

Question 3

The data interval is 10 seconds and the script sends every 4 seconds. What happens?

Question 4

What does tls_set() with no arguments do?

Key points
  • Prove the path from a laptop first: broker, credentials, topic and JSON, with clear errors.
  • The Device ID is the client ID and username; the Access Token is the password; TLS on port 8883.
  • Publish one JSON object per reading to d/<id>/t, with keys that match your field names.
  • Send no faster than the data interval, and never run two clients with the same ID.

The path works. Next, the other end of it: a real sensor on a real board, and how to turn its raw numbers into a reading you can trust.

Found this useful?

Discussion