Arduino, Openweather_nodemcu실습

이도현·2023년 8월 10일
0

아두이노 학습

목록 보기
34/34
#include <WifiMiniCom.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>

const char *ssid = "Campus7_Room4_2.4GHz";
//const char *password = "12345678";
const char *password = NULL;

WifiMiniCom com

String host = "api.openweathermap.org";
String url = "/data/2.5/weather?q=Seoul&APPID=93ec9acd67f5e6dfd08ff43c867eeac&units=metric";

// 디폴트는 켈빈 온도
// 섭씨 온도 = 캘빈 온드 - 273.15

bool request(WiFIClient &client){
	const int port = 80;
	if (!client.connect(host, port))
	{
		Serial.println("connection failed");
		return false;
	}

	Serial.print("Requesting URL: ");
	Serial.println(url);

	client.println("GET " + url + " HTTP/1.1"); // 요청 라인
	client.println("HOST: " + host);  // 헤더
	client.println("Connection: close");  // 헤더
	client.println();  // 헤더 끝 (빈 줄)

	return true;
}

void deserialize(String line){
	StaticJsonDocument<800> doc;

	auto error = deserializeJson(doc, line);
	if (error)
		Serial.print("deserializeJson() faile with code ");
		Serial.println(error.c_str());
		return;
	}

	String w_main = doc["weather"][0]["main"];
	double temp = doc["main"]["temp"].as<double>();
	double humi = doc["main"]["humidity"].as<double>();

	String msg = "weather: " + w_main;
	com.print(0. msg.c_str());
	com.print(1, "T:", temp, ", H:", humi);
}

String response(WiFiClient &client){
	int timeout = millis() + 5000;

	while(client.available() == 0){
		if (timeout - millis() < 0) {
			Serial.println(">>> Client Timeout !");
			client.stop();
			return "";
		}
	}

	bool isBody = false;
	String body = "";

	// find Body section
	while(client.available()){
		String lin = client.readStringUntil('\r');
		line.trim();
		if(line == ""){ // 헤더의 끝을 나타내는 빈 줄
			isBody = true;
			continue;
		}
		Serial.println(line);
		if(isBody){ // 현재 읽은 라인이 Body에 해당
			body = line;
			break;
		}
	}

	Serial.println();
	Serial.println("closing connection");

	return body;
}

void setup() {
	com.init(ssid, password);
}

void loop(){
	WiFiClient client;
	if(request(client)){
		String body = response(client);
		deserialize(body);
	}
	delay(100000);
}
  • OpenApi 클래스
    • web oepn api 호출 지원 클래스
// OpenApi.h
#pragma once

#include <ESP8266WiFi.h>

class OpenApi{
protected:
	String host;
	int port;

public:
	OpenApi(String host, int port = 80);
	String request(String url);
	bool request(WiFIClient &client, String url);
	String response(WiFiClient &client);
};
// OpenApi.cpp
#include "OpenApi.h"

OpenApi::OpenApi (String host, int port) :
	host(host), port(port)
}

bool OpenApi::request(WiFiClient &client, String url){
	if(!client.connect(host,port)){
		Serial.println("connection failed");
		return false;
	}

	Serial.print("Requestiong URL: ");
	Serial.println(url);

	client.println("GET " + URL = " HTTP/1.1");
	client.println("HOST " + host);
	client.println("Connection: close");
	client.println();
	return true;
}

String OpenApi::request(String url){
	WiFiClient client;

	if(!request(client, url)){
		return "";
	}
	return response(client);
}

String OpenApi::response(WiFiClient &client){
	int timeout = millis() + 5000;
	while(client.available() == 0){
		if(timeout - millis() < 0){
			Serial.println(">>> Client Timeout !");
			client.stop();
			return "";
		}
	}
	bool is body = false;
	String body = "";
	while(client.available()){
		String line = client.readStringUntil('\r');
		line.trim();
		if(line == ""){
			isBody = true;
			continue;
		}
		Serial.println(line);
		if(isBody){
			body = line;
			break;
		}
	}
	
	Serial.println();
	Serial.println("closing connection");
	return body;
}
// app.ino
#include <WifiMiniCom.h>
#include <ArduinoJson.h>
#include <OpenApi.h>

const char *ssid = "Campus7_Room4_2.4GHz";
// const char *password = "12345678";
const char *password = NULL;
String host  = "api.openweathermap.org";
String url ="/data/2.5/weather?q=Seoul&APPID=93ec9acd67f5e6d7fd08ff43c857eeac&units=metric";

WifiMiniCom com;
OpenApi api(host);

void deserialize(String line){
	StaticjsonDocument<900> doc;

	auto error = deserializeJson(doc, line);
	if(error)
		Serial.print("deserializeJson() failed with code ");
		Serial.println(error.c_str());
		return;
	}

	String w_main = doc["weather"][0]["main"]
	String temp = doc["main"]["temp"].as<double>();
	String humi = doc["main"]["humadity"].as<double>();
	String msg = w_main;

	String masg = "weather: " + w_main;
	com.print(0, mag, c_str());
	com.print(1, "T: ", temp , ", H:", humi);
}

void setup(){
	com.init(ssid,NULL);
}

void loop(){
	String result = api.request(url);
	if(result != ""){
		deserialize(result);
	}
	delay(100000);
}
profile
좋은 지식 나누어요

0개의 댓글