参考引用文章:
《ESP32 开发笔记(十一)使用 ESP32 做为 WebServer》
https://blog.youkuaiyun.com/qq_27114397/article/details/89643232 @InfiniteYuan
《HTML Response ContentType 大全》
https://www.cnblogs.com/tuyile006/archive/2009/03/05/1403857.html @小y
有项目需求,在esp32中调用jquery和JavaScript来美化页面,因为esp32空间不大,所以用了jquery mini。
因为网页访问的时候,是访问不同目录下的文件,如有文件结构
【思路】
但是在ESP32中没有做文件系统,所以干脆截取URI的目录,直接解析,然后通过response的方式把相关数据返回回去。
但是首先要把网页收进代码中。如果能顺便压缩下代码也是极好的。
步骤一:把网页放到程序中
参考《ESP32 开发笔记(十一)使用 ESP32 做为 WebServer》https://blog.youkuaiyun.com/qq_27114397/article/details/89643232 @InfiniteYuan
ponit:把文件用gzip打包,然后用filetoarray做成 *.h的文件。
gzip和gcc在mingw32的环境中已经有了,直接用就可以了,
filetoarray的代码见下:
// filetoarray.c
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp;
char *buffer;
long flen;
char *fname;
char pname[1024];
if ( argc == 2 ) {
fname = argv[1];
strcpy(pname, fname);
char *dot = strchr(pname, '.');
while (dot != NULL) {
*dot = '_';
dot = strchr(pname, '.');
}
} else {
printf("Filename not supplied\n");
return 1;
}
fp = fopen(fname, "rb");
fseek(fp, 0, SEEK_END);
flen = ftell(fp);
rewind(fp);
buffer = (char *)malloc((flen + 1) * sizeof(char));
fread(buffer, flen, 1, fp);
fclose(fp);
printf("\n//File: %s, Size: %lu\n", fname, flen);
printf("#define %s_len %lu\n", pname, flen);
printf("const uint8_t %s[] PROGMEM = {\n", pname);
long i;
for (i = 0; i < flen; i++) {
printf(" 0x%02X", (unsigned char)(buffer[i]));
if (i < (flen - 1)) {
printf(",");
}
if ((i % 16) == 15) {
printf("\n");
}
}
printf("\n};\n\n");
free(buffer);
return 0;
}
把上述文件保存成filetoarray.c文件,然后再mingw32环境中直接调用gcc即可
$ gcc filetoarray.c -o filetoarray
然后把所有的网页文件用gzip压缩一下,以index.css为例,直接运行gzip 加文件名,要注意的是:生成压缩包之后会删除源文件。
$ gzip index.css
然后调用filetoarray生成 *.h文件
$ ./filetoarray.exe index.css.gz > index_css.h
可以浏览一下index_css.h文件
//File: index.css.gz, Size: 1612
#define index_css_gz_len 1612
const uint8_t index_css_gz[] PROGMEM = {
0x1F, 0x8B, 0x08, 0x08, 0xFA, 0x12, 0xB5, 0x5E, 0x00, 0x03, 0x69, 0x6E, 0x64, 0x65, 0x78, 0x2E,//...
};
可以看到把原本的网页换成了数组形式的存在,
这个时候可以把uint8_t替换掉,在esp32中是 unsigned char,
PROGMEM这个标识符不存在,但是const之后已经是把这个网页放在代码区中的,所以可以直接删掉。
步骤二:在webserver中返回网页
做法比较通俗暴力,但是能用。
引用example/protocols/http_server/simple的工程,
则把涉及到用到的uri全部注册进去
httpd_uri_t basic_handlers[] = {
{
.uri = "/",
.method = HTTP_GET,
.handler = index_get_handler,
.user_ctx = NULL,
},
{
.uri = "/js/index.js",
.method = HTTP_GET,
.handler = link_js_indexjs_handler,
.user_ctx = NULL,
},
{
.uri = "/css/index.css",
.method = HTTP_GET,
.handler = link_css_indexcss_handler,
.user_ctx = NULL,
},
{
.uri = "/js/jquery.min.js",
.method = HTTP_GET,
.handler = link_js_jqueryminjs_handler,
.user_ctx = NULL,
},
}
// ...
httpd_handle_t start_webserver(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.stack_size = 6144;
// Start the httpd server
ESP_LOGW(TAG, "Starting server on port: '%d'", config.server_port);
if (httpd_start(&server, &config) == ESP_OK)
{
// Set URI