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 start(self): self._tracer.calls("XBeeXBIB.start()") # init self._xbee_manager and self._extended_address # then register ourself with our Xbee manager XBeeBase.pre_start(self) # Create a callback specification for our device address, endpoint # Digi XBee profile and sample cluster id: self._xbee_manager.register_sample_listener(self, self._extended_address, self.sample_indication) # Configure node sleep behavior: sleep_ms = SettingsBase.get_setting(self, "sleep_ms") awake_time_ms = SettingsBase.get_setting(self, "awake_time_ms") # The original sample rate is used as the sleep rate: xbee_sleep_cfg = self._xbee_manager.get_sleep_block( self._extended_address, sleep=sleep_ms > 0, sleep_rate_ms=sleep_ms, awake_time_ms=awake_time_ms) self._xbee_manager.xbee_device_config_block_add(self, xbee_sleep_cfg) # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(self._extended_address) # Configure pins DIO0 .. DIO3 for digital input: for io_pin in ['D0', 'D1', 'D2', 'D3']: xbee_ddo_cfg.add_parameter(io_pin, 3) # Turn off LEDs: for led in LED_IO_MAP: xbee_ddo_cfg.add_parameter(LED_IO_MAP[led], 0) # Assert that all pin pull-ups are enabled: xbee_ddo_cfg.add_parameter('PR', 0x1fff) # Enable I/O line monitoring on pins DIO0 .. DIO3: xbee_ddo_cfg.add_parameter('IC', 0xf) # Register this configuration block with the XBee Device Manager: self._xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) # Handle channels subscribed to output their data to our led # properties: cm = self._core.get_service("channel_manager") cp = cm.channel_publisher_get() for i in range(1, 4): setting_name = "led%d_source" % i channel_name = SettingsBase.get_setting(self, setting_name) if channel_name is not None: cp.subscribe(channel_name, (lambda prop: lambda cn: self.update_property(prop, cn))( "led%d" % i)) # we've no more to config, indicate we're ready to configure. return XBeeBase.start(self)
def make_request(self): success = True self._tracer.debug("make_request") extended_address = SettingsBase.get_setting(self, "extended_address") try: sample = self.__xbee_manager.xbee_device_ddo_get_param(extended_address, '1S') self.__decode_sample(sample) self._tracer.debug("Successfully retrieved and decoded sample.") except TypeError: success = False self._tracer.error("Device driver does not match with connected hardware.") pass except: success = False self._tracer.warning("Xmission failure, will retry.") pass # Schedule another heart beat poll, but only if we aren't in sleep mode. will_sleep = SettingsBase.get_setting(self, "sleep") if will_sleep != True: self.__schedule_request() self.__reschedule_retry_watchdog() return success
def repeat(self): if self.started == False: time.sleep(60) interval = SettingsBase.get_setting(self, "interval") if self.__event_timer is not None: try: self.__xbee_manager.xbee_device_schedule_cancel( self.__event_timer) except: pass self.__event_timer = self.__xbee_manager.xbee_device_schedule_after( SettingsBase.get_setting(self, "interval"), self.repeat) try: self.__upload_data() self.connected = 0 except: self.connected += 1 print "error in sending from repeat function"
def running_indication(self): # request initial status here. self.__tracer.info("Running indication") extended_address = SettingsBase.get_setting(self, "extended_address") humidity_present = SettingsBase.get_setting(self, "humidity_present") # this is a flawed design - if the gateway has just rebooted, # and the Xbee sensor sleeps (which it should), then an actual # GET_DDO will be issued, which causes Dia to freeze here and # almost certainly throw exception and put the device off line. try: dd_value = self.__xbee_manager.xbee_device_ddo_get_param( extended_address, 'DD', use_cache=True) except: self.__tracer.warning('Using default DD') dd_value = 0x0003000E module_id, product_id = parse_dd(dd_value) self.__tracer.info('DD info (module_id, product_id) = ' + '(0x%04x, 0x%04x)"', module_id, product_id) if product_id == PROD_DIGI_XB_SENSOR_LTH or humidity_present == True: self.__tracer.info("Sensor is a '%s' adding humidity channel", product_name(product_id)) self.add_property( ChannelSourceDeviceProperty(name="humidity", type=float, initial=Sample(timestamp=0, value=0.0, unit="%"), perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP)) else: self.__tracer.info("Sensor is a '%s' no humidity capability.", product_name(product_id))
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 start(self): # If the use_default_httpserver setting is specified, # the presentation will start own http server on the specified port. isDefault = SettingsBase.get_setting(self, 'use_default_httpserver') if not globals().has_key('Callback'): isDefault = False if isDefault: self._cb_handle = Callback(self.cb) self.__tracer.info("using web page %s and" " using digiweb", self.get_page()) else: self._cb_handle = self.get_channels try: port = SettingsBase.get_setting(self, 'port') self.__tracer.info("using port %d and BaseHTTPServer", port) HTTPServer.__init__(self, ('', port), WebRequestHandler) except Exception: self.__tracer.debug(traceback.format_exc()) self.socket.close() # Only start a thread if the Python web-server is # used: threading.Thread.start(self)
def start(self): """ Starts the web presentation module. If the use_default_httpserver setting is specified it starts own http server on the specified port. """ isDefault = SettingsBase.get_setting(self, 'use_default_httpserver') if not globals().has_key('Callback'): isDefault = False if isDefault: self._cb_handle = Callback(self.cb) print "Web2 (%s): using web page %s" % (self.__name, self.get_page()) print "... using digiweb" else: self._cb_handle = self.get_channels try: port = SettingsBase.get_setting(self, 'port') print "Web Presentation (%s): using port %d" % (self.__name, port) print "... using BaseHTTPServer" HTTPServer.__init__(self, ('', port), WebRequestHandler) except Exception: traceback.print_exc() self.socket.close() # Only start a thread if the Python web-server is # used: threading.Thread.start(self)
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 send_to_cosm(self, channel_name, value): self.__tracer.debug("Reveived a new sample from channel: %s" % channel_name) cosm_host = SettingsBase.get_setting(self, "cosm_host") cosm_key = SettingsBase.get_setting(self, 'cosm_key') cosm_feed_id0 = SettingsBase.get_setting(self, 'cosm_feed_id0') cosm_datastream0 = SettingsBase.get_setting(self, 'cosm_datastream0') if type(value) == type(float()): cosm_value = str(value) elif type(value) == type(str()): cosm_value = value elif type(value) == type(int()): cosm_value = str(value) elif type(value) == type(tuple()): cosm_value = urllib.quote(str(value)) else: self.__tracer.error("Value type not handled: %s" % type(value)) return feed_uri = "v2/feeds/%s/datastreams/%s/datapoints.csv" % ( cosm_feed_id0, cosm_datastream0) if self.use_proxy: conn = httplib.HTTPConnection(host=self.proxy_host, port=self.proxy_port) cosm_update_url = "http://%s/%s" % (cosm_host, feed_uri) self.__tracer.info( "Calling COSM with URL %s over http proxy %s:%d" % (cosm_update_url, self.proxy_host, self.proxy_port)) else: conn = httplib.HTTPConnection(host=cosm_host) cosm_update_url = "/%s" % feed_uri self.__tracer.info("Calling COSM with URL: %s" % cosm_update_url) try: conn.putrequest('POST', url=cosm_update_url) conn.putheader('X-ApiKey', cosm_key) clen = len(cosm_value) conn.putheader('Content-Length', ` clen `) conn.endheaders() conn.send(cosm_value) response = conn.getresponse() errcode = response.status errmsg = response.reason headers = response.msg conn.close() if errcode != 200 and errcode != 201: self.__tracer.error("Request ERROR: %d %s" % (errcode, errmsg)) else: self.__tracer.info("Request result: %s" % errmsg) except Exception, msg: self.__tracer.error( 'Exception raised during request. Exception was: %s' % (msg))
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 start(self): """Start the device driver. Returns bool.""" print '%s: Starting Device' % self.__name ## Initialize the serial interface: # pyserial expects ports base 0, not 1 xport = SettingsBase.get_setting(self, "port") - 1 xbaud = SettingsBase.get_setting(self, "baudrate") xpar = self.__derive_parity(SettingsBase.get_setting(self, "parity")) xtimout = SettingsBase.get_setting(self, "timeout") if sys.platform.startswith('digi'): msg = '//com//%d' % xport else: # is PC msg = 'COM%d' % (xport+1) print '%s: Opening serial port %s as %d,8,%s,1' % \ (self.__name, msg, xbaud, xpar) Serial.__init__(self, port=xport, baudrate=xbaud, parity=xpar, timeout=xtimout) self.__sched = self.__core.get_service("scheduler") # Scheduling first request self.__schedule_poll_cycle(self.INITIAL_POLL_SEC) return True
def start(self): """Start the device driver. Returns bool.""" self.logger.info("========== Starting up ==========") self.apply_settings() # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: extended_address = SettingsBase.get_setting(self, "extended_address") # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(extended_address) # Call the XBeeSerial function to add the initial set up of our device. # This will set up the destination address of the devide, and also set # the default baud rate, parity, stop bits and flow control. XBeeSerial.initialize_xbee_serial(self, xbee_ddo_cfg) # Register this configuration block with the XBee Device Manager: self.__xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) # Indicate that we have no more configuration to add: self.__xbee_manager.xbee_device_configure(self) threading.Thread.start(self) return True
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 start(self): xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Get the extended address of the device: extended_address = SettingsBase.get_setting(self, "extended_address") self.__xbee_manager.xbee_device_register(self) ddo_block = self.__xbee_manager.get_ddo_block(extended_address) sleep_block = self.__xbee_manager.get_sleep_block(extended_address, sleep=True) self.__xbee_manager.xbee_device_config_block_add(self, ddo_block) self.__xbee_manager.xbee_device_config_block_add(self, sleep_block) self.__xbee_manager.register_serial_listener(self, extended_address, self.__read_callback) self.__xbee_manager.register_sample_listener(self, extended_address, self.__read_callback2) self.__xbee_manager.xbee_device_configure(self) return True
def run(self): while self.started_flag: msg = self.queue.get() if not self.started_flag: return host = SettingsBase.get_setting(self, 'server_address') port = SettingsBase.get_setting(self, 'port') frm = SettingsBase.get_setting(self, 'from_address') to = SettingsBase.get_setting(self, 'to_address') try: s = smtplib.SMTP(host, port) except Exception, e: self.__tracer.error("Failed to connect to SMTP server") self.__tracer.warning("If using a DNS name, " + \ "make sure the Digi device is configured" + \ " to use the correct DNS server") try: error_list = s.sendmail(frm, to, msg) except: self.__tracer.error("Failed to send messages, please double check server/port") else: for err in error_list: self.__tracer.error("Failed to send message to %s address", err) s.quit()
def start(self): """Start the device driver. Returns bool.""" RobustBase.start_pre(self) # copy the Modbus Unit ID (slave id) to our Veris H8036 object x = SettingsBase.get_setting(self, "unit_id") self._my_tracer.debug("Setting Modbus Unit-ID:%d ", x) self._H8036.set_ModbusAddress(x) # create the Dia channels x = SettingsBase.get_setting(self, "channels") self._my_tracer.debug("Setting H8036 Mode:%s ", x) self._H8036.enable_channels(x) nam_list = self._H8036.get_channel_name_list() for nam in nam_list: self._my_tracer.debug("Adding Channel:%s ", nam) self.add_property( ChannelSourceDeviceProperty(name=nam, type=float, initial=Sample(0, 0.0, 'not init'), perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP)) RobustBase.start_post(self) return True
def start(self): """Start the device driver. Returns bool.""" ECM1240_Xbee.start(self) if self._import_settings(): self.apply_settings() logger_id = SettingsBase.get_setting(self, 'sunspec_lid') if (logger_id is None) or (logger_id.lower == 'none'): self._ecm._lid = None self._lid_ns = None #elif logger_id.lower is in ['mac', 'auto']: # self._ecm._lid = None # self._lid_ns = 'mac' else: self._ecm._lid = logger_id self._lid_ns = 'mac' format = SettingsBase.get_setting(self, 'sunspec_format').lower() if format in ECM1240_SunSpec.XML_FORM_LIST: self._ecm._xml_form = format self.__tracer.debug('%s: Selecting XML format "%s".', self.__showname, format) else: self.__tracer.error('%s: Unknown XML format "%s".', self.__showname, format) self._ecm._single_channel = SettingsBase.get_setting(self, 'single_channel') if self._ecm._single_channel: self.__tracer.debug('%s: Forcing Single Channel Mode', self.__showname) return True
def run(self): """run when our device driver thread is started""" self.sd = None '''/ import serial self.sd = serial.Serial( 0, #port number baudrate=115200, #baudrate bytesize=serial.EIGHTBITS, #number of databits parity=serial.PARITY_NONE, #enable parity checking stopbits=serial.STOPBITS_ONE, #number of stopbits timeout=3, #set a timeout value xonxoff=0, #enable software flow control rtscts=0, #enable RTS/CTS flow control ) ''' try: fd = None fd = open(path + 'id_secret_token.txt', 'r+') id = fd.readline() secret = fd.readline() token = fd.readline() fd.close() self.hvconn = HealthVaultConn(path, id, secret, token) except: traceback.print_exc() if fd != None: fd.close() self.hvconn = None ip = SettingsBase.get_setting(self, "server_ip") port = int(SettingsBase.get_setting(self, "server_port")) server = 'wsgiref' run_itty(server, ip, port)
def pre_start(self): """\ Do initial base class set up required before start, such as initialize self._xbee_manager and self._extended_address """ if self._xbee_manager is None: # then initialize things self._tracer.calls("XBeeBase.pre_start()") # Fetch the XBee Manager name from the Settings Manager: dm = self._core.get_service("device_driver_manager") self._xbee_manager = dm.instance_get( SettingsBase.get_setting(self, "xbee_device_manager")) # Register ourselves with the XBee Device Manager instance: self._xbee_manager.xbee_device_register(self) # Get the extended address of the device: self._extended_address = SettingsBase.get_setting(self, "extended_address") # Create a callback specification that calls back this driver when # our device has left the configuring state and has transitioned # to the running state: xbdm_running_event_spec = XBeeDeviceManagerRunningEventSpec() xbdm_running_event_spec.cb_set(self.running_indication) self._xbee_manager.xbee_device_event_spec_add(self, xbdm_running_event_spec) # else do nothing return
def __send_to_idigi(self, data): """ Sends data to iDigi Keyword arguments: data - the XML string to send """ filename = SettingsBase.get_setting(self, "filename") filename_format = SettingsBase.get_setting(self, "filename_format") filename = filename_format % (filename, self.__current_file_number) collection = SettingsBase.get_setting(self, "collection") secure = SettingsBase.get_setting(self, "secure") print "idigi_upload: Uploading %s to iDigi" % filename success, err, errmsg = idigi_data.send_idigi_data(data, filename, collection, secure) if not success: # if successful, delete upload list else try again next time print "idigi_db: Uploading ERROR %s (%s)" % (err,errmsg) self.__current_file_number += 1 max_files = SettingsBase.get_setting(self, "file_count") if self.__current_file_number >= max_files + 1: self.__current_file_number = 1 return success
def start(self): """Start the device driver. Returns bool.""" cm = self.__core.get_service("channel_manager") cp = cm.channel_publisher_get() cdb = cm.channel_database_get() left_channel_name = SettingsBase.get_setting(self, LEFT_VOLUME_CHANNEL) left_channel = cdb.channel_get(left_channel_name) right_channel_name = SettingsBase.get_setting(self, RIGHT_VOLUME_CHANNEL) right_channel = cdb.channel_get(right_channel_name) # Determine initial state: if left_channel.get().value >= right_channel.get().value: print "INIT LEFT: volume is %f" % (left_channel.get().value) self.__state = STATE_PUMP_OUT_LEFT self.property_set("left_pump_on", Sample(0, Boolean(True, STYLE_ONOFF))) else: print "INIT RIGHT: volume is %f" % (right_channel.get().value) self.__state = STATE_PUMP_OUT_RIGHT self.property_set("right_pump_on", Sample(0, Boolean(True, STYLE_ONOFF))) # Perform channel subscriptions: cp.subscribe(left_channel_name, lambda chan: self.tank_volume_update(chan, LEFT_VOLUME_CHANNEL)) cp.subscribe(right_channel_name, lambda chan: self.tank_volume_update(chan, RIGHT_VOLUME_CHANNEL)) return True
def run(self): """Worker thread for the TCPCSV client.""" state = STATE_NOTCONNECTED sd = None 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: print "TCPCSV(%s): error connecting to %s:%d: %s" % \ (self.__name, server, port, str(e)) time.sleep(RECONNECT_DELAY) continue state = STATE_CONNECTED if state == STATE_CONNECTED: sio = StringIO() self._write_channels(sio) try: sd.sendall(sio.getvalue()) except: try: sd.close() except: pass state = STATE_NOTCONNECTED continue del(sio) time.sleep(SettingsBase.get_setting(self, "interval"))
def receive(self, channel): """ Called whenever there is a new sample Keyword arguments: channel -- the channel with the new sample """ # we always cache if SettingsBase.get_setting(self, "compact_xml"): sam = self.__make_compact_xml(channel.name(),channel.get()) else: sam = self.__make_xml(channel.name(),channel.get()) self.__cache.append(sam) self.__sample_count += 1 print '%s:%d cache:%s' % (self.__name, self.__sample_count, sam) # If we have exceeded the sample threshold, notify the thread # responsible for pushing up data if self.__sample_count >= SettingsBase.get_setting(self, "sample_threshold"): # print "idigi_db: Reached threshold of %i, setting event flag" % sample_threshold self.__threshold_event.set() return
def start(self): """Start the device driver. Returns bool.""" cm = self.__core.get_service("channel_manager") cp = cm.channel_publisher_get() # cdb = cm.channel_database_get() # get the totalizer source, fault is bad/missing x = SettingsBase.get_setting(self, self.DIGITAL_SOURCE) try: cp.subscribe( x, self.prop_new_total ) bTimeSource = True print '%s: digital source channel is %s' % (self.show_name, x) except: traceback.print_exc() print '%s: no %s Channel (is bad!)' % (self.show_name,x) # return False # see if we want the delta channel try: x = eval( SettingsBase.get_setting(self, self.LATCH_OUT)) print '%s: latch channel is %s' % (self.show_name,x) self.latch_out = x if self.latch_out: # then create them self.add_property( ChannelSourceDeviceProperty( name='latch', type=bool, initial=Sample(0, False, 'bool' ), perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP) ) except: traceback.print_exc() print '%s: latch channel failed' % self.show_name # see if we want the hourly channel # try: # x = eval( SettingsBase.get_setting(self, self.HOURLY_OUT)) # print '%s: hourly channel is %s' % (self.show_name,x) # if x: # then create the channels # self.hourly = [-1,0] # self.add_property( # ChannelSourceDeviceProperty( # name='hourly_last', type=int, # initial=Sample(0, -1, '' ), # perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP) # ) #except: # traceback.print_exc() # print '%s: hourly channel failed' % self.show_name # Setting( name=self., type=str, required=False, # Setting( name=self.DAILY_OUT, type=str, required=False, return True
def run(self): """run when our device driver thread is started""" ip = SettingsBase.get_setting(self, "server_ip") port = int(SettingsBase.get_setting(self, "server_port")) server = 'wsgiref' run_itty(server, ip, port)
def create_filter_channel(self, source_channel, filter_channel): """\ Required override of the base channel's call of the same name. This allows us create/build a custom class to control the filter. Keyword arguments: source_channel -- the channel we are shadowing filter_channel -- the shadow/filter channel """ alarm_type_str = SettingsBase.get_setting(self, "alarm_type") threshold = SettingsBase.get_setting(self, "threshold") hysteresis = SettingsBase.get_setting(self, "hysteresis") readings = SettingsBase.get_setting(self, "readings") continuous = SettingsBase.get_setting(self, "continuous") if alarm_type_str == "High": alarm_type = ThresholdAlarmWithHysteresisFactory.HIGH elif alarm_type_str == "Low": alarm_type = ThresholdAlarmWithHysteresisFactory.LOW else: raise ValueError, "Alarm Type is not correct. Must be 'High' or 'Low'" return ThresholdAlarmWithHysteresis(self._name, self._core, source_channel, filter_channel, alarm_type, threshold, hysteresis, readings, continuous)
def pre_start(self): """\ Do initial base class set up required before start, such as initialize self._xbee_manager and self._extended_address """ if self._xbee_manager is None: # then initialize things self._tracer.calls("XBeeBase.pre_start()") # Fetch the XBee Manager name from the Settings Manager: dm = self._core.get_service("device_driver_manager") self._xbee_manager = dm.instance_get( SettingsBase.get_setting(self, "xbee_device_manager")) # Register ourselves with the XBee Device Manager instance: self._xbee_manager.xbee_device_register(self) # Get the extended address of the device: self._extended_address = SettingsBase.get_setting(self, "extended_address") # Create a callback specification that calls back this driver when # our device has left the configuring state and has transitioned # to the running state: xbdm_running_event_spec = XBeeDeviceManagerRunningEventSpec() xbdm_running_event_spec.cb_set(self.running_indication) self._xbee_manager.xbee_device_event_spec_add(self, xbdm_running_event_spec) # else do nothing return
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 time.sleep(1.0)
def apply_settings(self): """If settings are changed this is the final step before the settings are available to use""" SettingsBase.merge_settings(self) accepted, rejected, not_found = SettingsBase.verify_settings(self) if len(rejected) or len(not_found): self.logger.error("Settings rejected/not found: %s %s" % (rejected, not_found)) SettingsBase.commit_settings(self, accepted) # other parameter self.gateway_v1_backward_compatibility = SettingsBase.get_setting( self, 'gateway_v1_backward_compatibility') self.destinations = SettingsBase.get_setting(self, 'destinations') update_logging_level(self.logger, SettingsBase.get_setting(self, 'log_level')) # check if xbeerawout_channel must be changed if 'xbeerawout_interface' in accepted: # reinitialization will be done at first message send self.xbeerawout_channel = None return (accepted, rejected, not_found)
def start(self): # If the use_default_httpserver setting is specified, # the presentation will start own http server on the specified port. isDefault = SettingsBase.get_setting(self, 'use_default_httpserver') if not globals().has_key('Callback'): isDefault = False if isDefault: self._cb_handle = Callback(self.cb) self.__tracer.info("using web page %s and" " using digiweb", self.get_page()) else: self._cb_handle = self.get_channels try: port = SettingsBase.get_setting(self, 'port') self.__tracer.info("using port %d and BaseHTTPServer", port) HTTPServer.__init__(self, ('', port), WebRequestHandler) except Exception: self.__tracer.debug(traceback.format_exc()) self.socket.close() # Only start a thread if the Python web-server is # used: threading.Thread.start(self)
def run(self): while self.started_flag: msg = self.queue.get() if not self.started_flag: return host = SettingsBase.get_setting(self, 'server_address') port = SettingsBase.get_setting(self, 'port') frm = SettingsBase.get_setting(self, 'from_address') to = SettingsBase.get_setting(self, 'to_address') try: s = smtplib.SMTP(host, port) except Exception, e: self.__tracer.error("Failed to connect to SMTP server") self.__tracer.warning("If using a DNS name, " + \ "make sure the Digi device is configured" + \ " to use the correct DNS server") continue try: error_list = s.sendmail(frm, to, msg) except: self.__tracer.error( "Failed to send messages, please double check server/port") else: for err in error_list: self.__tracer.error("Failed to send message to %s address", err) s.quit()
def start(self): """Start the device driver. Returns bool.""" self.__tracer.info("Starting device") # force desired fixed parameters into our base/parent devices RobustXSerial.start_pre(self) # match our private tracer to Robust_Base's family one self.__tracer.level = self._tracer.level ## Remove the statistic channels if NOT desired # why add, then remove? Otherwise they don't exist at # start-up for subscription by other devices/presentations if not SettingsBase.get_setting(self, "add_statistics"): self.__tracer.info("Statistic Channels are disabled.") self.remove_list_of_properties( ["co2_stats", "hum_stats", "tmp_stats"]) self.__co2_stats = None self.__hum_stats = None self.__tmp_stats = None ## Force a default IA Modbus config if none # 'enabling' really only enables this config check if SettingsBase.get_setting(self, "enable_modbus"): try: if rci_modbus.rci_test_for_ia_table(): self.__tracer.info("Detected existing Modbus IA Config.") else: if rci_modbus.rci_create_ia_table_mbdia(): self.__tracer.info("Created new Modbus IA Config.") else: self.__tracer.error("Modbus IA Config creation FAILED.") except: self.__tracer.debug(traceback.format_exc()) self.__tracer.error('Modbus IA Config creation FAILED!') self.__three_command = SettingsBase.get_setting(self, "three_commands") # Create a DDO configuration block for this device: xbee_ddo_cfg = self.get_ddo_block() # enable/disable the LED statistics channels if SettingsBase.get_setting(self, "disable_led"): # disable by setting DIO-10 (p0) to 5/dig-out high xbee_ddo_cfg.add_parameter('P0', 5) else: # enable by setting DIO-10 (p0) to 1/RSSI/PWM xbee_ddo_cfg.add_parameter('P0', 1) # Register configuration blocks with the XBee Device Manager: self.get_xbee_manager().xbee_device_config_block_add(self, xbee_ddo_cfg) RobustXSerial.start_post(self) # force garbage collection in case we deleted big things gc.collect() return True
def __make_xml(self, channel_name, sample, type_info): ''' Version 1.1 xml (first versioned version, can be parsed by Device Cloud's initial "compact" version parser) ''' upload_type = SettingsBase.get_setting(self, 'upload_type') real = not SettingsBase.get_setting(self, 'legacy_time_format') if upload_type: frame = '<sample name="%s" value="%s" unit="%s" type="%s" '\ 'timestamp="%s" />' args = [_escape_entities(y) for y in \ [str(x) for x in (channel_name, sample.value, sample.unit, _type_str(type_info), iso_date(sample.timestamp, real_iso=real))]] else: frame = '<sample name="%s" value="%s" unit="%s" timestamp="%s" />' args = [_escape_entities(y) for y in \ [str(x) for x in (channel_name, sample.value, sample.unit, iso_date(sample.timestamp, real_iso=real))]] return frame % tuple(args)
def start(self): # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: extended_address = SettingsBase.get_setting(self, "extended_address") #register a callback for when the config is done xb_rdy_state_spec = XBeeDeviceManagerRunningEventSpec() xb_rdy_state_spec.cb_set(self._config_done_cb) self.__xbee_manager.xbee_device_event_spec_add(self, xb_rdy_state_spec) # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(extended_address) # Call the XBeeSerial function to add the initial set up of our device. # This will set up the destination address of the devidce, and also set # the default baud rate, parity, stop bits and flow control. XBeeSerial.initialize_xbee_serial(self, xbee_ddo_cfg) # Register this configuration block with the XBee Device Manager: self.__xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) # Indicate that we have no more configuration to add: self.__xbee_manager.xbee_device_configure(self) return True
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 make_request(self): success = True self._tracer.debug("make_request") extended_address = SettingsBase.get_setting(self, "extended_address") try: sample = self.__xbee_manager.xbee_device_ddo_get_param(extended_address, '1S') self.__decode_sample(sample) self._tracer.debug("Successfully retrieved and decoded sample.") except TypeError: success = False self._tracer.error("Device driver does not match with connected hardware.") pass except: success = False self._tracer.warning("Xmission failure, will retry.") pass # Schedule another heart beat poll, but only if we aren't in sleep mode. will_sleep = SettingsBase.get_setting(self, "sleep") if will_sleep != True: self.__schedule_request() self.__reschedule_retry_watchdog() return success
def start_post(self): self._tracer.debug("RobustXBee:Start_Post") hb = SettingsBase.get_setting(self, "heart_beat_sec") if (hb is not None) and (hb > 0): # then enable the periodic intake of data productions self.__xbee_manager.register_sample_listener(self, self.get_extended_address(), self._heart_beat_indication) hb = SettingsBase.get_setting(self, "heart_beat_io") if (hb is not None) and (len(hb) > 0): # then set a dummy IO to input, but only if HeartBeat active cfg = self.get_ddo_block() cfg.add_parameter(hb, 3) self.get_xbee_manager().xbee_device_config_block_add( self, cfg) else: # no heart_beat try: # remove the availability channel self.remove_one_property(self.RXBEE_DEF_AVAIL_CHAN) # remove the online channel self.remove_one_property(self.HB_STATUS_CHAN) except: pass # Indicate that we have no more configuration to add: self.get_xbee_manager().xbee_device_configure(self) return RobustBase.start_post(self)
def start_pre(self): """\ Start the device driver. """ self._tracer.debug("RobustXBee:Start_Pre") # suppress the Robust_Device start of polling until XBee config is done self._start_polling = False RobustBase.start_pre(self) # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.get_core().get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: self.__extended_address = SettingsBase.get_setting(self, "extended_address") # Create a callback to tell this driver when our device has left the # configuring state, transitioning to the running state x = XBeeDeviceManagerRunningEventSpec() x.cb_set(self.running_indication) self.__xbee_manager.xbee_device_event_spec_add(self, x) self.initialize_robust_xbee() return True
def start(self): """Start the device driver. Returns bool.""" RobustXSerial.start_pre(self) # create the Dia channels chns = SettingsBase.get_setting(self, "enable_channels") self._ecm.set_enabled_channels(chns) self.__chn_enabled = chns nam_list = [] if chns & self.ENB_CHN_WATT_CH1: nam_list.append(self._ecm.get_chn_name_power(1)) nam_list.append(self._ecm.get_chn_name_energy(1)) if chns & self.ENB_CHN_WATT_CH2: nam_list.append(self._ecm.get_chn_name_power(2)) nam_list.append(self._ecm.get_chn_name_energy(2)) if chns & self.ENB_CHN_CURRENT_CH1: nam_list.append(self._ecm.get_chn_name_current(1)) if chns & self.ENB_CHN_CURRENT_CH2: nam_list.append(self._ecm.get_chn_name_current(2)) if chns & self.ENB_CHN_VOLTAGE: nam_list.append(self._ecm.get_chn_name_voltage()) if chns & self.ENB_CHN_WATT_AUX1: nam_list.append(self._ecm.get_chn_name_power(3)) nam_list.append(self._ecm.get_chn_name_energy(3)) if chns & self.ENB_CHN_WATT_AUX2: nam_list.append(self._ecm.get_chn_name_power(4)) nam_list.append(self._ecm.get_chn_name_energy(4)) if chns & self.ENB_CHN_WATT_AUX3: nam_list.append(self._ecm.get_chn_name_power(5)) nam_list.append(self._ecm.get_chn_name_energy(5)) if chns & self.ENB_CHN_WATT_AUX4: nam_list.append(self._ecm.get_chn_name_power(6)) nam_list.append(self._ecm.get_chn_name_energy(6)) if chns & self.ENB_CHN_WATT_AUX5: nam_list.append(self._ecm.get_chn_name_power(7)) nam_list.append(self._ecm.get_chn_name_energy(7)) #ENB_CHN_SERIAL_NO = 0x0020 #ENB_CHN_FLAGS = 0x0040 #ENB_CHN_UNIT_ID = 0x0080 #ENB_CHN_SECONDS = 0x0400 for nam in nam_list: self.__tracer.debug("Adding Channel:%s ", nam) self.add_property( ChannelSourceDeviceProperty(name=nam, type=float, initial=Sample(0, 0.0, 'not init'), perms_mask=DPROP_PERM_GET, options=DPROP_OPT_AUTOTIMESTAMP)) x = SettingsBase.get_setting(self, "ac_voltage_adjust") self._ecm.set_ac_voltage_adjust(x) if x != 1.0: self.__tracer.debug("Setting AC Voltage Adjust of %f", x) RobustXSerial.initialize_xbee_serial(self) RobustXSerial.start_post(self) return True
def get_power_factor(self): pf_setting = SettingsBase.get_setting(self, 'pf_adjustment') dev_prof = SettingsBase.get_setting(self, 'device_profile') if dev_prof is not None: return self.check_profiles(dev_prof) else: return pf_setting
def get_power_factor(self): pf_setting = SettingsBase.get_setting(self, 'pf_adjustment') dev_prof = SettingsBase.get_setting(self, 'device_profile') if dev_prof is not None: return self.check_profiles(dev_prof) else: return pf_setting
def start(self): """Start the device driver. Returns bool.""" # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: extended_address = SettingsBase.get_setting(self, "extended_address") # Create a callback specification for our device address, endpoint # Digi XBee profile and sample cluster id: xbdm_rx_event_spec = XBeeDeviceManagerRxEventSpec() xbdm_rx_event_spec.cb_set(self.sample_indication) xbdm_rx_event_spec.match_spec_set( (extended_address, 0xe8, 0xc105, 0x92), (True, True, True, True)) self.__xbee_manager.xbee_device_event_spec_add(self, xbdm_rx_event_spec) # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(extended_address) xbee_ddo_cfg.add_parameter("NI", "") # Get the gateway's extended address: gw_xbee_sh, gw_xbee_sl = gw_extended_address_tuple() # Set the destination for I/O samples to be the gateway: xbee_ddo_cfg.add_parameter('DH', gw_xbee_sh) xbee_ddo_cfg.add_parameter('DL', gw_xbee_sl) #gw_mac = #xbee_ddo_cfg.add_parameter('ID', gw_mac) # Configure pins DI1 & DI2 for analog input: for io_pin in [ 'D1', 'D2' ]: xbee_ddo_cfg.add_parameter(io_pin, 2) # Configure the IO Sample Rate: sample_rate = SettingsBase.get_setting(self, "sample_rate_ms") xbee_ddo_cfg.add_parameter('IR', sample_rate) # Register this configuration block with the XBee Device Manager: self.__xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) self.property_set("incl", Sample(0, value=Boolean(bool(1), style=STYLE_ONOFF))) self.property_set("excl", Sample(0, value=Boolean(bool(0), style=STYLE_ONOFF))) # Indicate that we have no more configuration to add: self.__xbee_manager.xbee_device_configure(self) return True
def apply_settings(self): # use parent's apply accepted, rejected, not_found = RobustXSerial.apply_settings(self) self.__co2_delta = SettingsBase.get_setting(self, "co2_delta") self.__hum_delta = SettingsBase.get_setting(self, "hum_delta") self.__tmp_delta = SettingsBase.get_setting(self, "tmp_delta") return accepted, rejected, not_found
def __upload_data(self): """ Builds XML string of the channel state and pushes to iDigi """ self._count += 1 xml = cStringIO.StringIO() # xml.write("<?xml version=\"1.0\"?>") compact_xml = SettingsBase.get_setting(self, "compact_xml") if compact_xml: xml.write("<idigi_data compact=\"True\">") else: xml.write("<idigi_data>") # print "idigi_db: Uploading to iDigi" cm = self.__core.get_service("channel_manager") cdb = cm.channel_database_get() channel_list = SettingsBase.get_setting(self, "channels") if len(channel_list) == 0: channel_list = cdb.channel_list() new_sample_count = 0 for channel_name in channel_list: try: channel = cdb.channel_get(channel_name) sample = channel.get() if sample.timestamp >= self.__last_upload_time: # print "Channel %s was updated since last push" % channel_name new_sample_count += 1 compact_xml = SettingsBase.get_setting(self, "compact_xml") if compact_xml: xml.write(self.__make_compact_xml(channel_name, sample)) else: xml.write(self.__make_xml(channel_name, sample)) # else: # print "Channel %s was not updated since last push" % channel_name except: # Failed to retrieve the data pass xml.write("</idigi_data>") if self._count > 300 and new_sample_count == 0: self.reset() if new_sample_count > 0: self.__last_upload_time = time.time() self._count = 0 self.__send_to_idigi(xml.getvalue()) xml.close()
def start(self): # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: extended_address = SettingsBase.get_setting(self, 'extended_address') # Create a callback specification for our device address, endpoint # Digi XBee profile and sample cluster id: self.__xbee_manager.register_sample_listener(self, extended_address, self.sample_indication) # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(extended_address) # Configure pins DI1 .. DI3 for analog input: for io_pin in ['D1', 'D2', 'D3']: xbee_ddo_cfg.add_parameter(io_pin, 2) # Get the extended address of the device: default_state = SettingsBase.get_setting(self, 'default_state') if default_state != 'same': # Configure pin DI4 for digital output, default state setting: self.prop_set_power_control(Sample(0, str(Boolean(default_state, STYLE_ONOFF)))) else: self.property_set('power_on', Sample(0, UNKNOWN_POWER_STATE)) # Configure the IO Sample Rate: sample_rate = SettingsBase.get_setting(self, 'sample_rate_ms') xbee_ddo_cfg.add_parameter('IR', sample_rate) # Handle subscribing the devices output to a named channel, # if configured to do so: power_on_source = SettingsBase.get_setting(self, 'power_on_source') if power_on_source is not None: cm = self.__core.get_service('channel_manager') cp = cm.channel_publisher_get() cp.subscribe(power_on_source, self.update_power_state) # Register this configuration block with the XBee Device Manager: self.__xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) # Indicate that we have no more configuration to add: self.__xbee_manager.xbee_device_configure(self) return True
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 apply_settings(self): """If settings are changed this is the final step before the settings are available to use""" self.logger.info("apply_settings") SettingsBase.merge_settings(self) accepted, rejected, not_found = SettingsBase.verify_settings(self) if len(rejected) or len(not_found): self.logger.error ("Settings rejected/not found: %s %s" % (rejected, not_found)) SettingsBase.commit_settings(self, accepted) # other parameter self.gateway_v1_backward_compatibility = SettingsBase.get_setting(self, 'gateway_v1_backward_compatibility') self.destinations = SettingsBase.get_setting(self, 'destinations') self.msg_size_on_7_bits = SettingsBase.get_setting(self, 'msg_size_on_7_bits') update_logging_level (self.logger, SettingsBase.get_setting(self, 'log_level')) #configuration of the modem handler self.m10_handler.SC_Set_Library_Default_Settings( desired_gateway=m10_sc_api.DESIRED_GATEWAY_VALUES[SettingsBase.get_setting(self, 'desired_gateway')], def_polled=m10_sc_api.SC_POLL_MODE_VALUES[SettingsBase.get_setting(self, 'def_polled')], def_ack_level=m10_sc_api.ACK_LEVEL_VALUES[SettingsBase.get_setting(self, 'def_ack_level')], def_rep_or_ind=transform_in_usable_OR(SettingsBase.get_setting(self, 'def_rep_or_ind')), def_msg_or_ind=transform_in_usable_OR(SettingsBase.get_setting(self, 'def_msg_or_ind')), def_priority=m10_sc_api.PRIORITY_LVL[SettingsBase.get_setting(self, 'def_priority')], def_msg_body_type=m10_sc_api.MSG_BODY_TYPE_VALUES[SettingsBase.get_setting(self, 'def_msg_body_type')], def_serv_type=m10_sc_api.REPORTS_SERVICE_TYPE_VALUES[SettingsBase.get_setting(self, 'def_serv_type')], gwy_search_mode=m10_sc_api.GWY_SEARCH_MODE_VALUES[SettingsBase.get_setting(self, 'gwy_search_mode')] ) if self.m10_handler.serial_is_open(): #we send the configuration to the modem self.m10_handler.SC_Write_to_modem_Library_Default_Settings() return (accepted, rejected, not_found)
def start(self): """\ Start the Short Messaging Presentation instance. Returns bool. """ cm = self.__core.get_service("channel_manager") cp = cm.channel_publisher_get() cdb = cm.channel_database_get() # Get our SMS Settings values. # # Because of the way DIA requires defining a list in its configuration # file, the get_setting() call below will first return this value in a # dictionary with the actual transports list stored under the key name # of 'instance_list'. SMS_list = SettingsBase.get_setting(self, "SMS") # Allocate an SMS Manager based on the user settings. if SMS_list != {}: tm = self.__allocate_transport_manager('SMS', SMS_list) # Add it to our existing dictionary of transport managers. self.__transport_managers = dict(self.__transport_managers.items() + \ tm.items()) # Get our Iridium Settings values. # # Because of the way DIA requires defining a list in its configuration # file, the get_setting() call below will first return this value in a # dictionary with the actual transports list stored under the key name # of 'instance_list'. iridium_list = SettingsBase.get_setting(self, "Iridium") # Allocate an Iridium Manager based on the user settings. if iridium_list != {}: tm = self.__allocate_transport_manager('Iridium', iridium_list) # Add it to our existing dictionary of transport managers. self.__transport_managers = dict(self.__transport_managers.items() + \ tm.items()) # Get our clients list. # # Because of the way DIA requires defining a list in its configuration # file, the get_setting() call below will first return this value in a # dictionary with the actual client list stored under the key name of # 'instance_list'. client_list = SettingsBase.get_setting(self, "clients") try: client_list = client_list['instance_list'] except Exception, e: self.__tracer.error("Unable to get Client list %s", str(e)) client_list = []
def start(self): self._tracer.calls("XBeeRPM.start()") # init self._xbee_manager and self._extended_address # register ourself with our Xbee manager # create the self.running_indication callback XBeeBase.pre_start(self) # Create a callback specification for our device address, endpoint # Digi XBee profile and sample cluster id: self._xbee_manager.register_sample_listener(self, self._extended_address, self.sample_indication) # Create a DDO configuration block for this device: xbee_ddo_cfg = XBeeConfigBlockDDO(self._extended_address) # Configure pins DI1 .. DI3 for analog input: for io_pin in ['D1', 'D2', 'D3']: xbee_ddo_cfg.add_parameter(io_pin, 2) # Get the extended address of the device: default_state = SettingsBase.get_setting(self, 'default_state') if default_state != 'same': # Configure pin DI4 for digital output, default state setting: self.prop_set_power_control( Sample(0, str(Boolean(default_state, STYLE_ONOFF)))) else: self.property_set('power_on', Sample(0, UNKNOWN_POWER_STATE)) # Configure the IO Sample Rate: sample_rate = SettingsBase.get_setting(self, 'sample_rate_ms') xbee_ddo_cfg.add_parameter('IR', sample_rate) # new method for mesh health monitoring self.set_data_update_rate_seconds(sample_rate / 1000) # Handle subscribing the devices output to a named channel, # if configured to do so: power_on_source = SettingsBase.get_setting(self, 'power_on_source') if power_on_source is not None: cm = self._core.get_service('channel_manager') cp = cm.channel_publisher_get() cp.subscribe(power_on_source, self.update_power_state) # Register this configuration block with the XBee Device Manager: self._xbee_manager.xbee_device_config_block_add(self, xbee_ddo_cfg) # we've no more to config, indicate we're ready to configure. return XBeeBase.start(self)
def receive(self, channel): ''' Store a sample from a given channel and possibly trigger upload. The channel argument is ignored (but is required by the notification mechanism). ''' if not self.__enabled.isSet(): TRACER.debug('self.__enabled.isSet is NOT set') return sam = channel.get() if not SettingsBase.get_setting(self, "upload_time_zero"): if sam.timestamp == 0: TRACER.debug('discard sample with null time') return # save the sample try: self.__entry_lock.acquire() self.__sample_count += 1 prev = self.__upload_queue.get(channel.name(), (channel.type(), list())) prev[1].append(sam) self.__upload_queue[channel.name()] = prev mem_samples = self._samples_in_queue() # sync to disk? if mem_samples * SAMPLE_SIZE > MAX_SIZE: TRACER.info('flushing samples to disk due to memory ' \ 'constraint') self._sync_to_disk() elif digitime.time() - self.__sample_sync > DISK_FLUSH: TRACER.info('flushing samples to disk due to time') self._sync_to_disk() finally: self.__entry_lock.release() sample_threshold = SettingsBase.get_setting(self, "sample_threshold") if sample_threshold > 0 and self.__sample_count >= sample_threshold: # It really doesn't matter that we set sample count to zero # here... self.__upload sets self.__sample_count back to zero. # We just don't want to repeatedly bang on the threshold event. try: self.__entry_lock.acquire() self.__sample_count = 0 finally: self.__entry_lock.release() self.__threshold_event.set() self._tracer.debug("Reached threshold of %i, setting event flag", sample_threshold)
def __init__(self, name, core_services): self.__name = name self.__core = core_services self.__stopevent = threading.Event() from core.tracing import get_tracer self.__tracer = get_tracer(name) self.use_proxy = None self.proxy_host = None self.proxy_port = None # Configuration Settings: settings_list = [ Setting(name="cosm_host", type=str, required=False, default_value="api.cosm.com"), Setting(name="cosm_key", type=str, required=True), Setting(name="cosm_feed_id0", type=str, required=True), Setting(name="channel0", type=str, required=True), Setting(name="cosm_datastream0", type=str, required=True), Setting(name="use_proxy", type=bool, required=False, default_value=False), Setting(name="proxy_host", type=str, required=False), Setting(name="proxy_port", type=int, required=False, default_value=3128), ] PresentationBase.__init__(self, name=name, settings_list=settings_list) self.use_proxy = SettingsBase.get_setting(self, "use_proxy") if self.use_proxy: self.proxy_host = SettingsBase.get_setting(self, "proxy_host") self.proxy_port = SettingsBase.get_setting(self, "proxy_port") if not self.proxy_host: self.__tracer.warning( "proxy_host configuration parameter not set. Will ignore use_proxy to false" ) self.use_proxy = False threading.Thread.__init__(self, name=name) threading.Thread.setDaemon(self, True) return
def _get_current_filename(self): ''' Return the current data filename. ''' f_prefix = SettingsBase.get_setting(self, 'filename') llen = SettingsBase.get_setting(self, 'file_count') try: rlen = len(str(llen - 1)) except Exception: rlen = 0 fstring = "%%0%s" % (rlen) return ''.join((f_prefix, fstring, "i.xml")) \ % self._stats_file.file_number
def start(self): """Start up the XBeeString object, and add our own XBee Device Manager rx callbacks""" # Fetch the XBee Manager name from the Settings Manager: xbee_manager_name = SettingsBase.get_setting(self, "xbee_device_manager") dm = self.__core.get_service("device_driver_manager") self.__xbee_manager = dm.instance_get(xbee_manager_name) # Register ourselves with the XBee Device Manager instance: self.__xbee_manager.xbee_device_register(self) # Get the extended address of the device: self.extended_address = SettingsBase.get_setting( self, "extended_address") # Create a callback specification for our device address, endpoint # Digi XBee profile and sample cluster id: xbdm_rx_event_spec = XBeeDeviceManagerRxEventSpec() xbdm_rx_event_spec.cb_set(self.receive_data) xbdm_rx_event_spec.match_spec_set( (self.extended_address, XBEE_ENDPOINT_RESPONSE, XB_PROFILE_DIGI, 0), (True, False, True, False)) self.__xbee_manager.xbee_device_event_spec_add(self, xbdm_rx_event_spec) # Create a callback specification that calls back this driver when # our device has left the configuring state and has transitioned # to the running state: xbdm_running_event_spec = XBeeDeviceManagerRunningEventSpec() xbdm_running_event_spec.cb_set(self.request_info) self.__xbee_manager.xbee_device_event_spec_add( self, xbdm_running_event_spec) # Indicate that we have no more configuration to add: self.__xbee_manager.xbee_device_configure(self) # Add a wrapper for the XBee manager's schedule_after, schedule_cancel # routines. Round up timeout to nearest second (ConnectPort's time # resolution), otherwise, ConnectPort will round down (possibly to 0). self.timeout = GPIO_TIMEOUT / 1000. self.schedule_after = \ lambda cb, timeout=self.timeout, *args: \ self.__xbee_manager.xbee_device_schedule_after( ceil(timeout), cb, *args) self.schedule_cancel = self.__xbee_manager.xbee_device_schedule_cancel return True
def cb(self, typer, path, headers, args): tmp = {} if typer == "POST" or typer == "post": tmp = cgi.parse_qs(args) args = tmp for key in args: args[key] = args[key][0] page_setting = SettingsBase.get_setting(self, 'page') if path != ('/' + page_setting): return None try: if args == None or args["controller"] == None or args[ "controller"] == "index": return (digiweb.TextHtml, raw_html) cm = self.__core.get_service( "channel_manager").channel_database_get() channel_list = cm.channel_list() channel_list.sort() table = dict() for entry in channel_list: if entry in SettingsBase.get_setting(self, 'exclude'): continue device, channel_name = entry.split('.') channel = cm.channel_get(entry) if not table.has_key(device): table[device] = list() try: sample = channel.get() table[device].append((channel_name, sample.value, channel)) except: table[device].append(( channel_name, "(N/A)", "", "", )) sorted_table = list() for key in table.keys(): sorted_table.append((key, table[key])) sorted_table.sort(key=lambda x: x[0]) py_code = getattr(pyhtml, args["controller"])(locals()) return (digiweb.TextHtml, py_code.getvalue()) except Exception, e: import traceback return (digiweb.TextHtml, traceback.format_exc())
def _enabled_trigger(self, channel): ''' Listener for upload_control. set_run should only be true for initialization call ''' name = SettingsBase.get_setting(self, 'upload_control') try: channel = self.__cdb.channel_get(name) except ChannelDoesNotExist: # this is ok... we will get set on the first channel event return if not (channel.perm_mask() & DPROP_PERM_GET): TRACER.error('\'upload_control\' setting points to a ' \ 'channel without get permissions. ' \ 'Uploading will never be enabled.') return value = bool(channel.get().value) if not self.__control_initialized: self.__control_initialized = True TRACER.info('Triggering on %s, uploading is currently %s.' % (name, ('disabled', 'enabled')[int(value)])) elif name != channel.name(): raise ValueError('Unknown channel %s registered to upload ' \ 'control listener! This is definitely a ' \ 'programming error!' % (channel.name())) if value and not self.__enabled.isSet(): self.__enabled.set() elif not value and self.__enabled.isSet(): self.__enabled.clear()
def run(self): port = SettingsBase.get_setting(self, "port") self.__tracer.info("starting server on port %d", port) if sys.version_info >= (2, 5): xmlrpc_server = SimpleXMLRPCServer( addr=('', port), requestHandler=CustomXMLRPCRequestHandler, logRequests=0, allow_none=True) else: xmlrpc_server = SimpleXMLRPCServer( addr=('', port), requestHandler=CustomXMLRPCRequestHandler, logRequests=0) xmlrpc_server.register_introspection_functions() xmlrpc_server.register_instance(XMLRPCAPI(self.__core)) try: # Poll the stop event flag at a minimum of each second: while not self.__stopevent.isSet(): rl, wl, xl = select([xmlrpc_server.socket], [], [], 1.0) if xmlrpc_server.socket in rl: xmlrpc_server.handle_request() except: self.__tracer.error("Exception occured during XMLRPC request:") self.__tracer.debug(traceback.format_exc())
def make_request(self): self._tracer.calls("make_request") try: packet_size = SettingsBase.get_setting(self, "packet_size") except: packet_size = 1 buf = "" for i in range(0, packet_size): d = random.randint(0, 255) buf += chr(d) try: self._loopback_attempts += 1 ret = self.write(buf) if ret == False: raise Exception, "write failed" self._loopback_data = buf self._loopback_total_bytes_sent += len(buf) self.property_set("attempts", Sample(0, self._loopback_attempts, "")) self.property_set("total_bytes_sent", Sample(0, self._loopback_total_bytes_sent, "")) except: # try again later: self._tracer.warning("Xmission failure, will retry.") self.__schedule_request() self.__reschedule_retry_watchdog()
def _do_low_memory(self): # see if the user requested a low_memory_threshold check try: low_memory_threshold = SettingsBase.get_setting( self, "low_memory_threshold") low_memory_check = True except: low_memory_check = False # if low_memory_check is set, get system info and then # compare to required minimum memory mark if (low_memory_check): try: freeMemory = self.get_free_memory() except Exception, e: # We expect to be able to get memory stats. The fact # we can't is troubling enough that we should probably # reboot. self.reset() # Should not get here. If we do, bail. assert False # only stroke if we meet the conditions for free memory if (freeMemory < low_memory_threshold): self.__tracer.warning("memory low") self.reset()
def __import_settings(self): '''Pre-Process the settings, connverting if required''' # enble the trace as configured # self.set_trace(SettingsBase.get_setting(self, "trace").lower()) # Parse out the sample rate string, set self.__rate to seconds self.__adjust_sample_rate_sec() # no import of 'manual_trigger' required # handle the bus id list id_list = SettingsBase.get_setting(self, "bus_id_list") if isinstance(id_list, types.StringType): # convert YML string to list id_list = eval(id_list) elif isinstance(id_list, types.IntType): # repair YML's conversion of '(1)' to be just 1 id_list = tuple(id_list) print 'id_list = %s' % str(id_list) # create the sensor list for id in id_list: self._tracer.debug('%s: add sensor id tag %d', self.showname, id) sen = MassaM300_Sensor(id) sen.set_mode_multidrop(True) self.__sensor_list.append(sen) return