Python threading.currentThread() Examples

The following are code examples for showing how to use threading.currentThread(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 7 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        for i in xrange(5) :
            c = d.cursor()
            count = 0
            rec = c.first()
            while rec:
                count += 1
                key, data = rec
                self.assertEqual(self.makeData(key), data)
                rec = c.next()
            if verbose:
                print "%s: found %d records" % (name, count)
            c.close()

        if verbose:
            print "%s: thread finished" % name 
Example 2
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name
        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        count=len(keys)//len(readers)
        count2=count
        for x in keys :
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)

            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            count2-=1
            if not count2 :
                readers.pop().start()
                count2=count

        if verbose:
            print "%s: thread finished" % name 
Example 3
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def handle_error(self, request, client_address):
        """Override TCPServer method

        Error message goes to __stderr__.  No error message if exiting
        normally or socket raised EOF.  Other exceptions not handled in
        server code will cause os._exit.

        """
        try:
            raise
        except SystemExit:
            raise
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            os._exit(0)

#----------------- end class RPCServer -------------------- 
Example 4
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _getresponse(self, myseq, wait):
        self.debug("_getresponse:myseq:", myseq)
        if threading.currentThread() is self.sockthread:
            # this thread does all reading of requests or responses
            while 1:
                response = self.pollresponse(myseq, wait)
                if response is not None:
                    return response
        else:
            # wait for notification from socket handling thread
            cvar = self.cvars[myseq]
            cvar.acquire()
            while myseq not in self.responses:
                cvar.wait()
            response = self.responses[myseq]
            self.debug("_getresponse:%s: thread woke up: response: %s" %
                       (myseq, response))
            del self.responses[myseq]
            del self.cvars[myseq]
            cvar.release()
            return response 
Example 5
Project: robust-atd   Author: shadowbq   File: __init__.py    MIT License 6 votes vote down vote up
def worker(sema, pool, unsafe_options, src_path):

    '''Worker for Thread Pool'''
    # logging.debug('Waiting to join the pool')
    with sema:
        options = copy.copy(unsafe_options)
        name = threading.currentThread().getName()
        pool.make_active(name)

        if options.verbosity:
            print ("TPW{0} file => {1} opening".format(name, src_path))
        file_created = Handler(options, src_path)
        file_created.sort_file()

        pool.make_inactive(name)
        if options.verbosity:
            print ("TPW{0} file => {1} completed.".format(name, src_path)) 
Example 6
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: diningPhilosophers.py    MIT License 6 votes vote down vote up
def run(self):
    print("{} has started thinking".format(threading.currentThread().getName()))
    while True:
      time.sleep(random.randint(1,5))
      print("{} has finished thinking".format(threading.currentThread().getName()))
      self.leftFork.acquire()
      time.sleep(random.randint(1,5))
      try:
        print("{} has acquired the left fork".format(threading.currentThread().getName()))

        self.rightFork.acquire()
        try:
          print("{} has attained both forks, currently eating".format(threading.currentThread().getName()))
        finally:
          self.rightFork.release()   
          print("{} has released the right fork".format(threading.currentThread().getName()))
      finally:
        self.leftFork.release()
        print("{} has released the left fork".format(threading.currentThread().getName())) 
Example 7
Project: spqrel_tools   Author: LCAS   File: commandunderstood.py    MIT License 6 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        try:
            value =  memory_service.getData("command_understood")
        except RuntimeError:
            # the variable is not declared yet, so it is false
            value = 0

        if (value):
            v = 'true'
        else:
            v = 'false'
        set_condition(memory_service,'commandunderstood',v)

    print "commandunderstood thread quit" 
Example 8
Project: spqrel_tools   Author: LCAS   File: recdata.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    print "Action "+actionName+" "+params+" started"
    # action init
    if (params=='off'):
        memory_service.raiseEvent(logkey,0)
        print "  -- Recording data disabled --"
    else:
        memory_service.raiseEvent(logkey,1)
        print "  -- Recording data enabled --"
    
    # action exec
    time.sleep(1.0)

    # action end
    action_success(actionName,params) 
Example 9
Project: spqrel_tools   Author: LCAS   File: obstaclehere.py    MIT License 6 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        sonarValues =  memory_service.getListData(sonarValueList)
#       print "Sonar: [Front, Back]", sonarValues
        laserValues =  memory_service.getListData(laserValueList)
#       print "Laser center: ", laserValues[42],laserValues[44],laserValues[46] # X values of central beams
        # TODO
        #if (laserValues[42]>2 and laserValues[44]>2 and laserValues[46]>2):
        if (sonarValues[0] > 0.7):
            v = 'false'
        else:
            v = 'true'
        set_condition(memory_service,'obstaclehere',v)
        time.sleep(1)
    print "obstaclehere thread quit" 
Example 10
Project: spqrel_tools   Author: LCAS   File: wave.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    session = getattr(t, "session", None)
    memory_service = getattr(t, "mem_serv", None)
    rp_service = session.service("ALRobotPosture")
    animation_service = session.service("ALAnimationPlayer") ###### MODIFY THISS!!!
    print "Action "+actionName+" started with params "+params

    position = params
    if (position == 'up'):
        future = animation_service.run("animations/Stand/Gestures/You_1", _async=True)
    if (position == 'down'):
        future.cancel()
            
    # action end
    action_success(actionName,params) 
Example 11
Project: spqrel_tools   Author: LCAS   File: assign.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params
    # action init
    try:
        vp = params.split('_')
        print "  -- Assign: ",vp[0]," = ",vp[1]
        memory_service.insertData(vp[0],vp[1])
    except:
        print "ERROR in Assign parameters"
    # action init

    time.sleep(1.0)
		
    # action end
    action_success(actionName,params) 
Example 12
Project: spqrel_tools   Author: LCAS   File: alltasksconfirmed.py    MIT License 6 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        try:
            value =  memory_service.getData("tasks_to_confirm")
        except RuntimeError:
            # the variable is not declared yet, so it is false
            #print "ERROR retrieving value"
            value = 1

        if (value):
            v = 'false'
        else:
            v = 'true'
        set_condition(memory_service,'alltasksconfirmed',v)

    print "alltasksconfirmed thread quit" 
Example 13
Project: spqrel_tools   Author: LCAS   File: wait.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params
    # action init
    dt = 0.25
    count = int(float(params) / dt)
    # action init
    while (getattr(t, "do_run", True) and count>0): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count-1
        # action exec
        time.sleep(dt)

    # action end
    count = 0
    action_success(actionName,params) 
Example 14
Project: spqrel_tools   Author: LCAS   File: asrenable.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    print "Action "+actionName+" "+params+" started"
    # action init
    if (params=='off'):
        memory_service.raiseEvent(asrkey,'0')
    else:
        memory_service.raiseEvent(asrkey,'1')
    # action init
    
    time.sleep(1.0)

    # action end
    action_success(actionName,params) 
Example 15
Project: spqrel_tools   Author: LCAS   File: describetask.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    global response, lu4r_command
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    description = memory_service.getData("task_description")

    # pronuonce the description
    memory_service.raiseEvent("Veply", description)

    val = 0
    # wait for tts done
    print "wait"
    while (getattr(t, "do_run", True) and val == 0):
        print "Wait text pronounced"
        val = memory_service.getData("ALTextToSpeech/TextDone")
        time.sleep(0.5)

    # action end
    action_success(actionName,params) 
Example 16
Project: spqrel_tools   Author: LCAS   File: say.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params

    memory_service.raiseEvent("ASR_enable", "0")

    # action init
    val = 0
    tosay = phraseToSay(memory_service,params)
    tts_service.say(tosay)
    print "  -- Say: "+tosay
    #action init
    while (getattr(t, "do_run", True) and val == 0):
        print "Wait text pronounced"
        # action exec
        val = memory_service.getData("ALTextToSpeech/TextDone")
        # action exec
        time.sleep(0.1)

    # action end
    action_success(actionName,params) 
Example 17
Project: spqrel_tools   Author: LCAS   File: vsay.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params

    # action init
    memory_service.raiseEvent('DialogueVequest',"say_"+params)
    print "  -- VSay: "+params
    val = 0
    time.sleep(1)
    # action init
    
    while (getattr(t, "do_run", True) and val==0): 
        # print "Action "+actionName+" "+params+" exec..."
        # action exec 
        val = memory_service.getData("ALTextToSpeech/TextDone")
        # action exec
        time.sleep(0.5)

    # action end
    action_success(actionName,params) 
Example 18
Project: spqrel_tools   Author: LCAS   File: reccam.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    print "Action "+actionName+" "+params+" started"
    # action init
    if (params=='off'):
        memory_service.raiseEvent(logkey,0.0)
        print "  -- Recording data disabled --"
    else:
        memory_service.raiseEvent(logkey,0.5)
        print "  -- Recording data enabled --"

    # action exec
    time.sleep(1.0)

    # action end
    action_success(actionName,params) 
Example 19
Project: spqrel_tools   Author: LCAS   File: navigateto_naoqi.py    MIT License 6 votes vote down vote up
def actionThread_exec(params):
    global memory_service

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action " + actionName + " started with params " + str(params)

    # action init
    p = params.split('_')
    
    navigation_service = getattr(t, "session", None).service("ALNavigation")
    navigation_service.navigateTo(float(p[0]),float(p[1]))

    # action end
    action_success(actionName,params) 
Example 20
Project: spqrel_tools   Author: LCAS   File: arm.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    session = getattr(t, "session", None)
    memory_service = getattr(t, "mem_serv", None)
    rp_service = session.service("ALRobotPosture")
    animation_service = session.service("ALAnimationPlayer") ###### MODIFY THISS!!!
    print "Action "+actionName+" started with params "+params

    position = params
    if (position == 'up'):
        future = animation_service.run("animations/Stand/Gestures/You_1", _async=True)
    if (position == 'down'):
        future.cancel()
            
    # action end
    action_success(actionName,params) 
Example 21
Project: spqrel_tools   Author: LCAS   File: setpose.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    global goal_reached
    global memory_service

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action "+actionName+" started with params "+params

    # action init
    print "  -- SetPose: "+ params
    mem_key_setpose   = "NAOqiLocalizer/SetPose"
    pose = params.split("_")
    if (len(pose) == 3):
        posef = [float(pose[0]), float(pose[1]), float(pose[2])]
        memory_service.raiseEvent(mem_key_setpose, posef);

    action_success(actionName,params) 
Example 22
Project: spqrel_tools   Author: LCAS   File: dooropen.py    MIT License 6 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    while getattr(t, "do_run", True):
        sonarValues =  memory_service.getListData(sonarValueList)
	#print "Sonar: [Front, Back]", sonarValues
        laserValues =  memory_service.getListData(laserValueList)
        #print "Laser center: ", laserValues[42],laserValues[44],laserValues[46] # X values of central beams
        # TODO
	if (laserValues[42]>2 and laserValues[44]>2 and laserValues[46]>2 and sonarValues[0]>1):
            v = 'true'
        else:
            v = 'false'
        set_condition(memory_service,'dooropen',v)
#        print 'dooropen = ',v
        time.sleep(1)
    print "dooropen thread quit" 
Example 23
Project: spqrel_tools   Author: LCAS   File: trackface.py    MIT License 6 votes vote down vote up
def actionThread_exec(params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    session = getattr(t, "session", None)

    print "Action "+actionName+" started with params "+params

    # action init
    tracker_service = session.service("ALTracker")

    p = params.split('_')

    if p[0] == 'start':
        tracker_service.setMode("Head")

        tracker_service.registerTarget("Face", 0.15)
        tracker_service.track("Face")
    elif p[0] == 'stop':
        tracker_service.stopTracker()
        tracker_service.unregisterAllTargets()
    # action end
    action_success(actionName,params) 
Example 24
Project: spqrel_tools   Author: LCAS   File: interact.py    MIT License 6 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params

    modim_client = ModimWSClient()
    modim_client.setCmdServerAddr(pepper_ip, pepper_port)
    # action init
    count = 1
    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        #csend
        data_str = "im.execute('"+params+"')"

        rdata = modim_client.csend(data_str)
        
        count = count - 1
        # action exec
        time.sleep(0.1)

    # action end
    action_success(actionName,params)
    modim_client.cclose() 
Example 25
Project: spqrel_tools   Author: LCAS   File: storecentralperson.py    MIT License 6 votes vote down vote up
def actionThread_exec(params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action " + actionName + " started with params " + params

    while getattr(t, "do_run", True):
        print "Action " + actionName + " running params " + params
        plist = memory_service.getData("PeoplePerception/VisiblePeopleList")
        try:
            if (len(plist) > 0):
                p_id, p_x, p_y = find_center_person(plist, memory_service)
                if p_id > 0:
                    memory_service.insertData("center_person/id", str(p_id))
                    memory_service.insertData("center_person/pose", [p_x, p_y])
            break
        except Exception as e:
            print 'EXCEPTION: %s' % str(e)
            break
    # action exec
    time.sleep(0.1)

    # action end
    action_success(actionName,params) 
Example 26
Project: spqrel_tools   Author: LCAS   File: personbehind.py    MIT License 6 votes vote down vote up
def rhMonitorThread (memory_service):
    global last_personid
    t = threading.currentThread()
    print "personbehind thread started"
    personid = 0
    while getattr(t, "do_run", True):
        v = 'false'
        try:
            pdist = memory_service.getData("Device/SubDeviceList/Platform/Back/Sonar/Sensor/Value")
            #distance to consider that the person following
            
            if (pdist < 1.5):
                print "\n"
                print "[  PERSON BEHIND  ]"
                v = 'true'
        except:
            v = 'false'

        set_condition(memory_service,'personbehind',v)

        time.sleep(0.5)
    print "personbehind thread quit" 
Example 27
Project: spqrel_tools   Author: LCAS   File: tabletmanager.py    MIT License 6 votes vote down vote up
def touchMonitorThread (tablet_service, touch_service):
    tabletshow(tablet_service)
    t = threading.currentThread()
    cnt = 0
    while getattr(t, "do_run", True):
        b = check_event(touch_service)
        if (b):
            cnt += 1
        else:
            cnt = 0
        if (cnt>3):
            print "Two hands touched for more than 3 seconds!!!"
            tabletshow(tablet_service)   
            cnt = 0
        time.sleep(1)
    print "Exiting Thread" 
Example 28
Project: pyblish-win   Author: pyblish   File: decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setcontext(context):
        """Set this thread's context to context."""
        if context in (DefaultContext, BasicContext, ExtendedContext):
            context = context.copy()
            context.clear_flags()
        threading.currentThread().__decimal_context__ = context 
Example 29
Project: pyblish-win   Author: pyblish   File: decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getcontext():
        """Returns this thread's context.

        If this thread does not yet have a context, returns
        a new context and sets this thread's context.
        New contexts are copies of DefaultContext.
        """
        try:
            return threading.currentThread().__decimal_context__
        except AttributeError:
            context = Context()
            threading.currentThread().__decimal_context__ = context
            return context 
Example 30
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        if verbose:
            print "%s: creating records %d - %d" % (name, start, stop)

        count=len(keys)//len(readers)
        count2=count
        for x in keys :
            key = '%04d' % x
            dbutils.DeadlockWrap(d.put, key, self.makeData(key),
                                 max_retries=12)
            if verbose and x % 100 == 0:
                print "%s: records %d - %d finished" % (name, start, x)

            count2-=1
            if not count2 :
                readers.pop().start()
                count2=count

        if verbose:
            print "%s: finished creating records" % name

        if verbose:
            print "%s: thread finished" % name 
Example 31
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def writerThread(self, d, keys, readers):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        count=len(keys)//len(readers)
        while len(keys):
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                keys2=keys[:count]
                for x in keys2 :
                    key = '%04d' % x
                    d.put(key, self.makeData(key), txn)
                    if verbose and x % 100 == 0:
                        print "%s: records %d - %d finished" % (name, start, x)
                txn.commit()
                keys=keys[count:]
                readers.pop().start()
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                txn.abort() 
Example 32
Project: pyblish-win   Author: pyblish   File: test_thread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readerThread(self, d, readerNum):
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        finished = False
        while not finished:
            try:
                txn = self.env.txn_begin(None, self.txnFlag)
                c = d.cursor(txn)
                count = 0
                rec = c.first()
                while rec:
                    count += 1
                    key, data = rec
                    self.assertEqual(self.makeData(key), data)
                    rec = c.next()
                if verbose: print "%s: found %d records" % (name, count)
                c.close()
                txn.commit()
                finished = True
            except (db.DBLockDeadlockError, db.DBLockNotGrantedError), val:
                if verbose:
                    if sys.version_info < (2, 6) :
                        print "%s: Aborting transaction (%s)" % (name, val[1])
                    else :
                        print "%s: Aborting transaction (%s)" % (name,
                                val.args[1])
                c.close()
                txn.abort() 
Example 33
Project: pyblish-win   Author: pyblish   File: test_lock.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def theThread(self, lockType):
        import sys
        if sys.version_info[0] < 3 :
            name = currentThread().getName()
        else :
            name = currentThread().name

        if lockType ==  db.DB_LOCK_WRITE:
            lt = "write"
        else:
            lt = "read"

        anID = self.env.lock_id()
        if verbose:
            print "%s: locker ID: %s" % (name, anID)

        for i in xrange(1000) :
            lock = self.env.lock_get(anID, "some locked thing", lockType)
            if verbose:
                print "%s: Aquired %s lock: %s" % (name, lt, lock)

            self.env.lock_put(lock)
            if verbose:
                print "%s: Released %s lock: %s" % (name, lt, lock)

        self.env.lock_id_free(anID)


#---------------------------------------------------------------------- 
Example 34
Project: pyblish-win   Author: pyblish   File: test_threading.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ident_of_no_threading_threads(self):
        # The ident still must work for the main thread and dummy threads.
        self.assertFalse(threading.currentThread().ident is None)
        def f():
            ident.append(threading.currentThread().ident)
            done.set()
        done = threading.Event()
        ident = []
        thread.start_new_thread(f, ())
        done.wait()
        self.assertFalse(ident[0] is None)
        # Kill the "immortal" _DummyThread
        del threading._active[ident[0]]

    # run with a small(ish) thread stack size (256kB) 
Example 35
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def debug(self, *args):
        if not self.debugging:
            return
        s = self.location + " " + str(threading.currentThread().getName())
        for a in args:
            s = s + " " + str(a)
        print>>sys.__stderr__, s 
Example 36
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def asynccall(self, oid, methodname, args, kwargs):
        request = ("CALL", (oid, methodname, args, kwargs))
        seq = self.newseq()
        if threading.currentThread() != self.sockthread:
            cvar = threading.Condition()
            self.cvars[seq] = cvar
        self.debug(("asynccall:%d:" % seq), oid, methodname, args, kwargs)
        self.putmessage((seq, request))
        return seq 
Example 37
Project: pyblish-win   Author: pyblish   File: rpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def asyncqueue(self, oid, methodname, args, kwargs):
        request = ("QUEUE", (oid, methodname, args, kwargs))
        seq = self.newseq()
        if threading.currentThread() != self.sockthread:
            cvar = threading.Condition()
            self.cvars[seq] = cvar
        self.debug(("asyncqueue:%d:" % seq), oid, methodname, args, kwargs)
        self.putmessage((seq, request))
        return seq 
Example 38
Project: pyblish-win   Author: pyblish   File: run.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def handle_error(self, request, client_address):
        """Override RPCServer method for IDLE

        Interrupt the MainThread and exit server if link is dropped.

        """
        global quitting
        try:
            raise
        except SystemExit:
            raise
        except EOFError:
            global exit_now
            exit_now = True
            thread.interrupt_main()
        except:
            erf = sys.__stderr__
            print>>erf, '\n' + '-'*40
            print>>erf, 'Unhandled server exception!'
            print>>erf, 'Thread: %s' % threading.currentThread().getName()
            print>>erf, 'Client Address: ', client_address
            print>>erf, 'Request: ', repr(request)
            traceback.print_exc(file=erf)
            print>>erf, '\n*** Unrecoverable, server exiting!'
            print>>erf, '-'*40
            quitting = True
            thread.interrupt_main() 
Example 39
Project: pypette   Author: csurfer   File: basic.py    MIT License 5 votes vote down vote up
def print_job(message):
    """Sample method which takes a message to print."""
    print(threading.currentThread().getName(), "Starting")
    sleep(1)
    print("From within print_job : " + str(message))
    print(threading.currentThread().getName(), "Ending") 
Example 40
Project: pypette   Author: csurfer   File: basic.py    MIT License 5 votes vote down vote up
def print_corrupt(message):
    print(threading.currentThread().getName(), "Starting")
    sleep(1)
    print("From within print_corrupt : " + str(message))
    print(threading.currentThread().getName(), "Ending")
    raise Exception("lal")


# Create pipeline p2 
Example 41
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: orphanThreads.py    MIT License 5 votes vote down vote up
def child(self):
    print("{} starting".format(threading.currentThread().getName()))
    time.sleep(10)
    print("{} ending".format(threading.currentThread().getName())) 
Example 42
Project: Learning-Concurrency-in-Python   Author: PacktPublishing   File: identifyingThreads.py    MIT License 5 votes vote down vote up
def myThread():
  print("Thread {} starting".format(threading.currentThread().getName()))
  time.sleep(10)
  print("Thread {} ending".format(threading.currentThread().getName())) 
Example 43
Project: deep-learning-note   Author: wdxtub   File: 6_thread_wayC.py    MIT License 5 votes vote down vote up
def loop(nsec):
    myname = currentThread().name
    with lock:
        remaining.add(myname)
        print("[{}] Started {}".format(ctime(), myname))
    sleep(nsec)
    with lock:
        remaining.remove(myname)
        print("[{}] Completed {} ({} secs)".format(ctime(), myname, nsec))
        print("    (remaining: {})".format(remaining or "None")) 
Example 44
Project: spqrel_tools   Author: LCAS   File: naoqibag.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service, rate, output_file):
    print '%s Recording data at @%.2f Hz ...' %(time.strftime("%Y%m%d_%H%M%S", time.localtime()),rate)
    ts0 = time.time()
    tsl = []
    t = threading.currentThread()
    logheader(output_file,keys_list)
    while getattr(t, "do_run", True):
        try:
            values = memory_service.getListData(keys_list)
            if logdata(output_file,values):
                sys.stdout.write('.') # full log ok
            else:
                sys.stdout.write('-') # missing values
        except Exception as e:
            sys.stdout.write('X') # error
            print e
        dt = (int)(time.time() - ts0) / 60
        if (dt not in tsl):
            sys.stdout.write(str(dt))
            tsl.append(dt)
        sys.stdout.flush()
        time.sleep(1.0/rate)
    print "Exiting Thread Log"


# TTS callback
#Event: "ALTextToSpeech/CurrentSentence"
#callback(std::string eventName, std::string value, std::string subscriberIdentifier) 
Example 45
Project: spqrel_tools   Author: LCAS   File: movearm.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global memory_service

    t = threading.currentThread()
    motion_service = getattr(t, "session", None).service("ALMotion")

    print "Action "+actionName+" started with params "+params

    jointPosesStr = params.split("_")

    if len(jointPosesStr)!=6:
        print "Action "+actionName+" failed. Not enough joint args "
        action_fail(actionName,params)
   
    jointPoses = []
    for joint in jointPosesStr:
        jointPoses.append(float(joint))

    count = 1
        
    # action init
    while (getattr(t, "do_run", True) and count > 0): 

        # action exec
        #read current values to later restore position
        
        currentSensorAngles = motion_service.getAngles(jointsNames, True)
        #get the current joints stiffnesses
        currentStiffnesses = motion_service.getStiffnesses(jointsNames)
    
        motion_service.stiffnessInterpolation('RArm', 1, 0.2)
        motion_service.angleInterpolation(jointsNames, jointPoses,1.5,True)
 
        count -= 1
        # action exec

    # action end
    action_success(actionName,params) 
Example 46
Project: spqrel_tools   Author: LCAS   File: understandcommand.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global interpretations
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    sub2 = memory_service.subscriber(intkey)
    idsub2 = sub2.signal.connect(interpretations_callback)


    #tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params

   # memory_service.insertData("GoogleTranscription", "What's the longest street in the world?")

    memory_service.raiseEvent("UnderstandCommand", (str(params)))

    memory_service.insertData("CommandInterpretation", [])

    interpretations = None

    while (getattr(t, "do_run", True) and interpretations is None):
        print "Waiting for interpretation..."
        time.sleep(0.5)

    if interpretations is not None and len(interpretations) > 0:
        memory_service.insertData("command_understood", 1)
        memory_service.insertData("CommandInterpretation", interpretations)


    # action end
    action_success(actionName,params)

    sub2.signal.disconnect(idsub2) 
Example 47
Project: spqrel_tools   Author: LCAS   File: modiminit.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params

    v = params.split('_')
    dpath = v[0]
    pepper_ip = ''
    if len(v) > 1:
        pepper_ip = v[1]
    else:
        pepper_ip = os.getenv('PEPPER_IP')   
        
    # action init
    count = 1
    pepper_port = 9101
    setServerAddr(pepper_ip, pepper_port)
    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        data_str = "im.setProfile(['*', '*', 'en', '*'])"+"\n"
        data_str += "im.setPath('"+ demopath(dpath) +"')"+"\n###ooo###\n\n"
        csend(data_str)
        
        count = count - 1
        # action exec
        time.sleep(0.1)

    # action end
    action_success(actionName,params) 
Example 48
Project: spqrel_tools   Author: LCAS   File: dialoguestart.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    print "Action "+actionName+" "+params+" started"
    # action init
    memory_service.raiseEvent('DialogueVequest',params+'_start')
    # action init
    
    time.sleep(1.0)

    # action end
    action_success(actionName,params) 
Example 49
Project: spqrel_tools   Author: LCAS   File: bow.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    session = getattr(t, "session", None)
    memory_service = getattr(t, "mem_serv", None)
    rp_service = session.service("ALRobotPosture")
    animation_service = session.service("ALAnimationPlayer") ###### MODIFY THISS!!!
    print "Action "+actionName+" started with params "+params

    position = params
    future = animation_service.run("animations/Stand/Gestures/BowShort_1")
            
    # action end
    action_success(actionName,params) 
Example 50
Project: spqrel_tools   Author: LCAS   File: greet.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global memory_service
    global tts_service 

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    tts_service = getattr(t, "session", None).service("ALTextToSpeech")

    print "Action "+actionName+" started with params "+params

    if len(params) > 0:
        try:
            lang = params
            print " Setting LANG: ", lang
            tts_service.setLanguage(lang)
        except:
            print "ERROR in setting language"
    else:
        lang = "English"

    # action init
    count = 1

    # action exec
    while (getattr(t, "do_run", True) and count > 0): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        what_to_say = greet(lang)
        print what_to_say
        tts_service.say(what_to_say)
        count -= 1

    

    if len(params) > 0:
        tts_service.setLanguage("English")

    # action end
    action_success(actionName,params) 
Example 51
Project: spqrel_tools   Author: LCAS   File: moveto.py    MIT License 5 votes vote down vote up
def actionThread_exec(params):
    global memory_service

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action " + actionName + " started with params " + str(params)

    # action init
    p = params.split('_')
    target = [float(p[0]), float(p[1]), float(p[2])/180.0*math.pi]
    print "  -- MoveTo: " + str(target)
    
    motion_service = getattr(t, "session", None).service("ALMotion")

    # action init
    # action init

    #print "Action "+actionName+" "+params+" exec..."
    # action exec
    #motion_service.setExternalCollisionProtectionEnabled('Move', False)
    #time.sleep(1)
    motion_service.moveTo(target[0], target[1], target[2])
    motion_service.waitUntilMoveIsFinished()
    #motion_service.setExternalCollisionProtectionEnabled('Move', True)
    # action exec
        
    # action end
    motion_service.stopMove()
    action_success(actionName,params) 
Example 52
Project: spqrel_tools   Author: LCAS   File: wavingdetected.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service):
    global wavingdetected
    global wavingpersonid
    global wavingpersonx
    global wavingpersony

    wavingdetected = 0

    t = threading.currentThread()
    print "personhere thread started"

    while getattr(t, "do_run", True):
        plist = memory_service.getData("PeoplePerception/VisiblePeopleList")
        v = 'false'

        wavingDetection = memory_service.subscriber("Actions/PeopleWaving/NewDetection")
        idAnyDetection = wavingDetection.signal.connect(waving_callback)   

        if wavingdetected == 1:
            memory_service.insertData('Actions/wavingdetected/wavingpersonid',str(wavingpersonid))
            memory_service.insertData('Actions/wavingdetected/wavingpersonx',str(wavingpersonx))
            memory_service.insertData('Actions/wavingdetected/wavingpersony',str(wavingpersony))
            v = 'true'

        set_condition(memory_service,'wavingdetected',v)
        
        time.sleep(1)

    print "personhere thread quit" 
Example 53
Project: spqrel_tools   Author: LCAS   File: headpose.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")
    print "Action "+actionName+" started with params "+params
    # action init

    stiff_head = 0.6
    print "   Stiffness -  Head ",stiff_head
        
    names = "Head"
    stiffnessLists = stiff_head
    timeLists = 1.0
    motion_service.stiffnessInterpolation(names, stiffnessLists, timeLists)

    v = params.split('_')
    yaw = 0
    pitch = 0
    try:
        if (len(v)==2):
            yaw = float(v[0])/180.0*math.pi
            pitch = float(v[1])/180.0*math.pi
    except:
        print "headpose: ERROR in values ",v[0]," ",v[1]," - (using 0,0)"
    headtime = 1.0

    moveHead(motion_service, yaw, pitch, headtime)

    count=1

    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count - 1		
        # action exec
        time.sleep(0.5)
        
    # action end
    action_success(actionName,params) 
Example 54
Project: spqrel_tools   Author: LCAS   File: aimlsay.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global response
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    #tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params


    memory_service.raiseEvent("ASR_enable", "0")

    acb = memory_service.subscriber("DialogueVesponse")
    acb.signal.connect(response_cb)
    print "Subscriber connected!"

    # action init
    response = None
    memory_service.raiseEvent('ParseAIMLRequest', params)
    print "  -- aimlsay: "+params

    # wait for the response to arrive
    while (getattr(t, "do_run", True) and response is None):
        print "Wait, AIML is parsing sentence "
        # action exec
        time.sleep(0.5)

    # pronuonce the response
    memory_service.raiseEvent("Veply", response)

    val = 0
    # wait for tts done
    print "wait"
    while (getattr(t, "do_run", True) and val == 0):
        print "Wait text pronounced"
        val = memory_service.getData("ALTextToSpeech/TextDone")
        time.sleep(0.5)

    response = None
    # action end
    action_success(actionName,params) 
Example 55
Project: spqrel_tools   Author: LCAS   File: approach.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    session = getattr(t, "session", None)

    print "Action "+actionName+" started with params "+params

    # action init
    tracker_service = session.service("ALTracker")

    #We need to obtain the id of the person to approach

    val = params
    if (params[0]=='^'):
        print params[1:]
        personid = memory_service.getData(params[1:])

    print "Person ID = ",personid

    tracker_service.setMode("Navigate")
    
    # The robot stays a 50 centimeters of target with 10 cm precision
    tracker_service.setRelativePosition([-0.5, 0.0, 0.0, 0.1, 0.1, 0.3])

    tracker_service.registerTarget("People",personid)
    tracker_service.track("People")
    val = False
    # action init

    while (getattr(t, "do_run", True) and (not val)): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        val = get_condition(memory_service, params)
        # action exec
        time.sleep(0.25)

    # action end
    tracker_service.stopTracker()
    tracker_service.unregisterAllTargets()
    action_success(actionName,params) 
Example 56
Project: spqrel_tools   Author: LCAS   File: fullpeopleperception.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    print "fullpeopleperception thread started"

    while getattr(t, "do_run", True):
        
        plist = memory_service.getData("PeoplePerception/PeopleList")

        for personid in plist:
            pmemkey_dist   = "PeoplePerception/Person/"+str(personid)+"/Distance"
            pmemkey_angles = "PeoplePerception/Person/"+str(personid)+"/AnglesYawPitch"
            pmemkey_pos    = "PeoplePerception/Person/"+str(personid)+"/PositionInRobotFrame"
            pmemkey_sit    = "PeoplePerception/Person/"+str(personid)+"/IsSitting"
            pmemkey_wave   = "PeoplePerception/Person/"+str(personid)+"/IsWaving"
            pmemkey_height = "PeoplePerception/Person/"+str(personid)+"/RealHeight"
            pmemkey_shirt  = "PeoplePerception/Person/"+str(personid)+"/ShirtColor"
            pmemkey_face   = "PeoplePerception/Person/"+str(personid)+"/FacialPartsProperties"

            key_list = [pmemkey_dist, pmemkey_angles, pmemkey_pos, pmemkey_sit,
                        pmemkey_wave, pmemkey_height, pmemkey_shirt, pmemkey_face]
            
            data_list = memory_service.getListData(key_list)

            print "\n"
            print "[Person: ", personid, "]"
            #print "[Distance: ", data_list[0], "]"
            #print "[AnglesYawPitch: ", data_list[1], "]"
            #print "[PositionInRobotFrame: ", data_list[2], "]"
            #print "[IsSitting: ", data_list[3], "]"
            #print "[IsWaving: ", data_list[4], "]"
            #print "[RealHeight: ", data_list[5], "]"
            #print "[ShirtColor: ", data_list[6], "]"
            print  "[Mouth Coord (x,y): ", data_list[7][11][0][0], data_list[7][11][0][1] ,"]"
            #print "\n"


                    
        time.sleep(0.5)
        
    print "fullpeopleperception thread quit" 
Example 57
Project: spqrel_tools   Author: LCAS   File: headpitch.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")
    print "Action "+actionName+" started with params "+params
    # action init

    stiff_head = 0.6
    print "   Stiffness -  Head ",stiff_head
        
    names = "Head"
    stiffnessLists = stiff_head
    timeLists = 1.0
    motion_service.stiffnessInterpolation(names, stiffnessLists, timeLists)

    v = params.split('_')
    pitch = 0
    try:
        if (len(v)==1):
            pitch = float(v[0])/180.0*math.pi
    except:
        print "headpose: ERROR in values ",v[0],"  - (using 0)"
    headtime = 1.0

    moveHead(motion_service, pitch, headtime)

    count=1

    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count - 1		
        # action exec
        time.sleep(0.5)
        
    # action end
    action_success(actionName,params) 
Example 58
Project: spqrel_tools   Author: LCAS   File: dialogue.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global dialogue_response, orderID
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    acb = memory_service.subscriber("DialogueVesponse")
    acb.signal.connect(response_cb)


    print "Action "+actionName+" "+params+" started"
    # action init	
    print "  -- Dialogue: "+params
    memory_service.raiseEvent('DialogueVequest',params+'_start')
    
    dialogue_response = False
    # action init
    while (getattr(t, "do_run", True) and not dialogue_response): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec	
        # action exec
        time.sleep(0.5)

    print "Action "+actionName+" "+params+" terminated"
    # action end
    memory_service.raiseEvent('DialogueVequest',params+'_stop')
    
    if (params=='takeorder' and dialogue_response):
        pinfo = memory_service.getData('DialogueVesponse')
        try:
            json.loads(pinfo)
            orderID = orderID+1
            memkey = "Humans/Profile"+str(orderID)
            memory_service.insertData(memkey, pinfo)
        except:
            print "Not a valid JSON file"

    # action end
    # TODO acb. disconnect...
    action_success(actionName,params) 
Example 59
Project: spqrel_tools   Author: LCAS   File: dialoguestop.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    
    print "Action "+actionName+" "+params+" started"
    # action init
    memory_service.raiseEvent('DialogueVequest',params+'_stop')
    # action init
    
    time.sleep(1.0)

    # action end
    action_success(actionName,params) 
Example 60
Project: spqrel_tools   Author: LCAS   File: extracttasks.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global response, lu4r_command
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action "+actionName+" started with params "+params

    interpretation = ""

    # get the lu4r command
    interpretations = memory_service.getData("command_annotations")
    command_sentence = memory_service.getData("command_sentence")

    commands = {}
    to_say = ''
    #interpretation = interpretation.lower()
    #interpretation = interpretation.replace(")", "")
    #splitted = interpretation.split('(')
    #print splitted
    lu4r_interpretation = interpretations[0].lower()
    ws_interpretation = interpretations[1]

    int_dict = generateDict(lu4r_interpretation)
    print "LU4r DICTIONARY:", int_dict
    if "and" in int_dict.keys():
        int_dict = int_dict["and"]
    else:
        int_dict = [int_dict]

    memory_service.insertData("interpreted_tasks", str(int_dict))

    num_tasks = len(int_dict)
    memory_service.insertData("tasks_to_confirm", num_tasks)


    print int_dict
    print "Num tasks:", str(num_tasks)

    time.sleep(2)

    action_success(actionName,params) 
Example 61
Project: spqrel_tools   Author: LCAS   File: speechbtn.py    MIT License 5 votes vote down vote up
def actionThread_exec(params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    # tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action speechbtn started with params " + params
    # action init
    # action init
    if len(params) > 0:
        memory_service.raiseEvent('AnswerOptions', 'speechbtn_' + params)
    else:
        memory_service.raiseEvent('AnswerOptions', 'speechbtn')

    # action end
    sleep(.5)
    action_base.action_success(actionName,params) 
Example 62
Project: spqrel_tools   Author: LCAS   File: enter.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")


    print "Action "+actionName+" started with params "+params
    
    # action init
    print "  -- Enter: "+params
    values = params.split('_')
    x = values[0]
    y = values[1]
    t = values[2]
    time_ = values[3]
    without_collision_avoidance = values[4].lower() == 'true'

    #print "x: ",x
    #print "y: ",y
    #print "t: ",t
    # action init
    count = 1
    
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" cm/s exec..."
        # action exec
        if without_collision_avoidance:
            motion_service.setExternalCollisionProtectionEnabled('Move', False)
	    time.sleep(1)
        motion_service.move(float(x)/100.0,float(y)/100.0,float(t) / 180 * math.pi)
        # action exec
        time.sleep(float(time_))
	print 'done'
        motion_service.setExternalCollisionProtectionEnabled('Move', True)
        count = 0		
        
    # action end
    motion_service.stopMove()
    action_success(actionName,params) 
Example 63
Project: spqrel_tools   Author: LCAS   File: personsitting.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    print "personsitting thread started"
    
    while getattr(t, "do_run", True):

        plist = memory_service.getData("PeoplePerception/VisiblePeopleList")
        
        personid = 0
        IsSitting = 0
        v = 'false'

        #print "[ Person sitting = 0 ]"
        #try:
        if (plist!=None and len(plist)>0):
            for i in range (0,len(plist)):
                personid = plist[i]
                try:
                    IsSitting = memory_service.getData("PeoplePerception/Person/"+str(personid)+"/IsSitting")
                    # Save person position
                    memory_service.insertData("personsitting/test",personid)
                    if (IsSitting == 1):
                        px,py,pz = memory_service.getData("PeoplePerception/Person/"+str(personid)+"/PositionInRobotFrame")
                        print "[ Person sitting ]"
                        print "   X: " + str(px) + "  Y: " + str(py)
                        w_px, w_py = point2world(memory_service,[px,py])
                        memory_service.insertData("Condition/personsitting/world_coordinates",[w_px,w_py])
                        memory_service.insertData("Condition/personsitting/robot_coordinates_x",px)
                        memory_service.insertData("Condition/personsitting/robot_coordinates_y",py)
                        memory_service.insertData("Condition/personsitting/id",personid)
                        v = 'true'
                except:
                    pass
        #except:
        #    v = 'false'
        set_condition(memory_service,'personsitting',v)
        #print 'personhere:: value ',v

        time.sleep(1)
    print "personsitting thread quit" 
Example 64
Project: spqrel_tools   Author: LCAS   File: tvsay.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    #tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params
    #params_list = params.split("_")
    tobi_tts = ALProxy("ALTextToSpeech", os.environ['TOBI_IP'], 9559)
    tobi_tts.setParameter("speed", 90)
    tobi_tts.setParameter("pitchShift", 0.9)
    tobi_memory = ALProxy("ALMemory", os.environ['TOBI_IP'], 9559)
    # action init
    #memory_service.raiseEvent('DialogueVequest', "tvsay_"+params)
    to_say = ''
    if "hello" in params:
        to_say = "Hello! I'm Tobi! Can I help you?"
    elif "andreahere" in params:
        to_say = "Andrea is here!"
    elif "andreanothere" in params:
        to_say = "Andrea is not here!"
    tobi_tts.say(to_say)
    print "  -- VSay: "+params
    val = 0
    time.sleep(1)
    # action init

    while (getattr(t, "do_run", True) and val==0):
        # print "Action "+actionName+" "+params+" exec..."
        # action exec
        val = tobi_memory.getData("ALTextToSpeech/TextDone")
        # action exec
        time.sleep(0.5)

    # action end
    action_success(actionName,params) 
Example 65
Project: spqrel_tools   Author: LCAS   File: animation.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    session = getattr(t, "session", None)
    
    # init services
    memory_service = getattr(t, "mem_serv", None)
    rp_service = session.service("ALRobotPosture")
    motion_service = session.service("ALMotion")
    animation_service = session.service("ALAnimationPlayer")

    #get original stiffness

    # parse the paramaters
    print "Action "+actionName+" started with params "+params

    values = params.split('_')
    animation_name = parser(values[0])
    if values[1] == '1':
        async = False
    else:
        async = True

    # execute the animation
    animation = animation_service.run(animation_name, _async=async)
  
    # action end
    action_success(actionName,params) 
Example 66
Project: spqrel_tools   Author: LCAS   File: asr.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global response
    t = threading.currentThread()

    memory_service  = getattr(t, "mem_serv", None)

    #reset memory value
    memory_service.insertData("asrresponse", "")


    #establishing test vocabulary
    vocabulary = []
    if params == "drink":
        vocabulary = ["grape juice", "orange juice", "chocolate drink", "sprite", "coke"]
    elif params == "name":
        vocabulary = ["Alex", "Charlie", "Elizabeth", "Francis", "Jennifer", "Linda", "Mary", "Patricia", "Robin", "Skyler", "James", "John", "Michael", "Robert", "William"]
    elif params == "confirm":
        vocabulary = ["yes", "no"]

    asr_service.pause(True)
    asr_service.removeAllContext()
    try:
        asr_service.setVocabulary(vocabulary, True)
    except:
        print "error setting vocabulary"
    asr_service.pause(False)


    response = None
    #let it run
    while response is None:
        print "Waiting for an answer..."
        time.sleep(0.5)

    #save into memory
    memory_service.insertData("asrresponse", response)

    asr_service.pause(True)

    # action end
    action_success(actionName,params) 
Example 67
Project: spqrel_tools   Author: LCAS   File: interactq.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params

    modim_client = ModimWSClient()
    modim_client.setCmdServerAddr(pepper_ip, pepper_port)
    # action init
    count = 1
    # action init
    while (getattr(t, "do_run", True) and count>0):
        print "Action "+actionName+" "+params+" exec..."
        # action exec
	try:
            # set to false all the conditions in the action
            data_str = "im.listConditions('"+params+"')"
            rdata = modim_client.csend(data_str)

            ldata = eval(rdata) # rdata is the string representation of a list of strings
            # ldata is a list of conditions to set to false
            for cc in ldata:
                set_condition(memory_service, cc, 'false')
        #        print "Condition: ",cc,get_condition(memory_service, cc)
        except:
            print "listConditions failed"

        # now wait for the actual answer
        data_str = "im.ask('"+params+"')"
        #TODO make it interruptible !!!
        rdata = modim_client.csend(data_str)
        rdata = rdata.strip() # rdata is the answer of the ask action
            
        count = count - 1
        # action exec
        time.sleep(0.1)

    print "setting condition: %s true"%rdata
    set_condition(memory_service, rdata, 'true')
    # action end
    action_success(actionName,params)
    modim_client.cclose() 
Example 68
Project: spqrel_tools   Author: LCAS   File: generatetaskdescription.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    global response, lu4r_command
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action "+actionName+" started with params "+params

    task = eval(memory_service.getData("CurrentTaskInterpretation"))

    # current_task_i = len(tasks) - ttc
    # current_task = tasks[current_task_i]
    print "Confirming:",
    pp.pprint(task)

    print "command:", str(params)

    to_say = getToSay(task)

    print "Asking:", to_say

    #memory_service.insertData("tasks_to_confirm", ttc-1)

    memory_service.insertData("task_description", to_say)

    # time.sleep(2)

    action_success(actionName,params) 
Example 69
Project: spqrel_tools   Author: LCAS   File: saveposition.py    MIT License 5 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    print "Action "+actionName+" started with params "+params
    # action init
    count = 1
    try:
        car_x, car_y , car_t = memory_service.getData('NAOqiLocalizer/RobotPose')
        last_node = memory_service.getData('TopologicalNav/LastNode')
    except Exception:
        car_x = 0
        car_y = 0
        last_node = 'start'

    position_name = params
    # action init
    print "Action "+actionName+" "+params+" exec..."
    # action exec
    print "saved" + position_name
    
    memory_service.insertData(position_name+"/coordinates",str(car_x)+"_"+str(car_y))
    memory_service.insertData(position_name+"/waypoint", last_node)

    # action exec
    time.sleep(0.1)

    # action end
    action_success(actionName,params) 
Example 70
Project: spqrel_tools   Author: LCAS   File: turntosoundsource.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service):
    t = threading.currentThread()
    print "Monitoring Sound Detection"
    while getattr(t, "do_run", True):
        sound_value =  memory_service.getData("ALSoundLocalization/SoundLocated")
        if sound_value:
            print "Sound:", sound_value
        time.sleep(.2)

    print "Monitoring Sound Detection Finished"
    print "Exiting Thread" 
Example 71
Project: spqrel_tools   Author: LCAS   File: navigateto.py    MIT License 4 votes vote down vote up
def actionThread_exec(params):
    global goal_reached
    global memory_service
    # global tts_service
    global goal_failed

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")
    # tts_service = getattr(t, "session", None).service("ALTextToSpeech")

    print "Action " + actionName + " started with params " + params
    # tts_service.say("Going to location "+params)

    # action init
    target = params
    if target[0] == '^':
        target = memory_service.getData(target[1:])
    print "  -- Goto: " + str(target)
    mem_key_goal = "TopologicalNav/Goal"
    mem_key_status = "TopologicalNav/Status"
    mem_key_headcontrol = "PepperHeadControl/Enabled"

    memory_service.raiseEvent(mem_key_headcontrol, True)

    acb = memory_service.subscriber(mem_key_status)
    acb.signal.connect(navstatus_cb)

    goal_reached = False
    goal_failed = False
    memory_service.raiseEvent(mem_key_goal, target)

    # action init
    while getattr(t, "do_run", True) and not goal_reached and not goal_failed:
        time.sleep(0.5)
    if not getattr(t, "do_run", True):
        # cancelled send empty goal to stop
        memory_service.raiseEvent(mem_key_goal, "")

    #headpose.moveHead(motion_service, headYaw, headPitch, headtime)
    print "Action " + actionName + " " + params + " terminated"
    # action end
    memory_service.raiseEvent(mem_key_headcontrol, False)

    if goal_reached:
        action_base.action_success(actionName, params)
    else:
        action_base.action_failed(actionName, params) 
Example 72
Project: spqrel_tools   Author: LCAS   File: sounddetected.py    MIT License 4 votes vote down vote up
def rhMonitorThread (memory_service,motion_service):

    t = threading.currentThread()
    print "sound detected thread started"

    prev_time = 0
    while getattr(t, "do_run", True):
        v = 'false'
        #print "testing sound"
        
        sound_value = memory_service.getData("ALSoundLocalization/SoundLocated")
        #print sound_value
        #print "\n"
        #print "[ SOUND ]"
        #print "    time(s):", sound_value[0][0]
        #print "    confidence: ", sound_value[1][2]
        #print "    energy: ", sound_value[1][3]

        #print "[Head Position[6D]] in FRAME_TORSO", sound_value[2]
        #print "[Head Position[6D]] in FRAME_ROBOT", sound_value[3]
        #head_pose6d = almath.Position6D(sound_value[3][0],sound_value[3][1],sound_value[3][2],
        #                                sound_value[3][3],sound_value[3][4],sound_value[3][5])
        #print head_pose6d
        #head_transform = almath.transformFromPosition6D(head_pose6d)
        #print "[Head Transform] in FRAME_ROBOT"
        #print head_transform
        #print "\n"

        if sound_value != None and len(sound_value)>1 and prev_time != sound_value[0][0]:
            prev_time = sound_value[0][0]
            #print "confidence: ", sound_value[1][2]
            confidence = sound_value[1][2]
            if (confidence > 0.35):
                v = 'true'
                sound_azimuth = sound_value[1][0]
                head_yaw = sound_value[3][5]
                turn_angle = sound_azimuth + head_yaw
                turn_angle = int(turn_angle / math.pi * 180)
                memory_service.insertData('AngleSound', str(turn_angle) + "_REL")
               # print "\n"
                print "[SoundDetected] time: ", sound_value[0][0], "azimuth(rad): ", sound_azimuth
               # print "\n"

        set_condition(memory_service,'sounddetected',v)
        if v:
            time.sleep(2) #if true we give time to process the condition

        time.sleep(0.25)

    print "sounddetected thread quit" 
Example 73
Project: spqrel_tools   Author: LCAS   File: gotopos.py    MIT License 4 votes vote down vote up
def actionThread_exec(params):
    global goal_reached
    global memory_service

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)

    print "Action " + actionName + " started with params " + str(params)

    # action init
    p = params.split('_')
    target = [float(p[0]), float(p[1])]
    print "  -- Goto: " + str(target)
    mem_key_goal = "NAOqiPlanner/Goal"
    mem_key_status = "NAOqiPlanner/Status"
    mem_key_reset = "NAOqiPlanner/Reset"

    acb = memory_service.subscriber(mem_key_status)
    acb.signal.connect(plannerstatus_cb)

    motion_service = getattr(t, "session", None).service("ALMotion")

    goal_reached = False
    memory_service.raiseEvent(mem_key_goal, target)

    head_count = 0
    head_count_max = 6 
    # action init
    while (getattr(t, "do_run", True) and not goal_reached): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        time.sleep(0.5)
        head_count = head_count + 1
        if (head_count == head_count_max):
            head_count = 0
            headtime = 1.0
            headpose.moveHead(motion_service, headYaw, headPitch, headtime)
        # action exec
        
    # action end
    memory_service.raiseEvent(mem_key_reset,True);
    # TODO acb. disconnect...
    action_success(actionName,params) 
Example 74
Project: spqrel_tools   Author: LCAS   File: followuntil.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    session = getattr(t, "session", None)

    print "Action "+actionName+" started with params "+params

    # action init
    tracker_service = session.service("ALTracker")

    #We need to obtain the id of the person to follow
    #try:
    #    params = params.split('_')
    #except:
    #    params = params

    #if len(params) == 2:
    #    try:
    #        personid = memory_service.getData(params[1])
    #        params = params[0]
    #    except:
    #        pass
    #else:
    #    try:
    #        
    #    except:
    #        pass
    #print "Person ID = ",personid
    
    personid = memory_service.getData("EngagementZones/PersonEnteredZone1")
    tracker_service.setMode("Navigate")
    # The robot stays a 50 centimeters of target with 10 cm precision
    tracker_service.setRelativePosition([-0.5, 0.0, 0.0, 0.1, 0.1, 0.3])

    tracker_service.registerTarget("People",personid)
    tracker_service.track("People")
    val = False
    # action init

    while (getattr(t, "do_run", True) and (not val)): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        val = get_condition(memory_service, params)
        # action exec
        time.sleep(0.25)
		
    # action end
    tracker_service.stopTracker()
    tracker_service.unregisterAllTargets()
    action_success(actionName,params) 
Example 75
Project: spqrel_tools   Author: LCAS   File: execplan.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    global asr_value, lu4r_value

    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    tts_service = getattr(t, "session", None).service("ALTextToSpeech")
    print "Action "+actionName+" started with params "+params

    # action init
    command_understood = False    
    max_repetitions = 3 # max number of requests of repetitions of the command
    repetitions = 0
    memory_service.raiseEvent("ASR_enable","1")
    # action init

    while (not command_understood and repetitions < max_repetitions and getattr(t, "do_run", True)):

        # wait for command
        print '   -- Waiting for command'
        asr_value=''
        lu4r_value=''
        while (getattr(t, "do_run", True) and asr_value=='' and lu4r_value==''): 
            time.sleep(0.5)    

        if (lu4r_value!=''):
            print '   -- Command received: ',asr_value,' -> ',lu4r_value

            if (lu4r_value=='NO FRAME(S) FOUND'):                
                repetitions = repetitions + 1
                if (repetitions < max_repetitions):
                    memory_service.raiseEvent('DialogueVequest',"say_SOFTFAILUREMANAGEMENT")
            else:
                command_understood = True                

    if (command_understood):
        # compose and start plan
        doExecPlan(memory_service, lu4r_value, asr_value)  # non-blocking
        # wait for end of plan execution
        #val = 0
        #while (getattr(t, "do_run", True) and val==0): 
        #    time.sleep(2)
        #    try:
        #        actpl = memory_service.getData("PNP/ActivePlaces")
        #    except:
        #        actpl = ""
        #    #print "    [DEBUG] active places: ",actpl
        #    if ("goal" in actpl):
        #        val = 1
            
    else:
        memory_service.raiseEvent('DialogueVequest',"say_GIVEUP")


    # action end
    #cmd = "cd ../plans; ./run_plan.py --plan GPSR2"
    #os.system(cmd)
    memory_service.raiseEvent("ASR_enable","0")
    action_success(actionName,params) 
Example 76
Project: spqrel_tools   Author: LCAS   File: personhere.py    MIT License 4 votes vote down vote up
def rhMonitorThread (memory_service):
    global last_personid
    t = threading.currentThread()
    print "personhere thread started"

    while getattr(t, "do_run", True):
        plist = memory_service.getData("PeoplePerception/VisiblePeopleList")
        
        personid = 0
        v = 'false'
        if (plist!=None and len(plist)>0):
            personid = plist[0]

            #print 'personhere:: personid ',personid    
            pmemkey_dist = "PeoplePerception/Person/"+str(personid)+"/Distance"
            pmemkey_angles = "PeoplePerception/Person/"+str(personid)+"/AnglesYawPitch"
            pmemkey_pos = "PeoplePerception/Person/"+str(personid)+"/PositionInRobotFrame"

            pdist = memory_service.getData(pmemkey_dist)
            #print "personhere:: distance ",pdist
            if (pdist < p_dist_thres):
                v = 'true'
            else:
                v = 'false'

            if (v=='true' and personid != last_personid):
                pangles = memory_service.getData(pmemkey_angles)
                ppos    = memory_service.getData(pmemkey_pos)
                print 'personhere: ',str(personid),' dist: ', pdist, ' angle: ',pangles
                print 'personhere: ',str(personid),' Position (local): ',ppos
                memory_service.insertData('Actions/personhere/PersonAngleYaw',                    
                                          str(pangles[0]))
                memory_service.insertData('Actions/personhere/PersonAngleTurn',                    
                                          str((int)(pangles[0]/math.pi*180.0))+"_REL")
                memory_service.insertData('Actions/personhere/PersonID', personid)
                last_personid = personid

        #print plist
        #print "personhere", v
        set_condition(memory_service,'personhere',v)
        
        time.sleep(0.5)
    print "personhere thread quit" 
Example 77
Project: spqrel_tools   Author: LCAS   File: soundtrack.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    t = threading.currentThread()
    memory_service = getattr(t, "mem_serv", None)
    motion_service = getattr(t, "session", None).service("ALMotion")

    session = getattr(t, "session", None)

    print "Action "+actionName+" started with params "+params

    values = params.split('_')
    confidence_threshold = float(values[0])/100.0
    distance_to_people = float(values[1])
    time_to_rotate = int(values[2])

    print "Confidence: " , confidence_threshold
    print "Distance: " , distance_to_people
    print "Time: " , time_to_rotate

    # action init
   
    tracker_service = session.service("ALTracker")
    tracker_service.setMode("WholeBody")
    tracker_service.registerTarget("Sound",[distance_to_people,confidence_threshold])
    tracker_service.track("Sound")

    # action init

    val = False

    while (getattr(t, "do_run", True) and (not val)): 
        #print "Action "+actionName+" "+params+" exec..."
        # action exec
        try:
            sound_value = memory_service.getData("ALSoundLocalization/SoundLocated")
            if len(sound_value)> 1 :
                #print "confidence: ", sound_value[1][2]
                confidence = sound_value[1][2]
                if (confidence > confidence_threshold):
                    val = True
                    break
        except:
	        pass

        # action exec
        time.sleep(0.25)

    count = time_to_rotate * 10
    while (getattr(t, "do_run", True) and  val and count > 0):
        time.sleep(.1)
        count -= 1
		
    # action end
    tracker_service.stopTracker()
    tracker_service.unregisterAllTargets()
    action_success(actionName,params) 
Example 78
Project: spqrel_tools   Author: LCAS   File: updateheadpose.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    global motion_service
    global memory_service

    t = threading.currentThread()
    #memory_service = getattr(t, "mem_serv", None)
    #motion_service = getattr(t, "session", None).service("ALMotion")
    print "Action "+actionName+" started with params "+params
    # action init

    stiff_head = 0.6
    print "   Stiffness -  Head ",stiff_head
        
    names = "Head"
    stiffnessLists = stiff_head
    timeLists = 1.0
    motion_service.stiffnessInterpolation(names, stiffnessLists, timeLists)

    headtime = 1.0

    count=1

    v = params.split('_')
    yaw = 0
    pitch = 0
    try:
        if (len(v)==2):
            yaw = float(v[0])/180.0*math.pi
            pitch = float(v[1])/180.0*math.pi
    except:
        print "headpose: ERROR in values ",v[0]," ",v[1]," - (using 0,0)"
    
    moveHead(motion_service, yaw, pitch, headtime)


    # action init
    while (getattr(t, "do_run", True) and count>0): 
        print "Action "+actionName+" "+params+" exec..."
        # action exec
        count = count - 1		
        # action exec
        time.sleep(0.5)
        
        yawNew =  memory_service.getData('Action/UpdateHeadPose/HeadYaw/Value')
        pitchNew = memory_service.getData('Action/UpdateHeadPose/HeadPitch/Value')

        yawNew = float(yawNew)/180.0*math.pi
        pitchNew = float(pitchNew)/180.0*math.pi

        if (yawNew != yaw) or (pitchNew != pitch):
            yaw = yawNew
            pitch= pitchNew
            moveHead(motion_service, yaw, pitch, headtime)

        
    # action end
    action_success(actionName,params) 
Example 79
Project: spqrel_tools   Author: LCAS   File: googleasr.py    MIT License 4 votes vote down vote up
def actionThread_exec (params):
    global response, recording, audio_recorder, asr_service, memory_service, audio_filename
    t = threading.currentThread()

    memory_service  = getattr(t, "mem_serv", None)

    #reset memory value
    memory_service.insertData("googleasrresponse", "")

    #establishing test vocabulary
    vocabulary = ["grape juice", "orange juice", "chocolate drink", "sprite", "coke", "Alex",\
        "Charlie", "Elizabeth", "Francis", "Jennifer", "Linda", "Mary", "Patricia",\
        "Robin", "Skyler", "James", "John", "Michael", "Robert", "William", "yes", "no"] #add verbs

    asr_service.pause(True)
    asr_service.removeAllContext()
    try:
        asr_service.setVocabulary(vocabulary, True) # put multiple possibilities
    except:
        print "Error setting vocabulary"
    asr_service.pause(False)

    # start the microphone
    file_basename = "SPQRel_rec_"
    audio_filename = os.path.join("/tmp", file_basename + str(time.time()))
    audio_recorder.startMicrophonesRecording(audio_filename + ".wav", "wav", 44100, channels)
    recording = True
    print "audio_recorder started recording"

    response = None
    #let it run
    while response is None:
        print "Waiting for trascription..."
        time.sleep(0.5)

    #save into memory
    memory_service.insertData("googleasrresponse", response)

    asr_service.pause(True)

    #stop recording
    if recording:
        audio_recorder.stopMicrophonesRecording()
        recording = False

    # action end
    action_success(actionName,params) 
Example 80
Project: spqrel_tools   Author: LCAS   File: log_face_people_detection.py    MIT License 4 votes vote down vote up
def rhMonitorThread (memory_service):
    
    t = threading.currentThread()
    
    while getattr(t, "do_run", True):
        imageWidget.timerEvent()
        facevalues =  memory_service.getData("FaceDetected")        
        peoplevalues =  memory_service.getData("PeoplePerception/PeopleDetected")
        peoplevisible =  memory_service.getData("PeoplePerception/VisiblePeopleList")
        if facevalues:
            onFaceDetection(facevalues)
        if peoplevisible:
            detectiontimestamp=peoplevalues[0]
            currentimestamp={'secs':int(detectiontimestamp[0]),'nsecs':int(detectiontimestamp[1])}
            
            for idperson in peoplevisible:
                #try:
                angles =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/AnglesYawPitch")
                distance =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/Distance")
                height =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/RealHeight")
                shirtcolor =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/ShirtColor")
                shirtcolorHSV =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/ShirtColorHSV")
                PositionInRobotFrame =memory_service.getData( "PeoplePerception/Person/" +str(idperson)+"/PositionInRobotFrame")
                print '0'
                personinfo={'height': round(height,2), 'shirtcolor': shirtcolor, 'shirtcolorHSV':shirtcolorHSV} 
                poseinrobotframe={}
                pose={'distance': round(distance,2), 'pitch': round(angles[1],2), 'yaw':round(angles[0],2), 'poseinrobotframe':PositionInRobotFrame}    
                
                person={'timestamp':currentimestamp,'personid': idperson, 'info': personinfo, 'pose': pose}
                json_people=dumps(person)
                if log_enabled is True:
                    log_people.write(json_people+'\n')
                #except:
                 #   print 'Exception::', idperson, 'not found' 
                    
        time.sleep(imageWidget.delay)
        key = cv2.waitKey(1) & 0xFF  
        if key == ord("q"):
            break
    print "Exiting Thread"
    imageWidget.close()
    cv2.destroyAllWindows()