1
0

main.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 double getkWh(uint32_t *bigCnt, int32_t *cnt);
  18. extern void mqtt_init();
  19. extern void sendMQTTMessage(const char * topic, const char * data);
  20. extern void sendHTTPMessage(const double inData, const uint32_t bigCnt, const int32_t cnt);
  21. // Chip info:
  22. // This is esp32 chip with 2 CPU cores, WiFi/BT/BLE, silicon revision 1, 4MB external flash
  23. /** Electric meter:
  24. * 10000 impulses per kWh
  25. * Some normal max number could be 120 kWh/24h = 5 kWh/hour = 50000 pulses/hour = 833 pulses/min = 14 pulses/sec
  26. *
  27. * Counter is 16 bit signed = Max 32768 pulses = Will NOT work for one hour !!!!!
  28. * So we need some other way of counting higher numbers that will last for one h
  29. * Probably we need to use interrupts !
  30. */
  31. void app_main(void)
  32. {
  33. ESP_LOGI("MAIN", "HomeEnergyMeter ESP32");
  34. init_pcnt_unit();
  35. ledc_init();
  36. #ifdef WIFI_ENABLED
  37. initWifi(); // Init WIFI
  38. #endif
  39. mqtt_init();
  40. char dataStr[100];
  41. double kWh = 0.0;
  42. uint32_t bigCnt = 0;
  43. int32_t cnt = 0;
  44. while( true ) {
  45. kWh = getkWh(&bigCnt, &cnt);
  46. sprintf(dataStr,"%.5f",kWh);
  47. sendMQTTMessage("/sensors/energy/electricalTotal", dataStr);
  48. sendHTTPMessage(kWh, bigCnt, cnt);
  49. ESP_LOGI("MAIN", "%.4f %u %d",kWh,bigCnt,cnt);
  50. vTaskDelay(60000 / portTICK_PERIOD_MS);
  51. }
  52. esp_restart();
  53. }