AsyncWebSynchronization.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #ifndef ASYNCWEBSYNCHRONIZATION_H_
  2. #define ASYNCWEBSYNCHRONIZATION_H_
  3. // Synchronisation is only available on ESP32, as the ESP8266 isn't using FreeRTOS by default
  4. #include <ESPAsyncWebServer.h>
  5. #ifdef ESP32
  6. // This is the ESP32 version of the Sync Lock, using the FreeRTOS Semaphore
  7. class AsyncWebLock
  8. {
  9. private:
  10. SemaphoreHandle_t _lock;
  11. mutable void *_lockedBy;
  12. public:
  13. AsyncWebLock() {
  14. _lock = xSemaphoreCreateBinary();
  15. _lockedBy = NULL;
  16. xSemaphoreGive(_lock);
  17. }
  18. ~AsyncWebLock() {
  19. vSemaphoreDelete(_lock);
  20. }
  21. bool lock() const {
  22. extern void *pxCurrentTCB;
  23. if (_lockedBy != pxCurrentTCB) {
  24. xSemaphoreTake(_lock, portMAX_DELAY);
  25. _lockedBy = pxCurrentTCB;
  26. return true;
  27. }
  28. return false;
  29. }
  30. void unlock() const {
  31. _lockedBy = NULL;
  32. xSemaphoreGive(_lock);
  33. }
  34. };
  35. #else
  36. // This is the 8266 version of the Sync Lock which is currently unimplemented
  37. class AsyncWebLock
  38. {
  39. public:
  40. AsyncWebLock() {
  41. }
  42. ~AsyncWebLock() {
  43. }
  44. bool lock() const {
  45. return false;
  46. }
  47. void unlock() const {
  48. }
  49. };
  50. #endif
  51. class AsyncWebLockGuard
  52. {
  53. private:
  54. const AsyncWebLock *_lock;
  55. public:
  56. AsyncWebLockGuard(const AsyncWebLock &l) {
  57. if (l.lock()) {
  58. _lock = &l;
  59. } else {
  60. _lock = NULL;
  61. }
  62. }
  63. ~AsyncWebLockGuard() {
  64. if (_lock) {
  65. _lock->unlock();
  66. }
  67. }
  68. };
  69. #endif // ASYNCWEBSYNCHRONIZATION_H_