1
0

main.c 2.1 KB

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