函数的存在会破坏HTTP请求

时间:2014-01-25 21:33:15

标签: c arduino

所以我为Arduino编写了一些基本上只发出HTTP请求的代码。这是一个Twitter项目,但大多数Twitter信息都是通过PHP脚本收集的。 Arduino仅用于从文本文件和基于其内容的推文中收集少量文本。这些包括一个关注者数量的文件(如果它被更改的推文),最后提及日期(如果它被更改的推文),以及最新的关注者名称(在跟随者推文中用于提及用户)。

我编写了函数getLastFollowerName()来获取最后一个关注者的名字。它与函数checkMentions()和'checkFollowers()`执行相同的操作。但是,此功能会发生奇怪的事情。一旦我实现它,测试运行如下。

  1. 获取了followBy.txt中包含的用户名中的两个字符,然后Arduino代码停止了。
  2. 与1相同。
  3. getLastFollowerName()中的HTTP请求找不到两个\r\n字符,这意味着他们发现了一些他们不应该做的其他形式的响应。在打印此响应时,它开始打印整个HTML文档标题(DOCTYPE等),这是无意义的,因为我正在请求文本文件。
  4. 所有其他HTTP请求(checkMentions()checkFollowers())开始行为异常,与getLastFollowerName()请求在3中的行为方式相同。
  5. 所有后续运行都如4所述。所以我注释掉了getLastFollowerName()的函数调用,没有任何改变。我为函数注释了代码本身,一切都开始像我添加函数之前那样工作。

    所以我的问题是 - 即使没有被调用,该函数可能只是通过存在来破坏HTTP请求?它是代码本身,还是更有可能是函数的大小?如果是后者,如果我需要那个功能,我该如何解决这个问题?

    编辑:对不起,忘了粘贴代码。这是(删除一些敏感信息(WiFi信息,Twitter密钥等)

    #include <SPI.h>
    #include <WiFi.h>
    #include <Twitter.h>
    
    int led = 9; //put at 9 and GND
    
    char ssid[] = ""; //  your network SSID (name) 
    char pass[] = "";    // your network password (use for WPA, or use as key for WEP)
    
    int keyIndex = 0;            // your network key Index number (needed only for WEP)
    
    int status = WL_IDLE_STATUS; // status of the wifi connection
    
    // initialize the library instance:
    WiFiClient client;
    
    const unsigned long requestInterval = 30*1000;    // delay between requests; 30 seconds
    
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(199,59,149,200);    // numeric IP for api.twitter.com
    char server[] = "mysite.com";     // name address for twitter API
    
    boolean requested;                     // whether you've made a request since connecting
    unsigned long lastAttemptTime = 0;     // last time you connected to the server, in milliseconds
    
    Twitter twitter(""); //token authorized from (you do NOT need to reobtain this) 
    
    String lastCount = ""; //last number counted
    String lastDate = "";
    String lastFollower="";
    
    unsigned long startTime;
    const unsigned long connectTimeout = 15L * 1000L; // Max time to retry server link
    int numberOfBytes=0;
    
    void setup()
    {
      // reserve space for the strings:
    //  tweet.reserve(150);
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
    
      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present"); 
        // don't continue:
        while(true);
      } 
    
      // attempt to connect to Wifi network:
      while ( status != WL_CONNECTED) { 
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:    
        status = WiFi.begin(ssid, pass);
    
        // wait 10 seconds for connection:
        delay(5000);
        //delay(10000);
        //tweet("this is another test");
      }
    }
    
    void loop()
    {
      while(!checkFollowers()); //keep trying until successful
      client.stop();
      while(!checkMentions()); //keep trying until successful
      client.stop();
    }
    
    boolean checkFollowers()
    {
      //connectToServer();
      //delay(10000);
      String currentLine="";
      currentLine.reserve(256);
      if (client.connected())
      {
        Serial.println("Connected. Checking for availabilty of client...");
        if (client.available())
        {
          Serial.println("Client is available! Trying to read from client...");
          // read incoming bytes:
    
          if(client.find("\r\n\r\n"))
          {
    
          char inChar;
          while(inChar=client.read())
          {
            if(inChar==-1) break;
            currentLine+=inChar; //read in all characters of count
            Serial.print("\n\nCurrent follower count: " + currentLine + "\n\n");
            //if(inChar=='y' || inChar == 'n') break;
          }
          if(currentLine!=lastCount)
          //if(inChar=='y')
          {
            lastCount=currentLine;
    
    //        while(getLastFollowerName())
    //        {
    //          Serial.println("follower name not yet found");
    //        }
            //client.stop();
            //char finalTweet[170];
            //int n = sprintf(finalTweet, "%s%s", lastFollower, " Thanks for the follow!");
            tweet("Thanks for the tweet!");
            Serial.println("BLINKING LED");
            blink(3);
          }
          else
          {
            Serial.println("NOT BLINKING.");
            tweet("Someone should follow me!");
          }
          currentLine=""; //clear
          delay(5000); //delay 5 seconds (don't kill server)
          return true;
         }
         else
         {
           Serial.println("newlines not found - error with request");
           return false;
         }
        }
        else
        {
          Serial.println("followers not available");
          return false;
        }
      }
      else if (millis() - lastAttemptTime > requestInterval)
      {
        // if you're not connected, and two minutes have passed since
        // your last connection, then attempt to connect again:
        //runPhpScript(); //try to run PHP script to get latest info
        //connectToServer();
        makeHttpRequest("/private/followerScript.php");
        client.stop(); //cut connection after running script (I think this is what this does...)
        makeHttpRequest("/private/followerCount.txt");
        return false;
      }
      else
      {
        //Serial.print("f");
        return false;
      }
    }
    
    
    boolean checkMentions()
    {
      String currentLine="";
      if (client.connected())
      {
        Serial.println("Connected. Checking for availabilty of client...");
        if (client.available())
        {
          Serial.println("Client is available! Trying to read from client...");
          // read incoming bytes:
    
          if(client.find("\r\n\r\n"))
          {
    
          char inChar;
    
    //      inChar = client.read(); //read in a character
          while(inChar=client.read())
          {
            if(inChar==-1) break;
            currentLine+=inChar; //read in all characters of count
            Serial.print("\n\nCurrent mention date: " + currentLine + "\n\n");
          }
          if(currentLine!=lastDate)
          {
            lastDate=currentLine;
            Serial.println("BLINKING LED");
            tweet("Someone just mentioned me!");
            blink(3);
          }
          else
          {
            Serial.println("NOT BLINKING.");
            tweet("Someone should mention me!");
          }
          currentLine=""; //clear
          delay(5000); //delay 5 seconds (don't kill server)
          return true;
         }
         else
         {
           Serial.println("newlines not found - error with request");
           return false;
         }
        }
        else
        {
          Serial.println("mentions - not available");
          return false;
        }
    
      }
      else if (millis() - lastAttemptTime > requestInterval)
      {
        // if you're not connected, and two minutes have passed since
        // your last connection, then attempt to connect again:
        makeHttpRequest("/private/mentionScript.php");
        client.stop();
        makeHttpRequest("/private/mentionsDate.txt");
        return false;
      }
      else
      {
        //Serial.print("m");
        return false;
      }
    }
    
    boolean getLastFollowerName()
    {
      String currentLine="";
      if (client.connected())
      {
        //Serial.println("Connected. Checking for availabilty of client...");
        if (client.available())
        {
          Serial.println("Trying to read last follower name...");
    
          if(client.find("\r\n\r\n"))
          {
    
          char inChar;
    
          while(inChar=client.read())
          {
            if(inChar==-1) break;
            currentLine+=inChar; //read in all characters of count
            Serial.print("\n\nLast follower: " + currentLine + "\n\n");
          }
          lastFollower = currentLine; //store globally
          return true;
         }
         else
         {
           Serial.println("newlines not found - error with request");
           return false;
         }
        }
        else
        {
          return false;
        }
        return false;
      }
      else if (millis() - lastAttemptTime > requestInterval)
      {
        makeHttpRequest("/private/followedBy.txt");
    
        Serial.println("making HTTP request to followed by cache file");
        return false;
      }
      else
      {
        return false;
      }
    }
    
    void blink(int blinkCount) //blink specified number of times
    {
      for(int i = 0; i < blinkCount; i++)
      {
        for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5)
        { 
        // sets the value (range from 0 to 255):
          analogWrite(led, fadeValue);         
          // wait for 30 milliseconds to see the dimming effect    
          delay(40);                            
        } 
    
      // fade out from max to min in increments of 5 points:
        for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5)
        { 
          // sets the value (range from 0 to 255):
          analogWrite(led, fadeValue);         
          // wait for 30 milliseconds to see the dimming effect    
          delay(40);                            
        } 
      //digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      //delay(3000);               // wait for a second
      //digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      //delay(1000);               // wait for a second
      }
    }
    
    void makeHttpRequest(String url)
    {
      // attempt to connect, and wait a millisecond:
      Serial.println("connecting to server...");
      if (client.connect(server, 80))
      {
        Serial.println("making HTTP request to " + url + " ...");
        // make HTTP GET request to twitter:
        client.println("GET " + url + " HTTP/1.1");
        client.println("Host:mysite.com");
        client.println("Connection:close");
        client.println();
      }
      else
      {
        Serial.println("Failure to connect.");
      }
      // note the time of this connect attempt:
      lastAttemptTime = millis();
    }
    
    void tweet(char givenTweet[])
    {
      //start CLIENT code
      startTime = millis();
      char hashtag[] = "#hashtag";
    
      char tweet[170];
      int n=sprintf(tweet, "%s%s", givenTweet, hashtag);
    
      while((client.connect(server, 80) == false) &&
        ((millis() - startTime) < connectTimeout));
    
    
        if(client.connected())  // Success!
        {
          Serial.println("\nClient connected to server, ready to tweet!!!");
    
          if (twitter.post(tweet))
          {
            int status = twitter.wait(&Serial);
            if (status == 200) //this doesn't happen for some reason
            {
                 Serial.println("\nTweet Successful: OK.\n");  
            }
            else
            {
                Serial.print("\nTweet Failed : code ");
                //Serial.println(status);
            }
          }
          else
          {
              int statusNum = twitter.wait(&Serial);
              Serial.println("\nConnection to Twitter failed.\n");
              if(statusNum==0) //should always be
                Serial.println("No status number returned.");
           }
          client.stop();
      }
    
    }
    

1 个答案:

答案 0 :(得分:1)

几乎可以肯定你没有公羊。见http://playground.arduino.cc/Code/AvailableMemory