Arduino + ESP8266,我如何发送连续获取请求?

时间:2015-10-26 10:00:28

标签: tcp arduino esp8266

我有一个代码可以在这个网站https://hackaday.io/project/3072/instructions上找到。我通过稍微修改代码使代码工作,但主要问题是它只为GET请求提供一次。我想要的是连续页面提取,应该没有TCP连接关闭。 我尝试了不同的方法,但在1 GET请求后连接总是中断。 此外,如果我不发送任何GET请求,那么它会连续服务于域的索引页面,而不会破坏TCP连接。 这是原始代码http://dunarbin.com/esp8266/retroBrowser.ino
这是我的。

    #define SSID        "vivek"
    #define PASS        "bustedparamour21"
    #define DEST_HOST   "www.electronics2work.com"
    #define DEST_IP     "31.170.161.234"
    #define TIMEOUT     10000 // mS
    #define CONTINUE    false
    #define HALT        true

    #define ECHO_COMMANDS // Un-comment to echo AT+ commands to serial monitor

    // Print error message and loop stop.
    void errorHalt(String msg)
    {
      Serial.println(msg);
      Serial.println("HALT");
      while(true){};
    }

    // Read characters from WiFi module and echo to serial until keyword occurs or timeout.
    boolean echoFind(String keyword)
    {
      byte current_char   = 0;
      byte keyword_length = keyword.length();

      // Fail if the target string has not been sent by deadline.
      long deadline = millis() + TIMEOUT;
      while(millis() < deadline)
      {
        if (Serial1.available())
        {
          char ch = Serial1.read();
          Serial.write(ch);
          if (ch == keyword[current_char])
            if (++current_char == keyword_length)
            {
              Serial.println();
              return true;
            }
        }
      }
      return false;  // Timed out
    }

    // Read and echo all available module output.
    // (Used when we're indifferent to "OK" vs. "no change" responses or to get around firmware bugs.)
    void echoFlush()
      {while(Serial1.available()) Serial.write(Serial1.read());}

    // Echo module output until 3 newlines encountered.
    // (Used when we're indifferent to "OK" vs. "no change" responses.)
    void echoSkip()
    {
      echoFind("\n");        // Search for nl at end of command echo
      echoFind("\n");        // Search for 2nd nl at end of response.
      echoFind("\n");        // Search for 3rd nl at end of blank line.
    }

    // Send a command to the module and wait for acknowledgement string
    // (or flush module output if no ack specified).
    // Echoes all data received to the serial monitor.
    boolean echoCommand(String cmd, String ack, boolean halt_on_fail)
    {
      Serial1.println(cmd);
      #ifdef ECHO_COMMANDS
        Serial.print("--"); Serial.println(cmd);
      #endif

      // If no ack response specified, skip all available module output.
      if (ack == "")
        echoSkip();
      else
        // Otherwise wait for ack.
        if (!echoFind(ack))          // timed out waiting for ack string 
          if (halt_on_fail)
            errorHalt(cmd+" failed");// Critical failure halt.
          else
            return false;            // Let the caller handle it.
      return true;                   // ack blank or ack found
    }

    // Connect to the specified wireless network.
    boolean connectWiFi()
    {
      String cmd = "AT+CWJAP=\""; cmd += SSID; cmd += "\",\""; cmd += PASS; cmd += "\"";
      if (echoCommand(cmd, "OK", CONTINUE)) // Join Access Point
      {
        Serial.println("Connected to WiFi.");
        return true;
      }
      else
      {
        Serial.println("Connection to WiFi failed.");
        return false;
      }
    }

    // ******** SETUP ********
    void setup()  
    {
      Serial.begin(9600);         // Communication with PC monitor via USB
      Serial1.begin(9600);        // Communication with ESP8266 via 5V/3.3V level shifter

      Serial1.setTimeout(TIMEOUT);
      Serial.println("ESP8266 Demo");

      delay(2000); 
      Serial.println("Module is ready.");
      echoCommand("AT+GMR", "OK", CONTINUE);   // Retrieves the firmware ID (version number) of the module. 
      echoCommand("AT+CWMODE?","OK", CONTINUE);// Get module access mode. 

      // echoCommand("AT+CWLAP", "OK", CONTINUE); // List available access points - DOESN't WORK FOR ME

      echoCommand("AT+CWMODE=1", "", HALT);    // Station mode
      echoCommand("AT+CIPMUX=1", "", HALT);    // Allow multiple connections (we'll only use the first).

      //connect to the wifi
      boolean connection_established = false;
      for(int i=0;i<5;i++)
      {
        if(connectWiFi())
        {
          connection_established = true;
          break;
        }
      }
      if (!connection_established) errorHalt("Connection failed");

      delay(5000);

      //echoCommand("AT+CWSAP=?", "OK", CONTINUE); // Test connection
      echoCommand("AT+CIFSR", "", HALT);         // Echo IP address. (Firmware bug - should return "OK".)
      //echoCommand("AT+CIPMUX=0", "", HALT);      // Set single connection mode
    }

    // ******** LOOP ********
    void loop() 
    {
      // Establish TCP connection
      String cmd = "AT+CIPSTART=0,\"TCP\",\""; cmd += DEST_IP; cmd += "\",80";
      if (!echoCommand(cmd, "OK", CONTINUE)) return;
      delay(2000);

      // Get connection status 
      if (!echoCommand("AT+CIPSTATUS", "OK", CONTINUE)) 
      return;

      // Build HTTP request.
      cmd = "GET /";
      cmd +="iot/graphing.php?a=1&b=ldr&c=41 ";
      cmd += "HTTP/1.1\r\nHost: ";
      cmd += DEST_HOST; 
      cmd += ":80\r\n\r\n";

      // Ready the module to receive raw data
      if (!echoCommand("AT+CIPSEND=0,"+String(cmd.length()), ">", CONTINUE))
      {
        echoCommand("AT+CIPCLOSE", "", CONTINUE);
        Serial.println("Connection timeout.");
        return;
      }

      // Send the raw HTTP request
      echoCommand(cmd, "OK",CONTINUE );  // GET

      // Loop forever echoing data received from destination server.
      while(true)
        while (Serial1.available())
          Serial.write(Serial1.read());

      errorHalt("ONCE ONLY");
    }

此代码仅生成一次get请求。如何在不关闭TCP连接的情况下连续提供GET请求? 感谢提前!!

1 个答案:

答案 0 :(得分:1)

您需要使用AT + CIPCLOSE关闭连接,然后再次启动新连接。 例如,如果您需要每次建立两个连接(例如与2个网站建立连接),则可以建立1个连接,然后关闭此连接。现在建立另一个连接并关闭它。 我使用上面的逻辑在我的loop()函数中建立了2个连接,它工作正常。