M8dhouse
Published © GPL3+

IFTTT Button - adapted from Noel Portugal

This is a slightly adapted version of the excellent IFTTT Smart Button from Noel Portugal

BeginnerWork in progress6,555
IFTTT Button - adapted from Noel Portugal

Things used in this project

Hardware components

Espressif ESP8266 ESP-3
×1
Resistor 1k ohm
Resistor 1k ohm
×1
15K resistor
×1
1N4007 – High Voltage, High Current Rated Diode
1N4007 – High Voltage, High Current Rated Diode
×1
microswitch
×1

Software apps and online services

Maker service
IFTTT Maker service

Story

Read more

Code

init.lua

Lua
Startup LUA - provide 5 sec delay and then start real init file (my case two.lua)
--Startup file this will launch NextFile after 5sec delay so you can reset files after crash loops
NextFile="two.lua"
 l = file.list();
    for k,v in pairs(l) do
    --  print("name:"..k..", size:"..v)
         if k == NextFile then
         print("Wait 5 seconds please")
         tmr.alarm(0, 5000, 0, function() dofile(NextFile) end)
         print("Started file ".. NextFile)
         else
       --  do nothing
         end
    end
print("End of startup") 

two.lua

Lua
Init file
replace <MAKENAME> with the name of your event
replace <YOURKEY> with the key provided by IFTT for your MAKE channnel
replace the GPIO-ID to your GPIO output (here 6 = GPIO 12 on the ESP-3 / use 4 for the GPIO 2 of the ESP-1)
--init.lua - check correct ID for GPIO - here set to GPIO12
gpio.mode(6, gpio.OUTPUT)
gpio.write(6, gpio.HIGH)
cnt = 0

function file_exists(name)
   fileresult=file.open(name,"r")
   print(fileresult)
   if fileresult~=nil then file.close(fileresult) return true else return false end
end

if file_exists("customurl.txt") then 
    print("Custom URL")
    file.open("customurl.txt", "r")
    IFTTurl = file.readline()
    file.close()
    IFTThost = IFTTurl:match('^%w+://([^/]+)')
    print(IFTTurl)
    print(IFTThost)
  else
    print("Default URL")
    file.open("customurl.txt", "w+");
    IFTTurl = "http://maker.ifttt.com/trigger/<MAKENAME>/with/key/<YOURKEY>"
    IFTThost = "maker.ifttt.com"
    file.write(IFTTurl)
    file.flush()
    file.close()
end

print("Starting SmartButton: " .. node.chipid())
tmr.alarm(1, 1000, 1, function()
if wifi.sta.getip()== nil then
    cnt = cnt + 1
    print("(" .. cnt .. ") Waiting for IP...")
    if cnt == 10 then
        tmr.stop(1)
        dofile("setwifi.lua")
    end
else
    print(wifi.sta.getip())
    tmr.stop(1)
    dofile("ifttt.lua")
   
end
end)

iftt.lua

Lua
iftt execution code
--ifttt.lua
--URL and host come out of customurl.txt file
print("Sending to IFTTT")
print("URL: " .. IFTTurl)
print("Host: " .. IFTThost)
conn = nil
conn=net.createConnection(net.TCP, 0) 

conn:on("receive", function(conn, payload) 
    --Shutdown!
    gpio.write(6, gpio.LOW)

    --If esp is enabled that means the button is still pushed!
    tmr.alarm(0, 2000, 1, function()
        print("button pressed")
        reset()
    end)
     
end) 
     
conn:on("connection", function(conn, payload) 
     conn:send("GET " .. IFTTurl 
      .." HTTP/1.1\r\n" 
      .."Host: " .. IFTThost .. "\r\n"
      .."Accept: */*\r\n" 
      .."User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n" 
      .."\r\n")
      print("IFTTT request sent.") 
end) 
                                       
conn:dns(IFTThost,function(conn,ip) 
    if (ip) then
        print("We can connect to " .. ip)
        conn:connect(80,ip)
    else
        reset()
    end
end)

function reset()
    print("Resetting Wifi..")
    wifi.sta.disconnect()
    wifi.sta.config("","")
    dofile("setwifi.lua")
end

setwifi.lua

Lua
set wifi and start webpage
-- URL decode function
function unescape (s)
   s = string.gsub(s, "+", " ")
   s = string.gsub(s, "%%(%x%x)", function (h)
         return string.char(tonumber(h, 16))
       end)
   return s
end

--setwifi.lua
print("Entering wifi setup..")
wifi.setmode(wifi.STATIONAP)
--add ChipID to SSID
nodessid = "SmartButton" .. node.chipid()
cfg={}
    cfg.ssid=nodessid
  --cfg.password="12345678" --comment to leave open
wifi.ap.config(cfg)

ipcfg={}
    ipcfg.ip="192.168.1.1"
    ipcfg.netmask="255.255.255.0"
    ipcfg.gateway="192.168.1.1"
wifi.ap.setip(ipcfg)

--create server instance
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
        --get variables from the URL decode them and them place them in _GET array
        local _GET = {}
        if (vars ~= nil) then
            for name, value in string.gfind(vars, "([^&=]+)=([^&=]+)") do
              name = unescape(name)
              value = unescape(value)
              _GET[name] = value
              print(name)
              print(value)
            end

        end
        if path == "/favicon.ico" then
            conn:send("HTTP/1.1 404 file not found")
            return
        end   
        if (path == "/" and  vars == nil) then
            buf = buf.."<html><body style='width:90%;margin-left:auto;margin-right:auto;background-color:LightGray;'>";
            buf = buf.."<h1>SmartButton Wifi Configuration</h1>"
            buf = buf.."<form action='' method='get'>"
            buf = buf.."<h4>SSID:</h4>"
            buf = buf.."<input type='text' name='ssid' value='' maxlength='100' width='100px' placeholder='required' />"
            buf = buf.."<br><br>"
            buf = buf.."<h4>Password:</h4>"
            buf = buf.."<input type='text' name='password' value='' maxlength='100' width='100px' placeholder='required' />"
            buf = buf.."<br><br>"
            buf = buf.."<h4>Command:</h4>"
            buf = buf.."<input type='text' name='customurl' value='" .. IFTTurl .. "' maxlength='300' width='300px' />"
            buf = buf.."<p><input type='submit' value='Submit' style='height: 25px; width: 100px;'/></p>"
            buf = buf.."</body></html>"
    
        elseif (vars ~= nil) then
            restarting = "<html><body style='width:90%;margin-left:auto;margin-right:auto;background-color:LightGray;'><h1>Restarting...You may close this window.</h1></body></html>"
            client:send(restarting);
            client:close();
            if (_GET.ssid) then
                --save URL in text file
                file.remove("customurl.txt")
                tmr.delay(1000)
                file.open("customurl.txt", "w")
                file.write(_GET.customurl)
                file.flush()
                file.close()
                print("Setting to: ".. _GET.ssid)
                tmr.alarm(0, 5000, 1, function()
                wifi.setmode(wifi.STATION);
                wifi.sta.config(_GET.ssid,_GET.password);
                node.restart()
                end)
            end
        end
        client:send(buf);
        client:close();
        collectgarbage();
    end)
    
end)

Credits

M8dhouse

M8dhouse

4 projects • 7 followers
Thanks to NoelPortugal.

Comments