Layer: L7 Application ยท Build flags: PC_ENABLE_UDP_TELEMETRY
What this example teaches
For high-frequency metrics you often do not want the cost or back-pressure of TCP. This builds an InfluxDB line-protocol record and casts it to a collector over UDP once a second - zero-heap, no ACK, no retry. Point it at Telegraf or InfluxDB's UDP listener (or just nc -u -l 8094 to watch the packets).
Set the destination once:
pc_udp_telemetry_begin(COLLECTOR_IP, COLLECTOR_PORT);
Build a line into a caller-owned buffer, then cast it. pc_line_* appends typed fields (the i suffix InfluxDB uses for integers comes from the _int/_uint helpers); pc_udp_telemetry_cast() sends one datagram:
pc_line line;
pc_line_init(&line, buf, sizeof(buf), "esp32");
pc_line_add_uint(&line, "heap", ESP.getFreeHeap());
pc_line_add_float(&line, "temp", temperatureRead(), 1);
pc_udp_telemetry_cast(&line);
int8_t pc_net_rssi(void)
Station link RSSI in dBm, or 0 if not associated (and on host builds).
#define PC_UDP_TELEMETRY_BUF
Stack buffer for one telemetry line (bytes).
There is no server here - the device is purely a telemetry source - so loop() just casts on a timer.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPC_ENABLE_UDP_TELEMETRY=1" \
--lib="." examples/L7-Application/UdpTelemetry/UdpTelemetry.ino
nc -u -l 8094 # watch the line-protocol datagrams (set COLLECTOR_PORT to match)
Annotated source
The complete sketch (UdpTelemetry.ino), reproduced verbatim with added explanatory comments:
#define PC_ENABLE_UDP_TELEMETRY 1
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
static const char *COLLECTOR_IP = "192.168.1.10";
static const uint16_t COLLECTOR_PORT = 8094;
void setup()
{
Serial.begin(115200);
Serial.print("Connecting to WiFi");
{
delay(250);
Serial.print('.');
}
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
pc_udp_telemetry_begin(COLLECTOR_IP, COLLECTOR_PORT);
}
void loop()
{
static uint32_t last = 0;
if (millis() - last >= 1000)
{
last = millis();
pc_line line;
pc_line_init(&line, buf, sizeof(buf), "esp32");
pc_line_add_uint(&line, "heap", ESP.getFreeHeap());
pc_line_add_float(&line, "temp", temperatureRead(), 1);
if (pc_udp_telemetry_cast(&line))
Serial.printf("cast: %s\n", buf);
}
}
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
Fire-and-forget UDP telemetry cast (PC_ENABLE_UDP_TELEMETRY).