Sfoglia il codice sorgente

Added http client. All works.

Thomas Chef 3 anni fa
parent
commit
4113fae458
8 ha cambiato i file con 186 aggiunte e 41 eliminazioni
  1. 1 1
      main/CMakeLists.txt
  2. 1 1
      main/config.h
  3. 122 0
      main/http_client.c
  4. 2 2
      main/led_test_inout.c
  5. 15 9
      main/main.c
  6. 16 10
      main/mqtt.c
  7. 20 9
      main/pcnt_functions.c
  8. 9 9
      main/wifi.c

+ 1 - 1
main/CMakeLists.txt

@@ -1,4 +1,4 @@
-idf_component_register(SRCS "mqtt.c" "wifi.c"
+idf_component_register(SRCS "http_client.c" "mqtt.c" "wifi.c"
 "pcnt_functions.c" "main.c" "led_test_inout.c"
 "pcnt_functions.c" "wifi.c" "mqtt.c"
                     INCLUDE_DIRS "")

+ 1 - 1
main/config.h

@@ -2,7 +2,7 @@
 #define PULSES_PER_KWH      1000
 
 // These defines configures which code to generate (to save download time during development)
-#define CCFG_GEN_PULSE      // For testing purposes only (LED-Pulse 14Hz)
+//#define CCFG_GEN_PULSE      // For testing purposes only (LED-Pulse 14Hz)
 #define CCFG_PCNT           // pcnt-code that counts pulses
 #define WIFI_ENABLED
 

+ 122 - 0
main/http_client.c

@@ -0,0 +1,122 @@
+#include <string.h>
+#include <stdlib.h>
+#include "freertos/FreeRTOS.h"
+#include "freertos/task.h"
+#include "esp_log.h"
+#include "esp_system.h"
+#include "esp_event.h"
+
+#include "wifi.h"
+#include "config.h"
+
+#ifdef WIFI_ENABLED
+
+#include "nvs_flash.h"
+#include "esp_netif.h"
+#include "esp_tls.h"
+#include "esp_http_client.h"
+
+#define MAX_HTTP_RECV_BUFFER 512
+static const char *TAG = "HTTP_CLIENT";
+
+typedef struct {
+	double energyData_kWh;
+    uint32_t bigCnt;
+    int32_t cnt;
+} sensor_data;
+
+esp_err_t _http_event_handler(esp_http_client_event_t *evt)
+{
+    switch(evt->event_id) {
+        case HTTP_EVENT_ERROR:
+            ESP_LOGD(TAG, "HTTP_EVENT_ERROR");
+            break;
+        case HTTP_EVENT_ON_CONNECTED:
+            ESP_LOGD(TAG, "HTTP_EVENT_ON_CONNECTED");
+            break;
+        case HTTP_EVENT_HEADER_SENT:
+            ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT");
+            break;
+        case HTTP_EVENT_ON_HEADER:
+            ESP_LOGD(TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
+            break;
+        case HTTP_EVENT_ON_DATA:
+            ESP_LOGD(TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
+            if (!esp_http_client_is_chunked_response(evt->client)) {
+                // Write out data
+                // printf("%.*s", evt->data_len, (char*)evt->data);
+            }
+
+            break;
+        case HTTP_EVENT_ON_FINISH:
+            ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH");
+            break;
+        case HTTP_EVENT_DISCONNECTED:
+            ESP_LOGI(TAG, "HTTP_EVENT_DISCONNECTED");
+            int mbedtls_err = 0;
+            esp_err_t err = esp_tls_get_and_clear_last_error(evt->data, &mbedtls_err, NULL);
+            if (err != 0) {
+                ESP_LOGI(TAG, "Last esp error code: 0x%x", err);
+                ESP_LOGI(TAG, "Last mbedtls failure: 0x%x", mbedtls_err);
+            }
+            break;
+    }
+    return ESP_OK;
+}
+
+static void http_rest_with_url(void *pvParameters)
+{
+    esp_http_client_config_t config = {
+        .url = "http://192.168.1.110/electrical/register_sensor_data.php",
+        .event_handler = _http_event_handler,
+    };
+    esp_http_client_handle_t client = esp_http_client_init(&config);
+
+    
+
+    sensor_data *data = (sensor_data *)pvParameters;
+
+    char post_data[4096];
+    sprintf(post_data,"dataStr=%.4f&bigCnt=%u&cnt=%d",
+                        data->energyData_kWh, data->bigCnt, data->cnt
+                        );
+
+    //printf("\n%s\n",post_data);
+
+    esp_http_client_set_method(client, HTTP_METHOD_POST);
+    esp_http_client_set_post_field(client, post_data, strlen(post_data));
+    esp_err_t err = esp_http_client_perform(client);
+    if (err == ESP_OK) {
+        ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %d",
+                esp_http_client_get_status_code(client),
+                esp_http_client_get_content_length(client));
+    } else {
+        ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
+    }
+
+    esp_http_client_cleanup(client);
+}
+
+#endif
+
+static void http_send_data_task(void *pvParameters)
+{
+
+#ifdef WIFI_ENABLED
+    http_rest_with_url(pvParameters);
+#endif
+
+    vTaskDelete(NULL);
+}
+
+void sendHTTPMessage(const double inData, const uint32_t bigCnt, const int32_t cnt) {
+
+    static sensor_data data;
+
+    data.energyData_kWh = inData;
+    data.bigCnt = bigCnt;
+    data.cnt = cnt;
+    void *const ptr = (void *const)&data;
+
+    if( commIsUpAndRunning == 1 ) xTaskCreate(&http_send_data_task, "send_data_task", 8192, ptr, 5, NULL);
+}

+ 2 - 2
main/led_test_inout.c

@@ -19,7 +19,7 @@ void ledc_init(void)
     ledc_timer.speed_mode       = LEDC_LOW_SPEED_MODE;
     ledc_timer.timer_num        = LEDC_TIMER_0;
     ledc_timer.duty_resolution  = LEDC_TIMER_13_BIT;
-    ledc_timer.freq_hz          = 14;   // Should be 2 for some kind of max kWh
+    ledc_timer.freq_hz          = 100;   // Should be 2 for some kind of max kWh
     ledc_timer.clk_cfg          = LEDC_AUTO_CLK;
     ledc_timer_config(&ledc_timer);
 
@@ -34,7 +34,7 @@ void ledc_init(void)
     ledc_channel.hpoint     = 0;
     ledc_channel_config(&ledc_channel);
 
-    // Set duty to 50%
+    // Set duty to 5%
     ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0, 409)); // Set duty to 5%. ((2 ** 13) - 1) * 50% = 409
     // Update duty to apply the new value
     ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, LEDC_CHANNEL_0));

+ 15 - 9
main/main.c

@@ -15,11 +15,13 @@
 // Externs
 extern void ledc_init(void);
 extern void init_pcnt_unit();
-extern float getkWh();
+extern double getkWh(uint32_t *bigCnt, int32_t *cnt);
 
 extern void mqtt_init();
 extern void sendMQTTMessage(const char * topic, const char * data);
 
+extern void sendHTTPMessage(const double inData, const uint32_t bigCnt, const int32_t cnt);
+
 // Chip info:
 // This is esp32 chip with 2 CPU cores, WiFi/BT/BLE, silicon revision 1, 4MB external flash
 
@@ -34,30 +36,34 @@ extern void sendMQTTMessage(const char * topic, const char * data);
 
 void app_main(void)
 {
-    printf("HomeEnergyMeter ESP32\n");
+    ESP_LOGI("MAIN", "HomeEnergyMeter ESP32");
 
     init_pcnt_unit();
     ledc_init();
 #ifdef WIFI_ENABLED
     initWifi();             // Init WIFI
 #endif
-    vTaskDelay(5000 / portTICK_PERIOD_MS);
     mqtt_init();
 
-    float kWh;
+    char dataStr[100];
+    double kWh = 0.0;
+    uint32_t bigCnt = 0;
+    int32_t cnt = 0;
 
     while( true ) {
 
-        char dataStr[100];
 
-        kWh = getkWh();
+        kWh = getkWh(&bigCnt, &cnt);
 
-        sprintf(dataStr,"%f",kWh);
+        sprintf(dataStr,"%.5f",kWh);
 
         sendMQTTMessage("/sensors/energy/electricalTotal", dataStr);
 
-        printf("%f\n",kWh);
-        vTaskDelay(1000 / portTICK_PERIOD_MS);
+        sendHTTPMessage(kWh, bigCnt, cnt);
+
+        ESP_LOGI("MAIN", "%.4f   %u    %d",kWh,bigCnt,cnt);
+
+        vTaskDelay(60000 / portTICK_PERIOD_MS);
     }
     esp_restart();
 }

+ 16 - 10
main/mqtt.c

@@ -30,6 +30,8 @@
 #include "esp_log.h"
 #include "mqtt_client.h"
 
+#include "wifi.h"
+
 static const char *TAG = "MQTT";
 static esp_mqtt_client_handle_t client;
 static bool connected = false;
@@ -37,8 +39,8 @@ static bool connected = false;
 
 static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
 {
-    esp_mqtt_client_handle_t client = event->client;
-    int msg_id;
+    //esp_mqtt_client_handle_t client = event->client;
+    //int msg_id;
     // your_context_t *context = event->context;
     switch (event->event_id) {
         case MQTT_EVENT_CONNECTED:
@@ -73,10 +75,11 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_
     mqtt_event_handler_cb(event_data);
 }
 
+void    mqttTask(void *pvParameters) {
 
+    // Wait for tcpip-comm
+    while( commIsUpAndRunning == false ) vTaskDelay(10000 / portTICK_PERIOD_MS);
 
-void mqtt_init(void)
-{
     esp_mqtt_client_config_t mqtt_cfg = {
         .uri = "mqtt://192.168.1.110:1883",
         .password = CONFIG_ESP_MQTT_PASSWORD,
@@ -87,12 +90,15 @@ void mqtt_init(void)
     esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
     esp_mqtt_client_start(client);
 
-/*    while( 1 ) {
-        int msg_id;
-        msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
-        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
-        vTaskDelay(1000 / portTICK_PERIOD_MS);
-    }*/
+    vTaskDelete(NULL);
+}
+
+
+
+void mqtt_init(void)
+{
+    xTaskCreate(mqttTask, "MQTT-Task", 1024*10, NULL, 2, NULL);
+
 }
 
 void sendMQTTMessage(const char * topic, const char * data) {

+ 20 - 9
main/pcnt_functions.c

@@ -13,24 +13,31 @@
 
 // Example-code: https://github.com/espressif/esp-idf/blob/master/examples/peripherals/pcnt/pulse_count_event/main/pcnt_event_example_main.c
 
-// Counts full kWh
-static uint32_t kWh_Counter = 0;
+// Counts interrupts that occus every 32K Pulses
+// The counter register is 16 bit signed so we count to 32K before doing an interrupt
+// This equals to 32kWH consumed energy (at 1000 pulses per kWh)
+static uint32_t Counter_32K_Pulses = 0;
 
 const int pcntUnit = PCNT_UNIT_0;
 
-float getkWh() {
+double getkWh(uint32_t *bigCnt, int32_t *cnt) {
 
     pcnt_intr_disable(pcntUnit);
     volatile int32_t count = DPORT_REG_READ(0x3FF57060);
-    volatile uint32_t kWh = kWh_Counter;
+    volatile uint32_t bigCounter = Counter_32K_Pulses;
     pcnt_intr_enable(pcntUnit);
 
-    return (float)kWh + ((float)count/PULSES_PER_KWH);
+    *bigCnt = bigCounter;
+    *cnt = count;
+
+    const double retVal = ((double)bigCounter*32)+((double)count / PULSES_PER_KWH);
+
+    return retVal;
 }
 
 static void IRAM_ATTR pcnt_example_intr_handler(void *arg)
 {
-    kWh_Counter++;
+    Counter_32K_Pulses++;
 }
 
 void init_pcnt_unit()
@@ -49,7 +56,7 @@ void init_pcnt_unit()
         .lctrl_mode = PCNT_MODE_REVERSE, // Reverse counting direction if low
         .hctrl_mode = PCNT_MODE_KEEP,    // Keep the primary counter mode if high
         // Set the maximum and minimum limit values to watch
-        .counter_h_lim = PULSES_PER_KWH,
+        .counter_h_lim = 32000,
         .counter_l_lim = 0,
     };
     /* Initialize PCNT unit */
@@ -59,8 +66,12 @@ void init_pcnt_unit()
     //uint32_t c = p_pcnt_obj->hal.dev.hw.conf_unit[unit];
     //printf("Reg: %08x\n",(uint32_t)DPORT_REG_READ(0x3FF57000));
 
+    //The length of ignored pulses is provided in APB_CLK clock cycles by calling pcnt_set_filter_value().
+    //The current filter setting may be checked with pcnt_get_filter_value().
+    //The APB_CLK clock is running at 80 MHz.
+
     /* Configure and enable the input filter */
-    pcnt_set_filter_value(pcntUnit, 100);
+    pcnt_set_filter_value(pcntUnit, 1023); // APB_CLK=80MHz * 1023 is filtered out = 0,0127875mS (????)
     pcnt_filter_enable(pcntUnit);
 
     /* Enable int on high count limit */
@@ -81,6 +92,6 @@ void init_pcnt_unit()
 #else
 
 void init_pcnt_unit() { }
-float getkWh() { return 0.0f; }
+double getkWh() { return 0.0f; }
 
 #endif

+ 9 - 9
main/wifi.c

@@ -101,6 +101,14 @@ static void setupAndConfigureWiFi(void)
 
 void    wifiTask(void *pvParameters)
 {
+    //Initialize NVS
+    esp_err_t ret = nvs_flash_init();
+    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
+        ESP_ERROR_CHECK(nvs_flash_erase());
+        ret = nvs_flash_init();
+    }
+    ESP_ERROR_CHECK(ret);
+
     static TickType_t lastLogTime = 0;
 
     while(1) {
@@ -168,15 +176,7 @@ void    wifiTask(void *pvParameters)
 
 void initWifi(void)
 {
-  //Initialize NVS
-  esp_err_t ret = nvs_flash_init();
-  if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
-    ESP_ERROR_CHECK(nvs_flash_erase());
-    ret = nvs_flash_init();
-  }
-  ESP_ERROR_CHECK(ret);
-
-  xTaskCreate(wifiTask, "WiFi-Task", 1024*10, NULL, 2, NULL);
+    xTaskCreate(wifiTask, "WiFi-Task", 1024*10, NULL, 2, NULL);
 }
 
 #endif