From f764f2fe2f88ce79ef4dcf5b3abcabe48af145d2 Mon Sep 17 00:00:00 2001 From: Christian Loch Date: Thu, 5 Mar 2020 01:30:31 +0100 Subject: [PATCH] Added simple HTTP Server Rewrote print_data function Fixed multiple sensor usage on one I2C bus --- main/main.c | 465 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 379 insertions(+), 86 deletions(-) diff --git a/main/main.c b/main/main.c index 848561e..c29c3bc 100644 --- a/main/main.c +++ b/main/main.c @@ -4,16 +4,250 @@ #include #include "u8g2_esp32_hal.h" #include +#include +#include "freertos/event_groups.h" +#include "nvs_flash.h" +#include +#include + +#define WIFI_SSID "Netzknecht" +#define WIFI_PASS "SpvtNVYsSRTsX36I" +#define WIFI_RETRIES 10 + +static EventGroupHandle_t s_wifi_event_group; +#define WIFI_CONNECTED_BIT BIT0 +#define WIFI_FAIL_BIT BIT1 + +static const char *TAG = "wifi station"; +static int s_retry_num = 0; + +char cur_value_str[255]; + +/* An HTTP GET handler */ +static esp_err_t hello_get_handler(httpd_req_t *req) +{ + char* buf; + size_t buf_len; + + /* Get header value string length and allocate memory for length + 1, + * extra byte for null termination */ + buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1; + if (buf_len > 1) { + buf = malloc(buf_len); + /* Copy null terminated value string into buffer */ + if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) { + ESP_LOGI(TAG, "Found header => Host: %s", buf); + } + free(buf); + } + + buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1; + if (buf_len > 1) { + buf = malloc(buf_len); + if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) { + ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf); + } + free(buf); + } + + buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1; + if (buf_len > 1) { + buf = malloc(buf_len); + if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) { + ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf); + } + free(buf); + } + + /* Read URL query string length and allocate memory for length + 1, + * extra byte for null termination */ + buf_len = httpd_req_get_url_query_len(req) + 1; + if (buf_len > 1) { + buf = malloc(buf_len); + if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) { + ESP_LOGI(TAG, "Found URL query => %s", buf); + char param[32]; + /* Get value of expected key from query string */ + if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) { + ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param); + } + if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) { + ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param); + } + if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) { + ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param); + } + } + free(buf); + } + + /* Set some custom headers */ + httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1"); + httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2"); + + /* Send response with custom headers and body set as the + * string passed in user context*/ + const char* resp_str = cur_value_str; + httpd_resp_send(req, resp_str, strlen(resp_str)); + + /* After sending the HTTP response the old HTTP request + * headers are lost. Check if HTTP request headers can be read now. */ + if (httpd_req_get_hdr_value_len(req, "Host") == 0) { + ESP_LOGI(TAG, "Request headers lost"); + } + return ESP_OK; +} + +static httpd_uri_t hello = { + .uri = "/hello", + .method = HTTP_GET, + .handler = hello_get_handler, + /* Let's pass response string in user + * context to demonstrate it's usage */ + .user_ctx = "Hello World!" +}; + +static httpd_handle_t start_webserver(void) +{ + httpd_handle_t server = NULL; + httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + + // Start the httpd server + ESP_LOGI(TAG, "Starting server on port: '%d'", config.server_port); + if (httpd_start(&server, &config) == ESP_OK) { + // Set URI handlers + ESP_LOGI(TAG, "Registering URI handlers"); + httpd_register_uri_handler(server, &hello); + return server; + } + + ESP_LOGI(TAG, "Error starting server!"); + return NULL; +} + +static void stop_webserver(httpd_handle_t server) +{ + // Stop the httpd server + httpd_stop(server); +} + +static void disconnect_handler(void* arg, esp_event_base_t event_base, + int32_t event_id, void* event_data) +{ + httpd_handle_t* server = (httpd_handle_t*) arg; + if (*server) { + ESP_LOGI(TAG, "Stopping webserver"); + stop_webserver(*server); + *server = NULL; + } +} + +static void connect_handler(void* arg, esp_event_base_t event_base, + int32_t event_id, void* event_data) +{ + httpd_handle_t* server = (httpd_handle_t*) arg; + if (*server == NULL) { + ESP_LOGI(TAG, "Starting webserver"); + *server = start_webserver(); + } +} + +static void event_handler(void* arg, esp_event_base_t event_base, + int32_t event_id, void* event_data) +{ + if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { + esp_wifi_connect(); + } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { + if (s_retry_num < WIFI_RETRIES) { + esp_wifi_connect(); + s_retry_num++; + ESP_LOGI(TAG, "retry to connect to the AP"); + } else { + xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); + } + ESP_LOGI(TAG,"connect to the AP fail"); + } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { + ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; + ESP_LOGI(TAG, "got ip:%s", + ip4addr_ntoa(&event->ip_info.ip)); + s_retry_num = 0; + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + } +} + +void wifi_init_sta() +{ + s_wifi_event_group = xEventGroupCreate(); + + tcpip_adapter_init(); + + ESP_ERROR_CHECK(esp_event_loop_create_default()); + + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK(esp_wifi_init(&cfg)); + + //tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + //tcpip_adapter_ip_info_t info; + //ip4_addr_t gw; + //gw.addr = ipaddr_addr("192.168.0.1"); + //info.gw = gw; + //ip4_addr_t ip; + //ip.addr = ipaddr_addr("192.168.0.110"); + //info.ip = ip; + //ip4_addr_t netmask; + //netmask.addr = ipaddr_addr("255.255.255.0"); + //info.netmask = netmask; + //tcpip_adapter_sta_start(0, &info); + + ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); + ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL)); + + wifi_config_t wifi_config = { + .sta = { + .ssid = WIFI_SSID, + .password = WIFI_PASS + }, + }; + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) ); + ESP_ERROR_CHECK(esp_wifi_start() ); + + ESP_LOGI(TAG, "wifi_init_sta finished."); + + /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum + * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */ + EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group, + WIFI_CONNECTED_BIT | WIFI_FAIL_BIT, + pdFALSE, + pdFALSE, + portMAX_DELAY); + + //tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info); + /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually + * happened. */ + if (bits & WIFI_CONNECTED_BIT) { + ESP_LOGI(TAG, "connected to ap SSID:%s password:%s", + WIFI_SSID, WIFI_PASS); + } else if (bits & WIFI_FAIL_BIT) { + ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s", + WIFI_SSID, WIFI_PASS); + } else { + ESP_LOGE(TAG, "UNEXPECTED EVENT"); + } + + ESP_ERROR_CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler)); + ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler)); + vEventGroupDelete(s_wifi_event_group); +} void i2c_setup() { - printf("Setting up I²C driver... "); - //i2c_driver_install(0, I2C_MODE_MASTER, 0, 0, 0); + printf("Setting up I²C driver on port 1... "); i2c_config_t config; config.mode = I2C_MODE_MASTER; - config.sda_io_num = 18; + config.sda_io_num = 33; config.sda_pullup_en = GPIO_PULLUP_ENABLE; - config.scl_io_num = 19; + config.scl_io_num = 32; config.scl_pullup_en = GPIO_PULLUP_ENABLE; config.master.clk_speed = 100000; i2c_param_config(I2C_NUM_0, &config); @@ -27,34 +261,6 @@ void i2c_setup() printf("Driver install failed!\n"); } -void i2c_detect() -{ - printf("Scanning I²C bus:\n"); - uint8_t address; - printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\r\n"); - for (int i = 0; i < 128; i += 16) { - printf("%02x: ", i); - for (int j = 0; j < 16; j++) { - fflush(stdout); - address = i + j; - i2c_cmd_handle_t cmd = i2c_cmd_link_create(); - i2c_master_start(cmd); - i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, 0x1); - i2c_master_stop(cmd); - esp_err_t ret = i2c_master_cmd_begin(I2C_NUM_0, cmd, 50 / portTICK_RATE_MS); - i2c_cmd_link_delete(cmd); - if (ret == ESP_OK) { - printf("%02x ", address); - } else if (ret == ESP_ERR_TIMEOUT) { - printf("UU "); - } else { - printf("-- "); - } - } - printf("\r\n"); - } -} - int8_t i2c_read(uint8_t dev_id, uint8_t reg_addr, uint8_t *data, uint16_t len) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); @@ -105,18 +311,15 @@ void read_sensor(struct bme280_dev* dev, int32_t* temp, uint32_t* pressure, uint uint32_t req_delay; struct bme280_data comp_data; - /* Recommended mode of operation: Indoor navigation */ - dev->settings.osr_h = BME280_OVERSAMPLING_1X; + dev->settings.osr_h = BME280_OVERSAMPLING_16X; dev->settings.osr_p = BME280_OVERSAMPLING_16X; dev->settings.osr_t = BME280_OVERSAMPLING_16X; dev->settings.filter = BME280_FILTER_COEFF_16; settings_sel = BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL | BME280_OSR_HUM_SEL | BME280_FILTER_SEL; bme280_set_sensor_settings(settings_sel, dev); - /*Calculate the minimum delay required between consecutive measurement based upon the sensor enabled - * and the oversampling configuration. */ + req_delay = 12*bme280_cal_meas_delay(&(dev->settings)); - printf("req_delay=%i\r\n", req_delay); /* Continuously stream sensor data */ bme280_set_sensor_mode(BME280_FORCED_MODE, dev); @@ -128,59 +331,117 @@ void read_sensor(struct bme280_dev* dev, int32_t* temp, uint32_t* pressure, uint *humidity = comp_data.humidity; } -void print_data(u8g2_t* u8g2, int32_t temp, uint32_t pressure, uint32_t humidity) { - int32_t temp1 = temp / 100; - int32_t temp2 = (abs(temp) % 100) / 10; - uint32_t press1 = pressure / 100; - uint32_t humid1 = humidity / 1024; - uint32_t humid2 = (humidity - humid1*1024) * 10 / 1024; - //temp1 = 12; - //temp2 = 3; - int32_t temp3 = -1*temp1; - int32_t temp4 = temp2; - //press1 = 9999; - //humid1 = 13; - //humid2 = 4; - char temp1str[31]; - char temp1str2[32]; - sprintf(temp1str, "%d,%d", temp1, temp2); - if (temp1 < 10) { - sprintf(temp1str2, " %s", temp1str); - } else { - sprintf(temp1str2, "%s", temp1str); - } - char temp2str[31]; - char temp2str2[33]; - sprintf(temp2str, "%d,%d", temp3, temp4); - uint8_t spaces = 0; - if (temp3 > 0) - spaces++; - if (abs(temp3) < 10) - spaces++; - if (spaces == 2) - sprintf(temp2str2, " %s", temp2str); - else if (spaces == 1) - sprintf(temp2str2, " %s", temp2str); - else { - sprintf(temp2str2, "%s", temp2str); - } - char tempstr[70]; - sprintf(tempstr, "%s %s °C", temp1str2, temp2str2); +void read_sensor2(struct bme280_dev* dev, int32_t* temp, uint32_t* pressure, uint32_t* humidity) { + + uint8_t settings_sel; + uint32_t req_delay; + struct bme280_data comp_data; + + dev->settings.osr_h = BME280_OVERSAMPLING_16X; + dev->settings.osr_p = BME280_OVERSAMPLING_16X; + dev->settings.osr_t = BME280_OVERSAMPLING_16X; + dev->settings.filter = BME280_FILTER_COEFF_16; + + settings_sel = BME280_OSR_PRESS_SEL | BME280_OSR_TEMP_SEL | BME280_OSR_HUM_SEL | BME280_FILTER_SEL; + bme280_set_sensor_settings(settings_sel, dev); + /*Calculate the minimum delay required between consecutive measurement based upon the sensor enabled + * and the oversampling configuration. */ + req_delay = 12*bme280_cal_meas_delay(&(dev->settings)); + + bme280_set_sensor_mode(BME280_FORCED_MODE, dev); + /* Wait for the measurement to complete and print data @25Hz */ + dev->delay_ms(req_delay / portTICK_PERIOD_MS); + bme280_get_sensor_data(BME280_ALL, &comp_data, dev); + *temp = comp_data.temperature; + *pressure = comp_data.pressure; + *humidity = comp_data.humidity; +} + +void print_data(u8g2_t* u8g2, int32_t temp_raw, uint32_t pressure_raw, uint32_t humidity_raw, + int32_t temp2_raw, uint32_t pressure2_raw, uint32_t humidity2_raw) { + // Calc temperature pre and post comma values + int32_t temp_pre = temp_raw / 100; + int32_t temp_post = (abs(temp_raw) % 100) / 10; + int32_t temp2_pre = temp2_raw / 100; + int32_t temp2_post = (abs(temp2_raw) % 100) / 10; + + // Calc pressure values + uint32_t press = pressure_raw / 100; + uint32_t press2 = pressure2_raw / 100; + + // Calc humidity pre and post comma values + uint32_t humid_pre = humidity_raw / 1024; + uint32_t humid_post = (humidity_raw - humid_pre*1024) * 10 / 1024; + uint32_t humid2_pre = humidity2_raw / 1024; + uint32_t humid2_post = (humidity2_raw - humid2_pre*1024) * 10 / 1024; + + // Format temperatures + char temp_str[2*(sizeof(int)*8+1)+5] = ""; // "" + char temp_pre_str[sizeof(int)*8+1]; + itoa(temp_pre, temp_pre_str, 10); + char temp_post_str[sizeof(int)*8+1]; + itoa(temp_post, temp_post_str, 10); + char temp2_pre_str[sizeof(int)*8+1]; + itoa(temp2_pre, temp2_pre_str, 10); + char temp2_post_str[sizeof(int)*8+1]; + itoa(temp2_post, temp2_post_str, 10); + if (temp_pre < 10) + strcat(temp_str, " "); // Add space if first temperatur is just one digit long " " + strcat(temp_str, temp_pre_str); // " 1" + strcat(temp_str, ","); // " 1," + strcat(temp_str, temp_post_str); // " 1,3" + strcat(temp_str, " "); // " 1,3 " + if (temp2_pre >= 0) + strcat(temp_str, " "); // Add space if there is no minus sign " 1,3 " + if (temp2_pre < 10) + strcat(temp_str, " "); // Add space if second temperatur is just one digit long " 1,3 " + strcat(temp_str, temp2_pre_str); // " 1,3 7" + strcat(temp_str, ","); // " 1,3 7," + strcat(temp_str, temp2_post_str); // " 1,3 7,2" + strcat(temp_str, " °C"); // " 1,3 7,2 °C" + + // Format temperatures + char humid_str[2*(sizeof(int)*8+1)+5] = ""; // "" + char humid_pre_str[sizeof(int)*8+1]; + itoa(humid_pre, humid_pre_str, 10); + char humid_post_str[sizeof(int)*8+1]; + itoa(humid_post, humid_post_str, 10); + char humid2_pre_str[sizeof(int)*8+1]; + itoa(humid2_pre, humid2_pre_str, 10); + char humid2_post_str[sizeof(int)*8+1]; + itoa(humid2_post, humid2_post_str, 10); + strcat(humid_str, humid_pre_str); // "12" + strcat(humid_str, ","); // "12," + strcat(humid_str, humid_post_str); // "12,5" + strcat(humid_str, " "); // "12,5 " + strcat(humid_str, humid2_pre_str); // "12,5 45" + strcat(humid_str, ","); // "12,5 45," + strcat(humid_str, humid2_post_str); // "12,5 45,23" + strcat(humid_str, " %"); // "12,5 45,23 %" + + // Format pressure + char pressure_str[2*(sizeof(int)*8+1)+5] = ""; // "" + char press1_str[sizeof(int)*8+1]; + itoa(press, press1_str, 10); + char press2_str[sizeof(int)*8+1]; + itoa(press2, press2_str, 10); + if (press < 1000) + strcat(pressure_str, " "); + strcat(pressure_str, press1_str); + strcat(pressure_str, " "); + if (press2 < 1000) + strcat(pressure_str, " "); + strcat(pressure_str, press2_str); + strcat(pressure_str, " hPa"); + u8g2_ClearBuffer(u8g2); - - char pressstr[27]; - char humidstr[27]; - - sprintf(pressstr, "%d %d hPa", press1, press1); - sprintf(humidstr, "%d,%d %d,%d %%", humid1, humid2, humid1, humid2); - u8g2_SetFont(u8g2, u8g2_font_profont17_mf); int8_t fontheight = u8g2_GetAscent(u8g2); int8_t fontmargin = abs(u8g2_GetDescent(u8g2))+2; u8g2_DrawStr(u8g2, 0, fontheight, " IN OUT "); - u8g2_DrawStr(u8g2, 0, 2*fontheight + fontmargin, tempstr); - u8g2_DrawStr(u8g2, 0, 3*fontheight + 2*fontmargin, humidstr); - u8g2_DrawStr(u8g2, 0, 4*fontheight + 3*fontmargin, pressstr); + u8g2_DrawStr(u8g2, 0, 2*fontheight + fontmargin, temp_str); + u8g2_DrawStr(u8g2, 0, 3*fontheight + 2*fontmargin, humid_str); + u8g2_DrawStr(u8g2, 0, 4*fontheight + 3*fontmargin, pressure_str); u8g2_SendBuffer(u8g2); } @@ -189,6 +450,9 @@ void app_main(void) int32_t temp = 0; uint32_t pressure = 0; uint32_t humidity = 0; + int32_t temp2 = 0; + uint32_t pressure2 = 0; + uint32_t humidity2 = 0; // INIT SENSOR i2c_setup(); @@ -200,6 +464,15 @@ void app_main(void) dev.delay_ms = i2c_delay; bme280_init(&dev); + // INIT SENSOR2 + struct bme280_dev dev2; + dev2.dev_id = 0x77; + dev2.intf = BME280_I2C_INTF; + dev2.read = i2c_read; + dev2.write = i2c_write; + dev2.delay_ms = i2c_delay; + bme280_init(&dev2); + // INIT DISPLAY u8g2_esp32_hal_t u8g2_esp32_hal = U8G2_ESP32_HAL_DEFAULT; u8g2_esp32_hal.sda = 18; @@ -213,10 +486,30 @@ void app_main(void) u8g2_InitDisplay(&u8g2); // send init sequence to the display, display is in sleep mode after this, u8g2_SetPowerSave(&u8g2, 0); // wake up display + // INIT WIFI + //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); + + ESP_LOGI(TAG, "ESP_WIFI_MODE_STA"); + wifi_init_sta(); + + // INIT WEBSERVER + static httpd_handle_t server = NULL; + ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &connect_handler, &server)); + ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &disconnect_handler, &server)); + server = start_webserver(); + while (1) { read_sensor(&dev, &temp, &pressure, &humidity); + read_sensor(&dev2, &temp2, &pressure2, &humidity2); printf("%i °c, %i hPa, %i %%\r\n", temp, pressure, humidity); - print_data(&u8g2, temp, pressure, humidity); + printf("%i °c, %i hPa, %i %%\r\n", temp2, pressure2, humidity2); + print_data(&u8g2, temp, pressure, humidity, temp2, pressure2, humidity2); vTaskDelay(250 / portTICK_PERIOD_MS); } }