DHT / my_mqtt.h.sample /
8d9981e 5 years ago
1 contributor
56 lines | 1.852kb
#ifndef _MQTT_H
#define _MQTT_H

#include <PubSubClient.h> // Allows us to connect to, and publish to the MQTT broker


// MQTT
const int MAX_MQTT_CNX_RETRIES = 3;
static char mqtt_server[32] = "";
const char* mqtt_server_int = "192.168.0.1";
const char* mqtt_server_ext = "a.domain.tld";
const char* mqtt_topic = "topicDHT";
const int   mqtt_port = 1883;
// The client id identifies the ESP8266 device. Think of it a bit like a hostname (Or just a name, like Greg).
char clientID[22] = "";
const char* clientIDFmt="esp-%s";

const char* mqtt_user="esp8266";
const char* mqtt_password="SomeRandomPassword";

// Initialise the WiFi and MQTT Client objects
WiFiClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); // 1883 is the listener port for the Broker

void mqtt_connect() {
  if( 0 == strcmp(aplist[currentAPIndex].ssid,"wifi1") ) {
    //House Wifi
    client.setServer(mqtt_server_int, mqtt_port);
    //if (client.connect(clientID)) {
    if (client.connect(clientID,mqtt_user,mqtt_password)) {
      Serial.println("Connected to MQTT Broker : "+String(mqtt_server_int));
    } else {
      Serial.println("Connection to MQTT Broker "+String(mqtt_server_int)+"failed...");
      delay(2000);
    }
  } else {
    // External Wifi
    client.setServer(mqtt_server_ext, mqtt_port);
    if (client.connect(clientID,mqtt_user,mqtt_password)) {
      Serial.println("Connected to MQTT Broker : "+String(mqtt_server_ext));
    } else {
      Serial.println("Connection to MQTT Broker "+String(mqtt_server_ext)+"failed...");
      delay(2000);
    }
  }    
}

void mqtt_reconnect() {
  byte count = 0;
  while (!client.connected() && count < MAX_MQTT_CNX_RETRIES ) {
    Serial.print("Attempting MQTT reconnection...");
    mqtt_connect();
    count++;
  }
}
#endif //_MQTT_H