ESP8266 – Mini Pir, Switches & MQTT

Table of Contents

Sources

				
					//    _  ___   v0.1   __   _     _
//   | || \ \        / /  | |   (_)
//   | || |\ \  /\  / /__ | |__  _
//   |__   _\ \/  \/ / _ \| '_ \| |
//      | |  \  /\  / (_) | |_) | |
//      |_|   \/  \/ \___/|_.__/|_|.com
//
//  Closet Handler
//  ESP8266 - NodeMCU v0.3
//
// SWITCH = 1 => closed
// PIR    = 1 => movement #Problem if nothing connected because of pullup its still a 1!
//
// Code isn't 100% finished but should work!
//

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

#define LED LED_BUILTIN
#define data_switch_1 D1
#define data_switch_2 D2
#define data_pir_1 D5
#define data_pir_2 D6

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_intopic = "closetHandler-input";
char* mqtt_awaketopic = "closetHandler-awake";
char* mqtt_awakemsg = "awake-ClosetHandler";
char* mqtt_alivetopic = "closetHandler-alive";
char* mqtt_alivemsg = "alive-ClosetHandler-%ld";
unsigned int mqtt_aliveinterval = 1800; // s

char* mqtt_pir1_topic = "closet/at/pir1";
char* mqtt_pir2_topic = "closet/at/pir2";

char* mqtt_switch1_topic = "closet/at/switch1";
char* mqtt_switch2_topic = "closet/at/switch2";

unsigned int mqtt_pir1_message_interval = 10000; // ms
unsigned long mqtt_pir1_lastsent_message = 0;

unsigned int mqtt_pir2_message_interval = 10000; // ms
unsigned long mqtt_pir2_lastsent_message = 0;

unsigned int mqtt_switch1_message_interval = 1000; // ms
unsigned long mqtt_switch1_lastsent_message = 0;

unsigned int mqtt_switch2_message_interval = 1000; // ms
unsigned long mqtt_switch2_lastsent_message = 0;

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


int state_switch_1 = 0;
int old_state_switch_1;
int state_switch_2 = 0;
int old_state_switch_2;
int state_pir_1 = 0;
int old_state_pir_1;
int state_pir_2 = 0;
int old_state_pir_2;


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(BUILTIN_LED, LOW);
  } else {
    digitalWrite(BUILTIN_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: ");

      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(LED_BUILTIN, OUTPUT);
  pinMode(data_switch_1, INPUT_PULLUP);
  pinMode(data_switch_2, INPUT_PULLUP);
  pinMode(data_pir_1, INPUT_PULLUP);
  pinMode(data_pir_2, INPUT_PULLUP);

  // Tests the LED if it works
  for (int i = 0; i <= 8; i++) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(200);
    digitalWrite(LED_BUILTIN, 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("ClosetHandler - 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 == HIGH) {
      digitalWrite(LED_BUILTIN, HIGH);
    } else {
      digitalWrite(LED_BUILTIN, LOW);
    }
    // Switch 2
    state_switch_2 = digitalRead(data_switch_2);
    Serial.println(state_switch_2);
    // Pir 1
    state_pir_1 = digitalRead(data_pir_1);
    Serial.println(state_pir_1);
    // Pir 2
    state_pir_2 = digitalRead(data_pir_2);
    Serial.println(state_pir_2);
  }

  // PUBLISH MSGS
  // Switch 1
  if (now - mqtt_switch1_lastsent_message > mqtt_switch1_message_interval && old_state_switch_1 != state_switch_1) {
    old_state_switch_1 = state_switch_1;
    mqtt_switch1_lastsent_message = now;
    snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_1);
    client.publish(mqtt_switch1_topic, msg);
  }

  // Switch 2
  if (now - mqtt_switch2_lastsent_message > mqtt_switch2_message_interval && old_state_switch_2 != state_switch_2) {
    old_state_switch_2 = state_switch_2;
    mqtt_switch2_lastsent_message = now;
    snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_switch_2);
    client.publish(mqtt_switch2_topic, msg);
  }

  // Pir 1
  if (now - mqtt_pir1_lastsent_message > mqtt_pir1_message_interval && state_pir_1 == 1) {
    mqtt_pir1_lastsent_message = now;
    snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_pir_1);
    client.publish(mqtt_pir1_topic, msg);
  }

  // Pir 2
  if (now - mqtt_pir1_lastsent_message > mqtt_pir1_message_interval && state_pir_1 == 1) {
    mqtt_pir1_lastsent_message = now;
    snprintf (msg, MSG_BUFFER_SIZE, "%ld", state_pir_1);
    client.publish(mqtt_pir1_topic, msg);
  }

}
				
			

Leave a Comment