gpt4 book ai didi

c - 函数的存在会中断 HTTP 请求

转载 作者:行者123 更新时间:2023-11-30 15:39:39 26 4
gpt4 key购买 nike

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

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

  1. 获取了 followBy.txt 中包含的用户名中除两个字符之外的所有字符,然后 Arduino 代码停止运行。
  2. 与 1 相同。
  3. getLastFollowerName() 中的 HTTP 请求找不到两个 \r\n 字符,这意味着它们发现了一些不应该有的其他形式的响应到过。在打印此响应时,它开始打印整个 HTML 文档 header (DOCTYPE 等),这是无意义的,因为我请求的是文本文件。
  4. 所有其他 HTTP 请求(在 checkMentions()checkFollowers() 中)开始出现与 getLastFollowerName() 请求相同的行为3 内完成。

所有后续运行均如 4 中所述。因此,我注释掉了 getLastFollowerName() 的函数调用,并且没有任何更改。我注释掉了该函数的代码本身,一切都开始像添加该函数之前一样工作。

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

编辑:抱歉,忘记粘贴代码。就是这样(删除了一些敏感信息(WiFi 信息、Twitter key 等)

#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();
}

}

最佳答案

几乎可以肯定你的内存已经用完了。请参阅http://playground.arduino.cc/Code/AvailableMemory

关于c - 函数的存在会中断 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com