Control ESP8266 via a Webfront end using MQTT

Let’s control an ESP8266 via a web front end using MQTT.
I created my own personal hosted home automation server called LittleNodes.com for everyone to use for free. I pretty much used the below method to build it. Its running on Ubuntu and using the Mosquitto MQTT server.

It turned out pretty awesome if I may say so my self. For some inspiration head over to LittleNodes.com to get an idea of what’s possible using the information in this tutorial.

 

We will use an Apache based web server and PHP with Mosquitto MQTT server to accomplish this.
In this tutorial the ESP8266 will subscribe to a MQTT topic and we will let our web server control the built in LED of the ESP8266 on IO pin 2. In my case I’m using a NodeMCU.

First let’s get a bare minimum Mosquitto server setup. Everyrhing in this guide will be done using Windows. Setting it up using your favorite Linux distro wouldn’t  be much different but will not be covered here.

Download Mosquitto MQTT

After downloading it extract and copy the Publisher, Server and subscriber executable along with the config file into a separate folder of your choice.

Below is an example of the files you need.

Don’t change anything in the config yet, for this tutorial we will not be making use of any passwords or anything fancy.

Create 2 batch files, these batch files will only be used to test that our setup is working.

Batch File 1: localpub_off.bat
Replace the below mentioned IP with the IP of your computer where the MQTT server will be running.

mosquitto_pub -h 192.168.1.200 -p 1883 -m "0" -t "test" -d 

Batch File 2: localpub_on.bat
Replace the below mentioned IP with the IP of your computer where the MQTT server will be running.

mosquitto_pub -h 192.168.1.200 -p 1883 -m "1" -t "test" -d 

Note the 1 and the 0 in the batch file after -m (Message)

-h is the server
-p is the TCP port number. Port 1883 is the default.
-t is the topic
-d enables debug mode so we have a bit of verbose when things don’t work

Now over to the ESP8266
Download and install a MQTT pub/sub library.

Don’t bother with the example pub sub library, I prepared a bare minimum sketch for you.
In the below sketch change the IP and WIFI credentials to yours. Even though a username and password is specified in the below sketch the server will ignore it because authentication is not setup. I’m leaving it there so you know where to set it.

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


// Update these with values suitable for your network.

const char* ssid = "WIFI_AP_NAME";
const char* password = "WIFI_AP_PASSWORD";
const char* mqtt_server = "YOUR PC IP";

WiFiClient espClient;
PubSubClient client(espClient);


void setup_wifi() {

  delay(10);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }


}

void callback(char* topic, byte* payload, unsigned int length) {
  for (int i = 0; i < length; i++) {Serial.print((char)payload[i]);}

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {digitalWrite(2, LOW);} 
    else {
      digitalWrite(2, HIGH);  // Turn the LED off by making the voltage HIGH
       }

}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP8266Client-";
    if (client.connect(clientId.c_str(),"user","pass" )   ) 
    {  
      client.subscribe("test");
    } else {
      delay(5000);
    }
  }
}

void setup() {
  pinMode(2, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(250000);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);

  digitalWrite(2, LOW);
  delay(2000);
  digitalWrite(2, HIGH);
  
}

void loop() 
{

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


}

Via the command prompt navigate to the folder where you copied the server, broker publisher and config file. And then start the mosquitto server with the -v switch. The -v switch will output detailed connection activity.

mosquitto -v

Press the reset button on your ESP8266 so force it to reconnect to your MQTT server

As seen in the screenshot you should see your ESP8266 connect to your server.

From there execute the batch files we created earlier on.
Start with localpub_on.bat

The LED on the ESP9266 should turn on almost instantly. and should also turn off when you execute localpub_off.bat

If all went well you now have a workingMQTT server and ESP8266 based MQTT client that accept commands from the MQTT broker.

In order to control the ESP8266 from a web front-end we need to create a page that will execute the same commands that get’s executed when running the batch script via PHP.

For this we will use a MySQL/PHP/APACHE Stack. Either WAMP or XAMP will do. I prefer XAMP easier to install and is free of hastle unlike WAMP. But use what you wish.

Create a new folder in the document root of your Web server. When using WAMP it will be the www folder and XAMP it will be the htdocs folder.

Create 3 PHP files.

1. index.php

<html>


	<head>
	
	</head>
	
	<body>
	


<h2>My MQTT Switch</h2>



		
		<button onclick="SwitchOn()">Turn on ESP LED</button>
		<button onclick="SwitchOff()">Turn off ESP LED</button>
		
		


<h5>Console</h5>


</html>
	
</body>



	<script>
		
function SwitchOn()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("ActivityConsole").innerHTML = "LED turned On";
    }
};
xhttp.open("GET", "on.php", true);
xhttp.send();
}

function SwitchOff()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       document.getElementById("ActivityConsole").innerHTML = "LED turned Off";
    }
};
xhttp.open("GET", "off.php", true);
xhttp.send();
}		
		
	</script>

 

 

2. on.php

<?php exec('mosquitto_pub -h 192.168.1.200 -p 1883 -m "1" -t "test" -d'); ?>

3. off.php

<?php exec('mosquitto_pub -h 192.168.1.200 -p 1883 -m "0" -t "test" -d'); ?>

The page should look like this.

When you click the buttons the LED of the eSP8266 should turn on and off. Using Java script will also allow you to turn on and off the LED without a page refresh.

 

That’s It! and you are done.
In my next tutorial I will show you how you can turn all of this into a mobile app for Android and IOS using Cordova.

 

 

 

You May Also Like

About the Author: Martin Viljoen

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA ImageChange Image