1 // Copyright 2019 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 #include "ccomp_timer.h"
16 
17 #include "ccomp_timer_impl.h"
18 
19 #include "freertos/FreeRTOS.h"
20 #include "freertos/task.h"
21 #include "freertos/semphr.h"
22 
23 #include "esp_log.h"
24 #include "esp_intr_alloc.h"
25 
26 static const char TAG[] = "ccomp_timer";
27 
ccomp_timer_start(void)28 esp_err_t ccomp_timer_start(void)
29 {
30     esp_err_t err = ESP_OK;
31 
32     ccomp_timer_impl_lock();
33     if (ccomp_timer_impl_is_init()) {
34         if (ccomp_timer_impl_is_active()) {
35             err = ESP_ERR_INVALID_STATE;
36         }
37     }
38     else {
39         err = ccomp_timer_impl_init();
40     }
41     ccomp_timer_impl_unlock();
42 
43     if (err != ESP_OK) {
44         goto fail;
45     }
46 
47     err = ccomp_timer_impl_reset();
48 
49     if (err != ESP_OK) {
50         goto fail;
51     }
52 
53     err = ccomp_timer_impl_start();
54 
55     if (err == ESP_OK) {
56         return ESP_OK;
57     }
58 
59 fail:
60     ESP_LOGE(TAG, "Unable to start performance timer");
61     return err;
62 }
63 
ccomp_timer_stop(void)64 int64_t IRAM_ATTR ccomp_timer_stop(void)
65 {
66     esp_err_t err = ESP_OK;
67     ccomp_timer_impl_lock();
68     if (!ccomp_timer_impl_is_active()) {
69         err = ESP_ERR_INVALID_STATE;
70     }
71     ccomp_timer_impl_unlock();
72 
73     if (err != ESP_OK) {
74         goto fail;
75     }
76 
77     err = ccomp_timer_impl_stop();
78     if (err != ESP_OK) {
79         goto fail;
80     }
81 
82     int64_t t = ccomp_timer_get_time();
83 
84     err = ccomp_timer_impl_deinit();
85 
86     if (err == ESP_OK && t != -1) {
87         return t;
88     }
89 
90 fail:
91     ESP_LOGE(TAG, "Unable to stop performance timer");
92     return -1;
93 }
94 
ccomp_timer_get_time(void)95 int64_t IRAM_ATTR ccomp_timer_get_time(void)
96 {
97     return ccomp_timer_impl_get_time();
98 }
99