A customary web server example

Any home automation project using Raspberry Pi yields a lot of examples that involves building a web server that controls appliances within a local network that takes care of securing the place using electromechanical locks. We will build a simple web server that can be used to turn off an LED from a web page. This concept can be expanded to control multiple appliances and read sensor data from the GPIO interface of Raspberry Pi.

Note

This task is meant for absolute beginners who are not familiar with Python web framework tools. We are discussing this example considering some readers might jump right to Project 11, Home Automation Using Raspberry Pi.

Prepare for lift off

We will be building a web server using a Flask framework (http://flask.pocoo.org/). The Flask framework can be installed as follows:

sudo apt-get install python-pip
sudo pip install Flask

Engage thrusters

  1. The first part is setting up the landing page. When a user enters the address of the web server, the web page would be something like what is shown in the following screenshot. The HTML page consists of a single button called Sample Button.
    Engage thrusters

    A flask framework-based web server

  2. When a button is clicked, the incoming POST request is used to switch the states of the LED from ON to OFF and vice versa:
    @app.route('/', methods=['POST'])
    def record():
      #record all the data from the form
      global state
      if state == False:
        state = True
      else:
        state = False
      GPIO.output(25,state)
      return render_template('form_submit.html')
  3. The web server can be launched from the IP address of Raspberry Pi. The web page should be accessible from http://192.168.1.76:75:
    # Run the app :)
    if __name__ == '__main__':
      app.run( 
        host="0.0.0.0",
        port=int("75")
      )

The web server example is available along with this project. Check this book's website for more examples.

Objective complete – mini debriefing

Using the simple concept explained earlier, it is possible to control any appliance (by interfacing some control device such as the power switch tail to Raspberry Pi's GPIO pins). It is also possible to read sensor states as well as track any special information. For example, it is possible to track the status of a package that is expected to be delivered. USPS provides status of shipments that can be displayed on the web page (for more information on APIs, check out https://www.usps.com/business/web-tools-apis/welcome.htm).

In all these examples, we reviewed control appliances using Raspberry Pi within a local network. In the later task of this project, we will review controlling the device from anywhere over the Internet.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.150.183