MQTT PubSubClient Payload as String

Hi,

This is the code that worked for me.

//This is a simple code to handle MQTT payload as String.

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define C0 16
#define C1 5
#define C2 4
#define C3 0
#define C4 2
#define C5 14
#define C6 12
#define C7 13
#define C8 15

#define ssid “ssid”
#define password “pass”
#define mqtt_server “broker_ip”

#define client_name “NodeMCU 8CH”

const char* inTopic = “home/living”;
const char* msgTopic = “home/msg”;

char msgIN;

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
Serial.begin(115200);

setup_wifi();

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

pinMode(C0, OUTPUT);
pinMode(C1, OUTPUT);
pinMode(C2, OUTPUT);
pinMode(C3, OUTPUT);
pinMode(C4, OUTPUT);
pinMode(C5, OUTPUT);
pinMode(C6, OUTPUT);
pinMode(C7, OUTPUT);
pinMode(C8, OUTPUT);
digitalWrite(C0, LOW);
digitalWrite(C1, LOW);
digitalWrite(C2, LOW);
digitalWrite(C3, LOW);
digitalWrite(C4, LOW);
digitalWrite(C5, LOW);
digitalWrite(C6, LOW);
digitalWrite(C7, LOW);
digitalWrite(C8, LOW);

}
void loop()
{

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

client.loop();
delay(100);
}

void reconnect()
{
while (!client.connected())
{
Serial.println(“Attempting MQTT connection…”);

if (client.connect(client_name))
{
client.publish(msgTopic, “MQTT is connected”);
Serial.println(“connected”);
client.subscribe(inTopic);

}
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_wifi()
{

delay(100);

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

WiFi.begin(ssid, password);
WiFi.mode(WIFI_STA);

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

Serial.println(“WiFi connected”);
Serial.println("IP address: ");
Serial.print(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length)
{
String msgIN = “”;
for (int i=0;i<length;i++)
{
msgIN += (char)payload*;*
}
String msgString = msgIN;
Serial.println(msgString);

  • //Message as String*
  • if (msgString == “CH1ON”)*
  • {*
  • Serial.println(“Channel1 is ON”);*
  • client.publish(msgTopic, “Channel1 is ON”);*
  • digitalWrite(C1, HIGH);*
  • } else if (msgString == “CH1OFF”)*
  • {*
  • Serial.println(“Channel1 is OFF”);*
  • client.publish(msgTopic, “Channel1 is OFF”);*
  • digitalWrite(C1, LOW);*
  • }*
    }

//This is a simple code to handle MQTT payload as String.

Why on earth would you do THAT? Add a NULL to the payload, at the len position, and cast to a char *. Save boatloads of memory.