HTTPS Web Server

Agree007
Posts: 102
Joined: Mon Sep 18, 2017 7:11 pm
Location: Copenhagen

HTTPS Web Server

Postby Agree007 » Sat Jun 02, 2018 8:22 am

Looking for a light implementering of an HTTPS Web Server on the ESP32 using Arduino ide, with small examples.

So hope someone have one to share?

Thx in advance for your support.

1163167506
Posts: 30
Joined: Mon Jun 11, 2018 5:52 am

Re: HTTPS Web Server

Postby 1163167506 » Wed Jun 13, 2018 2:59 am

Example 1
#include<WiFi.h>

const char *ssid = "Charlie Testing AP";
const char *password = "12345678";
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
Serial.println();

Serial.print("Setting soft-AP ... ");

IPAddress softLocal(192,168,128,1);
IPAddress softGateway(192,168,128,1);
IPAddress softSubnet(255,255,255,0);

WiFi.softAPConfig(softLocal, softGateway, softSubnet);

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());

}

void loop()
{
WiFiClient client = server.available();
if (client)
{
Serial.println("\n[Client connected]");
while (client.connected())
{
// read line by line what the client (web browser) is requesting
if (client.available())
{

client.println(prepareHtmlPage());

break;

}
}
delay(1); // give the web browser time to receive the data

// close the connection:
client.stop();
Serial.println("[Client disonnected]");
}


}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
String htmlPage =
String("HTTP/1.1 200 OK\r\n") +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" + // the connection will be closed after completion of the response
"Refresh: 5\r\n" + // refresh the page automatically every 5 sec
"\r\n" +
"<!DOCTYPE HTML>" +
"<html>" +
"Analog input: " + String(analogRead(A0)) +
"</html>" +
"\r\n";
return htmlPage;
}


打印:
*******************************************************************
Example 2:
#include<WiFi.h>

const char *ssid = "Charlie Testing AP";
const char *password = "12345678";
WiFiServer server(80);
void setup()
{
Serial.begin(115200);
Serial.println();

Serial.print("Setting soft-AP ... ");

IPAddress softLocal(192,168,128,1);
IPAddress softGateway(192,168,128,1);
IPAddress softSubnet(255,255,255,0);

WiFi.softAPConfig(softLocal, softGateway, softSubnet);

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());

}

void loop() {
// 监听客户端传来的数据
WiFiClient client = server.available();
if (client) {
Serial.println("new client");
// 一个Http请求结尾必须带有回车换行
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// 如果收到空白行,说明http请求结束,并发送响应消息
if (c == '\n' && currentLineIsBlank) {
// 发送标准的HTTP响应
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// 添加一个meta刷新标签, 浏览器会每5秒刷新一次
// 如果此处刷新频率设置过高,可能会出现网页的卡死的状况
client.println("<meta http-equiv=\"refresh\" content=\"5\">");
// 输出每个模拟口读到的值
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// 已经开始一个新行
currentLineIsBlank = true;
}
else if (c != '\r') {
// 在当前行已经得到一个字符
currentLineIsBlank = false;
}
}
}
// 等待浏览器接收数据
delay(1);
// 断开连接
client.stop();
Serial.println("client disonnected");
}
}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
String htmlPage =
String("HTTP/1.1 200 OK\r\n") +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" + // the connection will be closed after completion of the response
"Refresh: 5\r\n" + // refresh the page automatically every 5 sec
"\r\n" +
"<!DOCTYPE HTML>" +
"<html>" +
"Analog input: " + String(analogRead(A0)) +
"</html>" +
"\r\n";
return htmlPage;
}

打印:
analog input 0 is 4095
analog input 1 is 0
analog input 2 is 4095
analog input 3 is 0
analog input 4 is 4095
analog input 5 is 0

后台串口打印:(该打印是 前台web 给后台发送的数据)
new client
GET / HTTP/1.1
Host: 192.168.4.1
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://192.168.4.1/
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9

client disonnected
*******************************************************************
Example 3
web通信
通过url带参数

#include <WiFi.h>

//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiAPPSK[] = "12345678";

/////////////////////
// Pin Definitions //
/////////////////////
const int LED_PIN = 5; // Thing's onboard, green LED
const int ANALOG_PIN = A0; // The only analog pin on the esp8266
const int DIGITAL_PIN = 12; // Digital pin to be read

WiFiServer server(80);

void setup()
{
initHardware();
setupWiFi();
server.begin();
}

void loop()
{
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Read the first line of the request
String req = client.readStringUntil('\r');
Serial.println(req);
client.flush();

// Match the request
int val = -1; // We'll use 'val' to keep track of both the
// request type (read/set) and value if set.
if (req.indexOf("/led/0") != -1)
val = 0; // Will write LED low
else if (req.indexOf("/led/1") != -1)
val = 1; // Will write LED high
else if (req.indexOf("/read") != -1)
val = -2; // Will print pin reads
// Otherwise request will be invalid. We'll say as much in HTML

// Set GPIO5 according to the request
if (val >= 0)
digitalWrite(LED_PIN, val);

client.flush();

// Prepare the response. Start with the common header:
String s = "HTTP/1.1 200 OK\r\n";
s += "Content-Type: text/html\r\n\r\n";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
// If we're setting the LED, print out a message saying we did
if (val >= 0)
{
s += "LED is now ";
s += (val)?"high":"low";
}
else if (val == -2)
{ // If we're reading pins, print out those values:
s += "Analog Pin = ";
s += String(analogRead(ANALOG_PIN));
s += "<br>"; // Go to the next line.
s += "Digital Pin 12 = ";
s += String(digitalRead(DIGITAL_PIN));
}
else
{
s += "Invalid Request.<br> Try /led/1, /led/0, or /read.";
}
s += "</html>\n";

// Send the response to the client
client.print(s);
delay(1);
Serial.println("Client disonnected");

// The client will actually be disconnected
// when the function returns and 'client' object is detroyed
}

void setupWiFi()
{
WiFi.mode(WIFI_AP);

// Do a little work to get a unique-ish name. Append the
// last two bytes of the MAC (HEX'd) to "Thing-":
String AP_NameString = "ESP8266 Thing ";

char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, AP_NameString.length() + 1, 0);

for (int i=0; i<AP_NameString.length(); i++)
AP_NameChar = AP_NameString.charAt(i);

WiFi.softAP(AP_NameChar, WiFiAPPSK);

Serial.println();
Serial.print ( "IP address: " );
Serial.println ( WiFi.softAPIP() );

}

void initHardware()
{
Serial.begin(115200);
pinMode(DIGITAL_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Don't need to set ANALOG_PIN as input,
// that's all it can be.
}

*******************************************************************
Example 4
web 调试:
#include<WiFi.h>

const char *ssid = "Charlie Testing AP";
const char *password = "12345678";
WiFiServer server(80);
String readString="";
int Light=2;
int Sensor=A0;
WiFiClient client;

void setup()
{
Serial.begin(115200);
Serial.println();

Serial.print("Setting soft-AP ... ");

IPAddress softLocal(192,168,128,1);
IPAddress softGateway(192,168,128,1);
IPAddress softSubnet(255,255,255,0);

WiFi.softAPConfig(softLocal, softGateway, softSubnet);

WiFi.softAP(ssid, password);

IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());

}

void loop() {
// 监听连入的客户端
client = server.available();
if (client) {
Serial.println("new client");
boolean currentLineIsBlank = false;
while (client.connected()) {
Serial.println("\n #####zf connected");
if (client.available()) {
Serial.println("\n #####zf available");
char c = client.read();
readString += c;
if (c == '\n') {
Serial.println("\n #####zf get nnnnn");
Serial.println(readString);

//检查收到的信息中是否有”on”,有则开灯
if(readString.indexOf("?on") >0) {
digitalWrite(Light, HIGH);
Serial.println("Led On");
break;
}
//检查收到的信息中是否有”off”,有则关灯
if(readString.indexOf("?off") >0) {
digitalWrite(Light, LOW);
Serial.println("Led Off");
break;
}
//检查收到的信息中是否有”getBrightness”,有则读取光敏模拟值,并返回给浏览器
if(readString.indexOf("?getBrightness") >0) {
client.println(analogRead(Sensor));
break;
}
//发送HTML文本
Serial.println("\n #####zf begin send html");
client.println(testSendHTML());
//client.println(prepareHtmlPage());
Serial.println("\n #####zf end send html");
break;
}
}
else
{
Serial.println("\n #####zf not ava");
}
}
delay(5);
client.stop();
Serial.println("client disonnected");
readString="";
}
}

// 用于输出HTML文本的函数
void SendHTML()
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html><head><meta charset=\"UTF-8\"><title>OpenJumper!Arduino Web Server</title><script type=\"text/javascript\">");
client.println("function send2arduino(){var xmlhttp;if (window.XMLHttpRequest)xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");element=document.getElementById(\"light\");if (element.innerHTML.match(\"Turn on\")){element.innerHTML=\"Turn off\"; xmlhttp.open(\"GET\",\"?on\",true);}else{ element.innerHTML=\"Turn on\";xmlhttp.open(\"GET\",\"?off\",true); }xmlhttp.send();}");
client.println("function getBrightness(){var xmlhttp;if (window.XMLHttpRequest)xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200)document.getElementById(\"brightness\").innerHTML=xmlhttp.responseText;};xmlhttp.open(\"GET\",\"?getBrightness\",true); xmlhttp.send();}window.setInterval(getBrightness,1000);</script>");
client.println("</head><body><div align=\"center\"><h1>Arduino Web Server</h1><div>brightness:</div><div id=\"brightness\">");
client.println(analogRead(Sensor));
client.println("</div><button id=\"light\" type=\"button\" onclick=\"send2arduino()\">Turn on</button><button type=\"button\" onclick=\"alert('OpenJumper Web Server')\">About</button></div></body></html>");
}

String testSendHTML()
{
String htmlPage =
String("HTTP/1.1 200 OK\r\n") +
"Content-Type: text/html\r\n" +
"Connection: close\r\n" + // the connection will be closed after completion of the response
"\r\n" +
"<!DOCTYPE HTML>" +
"<html><head><meta charset=\"UTF-8\"><title>OpenJumper!Arduino Web Server</title><script type=\"text/javascript\">" +
"function send2arduino(){var xmlhttp;if (window.XMLHttpRequest)xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");element=document.getElementById(\"light\");if (element.innerHTML.match(\"Turn on\")){element.innerHTML=\"Turn off\"; xmlhttp.open(\"GET\",\"?on\",true);}else{ element.innerHTML=\"Turn on\";xmlhttp.open(\"GET\",\"?off\",true); }xmlhttp.send();}" +
"function getBrightness(){var xmlhttp;if (window.XMLHttpRequest)xmlhttp=new XMLHttpRequest();else xmlhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200)document.getElementById(\"brightness\").innerHTML=xmlhttp.responseText;};xmlhttp.open(\"GET\",\"?getBrightness\",true); xmlhttp.send();}window.setInterval(getBrightness,1000);</script>" +
"</head><body><div align=\"center\"><h1>Arduino Web Server</h1><div>brightness:</div><div id=\"brightness\">" +
String(analogRead(Sensor)) +
"</div><button id=\"light\" type=\"button\" onclick=\"send2arduino()\">Turn on</button><button type=\"button\" onclick=\"alert('OpenJumper Web Server')\">About</button></div></body></html>";
return htmlPage;
}

显示页面:

*******************************************************************

Who is online

Users browsing this forum: No registered users and 43 guests