ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ESP32实验-自建web服务器配网01

2021-06-30 12:03:07  阅读:553  来源: 互联网

标签:web 01 ESP ESP32 wifi esp WIFI include event


目标

通过esp32自建web服务器实现配网。具体来说:
1、esp32上电,手机/电脑/平板连上esp32的wifi。
2、用浏览器访问esp32的网址esp32默认是192.168.4.1
3、在web页面中输入需要esp32连接的wifi名称,和wifi密码
4、esp32自动连接上指定的wifi

需求分析

1、为什么要用自建web服务器的方式配网,而不使用esp32官方推荐的ble或者smartconfig 方式配网?

  • 自建web服务器的优势非常明显,兼容性性强,只需要一台拥有浏览器且能连接wifi的智能终端设备即可完成配网。
  • ble和smartconfig方式优势是有官方现成的例程,开发快捷。缺点也非常明显,需要在手机上安装app,如果用电脑,还无法实现配网。兼容性非常差。为了配网还要安装一个app,不方便。

2、mvp功能。拿到一个目标后,第一时间是找出,能够实现该目标的最小功能集合。只求功能,不求代码优美,界面优美,功能完美。基于此,可以将mvp功能梳理出来。

  • 实现web界面post及get功能请求,此方式可以在eps32 station模式(通过example_connectl连上wifi)下实现,节省时间(避免电脑来回切换wifi,和esp32ap)。整体界面只需要两个标签,两个输入框,一个按钮组成
    在这里插入图片描述
  • ESP32实现wifi名称和密码解析,构想名称和密码发送格式采用网络传输常用的json格式,发送方法采用post方法
  • 实现eps32 ap 和station模式切换,采用ap模式收到了wifi名称和密码后,将ap模式切换为station模式,中间采用延时实现,最为简单,后续可以用freertos信号量来触发模式切换。整体流程是,连上ap,输入wifi信息,此时esp32程序进入延时,延时时间到,切换到station模式

效果展示
1、界面展示
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
此次已经完成最小mvp的开发,实现了通过连接esp32 ap 输入wifi信息,实现配网的功能。

代码展示

注意:web界面需要用谷歌浏览器访问,手机上要用uc浏览器访问,华为手机自带浏览器和qq浏览器访问不了web界面,原因还未找出来,因为这个问题,折腾了好几个小时,还以为代码哪里有问题

1、界面代码

<!DOCTYPE html>
<table class="fixed" border="0">

    <col width="1000px" /><col width="500px" />
        <h3>wifi 密码配置</h3>
    <div>
        <label for="name">wifi名称</label>
        <input type="text" id="wifi" name="car_name" placeholder="ssid">
        <br>
        <label for="type">密码</label>
        <input type="text" id="code" name="car_type" placeholder="password">
        <br>
        <button id ="send_WIFI" type="button" οnclick="send_wifi()">提交</button>
    </div>
</table>
<script>
function setpath() {
    var default_path = document.getElementById("newfile").files[0].name;
    document.getElementById("filepath").value = default_path;
}

function send_wifi() {
    var input_ssid = document.getElementById("wifi").value;
    var input_code = document.getElementById("code").value;
    var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/wifi_data", true);
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                if (xhttp.status == 200) {
                    console.log(xhttp.responseText);
                } else if (xhttp.status == 0) {
                    alert("Server closed the connection abruptly!");
                    location.reload()
                } else {
                    alert(xhttp.status + " Error!\n" + xhttp.responseText);
                    location.reload()
                }
            }
        };
    var data = {
        "wifi_name":input_ssid,
        "wifi_code":input_code
    }
        xhttp.send(JSON.stringify(data));
}
</script>

最后送json数据的时候,要用JSON.stringify方法格式化data,否则esp32解析json会报错,此处一定要注意!!!
整体html界面非常简单,没有基础的也很容易读懂,里面写了一个js函数,该函数是在点击按钮的时候触发,功能主要是读取文本框输入的数据,将数据封装为json格式,然后post发送数据,xhttp.open(“POST”, “/wifi_data”, true);中的url “/wifi_data”和esp32服务端中的定义要一致,否则是无法成功的。

web 服务端代码展示
基于esp32 file_server例程修改

esp_err_t start_file_server(const char *base_path)
{
    static struct file_server_data *server_data = NULL;

    /* Validate file storage base path */
    if (!base_path || strcmp(base_path, "/spiffs") != 0) {
        ESP_LOGE(TAG, "File server presently supports only '/spiffs' as base path");
        return ESP_ERR_INVALID_ARG;
    }

    if (server_data) {
        ESP_LOGE(TAG, "File server already started");
        return ESP_ERR_INVALID_STATE;
    }

    /* Allocate memory for server data */
    server_data = calloc(1, sizeof(struct file_server_data));
    if (!server_data) {
        ESP_LOGE(TAG, "Failed to allocate memory for server data");
        return ESP_ERR_NO_MEM;
    }
    strlcpy(server_data->base_path, base_path,
            sizeof(server_data->base_path));

    httpd_handle_t server = NULL;
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();

    /* Use the URI wildcard matching function in order to
     * allow the same handler to respond to multiple different
     * target URIs which match the wildcard scheme */
    config.uri_match_fn = httpd_uri_match_wildcard;

    ESP_LOGI(TAG, "Starting HTTP Server");
    if (httpd_start(&server, &config) != ESP_OK) {
        ESP_LOGE(TAG, "Failed to start file server!");
        return ESP_FAIL;
    }

    /* URI handler for getting uploaded files */
    httpd_uri_t file_download = {
        .uri       = "/*",  // Match all URIs of type /path/to/file
        .method    = HTTP_GET,
        .handler   = download_get_handler,
        .user_ctx  = server_data    // Pass server data as context
    };
    httpd_register_uri_handler(server, &file_download);


    httpd_uri_t wifi_data = {
        .uri       = "/wifi_data",   // Match all URIs of type /delete/path/to/file
        .method    = HTTP_POST,
        .handler   = send_wifi_handler,
        .user_ctx  = server_data    // Pass server data as context
    };
    httpd_register_uri_handler(server, &wifi_data);
    return ESP_OK;
}

主要关注最后两个注册函数,
1、file_download函数,其中的句柄函数为download_get_handler,当用户访问根目录,就是192.,168.4.1的时候,服务端会调用download_get_handler函数,实现web页面的加载。
2、wifi_data 函数,当用户请求/wifi_data目录时(点击按钮,post会请求该目录),会调用send_wifi_handler函数,处理post请求以及发送过来的json数据

static esp_err_t send_wifi_handler(httpd_req_t *req)
{
    int total_len = req->content_len;
    int cur_len = 0;
    char *buf = ((struct file_server_data *)(req->user_ctx))->scratch;
    int received = 0;
    if (total_len >= SCRATCH_BUFSIZE) {
        /* Respond with 500 Internal Server Error */
        httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "content too long");
        return ESP_FAIL;
    }
    while (cur_len < total_len) {
        received = httpd_req_recv(req, buf + cur_len, total_len);
        if (received <= 0) {
            /* Respond with 500 Internal Server Error */
            httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "Failed to post control value");
            return ESP_FAIL;
        }
        cur_len += received;
    }
    // char *str_u = "abcdefg";
    // for(int i = 0; i<sizeof(str_u);i++){
    //     putchar(str_u[i]);
    // }
    buf[total_len] = '\0';
    printf("recived data length is :%d\n",total_len);
    for (int i = 0; i <total_len ; i++){
        putchar(buf[i]);
    }
    printf("\r\nwifi data recived!\r\n");
     cJSON *root = cJSON_Parse(buf);
    //  int ssid = cJSON_GetObjectItem(root, "wifi_name")->valueint;
    //  int code = cJSON_GetObjectItem(root, "wifi_code")->valueint;

     char *ssid = cJSON_GetObjectItem(root, "wifi_name")->valuestring;
     char *code = cJSON_GetObjectItem(root, "wifi_code")->valuestring;
     int len1 = strlen(ssid);
     int len2 = strlen(code);
     memcpy(user_id,ssid,strlen(ssid));
     memcpy(user_code,code,strlen(code));
     user_id[len1] = '\0';
     user_code[len2] = '\0';
     cJSON_Delete(root);
    //  ESP_LOGI(TAG, "json load  finished. SSID:%d password:%d ",ssid,code);
    // ESP_LOGI(TAG, "json load  finished. SSID:%s password:%s ",user_id,user_code);
    printf("\r\nwifi_ssid:");
    for(int i = 0;i<len1;i++){
        printf("%c",user_id[i]);
    }

    printf("\r\nwifi_code:");
    for(int i = 0;i<len2;i++){
        printf("%c",user_code[i]);
    }
    printf("\r\n");
    httpd_resp_sendstr(req, "Post control value successfully");
    return ESP_OK;
}
/* Function to start the file server */

注意:
1、wifi名称和密码是字符串,故解析的时候要用使用valuestring的值,这个表示里面的数据用字符串格式解析,valueint表示数据用整形数据接收。
2、定义两个全局变量char ssid[32];char code[64];这个长度是esp32默认支持的长度,json解析到的名称和密码存储到这两个数组中,用到memcpy函数。
3、将数组中无效位的第一位写成’\0’,esp32判断字符串完成的标志就是’\0’
4、最后就是将解析出来的数据进行打印

主函数代码展示

void app_main(void)
{
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    // ESP_ERROR_CHECK(example_connect());
    wifi_init_softap();
    /* Initialize file storage */
    ESP_ERROR_CHECK(init_spiffs());
    /* Start the file server */
    ESP_ERROR_CHECK(start_file_server("/spiffs"));
       vTaskDelay(60000 / portTICK_PERIOD_MS);
    wifi_init_sta(user_id,user_code);
}

整个个工程是基于file_server修改,如果删除掉init_spiffs函数,编译会报错,暂时保留,后期优化代码的时候再处理
整个过程很简单,先开启ap模式,然后开启web服务,延时60s,切换为station模式,连上设定的wifi。如果60s内没有完成wifi信息的输入,程序也会切换到station模式,最后会联网不成功。

wifi_station代码展示


#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"
#include <stdlib.h>
#include "freertos/event_groups.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_netif.h"

#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"

#include "esp_tls.h"
#include "esp_crt_bundle.h"

#include "esp_http_client.h"


/* The examples use WiFi configuration that you can set via project configuration menu

   If you'd rather not, just change the below entries to strings with
   the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
*/
#define EXAMPLE_ESP_WIFI_SSID      "GAUSSIAN"
#define EXAMPLE_ESP_WIFI_PASS      "gaussian705"
#define EXAMPLE_ESP_MAXIMUM_RETRY  5

/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event, but we only care about two events:
 * - we are connected to the AP with an IP
 * - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

static const char *TAG = "wifi station";

static int s_retry_num = 0;

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 < EXAMPLE_ESP_MAXIMUM_RETRY) {
            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:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

void wifi_init_sta(unsigned char *name,unsigned char *code)
{
    s_wifi_event_group = xEventGroupCreate();

    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));

    wifi_config_t wifi_config = {
        .sta = {
            // .ssid = "a",
            // .password = "b",
            /* Setting a password implies station will connect to all security modes including WEP/WPA.
             * However these modes are deprecated and not advisable to be used. Incase your Access point
             * doesn't support WPA2, these mode can be enabled by commenting below line */
	     .threshold.authmode = WIFI_AUTH_WPA2_PSK,

            .pmf_cfg = {
                .capable = true,
                .required = false
            },
        },
    };
    memcpy(wifi_config.sta.ssid,name,32);
    memcpy(wifi_config.sta.password,code,64);
    
    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);

    /* 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",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else if (bits & WIFI_FAIL_BIT) {
        ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else {
        ESP_LOGE(TAG, "UNEXPECTED Eprotocol_examples_common.h:ENT");
    }

    /* The event will not be processed after unregister */
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
    vEventGroupDelete(s_wifi_event_group);
}

其中
memcpy(wifi_config.sta.ssid,name,32);
memcpy(wifi_config.sta.password,code,64);将wifi名称和密码复制到wificonfig结构体。

wifi_ap代码展示


#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"

#include "wifi_ap.h"

// #define EXAMPLE_ESP_WIFI_SSID      CONFIG_AP_ESP_WIFI_SSID
// #define EXAMPLE_ESP_WIFI_PASS      CONFIG_AP_ESP_WIFI_PASSWORD
// #define EXAMPLE_ESP_WIFI_CHANNEL   CONFIG_AP_ESP_WIFI_CHANNEL
// #define EXAMPLE_MAX_STA_CONN       CONFIG_AP_ESP_MAX_STA_CONN

#define EXAMPLE_ESP_WIFI_SSID      "ESP32"
#define EXAMPLE_ESP_WIFI_PASS      "12345678"
#define EXAMPLE_ESP_WIFI_CHANNEL   1
#define EXAMPLE_MAX_STA_CONN       4
static const char *TAG = "wifi softAP";

static void wifi_event_handler(void* arg, esp_event_base_t event_base,
                                    int32_t event_id, void* event_data)
{
    if (event_id == WIFI_EVENT_AP_STACONNECTED) {
        wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
        ESP_LOGI(TAG, "station "MACSTR" join, AID=%d",
                 MAC2STR(event->mac), event->aid);
    } else if (event_id == WIFI_EVENT_AP_STADISCONNECTED) {
        wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
        ESP_LOGI(TAG, "station "MACSTR" leave, AID=%d",
                 MAC2STR(event->mac), event->aid);
    }
}

void wifi_init_softap(void)
{
    // ESP_ERROR_CHECK(esp_netif_init());
    // ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_ap();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &wifi_event_handler,
                                                        NULL,
                                                        NULL));

    wifi_config_t wifi_config = {
        .ap = {
            .ssid = EXAMPLE_ESP_WIFI_SSID,
            .ssid_len = strlen(EXAMPLE_ESP_WIFI_SSID),
            .channel = EXAMPLE_ESP_WIFI_CHANNEL,
            .password = EXAMPLE_ESP_WIFI_PASS,
            .max_connection = EXAMPLE_MAX_STA_CONN,
            .authmode = WIFI_AUTH_WPA_WPA2_PSK
        },
    };
    if (strlen(EXAMPLE_ESP_WIFI_PASS) == 0) {
        wifi_config.ap.authmode = WIFI_AUTH_OPEN;
    }

    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
    ESP_ERROR_CHECK(esp_wifi_start());

    ESP_LOGI(TAG, "wifi_init_softap finished. SSID:%s password:%s channel:%d",
             EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS, EXAMPLE_ESP_WIFI_CHANNEL);
}

CMake注意事项

在这里插入图片描述

官方源码中,用户自己写的只有.c文件,没有.h文件,是因为行业惯例还是,编译器自动识别,不需要在.h文件中进行函数声明和变量声明?希望大佬能指点下
当包含了自己写.h文件后,编译时,还是报错,说函数未定义,折腾好好久,才发现,需要在CMakeList.txt文件中包含对应的.c文件

idf_component_register(SRCS "main.c" "file_server.c"
  "wifi_ap.c" "wifi_station.c"                 INCLUDE_DIRS "."
                    EMBED_FILES "favicon.ico" "upload_script.html")

包含之后,编译就正常了。

最后,需要源码的同学,请在评论区留下你的邮箱。大家一起共同进步。

后期功能规划
1、优化web显示效果,提升浏览器的兼容性
2、用信号量触发station模式,解析出wifi名称和密码才进行station模式切换,否则一直等待
3、wifi名称密码记忆功能,将wifi名称密码存储到eps32自带的flash某个区域,首次配网成功后,下一次上电,自动读取存储的wifi信息,并联网,如果联网不成功,报出错误,同时切换到ap配网模式
4、代码优化,优化掉无用的代码,程序封装。以用于未来其他功能需要联网功能的开发

标签:web,01,ESP,ESP32,wifi,esp,WIFI,include,event
来源: https://blog.csdn.net/sinat_36568888/article/details/118355836

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有