#include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "driver/ledc.h" #include "driver/pcnt.h" #include "esp_attr.h" #include "esp_log.h" #include "mqtt.h" #include "readTemps.h" #include "kWhCounter.h" uint32_t kWh_cnt = 0; // No of seconds of active VBB #ifdef ENABLE_KWH_COUNTER void counterControlTask(void *pvParameters) { ESP_LOGI("kWhCounter", "counterControlTask starting. Core:%d",xPortGetCoreID()); char txt[50]; uint32_t secondCnt = 0; uint32_t activeCnt = 0; TickType_t vLastWakeTime = xTaskGetTickCount(); const TickType_t xFreq = 100 / portTICK_PERIOD_MS; // 100mS. 10 measurements / second while( 1 ) { for(uint8_t i=10; i>0; i-- ) { vTaskDelayUntil( &vLastWakeTime, xFreq ); if( gpio_get_level(KWH_COUNTER_INPUT_IO) == 1 ) activeCnt++; } if( activeCnt > 0 ) kWh_cnt++; if( ++secondCnt == 60 ) { // Every 60 seconds ESP_LOGI("kWhCounter", "60 sec. Measure. Pin: %u Tot:%u", activeCnt, kWh_cnt); // Every 60 seconds we do a small 10 second pause to read out some temperature data // The OWB is sensitive to interrupts, so thats why we pause everything a little while sprintf(txt,"%u",kWh_cnt); sendMQTTMessage("basement/boiler/onTime", txt); vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s // Start temp measuring task xTaskCreate(readAndSendTemps, "readAndSendTemps", 1024*10, NULL, 2, NULL); vTaskDelayUntil( &vLastWakeTime, 5000 / portTICK_PERIOD_MS ); // Sleep 5s if( activeCnt > 0 ) kWh_cnt += 10; // Add 10 seconds for the seconds that we where sleeping, if active secondCnt = 10; } activeCnt = 0; } } void kWhCounter_init() { ESP_LOGI("kWhCounter", "kWhCounter_init()"); gpio_set_direction(KWH_COUNTER_INPUT_IO, GPIO_MODE_INPUT); xTaskCreate(counterControlTask, "counterControlTask", 1024*10, NULL, 2, NULL); } #endif