예제 #1
0
    def configure(self, config_name, action, contents):
        """
        Called after the Agent has connected to the message bus. If a configuration exists at startup
        this will be called before onstart.

        Is called every time the configuration in the store changes.
        """
        config = self.default_config.copy()
        config.update(contents)

        _log.debug("Configuring Agent")

        try:
            period = int(config["period"])
            points = config["points"]
        except ValueError as e:
            _log.error("ERROR PROCESSING CONFIGURATION: {}".format(e))
            return

        self.period = period
        self.points = points

        if self.periodic is not None:
            self.periodic.cancel()

        self.periodic = self.core.schedule(periodic(self.period),
                                           self.process_points)
예제 #2
0
class NodeRedSubscriber(Agent):

    def onmessage(self, peer, sender, bus, topic, headers, message):
        d = {'topic': topic,
             'headers': headers,
             'message': message}
        sys.stdout.write(jsonapi.dumps(d)+'\n')
        sys.stdout.flush()

    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        for prefix in topic_prefixes_to_watch:
            self.vip.pubsub.subscribe(peer='pubsub', prefix=prefix, callback=self.onmessage).get(timeout=10)

    # Demonstrate periodic decorator and settings access
    @Core.schedule(periodic(heartbeat_period))
    def publish_heartbeat(self):
        now = utils.format_timestamp(datetime.utcnow())
        headers = {
            headers_mod.CONTENT_TYPE: headers_mod.CONTENT_TYPE.PLAIN_TEXT,
            headers_mod.DATE: now,
            headers_mod.TIMESTAMP: now
        }
        result = self.vip.pubsub.publish('pubsub', 'heartbeat/NodeRedSubscriber', headers, now)
        result.get(timeout=10)
예제 #3
0
파일: agent.py 프로젝트: tpktang/volttron
    def _configure(self, config_name, action, contents):
        config = self.default_config.copy()
        config.update(contents)

        _log.debug("Configuring External Data agent")

        global_topic_prefix = config.get('global_topic_prefix', "")

        self.sources = self._validate_sources(config.get("sources", []), global_topic_prefix)

        self.topic = PUBLISH_TOPIC(base=global_topic_prefix, source=None, key=None)

        self.default_user = config.get('default_user')
        self.default_password = config.get('default_password')

        try:
            interval = float(config.get("interval", 300.0))
        except ValueError:
            _log.error("Error setting scrape interval, reverting to default of 300 seconds")
            interval = 300.0

        if self.periodic is not None:
            self.periodic.cancel()

        self.periodic = self.core.schedule(periodic(interval), self._publish_data)
예제 #4
0
파일: agent.py 프로젝트: Kisensum/volttron
    def configure(self, config_name, action, contents):
        """
        Called after the Agent has connected to the message bus. If a configuration exists at startup
        this will be called before onstart.

        Is called every time the configuration in the store changes.
        """
        config = self.default_config.copy()
        config.update(contents)

        _log.debug("Configuring Agent")

        try:
            period = int(config["period"])
            points = config["points"]
        except ValueError as e:
            _log.error("ERROR PROCESSING CONFIGURATION: {}".format(e))
            return

        self.period = period
        self.points = points

        if self.periodic is not None:
            self.periodic.cancel()

        self.periodic = self.core.schedule(periodic(self.period), self.process_points)
예제 #5
0
 def setup(self, sender, **kwargs):
     self.vip.rpc.export(self.foo)
     self.vip.rpc.export(self.baz, 'bar')
     self.vip.rpc.export(meh)
     self.vip.pubsub.add_bus('')
     self.core.onfinish.connect(self.finish)
     self.core.schedule(periodic(5), self.saybye)
예제 #6
0
파일: agent.py 프로젝트: Kisensum/volttron
    def _configure(self, config_name, action, contents):
        config = self.default_config.copy()
        config.update(contents)

        _log.debug("Configuring External Data agent")

        global_topic_prefix = config.get('global_topic_prefix', "")

        self.sources = self._validate_sources(config.get("sources", []), global_topic_prefix)

        self.topic = PUBLISH_TOPIC(base=global_topic_prefix,
                                  source=None,
                                  key=None)

        self.default_user = config.get('default_user')
        self.default_password = config.get('default_password')

        try:
            interval = float(config.get("interval", 300.0))
        except ValueError:
            _log.error("Error setting scrape interval, reverting to default of 300 seconds")
            interval = 300.0

        if self.periodic is not None:
            self.periodic.cancel()

        self.periodic = self.core.schedule(periodic(interval), self._publish_data)
예제 #7
0
 def setup(self, sender, **kwargs):
     self.vip.rpc.export(self.foo)
     self.vip.rpc.export(self.baz, 'bar')
     self.vip.rpc.export(meh)
     self.vip.pubsub.add_bus('')
     self.core.onfinish.connect(self.finish)
     self.core.schedule(periodic(5), self.saybye)
예제 #8
0
 def starting_mongo(self, sender, **kwargs):
     _log.debug("In on start method. scheduling periodic call to rollup "
                "data")
     if not self._readonly:
         delay = timedelta(seconds=self.periodic_rollup_initial_wait)
         self.core.schedule(periodic(self.periodic_rollup_frequency,
                                     start=delay),
                            self.periodic_rollup)
예제 #9
0
    def start(self):
        """RPC method

        Starts an agent's heartbeat.
        """
        if not self.enabled:
            self.scheduled = self.core().schedule(periodic(self.period), self.publish)
            self.enabled = True
예제 #10
0
 def starting_mongo(self, sender, **kwargs):
     _log.debug("In on start method. scheduling periodic call to rollup "
                "data")
     if not self._readonly:
         delay = timedelta(seconds=self.periodic_rollup_initial_wait)
         self.core.schedule(periodic(self.periodic_rollup_frequency,
                                     start=delay),
                            self.periodic_rollup)
예제 #11
0
파일: agent.py 프로젝트: VOLTTRON/volttron
 def _periodic_pub(self, func, period):
     """Periodically call func and publish its return value"""
     def pub_wrapper():
         data = func()
         topic = self.base_topic + '/' + func.__name__
         self.vip.pubsub.publish(peer='pubsub', topic=topic, message=data)
     sched = self.core.schedule(periodic(period), pub_wrapper)
     self._scheduled.append(sched)
예제 #12
0
파일: agent.py 프로젝트: tpktang/volttron
    def restart_greenlet(self):
        if self.scheduled_update is not None:
            self.scheduled_update.cancel()
            self.scheduled_update = None

        # Don't start (or restart) the greenlet if we haven't processed the registry config
        # or there are no registers processed.
        if self.registers:
            self.scheduled_update = self.core.schedule(periodic(self.check_interval*60), self.update)
예제 #13
0
파일: agent.py 프로젝트: Kisensum/volttron
 def _periodic_pub(self, func, period):
     """Periodically call func and publish its return value"""
     def pub_wrapper():
         data = func()
         topic = self.base_topic + '/' + func.__name__
         self.vip.pubsub.publish(peer='pubsub', topic=topic,
                                 message=data)
     sched = self.core.schedule(periodic(period), pub_wrapper)
     self._scheduled.append(sched)
예제 #14
0
파일: agent.py 프로젝트: tpktang/volttron
    def onstart_method(self, sender):
        """The agent has started. Perform initialization and spawn the main process loop."""
        _log.debug('Starting agent')

        # Subscribe to the VENAgent's event and report parameter publications.
        self.vip.pubsub.subscribe(peer='pubsub', prefix=topics.OPENADR_EVENT, callback=self.receive_event)
        self.vip.pubsub.subscribe(peer='pubsub', prefix=topics.OPENADR_STATUS, callback=self.receive_status)

        self.core.schedule(periodic(self.report_interval_secs), self.issue_rpcs)
예제 #15
0
파일: agent.py 프로젝트: Kisensum/volttron
    def restart_greenlet(self):
        if self.scheduled_update is not None:
            self.scheduled_update.cancel()
            self.scheduled_update = None

        # Don't start (or restart) the greenlet if we haven't processed the registry config
        # or there are no registers processed.
        if self.registers:
            self.scheduled_update = self.core.schedule(periodic(self.check_interval*60), self.update)
예제 #16
0
    def onstart(self, sender, **kwargs):
        # Start an agent to send heartbeats to the other failover instance
        self.heartbeat = self.build_connection()

        connected = self.heartbeat.is_connected()
        _log.debug("is connected to remote instance: {}".format(connected))

        def heartbeat():
            try:
                self.heartbeat.publish('heartbeat/{}'.format(self.agent_id))
                self.last_connected = self.timestamp()
            except Unreachable:
                if self.timestamp() < self.last_connected + self.timeout:
                    _log.debug("Attempting reconnect to remote instance")
                    self.heartbeat.kill()
                    self.heartbeat = self.build_connection()
                    self.last_connected = self.timestamp()

        self.core.schedule(periodic(self.heartbeat_period), heartbeat)
        self.core.schedule(periodic(1), self.check_pulse)
예제 #17
0
파일: agent.py 프로젝트: Kisensum/volttron
    def onstart(self, sender, **kwargs):
        # Start an agent to send heartbeats to the other failover instance
        self.heartbeat = self.build_connection()

        connected = self.heartbeat.is_connected()
        _log.debug("is connected to remote instance: {}".format(connected))

        def heartbeat():
            try:
                self.heartbeat.publish('heartbeat/{}'.format(self.agent_id))
                self.last_connected = self.timestamp()
            except Unreachable:
                if self.timestamp() < self.last_connected + self.timeout:
                    _log.debug("Attempting reconnect to remote instance")
                    self.heartbeat.kill()
                    self.heartbeat = self.build_connection()
                    self.last_connected = self.timestamp()

        self.core.schedule(periodic(self.heartbeat_period), heartbeat)
        self.core.schedule(periodic(1), self.check_pulse)
예제 #18
0
파일: agent.py 프로젝트: Kisensum/volttron
 def onstart_method(self, sender):
     """The test agent has started. Perform initialization and spawn the main process loop."""
     _log.debug('Starting MesaTestAgent')
     if self.point_config:
         # This test agent can configure the points itself, or (by default) it can rely on the DNP3 driver to do it.
         _log.debug('Sending DNP3 point map: {}'.format(self.point_config))
         self.send_rpc('config_points', self.point_config)
     # Subscribe to the MesaAgent's point, function, and outstation_status publications.
     self.vip.pubsub.subscribe(peer='pubsub', prefix=self.point_topic, callback=self.receive_point_value)
     self.vip.pubsub.subscribe(peer='pubsub', prefix=self.function_topic, callback=self.receive_function)
     self.vip.pubsub.subscribe(peer='pubsub', prefix=self.outstation_status_topic, callback=self.receive_status)
     self.core.schedule(periodic(RPC_INTERVAL_SECS), self.issue_rpcs)
예제 #19
0
class ExampleAgent(Agent):
    @Core.receiver('onsetup')
    def setup(self, sender, **kwargs):
        self.vip.rpc.export(self.foo)
        self.vip.rpc.export(self.baz, 'bar')
        self.vip.rpc.export(meh)
        self.vip.pubsub.add_bus('')
        self.core.onfinish.connect(self.finish)
        self.core.schedule(periodic(5), self.saybye)

    @Core.receiver('onstart')
    def starting(self, sender, **kwargs):
        print('agent starting')
        _, _, my_id = self.vip.hello().get(timeout=3)
        print('I am', my_id)
        self.vip.pubsub.subscribe(my_id, 'this/topic', self.onmessage)

    def onmessage(self, peer, sender, bus, topic, headers, message):
        print(
            'received: peer=%r, sender=%r, bus=%r, topic=%r, headers=%r, message=%r'
            % (peer, sender, bus, topic, headers, message))

    @Core.receiver('onstop')
    def stopping(self, sender, **kwargs):
        print('agent stopping')

    def finish(self, sender, **kwargs):
        print('agent finished')

    @Core.schedule(periodic(3))
    def sayhi(self):
        print('hello')

    def saybye(self):
        print('bye')

    @RPC.export
    def hello(self, name):
        return 'Hello, %s!' % (name, )

    @RPC.export('bye')
    def goodbye(self, name):
        return 'Bye, %s!' % (name, )

    def foo(self):
        return 'foo'

    def baz(self):
        return 'baz'
예제 #20
0
 def onstart_method(self, sender):
     """The test agent has started. Perform initialization and spawn the main process loop."""
     _log.debug('Starting MesaTestAgent')
     if self.point_config:
         # This test agent can configure the points itself, or (by default) it can rely on the DNP3 driver to do it.
         _log.debug('Sending DNP3 point map: {}'.format(self.point_config))
         self.send_rpc('config_points', self.point_config)
     # Subscribe to the MesaAgent's point, function, and outstation_status publications.
     self.vip.pubsub.subscribe(peer='pubsub',
                               prefix=self.point_topic,
                               callback=self.receive_point_value)
     self.vip.pubsub.subscribe(peer='pubsub',
                               prefix=self.function_topic,
                               callback=self.receive_function)
     self.vip.pubsub.subscribe(peer='pubsub',
                               prefix=self.outstation_status_topic,
                               callback=self.receive_status)
     self.core.schedule(periodic(RPC_INTERVAL_SECS), self.issue_rpcs)
예제 #21
0
class StandAloneWithAuth(Agent):
    ''' A standalone agent that demonstrates how to use agent authorization'''

    # Demonstrate calling methods via RPC
    @Core.schedule(periodic(heartbeat_period))
    def call_foo_and_bar(self):
        foo_result = self.vip.rpc.call(IDENTITY, 'foo').get(timeout=5)
        sys.stdout.write('foo returned: {}\n'.format(foo_result))
        bar_result = self.vip.rpc.call(IDENTITY, 'bar').get(timeout=5)
        sys.stdout.write('bar returned: {}\n'.format(bar_result))

    @RPC.export
    def foo(self):
        return 'Anybody can call this function via RPC'

    @RPC.export
    @RPC.allow('can_call_bar')
    def bar(self):
        return 'If you can see this, then you have the required capabilities'
예제 #22
0
파일: agent.py 프로젝트: tpktang/volttron
class CAgent(Agent):
    def __init__(self, config_path, **kwargs):
        super(CAgent, self).__init__(**kwargs)

        so_filename = __file__.rsplit('/', 1)[0] + '/' + 'libfoo.so'

        cdll.LoadLibrary(so_filename)
        self.shared_object = CDLL(so_filename)

        self.get_water_temperature = self.shared_object.get_water_temperature
        self.get_water_temperature.restype = c_float

    @Core.schedule(periodic(PUBLISH_PERIOD))
    def publish_water_temperature(self):
        """Call the function from the shared object.
        """
        wt = self.get_water_temperature()
        _log.debug(wt)
        self.vip.pubsub.publish('pubsub', 'device/WATER_TEMP=' + str(wt))
예제 #23
0
class StandAloneListener(Agent):
    ''' A standalone version of the ListenerAgent'''
    def onmessage(self, peer, sender, bus, topic, headers, message):
        '''Handle incoming messages on the bus.'''
        d = {'topic': topic, 'headers': headers, 'message': message}
        sys.stdout.write(jsonapi.dumps(d) + '\n')

    @Core.receiver('onstart')
    def start(self, sender, **kwargs):
        '''Handle the starting of the agent.
        
        Subscribe to all points in the topics_prefix_to_watch tuple
        defined in settings.py.
        '''

        for prefix in topics_prefixes_to_watch:
            sys.stdout.write('connecting to prefix: {}\n'.format(prefix))
            self.vip.pubsub.subscribe(peer='pubsub',
                                      prefix=prefix,
                                      callback=self.onmessage).get(timeout=5)

    # Demonstrate periodic decorator and settings access
    @Core.schedule(periodic(heartbeat_period))
    def publish_heartbeat(self):
        '''Send heartbeat message every heartbeat_period seconds.

        heartbeat_period is set and can be adjusted in the settings module.
        '''
        sys.stdout.write('publishing heartbeat.\n')
        now = utils.format_timestamp(datetime.utcnow())
        headers = {
            #'AgentID': self._agent_id,
            headers_mod.CONTENT_TYPE:
            headers_mod.CONTENT_TYPE.PLAIN_TEXT,
            headers_mod.DATE:
            now,
            headers_mod.TIMESTAMP:
            now
        }
        self.vip.pubsub.publish('pubsub', 'heartbeat/standalonelistener',
                                headers, now).get(timeout=5)
예제 #24
0
 def setup(self, sender, **kwargs):
 
     '****** Reading the config file and build the URL  *****'
                
     agent_id = self.config['agentid']
     poll_time = self.config['poll_time']
     state=self.config['state']
     city=self.config['city']
     zip_code = self.config["zip"]
     
     base = "http://api.wunderground.com/api/" +  settings.KEY
     self.requestUrl_conditions = base + "/conditions/q/"+zip_code + ".json"
     self.requestUrl_forecast = base + "/hourly/q/"+ state + "/" +city + ".json"
     
     now = datetime.datetime.now()
     self.hour=now.hour
     self.request_forecast=self.config['request_forecast']
     self.request_conditions=self.config['request_conditions']
     self.init=True
     
     self.data_path_base=self.config['database']
                   
     
     '*****   Start data acquisition   *********'
     
     if self.init and self.request_forecast :
         self.init=False
         self.weather_forecast() 
     
     if (poll_time < 180) or (poll_time % 60 !=0):
         _log.debug("Invalid poll_time : Too low or non minute expressed")
     else:
         now=datetime.datetime.now()
         _log.debug("Waiting to start querying the data... ")  #If poll_time = 5min, wait until appropriate time stamp (up to 4min59s!)
         while (now.minute % (poll_time/60) != 0):
             now=datetime.datetime.now()
         _log.debug("... Start periodic URL Request")   
         self.weather = self.core.schedule(periodic(poll_time),self.weather_conditions)
예제 #25
0
파일: agent.py 프로젝트: TPponmat/Agent
class Plugagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    def getstatus_proc(self, devices):  # Function for MultiProcess

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS

        _log.info(msg="Start Get Status from {}".format(devices[1]))

        try:
            plug = api.API(model='TPlinkPlug',
                           api='API3',
                           agent_id='TPlinkPlugAgent',
                           types='plug',
                           ip=devices[1],
                           port=9999)

            plug.getDeviceStatus()

            # TODO : Update Firebase with _status variable
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('DT').set(
                    datetime.now().replace(microsecond=0).isoformat())
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('STATUS').set(plug.variables['status'])
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('POWER').set(plug.variables['power'])
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('CURRENT').set(plug.variables['current'])
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('VOLTAGE').set(plug.variables['voltage'])
            db.child(gateway_id).child('devicetype').child('plug').child(
                devices[0]).child('TIMESTAMP').set(
                    datetime.now().replace(microsecond=0).isoformat())

        except Exception as err:
            pass

    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(open(self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):

        # TODO :  Start Server Listener Here

        pass

    # -- Direct Control From Web Application
    @PubSub.subscribe('pubsub', "web/control/plug")
    def on_match_sendcommand(self, peer, sender, bus, topic, headers, message):

        _log.info("Get Message : {}".format(message))
        msg = message

        # print(msg)
        device_id = msg.get('device_id')
        command = msg.get('command')

        print(device_id)
        print(command)

        print("----------------------------------------------")
        device_info = self.members.get(device_id)

        self.plug = api.API(model='TPlinkPlug',
                            api='API3',
                            agent_id='TPlinkPlugAgent',
                            types='plug',
                            ip=device_info,
                            port=9999)

        # self.plug.getDeviceStatus()
        self.plug.setDeviceStatus(msg)
        # self.plug.getDeviceStatus()
        del self.plug

    @Core.schedule(periodic(60))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            # proc = Process(target=self.getstatus_proc, args=(devices,))
            # procs.append(proc)
            # proc.start()

            #  --- Change Multiprocess to async function
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self.getstatus_proc(devices=devices))
예제 #26
0
파일: agent.py 프로젝트: tpktang/volttron
class AlertAgent(Agent):
    def __init__(self, config_path, **kwargs):
        super(AlertAgent, self).__init__(**kwargs)
        self.config = utils.load_config(config_path)
        self.group_instances = {}
        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

    @property
    def remote_agent(self):
        if self._remote_agent is None:
            if not self._creating_agent:
                self._creating_agent = True
                try:
                    # Single method to connect to remote instance in following combinations
                    # zmq -> zmq
                    # rmq -> rmq enabled with web
                    # zmq -> zmq enabled with web
                    # rmq -> zmq enabled with web
                    value = self.vip.auth.connect_remote_platform(
                        self.remote_address, serverkey=self.remote_serverkey)

                    if isinstance(value, Agent):
                        self._remote_agent = value
                        self._remote_agent.vip.ping("").get(timeout=2)
                        self.vip.health.set_status(STATUS_GOOD)
                    else:
                        _log.error("Exception creation remote agent")
                        status_context = "Couldn't connect to remote platform at: {}".format(
                            self.remote_address)
                        _log.error(status_context)
                        self._remote_agent = None
                except (gevent.Timeout, ZMQError):
                    _log.error("Exception creation remote agent")
                    status_context = "Couldn't connect to remote platform at: {}".format(
                        self.remote_address)
                    _log.error(status_context)
                    self._remote_agent = None
                    self.vip.health.set_status(STATUS_BAD, status_context)
                finally:
                    self._creating_agent = False
        return self._remote_agent

    def reset_remote_agent(self):
        if not self._resetting_remote_agent and not self._creating_agent:
            if self._remote_agent is not None:
                self._remote_agent.core.stop()
            self._remote_agent = None
            self._resetting_remote_agent = False

    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        """
        Setup database tables for persistent logs
        """
        db_dir = os.getcwd()
        data_dir = ""
        if utils.is_secure_mode():
            for d in os.listdir(os.path.basename(os.getcwd())):
                if d.endswith(".agent-data"):
                    data_dir = d
                    break
            if data_dir:
                db_dir = os.path.join(os.getcwd(), data_dir)

        self._connection = sqlite3.connect(
            os.path.join(db_dir, 'alert_log.sqlite'),
            detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
        c = self._connection.cursor()

        c.execute("CREATE TABLE IF NOT EXISTS topic_log( "
                  "topic TEXT, "
                  "last_seen_before_timeout TIMESTAMP, "
                  "first_seen_after_timeout TIMESTAMP,"
                  "PRIMARY KEY(topic, last_seen_before_timeout))")

        c.execute("CREATE INDEX IF NOT EXISTS topic_index ON "
                  "topic_log (topic)")
        c.execute("CREATE INDEX IF NOT EXISTS down_time_index ON "
                  "topic_log (last_seen_before_timeout)")
        c.execute("CREATE INDEX IF NOT EXISTS up_time_index ON "
                  "topic_log (first_seen_after_timeout)")

        c.execute("CREATE TABLE IF NOT EXISTS agent_log ("
                  "start_time TIMESTAMP, "
                  "stop_time TIMESTAMP)")
        c.execute("CREATE INDEX IF NOT EXISTS stop_ts_index ON "
                  "agent_log (stop_time)")
        c.execute("INSERT INTO agent_log(start_time) values(?)",
                  (get_aware_utc_now(), ))
        c.close()
        self._connection.commit()

        for group_name, config in self.config.items():
            if group_name != 'publish-settings':
                self.group_instances[group_name] = self.create_alert_group(
                    group_name, config)

    def create_alert_group(self, group_name, config):
        group = AlertGroup(group_name,
                           config,
                           self._connection,
                           main_agent=self,
                           publish_local=self.publish_local,
                           publish_remote=self.publish_remote)

        return group

    @Core.receiver('onstop')
    def onstop(self, sender, **kwargs):
        c = self._connection.cursor()
        c.execute(
            "UPDATE agent_log set stop_time = ? "
            " WHERE start_time = (SELECT max(start_time) from agent_log)",
            (get_aware_utc_now(), ))
        c.close()
        gevent.sleep(0.1)
        self._connection.commit()
        self._connection.close()

    @RPC.export
    def watch_topic(self, group, topic, timeout):
        """RPC method

        Listen for a topic to be published within a given
        number of seconds or send alerts. If the given group is new
        creates and starts an instance of AlertGroup agent for the new group.
        The alert group agent, onstart, will start watching for the given
        topics

        :pararm group: Group that should watch the topic.
        :type group: str
        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        """
        if self.group_instances.get(group) is None:
            self.group_instances[group] = self.create_alert_group(
                group, {topic: timeout})
        else:
            self.group_instances[group].watch_topic(topic, timeout)
            self.group_instances[group].restart_timer()

    @RPC.export
    def watch_device(self, group, topic, timeout, points):
        """RPC method

        Watch a device's ALL topic and expect points. If the given group is new
        creates and starts an instance of group agent for the new group. The
        group onstart will start watching for the given device points

        :pararm group: Group that should watch the device.
        :type group: str
        :param topic: Topic expected to be published.
        :type topic: str
        :param timeout: Seconds before an alert is sent.
        :type timeout: int
        :param points: Points to expect in the publish message.
        :type points: [str]
        """
        if self.group_instances.get(group) is None:
            self.group_instances[group] = self.create_alert_group(
                group, {topic: {
                    "seconds": timeout,
                    "points": points
                }})
        else:
            self.group_instances[group].watch_device(topic, timeout, points)
            self.group_instances[group].restart_timer()

    @RPC.export
    def ignore_topic(self, group, topic):
        """RPC method

        Remove a topic from agent's watch list. Alerts will no
        longer be sent if a topic stops being published.

        :param group: Group that should ignore the topic.
        :type group: str
        :param topic: Topic to remove from the watch list.
        :type topic: str
        """
        group = self.group_instances[group]
        group.ignore_topic(topic)

    @Core.schedule(periodic(1))
    def decrement_ttl(self):
        """Periodic call

        Used to maintain the time since each topic's last publish.
        Sends an alert if any topics are missing.
        """

        # Loop through each alert group
        for name in self.group_instances:

            topics_timedout = set()
            alert_topics = set()

            # Loop through topics in alert group
            for topic in self.group_instances[name].wait_time.keys():

                # Send an alert if a topic hasn't been
                self.group_instances[name].topic_ttl[topic] -= 1
                if self.group_instances[name].topic_ttl[topic] <= 0:
                    alert_topics.add(topic)
                    self.group_instances[name].topic_ttl[
                        topic] = self.group_instances[name].wait_time[topic]
                    if topic not in self.group_instances[name].unseen_topics:
                        topics_timedout.add(topic)
                        self.group_instances[name].unseen_topics.add(topic)

                # Send an alert if a point hasn't been seen
                try:
                    points = self.group_instances[name].point_ttl[topic].keys()
                    for p in points:
                        self.group_instances[name].point_ttl[topic][p] -= 1
                        if self.group_instances[name].point_ttl[topic][p] <= 0:
                            self.group_instances[name].point_ttl[topic][
                                p] = self.group_instances[name].wait_time[
                                    topic]
                            alert_topics.add((topic, p))
                            if (
                                    topic, p
                            ) not in self.group_instances[name].unseen_topics:
                                topics_timedout.add((topic, p))
                                self.group_instances[name].unseen_topics.add(
                                    (topic, p))
                except KeyError:
                    pass

            if alert_topics:
                try:
                    self.group_instances[name].send_alert(list(alert_topics))
                except ZMQError:
                    self.group_instances[name].main_agent.reset_remote_agent()

            if topics_timedout:
                self.group_instances[name].log_timeout(list(topics_timedout))
예제 #27
0
class Wiscotelnetagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    async def getstatus_proc(self, devices):  # Function for Asyncronous

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS
        _log.info(msg="Start Get Status from {}".format(devices[1]))
        loop = asyncio.get_event_loop()

        def getstatus_task(devices):

            try:
                wisco = api.API(model='Wisco',
                                api='API3',
                                agent_id='27WIS010101',
                                types='sensor',
                                ip=(devices[1])['ip'],
                                port=(devices[1])['port'])

                wisco.getDeviceStatus()

                # TODO : Update Firebase with _status variable
                db.child(gateway_id).child('devicetype').child(
                    'weatherstation').child(devices[0]).child('DT').set(
                        datetime.now().replace(microsecond=0).isoformat())
                db.child(gateway_id).child('devicetype').child(
                    'weatherstation').child(
                        devices[0]).child('MODULETEMP').set(
                            wisco.variables['moduletemp'])

            except Exception as err:
                pass

        try:
            loop.run_in_executor(None, getstatus_task, devices)
            # response1 = await future1
            loop.close()
            res = await loop

        except Exception as e:
            pass

    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(
            open(os.environ['VOLTTRON_ROOT'] + self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):

        # TODO :  Start Server Listener Here

        pass

    @Core.schedule(periodic(60))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            # proc = Process(target=self.getstatus_proc, args=(devices,))
            # procs.append(proc)
            # proc.start()

            #  --- Change Multiprocess to async function
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self.getstatus_proc(devices=devices))
예제 #28
0
class DDSAgent(Agent):
    def __init__(self, config_path, **kwargs):
        super(DDSAgent, self).__init__(**kwargs)

        self.reader = {}
        self.writer = {}

        config = utils.load_config(config_path)

        for typename, type_config in config.iteritems():
            participant_name = type_config['participant_name']
            xml_config_path = type_config['xml_config_path']
            publisher_name = type_config['publisher_name']
            subscriber_name = type_config['subscriber_name']
            connector = rti.Connector(participant_name, xml_config_path)

            self.writer[typename] = connector.getOutput(publisher_name)
            self.reader[typename] = connector.getInput(subscriber_name)

    @Core.schedule(periodic(1))
    def publish_demo(self):
        """
        Publish a square that follows a circular path.
        Can be visualized by running the *rtishapesdemo*
        program and subscribing to *square*.
        """

        sample = {"shapesize": 30, "color": "BLUE"}

        center = 100
        radius = 50
        now = datetime.datetime.now()
        radians = pi * float(now.second) / 15.0

        sample['x'] = center + int(radius * cos(radians))
        sample['y'] = center + int(radius * sin(radians))

        self.write_to_dds('square', sample)

    @RPC.export
    def read_from_dds(self, typename):
        """ RPC method

        Read samples from the DDS message bus.

        A data access method must be called before we can
        examine `samples` in the vernacular of DDS. This
        examples uses read(), which *does not* modify the
        reader's receive queue. The other option is take(),
        which *does* remove data from the receive queue.

        :param typename: Name of the type to read.
        :type typename: str
        :returns: samples available on the DDS message bus
        :rtype: list of dictionaries

        .. warning:: Attempting to read a type of **typename**
                     that was not in the config file will raise
                     KeyError.
        """

        reader = self.reader[typename]
        reader.read()

        # For this example we'll return all samples we can see
        samples = []

        # Find out how many samples we have so
        # they can be explicitly indexed
        n_samples = reader.samples.getLength()

        # Indexes start at one. Yuck.
        for i in range(1, n_samples + 1):
            if reader.infos.isValid(i):
                # Struct fields can be retrieved as a dict
                # or accessed individually. A dictionary
                # will be easier in most cases.
                d = reader.samples.getDictionary(i)
                samples.append(d)

        return samples

    @RPC.export
    def write_to_dds(self, typename, sample):
        """ RPC method

        Write sample to the DDS message bus.

        :param typename: Name of the type to write.
        :type typename: str
        :param sample: Data to write to DDS bus.
        :type sample: dict

        .. warning:: Attempting to write to a type of **typename**
                     that was not in the config file will raise
                     KeyError.
        """

        writer = self.writer[typename]
        writer.instance.setDictionary(sample)
        writer.write()
예제 #29
0
class Automation1agent(Agent):
    """
    Document agent constructor here.
    """

    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)

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):
        
        # TODO :  Start Server Listener Here

        pass

    @Core.schedule(periodic(600))
    def updatestatus(self):
        _log.info(msg="Check multisensor data from firebase")

        multi_temp = float(db.child(gateway_id).child('devicetype').child('multisensor').child('MS202001').child('TEMPERATURE').get().val())
        # print("multi_temp: {}".format(multi_temp))

        ac_status = db.child(gateway_id).child('devicetype').child('ac').child('AC202001').child('STATUS').get().val()
        # ac_status = db.child(gateway_id).child('devicetype').child('ac').child('AC101001').child('STATUS').get().val()
        # print("ac status: {}".format(ac_status))

        try:
            auto_time = datetime.strptime(db.child(gateway_id).child('time_automation1').get().val(), "%Y-%m-%dT%H:%M:%S")
            # print("time_now-try: {}".format(auto_time))

        except:
            auto_time = datetime.now()
            # print("time_now-except: {}".format(auto_time))
            pass

        time_now = datetime.now()
        # print("time_now: {}".format(time_now))
        duration = time_now - auto_time
        # print("diff time: {}".format(duration))
        duration_in_s = duration.total_seconds()
        # print("diff second: {}".format(duration_in_s))
        diff_min = divmod(duration_in_s, 60)[0]
        # print("diff min: {}".format(diff_min))

        if (multi_temp >= 25) and (ac_status == 'OFF'):
            self.daikin = api.API(model='daikin', type='AC', api='API', agent_id='ACAgent',
                                  url='http://192.168.10.238', port=502,
                                  parity='E', baudrate=9600,
                                  startregis=2006, startregisr=2012)

            self.daikin.setDeviceStatus({"status": "ON", "mode": "COLD", "stemp":"18"})
            # self.daikin.getDeviceStatus()
            del self.daikin
            db.child(gateway_id).child('time_automation1').set(datetime.now().replace(microsecond=0).isoformat())
            print("automation-on")

        elif (multi_temp < 25) and (diff_min >= 120) and (ac_status == 'ON'):
            self.daikin = api.API(model='daikin', type='AC', api='API', agent_id='ACAgent',
                                  url='http://192.168.10.238', port=502,
                                  parity='E', baudrate=9600,
                                  startregis=2006, startregisr=2012)

            self.daikin.setDeviceStatus({"status": "OFF"})
            # self.daikin.getDeviceStatus()
            del self.daikin
            print("automation-off")

        else:
            pass
예제 #30
0
 def start(self, sender):
     _log.debug("Starting Director for MarketServiceAgent")
     self.sender = sender
     self.sender.core.schedule(periodic(self.market_period), self._trigger)
예제 #31
0
파일: agent.py 프로젝트: Kisensum/volttron
 def onstart(self, sender, **kwargs):
     self.core.schedule(periodic(self.check_period), self.watch_agents)
예제 #32
0
class Invertertelnetagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    def getstatus_proc(self, devices):  # Function for MultiProcess

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS

        _log.info(msg="Start Get Status from {}".format(devices[1]))

        try:
            inverter = api.API(model = 'Growatt', api = 'API3', agent_id = '28INVIN202001', types = 'inverter',
                               ip=(devices[1])['ip'], port=(devices[1])['port'])

            inverter.getDeviceStatus()



            # TODO : Update Firebase with _status variable
            try:

                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('BATTERY_PERCENTAGE').set(inverter.variables['batt_percen'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('LOAD_ACTIVE_POWER').set(inverter.variables['load_act_P'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('PV_DAILY_POWER_GEN').set(inverter.variables['PV_daily_P_gen'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('PV_TOTAL_POWER_GEN').set(inverter.variables['PV_total_P_gen'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('DAILY_LOAD_CONSUMPTION').set(inverter.variables['daily_load_con'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('DAILY_POWER_INTAKE_FROM_GRID').set(inverter.variables['daily_P_intake_grid'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('TOTAL_POWER_INTAKE_FROM_GRID').set(inverter.variables['total_P_intake_grid'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('DAILY_POWER_FED_TO_GRID').set(inverter.variables['daily_P_fed_grid'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('TOTAL_POWER_FED_TO_GRID').set(inverter.variables['total_P_fed_grid'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('OUTPUT_POWER').set(inverter.variables['output_P'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('SOH').set(inverter.variables['SOH'])
                # db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('BMS_BATTERY_STATUS').set(inverter.variables['BMS_batt_status'])

                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('DT').set(datetime.now().replace(microsecond=0).isoformat())
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('BATTERY_POWER').set(inverter.variables['batt_P'])
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('PV_TOTAL_POWER').set(inverter.variables['PV_total_P'])

                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('batt_percen').set(inverter.variables['batt_percen'])
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('load_act_P').set(inverter.variables['load_act_P'])
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('PV_total_P').set(inverter.variables['PV_total_P'])
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('grid_P').set(inverter.variables['output_P'])
                db.child(gateway_id).child('devicetype').child('inverter').child(devices[0]).child('SOH').set(inverter.variables['SOH'])


            except Exception as err:
                print("ERROR firebase: {}".format(err))
                pass


        except Exception as err:
            pass


    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(open(os.environ['VOLTTRON_ROOT']+self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):
        # TODO :  Start Server Listener Here

        pass

    @Core.schedule(periodic(317))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            proc = Process(target=self.getstatus_proc, args=(devices,))
            procs.append(proc)
            proc.start()
예제 #33
0
    class ExampleSubscriber(Agent):
        '''
        This agent demonstrates usage of the 3.0 pubsub service as well as 
        interfacting with the historian. This agent is mostly self-contained, 
        but requires the historian to be running to demonstrate the query feature.
        '''
        def __init__(self, **kwargs):
            super(ExampleSubscriber, self).__init__(**kwargs)

        @Core.receiver('onsetup')
        def setup(self, sender, **kwargs):
            # Demonstrate accessing a value from the config file
            self._agent_id = config['agentid']

        @PubSub.subscribe('pubsub', all_topic)
        def match_device_all(self, peer, sender, bus, topic, headers, message):
            '''
            This method subscribes to all points under a device then pulls out 
            the specific point it needs.
            The first element of the list in message is a dictionairy of points 
            under the device. The second element is a dictionary of metadata for points.
            '''

            print("Whole message", message)

            #The time stamp is in the headers
            print('Date', headers['Date'])

            #Pull out the value for the point of interest
            print("Value", message[0]['OutsideAirTemperature'])

            #Pull out the metadata for the point
            print('Unit', message[1]['OutsideAirTemperature']['units'])
            print('Timezone', message[1]['OutsideAirTemperature']['tz'])
            print('Type', message[1]['OutsideAirTemperature']['type'])

        @PubSub.subscribe('pubsub', oat_point)
        def on_match_OAT(self, peer, sender, bus, topic, headers, message):
            '''
            This method subscribes to the specific point topic.
            For these topics, the value is the first element of the list 
            in message.
            '''

            print("Whole message", message)
            print('Date', headers['Date'])
            print("Value", message[0])
            print("Units", message[1]['units'])
            print("TimeZone", message[1]['tz'])
            print("Type", message[1]['type'])

        @PubSub.subscribe('pubsub', '')
        def on_match_all(self, peer, sender, bus, topic, headers, message):
            ''' This method subscibes to all topics. It simply prints out the 
            topic seen.
            '''

            print(topic)


#
# Demonstrate periodic decorator and settings access

        @Core.schedule(periodic(10))
        def lookup_data(self):
            '''
            This method demonstrates how to query the platform historian for data
            This will require that the historian is already running on the platform.
            '''

            try:

                result = self.vip.rpc.call(
                    #Send this message to the platform historian
                    #Using the reserved ID
                    'platform.historian',
                    #Call the query method on this agent
                    'query',
                    #query takes the keyword arguments of:
                    #topic, then optional: start, end, count, order
                    #                                            start= "2015-10-14T20:51:56",
                    topic=query_point,
                    count=20,
                    #RPC uses gevent and we must call .get(timeout=10)
                    #to make it fetch the result and tell
                    #us if there is an error
                    order="FIRST_TO_LAST").get(timeout=10)
                print('Query Result', result)
            except Exception as e:
                print("Could not contact historian. Is it running?")
                print(e)

        @Core.schedule(periodic(10))
        def pub_fake_data(self):
            ''' This method publishes fake data for use by the rest of the agent.
            The format mimics the format used by VOLTTRON drivers.
            
            This method can be removed if you have real data to work against.
            '''

            #Make some random readings
            oat_reading = random.uniform(30, 100)
            mixed_reading = oat_reading + random.uniform(-5, 5)
            damper_reading = random.uniform(0, 100)

            # Create a message for all points.
            all_message = [{
                'OutsideAirTemperature': oat_reading,
                'MixedAirTemperature': mixed_reading,
                'DamperSignal': damper_reading
            }, {
                'OutsideAirTemperature': {
                    'units': 'F',
                    'tz': 'UTC',
                    'type': 'float'
                },
                'MixedAirTemperature': {
                    'units': 'F',
                    'tz': 'UTC',
                    'type': 'float'
                },
                'DamperSignal': {
                    'units': '%',
                    'tz': 'UTC',
                    'type': 'float'
                }
            }]

            #Create messages for specific points
            oat_message = [
                oat_reading, {
                    'units': 'F',
                    'tz': 'UTC',
                    'type': 'float'
                }
            ]
            mixed_message = [
                mixed_reading, {
                    'units': 'F',
                    'tz': 'UTC',
                    'type': 'float'
                }
            ]
            damper_message = [
                damper_reading, {
                    'units': '%',
                    'tz': 'UTC',
                    'type': 'float'
                }
            ]

            #Create timestamp
            now = utils.format_timestamp(datetime.utcnow())
            headers = {headers_mod.DATE: now, headers_mod.TIMESTAMP: now}

            #Publish messages
            self.vip.pubsub.publish('pubsub', all_topic, headers, all_message)

            self.vip.pubsub.publish('pubsub', oat_point, headers, oat_message)

            self.vip.pubsub.publish('pubsub', mixed_point, headers,
                                    mixed_message)

            self.vip.pubsub.publish('pubsub', damper_point, headers,
                                    damper_message)
예제 #34
0
파일: agent.py 프로젝트: TPponmat/Agent
class ListenerAgent(Agent):
    """Listens to everything and publishes a heartbeat according to the
    heartbeat period specified in the settings module.
    """

    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.flag = None

        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


    @Core.receiver('onsetup')
    def onsetup(self, sender, **kwargs):
        # Demonstrate accessing a value from the config file
        _log.info(self.config.get('message', DEFAULT_MESSAGE))
        self._agent_id = self.config.get('agentid')



    @Core.receiver('onstart')
    def onstart(self, sender, **kwargs):
        self.flag = True

        # listener = threading.Thread(target=self.amqp_listener())
        # _log.debug("Start CloudAMQP Consume services ")
        # _log.info("Start Threading for Listener Services")
        # listener.daemon = True
        # listener.start()


        # listener = threading.Thread(target=self.amqp_listener)
        # # checker = threading.Thread(target=self.worker)
        #
        # _log.debug("Start CloudAMQP Consume services ")
        # _log.info("Start Threading for Listener Services")
        #
        #
        # listener.start()
        # checker.start()


    def worker(self):
        _log.info("Worker Thread")
        for i in range(1,100):
            print(i)
            time.sleep(1)


    def callback(self,ch, method, properties, body):
        # print("Got Message : {}".format(body))

        msg = dict(json.loads(body))
        topic = msg.get('topic', 'web/control/error')
        message = msg.get('body', {})

        _log.info(">> TOPIC : {}".format(topic))
        _log.info(">> COMMAND : {}".format(message))

        self.vip.pubsub.publish('pubsub', topic,
                                message=message
                                )


    def amqp_listener(self):

        try:

            _log.info(">>> : Thread Started")
            self.url_rabbitmq = os.environ.get('CLOUDAMQP_URL',
                                               'amqp://*****:*****@mustang.rmq.cloudamqp.com/zlfcmyqb')

            self.params = pika.URLParameters(self.url_rabbitmq)
            self.connection = pika.BlockingConnection(self.params)
            self.channel = self.connection.channel()  # start a channel
            self.channel.queue_declare(queue='pdfprocess')
            self.channel.basic_consume('pdfprocess', self.callback, auto_ack=True)
            self.channel.start_consuming()
            self.connection.close()


        except:
            _log.error("Services AMPQ Has a Problem")

    @Core.schedule(periodic(60))
    def on_interval(self):
        # Broadcast Message from UDP Server
        _log.info(msg=">>> : Is Listener Alive ?")
        if self.flag:
            self.flag = False
            self.listener = threading.Thread(target=self.amqp_listener)
            _log.debug("Start CloudAMQP Consume services ")
            _log.info("Start Threading for Listener Services")
            self.listener.start()

        if not self.flag:
            if self.listener.is_alive() is True:
                _log.info(msg="<<< : Listener Thread is Alive")
            else:
                self.flag = True
                del self.listener
예제 #35
0
파일: agent.py 프로젝트: TPponmat/Agent
class Aeotecagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    async def getstatus_proc(self, devices):  # Function for Asyncronous

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS
        _log.info(msg="Start Get Status from {}".format(devices[1]))
        loop = asyncio.get_event_loop()

        def getstatus_task(devices):

            try:
                multisensor = api.API(model='Sensor', types='illuminances', api='API3', agent_id='18ORC_OpenCloseAgent',
                                      url=(devices[1])['url'], bearer=(devices[1])['bearer'], device=(devices[1])['device'])

                multisensor.getDeviceStatus()

                # TODO : Update Firebase with _status variable
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('DT').set(multisensor.variables['unitTime'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('HUMIDITY').set(multisensor.variables['humidity'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('ILLUMINANCE').set(multisensor.variables['illuminance'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('MOTION').set(multisensor.variables['motion'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('TAMPER').set(multisensor.variables['tamper'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('TEMPERATURE').set(multisensor.variables['temperature'])
                db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('TIMESTAMP').set(datetime.now().replace(microsecond=0).isoformat())

            except Exception as err:
                pass

        try:
            loop.run_in_executor(None, getstatus_task, devices)
            # response1 = await future1

        except Exception as e:
            pass


    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(open(self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):
        
        # TODO :  Start Server Listener Here

        pass

    @Core.schedule(periodic(20))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            # proc = Process(target=self.getstatus_proc, args=(devices,))
            # procs.append(proc)
            # proc.start()

            #  --- Change Multiprocess to async function
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self.getstatus_proc(devices=devices))
예제 #36
0
 def start(self, sender):
     _log.debug("Starting Director for MarketServiceAgent")
     self.sender = sender
     self.sender.core.schedule(periodic(self.market_period), self._trigger)
예제 #37
0
class Daikinagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    async def getstatus_proc(self, devices):  # Function for Asyncronous

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS
        _log.info(msg="Start Get Status from {}".format(devices[1]))
        loop = asyncio.get_event_loop()

        def getstatus_task(devices):

            try:
                daikin = api.API(model='daikin',
                                 type='AC',
                                 api='API',
                                 agent_id='ACAgent',
                                 url=devices[1],
                                 port=502,
                                 parity='E',
                                 baudrate=9600,
                                 startregis=2006,
                                 startregisr=2012)

                daikin.getDeviceStatus()

                # TODO : Update Firebase with _status variable
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('DT').set(
                        datetime.now().replace(microsecond=0).isoformat())
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('STATUS').set(daikin.variables['status'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('MODE').set(daikin.variables['mode'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('FAN_SPEED').set(daikin.variables['fan'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('SET_TEMPERATURE').set(
                        daikin.variables['set_temperature'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('SET_HUMIDITY').set(
                        daikin.variables['set_humidity'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('TEMPERATURE').set(
                        daikin.variables['current_temperature'])
                db.child(gateway_id).child('devicetype').child('ac').child(
                    devices[0]).child('TIMESTAMP').set(
                        datetime.now().replace(microsecond=0).isoformat())

            except Exception as err:
                pass

        try:
            loop.run_in_executor(None, getstatus_task, devices)
            # response1 = await future1

        except Exception as e:
            pass

    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(open(self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):

        # TODO :  Start Server Listener Here

        pass

    @PubSub.subscribe('pubsub', 'web/control/ac')
    def on_match_sendcommand(self, peer, sender, bus, topic, headers, message):

        _log.info("Get Message : {}".format(message))
        msg = message
        # print(msg)
        device_id = msg.get('device_id')
        command = msg.get('command')

        print(device_id)
        print(command)
        print("----------------------------------------------")
        device_info = self.members.get(device_id)

        self.daikin = api.API(model='daikin',
                              type='AC',
                              api='API',
                              agent_id='ACAgent',
                              url=device_info,
                              port=502,
                              parity='E',
                              baudrate=9600,
                              startregis=2006,
                              startregisr=2012)

        # self.daikin.getDeviceStatus()
        self.daikin.setDeviceStatus(command)
        # self.daikin.getDeviceStatus()
        del self.daikin

    @Core.schedule(periodic(60))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            # proc = Process(target=self.getstatus_proc, args=(devices,))
            # procs.append(proc)
            # proc.start()

            #  --- Change Multiprocess to async function
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop = asyncio.get_event_loop()
            loop.run_until_complete(self.getstatus_proc(devices=devices))
예제 #38
0
파일: agent.py 프로젝트: TPponmat/Agent
class Invertertelnetagent(Agent):
    """
    Document agent constructor here.
    """

    # TODO -- Need Revise again
    def getstatus_proc(self, devices):  # Function for MultiProcess

        # Devices is tuple index 0 is Devices ID , 1 is IPADDRESS

        _log.info(msg="Start Get Status from {}".format(devices[1]))

        try:
            inverter = api.API(model='Growatt',
                               api='API3',
                               agent_id='28INVIN202001',
                               types='inverter',
                               ip=(devices[1])['ip'],
                               port=(devices[1])['port'])

            inverter.getDeviceStatus()

            # TODO : Update Firebase with _status variable
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('DT').set(multisensor.variables['unitTime'])
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('HUMIDITY').set(multisensor.variables['humidity'])
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('ILLUMINANCE').set(multisensor.variables['illuminance'])
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('MOTION').set(multisensor.variables['motion'])
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('TAMPER').set(multisensor.variables['tamper'])
            # db.child(gateway_id).child('devicetype').child('multisensor').child(devices[0]).child('TEMPERATURE').set(multisensor.variables['temperature'])

        except Exception as err:
            pass

    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(open(self.iplist_path))

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):

        # TODO :  Start Server Listener Here

        pass

    @Core.schedule(periodic(60))
    def updatestatus(self):
        _log.info(msg="Get Current Status")
        procs = []

        for k, v in self.members.items():
            devices = (k, v)
            proc = Process(target=self.getstatus_proc, args=(devices, ))
            procs.append(proc)
            proc.start()
예제 #39
0
파일: agent.py 프로젝트: Soulweed/Agent
class Interactlightingagent(Agent):
    """
    Document agent constructor here.
    """
    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.iplist_path = self.config.get('pathconf')
        self.members = json.load(
            open(os.environ['VOLTTRON_ROOT'] + self.iplist_path))
        self.access_token = None

        _log.debug("IP List : {}".format(self.members))

        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

    @Core.receiver("onstart")
    def onstart(self, sender, **kwargs):

        # TODO :  Start Server Listener Here

        pass

    # -- Direct Control From Web Application
    @PubSub.subscribe('pubsub', "web/control/lighting")
    def on_match_sendcommand(self, peer, sender, bus, topic, headers, message):

        _log.info("Get Message : {}".format(message))
        msg = message
        # print(msg)
        device_id = msg.get('device_id')
        if 'command' in msg.keys():
            command = json.loads(msg.get('command'))  # {status: ON}
        elif 'status' in msg.keys():
            command = {"status": msg.get('status')}
        else:
            command = {}
        print(device_id)
        print(command)
        print("----------------------------------------------")
        device_info = self.members.get(device_id)

        try:
            self.interact = api.API(model='Interact',
                                    api='API3',
                                    agent_id='25INTF73D39F6',
                                    types='lighting',
                                    uuid=device_info['uuid'])

            # self.plug.getDeviceStatus()
            self.interact.setDeviceStatus(command, self.access_token)
            # self.plug.getDeviceStatus()
        except Exception as err:
            pass

    @Core.schedule(periodic(3000))
    def on_interval(self):
        self.access_token = api.API().get_token()
        _log.info(msg="Access Token : {}".format(self.access_token))
예제 #40
0
 def onstart(self, sender, **kwargs):
     self.core.schedule(periodic(self.check_period), self.watch_agents)