Hello community.
I am just getting started with MQTT. It’s been working pretty good. I can now switch a relay connected to a NodeMCU using openhab. I will write up a documentation, once everything works as expected. For me this is a huge challenge, because programming in C (well actually programming in general) is quite new to me. So bear with me with this probably rather simple task…
Here is my Arduino Code:
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
const char* ssid = "NAME of SSID";
const char* password = "pwdforWIFI";
const char* mqtt_server = "SERVERAdress";
const int switchRelay1 = D1;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(100);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
pinMode(switchRelay1, OUTPUT);
digitalWrite(switchRelay1, HIGH);
Serial.begin(115200);
delay(100);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
delay(2000);
}
void loop(){
if (!client.connected() && WiFi.status() == 3) {reconnect();}
client.loop();
delay(10);
}
void callback(char* topic, byte* payload, unsigned int length) {
String topicStr = topic;
Serial.println("Callback update.");
Serial.print("Topic: ");
Serial.println(topicStr);
if (topicStr == "mqtt/irrigation/relay1/switch")
{
if(payload[0] == '1'){
digitalWrite(switchRelay1, LOW);
client.publish("mqtt/irrigation/relay1/state", "1");
}
else if (payload[0] == '0'){
digitalWrite(switchRelay1, HIGH);
client.publish("mqtt/irrigation/relay1/state", "0");
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str(), "USERMQTT", "PWDMQTT")) {
Serial.println("MQTT connected");
client.subscribe("mqtt/irrigation/relay1/switch");
}
else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
I have one problem with the state: Whenever the Modul is restarted, I want it to send the initial state (OFF on startup) so that the switches in openhab return to OFF state. Where would I put the publish message client.publish("mqtt/irrigation/relay1/state", "0")
in the code? Does it belong in the void reconnect ()
part (the very end)? It tried yesterday and didn’t get it to work.