Thursday, September 1, 2016

ESP Relayserver

So I was busy with a project and things would not work out as I wanted. The hardware was Ok but I had some serious problems concerning the software for the ESP8266 written in LUA. To take my mind of the problem I decided to start another project.




What I wanted was an easy way to switch a relay on or off over the internet. Now this is something that already has been done a load of times, however I wanted to incorporate something that is so obvious, but I never saw it done before.

I wanted the realy to have a manual override.

What´s the reason for that. Well imagine you have a relay that you can switch on and off over the internet and you switch a lamp with it. That is obviously nice but how about you switching it on remotely while the people at home do not want that. Well they can of course pull the mains plug out. But that´s not convenient and you who are at a remote place then will not now that the lamp is out. So I wanted not only a manual override but also a feedback to the internet about the state of the lamp. And that really is not something I have seen in someone elses project before.

It really turned out very simple.

The relay.




Modern relays can be bought for, at the time of this writing, way below 1 dollar or euro. Best part is that they have everything on board for working with a micro-controller. They have a power-led and a led that shows wether the relay is active or not. Next to that they incorporate a power transistor and all electronics further needed. So the only thing you need to supply is power and a digital on or off signal.

If you have some old relays in stock you can still read on. You just have to make your own relay controller and that's not so difficult either. Just follow the guide I wrote in this story, and attach the base of the transitor to the ESP8266 which we are going to use.

Power supply

As this is going to be a stand-alone project it needs a power supply. I used an USB mains adapter for this as, how convenient, it has an USB connection with which we can feed the NodeMCU board and relay we are going to use in this project.




BEWARE
WE ARE GOING TO WORK WITH MAINS CONNECTIONS HERE AND THEY ARE REALLY HAZARDOUS. PLEASE STAY AWAY FROM THE MAINS ADAPTER IF YOU DO NOT KNOW WHAT YOU ARE DOING AND ARE NOT AWARE OF THE DANGERS INVOLVED.
I ACCEPT NO LIABILITY OR RESPONSABILITY FOR YOU FOLLOWING THIS PROJECT AND GETTING INJURED/KILLED  OR HAVING YOUR HOUSE BURNED DOWN OR WHATEVER DAMAGE MAY RESULT FROM FOLLOWING THESE BUILD INSTRUCTIONS OR YOUR OWN VARIATIONS OF IT.

Before making any alterations to the adapter make shure it is not plugged in the mains !!!




First I started with taking the USB mains adapter apart. As you can see it is a perfect fit in the small housing.




If you remove the print out of the housing you can see two leads (red and black) going to the mains connection. Cut these loose. We now have the print seperated from the housing and that is what we need for our project.

Mains cable.

Before proceeding make sure the mains-cable is unplugged !!!



You will need a mains cable with a plug on one side and a contra plug on the other side. The plug will go into the mains outlet in the wall and your lamp (motor, pump or whatever) will be plugged into the contraplug.

Somewhere in the middle or whatever suit you best cut the wire and strip it. Put it in a screw terminal and on one side attach the black and red wire from the USB-Mains adapter so that will be powered. Now on the other side (this will be the side with the contra plug) a few inches away cut 1 wire of the mains cable and strip the ends. Feed the ends in the relay's terminal screws.

Wiring the ESP8266

I used a NodeMCU version of the ESP8266. This has the advantage that it is USB powered, can easily be programmed (directly over USB) and has many I/O pins.






I think the schematics and the breadboard layout tell it all.

I used two switches attached to D1 and D2. These are the MANUAL OVERRULE and MANUAL SELECT switch.
A led attached to a delimiting resistor is attached to D4 and that will give a visual feedback wether MANUAL OVERRIDE is switched on or off.
The Relay is attached to ground, 5 volts and to pin D3 of the NodeMCU which triggers it.
And that's all.

Casing



I wanted a nice casing for this so I started my (now favorite) design program 123D-Design. Lately I have been switching from Tinkercad to 123D-Design. 123D-Design has a few nice tricks up its sleeve and it works off-line which seems to be a bit faster as Tinkercad. I can save all my files locally and am not depended on the quirks of a slow, bad or busy internet connection. 123D-design is now part of the 123D family which is owned by Autocad. So switching did not make me feel a traitor.

I made a casing which has 3 distinct compartiments. One for the mains-part, one for the realy, and one for the electronics. On the side of the casing I made holes for switches and the led.

The Led is places next to the MANUAL-OVERRIDE switch. The On-Off switch is put a bit further away.



And At last a fitting lid was made.


Putting it all together.



As you can see I drilled two holes trough which the mains cable enters the housing.
On the left side of the casing is the power supply, attached with a normal USB-cable to the NodeMCU on the right side. In the middle is the relay.
I Put the NodeMCU on a stripboard which makes it easy to get it out of the casing if I want to alter the software in the future.


For safety I glued all the components to the casing using a hot-glue gun. I also taped down the contacts on the switches for preventing any short circuit.


The software

The software is written in LUA. The download link is at the bottom of this page, you can however also copy and paste it from the next listing.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
wifi.setmode(wifi.STATION)
wifi.sta.config("MYROUTERNAME","PASSWORD")
print(wifi.sta.getip())
relay = 3
relaystate = 0
switch1 = 2
manual =1
led = 4
gpio.mode(led, gpio.OUTPUT)
gpio.write(led,gpio.LOW);
gpio.mode(relay, gpio.OUTPUT)
gpio.write(relay, gpio.HIGH);
relaystate=0
gpio.mode(switch1, gpio.INPUT, gpio.PULLUP);
gpio.mode(manual, gpio.INPUT, gpio.PULLUP);
srv=net.createServer(net.TCP)

tmr.alarm(1, 1000, 1, function()
if (gpio.read(manual) == 0) then
    gpio.write(led,gpio.HIGH);
    print (gpio.read(switch1))
    if (gpio.read(switch1) == 0) then
    gpio.write(relay,gpio.LOW);
    relaystate=1
    elseif (gpio.read(switch1) == 1) then
    gpio.write(relay,gpio.HIGH);
    relaystate=0
    end
end
if (gpio.read(manual) == 1) then
gpio.write(led,gpio.LOW);
end
end)



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..'<head><meta http-equiv="refresh" content="20" /></head>'
        buf = buf.."<h1> ESP8266 Relay Switch</h1>";
        buf = buf.."<h1> Luc Volders 2016</h1>";
        if (gpio.read(manual) == 0) then
            buf = buf.."<br/>";
            buf = buf.."Manual override = ON"
            buf = buf.."<br/><br/>";
        elseif (gpio.read(manual) == 1) then
            buf = buf.."<br/>";
            buf = buf.."Manual override = OFF"
            buf = buf.."<br/><br/>";
        end
            if (gpio.read(switch1) == 0) then
                buf = buf.."Manual Switch = ON";
            elseif (gpio.read(switch1) == 1) then
                buf = buf.."Manual Switch = OFF";
            end
            buf = buf.."<br/>";
            if (relaystate == 1) then
                buf = buf.."Relay is ON";
            elseif (relaystate == 0) then   
                buf = buf.."Relay is OFF";
            end 
            buf = buf.."<br/><br/>";    
        --end
        buf = buf.."<p>GPIO0 <a href=\"?pin=ON1\"><button>ON</button></a>&nbsp;<a href=\"?pin=OFF1\"><button>OFF</button></a></p>";
        local _on,_off = "",""
        if (gpio.read(manual) == 1) then
            if(_GET.pin == "ON1")then
                gpio.write(relay, gpio.LOW);
                relaystate=1
            elseif(_GET.pin == "OFF1")then
                gpio.write(relay, gpio.HIGH); 
                relaystate=0    
            end
        end    
        client:send(buf);
        client:close();
        collectgarbage();
    end)
end)

Make sure you put the right information in line 2 substituing MYROUTERNAME and PASSWORD with your router info.
The next lines do the setup by defining the I/O ports as input or output and giving the variables the right initial values.

In line 18 the timer function constantly checks wether thw Manual-Override button has been pressed. If it is the led is put on otherwise the led is switched off. Next the routine tests the switch button which puts the relay on or off.

From line 37 onwards the web-page is defined and build.
In line 50 I use a trick I have used before. I put a refresh statement on the page wich makes sure the page is refreshed every 20 seconds. You may alter this to your liking by altering the figure 20 which sets the seconds before refreshing.

Lines 53 to 61 test wether the MANUAl-OVERRIDE is on or off and displays that information on the web-page.

Lines 62 to 73 test the state of the switch and tests the variable relaystate that holds info about the relaystate (duh) and display that info on the webpage.

The last lines detect what button you press on the webpage (on or off) and act accordingly by putting the relay on or off.

Wow !!! A complete relay commander on a webpage with actual feedback on the state of the buttons in just 90 lines of code !!!!!

As my web-page says GPIO0 you might alter the text in line 75 in "Put the Relay" or something to your liking.

Actually I urge you to alter the text in this program anyhow. That will give you more feeling in LUA programming.

You could also alter the entire program in switching more relays. As we have pins D5, D6, D7 and D8 unused you could add another 4 relays or 2 relays and 2 control leds. This would have you change the casing also which is also a good exercise in working with CAD/CAM programs.

Putting it to work.

First put the mains plug in a mains wall-socket and wait a few seconds. 

Then open the configuration screen of your network router in your browser. Now look at the screen that shows you all connected devices.



In the above screen you can see that there are several wired devices attached : my computer, my Buffalo NAS and my Raspberry Printerserver with an Epson printer connected. Above these you can see an unknow device. That'll be the ESP8266 relayserver.



If I click on - Unknown - the router reveals the IP number.

Now put this IP number in your browser and instantly the webpage will be presented.



First push the MANUAL-OVERRIDE on the casing and you will see the text on the screen alter after a while (max 20 seconds which is the refresh rate of the screen discussed in the software). If MANUAL-OVERRIDE is on you can put the relay on or off with the switch on the casing. If MANUAL-OVERRIDE is on you can push the on-and off buttons on the webpage but nothing will happen.

If MANUAL-OVERRIDE is off the switch on the casing will not work and you can put the relay on or off with the buttons on the web-page.


Please be aware that if you switch the relayserver totally off (by unplugging the mains) the next time you start it it may get another IP number unless you give it a fixed IP number (you can do that in your Router's menu).That is what happened in my case so the IP number in the router-screen above is different as the IP number I used to call the web-page as the pictures were taken on a later date.

In real-life.




It works like a charm and is easy to use. The manual-override is a logical, nice and handy touch. And to be frank I am pleased with the casing and the complete design. It is a fun project which is simple to build and does not take a lot of time except for the printing of the case which took a few hours.

I can access the webpage from my computer, my phone and my tablet and as I opened a port on my router I can switch the relay on or off from any place in the world.

Just one word: NEAT !!!

Source codes.

As you know I am a grat fan of open-source software. Therefore as always all software and schematics are free to use and modify. Even the STL files for the casing are open. You can find all the sources on my Github repositry.

https://github.com/Lucvolders/ESP-Relayserver

So till next time
Have fun

Luc Volders