MQTT — Publish and Subscribe💻 Code
MQTT is the standard lightweight IoT protocol. Send sensor readings to a broker and receive commands.
⚡ You need a broker. Mosquitto on a Pi is the easiest local option. HiveMQ offers a free public broker for testing.
MQTT is the standard lightweight IoT protocol. Send sensor readings to a broker and receive commands.
# MicroPython -- umqtt.simple
from umqtt.simple import MQTTClient
import time
CLIENT = b'pico-sensor-01'
BROKER = '192.168.1.100' # Your broker IP
PORT = 1883
def on_message(topic, msg):
print(f'Topic: {topic.decode()} Msg: {msg.decode()}')
c = MQTTClient(CLIENT, BROKER, PORT)
c.set_callback(on_message)
c.connect()
c.subscribe(b'home/commands/#')
while True:
c.check_msg() # Non-blocking check for incoming messages
c.publish(b'home/sensors/temp', b'22.5')
time.sleep(5)
# Raspberry Pi -- paho-mqtt
# pip3 install paho-mqtt
import paho.mqtt.client as mqtt
def on_message(client, userdata, msg):
print(f'{msg.topic}: {msg.payload.decode()}')
client = mqtt.Client()
client.on_message = on_message
client.connect('localhost', 1883)
client.subscribe('home/#')
client.publish('home/pi/status', 'online')
client.loop_forever()Home Assistant Integration📖 Reference
Three ways to get your maker devices talking to Home Assistant.
⚡ ESPHome is by far the easiest for ESP32/ESP8266 -- zero custom code needed for most sensors.
Three ways to get your maker devices talking to Home Assistant.
1. ESPHome (easiest -- ESP32 / ESP8266):
- Install ESPHome addon in Home Assistant
- Write a simple YAML config -- no Python/C++ needed
- Flash once via USB, then OTA updates over WiFi
- Sensors auto-discovered in HA
- Supports: BME280, DHT22, PIR, ultrasonic, OLED, and 100+ more
URL: https://esphome.io
2. MQTT Auto-Discovery (any platform, MicroPython etc.):
Publish config JSON once, HA creates the entity automatically.
Config topic: homeassistant/sensor/DEVICE_ID/temperature/config
Config payload:
{
'name': 'Living Room Temp',
'device_class': 'temperature',
'state_topic': 'home/livingroom/temperature',
'unit_of_measurement': 'C',
'unique_id': 'lr_temp_01'
}
Then just publish readings to the state_topic.
3. REST API (any device with HTTP):
GET http://homeassistant.local:8123/api/states/sensor.temp
POST http://homeassistant.local:8123/api/states/sensor.temp
Header: Authorization: Bearer <long-lived-access-token>
Body: {"state": "22.5", "attributes": {"unit_of_measurement": "C"}}
Generate token: Profile -> Long-Lived Access TokensNTP Time Sync💻 Code
Sync the device clock with internet time servers for accurate timestamps and scheduling.
⚡ Requires WiFi. Call once at boot. NTP returns UTC -- apply your timezone offset manually.
Sync the device clock with internet time servers for accurate timestamps and scheduling.
# MicroPython (ESP32 or Pico W)
import ntptime, time
def sync_time(timezone_offset_hours=0):
try:
ntptime.settime() # Syncs from pool.ntp.org (UTC)
print('Time synced:', time.localtime())
except Exception as e:
print('NTP failed:', e)
# Use a different NTP server
ntptime.host = 'time.cloudflare.com'
# Format current time
t = time.localtime()
print(f'{t[0]}-{t[1]:02d}-{t[2]:02d} {t[3]:02d}:{t[4]:02d}:{t[5]:02d} UTC')
# Apply UTC offset (e.g. UTC+1)
UTC_OFFSET = 1 * 3600 # seconds
adjusted = time.localtime(time.time() + UTC_OFFSET)
# Raspberry Pi -- handled by OS automatically
# Check status:
# timedatectl status
# Set timezone:
# sudo timedatectl set-timezone Europe/LondonNo entries match