I am writing a code using ethercard library which sends a post request in setup by calling sendData() and recieves get requests in loop() function but the issue is i am able to do only one task (either send post request or recieve get request) one of them fails(the first called only works).How do i close tcp connection socket after use.
#include <EtherCard.h>
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
int fPin = 10;
int bPin = 9;
char website[] = "172.26.40.209";
void sendData(){
int count = 0;
while(count < 2){
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
count++;
timer = millis() + 5000;
Serial.println();
Serial.print("<<< REQ ");
char a1[10],a2[10],a3[10],a4[10],ipSend[20];
sprintf(ipSend,"%d.%d.%d.%d",ether.myip[0],ether.myip[1],ether.myip[2],ether.myip[3]);
char b1[10],b2[10],b3[10],b4[10],b5[10],b6[10],macSend[25];
sprintf(macSend,"%d:%d:%d:%d:%d:%d",mymac[0],mymac[1],mymac[2],mymac[3],mymac[4],mymac[5]);
Stash stash;
byte sd = stash.create();
stash.print("ip=");
stash.print(ipSend);
stash.print("&mac=");
stash.print(macSend);
stash.save();
Stash::prepare(PSTR("POST http://$F:8080/Connect/Arduino_data HTTP/1.1" "\r\n"
"Host: $F:8080" "\r\n"
"Content-Length: $D" "\r\n"
"\r\n"
"$H"),
website, website, stash.size(), sd);
ether.tcpSend();
}
}
}
void setup () {
pinMode(fPin, OUTPUT);
pinMode(bPin, OUTPUT);
digitalWrite(bPin,HIGH);
Serial.begin(9600);
Serial.println('A');
Serial.println("\n[webClient]");
if (ether.begin(sizeof Ethernet::buffer, mymac,8) == 0)
Serial.println("Failed to access Ethernet controller");
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
ether.printIp("IP: ", ether.myip);
ether.printIp("GW: ", ether.gwip);
ether.printIp("DNS: ", ether.dnsip);
ether.parseIp(ether.hisip, website);
ether.hisport = 8080;
ether.printIp("SRV: ", ether.hisip);
sendData(); // for post request
}
void loop () { //getting get requests
word len = ether.packetReceive();
word pos = ether.packetLoop(len);
if (strstr((char *)Ethernet::buffer + pos, "GET /?PIN9=ON") != 0) {
Serial.println("Received ON command");
digitalWrite(bPin, HIGH);
}else if (strstr((char *)Ethernet::buffer + pos, "GET /?PIN9=OFF") != 0) {
Serial.println("Received OFF command");
digitalWrite(bPin, LOW);
}else if (strstr((char *)Ethernet::buffer + pos, "GET /?PIN10=ON") != 0) {
Serial.println("Received ON command");
digitalWrite(fPin, HIGH);
}else if (strstr((char *)Ethernet::buffer + pos, "GET /?PIN10=OFF") != 0) {
Serial.println("Received OFF command");
digitalWrite(fPin, LOW);
}
}