Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

about publishing more than 2 topic #182

Open
mushfiq-heraclius-xen opened this issue Jul 20, 2016 · 22 comments
Open

about publishing more than 2 topic #182

mushfiq-heraclius-xen opened this issue Jul 20, 2016 · 22 comments

Comments

@mushfiq-heraclius-xen
Copy link

this library is just owsum and amazing i must admit it, it works very smooth whenever only 1 or 2 topic is published, but unfortunately when i try to publish more than 2 topic it starts malfunctioning........after publishing it gets stop and sometime it publishes again and then stop ......and then nothing is publishing anymore! whats the fix i can do to overcome this pathetic problem ??

@chrigu1981
Copy link

same here. any news on that?

@knolleary
Copy link
Owner

Sorry not to have followed up on this. Without a lot more detail as to what you're trying to do and what behaviour you're seeing I cannot help.

@chrigu1981
Copy link

chrigu1981 commented Nov 18, 2016

hi,

after a callback i set a flag that a message needs to publish. if the esp receives more than one callback in a short time the esp hangs forever without any exception. it seems that when the esp is publishing something and at the same time is receiving a callback the esp will hang...

i use an older version of the pubsubclient (1.99.1) but just tested with the current version and it seems to be the same...

thanks for the awsome library anyway :) i use it on about 20 devices.
just have some troubles on my 433Mhz Controller where i need to subscribe/publish to multiple topics

@Suxsem
Copy link

Suxsem commented Nov 18, 2016

Just for testing purpose, can you please try with my fork? https://github.com/suxsem/pubsubclient/

@chrigu1981
Copy link

thank you. i will take a look and give you feedback

@Suxsem
Copy link

Suxsem commented Nov 21, 2016

@chrigu1981 any news?

@chrigu1981
Copy link

hi @Suxsem
thank you very much. it works since 2 days without any problems

@BlackXDragon
Copy link

Hello, I have this same problem and @Suxsem 's fork isn't helping me... Please help...

@chrigu1981
Copy link

@BlackXDragon can you post your code?

@BlackXDragon
Copy link

@chrigu1981 this is the code:

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#include<string.h>

#include<SoftwareSerial.h>

#include <PubSubClient.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"

const char* mqtt_server = "broker.mqtt-dashboard.com";
long lastMsg = 0;

WiFiClient espClient;
PubSubClient client(espClient);

SoftwareSerial ss(D1,D2);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (((char)payload[0]=='$') && ((char)payload[1]=='#')) {
    ArduinoOTA.handle();
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESPConnext-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("blahbus", "connected");
      // ... and resubscribe
      client.subscribe("blahbusin");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  ss.begin(9600);
  Serial.println("Booting");
  WiFiManager wifiManager;

  if(!wifiManager.autoConnect("ConnextESP","conn***")) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());

  // Port defaults to 8266
  ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname("ConnextESPOTA");

  // No authentication by default
  ArduinoOTA.setPassword("conn***");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH)
      type = "sketch";
    else // U_SPIFFS
      type = "filesystem";

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  digitalWrite(2,HIGH);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void append(char* s, char c) {
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  Serial.print(".");
  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    char* op="";
    while(!ss.available());
    while(ss.available()) {
      append(op,ss.read());
    }
    Serial.println("\nSending data...");
    client.publish("blahbus",op);
  }
}

@chrigu1981
Copy link

you are trying to subscribe to just one topic? what in detail is the problem?

@BlackXDragon
Copy link

The problem is that the last line; i.e., client.publish("blahbus",op); publishes my data only once. It fails to send the data more than once.

@chrigu1981
Copy link

try to call client.loop(); in while loop

@BlackXDragon
Copy link

Ok, I'll try that...

@BlackXDragon
Copy link

This is my new code, and the problem still persists:

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#include<string.h>

#include<SoftwareSerial.h>

#include <PubSubClient.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"

const char* mqtt_server = "broker.mqtt-dashboard.com";
long lastMsg = 0;

WiFiClient espClient;
PubSubClient client(espClient);

SoftwareSerial ss(D1,D2);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (((char)payload[0]=='$') && ((char)payload[1]=='#')) {
    ArduinoOTA.handle();
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESPConnext-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("blahbus", "connected");
      // ... and resubscribe
      client.subscribe("blahbusin");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  ss.begin(9600);
  Serial.println("Booting");
  WiFiManager wifiManager;

  if(!wifiManager.autoConnect("ConnextESP","conn***")) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());

  // Port defaults to 8266
  ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname("ConnextESPOTA");

  // No authentication by default
  ArduinoOTA.setPassword("conn***");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH)
      type = "sketch";
    else // U_SPIFFS
      type = "filesystem";

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  digitalWrite(2,HIGH);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void append(char* s, char c) {
        int len = strlen(s);
        s[len] = c;
        s[len+1] = '\0';
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    char* op="";
    while(!ss.available()) {
      client.loop();
    }
    while(ss.available()) {
      append(op,ss.read());
      client.loop();
    }
    Serial.println("Sending data...");
    client.publish("blahbus",op);
  }
}

@BlackXDragon
Copy link

Hey!! @chrigu1981 !! I rectified the problem!! Thanks for the help!!!

@chrigu1981
Copy link

nice :) can you share what you‘ve done?

@BlackXDragon
Copy link

I used the TinyGPS++ library instead of using the raw bitstream from serial...

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

#include <TinyGPS++.h>

#include<string.h>

#include<SoftwareSerial.h>

#include <PubSubClient.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include "WiFiManager.h"

const char* mqtt_server = "broker.mqtt-dashboard.com";
long lastMsg = 0;

WiFiClient espClient;
PubSubClient client(espClient);

TinyGPSPlus gps;
SoftwareSerial ss(D1,D2);

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (((char)payload[0]=='$') && ((char)payload[1]=='#')) {
    ArduinoOTA.handle();
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESPConnext-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("blahbus", "connected");
      // ... and resubscribe
      client.subscribe("blahbusin");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  ss.begin(9600);
  Serial.println("Booting");
  WiFiManager wifiManager;

  if(!wifiManager.autoConnect("ConnextESP","conn***")) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());

  // Port defaults to 8266
  ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname("ConnextESPOTA");

  // No authentication by default
  ArduinoOTA.setPassword("conn***");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH)
      type = "sketch";
    else // U_SPIFFS
      type = "filesystem";

    // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  digitalWrite(2,HIGH);
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  if (now - lastMsg > 5000) {
    lastMsg = now;
    char* op="";
    sprintf(op,"%d,%d,%f,%d,%f,%f,%d,%d,%d,%f,%d,%f,%d,%f,%d",gps.satellites.value(),gps.satellites.isValid(),gps.hdop.value(),gps.hdop.isValid(),gps.location.lat(),gps.location.lng(),gps.location.isValid(),gps.date.value(),gps.time.value(),gps.altitude.meters(),gps.altitude.isValid(),gps.course.deg(),gps.course.isValid(),gps.speed.kmph(),gps.speed.isValid());
    Serial.println("Sending data...");
    client.publish("blahbus",op);
  }
}

@zihny
Copy link

zihny commented Apr 27, 2019

I'm currently having the same problem. I'm trying to publish 2 topics.
Below is code for only one topic and it works wonders,
`/**************

  • Include Libraries
    **************/
    #include <WiFi.h>
    #include <PubSubClient.h>
    #include "EmonLib.h" // Include Emon Library
    EnergyMonitor emon1; // Create an instance

/**************

  • Define Constants
    **************/
    #define WIFISSID "Phone" // Put your WifiSSID here
    #define PASSWORD "easyas123" // Put your wifi password here
    #define TOKEN "A1E-u6rc9XiBSNLOgxaumeak5qLcZrchc3" // Put your Ubidots' TOKEN
    #define MQTT_CLIENT_NAME "try" // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string;
    //it should be a random and unique ascii string and different from all other devices

#define VARIABLE_LABEL "sensor" // Assing the variable label
#define DEVICE_LABEL "esp32" // Assig the device label

#define SENSOR 35 // Set the GPIO12 as SENSOR

char mqttBroker[] = "things.ubidots.com";
char payload[100];
char topic[150];
// Space to store values to send
char str_sensor[10];
char str_lat[6];
char str_lng[6];

/**************

  • Auxiliar Functions
    **************/
    WiFiClient ubidots;
    PubSubClient client(ubidots);

void callback(char* topic, byte* payload, unsigned int length) {
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
String message(p);
Serial.write(payload, length);
Serial.println(topic);
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");

// Attemp to connect
if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
  Serial.println("Connected");
} else {
  Serial.print("Failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 2 seconds");
  // Wait 2 seconds before retrying
  delay(2000);
}

}
}

/**************

  • Main Functions
    **************/
    void setup()

{
Serial.begin(115200);
WiFi.begin(WIFISSID, PASSWORD);
// Assign the pin as INPUT
pinMode(SENSOR, INPUT);

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

while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}

Serial.println("");
Serial.println("WiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqttBroker, 1883);
client.setCallback(callback);
{
Serial.begin(9600);

emon1.current(35, 2.5); // Current: input pin, calibration.
}
}

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

double Irms = emon1.calcIrms(1480); // Calculate Irms only

sprintf(topic, "%s%s", "/v1.6/devices/try", DEVICE_LABEL);
sprintf(payload, "%s", ""); // Cleans the payload
sprintf(payload, "{"%s":", VARIABLE_LABEL); // Adds the variable label

float sensor = analogRead(SENSOR);
float lat = 6.101;
float lng= -1.293;

/* 4 is mininum width, 2 is precision; float value is copied onto str_sensor*/
dtostrf(sensor, 4, 2, str_sensor);
dtostrf(lat, 4, 2, str_lat);
dtostrf(lng, 4, 2, str_lng);

sprintf(payload, "%s {"value": %s", payload, str_sensor); // Adds the value
sprintf(payload, "%s, "context":{"lat": %s, "lng": %s}", payload, str_lat, str_lng); // Adds coordinates
sprintf(payload, "%s } }", payload); // Closes the dictionary brackets
Serial.println(Irms);
client.publish(topic, payload);
client.loop();
delay(1000);
}however it do not work when i try to add another topic. this is what i did after,/**************

  • Include Libraries
    **************/
    #include <WiFi.h>
    #include <PubSubClient.h>
    #include "EmonLib.h" // Include Emon Library
    EnergyMonitor emon1; // Create an instance

/**************

  • Define Constants
    **************/
    #define WIFISSID "Phone" // Put your WifiSSID here
    #define PASSWORD "easyas123" // Put your wifi password here
    #define TOKEN "A1E-u6rc9XiBSNLOgxaumeak5qLcZrchc3" // Put your Ubidots' TOKEN
    #define MQTT_CLIENT_NAME "try" // MQTT client Name, please enter your own 8-12 alphanumeric character ASCII string;
    //it should be a random and unique ascii string and different from all other devices

#define VARIABLE_LABEL "current" // Assing the variable label
#define VARIABLE_LABEL2 "sensor" // Assing the variable label

#define DEVICE_LABEL "esp32" // Assig the device label

#define SENSOR 35 // Set the GPIO12 as SENSOR*/

char mqttBroker[] = "things.ubidots.com";
char payload[100];
char topic[150];
char topic2[150];
// Space to store values to send
char str_current[10];
char str_sensor[10];
char str_lat[6];
char str_lng[6];

/**************

  • Auxiliar Functions
    **************/
    WiFiClient ubidots;
    PubSubClient client(ubidots);
    /PubSubClient client(ubidots2);/

void callback(char* topic, byte* payload, unsigned int length)
{
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
String message(p);
Serial.write(payload, length);
Serial.println(topic);
}

/* char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
String message(p);
Serial.write(payload, length);
Serial.println(topic2));*/

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println("Attempting MQTT connection...");

// Attemp to connect
if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
  Serial.println("Connected");
} else {
  Serial.print("Failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 2 seconds");
  // Wait 2 seconds before retrying
  delay(2000);
}

}
}

/**************

  • Main Functions
    **************/
    void setup()

{
Serial.begin(115200);
WiFi.begin(WIFISSID, PASSWORD);
// Assign the pin as INPUT
pinMode(SENSOR, INPUT);

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

while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}

Serial.println("");
Serial.println("WiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqttBroker, 1883);

client.setCallback(callback);
{

emon1.current(33, 25.7); // Current: input pin, calibration.
emon1.current(35, 2.5); // Current: input pin, calibration.

}

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

double Irms = emon1.calcIrms(1480); // Calculate Irms only
double Irms2 = emon1.calcIrms(1480); // Calculate Irms only

sprintf(topic, "%s%s", "/v1.6/devices/try", DEVICE_LABEL);
sprintf(payload, "%s", ""); // Cleans the payload
sprintf(payload, "{"%s":", VARIABLE_LABEL); // Adds the variable label

sprintf(topic2, "%s%s", "/v1.6/devices/try", DEVICE_LABEL);
sprintf(payload, "%s", ""); // Cleans the payload
sprintf(payload, "{"%s":", VARIABLE_LABEL2); // Adds the variable label

float current = emon1.Irms;
float sensor = analogRead(SENSOR);
float lat = 6.101;
float lng= -1.293;

/* 4 is mininum width, 2 is precision; float value is copied onto str_current*/
dtostrf(sensor,4,2,str_sensor);
dtostrf(current, 4, 2, str_current);

dtostrf(lat, 4, 2, str_lat);
dtostrf(lng, 4, 2, str_lng);

sprintf(payload, "%s {"value": %s", payload, str_current); // Adds the value
sprintf(payload, "%s, "context":{"lat": %s, "lng": %s}", payload, str_lat, str_lng); // Adds coordinates
sprintf(payload, "%s } }", payload); // Closes the dictionary brackets
Serial.print("current: ");
Serial.println(Irms);

sprintf(payload, "%s, "context":{"lat": %s, "lng": %s}", payload, str_lat, str_lng); // Adds coordinates
sprintf(payload, "%s", ""); // Cleans the payload*/

sprintf(payload, "%s {"value": %s", payload, str_sensor); // Adds the value
sprintf(payload, "{"%s":", VARIABLE_LABEL2); // Adds the variable label
sprintf(payload, "%s } }", payload); // Closes the dictionary brackets

Serial.print("current2: ");
Serial.println(Irms2);

client.publish(topic, payload);
client.publish(topic2,payload);

client.loop();
delay(1000);
}
`

anyone knows how?

@Psykozis
Copy link

@zihny Do you have fix it? I'm with same problem as you...
I'm trying to isolate the problem. but still with no idea.

@thijsdebont
Copy link

thijsdebont commented Mar 28, 2020

I see couple of things wrong with @zihny code. First, the delay(1000); in loop() is bad practice. It blocks everything for a long time. Second, the char pointers 'payload' and 'topic' are used as both a global variable for publishing ánd in the mqtt callback. The globals should be given another name, since it is likely it gets partially overwritten. Then the length of the global topic and topic2 variables. 150 is way too much. Set it something that actually matches the max topic length.

How are you checking if messages actually get published? I don't see any subscription in the sketch to trigger callback.

Edit: sprintf is used wrong as well. When setting up the payload, it points to the start of char array and overwrites the previous sprintf statement. Plus, you should use escape character ( \ ) before the quote marks that should be added as a character to the character string. Otherwise, the character string is terminated prematurely.

@Psykozis
Copy link

Psykozis commented Mar 29, 2020

@thijsdebont I create a new issuem cause Ithink I'm with another problem
but if you see a thing i don't, thanx man!
#725

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants