-->
Page 1 of 1

how to get the client handle in rtos mqtt example

PostPosted: Thu Jun 10, 2021 4:09 am
by sunbelt57
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?

Re: how to get the client handle in rtos mqtt example

PostPosted: Thu Jun 10, 2021 4:05 pm
by quackmore
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);
}

Re: how to get the client handle in rtos mqtt example

PostPosted: Tue Jun 15, 2021 9:09 am
by sunbelt57
I think you meant:
Code: Select allesp_mqtt_client_handle_t get_mqtt_client_handle(void)
{
    return client;
}

but, yeah, that worked! Thanks.