Пример #1
0
    def test_sqs_longpoll(self):
        c = SQSConnection()
        queue_name = "test_sqs_longpoll_%s" % int(time.time())
        queue = c.create_queue(queue_name)
        self.addCleanup(c.delete_queue, queue, True)
        messages = []

        # The basic idea is to spawn a timer thread that will put something
        # on the queue in 5 seconds and verify that our long polling client
        # sees the message after waiting for approximately that long.
        def send_message():
            messages.append(queue.write(queue.new_message("this is a test message")))

        t = Timer(5.0, send_message)
        t.start()
        self.addCleanup(t.join)

        start = time.time()
        response = queue.read(wait_time_seconds=10)
        end = time.time()

        t.join()
        self.assertEqual(response.id, messages[0].id)
        self.assertEqual(response.get_body(), messages[0].get_body())
        # The timer thread should send the message in 5 seconds, so
        # we're giving +- .5 seconds for the total time the queue
        # was blocked on the read call.
        self.assertTrue(4.5 <= (end - start) <= 5.5)
Пример #2
0
def run(data, d=None):
	global timer
	print(data)

	if data == "ring":
		if int(d) == 1:
			if timer:
				timer.cancel()

			timer = Timer(60, genugdavon)
			timer.start()

			check = Thread(target=check_locks)
			check.start()

			putfile('/sys/class/gpio/gpio11/value', '0')

			playsound("/root/ring-bb.wav")
		else:
			playsound("/root/ring-fis.wav")
	

	if data == "open":
#		if not locked_oben:
		playsound("/root/open.wav")
	
	if data == "summ":
		if timer:
			timer.cancel()

#		if not locked_oben:
		putfile('/sys/class/gpio/gpio11/value', '1')
		playsound("/root/summ.wav")
Пример #3
0
class Countdown(object):
    """
    Countdown timer starts immediatly on init from `start_value` and counts down
    to zero, then counts up with negated time. Only displays minutes and
    seconds. No pause or reset available. Each "tick" of the clock is passed to
    the callback function as a string. """
    
    def __init__(self, start_value, callback):
        self._finished = False
        self.start_value = start_value
        self.callback = callback
        self.start_time = now()
        self._update()

    def _update(self):
        self._set_time(now() - self.start_time)
        if not self._finished:
            self._timer = Timer(1, self._update)
            self._timer.start()

    def _set_time(self, value):
        neg = '' 
        if self.start_value > value:
            value = self.start_value - value
        elif self.start_value < value:
            value = value - self.start_value
            neg = '-'
        else:
            value = 0
        mm, ss = divmod(value, 60)
        self.callback("{}{:02d}:{:02d}".format(neg, mm, ss))

    def stop(self):
        self._timer.cancel()
        self._finished = True
class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue:  # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            # Just in case thread is running and cancel fails.
            self._should_continue = False
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")
Пример #5
0
def run(dir, main="tmp"):
    try:
        ##print("DEBUG:", [
        ## config.JAVA_CMD,
        ##    "-Djava.security.manager",
        ##    "-Djava.security.policy=whiley.policy",
        ##    "-cp",config.WYJC_JAR + ":" + dir,
        ##    main
        ##    ])
        # run the JVM
        proc = subprocess.Popen([
                                    config.JAVA_CMD,
                                    "-Djava.security.manager",
                                    "-Djava.security.policy=whiley.policy",
                                    "-cp", config.WYJC_JAR + ":" + dir,
                                    main
                                ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
        # Configure Timeout
        kill_proc = lambda p: p.kill()
        timer = Timer(20, kill_proc, [proc])
        timer.start()
        # Run process        
        (out, err) = proc.communicate()
        timer.cancel()
        # Check what happened
        if proc.returncode >= 0:
            return out
        else:
            return "Timeout: Your program ran for too long!"
    except Exception as ex:
        # error, so return that
        return "Run Error: " + str(ex)
Пример #6
0
class Handler():
    """Queues filesystem events for broadcast"""

    def __init__(self):
        """Create an event handler"""
        ## Timer used to prevent notification floods
        self._timer = None
        ## The files that have changed since the last broadcast
        self._files = set()
        ## Lock to protect files and timer from threading issues
        self._lock = Lock()

    def broadcast(self):
        """Broadcasts a list of all files touched since last broadcast"""
        with self._lock:
            cola.notifier().broadcast(signals.update_status, self._files)
            self._files = set()
            self._timer = None

    def handle(self, path):
        """Queues up filesystem events for broadcast"""
        with self._lock:
            self._files.add(path)
            if self._timer is None:
                self._timer = Timer(0.333, self.broadcast)
                self._timer.start()
    def setupClient(self, topic, msg_type, wait_duration=10):
        """
        Tries to set up an action client for calling it later.
        
        @type topic: string
        @param topic: The topic of the action to call.
        
        @type msg_type: msg type
        @param msg_type: The type of messages of this action client.
        
        @type wait_duration: int
        @param wait_duration: Defines how long to wait for the given client if it is not available right now.
        """
        if topic not in ProxyActionClient._clients:
            client = actionlib.SimpleActionClient(topic, msg_type)
            t = Timer(1, self._print_wait_warning, [topic])
            t.start()
            available = client.wait_for_server(rospy.Duration.from_sec(wait_duration))
            warning_sent = False
            try:
                t.cancel()
            except Exception as ve:
                # already printed the warning
                warning_sent = True

            if not available:
                Logger.logerr("Action client %s timed out!" % topic)
            else:
                ProxyActionClient._clients[topic] = client
                if warning_sent:
                    Logger.loginfo("Finally found action client %s..." % (topic))
Пример #8
0
 def view_image(self, im, auto_close=True):
     # use a manager to open so will auto close on quit
     self.open_view(im)
     if auto_close:
         minutes = 2
         t = Timer(60 * minutes, im.close_ui)
         t.start()
Пример #9
0
  def run(self, app, type):
    # Invoke wren and run the test.
    test_arg = self.path
    if type == "api test":
      # Just pass the suite name to API tests.
      test_arg = basename(splitext(test_arg)[0])

    proc = Popen([app, test_arg], stdin=PIPE, stdout=PIPE, stderr=PIPE)

    # If a test takes longer than two seconds, kill it.
    #
    # This is mainly useful for running the tests while stress testing the GC,
    # which can make a few pathological tests much slower.
    timed_out = [False]
    def kill_process(p):
      timed_out[0] = True
      p.kill()

    timer = Timer(2, kill_process, [proc])

    try:
      timer.start()
      out, err = proc.communicate(self.input_bytes)

      if timed_out[0]:
        self.fail("Timed out.")
      else:
        self.validate(type == "example", proc.returncode, out, err)
    finally:
      timer.cancel()
class PeriodicTimer(object):

    def __init__(self, frequency=60, *args, **kwargs):
        self.is_stopped = Event()
        self.is_stopped.clear()

        self.interval = frequency
        self._timer = Timer(self.frequency, self._check_for_event, ())
        self._timer.daemon = True

    @property
    def interval(self):
        return self.frequency

    @interval.setter
    def interval(self, frequency):
        self.frequency = frequency
        self.stop()
        try:
            if self._timer:
                self._timer.cancel()
                del(self._timer)
        except AttributeError, ex:
            pass
        self._timer = Timer(self.frequency, self._check_for_event, ())
        return self.frequency
Пример #11
0
class TimerMixIn(object):
  
    def __init__(self, *argl, **argd):
        super(TimerMixIn,self).__init__(*argl,**argd)
        self.timer = None
        self.timerSuccess = True
          
    def startTimer(self, secs):
        if self.timer is not None:
            self.cancelTimer()
        self.timer = Timer(secs, self.__handleTimerDone)
        self.timerSuccess = False
        self.timer.start()
  
    def cancelTimer(self):
        if self.timer is not None and self.timer:
             self.timer.cancel()
             self.timer = None
             self.timerSuccess = False
  
    def timerRunning(self):
        return self.timer is not None
        
    def timerWasCancelled(self):
        return not self.timerSuccess
  
    def __handleTimerDone(self):
        self.scheduler.wakeThread(self)
        self.timer = None
        self.timerSuccess = True
Пример #12
0
def dataout():
    global timer1
    timer1 = Timer(1.0 / data_freq, dataout)
    timer1.start()
    lock.acquire()
    print "{:+.3f}".format(data.popleft())
    lock.release()
Пример #13
0
 def create_session(self):
     log.info("Enabling for MAC %s" % (self.mac))
     sys_cmd = "iptables -I internet 1 -t mangle -m mac --mac-source %s -j RETURN" % self.mac
     log.info(sys_cmd)
     log.info(os.popen(sys_cmd).read())
     callback = Timer(self.length, self.destroy_session)
     callback.start()
Пример #14
0
 def defer(self, t, run_on_cancel, func, *args):
     event = Timer(t, self.run_action, kwargs={'func': func, 'args': args})
     event.name = '%s deferring %s' % (event.name, func.__name__)
     event.start()
     with worker_lock:
         self.events[event.ident] = Event(event, run_on_cancel)
     return event.ident
Пример #15
0
    def _connected(self, link_uri):
        """ This callback is called form the Crazyflie API when a Crazyflie
        has been connected and the TOCs have been downloaded."""
        print('Connected to %s' % link_uri)

        # The definition of the logconfig can be made before connecting
        self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=10)
        self._lg_stab.add_variable('stabilizer.roll', 'float')
        self._lg_stab.add_variable('stabilizer.pitch', 'float')
        self._lg_stab.add_variable('stabilizer.yaw', 'float')

        # Adding the configuration cannot be done until a Crazyflie is
        # connected, since we need to check that the variables we
        # would like to log are in the TOC.
        try:
            self._cf.log.add_config(self._lg_stab)
            # This callback will receive the data
            self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
            # This callback will be called on errors
            self._lg_stab.error_cb.add_callback(self._stab_log_error)
            # Start the logging
            self._lg_stab.start()
        except KeyError as e:
            print('Could not start log configuration,'
                  '{} not found in TOC'.format(str(e)))
        except AttributeError:
            print('Could not add Stabilizer log config, bad configuration.')

        # Start a timer to disconnect in 10s
        t = Timer(5, self._cf.close_link)
        t.start()
Пример #16
0
def initial():

		#UDP socket works
	print 'Waiting For Peers.... :)'
	sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	sock_udp.bind((SERVER_IP,SERVER_PORT))
	peer_data = ''
	t = Timer (TIMER_IDLE_PEER, timer_function)
	t.start()
	exp_seq=1
	old_buffer=''
		#Request from Peer
	while True:
		recv_buffer,addr = sock_udp.recvfrom(4096)
		if recv_buffer == 'list':
			sock_udp.sendto(str(peer_list), addr)
		else:
			sock_udp.sendto(recv_buffer,addr)
			if old_buffer != recv_buffer:
				old_buffer = recv_buffer
				recv_buffer_split = recv_buffer.split()
				recv_buffer_len = len(recv_buffer_split)
				num_pkts = recv_buffer_split.pop(recv_buffer_len-1)
				seq_pkt = recv_buffer_split.pop(recv_buffer_len-2)
				exp_seq=exp_seq+1
				peer_data = peer_data + ''.join((str(x)+' ') for x in recv_buffer_split)
				if num_pkts == seq_pkt:
					thread = Thread(target = process_packet, args = (peer_data,sock_udp,addr))
					thread.start() #TEST THREADING!!!!!!!!!!!!!!!!!!!!
					#thread.join()
					peer_data = ''
					exp_seq=1
Пример #17
0
 def request_handler(self):
    timeout = self.opcd.get('power_save_timeout')
    req = PowerReq()
    rep = PowerRep()
    timer = None
    while True:
       rep.status = OK
       try:
          req_data = self.ctrl_socket.recv()
       except:
          sleep(1)
          continue
       try:
          req.ParseFromString(req_data)
       except:
          rep.status = E_SYNTAX
       else:
          try:
             timer.cancel()
          except:
             pass
          if req.cmd == STAND_POWER:
             timer = Timer(timeout, self.power_off)
             timer.start()
          else:
             if self.critical:
                # flying command is not allowed if battery was critical:
                rep.status = E_POWER
             else:
                self.gpio_mosfet.set_gpio(self.power_pin, True)
       self.ctrl_socket.send(rep.SerializeToString())
Пример #18
0
 def run(self):
     while self.is_running:
         try:
             super(SerializeThread, self).run()
         except Exception, e:
             log.error("Exception in thread %s: %s", self.name, e)
             delay = TIMER_DELAYS[self.name]
             if delay > MAX_DELAY:
                 num_attempts = int(math.log((delay/10), 2));
                 log.error("Giving up re-spawning serialization " 
                     "worker after %d seconds (%d attempts).", 
                     delay, num_attempts
                 )
                 notify_serialization_failure(None,
                     subject="Notice - Bungeni Serialization Workers",
                     body="""Unable to restart serialization worker.
                 Please check the Bungeni logs."""
                 )
             else:
                 log.info("Attempting to respawn serialization "
                     "consumer in %d seconds", delay
                 )
                 next_delay = delay * 2
                 timer = Timer(delay, init_thread, [], 
                     {"delay": next_delay })
                 timer.daemon = True
                 timer.start()
             self.is_running = False
             del TIMER_DELAYS[self.name]
Пример #19
0
class InternalServer(HTTPServer):

    def kill_me(self):
        self.shutdown()
        logging.info("The server's life has come to an end, pid: {}".format(os.getpid()))


    def reset_selfdestruct_timer(self):
        if self.self_destruct_timer:
            self.self_destruct_timer.cancel()

        self.self_destruct_timer = Timer(LIFESPAN, self.kill_me)
        self.self_destruct_timer.start()


    def __init__(self, server_address, RequestHandlerClass, 
                 bind_and_activate=True):

        HTTPServer.__init__(self, server_address, RequestHandlerClass, 
                            bind_and_activate=bind_and_activate)
        
        self.self_destruct_timer = None
        self.clients = 1
        self.reset_selfdestruct_timer()


    def suicide(self):
        self.clients -= 1
        if self.clients == 0:
            if self.self_destruct_timer is not None:
                self.self_destruct_timer.cancel()

            quick_and_painless_timer = Timer(0.1, self.kill_me)
            quick_and_painless_timer.start()
Пример #20
0
def clean_avisos():
    global avisos_n
    logger.info("avisos_n = 0")
    avisos_n = 0
    global hilo
    hilo = Timer(config['clean_time'], clean_avisos)
    hilo.start()
Пример #21
0
def scheduleFlight(res, flight, blocking=False, scheduler=None):
  flight_time = time_module.mktime(flight.legs[0].depart.dt_utc.utctimetuple()) - time_module.timezone
  seconds_before = config["CHECKIN_WINDOW"] + 24*60*60 # how many seconds before the flight time do we check in
  flight.sched_time = flight_time - seconds_before
  flight.sched_time_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc) - timedelta(seconds=seconds_before))
  flight.seconds = flight.sched_time - time_module.time()
  # Retrieve timezone and apply it because datetimes are stored as naive (no timezone information)
  tz = airport_timezone_map[flight.legs[0].depart.airport]
  flight.sched_time_local_formatted = DateTimeToString(flight.legs[0].depart.dt_utc.replace(tzinfo=utc).astimezone(tz) - timedelta(seconds=seconds_before))
  db.Session.commit()
  dlog("Flight time: %s" % flight.legs[0].depart.dt_formatted)
  if config["CELERY"]:
    from tasks import check_in_flight
    result = check_in_flight.apply_async([res.id, flight.id], countdown=flight.seconds)
    flight.task_uuid = result.id
    db.Session.commit()
  elif not blocking:
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC) in", int(flight.seconds/60/60), "hrs", int(flight.seconds/60%60),  "mins from now..."
    t = Timer(flight.seconds, TryCheckinFlight, (res.id, flight.id, None, 1))
    t.daemon = True
    t.start()
    # DEBUG
    # if flight == res.flights[0]:
    #   Timer(5, TryCheckinFlight, (res, flight, None, 1)).start()
  else:
    scheduler.enterabs(flight.sched_time, 1, TryCheckinFlight, (res.id, flight.id, scheduler, 1))
    result = "Scheduling check in for flight at", flight.legs[0].depart.dt_formatted, "(local), ", flight.legs[0].depart.dt_utc_formatted, "(UTC)"
  print result
  dlog('Checkin scheduled at (UTC): %s' % flight.sched_time_formatted)
  dlog('Checkin scheduled at (local): %s' % flight.sched_time_local_formatted)
  dlog('Flights scheduled.  Waiting...')
  return result
Пример #22
0
class IOServer(threading.Thread):
    # 6 7 8 9 
    # l d u r
    uPin = 15 # u <-> d
    lPin = 27 # l <-r
    rPin = 14
    dPin = 18
    def __init__(self):
        threading.Thread.__init__(self)
        # tprint(self.currentState)
        GPIO.setmode(GPIO.BCM)
        setupGPIO(self.uPin, self.upButtonHandler)
        setupGPIO(self.lPin, self.leftButtonHandler)
        setupGPIO(self.rPin, self.rightButtonHandler)
        setupGPIO(self.dPin, self.downButtonHandler)
        self.quit = False
        self.lcd = get_lcdcontroller()
        self.timer = Timer(0.5, self.timeoutHandler)
        
    def run(self):
        tprint("start ioserver")
        self.timer.start()
        lcd = self.lcd
        while True:
            c = getch()
            if (c == 'w'):
                lcd.up()
            elif (c == 'a'):
                lcd.left()
            elif (c == 's'):
                lcd.down()
            elif (c == 'd'):
                lcd.right()
            elif (c == ' '):
                lcd.center()
            elif (c == 'u'):
                lcd.updateDisplay()
            elif (c == 'q'):
                self.quit = True
                break
            else:
                tprint("Unknown Command")

    def upButtonHandler(self, pin = None):
        self.lcd.up()
        
    def downButtonHandler(self, pin = None):
        self.lcd.down()
        
    def leftButtonHandler(self, pin = None):
        self.lcd.left()

    def rightButtonHandler(self, pin = None):
        self.lcd.right()

    def timeoutHandler(self):
        self.lcd.updateDisplay()
        if not self.quit:
            self.timer = Timer(0.5, self.timeoutHandler)
            self.timer.start()
Пример #23
0
class RepeatTimer:
    """Timer that repeats itself `interval` seconds /after/ each function call returns."""

    def __init__(self, interval, fn, args=None, kwargs=None):
        self.cancelled = False

        args = args or ()
        kwargs = kwargs or {}

        def repeater():
            if self.cancelled:
                return

            fn(*args, **kwargs)
            self.timer = Timer(interval, repeater)
            self.timer.start()

        self.timer = Timer(interval, repeater)

    def start(self):
        logging.debug('starting timer')
        self.timer.start()

    def cancel(self):
        logging.debug('cancelling timer')
        # `timer.cancel()` won't cancel properly if within repeater call, so use internal check
        self.cancelled = True
Пример #24
0
class OpeningState:
    def __init__(self, door_model):
        self.door_model = door_model

    def door_position_changed(self, new_position):
        if new_position == DOOR_POSITION_OPEN:
            self.door_model.set_new_state("Open")
        elif new_position == DOOR_POSITION_CLOSED:
            self.door_model.set_new_state("Closed")

    def enter(self):
        logger.debug("State 'opening' entered")
        self.timer = Timer(self.door_model.transit_time, self._transit_timeout)
        self.timer.start()

    def exit(self):
        logger.debug("State 'opening' exited")
        if self.timer:
            self.timer.cancel()
            self.timer = False

    def _transit_timeout(self):
        logger.info("Transit timeout reached")
        self.timer = False
        self.door_model.set_new_state("Intermediate")
def setInterval(func, sec):
    def func_wrapper():
        setInterval(func, sec)
        func()
    t = Timer(sec, func_wrapper)
    t.start()
    return t
Пример #26
0
    def _on_message(self, ws, message):
        self.logger.info("Connection: Message - %s" % message)

        # Stop our timeout timer, since we got some data
        self.connection_timer.cancel()
        self.ping_timer.cancel()

        params = self._parse(message)

        if 'event' in params.keys():
            if 'channel' not in params.keys():
                # We've got a connection event.  Lets handle it.
                if params['event'] in self.event_callbacks.keys():
                    for callback in self.event_callbacks[params['event']]:
                        callback(params['data'])
                else:
                    self.logger.info("Connection: Unhandled event")
            else:
                # We've got a channel event.  Lets pass it up to the pusher
                # so it can be handled by the appropriate channel.
                self.event_handler(
                    params['event'],
                    params['data'],
                    params['channel']
                )

        # We've handled our data, so restart our connection timeout handler
        self.connection_timer = Timer(self.connection_timeout, self._connection_timed_out)
        self.connection_timer.start()

        self.ping_timer = Timer(self.ping_interval, self.send_ping)
        self.ping_timer.start()
Пример #27
0
    def onStatusUpdate(self, cmd):
        cmd.updateTime = time.time()
        # append the command's status to the rendernode's history
        if isFinalStatus(cmd.status):
            # only if we don't already have a command for this task
            if hasattr(cmd.renderNode, 'tasksHistory') and cmd.task.id not in cmd.renderNode.tasksHistory:
                cmd.renderNode.tasksHistory.append(cmd.task.id)
                cmd.renderNode.history.append(cmd.status)
        if cmd.status is CMD_DONE:
            # TOFIX: handle CANCEL status and update end time when cancelling a
            # job so that it can be properly cleaned
            cmd.endTime = cmd.updateTime
            cmd.computeAvgTimeByFrame()
            cmd.attempt += 1

        # autoretry
        elif cmd.status is CMD_ERROR:
            cmd.attempt += 1

            LOGGER.debug("Mark command %d for auto retry in %ds  (%d/%d)" % (cmd.id, singletonconfig.get('CORE', 'DELAY_BEFORE_AUTORETRY'), cmd.attempt, cmd.task.maxAttempt))
            if cmd.attempt < cmd.task.maxAttempt:
                t = Timer(singletonconfig.get('CORE', 'DELAY_BEFORE_AUTORETRY'), self.autoretry, [cmd])
                t.start()

        elif cmd.status is CMD_ASSIGNED:
            cmd.startTime = cmd.updateTime
        elif cmd.status < CMD_ASSIGNED:
            cmd.startTime = None
Пример #28
0
	def sync (self):
		if len (self.clients) == 0:
			self.logger.debug ('No clients available, bootstrapping...')
			self.reboot ()
			return

		if len (self.clients) < self.minpeers:
			self.logger.debug ('Available clients are less than minpeers, bootstrapping...')

			if self.boottimer != None:
				self.boottimer.cancel ()

			self.boottimer = Timer (5.0, self.reboot)
			self.boottimer.start ()


		for p in self.clients:
			#r = random.randint(0, len (self.clients) - 1)
			#p = self.clients [r]
			try:
				getblock = clients.GetBlocks ([int (self.db['lastblockhash'], 16)])
				p.send_message (getblock)
			except Exception as e:
				#self.logger.error ('Node fail.')
				if not p.reconnect ():
					self.logger.debug ('Removed unreachable peer %s (%s)', str (p.host), e)
					self.clients.remove (p)
					self.logger.debug ('Available peers: %d', len (self.clients))


		self.synctimer.cancel ()
		self.synctimer = Timer (5.0, self.sync)
		self.synctimer.start ()
Пример #29
0
    def __init__(self, name) :
       
        rospy.on_shutdown(self._on_node_shutdown)
        self.current_node = "Unknown"
        self.nogo_pre_active = False
        self.nogo_active = False
        self.nogos=[]
        self.stop_services=["/enable_motors", "/emergency_stop", "/task_executor/set_execution_status"]
        self.activate_services=["/enable_motors", "/reset_motorstop", "/task_executor/set_execution_status"]

        #Waiting for Topological Map        
        self._map_received=False
        rospy.Subscriber('/topological_map', TopologicalMap, self.MapCallback)      
        rospy.loginfo("Waiting for Topological map ...")        
        while not self._map_received :
            pass
        rospy.loginfo(" ...done")


        self.update_service_list()
        print self.av_stop_services, self.av_activate_services
        
    
        #Subscribing to Localisation Topics
        rospy.loginfo("Subscribing to Localisation Topics")
        rospy.Subscriber('/current_node', String, self.currentNodeCallback)
        rospy.loginfo(" ...done")

        self.nogos = self.get_no_go_nodes()
        print self.nogos
        self._killall_timers=False
        t = Timer(1.0, self.timer_callback)
        t.start()
        rospy.loginfo("All Done ...")
        rospy.spin()
Пример #30
0
class ThreddsConnection(object):

    def __init__(self, app, random_state, timeout=300.0,
                 cached=False, **fs_args):
        """ Create an expiring connection to the THREDDS server.

        The connection will drop after 5 minutes of non-use. Any subsequent
        attempt to use the connection will initiate a new one. Access to the
        connection is RLock'd to ensure only one connection is alive at a time.

        Parameters:
        timeout : int, seconds
            The length of time in seconds to hold open a connection.

        Remaining keyword args are passed to the connection's constructor.
        """
        self.app = app
        self.random_state = random_state
        self.cached = cached
        self._fs = {}
        self._fs_lock = RLock()
        self._fs_args = fs_args
        self._timer = None
        self.timeout = float(timeout)

    def cached():
        doc = "If True, use cached data."

        def fget(self):
            return self._cached

        def fset(self, value):
            self.datasources = {
                'hindcast':
                    HINDCAST_CACHE_DATA_URI if value else HINDCAST_DATA_URI,
                'forecast':
                    FORECAST_CACHE_DATA_URI if value else FORECAST_DATA_URI,
            }
            self._cached = value
        return locals()
    cached = property(**cached())

    def _forget(self):
        self.app.logger.info("Closing THREDDS connection")
        if self._timer:
            self._timer.cancel()
            self._timer = None
        self._fs = {}

    def _reset_timer(self):
        self.app.logger.info("Resetting THREDDS connection timer")
        if self._timer:
            self._timer.cancel()
        self._timer = Timer(self.timeout, self._forget)
        self._timer.start()

    hindcast_fs = property(fget=partial(fget, datasource='hindcast'),
                           fdel=fdel)
    forecast_fs = property(fget=partial(fget, datasource='forecast'),
                           fdel=fdel)