最近在使用esp32搭建web服务器测试,发现esp32搭建这类开发环境还是比较方便的。具体的http协议这里就不再赘述,我们主要说一下如何使用esp32提供的api来搭建我们的http web。
一、web服务器搭建过程
1、配置web服务器
在esp-idf中,web服务器使用httpd组件实现。我们需要先创建httpd_config_t结构体,指定服务器的端口、最大并发连接数、uri匹配处理器等选项。然后,我们通过调用httpd_start函数来启动web服务器。(使用默认的配置就可以,包括端口号都已经默认配置好了)
httpd_config_t config = httpd_default_config(); httpd_handle_t server = null; // 设置服务器端口为80 config.server_port = 80; // 创建http服务器句柄 if (httpd_start(&server, &config) != esp_ok) { printf("error starting server!\n"); return; }
2、 注册 uri处理器
在web服务器启动后,我们需要为不同的uri注册处理器函数。当web服务器接收到请求时,会根据请求的uri选择相应的处理器函数进行处理。在esp-idf中,我们可以使用httpd_register_uri_handler函数注册uri处理器。该函数的原型如下
esp_err_t httpd_register_uri_handler(httpd_handle_t hd, const httpd_uri_t *uri)
其中,hd参数为http服务器句柄;uri参数为包含uri路径、http方法、处理函数等信息的结构体指针。例如:
static const httpd_uri_t echo = { .uri = "/", .method = http_post, .handler = echo_post_handler, .user_ctx = null }; static esp_err_t echo_post_handler(httpd_req_t *req) { char buf[100]; // char ssid[10]; // char pswd[10]; int ret, remaining = req->content_len; while (remaining > 0) { /* read the data for the request */ if ((ret = httpd_req_recv(req, buf, min(remaining, sizeof(buf)))) <= 0) { if (ret == httpd_sock_err_timeout) { /* retry receiving if timeout occurred */ continue; } return esp_fail; } /* send back the same data */ httpd_resp_send_chunk(req, buf, ret); remaining -= ret; esp_err_t e = httpd_query_key_value(buf,"ssid",wifi_name,sizeof(wifi_name)); if(e == esp_ok) { printf("ssid = %s\r\n",wifi_name); } else { printf("error = %d\r\n",e); } e = httpd_query_key_value(buf,"password",wifi_password,sizeof(wifi_password)); if(e == esp_ok) { printf("pswd = %s\r\n",wifi_password); } else { printf("error = %d\r\n",e); } /* log data received */ esp_logi(tag, "=========== received data =========="); esp_logi(tag, "%.*s", ret, buf); esp_logi(tag, "===================================="); } // end response httpd_resp_send_chunk(req, null, 0); if(strcmp(wifi_name ,"\0")!=0 && strcmp(wifi_password,"\0")!=0) { xsemaphoregive(ap_sem); esp_logi(tag, "set wifi name and password successfully! goto station mode"); } return esp_ok; }
html的网页如下:这个网页包含了按钮的定义,以及发送json格式的数据。
最后送json数据的时候,要用json.stringify方法格式化data,否则esp32解析json会报错,此处一定要注意!!!
整体html界面非常简单,没有基础的也很容易读懂,里面写了一个js函数,该函数是在点击按钮的时候触发,功能主要是读取文本框输入的数据,将数据封装为json格式,然后post发送数据,xhttp.open(“post”, “/wifi_data”, true);中的url “/wifi_data”和esp32服务端中的定义要一致,否则是无法成功的。
<!doctype html> <head> <meta charset="utf-8"> <title>web server system</title> </head> <table class="fixed" border="5"> <col width="1000px" /><col width="500px" /> <tr><td> <h2 style=" text-align:center;"> **** web server ***</h2> <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" onclick="send_wifi()">提交</button> </div> </td><td> <table border="10"> <tr> <td> <label for="newfile">upload a file</label> </td> <td colspan="2"> <input id="newfile" type="file" onchange="setpath()" style="width:100%;"> </td> </tr> <tr> <td> <label for="filepath">set path on server</label> </td> <td> <input id="filepath" type="text" style="width:100%;"> </td> <td> <button id="upload" type="button" onclick="upload()">upload</button> </td> </tr> </table> </td></tr> </table> <script> function setpath() { var default_path = document.getelementbyid("newfile").files[0].name; document.getelementbyid("filepath").value = default_path; } function upload() { var filepath = document.getelementbyid("filepath").value; var upload_path = "/upload/" + filepath; var fileinput = document.getelementbyid("newfile").files; /* max size of an individual file. make sure this * value is same as that set in file_server.c */ var max_file_size = 200*1024; var max_file_size_str = "200kb"; if (fileinput.length == 0) { alert("no file selected!"); } else if (filepath.length == 0) { alert("file path on server is not set!"); } else if (filepath.indexof(' ') >= 0) { alert("file path on server cannot have spaces!"); } else if (filepath[filepath.length-1] == '/') { alert("file name not specified after path!"); } else if (fileinput[0].size > 200*1024) { alert("file size must be less than 200kb!"); } else { document.getelementbyid("newfile").disabled = true; document.getelementbyid("filepath").disabled = true; document.getelementbyid("upload").disabled = true; var file = fileinput[0]; var xhttp = new xmlhttprequest(); xhttp.onreadystatechange = function() { if (xhttp.readystate == 4) { if (xhttp.status == 200) { document.open(); document.write(xhttp.responsetext); document.close(); } else if (xhttp.status == 0) { alert("server closed the connection abruptly!"); location.reload() } else { alert(xhttp.status + " error!\n" + xhttp.responsetext); location.reload() } } }; xhttp.open("post", upload_path, true); xhttp.send(file); } } 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>
static esp_err_t html_default_get_handler(httpd_req_t *req) { // /* send html file header */ // httpd_resp_sendstr_chunk(req, "<!doctype html><html><body>"); /* get handle to embedded file upload script */ extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start"); extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end"); const size_t upload_script_size = (upload_script_end - upload_script_start); /* add file upload form and script which on execution sends a post request to /upload */ httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size); /* send remaining chunk of html file to complete it */ httpd_resp_sendstr_chunk(req, "</body></html>"); /* send empty chunk to signal http response completion */ httpd_resp_sendstr_chunk(req, null); return esp_ok; } httpd_uri_t html_default = { .uri = "/", // match all uris of type /path/to/file .method = http_get, .handler = html_default_get_handler, .user_ctx = "html" // pass server data as context }; httpd_register_uri_handler(server, &html_default);
这里要特别注意:
1)、.uri = "/",这个表示当你打开网页的ip地址后第一个要显示的页面,也就是要放到根目录下("/"也就是根目录)。
2)、esp32可以直接将html的网页编译进来不需要转为数组,但在cmakelist.txt文件中需要embed_files upload_script.html这样的形式引入网页文件。这个html编译出出来的文本文件怎么使用呢。wifi.html编译出来一般名称是默认的_binary_名称_类型_start。这个指针代编译出来文件的起始地址。_binary_名称_类型_end,代表结束地址。wifi.html的引用方式如下。通过以下的方式就可以获得html这个大数组。
extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start"); extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end"); const size_t upload_script_size = (upload_script_end - upload_script_start); /* add file upload form and script which on execution sends a post request to /upload */ httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size);
3、实现uri处理函数
在注册uri处理器后,我们需要实现对应的处理器函数。uri处理器函数的原型为:
typedef esp_err_t (*httpd_uri_func_t)(httpd_req_t *req);
如上面示例中的:
static esp_err_t html_default_get_handler(httpd_req_t *req)
4、处理http请求
在uri处理器函数中,我们可以通过http请求信息结构体指针httpd_req_t获取http请求的各种参数和数据。以下是一些常用的http请求处理函数:
httpd_req_get_hdr_value_str:获取http请求头中指定字段的值(字符串格式)
httpd_req_get_url_query_str:获取http请求url中的查询参数(字符串格式)
httpd_query_key_value:解析http请求url中的查询参数,获取指定参数名的值(字符串格式)
httpd_req_recv:从http请求接收数据
httpd_req_send:发送http响应数据
httpd_resp_set_type:设置http响应内容的mime类型
httpd_resp_send_chunk:分块发送http响应数据。
例如,以下是一个uri处理器函数的示例,用于处理/echo路径的post请求:
static esp_err_t echo_post_handler(httpd_req_t *req) { char buf[1024]; int ret, remaining = req->content_len; // 从http请求中接收数据 while (remaining > 0) { ret = httpd_req_recv(req, buf, min(remaining, sizeof(buf))); if (ret <= 0) { if (ret == httpd_sock_err_timeout) { // 处理超时 httpd_resp_send_408(req); } return esp_fail; } // 处理接收到的数据 // ... remaining -= ret; } // 发送http响应 httpd_resp_set_type(req, httpd_type_text); httpd_resp_send(req, "received data: ", -1); httpd_resp_send_chunk(req, buf, req->content_len); httpd_resp_send_chunk(req, null, 0); return esp_ok; }
5、 发送响应
在uri处理函数中,可以使用httpd_resp_send()函数将响应发送回客户端。该函数需要传入一个httpd_req_t结构体作为参数,该结构体表示http请求和响应。
例如,在上面的hello_get_handler处理函数中,可以使用httpd_resp_send()函数将“hello, world!”字符串作为响应发送回客户端:
static esp_err_t hello_get_handler(httpd_req_t *req) { const char* resp_str = "hello, world!"; httpd_resp_send(req, resp_str, strlen(resp_str)); return esp_ok; }
二、主要使用api的说明
1. httpd_register_uri_handler
用于将http请求的uri路由到处理程序。这个函数接收两个参数:httpd_handle_t类型的http服务器句柄和httpd_uri_t类型的uri配置。
2. httpd_handle_t
httpd_handle_t是http服务器的一个句柄,它是通过httpd_start函数创建的。而httpd_uri_t则定义了http请求的uri信息,包括uri路径、http请求方法和处理函数等。
3. httpd_query_key_value获取变量值
httpd_query_key_value 用于从查询字符串中获取指定键的值。查询字符串是指url中?后面的部分,包含多个键值对,每个键值对之间使用&分隔。例如,对于以下url:
http://192.168.1.1/path/to/handler?key1=value1&key2=value2
获取其中的:
esp_err_t httpd_query_key_value(const char *query, const char *key, char *buf, size_t buf_len);
这是一个使用示例
char query_str[] = "key1=value1&key2=value2"; char key[] = "key1"; char value[16]; if (httpd_query_key_value(query_str, key, value, sizeof(value)) == esp_ok) { printf("value=%s\n", value); } else { printf("key not found\n"); }
4. 获取get参数示例
下面定义的 handler 演示了如何从请求参数里解析 字符串param1和整型变量param2:
esp_err_t index_handler(httpd_req_t *req) { char* query_str = null; char param1_value[10] = {0}; int param2_value=0; query_str = strstr(req->uri, "?"); if(query_str!=null){ query_str ++; httpd_query_key_value(query_str, "param1", param1_value, sizeof(param1_value)); char param2_str[10] = {0}; httpd_query_key_value(query_str, "param2", param2_str, sizeof(param2_str)); param2_value = atoi(param2_str); } char resp_str[50] = {0}; snprintf(resp_str, sizeof(resp_str), "param1=%s, param2=%d", param1_value, param2_value); httpd_resp_send(req, resp_str, strlen(resp_str)); return esp_ok; }
5. 获取post参数示例
下面的示例代码中根据httpd_req_t的content_len来分配一个缓冲区,并解析请求中的post参数:
esp_err_t post_demo_handler(httpd_req_t *req) { char post_string[64]; int post_int=0; if (req->content_len > 0) { // 从请求体中读取post参数 char *buf = malloc(req->content_len + 1); int ret = httpd_req_recv(req, buf, req->content_len); if (ret <= 0) { // 接收数据出错 free(buf); return esp_fail; } buf[req->content_len] = '\0'; // 解析post参数 char *param_str; param_str = strtok(buf, "&"); while (param_str != null) { char *value_str = strchr(param_str, '='); if (value_str != null) { *value_str++ = '\0'; if (strcmp(param_str, "post_string") == 0) { strncpy(post_string, value_str, sizeof(post_string)); } else if (strcmp(param_str, "post_int") == 0) { post_int = atoi(value_str); } } param_str = strtok(null, "&"); } free(buf); } // 将结果打印输出 printf("post_string=%s, post_int=%d\n", post_string, post_int); // 返回成功 httpd_resp_send(req, null, 0); return esp_ok; } httpd_uri_t post_uri = { .uri = "/post", .method = http_post, .handler = post_demo_handler, .user_ctx = null };
到此这篇关于搭建http的webserver的服务器的文章就介绍到这了,更多相关http的webserver服务器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论