knolleary / pubsubclient

A client library for the Arduino Ethernet Shield that provides support for MQTT.
http://pubsubclient.knolleary.net/
MIT License
3.78k stars 1.46k forks source link

Callback topic is only 0 #986

Closed softwarecrash closed 1 year ago

softwarecrash commented 1 year ago

Hello, i struggle with the callback method, publish works great, subscribe working too, but when i neet the topic var to find out where the payload comes it gives me only 0 ore sometime 0! back. i have reduced my code to the essentials so it looks a little bit curios, to find the fault, without success. can anyone see my fault?

running on a esp8266 with saved wifi credits

#include <Arduino.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <ESPAsyncWiFiManager.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

WiFiClient client;
PubSubClient mqttclient(client);
String topicStrg;

AsyncWebServer server(80);
AsyncWebSocketClient *wsClient;
DNSServer dns;

bool testbool = false;

void callback(char *topic, byte *payload, unsigned int length)
{
    String messageTemp;
    for (unsigned int i = 0; i < length; i++)
    {
      messageTemp += (char)payload[i];
    }
    mqttclient.publish((topicStrg + "/debugmessage").c_str(), String(messageTemp).c_str());
    //here get only 0 so i cant switch between topic messages
    mqttclient.publish((topicStrg + "/debugtop").c_str(), String(topic).c_str());
    Serial.println(String(topic)); // gives 0␚ back
}

void setup()
{
  Serial.begin(9600);
  WiFi.persistent(true);                           // fix wifi save bug

  topicStrg = "test-bms/test"; // new test for simplify mqtt publishes
  AsyncWiFiManager wm(&server, &dns);

  bool res = wm.autoConnect("DALY-BMS-AP");

  wm.setConnectTimeout(30);       // how long to try to connect for before continuing
  wm.setConfigPortalTimeout(120); // auto close configportal after n seconds

  mqttclient.setServer("10.10.10.10", 1885);
  mqttclient.setCallback(callback);
  mqttclient.setBufferSize(512);

  if (!mqttclient.connected())
    mqttclient.connect("test", "mqttuser", "xxxx");
  if (mqttclient.connect("test"))
  {
    Serial.println("connected begin subscribe");
      mqttclient.subscribe(String(topicStrg + "/Pack_DischargeFET").c_str());
      mqttclient.subscribe(String(topicStrg + "/Pack_ChargeFET").c_str());
      mqttclient.subscribe(String(topicStrg + "/Pack_SOC").c_str());
  }
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    mqttclient.loop(); // Check if we have something to read from MQTT
  if(testbool == false)
  {
    mqttclient.publish((topicStrg + "/Pack_SOC").c_str(), String("100").c_str());
    mqttclient.publish((topicStrg + "/Pack_ChargeFET").c_str(), "true");
    mqttclient.publish((topicStrg + "/Pack_DischargeFET").c_str(), "true");
    testbool = true;
  }
  }
  //yield();
}