Raspberry上的Python Tornado Websocket - 从服务器向客户端发送数据

时间:2017-09-20 19:28:55

标签: javascript python websocket raspberry-pi tornado

我正在研究项目,我想使用Raspberry Pi Zero W来控制电机并读取陀螺仪的读数。然后,通过Tornado websocket我想显示读数并向服务器发送消息。我可以实现负责读取陀螺仪或控制电机的功能,我可以通过发送来自客户端(网络浏览器)的请求来控制电机,但令我困惑的是从服务器到客户端的通信。我如何发送数据,在这种情况下,陀螺读数(假设每1秒钟)到.html对象?我怎么能循环一切?

提前致谢!

!/usr/bin/python2
 -*- coding: utf-8 -*-

import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import tornado.httpserver

import RPi.GPIO as GPIO

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)

ClientWebsocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print('Connection opened !!from: {}'.format(self.request.remote_ip))
        self.write_message('Connection opened!!')

    def on_close(self):
        print('Connection closed!!')

    def on_message(self, message):
        print(message)

        if message == '\"forward\"':
            GPIO.output(20,True)
            GPIO.output(21,False)
            self.write_message('Forward')
        elif message == '\"backward\"':
            GPIO.output(20,False)
            GPIO.output(21,True)
            self.write_message('Backward')
        elif message == '\"stop\"':
            GPIO.output(20,False)
            GPIO.output(21,False)
            self.write_message('Stop')

        else:        
            self.write_message('Unknown command!!')
            print('Unknown unknown')

class MainHandler(tornado.web.RequestHandler):

    def get(self):
        self.write( """
<html>
    <head>
        <title>Gyro & Accelerometer</title>
    </head>

    <body>
     Websocket Raspberry Readings

        <hr/>

        <div>

           <div  style="position:relative; width:400px; height:80px;" >
               <div id="addr" style="width:400px; height:20px;">    addr    </div>
               <div id="status" style="width:400px; height:20px;">  status  </div>
               <div id="msg" style="width:400px; height:20px;">     message </div>
           </div>

        </div>

        <hr/>

        Connection Status
        <div id="connection" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            connection
        </div>

        <div>Control</div>

        <button id="forward" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            FORWARD
        </button>

        <button id="backward" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            BACKWARD
        </button>

        <button id="stop" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            STOP
        </button>    

        <div>Gyro Readings</div>
        <div id="Gyro" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            Gyro
        </div>

        Accelerometer Readings
        <div id="Accelerometer" style="position:relative; width:200px; height:40px;background:lightgrey; font: 30px arial, sans-serif;" >
            Accelerometer
        </div>

         <script type="text/javascript">
    "use strict";

    console.log("starting...");
    var addr = "ws://" + window.location.hostname + ":" + window.location.port + "/ws";
    console.log(addr);
    document.getElementById("addr").innerHTML = addr;
    var websocket = new WebSocket( addr );

    websocket.onmessage = function(e)
    {
        var server_message = e.data;
        var obj = JSON.parse(server_message);

        console.log(server_message);
    }

    websocket.onopen = function(){
       console.log('Connection open!');
       document.getElementById("connection").style.background = 'lightgreen';
       document.getElementById("Gyro").style.background = 'green';
       document.getElementById("Accelerometer").style.background = 'green';
       document.getElementById("status").innerHTML = 'connected !';
    }

    websocket.onclose = function(){
       console.log('Connection closed');
       document.getElementById("connection").style.background = 'red';
       document.getElementById("status").innerHTML = 'disconnected';
       document.getElementById("Gyro").innerHTML = '-';
       document.getElementById("Accelerometer").innerHTML = '-';
    }

    function onClickForward() {
            try {
                websocket.send( JSON.stringify( 'forward' ) );
                document.getElementById("forward").style.background = 'black';
            }
            catch(err) {
                console.log( err.message );
            }
    }

    document.getElementById("forward").addEventListener("click", onClickForward);

    function onClickBackward() {
            try {
                websocket.send( JSON.stringify( "backward" ) );
                document.getElementById("backward").style.background = 'black';
            }
            catch(err) {
                console.log( err.message );
            }
    }

    document.getElementById("backward").addEventListener("click", onClickBackward);

    function onClickStop() {
                try {
                    websocket.send( JSON.stringify( "stop" ) );
                    document.getElementById("stop").style.background = 'black';
                }
                catch(err) {
                    console.log( err.message );
                }
        }

    document.getElementById("stop").addEventListener("click", onClickStop);

  </script>

    </body>
</html>
""")

    def check_origin(self,origin):
        return True


def make_app():
    return tornado.web.Application(
        [
            (r"/ws", ClientWebsocketHandler),
            (r"/", MainHandler)
        ]
        )

if __name__ == "__main__":
    tornado.options.parse_command_line()
    server = make_app()
    server = tornado.httpserver.HTTPServer(server)
    server.listen(8001)
    tornado.ioloop.IOLoop.instance().start()

0 个答案:

没有答案