CallBack MQTT PUBSUB doesn't work

Hi Once I got it all working but now after weeks of trying it doesn't. It's a simple sketch about using MQTT for sending and receiving a message. Sending works fine but receiving doesn't give any respond. Not even the topic. What do I do wrong? Can anyone help me? I would like to ad my code to this topic, how can I do that? Hope I did it well.

#include <ArduinoJson.h>

//#include <Arduino_JSON.h>

#include <DallasTemperature.h>
#include <OneWire.h>
const int temperature_pin = 21; // connection pin DS18B20
OneWire oneWire(temperature_pin);
DallasTemperature sensors(&oneWire);
/*
  This skech works on a 32ESP dev wroom board to
*/
#include <PubSubClient.h>
#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti WiFiMulti;
WiFiClient espClient;
PubSubClient mqttClient(espClient);

const uint8_t mqtt_server[] = {192, 168, 2, 150};
const char* WiFiUser = "XXXXXXXX";
const char* WiFiPassword = "XXXXXXXXX";
const char* mqttUser = "";
const char* mqttPassword = "";
const int DomoticzInx = 8;
//int readerHumidity = 0;
//const int reader_1 = 35; // connection pin sensor humidity
//const int reader_1_power = 32;
char msg[50];
int value = 0;
float temperatureOld ;

const int ledPin = 15; // connection pin relais
// StaticJsonDocument<200> doc; // <- a little more than 200 bytes in the stack
//JSONVar data;

// ////////////////call back////////////////////////////////////
void callback(char* topic, byte* payload, unsigned int length) {

  char str[length + 1];
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  int i = 0;
  for (i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    str[i] = (char)payload[i];

  }
  str[i] = 0; // Null termination
  Serial.println();
  //practise string
  //char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

  StaticJsonDocument <256> doc;
  deserializeJson(doc, payload);


  // deserializeJson(doc,str); can use string instead of payload
  const char* sensor = doc["sensor"];
  long time          = doc["time"];
  float latitude    = doc["data"][0];
  float longitude   = doc["data"][1];


  Serial.println("latitude =");
  Serial.println(latitude, 2);
  Serial.println(sensor);

}
// ///////////////reconnect////////////////////////////
void reconnect() {
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("esp32temp666666666666", mqttUser, mqttPassword)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

// ////////////////////////////setup/////////////////////
void setup()
{
  Serial.begin(115200);
  delay(100);

  sensors.begin(); // Start the DS18B20 sensor
  WiFiMulti.addAP(WiFiUser, WiFiPassword);  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Waiting for WiFi... ");

  while (WiFiMulti.run() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

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

  mqttClient.setServer(mqtt_server, 1883);
  mqttClient.setCallback(callback);

  pinMode(ledPin, OUTPUT);
}

// //////////////////////////loop////////////////////////
void loop()
{
  if (!mqttClient.connected()) {
    reconnect();
  }
  mqttClient.loop();


  sensors.requestTemperatures();                      //prepair and send
  delay(20);
  float temperatureC = sensors.getTempCByIndex(0);
  if ((temperatureC < (temperatureOld - 0.3)) or (temperatureC > (temperatureOld + 0.3)) ) {
    temperatureOld = temperatureC;
    char tempString[8];
    dtostrf(temperatureC, 1, 1, tempString);
    Serial.print("Temperatue: ");
    Serial.println(tempString);
    toDomoticzTemp(tempString);
  }

}
// ////////////////SendToDomotczTemperature//////////////////////////////

void toDomoticzTemp(String temperature) {
  StaticJsonDocument<256> doc;
  doc["idx"] = DomoticzInx ;
  //data["nvalue"] = 22;
  doc["svalue"] = temperature ;
  char out[128];
  int b = serializeJson(doc, out);
  Serial.print("publishing bytes = ");
  Serial.println(b, DEC);
  mqttClient.publish("domoticz/in", out);

  // “domoticz/in” , “{ \”idx\”:1,\”nvalue\”:0,\”svalue\”:\”18.4\”}// tempeature
  // “domoticz/in” , “{ \”idx\”:2,\”nvalue\”:0,\”svalue\”:\”1.2 ; 33 ; 1\”}// first temp, then hum, then ?

}

first off, edit you post and use code tags for your script please

secondly, I would not use delay() in void loop() {}

Serial prints in a callback, not a good idea for working code. The pubsub ISR should be lean and quick. Just receive the data and use another function to parse the received data.

Which topic does your code subscribe to?

Get rid of the delay in loop().

And you should not be doing the multi post on the same subject thing.

CODE TAGS???????

Other post/duplicate DELETED
Please do NOT cross post / duplicate as it wastes peoples time and efforts to have more than one post for a single topic.

Continued cross posting could result in a time out from the forum.

Could you also take a few moments to Learn How To Use The Forum.

Other general help and troubleshooting advice can be found here.
It will help you get the best out of the forum in the future.

If you post your code as described in How to get the best out of this forum, more forum members will read it.

This is good advise, but it has nothing to do with the original question.

Any ISR should be clean and quick, but this still doesn't answer the question.

But.

If you don't subscribe to a topic then you can't have any pudding. How can you have any pudding if you don't subscribe to a topic?

1 Like

Tank you all for your help. I've learned some useful things. But could you also give me a hand with solving the problem about the function CallBack not responding? The Serial.print was added to see what happens in the CallBack function and the delay was added later after having a little misunderstanding between me and the reading of the temperature sensor. Most of the time I get the right temperature read out but once in a while it seems to be -127 c and it doesn't feel that cold at all. I don't think that the delay() or the Serial.print are the problem for not working of the CallBack function.

Idohowalker many thanks. It took me a while to understand but it's working now. I added mqttClient.subscribe("domoticz/out"); to the function reconnect and the CallBack function works fine. Thanks everyone for your help, you've save my live probably as I was becoming pretty desperate.

1 Like