Smart Home – Programming ESP8266 Module
Assuming your module is already armed with the NodeMCU firmware, its time to program our end point so we could control it remotely through wifi. In our case at the moment, we simply need to control one of its output PIN to give out power ( Switch on / off ) depending on the signals we send through our home bridge device.
An easy way to do this is to run a small webserver on our ESP module and set few url’s to control our output. In our case we just need two unique url’s to switch on and off. Or we can also create a more generic url which we can pass on PIN numbers and STATUS to switch on and off. but that seems unnecessarily open and i’d prefer to have pre defined urls according to the need.
Its time to start programming our module. Assuming you already have ESPlorer application and its all setup to communicate with your device, lets insert the following lua code in to the ESP module.
wifi.setmode(wifi.STATION)
wifi.sta.config("WIFI_SSID","WIFI_PASSWORD")
led1 = 0
gpio.mode(led1, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(client,request)
local buf = "";
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf = buf.."
<h1> ESP8266 Web Server</h1>
”;
buf = buf..”
GPIO0 <a href="?pin=ON1"><button>ON</button></a> <a href="?pin=OFF1"><button>OFF</button></a>
”;
local _on,_off = "",""
if(_GET.pin == “ON1”)then
gpio.write(led1, gpio.LOW);
elseif(_GET.pin == “OFF1”)then
gpio.write(led1, gpio.HIGH);
end
—client:send(buf);
client:close();
collectgarbage();
end)
end)
This is a temporary script i’ve written to test things out at the time of writing this posts. Incase i forgot to come back here and update, please get the latest codes from here https://github.com/nilansanjaya/smart-home/
When you are done sending that code to your ESP module, you should now be able to switch on and off its built in LED light using the below url’s ( Assuming you are connected to the same wifi network )
http://youripaddress/?pin=ON1
http://youripaddress/?pin=OFF1
If that’s working, you can simply send requests to this through homebridge. Details on that should be on another post.