ESP8266 WiFi module

From Domoticz
Jump to: navigation, search

Using a ESP8266 as a WiFi temperature sensor for Domoticz

Background

The ESP8266 is a complete and self-contained WiFi network solution.

In it's original form it is a simple serial to WiFi converter that can be used to interact with the serial ports of micro-controllers over WiFi. But you can flash the units with other, community driven, firmware. These firmwares give the ESP8266 the ability to operate without a micro-controller, and run code in its own processor. It has GPIO ports that can be utilized for attaching sensors or switches. The possibilities are almost endless.

See https://nurdspace.nl/ESP8266 for more info about this cheap WiFi module.


In this example I will show you what is needed to use a standalone ESP8266 with a 1wire DS18B20 temp. sensor attached to one of the available GPIO ports, and have it send the temp. value with intervals to Domoticz.

There are some prequisits that I will not describe.

You must be able to flash the ESP8266 (see http://www.xess.com/blog/esp8266-reflash/ for instance)

You know something about LUA scripting

You know how to put LUA script on the ESP8266. I like to use ESPlorer for this. http://esp8266.ru/esplorer/

You must be able to create a virtual temp. sensor.


Creating a virtual temp. sensor

The first step is to create a virtual temp. sensor. So, first create a Dummy harware device and then select Temperature from the devices drop down list.

Write down the index numer of the temp. sensor you have created. You will need it later.


Setting up your ESP8266

I have chosen to use NodeMcu (http://nodemcu.com/index_en.html) as the firmware for my ESP8266. This gives me the ability to run LUA scripts natively on my ESP8266.

After flashing the ESP8266 with NodeMcu, it will search for an file called init.lua at boot. So that will be the first file we have to create.

In this script we will tell the module the info it needs to connect to the WiFi network, and which script to run next.


Because some like DHCP, and some like fixed IP adresses I've added both examples.

Init.lua wich uses DHCP

 --init.lua
 wifi.setmode(wifi.STATION)
 wifi.sta.config("YOUR SSID","YOUR KEY")
 wifi.sta.connect()
 tmr.alarm(1, 1000, 1, function()
  if wifi.sta.getip()== nil then
  print("IP unavaiable, Waiting...")
 else
  tmr.stop(1)
 print("ESP8266 mode is: " .. wifi.getmode())
 print("The module MAC address is: " .. wifi.ap.getmac())
 print("Config done, IP is "..wifi.sta.getip())
 dofile ("domoticz.lua")
 end
 end)

init.lua wich uses fixed IP adresses

 wifi.setmode(wifi.STATION)
 wifi.sta.config("YOUR SSID","YOUR KEY")
 wifi.sta.connect()
 wifi.sta.setip({ip="FIXED IP ADDRESS",netmask="YOUR NETMASK",gateway="YOUR GATEWAY"})
 print("ESP8266 mode is: " .. wifi.getmode())
 print("The module MAC address is: " .. wifi.ap.getmac())
 print("Config done, IP is "..wifi.sta.getip())
 dofile ("domoticz.lua")


After uploading the init.lua file to the ESP8266, you can reboot it to see that is connects to your WiFi network. It wil give you an error because it searches for an other script (domoticz.lua) that we are going to create now.

The next step is creating the LUA script that reads the temparature and sends it to your Domoticz server. This script has one dependency, a lua sript called ds18b20.lua. This script can be found at the github repository of NodeMcu (https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_modules/ds18b20/ds18b20.lua) and does not need any changes before uploading it to the ESP8266.

I have connected my DS18B20 sensor to GPIO2 on the ESP8266, but you can connect it to any GPIO pin you want. Just put a 4.7k resistor between VDD and the Data line of the DS18B20 and change it in the script so it matches your setup. The ID of my virtual temp. sensor was 32. Don't forget to change it to the id of your sensor.

Script that sends the data to Domoticz.

 --domoticz.lua
 require('ds18b20')
 -- ESP-01 GPIO Mapping
 gpio0 =3
 gpio2 =4
 ds18b20.setup(gpio2)
 t=ds18b20.read()
 print("Temp:" .. ds18b20.read() .. " C\n")
 if(t==nil) then
 t=0
 end
 tmr.alarm(0,30000, 1, function()
 t=ds18b20.read()
 conn=net.createConnection(net.TCP, 0)
 conn:on("receive", function(conn, payload) print(payload) end )
 conn:connect(8080,"DOMOTICZ IP")
 conn:send("GET /json.htm?type=command&param=udevice&idx=32&nvalue=0&svalue=" .. t .. " HTTP/1.1\r\nHost: www.local.lan\r\n"
 .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
 end)

Wrap up

At this point, you should have an ESP8266 with three files on it. init.lua, ds18b20.lua and domoticz.lua. This enables it to logon to your wifi network, read the DS18B20 and send the data to Domoticz every 30 seconds. Just add a powersupply to it, and put it anywhere. You only need WiFi reception at the place you put it.

Have fun!

Other projects with ESP8266 and Domoticz

LED-dimmer and WiFi-wallswitch

Quindor has made a few nice tutorials to create a ESP8266 WiFi LED-dimmer that can be controlled by Domoticz.

ESP8266 WiFi LED dimmer Part 1 of X: The setup
ESP8266 WiFi LED dimmer Part 2 of X: The Hardware
ESP8266 WiFi LED dimmer Part 3 of X: Flashing and programming the ESP-01
ESP8266 WiFi LED dimmer Part 4 of X: Configuring Domoticz
ESP8266 WiFi LED dimmer Part 5 of X: Ikea Lamp hacks
ESP8266 WiFi LED dimmer Part 6 of X: ESP8266 Domoticz Wall Switch

kWh-pulse counter and gasmeter reader

A user from the Dutch forum Tweakers has made some code to read the pulses of the blinking LED on your electricity-meter. It can also read your gasmeter (if it has a magnet inside the counter) with a reedswitch.
You can find his code here: http://gathering.tweakers.net/forum/list_message/43783066#43783066
The description is in Dutch unfortunately.

Measuring temperatures of central heating to improve efficiency

By using a ESP8266 and 2x DS18B20 temperature sensors you can measure the temperature of the incoming & outgoing pipes of your central gas heater ('CV-ketel' in Dutch). This is conventient when improving efficiency of your installation.
By making your installation more efficient (see this Dutch topic for how to do that: http://gathering.tweakers.net/forum/list_messages/1619229 ) you can save a lot of money on your gasbill!
For this you need good logging, which can be made by using the ESP8266 and some Python logging + graphing that a forum member ('nickyb2') made.
The ESP project can be found here http://domoticz.com/forum/viewtopic.php?f=38&t=5301#p36556

Coffee machine controlled via Domoticz

I worked on a WiFi enabled coffee machine, it uses an esp8266 to control the machine and displays a custom widget in Domoticz (using the interface Dashticz)
WiFi on my coffe machine part 1 planning
WiFi on my coffe machine part 2 installing the esp8266 in the machine
WiFi on my coffe machine part 3 Domoticz setup

Note: Although the above mentioned project is documented extensively in the three pages (links), it does not work as advertised. One should be prepared to do some circuitboard redesign and scripting redesign (or rewrite) to get this functioning with correct status being displayed in domoticz all the time. The project as described is however a good place to start!

Battery powered temperature and humidity sensors

I started making a network of WiFi enabled sensors in my house. They are using the esp8266 and are battery powered so they can be put anywhere. Using the esp8266 deep sleep capacity, I managed to achieve several weeks autonomy with a set of li-ion batteries.
powered temperature and humidity sensors

ESP Easy

Perhaps a other very simple way to use the ESP with Domoticz.
Flash the firmware [ very simple ] and you have a lot modules to use much different devices in Domoticz!
link: ESP Easy
Perhaps the easy est way to use the ESP with Domoticz

ESP8266 Temperature sensor using Arduino IDE


This method uses an ESP8266 programmed via the arduino IDE, to send sensor data directly to Domoticz. It is easily adaptable for an arduino with ethernet or wifi add ons.

Add virtual hardware
To be able to communicate with devices like the ESP, we have to add virtual hardware to Domoticz. This step has to be done only once in your setup.

From the main Domoticz Menu, Select Setup -> Hardware Add type "Dummy" making sure to tick the enabled box, and leave data time out disabled.

Create a virtual sensor
The new hardware should be in the list and there should be a button "Create Virtual Sensors" Click the button "Create Virtual Sensors" and choose Sensor Type "Temp+Hum"

From the main Domoticz Menu, Select Setup -> Devices Note down the IDX number of your virtual sensor - you'll need to add it to the arduino code.

Sending data from arduino/ESP to Domoticz
This uses HTTP GET. Formatting must be correct.
http://www.domoticz.com/wiki/Domoticz_API/JSON_URL%27s#Temperature.2Fhumidity has a list of all urls that Domoticz uses.

Temperature/humidity

domoticzIP:PORT/json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP;HUM;HUM_STAT

   IDX = id of your device (This number can be found in the devices tab in the column "IDX")
   TEMP = Temperature
   HUM = Humidity
   HUM_STAT = Humidity status

HUM_STAT can be one of:

   0=Normal
   1=Comfortable
   2=Dry
   3=Wet

Arduino IDE code

#include <Wire.h>
#include <SparkFun_Si7021_Breakout_Library.h> //https://github.com/sparkfun/Si7021_Breakout/blob/master/Libraries/Arduino/Si7021/src/SparkFun_Si7021_Breakout_Library.h
#include <ESP8266WiFi.h>

// int status = WL_IDLE_STATUS;     // the Wifi radio's status
WiFiClient client;

// domoticz
 const char * domoticz_server = "192.168.1.10"; //Domoticz port
 int port = 8080; //Domoticz port
 int idx = 5; //IDX for this virtual sensor, found in Setup -> Devices

 float humidity = 0;
 float temp = 0;
  
 // Create Instance of HTU21D or SI7021 temp and humidity sensor and MPL3115A2 barrometric sensor
 Weather sensor;
  
 void setup()
 {
     // Initialize the I2C sensors and ping them
     sensor.begin();
 }

 void loop()
 {
    // Get readings from all sensors
    getWeather();
    printInfo();
    delay(60000); // Wait 60 seconds
 }

 void getWeather()
 {
    // Measure Relative Humidity from the HTU21D or Si7021
    humidity = sensor.getRH();
    // Measure Temperature from the HTU21D or Si7021
    temp = sensor.getTemp();
    // Temperature is measured every time RH is requested. It is faster, therefore, to read it from previous RH measurement with getTemp() instead with readTemp()
 }
   
 void printInfo()
 {
    // Domoticz format /json.htm?type=command&param=udevice&idx=IDX&nvalue=0&svalue=TEMP;HUM;HUM_STAT

    if (client.connect(domoticz_server,port)) {

        client.print("GET /json.htm?type=command&param=udevice&idx=");
        client.print(idx);
        client.print("&nvalue=0&svalue=");
        client.print(temp);
        client.print(";");
        client.print(humidity);
        client.print(";0"); //Value for HUM_STAT. Can be one of: 0=Normal, 1=Comfortable, 2=Dry, 3=Wet
        client.println(" HTTP/1.1");
        client.print("Host: ");
        client.print(domoticz_server);
        client.print(":");
        client.println(port);
        client.println("User-Agent: Arduino-ethernet");
        client.println("Connection: close");
        client.println();
        
        client.stop();
     }
  }