Skip to content

Commit

Permalink
[ESP32] Refactor ESP32 all-clusters-app example (#15624)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
lcj446068124 authored and pull[bot] committed Jul 13, 2023
1 parent b465405 commit 1539610
Show file tree
Hide file tree
Showing 15 changed files with 1,081 additions and 775 deletions.
181 changes: 181 additions & 0 deletions examples/all-clusters-app/esp32/main/AppTask.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
/*
*
* Copyright (c) 2022 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "AppTask.h"
#include "Button.h"
#include "DeviceWithDisplay.h"
#include "Globals.h"
#include "LEDWidget.h"
#include "ScreenManager.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_spi_flash.h"
#include "freertos/FreeRTOS.h"
#include <app/server/OnboardingCodesUtil.h>

#define APP_TASK_NAME "APP"
#define APP_EVENT_QUEUE_SIZE 10
#define APP_TASK_STACK_SIZE (3072)

static const char * TAG = "app-task";

namespace {

QueueHandle_t sAppEventQueue;
TaskHandle_t sAppTaskHandle;

} // namespace

AppTask AppTask::sAppTask;

CHIP_ERROR AppTask::StartAppTask()
{
sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent));
if (sAppEventQueue == NULL)
{
ESP_LOGE(TAG, "Failed to allocate app event queue");
return APP_ERROR_EVENT_QUEUE_FAILED;
}

// Start App task.
BaseType_t xReturned;
xReturned = xTaskCreate(AppTaskMain, APP_TASK_NAME, APP_TASK_STACK_SIZE, NULL, 1, &sAppTaskHandle);
return (xReturned == pdPASS) ? CHIP_NO_ERROR : APP_ERROR_CREATE_TASK_FAILED;
}

CHIP_ERROR AppTask::Init()
{
/* Print chip information */
esp_chip_info_t chip_info;
esp_chip_info(&chip_info);
ESP_LOGI(TAG, "This is ESP32 chip with %d CPU cores, WiFi%s%s, ", chip_info.cores,
(chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "", (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");
ESP_LOGI(TAG, "silicon revision %d, ", chip_info.revision);
ESP_LOGI(TAG, "%dMB %s flash\n", spi_flash_get_chip_size() / (1024 * 1024),
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");

CHIP_ERROR err = CHIP_NO_ERROR;
statusLED1.Init(STATUS_LED_GPIO_NUM);
// Our second LED doesn't map to any physical LEDs so far, just to virtual
// "LED"s on devices with screens.
statusLED2.Init(GPIO_NUM_MAX);
bluetoothLED.Init();
wifiLED.Init();
pairingWindowLED.Init();

// Print QR Code URL
PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE));

#if CONFIG_HAVE_DISPLAY
InitDeviceDisplay();
#endif
return err;
}

void AppTask::AppTaskMain(void * pvParameter)
{
AppEvent event;
CHIP_ERROR err = sAppTask.Init();
if (err != CHIP_NO_ERROR)
{
ESP_LOGI(TAG, "AppTask.Init() failed due to %" CHIP_ERROR_FORMAT, err.Format());
return;
}

ESP_LOGI(TAG, "App Task started");

while (true)
{
BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10));
while (eventReceived == pdTRUE)
{
sAppTask.DispatchEvent(&event);
eventReceived = xQueueReceive(sAppEventQueue, &event, 0); // return immediately if the queue is empty
}
}
}

void AppTask::PostEvent(const AppEvent * aEvent)
{
if (sAppEventQueue != NULL)
{
BaseType_t status;
if (xPortInIsrContext())
{
BaseType_t higherPrioTaskWoken = pdFALSE;
status = xQueueSendFromISR(sAppEventQueue, aEvent, &higherPrioTaskWoken);
}
else
{
status = xQueueSend(sAppEventQueue, aEvent, 1);
}
if (!status)
ESP_LOGE(TAG, "Failed to post event to app task event queue");
}
else
{
ESP_LOGE(TAG, "Event Queue is NULL should never happen");
}
}

void AppTask::DispatchEvent(AppEvent * aEvent)
{
if (aEvent->mHandler)
{
aEvent->mHandler(aEvent);
}
else
{
ESP_LOGI(TAG, "Event received with no handler. Dropping event.");
}
}

void AppTask::ButtonEventHandler(uint8_t btnIdx, uint8_t btnAction)
{
AppEvent button_event = {};
button_event.mType = AppEvent::kEventType_Button;
button_event.mButtonEvent.mPinNo = btnIdx;
button_event.mButtonEvent.mAction = btnAction;

if (btnAction == APP_BUTTON_PRESSED)
{
button_event.mHandler = ButtonPressedAction;
sAppTask.PostEvent(&button_event);
}
}

void AppTask::ButtonPressedAction(AppEvent * aEvent)
{
#if CONFIG_DEVICE_TYPE_M5STACK
uint32_t io_num = aEvent->mButtonEvent.mPinNo;
int level = gpio_get_level((gpio_num_t) io_num);
if (level == 0)
{
bool woken = WakeDisplay();
if (woken)
{
return;
}
// Button 1 is connected to the pin 39
// Button 2 is connected to the pin 38
// Button 3 is connected to the pin 37
// So we use 40 - io_num to map the pin number to button number
ScreenManager::ButtonPressed(40 - io_num);
}
#endif
}
103 changes: 71 additions & 32 deletions examples/all-clusters-app/esp32/main/Button.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/*
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2018 Nest Labs, Inc.
* Copyright (c) 2022 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -20,59 +19,99 @@
/**
* @file Button.cpp
*
* Implements a Button tied to a GPIO and provides debouncing and polling
* Implements a Button tied to a GPIO and provides debouncing
*
**/

#include "driver/gpio.h"
#include "esp_check.h"
#include "esp_log.h"
#include "esp_system.h"

#include "AppTask.h"
#include "Button.h"
#include "Globals.h"
#include "ScreenManager.h"
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#include <vector>

extern const char * TAG;
static const char * TAG = "Button.cpp";

esp_err_t Button::Init(gpio_num_t gpioNum, uint16_t debouncePeriod)
{
mGPIONum = gpioNum;
mDebouncePeriod = debouncePeriod / portTICK_PERIOD_MS;
mState = false;
mLastPolledState = false;
extern Button gButtons[BUTTON_NUMBER];

esp_err_t err = gpio_set_direction(gpioNum, GPIO_MODE_INPUT);
if (err == ESP_OK)
{
Poll();
}
return err;
}
Button::Button() {}

bool Button::Poll()
Button::Button(gpio_num_t gpioNum)
{
uint32_t now = xTaskGetTickCount();

bool newState = gpio_get_level(mGPIONum) == 0;
mGPIONum = gpioNum;
}

if (newState != mLastPolledState)
int32_t Find_Button_Via_Pin(gpio_num_t gpioNum)
{
for (int i = 0; i < BUTTON_NUMBER; i++)
{
mLastPolledState = newState;
mLastReadTime = now;
if (gButtons[i].GetGPIONum() == gpioNum)
{
return i;
}
}
return -1;
}

else if (newState != mState && (now - mLastReadTime) >= mDebouncePeriod)
void IRAM_ATTR button_isr_handler(void * arg)
{
uint32_t gpio_num = (uint32_t) arg;
int32_t idx = Find_Button_Via_Pin((gpio_num_t) gpio_num);
if (idx == -1)
{
mState = newState;
mPrevStateDur = now - mStateStartTime;
mStateStartTime = now;
return true;
return;
}
BaseType_t taskWoken = pdFALSE;
xTimerStartFromISR(gButtons[idx].mbuttonTimer,
&taskWoken); // If the timer had already been started ,restart it will reset its expiry time
}

return false;
esp_err_t Button::Init()
{
return Init(mGPIONum);
}

uint32_t Button::GetStateDuration()
esp_err_t Button::Init(gpio_num_t gpioNum)
{
esp_err_t ret = ESP_OK;

mGPIONum = gpioNum;
// zero-initialize the config structure.
gpio_config_t io_conf = {};
// interrupt of falling edge
io_conf.intr_type = GPIO_INTR_NEGEDGE;
// bit mask of the pins, use GPIO4/5 here
io_conf.pin_bit_mask = 1ULL << gpioNum;
// set as input mode
io_conf.mode = GPIO_MODE_INPUT;
// enable pull-up mode
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;

gpio_config(&io_conf);

// hook isr handler for specific gpio pin
ret = gpio_isr_handler_add(gpioNum, button_isr_handler, (void *) gpioNum);
ESP_RETURN_ON_ERROR(ret, TAG, "gpio_isr_handler_add failed: %s", esp_err_to_name(ret));

mbuttonTimer = xTimerCreate("BtnTmr", // Just a text name, not used by the RTOS kernel
pdMS_TO_TICKS(50), // timer period
false, // no timer reload (==one-shot)
(void *) (int) gpioNum, // init timer id = gpioNum index
TimerCallback // timer callback handler (all buttons use
// the same timer cn function)
);

return ESP_OK;
}
void Button::TimerCallback(TimerHandle_t xTimer)
{
return (xTaskGetTickCount() - mStateStartTime) * portTICK_PERIOD_MS;
// Get the button index of the expired timer and call button event Handler.
uint32_t gpio_num = (uint32_t) pvTimerGetTimerID(xTimer);
GetAppTask().ButtonEventHandler(gpio_num, APP_BUTTON_PRESSED);
}
Loading

0 comments on commit 1539610

Please sign in to comment.