main.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #ifdef MQTT_ENABLED
  40. mqtt_init();
  41. #endif
  42. char dataStr[100];
  43. double kWh = 0.0;
  44. uint32_t bigCnt = 0;
  45. int32_t cnt = 0;
  46. while( true ) {
  47. kWh = getkWh(&bigCnt, &cnt);
  48. sprintf(dataStr,"%.5f",kWh);
  49. // @TODO This is changed for testing
  50. #ifdef MQTT_ENABLED
  51. sendMQTTMessage("/sensors/TEST/energy/electricalTotal", dataStr);
  52. #endif
  53. #ifdef WIFI_ENABLED
  54. sendHTTPMessage(kWh, bigCnt, cnt);
  55. #endif
  56. ESP_LOGI("MAIN", "%.4f %u %d",kWh,bigCnt,cnt);
  57. vTaskDelay(60000 / portTICK_PERIOD_MS);
  58. }
  59. esp_restart();
  60. }