ESP8266 Web Server python Home Automation - Black keyhole

welcome to our keyhole, we provide you various knowledge from various sources such as Electric&Electronic, Health, Arduino, IOT, Diy projects, A/l past paper and model paper, Even though you can keep in touch with current technology

ESP8266 Web Server python Home Automation

Share This





In this tutorial I will show you how to make ESP8266 webserver that controls relay using MicroPython firmware. If you didn't see my previous post about how to coonect MicroPython firmware with ESP8266 click here to continue.

Components that I have used

     1. 5v Relay module

     2. A/C bulb

     3. Bulb holder

     4. NodeMCU

     5.Jumper wires



  Circuit


             
     

Creating the main.py file on your board


           1. Press the new file button to create a new file

           2. Press the Save file button to save the file in your computer

           3. Then a new window will open and save that file with a name as per your wish. and don't forget to add ".py" extension with that file.

          4. After that, you should see that file with boot.py file. if you did't see that file with boot.py file press the Reset button of your NodeMCU board and click the link button to un link and again click it for make link. then you should see that file with boot.py file. You can check the tutorial  video from You Tube.


  Click here to Download the  Code

 Code Explanation

      boot.py

We need to create our webserver using sockets and the Python socket API. So we need to import the library as follows.

try:
  import usocket as socket
except:
  import socket
                  
we need to import pin class from machine module to able to interact with GPIO pins

from machine import Pin

next we need to import networ library to connect ESP8266 with WIFI-network

import network


 The following lines turn off vendor OS debugging messages:

import esp
esp.osdebug(None)


Then, we run a garbage collector. A garbage collector is a form of automatic memory management. This is a way to reclaim memory occupied by objects that are no longer in used by the program. This is useful to save space in the flash memory.


import gc
gc.collect()
    

next we need to put the network credentials

ssid = 'your network name'
password = 'your network password'


set ESP8266 as a WIFI-station

station = network.WLAN(network.STA_IF)


 After that, activate the station:

station.active(True)

ESP8266 connects to your router using the SSID and password defined earlier:

station.connect(ssid, password)

The following statement ensures that the code doesn’t proceed while the ESP is not connected to your network.

while station.isconnected() == False:
  pass

After successful, print network parameters
 
print('Connection successful')
print(station.ifconfig())

here we have created GPIO output:

relay = Pin(5, Pin.OUT)


Main.py
   
  This function returns a variable called html that contains the HTML text to build the web page

 def web_page():

The web page displays the current GPIO state.

if relay.value() == 1:
    relay_state = ''
  else:
    relay_state = 'checked'

html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
<style> 
  body{font-family:Arial; text-align: center; margin: 0px auto; padding-top:30px;}
  .switch{position:relative;display:inline-block;width:120px;height:68px}.switch
 input{display:none}
  .slider{position:absolute;top:0;left:0;right:0;bottom:0;background-color:
#ccc;border-radius:34px}
  .slider:before{position:absolute;content:"";height:52px;width:52px;left:8px;bottom:
8px;background-color:#fff;-webkit-transition:.4s;transition:.4s;border-radius:68px}
  input:checked+.slider{background-color:#2196F3}
  input:checked+.slider:before{-webkit-transform:translateX(52px);
-ms-transform:translateX(52px);transform:translateX(52px)}
  </style><script>function toggleCheckbox(element) { var xhr = new XMLHttpRequest(); 
if(element.checked){ xhr.open("GET", "/?relay=on", true); }
  else { xhr.open("GET", "/?relay=off", true); } xhr.send(); }</script></head><body>
  <h1>ESP Relay Web Server</h1>
  <h2>
  <a href="https://www.youtube.com/channel/UCEIUbi1n2LqyNOl97c-InAQ?view_as=subscriber">
Subcribe Black keyhole</a></h2>
  <h3>
  <a href="https://www.blackkeyhole.com/">Visit my web page for more project</a></h3>
  <label class="switch"><input type="checkbox" onchange="toggleCheckbox(this)" %s><span
 class="slider">
  </span></label></body></html>""" % (relay_state)
  return html


After creating the HTML to build the web page, we need to create a listening socket to listen for incoming requests and send the HTML text in response.

To create a socket:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Next, bind the socket to an address

s.bind((''80))


The next line enables the server to accept connections; it makes a “listening” socket. The argument specifies the maximum number of queued connections. The maximum is 5.

s.listen(5)


In the while loop is where we listen for requests and send responses. When a client connects, the server calls the accept() method to accept the connection. When a client connects, it saves a new socket object to accept and send data on the conn variable, and saves the client address to connect to the server on the addr variable.


while True:
  try:
    if gc.mem_free() < 102000:
      gc.collect()
    conn, addr = s.accept()
    conn.settimeout(3.0)
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    conn.settimeout(None)
    request = str(request)
    print('Content = %s' % request)
    relay_on = request.find('/?relay=on')
    relay_off = request.find('/?relay=off')
    if relay_on == 6:
      print('RELAY ON')
      relay.value(0)
    if relay_off == 6:
      print('RELAY OFF')
      relay.value(1)
    response = web_page()
    conn.send('HTTP/1.1 200 OK\n')
    conn.send('Content-Type: text/html\n')
    conn.send('Connection: close\n\n')
    conn.sendall(response)
    conn.close()
  except OSError as e:
    conn.close()
    print('Connection closed')



Final
  
    Finaly everything is done, Upload the main.py and boot.py file to ESP8266. You should see that your wifi is established and it has been printing your IP address. copy that IP address and past it in your browser. then should see the effect on your web page and Play with that button😉. Hope You have like this post also keep share this post between your friends or family members who aspiring to make these kind of stuffs. and don't forget to press the subscribe button for my You Tube channel that I had provided above in this article.😊








8 comments:

  1. Bro ur awesome ... Expecting more contents from u ... Keep rocking🙌

    ReplyDelete
    Replies
    1. Thank you , keep in touch with my YouTube channel also

      https://www.youtube.com/channel/UCEIUbi1n2LqyNOl97c-InAQ

      Delete
  2. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Take me to another useless website

    ReplyDelete
  3. I don t have the time at the moment to fully read your site but I have bookmarked it and also add your RSS feeds. I will be back in a day or two. thanks for a great site. SEO Guadalajara

    ReplyDelete
  4. You can consider automation achieving repeatable errands without human intercession, and arrangement as the way toward hanging together a progression of these assignments to achieve a cycle or work process. AGV solution

    ReplyDelete
  5. Micropython
    Is that can support for Arduino Uno

    ReplyDelete

business queries

Pages