Layer: L7 Application ยท Build flags: PROTOCORE_ENABLE_GUARDRAILS
What this example teaches
A long-running device dies quietly when it runs out of heap or stack. Guardrails watch four resources - free heap, heap low-water, largest free block (fragmentation), and this task's remaining stack - and fire a callback when any crosses its PROTOCORE_GUARDRAIL_* floor, so the app can shed load, drop to a safe state, or reboot before exhaustion bites. The live snapshot is also served as JSON at /health.
Install a breach callback, then check periodically:
protocore_guardrails_begin(on_breach);
void loop() {
if ()
protocore_guardrails_check();
}
The callback receives a bitmask of which floors were breached and the full health snapshot:
static void on_breach(uint8_t breaches, const protocore_health *h) {
Serial.printf("[guardrail] breach=0x%02x heap=%u frag=%u stack=%u\n",
breaches, (unsigned)h->free_heap, (unsigned)h->largest_free_block, (unsigned)h->stack_free);
}
protocore_guardrails_sample(&h) fills a snapshot on demand and protocore_health_json() serializes it for the /health endpoint.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--project-option="build_flags=-DPROTOCORE_ENABLE_GUARDRAILS=1" \
--lib="." examples/L7-Application/Guardrails/Guardrails.ino
curl http://<ip>/health # JSON: free heap, largest block, stack free
Annotated source
The complete sketch (Guardrails.ino), reproduced verbatim with added explanatory comments:
#define PROTOCORE_ENABLE_GUARDRAILS 1
#include "protocore.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
PC server;
static void on_breach(uint8_t breaches, const protocore_health *h)
{
Serial.printf("[guardrail] breach=0x%02x heap=%u frag=%u stack=%u\n", breaches, (unsigned)h->free_heap,
(unsigned)h->largest_free_block, (unsigned)h->stack_free);
}
void setup()
{
Serial.begin(115200);
Physical.wifi->init(SSID, PASSWORD);
while (!Physical.wifi->ready())
delay(250);
Serial.print("IP: ");
uint32_t ip = Physical.link->egress_ip();
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
protocore_guardrails_begin(on_breach);
protocore_health h;
protocore_guardrails_sample(&h);
char buf[128];
protocore_health_json(&h, buf, sizeof(buf));
server.send(id, 200, "application/json", buf);
});
server.begin(80);
}
void loop()
{
static uint32_t last = 0;
if (millis() - last >= 1000)
{
last = millis();
protocore_guardrails_check();
}
}
Runtime heap/stack guardrails (PROTOCORE_ENABLE_GUARDRAILS).
@ HTTP_GET
Safe, idempotent read.
Layer 1 (Physical) - link bring-up, the interface registry, and live egress reporting.