[SOLVED] Arduino Wifi101 only posts one or two times then fails

Hi, I have a Arduino Wifi101 and a Mega R3 and I am trying to just post one variable Ubidots and it works for the first or second post then stops. The code seems to run ok on the Arduino but for some reason stops midway through the posting process. Any thoughts would be greatly appreciated!!

Jon

Below is a sample of the serial output:

first successful post:

The full HTTP is:

POST /api/v1.6/collections/values/?force=true HTTP/1.1
Host: things.ubidots.com
User-Agent: Arduino-WiFi/1.1
X-Auth-Token: XXXXXXX
Connection: close
Content-Type: application/json
Content-Length: 58

[{"variable": "XXXXXXXX", "value":1.00}]

The TCP socket is opened
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 29 Aug 2017 13:46:16 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Vary: Cookie
Allow: POST, OPTIONS

Unsuccessful post:

The full HTTP is:

POST /api/v1.6/collections/values/?force=true HTTP/1.1
Host: things.ubidots.com
User-Agent: Arduino-WiFi/1.1
X-Auth-Token: XXXXXX
Connection: close
Content-Type: application/json
Content-Length: 58

[{"variable": "XXXXXXX", "value":1.00}]

My code is below:

#include <UbidotsArduino.h>
#include <SPI.h>
#include <WiFi101.h>


#define ID  "XXXXXX"  // Put here your Ubidots variable ID

#define TOKEN  "lXXXXXXX"  // Put here your Ubidots TOKEN

char ssid[] = "XXXXX"; //  your network SSID (name)
char pass[] = "XXXXX";    // 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;

Ubidots client(TOKEN);

#define ARRAYSIZE 8

int test[ARRAYSIZE] = {0,0,0,0,0,0,0,0};

void setup(){
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port 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);
    }

    String fv = WiFi.firmwareVersion();
    if (fv != "1.1.0") {
        Serial.println("Please upgrade the firmware");
    }

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

    pinMode(2,INPUT);
}
void loop(){
       
   for (int x = 0; x < 8; x++){
        test[x] = digitalRead(2);
   }


   
    Serial.println(WiFi.status());
   Serial.println(test[0]);
   client.add(ID,test[0]);   
   client.sendAll();
        delay(10000);
}

Greetings sir, as the WiFi101 is actually retired from the market our library is deprecated and will not be updated. I advice you to create your own snippet, please refer to this code and adapt it to your needs, you should simply change the way as the TCP client is declared.

Hope it helps you.

Regards

Thanks !! I will give that a try later on tonight.

Appreciate the advice.

Jon

Hey Jon!

I built this sample code that should works without any issue. I made the test using other board because at the moment I don’t have the WiFi shield, I already made the modifications including the WiFi client, so don’t worry about any modification. Please, can you make the test and verify that everything is working properly in your side? :grinning:

You just have to assign the WiFi credentials and your Ubidots TOKEN where is indicated:

/********************************
 * Libraries included
 *******************************/
#include <WiFi.h>

/********************************
 * Constants and objects
 *******************************/
namespace {
  char * SSID_NAME = "assign_your_wifi_ssid"; // Put here your SSID name
  char * SSID_PASS = "assign_your_wifi_ssid_password"; // Put here your Network password
  const char * SERVER = "things.ubidots.com";
  const char * TOKEN = "assign_your_ubidots_token"; // Assign your Ubidots TOKEN
  const char * DEVICE_LABEL = "arduino"; // Assign the device label to get the values of the variables
  const char * VARIABLE_LABEL_1 = "temperature"; // Assign the variable label to get the last value
  const char * VARIABLE_LABEL_2 = "humidity"; // Assign the variable label to get the last value
  const char * USER_AGENT = "ArduinoWifi";
  const char * VERSION = "1.0";
  const int PORT = 80;
  char str_temp[30];
  char str_hum[30];
}

WiFiClient client;

/********************************
 * Auxiliar Functions
 *******************************/

/*
   this method makes a HTTP connection to the server
   and send request to post data to Ubidots
*/

float SendToUbidots(char* payload) {

  char* topic = (char *) malloc(sizeof(char) * 700);
  uint8_t timeout = 0; // Max timeout to retrieve data
  uint8_t max_retries = 0; // Max retries to make attempt connection

  int i = strlen(payload); 
  /* Builds the request POST - Please reference this link to know all the request's structures https://ubidots.com/docs/api/ */
  sprintf(topic, "POST /api/v1.6/devices/%s/?force=true HTTP/1.1\r\n", DEVICE_LABEL);
  sprintf(topic, "%sHost: things.ubidots.com\r\n", topic);
  sprintf(topic, "%sUser-Agent: %s/%s\r\n", topic, USER_AGENT, VERSION);
  sprintf(topic, "%sX-Auth-Token: %s\r\n", topic, TOKEN);
  sprintf(topic, "%sConnection: close\r\n", topic);
  sprintf(topic, "%sContent-Type: application/json\r\n", topic);
  sprintf(topic, "%sContent-Length: %d\r\n\r\n", topic, i);
  sprintf(topic, "%s%s\r\n", topic, payload);
  
  /* Initial connection */
  client.connect(SERVER, PORT);
  
  /* Reconnect the client when is disconnected */
  while (!client.connected()) {
    Serial.println("Attemping to connect");
    if (client.connect(SERVER, PORT)) {
      break;
    }

    // Tries to connect five times as max
    max_retries++;
    if (max_retries > 5) {
      Serial.println("Could not connect to server");
      free(topic);
      return NULL;
    }
    delay(5000);
  }

  /* Make the HTTP request to the server*/
  client.print(topic);

  /* Reach timeout when the server is unavailable */
  while (!client.available() && timeout < 2000) {
    timeout++;
    delay(1);
    if (timeout >= 2000) {
      Serial.println(F("Error, max timeout reached"));
      client.stop();
      free(topic);
      return NULL;
    }
  }

  /* Reads the response from the server */
  while (client.available()) {
    char c = client.read();
    Serial.write(c); // Uncomment this line to visualize the response from the server
    if (c == -1) {
      Serial.println(F("Error reading data from server"));
      client.stop();
      free(topic);
      return NULL;
    }
  }
  free(topic);
  /* Disconnecting the client */
  client.stop();
}

/********************************
 * Main Functions
 *******************************/

void setup() {
  Serial.begin(115200);
  //Serial.println("Serial init...");
  /* Connects to AP */
  WiFi.begin(SSID_NAME, SSID_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    }

  Serial.println(F("WiFi connected"));
  Serial.println(F("IP address: "));
  Serial.println(WiFi.localIP());

}

void loop() {
  /* Reads sensors values */
  float temperature = 25.05;
  float humidity = 50.54;

  /*---- Transforms the values of the sensors to char type -----*/

  /* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
  dtostrf(temperature, 4, 2, str_temp);
  dtostrf(humidity, 4, 2, str_hum); 
  
  char* payload = (char *) malloc(sizeof(char) * 220);
  /* Builds the payload - {"temperature":25.00,"humidity":50.00} */
  sprintf(payload, "{\"");
  sprintf(payload, "%s%s\":%s", payload, VARIABLE_LABEL_1, str_temp);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_2, str_hum);
  sprintf(payload, "%s}", payload);

  Serial.println(payload);
  /* Calls the Ubidots Function POST */
  SendToUbidots(payload);
  
  /* Prints the data posted on the Serial Monitor */
  Serial.println("Posting data to Ubidots");
  Serial.print("Temperature: ");
  Serial.println(temperature);
  Serial.print("Humidity: ");
  Serial.println(humidity);
  
  /* free memory */
  free(payload);
  delay(5000);
}

I hope everything works properly!

All the best,
Maria C.

Thanks Maria!! I will give that a try, I tried the first code from jotathebest and it posted 2 times then the connection to ubidots is lost. The wifi101 board stays connected to my router but for some reason the connection to ubidots is lost.

Thanks
Jon

Maria, I just was able to try the code and unfortunately it only uploads twice then just fails to connect to the ubidots server. Below is a snapshot of the serial monitor:

WiFi connected
IP address:
67769516
{"xxxxxxx:25.05}
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 02 Sep 2017 22:40:44 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Vary: Cookie
Allow: POST, OPTIONS

34
{“xxxxxxx”: [{“status_code”: 201}]}
0

Posting data to Ubidots
Temperature: 25.05
Humidity: 50.54
{“xxxxxx”:25.05}
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 02 Sep 2017 22:40:50 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Vary: Cookie
Allow: POST, OPTIONS

34
{“xxxxxxxxxxxxxxxxx”: [{“status_code”: 201}]}
0

Posting data to Ubidots
Temperature: 25.05
Humidity: 50.54
{“xxxxxxxxxxx”:25.05}
Attemping to connect
Attemping to connect
Attemping to connect

Any other ideas? Maybe I just need to get a different board to use with Ubidots???

Thanks
Jon

It seems that your board loses the connection with the server, I do not know exactly why. Include a reconnect routine inside your loop() function, in that way you try to reconnect before of sending any data, below you can find a reconnection reference example piece of code:

/* Reconnect the client when is disconnected */
  while (!client.connected()) {
    Serial.println("Attemping to connect");
    if (client.connect(SERVER, PORT)) {
      break;
    }

    // Tries to connect five times as max
    max_retries++;
    if (max_retries > 5) {
      Serial.println("Could not connect to server");
      free(topic);
      return NULL;
    }
    delay(5000);
  }

About your question “Any other ideas? Maybe I just need to get a different board to use with Ubidots???”, as your actual board has been discontinued and it is out of the market, I advise you to use another board with better support, even a cheap ESP8266 would be a nice decision for your MVP.

Regards