首先在Ubuntu上利用Flask搭建一個簡單的服務器,并且打開
利用配置好ESP32的Arduino開發環境后自帶的"WiFi.h"搭建一個簡單的客戶端
#include <WiFi.h>
const char *ssid = "****";
const char *password = "********";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Try Connecting to ");
Serial.println(ssid);
// Connect to your wi-fi modem
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected successfully");
}
void loop() {
// put your main code here, to run repeatedly:
WiFiClient client;
Serial.println("try");
if (client.connect("192.168.4.126", 8080)) //80為一般網站的埠號
{
Serial.println("succeeded!");
String dataToSend = "Hello!";
//向服務器發送請求頭,請求該網頁的http檔案 具體內容可以百度:http 請求行 格式
String request = (String)("GET / HTTP/1.1\r\n")+
"Content-Length: " + dataToSend.length() + "\r\n" +
"Connection: Keep Alive\r\n\r\n" +
dataToSend;
client.print(request);
//client.print("");
//以下代碼將收到的網頁資料按行列印輸出
//如果是瀏覽器,則會將收到的html檔案渲染成我們一般看到的網頁
delay(100);
while (client.available()) //如果已連接或有收到的未讀取的資料
{
if (client.available()) //如果有資料可讀取
{
String line = client.readStringUntil('\n'); //按行讀取資料
if(line.indexOf("Time called is ") != -1)
{
Serial.println(line);
delay(5);
}
else continue;
}
}
client.stop(); //關閉當前連接
}
else
{
Serial.println("訪問失敗");
client.stop(); //關閉當前連接
}
delay(1000);
}
Flask服務器
from flask import Flask
from flask import request
from flask import make_response
from flask import send_from_directory
import time
import json
import os
import socket
app = Flask(__name__)
@app.route('/')
def returnTime():
timeStamp = time.time()
stringToReturn = "Time called is :%f"%timeStamp
print(request.get_data().decode())
# print(stringToReturn)
return json.dumps(stringToReturn)
if __name__ == '__main__':
#獲取本機電腦名
myname = socket.getfqdn(socket.gethostname( ))
#獲取本機ip
myaddr = socket.gethostbyname(myname)
print(myaddr)
app.run(host = '0.0.0.0', port = 8080, debug=True)
其中的重點是服務器回傳的資料本身會包含一些response header的內容,但是在單片機的簡單客戶端中這些資料并沒有用處,所以使用一些語法將這個資料去掉
if(line.indexOf("Time called is ") != -1)
{
Serial.println(line);
delay(5);
}
假如只是使用上面的方式進行資料接收的話將無法實作服務器接收到下位機(也就是ESP32發出的資料)從而無法實作互相通信功能
此時需要撰寫更詳細規范的http請求如下
String dataToSend = "Hello!";
//向服務器發送請求頭,請求該網頁的http檔案 具體內容可以百度:http 請求行 格式
String request = (String)("GET / HTTP/1.1\r\n")+
"Content-Length: " + dataToSend.length() + "\r\n" +
"Connection: Keep Alive\r\n\r\n" +
dataToSend;
client.print(request);
此時實作的效果為
下位機端:

服務器端:

此時得到的字串是byte型別的字串,是在瀏覽器和服務器之間發送資料的常見字串形式,于普通字串的互相轉換方式為
str.encode('utf-8')
bytes.decode('utf-8')
decode之后輸出的字串為

以上就實作了ESP32作為Client與Server的資料收發
給一個http請求的參考
String postRequest =(String)("POST ") + "/ HTTP/1.1\r\n" +
"Content-Type: application/json;charset=utf-8\r\n" +
"Host: " + host + ":" + httpPort + "\r\n" +
"Content-Length: " + length + "\r\n" +
"Connection: Keep Alive\r\n\r\n" +
data+"\r\n";
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/293426.html
標籤:其他
上一篇:電信運營商基于 MQTT 協議 構建千萬級 IoT 設備管理平臺
下一篇:藍橋杯物聯網教程匯總
