1
0
mirror of https://github.com/esphome/esphome.git synced 2025-10-29 22:24:26 +00:00

Lock scheduler items while modifying them (#4410)

* Cosmetic fixes to scheduler code

* Add generic Mutex API

* Lock scheduler items while modifying them

* Always defer MQTT callbacks on Arduino
This commit is contained in:
Oxan van Leeuwen
2023-02-26 19:43:08 +01:00
committed by GitHub
parent 1a9141877d
commit 86c0e6114f
5 changed files with 100 additions and 12 deletions

View File

@@ -14,6 +14,14 @@
#include <esp_heap_caps.h>
#endif
#if defined(USE_ESP32)
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#elif defined(USE_RP2040)
#include <FreeRTOS.h>
#include <semphr.h>
#endif
#define HOT __attribute__((hot))
#define ESPDEPRECATED(msg, when) __attribute__((deprecated(msg)))
#define ALWAYS_INLINE __attribute__((always_inline))
@@ -516,6 +524,39 @@ template<typename T> class Parented {
/// @name System APIs
///@{
/** Mutex implementation, with API based on the unavailable std::mutex.
*
* @note This mutex is non-recursive, so take care not to try to obtain the mutex while it is already taken.
*/
class Mutex {
public:
Mutex();
Mutex(const Mutex &) = delete;
void lock();
bool try_lock();
void unlock();
Mutex &operator=(const Mutex &) = delete;
private:
#if defined(USE_ESP32) || defined(USE_RP2040)
SemaphoreHandle_t handle_;
#endif
};
/** Helper class that wraps a mutex with a RAII-style API.
*
* This behaves like std::lock_guard: as long as the object is alive, the mutex is held.
*/
class LockGuard {
public:
LockGuard(Mutex &mutex) : mutex_{mutex} { mutex_.lock(); }
~LockGuard() { mutex_.unlock(); }
private:
Mutex &mutex_;
};
/** Helper class to disable interrupts.
*
* This behaves like std::lock_guard: as long as the object is alive, all interrupts are disabled.