1
0

main.c 2.0 KB

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