def kafka_agent(config_path, **kwargs): ''' Function: Return KafkaAgent object with configuration information Args: Same with Class Args Returns: KafkaAgent object Note: None Created: SungonLee, 2017-10-20 Deleted: . ''' # get config information config = utils.load_config(config_path) services_topic_list = config.get('services_topic_list') kafka_broker_ip = config.get('kafka_broker_ip') kafka_broker_port = config.get('kafka_broker_port') kafka_producer_topic = config.get('kafka_producer_topic') kafka_consumer_topic = config.get('kafka_consumer_topic') if 'all' in services_topic_list: services_topic_list = [topics.DRIVER_TOPIC_BASE, topics.LOGGER_BASE, topics.ACTUATOR, topics.ANALYSIS_TOPIC_BASE] return KafkaAgent(services_topic_list, kafka_broker_ip, kafka_broker_port, kafka_producer_topic, kafka_consumer_topic, **kwargs)
def hello_agent(config_path, **kwargs): # home = os.path.expanduser(os.path.expandvars( # os.environ.get('VOLTTRON_HOME', '~/.volttron'))) # vip_address = 'ipc://@{}/run/vip.socket'.format(home) config = utils.load_config(config_path) def get_config(name, default=None): try: return kwargs.pop(name) except KeyError: return config.get(name, default) agentid = get_config('agentid') vip_identity = get_config('vip_identity') if not vip_identity: vip_identity = os.environ.get('AGENT_UUID') class Agent(BaseAgent): def __init__(self, **kwargs): super(Agent, self).__init__(vip_identity=vip_identity, **kwargs) @export() def sayHello(self, payload="'name': 'juniper'"): return "Hello, {them} from {me}".format(them=payload['name'], me=agentid) Agent.__name__ = 'HelloAgent' return Agent(**kwargs)
def __init__(self, **kwargs): ''' Initialize class from config file ''' super(ThermostatRelayAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.volttime = None self.task = 0 # points of interest for demo self.point_name_map = { 'tstat_mode' : "tmode", 'tstat_temp_sensor' : "temp", 'tstat_heat_sp' : 't_heat', 'tstat_cool_sp' : "t_cool", 'tstat_fan_mode' : 'fmode', 'tstat_hvac_state' : 'tstate' } self.units_map = { 'tstat_mode' : "state", 'tstat_temp_sensor' : "F", 'tstat_heat_sp' : 'F', 'tstat_cool_sp' : "F", 'tstat_fan_mode' : 'state', 'tstat_hvac_state' : 'state' }
def historian(config_path, **kwargs): """ This method is called by the :py:func:`influx.historian.main` to parse the passed config file or configuration dictionary object, validate the configuration entries, and create an instance of InfluxdbHistorian :param config_path: could be a path to a configuration file or can be a dictionary object :param kwargs: additional keyword arguments if any :return: an instance of :py:class:`InfluxdbHistorian` """ if isinstance(config_path, dict): config_dict = config_path else: config_dict = utils.load_config(config_path) connection = config_dict.pop('connection', {}) aggregations = config_dict.pop("aggregations", {}) # assert connection is not None # params = connection.get('params', None) # assert params is not None InfluxdbHistorian.__name__ = 'InfluxdbHistorian' utils.update_kwargs_with_config(kwargs, config_dict) _log.debug("In influx historian before calling class kwargs is {}".format( kwargs)) return InfluxdbHistorian(connection, aggregations, **kwargs)
def fncs_example(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: FncsExample :rtype: FncsExample """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using Agent defaults for starting configuration.") if not config.get("topic_mapping"): raise ValueError("Configuration must have a topic_mapping entry.") topic_mapping = config.get("topic_mapping") federate = config.get("federate_name") broker_location = config.get("broker_location", "tcp://localhost:5570") time_delta = config.get("time_delta", "1s") sim_length = config.get("sim_length", "60s") stop_agent_when_sim_complete = config.get("stop_agent_when_sim_complete", False) subscription_topic = config.get("subscription_topic", None) return FncsExample(topic_mapping=topic_mapping, federate_name=federate, broker_location=broker_location, time_delta=time_delta,subscription_topic=subscription_topic, sim_length=sim_length, stop_agent_when_sim_complete=stop_agent_when_sim_complete, **kwargs)
def __init__(self, config_path, **kwargs): super(PGnEAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.site = self.config.get('campus') self.building = self.config.get('building') self.out_temp_unit = self.config.get('out_temp_unit') self.out_temp_name = self.config.get('out_temp_name') self.power_unit = self.config.get('power_unit') self.power_name = self.config.get('power_name') self.aggregate_in_min = self.config.get('aggregate_in_min') self.aggregate_freq = str(self.aggregate_in_min) + 'Min' self.ts_name = self.config.get('ts_name') self.calc_mode = self.config.get('calculation_mode', 0) self.manual_set_adj_value = self.config.get('manual_set_adj_value', False) self.fix_adj_value = self.config.get('fix_adj_value', 1.26) self.tz = self.config.get('tz') self.local_tz = pytz.timezone(self.tz) self.one_day = timedelta(days=1) self.min_adj = 1 self.max_adj = 1.4 #Debug self.debug_folder = self.config.get('debug_folder') + '/' self.debug_folder = self.debug_folder.replace('//', '/') self.wbe_csv = self.config.get('wbe_file') # self.bday_us = CustomBusinessDay(calendar=USFederalHolidayCalendar())
def light_agent(config_path, **kwargs): """Parses the Electric Meter Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using defaults for starting configuration.") market_name = config.get('market_name') k= config.get('k', 0) qmax= float(config.get('Pmax', 0)) Pabsnom= float(config.get('Pabsnom', 0)) nonResponsive= config.get('nonResponsive', False) agent_name= config.get('agent_name') subscribing_topic= config.get('subscribing_topic', '') verbose_logging= config.get('verbose_logging', True) return LightAgent(market_name,agent_name,k,qmax,Pabsnom,nonResponsive,verbose_logging,subscribing_topic, **kwargs)
def __init__(self, config_path, **kwargs): super(SmartStrip, self).__init__(**kwargs) _log.debug("vip_identity: " + self.core.identity) self.config = utils.load_config(config_path) self._configGetPoints() self._configGetInitValues()
def __init__(self, **kwargs): ''' Initialize class from config file ''' super(CEA2045RelayAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.volttime = None self.mode_CEA2045_array = ['emergency','shed','normal'] # possible states of the appliance self.cea_rate = { 'Running Normal' : 2, 'Running Curtailed Grid' : 1, 'Idle Grid' : 0, 'Idle Normal': 0, 'SGD Error Condition':0, 'Running Heightened Grid':3 } self.device1_mode = {'cea2045state' : 'Idle Normal'} self.device2_mode = None self.task = 0 # points of interest for demo self.point_name_map = { 'cea2045state': 'cea2045state' } self.writable_points = {'cea2045state'}
def ahu_agent(config_path, **kwargs): """Parses the Electric Meter Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using defaults for starting configuration.") air_market_name = config.get('market_name1', 'air') electric_market_name = config.get('market_name2', 'electric') agent_name= config.get('agent_name') subscribing_topic= config.get('subscribing_topic') c0= config.get('c0') c1= config.get('c1') c2= config.get('c2') c3= config.get('c3') COP= config.get('COP') verbose_logging= config.get('verbose_logging', True) return AHUAgent(air_market_name,electric_market_name,agent_name,subscribing_topic,c0,c1,c2,c3,COP,verbose_logging, **kwargs)
def __init__(self, config_path, **kwargs): super(PublisherAgent2, self).__init__(**kwargs) self._config = load_config(config_path) self._src_file_handle = open(settings.source_file) header_line = self._src_file_handle.readline().strip() self._headers = header_line.split(',')
def __init__(self, config_path, **kwargs): config = utils.load_config(config_path) # We pass every optional parameter to the MQTT library functions so they # default to the same values that paho uses as defaults. self.mqtt_qos = config.get('mqtt_qos', 0) self.mqtt_retain = config.get('mqtt_retain', False) self.mqtt_hostname = config.get('mqtt_hostname', 'localhost') self.mqtt_port = config.get('mqtt_port', 1883) self.mqtt_client_id = config.get('mqtt_client_id', '') self.mqtt_keepalive = config.get('mqtt_keepalive', 60) self.mqtt_will = config.get('mqtt_will', None) self.mqtt_auth = config.get('mqtt_auth', None) self.mqtt_tls = config.get('mqtt_tls', None) protocol = config.get('mqtt_protocol', MQTTv311) if protocol == "MQTTv311": protocol = MQTTv311 elif protocol == "MQTTv31": protocol = MQTTv31 if protocol not in (MQTTv311, MQTTv31): raise ValueError("Unknown MQTT protocol: {}".format(protocol)) self.mqtt_protocol = protocol # will be available in both threads. self._last_error = 0 super(MQTTHistorian, self).__init__(**kwargs)
def historian(config_path, **kwargs): config = utils.load_config(config_path) class NullHistorian(BaseHistorian): '''This historian forwards data to another platform. ''' @Core.receiver("onstart") def starting(self, sender, **kwargs): _log.debug('Null historian started.') def publish_to_historian(self, to_publish_list): _log.debug("recieved {} items to publish" .format(len(to_publish_list))) self.report_all_handled() def query_historian(self, topic, start=None, end=None, agg_type=None, agg_period=None, skip=0, count=None, order="FIRST_TO_LAST"): """Not implemented """ raise NotImplemented("query_historian not implimented for null historian") return NullHistorian(**kwargs)
def mesa_test_agent(config_path, **kwargs): """ Parse the TestAgent configuration file and return an instance of the agent that has been created using that configuration. See initialize_config() method documentation for a description of each configurable parameter. This agent can be installed from a command-line shell as follows: export VOLTTRON_ROOT=<your volttron install directory> export MESA_TEST=$VOLTTRON_ROOT/services/core/MesaAgent/tests/TestAgent cd $VOLTTRON_ROOT python scripts/install-agent.py -s $$MESA_TEST -i mesatest -c $MESA_TEST/testagent.config -t mesatest -f :param config_path: (str) Path to a configuration file. :returns: TestAgent instance """ try: config = utils.load_config(config_path) except (StandardError, err): _log.error("Error loading MesaTestAgent configuration: {}".format(err)) config = {} mesaagent_id = config.get('mesaagent_id', 'mesaagent') point_topic = config.get('point_topic', 'mesa/point') function_topic = config.get('function_topic', 'mesa/function') outstation_status_topic = config.get('outstation_status_topic', 'mesa/outstation_status') point_config = config.get('point_config', None) return MesaTestAgent(mesaagent_id, point_topic, function_topic, outstation_status_topic, point_config, **kwargs)
def main(argv=sys.argv): '''Main method called by the eggsecutable.''' p_process = None try: config_path = os.environ.get('AGENT_CONFIG') sub_path = os.environ.get('AGENT_SUB_ADDR') config = utils.load_config(config_path) command = config['exec'] p_process = subprocess.Popen(command.split()) agent = ProcessAgent(sub_path, p_process) agent.run() except Exception as e: _log.exception('unhandled exception') finally: if p_process is None: return 1 if p_process.poll() is None: p_process.send_signal(signal.SIGINT) time.sleep(2) if p_process.poll() is None: p_process.terminate() time.sleep(2) if p_process.poll() is None: p_process.kill() time.sleep(2) return p_process.poll()
def historian(config_path, **kwargs): config = utils.load_config(config_path) services_topic_list = config.get('services_topic_list', [ topics.DRIVER_TOPIC_BASE, topics.LOGGER_BASE, topics.ACTUATOR, topics.ANALYSIS_TOPIC_BASE ]) custom_topic_list = config.get('custom_topic_list', []) topic_replace_list = config.get('topic_replace_list', []) destination_vip = config.get('destination-vip') destination_historian_identity = config.get('destination-historian-identity', 'platform.historian') backup_storage_limit_gb = config.get('backup_storage_limit_gb', None) gather_timing_data = config.get('gather_timing_data', False) hosts = KnownHostsStore() destination_serverkey = hosts.serverkey(destination_vip) if destination_serverkey is None: _log.info("Destination serverkey not found in known hosts file, using config") destination_serverkey = config['destination-serverkey'] return DataMover(services_topic_list, custom_topic_list, topic_replace_list, destination_vip, destination_serverkey, destination_historian_identity, gather_timing_data, backup_storage_limit_gb=backup_storage_limit_gb, **kwargs)
def __init__(self, config_path, **kwargs): kwargs.pop("identity", None) super(EmailerAgent, self).__init__(identity="platform.emailer", **kwargs) config = utils.load_config(config_path) self._smtp = config.get("smtp-address", None) self._from = config.get("from-address", None) self._to = config.get("to-addresses", None) self._allow_frequency = config.get("allow-frequency-minutes", 60) self._allow_frequency_seconds = self._allow_frequency * 60 if not self._from and self._to: raise ValueError('Invalid from/to addresses specified.') if self._smtp is None: raise ValueError('Invalid smtp-address') # will throw an error if can't connect try: s = smtplib.SMTP(self._smtp) s.quit() except socket.gaierror: raise ValueError('Invalid smtp-address') _log.debug('Allow frequency in seconds is: {}'.format(self._allow_frequency_seconds)) self._sent_emails = None self._read_store()
def historian(config_path, **kwargs): """ This method is called by the :py:func:`sqlhistorian.historian.main` to parse the passed config file or configuration dictionary object, validate the configuration entries, and create an instance of SQLHistorian :param config_path: could be a path to a configuration file or can be a dictionary object :param kwargs: additional keyword arguments if any :return: an instance of :py:class:`sqlhistorian.historian.SQLHistorian` """ if isinstance(config_path, dict): config_dict = config_path else: config_dict = utils.load_config(config_path) connection = config_dict.get('connection', None) assert connection is not None database_type = connection.get('type', None) assert database_type is not None params = connection.get('params', None) assert params is not None SQLHistorian.__name__ = 'SQLHistorian' utils.update_kwargs_with_config(kwargs, config_dict) _log.debug("In sql historian before calling class kwargs is {}".format( kwargs)) return SQLHistorian(**kwargs)
def sep2_agent(config_path, **kwargs): """Parses the SEP2 Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: SEP2 Agent :rtype: SEP2Agent """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using SEP2 Agent defaults for starting configuration.") devices = config.get('devices', []) # To add devices, include them in a config file sep2_server_sfdi = config.get('sep2_server_sfdi', 'foo') # This default should be overridden in config file sep2_server_lfdi = config.get('sep2_server_lfdi', 'bar') # This defauly should be overridden in config file load_shed_device_category = config.get('load_shed_device_category', '0020') timezone = config.get('timezone', 'America/Los_Angeles') return SEP2Agent(devices, sep2_server_sfdi, sep2_server_lfdi, load_shed_device_category, timezone, **kwargs)
def __init__(self, config_path, **kwargs): super(AlertAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.group_agent = {} self._connection = None self.publish_settings = self.config.get('publish-settings') self._remote_agent = None self._creating_agent = False self._resetting_remote_agent = False self.publish_remote = False self.publish_local = True if self.publish_settings: self.publish_local = self.publish_settings.get('publish-local', True) self.publish_remote = self.publish_settings.get('publish-remote', False) remote = self.publish_settings.get('remote') if self.publish_remote and not remote: raise ValueError("Configured publish-remote without remote section") self.remote_identity = remote.get('identity', None) self.remote_serverkey = remote.get('serverkey', None) self.remote_address = remote.get('vip-address', None) # The remote serverkey need not be specified if the serverkey is added # to the known hosts file. If it is not specified then the call to # build agent will fail. Note not sure what rabbit will do in this # case # # TODO: check rabbit. if self.publish_remote: assert self.remote_identity assert self.remote_address
def __init__(self, config_path, **kwargs): super(TCMAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.site = self.config.get('campus') self.building = self.config.get('building') self.unit = self.config.get('unit') self.subdevices = self.config.get('subdevices') self.out_temp_name = self.config.get('out_temp_name') self.supply_temp_name = self.config.get('supply_temp_name') self.zone_temp_name = self.config.get('zone_temp_name') self.air_flow_rate_name = self.config.get('air_flow_rate_name') self.aggregate_in_min = self.config.get('aggregate_in_min') self.aggregate_freq = str(self.aggregate_in_min) + 'Min' self.ts_name = self.config.get('ts_name') self.Qhvac_name = 'Q_hvac' self.Qhvac_new_name = 'Q_hvac_new' self.zone_temp_new_name = self.zone_temp_name + '_new' self.window_size_in_day = int(self.config.get('window_size_in_day')) self.min_required_window_size_in_percent = float(self.config.get('min_required_window_size_in_percent')) self.interval_in_min = int(self.config.get('interval_in_min')) self.no_of_recs_needed = self.window_size_in_day * 24 * (60 / self.interval_in_min) self.min_no_of_records_needed_after_aggr = int(self.min_required_window_size_in_percent/100 * self.no_of_recs_needed/self.aggregate_in_min) self.schedule_run_in_sec = int(self.config.get('schedule_run_in_day')) * 86400 self.rho = 1.204 self.c_p = 1006.0
def tagging_service(config_path, **kwargs): """ This method is called by the :py:func:`service.tagging.main` to parse the passed config file or configuration dictionary object, validate the configuration entries, and create an instance of SQLTaggingService :param config_path: could be a path to a configuration file or can be a dictionary object :param kwargs: additional keyword arguments if any :return: an instance of :py:class:`service.tagging.SQLTaggingService` """ _log.debug("kwargs before init: {}".format(kwargs)) if isinstance(config_path, dict): config_dict = config_path else: config_dict = utils.load_config(config_path) _log.debug("config_dict before init: {}".format(config_dict)) if not config_dict.get('connection') or \ not config_dict.get('connection').get('params') or \ not config_dict.get('connection').get('params').get('database'): raise ValueError("Missing database connection parameters. Agent " "configuration should contain database connection " "parameters with the details about type of database" "and name of database. Please refer to sample " "configuration file in Agent's source directory.") utils.update_kwargs_with_config(kwargs,config_dict) return SQLiteTaggingService(**kwargs)
def historian(config_path, **kwargs): """ This method is called by the :py:func:`crate_historian.historian.main` to parse the passed config file or configuration dictionary object, validate the configuration entries, and create an instance of MongodbHistorian :param config_path: could be a path to a configuration file or can be a dictionary object :param kwargs: additional keyword arguments if any :return: an instance of :py:class:`CrateHistorian` """ if isinstance(config_path, dict): config_dict = config_path else: config_dict = utils.load_config(config_path) connection = config_dict.get('connection', None) assert connection is not None database_type = connection.get('type', None) assert database_type is not None params = connection.get('params', None) assert params is not None topic_replacements = config_dict.get('topic_replace_list', None) _log.debug('topic_replacements are: {}'.format(topic_replacements)) CrateHistorian.__name__ = 'CrateHistorian' return CrateHistorian(config_dict, topic_replace_list=topic_replacements, **kwargs)
def __init__(self, config_path, **kwargs): super(HPWHMeasureAgent, self).__init__(**kwargs) # Load library from config file self.config = utils.load_config(config_path) # Make variables for ADC Pins self.ADC = AIN4 # Set up pins for SPI interface, thermocouple readings CLK = 'P9_12' CS = 'P9_15' DO = 'P9_23' self.sensor_up = MAX31855.MAX31855(CLK, CS, DO) CLK = 'P8_7' CS = 'P8_8' DO = 'P8_9' self.sensor_low = MAX31855.MAX31855(CLK, CS, DO) # nn is a placeholder for list operations self.nn = 0 # ii is total samples to keep in moving avg. time*samplerate self.ii = settings.seconds * 1 / settings.temp_int # Initialize empty values lists self.values_up = [0]*int(self.ii) self.values_low = [0]*int(self.ii)
def market_service_agent(config_path, **kwargs): """Parses the Market Service Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ _log.debug("Starting MarketServiceAgent") try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using Market Service Agent defaults for starting configuration.") market_period = int(config.get('market_period', 300)) reservation_delay = int(config.get('reservation_delay', 0)) offer_delay = int(config.get('offer_delay', 120)) verbose_logging = int(config.get('verbose_logging', True)) return MarketServiceAgent(market_period, reservation_delay, offer_delay, verbose_logging, **kwargs)
def smarthub(config_path, **kwargs): config = utils.load_config(config_path) vip_identity = config.get('vip_identity', 'iiit.smarthub') # This agent needs to be named iiit.smarthub. Pop the uuid id off the kwargs kwargs.pop('identity', None) Agent.__name__ = 'SmartHub_Agent' return SmartHub(config_path, identity=vip_identity, **kwargs)
def __init__(self, config_path, **kwargs): super(WbeAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.site = self.config.get('campus') self.building = self.config.get('building') self.out_temp_unit = self.config.get('out_temp_unit', '') self.out_temp_name = self.config.get('out_temp_name') self.power_unit = self.config.get('power_unit', '') self.power_name = self.config.get('power_name') self.zip = self.config.get('zip') self.object_id = self.config.get('object_id') self.variable_id = self.config.get('variable_id') self.n_degrees = self.config.get('n_degrees') self.deviation = self.config.get('deviation') self.time_diff_tol = self.config.get('time_diff_tol') self.oat_diff_tol = self.config.get('oat_diff_tol') self.cost_limit = self.config.get('cost_limit') self.price = self.config.get('price') self.threshold = self.config.get('threshold') self.out_temp_topic = '/'.join([self.site, self.building, self.out_temp_unit, self.out_temp_name]) self.out_temp_topic = self.out_temp_topic.replace('//', '/') self.power_topic = '/'.join([self.site, self.building, self.power_unit, self.power_name]) self.power_topic = self.power_topic.replace('//', '/') self.tz = self.config.get('tz') self.local_tz = pytz.timezone(self.tz) self.utc_tz = pytz.timezone('UTC') self.model_start = self.config.get('model_start', None) self.model_stop = self.config.get('model_stop', None) self.actual_start = self.config.get('prediction_start', None) self.actual_stop = self.config.get('prediction_stop', None) self.operation_mode = self.config.get('operation_mode') if self.operation_mode == 1: self.cur_analysis_time_utc = datetime.utcnow() else: self.cur_analysis_time = self.local_tz.localize(parser.parse(self.config.get('cur_time'))) self.cur_analysis_time_utc = self.cur_analysis_time.astimezone(pytz.utc) self.configure_start_stop() self.db_folder = self.config.get('db_folder') + '/' self.db_folder = self.db_folder.replace('//', '/') self.debug_folder = self.config.get('debug_folder') + '/' self.debug_folder = self.debug_folder.replace('//', '/') #Wbe/request/start/end self.request_topic_prefix = 'wbe/request' self.weather_req_topic = 'weather2/request/forecast10/ZIP/{zip}/all'.format(zip=self.zip) self.weather_resp_topic = 'weather2/response/forecast10/ZIP/{zip}/all'.format(zip=self.zip) self.forecast_data = None
def __init__(self, config_path, **kwargs): '''Initialize instance attributes.''' super(AskAgent, self).__init__(**kwargs) self.config = {'address': ('127.0.0.1', 7575), 'state': 'on', 'backlog': 5} if config_path: self.config.update(utils.load_config(config_path)) self.ask_socket = None self.state = None
def __init__(self, config_path, **kwargs): super(HPWHControlAgent, self).__init__(**kwargs) # load library from config file self.config = utils.load_config(config_path) # Make variables for GPIO Pins self.fan1 = GPIO1_15 # fan 1 (P8_15) self.fan2 = GPIO1_14 # fan 2 (P8_16) self.fan1_pwm = PWM1A # fan 2 speed (P9_14) self.fan2_pwm = PWM2B # fan 2 speed (P8_13) self.HP = GPIO1_13 # heat pump relay (P8_11, RY1) self.up_element = GPIO1_12 # upper element (P8_12, RY2) self.low_element = GPIO0_26 # lower element (P8_14, RY3) # Initialize GPIO pin mode pinMode(self.fan1, OUTPUT) pinMode(self.fan2, OUTPUT) pinMode(self.HP, OUTPUT) pinMode(self.up_element, OUTPUT) pinMode(self.low_element, OUTPUT) # Initialize output pins to LOW (off) digitalWrite(self.fan1, LOW) digitalWrite(self.fan2, LOW) digitalWrite(self.HP, LOW) digitalWrite(self.up_element, LOW) digitalWrite(self.low_element, LOW) # Initialize fans to 0 duty cycle analogWrite(self.fan1_pwm, 0) analogWrite(self.fan2_pwm, 0) # Set PWM frequency to 15,000 Hz pwmFrequency(self.fan1_pwm, 15000) pwmFrequency(self.fan2_pwm, 15000) # Initialize flags self.state = False self.fast = False self.regular = False self.mode = "off" self.cost_level = "low" self.cost = 0 # Initialize upper & lower sensor temps (set to same as desired_temp) self.up_temp = 120 self.low_temp = 120 # Initialize default temp self.desired_temp = 120 # High deadband limit is 0F above desired temp self.hi_deadband = self.desired_temp + 0 # Low deadband limit is 18F below desired temp self.low_deadband = self.desired_temp - 18 # Lowest limit before elements turn on is 22F below desired temp self.low_limit = self.desired_temp - 22
def __init__(self, config_path, **kwargs): super(WeatherAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) # dictionary of different topics being published self.current_publishes = {} # Change next line to your wunderground API key self.api_key = '' self.default_config = {'api_key': self.api_key} self.vip.config.set_default("config", self.default_config) self.vip.config.subscribe(self.configure, actions=["NEW", "UPDATE"], pattern="config")
def __init__(self, config_path, **kwargs): MarketAgent.__init__(self, **kwargs) self.config_path = config_path self.config = utils.load_config(config_path) self.name = self.config.get('name') self.T = int(self.config.get('T', 24)) self.db_topic = self.config.get("db_topic", "tnc") self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic) self.campus_demand_topic = "{}/campus/city/demand".format( self.db_topic) self.campus_supply_topic = "/".join( [self.db_topic, "campus/{}/supply"]) # Create market names to join self.quantities = [None] * self.T self.reserves = [None] * self.T self.base_market_name = 'electric' # Need to agree on this with other market agents self.market_names = [] for i in range(self.T): self.market_names.append('_'.join([self.base_market_name, str(i)]))
def bacnet_proxy_agent(config_path, **kwargs): config = utils.load_config(config_path) vip_identity = config.get("vip_identity", "platform.bacnet_proxy") # pop off the uuid based identity kwargs.pop('identity', None) device_address = config["device_address"] max_apdu_len = config.get("max_apdu_length", 1024) seg_supported = config.get("segmentation_supported", "segmentedBoth") obj_id = config.get("object_id", 599) obj_name = config.get("object_name", "Volttron BACnet driver") ven_id = config.get("vendor_id", 15) return BACnetProxyAgent(device_address, max_apdu_len, seg_supported, obj_id, obj_name, ven_id, heartbeat_autostart=True, identity=vip_identity, **kwargs)
def load_me(config_path, **kwargs): """ Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Setteroccvav :rtype: Setteroccvav """ try: global config config = utils.load_config(config_path) _log.debug(f'[Simple DR Agent INFO] - debug config {config}') except Exception: config = {} if not config: _log.debug("[Simple DR Agent INFO] - Using Agent defaults for starting configuration.") return Setteroccvav(**kwargs)
def solaragent(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Solaragent :rtype: Solaragent """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using Agent defaults for starting configuration.") setting1 = int(config.get('setting1', 1)) setting2 = config.get('setting2', "some/random/topic") return Solaragent(setting1, setting2, **kwargs)
def control_agent(config_path, **kwargs): """ Parse the ControlAgentSim configuration file and return an instance of the agent that has been created using that configuration. See initialize_config() method documentation for a description of each configurable parameter. :param config_path: (str) Path to a configuration file. :returns: ControlAgentSim instance """ try: config = utils.load_config(config_path) except Exception as err: _log.error("Error loading configuration: {}".format(err)) config = {} venagent_id = config.get('venagent_id') opt_type = config.get('opt_type') report_interval_secs = config.get('report_interval_secs') baseline_power_kw = config.get('baseline_power_kw') sine_period_secs = config.get('sine_period_secs') return ControlAgentSim(venagent_id, opt_type, report_interval_secs, baseline_power_kw, sine_period_secs, **kwargs)
def DataPub(config_path, **kwargs): '''Emulate device driver to publish data and Actuatoragent for testing. The first column in the data file must be the timestamp and it is not published to the bus unless the config option: 'use_timestamp' - True will use timestamp in input file. timestamps. False will use the current now time and publish using it. ''' conf = utils.load_config(config_path) _log.debug(str(conf)) use_timestamp = conf.get('use_timestamp', True) remember_playback = conf.get('remember_playback', False) reset_playback = conf.get('reset_playback', False) publish_interval = float(conf.get('publish_interval', 5)) base_path = conf.get('basepath', "") input_data = conf.get('input_data', []) # unittype_map maps the point name to the proper units. unittype_map = conf.get('unittype_map', {}) # should we keep playing the file over and over again. replay_data = conf.get('replay_data', False) max_data_frequency = conf.get("max_data_frequency") return Publisher(use_timestamp=use_timestamp, publish_interval=publish_interval, base_path=base_path, input_data=input_data, unittype_map=unittype_map, max_data_frequency=max_data_frequency, replay_data=replay_data, remember_playback=remember_playback, reset_playback=reset_playback, **kwargs)
def continuousroller(config_path, **kwargs): """ Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Continuousroller :rtype: Continuousroller """ try: config = utils.load_config(config_path) _log.debug(f'[Conninuous Roller Agent INFO] - config Load SUCESS') except Exception: _log.debug(f'[Conninuous Roller Agent INFO] - config Load FAIL') config = {} if not config: _log.info("Using Agent defaults for starting configuration.") return Continuousroller(**kwargs)
def __init__(self, config_path, **kwargs): global agent_id super(ApprovalHelperAgent, self).__init__(**kwargs) config = utils.load_config(config_path) sys.path.append(PROJECT_DIR) db_host = settings.DATABASES['default']['HOST'] db_port = settings.DATABASES['default']['PORT'] db_database = settings.DATABASES['default']['NAME'] db_user = settings.DATABASES['default']['USER'] db_password = settings.DATABASES['default']['PASSWORD'] self.curcon = db_helper.db_connection() def get_config(name): try: kwargs.pop(name) except KeyError: return config.get(name, '') agent_id = get_config('agent_id') self.agent_id = str(agent_id)
def __init__(self, config_path, **kwargs): super(EmailerAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.smtp_address = self.config.get("smtp-address", None) self.from_address = self.config.get("from-address", None) self.to_address = self.config.get("to-addresses", None) self.smtp_port = self.config.get("smtp-port", None) self.smtp_username = self.config.get("smtp-username", None) self.smtp_password = self.config.get("smtp-password", None) self.smtp_tls = self.config.get("smtp-tls", None) self.allow_frequency_minutes = self.config.get( "allow-frequency-minutes", 60) self._allow_frequency_seconds = self.allow_frequency_minutes * 60 self.smtp_tls = self.config.get("smtp-tls", None) self.default_config = dict( smtp_address=self.smtp_address, from_address=self.from_address, to_addresses=self.to_address, smtp_port=self.smtp_port, smtp_username=self.smtp_username, smtp_password=self.smtp_password, smtp_tls=self.smtp_tls, allow_frequency_minutes=self.allow_frequency_minutes, alert_from_address=self.from_address, alert_to_addresses=self.to_address, send_alerts_enabled=True, record_sent_emails=True) self.current_config = None self.vip.config.set_default("config", self.default_config) self.vip.config.subscribe(self.configure_main, actions=["NEW", "UPDATE"], pattern="*") # Keep track of keys that have been added to send with. self.tosend = {} # Keep track of how often we send an email out based on key so we don't overload admins. self.sent_alert_emails = {}
def electric_buyer_agent(config_path, **kwargs): """Parses the Electric Meter Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ _log.debug("Starting SampleElectricMeterAgent") try: config = utils.load_config(config_path) except Exception: config = {} if not config: _log.info("Using Sample Electric Meter Agent defaults for starting configuration.") market_name = config.get('market_name', 'electric') return SampleElectricBuyerAgent(market_name, **kwargs)
def __init__(self, config_path, **kwargs): Agent.__init__(self, **kwargs) myTransactiveNode.__init__(self) self.config_path = config_path self.config = utils.load_config(config_path) self.name = self.config.get('name') self.market_cycle_in_min = int( self.config.get('market_cycle_in_min', 60)) self.duality_gap_threshold = float( self.config.get('duality_gap_threshold', 0.01)) self.building_names = self.config.get('buildings', []) self.building_powers = self.config.get('building_powers') self.db_topic = self.config.get("db_topic", "tnc") self.PV_max_kW = float(self.config.get("PV_max_kW")) self.city_loss_factor = float(self.config.get("city_loss_factor")) self.neighbors = [] self.city_supply_topic = "{}/city/campus/supply".format(self.db_topic) self.building_demand_topic = "/".join( [self.db_topic, "{}/campus/demand"]) self.campus_demand_topic = "{}/campus/city/demand".format( self.db_topic) self.campus_supply_topic = "/".join( [self.db_topic, "campus/{}/supply"]) self.reschedule_interval = timedelta(minutes=10, seconds=1) self.simulation = self.config.get('simulation', False) self.simulation_start_time = parser.parse( self.config.get('simulation_start_time')) self.simulation_one_hour_in_seconds = int( self.config.get('simulation_one_hour_in_seconds')) Timer.created_time = datetime.now() Timer.simulation = self.simulation Timer.sim_start_time = self.simulation_start_time Timer.sim_one_hr_in_sec = self.simulation_one_hour_in_seconds
def __init__(self, config_path, **kwargs): """ Configures the `AlertMonitorAgent` Validates that the outfile parameter in the config file is specified and sets up the agent. @param config_path: path to the configuration file for this agent. @param kwargs: @return: """ config = utils.load_config(config_path) self._outfile = config.pop('outfile') if not self._outfile: raise ValueError('Invalid outfile parameter in config file.') # pop off the identity arge because we are goint to explicitly # set it to our identity. If we didn't do this it would cause # an error. The default identity is the uuid of the agent. kwargs.pop('identity') _log.debug('outfile is {}'.format(os.path.abspath(self._outfile))) super(AlertMonitorAgent, self).__init__(**kwargs)
def PingPongAgent(config_path, **kwargs): '''Agent to demonstrate agent-initiated mobility. The agent periodically calculates the next host to visit from the hosts list specified in the config file and requests a move. ''' config = utils.load_config(config_path) period = config.get('period', 30) hosts = config['hosts'] uuid = os.environ['AGENT_UUID'] class Agent(PublishMixin, BaseAgent): @matching.match_glob('platform/move/reply/' + uuid) def on_move_fail(self, topic, headers, message, match): error, = message _log.error('attempt to move %s failed: %s', uuid, error) @periodic(period) def move(self): count = 0 try: file = open('count', 'r') except IOError as exc: if exc.errno != errno.ENOENT: _log.error('error opening count file: %s', exc) return else: try: count = int(file.read().strip()) except ValueError: count = 0 host = hosts[count % len(hosts)] with open('count', 'w') as file: file.write(str(count + 1)) self.publish('platform/move/request/' + uuid, {}, host) Agent.__name__ = 'PingPongAgent' return Agent(**kwargs)
def historian(config_path, **kwargs): """ Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: `FactsService` :rtype: `FactsService` """ if isinstance(config_path, dict): config_dict = config_path else: config_dict = utils.load_config(config_path) # Gather all settings from configuration into kwargs. # This ensures that settings common to all historians # are passed to BaseHistorian. utils.update_kwargs_with_config(kwargs, config_dict) return FactsService(**kwargs)
def data_cleaner(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: DataCleaner :rtype: DataCleaner """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using Agent defaults for starting configuration.") period = int(config.get('period', 300)) points = config.get('points', {}) return DataCleaner(period, points, **kwargs)
def __init__(self, config_path, **kwargs): super(ListenerAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self._agent_id = self.config.get('agentid', DEFAULT_AGENTID) self._message = self.config.get('message', DEFAULT_MESSAGE) self._heartbeat_period = self.config.get('heartbeat_period', DEFAULT_HEARTBEAT_PERIOD) try: self._heartbeat_period = int(self._heartbeat_period) except: _log.warning( 'Invalid heartbeat period specified setting to default') self._heartbeat_period = DEFAULT_HEARTBEAT_PERIOD log_level = self.config.get('log-level', 'INFO') if log_level == 'ERROR': self._logfn = _log.error elif log_level == 'WARN': self._logfn = _log.warning elif log_level == 'DEBUG': self._logfn = _log.debug else: self._logfn = _log.info
def darksky(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Darksky :rtype: Darksky """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.error("Darksky agent configuration: ".format(config)) if "api_key" not in config: raise RuntimeError("Darksky agent must be configured with an api key.") _log.debug("config_dict before init: {}".format(config)) utils.update_kwargs_with_config(kwargs, config) return Darksky(**kwargs)
def __init__(self, config_path, **kwargs): super().__init__(**kwargs) self.config = utils.load_config(config_path) self._agent_id = self.config.get('agentid', DEFAULT_AGENTID) self._message = self.config.get('message', DEFAULT_MESSAGE) self._heartbeat_period = self.config.get('heartbeat_period', DEFAULT_HEARTBEAT_PERIOD) self._address = self.config.get('address') self._url = self.config.get('url') self._client_id = self.config.get('client_id') self._username = self.config.get('username') self._password = self.config.get('password') self._client_secret = self.config.get('client_secret') self.apiLib = importlib.import_module( "Agent.NetatmoAgent.multisensor.netatmo_driver") self.netatmo = self.apiLib.API(address=self._address, url=self._url, client_id=self._client_id, username=self._username, password=self._password, client_secret=self._client_secret) try: self._heartbeat_period = int(self._heartbeat_period) except: _log.warning( 'Invalid heartbeat period specified setting to default') self._heartbeat_period = DEFAULT_HEARTBEAT_PERIOD log_level = self.config.get('log-level', 'INFO') if log_level == 'ERROR': self._logfn = _log.error elif log_level == 'WARN': self._logfn = _log.warn elif log_level == 'DEBUG': self._logfn = _log.debug else: self._logfn = _log.info
def fncs_example(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: FncsExample :rtype: FncsExample """ try: config = utils.load_config(config_path) except Exception: config = {} if not config: _log.info("Using Agent defaults for starting configuration.") if not config.get("topic_mapping"): raise ValueError("Configuration must have a topic_mapping entry.") topic_mapping = config.get("topic_mapping") federate = config.get("federate_name") broker_location = config.get("broker_location", "tcp://localhost:5570") time_delta = config.get("time_delta", "1s") sim_length = config.get("sim_length", "60s") stop_agent_when_sim_complete = config.get("stop_agent_when_sim_complete", False) subscription_topic = config.get("subscription_topic", None) return FncsExample( topic_mapping=topic_mapping, federate_name=federate, broker_location=broker_location, time_delta=time_delta, subscription_topic=subscription_topic, sim_length=sim_length, stop_agent_when_sim_complete=stop_agent_when_sim_complete, **kwargs)
def historian(config_path, **kwargs): config = utils.load_config(config_path) custom_topic_list = config.pop('custom_topic_list', []) topic_replace_list = config.pop('topic_replace_list', []) destination_vip = config.pop('destination-vip', None) service_topic_list = config.pop('service_topic_list', None) if service_topic_list is not None: w = "Deprecated service_topic_list. Use capture_device_data " \ "capture_log_data, capture_analysis_data or capture_record_data " \ "instead!" _log.warning(w) # Populate the new values for the kwargs based upon the old data. kwargs['capture_device_data'] = True if ("device" in service_topic_list or "all" in service_topic_list) else False kwargs['capture_log_data'] = True if ("datalogger" in service_topic_list or "all" in service_topic_list) else False kwargs['capture_record_data'] = True if ("record" in service_topic_list or "all" in service_topic_list) else False kwargs['capture_analysis_data'] = True if ("analysis" in service_topic_list or "all" in service_topic_list) else False hosts = KnownHostsStore() destination_serverkey = hosts.serverkey(destination_vip) if destination_serverkey is None: _log.info("Destination serverkey not found in known hosts file, using config") destination_serverkey = config.pop('destination-serverkey') else: config.pop('destination-serverkey', None) required_target_agents = config.pop('required_target_agents', []) cache_only = config.pop('cache_only', False) utils.update_kwargs_with_config(kwargs, config) return ForwardHistorian(destination_vip, destination_serverkey, custom_topic_list=custom_topic_list, topic_replace_list=topic_replace_list, required_target_agents=required_target_agents, cache_only=cache_only, **kwargs)
def extract_criteria(filename): """ Extract pairwise criteria parameters :param filename: :return: """ criteria_labels = {} criteria_matrix = {} config_matrix = utils.load_config(filename) # check if file has been updated or uses old format _log.debug("CONFIG_MATRIX: {}".format(config_matrix)) if "curtail" not in config_matrix.keys( ) and "augment" not in config_matrix.keys(): config_matrix = {"curtail": config_matrix} _log.debug("CONFIG_MATRIX: {}".format(config_matrix)) for state in config_matrix: index_of = dict([(a, i) for i, a in enumerate(config_matrix[state].keys())]) criteria_labels[state] = [] for label, index in index_of.items(): criteria_labels[state].insert(index, label) criteria_matrix[state] = [[0.0 for _ in config_matrix[state]] for _ in config_matrix[state]] for j in config_matrix[state]: row = index_of[j] criteria_matrix[state][row][row] = 1.0 for k in config_matrix[state][j]: col = index_of[k] criteria_matrix[state][row][col] = float( config_matrix[state][j][k]) criteria_matrix[state][col][row] = float( 1.0 / criteria_matrix[state][row][col]) return criteria_labels, criteria_matrix
def __init__(self, config_path, **kwargs): super(PGnEAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.site = self.config.get('campus') self.building = self.config.get('building') self.temp_unit = self.config.get('temp_unit') self.power_unit = self.config.get('power_unit') self.out_temp_name = self.config.get('out_temp_name') self.power_name = self.config.get('power_name') self.aggregate_in_min = self.config.get('aggregate_in_min') self.aggregate_freq = str(self.aggregate_in_min) + 'Min' self.ts_name = self.config.get('ts_name') self.window_size_in_day = int(self.config.get('window_size_in_day')) self.min_required_window_size_in_percent = float( self.config.get('min_required_window_size_in_percent')) self.interval_in_min = int(self.config.get('interval_in_min')) self.no_of_recs_needed = 10 # self.window_size_in_day * 24 * (60 / self.interval_in_min) self.min_no_of_records_needed_after_aggr = int( self.min_required_window_size_in_percent / 100 * self.no_of_recs_needed / self.aggregate_in_min) self.schedule_run_in_sec = int( self.config.get('schedule_run_in_hr')) * 3600
def meter_agent(config_path, **kwargs): """Parses the Electric Meter Agent configuration and returns an instance of the agent created using that configuation. :param config_path: Path to a configuation file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ _log.debug("Starting MeterAgent") try: config = utils.load_config(config_path) except Exception: config = {} if not config: _log.info("Using defaults for starting configuration.") market_name = config.get('market_name', 'electric') price = config.get('price', 55) verbose_logging = config.get('verbose_logging', True) return MeterAgent(market_name, price, verbose_logging, **kwargs)
def __init__(self, **kwargs): ''' Initialize class from config file ''' super(CEA2045RelayAgent, self).__init__(**kwargs) self.config = utils.load_config(config_path) self.volttime = None self.mode_CEA2045_array = ['emergency', 'shed', 'normal'] # possible states of the appliance self.cea_rate = { 'Running Normal': 2, 'Running Curtailed Grid': 1, 'Idle Grid': 0, 'Idle Normal': 0, 'SGD Error Condition': 0, 'Running Heightened Grid': 3 } self.device1_mode = {'cea2045state': 'Idle Normal'} self.device2_mode = None self.task = 0 # points of interest for demo self.point_name_map = {'cea2045state': 'cea2045state'} self.writable_points = {'cea2045state'}
def obix_history(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: ObixHistory :rtype: ObixHistory """ try: config = utils.load_config(config_path) except StandardError: config = {} if not config: _log.info("Using Agent defaults for starting configuration.") url = config.get('url') username = config.get('username') password = config.get('password') path_prefix = config.get("path_prefix", "devices/obix/history") try: check_interval = float(config.get('check_interval', 15)) except ValueError: _log.warning("bad check interval, defaulting to 15") check_interval = 15 register_config = config.get('register_config') historian_name = config.get('historian_name') default_last_read = config.get('default_last_read', 24) return ObixHistory(url, username, password, check_interval, path_prefix, register_config, historian_name, default_last_read, **kwargs)
def __init__(self, config_path, **kwargs): super(FaultDetectionAgent, self).__init__(**kwargs) #1. initialize all agent variables config = utils.load_config(config_path) self.agent_id = config.get('agent_id', 'faultdetectionagent') self.variables = dict() self.enabled = True trigger_values = {'temperature_low': 60, 'temperature_high': 85} self.data = { 'thermostat': 'RTH8_1169269', 'powermeter': '', 'sensitivity': 'low', 'fault': 'No', 'weather_agent': settings.weather_agent, 'trigger_values': trigger_values, 'temp_low_trigger_enabled': True, 'temp_high_trigger_enabled': True, 'profile_trigger_enabled': True } self.dashboard_view = { "top": None, "center": { "type": "image", "value": 'wattstopper_on.png' }, "bottom": BEMOSS_ONTOLOGY.STATUS.NAME } self.sensitivity_std_factor = {'low': 3, 'medium': 2, 'high': 1} self.trained = False self.notification_variables = dict() self.last_fault_time = None self.profile_anamoly = False self.problems = [] self.low_temp_anamoly = False self.high_temp_anamoly = False self.thermostat_nickname = ''
def cloud_agent(config_path, **kwargs): ''' Function: Return CloudAgent object with configuration information Args: Same with Class Args Returns: CloudAgent object Note: None Created: JinhoSon, 2017-04-14 Deleted: . ''' # get config information config = utils.load_config(config_path) source = config.get('source') destination_ip = config.get('destination_ip') destination_port = config.get('destination_port') services_topic_list = config.get('services_topic_list') database_name = config.get('database_name') collection_name = config.get('collection_name') command_topic = config.get('command_topic') cloud_broker_ip = config.get('cloud_broker_ip') cloud_broker_port = config.get('cloud_broker_port') cloud_producer_topic = config.get('cloud_producer_topic') cloud_consumer_topic = config.get('cloud_consumer_topic') if 'all' in services_topic_list: services_topic_list = [ topics.DRIVER_TOPIC_BASE, topics.LOGGER_BASE, topics.ACTUATOR, topics.ANALYSIS_TOPIC_BASE ] return CloudAgent(source, destination_ip, destination_port, services_topic_list, database_name, collection_name, command_topic, cloud_broker_ip, cloud_broker_port, cloud_producer_topic, cloud_consumer_topic, **kwargs)
def extract_criteria(filename): """ Extract pairwise criteria parameters :param filename: :return: """ config_matrix = utils.load_config(filename) index_of = dict([(a, i) for i, a in enumerate(config_matrix.keys())]) criteria_labels = [] for label, index in index_of.items(): criteria_labels.insert(index, label) criteria_matrix = [[0.0 for _ in config_matrix] for _ in config_matrix] for j in config_matrix: row = index_of[j] criteria_matrix[row][row] = 1.0 for k in config_matrix[j]: col = index_of[k] criteria_matrix[row][col] = float(config_matrix[j][k]) criteria_matrix[col][row] = float(1.0 / criteria_matrix[row][col]) return criteria_labels, criteria_matrix
def __init__(self, config_path, **kwargs): super(IlluminanceBasedLightingControl, self).__init__(**kwargs) self.variables = kwargs # 2. @params agent config = utils.load_config(config_path) def get_config(name): try: kwargs.pop(name) except KeyError: return config.get(name, '') self.curcon = db_helper.db_connection() self.app_id = get_config('agent_id') self.update_para('all') # monitor time should be larger or equal to device monitor time. self.monitor_time = int(settings.DEVICES['device_monitor_time']) self.calibrate_topic = 'to/' + self.app_id + '/from/ui/calibrate' self.update_target_topic = 'to/' + self.app_id + '/from/ui/update_target' self.firsttime = True
def uncontrol_agent(config_path, **kwargs): """Parses the uncontrollable load agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Market Service Agent :rtype: MarketServiceAgent """ _log.debug("Starting the uncontrol agent") try: config = utils.load_config(config_path) except Exception: config = {} if not config: _log.info("Using defaults for starting configuration.") agent_name = config.get("agent_name", "uncontrol") base_name = config.get('market_name', 'electric') market_name = [] q_uc = [] for i in range(24): market_name.append('_'.join([base_name, str(i)])) q_uc.append(float(config.get("power_" + str(i), 0))) verbose_logging = config.get('verbose_logging', True) building_topic = topics.DEVICES_VALUE(campus=config.get("campus", ""), building=config.get("building", ""), unit=None, path="", point="all") devices = config.get("devices") return UncontrolAgent(agent_name, market_name, verbose_logging, q_uc, building_topic, devices, **kwargs)