ESP8266 – MQTT

Table of Contents

Sources

Starter-Code

Leave a Comment

				
					//    _  ___          __   _     _
//   | || \ \        / /  | |   (_)
//   | || |\ \  /\  / /__ | |__  _
//   |__   _\ \/  \/ / _ \| '_ \| |
//      | |  \  /\  / (_) | |_) | |
//      |_|   \/  \/ \___/|_.__/|_|.com
//
//  MQTT STARTER
//  ESP8266
//

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

#ifndef STASSID
#define STASSID "WIFISSID"
#define STAPSK  "WIFIPASSWORD"
#define MQTTUSR "MQTTUSER"
#define MQTTPW "MQTTPASSWORD"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* mqtt_server = "URL";
const unsigned int mqtt_port = 1883;
const char* mqtt_user = MQTTUSR;
const char* mqtt_password = MQTTPW;

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");
      // Once connected, publish an announcement...
      client.publish("closetHandler-awake", "hello world");
      // ... and resubscribe
      client.subscribe("closetHandler-input");
    } 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);

  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 > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("closetHandler-output", msg);
  }
}