My DHT22 Fails to connect to Losant despite Authorized

Dear Team, Please I need help in connecting to Losant. From my dashboard I could see the device authorized but no temperature data is sent to Losant and on the IDE it kept displaying : connecting… for as long as i could watch it. below is my code, where could I have missed it? Please help Team.

/**
 * 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 = "xxxxxxxxx ";
const char* WIFI_PASS = "xxxxxxxxxxx";

// Losant credentials.
const char* LOSANT_DEVICE_ID = "5c969696750e410008xxxxxxxx";
const char* LOSANT_ACCESS_KEY = "71c6f048-58eb-49a4-9319-43xxxxxxxxx";
const char* LOSANT_ACCESS_SECRET = "e969e66abd3d19ad289e2927a7b950317720c250984d79062ef49axxxxxxxxxx";


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 5 seconds.
    if(millis() - wifiConnectStart > 5000) {
      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": "575ecf887ae143cd83dc4aa2",
   *     "key": "this_would_be_the_key",
   *     "secret": "this_would_be_the_secret"
   *   }
   *
   */

  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");
        }
      }
    } 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.print(".");
  }

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

void setup() {
  Serial.begin(9600);
  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) {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& root = jsonBuffer.createObject();
  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 2 seconds.
  if(timeSinceLastRead > 2000) {
    // 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;
}```

Hello @Ogbe_Isaac,

There are couple ways we can go about debugging this to find a solution. The code in question is:

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

  device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

  while(!device.connected()) {
    delay(500);
    Serial.print(".");
  }

The first step is to log the underlying MQTT client’s state to try to see why the board is not reaching Losant. Add a print to the connect loop:

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

This will log a number we can use for debugging.

The second step is detailed further in this forum post (the device in this post is different, but the steps are similar for debugging). The change here is to try connecting without SSL to see if that eliminates the issue. There’s only two changes that need to be made:

  1. Change WiFiSSLClient to WiFiClient
  2. Change device.connectSecure(...) to device.connect(...)

Also be sure to check that you have increased the underlying MQTT library’s memory limit, as detailed in this blog article:

The PubSubClinet MQTT library has a default memory limit that is not enough to support all the values that the DHT22 sensor can collect. The error is also not apparent, which makes it hard to track. To increase the memory limit, please check out this forum post.

Hopefully this helps,
Julia

Hello @JuliaKempf ,

I have the exact same problem described by @Ogbe_Isaac above.
I added the print to the connect loop

 Serial.println(device.mqttClient.state()); // HERE

And I’m getting a -2

Can you help me?
Thanks

2 Likes

Hello everyone!!!
i´m getting the same error -2,

what i did so far;
i edited the PubSubClient.h file and change original valuto from 128 to 256 (#define MQTT_MAX_PACKET_SIZE 256)

help us! please!!!

thanks in advance

2 Likes

Got it fix, ok here is what i did:
1- In the Arduino IDE Library:
i edited the PubSubClient.h file and change original value to from 128 to 256 (#define MQTT_MAX_PACKET_SIZE 256)

2- Change the following lines:

from:
WiFiClientSecure wifiClient;
to:
WiFiClient WiFiClient;

from:
device.connectSecure(wifiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);
to:
device.connect(WiFiClient, LOSANT_ACCESS_KEY, LOSANT_ACCESS_SECRET);

this work for me.

08

4 Likes

ARE THESE LINES IN HEADER FILE ?

I am using the Adafruit Feather Huzzah w/ESP8266 and not able to read the DHT! Any tips? I have played around the code and used the Huzzah and DHT code that I got to work - but not getting to work with Losant. The above steps by Daniel work very well and I DO CONNECT. But no DHT data :frowning:

1 Like

I got it to work… but getting some errors on the other end…

Anybody seen this?

FIXED - changed the case on the device and all worked.

2 Likes

I did this and it worked… Thank you, thank you very much. 4 days of suffering have now ended. Have a good one mate!

2 Likes