Documentation · For device manufacturers
Your own ESP32 device: example and help with integration
Contents
This page is for manufacturers who want to build onlineWatt into their own device, or to build their own converter with an ESP32 microcontroller. It shows the shortest way from an empty board to values in the portal. The full interface description is on the page Connecting devices: MQTT and HTTP API.
What you need
- A manufacturer account in onlineWatt – set up by agreement, see The portal for device manufacturers.
- A device type with MQTT communication and a mapping, and in it one created device for testing. From its detail you copy the MQTT user, the MQTT password and the device number from the MQTT topics.
- The MQTT broker address – you receive it from onlineWatt when the account is set up.
- A board with an ESP32 (the example is built for ESP32-S3) and a development environment for Arduino core 3.x, for example PlatformIO; the ArduinoJson 7 library.
Procedure
1. Create the type and the device in the portal
In Types of devices click Add type of device, choose the technology and Communication MQTT and write the values you will send into the Mapping field. Then in Devices click Add device.
2. Copy the credentials
Devices → three dots → Edit: MQTT user, MQTT password and MQTT topics. The number in the topic onlinewatt/devices/123/metrics is the device number (DEVICE_ID).
3. Upload the example
Fill in the values at the beginning of the file and upload the example to the board.
4. Check the portal
In the Devices list the time in the Last metrics column of your unit changes within a minute. The values are seen by the customer or installation company that registers the device with its serial number and registration token. These belong on the device's rating label; for ESP32 devices we can supply ready-made labels with the serial number and token – write to info@onlinewatt.com.
Example
The example connects to Wi-Fi and to the broker over TLS, sends the average of the measured values once a minute, receives commands from the portal and answers them. Comments in the code are in Czech.
// onlineWatt – minimální příklad pro ESP32 (Arduino core 3.x, ESP-IDF 5)
// Posílá metriky jednou za minutu, přijímá příkazy z portálu a odpovídá na ně.
#include <Arduino.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#include <esp_crt_bundle.h>
#include <mqtt_client.h>
// --- Doplňte. V ostrém zařízení ukládejte údaje do NVS, ne do zdrojového kódu. ---
static const char* WIFI_SSID = "vase-wifi";
static const char* WIFI_PASS = "heslo-wifi";
static const char* BROKER_URI = "mqtts://ADRESA_BROKERU:PORT"; // sdělí onlineWatt
static const char* DEVICE_ID = "123"; // číslo z MQTT topiků v detailu zařízení
static const char* MQTT_USER = "mqtt-uzivatel"; // MQTT uživatel z detailu zařízení
static const char* MQTT_PASS = "mqtt-heslo"; // MQTT heslo z detailu zařízení
static esp_mqtt_client_handle_t client = nullptr;
static volatile bool mqttConnected = false;
static QueueHandle_t commands = nullptr;
static String topicBase, clientId;
static bool publishJson(const char* suffix, JsonDocument& doc) {
if (!mqttConnected) return false;
String topic = topicBase + "/" + suffix, payload;
serializeJson(doc, payload);
// QoS 1, bez retain
return esp_mqtt_client_enqueue(client, topic.c_str(), payload.c_str(), payload.length(), 1, 0, true) >= 0;
}
static void onMqttEvent(void*, esp_event_base_t, int32_t eventId, void* data) {
auto* ev = static_cast<esp_mqtt_event_handle_t>(data);
switch ((esp_mqtt_event_id_t)eventId) {
case MQTT_EVENT_CONNECTED: {
mqttConnected = true;
String t = topicBase + "/commands";
esp_mqtt_client_subscribe(client, t.c_str(), 1);
break;
}
case MQTT_EVENT_DISCONNECTED:
mqttConnected = false;
break;
case MQTT_EVENT_DATA: {
if (ev->data_len != ev->total_data_len) break; // příkazy jsou krátké, fragmenty neřešíme
char* copy = strndup(ev->data, ev->data_len); // zpracujeme v loop(), ne v obsluze události
if (copy && xQueueSend(commands, ©, 0) != pdTRUE) free(copy);
break;
}
default:
break;
}
}
static void startMqtt() {
topicBase = String("onlinewatt/devices/") + DEVICE_ID;
clientId = "esp32-" + String((uint32_t)(ESP.getEfuseMac() >> 16), HEX); // musí být jedinečné
esp_mqtt_client_config_t cfg = {};
cfg.broker.address.uri = BROKER_URI;
cfg.broker.verification.crt_bundle_attach = esp_crt_bundle_attach; // ověření certifikátu serveru (TLS)
cfg.credentials.client_id = clientId.c_str();
cfg.credentials.username = MQTT_USER;
cfg.credentials.authentication.password = MQTT_PASS;
cfg.session.disable_clean_session = true; // trvalá relace: příkazy se při výpadku neztratí
cfg.session.keepalive = 60;
cfg.network.reconnect_timeout_ms = 10000;
client = esp_mqtt_client_init(&cfg);
esp_mqtt_client_register_event(client, MQTT_EVENT_ANY, onMqttEvent, nullptr);
esp_mqtt_client_start(client);
}
// Sem patří čtení vašeho zařízení (Modbus, čidla…). Příklad vrací smyšlené hodnoty.
static float readPvPowerKw() { return 2.0f + (float)random(0, 100) / 100.0f; }
static float readBatterySoc() { return 64.5f; }
static void handleCommand(const char* json) {
JsonDocument cmd, resp;
if (deserializeJson(cmd, json)) return;
const char* name = cmd["command"] | "";
resp["uid"] = cmd["uid"]; // uid vraťte beze změny, portál podle něj spáruje odpověď
bool button = strncmp(name, "IndoorTemp", 10) == 0; // tlačítka portálu: IndoorTemp-2 … IndoorTemp+2
if (button || strcmp(name, "set_temperature") == 0) {
int offset = button ? atoi(name + 10) : (cmd["temperature_offset"] | 0);
// Zde nastavte zařízení. Potom pošlete událost se speciální akcí pro daný posun
// (topik events, {"id": číslo události}) a nový stav v dalších metrikách.
resp["response"]["success"] = true;
resp["response"]["message"] = String("Posun teploty nastaven na ") + offset + " °C";
} else {
resp["response"]["success"] = false;
resp["response"]["message"] = String("Neznámý příkaz: ") + name;
}
publishJson("commands_response", resp);
}
void setup() {
Serial.begin(115200);
commands = xQueueCreate(8, sizeof(char*));
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
startMqtt();
}
void loop() {
static uint32_t lastSample = 0, lastSend = 0, samples = 0;
static float sumPower = 0;
char* json = nullptr;
if (xQueueReceive(commands, &json, 0) == pdTRUE && json) {
handleCommand(json);
free(json);
}
if (millis() - lastSample >= 1000) { // vzorek každou sekundu
lastSample = millis();
sumPower += readPvPowerKw();
samples++;
}
if (millis() - lastSend >= 60000 && samples) { // jednou za minutu průměr vzorků
lastSend = millis();
JsonDocument m; // plochý JSON, názvy podle mappingu typu zařízení
m["mppt1_power"] = sumPower / samples;
m["battery_soc"] = readBatterySoc();
m["sw_version"] = "1.0.0";
if (publishJson("metrics", m)) { sumPower = 0; samples = 0; }
}
delay(10);
}Rules the device must follow
- Encrypted connection only (TLS) with verification of the server certificate.
- A unique
client_idfor each unit, for example derived from the chip's serial number. - Persistent session:
clean sessionswitched off. MQTT 3.1.1 is enough; with MQTT 5 set aSession Expiry Interval. - Metrics once a minute, QoS 1, without the retain flag. Send the average of the samples since the previous message; the portal does not accept back-filling of older data.
- When metrics do not arrive for about 5 minutes, the portal marks the device as offline. Do not send a separate status message (last will, heartbeat).
- One device in the portal is either a PV system or a heat pump. Add up several inverters at one site into one set of values.
- Signs: minus means battery discharging and feed-in to the distribution grid; plus means production, charging and consumption from the grid.
- Send versions in the fields
hw_versionandsw_version. - Answer every command with the same
uid. After a temperature change, send an event with the special action for that shift and the new state in the following metrics. - Do not store credentials in the source code. Write them into the device only during production, into protected memory.
Other microcontrollers and languages
The interface is plain MQTT with JSON, so another microcontroller, a single-board computer or a PLC with an MQTT client and TLS support works the same way. The same rules apply. For Tecomat PLCs there is a separate example in the Mosaic environment.
Development with the help of AI
AI assistants are good at writing ESP32 firmware. Give the assistant a link to this page and to the page Connecting devices: MQTT and HTTP API and tell it:
- which board you have and how it reads data (Modbus RTU or TCP, sensors, your own bus),
- which values you want to send and under which field names,
- whether the device should receive commands,
- that it must follow the rules on this page.
Do not paste device credentials into the conversation with the AI; fill them in only in the finished device.
We will help you
We help with integration: with designing the mapping and event types, with a test device and with checking that data reaches the portal correctly. Write to info@onlinewatt.com which device you make and how it communicates.
Limits of the example
- The example is a starting point, not finished firmware: it does not handle Wi-Fi setup by the user, remote updates, storing credentials in protected memory or reading a real device.
- The values in the example are made up.
← All documentation · Found a mistake or missing something? Write to info@onlinewatt.com.