def get_firmware_version(): """\ Returns a tuple of the Device firmware version using RCI. The tuple is an n-tuple of the form (p, q, r, ..) where the original version string was p.q.r.. For example the version string "2.8.1" will return (2, 8, 1). This call is often required to determine future system behavior, therefore it will retry until it completes successfully. """ i = 3 while i > 0: try: device_info = query_state("device_info") i = -1 except Exception, e: i -= 1 _tracer.error( "get_firmware_version(): WARNING, query_state() failed: %s", str(e)) digitime.sleep(1) if i == 0: _tracer.critical( "get_firmware_version(): fatal exception caught! Halting execution." )
def make_request(self): self._tracer.calls("make_request") # first thing, RE-SCHEDULE so we keep running despite a fault self.__schedule_request() self.__req_cnt += 1 self.__response_buffer = "" if self.__mode == self.MODE_WAIT_RSP: self._tracer.warning("Last Poll never finished") self.update_availability() if M300_DO_TRIGGER: # for testing only buf = self.__sensor.req_software_trigger_1() self.write(buf) digitime.sleep(0.1) buf = self.__sensor.req_status_3() try: ret = self.write(buf) if ret == False: raise Exception, "write failed" self.__mode = self.MODE_WAIT_RSP except: # try again later: self._tracer.error("xmission failure.") self.__mode = self.MODE_IDLE return
def run(self): # Set the value of the channels with the configured settings full_string = (SettingsBase.get_setting(self, "prefix_init") + SettingsBase.get_setting(self, "suffix_init")) self.property_set( "prefix_string", Sample(0, SettingsBase.get_setting(self, "prefix_init"))) self.property_set( "suffix_string", Sample(0, SettingsBase.get_setting(self, "suffix_init"))) self.property_set("xtended_string", Sample(0, full_string)) while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # increment counter property: full_string = (self.property_get("prefix_string").value + self.property_get("suffix_string").value) self.property_set("xtended_string", Sample(0, full_string)) digitime.sleep(SettingsBase.get_setting(self, "update_rate"))
def run(self): interval = SettingsBase.get_setting(self, "initial_upload") if interval is None: interval = SettingsBase.get_setting(self, "interval") self.__last_upload_clock = 0 self.__last_upload_time = 0 while not self.__stopevent.isSet(): try: # 32 bit modulo math to account for an NDS bug :-( now = int(digitime.real_clock()) & 0xffffffff time_passed = (now - self.__last_upload_clock) & 0xffffffff interval_met = (interval > 0 and time_passed > interval) threshold_met = self.__threshold_event.isSet() if interval_met: interval = SettingsBase.get_setting(self, "interval") self.__sample_count = 0 self.__threshold_event.clear() self.__upload_data() elif threshold_met: interval = SettingsBase.get_setting(self, "interval") self.__threshold_event.clear() self.__upload_data() digitime.sleep(1) except Exception, e: self.__tracer.error("exception while uploading: %s", str(e))
def __wait_until_system_ready(self): """Waits until subsystems indicate they are ready. Returns None.""" # Python executes on the Digi device before all subsystems # are fully initialized, some simple checks should be performed # in order to simplify the number of exceptions that would # otherwise need to be tested for during driver initialization. # Test to see if the TCP/IP stack is available. tcpip_stack_ready = False for portnum in xrange(54146, 65535): try: sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sd.bind(('', portnum)) sd.close() except Exception, e: # Embedded TCP/IP stack not ready or trial port in use. # Sleep for one second... traceback.print_exc() print "Core: Waiting for network (port tested: %d, e: %s)..." % \ (portnum, str(e)) digitime.sleep(1) # ...and try another port. continue # Test succeeded, exit loop. tcpip_stack_ready = True break
def run(self): #Get the device properties time_sleep = SettingsBase.get_setting(self, "update_rate") self.input_gpios = SettingsBase.get_setting(self, "input_gpios") self.output_gpios = SettingsBase.get_setting(self, "output_gpios") #Call the GPIOs initializer method self.initialize_gpios() #Start the refresh thread while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break try: while self.setting_gpio: pass self.get_GPIOs() except Exception, e: self.__tracer.error("Unable to update values: %s", str(e)) #Sleep the time configured in settings (in seconds) digitime.sleep(time_sleep)
def run(self): type = SettingsBase.get_setting(self, "type") if type == "serial": from presentations.console.console_serial_server import \ ConsoleSerialServer server = ConsoleSerialServer( SettingsBase.get_setting(self, "device"), SettingsBase.get_setting(self, "baudrate"), self.__core, self.__stopevent) else: server = ConsoleTcpServer( ('', SettingsBase.get_setting(self, "port")), ConsoleTcpRequestHandler, self.__core, self.__stopevent) while 1: if self.__stopevent.isSet(): break if isinstance(server, ConsoleTcpServer): r, w, e = select([server.socket], [], [], 1.0) else: r = True # Serial ports are always ready if r: # Spawns a thread for TCP, blocks for Serial server.handle_request() while hasattr(server, "handlers") and len(server.handlers): # Wait for handlers to exit digitime.sleep(1.0)
def run(self): while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break try: self._tracer.info("Reading GPS data.....") gps_data = digihw.gps_location() #Retrieve information from gps_location name = ['latitude', 'longitude', 'altitude', 'current_time'] for index in range(len(name)): self.property_set(name[index], Sample(0, value=gps_data[index])) except: import traceback traceback.print_exc() self._tracer.info("Unable to get a GPS signal.") self._tracer.info( "Please place the GPS antenna in another place.") digitime.sleep(SettingsBase.get_setting(self, "sample_rate"))
def run(self): #Get the device properties time_sleep = SettingsBase.get_setting(self,"update_rate") self.input_gpios = SettingsBase.get_setting(self,"input_gpios") self.output_gpios = SettingsBase.get_setting(self,"output_gpios") #Call the GPIOs initializer method self.initialize_gpios() #Start the refresh thread while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break try: while self.setting_gpio: pass self.get_GPIOs() except Exception, e: self.__tracer.error("Unable to update values: %s", str(e)) #Sleep the time configured in settings (in seconds) digitime.sleep(time_sleep)
def __wait_until_system_ready(self): """Waits until subsystems indicate they are ready. Returns None.""" # Python executes on the Digi device before all subsystems # are fully initialized, some simple checks should be performed # in order to simplify the number of exceptions that would # otherwise need to be tested for during driver initialization. # Test to see if the TCP/IP stack is available. tcpip_stack_ready = False for portnum in xrange(54146, 65535): try: sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sd.bind(('', portnum)) sd.close() except Exception, e: # Embedded TCP/IP stack not ready or trial port in use. # Sleep for one second... print "Core: Waiting for network (port tested: %d, e: %s)..." % \ (portnum, str(e)) digitime.sleep(1) # ...and try another port. continue # Test succeeded, exit loop. tcpip_stack_ready = True break
def get_firmware_version(): """\ Returns a tuple of the iDigi Device firmware version using RCI. The tuple is an n-tuple of the form (p, q, r, ..) where the original version string was p.q.r.. For example the version string "2.8.1" will return (2, 8, 1). This call is often required to determine future system behavior, therefore it will retry until it completes successfully. """ i = 3 while i > 0: try: device_info = query_state("device_info") i = -1 except Exception, e: i -= 1 _tracer.error("get_firmware_version(): WARNING, query_state() failed: %s", str(e)) digitime.sleep(1) if i == 0: _tracer.critical("get_firmware_version(): fatal exception caught! Halting execution.")
def run(self): self.subscribe_write_channels() while not self.__stopevent.isSet(): digitime.sleep(3.0) return
def run(self): """\ Runs the device driver. The main function of this driver. It shall run forever until it is told to stop by the stop function. """ self.__tracer.info("XBeeAutoEnum: discover_thread start") discover_rate = SettingsBase.get_setting(self, "discover_rate") # Schedule the last discover time such that we will do our first # discover on the network 3 minutes after we started. # This allows the Dia to stabilize, configure any static XBee devices # and have things settle down a bit. last_discover_time = digitime.real_clock() - discover_rate + 120 count = 0 while True: if count < 60: count += 1 digitime.sleep(1) continue if self.__stopevent.isSet(): self.__stopevent.clear() break # Check to see if we should do a network discover. if last_discover_time + discover_rate <= digitime.real_clock(): try: self.__discover_poll() except: # Any exceptions taken here are not a problem. # We will pick up any new devices next poll cycle. pass last_discover_time = digitime.real_clock() # Try to a get a new device from the Queue, blocking for # up to 5 seconds. try: addr = self.__add_device_queue.get(True, 5.0) except Queue.Empty: continue if addr != None: already_in = self.__check_if_device_is_already_in_system(addr) if already_in == False: self.__add_new_device(addr) else: digitime.sleep(1) # Unregister ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_unregister(self) self.__tracer.info("XBeeAutoEnum: discover_thread end")
def run(self): serial_device = SettingsBase.get_setting(self, "serial_device") baud_rate = SettingsBase.get_setting(self, "serial_baud") # The way we read the NMEA-0183 data stream is different between # the nds-based products and the X3 products. # # The nds-based product has the data stream coming in over # a serial port, so we need to be able to set the baud rate. # # The X3-based product has the data stream coming in over I2C, # which does not require setting any sort of baud rate. # Also, the X3 platform is slower than the nds based platforms, # so we offer a way to delay reading the stream, so that parsing # the stream doesn't monopolize the cpu. if get_platform_name() == 'digix3': sample_rate_sec = SettingsBase.get_setting(self, "sample_rate_sec") else: sample_rate_sec = 0 _serial = serial.Serial(port=serial_device, baudrate=baud_rate, timeout=SHUTDOWN_WAIT) nmea_obj = nmea.NMEA() while 1: if self.__stopevent.isSet(): self.__stopevent.clear() _serial.close() break # 16384 is a MAGIC NUMBER that came into existence # before my time... my (extremely limited) testing # has shown that this number makes for clean cut-offs # in talker strings (as defined by the NMEA 0183 # Protocol definition (v3)) # # In other words, you always get the full last line # up to and including the line-terminating '\r\n'. # # This makes the nmea parser joyful. # this returns '' on a timeout data = _serial.read(size=16384) # Read in the NMEA-0183 stream data, and parse it if data and len(data) > 0: self.__tracer.debug(data) nmea_obj.feed(data, self.property_setter) digitime.sleep(sample_rate_sec)
def run(self): self._logger.debug("starting to run.") while not self.__stopevent.isSet(): digitime.sleep (60) self._logger.info("Out of run loop. Shutting down...") # Clean up channel registration self.__cp.unsubscribe_from_all(self._receive_sensor_data_callback_synchronized)
def run(self): self.__logger.info("Starting DIA module %s" % self.__name) initial_sample = self.property_get("raw_in") print initial_sample.value while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # NOT REACHED digitime.sleep(_SLEEP_TIME_IN_MAINLOOP) self.__logger.info("Terminating DIA module %s" % self.__name)
def run(self): cm = self.__core.get_service("channel_manager") cp = cm.channel_publisher_get() cdb = cm.channel_database_get() #threshold = SettingsBase.get_setting(self, 'acc_threshold') sample_rate_ms = SettingsBase.get_setting(self, 'sample_rate_ms') #self._tracer.info("Threshold set to %.3fG" %threshold) if digihw.NB_GPIO != len(channel_type): self._tracer.info('Invalid number of channels') while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # acceleration_value = self.update_accelerometer_info() # self.property_set("acceleration", Sample(0, acceleration_value)) for index, ch_type in enumerate(channel_type): if ch_type == 'in': current_status = bool(digihw.gpio_get_value(index)) digihw.gpio_set_input(index) self.property_set('channel%d_input' %(index+1), \ Sample(0, current_status)) elif ch_type == 'out': status = self.property_get('channel%d_output' %(index+1)).value digihw.gpio_set_value(index, status) try: self._tracer.info("Reading GPS data.....") gps_data = digihw.gps_location() #Retrieve information from gps_location name = ['latitude', 'longitude', 'altitude', 'current_time'] for index in range(len(name)): self.property_set(name[index], Sample(0, value = gps_data[index])) except: import traceback traceback.print_exc() self._tracer.info("Unable to get a GPS signal.") self._tracer.info("Please place the GPS antenna in another place.") status = digihw.ignition_sense() self.property_set("ignition_status", Sample(0, status)) digitime.sleep(sample_rate_ms / 1000)
def run(self): """\ Runs the device driver. The main function of this driver. It shall run forever until it is told to stop by the stop function. """ self.__tracer.info("XBeeAutoEnum: discover_thread start") discover_rate = SettingsBase.get_setting(self, "discover_rate") # Schedule the last discover time such that we will do our first # discover on the network 3 minutes after we started. # This allows the DIA to stabilize, configure any static XBee devices # and have things settle down a bit. last_discover_time = digitime.real_clock() - discover_rate + 180 while True: if self.__stopevent.isSet(): self.__stopevent.clear() break # Check to see if we should do a network discover. if last_discover_time + discover_rate <= digitime.real_clock(): try: self.__discover_poll() except: # Any exceptions taken here are not a problem. # We will pick up any new devices next poll cycle. pass last_discover_time = digitime.real_clock() # Try to a get a new device from the Queue, blocking for # up to 5 seconds. try: addr = self.__add_device_queue.get(True, 5.0) except Queue.Empty: continue if addr != None: already_in = self.__check_if_device_is_already_in_system(addr) if already_in == False: self.__add_new_device(addr) else: digitime.sleep(1) # Unregister ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_unregister(self) self.__tracer.info("XBeeAutoEnum: discover_thread end")
def run(self): self.prop_set_global_reset(0) while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # increment counter property: counter_value = self.property_get("counter").value self.property_set("counter", Sample(0, counter_value + 1)) digitime.sleep(SettingsBase.get_setting(self,"update_rate"))
def do_blink_pattern(self, pattern): d = {} for led in self.supported_leds: d[led] = False for (duration, led) in pattern: duration = float(duration) led = int(led) if self.stop_event.is_set() or self.clear_event.is_set(): return d[led] = not d[led] user_led_set(d[led], led) digitime.sleep(duration)
def run(self): # Baseline relative time targets self._set_targets() while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break rate = SettingsBase.get_setting(self, PROP_TICK_RATE) self._trigger(rate) time.sleep(rate) return
def run(self): """run when our device driver thread is started""" # Take all the driver settings self.get_settings() # Save the current level percent self.current_level = self.initial_level # Save the current temperature self.current_temperature = self.initial_temperature # Obtain and save the current tank volume self.current_volume = self.get_initial_volume(self.initial_level) while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # Calculate the new level percent of the tank new_level = self.get_new_volume_percent() # Check if the level is growing or descending if (new_level > self.current_level): self.level_growing = True elif (new_level < self.current_level): self.level_growing = False # Save the level percent for the next time self.current_level = new_level # Calculate the new temperature of the tank new_temperature = self.get_new_temperature() # Check if the temperature is growing or descending if (new_temperature > self.current_temperature): self.temperature_growing = True elif (new_temperature < self.current_temperature): self.temperature_growing = False # Save the temperature for the next time self.current_temperature = new_temperature # Set the new level percent on its corresponding channel self.set_new_level(self.current_level) # Set the new temperature on its corresponding channel self.set_new_temperature(self.current_temperature) # Check if any alarm should be triggered self.check_alarms() # Sleep one second digitime.sleep(1)
def wait_for_shutdown(self, timeout=None): """ Blocks the current thread for optional `timeout` seconds while waiting for a shutdown request. If `timeout` is not given, this call will block indefinitely until another thread calls request_shutdown() """ # polling is cheaper than waiting # on a threading.Condition object if timeout is None: while not self.shutdown_requested(): digitime.sleep(1) else: for i in range(timeout): if self.shutdown_requested(): break else: digitime.sleep(1)
def run(self): while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break try: device_stats = query_state("device_stats") for stat in [ 'uptime', 'cpu', 'freemem', 'usedmem', 'totalmem' ]: for item in device_stats: data = item.find(stat) if data != None: data = data.text break else: continue if stat == 'uptime': self.property_set( "uptime", Sample(0, int(float(data)), unit="sec")) elif stat == 'cpu': self.property_set("cpu_utilization", Sample(0, int(data), unit="%")) elif stat == 'freemem': self.property_set("free_memory", Sample(0, int(data), unit="bytes")) elif stat == 'usedmem': self.property_set("used_memory", Sample(0, int(data), unit="bytes")) elif stat == 'totalmem': self.property_set("total_memory", Sample(0, int(data), unit="bytes")) except Exception, e: self.__tracer.error("Unable to update stat: %s", str(e)) digitime.sleep(SettingsBase.get_setting(self, "update_rate"))
def start(self): self._logger.info('Start') while 1: interface = SettingsBase.get_setting(self, 'interface') if self.__stopevent.isSet(): self.__stopevent.clear() break if on_digi_board() and (not SettingsBase.get_setting( self, "no_digicli")): current_ip_address = self._get_ip_address_with_digicli() else: current_ip_address = self._get_ip_address_with_socket() if current_ip_address: # we got a valid address if current_ip_address != self._published_ip_address: # address has changed => update it self._logger.debug('Got new IP address for interface: %s' % interface) if self._update_dtdns(): self._published_ip_address = current_ip_address else: self._logger.debug('IP address unchanged') # wait and check for new address change digitime.sleep( SettingsBase.get_setting(self, 'address_update_rate')) else: self._logger.debug('No valid IP address for interface: %s' % interface) # wait and check for new address availability digitime.sleep( SettingsBase.get_setting(self, 'check_for_valid_address_rate')) self._logger.info('Terminating') return True
def run(self): while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break try: device_stats = query_state("device_stats") for stat in ['uptime', 'cpu', 'freemem', 'usedmem', 'totalmem']: for item in device_stats: data = item.find(stat) if data != None: data = data.text break else: continue if stat == 'uptime': self.property_set("uptime", Sample(0, int(float(data)), unit="sec")) elif stat == 'cpu': self.property_set("cpu_utilization", Sample(0, int(data), unit="%")) elif stat == 'freemem': self.property_set("free_memory", Sample(0, int(data), unit="bytes")) elif stat == 'usedmem': self.property_set("used_memory", Sample(0, int(data), unit="bytes")) elif stat == 'totalmem': self.property_set("total_memory", Sample(0, int(data), unit="bytes")) except Exception, e: self.__tracer.error("Unable to update stat: %s", str(e)) digitime.sleep(SettingsBase.get_setting(self,"update_rate"))
def run(self): state = STATE_NOTCONNECTED sd = None last_write = 0 while not self.__stopevent.isSet(): if state == STATE_NOTCONNECTED: server = SettingsBase.get_setting(self, "server") port = SettingsBase.get_setting(self, "port") sd = socket(AF_INET, SOCK_STREAM) try: sd.connect((server, port)) except Exception, e: self.__tracer.error("error connecting to %s:%d: %s", \ server, port, str(e)) digitime.sleep(RECONNECT_DELAY) continue state = STATE_CONNECTED interval = SettingsBase.get_setting(self, "interval") if state == STATE_CONNECTED \ and digitime.real_clock() > last_write + interval: sio = StringIO() self._write_channels(sio) try: sd.sendall(sio.getvalue()) last_write = digitime.real_clock() except: try: sd.close() except: pass state = STATE_NOTCONNECTED continue del (sio) digitime.sleep(min(SHUTDOWN_WAIT, interval))
def run(self): # Set the value of the channels with the configured settings full_string = (SettingsBase.get_setting(self, "prefix_init") + SettingsBase.get_setting(self, "suffix_init")) self.property_set("prefix_string", Sample(0, SettingsBase.get_setting (self,"prefix_init"))) self.property_set("suffix_string", Sample(0, SettingsBase.get_setting (self,"suffix_init"))) self.property_set("xtended_string", Sample(0, full_string)) while 1: if self.__stopevent.isSet(): self.__stopevent.clear() break # increment counter property: full_string = (self.property_get("prefix_string").value + self.property_get("suffix_string").value) self.property_set("xtended_string", Sample(0, full_string)) digitime.sleep(SettingsBase.get_setting(self,"update_rate"))
def open_socket(self): if self.__sock is not None: del self.__sock gc.collect() try: host = SettingsBase.get_setting(self, 'host') self._my_tracer.debug("See Host %s", host) host = eval(host) if len(host) < 2: raise 'Host needs to be tuple like ("127.0.0.1", 502)' # open our Modbus/TCP socket self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) self.__sock.settimeout( 20.0) self.__sock.connect(host) except socket.error: self._my_tracer.warning('Socket connect failed! Loop up and try socket again') traceback.print_exc() self.__sock = None except: traceback.print_exc() self.__sock = None if self.__sock is None: self._my_tracer.debug("Open Socket Failed, sleep 60 seconds") gc.collect() digitime.sleep( 60) return False self._my_tracer.debug("Open Socket Succeeded") return True
print "done." # close all outputs # At this point, we shouldn't have any more messages... print "Core: Stopping tracing_manager...", self.get_service('tracing_manager').stop() print "done." other_threads = _get_other_threads() count_sleeps = 0 while other_threads: if count_sleeps % 10 == 0: print ('Core: Threads still running (%s).' '\nWaiting for them ' 'to terminate... ') % (str(other_threads)) digitime.sleep(1) count_sleeps += 1 other_threads = _get_other_threads() print "Core: All threads stopped." # STUB: add sleep code if hasattr(self, '__sleep_req') and self.__sleep_req: print "Core: sleeping not implemented" print "\t(%d seconds requested)" % self.__sleep_req def wait_for_shutdown(self, timeout=None): """ Blocks the current thread for optional `timeout` seconds while waiting for a shutdown request. If `timeout` is not given, this call will block indefinitely until another thread
def run(self): """\ The Run method. """ # Create a shorthand list of our stored clients, along with any # stored messages we want to send to each client. client_message_list = [] for client in self.client_list: e = dict(name = client.name(), client = client, message_list = []) client_message_list.append(e) wait_time = SHUTDOWN_WAIT while not self.__stopevent.isSet(): try: #self.__tracer.info("ShortMessaging: Before sleeping of %d seconds", \ # wait_time) digitime.sleep(wait_time) #self.__tracer.info("ShortMessaging: After sleeping of %d seconds", \ # wait_time) current_time = digitime.time() # Walk through the queued up channels that have updates # waiting to be sent. #self.__tracer.info("ShortMessaging: Len of Watched List: %d", \ # len(self.__channels_being_watched)) #for entry in self.__channels_being_watched: # for filter in entry['filters']: # self.__print_statistics(entry['channel'], filter) #self.__tracer. "ShortMessaging: Len of Coalesce List: %d", \ # len(self.__coalesce_list)) #for entry in self.__coalesce_list: # self.__print_statistics(entry['channel'], entry['filter']) for entry in copy.copy(self.__coalesce_list): filter = entry['filter'] messages = entry['messages'] interval = filter['interval'] * 60 last = filter['last_sent'] # See if the time is up, and that we need to send # a new update. if (last + interval) < current_time: self.__tracer.info("Past Time, Should Send!") for message in messages: # Find the correct client entry. for client in client_message_list: if message['client'] == client['name']: break else: self.__tracer.warning("Run: Unable to find " \ "Client in Client List") continue # Add message to the list of messages we should # send to this client. client['message_list'].append(message['message']) # Bump our filter's total sent value. filter['total_sent'] += 1 # Bump our filter's last sent value to the current time filter['last_sent'] = current_time # Finally, remove entry from our list. self.__coalesce_list.remove(entry) # Walk each client in our message list cache for client in client_message_list: # Check to see if the client has any data that needs # to be sent. if len(client['message_list']) > 0: ret = client['client'].send_message(client['message_list']) if ret == False: self.__tracer.error("Unable to send message!") client['message_list'] = [] except Exception, e: self.__tracer.error("exception while uploading: %s", str(e))
def run(self): """\ The Run method. """ # Create a shorthand list of our stored clients, along with any # stored messages we want to send to each client. client_message_list = [] for client in self.client_list: e = dict(name=client.name(), client=client, message_list=[]) client_message_list.append(e) wait_time = SHUTDOWN_WAIT while not self.__stopevent.isSet(): try: #self.__tracer.info("ShortMessaging: Before sleeping of %d seconds", \ # wait_time) digitime.sleep(wait_time) #self.__tracer.info("ShortMessaging: After sleeping of %d seconds", \ # wait_time) current_time = digitime.time() # Walk through the queued up channels that have updates # waiting to be sent. #self.__tracer.info("ShortMessaging: Len of Watched List: %d", \ # len(self.__channels_being_watched)) #for entry in self.__channels_being_watched: # for filter in entry['filters']: # self.__print_statistics(entry['channel'], filter) #self.__tracer. "ShortMessaging: Len of Coalesce List: %d", \ # len(self.__coalesce_list)) #for entry in self.__coalesce_list: # self.__print_statistics(entry['channel'], entry['filter']) for entry in copy.copy(self.__coalesce_list): filter = entry['filter'] messages = entry['messages'] interval = filter['interval'] * 60 last = filter['last_sent'] # See if the time is up, and that we need to send # a new update. if (last + interval) < current_time: self.__tracer.info("Past Time, Should Send!") for message in messages: # Find the correct client entry. for client in client_message_list: if message['client'] == client['name']: break else: self.__tracer.warning("Run: Unable to find " \ "Client in Client List") continue # Add message to the list of messages we should # send to this client. client['message_list'].append(message['message']) # Bump our filter's total sent value. filter['total_sent'] += 1 # Bump our filter's last sent value to the current time filter['last_sent'] = current_time # Finally, remove entry from our list. self.__coalesce_list.remove(entry) # Walk each client in our message list cache for client in client_message_list: # Check to see if the client has any data that needs # to be sent. if len(client['message_list']) > 0: ret = client['client'].send_message( client['message_list']) if ret == False: self.__tracer.error("Unable to send message!") client['message_list'] = [] except Exception, e: self.__tracer.error("exception while uploading: %s", str(e))
def run(self): # validate control channel run_chan = SettingsBase.get_setting(self, 'upload_control') if not self._validate_channel(run_chan): TRACER.error('Couldn\'t validate channel setting... dying.') self._core.request_shutdown() return # Subscribe to a named channel to force a snap-shot upload x = SettingsBase.get_setting(self, 'trigger_snapshot') if x is not None and len(x) > 0: # these are set in our self.__init__ # chm = core_services.get_service("channel_manager") # self.__cp = chm.channel_publisher_get() self.__cp.subscribe(x, self._trigger_snapshot) start_time = digitime.time() upload_now = SettingsBase.get_setting(self, "initial_upload") interval = SettingsBase.get_setting(self, "interval") snapshot_interval = SettingsBase.get_setting(self, 'snapshot_interval') # track last upload signal (this is separate from last success/fail) last = digitime.time() last_snapshot = digitime.time() while not self.__stopevent.isSet(): try: # spin/sleep until we get enabled self.__enabled.wait(MAX_SLEEP) if not self.__enabled.isSet(): continue # handle initial upload if upload_now > 0: diff = start_time + upload_now - digitime.time() if diff <= 0: upload_now = 0 self.__upload_data(force=True) else: # spin here digitime.sleep(min(MAX_SLEEP, diff)) continue if snapshot_interval > 0 and \ digitime.time() - last_snapshot >= snapshot_interval: last_snapshot = digitime.time() self.__upload_data(force=True) tts = MAX_SLEEP if interval > 0: now = digitime.time() time_passed = now - max(self._stats_file.last_success, self._stats_file.last_failure, last) tts = interval - time_passed if tts <= 0: self.__upload_data() last = now # hang out for a while self.__threshold_event.wait(min(MAX_SLEEP, tts)) if self.__threshold_event.isSet(): self.__upload_data() except Exception, e: self._tracer.error("exception in EDP upload thread: %s", str(e))
def reset(self): process_request('<rci_request><reboot /></rci_request>') # Give us some time to reboot. We should not return. while True: digitime.sleep(60)