Arduino IDE for ESP8266內(nèi)置的各種通信手段,相比起功能全面但是不方便使用的Socket通信,作者賦予了更強(qiáng)大的功能,那就是HTTP組件,第一篇文章里邊說(shuō)了簡(jiǎn)單HTTP服務(wù)端,這里來(lái)說(shuō)說(shuō)HTTP客戶端。整個(gè)教程就以上傳Yeelink數(shù)據(jù)點(diǎn)為目的制作一個(gè)HTTP客戶端。
#include <ESP8266WiFi.h>#include <ESP8266HTTPClient.h>#define UKey "" // Yeelink提供的U-ApiKeyString ssid = ""; // 需要連接的wifi熱點(diǎn)名稱String password = ""; // 需要連接的wifi熱點(diǎn)密碼/* 上傳數(shù)據(jù)到服務(wù)器。 * device為設(shè)備號(hào),sensor為傳感器號(hào),data為上傳數(shù)據(jù)點(diǎn)的值 * 這里默認(rèn)上傳到最新的數(shù)據(jù)點(diǎn)上,需要上傳到特定點(diǎn)上就得在post內(nèi)容中單獨(dú)加入時(shí)間戳 */void uploadYeelinkData(String device, String sensor, String data) { HTTPClient http; const String apiAddress = "/v1.1/device/" + device + "/sensor/" + sensor + "/datapoints"; http.begin("api.yeelink.net", 80, apiAddress); http.addHeader("U-ApiKey",UKey, true); int httpCode = http.POST("{\"value\":" + data + "}"); Serial.print("code:"); Serial.println(httpCode); if(httpCode == 200) { // 訪問(wèn)成功,取得返回參數(shù) String payload = http.getString(); Serial.println(payload); } else { // 訪問(wèn)不成功,打印原因 String payload = http.getString(); Serial.print("context:"); Serial.println(payload); }}/* 從服務(wù)器取得數(shù)據(jù) * device為設(shè)備號(hào),sensor為傳感器號(hào) */void readYeelinkData(String device, String sensor) { HTTPClient http; // 這里使用的api是v1.0的,v1.1的api需要提供U-ApiKey const String apiAddress = "/v1.0/device/" + device + "/sensor/" + sensor + "/datapoints"; http.begin("api.yeelink.net", 80, apiAddress); int httpCode = http.GET(); // 使用GET形式來(lái)取得數(shù)據(jù) Serial.print("code:"); Serial.println(httpCode); if(httpCode == 200) { // 訪問(wèn)成功,取得返回參數(shù) String payload = http.getString(); Serial.println(payload); } else { // 訪問(wèn)不成功,打印原因 String payload = http.getString(); Serial.print("context:"); Serial.println(payload); }}void setup() { Serial.begin ( 115200 ); int connectCount = 0; WiFi.begin ( ssid.c_str(), password.c_str() ); while ( WiFi.status() != WL_CONNECTED ) { delay ( 1000 ); Serial.print ( "." ); if(connectCount > 30) { Serial.println( "Connect fail!" ); break; } connectCount += 1; } if(WiFi.status() == WL_CONNECTED) { Serial.println ( "" ); Serial.print ( "Connected to " ); Serial.println ( ssid ); Serial.print ( "IP address: " ); Serial.println ( WiFi.localIP() ); connectCount = 0; } //readYeelinkData("8938", "28887"); // 讀取數(shù)據(jù)點(diǎn)測(cè)試 uploadYeelinkData("8938", "28887", "1"); // 寫入數(shù)據(jù)點(diǎn)測(cè)試} void loop() { }
例程里邊的關(guān)鍵點(diǎn)基本已經(jīng)標(biāo)注上了注視,作者封裝了一個(gè)HttpClient類,這個(gè)類使得Http通信變得非常的簡(jiǎn)單,平時(shí)在pc上編寫Http一樣簡(jiǎn)單,可以簡(jiǎn)單的添加Header,post數(shù)據(jù),不用像W5100模塊那樣,整個(gè)通信的報(bào)文都需要自己來(lái)編寫,稍有點(diǎn)不對(duì)就會(huì)導(dǎo)致通信失敗。
下一篇教程:Arduino IDE for ESP8266教程(四)路由系統(tǒng)
聯(lián)系客服