2016-09-27 136 views
0

使用帶有Nodemcu-esp12e模塊的Arduino IDE,我創建了一個程序,該程序發出HTTP GET請求。使用Arduino IDE和nodemcu-esp-12e驗證HTTP GET請求的返回

但是,我不知道如何才能正確處理這次諮詢的回報。

我使用'indexOf'函數驗證返回是否返回false/off或true/on。

這是驗證退貨的正確方法嗎?
有關如何改進此代碼的任何建議?

#include <ESP8266WiFi.h> 
const char* ssid  = "mywifiid"; 
const char* password = "mypassword"; 
IPAddress host(192,168,0,11); 

void setup() { 
    Serial.begin(115200); 
    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()); 
} 

void loop() { 
    // 
    Serial.print("connecting to "); 
    Serial.println(host); 
    // 
    WiFiClient client; 
    const int httpPort = 80; 
    if (!client.connect(host, httpPort)) { 
    Serial.println("connection failed"); 
    return; 
    } 
    else{ 
    Serial.println("connection success"); 
    } 
    // 
    String get = "http://localhost/Test/GetStatusSensor?idsensor=2"; 
    Serial.println(get); 
    // 
    client.print("GET " + get + "\r\nHTTP/1.1\r\nHost: localhost\Test\r\nConnection: keep-alive\r\n\r\n"); 
    // 
    while(client.available()){ 
    String line = client.readStringUntil('\r'); 
    // 
    int iret= line.indexOf('on'); 
    // 
    Serial.print(line); 
    Serial.println(String(iret)); 
    // 
    if (iret> 0) { 
     // 
     Serial.println("On"); 
    } 
    else { 
     Serial.println("Off"); 
    }  
    } 
    // 
    Serial.println(); 
    Serial.println("closing connection"); 
    delay(20000); // 20 sec 
} 
+0

Arduino是不是C! – Olaf

+0

感謝您的更正! –

+0

http://stackoverflow.com/questions/11812850/does-arduino-use-c-or-c –

回答

1

我的建議是使用JSON切換到更具結構化的通信方式。您可以定義自定義數據名稱和類型並輕鬆覆蓋它們。看看它在:

https://github.com/bblanchon/ArduinoJson

這裏是一些JSON例如,從HttpClient的例子:

DynamicJsonBuffer jsonBuffer(BUFFER_SIZE); 

    JsonObject& root = jsonBuffer.parseObject(client); 

    if (!root.success()) { 
    Serial.println("JSON parsing failed!"); 
    return false; 
    } 

    // Here were copy the strings we're interested in 
    strcpy(userData->name, root["name"]); 
    strcpy(userData->company, root["company"]["name"]);