Hello
I am using esp8266 and MQTT.
I’m going to use publish and subscribe to output sensor values and switch toggle.
Outputting with ‘publish’ works well. However, ‘subscribe’ is ignored. Maybe the callback function is not called.
This is part of my code.
#include <ESP8266WiFi.h>
#include <PubSubClient.h> //MQTT
const char* mqtt_server = ""
const char* ssid = "";
const char* password = "";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
//WiFi Server
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
client.setCallback(callback); //MOTT receive callback
}
void loop() {
if (!client.connected()) //서버 연결 끊기면 다시 연결 대기
{
reconnect();
}
.
.
.
//Send to MQTT sensor value (success)
sprintf(bpm_msg, "BMP : %d", beatAvg);
client.publish("/bpm", bpm_msg);
sprintf(spo2_msg, "SPO2 : %d", SPO2f);
client.publish("/spo2", spo2_msg);
}
void reconnect()
{
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Try MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client"))
{
Serial.println("connected");
client.subscribe("/mode"); //received from mode topic
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) //call when received?
{
Serial.print("Message arrived ["); //Not outputed!!
Serial.print(topic);
Serial.print("] ");
String message;
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
//MQTT received
if (topic == '/mode') //mode토픽에서 수신
{
Serial.print("Status : ");
if ((char)payload[0] == 'on')
{
mode_state = 1;
Serial.println("ON");
}
if ((char)payload[0] == 'off')
{
mode_state = 0;
Serial.println("OFF");
}
}
}
And I used MQTT in Node RED.
On the dashboard, switch on/off control works well and outputs well to debug mqtt.
Can I get some help with this problem?
Thank you.