1 /* ESP Event C++ Example
2 
3    This example code is in the Public Domain (or CC0 licensed, at your option.)
4 
5    Unless required by applicable law or agreed to in writing, this
6    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7    CONDITIONS OF ANY KIND, either express or implied.
8 */
9 #include <iostream>
10 #include <thread>
11 #include "esp_event_cxx.hpp"
12 #include "esp_event.h"
13 #include "esp_err.h"
14 
15 using namespace idf::event;
16 using namespace std;
17 
18 #define EVENT_NUM 10
19 
20 ESP_EVENT_DEFINE_BASE(TEST_EVENT_BASE);
21 static ESPEventID TEST_EVENT_ID_0(0);
22 static ESPEventID TEST_EVENT_ID_1(1);
23 
24 // the events we want to register
25 static ESPEvent TEMPLATE_EVENT_0(TEST_EVENT_BASE, TEST_EVENT_ID_0);
26 static ESPEvent TEMPLATE_EVENT_1(TEST_EVENT_BASE, TEST_EVENT_ID_1);
27 
28 // helper function to post events, simulating an event source
post_events()29 void post_events() {
30     for (int i = 0; i < EVENT_NUM; i++) {
31         ESP_ERROR_CHECK(esp_event_post(TEST_EVENT_BASE,
32                 i % 2 ? TEST_EVENT_ID_1.get_id() : TEST_EVENT_ID_0.get_id(),
33                 nullptr,
34                 0,
35                 portMAX_DELAY));
36         this_thread::sleep_for(chrono::seconds(1));
37     }
38 }
39 
app_main(void)40 extern "C" void app_main(void)
41 {
42     ESPEventHandlerSync event_handler(make_shared<ESPEventLoop>());
43     event_handler.listen_to(TEMPLATE_EVENT_0);
44     event_handler.listen_to(TEMPLATE_EVENT_1);
45     cout << "started event loop" << endl;
46 
47     thread th(post_events);
48 
49     // waiting for two events to be posted via post_events()
50     this_thread::sleep_for(chrono::milliseconds(1100));
51 
52     // reading the two already received events, then running into timeout
53     for (;;) {
54         ESPEventHandlerSync::EventResultTimed result = event_handler.wait_event_for(std::chrono::milliseconds(500));
55 
56         if (result.timeout) { // if timeout, then the default esp event will be sent with invalid base
57             break;
58         } else {
59             cout << "event base " << result.event.base
60                     << ", ID: " << result.event.id
61                     << "; called first round" << endl;
62         }
63     }
64 
65     cout << "received timeout" << endl;
66     this_thread::sleep_for(chrono::milliseconds(2000));
67 
68     // Read the events we missed up until now and then continue reading
69     for (int i = 0; i < EVENT_NUM - 2; i++) {
70         ESPEventHandlerSync::EventResult result = event_handler.wait_event();
71         cout << "event base " << result.event.base
72                 << ", ID: " << result.event.id
73                 << "; called second round" << endl;
74     }
75 
76     th.join();
77 
78     // checking whether events were missed by the ESPEventHandlerSync class
79     cout << "Missed: " << event_handler.get_send_queue_errors() << " events" << endl;
80 }
81