Device won't transmit to Losant, mqttClient.state -2

@Wayne_Hughes,

Would you happen to be providing your own id? That id should be an id of a Losant Device. To help, you can copy the ID in the UI:

1 Like

DING DING DING!

So I had a friendly name associated with my device and I thought that was the device ID. When I hit the copy button it gave me a generated ID which I put into my sketch and now it connects - thank you!!!

1 Like

Thank you @Pinyo_Folvig, unfortunately the device still doesn’t want to connect even with the certificate included.

I was able to include the MQTT error code @anaptfox used for testing though.
For the return code I get: LWMQTT_SUCCESS = 0
For the error code I get: LWMQTT_NETWORK_FAILED_CONNECT = -3

Each time I start up the device, I get an “authentication succeeded” message in the Losant dashboard for my device ID but nothing happens after this.

@anaptfox any ideas what the problem could be based on these codes?

@Elizabeth_McGee,

Would you be able to provide a snippet of the code currently running on your device?

Since your last post, we have updated the the example code in our GitHub repository.

Something I find interesting, though:

Each time I start up the device, I get an “authentication succeeded” message in the Losant dashboard for my device ID but nothing happens after this.

Are you getting this message first, and then after some time, your device is disconnecting from Losant? How much time is passing between a successful connection and the disconnect?

Any extra information you can provide will help me give you the best answer I can!

Thank you,
Heath

Hi @Heath,

Below is the code I am using for my device, it is based on the original sketch provided by @anaptfox here, however I am using the WEMOS D1 Mini Pro instead of the board listed in the tutorial. I also updated the code to JSON 6. I get the “authentication succeeded” message as soon as the device is connected but it seems to disconnect immediately based on the error codes in the serial monitor. There is no indication in the Losant application log that the device has disconnected, but it doesn’t log any sensor readings either. I reviewed the link you provided with the updated examples but unfortunately don’t know too much about this language to understand which sections need changed on my end. Do you see anything in the code I currently have that would be causing the problem?

Thank you,
Elizabeth

#include <Losant.h>
/**
 * Example for sending temperature and humidity
 * to the cloud using the DHT22 and ESP8266
 *
 * Copyright (c) 2016 Losant IoT. All rights reserved.
 * https://www.losant.com
 */


#include "DHT.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Losant.h>



#define DHTPIN 4     // what digital pin the DHT22 is conected to
#define DHTTYPE DHT22   // There are multiple kinds of DHT sensors

DHT dht(DHTPIN, DHTTYPE);



// WiFi credentials.
const char* WIFI_SSID = "xxxx";
const char* WIFI_PASS = "xxxx";

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

// Cert taken from 
// https://github.com/Losant/losant-mqtt-ruby/blob/master/lib/losant_mqtt/RootCA.crt
static const char digicert[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh
MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD
QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT
MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB
CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97
nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt
43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P
T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4
gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO
BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR
TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw
DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr
hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg
06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF
PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls
YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk
CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=
-----END CERTIFICATE-----
)EOF";

BearSSL::WiFiClientSecure wifiClient;

LosantDevice device(LOSANT_DEVICE_ID);



// WiFiClientSecure wifiClient;

// LosantDevice device(LOSANT_DEVICE_ID);

void connect() {

  // Connect to Wifi.
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  // WiFi fix: https://github.com/esp8266/Arduino/issues/2186
  WiFi.persistent(false);
  WiFi.mode(WIFI_OFF);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  unsigned long wifiConnectStart = millis();

  while (WiFi.status() != WL_CONNECTED) {
// Check to see if
if (WiFi.status() == WL_CONNECT_FAILED) {
  Serial.println("Failed to connect to WIFI. Please verify credentials: ");
  Serial.println();
  Serial.print("SSID: ");
  Serial.println(WIFI_SSID);
  Serial.print("Password: ");
  Serial.println(WIFI_PASS);
  Serial.println();
}

delay(500);
Serial.println("...");
// Only try for 30 seconds seconds.
if(millis() - wifiConnectStart > 30000) {
  Serial.println("Failed to connect to WiFi");
  Serial.println("Please attempt to send updated configuration parameters.");
  return;
}
  }

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

  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");

  /* Create JSON payload to sent to Losant
   *
   *   {
   *     "deviceId": "xxxxx",
   *     "key": "this_would_be_the_key",
   *     "secret": "this_would_be_the_secret"
   *   }
   *
   */

StaticJsonDocument<200> doc;
JsonObject root = doc.to<JsonObject>();
  root["deviceId"] = LOSANT_DEVICE_ID;
  root["key"] = LOSANT_ACCESS_KEY;
  root["secret"] = LOSANT_ACCESS_SECRET;
  String buffer;
serializeJson(doc, 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");
    }
  }
} else {
    Serial.println("Failed to connect to Losant API.");

   }

  http.end();

  // Connect to Losant.
  Serial.println();
  Serial.print("Connecting to Losant...");


  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  while(!device.connected()) {
delay(500);
   // Serial.println(device.mqttClient.state()); // HERE
   Serial.println("Last Error:");
Serial.println(device.mqttClient.lastError());
Serial.println("Return Code:");
Serial.println(device.mqttClient.returnCode());
Serial.println("."); 
  }

  Serial.println("Connected!");
  Serial.println();
  Serial.println("This device is now ready for use!");
}

void setup() {
  Serial.begin(115200);
  Serial.setTimeout(2000);

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

  Serial.println("Device Started");
  Serial.println("-------------------------------------");
  Serial.println("Running DHT!");
  Serial.println("-------------------------------------");

  connect();
}



void report(double humidity, double tempC, double tempF, double heatIndexC, double heatIndexF) {
StaticJsonDocument<500> doc;
JsonObject root = doc.to<JsonObject>();
  root["humidity"] = humidity;
  root["tempC"] = tempC;
  root["tempF"] = tempF;
  root["heatIndexC"] = heatIndexC;
  root["heatIndexF"] = heatIndexF;
  device.sendState(root);
  Serial.println("Reported!");
}





int timeSinceLastRead = 0;
void loop() {
   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();

  // Report every 15 minutes.
  if(timeSinceLastRead > 900000) {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true) 
float f = dht.readTemperature(true);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
  Serial.println("Failed to read from DHT sensor!");
  timeSinceLastRead = 0;
  return;
}

// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print("Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
report(h, t, f, hic, hif);

timeSinceLastRead = 0;
  }
  delay(100);
  timeSinceLastRead += 100;
}

Hi @Elizabeth_McGee ,

I don’t think your variables are lining up. Try aligning the variables in the loop section with the report section:
“root[“humidity”] = humidity;”
would be:
“root[“humidity”] = h;”

I would also try using just “report();” instead of “report(h, t, f, hic, hif);” - might be a little more flexible in the future to add new items.

HTH

Also, wanted to be sure to thank @anaptfox for the help - I now have data showing up in the graph - hooray!!!