- C++ 56.7%
- C 34.9%
- Python 8.4%
Seen on hardware: a plain `wlink dump` (or `wlink sdi-print enable`) on a running board left RCC_CTLR at 0x03007583, HSE and PLL3 off and the PLL on HSI. The PHY lost its clock, so the link went down and stayed down; the RTC, on HSE / 128, stopped; MQTT timed out at the broker 12 s later. A reset after the attach, which `wlink flash` does, is clean. SDI print also dropped output and then refused with "Please check the SDI", so PA9 is the way to log. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|---|---|---|
| docs | ||
| examples | ||
| tools | ||
| wch | ||
| .gitignore | ||
| esp_log_compat.h | ||
| library.json | ||
| README.md | ||
| SmartLib.cpp | ||
| SmartLib.h | ||
SmartLib
WiFi/Ethernet + MQTT plumbing for custom smart devices. Topics are always
<deviceName>/TX/<subtopic> device -> broker
<deviceName>/RX/<subtopic> broker -> device (subscribed automatically)
A whole device
#include <SmartLib.h>
#define RELAY 5
SmartLib Smart("KitchenLight", "ssid", "pass", "192.168.1.100", "user", "pass", LED_BUILTIN);
void publishState()
{
Smart.sendToMQTTStr("Relay", digitalRead(RELAY) ? "on" : "off", true); // retained
}
void onRelay(const char *topic, const String &payload)
{
digitalWrite(RELAY, SmartLib::isOn(payload));
Smart.replyTo(topic, digitalRead(RELAY) ? "on" : "off"); // -> KitchenLight/TX/Relay
}
void setup()
{
pinMode(RELAY, OUTPUT);
Smart.on("Relay", onRelay); // KitchenLight/RX/Relay
Smart.setConnectedCallback(publishState); // re-announce after every reconnect
Smart.setOTAPassword("ota-secret"); // OTA stays off without one
Smart.setFirmwareVersion("1.0.0"); // shown by smartscan and in /TX/Info
Smart.begin();
}
void loop()
{
Smart.loop();
static uint32_t lastDiag = 0;
if (Smart.getStatus() && SmartLib::every(lastDiag, 60000))
Smart.publishDiagnostics();
}
Examples
| Relay | WiFi relay with a local button: retained state, republish on reconnect, safe state before OTA |
| Sensor | Timestamped readings (NTP), a period settable over MQTT, diagnostics |
| EthernetW5500 | The same over a W5500 on an ESP32-S2: SPI pins, MAC, active-low LED |
| Listener | Following another device (onRaw), +/# wildcards, rxSubTopic |
| CH32V317 | A relay on the chip's own Ethernet with the noneos-sdk, see below |
Several WiFi networks
Smart.addWiFi("Garage", "pass2"); // before begin()
Smart.addWiFi(ssids, passes, count); // or a whole list
With more than one network the device scans on every (re)connect and joins
the strongest known one in range (up to SMARTLIB_MAX_WIFI, 4 by default).
Repeating the constructor's network is fine, duplicates are ignored. A known
network the scan doesn't show (hidden SSID) still gets its turn. The network
in use is the ssid field of <device>/TX/Info.
Credentials are not saved by the WiFi SDK (WiFi.persistent(false)):
SmartLib hands them over on every connect, so an old password doesn't linger
in flash after a change.
Routing
on(filter, handler)— filter is relative to<device>/RX/, MQTT wildcards work:on("Relay/+", ...)catchesRelay/1,on("#", ...)catches everything.onRaw(filter, handler[, qos])— absolute topic anywhere on the broker, e.g.onRaw("Thermostat/TX/Temperature", ...). Resubscribed on every reconnect, at QoS 0 unlessqosis 1.setMQTTCallback(cb)— the old raw callback, still there, runs before routing.- Filters are stored by pointer, so pass string literals or globals.
Availability
On by default: <device>/TX/Availability is published online (retained) on
connect, and the broker publishes offline there via the last will if the
device drops off — that's what Home Assistant's availability_topic wants.
online is republished every minute while connected, so a stale offline
(a last will from an abandoned session on a backup broker, carried over by a
bridge) is corrected within a minute.
Change with setAvailability("Status/Online", "1", "0") or turn it off with
disableAvailability(), before begin().
Helpers
sendToMQTTStr(t, p, retain) |
publish a string |
sendToMQTT(t, fmt, ...) / sendToMQTTRetained |
printf-style publish |
setBufferSize(bytes) |
MQTT packet buffer, 512 by default (topic + payload + header) |
replyTo(rxTopic, payload) |
answer on the TX topic mirroring an RX topic |
publishDiagnostics() |
uptime / heap / IP / RSSI as JSON |
rxSubTopic(topic) |
strip <device>/RX/ off a received topic |
getIP(), getRSSI(), deviceName(), getStatus() |
state |
SmartLib::isOn(payload) |
1/on/true/yes/open -> true |
SmartLib::every(last, ms) |
non-blocking interval |
SmartLib::topicMatches(filter, topic) |
MQTT wildcard match |
loop() keeps WiFi/Ethernet and MQTT connected on its own; reconnects are
rate-limited and DHCP is retried if it failed at boot, so nothing blocks the
sketch for long. One SmartLib instance per sketch.
Finding devices
Every device calls itself by its name on the network: the device name,
reduced to letters, digits and - ("Lora Gateway" -> Lora-Gateway), is
used as
- the DHCP hostname, so the router's lease list shows
KitchenLightinstead ofesp32c3-CCC62C(Ethernet too, via the Ethernet fork below), - the mDNS name on WiFi:
KitchenLight.local, - the MQTT client id:
KitchenLight-CCC62C(broker logs).
Override with setHostname("...") before begin().
tools/smartscan.py lists every SmartLib device in an address range. Each
device answers a probe on UDP 3234 with its name, IP, MAC, chip, firmware,
uptime, RSSI and MQTT/OTA/NTP state:
tools/smartscan.py # local subnets, interactive
tools/smartscan.py 192.168.1.0/24 # or 192.168.1.20-80, or 10.0.0.5-10.0.1.40
tools/smartscan.py --once # plain table; --json for scripts
In the list, i blinks the selected device's activity LED so you can find it
physically, and Enter shows the details and the OTA upload settings. More in
tools/README.md. The same
blink is <device>/RX/Identify (payload: seconds, default 10, 0 stops).
The same information is published retained on <device>/TX/Info on every
connect. setFirmwareVersion("1.2.0") adds your version to it; the md5 field
tells builds apart even when the version doesn't change.
OTA
On by default on ESP32 / S2 / S3 / C3 / ESP8266, over WiFi (ArduinoOTA) and over W5x00 Ethernet (the same espota protocol, implemented by SmartLib). A password is required: without one OTA stays off and says so in the log.
Smart.setOTAPassword(OTA_PASSWORD); // or build_flags = -DSMARTLIB_OTA_PASSWORD=\"...\"
Smart.allowOTAWithoutPassword(); // testing only
Smart.disableOTA();
Smart.setOTAStartCallback(safeState); // relays off etc. before flashing starts
Then upload with upload_protocol = espota and upload_port = <hostname>.local
(the IP on Ethernet). docs/OTA.md covers the whole thing:
the first USB flash, PlatformIO / Arduino IDE / espota setups, the firewall
port the device connects back to, and troubleshooting.
Just before flashing, the device publishes offline on its availability topic
and disconnects from MQTT; a failed update reconnects. The partition table
needs two app slots (the default one has them; min_spiffs.csv if the
firmware is big).
Time
NTP starts by itself once the network is up, using the NTP server the DHCP
server offers (option 42), or pool.ntp.org if it offers none. On WiFi lwIP
also picks up a changed server on lease renewal. Local time defaults to
Europe/Prague.
Smart.setTimezone("UTC0"); // POSIX TZ, before begin()
Smart.setNTPServer("cz.pool.ntp.org"); // fallback when DHCP has none
Smart.disableNTP();
time(nullptr); // UTC epoch, as usual
SmartLib::timeValid(); // clock set?
char now[32];
SmartLib::timeString(now, sizeof(now)); // "2026-09-27T14:03:11+0200"
-DSMARTLIB_DEFAULT_TZ=... / -DSMARTLIB_DEFAULT_NTP=... change the defaults
for a whole project.
Ethernet
SmartLib depends on a fork of the Ethernet library
that fixes the send/flush loops that hang forever when the cable is pulled or
the peer disappears, sends the DHCP hostname and asks DHCP for an NTP server.
Remove arduino-libraries/Ethernet from a project's lib_deps (and any
patch_ethernet.py), otherwise the build warns that the upstream library was
picked.
Ethernet uses more W5x00 sockets now: MQTT, OTA and discovery stay open, and
NTP, DHCP and DNS open one briefly. That's fine on a W5500 (8 sockets); on a
W5100 (4) call disableDiscovery() if the sketch opens sockets of its own.
CH32V317
On PlatformIO's noneos-sdk framework SmartLib runs on the chip's own MAC +
10/100M PHY, through WCH's WCHNET stack: no Arduino core, no W5x00, no
Ethernet or PubSubClient library. examples/CH32V317
is a complete project. What differs from the rest of this page:
// No pins for the PHY, and the MAC address comes from the chip.
SmartLib Smart("Relay317", "192.168.1.100", "user", "pass", SMARTLIB_PIN('B', 0));
SmartLib Smart("Relay317", mac, "192.168.1.100", "user", "pass"); // your own MAC
int main(void)
{
SystemCoreClockUpdate();
Delay_Init();
USART_Printf_Init(115200); // optional: without it SmartLib does not log
Smart.begin(); // does not wait for the link or for DHCP
while (1)
Smart.loop(); // this also runs the network stack
}
platformio.ini:
platform = https://github.com/Community-PIO-CH32V/platform-ch32v.git#6f351d406baa2bf19a368fee9560294c1edaa792
board = genericCH32V317VCT6 ; or genericCH32V317WCU6
framework = noneos-sdk
board_build.clock_source = hse+pll
board_build.stack_size = 4096 ; 2 KB is tight with SmartLib's JSON
lib_deps = https://forgejo.vratk0529.com/vratk0529/SmartLib.git
- 8 MHz crystal required. The PHY's clock comes from HSE alone, and WCH's driver only sets it up for 8 MHz. SmartLib starts HSE itself if the system clock runs from HSI (the board default).
- Taken by SmartLib: SysTick (stack clock and
millis(), 1 ms resolution, no interrupt),ETH_IRQHandler, the RTC and the RNG.Delay_Us()andDelay_Ms()still work: they are redirected at link time, because the SDK's would stop SysTick. All the timers are yours. The cable side is on the dedicated MDITP/N, MDIRP/N, LED0 and LED1 pins; PE7-PE15 and PD8, which the reference manual lists for the RMII, are wiring inside the chip, not pins of this package. - Don't use PC13-PC15 for an LED. The datasheet rules them out as current sources, and they pass 3 mA at most.
- Keep the main loop moving. Nothing runs the stack between
loop()calls, so wait withdelay()orSmartLib::every(), notDelay_Ms(). - 45 KB of RAM. The linker script assumes the 256K flash + 64K RAM split. A
chip whose option bytes say otherwise has to be set to it (or a split with
more RAM) with WCH's tools, or it crashes before
main(). - Don't attach the WCH-Link to a running board. Its attach turns HSE off and
runs the chip from HSI: the link goes down and the clock stops, until a reset.
Flashing ends in a reset, so that is fine, but any other
wlinkcommand, SDI print included, is not. For logs, wire PA9 to a serial adapter instead. - Time works as described above, except:
- DHCP cannot name a server, because WCHNET does not ask for one. It is
setNTPServer()orpool.ntp.org. An IP address works too, and avoids the DNS lookup, which holds uploop()for up to 5 s when nothing answers. With no internet at all, use a server on your network ordisableNTP(). - The clock is the chip's RTC, from the 8 MHz crystal divided by 128 and
corrected hourly. With the ±40 ppm crystal the datasheet asks for, that is
at most 0.15 s off before each correction, whatever the system clock runs
from. It starts in
begin(), and until thentime()starts from 0. - It keeps going through a reset, so
timeValid()stays true, up to a second off until NTP answers. After a power loss it is false until NTP answers, even with a battery on VBAT: the RM calls the RTC indeterminate when VDD goes while it runs from HSE. - With a 32.768 kHz crystal and a battery on VBAT,
-D SMARTLIB_RTC_LSEkeeps time through a power loss too. It takes PC14 and PC15, and if the crystal does not start within 2 s it uses HSE after all. Changing this resets the backup domain, and with it the backup registers. setTimezone()zone names must be letters: newlib misreads<+03>-3, so writeXXX-3.
- DHCP cannot name a server, because WCHNET does not ask for one. It is
- Reset reason is in the Info JSON as on ESP, and
smartlibResetReason()returns it.begin()clears the RCC's reset flags to keep each boot's apart, so read those first if you want them yourself. - Logging goes through
printf(), which blocks the network stack. Debug and verbose messages are compiled out unless you set-D SMARTLIB_LOG_LEVEL=4or5(1 is errors only). - Not available: OTA (ESP only, as on STM32), so no
setOTAPassword()and so on; WiFi, of course. - MQTT is a small built-in client with PubSubClient's limits: QoS 0
publishes, subscriptions up to QoS 1.
setBufferSize()sizes separate send and receive buffers, 15 bytes at the least. - Discovery holds one probe at a time, a second arriving before the next
loop()is dropped. Scan again if a device is missing. - Pins are
SMARTLIB_PIN('A', 1);pinMode(pin, OUTPUT),digitalWrite(),millis(),delay()and a minimalStringexist, the rest of the Arduino API doesn't. Handlers look the same as everywhere else.
Upgrading from 1.4
- Nothing to change. The CH32V317 now has NTP time, on by default: call
disableNTP()to keep it from reaching out topool.ntp.org. It keeps the time on the RTC, so a sketch of its own can no longer use that. - On Ethernet, NTP retries back off from 30 s to 4 minutes until the first sync and after a failed hourly one, and replies have to echo the request's transmit timestamp, as RFC 5905 servers do.
Upgrading from 1.3
- Nothing to change.
library.jsonnow asks forPubSubClientandEtherneton the Arduino framework only.
Upgrading from 1.1
- Nothing to change. The WiFi SDK no longer stores the credentials in flash,
and
<device>/TX/Infohas a newssidfield.
Upgrading from 1.0
- Set an OTA password, or OTA stays off.
- The MQTT client id changed from
esp32-client-<MAC>to<hostname>-<MAC tail>. <device>/TX/Infois new, and<device>/RX/Identifyis now handled by SmartLib instead of reaching youron("#")handler.- Drop your own NTP / ArduinoOTA code, and
arduino-libraries/Ethernet.