1 // Copyright 2020 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //         http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifdef __cpp_exceptions
16 
17 #include <functional>
18 #include "esp_timer_cxx.hpp"
19 #include "esp_exception.hpp"
20 
21 using namespace std;
22 
23 namespace idf {
24 
25 namespace esp_timer {
26 
ESPTimer(function<void ()> timeout_cb,const string & timer_name)27 ESPTimer::ESPTimer(function<void()> timeout_cb, const string &timer_name)
28     : timeout_cb(timeout_cb), name(timer_name)
29 {
30     if (timeout_cb == nullptr) {
31         throw ESPException(ESP_ERR_INVALID_ARG);
32     }
33 
34     esp_timer_create_args_t timer_args = {};
35     timer_args.callback = esp_timer_cb;
36     timer_args.arg = this;
37     timer_args.dispatch_method = ESP_TIMER_TASK;
38     timer_args.name = name.c_str();
39 
40     CHECK_THROW(esp_timer_create(&timer_args, &timer_handle));
41 }
42 
~ESPTimer()43 ESPTimer::~ESPTimer()
44 {
45     // Ignore potential ESP_ERR_INVALID_STATE here to not throw exception.
46     esp_timer_stop(timer_handle);
47     esp_timer_delete(timer_handle);
48 }
49 
esp_timer_cb(void * arg)50 void ESPTimer::esp_timer_cb(void *arg)
51 {
52     ESPTimer *timer = static_cast<ESPTimer*>(arg);
53     timer->timeout_cb();
54 }
55 
56 } // esp_timer
57 
58 } // idf
59 
60 #endif // __cpp_exceptions
61