Hello,
Im having problems with my code, im trying to call "void callback" but its not doing its code part.
MQTT is working - its publishing "1.switch Online" when it connects to broker.
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define wifi_ssid "SSID"
#define wifi_password "SSID_PASS"
#define mqtt_server "192.168.8.2"
#define mqtt_user "openhab"
#define mqtt_password "PASS"
#define humidity_topic "sensor/humidity"
#define temperature_topic "sensor/temperature"
#define DHTPIN 13
#define Relejs 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE,15);
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, 1883);
pinMode(Relejs, OUTPUT);
digitalWrite(Relejs, HIGH);
client.setCallback(callback);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(wifi_ssid);
WiFi.begin(wifi_ssid, wifi_password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
// If you do not want to use a username and password, change next line to
// if (client.connect("ESP8266Client")) {
if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
Serial.println("connected");
client.publish("/home/openhab/in/DEMO_STATE","1.switch Online");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
callback;
}
void callback(char* topic, byte* payload, unsigned int length) {
//convert topic to string to make it easier to work with
String topicStr = topic;
client.publish("/home/openhab/in/DEMO_STATE","CALLBACK IS WORKING");
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
client.publish("/home/openhab/in/DEMO_Temp",String(t).c_str(),true);
client.publish("/home/openhab/in/DEMO_Hum",String(h).c_str(),true);
Serial.print(t);
Serial.print(h);
delay(5000);
if (topicStr == "/home/openhab/DEMO_SWITCH/")
{
//turn the switch on if the payload is '1' and publish to the MQTT server a confirmation message
if(payload[0] == 'ON'){
digitalWrite(Relejs, LOW);
client.publish("/home/openhab/DEMO_SWITCH/", "1");
}
//turn the switch off if the payload is '0' and publish to the MQTT server a confirmation message
else if (payload[0] == 'OFF'){
digitalWrite(Relejs, HIGH);
client.publish("/home/openhab/DEMO_SWITCH/", "0");
}
}
}