kWhCounter.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "freertos/FreeRTOS.h"
  2. #include "freertos/task.h"
  3. #include "freertos/queue.h"
  4. #include "driver/ledc.h"
  5. #include "driver/pcnt.h"
  6. #include "esp_attr.h"
  7. #include "esp_log.h"
  8. #include "mqtt.h"
  9. #include "readTemps.h"
  10. #include "kWhCounter.h"
  11. uint32_t kWh_cnt = 0; // No of seconds of active VBB
  12. #ifdef ENABLE_KWH_COUNTER
  13. void counterControlTask(void *pvParameters) {
  14. ESP_LOGI("kWhCounter", "counterControlTask starting. Core:%d",xPortGetCoreID());
  15. char txt[50];
  16. uint32_t secondCnt = 0;
  17. uint32_t activeCnt = 0;
  18. TickType_t vLastWakeTime = xTaskGetTickCount();
  19. const TickType_t xFreq = 100 / portTICK_PERIOD_MS; // 100mS. 10 measurements / second
  20. while( 1 ) {
  21. for(uint8_t i=10; i>0; i-- ) {
  22. vTaskDelayUntil( &vLastWakeTime, xFreq );
  23. if( gpio_get_level(KWH_COUNTER_INPUT_IO) == 1 ) activeCnt++;
  24. }
  25. if( activeCnt > 0 ) kWh_cnt++;
  26. ESP_LOGI("kWhCounter", "1s Pin: %u Tot:%u", activeCnt, kWh_cnt);
  27. if( ++secondCnt == 60 ) {
  28. // Every 60 seconds
  29. ESP_LOGI("kWhCounter", "60 sec. Measure. Pin: %u Tot:%u", activeCnt, kWh_cnt);
  30. // Every 60 seconds we do a small 10 second pause to read out some temperature data
  31. // The OWB is sensitive to interrupts, so thats why we pause everything a little while
  32. sprintf(txt,"%u",kWh_cnt);
  33. sendMQTTMessage("basement/boiler/onTime", txt);
  34. vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s
  35. // Start temp measuring task
  36. xTaskCreatePinnedToCore(readAndSendTemps, "readAndSendTemps", 1024*10, NULL, 2, NULL,1);
  37. vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s
  38. if( activeCnt > 0 ) kWh_cnt += 10; // Add 10 seconds for the seconds that we where sleeping, if active
  39. secondCnt = 10;
  40. }
  41. activeCnt = 0;
  42. }
  43. }
  44. void kWhCounter_init()
  45. {
  46. ESP_LOGI("kWhCounter", "kWhCounter_init()");
  47. gpio_set_direction(KWH_COUNTER_INPUT_IO, GPIO_MODE_INPUT);
  48. xTaskCreatePinnedToCore(counterControlTask, "counterControlTask", 1024*10, NULL, 2, NULL,1);
  49. }
  50. #endif