Skip to main content

Step 4: Connect to RelayX

Create device/main/app_shared.cpp to define the shared state and the device config:

#include "app_shared.h"

std::atomic<uint32_t> g_sample_rate_ms{SAMPLE_RATE_DEFAULT_MS};
RelayDevice *g_device = nullptr;
EventGroupHandle_t g_state_events = nullptr;

const relay_device_config_t device_config = {
.api_key = "your_api_key",
.secret = "your_api_secret",
.mode = RELAY_MODE_PRODUCTION,
};

Create device/main/device_task.cpp with the task that owns the RelayX connection:

#include "device_task.h"
#include "app_shared.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"

static const char *TAG = "device-task";

static void device_task(void *) {
g_device = new RelayDevice(device_config);

g_device->connection.on_status([](relay_connection_status_t status) {
if (status == RELAY_STATUS_CONNECTED) {
ESP_LOGI(TAG, "Device connected");
xEventGroupSetBits(g_state_events, DEVICE_READY_BIT);
}
});

g_device->connect();

while (true) {
g_device->process();
vTaskDelay(pdMS_TO_TICKS(10));
}
}

void device_task_start() {
xTaskCreate(device_task, "device_task", 16384, nullptr, 5, nullptr);
}

The SDK is callback-driven. Call process() on a tight loop to pump the connection, and subscribe to connection.on_status to learn when the device is ready. Setting DEVICE_READY_BIT lets other tasks wait on this event before they try to publish.

Create device/main/main.cpp to boot everything:

#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "nvs_flash.h"

#include "app_shared.h"
#include "device_task.h"
#include "wifi.h"

extern "C" void app_main(void) {
nvs_flash_init();
g_state_events = xEventGroupCreate();

wifi_init_and_wait();
device_task_start();
}

wifi_init_and_wait() is a short helper in device/main/wifi.cpp that brings up WiFi in station mode and blocks until the device has an IP. The full implementation is in the reference repo.

Test it

Build and flash:

# Build the firmware
idf.py build

# Upload and stream logs from the device
idf.py -p /dev/cu.usbserial-110 flash monitor

You should see the device connect within a few seconds:

I (4312) device-task: Device connected