Chat freely about anything...

User avatar
By sunbelt57
#91595 I'm working with one of the examples that comes with the RTOS SDK: (examples/protocols/mqtt/tcp) and I have added the serial port because I want to send data to be published to the MQTT broker. So in my UART queue, I call
Code: Select allesp_mqtt_client_publish()
but I don't have a handle to the client, which is only set within the callback. I tried using a global copy of the client handle, but it didn't work, besides being a bad idea:


Code: Select allesp_mqtt_client_handle_t gclient = NULL;

static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
    esp_mqtt_client_handle_t client = event->client;
    gclient = client;
    int msg_id;
    // your_context_t *context = event->context;
    switch (event->event_id) {
        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
            msg_id = esp_mqtt_client_subscribe(client, "debug/test1", 0);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

            msg_id = esp_mqtt_client_subscribe(client, "debug/test2", 1);
            ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);
            /*
            msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
            ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);


Is there any graceful way to get the client handle outside of the callback? Or maybe another way would be to create a custom event and send that message to the callback?
User avatar
By quackmore
#91599 esp_mqtt_client_init sets the client handle

so you just have to "save" it when you init your client
and define a method to retrieve it

like this (for instance)

Code: Select all
static esp_mqtt_client_handle_t client;

mqtt_client_handle_t get_mqtt_client_handle(void)
{
    return client;
}

static void mqtt_app_start(void)
{
    const esp_mqtt_client_config_t mqtt_cfg = {
        .uri = CONFIG_BROKER_URI,
        .cert_pem = (const char *)mqtt_eclipse_org_pem_start,
    };

    ESP_LOGI(TAG, "[APP] Free memory: %d bytes", esp_get_free_heap_size());
    client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
    esp_mqtt_client_start(client);
}