Introduction: Remote Temperature Monitoring Using MQTT and ESP8266 Modules

If you want to monitor some remote temperatures this Instructable will show you can do this by using some ESP8266 modules, MQTT (with a broker), LCD screen (for local monitoring), home-assistant (for local and remote monitoring), and of cause some temperature sensors (I use DS18b20 as they are pretty good and cheap enough)

I will divide this Instructable into several little projects as there is quite a bit to do to get it all working. These will be:

  1. Build a temperature sensor using an ESP8266 and DS18b20 - output to serial
  2. Setup MQTT broker on a ubuntu server
  3. Modify the sketch on the ESP8266 to publish temperature to the MQTT broker
  4. Connect LCD screen to another ESP8266 for local monitoring (Instructable https://www.instructables.com/id/Using-a-Nodemcu-Devkit-esp8266-to-Display-Temperat/)
  5. Install and configure home-assistant on a ubuntu server (for local and remote monitoring)

Step 1: Build a Temperature Sensor Using an ESP8266 and DS18b20 - Output to Serial

Connecting the DS18b20 to the ESP8266 is very simple. The picture above along with the BreadBoard Fritzing should help.

You simply connect the left hand pin to Ground, the centre pin to the GPIO that you want to use (I use D1 which is GPIO5), and the right had ping to 5v.

Once this is all connected up you can use the Simple DallasTemperature example to get the temperature from the sensor which is sent to the serial output.

I added sensors.setResolution(12) which sets the resolution of the device to 12 bits so that I get a more precise temperature reading. You can see from the values below what you can expect from each of the bit resolutions:

Mode Resol Conversion time

9 bits 0.5°C 93.75 ms

10 bits 0.25°C 187.5 ms

11 bits 0.125°C 375 ms

12 bits 0.0625°C 750 ms

You can get the library for the DS18b20 from the Arduino Library manager, so no need to download it from github separately.


Step 2: Setup MQTT Broker on a Ubuntu Server

This part of the Instructable assumes you know how to install and update ubuntu. Once you have got this far you'll need to install mosquitto.

root@ubuntu:~# apt-get install mosquitto
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libwebsockets3
The following NEW packages will be installed
  libwebsockets3 mosquitto
0 to upgrade, 2 to newly install, 0 to remove and 3 not to upgrade.
Need to get 0 B/163 kB of archives.
After this operation, 490 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Selecting previously unselected package libwebsockets3:amd64.
(Reading database ... 64521 files and directories currently installed.)
Preparing to unpack .../libwebsockets3_1.2.2-1_amd64.deb ...
Unpacking libwebsockets3:amd64 (1.2.2-1) ...
Selecting previously unselected package mosquitto.
Preparing to unpack .../mosquitto_1.4.8-0mosquitto1_amd64.deb ...
Unpacking mosquitto (1.4.8-0mosquitto1) ...
Processing triggers for ureadahead (0.100.0-16) ...
Processing triggers for man-db (2.6.7.1-1ubuntu1) ...
Setting up libwebsockets3:amd64 (1.2.2-1) ...
Setting up mosquitto (1.4.8-0mosquitto1) ...
mosquitto start/running, process 12955
Processing triggers for libc-bin (2.19-0ubuntu6.7) ...

Once mosquitto is installed it should be running, check it by running a ps:

root@ubuntu:~# ps aux |grep mosquitto
mosquit+ 12955  0.1  0.0  37236  2420 ?        Ss   16:45   0:01 /usr/sbin/mosquitto -c /etc/mosquitto/mosquitto.conf
root     13307  0.0  0.0  11744   948 pts/0    S+   16:58   0:00 grep --color=auto mosquitto

Now if you run the following command to subscribe to the broker you should see nothing, but mosquitto_sub will sit and wait for something to be published to the broker.

root@ubuntu:~# mosquitto_sub -h localhost -v -t "#"

This will subscribe to all topics (as you've used the # for the topic) so anything that is sent to the broker will be displayed.

Then in another ssh window send a message to the broker as follows :

rot@ubuntu:~# mosquitto_pub -h localhost -t "ha/test" -m "Hello"

Then back in the other window that is running the mosquitto_sub you should see the following :

root@ubuntu:~# mosquitto_sub -h localhost -v -t "#"
ha/test Hello

This shows that the broker is working and is ready for receiving data from the ESP8266 nodes and sending it onto home-assistant.

Step 3: Modify the Sketch on the ESP8266 to Publish Temperature to the MQTT Broker

Now that the MQTT broker is running on your ubuntu server you can now update the sketch on your ESP8266 to start sending temperatures to it.

The follow sketch will need a little modifying to include your own wifi SSID and the IP address of your ubuntu server that has mosquitto running on it.

You will need the following libraries which you can get from github:

#include <ESP8266WiFi.h>

#include <PubSubClient.h>

#include <OneWire.h>

#include <DallasTemperature.h>

// Data wire is plugged into pin 2 on the Arduino #define ONE_WIRE_BUS 5

// Setup a oneWire instance to communicate with any OneWire devices // (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

// Update these with values suitable for your network. const char* ssid = ""; const char* password = ""; const char* mqtt_server = "";

WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; float temp = 0; int inPin = 5;

void setup_wifi() { delay(10); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); }

void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient_temperature_sensor")) { Serial.println("connected"); } 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); setup_wifi(); client.setServer(mqtt_server, 1883); pinMode(inPin, INPUT); sensors.begin(); }

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

long now = millis(); if (now - lastMsg > 60000) { lastMsg = now; sensors.setResolution(12); sensors.requestTemperatures(); // Send the command to get temperatures temp = sensors.getTempCByIndex(0); Serial.println(temp); if((temp > -20) && (temp <60)) { client.publish("ha/_temperature1", String(temp).c_str(),TRUE); } } }

.

Step 4: Install and Configure Home-assistant on a Ubuntu Server (for Local and Remote Monitoring)

For full instructions to install and configure home-assistant you can pop over to https://home-assistant.io/getting-started/. But here are some pointers to get things working.

You will need to have python3-pip installed first of all:

root@ubuntu:~# apt-get install python3-pip

Once pip is installed you can install home-assistant:

pip3 install homeassistant

You then just run hass as follows:

root@ubuntu:~# hass

This will run hass and will create a basic configuration file which we will now edit to add the sensor for the temperature.

Your home-assistant configuration file should be in your /home/USERID/.homeassistant dir, called configuration.yaml. Open this and you'll need to add a section for the MQTT server and add a new sensor to it as follows:

mqtt:
  broker: 127.0.0.1
  port: 1883
  keepalive: 1000
  protocol: 3.1
  client_id: home-assistant-1

sensor:
   platform: mqtt
   state_topic: "ha/_temperature1"
   name: "Back garden"
   unit_of_measurement: "°C"
   qos: 1

As you can see the state_topic is the same as what you have set in the sketch on the ESP8266. Once you have saved the config file, restart hass, by just pressing ctrl-c to stop it then run it again by typing hass again.

If you then browse to the IP address of your ubuntu server on port 8123 (default port for home-assistant) you should see something like the pic above.

If you want to add the temperature to a 'card' on the webpage, which does look much nicer, then you can just add a group for the temperatures (in this case just the one temperature for now) as follows:

group:  temperatures:
    name: Temperatures
    entities:
       - sensor.back_garden