Tutorial: Smart Home (MQTT + Home Assistant) & Industrial Buses (Modbus & CAN)

PylotOS bridges hobbyist/maker handhelds and industrial automation out of the box with zero external library bloat: MQTT 3.1.1 + Home Assistant Auto-Discovery, Modbus RTU (CRC-16) / Modbus TCP (MBAP), and Native ESP-IDF TWAI (CAN 2.0B).


1. Zero-Dependency MQTT + Home Assistant Auto-Discovery (pylotos.mqtt_ha)

pylotos.mqtt_ha reads hal.describe() and generates retained homeassistant/sensor/pylotos_<node>/*/config JSON payloads automatically (Heap Free, Uptime, plus Battery and Wi-Fi RSSI when supported by the board):

import json
import hal
from pylotos.mqtt_ha import MqttHaService, build_ha_discovery_messages

# Inspect generated Home Assistant discovery topics offline:
for topic, payload_json in build_ha_discovery_messages(node_id="kitchen_dial"):
    print(topic, "->", payload_json)

# Connect & publish live telemetry from an async app or `/apps/services/` daemon:
svc = MqttHaService(host="192.168.1.10", port=1883, username="ha", password="secret")
await svc.connect()
await svc.publish_discovery()
await svc.publish(
    "pylotos/" + svc.node_id + "/state",
    json.dumps({"heap_free": hal.mem_info()["heap_free_bytes"], "uptime_s": 120}),
)
await svc.close()

Inbound command topics are automatically screened by pylotos.policy.evaluate() so unauthorized MQTT publishers cannot read secrets or execute unapproved actions.


2. Industrial Modbus RTU (CRC-16) & Modbus TCP (MBAP) (pylotos.modbus)

Communicate with RS-485 energy meters, VFDs, and industrial PLCs over UART (RTU) or Wi-Fi/W5500 Ethernet (TCP :502):

from pylotos import modbus

# 1. Modbus RTU (RS-485): Read 2 Holding Registers starting at 0x0010 from Slave #1
pdu = modbus.build_read_holding_pdu(start_addr=0x0010, count=2)
rtu_frame = modbus.build_rtu_frame(unit_id=1, func_code=0x03, pdu_payload=pdu)
unit_id, fc, body = modbus.parse_rtu_frame(rtu_frame)  # Verifies polynomial 0xA001 CRC-16!

# 2. Async Modbus TCP Client (:502 MBAP):
client = modbus.ModbusTcpClient("192.168.1.50", port=502, unit_id=1)
await client.connect()
registers = await client.read_holding_registers(start_addr=0x0000, count=4)
await client.close()

3. Native CAN 2.0A/B (TWAI) Controller (hal.can_*)

Pair any ESP32 / ESP32-S3 / ESP32-C3 / ESP32-C6 Grove port with an external SN65HVD230 / TJA1051 CAN transceiver (e.g., M5Stack CAN Unit):

import hal

hal.can_init(tx_gpio=2, rx_gpio=1, bitrate_bps=500_000, listen_only=False)
hal.can_send(0x180, b"\x11\x22\x33\x44", extended=False)

rx_buf = bytearray(8)
res = hal.can_recv_into(rx_buf, timeout_ms=20)
if res is not None:
    arb_id, dlc, is_extended = res
    print(hex(arb_id), bytes(rx_buf[:dlc]))
hal.can_deinit()

Try both interactive Smart Home & Industrial apps in pylotos-sim:

pylotos-sim examples/mqtt_home_assistant_dashboard.py --board m5stack_dial --port 8080
pylotos-sim examples/modbus_plc_and_can_gateway.py --board m5stack_core2 --port 8080