#!/usr/bin/env python # -*- coding: utf-8 -*- from tornado.ioloop import IOLoop, PeriodicCallback from tornado import gen from tornado.websocket import websocket_connect import edcoRobot03 from threading import Thread, Lock import multiprocessing mutex = Lock() class Client(object): def __init__(self, url, timeout): self.url = url self.timeout = timeout self.ioloop = IOLoop.instance() self.ws = None self.nCmpt = 0 self.robot = edcoRobot03.EdcoRobot() self.connect() PeriodicCallback(self.keep_alive, 200).start() self.ioloop.start() @gen.coroutine def connect(self): print ("trying to connect Client") try: self.ws = yield websocket_connect(self.url) except Exception as e: print ("connection error") else: print ("connected Client") self.run() @gen.coroutine def run(self): while True: msg = yield self.ws.read_message() # print ("%s"%msg) if msg is None: print ("connection Client closed") self.ws = None break def keep_alive(self): # self.nCmpt = self.nCmpt+1 if self.ws is None: self.connect() print("He arribat aquí") else: mutex.acquire() sensorsJS = self.robot.vSensors() self.ws.write_message(sensorsJS) mutex.release() class ClientMotion(object): def __init__(self, url, timeout): self.url = url self.timeout = timeout self.ioloop = IOLoop.instance() self.ws = None self.nCmpt = 0 self.robot = edcoRobot03.EdcoRobot() self.connect() # PeriodicCallback(self.keep_alive, 200).start() self.ioloop.start() @gen.coroutine def connect(self): print ("trying to connect ClientMotion") try: self.ws = yield websocket_connect(self.url) except Exception as e: print ("connection error") else: print ("connected ClientMotion") self.run() @gen.coroutine def run(self): while True: msg = yield self.ws.read_message() # print ("%s"%msg) # {"left":0,"right":0} self.szLeft,self.szRight = msg.split(',') self.nLeft = int(self.szLeft[8:]) self.nRight = int(self.szRight[8:-1]) print("left: %d" % self.nLeft) print("right: %d" % self.nRight) """ print("left: %s" % self.szLeft[8:]) print("right: %s" % self.szRight[8:-1]) """ mutex.acquire() self.robot.vMotion(self.nLeft,self.nRight) mutex.release() if msg is None: print ("connection ClientMotion closed") self.ws = None break def keep_alive(self): # self.nCmpt = self.nCmpt+1 if self.ws is None: self.connect() print("He arribat aquí") else: pass def startClient(): global client PORT = 8800 client = Client("ws://localhost:8800/robot01/", 5) print ("serving at port %d"% PORT) def startClientMotion(): global clientMotion PORT = 8800 clientMotion = ClientMotion("ws://localhost:8800/motion/", 5) print ("serving at port %d"% PORT) if __name__ == "__main__": try: p1 = multiprocessing.Process(name='p1', target=startClient) p = multiprocessing.Process(name='p', target=startClientMotion) p1.start() p.start() except KeyboardInterrupt: p1.join() p.join() print ("\nSortint ...") clientMotion.robot.pwmBR.stop() clientMotion.robot.pwmBL.stop() clientMotion.robot.pwmFR.stop() clientMotion.robot.pwmFL.stop()