2016-09-27 95 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"]);