kWhCounter.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. if( ++secondCnt == 60 ) {
  27. // Every 60 seconds
  28. ESP_LOGI("kWhCounter", "60 sec. Measure. Pin: %u Tot:%u", activeCnt, kWh_cnt);
  29. // Every 60 seconds we do a small 10 second pause to read out some temperature data
  30. // The OWB is sensitive to interrupts, so thats why we pause everything a little while
  31. sprintf(txt,"%u",kWh_cnt);
  32. sendMQTTMessage("basement/boiler/onTime", txt);
  33. vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s
  34. // Start temp measuring task
  35. xTaskCreatePinnedToCore(readAndSendTemps, "readAndSendTemps", 1024*10, NULL, 2, NULL,1);
  36. vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s
  37. if( activeCnt > 0 ) kWh_cnt += 10; // Add 10 seconds for the seconds that we where sleeping, if active
  38. secondCnt = 10;
  39. }
  40. activeCnt = 0;
  41. }
  42. }
  43. void kWhCounter_init()
  44. {
  45. ESP_LOGI("kWhCounter", "kWhCounter_init()");
  46. gpio_set_direction(KWH_COUNTER_INPUT_IO, GPIO_MODE_INPUT);
  47. xTaskCreatePinnedToCore(counterControlTask, "counterControlTask", 1024*10, NULL, 2, NULL,1);
  48. }
  49. #endif