COSM + arduino ethernet FROZEN !!!!

Dear all,
Have you had any problems with the feed cosm?
I'm sending temperature and humidity sensor DHT22 to cosm and everything works fine until after a while (variable times 20 min. sometimes 2 hours) ... it freeze all!
I do not understand! I am attaching the code ...
Help!!

#include <SPI.h>
#include <Ethernet.h>
#include <DHT.h>

#define APIKEY         "xxx
#define FEEDID         xxx // your feed ID
#define USERAGENT      "xxx)" // user agent is the project name

#define DHTPIN         7      // Data pin for the HUMID module
#define DHTTYPE        DHT22  // Sensor used on the HUMID module

DHT dht(DHTPIN, DHTTYPE);

// assign a MAC address for the ethernet controller.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield fill in your address here:
//byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; 


// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10,0,1,20);
// initialize the library instance:
EthernetClient client;

// 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(173,203,98,29);    // numeric IP for api.cosm.com
//char server[] = "api.cosm.com";   // name address for cosm API

unsigned long lastConnectionTime = 0;          // last time you connected to the server, in milliseconds
boolean lastConnected = false;                 // state of the connection last time through the main loop
//const unsigned long postingInterval = 30*1000; //delay between updates to Cosm.com
const unsigned long postingInterval = 60000; //delay between updates to Cosm.com

void setup() {
  // start serial port:
  Serial.begin(38400);
  // start the HUMID module:
  dht.begin();
  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // DHCP failed, so use a fixed IP address:
    Ethernet.begin(mac, ip);
  }
  Serial.println(Ethernet.localIP());  // questo programma prende il DHCP !!!!!!!
}

void loop() {
  
  
  // read the analog sensor:
  int sensorReading = analogRead(A0);   

  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
  
  if (millis() < lastConnectionTime) lastConnectionTime = millis();    // evita il blocco dopo 50gg poiché millis() si azzera

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    float temperatureReading = dht.readTemperature();
    Serial.print("Temperature: ");
    Serial.println(temperatureReading);
    float humidityReading    = dht.readHumidity();
    Serial.print("Humidity: ");
    Serial.println(humidityReading);
    sendData(temperatureReading, humidityReading);
  }
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
}

// this method makes a HTTP connection to the server:
boolean sendData(float thisTemperature, float thisHumidity) {
  if (client.connected()) client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("PUT /v2/feeds/");
    client.print(FEEDID);
    client.println(".csv HTTP/1.1");
    client.println("Host: api.cosm.com");
    client.print("X-ApiKey: ");
    client.println(APIKEY);
    client.print("User-Agent: ");
    client.println(USERAGENT);
    client.print("Content-Length: ");

    /*
     work out the length of the string:
     "temperature," = 12 + 
     digits of temperature value + 
     "humidity," = 9 +
     digits of humidity value + 
     "\r\n" = 2
     */
    int length = 12 + countDigits(thisTemperature,2) + 2 + 9 + countDigits(thisHumidity,2) + 2;

    // calculate the length of the sensor reading in bytes:
    client.println(length);

    // last pieces of the HTTP PUT request:
    client.println("Content-Type: text/csv");
    client.println("Connection: close");
    client.println();

    // here's the actual content of the PUT request:
    client.print("temperature,");
    client.println(thisTemperature);
    client.print("humidity,");
    client.println(thisHumidity);
    client.println();
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
    Serial.println("data uploaded");
	
  } 
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

// Counts digits of a floating point number, to calculate content length
// for an HTTP call.
// Based on Arduino's internal printFloat() function.
int countDigits(double number, int digits)  { 
  int n = 0;

  // Handle negative numbers
  if (number < 0.0)
  {
    n++; // "-";
    number = -number;
  }

  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i) {
    rounding /= 10.0;
  }
  number += rounding;

  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;

  while (int_part > 0) {
    int_part /= 10;
    n++;
  }
  // Print the decimal point, but only if there are digits beyond
  if (digits > 0) {
    n++; //"."; 
  }

  // Extract digits from the remainder one at a time
  while (digits-- > 0)
  {
    remainder *= 10.0;
    int toPrint = int(remainder);
    n ++; // += String(toPrint);
    remainder -= toPrint; 
  } 
  return n;
}

Where in that code are you reading the response from the server? That might help troubleshoot that.

If, by chance, the server gets a packet on the way before it gets the client.stop(), and you do not empty the socket rx buffer, the socket/connection will not close properly and you lose that socket. You have only 4 sockets.

Thank you for your reply !

How can I empty the buffer ??

P.S.
this is what happened on my serial monitor when cosm was freezing:

Temperature: 20.00
Humidity: 45.40
1652.00
connection fails
Temperature: 20.00
Humidity: 45.40
1652.00
connection fails
Temperature: 20.00
Humidity: 45.40
1652.00
connection fails

The connection probably fails because you do not have any sockets remaining to make a connection. I have client code in the playground that handles that.
http://playground.arduino.cc/Code/WebClient
...and zoomkat has some good client code posted on the forum. Do a search and you should find it, or wait a couple minutes and he will probably post it here for you. His code does the same thing mine does in a slightly different way, but the effect is the same. The rx buffer is emptied as the packets arrive. When the server gets the last ACK for the last packet is has to send, it will close the connection from its end. Then you close your end.

Sorry Surfer but i'm not able to change it for my cosm code,
can you help me ?
Thanks a lot !!!!!!

kove3374:
everything works fine until after a while (variable times 20 min. sometimes 2 hours) ... it freeze all!

There have been a number of posts like this lately. I suspect the first four lines of your code say it all. You are not using the latest libraries from cosm.

#include <HttpClient.h>
#include <Cosm.h>

They are from github. Check the cosm forum for details if you need. Other than making your code look a lot simpler, I don't actually know what these libraries do, so this is not a guarantee you will fix your problem, but singing from the same songsheet as those who don't have a problem will surely help.

Ilya will tell you much the same thing.

I would use something like this.

boolean sendData(float thisTemperature, float thisHumidity) {

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("PUT /v2/feeds/");
    client.print(FEEDID);
    client.println(".csv HTTP/1.1");
    client.println("Host: api.cosm.com");
    client.print("X-ApiKey: ");
    client.println(APIKEY);
    client.print("User-Agent: ");
    client.println(USERAGENT);
    client.print("Content-Length: ");

    /*
     work out the length of the string:
     "temperature," = 12 + 
     digits of temperature value + 
     "humidity," = 9 +
     digits of humidity value + 
     "\r\n" = 2
     */
    int length = 12 + countDigits(thisTemperature,2) + 2 + 9 + countDigits(thisHumidity,2) + 2;

    // calculate the length of the sensor reading in bytes:
    client.println(length);

    // last pieces of the HTTP PUT request:
    client.println("Content-Type: text/csv");
    client.println("Connection: close");
    client.println();

    // here's the actual content of the PUT request:
    client.print("temperature,");
    client.println(thisTemperature);
    client.print("humidity,");
    client.println(thisHumidity);
    client.println();
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
    Serial.println("data uploaded");
	
  } 
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
    // return fail
    return false;
  }

  // stay in the next loop until the server closes the connection
  while(client.connected()) {
    while(client.available()) {
      Serial.write(client.read());
    }
  }

  // now that the server closed its end, close this end
  client.stop();
  // return success
  return true;
}

edit: My bad. I forgot an opening parenthesis on client.read(). I fixed it.

Thank you Surfer, I'm testing the code
I'll let you know the results !!!!