How many "Event_handler" can be created?

Description

ESP32 M5Stack Core 2

lvgl@^8.1.0

Need help using Arduinojson to send messages to MQTT. From each object separately. How many “Event_handler” can be created without sacrificing performance.

I use new “Event_handler” for each new object.

Code to reproduce

The code block(s) should be formatted like:

StaticJsonDocument<256> doc;
char buffer[256];
JsonObject switch1 = doc.createNestedObject();

The code block(s) should be formatted like:

static void event_handler(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * obj = lv_event_get_target(e);
    if(code == LV_EVENT_VALUE_CHANGED) 
    {
      data["switch"] = lv_obj_has_state(obj, LV_STATE_CHECKED) ? "ON" : "OFF";
      serializeJson(doc, buffer);
      mqtt.publish("NESTControl/state", buffer);
    }
}

Screenshot and/or video


Screenshot_7

each event_handler will be a item of event_handlers array inside lv_object. LVGL on event call will cycle behind this array and call this handlers one by one serially.
this array will be reallocated on evety new event assigment, so you will need enought amount of RAM for sizeof(void *) * event_count.
I think you can’t do this action lighter.
OR
you can have only ONE event_handler for all checkers BUT use user_data as event source:

//one handler for all switches
lv_obj_add_event_cb(switch1, event_handler, LV_EVENT_VALUE_CHANGED, "NESTControl/state");
...
lv_obj_add_event_cb(switch2, event_handler, LV_EVENT_VALUE_CHANGED, "KtchenSwitch/state");

static void event_handler(lv_event_t * e)
{
    lv_obj_t * obj = lv_event_get_target(e);
    char * sender = (char *)lv_event_get_user_data(e);
    data["switch"] = lv_obj_has_state(obj, LV_STATE_CHECKED) ? "ON" : "OFF";
    serializeJson(doc, buffer);
    mqtt.publish(sender, buffer);
}

You can ommit lv_event_get_code() step if you will make
lv_obj_add_event_cb(switch, event_handler, LV_EVENT_VALUE_CHANGED, NULL);
this will bind action only for LV_EVENT_VALUE_CHANGED event and not need to check it again.

If you use RTOS in base of you firmware, I think the better way will be make packets send in separate thread from UI thread. And from LVGL event_handler add item to Query wich will be Received in send Thread and make packet send. This will prevent UI freezes…

1 Like

Thanks for the advice. this method does not work. lv_event_get_user_data(e) gets NULL. At this point, lv_obj_add_event_cb(switch, event_handler, LV_EVENT_VALUE_CHANGED, NULL); unable to insert char *.

:man_facepalming:
lv_obj_add_event_cb(switch2, event_handler, LV_EVENT_VALUE_CHANGED, (void *)"KtchenSwitch/state");

1 Like

Many thanks!!! This solved everything!!!

1 Like