8.抓取中央氣象局資料

#include "ESP8266WiFi.h"

#include "ArduinoJson.h"

void get_Weather(); // Function 原型

bool showWeather(char *json);

// ===== Wifi setup =====

const char *ssid = "SSID";

const char *password = "PASSWORD";

// ===== setup =====

const char *host = "opendata.cwb.gov.tw";

const char *dataid = "O-A0003-001";

const char *locationName = "板橋";

const char *privateKey = "CWB API-KEY";

const char *elementName = "TEMP";//可用逗號隔開來取得多筆資料,詳細請見 CWB_Opendata_API.pdf

// ===== Variable Number setup =====

static char respBuf[4096];

float data;

unsigned long prevTime;

void setup() {

Serial.begin(115200);

delay(10);

Serial.print("Connecting to ");

Serial.println(ssid);

WiFi.mode(WIFI_STA);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED){

delay(200);

Serial.print(".");

}

Serial.println("WiFi connected");

Serial.println("IP address: ");

Serial.println(WiFi.localIP());

}

void loop(){

get_Weather("TEMP");

get_Weather("HUMD");

delay(3000);

}

void get_Weather(String data_mode){

Serial.print("Connecting to ");

Serial.println(host);

WiFiClient client;

const int httpPort = 80;

if (!client.connect(host, httpPort)) {return;}

// Create a URI for the request

String url = "/api/v1/rest/datastore/";

url += dataid;

url += "?Authorization=";

url += privateKey;

url += "&locationName=";

url += locationName;

url += "&elementName=";

url += data_mode;

client.print(String("GET ") + url + " HTTP/1.1\r\n" +

"Host: " + host + "\r\n" +

"Connection: close\r\n\r\n");

client.flush();

int respLen = 0;

bool skip_headers = true;

while (client.connected() || client.available()){

if (skip_headers) {

String aLine = client.readStringUntil('\n');

//Serial.print("aLine=");

//Serial.println(aLine);

if (aLine.length() <= 1) {skip_headers = false;}

}else{

int bytesIn;

bytesIn = client.read((uint8_t *)&respBuf[respLen], sizeof(respBuf) - respLen);

//Serial.print("bytesIn=");

//Serial.println(bytesIn);

if (bytesIn > 0) {respLen += bytesIn;

if (respLen > sizeof(respBuf)){respLen = sizeof(respBuf);}

}else if (bytesIn < 0){Serial.println(F("read error "));}

}

delay(1);

}

Serial.println("closing connection");

client.stop();

if (respLen >= sizeof(respBuf)){Serial.print(F("respBuf overflow "));return;}

respBuf[respLen++] = '\0';

//Serial.print("respBuf=");

//Serial.println(respBuf);

showWeather(respBuf);

Serial.print(data_mode);

Serial.print("=");

Serial.println(data);

}

bool showWeather(char *json){

StaticJsonBuffer<6400> jsonBuffer;

char *jsonstart = strchr(json, '{');

json = jsonstart;

JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success()) { }

int stationId = root["records"]["location"][0]["stationId"];

data = root["records"]["location"][0]["weatherElement"][0]["elementValue"];

}