공공데이터 미세먼지 구현 esp32 코드
본문 바로가기
카테고리 없음

공공데이터 미세먼지 구현 esp32 코드

by 하고싶은거하는여자 2024. 11. 9.
728x90
반응형
#include <WiFi.h>
#include <time.h>
const char* ssid = "iot2024";          // WiFi 네트워크 이름(SSID) 입력
const char* password = "a123456789";  // WiFi 네트워크 비밀번호 입력
const int httpPort = 80;
const char* apiKey = "lDEdd33YlrBTh3cK%2BWHVYFP1Yc6UviDPFZP%2BVRcFaSqFtzZs7W%2BMXx5wmG1J08ejVd5nmwPQ15qDQmEXbKPqvg%3D%3D";
const char* version = "&ver=1.0";
const char* server = "apis.data.go.kr";
const char* stationName = "산격동";  //지명
const char* returnType = "xml";
const char* numOfRows = "1";
const char* pageNo = "1";
const char* dataTerm = "DAILY";

WiFiClient client;

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  String a[3];
  int i = 0;
  String dateNtime;
  String pm10Val;
  String pm10Grade;
  String tmp_str;
  static int IntervalReq = 600;  
  if (IntervalReq++ >= 600) {  //600초 간격으로 data요청
    IntervalReq = 0;
    Requesthttp();
  }
  delay(50);
  while (client.available()) {
    String line = client.readStringUntil('\n');
    Serial.println(line);
  }
  delay(1000);
}

void Requesthttp() {
  if (client.connect(server, httpPort)) {
    Serial.println("\nSuccessed connection, and request http protocol");
    client.print(String("Get /B552584/ArpltnInforInqireSvc"));
    client.print(String("/getMsrstnAcctoRltmMesureDnsty?serviceKey="));
    client.print(String(apiKey));
    client.print(String("&returnType=") + String(returnType));
    client.print(String("&numOfRows=") + String(numOfRows));
    client.print(String("&pageNo=") + String(pageNo));
    client.print(String("&stationName=") + urlencode(String(stationName)));
    client.print(String("&dataTerm=") + String(dataTerm));
    client.print(String(version));
    client.print(String(" HTTP/1.1\r\n"));
    client.print(String("Host: ") + String(server) + String("\r\n"));
    client.print(String("Connection: close\r\n"));
    client.print(String("\r\n\r\n"));
  } else {
    Serial.println("\nfailed connection");
  }
}

String urlencode(String str) {
  String encodedString = "";
  char c;
  char code0;
  char code1;
  for (int i = 0; i < str.length(); i++) {
    c = str.charAt(i);
    if (c == ' ') {
      encodedString += '+';
    } else if (isalnum(c)) {
      encodedString += c;
    } else {
      code1 = (c & 0xf) + '0';
      if ((c & 0xf) > 9) {
        code1 = (c & 0xf) - 10 + 'A';
      }
      c = (c >> 4) & 0xf;
      code0 = c + '0';
      if (c > 9) {
        code0 = c - 10 + 'A';
      }
      encodedString += '%';
      encodedString += code0;
      encodedString += code1;
    }
  }
  return encodedString;
}
728x90
반응형

댓글