How to pass payload to a task

Blaise70
Posts: 2
Joined: Tue Oct 02, 2018 8:19 pm

How to pass payload to a task

Postby Blaise70 » Tue Oct 02, 2018 8:39 pm

Hi,

I'd like to pass the payload (event->data and event->topic) to a task from the mqtt_event_handler.
The event handler receives a pointer to the struct esp_mqtt_event_handle_t and it can be processed in the event handler itself.
In my understanding this event handler is kind of call back function and data processing which might consume time and/or requires other resources is not suggested to be placed here. Therefore I'd like to move the processing to a separate task which can be notified from within the event handler.
What is not clear for me is the availability of the event struct. I guess this is created/instantiated somewhere in the mqtt driver and a pointer is passed to the event handler. So passing this pointer forward to my task is not safe. This struct might/will be destroyed by the driver some time. If I want to ensure that the payload is available for my task I have to create a copy of it. And not only the event struct, but also the data and topic buffers, since these fields are only pointers to the exact data.
Can someone explain this process in more detail? Is there an example available for a similar solution?

Thanks for your kind help in advance.
Best regards,
Blaise
--
Blaise

chegewara
Posts: 582
Joined: Wed Jun 14, 2017 9:00 pm

Re: How to pass payload to a task

Postby chegewara » Wed Oct 03, 2018 5:18 pm


chrismerck
Posts: 25
Joined: Tue May 29, 2018 8:00 pm

Re: How to pass payload to a task

Postby chrismerck » Thu Oct 04, 2018 2:51 pm

Hi Blase,

Often you can process the message within the mqtt_subscribe_callback. You just want to check that that callback is a normal task context and has a moderate priority. --- You wouldn't want to process the message from interrupt context, or within a task with very high priority.

That said, if you have some long-running operation that you don't want to block mqtt_subscribe_callback, use a queue. Consider creating your own struct to put on the queue to de-couple your processing code from the mqtt structure type. In this situation I often use (gasp) dynamic allocation with malloc() for the struct, and just place a pointer to the struct on the queue. This is safe as long as you remember to free() the struct when done with it on the receiving side, or if it fails to enqueue.

Hope that helps.

-Chris

Blaise70
Posts: 2
Joined: Tue Oct 02, 2018 8:19 pm

Re: How to pass payload to a task

Postby Blaise70 » Thu Oct 04, 2018 7:58 pm

Hi Chris and Chegewara,

Thanks for your kind reply. Yes, I see that queue is a handful solution for this situation. I also like the idea to define my own struct which represents only the necessary information.
Thanks for your kind help again.
Best regards,
Blaise
--
Blaise

Who is online

Users browsing this forum: No registered users and 3 guests