DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
BETTESWORTHConstruction
Building Automation

ESP32 and Toit: Integrating Home Assistant Through MQTT

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—Toit can connect an ESP32 to Home Assistant through MQTT. The practical architecture is Toit application on an ESP32 → MQTT broker → Home Assistant MQTT integration. Toit runs the embedded application and handles MQTT communication; Home Assistant interprets the messages as sensors, switches, or other entities.

There is no need for a custom Home Assistant integration, but Toit will not create Home Assistant entities automatically. For automatic setup, the ESP32 must publish valid MQTT discovery configuration messages, then publish its actual sensor state or actuator state on the topics described by that configuration.

As an Amazon Associate I earn from qualifying purchases.

How the integration works

ESP32 running Toit
        ↓
MQTT broker, such as Mosquitto
        ↓
Home Assistant MQTT integration

Both the ESP32 and Home Assistant connect to the same MQTT broker. The ESP32 publishes telemetry, availability, and discovery messages. It can also subscribe to command topics, allowing Home Assistant to control a relay, light, valve, fan, or other hardware.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Toit is an embedded programming environment and runtime designed for devices such as supported ESP32 boards. Its Jaguar tooling is used to install the firmware, configure the device, and deploy applications. Toit provides an MQTT package for publishing, subscribing, authentication, and TLS. See the Toit device setup guide and Toit MQTT tutorial.

#1 Best Overall
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (3PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • ESP32 is a safe, reliable, and scalable to a variety of applications

Home Assistant contributes the MQTT integration, entity model, dashboards, automations, and MQTT discovery support. The default discovery prefix is homeassistant. Home Assistant supports MQTT sensors, binary sensors, switches, lights, buttons, numbers, fans, covers, and other entity types through documented MQTT conventions. The current configuration area is under Settings > Devices & services; labels can vary slightly by Home Assistant edition and release. Consult the current MQTT documentation if your interface differs.

What you need

  • A supported ESP32 board, USB cable, and suitable power supply.
  • Toit and the Jaguar development tool.
  • A Home Assistant installation.
  • An MQTT broker reachable by both Home Assistant and the ESP32.
  • A sensor or actuator with a suitable Toit driver or GPIO implementation.
  • Broker credentials if authentication is enabled.

Toit’s setup documentation describes standard ESP32 WROOM- and WROVER-based boards as typical starting points, but support should be checked for the exact ESP32 variant before buying a board. Requirements may differ for ESP32-C3, C6, S3, and other families.

Set up a private MQTT broker

MQTT is broker-based: the ESP32 and Home Assistant normally do not communicate directly. For a home or building-automation installation, use a private, locally managed broker. Home Assistant commonly recommends its official Mosquitto Broker app where that installation method is available, although a separately managed Mosquitto server or another compatible broker can also work. Follow Home Assistant’s broker setup guidance.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The Toit tutorial uses test.mosquitto.org for demonstration. That is useful for a short connectivity experiment, but it is not appropriate for household or construction-site controls, credentials, telemetry, or anything safety-sensitive. Use a private broker with authentication and access controls.

Record these values before writing the application:

  • Broker hostname or IP address.
  • MQTT port.
  • Username and password, if required.
  • Whether TLS is required.
  • Topic permissions for the device.

Prepare the ESP32 with Toit

Follow the current Toit device instructions to install Jaguar, connect the board, flash Toit firmware, configure Wi-Fi, and run a basic application. Then install the MQTT package:

jag pkg install github.com/toitware/mqtt@v2

Pinning the major package version makes the example more reproducible than using an unversioned dependency. Package APIs can change, so check the pinned package documentation when adding options such as retained messages, Last Will configuration, or QoS.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For TLS certificate roots, the official tutorial also installs:

Rank #2
ELEGOO 3PCS ESP-32 Dev Boards, ESP-WROOM-32, USB-C, WiFi Bluetooth 4.2 | Low-power IoT Applications, Smart Devices, Automation, Wireless Communication, GPIO Headers, Simplifying Development
  • Dual-Core Performance Up to 240 MHz: Run sensor processing, wireless communication, automation logic and connected-device tasks on a 32-bit dual-core ESP32 platform designed for responsive embedded and IoT projects
  • Built-in Wi-Fi and Bluetooth 4.2: Connect to 2.4 GHz Wi-Fi networks or use Bluetooth Classic and BLE for wireless sensors, smart devices, remote controls, home automation and other connected projects
  • Flexible Power-Saving Modes: ESP32 power-management features support dynamic clock scaling and low-power operating modes, helping developers reduce energy use in compatible sensing, monitoring and connected-device applications, suitable for battery-powered Internet of Things (IoT) devices.
  • USB-C Programming with CP2102: Connect through USB-C for power, sketch uploads and serial monitoring, while GPIO, UART, SPI and I2C interfaces support sensors, displays, motor drivers and other modules (USB-C cable not included)
  • Over-the-Air Update Support: Configure OTA functionality through a compatible ESP-32 software framework to update deployed firmware over Wi-Fi without reconnecting the board by USB for every revision
jag pkg install github.com/toitware/toit-cert-roots@v1

Test ordinary MQTT before adding discovery

First prove that the ESP32 can connect and publish. Do not begin with Home Assistant discovery; otherwise a broker, Wi-Fi, authentication, topic, and JSON problem can look like a Home Assistant problem.

A minimal Toit publishing skeleton is:

import mqtt
import encoding.json

BROKER ::= "192.168.1.10"
STATE-TOPIC ::= "home/esp32/living-room/temperature"

main:
  client := mqtt.Client --host=BROKER
  client.start --client-id="toit-esp32-living-room"

  payload := json.encode {
    "temperature": 22.5
  }

  client.publish STATE-TOPIC payload

The broker address and client ID are examples. Replace the address with your broker and use a unique client ID for every physical device. The value passed to publish must be an io.Data; a string or byte array is commonly used.

A real sensor should keep the connection open and publish periodically rather than reconnecting for every reading:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import mqtt
import encoding.json

BROKER ::= "192.168.1.10"
CLIENT-ID ::= "toit-esp32-living-room"
STATE-TOPIC ::= "home/esp32/living-room/temperature"

main:
  client := mqtt.Client --host=BROKER
  client.start --client-id=CLIENT-ID

  while true:
    temperature := read-temperature

    payload := json.encode {
      "temperature": temperature
    }

    client.publish STATE-TOPIC payload
    sleep --ms=30_000

read-temperature is application-specific pseudocode, not a built-in Toit function. Implement it with the driver for the sensor you selected.

From a machine with MQTT utilities installed, inspect the traffic with:

mosquitto_sub -h BROKER_HOST -v -t 'home/esp32/#'

Home Assistant’s MQTT testing documentation also describes useful MQTT testing tools.

Add a Home Assistant temperature sensor with MQTT discovery

Publishing home/esp32/living-room/temperature proves MQTT connectivity, but it does not tell Home Assistant that the topic represents a temperature sensor. Discovery supplies that description.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a single-component discovery message, Home Assistant uses:

Rank #3
Sale
ELEGOO ESP-32 Super Starter Kit with Tutorial Compatible with Arduino IDE | Development Board, USB-C Dual Core Microcontroller Support AP/STA/AP+STA, CP2102 Chip, WiFi, Bluetooth, 200+ parts for IoT
  • Powerful ESP-32 Board: Unlock the world of Internet of Things (IoT) and advanced electronics with the heart of this kit: the ESP-32 board. It features a powerful dual-core processor, integrated Wi-Fi and Bluetooth 4.2, making it perfect for building connected, smart devices that communicate with your phone or the cloud. It's fully compatible with the Arduino IDE for easy programming.
  • Super Starter Kit: This kit contains over 35 different modules and electronic components, including sensors, displays, motors, and input devices. From LEDs and buttons to an OLED screen, servo motor, and keypad, you have everything needed to explore a vast range of projects in one box.
  • Step by Step Online Tutorial: Jump right in with our detailed, beginner-friendly tutorial. Access 30+ projects with complete code, clear circuit diagrams, and step-by-step instructions. Learn the fundamentals of electronics, coding, and how to utilize the ESP-32's unique capabilities without any prior experience.
  • Hands-on Learning for All Skill Levels: Perfect for students, makers, engineers, and hobbyists. Start with basic circuits and coding, then progress to intermediate and advanced IoT applications. Build practical projects like weather stations, smart home controllers, remote-controlled devices, and interactive gadgets. The skills you learn are the foundation for real-world innovation.
  • Quality & Great Support: Elegoo is committed to quality. We provide a clear, detailed tutorial guide, refined code, and a well-organized component kit. All modules are carefully selected for reliability and ease of use. Our dedicated technical support team and active online community are ready to help you succeed in your learning journey.
<discovery_prefix>/<component>/[<node_id>/]<object_id>/config

For this example, publish the following JSON to:

homeassistant/sensor/toit_living_room_temperature/config
{
  "name": "Temperature",
  "unique_id": "toit_living_room_temperature",
  "state_topic": "home/esp32/living-room/temperature",
  "value_template": "{{ value_json.temperature }}",
  "unit_of_measurement": "°C",
  "device_class": "temperature",
  "state_class": "measurement",
  "availability_topic": "home/esp32/living-room/status",
  "payload_available": "online",
  "payload_not_available": "offline",
  "device": {
    "identifiers": ["toit-esp32-living-room"],
    "name": "Toit ESP32 Living Room",
    "manufacturer": "Custom",
    "model": "ESP32 running Toit"
  }
}

The matching state message is published to home/esp32/living-room/temperature:

{"temperature":22.5}

Important fields include:

  • unique_id gives the entity a stable identity and prevents duplicates.
  • state_topic identifies the topic carrying the current reading.
  • value_template extracts the temperature property from the JSON payload.
  • unit_of_measurement, device_class, and state_class help Home Assistant display and interpret the reading.
  • device groups this entity with other entities from the same ESP32.
  • availability_topic lets Home Assistant show the device as unavailable.

Discovery configuration and state are separate messages. Publishing the configuration does not publish the current measurement; the ESP32 must publish state as well.

Discovery identifiers should use stable letters, numbers, underscores, and hyphens. Never generate a new unique_id on every reboot.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add a switch or relay

For a relay, publish discovery configuration to:

homeassistant/switch/toit_living_room_relay/config
{
  "name": "Relay",
  "unique_id": "toit_living_room_relay",
  "command_topic": "home/esp32/living-room/relay/set",
  "state_topic": "home/esp32/living-room/relay/state",
  "payload_on": "ON",
  "payload_off": "OFF",
  "state_on": "ON",
  "state_off": "OFF",
  "availability_topic": "home/esp32/living-room/status",
  "payload_available": "online",
  "payload_not_available": "offline",
  "device": {
    "identifiers": ["toit-esp32-living-room"],
    "name": "Toit ESP32 Living Room",
    "manufacturer": "Custom",
    "model": "ESP32 running Toit"
  }
}

The Toit program subscribes to home/esp32/living-room/relay/set:

import mqtt

BROKER ::= "192.168.1.10"
COMMAND-TOPIC ::= "home/esp32/living-room/relay/set"
STATE-TOPIC ::= "home/esp32/living-room/relay/state"

main:
  client := mqtt.Client --host=BROKER
  client.start --client-id="toit-living-room-01"

  client.subscribe COMMAND-TOPIC:: | topic/string payload/ByteArray |
    command := payload.to-string

    if command == "ON":
      relay-on
      client.publish STATE-TOPIC "ON"
    elif command == "OFF":
      relay-off
      client.publish STATE-TOPIC "OFF"

relay-on and relay-off are placeholders. Replace them with the appropriate Toit GPIO or peripheral operations. A robust implementation should publish state only after the hardware operation has succeeded, and should read back the resulting state where that is possible. Receiving an ON command is not proof that a relay physically switched on.

For mains-voltage equipment, use an appropriately rated, enclosed relay module and follow electrical regulations. The ESP32 GPIO must not switch mains directly.

Availability and restart recovery

A device that publishes discovery once at boot may appear to work initially but fail to return correctly after Home Assistant or the broker restarts. Plan recovery explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Publish availability on:

home/esp32/living-room/status

Use online when the device is connected and operational, and configure the MQTT connection’s Last Will to publish offline if the selected Toit MQTT API supports the required Last Will options. Verify those option names against the pinned package version rather than copying unverified parameters.

Rank #4
ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA Compatible with Arduino IDE (1 PCS)
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Support LWIP protocol, Freertos;ESP32 is a safe, reliable, and scalable to a variety of applications
  • SupportThree Modes: AP, STA, and AP+STA
  • Ultra-Low power consumption, Compatible with Arduino IDE
  • 1PCS 30Pin ESP32 Development Board 2.4GHz WiFi Dual Cores Microcontroller Integrated with Antenna RF Low Noise Amplifiers Filters

Home Assistant’s default birth topic is:

homeassistant/status

Its online payload is:

online

A useful recovery design is:

  1. The ESP32 subscribes to homeassistant/status.
  2. When it receives online, it republishes each discovery configuration message.
  3. It republishes the current sensor and actuator state.
  4. It continues normal periodic telemetry afterward.

Home Assistant documents two main approaches: retain discovery configuration messages at the broker, or listen for the birth message and republish discovery. Retained discovery is convenient, but stale retained configuration can leave old entities behind. The birth-message approach avoids relying on unverified retain-argument syntax in the Toit example and makes the recovery event explicit.

State may also need to be republished after discovery is processed. A configuration message tells Home Assistant how to interpret a topic; it does not necessarily provide the current value.

Authentication and TLS

The Toit MQTT tutorial shows authenticated connections using session options:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
options := mqtt.SessionOptions
    --client-id=CLIENT-ID
    --username=MY-USERNAME
    --password=MY-PASSWORD

client.start --options=options

For TLS, the documented pattern installs common trusted roots and uses the TLS client constructor:

import mqtt
import certificate-roots

main:
  certificate-roots.install-common-trusted-roots

  client := mqtt.Client.tls --host=BROKER
  client.start --client-id="toit-esp32-01"

TLS protects the connection in transit, but it does not replace broker authentication, topic permissions, unique client IDs, or safe credential storage. Use separate credentials for devices or device groups where practical, restrict each account to the topics it needs, and never commit passwords to a public repository.

Home Assistant’s MQTT integration also documents broker certificate validation and client-certificate options. Review the current security settings for your broker deployment.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

QoS: choose it for the message, not the slogan

The Toit MQTT tutorial documents:

  • QoS 0: at-most-once delivery.
  • QoS 1: at-least-once delivery, which can produce duplicates.
  • QoS 2: exactly-once delivery in MQTT terminology, but QoS 2 is not implemented in the documented Toit MQTT library.

QoS 0 is often suitable for frequent temperature or humidity readings where an occasional lost sample is harmless. QoS 1 can be more appropriate for important commands or state transitions, but command handlers must tolerate duplicate delivery. Make commands idempotent where possible: applying ON twice should still leave the relay on, not trigger an unintended toggle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

QoS does not correct a wrong topic, failed hardware, lost Wi-Fi, stale state, duplicate device ID, or unsafe actuator logic.

Best Value
HiLetgo ESP-WROOM-32 ESP32 ESP-32S Development Board 2.4GHz Dual-Mode WiFi + Bluetooth Dual Cores Microcontroller Processor Integrated with Antenna RF AMP Filter AP STA for Arduino IDE
  • 2.4GHz Dual Mode WiFi + Bluetooth Development Board
  • Ultra-Low power consumption, works perfectly with the Arduino IDE
  • Support LWIP protocol, Freertos
  • SupportThree Modes: AP, STA, and AP+STA
  • ESP32 is a safe, reliable, and scalable to a variety of applications

Troubleshooting checklist

No MQTT connection

  1. Confirm the ESP32 has Wi-Fi access.
  2. Verify the broker hostname, port, username, and password.
  3. Check that the broker is reachable from the ESP32’s network.
  4. Confirm firewall rules and broker ACLs.
  5. Use a unique client ID.
  6. If using TLS, check the broker certificate, clock, trusted roots, and TLS port.

Messages are not visible

Subscribe broadly while testing:

mosquitto_sub -h BROKER_HOST -v -t '#'

Then narrow the subscription to the device namespace. Check that the ESP32 and Home Assistant are using the same broker, not two different broker instances or ports.

No Home Assistant entity appears

  1. Confirm the MQTT integration is configured in Home Assistant.
  2. Check that the discovery prefix is normally homeassistant, unless you changed it.
  3. Verify the topic ends in /config.
  4. Confirm the component is valid, such as sensor or switch.
  5. Validate the JSON syntax.
  6. Check that unique_id is present and stable.
  7. Inspect discovery traffic with mosquitto_sub -h BROKER_HOST -v -t 'homeassistant/#'.

The entity is unavailable

Compare the configured availability_topic, payload_available, and payload_not_available with the actual messages. Also check that the ESP32 republishes discovery and state after a Home Assistant restart or reconnect.

The entity appears twice

Look for changed unique_id values, duplicated discovery topics, multiple boards using the same identity, or old retained discovery messages. Use a stable device-specific identifier. If an obsolete retained discovery configuration remains, remove it using the broker’s documented retained-message deletion procedure; the exact command depends on the MQTT client and broker.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The switch changes in Home Assistant but the hardware does not

Check the command topic, exact capitalization of ON and OFF, broker permissions, and whether the subscription is active after reconnect. Register subscription routes before connecting if that matches the Toit MQTT package’s reconnect guidance, so messages are not missed during connection recovery.

The state is stale

Publish state after the hardware operation, not merely after receiving a command. If the device can be locally overridden or the actuator can fail, read back the actual state where possible and publish that result.

Toit, ESPHome, or ESP-IDF?

Choose When it makes sense Main trade-off
Toit + MQTT You want a programmable runtime, custom concurrency, unusual peripherals, MQTT interoperability, or a path toward managed device fleets. You must implement discovery, availability, reconnect behavior, and state conventions.
ESPHome Your priority is a fast Home Assistant device using an existing component and configuration-based workflow. Less flexible for an application that falls outside supported component patterns.
Arduino or ESP-IDF You need the broadest library ecosystem, vendor SDK control, or existing firmware and ESP-MQTT examples. You own more of the firmware, networking, reconnect, and integration code.

ESPHome’s MQTT component includes Home Assistant-oriented discovery behavior. It may be the faster choice for a conventional building sensor or relay. Toit is more compelling when the device is a genuinely custom embedded application rather than simply a sensor endpoint.

MQTT is not universally better than a native Home Assistant API. MQTT is a strong choice when other systems may consume the data, when loose coupling matters, or when the device should remain broker-oriented. A native API can be simpler when Home Assistant is the only target and the selected firmware supports it directly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the complete failure path

Do not stop when the first entity appears. Test:

  • ESP32 reboot.
  • Home Assistant restart.
  • Broker restart.
  • Temporary Wi-Fi loss.
  • Duplicate QoS 1 command delivery.
  • Invalid command payloads.
  • Deleted discovery configuration.
  • Disconnected or failed sensors.
  • Two devices with similar names.
  • Actuator failure or local override.

The result should be predictable: entities return after restart, unavailable devices are shown as unavailable, commands do not create unsafe toggles, and stable IDs do not produce duplicate entities.

Conclusion

Toit gives the ESP32 a flexible embedded application runtime, MQTT provides a vendor-neutral transport, and Home Assistant MQTT discovery makes the device visible in the Home Assistant interface. The integration is practical for custom sensors and building-control hardware, but the developer must deliberately implement discovery, availability, state confirmation, reconnect handling, and restart recovery.

For a standard Home Assistant sensor, ESPHome may require less integration work. For custom hardware or a more capable application that may serve several MQTT consumers, Toit plus MQTT provides a clean separation between device logic and home- or building-automation software.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.