1 /*
2  * SPDX-FileCopyrightText: 2018-2023 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdlib.h>
8 #include <string.h>
9 #include <stdio.h>
10 #include <stdbool.h>
11 
12 #include "esp_log.h"
13 
14 #include "esp_event.h"
15 #include "esp_event_internal.h"
16 #include "esp_event_private.h"
17 
18 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
19 #include "esp_timer.h"
20 #endif
21 
22 /* ---------------------------- Definitions --------------------------------- */
23 
24 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
25 // LOOP @<address, name> rx:<recieved events no.> dr:<dropped events no.>
26 #define LOOP_DUMP_FORMAT              "LOOP @%p,%s rx:%" PRIu32 " dr:%" PRIu32 "\n"
27  // handler @<address> ev:<base, id> inv:<times invoked> time:<runtime>
28 #define HANDLER_DUMP_FORMAT           "  HANDLER @%p ev:%s,%s inv:%" PRIu32 " time:%lld us\n"
29 
30 #define PRINT_DUMP_INFO(dst, sz, ...)  do { \
31                                             int cb = snprintf(dst, sz, __VA_ARGS__); \
32                                             dst += cb; \
33                                             sz -= cb; \
34                                         } while(0);
35 #endif
36 
37 /* ------------------------- Static Variables ------------------------------- */
38 
39 static const char* TAG = "event";
40 static const char* esp_event_any_base = "any";
41 
42 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
43 static SLIST_HEAD(esp_event_loop_instance_list_t, esp_event_loop_instance) s_event_loops =
44         SLIST_HEAD_INITIALIZER(s_event_loops);
45 
46 static portMUX_TYPE s_event_loops_spinlock = portMUX_INITIALIZER_UNLOCKED;
47 #endif
48 
49 
50 /* ------------------------- Static Functions ------------------------------- */
51 
52 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
53 
54 
esp_event_dump_prepare(void)55 static int esp_event_dump_prepare(void)
56 {
57     esp_event_loop_instance_t* loop_it;
58     esp_event_loop_node_t *loop_node_it;
59     esp_event_base_node_t* base_node_it;
60     esp_event_id_node_t* id_node_it;
61     esp_event_handler_node_t* handler_it;
62 
63     // Count the number of items to be printed. This is needed to compute how much memory to reserve.
64     int loops = 0, handlers = 0;
65 
66     portENTER_CRITICAL(&s_event_loops_spinlock);
67 
68     SLIST_FOREACH(loop_it, &s_event_loops, next) {
69         SLIST_FOREACH(loop_node_it, &(loop_it->loop_nodes), next) {
70             SLIST_FOREACH(handler_it, &(loop_node_it->handlers), next) {
71                 handlers++;
72             }
73 
74             SLIST_FOREACH(base_node_it, &(loop_node_it->base_nodes), next) {
75                 SLIST_FOREACH(handler_it, &(base_node_it->handlers), next) {
76                     handlers++;
77                 }
78                 SLIST_FOREACH(id_node_it, &(base_node_it->id_nodes), next) {
79                     SLIST_FOREACH(handler_it, &(id_node_it->handlers), next) {
80                         handlers++;
81                     }
82                 }
83             }
84         }
85         loops++;
86     }
87 
88     portEXIT_CRITICAL(&s_event_loops_spinlock);
89 
90     // Reserve slightly more memory than computed
91     int allowance = 3;
92     int size = (((loops + allowance) * (sizeof(LOOP_DUMP_FORMAT) + 10 + 20 + 2 * 11)) +
93                         ((handlers + allowance) * (sizeof(HANDLER_DUMP_FORMAT) + 10 + 2 * 20 + 11 + 20)));
94 
95     return size;
96 }
97 #endif
98 
esp_event_loop_run_task(void * args)99 static void esp_event_loop_run_task(void* args)
100 {
101     esp_err_t err;
102     esp_event_loop_handle_t event_loop = (esp_event_loop_handle_t) args;
103 
104     ESP_LOGD(TAG, "running task for loop %p", event_loop);
105 
106     while(1) {
107         err = esp_event_loop_run(event_loop, portMAX_DELAY);
108         if (err != ESP_OK) {
109             break;
110         }
111     }
112 
113     ESP_LOGE(TAG, "suspended task for loop %p", event_loop);
114     vTaskSuspend(NULL);
115 }
116 
handler_execute(esp_event_loop_instance_t * loop,esp_event_handler_node_t * handler,esp_event_post_instance_t post)117 static void handler_execute(esp_event_loop_instance_t* loop, esp_event_handler_node_t *handler, esp_event_post_instance_t post)
118 {
119     ESP_LOGD(TAG, "running post %s:%"PRIu32" with handler %p and context %p on loop %p", post.base, post.id, handler->handler_ctx->handler, &handler->handler_ctx, loop);
120 
121 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
122     int64_t start, diff;
123     start = esp_timer_get_time();
124 #endif
125     // Execute the handler
126 #if CONFIG_ESP_EVENT_POST_FROM_ISR
127     void* data_ptr = NULL;
128 
129     if (post.data_set) {
130         if (post.data_allocated) {
131             data_ptr = post.data.ptr;
132         } else {
133             data_ptr = &post.data.val;
134         }
135     }
136 
137     (*(handler->handler_ctx->handler))(handler->handler_ctx->arg, post.base, post.id, data_ptr);
138 #else
139     (*(handler->handler_ctx->handler))(handler->handler_ctx->arg, post.base, post.id, post.data);
140 #endif
141 
142 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
143     diff = esp_timer_get_time() - start;
144 
145     xSemaphoreTake(loop->profiling_mutex, portMAX_DELAY);
146 
147     // At this point handler may be already unregistered.
148     // This happens in "handler instance can unregister itself" test case.
149     // To prevent memory corruption error it's necessary to check if pointer is still valid.
150     esp_event_loop_node_t* loop_node;
151     esp_event_handler_node_t* handler_node;
152     SLIST_FOREACH(loop_node, &(loop->loop_nodes), next) {
153         SLIST_FOREACH(handler_node, &(loop_node->handlers), next) {
154             if(handler_node == handler) {
155                 handler->invoked++;
156                 handler->time += diff;
157             }
158         }
159     }
160 
161     xSemaphoreGive(loop->profiling_mutex);
162 #endif
163 }
164 
handler_instances_add(esp_event_handler_nodes_t * handlers,esp_event_handler_t event_handler,void * event_handler_arg,esp_event_handler_instance_context_t ** handler_ctx,bool legacy)165 static esp_err_t handler_instances_add(esp_event_handler_nodes_t* handlers, esp_event_handler_t event_handler, void* event_handler_arg, esp_event_handler_instance_context_t **handler_ctx, bool legacy)
166 {
167     esp_event_handler_node_t *handler_instance = calloc(1, sizeof(*handler_instance));
168 
169     if (!handler_instance) return ESP_ERR_NO_MEM;
170 
171     esp_event_handler_instance_context_t *context = calloc(1, sizeof(*context));
172 
173     if (!context) {
174         free(handler_instance);
175         return ESP_ERR_NO_MEM;
176     }
177 
178     context->handler = event_handler;
179     context->arg = event_handler_arg;
180     handler_instance->handler_ctx = context;
181 
182     if (SLIST_EMPTY(handlers)) {
183         SLIST_INSERT_HEAD(handlers, handler_instance, next);
184     }
185     else {
186         esp_event_handler_node_t *it = NULL, *last = NULL;
187 
188         SLIST_FOREACH(it, handlers, next) {
189             if (legacy) {
190                 if(event_handler == it->handler_ctx->handler) {
191                     it->handler_ctx->arg = event_handler_arg;
192                     ESP_LOGW(TAG, "handler already registered, overwriting");
193                     free(handler_instance);
194                     free(context);
195                     return ESP_OK;
196                 }
197             }
198             last = it;
199         }
200 
201         SLIST_INSERT_AFTER(last, handler_instance, next);
202     }
203 
204     // If the caller didn't provide the handler instance context, don't set it.
205     // It will be removed once the event loop is deleted.
206     if (handler_ctx) {
207         *handler_ctx = context;
208     }
209 
210     return ESP_OK;
211 }
212 
base_node_add_handler(esp_event_base_node_t * base_node,int32_t id,esp_event_handler_t event_handler,void * event_handler_arg,esp_event_handler_instance_context_t ** handler_ctx,bool legacy)213 static esp_err_t base_node_add_handler(esp_event_base_node_t* base_node,
214         int32_t id,
215         esp_event_handler_t event_handler,
216         void *event_handler_arg,
217         esp_event_handler_instance_context_t **handler_ctx,
218         bool legacy)
219 {
220     if (id == ESP_EVENT_ANY_ID) {
221         return handler_instances_add(&(base_node->handlers), event_handler, event_handler_arg, handler_ctx, legacy);
222     }
223     else {
224         esp_err_t err = ESP_OK;
225         esp_event_id_node_t *it = NULL, *id_node = NULL, *last_id_node = NULL;
226 
227         SLIST_FOREACH(it, &(base_node->id_nodes), next) {
228             if (it->id == id) {
229                 id_node = it;
230             }
231             last_id_node = it;
232         }
233 
234         if (!last_id_node || !id_node) {
235             id_node = (esp_event_id_node_t*) calloc(1, sizeof(*id_node));
236 
237             if (!id_node) {
238                 ESP_LOGE(TAG, "alloc for new id node failed");
239                 return ESP_ERR_NO_MEM;
240             }
241 
242             id_node->id = id;
243 
244             SLIST_INIT(&(id_node->handlers));
245 
246             err = handler_instances_add(&(id_node->handlers), event_handler, event_handler_arg, handler_ctx, legacy);
247 
248             if (err == ESP_OK) {
249                 if (!last_id_node) {
250                     SLIST_INSERT_HEAD(&(base_node->id_nodes), id_node, next);
251                 }
252                 else {
253                     SLIST_INSERT_AFTER(last_id_node, id_node, next);
254                 }
255             } else {
256                 free(id_node);
257             }
258 
259             return err;
260         }
261         else {
262             return handler_instances_add(&(id_node->handlers), event_handler, event_handler_arg, handler_ctx, legacy);
263         }
264     }
265 }
266 
loop_node_add_handler(esp_event_loop_node_t * loop_node,esp_event_base_t base,int32_t id,esp_event_handler_t event_handler,void * event_handler_arg,esp_event_handler_instance_context_t ** handler_ctx,bool legacy)267 static esp_err_t loop_node_add_handler(esp_event_loop_node_t* loop_node,
268         esp_event_base_t base,
269         int32_t id,
270         esp_event_handler_t event_handler,
271         void *event_handler_arg,
272         esp_event_handler_instance_context_t **handler_ctx,
273         bool legacy)
274 {
275     if (base == esp_event_any_base && id == ESP_EVENT_ANY_ID) {
276         return handler_instances_add(&(loop_node->handlers), event_handler, event_handler_arg, handler_ctx, legacy);
277     }
278     else {
279         esp_err_t err = ESP_OK;
280         esp_event_base_node_t *it = NULL, *base_node = NULL, *last_base_node = NULL;
281 
282         SLIST_FOREACH(it, &(loop_node->base_nodes), next) {
283             if (it->base == base) {
284                 base_node = it;
285             }
286             last_base_node = it;
287         }
288 
289         if (!last_base_node ||
290         	!base_node ||
291             (base_node && !SLIST_EMPTY(&(base_node->id_nodes)) && id == ESP_EVENT_ANY_ID) ||
292             (last_base_node && last_base_node->base != base && !SLIST_EMPTY(&(last_base_node->id_nodes)) && id == ESP_EVENT_ANY_ID)) {
293             base_node = (esp_event_base_node_t*) calloc(1, sizeof(*base_node));
294 
295             if (!base_node) {
296                 ESP_LOGE(TAG, "alloc mem for new base node failed");
297                 return ESP_ERR_NO_MEM;
298             }
299 
300             base_node->base = base;
301 
302             SLIST_INIT(&(base_node->handlers));
303             SLIST_INIT(&(base_node->id_nodes));
304 
305             err = base_node_add_handler(base_node, id, event_handler, event_handler_arg, handler_ctx, legacy);
306 
307             if (err == ESP_OK) {
308                 if (!last_base_node) {
309                     SLIST_INSERT_HEAD(&(loop_node->base_nodes), base_node, next);
310                 }
311                 else {
312                     SLIST_INSERT_AFTER(last_base_node, base_node, next);
313                 }
314             } else {
315                 free(base_node);
316             }
317 
318             return err;
319         } else {
320             return base_node_add_handler(base_node, id, event_handler, event_handler_arg, handler_ctx, legacy);
321         }
322     }
323 }
324 
handler_instances_remove(esp_event_handler_nodes_t * handlers,esp_event_handler_instance_context_t * handler_ctx,bool legacy)325 static esp_err_t handler_instances_remove(esp_event_handler_nodes_t* handlers, esp_event_handler_instance_context_t* handler_ctx, bool legacy)
326 {
327     esp_event_handler_node_t *it, *temp;
328 
329     SLIST_FOREACH_SAFE(it, handlers, next, temp) {
330         if (legacy) {
331             if (it->handler_ctx->handler == handler_ctx->handler) {
332                 SLIST_REMOVE(handlers, it, esp_event_handler_node, next);
333                 free(it->handler_ctx);
334                 free(it);
335                 return ESP_OK;
336             }
337         } else {
338             if (it->handler_ctx == handler_ctx) {
339                 SLIST_REMOVE(handlers, it, esp_event_handler_node, next);
340                 free(it->handler_ctx);
341                 free(it);
342                 return ESP_OK;
343             }
344         }
345     }
346 
347     return ESP_ERR_NOT_FOUND;
348 }
349 
350 
base_node_remove_handler(esp_event_base_node_t * base_node,int32_t id,esp_event_handler_instance_context_t * handler_ctx,bool legacy)351 static esp_err_t base_node_remove_handler(esp_event_base_node_t* base_node, int32_t id, esp_event_handler_instance_context_t* handler_ctx, bool legacy)
352 {
353     if (id == ESP_EVENT_ANY_ID) {
354         return handler_instances_remove(&(base_node->handlers), handler_ctx, legacy);
355     }
356     else {
357         esp_event_id_node_t *it, *temp;
358         SLIST_FOREACH_SAFE(it, &(base_node->id_nodes), next, temp) {
359             if (it->id == id) {
360                 esp_err_t res = handler_instances_remove(&(it->handlers), handler_ctx, legacy);
361 
362                 if (res == ESP_OK) {
363                     if (SLIST_EMPTY(&(it->handlers))) {
364                         SLIST_REMOVE(&(base_node->id_nodes), it, esp_event_id_node, next);
365                         free(it);
366                         return ESP_OK;
367                     }
368                 }
369             }
370         }
371     }
372 
373     return ESP_ERR_NOT_FOUND;
374 }
375 
loop_node_remove_handler(esp_event_loop_node_t * loop_node,esp_event_base_t base,int32_t id,esp_event_handler_instance_context_t * handler_ctx,bool legacy)376 static esp_err_t loop_node_remove_handler(esp_event_loop_node_t* loop_node, esp_event_base_t base, int32_t id, esp_event_handler_instance_context_t* handler_ctx, bool legacy)
377 {
378     if (base == esp_event_any_base && id == ESP_EVENT_ANY_ID) {
379         return handler_instances_remove(&(loop_node->handlers), handler_ctx, legacy);
380     }
381     else {
382         esp_event_base_node_t *it, *temp;
383         SLIST_FOREACH_SAFE(it, &(loop_node->base_nodes), next, temp) {
384             if (it->base == base) {
385                 esp_err_t res = base_node_remove_handler(it, id, handler_ctx, legacy);
386 
387                 if (res == ESP_OK) {
388                     if (SLIST_EMPTY(&(it->handlers)) && SLIST_EMPTY(&(it->id_nodes))) {
389                         SLIST_REMOVE(&(loop_node->base_nodes), it, esp_event_base_node, next);
390                         free(it);
391                         return ESP_OK;
392                     }
393                 }
394             }
395         }
396     }
397 
398     return ESP_ERR_NOT_FOUND;
399 }
400 
handler_instances_remove_all(esp_event_handler_nodes_t * handlers)401 static void handler_instances_remove_all(esp_event_handler_nodes_t* handlers)
402 {
403     esp_event_handler_node_t *it, *temp;
404     SLIST_FOREACH_SAFE(it, handlers, next, temp) {
405         SLIST_REMOVE(handlers, it, esp_event_handler_node, next);
406         free(it->handler_ctx);
407         free(it);
408     }
409 }
410 
base_node_remove_all_handler(esp_event_base_node_t * base_node)411 static void base_node_remove_all_handler(esp_event_base_node_t* base_node)
412 {
413     handler_instances_remove_all(&(base_node->handlers));
414 
415     esp_event_id_node_t *it, *temp;
416     SLIST_FOREACH_SAFE(it, &(base_node->id_nodes), next, temp) {
417         handler_instances_remove_all(&(it->handlers));
418         SLIST_REMOVE(&(base_node->id_nodes), it, esp_event_id_node, next);
419         free(it);
420     }
421 }
422 
loop_node_remove_all_handler(esp_event_loop_node_t * loop_node)423 static void loop_node_remove_all_handler(esp_event_loop_node_t* loop_node)
424 {
425     handler_instances_remove_all(&(loop_node->handlers));
426 
427     esp_event_base_node_t *it, *temp;
428     SLIST_FOREACH_SAFE(it, &(loop_node->base_nodes), next, temp) {
429         base_node_remove_all_handler(it);
430         SLIST_REMOVE(&(loop_node->base_nodes), it, esp_event_base_node, next);
431         free(it);
432     }
433 }
434 
post_instance_delete(esp_event_post_instance_t * post)435 static void inline __attribute__((always_inline)) post_instance_delete(esp_event_post_instance_t* post)
436 {
437 #if CONFIG_ESP_EVENT_POST_FROM_ISR
438     if (post->data_allocated && post->data.ptr) {
439         free(post->data.ptr);
440     }
441 #else
442     if (post->data) {
443         free(post->data);
444     }
445 #endif
446     memset(post, 0, sizeof(*post));
447 }
448 
449 /* ---------------------------- Public API --------------------------------- */
450 
esp_event_loop_create(const esp_event_loop_args_t * event_loop_args,esp_event_loop_handle_t * event_loop)451 esp_err_t esp_event_loop_create(const esp_event_loop_args_t* event_loop_args, esp_event_loop_handle_t* event_loop)
452 {
453     if (event_loop_args == NULL) {
454         ESP_LOGE(TAG, "event_loop_args was NULL");
455         return ESP_ERR_INVALID_ARG;
456     }
457 
458     if (event_loop == NULL) {
459         ESP_LOGE(TAG, "event_loop was NULL");
460         return ESP_ERR_INVALID_ARG;
461     }
462 
463     esp_event_loop_instance_t* loop;
464     esp_err_t err = ESP_ERR_NO_MEM; // most likely error
465 
466     loop = calloc(1, sizeof(*loop));
467     if (loop == NULL) {
468         ESP_LOGE(TAG, "alloc for event loop failed");
469         return err;
470     }
471 
472     loop->queue = xQueueCreate(event_loop_args->queue_size , sizeof(esp_event_post_instance_t));
473     if (loop->queue == NULL) {
474         ESP_LOGE(TAG, "create event loop queue failed");
475         goto on_err;
476     }
477 
478     loop->mutex = xSemaphoreCreateRecursiveMutex();
479     if (loop->mutex == NULL) {
480         ESP_LOGE(TAG, "create event loop mutex failed");
481         goto on_err;
482     }
483 
484 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
485     loop->profiling_mutex = xSemaphoreCreateMutex();
486     if (loop->profiling_mutex == NULL) {
487         ESP_LOGE(TAG, "create event loop profiling mutex failed");
488         goto on_err;
489     }
490 #endif
491 
492     SLIST_INIT(&(loop->loop_nodes));
493 
494     // Create the loop task if requested
495     if (event_loop_args->task_name != NULL) {
496         BaseType_t task_created = xTaskCreatePinnedToCore(esp_event_loop_run_task, event_loop_args->task_name,
497                     event_loop_args->task_stack_size, (void*) loop,
498                     event_loop_args->task_priority, &(loop->task), event_loop_args->task_core_id);
499 
500         if (task_created != pdPASS) {
501             ESP_LOGE(TAG, "create task for loop failed");
502             err = ESP_FAIL;
503             goto on_err;
504         }
505 
506         loop->name = event_loop_args->task_name;
507 
508         ESP_LOGD(TAG, "created task for loop %p", loop);
509     } else {
510         loop->name = "";
511         loop->task = NULL;
512     }
513 
514     loop->running_task = NULL;
515 
516 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
517     portENTER_CRITICAL(&s_event_loops_spinlock);
518     SLIST_INSERT_HEAD(&s_event_loops, loop, next);
519     portEXIT_CRITICAL(&s_event_loops_spinlock);
520 #endif
521 
522     *event_loop = (esp_event_loop_handle_t) loop;
523 
524     ESP_LOGD(TAG, "created event loop %p", loop);
525 
526     return ESP_OK;
527 
528 on_err:
529     if (loop->queue != NULL) {
530         vQueueDelete(loop->queue);
531     }
532 
533     if (loop->mutex != NULL) {
534         vSemaphoreDelete(loop->mutex);
535     }
536 
537 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
538     if (loop->profiling_mutex != NULL) {
539         vSemaphoreDelete(loop->profiling_mutex);
540     }
541 #endif
542 
543     free(loop);
544 
545     return err;
546 }
547 
548 // On event lookup performance: The library implements the event list as a linked list, which results to O(n)
549 // lookup time. The test comparing this implementation to the O(lg n) performance of rbtrees
550 // (https://github.com/freebsd/freebsd/blob/master/sys/sys/tree.h)
551 // indicate that the difference is not that substantial, especially considering the additional
552 // pointers per node of rbtrees. Code for the rbtree implementation of the event loop library is archived
553 // in feature/esp_event_loop_library_rbtrees if needed.
esp_event_loop_run(esp_event_loop_handle_t event_loop,TickType_t ticks_to_run)554 esp_err_t esp_event_loop_run(esp_event_loop_handle_t event_loop, TickType_t ticks_to_run)
555 {
556     assert(event_loop);
557 
558     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
559     esp_event_post_instance_t post;
560     TickType_t marker = xTaskGetTickCount();
561     TickType_t end = 0;
562 
563 #if (configUSE_16_BIT_TICKS == 1)
564     int32_t remaining_ticks = ticks_to_run;
565 #else
566     int64_t remaining_ticks = ticks_to_run;
567 #endif
568 
569     while(xQueueReceive(loop->queue, &post, ticks_to_run) == pdTRUE) {
570         // The event has already been unqueued, so ensure it gets executed.
571         xSemaphoreTakeRecursive(loop->mutex, portMAX_DELAY);
572 
573         loop->running_task = xTaskGetCurrentTaskHandle();
574 
575         bool exec = false;
576 
577         esp_event_handler_node_t *handler, *temp_handler;
578         esp_event_loop_node_t *loop_node, *temp_node;
579         esp_event_base_node_t *base_node, *temp_base;
580         esp_event_id_node_t *id_node, *temp_id_node;
581 
582         SLIST_FOREACH_SAFE(loop_node, &(loop->loop_nodes), next, temp_node) {
583             // Execute loop level handlers
584             SLIST_FOREACH_SAFE(handler, &(loop_node->handlers), next, temp_handler) {
585                 handler_execute(loop, handler, post);
586                 exec |= true;
587             }
588 
589             SLIST_FOREACH_SAFE(base_node, &(loop_node->base_nodes), next, temp_base) {
590                 if (base_node->base == post.base) {
591                     // Execute base level handlers
592                     SLIST_FOREACH_SAFE(handler, &(base_node->handlers), next, temp_handler) {
593                         handler_execute(loop, handler, post);
594                         exec |= true;
595                     }
596 
597                     SLIST_FOREACH_SAFE(id_node, &(base_node->id_nodes), next, temp_id_node) {
598                         if (id_node->id == post.id) {
599                             // Execute id level handlers
600                             SLIST_FOREACH_SAFE(handler, &(id_node->handlers), next, temp_handler) {
601                                 handler_execute(loop, handler, post);
602                                 exec |= true;
603                             }
604                             // Skip to next base node
605                             break;
606                         }
607                     }
608                 }
609             }
610         }
611 
612         esp_event_base_t base = post.base;
613         int32_t id = post.id;
614 
615         post_instance_delete(&post);
616 
617         if (ticks_to_run != portMAX_DELAY) {
618             end = xTaskGetTickCount();
619             remaining_ticks -= end - marker;
620             // If the ticks to run expired, return to the caller
621             if (remaining_ticks <= 0) {
622                 xSemaphoreGiveRecursive(loop->mutex);
623                 break;
624             } else {
625                 marker = end;
626             }
627         }
628 
629         loop->running_task = NULL;
630 
631         xSemaphoreGiveRecursive(loop->mutex);
632 
633         if (!exec) {
634             // No handlers were registered, not even loop/base level handlers
635             ESP_LOGD(TAG, "no handlers have been registered for event %s:%"PRIu32" posted to loop %p", base, id, event_loop);
636         }
637     }
638 
639     return ESP_OK;
640 }
641 
esp_event_loop_delete(esp_event_loop_handle_t event_loop)642 esp_err_t esp_event_loop_delete(esp_event_loop_handle_t event_loop)
643 {
644     assert(event_loop);
645     ESP_LOGD(TAG, "deleting loop %p", (void*) event_loop);
646 
647     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
648     SemaphoreHandle_t loop_mutex = loop->mutex;
649 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
650     SemaphoreHandle_t loop_profiling_mutex = loop->profiling_mutex;
651 #endif
652 
653     xSemaphoreTakeRecursive(loop->mutex, portMAX_DELAY);
654 
655 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
656     xSemaphoreTake(loop->profiling_mutex, portMAX_DELAY);
657     portENTER_CRITICAL(&s_event_loops_spinlock);
658     SLIST_REMOVE(&s_event_loops, loop, esp_event_loop_instance, next);
659     portEXIT_CRITICAL(&s_event_loops_spinlock);
660 #endif
661 
662     // Delete the task if it was created
663     if (loop->task != NULL) {
664         vTaskDelete(loop->task);
665     }
666 
667     // Remove all registered events and handlers in the loop
668     esp_event_loop_node_t *it, *temp;
669     SLIST_FOREACH_SAFE(it, &(loop->loop_nodes), next, temp) {
670         loop_node_remove_all_handler(it);
671         SLIST_REMOVE(&(loop->loop_nodes), it, esp_event_loop_node, next);
672         free(it);
673     }
674 
675     // Drop existing posts on the queue
676     esp_event_post_instance_t post;
677     while(xQueueReceive(loop->queue, &post, 0) == pdTRUE) {
678         post_instance_delete(&post);
679     }
680 
681     // Cleanup loop
682     vQueueDelete(loop->queue);
683     free(loop);
684     // Free loop mutex before deleting
685     xSemaphoreGiveRecursive(loop_mutex);
686 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
687     xSemaphoreGive(loop_profiling_mutex);
688     vSemaphoreDelete(loop_profiling_mutex);
689 #endif
690     vSemaphoreDelete(loop_mutex);
691 
692     return ESP_OK;
693 }
694 
esp_event_handler_register_with_internal(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_t event_handler,void * event_handler_arg,esp_event_handler_instance_context_t ** handler_ctx_arg,bool legacy)695 esp_err_t esp_event_handler_register_with_internal(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
696                                           int32_t event_id, esp_event_handler_t event_handler, void* event_handler_arg,
697                                           esp_event_handler_instance_context_t** handler_ctx_arg, bool legacy)
698 {
699     assert(event_loop);
700     assert(event_handler);
701 
702     if (event_base == ESP_EVENT_ANY_BASE && event_id != ESP_EVENT_ANY_ID) {
703         ESP_LOGE(TAG, "registering to any event base with specific id unsupported");
704         return ESP_ERR_INVALID_ARG;
705     }
706 
707     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
708 
709     if (event_base == ESP_EVENT_ANY_BASE) {
710         event_base = esp_event_any_base;
711     }
712 
713     esp_err_t err = ESP_OK;
714 
715     xSemaphoreTakeRecursive(loop->mutex, portMAX_DELAY);
716 
717     esp_event_loop_node_t *loop_node = NULL, *last_loop_node = NULL;
718 
719     SLIST_FOREACH(loop_node, &(loop->loop_nodes), next) {
720         last_loop_node = loop_node;
721     }
722 
723     bool is_loop_level_handler = (event_base == esp_event_any_base) && (event_id == ESP_EVENT_ANY_ID);
724 
725     if (!last_loop_node ||
726        (last_loop_node && !SLIST_EMPTY(&(last_loop_node->base_nodes)) && is_loop_level_handler)) {
727         loop_node = (esp_event_loop_node_t*) calloc(1, sizeof(*loop_node));
728 
729         if (!loop_node) {
730             ESP_LOGE(TAG, "alloc for new loop node failed");
731             err = ESP_ERR_NO_MEM;
732             goto on_err;
733         }
734 
735         SLIST_INIT(&(loop_node->handlers));
736         SLIST_INIT(&(loop_node->base_nodes));
737 
738         err = loop_node_add_handler(loop_node, event_base, event_id, event_handler, event_handler_arg, handler_ctx_arg, legacy);
739 
740         if (err == ESP_OK) {
741             if (!last_loop_node) {
742                 SLIST_INSERT_HEAD(&(loop->loop_nodes), loop_node, next);
743             }
744             else {
745                 SLIST_INSERT_AFTER(last_loop_node, loop_node, next);
746             }
747         } else {
748             free(loop_node);
749         }
750     }
751     else {
752         err = loop_node_add_handler(last_loop_node, event_base, event_id, event_handler, event_handler_arg, handler_ctx_arg, legacy);
753     }
754 
755 on_err:
756     xSemaphoreGiveRecursive(loop->mutex);
757     return err;
758 }
759 
esp_event_handler_register_with(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_t event_handler,void * event_handler_arg)760 esp_err_t esp_event_handler_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
761                                         int32_t event_id, esp_event_handler_t event_handler, void* event_handler_arg)
762 {
763     return esp_event_handler_register_with_internal(event_loop, event_base, event_id, event_handler, event_handler_arg, NULL, true);
764 }
765 
esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_t event_handler,void * event_handler_arg,esp_event_handler_instance_t * handler_ctx_arg)766 esp_err_t esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
767                                           int32_t event_id, esp_event_handler_t event_handler, void* event_handler_arg,
768                                           esp_event_handler_instance_t* handler_ctx_arg)
769 {
770     return esp_event_handler_register_with_internal(event_loop, event_base, event_id, event_handler, event_handler_arg, (esp_event_handler_instance_context_t**) handler_ctx_arg, false);
771 }
772 
esp_event_handler_unregister_with_internal(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_instance_context_t * handler_ctx,bool legacy)773 esp_err_t esp_event_handler_unregister_with_internal(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
774                                             int32_t event_id, esp_event_handler_instance_context_t* handler_ctx, bool legacy)
775 {
776     assert(event_loop);
777     assert(handler_ctx);
778 
779     if (event_base == ESP_EVENT_ANY_BASE && event_id != ESP_EVENT_ANY_ID) {
780         ESP_LOGE(TAG, "unregistering to any event base with specific id unsupported");
781         return ESP_FAIL;
782     }
783 
784     if (event_base == ESP_EVENT_ANY_BASE) {
785         event_base = esp_event_any_base;
786     }
787 
788     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
789 
790     xSemaphoreTakeRecursive(loop->mutex, portMAX_DELAY);
791 
792     esp_event_loop_node_t *it, *temp;
793 
794     SLIST_FOREACH_SAFE(it, &(loop->loop_nodes), next, temp) {
795         esp_err_t res = loop_node_remove_handler(it, event_base, event_id, handler_ctx, legacy);
796 
797         if (res == ESP_OK && SLIST_EMPTY(&(it->base_nodes)) && SLIST_EMPTY(&(it->handlers))) {
798             SLIST_REMOVE(&(loop->loop_nodes), it, esp_event_loop_node, next);
799             free(it);
800             break;
801         }
802     }
803 
804     xSemaphoreGiveRecursive(loop->mutex);
805 
806     return ESP_OK;
807 }
808 
esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_t event_handler)809 esp_err_t esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
810                                             int32_t event_id, esp_event_handler_t event_handler)
811 {
812     esp_event_handler_instance_context_t local_handler_ctx;
813     local_handler_ctx.handler = event_handler;
814     local_handler_ctx.arg = NULL;
815 
816     return esp_event_handler_unregister_with_internal(event_loop, event_base, event_id, &local_handler_ctx, true);
817 }
818 
esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,esp_event_handler_instance_t handler_ctx_arg)819 esp_err_t esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop, esp_event_base_t event_base,
820                                             int32_t event_id, esp_event_handler_instance_t handler_ctx_arg)
821 {
822     if (!handler_ctx_arg) return ESP_ERR_INVALID_ARG;
823 
824     return esp_event_handler_unregister_with_internal(event_loop, event_base, event_id, (esp_event_handler_instance_context_t*) handler_ctx_arg, false);
825 }
826 
esp_event_post_to(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,const void * event_data,size_t event_data_size,TickType_t ticks_to_wait)827 esp_err_t esp_event_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id,
828                             const void* event_data, size_t event_data_size, TickType_t ticks_to_wait)
829 {
830     assert(event_loop);
831 
832     if (event_base == ESP_EVENT_ANY_BASE || event_id == ESP_EVENT_ANY_ID) {
833         return ESP_ERR_INVALID_ARG;
834     }
835 
836     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
837 
838     esp_event_post_instance_t post;
839     memset((void*)(&post), 0, sizeof(post));
840 
841     if (event_data != NULL && event_data_size != 0) {
842         // Make persistent copy of event data on heap.
843         void* event_data_copy = calloc(1, event_data_size);
844 
845         if (event_data_copy == NULL) {
846             return ESP_ERR_NO_MEM;
847         }
848 
849         memcpy(event_data_copy, event_data, event_data_size);
850 #if CONFIG_ESP_EVENT_POST_FROM_ISR
851         post.data.ptr = event_data_copy;
852         post.data_allocated = true;
853         post.data_set = true;
854 #else
855         post.data = event_data_copy;
856 #endif
857     }
858     post.base = event_base;
859     post.id = event_id;
860 
861     BaseType_t result = pdFALSE;
862 
863     // Find the task that currently executes the loop. It is safe to query loop->task since it is
864     // not mutated since loop creation. ENSURE THIS REMAINS TRUE.
865     if (loop->task == NULL) {
866         // The loop has no dedicated task. Find out what task is currently running it.
867         result = xSemaphoreTakeRecursive(loop->mutex, ticks_to_wait);
868 
869         if (result == pdTRUE) {
870             if (loop->running_task != xTaskGetCurrentTaskHandle()) {
871                 xSemaphoreGiveRecursive(loop->mutex);
872                 result = xQueueSendToBack(loop->queue, &post, ticks_to_wait);
873             } else {
874                 xSemaphoreGiveRecursive(loop->mutex);
875                 result = xQueueSendToBack(loop->queue, &post, 0);
876             }
877         }
878     } else {
879         // The loop has a dedicated task.
880         if (loop->task != xTaskGetCurrentTaskHandle()) {
881             result = xQueueSendToBack(loop->queue, &post, ticks_to_wait);
882         } else {
883             result = xQueueSendToBack(loop->queue, &post, 0);
884         }
885     }
886 
887     if (result != pdTRUE) {
888         post_instance_delete(&post);
889 
890 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
891         atomic_fetch_add(&loop->events_dropped, 1);
892 #endif
893         return ESP_ERR_TIMEOUT;
894     }
895 
896 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
897     atomic_fetch_add(&loop->events_recieved, 1);
898 #endif
899 
900     return ESP_OK;
901 }
902 
903 #if CONFIG_ESP_EVENT_POST_FROM_ISR
esp_event_isr_post_to(esp_event_loop_handle_t event_loop,esp_event_base_t event_base,int32_t event_id,const void * event_data,size_t event_data_size,BaseType_t * task_unblocked)904 esp_err_t esp_event_isr_post_to(esp_event_loop_handle_t event_loop, esp_event_base_t event_base, int32_t event_id,
905                             const void* event_data, size_t event_data_size, BaseType_t* task_unblocked)
906 {
907     assert(event_loop);
908 
909     if (event_base == ESP_EVENT_ANY_BASE || event_id == ESP_EVENT_ANY_ID) {
910         return ESP_ERR_INVALID_ARG;
911     }
912 
913     esp_event_loop_instance_t* loop = (esp_event_loop_instance_t*) event_loop;
914 
915     esp_event_post_instance_t post;
916     memset((void*)(&post), 0, sizeof(post));
917 
918     if (event_data_size > sizeof(post.data.val)) {
919         return ESP_ERR_INVALID_ARG;
920     }
921 
922     if (event_data != NULL && event_data_size != 0) {
923         memcpy((void*)(&(post.data.val)), event_data, event_data_size);
924         post.data_allocated = false;
925         post.data_set = true;
926     }
927     post.base = event_base;
928     post.id = event_id;
929 
930     BaseType_t result = pdFALSE;
931 
932     // Post the event from an ISR,
933     result = xQueueSendToBackFromISR(loop->queue, &post, task_unblocked);
934 
935     if (result != pdTRUE) {
936         post_instance_delete(&post);
937 
938 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
939         atomic_fetch_add(&loop->events_dropped, 1);
940 #endif
941         return ESP_FAIL;
942     }
943 
944 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
945     atomic_fetch_add(&loop->events_recieved, 1);
946 #endif
947 
948     return ESP_OK;
949 }
950 #endif
951 
esp_event_dump(FILE * file)952 esp_err_t esp_event_dump(FILE* file)
953 {
954 #ifdef CONFIG_ESP_EVENT_LOOP_PROFILING
955     assert(file);
956 
957     esp_event_loop_instance_t* loop_it;
958     esp_event_loop_node_t *loop_node_it;
959     esp_event_base_node_t* base_node_it;
960     esp_event_id_node_t* id_node_it;
961     esp_event_handler_node_t* handler_it;
962 
963     // Allocate memory for printing
964     int sz = esp_event_dump_prepare();
965     char* buf = calloc(sz, sizeof(char));
966     char* dst = buf;
967 
968     char id_str_buf[20];
969 
970     // Print info to buffer
971     portENTER_CRITICAL(&s_event_loops_spinlock);
972 
973     SLIST_FOREACH(loop_it, &s_event_loops, next) {
974         uint32_t events_recieved, events_dropped;
975 
976         events_recieved = atomic_load(&loop_it->events_recieved);
977         events_dropped = atomic_load(&loop_it->events_dropped);
978 
979         PRINT_DUMP_INFO(dst, sz, LOOP_DUMP_FORMAT, loop_it, loop_it->task != NULL ? loop_it->name : "none" ,
980                         events_recieved, events_dropped);
981 
982         int sz_bak = sz;
983 
984         SLIST_FOREACH(loop_node_it, &(loop_it->loop_nodes), next) {
985             SLIST_FOREACH(handler_it, &(loop_node_it->handlers), next) {
986                 PRINT_DUMP_INFO(dst, sz, HANDLER_DUMP_FORMAT, handler_it->handler_ctx->handler, "ESP_EVENT_ANY_BASE",
987                                 "ESP_EVENT_ANY_ID", handler_it->invoked, handler_it->time);
988             }
989 
990             SLIST_FOREACH(base_node_it, &(loop_node_it->base_nodes), next) {
991                 SLIST_FOREACH(handler_it, &(base_node_it->handlers), next) {
992                     PRINT_DUMP_INFO(dst, sz, HANDLER_DUMP_FORMAT, handler_it->handler_ctx->handler, base_node_it->base ,
993                                     "ESP_EVENT_ANY_ID", handler_it->invoked, handler_it->time);
994                 }
995 
996                 SLIST_FOREACH(id_node_it, &(base_node_it->id_nodes), next) {
997                     SLIST_FOREACH(handler_it, &(id_node_it->handlers), next) {
998                         memset(id_str_buf, 0, sizeof(id_str_buf));
999                         snprintf(id_str_buf, sizeof(id_str_buf), "%" PRIi32, id_node_it->id);
1000 
1001                         PRINT_DUMP_INFO(dst, sz, HANDLER_DUMP_FORMAT, handler_it->handler_ctx->handler, base_node_it->base ,
1002                                         id_str_buf, handler_it->invoked, handler_it->time);
1003                     }
1004                 }
1005             }
1006         }
1007 
1008         // No handlers registered for this loop
1009         if (sz == sz_bak) {
1010             PRINT_DUMP_INFO(dst, sz, "  NO HANDLERS REGISTERED\n");
1011         }
1012     }
1013 
1014     portEXIT_CRITICAL(&s_event_loops_spinlock);
1015 
1016     // Print the contents of the buffer to the file
1017     fprintf(file, buf);
1018 
1019     // Free the allocated buffer
1020     free(buf);
1021 #endif
1022     return ESP_OK;
1023 }
1024