728x90
HTTP POST
Reference들을 통하여 ESP32 HTTP post 전송 코드를 짬
-
#include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> #include <HttpClient.h> const char* ssid = "juzeor"; //wift 아이디 const char* password = "space!"; // wifi 비번 const char* serverName = "http://00.000.00.00:0000/{server post get}"; // 웹서버주소 {server post get} : 해당 부분은 FAST API부분에서 POST를 받는 주소 부분임 int value; int sensor_number = 12; // 임의의 숫자를 넣어주었다. int analog = 25; // esp에 연결된 핀 번호 IPAddress hostIp(00, 000, 00, 00); //웹서버의 ip 주소 int SERVER_PORT = 5000; // 웹서버 포트 번호 WiFiClient client; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); // 와이파이 접속 while (WiFi.status() != WL_CONNECTED) { //Check for the connection delay(1000); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); } void loop() { if(WiFi.status()== WL_CONNECTED){ //Check WiFi connection status value = analogRead(analog); // esp32에서 읽은 co2 값을 value에 저장한다. HTTPClient http; http.begin(serverName); //Specify destination for HTTP request http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header, Json형식의 타입이다. String httpRequestData = "sensor_number="+String(sensor_number)+"&value="+String(value); // 가장 중요한 Json 데이터를 입력하는 부분이다 = 의 왼쪽이 key값 오른쪽이 value 값이고 &를 기준으로 쌍이 나뉘어진다. Serial.println(httpRequestData); //시리얼 모니터에 Json 형식의 데이터를 찍어준다. int httpResponseCode = http.POST(httpRequestData); //Send the actual POST request if(httpResponseCode>0){ // 잘 전송되었으면 String response = http.getString(); //Get the response to the request Serial.println(httpResponseCode); //Print return code Serial.println(response); //Print request answer }else{ Serial.print("Error on sending POST: "); Serial.println(httpResponseCode); } http.end(); //Free resources }else{ Serial.println("Error in WiFi connection"); } delay(30000000); //Send a request every 10 seconds }
HTTPClient 관련 설명
#include <HTTPClient.h>
begin - 접속하고 싶은 server 주소
Content-type 별 양식
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header, Json형식의 타입이다. http.addHeader("Content-Type", "application/json"); // Json type http.addHeader("Content-Type", "text/plain");
-
넘겨주는 String이 너무 클 때는 주소 값으로 넘겨줄 수도 있다.
하지만 이 역시 일정 길이 이상을 넘으면 문제가 될 수 있음
- Appdata folder > esp32 > hardware 설치 라이브러리 폴더에 들어가면 해당 내용을 확인할 수 있다
- https://github.com/espressif/arduino-esp32/blob/master/libraries/HTTPClient/src/HTTPClient.cpp#L573 : 원본 라이브러리 코드 확인
int httpResponseCode = http.POST(httpRequestData); int httpResponseCode = http.POST((uint8_t *) httpRequestData.c_str(), httpRequestData.length());
FAST API를 이용한 서버
- 127.0.0.1:5000/docs ⇒ fast api 에서 제공하는 서비스 화면을 확인할 수 있다 손쉽게 관리가 가능!
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
from datetime import datetime
from typing import List, Dict
app = FastAPI()
'''
Type : Json
{
id : str,
array_ : [{
n : int,
data : {
g : str,
h : str}
}]
}
'''
class InnerData(BaseModel):
g: str
h: str
class Number(BaseModel):
n: int
data : InnerData
class Data(BaseModel):
id: str
array_ : List[Number]
class Data_each(BaseModel):
id: str
n: int
m: Measurement
# all channel
@app.post("/{server post get}")
def receive_data(data: Data):
received_id = data.id
received_chm = data.chm
current_time = datetime.now().isoformat()
return {"id": received_id, "n":channel, "time" : current_time}
'''
Type : Text
'''
class TextResponse(BaseModel):
received_text: str
@app.post("/text/", response_model=TextResponse, summary="Process Text (Docs)")
async def process_text(request: Request):
text_body = await request.body()
received_text = text_body.decode()
print(len(received_text))
return TextResponse(received_text=received_text)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5000)
pip install uvicorn
uvicorn main:app --host 0.0.0.0 --port 5000 --reload
Reference
https://juzero-space.tistory.com/26
https://randomnerdtutorials.com/esp32-http-get-post-arduino/
728x90
'Done > With Sensor, Board' 카테고리의 다른 글
[Project 1] 10주 프로젝트 목표 수립하기 (0) | 2024.04.16 |
---|---|
[6dof-pose estimation]DOPE-ROS-D435 DOCKER 파일 만들기 (0) | 2022.07.28 |
Realsense d435 depth 활용 이미지에서 카메라로 부터 3차원 좌표 deproject 2D pixel to 3D points (0) | 2022.07.06 |
Yujin Lidar viewer settings (0) | 2022.03.23 |
Camera calibration (0) | 2022.02.24 |