상세 컨텐츠

본문 제목

아두이노 esp-01 http 통신(WiFiEsp.h)

아두이노

by nownow 2025. 1. 13. 15:16

본문

https://github.com/present0917/arduinoFingerPrint

해당 프로젝트를 진행하며 esp-01을 활용한 http 클라이언트 구현 중 내용정리 포스팅 입니다.

 

웹서버에 http request를 보내고 response를 처리하기 위해 esp-01 모듈을 구매하고

WiFiEsp.h 라이브러리를 사용했습니다.

https://github.com/bportaluri/WiFiEsp

라이브러리 git repo의 examples와 포럼 글을 참고해 작성했습니다.

void httpRequest() {
  client.stop();
  client.flush();
  client.setTimeout(10000);
  if (client.connect(서버ip, 포트번호)) {
    client.println("GET /api/bus/1 HTTP/1.1");
    //client.println("Host: ");
    client.println("Connection: close");
    client.println();
    lastConnectionTime = millis();
  } else {
    Serial.println("Connection failed");
  }
}

get 요청입니다.

void postmethod() {
  String postData;
  postData = "{\"busId\": \"" + padNum + "\", \"Id\": \"" + postId + "\", \"message\": \"" + "test" + "\"}";
  int contentLength = postData.length();
  
  if (client.connect(SERVER, HTTPPORT)) {
    // Send HTTP POST request
    client.print("POST ");
    client.print(PATH);
    client.print(" HTTP/1.1\r\n");
    client.print("Host: ");
    client.print(SERVER);
    client.print("\r\n");
    client.print("Content-Type: application/json\r\n");
    client.print("Content-Length: ");
    client.print(contentLength);
    client.print("\r\n\r\n");
    client.print(postData);
    //client.print("\r\n");
    // Close connection
  } else {
    Serial.println("Failed to connect to server");
  }
  delay(1000);
}

post 요청입니다.

각 메서드의 양식에 따라 \r\n도 신경써서 작성해주셔야 합니다.

 

void getbody() {
  bool isBody = false;
  String line;
  while (client.available()) {
    line = client.readStringUntil('\n');
    if (line == "\r") {
      isBody = true;  // 헤더가 끝나고 본문이 시작됨
      continue;       // 본문의 첫 줄을 읽기 위해 계속
    }
    if (isBody) {
      DynamicJsonDocument doc(1024);
      //Serial.println(line);  // 본문 출력
      DeserializationError error = deserializeJson(doc, line);
      String response = doc["type"];
      if (response!="null"){
        Serial.println(response);
      }
      }
    } 
  }
}

response를 파싱해서 저장하는 부분입니다.