Skip to content

Commit 1539610

Browse files
lcj446068124pull[bot]
authored andcommitted
[ESP32] Refactor ESP32 all-clusters-app example (#15624)
* esp: refactor main.cpp in all-cluster-app * move m5stack code to separate file * esp: refactor button driver in all-cluster-app * change M5Stack button driver from poll to isr * delete unused head file in main.cpp * esp: optimize all-cluster-app user task execution process * use App Task to manage user tasks * update copyright to latest * optimize button debouncing mechanism
1 parent b465405 commit 1539610

15 files changed

+1081
-775
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
/*
2+
*
3+
* Copyright (c) 2022 Project CHIP Authors
4+
* All rights reserved.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
#include "AppTask.h"
20+
#include "Button.h"
21+
#include "DeviceWithDisplay.h"
22+
#include "Globals.h"
23+
#include "LEDWidget.h"
24+
#include "ScreenManager.h"
25+
#include "driver/gpio.h"
26+
#include "esp_log.h"
27+
#include "esp_spi_flash.h"
28+
#include "freertos/FreeRTOS.h"
29+
#include <app/server/OnboardingCodesUtil.h>
30+
31+
#define APP_TASK_NAME "APP"
32+
#define APP_EVENT_QUEUE_SIZE 10
33+
#define APP_TASK_STACK_SIZE (3072)
34+
35+
static const char * TAG = "app-task";
36+
37+
namespace {
38+
39+
QueueHandle_t sAppEventQueue;
40+
TaskHandle_t sAppTaskHandle;
41+
42+
} // namespace
43+
44+
AppTask AppTask::sAppTask;
45+
46+
CHIP_ERROR AppTask::StartAppTask()
47+
{
48+
sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent));
49+
if (sAppEventQueue == NULL)
50+
{
51+
ESP_LOGE(TAG, "Failed to allocate app event queue");
52+
return APP_ERROR_EVENT_QUEUE_FAILED;
53+
}
54+
55+
// Start App task.
56+
BaseType_t xReturned;
57+
xReturned = xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, NULL, 1, &sAppTaskHandle);
58+
return (xReturned == pdPASS) ? CHIP_NO_ERROR : APP_ERROR_CREATE_TASK_FAILED;
59+
}
60+
61+
CHIP_ERROR AppTask::Init()
62+
{
63+
/* Print chip information */
64+
esp_chip_info_t chip_info;
65+
esp_chip_info(&chip_info);
66+
ESP_LOGI(TAG, "This is ESP32 chip with %d CPU cores, WiFi%s%s, ", chip_info.cores,
67+
(chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "", (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");
68+
ESP_LOGI(TAG, "silicon revision %d, ", chip_info.revision);
69+
ESP_LOGI(TAG, "%dMB %s flash\n", spi_flash_get_chip_size() / (1024 * 1024),
70+
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");
71+
72+
CHIP_ERROR err = CHIP_NO_ERROR;
73+
statusLED1.Init(STATUS_LED_GPIO_NUM);
74+
// Our second LED doesn't map to any physical LEDs so far, just to virtual
75+
// "LED"s on devices with screens.
76+
statusLED2.Init(GPIO_NUM_MAX);
77+
bluetoothLED.Init();
78+
wifiLED.Init();
79+
pairingWindowLED.Init();
80+
81+
// Print QR Code URL
82+
PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE));
83+
84+
#if CONFIG_HAVE_DISPLAY
85+
InitDeviceDisplay();
86+
#endif
87+
return err;
88+
}
89+
90+
void AppTask::AppTaskMain(void * pvParameter)
91+
{
92+
AppEvent event;
93+
CHIP_ERROR err = sAppTask.Init();
94+
if (err != CHIP_NO_ERROR)
95+
{
96+
ESP_LOGI(TAG, "AppTask.Init() failed due to %" CHIP_ERROR_FORMAT, err.Format());
97+
return;
98+
}
99+
100+
ESP_LOGI(TAG, "App Task started");
101+
102+
while (true)
103+
{
104+
BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10));
105+
while (eventReceived == pdTRUE)
106+
{
107+
sAppTask.DispatchEvent(&event);
108+
eventReceived = xQueueReceive(sAppEventQueue, &event, 0); // return immediately if the queue is empty
109+
}
110+
}
111+
}
112+
113+
void AppTask::PostEvent(const AppEvent * aEvent)
114+
{
115+
if (sAppEventQueue != NULL)
116+
{
117+
BaseType_t status;
118+
if (xPortInIsrContext())
119+
{
120+
BaseType_t higherPrioTaskWoken = pdFALSE;
121+
status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken);
122+
}
123+
else
124+
{
125+
status = xQueueSend(sAppEventQueue, aEvent, 1);
126+
}
127+
if (!status)
128+
ESP_LOGE(TAG, "Failed to post event to app task event queue");
129+
}
130+
else
131+
{
132+
ESP_LOGE(TAG, "Event Queue is NULL should never happen");
133+
}
134+
}
135+
136+
void AppTask::DispatchEvent(AppEvent * aEvent)
137+
{
138+
if (aEvent->mHandler)
139+
{
140+
aEvent->mHandler(aEvent);
141+
}
142+
else
143+
{
144+
ESP_LOGI(TAG, "Event received with no handler. Dropping event.");
145+
}
146+
}
147+
148+
void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction)
149+
{
150+
AppEvent button_event = {};
151+
button_event.mType = AppEvent::kEventType_Button;
152+
button_event.mButtonEvent.mPinNo = btnIdx;
153+
button_event.mButtonEvent.mAction = btnAction;
154+
155+
if (btnAction == APP_BUTTON_PRESSED)
156+
{
157+
button_event.mHandler = ButtonPressedAction;
158+
sAppTask.PostEvent(&button_event);
159+
}
160+
}
161+
162+
void AppTask::ButtonPressedAction(AppEvent * aEvent)
163+
{
164+
#if CONFIG_DEVICE_TYPE_M5STACK
165+
uint32_t io_num = aEvent->mButtonEvent.mPinNo;
166+
int level = gpio_get_level((gpio_num_t) io_num);
167+
if (level == 0)
168+
{
169+
bool woken = WakeDisplay();
170+
if (woken)
171+
{
172+
return;
173+
}
174+
// Button 1 is connected to the pin 39
175+
// Button 2 is connected to the pin 38
176+
// Button 3 is connected to the pin 37
177+
// So we use 40 - io_num to map the pin number to button number
178+
ScreenManager::ButtonPressed(40 - io_num);
179+
}
180+
#endif
181+
}
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
/*
22
*
3-
* Copyright (c) 2020 Project CHIP Authors
4-
* Copyright (c) 2018 Nest Labs, Inc.
3+
* Copyright (c) 2022 Project CHIP Authors
54
* All rights reserved.
65
*
76
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,59 +19,99 @@
2019
/**
2120
* @file Button.cpp
2221
*
23-
* Implements a Button tied to a GPIO and provides debouncing and polling
22+
* Implements a Button tied to a GPIO and provides debouncing
2423
*
2524
**/
2625

2726
#include "driver/gpio.h"
27+
#include "esp_check.h"
2828
#include "esp_log.h"
2929
#include "esp_system.h"
3030

31+
#include "AppTask.h"
3132
#include "Button.h"
33+
#include "Globals.h"
34+
#include "ScreenManager.h"
3235
#include <lib/support/CodeUtils.h>
3336
#include <platform/CHIPDeviceLayer.h>
37+
#include <vector>
3438

35-
extern const char * TAG;
39+
static const char * TAG = "Button.cpp";
3640

37-
esp_err_t Button::Init(gpio_num_t gpioNum, uint16_t debouncePeriod)
38-
{
39-
mGPIONum = gpioNum;
40-
mDebouncePeriod = debouncePeriod / portTICK_PERIOD_MS;
41-
mState = false;
42-
mLastPolledState = false;
41+
extern Button gButtons[BUTTON_NUMBER];
4342

44-
esp_err_t err = gpio_set_direction(gpioNum, GPIO_MODE_INPUT);
45-
if (err == ESP_OK)
46-
{
47-
Poll();
48-
}
49-
return err;
50-
}
43+
Button::Button() {}
5144

52-
bool Button::Poll()
45+
Button::Button(gpio_num_t gpioNum)
5346
{
54-
uint32_t now = xTaskGetTickCount();
55-
56-
bool newState = gpio_get_level(mGPIONum) == 0;
47+
mGPIONum = gpioNum;
48+
}
5749

58-
if (newState != mLastPolledState)
50+
int32_t Find_Button_Via_Pin(gpio_num_t gpioNum)
51+
{
52+
for (int i = 0; i < BUTTON_NUMBER; i++)
5953
{
60-
mLastPolledState = newState;
61-
mLastReadTime = now;
54+
if (gButtons[i].GetGPIONum() == gpioNum)
55+
{
56+
return i;
57+
}
6258
}
59+
return -1;
60+
}
6361

64-
else if (newState != mState && (now - mLastReadTime) >= mDebouncePeriod)
62+
void IRAM_ATTR button_isr_handler(void * arg)
63+
{
64+
uint32_t gpio_num = (uint32_t) arg;
65+
int32_t idx = Find_Button_Via_Pin((gpio_num_t) gpio_num);
66+
if (idx == -1)
6567
{
66-
mState = newState;
67-
mPrevStateDur = now - mStateStartTime;
68-
mStateStartTime = now;
69-
return true;
68+
return;
7069
}
70+
BaseType_t taskWoken = pdFALSE;
71+
xTimerStartFromISR(gButtons[idx].mbuttonTimer,
72+
&taskWoken); // If the timer had already been started ,restart it will reset its expiry time
73+
}
7174

72-
return false;
75+
esp_err_t Button::Init()
76+
{
77+
return Init(mGPIONum);
7378
}
7479

75-
uint32_t Button::GetStateDuration()
80+
esp_err_t Button::Init(gpio_num_t gpioNum)
81+
{
82+
esp_err_t ret = ESP_OK;
83+
84+
mGPIONum = gpioNum;
85+
// zero-initialize the config structure.
86+
gpio_config_t io_conf = {};
87+
// interrupt of falling edge
88+
io_conf.intr_type = GPIO_INTR_NEGEDGE;
89+
// bit mask of the pins, use GPIO4/5 here
90+
io_conf.pin_bit_mask = 1ULL << gpioNum;
91+
// set as input mode
92+
io_conf.mode = GPIO_MODE_INPUT;
93+
// enable pull-up mode
94+
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
95+
96+
gpio_config(&io_conf);
97+
98+
// hook isr handler for specific gpio pin
99+
ret = gpio_isr_handler_add(gpioNum, button_isr_handler, (void *) gpioNum);
100+
ESP_RETURN_ON_ERROR(ret, TAG, "gpio_isr_handler_add failed: %s", esp_err_to_name(ret));
101+
102+
mbuttonTimer = xTimerCreate("BtnTmr", // Just a text name, not used by the RTOS kernel
103+
pdMS_TO_TICKS(50), // timer period
104+
false, // no timer reload (==one-shot)
105+
(void *) (int) gpioNum, // init timer id = gpioNum index
106+
TimerCallback // timer callback handler (all buttons use
107+
// the same timer cn function)
108+
);
109+
110+
return ESP_OK;
111+
}
112+
void Button::TimerCallback(TimerHandle_t xTimer)
76113
{
77-
return (xTaskGetTickCount() - mStateStartTime) * portTICK_PERIOD_MS;
114+
// Get the button index of the expired timer and call button event Handler.
115+
uint32_t gpio_num = (uint32_t) pvTimerGetTimerID(xTimer);
116+
GetAppTask().ButtonEventHandler(gpio_num, APP_BUTTON_PRESSED);
78117
}

0 commit comments

Comments
 (0)