Dear all,
I've read through the forum but have not found any solution to my problem so I decided to create my own topic here, thank you in advance for your help.
My problem is as follows: I'm posting a request (with a press of a button) to a web server which returns JSON object. At first press of the button the client is able to connect and response comes as expected. But when I do this again connection fails (client.connect(...)) and returns 0 as an error code. Please see my code below:
When button is pressed the following function is called:
void buttonPress() {
if (client.connect(mirServer, 80)) {
Serial.print("connected to ");
Serial.println(client.remoteIP());
client.println("POST /cgi-bin/test.cgi HTTP/1.1");
client.println("Host: 192.168.1.22");
client.println("Content-Type: application/json");
client.println("Accept-Language: en_US");
client.print("Authorization: Basic ");
client.println(authToken);
client.print("Content-length: ");
client.println(jsonStr.length());
client.println();
client.println(jsonStr);
client.println("Connection: close");
client.println();
// Check HTTP status
char status[32] = {0};
client.readBytesUntil('\r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
// Skip HTTP headers
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
}
An this is the loop:
void loop() {
// // First button was pressed
buttonStateHandler(digitalRead(button1Pin),button1Pin);
buttonStateHandler(digitalRead(button2Pin),button2Pin);
buttonStateHandler(digitalRead(button3Pin),button3Pin);
buttonStateHandler(digitalRead(button4Pin),button4Pin);
char resp[561];
if (client.available()) {
client.readBytesUntil('\r', resp, sizeof(resp));
StaticJsonBuffer<561> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(resp);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
Serial.println(F("Response STATE:"));
Serial.println(root["state"].as<char*>());
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
}
}
I'm totally stuck at this point any help would be highly appreciated.