main.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include <stdio.h>
  2. #include "sdkconfig.h"
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "esp_system.h"
  6. #include "esp_spi_flash.h"
  7. #include "freertos/queue.h"
  8. #include "driver/ledc.h"
  9. #include "driver/pcnt.h"
  10. #include "esp_attr.h"
  11. #include "esp_log.h"
  12. #include "config.h"
  13. #include "wifi.h"
  14. // Externs
  15. extern void ledc_init(void);
  16. extern void init_pcnt_unit();
  17. extern uint32_t getkWh();
  18. extern void mqtt_init();
  19. extern void sendMQTTMessage(const char * topic, const char * data);
  20. // Chip info:
  21. // This is esp32 chip with 2 CPU cores, WiFi/BT/BLE, silicon revision 1, 4MB external flash
  22. /** Electric meter:
  23. * 10000 impulses per kWh
  24. * Some normal max number could be 120 kWh/24h = 5 kWh/hour = 50000 pulses/hour = 833 pulses/min = 14 pulses/sec
  25. *
  26. * Counter is 16 bit signed = Max 32768 pulses = Will NOT work for one hour !!!!!
  27. * So we need some other way of counting higher numbers that will last for one h
  28. * Probably we need to use interrupts !
  29. */
  30. void app_main(void)
  31. {
  32. ESP_LOGI("MAIN", "HomeEnergyMeter ESP32");
  33. init_pcnt_unit();
  34. ledc_init();
  35. #ifdef WIFI_ENABLED
  36. initWifi(); // Init WIFI
  37. #endif
  38. mqtt_init();
  39. uint32_t kWh = 0;
  40. char txt[100];
  41. TickType_t vLastWakeTime = xTaskGetTickCount();
  42. const TickType_t xFreq = 60000 / portTICK_PERIOD_MS;
  43. while( true ) {
  44. kWh = getkWh();
  45. sprintf(txt,"%u",kWh);
  46. sendMQTTMessage("basement/meter/electricalTotal", txt);
  47. ESP_LOGI("MAIN", "%u",kWh);
  48. vTaskDelayUntil( &vLastWakeTime, xFreq );
  49. }
  50. esp_restart();
  51. }