DHT22 getting started device.sendState problem

Hey I´m struggeling withe the DHT22 project.
I followed the Instruction and the description about the update from json5 to json6.
But Now the code can not be compiled. I always get the following error:
no matching function for call to ‘LosantDevice::sendState(ArduinoJson6161_11::StaticJsonDocument<500u>&)’

If i uncomment the device.sendState line the code works, but no data is send.
Also sendState is not coloured like in the example

Hello @Matthias_Kamps,

Welcome to the Losant forums, we’re happy you’re here!

Would you be able to send me a link to the example you’re following? Would you also be able to send me your code, or at least some snippets of it?

Thank you,
Heath

Of Course!
This is the example:

And a snippet of my code:

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

Is there any way to post the complete code?

@Matthias_Kamps,

You sent the exact snippet I was looking for, I appreciate it!

You’re using StaticJsonDocument correctly, which is great. But you’re missing one small step. StaticJsonDocument is ArduinoJson’s type for JSON, you’ll need to cast it to a JSON object before sending state since Losant is expecting a JSON Obejct.

You can do this by adding JsonObject root = doc.to<JsonObject>(); and then modifying the device.sendState to be device.sendState(root);

So your function would look like:

void report(double humidity, double tempC, double heatIndexC) {
  StaticJsonDocument<500> doc;

  doc[“humidity”] = humidity;
  doc[“tempC”] = tempC;
  //doc[“tempF”] = tempF;
  doc[“heatIndexC”] = heatIndexC;
  //doc[“heatIndexF”] = heatIndexF;
  JsonObject root = doc.to<JsonObject>();
  device.sendState(root);
  Serial.println(“Reported!”);
}

Let me know if this works for you or if you have any other questions.

Thanks,
Heath

The code can be compiled now and there is communication.
But there is still no data transfer.
grafik

@Matthias_Kamps,

I think this would be the perfect place to see the rest of your code!

Are you getting sensor readings in your serial monitor?
How are you calling the report() function you defined?

I’d also like to point out that our forums have a great search utility. Here are some links I found that are similar to your question:

Thank you,
Heath

Yes, I can see my measurements on ther serial monitor.

Here is my complete code:
(Sorry for so many parts, but it did not work in One Post)

#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 = "XX";
const char* WIFI_PASS = "XX";

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


WiFiClient 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"
   *   }
   *
   */

  StaticJsonDocument<200> doc;

  doc["deviceId"] = LOSANT_DEVICE_ID;
  doc["key"] = LOSANT_ACCESS_KEY;
  doc["secret"] = LOSANT_ACCESS_SECRET;
  String buffer;
  serializeJson(doc, Serial);

  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.connect(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) { }
  
  dht.begin();

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

  connect();
}
void report(double humidity, double tempC, double heatIndexC) {
  StaticJsonDocument<500> doc;
  
  doc["humidity"] = humidity;
  doc["tempC"] = tempC;
  //doc["tempF"] = tempF;
  doc["heatIndexC"] = heatIndexC;
  //doc["heatIndexF"] = heatIndexF;
  device.sendState(doc);
  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, hic);

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

@Matthias_Kamps,

Thanks so much!

You mentioned that you are getting measurements in your serial monitor. Would you be able to send me a screenshot of that? One that includes the startup sequence, and the first few sensor readings?

Thank you,
Heath

Shure!
I just cuted out the SSID, the Dievice ID, the key and the secret

@Matthias_Kamps,

The code you sent is still missing a piece in the report function. Were you able to implement the changes above with the JsonObject?

void report(double humidity, double tempC, double heatIndexC) {
  StaticJsonDocument<500> doc;

  doc[“humidity”] = humidity;
  doc[“tempC”] = tempC;
  //doc[“tempF”] = tempF;
  doc[“heatIndexC”] = heatIndexC;
  //doc[“heatIndexF”] = heatIndexF;

  JsonObject root = doc.to<JsonObject>();

  device.sendState(root);
  Serial.println(“Reported!”);
}

Another debug option you have is to go into your local copy of the Losant client code and add a Serial.println(stateStr) before mqttClient.publish in LosantDevice.h. You can find this file in your Arduino Libraries, usually at Documents/Arduino/Libraries. Doing this would allow you to see exactly what is being sent as state to Losant.

Thank you,
Heath

Oh you´re right I sent you a former version of my Code.
This is the current verison:

#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>


#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 = "";
const char* WIFI_PASS = "";

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


WiFiClient 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"
   *   }
   *
   */

  StaticJsonDocument<200> doc;

  doc["deviceId"] = LOSANT_DEVICE_ID;
  doc["key"] = LOSANT_ACCESS_KEY;
  doc["secret"] = LOSANT_ACCESS_SECRET;
  String buffer;
  serializeJson(doc, Serial);

  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.connect(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) { }
  
  dht.begin();

  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;
  
  doc["humidity"] = humidity;
  doc["tempC"] = tempC;
  doc["tempF"] = tempF;
  doc["heatIndexC"] = heatIndexC;
  doc["heatIndexF"] = heatIndexF;
  JsonObject root = doc.to<JsonObject>();
  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;
}

I can´t find this line in my LosantDevice.h
There is only : MQTTClient mqttClient = MQTTClient(MQTT_MAX_PACKET_SIZE);

@Matthias_Kamps,

My apologies. It should be in LosantDevice.cpp.

I’m looking over your code now!

Thank you,
Heath

Yes that worked!
It looks in deed, like it does not send any data.

@Matthias_Kamps,

Thank so much, this is certainly interesting.

Would you be able to add serializeJson(root, Serial); to your report function? It would look like this:

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

This will allow you to see what the root object looks like before we send it to Losant.

Thank you,
Heath

Of course!
This is what the serial monitor shows now:

By the way, thank you for your help already. Never seen such fast an qualified response in a Forum!!

@Matthias_Kamps,

Something small, but I think it may be the issue.

In your code you have: JsonObject root = doc.to<JsonObject>();

Instead of .to<... it should be .as<...

So you’re new line there would be:

JsonObject root = doc.as<JsonObject>();

Cheers,
Heath

That´s it !!
Thank you verry much!
Nice to get some help from a genius! :smiley:

1 Like