本文整理汇总了Python中volttron.platform.agent.utils.setup_logging函数的典型用法代码示例。如果您正苦于以下问题:Python setup_logging函数的具体用法?Python setup_logging怎么用?Python setup_logging使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setup_logging函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(argv=sys.argv):
'''Main method called to start the agent.'''
utils.setup_logging()
try:
utils.vip_main(hello_agent)
except Exception:
_log.exception('unhandled exception')
示例2: __init__
def __init__(self, **kwargs):
super(Agent, self).__init__(**kwargs)
self.normal_firststage_fanspeed = config.get('normal_firststage_fanspeed', 75.0)
self.normal_secondstage_fanspeed = config.get('normal_secondstage_fanspeed', 90.0)
self.normal_damper_stpt = config.get('normal_damper_stpt', 5.0)
self.normal_coolingstpt = config.get('normal_coolingstpt', 74.0)
self.normal_heatingstpt = config.get('normal_heatingstpt', 67.0)
self.smap_path = config.get('smap_path')
self.default_cooling_stage_differential = 0.5
self.current_spacetemp = 0.0
self.building_thermal_constant = config.get('building_thermal_constant', 4.0)
self.timestep_length = config.get('timestep_length', 900)
self.csp_cpp = config.get('csp_cpp', 80.0)
self.csp_pre = config.get('csp_pre', 67.0)
self.restore_window = int(((self.csp_cpp - self.normal_coolingstpt)/self.building_thermal_constant) *3600)
self.state = 'STARTUP'
self.e_start_msg = None
self.error_handler = None
self.actuator_handler = None
self.pre_cool_idle = None
self.e_start = None
self.e_end = None
self.pre_stored_spacetemp =None
self.device_schedule = {}
self.all_scheduled_events = {}
self.currently_running_dr_event_handlers = []
self.headers = {headers_mod.CONTENT_TYPE: headers_mod.CONTENT_TYPE.JSON, 'requesterID': agent_id}
utils.setup_logging()
self._log = logging.getLogger(__name__)
示例3: main
def main(argv=sys.argv):
'''Main method called to start the agent.'''
utils.setup_logging()
try:
utils.default_main(UIAgent,
description='VOLTTRON platform™ agent for remote user interaction.',
argv=argv)
except Exception:
_log.exception('unhandled exception')
示例4: __init__
def __init__(self, **kwargs):
super(Agent, self).__init__(**kwargs)
path = os.path.abspath(settings.source_file)
print path
self._src_file_handle = open(path)
header_line = self._src_file_handle.readline().strip()
self._headers = header_line.split(',')
self.end_time = None
self.start_time = None
self.task_id = None
utils.setup_logging()
self._log = logging.getLogger(__name__)
logging.basicConfig(level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
示例5: __init__
def __init__(self, **kwargs):
'''Initialize data publisher class attributes.'''
super(Agent, self).__init__(**kwargs)
self._agent_id = conf.get('publisherid')
self._src_file_handle = open(path)
header_line = self._src_file_handle.readline().strip()
self._headers = header_line.split(',')
self.end_time = None
self.start_time = None
self.task_id = None
utils.setup_logging()
self._log = logging.getLogger(__name__)
self.scheduled_event = None
logging.basicConfig(
level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
self._log.info('DATA PUBLISHER ID is PUBLISHER')
示例6: __init__
def __init__(self, **kwargs):
'''Initialize data publisher class attributes.'''
super(Publisher, self).__init__(**kwargs)
self._agent_id = conf.get('publisherid')
self._src_file_handle = open(path, 'rb')
# Uses dictreader so that thee first line in the file is auto
# ingested and becaums the headers for the dictionary. Use the
# fieldnames property to get the names of the fields available.
self._reader = csv.DictReader(self._src_file_handle,
delimiter=',')
self.end_time = None
self.start_time = None
self.task_id = None
utils.setup_logging()
self._log = logging.getLogger(__name__)
self.scheduled_event = None
logging.basicConfig(
level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
if remember_playback:
self._log.info('Keeping track of line being played in case of interuption.')
else:
self._log.info('Not storing line being played (enable by setting remember_playback=1 in config file')
self._log.info('Publishing Starting')
self._line_on = 0
start_line = self.get_start_line()
# Only move the start_line if the reset_playback switch is off and
# the remember_playback switch is on.
if not reset_playback and remember_playback:
while self._line_on - 1 < start_line:
self._reader.next()
self._line_on+=1
self._log.info('Playback starting on line: {}'.format(self._line_on))
示例7: __init__
def __init__(self, **kwargs):
'''Initialize data publisher class attributes.'''
super(Publisher, self).__init__(**kwargs)
self._agent_id = conf.get('publisherid')
self._src_file_handle = open(path, 'rb')
# Uses dictreader so that thee first line in the file is auto
# ingested and becaums the headers for the dictionary. Use the
# fieldnames property to get the names of the fields available.
self._reader = csv.DictReader(self._src_file_handle,
delimiter=',')
self.end_time = None
self.start_time = None
self.task_id = None
utils.setup_logging()
self._log = logging.getLogger(__name__)
self.scheduled_event = None
logging.basicConfig(
level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
self._log.info('DATA PUBLISHER ID is PUBLISHER')
示例8: import
from volttron.platform.vip.agent import Agent, Core
from volttron.platform.jsonrpc import RemoteError
from volttron.platform.agent.driven import ConversionMapper
from volttron.platform.messaging import (headers as headers_mod, topics)
import dateutil.tz
__version__ = "1.0.8"
__author1__ = "Craig Allwardt <[email protected]>"
__author2__ = "Robert Lutes <[email protected]>"
__author3__ = "Poorva Sharma <[email protected]>"
__copyright__ = "Copyright (c) 2017, Battelle Memorial Institute"
__license__ = "FreeBSD"
DATE_FORMAT = "%m-%d-%y %H:%M"
setup_logging()
_log = logging.getLogger(__name__)
logging.basicConfig(level=logging.info, format="%(asctime)s %(levelname)-8s %(message)s", datefmt=DATE_FORMAT)
def driven_agent(config_path, **kwargs):
"""
Reads agent configuration and converts it to run driven agent.
:param config_path:
:param kwargs:
:return:
"""
config = utils.load_config(config_path)
arguments = config.get("arguments")
actuation_mode = True if config.get("actuation_mode", "PASSIVE") == "ACTIVE" else False
示例9: DrivenAgent
def DrivenAgent(config_path, **kwargs):
config = utils.load_config(config_path)
agent_id = config.get('agentid')
conversions = config.get('conversion_map')
validation_error = ""
device_topic = config.get('device')
if not device_topic:
validation_error += "Invalid device specified in config\n"
else:
if not device_topic[-4:] == '/all':
device_topic += '/all'
application = config.get('application')
if not application:
validation_error += "Invalid application specified in config\n"
utils.setup_logging()
_log = logging.getLogger(__name__)
logging.basicConfig(level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
if validation_error:
_log.error(validation_error)
raise ValueError(validation_error)
config.update(kwargs)
klass = _get_class(application)
# This instances is used to call the applications run method when
# data comes in on the message bus. It is constructed here so that
# each time run is called the application can keep it state.
app_instance = klass(**config)
class Agent(PublishMixin, BaseAgent):
'''Agent listens to message bus device and runs when data is published.
'''
def __init__(self, **kwargs):
super(Agent, self).__init__(**kwargs)
self._update_event = None
self._update_event_time = None
self._device_states = {}
self._kwargs = kwargs
_log.debug("device_topic is set to: "+device_topic)
@matching.match_exact(device_topic)
def on_received_message(self, topic, headers, message, matched):
_log.debug("Message received")
_log.debug("MESSAGE: "+ jsonapi.dumps(message[0]))
_log.debug("TOPIC: "+ topic)
data = jsonapi.loads(message[0])
results = app_instance.run(datetime.now(),data)
self._process_results(results)
def _process_results(self, results):
_log.debug('Processing Results!')
for key, value in results.commands.iteritems():
_log.debug("COMMAND: {}->{}".format(key, value))
for value in results.log_messages:
_log.debug("LOG: {}".format(value))
for key, value in results.table_output.iteritems():
_log.debug("TABLE: {}->{}".format(key, value))
Agent.__name__ = 'DrivenLoggerAgent'
return Agent(**kwargs)
示例10: AFDDAgent
def AFDDAgent(config_path, **kwargs):
config = utils.load_config(config_path)
agent_id = config['agentid']
termination_window = config.get('termination_window', 600)
min_run_window = config.get('min_run_window', 3600 + termination_window)
rtu_path = dict((key, config[key])
for key in ['campus', 'building', 'unit'])
day_run_interval = config.get('day_run_interval')
start_hour = config.get('start_hour')
start_minute = config.get('start_minute')
volttron_flag = config.get('volttron_flag')
debug_flag = True
zip_code = config.get('zip_code')
utils.setup_logging()
_log = logging.getLogger(__name__)
logging.basicConfig(level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
class Agent(PublishMixin, BaseAgent):
def __init__(self, **kwargs):
super(Agent, self).__init__(**kwargs)
self.lock_timer = None
self.lock_acquired = False
self.tasklet = None
self.data_queue = green.WaitQueue(self.timer)
self.value_queue = green.WaitQueue(self.timer)
self.weather_data_queue = green.WaitQueue(self.timer)
self.last_run_time = None
self.is_running = False
self.remaining_time = None
self.task_id= agent_id
self.retry_schedule = None
self.start = None
self.end = None
def setup(self):
super(Agent, self).setup()
self.scheduled_task()
def startrun(self, algo=None):
_log.debug('start diagnostic')
if algo is None:
algo = afdd.AFDD(self,config_path).run_all
self.tasklet = greenlet.greenlet(algo)
self.is_running = True
self.last_run_time = datetime.datetime.now()
self.tasklet.switch()
def scheduled_task(self):
'''
Schedule re-occuring diagnostics
'''
_log.debug('Schedule Dx')
headers = {
'type': 'NEW_SCHEDULE',
'requesterID': agent_id,
'taskID': agent_id,
'priority': 'LOW_PREEMPT'
}
min_run_hour = math.floor(min_run_window/3600)
min_run_minute = int((min_run_window/3600 - min_run_hour)*60)
self.start = datetime.datetime.now().replace(hour=start_hour, minute=start_minute)
self.end = self.start + datetime.timedelta(hours=2,minutes=30)
run_start = self.end - datetime.datetime.now()
required_diagnostic_time = datetime.timedelta(hours = min_run_hour, minutes=min_run_minute)
if run_start < required_diagnostic_time:
self.start = self.start + datetime.timedelta(days=1)
self.end = self.start + datetime.timedelta(hours=2,minutes=30)
sched_time = datetime.datetime.now() + datetime.timedelta(days=day_run_interval + 1)
sched_time = sched_time.replace(hour=0,minute=1)
else:
sched_time = datetime.datetime.now() + datetime.timedelta(days=day_run_interval)
self.start = str(self.start)
self.end = str(self.end)
self.task_timer = self.periodic_timer(60, self.publish_json,
topics.ACTUATOR_SCHEDULE_REQUEST(), headers,[["{campus}/{building}/{unit}".format(**rtu_path),self.start,self.end]])
event = sched.Event(self.scheduled_task)
self.next = self.schedule(sched_time, event)
@matching.match_headers({headers_mod.REQUESTER_ID: agent_id,'type': 'CANCEL_SCHEDULE'})
@matching.match_exact(topics.ACTUATOR_SCHEDULE_RESULT())
def preempt(self):
if self.is_running:
#.........这里部分代码省略.........
示例11: DrivenAgent
def DrivenAgent(config_path, **kwargs):
'''Driven harness for deployment of OpenEIS applications in VOLTTRON.'''
config = utils.load_config(config_path)
mode = True if config.get('mode', 'PASSIVE') == 'ACTIVE' else False
validation_error = ''
device = dict((key, config['device'][key])
for key in ['campus', 'building', 'unit'])
agent_id = config.get('agentid')
if not device:
validation_error += 'Invalid agent_id specified in config\n'
if not device:
validation_error += 'Invalid device path specified in config\n'
actuator_id = agent_id + '_' +"{campus}/{building}/{unit}".format(**device)
application = config.get('application')
if not application:
validation_error += 'Invalid application specified in config\n'
utils.setup_logging()
_log = logging.getLogger(__name__)
logging.basicConfig(level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
if validation_error:
_log.error(validation_error)
raise ValueError(validation_error)
config.update(config.get('arguments'))
converter = ConversionMapper()
output_file = config.get('output_file')
klass = _get_class(application)
# This instances is used to call the applications run method when
# data comes in on the message bus. It is constructed here so that
# each time run is called the application can keep it state.
app_instance = klass(**config)
class Agent(PublishMixin, BaseAgent):
'''Agent listens to message bus device and runs when data is published.
'''
def __init__(self, **kwargs):
super(Agent, self).__init__(**kwargs)
self._update_event = None
self._update_event_time = None
self.keys = None
self._device_states = {}
self._kwargs = kwargs
self.commands = {}
self.current_point = None
self.current_key = None
self.received_input_datetime = None
if output_file != None:
with open(output_file, 'w') as writer:
writer.close()
self._header_written = False
@matching.match_exact(topics.DEVICES_VALUE(point='all', **device))
def on_received_message(self, topic, headers, message, matched):
'''Subscribe to device data and convert data to correct type for
the driven application.
'''
_log.debug("Message received")
_log.debug("MESSAGE: " + jsonapi.dumps(message[0]))
_log.debug("TOPIC: " + topic)
data = jsonapi.loads(message[0])
#TODO: grab the time from the header if it's there or use now if not
self.received_input_datetime = datetime.utcnow()
results = app_instance.run(self.received_input_datetime, data)
self._process_results(results)
def _process_results(self, results):
'''Run driven application with converted data and write the app
results to a file or database.
'''
_log.debug('Processing Results!')
for key, value in results.commands.iteritems():
_log.debug("COMMAND: {}->{}".format(key, value))
for value in results.log_messages:
_log.debug("LOG: {}".format(value))
for key, value in results.table_output.iteritems():
_log.debug("TABLE: {}->{}".format(key, value))
# publish to output file if available.
if output_file != None:
if len(results.table_output.keys()) > 0:
for _, v in results.table_output.items():
fname = output_file # +"-"+k+".csv"
for r in v:
with open(fname, 'a+') as f:
keys = r.keys()
fout = csv.DictWriter(f, keys)
if not self._header_written:
fout.writeheader()
self._header_written = True
# if not header_written:
# fout.writerow(keys)
fout.writerow(r)
f.close()
# publish to message bus.
if len(results.table_output.keys()) > 0:
now = utils.format_timestamp(self.received_input_datetime)
headers = {
headers_mod.CONTENT_TYPE: headers_mod.CONTENT_TYPE.JSON,
#.........这里部分代码省略.........
示例12: DeviceDiscoveryAgent
import json
import datetime
import time
import logging
import os
import re
from volttron.platform.agent import BaseAgent, PublishMixin
from volttron.platform.agent import utils, matching
from volttron.platform.messaging import headers as headers_mod
from urlparse import urlparse
import settings
import netifaces as ni
import ast
import subprocess
utils.setup_logging() # setup logger for debugging
_log = logging.getLogger(__name__)
# Step1: Agent Initialization
def DeviceDiscoveryAgent(config_path, **kwargs):
config = utils.load_config(config_path) # load the config_path from devicediscoveryagent.launch.json
def get_config(name):
try:
value = kwargs.pop(name) # from the **kwargs when call this function
except KeyError as er:
print "keyError", er
return config.get(name, '')
# 1. @params agent
agent_id = get_config('agent_id')
device_scan_time = get_config('device_scan_time')
示例13:
from datetime import datetime
import os
import sys
import json
import gevent
import logging
from gevent.core import callback
from gevent import Timeout
from volttron.platform.messaging import headers as headers_mod
from volttron.platform.vip.agent import Agent, PubSub, Core
from volttron.platform.agent import utils
# Log warnings and errors to make the node red log less chatty
utils.setup_logging(level=logging.WARNING)
_log = logging.getLogger(__name__)
# These are the options that can be set from the settings module.
from settings import agent_kwargs
''' takes two arguments. Firist is topic to publish under. Second is message. '''
if __name__ == '__main__':
try:
# If stdout is a pipe, re-open it line buffered
if utils.isapipe(sys.stdout):
# Hold a reference to the previous file object so it doesn't
# get garbage collected and close the underlying descriptor.
stdout = sys.stdout
sys.stdout = os.fdopen(stdout.fileno(), 'w', 1)
示例14: MongodbAggregateHistorian
# under Contract DE-AC05-76RL01830
# }}}
from __future__ import absolute_import
import logging
import sys
import bson
from bson import ObjectId
import pymongo
from volttron.platform.agent import utils
from volttron.platform.agent.base_aggregate_historian import AggregateHistorian
from volttron.platform.dbutils import mongoutils
utils.setup_logging(logging.DEBUG)
_log = logging.getLogger(__name__)
__version__ = '1.0'
class MongodbAggregateHistorian(AggregateHistorian):
"""
Agent to aggregate data in historian based on a specific time period.
This aggregegate historian aggregates data collected by mongo historian.
"""
def __init__(self, config_path, **kwargs):
"""
Validate configuration, create connection to historian, create
aggregate tables if necessary and set up a periodic call to
aggregate data
示例15: passiveafdd
def passiveafdd(config_path, **kwargs):
'''Passive fault detection application for AHU/RTU economizer systems'''
config = utils.load_config(config_path)
rtu_path = dict((key, config[key])
for key in ['campus', 'building', 'unit'])
utils.setup_logging()
_log = logging.getLogger(__name__)
logging.basicConfig(level=logging.debug,
format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%m-%d-%y %H:%M:%S')
class Agent(PublishMixin, BaseAgent):
def __init__(self, **kwargs):
'''Input and initialize user configurable parameters.'''
super(Agent, self).__init__(**kwargs)
# Agent Configuration parameters
self.agent_id = config.get('agentid')
self.aggregate_data = int(config.get("aggregate_data", 1))
self.matemp_missing = int(config.get("matemp_missing"))
# Temperature sensor diagnostic thresholds
self.mat_low = float(config.get("mat_low", 50.0))
self.mat_high = float(config.get("mat_high", 90.0))
self.oat_low = float(config.get("oat_low", 30.0))
self.oat_high = float(config.get("oat_high", 120.0))
self.rat_low = float(config.get("rat_low", 50.0))
self.rat_high = float(config.get("rat_high", 90.0))
self.temp_sensor_threshold = (
float(config.get("temp_sensor_threshold", 5.0)))
self.temp_deadband = config.get('temp_deadband', 2.5)
# Economizer diagnostic thresholds and parameters
self.high_limit = float(config.get("high_limit", 60.0))
self.economizer_type = int(config.get("economizer_type", 0))
self.damper_minimum = float(config.get("damper_minimum", 15.0))
self.minimum_oa = float(config.get("minimum_oa", 0.1))
self.oae2_damper_threshold = (
float(config.get("oae2_damper_threshold", 30.0)))
self.oae2_oaf_threshold = \
float(config.get("oae2_oaf_threshold", 0.25))
self.oae4_oaf_threshold = \
float(config.get("oae4_oaf_threshold", 0.25))
self.oae5_oaf_threshold = \
float(config.get("oae5_oaf_threshold", 0))
self.damper_deadband = config.get('damper_deadband', 10.0)
# RTU rated parameters (e.g., capacity)
self.eer = float(config.get("EER", 10))
tonnage = float(config.get("tonnage"))
if tonnage:
self.cfm = 300*tonnage
self.csv_input = int(config["csv_input"])
# Point names for input file (CSV) or BACnet config
self.timestamp_name = config.get('timestamp_name')
self.input_file = config.get('input_file', 'CONFIG_ERROR')
self.oat_name = config.get('oat_point_name')
self.rat_name = config.get('rat_point_name')
self.mat_name = config.get('mat_point_name')
self.fan_status_name = config.get('fan_status_point_name')
self.cool_cmd_name = config.get('cool_cmd_name')
self.heat_cmd_name = config.get('heat_cmd_name')
self.damper_name = config.get('damper_point_name')
# Misc. data configuration parameters
self.sampling_rate = config.get('sampling_rate')
self.mat_missing = config.get('mixed_air_sensor_missing')
# Device occupancy schedule
sunday = config.get('Sunday')
monday = config.get('Monday')
tuesday = config.get('Tuesday')
wednesday = config.get('Wednesday')
thursday = config.get('Thursday')
friday = config.get('Friday')
saturday = config.get('Saturday')
self.schedule_dict = dict({0: sunday, 1: monday, 2: tuesday,
3: wednesday, 4: thursday, 5: friday,
6: saturday})
# Initialize raw data arrays used during data aggregation
self.oaf_raw = []
self.timestamp_raw = []
self.matemp_raw = []
self.oatemp_raw = []
self.ratemp_raw = []
self.cooling_raw = []
self.heating_raw = []
self.damper_raw = []
self.fan_status_raw = []
# Initialize final data arrays used during diagnostics
self.oaf = []
self.timestamp = []
self.matemp = []
self.oatemp = []
self.ratemp = []
self.cooling = []
self.heating = []
self.damper = []
self.fan_status = []
self.run_aggregate = None
self.names = [config.get('oat_point_name'),
config.get('mat_point_name'),
config.get('dat_point_name'),
config.get('rat_point_name'),
config.get('damper_point_name'),
#.........这里部分代码省略.........