papous
Posts: 38
Joined: Fri Jan 05, 2018 5:50 am

Tornado, websockets and coroutines. Unsolvable problem?

Wed May 23, 2018 9:23 am

Consider this:
I have created a robot car which is nicely controlled from a web page using Tornado, websockets and jquery .
The problem arises when you want sensors to provide inputs to the program that will alter its behaviour (stop, turn etc.)
How is this implemented? what if you have more than one sensor inputs? It is proposed that you should use coroutines as threading is not safe with Tornado. So here is some code:

Code: Select all

class MainHandler(tornado.web.RequestHandler):
  def get(self):
     print ("[HTTP](MainHandler) User Connected.")
     self.render("index.html")
	
class WSHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        print ('[WS] Connection was opened.')

    def on_message(self, message):
        print ('[WS] Incoming message:', message)

        if message == 'F':
            '''
            robot goes forward
            '''
            
@gen.coroutine
def distance2object():
    if distance_detected<30:
        '''
        STOP THE ROBOT
        '''
    else:
        pass
   yield gen.sleep(1)# Allow other processing while we wait 1 sec.


application = tornado.web.Application([
  (r'/', MainHandler),
  (r'/ws', WSHandler),
  ], **settings
    )

if __name__ == "__main__":
    try:
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(PORT)
        main_loop = tornado.ioloop.IOLoop.instance()
        print ("Tornado Server started"        )
        main_loop.start()
Where and how can I use the coroutine to achieve the desired effect (ie the robot stops when near an object)?
Thanks for your attention

Return to “Python”

Who is online

Users browsing this forum: No registered users and 19 guests