evhttp_request_new() evhttp_request return null - libevent

I write a libevet program to get data from some web interface.
the code like this:
sometimes the struct evhttp_request *req of self->done is NULL.
I cannot find why of this .
response->connecttime = spi_utils_float_time();
self->evreq = evhttp_request_new(self->done, task);
if (self->evreq == NULL) {
SPI_LOG_ERROR("spider", "cannot create evhttp_request");
goto download_error;
}
/* bson_print(&task->task); */
/** set header and body */
/* TODO: set timeout */
spi_http_request_split_header(self, self->header->str, self->evreq);
if (self->body != NULL)
evbuffer_add_printf(self->evreq->output_buffer, (const char*)self->body->str);
if (self->method == spi_http_post)
cmd_type = EVHTTP_REQ_POST;
self->evcon = evhttp_connection_new(self->host->str, self->port);
if (self->evcon == NULL) {
SPI_LOG_ERROR("spider", "evhttp_connection_new Failed!\n");
goto download_error;
}
SPI_LOG_DEBUG("spider", "set retries: %d.", 5);
evhttp_connection_set_retries(self->evcon, 3);
SPI_LOG_DEBUG("spider", "set timeout: %d.", 60);
evhttp_connection_set_timeout(self->evcon, 20);
response->connectedtime = spi_utils_float_time();
response->crawltime = spi_utils_float_time();
SPI_LOG_DEBUG("spider", "evhttp_make_request");
if (evhttp_make_request(self->evcon, self->evreq, cmd_type, self->path->str) == -1) {
SPI_LOG_ERROR("spider", "evhttp_make_request Failed.\n");
goto download_error;
}

(From your question it's not entirely clear where you're getting the NULL, but maybe what you mean is that)
the callback passed to evhttp_request_new might get NULL if there was a timeout.

Related

Reading unread emails with selenium

i have the below code to read emails and check if the subject is matching with the expected message
Message[] messages = folder.getMessages();
String message="Thanks for contacting";
if(folder.getUnreadMessageCount()!=0)
{
for (Message mail : messages)
{
if(!mail.isSet(Flags.Flag.SEEN) && mail.getSubject().contains("Thanks"))//if mail is unread and the message matches
{
mail.setFlag(Flags.Flag.SEEN, true);
softAssert.assertTrue(true,"Email received ->");
Reporter.log("Email received ->" + mail.getSubject(), true);
break;
}
if(!mail.isSet(Flags.Flag.SEEN) && !mail.getSubject().contains("Thanks"))//if mail is unread and the message does not match
{
System.out.println(mail.getSubject() + "-> is not the email we are looking for");
}
}
}
else
{
softAssert.assertTrue(false,"Email not received");
Reporter.log("Email not received ->" + message, true);
}
The problem is I want to fail this test if both the conditions inside the for loop fail. if i put the else inside the for loop it prints not received for reach element in the loop. how do i go about this?
You can use boolean expression. See the below simple example,
boolean test = true;
boolean test2 = true;
for (int i = 0; i < 3; i++) {
if (!test) {
System.out.println("Test value is false.");
} else {
test = false;
}
if (!test2) {
System.out.println("Test2 value is false.");
} else {
test2 = false;
}
if(!test && !test2) {
System.out.println("Breaking loop.");
break;
}
}
Create two boolean variables and set their values as true incase if your if condition fails inside the loop then by using else block change the boolean value to false and do the same for your second if condition as well. In the last if condition if both statements fails then break the loop.

Null pointer exception on Processing (ldrValues)

My code involves both Processing and Arduino. 5 different photocells are triggering 5 different sounds. My sound files play only when the ldrvalue is above the threshold.
The Null Pointer Exception is highlighted on this line
for (int i = 0; i < ldrValues.length; i++) {
I am not sure which part of my code should be changed so that I can run it.
import processing.serial.*;
import processing.sound.*;
SoundFile[] soundFiles = new SoundFile[5];
Serial myPort; // Create object from Serial class
int[] ldrValues;
int[] thresholds = {440, 490, 330, 260, 450};
int i = 0;
boolean[] states = {false, false, false, false, false};
void setup() {
size(200, 200);
println((Object[])Serial.list());
String portName = Serial.list()[3];
myPort = new Serial(this, portName, 9600);
soundFiles[0] = new SoundFile(this, "1.mp3");
soundFiles[1] = new SoundFile(this, "2.mp3");
soundFiles[2] = new SoundFile(this, "3.mp3");
soundFiles[3] = new SoundFile(this, "4.mp3");
soundFiles[4] = new SoundFile(this, "5.mp3");
}
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}
You're approach is shall we say optimistic ? :)
It's always assuming there was a message from Serial, always formatted the right way so it could be parsed and there were absolutely 0 issues buffering data (incomplete strings, etc.))
The simplest thing you could do is check if the parsing was successful, otherwise the ldrValues array would still be null:
void draw()
{
background(255);
//serial loop
while (myPort.available() > 0) {
String myString = myPort.readStringUntil(10);
if (myString != null) {
//println(myString);
ldrValues = int(split(myString.trim(), ','));
//println(ldrValues);
}
}
// double check parsing int values from the string was successfully as well, not just buffering the string
if(ldrValues != null){
for (int i = 0; i < ldrValues.length; i++) {
println(states[i]);
println(ldrValues[i]);
if (ldrValues[i] > thresholds[i] && !states[i]) {
println("sensor " + i + " is activated");
soundFiles[i].play();
states[i] = true;
}
if (ldrValues[i] < thresholds[i]) {
println("sensor " + i + " is NOT activated");
soundFiles[i].stop();
states[i] = false;
}
}
}else{
// print a helpful debugging message otherwise
println("error parsing ldrValues from string: " + myString);
}
}
(Didn't know you could parse a int[] with int(): nice!)

Why is the deleted file commit by default when using the commit command in libgit2?

I delete the file: user git_remove_bypath and git_index_write
I use the index to commit, and don't commit the file by removed file,but the file by my removed also commit success.
int commit(void *repository, const char *file_name[], const unsigned int file, const char *message, void *payload)
{
int error = -1;
git_signature *signature = NULL;
/*git git; identify of any object*/
/*git commit_id; identify of any object*/
void* index = NULL;
void* tree = NULL;
do /* try catch */
{
const char *path = git_repository_path((git_repository*)repository);
/*get signature*/
error = git_signature_default(&signature, (git_repository*)repository);
/*get repository head*/
error = git_repository_head(&ref_head,(git_repository*)repository);
if (error == GIT_OK)
{
error = git_commit_lookup(&parent_commit, (git_repository*)repository, git_reference_target(ref_head));
}
else if (error != -9)
{
break;
}
/*get repository index*/
error = git_repository_index((git_index**)&index, (git_repository*)repository);
for(int i = 0; i < Count; ++i)
{
/*get statue*/
error = git_status_file(&flags, (git_repository *)repository, file_name[i]);
if(-3 == error || -5 == error)
{
continue;
}
if( GIT_STATUS_INDEX_DELETED & flags || GIT_STATUS_WT_DELETED & flags )
{
/*remove file*/
error = git_index_remove_bypath((git_index *)index, file_name[i]);
}
else
{
/*add file*/
error = git_index_add_bypath((git_index *)index, file_name[i]);
}
/*write disk*/
error = git_index_write((git_index*)index);
}
/* Get the index and write it to a tree */
error = git_index_write_tree(&git, (git_index*)index);
/* lookup tree */
error = git_tree_lookup((git_tree**)&tree, (git_repository *)repository, &git);
/* Do the commit*/
error = git_commit_create(&commit_id, (git_repository*)repository, "HEAD", signature, signature, NULL,
message, (git_tree *)tree, 1, parents);
}while(0);
}

How can I write code to receive whole string from a device on rs232?

I want to know how to write code which receives specific string.for example, this one OK , in this I only need "OK" string.
Another string is also like OK
I have written code in keil c51 for at89s52 microcontroller which works but I need more reliable code.
I'm using interrupt for rx data from rs232 serial.
void _esp8266_getch() interrupt 4 //UART Rx.{
if(TI){
TI=0;
xmit_bit=0;
return ;
}
else
{
count=0;
do
{
while(RI==0);
rx_buff=SBUF;
if(rx_buff==rx_data1) //rx_data1 = 0X0D /CR
{
RI=0;
while(RI==0);
rx_buff=SBUF;
if(rx_buff==rx_data2) // rx_data2 = 0x0A /LF
{
RI=0;
data_in_buffer=1;
if(loop_conti==1)
{
if(rec_bit_flag==1)
{
data_in_buffer=0;
loop_conti=0;
}
}
}
}
else
{
if(data_in_buffer==1)
{
received[count]=rx_buff; //my buffer in which storing string
rec_bit_flag=1;
count++;
loop_conti=1;
RI=0;
}
else
{
loop_conti=0;
rec_bit_flag=0;
RI=0;
}
}
}
while(loop_conti==1);
}
rx_buff=0;
}
This is one is just for reference, you need develop the logic further to your needs. Moreover, design is depends on what value is received, is there any specific pattern and many more parameter. And this is not a tested code, I tried to give my idea on design, with this disclaimer here is the sample..
//Assuming you get - "OK<CR><LF>" in which <CR><LF> indicates the end of string steam
int nCount =0;
int received[2][BUF_SIZE]; //used only 2 buffers, you can use more than 2, depending on how speed
//you receive and how fast you process it
int pingpong =0;
bool bRecFlag = FALSE;
int nNofbytes = 0;
void _esp8266_getch() interrupt 4 //UART Rx.
{
if(TI){
TI=0;
xmit_bit=0;
return ;
}
if(RI) // Rx interrupt
{
received[pingpong][nCount]=SBUF;
RI =0;
if(nCount > 0)
{
// check if you receive end of stream value
if(received[pingpong][nCount-1] == 0x0D) && (received[pingpong][nCount] == 0x0A))
{
bRecFlag = TRUE;
pingpong = (pingpong == 0);
nNofbytes = nCount;
nCount = 0;
return;
}
}
nCount++;
}
return;
}
int main()
{
// other stuff
while(1)
{
// other stuff
if(bRecFlag) //String is completely received
{
buftouse = pingpong ? 0 : 1; // when pingpong is 1, buff 0 will have last complete string
// when pingpong is 0, buff 1 will have last complete string
// copy to other buffer or do action on received[buftouse][]
bRecFlag = false;
}
// other stuff
}
}

How to check forwarded Packets in UDPBasicApp in Omnet

How can I modify UDPBasicApp to find duplicates in the messages recieved?
I made these changes to the class UDPBasicApp.cc to add an extra step to check recieved udp data packets like below, but I see no effect in .sca/.vec and does not even show bubbles.
Where could the error be?
void UDPBasicApp::handleMessageWhenUp(cMessage *msg)
{
if (msg->isSelfMessage()) {
ASSERT(msg == selfMsg);
switch (selfMsg->getKind()) {
case START:
processStart();
break;
case SEND:
processSend();
break;
case STOP:
processStop();
break;
default:
throw cRuntimeError("Invalid kind %d in self message", (int)selfMsg->getKind());
}
}
else if (msg->getKind() == UDP_I_DATA) {
// process incoming packet
//-----------------------------------------------------Added step
//std::string currentMsg= "" + msg->getTreeId();
std::string currentPacket= PK(msg)->getName();
if( BF->CheckBloom(currentPacket) == 1) {
numReplayed++;
getParentModule()->bubble("Replayed!!");
EV<<"----------------------WSNode "<<getParentModule()->getIndex() <<": REPLAYED! Dropping Packet\n";
delete msg;
return;
}
else
{
BF->AddToBloom(currentPacket);
numLegit++;
getParentModule()->bubble("Legit.");
EV<<"----------------------WSNode "<<getParentModule()->getIndex() <<":OK. Pass.\n";
}
//-----------------------------------------------------------------------------
processPacket(PK(msg));
}
else if (msg->getKind() == UDP_I_ERROR) {
EV_WARN << "Ignoring UDP error report\n";
delete msg;
}
else {
throw cRuntimeError("Unrecognized message (%s)%s", msg->getClassName(), msg->getName());
}
if (hasGUI()) {
char buf[40];
sprintf(buf, "rcvd: %d pks\nsent: %d pks", numReceived, numSent);
getDisplayString().setTagArg("t", 0, buf);
}
}
Since I don't have enough context about the entities participating in your overall system, I will provide the following idea:
You can add a unique ID to each message of your application by adding the following line to your applications *.msg:
int messageID = simulation.getUniqueNumber();
Now on the receiver side you can have an std::map<int, int> myMap where you store the <id,number-of-occurences>
Each time you receive a message you add the message to the std::map and increment the number-of-occurences
if(this->myMap.count(myMessage->getUniqueID) == 0) /* check whether this ID exists in the map */
{
this->myMap.insert(std::make_pair(myMessage->getUniqueID(), 1)); /* add this id to the map and set the counter to 1 */
}
else
{
this->myMap.at(myMessage->getUniqueID())++; /* add this id to the map and increment the counter */
}
This will allow you to track whether the same message has been forwarded twice, simply by doing:
if(this->myMap.at(myMessage->getUniqueID()) != 1 ) /* the counter is not 1, message has been "seen" more than once */
The tricky thing for you is how do you define whether a message has been seen twice (or more).