CPUUsageTracker.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #ifdef ESP32
  2. #include "CPUUsageTracker.h"
  3. #include "esp_freertos_hooks.h"
  4. volatile uint32_t CPUUsageTracker::s_ticks[2] = {0, 0};
  5. TaskHandle_t CPUUsageTracker::s_idle_handle = nullptr;
  6. void IRAM_ATTR CPUUsageTracker::s_tick_hook() {
  7. s_ticks[xTaskGetCurrentTaskHandle() != s_idle_handle]++;
  8. }
  9. void CPUUsageTracker::s_sample_cb(void* arg) {
  10. static_cast<CPUUsageTracker*>(arg)->_onSample();
  11. }
  12. void CPUUsageTracker::_onSample() {
  13. const uint32_t idle = s_ticks[0];
  14. const uint32_t busy = s_ticks[1];
  15. const uint32_t di = idle - _last_idle;
  16. const uint32_t db = busy - _last_busy;
  17. _last_idle = idle;
  18. _last_busy = busy;
  19. const uint32_t total = di + db;
  20. const float sample = (total > 0) ? (float)db / (float)total : 0.0f;
  21. const uint8_t s8 = (uint8_t)(sample * 255.0f + 0.5f);
  22. const uint16_t last = _sma_buf[_sma_idx];
  23. _sma_buf[_sma_idx] = s8;
  24. _sma_sum = (_sma_sum - last) + s8;
  25. _sma_idx = (_sma_idx + 1) & (SMA_WINDOW - 1);
  26. }
  27. void CPUUsageTracker::begin() {
  28. s_idle_handle = xTaskGetIdleTaskHandleForCPU(0);
  29. esp_register_freertos_tick_hook_for_cpu(s_tick_hook, 0);
  30. esp_timer_create_args_t args = {
  31. .callback = s_sample_cb,
  32. .arg = this,
  33. .dispatch_method = ESP_TIMER_TASK,
  34. .name = "cpu_sample"
  35. };
  36. esp_timer_create(&args, &_timer);
  37. esp_timer_start_periodic(_timer, 60000000ULL / SMA_WINDOW); // SMA_WINDOW samples per minute
  38. }
  39. #endif