Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / examples / all-clusters-app / esp32 / main / Button.cpp
1 /*
2  *
3  *    Copyright (c) 2020 Project CHIP Authors
4  *    Copyright (c) 2018 Nest Labs, Inc.
5  *    All rights reserved.
6  *
7  *    Licensed under the Apache License, Version 2.0 (the "License");
8  *    you may not use this file except in compliance with the License.
9  *    You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *    Unless required by applicable law or agreed to in writing, software
14  *    distributed under the License is distributed on an "AS IS" BASIS,
15  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *    See the License for the specific language governing permissions and
17  *    limitations under the License.
18  */
19
20 /**
21  * @file Button.cpp
22  *
23  * Implements a Button tied to a GPIO and provides debouncing and polling
24  *
25  **/
26
27 #include "driver/gpio.h"
28 #include "esp_log.h"
29 #include "esp_system.h"
30
31 #include "Button.h"
32 #include <platform/CHIPDeviceLayer.h>
33 #include <support/CodeUtils.h>
34
35 extern const char * TAG;
36
37 esp_err_t Button::Init(gpio_num_t gpioNum, uint16_t debouncePeriod)
38 {
39     esp_err_t err;
40
41     mGPIONum         = gpioNum;
42     mDebouncePeriod  = debouncePeriod / portTICK_PERIOD_MS;
43     mState           = false;
44     mLastPolledState = false;
45
46     err = gpio_set_direction(gpioNum, GPIO_MODE_INPUT);
47     SuccessOrExit(err);
48
49     Poll();
50
51 exit:
52     return err;
53 }
54
55 bool Button::Poll()
56 {
57     uint32_t now = xTaskGetTickCount();
58
59     bool newState = gpio_get_level(mGPIONum) == 0;
60
61     if (newState != mLastPolledState)
62     {
63         mLastPolledState = newState;
64         mLastReadTime    = now;
65     }
66
67     else if (newState != mState && (now - mLastReadTime) >= mDebouncePeriod)
68     {
69         mState          = newState;
70         mPrevStateDur   = now - mStateStartTime;
71         mStateStartTime = now;
72         return true;
73     }
74
75     return false;
76 }
77
78 uint32_t Button::GetStateDuration()
79 {
80     return (xTaskGetTickCount() - mStateStartTime) * portTICK_PERIOD_MS;
81 }