Connection issues with losant, uploading data (sporadic reporting)

mqtt
esp8266
#1

Dear all,

I have a working code on and ESP8266 (nodeMCU) with a BME280 sensor that sends data to the Losant platform. Everything is showing in the dashboard and it works fine BUT sometimes the data packages are not taken by Losant. So, what I mean is, I let it report to Losant every 90 seconds and sometimes it reports 3-4 times after each other (so every 90 seconds) and then suddenly it skips 3-4 times (270 seconds) the data report.

When I look at the serial monitor in Arduino, the packages are send and were successful reported every 90 seconds. However when I look at the application log in Losant the device was authorized at that time but did not connect and thus did not report…

Even stranger, it is linked to the ESP.deepsleep time. If I take a deepsleep time of 20 seconds it constantly reports and connects. However,if I extend that time to 60 seconds the same happens again.
Also, the code and reporting only works when I leave out the while(!device.connect()) in the code… When I leave it in I get an mqttclient state error of -2.

Does anyone know what is going on?
I have been stuck on this for a month now… :frowning:

The code is below:

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Losant.h>
#include <Adafruit_BME280.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DNSServer.h> 
#include <ESP8266WebServer.h> 
#include <WiFiManager.h>

#define D1 5
#define D2 4
#define D3 0
#define D4 2

// assign the SPI bus to pins
#define BME_SCK D1
#define BME_MISO D4
#define BME_MOSI D2
#define BME1_CS D3

Adafruit_BME280 bme1(BME1_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

// Losant credentials.
const char* LOSANT_DEVICE_ID = "XXXXXXX";
const char* LOSANT_ACCESS_KEY = "XXXXXXX";
const char* LOSANT_ACCESS_SECRET = "XXXXXXX";

WiFiClientSecure wifiClient;
LosantDevice device(LOSANT_DEVICE_ID);

void connect() {
  WiFiManager wifiManager;
  //first parameter is name of access point, second is the password
  wifiManager.autoConnect("RTP_Sensor");
  Serial.println();
  Serial.print("Connecting to Losant...");
  Serial.print("Authenticating Device...");

  HTTPClient http;
  http.begin("http://api.losant.com/auth/device");
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Accept", "application/json");

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["deviceId"] = LOSANT_DEVICE_ID;
  root["key"] = LOSANT_ACCESS_KEY;
  root["secret"] = LOSANT_ACCESS_SECRET;
  String buffer;
  root.printTo(buffer);

  int httpCode = http.POST(buffer);

  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      Serial.println("This device is authorized!");
    } else {
      Serial.println("Failed to authorize device to Losant.");
      if (httpCode == 400) {
        Serial.println("Validation error: The device ID, access key, or access secret is not in the proper format.");
      } else if (httpCode == 401) {
        Serial.println("Invalid credentials to Losant: Please double-check the device ID, access key, and access secret.");
      } else {
        Serial.println("Unknown response from API");
      }
      Serial.println("Current Credentials: ");
      Serial.println("Device id: ");
    }
  } else {
    Serial.println("Failed to connect to Losant API.");
  }
  http.end();
  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

//  while(!device.connected()) {
//    delay(500);
//    Serial.println(device.mqttClient.state()); // HERE
//    Serial.print(".");
//}
  Serial.println("Connected! Ready for use!!");
}

void report(double Hum, double Temp, double DP, double Pres) {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  root["Humidity"] = Hum;
  root["Temperature"] = Temp;
  root["DewPoint"] = DP;
  root["Pressure"] = Pres;
  device.sendState(root);
}

void setup() {
  Serial.begin(115200);
  Serial.println(F("BME280 test"));

  // Wait for serial to initialize.
  while (!Serial) { }

    bool status;
    // default settings
    status = bme1.begin();
    if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring!");
    }
   bool toReconnect = false;
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Disconnected from WiFi");
    toReconnect = true;
  }
  if (!device.connected()) {
    Serial.println("Disconnected from MQTT");
    Serial.println(device.mqttClient.state());
    toReconnect = true;
  }
  if (toReconnect) {
    connect();
  }
  
  device.loop();
    float Hum = bme1.readHumidity();
    // Read temperature as Celsius (the default)
    float Temp = bme1.readTemperature();
    //calculate dewpoint
    int DP = (bme1.readTemperature()-0.36*(100.0-bme1.readHumidity()));
    // Read pressure
    float Pres = bme1.readPressure()/100.0F;
    Serial.print("Humidity = ");
    Serial.print(Hum);
    Serial.println(" %");
    Serial.print("Temperature = ");
    Serial.print(Temp);
    Serial.println(" *C"); 
    Serial.print("DewPoint = ");
    Serial.print(DP);
    Serial.println(" *C");
    Serial.print("Pressure = ");
    Serial.print(Pres);
    Serial.println(" hPa");
    report(Hum, Temp, DP, Pres);
  
  delay(3000);
  Serial.println("Going into deep sleep for 90 seconds");
  ESP.deepSleep(90e6); // is 90 seconds
}

void loop() {
}

Any help more than welcome!
Also, if I made some obvious mistakes in the code if you can please send me in the right direction with a link where I can learn more, that would be great. I am learning for a while now but I know there is still a lot to learn…

Thanks!
Tom

#2

Hi @PBM_Ugent,

We have a forum post here with a similar problem that provides some steps for debugging. I believe this should help, but if not, let me know and we will continue to look into this. :grinning:

I will also look into the deep sleep time to see how that might be affecting your connection.

Thanks!
Julia