Esempio n. 1
0
    def __init__(self, config):
        super().__init__(config)

        LOG.info('authenticating to neurio api')
        LOG.debug('key = {client_id}, secret = {client_secret}'.format(
            **(self.config)))

        tp = neurio.TokenProvider(key=self.config['client_id'],
                                  secret=self.config['client_secret'])
        self.nc = neurio.Client(token_provider=tp)
Esempio n. 2
0
 def update(self):
     """Get the Neurio monitor data from the web service."""
     import neurio
     try:
         neurio_tp = neurio.TokenProvider(
             key=self.api_key, secret=self.api_secret)
         neurio_client = neurio.Client(token_provider=neurio_tp)
         sample = neurio_client.get_samples_live_last(
             sensor_id=self.sensor_id)
         self._state = sample['consumptionPower']
     except (requests.exceptions.RequestException, ValueError):
         _LOGGER.warning('Could not update status for %s', self.name)
Esempio n. 3
0
    def __init__(self, api_key, api_secret, sensor_id):
        """Initialize the data."""
        self.api_key = api_key
        self.api_secret = api_secret
        self.sensor_id = sensor_id

        self._daily_usage = None
        self._active_power = None

        self._state = None

        neurio_tp = neurio.TokenProvider(key=api_key, secret=api_secret)
        self.neurio_client = neurio.Client(token_provider=neurio_tp)
Esempio n. 4
0
    def __init__(self, secret_file_name):
        config = ConfigParser.RawConfigParser()
        config.read(secret_file_name)

        tp = neurio.TokenProvider(key=config.get('auth','key'),
                                  secret=config.get('auth','secret'))
        sensor_id = config.get('device', 'id')
        nc = neurio.Client(token_provider=tp)

        # Wrap Neurio client with our Neurio class:
        self.__class__ = type(nc.__class__.__name__,
                              (self.__class__, nc.__class__),
                              {})
        self.__dict__ = nc.__dict__
        self.sensor_id = sensor_id
    def __init__(self, cfg, monitor_id, time_zone, activation_time):

        logger.debug("Instantiating Neurio Client for monitor %s" % monitor_id)
        self.monitorType = "neurio"
        self.monitor_id = monitor_id
        self.time_zone = time_zone
        self.activation_time = activation_time
        self.query_period = pd.Timedelta(31, 'D')

        client_id = cfg.get(self.monitorType, "clientID")
        secret = cfg.get(self.monitorType, "secret")

        tp = neurio.TokenProvider(key=client_id, secret=secret)
        self.client = neurio.Client(
            token_provider=tp)  # interface to remote data
Esempio n. 6
0
def setup_neurio(config):

    tp = neurio.TokenProvider(key=config['neurio']['client id'],
                              secret=config['neurio']['client secret'])
    nc = neurio.Client(token_provider=tp)
    user_info = nc.get_user_information()

    pp = pprint.PrettyPrinter(indent=4)
    ip_address = user_info['locations'][0]['sensors'][0]['ipAddress']

    sample = nc.get_samples_live_last(sensor_id='0x0000C47F51019C5A')
    pp.pprint(sample)

    sample = nc.get_local_current_sample(ip_address)

    pp.pprint(sample)
Esempio n. 7
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Neurio sensor."""
    name = config.get(CONF_NAME)
    api_key = config.get(CONF_API_KEY)
    api_secret = config.get(CONF_API_SECRET)
    sensor_id = config.get(CONF_SENSOR_ID)

    if not sensor_id:
        import neurio
        neurio_tp = neurio.TokenProvider(key=api_key, secret=api_secret)
        neurio_client = neurio.Client(token_provider=neurio_tp)
        user_info = neurio_client.get_user_information()
        _LOGGER.warning('Sensor ID auto-detected, set api_sensor_id: "%s"',
                        user_info["locations"][0]["sensors"][0]["sensorId"])
        sensor_id = user_info["locations"][0]["sensors"][0]["sensorId"]

    add_devices([NeurioEnergy(api_key, api_secret, name, sensor_id)])
Esempio n. 8
0
    def __init__(self, api_key, api_secret, sensor_id):
        """Initialize the data."""
        self.api_key = api_key
        self.api_secret = api_secret
        self.sensor_id = sensor_id

        self._daily_usage = None
        self._active_power = None

        self._state = None

        neurio_tp = neurio.TokenProvider(key=api_key, secret=api_secret)
        self.neurio_client = neurio.Client(token_provider=neurio_tp)

        if not self.sensor_id:
            user_info = self.neurio_client.get_user_information()
            _LOGGER.warning(
                "Sensor ID auto-detected: %s",
                user_info["locations"][0]["sensors"][0]["sensorId"],
            )
            self.sensor_id = user_info["locations"][0]["sensors"][0]["sensorId"]
Esempio n. 9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the Neurio sensor."""
    api_key = config.get("api_key")
    api_secret = config.get("api_secret")
    sensor_id = config.get("sensor_id")
    if not api_key and not api_secret:
        _LOGGER.error(
            "Configuration Error"
            "Please make sure you have configured your api key and api secret")
        return None
    if not sensor_id:
        import neurio
        neurio_tp = neurio.TokenProvider(key=api_key, secret=api_secret)
        neurio_client = neurio.Client(token_provider=neurio_tp)
        user_info = neurio_client.get_user_information()
        _LOGGER.warning('Sensor ID auto-detected, set api_sensor_id: "%s"',
                        user_info["locations"][0]["sensors"][0]["sensorId"])
        sensor_id = user_info["locations"][0]["sensors"][0]["sensorId"]
    dev = []
    dev.append(NeurioEnergy(api_key, api_secret, sensor_id))
    add_devices(dev)
Esempio n. 10
0
def main():
    args = parse_args()
    logging.basicConfig(level='INFO')

    LOG.info('authenticating to neurio api')
    tp = neurio.TokenProvider(key=args.client_id, secret=args.client_secret)
    nc = neurio.Client(token_provider=tp)

    LOG.info('connecting to mqtt broker')
    mq = mqtt.Client()
    mq.loop_start()
    mq.connect(args.mqtt_server)

    while True:
        sample = nc.get_samples_live_last(args.sensor_id)
        del sample['timestamp']
        sample['sensor_id'] = args.sensor_id
        sample['sensor_type'] = 'neurio'
        LOG.info('sending sample %s', sample)
        topic = '{}/neurio/{}'.format(args.topic, args.sensor_id)
        msg = json.dumps(sample)
        mq.publish(topic, msg)

        time.sleep(args.interval)
Esempio n. 11
0
#!/usr/bin/env python
"""
Copyright 2015, 2016 Jordan Husney <*****@*****.**>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
sys.path.append("..")

import neurio

import example_keys
sensor_id = "0x0013A20040B65FAD"

tp = neurio.TokenProvider(key=example_keys.key, secret=example_keys.secret)
nc = neurio.Client(token_provider=tp)

sample = nc.get_samples_live_last(sensor_id=sensor_id)

print "Current power consumption: %d W" % (sample['consumptionPower'])
Esempio n. 12
0
 def test_token_provider_invalid_credentials(self):
     tp = neurio.TokenProvider(key=example_keys.key,
                               secret=example_keys.secret)
     with self.assertRaises(Exception):
         tp.get_token()
Esempio n. 13
0
 def test_token_provider_get_token(self):
     tp = neurio.TokenProvider(key=test_keys.key, secret=test_keys.secret)
     self.assertIsNotNone(tp.get_token(), "unable to fetch token")
Esempio n. 14
0
 def test_token_provider_init(self):
     tp = neurio.TokenProvider(key=test_keys.key, secret=test_keys.secret)
     self.assertIsNotNone(tp)
Esempio n. 15
0
def main(argv):

    #make the keys available
    global APIKEY
    global SYSTEMID

    entireDay = False
    donation = False

    getSensorId = False

    ltz = dateutil.tz.tzlocal()
    UTCtz = dateutil.tz.tzutc()

    APIKEY = my_keys.APIKEY
    SYSTEMID = my_keys.SYSTEMID

    if my_keys.DONATION:
        maxEntries = 100
    else:
        maxEntries = 30

    try:
        opts, args = getopt.getopt(argv, "sht:", ["hoursBack"])
    except getopt.GetoptError:
        print 'neurioToPvoutput -sh -t dHrs '
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-s"):
            getSensorId = True
        if opt in ("-t"):
            dHrs = int(arg)
            entireDay = True
        if opt in ("-h"):
            print 'neurio_pvoutput -udh -t dHrs '
            print '-s print sensor id'
            print '-h print help info'
            print '-t dHrs - dHrs = number of hours in the past go get the neurio data'
            sys.exit(0)

    # get the Neurio token
    tp = neurio.TokenProvider(key=my_keys.key, secret=my_keys.secret)
    nc = neurio.Client(token_provider=tp)

    #read the sensor Id
    if getSensorId:
        user_info = nc.get_user_information()
        locations = user_info.get("locations")
        sensors = locations[0].get("sensors")
        sensorId = sensors[0].get("sensorId")
        print "Sensor Id = " + sensorId.encode("utf-8")
        sys.exit(0)

    #Neurio doesnt allow more than a days worth of data in a single request
    #so limit the data to either now - 1day or input offset time + 1 day
    if entireDay:
        stime = datetime.datetime.now() - datetime.timedelta(hours=dHrs)
        etime = stime + datetime.timedelta(days=1)
    else:
        stime = datetime.datetime.now() - datetime.timedelta(days=1)
        etime = stime + datetime.timedelta(days=1)
    etime = etime - datetime.timedelta(hours=1)

    #nuerio uses UTC, so we need to convert localtime to UTC and
    #format the strings that neurio expects
    stime = stime.replace(tzinfo=ltz)
    etime = etime.replace(tzinfo=ltz)
    stimeString = stime.astimezone(UTCtz).strftime("%Y-%m-%dT%H:%M:%S")
    etimeString = etime.astimezone(UTCtz).strftime("%Y-%m-%dT%H:%M:%S")
    print etimeString
    print stimeString

    #read the data from neurio
    current = nc.get_samples_live_last(my_keys.sensor_id)
    print current
    stats = nc.get_samples_stats(my_keys.sensor_id, stimeString, "minutes",
                                 etimeString, 5, 500, 1)
    #stats = nc.get_samples_stats(my_keys.sensor_id,stimeString,"hours",etimeString)
    print stats

    cnt = 0
    batchString = ''

    #build the string from the stats we read
    for item in stats:

        #read the time
        time = dateutil.parser.parse(item.get("start")).astimezone(ltz)
        print time

        #Read in the Energy and convert it to power in the 5 minute time
        #Energy is in WattSec, Pvoutput wants watts
        #So WattSec/3600Sec/Hr*12(5minute periods/hour) = Watts in the 5minute period
        cons = float(item.get("consumptionEnergy")) / 3600 * 12
        gen = float(item.get("generationEnergy")) / 3600 * 12

        #store the date,time,-1,,generatedPower,-1,consumedPower
        batchString = batchString + time.strftime(
            "%Y%m%d,%H:%M") + ',-1,' + str(int(gen + 0.5)) + ',-1,' + str(
                int(cons + 0.5)) + ';'
        cnt = cnt + 1
        #We can't exceed the pvoutput limits so check if we have hit the limit for each batch upload
        if cnt == maxEntries:
            log_pvoutput(batchString)
            cnt = 0
            batchString = ''

    #finally check to see if there are any left over entries to uplad
    if cnt > 0:
        log_pvoutput(batchString)
Esempio n. 16
0
 def setUp(self):
     self.tp = neurio.TokenProvider(key=test_keys.key,
                                    secret=test_keys.secret)
     self.nc = neurio.Client(token_provider=self.tp)
Esempio n. 17
0
from __future__ import print_function
import neurio
import os

# Setup authentication:
tp = neurio.TokenProvider(key=os.environ.get('NEURIO_KEY'),
                          secret=os.environ.get('NEURIO_SECRET'))
# Create client that can authenticate itself:
nc = neurio.Client(token_provider=tp)
# Get user information (including sensor ID and location ID)
user_info = nc.get_user_information()

print("Sensor ID %s, location ID %s" %
      (user_info["locations"][0]["sensors"][0]["sensorId"],
       user_info["locations"][0]["id"]))

# Fetch sample from the remote API (not the local device.):
sample = nc.get_samples_live_last(
    sensor_id=user_info["locations"][0]["sensors"][0]["sensorId"])

print("Current power consumption: %d W" % (sample['consumptionPower']))