简体   繁体   中英

Running Background task with Python and Tornado

I have been a web application developer for several years and now playing with Python and Robotics.

I have set up Python Tornado to run based on javascript websocket commands. This is great, moves motors, turns on LEDs. not a problem.

2 things I want to do.

1) Flash the LEDs

2) using Ultrasonic Range sensors, stop the FORWARD action IF range < X

I know how to do both within itself.

BUT, the way I have my python is as follows

WS.py

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import time
# My Over python module
import tank

class WSHandler(tornado.websocket.WebSocketHandler):

    def open(self):

        print 'New connection was opened'
        self.write_message("Welcome to my websocket!")
        tank.init()

    def on_message(self, message):
        print 'Incoming message:', message
        tank.run(message)
        self.write_message("You said: " + message)

   def on_close(self):
       tank.end()
       print 'Connection was closed...'
   def check_origin(self, origin):
       return True
application = tornado.web.Application([
  (r'/ws', WSHandler),
])

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

TANK.py import RPi.GPIO as gpio import time

def init():
    #Setting up all my pins, Not going to add all

def moveForward():
    #open GPIO pins to move motors forward
def stop():
    # close all GPIO pins to stop motors

def run(action):
    # the method called by the IOLoop
    if action == 'go':
        moveForward()
    elif action == 'stop':
        stop()
    else:
        print "Oops, i cocked up"

NOTE: tank.py is a summary and not actual code.

My JS works on Mouse Down, call my python WS with go, mouse up, call stop

As i said, WORKS FINE

but if I add a while loop on the moveForward() method to work out the range and stop if close, then my WS will be tied and not listen for STOP

likewise, if I run a method which turns LED on, sleeps, turn off, sleeps, My WS will not be able to listen to any commands.

Sounds like you need to yield to the IOLoop so it can process more inputs, while at the same time continuing execution in "moveForward".

If you need to pause between loops in moveForward, do something like:

@gen.coroutine
def moveForward():
    while True:
        do_something()
        # Allow other processing while we wait 1 sec.
        yield gen.sleep(1)

Never use "time.sleep" in a Tornado callback or coroutine, it blocks all event processing for your entire process. Use IOLoop.add_timeout, or "yield gen.sleep(n)", instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM