20-2 Raspberry Pi build server Tornado Web Server

Drive.google.com/drive/folders/1ahbeoEHkjxoo4NV1wReOmpoRWbl448z-

 

1.Tornado Profile

Tornado written in Python using a relatively simple non-blocking Web server, which is non-blocking server, but also very fast. Enrichment of its non-blocking mode and the use of epoll, Tornado can handle thousands of connections per second, so the Tornado is an ideal framework for real-time Web services.

Official Website: http: //www.tornadoweb.cn

Official documents: http: //www.tornadoweb.cn/documentation

The entire document on a Web page, the http server commonly used features are about it again, if programmed basis, you should soon be able to get started.

2.Tornado installation

Mode 1: pip install:
sudo install PIP Tornado


Embodiment 2: a source installation:
wget https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz
the tar-4.3.tar.gz xvzf Tornado
CD-Tornado 4.3
Python setup.py Build
sudo Python setup.py install

 

Second, the basic principle

 

Tornado official borrow Hello World example:

import tornado.ioloop
import tornado.web
 
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
 
application = tornado.web.Application([
    (r"/", MainHandler),
])
 
if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

  

General idea is: http port open listening by Tornado, are preset routing rules, when a request meets the routing rules, call the corresponding Handler for processing, which is the approach most Web servers. Support get and post requests.

 

Extend it, use Tornado set up a http server, put on top of a web page, web client incoming GPIO pin number and status need to be controlled, the server receives the incoming parameters, make the appropriate treatment, can achieve the level of control GPIO pins the output.



Third, the implementation steps

1. The front end html page

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>树莓派Web控制中心</title>
    <script src="static/js/jquery-3.2.1.min.js" type="text/javascript"></script>
    <script src="static/js/bootstrap.min.js" type="text/javascript"></script>
    <link href="static/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="static/css/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet"
        type="text/css" />
    <style type="text/css">
        .page-header { margin: 20px 0; border-bottom: 1px solid #eee; padding-bottom: 0; text-align: center; }
        .btn-item { text-align: center; }
        i { margin-right: 3px; display: inline-block; }
        h1 { text-align: center; }
        .tip { font-weight: bold; color: black; }
        .lead { font-size: small; }
        .gpio-item { text-align: center; }
        .btn-gnd, .btn-gpio { padding: 10px 5px; margin-bottom: 5px; width: 100%; font-size: small; }
        .gpio .row { margin-top: 5px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="page-header">
            <h3>
                Raspberry Pi Web Control Center </ H3> 
            <P class = "Lead"> 
                various sensors for controlling the connection to the Raspberry Pi 
            </ P> 
        </ div> 
        <div class = "Panel Panel-default"> 
            < div class = "panel-heading" > 
                equipment </ div> 
            <div class = "Panel-body"> 
                <div class = "Row"> 
                    <div class = "COL-XS-. 3 BTN-Item"> 
                    </ div > 
                    <div class = "COL. 3-XS-BTN-Item"> 
                        <a class="btn btn-danger btn-trigger"> <I class = "FA-FA Power-OFF"> </i>关机</a>
                    </div>
                    <div class="col-xs-3 btn-item">
                        <a class="btn btn-primary btn-trigger"><i class="fa fa-refresh"></i>重启</a>
                    </div>
                    <div class="col-xs-3 btn-item">
                    </div>
                    <script type="text/javascript">
                        var url = "/";
                        $(function () { 
                            $(".btn-trigger").click(function () {
                                var text = $(this).text().replace(/ /g, "").replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "");
                                var cmd = "";
                                switch (text) {
                                    case "关机":
                                        cmd = "sudo shutdown -h now";
                                        BREAK; 
                                    Case "reboot": 
                                            // $ (."tip").html(result);
                                        cmd = "sudo reboot";
                                        break;
                                } 
                                IF (Confirm The ( "? You sure you want to execute the command")) { 
                                    $ .ajax ({ 
                                        of the type: "POST", 
                                        url: url, 
                                        the Data: { 
                                            Action: "RUN-shell-cmd", 
                                            cmd: cmd 
                                        }, 
                                        Success: function (Result) { 
                                } 
                            });
                                        }
                                    });
                        });
                    </script>
                </div>
            </div>
        </div>
        <div class="panel panel-default">
            <div class="panel-heading">
                GPIO (蓝色->低电平,红色->高电平)</div>
            <div class="panel-body gpio">
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        左侧
                    </div>
                    <div class="col-xs-6 gpio-item "> 
                    </ div>
                        right
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (9) 左05</button>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (6) 右03</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="17">17 (11) 左06</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="18">18 (12) 右06</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="27">27 (13) 左07</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (14) 右07</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="22">22 (15) 左08</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="23">23 (16) 右08</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (25) 左13</button>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="24">24 (18) 右09</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="5">05 (29) 左15</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (20) 右10</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="6">06 (31) 左16</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="25">25 (22) 右11</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="13">13 (33) 左17</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (30) 右15</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="19">19 (35) 左18</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="12">12 (32) 右16</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="26">26 (37) 左19</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (34) 右17</button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="20">20 (37) 右19</a>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="16">16 (36) 右18</a>
                    </div>
                </div>
                <div class="row">
                    <div class="col-xs-6 gpio-item">
                        <button disabled="disabled" class="btn btn-info btn-gnd">
                            GND (39) 右20</button>
                    </div>
                    <div class="col-xs-6 gpio-item">
                        <a class="btn btn-primary btn-gpio" pin="21">21 (40) 右20</a>
                    </div>
                </div>
                <script type="text/javascript">
                    $(function () {
                        $(".btn-gpio").click(function () {
                            var gpio = $(this).attr("pin");
                            if ($(this).hasClass("btn-danger")) {
                                $(this).removeClass("btn-danger").addClass("btn-primary");
                            } else {
                                $(this).removeClass("btn-primary").addClass("btn-danger");
                            }
                            var status = $(this).hasClass("btn-danger") ? 1 : 0;
                            $ .ajax ({
                                type: "POST",
                                url: url,
                                data: {
                                    action: "set-gpio-pin",
                                    pin: gpio,
                                    status: status
                                },
                                success: function (result) {
                                    //$(".tip").html(result);
                                }
                            });
 
                        });
                    })
                </script>
            </div>
        </div>
    </div>
</body>
</html>


  

2.Python script

#coding: utf8
import sys
import RPi.GPIO as GPIO
import time
import os
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import define,options
 
#初始化
def init():
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
 
#设置GPIO针脚电平输出
def SetPinStatus(pin,status):
    GPIO.cleanup(int(pin))
    GPIO.setup(int(pin),GPIO.OUT)
    if(int(status)==0):
        GPIO.output(int(pin),GPIO.LOW)
    else:
        GPIO.output(int(pin),GPIO.HIGH)
    
#路由处理	
class IndexHandler(tornado.web.RequestHandler):
        GET DEF (Self): 
                self.render ( "index.html") 
        DEF POST (Self): 
                the init () 
		Action = self.get_argument ( 'Action') 
		# Set GPIO pin level output 
		if (action == "set- PIN-GPIO "): 
		    PIN = self.get_argument ( 'PIN') 
                    Status = self.get_argument ( 'Status') 
		    SetPinStatus (PIN, Status) 
		    self.write (" to true ") 
		# shell script, such as: shutdown, restart 
		elif (== Action "RUN-the shell-cmd"): 
		    cmd = self.get_argument ( 'cmd') 
                    the os.system (cmd)					 
                
IF the __name__ == '__main__': 
    # console output response result, a formal environment may not open 
    # tornado.options.parse_command_line()
    settings={ 
        "static_path": os.path.join (os.path.dirname(__file__),"static")
        }
    app = tornado.web.Application(
        handlers=[
            (r"/",IndexHandler),
            (r"(apple-touch-icon\.png)",tornado.web.StaticFileHandler,dict(path=settings['static_path']))
        ],**settings)
    
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8020)
    tornado.ioloop.IOLoop.instance().start()
    GPIO.cleanup()

  

3. Directory Structure

 

4. Deploy debugging

Enter in a terminal: python /var/www/html/pi/gpio/gpio.py (raspberry pie for my path in the file path, the actual path to your own environment prevail.)

If the terminal is not an error, then open the browser, enter the address: http: // localhost: 8020 to access to the page, is a python script in 8020 listening port, you can set your own.

5. Run results

 

6. Download the source code

http://download.csdn.net/download/a497785609/9990088

Guess you like

Origin www.cnblogs.com/kekeoutlook/p/11267389.html