DeepSleepLock.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /* mbed Microcontroller Library
  2. * Copyright (c) 2017 ARM Limited
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef MBED_DEEPSLEEPLOCK_H
  17. #define MBED_DEEPSLEEPLOCK_H
  18. #include <limits.h>
  19. #include "platform/mbed_power_mgmt.h"
  20. #include "platform/mbed_critical.h"
  21. namespace mbed {
  22. /** \addtogroup platform */
  23. /** @{*/
  24. /**
  25. * \defgroup platform_DeepSleepLock DeepSleepLock functions
  26. * @{
  27. */
  28. /** RAII object for disabling, then restoring the deep sleep mode
  29. * Usage:
  30. * @code
  31. *
  32. * void f() {
  33. * // some code here
  34. * {
  35. * DeepSleepLock lock;
  36. * // Code in this block will run with the deep sleep mode locked
  37. * }
  38. * // deep sleep mode will be restored to their previous state
  39. * }
  40. * @endcode
  41. */
  42. class DeepSleepLock {
  43. private:
  44. uint16_t _lock_count;
  45. public:
  46. DeepSleepLock(): _lock_count(1)
  47. {
  48. sleep_manager_lock_deep_sleep();
  49. }
  50. ~DeepSleepLock()
  51. {
  52. if (_lock_count) {
  53. sleep_manager_unlock_deep_sleep();
  54. }
  55. }
  56. /** Mark the start of a locked deep sleep section
  57. */
  58. void lock()
  59. {
  60. uint16_t count = core_util_atomic_incr_u16(&_lock_count, 1);
  61. if (1 == count) {
  62. sleep_manager_lock_deep_sleep();
  63. }
  64. if (0 == count) {
  65. MBED_ERROR1(MBED_MAKE_ERROR(MBED_MODULE_PLATFORM, MBED_ERROR_CODE_OVERFLOW), "DeepSleepLock overflow (> USHRT_MAX)", count);
  66. }
  67. }
  68. /** Mark the end of a locked deep sleep section
  69. */
  70. void unlock()
  71. {
  72. uint16_t count = core_util_atomic_decr_u16(&_lock_count, 1);
  73. if (count == 0) {
  74. sleep_manager_unlock_deep_sleep();
  75. }
  76. if (count == USHRT_MAX) {
  77. core_util_critical_section_exit();
  78. MBED_ERROR1(MBED_MAKE_ERROR(MBED_MODULE_PLATFORM, MBED_ERROR_CODE_UNDERFLOW), "DeepSleepLock underflow (< 0)", count);
  79. }
  80. }
  81. };
  82. /**@}*/
  83. /**@}*/
  84. }
  85. #endif