1-6 从互联网获取数据

现在我们已将ESP8266连接到Wi-Fi网络,我们可以在互联网上接收和发送数据。不仅如此。我们还可以从输入或连接到电路板的传感器读取数据,并将其值发送到互联网。

首先,让我们阅读一些数据以及比当前天气数据更有趣的内容?让我们在 http://www.wunderground.com 上创建一个帐户,然后转到 https://www.wunderground.com/weather/api/d/pricing.htm, 在那里您将以0美元购买一个密钥,如图所示在下图中。填写有关项目的一些数据后,您将获得密钥:

正如您所看到的,使用开发人员密钥,您每分钟有10个有限的呼叫,这意味着您可以每6秒获取一次数据。稍后在代码中,我们将每10秒获取一次数据。

要检查API_KEY,请在浏览器中使用它并检查您是否获得了任何数据。

使用您自己的密钥替换掉 APY_KEY:

在此之后,如果您在浏览器中导航到此链接,

http://api.wunderground.com/api/APY_KEY/coditions/q/NLEindhaven.json

你将从wunderground.com服务器获得JSON格式的响应:

引入 ESP8266WiFi 库和 ESP8266HTTPClient 库,它允许您执行HTTP GET操作以获得与使用浏览器相同的JSON格式消息:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClien.h>

声明您的WI-Fi网络的SSID和密码:

const char * ssid = “Your_WiFi_Name”;
const char * password = “Your_WiFi_Password”;
const String WUNDERGROUND_API_KEY = “YOUR_Wundergtound_API_KEY”;
const String WUNDERGROUND_COUNTRY = “NL”;
const String WUNDERGROUND_CITY = “Eindhoven”;

构造将用于获取数据的URL:

const String dataURL = http://api.wunderground.com/api/ + WUNDERGROUND_API_KEY + “/conditions/q/” + WUNDERGROUND_COUNTRY + “/“ + WUNDERGROUND_CITY + “.json”;

像往常一样,在 setup  部分,我们将连接到Wi-Fi网络:

Void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print(“Connecting to ”);
  Serial.println(ssid);
  WiFi.begin(ssid,password);
  while(WiFi.status() != WL_CONNECTED){
    delay(500);
    Serial.print(“.”);
  }
  Serial.println(“”);
  Serial.println(“WiFi connected”);
  Serial.println(“IP address: ”);
  Serial.println(“WiFi.localIP()”);
}

在循环中,如果连接了Wi-Fi状态,那么您将实例化名为http的HTTPClient对象,并开始从之前构建的链接每10秒获取一次数据。在 payload  变量中,您将获得来自服务器的整个响应:

Void loop(){
  If(WiFi.status() == WL_CONNECTED){
     HTTPClient http;
     http.begin(dataURL);
     inthttpCode = http.GET();
     if(httpCode>0){
      // HTTP header has been send and Server response header has been handled
      Serial.printf(“[HTTP] GET … code: %d\n”, httpCode);
      // file found at server
      If(httpCode == HTTP_CODE_OK) {
       String payload = http.getString();
       Serial.println(payload);
      }
    }
  }
  Delay(10000);
}

If getting data every 10 seconds is too often, let’s change it to once a minute by replacing the delay(10000) call that is blocking other code executions.

如果每10秒获取一次数据太频繁,那么让我们通过替换阻止其他代码执行的 delay(10000) 延迟函数的调用为每分钟一次。

所以,在 const String WUNDERGROUND_CITY =“Eindhoven” 之后; ,添加两行代码:

 const long interval = 60*1000;
 unsigned long previuousMillis = 0;

现在,loop  函数将更改如下:

Void loop(){
   unsigned long currentMillis = millis();
   if (currentMills = previousMillis >= interval){
      previousMillis = currentMillis;
      if(WiFi.status() == WL_CONNECTED){
        HTTPClient http;
        http.begin(dataURL);
        inthttpCode = http.GET();
        if (httpCode > 0){
          // HTTP header has been send and Server response header has been handled
          Serial.printf(“[HTTP] GET … code: %d\n”, httpCode);
          // file found at server
          If(httpCode == HTTP_CODE_OK) {
            String payload = http.getString();
            Serial.println(payload);
          }
       }
      }
  }
}

现在,串行监视器每分钟将显示一个巨大的JSON,其中包含有关从温度到湿度,风速,露点等天气的所有信息,如下所示:

但是,如果您只想从此JSON获取某些特定数据,该怎么办?幸运的是,有一个Wunderground库。要安装它,请转到Sketch |包括库|管理图书馆并搜索ESP8266气象站。安装此livrary后,您还需要安装将解析收到的JSON的Json Straming Parser库。您可以按照以下步骤操作:

1.安装ESP8266气象站库:

2.另外,安装JSON Streaming Parse库:

现在,让我们获取相同的数据,因此将使用相同的API_KEY,但数据由livrary函数解析:

1.包括ESP8266 Wi-Fi.h,JSONListener.h和WundergroundCLient的头文件:

But what if you want to get only some specific data from this JSON? Fortunately, there is a Wunderground library for this. To install it, go to Sketch | Include Library | Manage Libraries and search for ESP8266 Weather Station. After installing this livrary, you also need to install the Json Straming Parser library that will  parse the received JSON. You can follow these steps:

1. Install the ESP8266 Weather Station library:

2. Also, install  the JSON Streaming Parse library:

Now, let's get the same data, so the same API_KEY will be used but the data is parsed by livrary functions:

1. Include the headers' files for ESP8266 Wi-Fi.h, JSONListener.h and WundergroundCLient:

#include <ESP8266WiFi.h>
#include <JsonListener.h>
#include "WundergroundClient.h"

2. Define the API_KEY and set the metric Boolean variable:

const String WUNDERGRROUND_API_KEY = "YOUR_API_KEY";
constboolean IS_METRIC = true;

3. Initialize WundergoundClient for the metric system:

WundergroundClientweather_data(IS_METRIC);

4.Also, initialize the Wi-Fi settings and constants used in getting the weather data:

const char* WIFI_SSID = "YOUR_WIFI_SSID";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const String WUNDERGROUND_LANGUAGE = "EN";
const String WUNDERGROUND_COUNTRY = "NL";
const String WUNDERGROUND_CITY = "Eind-hoven";
WiFiClientwifiClient;

5. Initialize the setup function to connect to the Wi-Fi network:

void setup(){
  Serial.begin(115200);
  delay(10);
  
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  delay(20);
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);
  while(WiFi.status()!= WL_CONNECTED){
    delay(500);
    Serial.print(".");  
  }
  Serial.println("");
  Serial.println("WiFi connected!");
  Serial.println();
}

 6. In the loop function, get the data from the wunderground.com site every miunte and show it in the Serial Monitor window: wda

void loop() {
  if((millis() % (60 * 1000))==0){
    Serial.println() ;
    Serial.println("\n\nNext Loop-Step: " + String (millis()) + ":");
    weather_data.updateConditions(WUNDERGRROUND_API_KEY, WUNDERGROUND_LANGUAGE, WUNDERGROUND_COUNTRY, WUNDERGROUND_CITY);
    Serial.println("wundergroundHours: " + weather_data.getHours());
    Serial.println ("wundergroundMinutes: " + weather_data.getMinutes());
    Serial.println ("wundergroundSeconds: "+ weather_data.getSeconds());
    Serial.println ("wundergroundDate: "+weather_data.getDate());
    Serial.println ("wundergroundMoonPctIlum: " + weather_data.getMoonPctIlum());
    Serial.println ("wundergroundMoonAge: "+ weather_data.getMoonAge());
    Serial.println("wundergroundMoonPhase: " + weather_data.getMoonPhase());
    Serial.println ("wundergroundSunriseTime: " + weather_data.getSunriseTime());
    Serial.println("wundergroundSunsetTime: " + weather_data.getSunsetTime());
    Serial.println("wundergroundMoonriseTime: " + weather_data.getMoonriseTime());
    Serial.println ("wundergroundMoonsetTime: " + weather_data.getMoonsetTime());
    Serial.println("wundergroundWindSpeed: " + weather_data.getWindSpeed());
    Serial.println("wundergroundWindDir: "+ weather_data.getWindDir());
    Serial.println ("wundergroundCurrentTemp: " + weather_data.getCurrentTemp());
    Serial.println ("wundergroundTodayIcon: " + weather_data.getTodayIcon());
    Serial.println ("wundergroundTodayIconText: " + weather_data.getTodayIconText());
    Serial.println (" wundergroundMeteoconIcon: " + weather_data.getMeteoconIcon (weather_data. getTodayIconText()));
    Serial.println ("wundergroundWeatherText: " + weather_data.getWeatherText()) ;
    Serial.println("wundergroundHumidity: "+ weather_data.getHumidity());
    Serial.println("wundergroundPressure: " + weather_data.getPressure());
    Serial.println ("wundergroundDewPoint: "+ weather_data.getDewPoint());
    Serial.println ("wundergroundPrecipitationToday: "+ weather_data.getPrecipitationToday());
    Serial.println();
    Serial.println("-------------------------------------/ \n");
  }
}

7. The output for the Serial Monitor is as follows: 

Now, as an exercise, you can read the temperature and turn on or off an LED' if there are icing conditions or humidity and the temperature is too high outside.

猜你喜欢

转载自blog.csdn.net/countofdane/article/details/85753624
1-6