ESP32 – RF Module -> MQTT

Table of Contents

Links

Starter-Code

				
					//    _  ___          __   _     _
//   | || \ \        / /  | |   (_)
//   | || |\ \  /\  / /__ | |__  _
//   |__   _\ \/  \/ / _ \| '_ \| |
//      | |  \  /\  / (_) | |_) | |
//      |_|   \/  \/ \___/|_.__/|_|.com
//
//  RF-Relais -> MQTT
//  ESP32_Dev_v4 - NO onboard LED!
//

#include <WiFi.h>
#include <PubSubClient.h>

#define ONBOARD_LED 2
#define data_switch_1 16
#define data_switch_2 17
#define data_switch_3 18
#define data_switch_4 19

const char* ssid     = "";
const char* password = "";
const char* mqtt_user = "";
const char* mqtt_password = "";
const char* mqtt_server = "";
const unsigned int mqtt_port = 1883;

char* mqtt_outtopic = "garage/rfbridge/output";
char* mqtt_intopic = "garage/rfbridge/input";
char* mqtt_awaketopic = "garage/rfbridge/awake";
char* mqtt_awakemsg = "awake-rfbridge-esp32";
char* mqtt_alivetopic = "garage/rfbridge/alive";
char* mqtt_alivemsg = "alive-rfbridge-esp32-%ld";
unsigned int mqtt_aliveinterval = 1800; //0.5h

char* mqtt_switch1_topic = "garage/rfbridge/switch1";
char* mqtt_switch2_topic = "garage/rfbridge/switch2";
char* mqtt_switch3_topic = "garage/rfbridge/switch3";
char* mqtt_switch4_topic = "garage/rfbridge/switch4";

unsigned int digitalReadInterval = 150; // ms
unsigned long lastDigitalReadInterval = 0;

int state_switch_1 = 0;
int state_switch_2 = 0;
int state_switch_3 = 0;
int state_switch_4 = 0;

int old_state_switch_1;
int old_state_switch_2;
int old_state_switch_3;
int old_state_switch_4;

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;


void setup_wifi() {
  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  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) {
  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] == '1') {
    digitalWrite(ONBOARD_LED, LOW);
  } else {
    digitalWrite(ONBOARD_LED, HIGH);
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ClosetHandler-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), mqtt_user, mqtt_password)) {
      Serial.println("connected");

      client.publish(mqtt_awaketopic, mqtt_awakemsg);
      Serial.print("Awake message on: ");
      Serial.print(mqtt_intopic);
      Serial.print(" with message: ");
      Serial.println(mqtt_awakemsg);

      client.subscribe(mqtt_intopic);
      Serial.print("subscribed: ");
      Serial.println(mqtt_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() {
  Serial.begin(115200);
  pinMode(ONBOARD_LED, OUTPUT);
  pinMode(data_switch_1, INPUT_PULLUP);
  pinMode(data_switch_2, INPUT_PULLUP);
  pinMode(data_switch_3, INPUT_PULLUP);
  pinMode(data_switch_4, INPUT_PULLUP);

  // Tests the LED if it works
  for (int i = 0; i <= 8; i++) {
    digitalWrite(ONBOARD_LED, LOW);
    delay(200);
    digitalWrite(ONBOARD_LED, HIGH);
    delay(200);
  }

  delay(10);
  Serial.println(F("__________________________________________"));
  Serial.println(F(""));
  Serial.println(F("  _  _ __   v0.1   __     _      _ "));
  Serial.println(F(" | || |\\ \\        / /    | |    (_)"));
  Serial.println(F(" | || |_\\ \\  /\\  / /___  | |__   _ "));
  Serial.println(F(" |__   _|\\ \\/  \\/ // _ \\ | '_ \\ | |"));
  Serial.println(F("    | |   \\  /\\  /| (_) || |_) || |"));
  Serial.println(F("    |_|    \\/  \\/  \\___/ |_.__/ |_|"));
  Serial.println(F(""));
  Serial.println(F("__________________________________________"));
  Serial.println(F(""));

  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);


  Serial.println(F("__________________________________________"));
  Serial.println(F(""));
  Serial.println(F("RFBridge - Initialized"));
  Serial.println(F("__________________________________________"));
  Serial.println(F(""));
}

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

  unsigned long now = millis();
  if (now - lastMsg > (mqtt_aliveinterval * 1000)) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, mqtt_alivemsg, value);
    Serial.print("Publish alive message: ");
    Serial.println(msg);
    client.publish(mqtt_alivetopic, msg);
  }

  now = millis();
  if (now - lastDigitalReadInterval > digitalReadInterval) {
    lastDigitalReadInterval = now;

    // Switch 1
    state_switch_1 = digitalRead(data_switch_1);
    Serial.println(state_switch_1);

    if (state_switch_1 == 1) {
      old_state_switch_1 = 1;
    }
    if (state_switch_1 == 0 && old_state_switch_1 == 1) {
      old_state_switch_1 = 0;
      snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_1);
      client.publish(mqtt_switch1_topic, msg);
    }

    // Switch 2
    state_switch_2 = digitalRead(data_switch_2);
    Serial.println(state_switch_2);

    if (state_switch_2 == 1) {
      old_state_switch_2 = 1;
    }
    if (state_switch_2 == 0 && old_state_switch_2 == 1) {
      old_state_switch_2 = 0;
      snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_2);
      client.publish(mqtt_switch2_topic, msg);
    }

    // Switch 3
    state_switch_3 = digitalRead(data_switch_3);
    Serial.println(state_switch_3);

    if (state_switch_3 == 1) {
      old_state_switch_3 = 1;
    }
    if (state_switch_3 == 0 && old_state_switch_3 == 1) {
      old_state_switch_3 = 0;
      snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_3);
      client.publish(mqtt_switch3_topic, msg);
    }

    // Switch 4
    state_switch_4 = digitalRead(data_switch_4);
    Serial.println(state_switch_4);

    if (state_switch_4 == 1) {
      old_state_switch_4 = 1;
    }
    if (state_switch_4 == 0 && old_state_switch_4 == 1) {
      old_state_switch_4 = 0;
      snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_4);
      client.publish(mqtt_switch4_topic, msg);
    }
  }
}
				
			

Leave a Comment