Exemplo n.º 1
0
def run(emparts,config):
    global mqtt_last_update
    global mqtt_debug


    # Only update every X seconds
    if time.time() < mqtt_last_update + int(config.get('min_update', 20)):
        if (mqtt_debug > 1):
            print("mqtt: data skipping")
        return

    # prepare mqtt settings
    mqtthost = config.get('mqtthost', 'mqtt')
    mqttport = config.get('mqttport', 1883)
    mqttuser = config.get('mqttuser', None)
    mqttpass = config.get('mqttpass', None)
    mqtttopic = config.get('mqtttopic',"SMA-EM/status")
    mqttfields = config.get('mqttfields', 'pconsume,psupply')
    publish_single = int(config.get('publish_single',0))

    # mqtt client settings
    myhostname = platform.node()
    mqtt_clientID = 'SMA-EM@' + myhostname
    client = mqtt.Client(mqtt_clientID)
    if None not in [mqttuser,mqttpass]:
        client.username_pw_set(username=mqttuser, password=mqttpass)

    #last aupdate
    mqtt_last_update = time.time()


    serial = emparts['serial']
    data = {}
    for f in mqttfields.split(','):
        data[f] = emparts[f]

    #add pv data
    try:
        #add summ value to
        from features.pvdata import pv_data
        pvpower=pv_data.get("AC Power",0)
        if pvpower is None: pvpower = 0
        pconsume=emparts.get('pconsume',0)
        psupply=emparts.get('psupply',0)
        pusage=pvpower+pconsume-psupply
        data['pvsum']=pvpower
        data['pusage']=pusage
    except:
        pv_data = None
        pass


    data['timestamp']=mqtt_last_update
    payload=json.dumps(data)
    topic=mqtttopic+'/'+str(serial)
    try:
            # mqtt connect
            client.connect(str(mqtthost), int(mqttport))
            client.on_publish = on_publish
            client.publish(topic, payload)
            # publish each value as separate topic
            if publish_single == 1:
                for item in data.keys():
                    itemtopic=topic+'/'+item
                    if mqtt_debug > 0:
                        print("mqtt: publishing %s:%s" % (itemtopic,data[item]) )
                    client.publish(itemtopic,str(data[item]))
            if mqtt_debug > 0:
                print("mqtt: sma-em data published %s:%s" % (
                    format(time.strftime("%H:%M:%S", time.localtime(mqtt_last_update))),payload))

            #pvoption
            mqttpvtopic = config.get('pvtopic', None)
            if None not in [pv_data,mqttpvtopic]  :
                if pv_data is not None:
                    pvserial = pv_data.get("serial")
                    pvtopic=mqttpvtopic+'/'+str(pvserial)
                    payload=json.dumps(pv_data)
                    client.publish(pvtopic, payload)
                    if mqtt_debug > 0:
                        print("mqtt: sma-pv data published %s:%s" % (
                            format(time.strftime("%H:%M:%S", time.localtime(mqtt_last_update))),payload))

    except Exception as e:
            print("mqtt: Error publishing")
            print(e)
            pass
Exemplo n.º 2
0
def run(emparts, config):
    global symcon_last_update
    global symcon_debug

    # Only update every X seconds
    if time.time() < symcon_last_update + int(config.get('min_update', 20)):
        if (symcon_debug > 1):
            print("Symcon: data skipping")
        return

    # prepare hook settings
    host = config.get('host', 'ips')
    port = config.get('port', 3777)
    timeout = config.get('timeout', 5)
    emhook = config.get('emhook', '/hook/smaem')
    user = config.get('user', None)
    password = config.get('password', None)
    fields = config.get('fields', 'pconsume,psupply')

    # mqtt client settings
    myhostname = platform.node()

    symcon_last_update = time.time()

    url = 'http://' + host + ':' + str(port) + emhook

    #last aupdate
    symcon_last_update = time.time()

    serial = emparts['serial']
    data = {}
    for f in fields.split(','):
        data[f] = emparts[f]

    data['timestamp'] = symcon_last_update
    data['sender'] = myhostname
    data['serial'] = str(serial)
    payload = json.dumps(data)

    #prepare request
    req = urllib.request.Request(url)
    req.add_header('Content-Type', 'application/json; charset=utf-8')
    dataasbytes = payload.encode('utf-8')  # needs to be bytes
    req.add_header('Content-Length', len(dataasbytes))
    #print(dataasbytes)
    req.add_header("User-Agent", "SMEM")

    #prepare auth
    if None not in [user, password]:
        passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, url, user, password)
        authhandler = urllib.request.HTTPBasicAuthHandler(passman)
        opener = urllib.request.build_opener(authhandler)
        urllib.request.install_opener(opener)
        if symcon_debug > 2:
            print('Symcon EM: use Basic auth')

    #send it
    try:
        response = urllib.request.urlopen(req,
                                          data=dataasbytes,
                                          timeout=int(timeout))

    except urllib.error.HTTPError as e:
        if symcon_debug > 0:
            print('Symcon EM: HTTPError: {%s} to %s' % (format(e.code), url))
        pass
    except urllib.error.URLError as e:
        if symcon_debug > 0:
            print('Symcon EM: URLError: {%s} to %s ' % (format(e.reason), url))
        pass
    except Exception as e:
        if symcon_debug > 0:
            print("Symcon EM: Error from symcon request")
            print(e)
        pass
    else:
        if symcon_debug > 0:
            print("Symcon EM: data published %s:%s to %s" % (format(
                time.strftime("%H:%M:%S", time.localtime(symcon_last_update))),
                                                             payload, url))

    #send pv data
    pvhook = config.get('pvhook')
    pvfields = config.get('pvfields', 'AC Power,daily yield')
    if None in [pvhook, pvfields]: return
    try:
        from features.pvdata import pv_data
    except:
        return

    serial = pv_data['serial']
    data = {}
    pvurl = 'http://' + host + ':' + str(port) + pvhook
    pvpower = pv_data.get("AC Power")
    if None in [serial, pvpower]: return
    for f in pvfields.split(','):
        data[f] = pv_data.get(f, 0)

    data['timestamp'] = symcon_last_update
    data['sender'] = myhostname
    data['serial'] = str(serial)
    pvpayload = json.dumps(data)

    # prepare request
    pvreq = urllib.request.Request(pvurl)
    pvreq.add_header('Content-Type', 'application/json; charset=utf-8')
    pvdataasbytes = pvpayload.encode('utf-8')  # needs to be bytes
    pvreq.add_header('Content-Length', len(pvdataasbytes))
    # print(dataasbytes)
    pvreq.add_header("User-Agent", "SMWR")

    # prepare auth
    if None not in [user, password]:
        passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
        passman.add_password(None, pvurl, user, password)
        authhandler = urllib.request.HTTPBasicAuthHandler(passman)
        opener = urllib.request.build_opener(authhandler)
        urllib.request.install_opener(opener)
        if symcon_debug > 2:
            print('Symcon PV: use Basic auth')

    # send it

    try:
        response = urllib.request.urlopen(pvreq,
                                          data=pvdataasbytes,
                                          timeout=int(timeout))

    except urllib.error.HTTPError as e:
        if symcon_debug > 0:
            print('Symcon PV : HTTPError: {%s} to %s ' %
                  (format(e.reason), pvurl))
        pass
    except urllib.error.URLError as e:
        if symcon_debug > 0:
            print('Symcon PV: URLError: {%s} to %s ' %
                  (format(e.reason), pvurl))
        pass
    except Exception as e:
        if symcon_debug > 0:
            print("Symcon PV: Error from symcon request")
            print(e)
        pass
    else:
        if symcon_debug > 0:
            print("Symcon PV: data published %s:%s to %s" % (format(
                time.strftime("%H:%M:%S", time.localtime(symcon_last_update))),
                                                             pvpayload, pvurl))
Exemplo n.º 3
0
def run(emparts, config):
    global mqtt_last_update
    global mqtt_debug

    # Only update every X seconds
    if time.time() < mqtt_last_update + int(config.get('min_update', 20)):
        if (mqtt_debug > 1):
            print("mqtt: data skipping")
        return

    # prepare mqtt settings
    mqtthost = config.get('mqtthost', 'mqtt')
    mqttport = config.get('mqttport', 1883)
    mqttuser = config.get('mqttuser', None)
    mqttpass = config.get('mqttpass', None)
    mqtttopic = config.get('mqtttopic', "SMA-EM/status")
    mqttfields = config.get('mqttfields', 'pconsume,psupply')
    publish_single = int(config.get('publish_single', 0))

    ssl_activate = config.get('ssl_activate', False)
    ssl_ca_file = config.get('ssl_ca_file', None)
    ssl_certfile = config.get('ssl_certfile', None)
    ssl_keyfile = config.get('ssl_keyfile', None)
    tls_protocol = config.get('tls_protocol', "2")
    if tls_protocol == "1":
        tls = ssl.PROTOCOL_TLSv1_1
    elif tls_protocol == "2":
        tls = ssl.PROTOCOL_TLSv1_2
    else:
        tls = ssl.PROTOCOL_TLSv1_2
        if mqtt_debug > 0:
            print("tls_protocol %s unsupported, use (TLSv1.)2" % tls_protocol)

    # mqtt client settings
    myhostname = platform.node()
    mqtt_clientID = 'SMA-EM@' + myhostname
    client = mqtt.Client(mqtt_clientID)
    if None not in [mqttuser, mqttpass]:
        client.username_pw_set(username=mqttuser, password=mqttpass)

    if ssl_activate == "1":
        # and ssl_ca_file:
        if ssl_certfile and ssl_keyfile and ssl_ca_file:
            # use client cert
            client.tls_set(ssl_ca_file, certfile=ssl_certfile, keyfile=ssl_keyfile, tls_version=tls)
            if mqtt_debug > 0:
                print("mqtt: ssl ca and client verify enabled")
        elif ssl_ca_file:
            # no client cert
            client.tls_set(ssl_ca_file, tls_version=tls)
            if mqtt_debug > 0:
                print("mqtt: ssl ca verify enabled")
        else:
            # disable certificat verify as there is no certificate
            client.tls_set(tls_version=tls)
            client.tls_insecure_set(True)
            if mqtt_debug > 0:
                print("mqtt: ssl verify disabled")
    else:
        if mqtt_debug > 0:
            print("mqtt: ssl disabled")

    # last aupdate
    # last aupdate
    mqtt_last_update = time.time()

    serial = emparts['serial']
    data = {}
    for f in mqttfields.split(','):
        data[f] = emparts.get(f, 0)

    # add pv data
    try:
        # add summ value to
        from features.pvdata import pv_data
        pvpower = pv_data.get("AC Power", 0)
        if pvpower is None: pvpower = 0
        pconsume = emparts.get('pconsume', 0)
        psupply = emparts.get('psupply', 0)
        pusage = pvpower + pconsume - psupply
        data['pvsum'] = pvpower
        data['pusage'] = pusage
        # daily sum
        daily = pv_data.get("daily yield", 0)
        if daily is None: daily = 0
        data['pvdaily'] = daily

    except:
        pv_data = None
        pass

    data['timestamp'] = mqtt_last_update
    payload = json.dumps(data)
    topic = mqtttopic + '/' + str(serial)
    try:
        # mqtt connect
        client.connect(str(mqtthost), int(mqttport))
        client.on_publish = on_publish
        client.publish(topic, payload)
        if mqtt_debug > 0:
            print("mqtt: sma-em topic %s data published %s:%s" % (topic,
                                                                  format(time.strftime("%H:%M:%S", time.localtime(
                                                                      mqtt_last_update))), payload))
        # publish each value as separate topic
        if publish_single == 1:
            for item in data.keys():
                itemtopic = topic + '/' + item
                if mqtt_debug > 0:
                    print("mqtt: publishing %s:%s" % (itemtopic, data[item]))
                client.publish(itemtopic, str(data[item]))

        # pvoption
        mqttpvtopic = config.get('pvtopic', None)
        if None not in [pv_data, mqttpvtopic]:
            if pv_data is not None:
                pvserial = pv_data.get("serial")
                pvtopic = mqttpvtopic + '/' + str(pvserial)
                payload = json.dumps(pv_data)
                # process last publish
                client.loop(1)
                # sendf pv topic
                client.publish(pvtopic, payload)
                if mqtt_debug > 0:
                    print("mqtt: sma-pv topic %s data published %s:%s" % (pvtopic,
                                                                          format(time.strftime("%H:%M:%S",
                                                                                               time.localtime(
                                                                                                   mqtt_last_update))),
                                                                          payload))

    except Exception as e:
        print("mqtt: Error publishing")
        print(traceback.format_exc())
        pass
Exemplo n.º 4
0
def run(emparts, config):
    global influx_last_update
    global influx_debug

    # Only update every X seconds
    if time.time() < influx_last_update + int(config.get('min_update', 20)):
        if (influx_debug > 1):
            print("InfluxDB: data skipping")
        return

    # db connect
    db = config.get('db', 'SMA')
    host = config.get('host', 'influxdb')
    port = int(config.get('port', 8086))
    ssl = bool(config.get('ssl'))
    timeout = int(config.get('timeout', 5))
    user = config.get('user', None)
    password = config.get('password', None)
    mesurement = config.get('measurement', 'SMAEM')
    fields = config.get('fields', 'pconsume,psupply')
    pvfields = config.get('pvfields')
    influx = None

    # connect to db, create one if needed
    try:
        if ssl == True:
            influx = InfluxDBClient(host=host,
                                    port=port,
                                    ssl=ssl,
                                    verify_ssl=ssl,
                                    username=user,
                                    password=password,
                                    timeout=timeout)
            if influx_debug > 0:
                print("Influxdb: use ssl")
        else:
            influx = InfluxDBClient(host=host,
                                    port=port,
                                    username=user,
                                    password=password,
                                    timeout=timeout)

        dbs = influx.get_list_database()
        if influx_debug > 1:
            print(dbs)
        if not {"name": db} in dbs:
            print(db + ' not in list, create')
            influx.create_database(db)

        influx.switch_database(db)
        if influx_debug > 1:
            print("Influxdb connected to '%s' @ '%s'(%s)" %
                  (str(user), host, db))

    except InfluxDBClientError as e:
        if influx_debug > 0:
            print("InfluxDB:  Connect Error to '%s' @ '%s'(%s)" %
                  (str(user), host, db))
            print(format(e))
        return
    except Exception as e:
        if influx_debug > 0:
            print("InfluxDB: Error while connecting to '%s' @ '%s'(%s)" %
                  (str(user), host, db))
            print(e)
        return

    myhostname = platform.node()
    influx_last_update = time.time()
    now = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

    # last aupdate
    influx_last_update = time.time()
    serial = emparts['serial']

    # data fields
    data = {}
    for f in fields.split(','):
        data[f] = emparts.get(f)
        if data[f] is None: data[f] = 0.0

    # data point
    influx_data = {}
    influx_data['measurement'] = mesurement
    influx_data['time'] = now
    influx_data['tags'] = {}
    influx_data['tags']["serial"] = serial
    pvpower = 0
    pdirectusage = 0
    pbattery = 0

    try:
        from features.pvdata import pv_data

        for inv in pv_data:
            # handle missing data during night hours
            if inv.get("AC Power") is None:
                pass
            elif inv.get("DeviceClass") == "Solar Inverter":
                pvpower += inv.get("AC Power")
            elif inv.get("DeviceClass") == "Battery Inverter":
                pbattery += inv.get("AC Power")

        pconsume = emparts.get('pconsume', 0)
        psupply = emparts.get('psupply', 0)
        pusage = pvpower + pconsume - psupply
        # total power consumption (grid + battery discharge)
        phouse = pvpower + pconsume - psupply + pbattery

        if pdirectusage is None: pdirectusage = 0
        if pvpower > pusage:
            pdirectusage = pusage
        else:
            pdirectusage = pvpower

        data['pdirectusage'] = float(pdirectusage)
        data['pvpower'] = float(pvpower)
        data['pusage'] = float(pusage)
        data['pbattery'] = float(pbattery)
        data['phouse'] = float(phouse)
    except:
        # Kostal inverter? (pvdata_kostal_json)
        print("except - no sma - inverter")
        try:
            from features.pvdata_kostal_json import pv_data
            pvpower = pv_data.get("AC Power")
            if pvpower is None: pvpower = 0
            pconsume = emparts.get('pconsume', 0)
            psupply = emparts.get('psupply', 0)
            pusage = pvpower + pconsume - psupply
            if pdirectusage is None: pdirectusage = 0
            if pvpower > pusage:
                pdirectusage = pusage
            else:
                pdirectusage = pvpower
            data['pdirectusage'] = pdirectusage
            data['pvpower'] = pvpower
            data['pusage'] = pusage
        except:
            pv_data = None
            print("no kostal inverter")
        pass

    influx_data['fields'] = data
    points = [influx_data]

    # send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print(
                "InfluxDB failed data:" + format(
                    time.strftime("%H:%M:%S",
                                  time.localtime(influx_last_update))),
                format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: em data published %s:%s" % (format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                                                         format(points)))

    pvmeasurement = config.get('pvmeasurement')
    if None in [pvfields, pv_data, pvmeasurement]: return

    influx_data = []
    datapoint = {
        'measurement': pvmeasurement,
        'time': now,
        'tags': {},
        'fields': {}
    }
    taglist = ['serial', 'DeviceID', 'Device Name']
    tags = {}
    fields = {}

    if pv_data is not None:
        for inv in pv_data:
            # add tag columns and remove from data list
            for t in taglist:
                tags[t] = inv.get(t)

            for f in pvfields.split(','):
                fields[f] = inv.get(f)

            datapoint['tags'] = tags.copy()
            datapoint['fields'] = fields.copy()
            influx_data.append(datapoint.copy())

    # send it
    try:
        influx.write_points(influx_data, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print(
                "InfluxDB failed pv data:" + format(
                    time.strftime("%H:%M:%S",
                                  time.localtime(influx_last_update))),
                format(influx_data))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: pv data published %s:%s" % (format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                                                         format(influx_data)))

    # Edimax smartplug data #####
    from features.ediplugs import edi_data
    edimeasurement = config.get('edimeasurement')

    if None in [edi_data, edimeasurement]: return

    influx_data = []
    datapoint = {
        'measurement': edimeasurement,
        'time': now,
        'tags': {},
        'fields': {}
    }
    taglist = ['vendor', 'model', 'mac', 'name']
    fieldlist = ['state', 'pconsume', 'aconsume']
    tags = {}
    fields = {}

    for inv in edi_data:
        for t in taglist:
            tags[t] = inv.get(t)

        for f in fieldlist:
            fields[f] = inv.get(f)

        datapoint['tags'] = tags.copy()
        datapoint['fields'] = fields.copy()
        influx_data.append(datapoint.copy())

    points = influx_data

    #send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print("InfluxDB failed edi data:" + format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update)))
                  + format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: edi data published %s:%s" % (format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                                                          format(points)))
Exemplo n.º 5
0
def run(emparts, config):
    global influx2_debug
    global influx2_last_update
    global influx2_client
    global influx2_write_api

    # Only update every X seconds
    if time.time() < influx2_last_update + int(config.get('min_update', 20)):
        if (influx2_debug > 1):
            print("InfluxDB: data skipping")
        return
    influx2_last_update = time.time()

    mesurement = config.get('measurement', 'SMAEM')
    fields = config.get('fields', 'pconsume,psupply')
    serial = emparts['serial']

    # data fields
    data = {}
    for f in fields.split(','):
        data[f] = emparts.get(f)
        if data[f] is None:
            data[f] = 0.0

    # inverter data
    pvpower = 0
    pdirectusage = 0
    try:
        from features.pvdata import pv_data
        for inv in pv_data:
            # handle missing data during night hours
            if inv.get("AC Power") is None:
                pass
            elif inv.get("DeviceClass") == "Solar Inverter":
                pvpower += inv.get("AC Power", 0)
        pconsume = emparts.get('pconsume', 0)
        psupply = emparts.get('psupply', 0)
        pusage = pvpower + pconsume - psupply

        if pdirectusage is None:
            pdirectusage = 0
        if pvpower > pusage:
            pdirectusage = pusage
        else:
            pdirectusage = pvpower
        data['pdirectusage'] = float(pdirectusage)
        data['pvpower'] = float(pvpower)
        data['pusage'] = float(pusage)
    except:
        # Kostal inverter? (pvdata_kostal_json)
        if influx2_debug > 0:
            print("InfluxDB2: " + "except - no sma - inverter")
        try:
            from features.pvdata_kostal_json import pv_data
            pvpower = pv_data.get("AC Power")
            if pvpower is None:
                pvpower = 0
            pconsume = emparts.get('pconsume', 0)
            psupply = emparts.get('psupply', 0)
            pusage = pvpower + pconsume - psupply
            if pdirectusage is None:
                pdirectusage = 0
            if pvpower > pusage:
                pdirectusage = pusage
            else:
                pdirectusage = pvpower
            data['pdirectusage'] = float(pdirectusage)
            data['pvpower'] = float(pvpower)
            data['pusage'] = float(pusage)
        except:
            pv_data = None
            if influx2_debug > 0:
                print("InfluxDB2: " + "no kostal inverter")
        pass

    # data point
    influx_data = {}
    influx_data['measurement'] = mesurement
    influx_data['time'] = datetime.utcnow()
    influx_data['tags'] = {}
    influx_data['tags']["serial"] = serial
    influx_data['fields'] = data
    points = [influx_data]

    # write em data
    org = config.get('org', "my-org")
    bucket = config.get('bucket', "my-bucket")
    influx2_write_api.write(bucket,
                            org,
                            points,
                            write_precision=WritePrecision.S)

    # prepare pv data
    pvfields = config.get('pvfields')
    pvmeasurement = config.get('pvmeasurement')
    if None in [pvfields, pv_data, pvmeasurement]:
        return

    # pv data are empty on first call
    if not pv_data:
        if influx2_debug > 0:
            print("pv_data empty")
        return

    points = []
    influx_data = []
    datapoint = {
        'measurement': pvmeasurement,
        'time': datetime.utcnow(),
        'tags': {},
        'fields': {}
    }
    taglist = ['serial', 'DeviceID']
    tags = {}
    fields = {}
    for inv in pv_data:
        # add tag columns and remove from data list
        for t in taglist:
            if inv.get(t) is None:
                pass
            else:
                tags[t] = inv.get(t)
                inv.pop(t)

        # only if we have values
        if pv_data is not None:
            for f in pvfields.split(','):
                if inv.get(f) is None:
                    pass
                else:
                    fields[f] = inv.get(f)

        datapoint['tags'] = tags.copy()
        datapoint['fields'] = fields.copy()
        influx_data.append(datapoint.copy())

    # write pv data
    points = influx_data
    influx2_write_api.write(bucket,
                            org,
                            points,
                            write_precision=WritePrecision.S)
Exemplo n.º 6
0
def run(emparts, config):
    global influx_last_update
    global influx_debug

    # Only update every X seconds
    if time.time() < influx_last_update + int(config.get('min_update', 20)):
        if (influx_debug > 1):
            print("InfluxDB: data skipping")
        return

    # db connect
    db = config.get('db', 'SMA')
    host = config.get('host', 'influxdb')
    port = int(config.get('port', 8086))
    timeout = int(config.get('timeout', 5))
    user = config.get('user', None)
    password = config.get('password', None)
    mesurement = config.get('measurement', 'SMAEM')
    fields = config.get('fields', 'pconsume,psupply')
    pvfields = config.get('pvfields')
    influx = None
    #connect to db, create one if needed
    try:
        influx = InfluxDBClient(host=host,
                                port=port,
                                username=user,
                                password=password,
                                timeout=timeout)
        dbs = influx.get_list_database()
        if influx_debug > 1:
            print(dbs)
        if not {"name": db} in dbs:
            print(db + ' not in list, create')
            influx.create_database(db)

        influx.switch_database(db)
        if influx_debug > 1:
            print("Influxdb connected to '%s' @ '%s'(%s)" %
                  (str(user), host, db))

    except InfluxDBClientError as e:
        if influx_debug > 0:
            print("InfluxDB:  Connect Error to '%s' @ '%s'(%s)" %
                  (str(user), host, db))
            print(format(e))
        return
    except Exception as e:
        if influx_debug > 0:
            print("InfluxDB: Error while connecting to '%s' @ '%s'(%s)" %
                  (str(user), host, db))
            print(e)
        return

    myhostname = platform.node()
    influx_last_update = time.time()
    now = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

    #last aupdate
    influx_last_update = time.time()
    serial = emparts['serial']

    #data fields
    data = {}
    for f in fields.split(','):
        data[f] = emparts[f]

    # data point
    influx_data = {}
    influx_data['measurement'] = mesurement
    influx_data['time'] = now
    influx_data['tags'] = {}
    influx_data['tags']["serial"] = serial
    pvpower = 0
    try:
        from features.pvdata import pv_data
        pvpower = pv_data.get("AC Power")
        if pvpower is None: pvpower = 0
        pconsume = emparts.get('pconsume', 0)
        psupply = emparts.get('psupply', 0)
        pusage = pvpower + pconsume - psupply
        data['pvpower'] = pvpower
        data['pusage'] = pusage
    except:
        pv_data = None
        pass

    influx_data['fields'] = data
    points = [influx_data]

    # send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print(
                "InfluxDB failed data:" + format(
                    time.strftime("%H:%M:%S",
                                  time.localtime(influx_last_update))),
                format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: em data published %s:%s" % (format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                                                         format(points)))

    pvmeasurement = config.get('pvmeasurement')
    if None in [pvfields, pv_data, pvmeasurement]: return

    influx_data = {}
    data = {}
    influx_data['measurement'] = pvmeasurement
    influx_data['time'] = now
    pvserial = pv_data.get('serial')
    influx_data['tags'] = {}
    influx_data['tags']["serial"] = pvserial
    #unly if we have values
    if pvpower is not None:
        for f in pvfields.split(','):
            data[f] = pv_data.get(f, 0)

    influx_data['fields'] = data
    points = [influx_data]

    #send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print(
                "InfluxDB failed pv data:" + format(
                    time.strftime("%H:%M:%S",
                                  time.localtime(influx_last_update))),
                format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: pv data published %s:%s" % (format(
                time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                                                         format(points)))
Exemplo n.º 7
0
def run(emparts,config):
    global influx_last_update
    global influx_debug

    # Only update every X seconds
    if time.time() < influx_last_update + int(config.get('min_update', 20)):
        if (influx_debug > 1):
            print("InfluxDB: data skipping")
        return

    # db connect
    db = config.get('db', 'SMA')
    host = config.get('host', 'influxdb')
    port = int(config.get('port', 8086))
    timeout = int(config.get('timeout', 5))
    user = config.get('user', None)
    password = config.get('password',None )
    mesurement= config.get('measurement','SMAEM' )
    fields = config.get('fields', 'pconsume,psupply')
    pvfields=config.get('pvfields')
    influx=None
    #connect to db, create one if needed
    try:
        influx = InfluxDBClient(host=host, port=port, username=user, password=password,timeout=timeout)
        dbs = influx.get_list_database()
        if influx_debug>1:
            print(dbs)
        if not {"name": db} in dbs:
            print(db + ' not in list, create')
            influx.create_database(db)

        influx.switch_database(db)
        if influx_debug > 1:
            print("Influxdb connected to '%s' @ '%s'(%s)" % (str(user), host, db))

    except InfluxDBClientError as e:
        if influx_debug > 0:
            print("InfluxDB:  Connect Error to '%s' @ '%s'(%s)" % (str(user), host, db))
            print(format(e))
        return
    except Exception as e:
        if influx_debug > 0:
            print("InfluxDB: Error while connecting to '%s' @ '%s'(%s)" % (str(user), host, db))
            print(e)
        return





    myhostname = platform.node()
    influx_last_update = time.time()
    now = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

    #last aupdate
    influx_last_update = time.time()
    serial = emparts['serial']

    #data fields
    data={}
    for f in fields.split(','):
        data[f] = emparts[f]

    # data point
    influx_data = {}
    influx_data['measurement'] = mesurement
    influx_data['time'] = now
    influx_data['tags']={}
    influx_data['tags']["serial"]=serial
    pvpower=0
    try:
        from features.pvdata import pv_data
        pvpower = pv_data.get("AC Power")
        if pvpower is None: pvpower=0
        pconsume = emparts.get('pconsume', 0)
        psupply = emparts.get('psupply', 0)
        pusage = pvpower + pconsume - psupply
        data['pvpower'] = pvpower
        data['pusage'] = pusage
    except:
        pv_data = None
        pass

    influx_data['fields'] = data
    points = [influx_data]

    # send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' %(format(e)))
            print("InfluxDB failed data:" + format(time.strftime("%H:%M:%S", time.localtime(influx_last_update))),
                  format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: em data published %s:%s" % (
            format(time.strftime("%H:%M:%S", time.localtime(influx_last_update))), format(points)))

    pvmeasurement=config.get('pvmeasurement')
    if None in [pvfields,pv_data,pvmeasurement]: return

    influx_data = {}
    data={}
    influx_data['measurement'] = pvmeasurement
    influx_data['time'] = now
    pvserial=pv_data.get('serial')
    influx_data['tags'] = {}
    influx_data['tags']["serial"] = pvserial
    #unly if we have values
    if pvpower is not None:
        for f in pvfields.split(','):
            data[f] = pv_data.get(f,0)

    influx_data['fields'] = data
    points=[influx_data]

    #send it
    try:
        influx.write_points(points, time_precision='s', protocol='json')
    except InfluxDBClientError as e:
        if influx_debug > 0:
            print('InfluxDBError: %s' % (format(e)))
            print("InfluxDB failed pv data:"+format(time.strftime("%H:%M:%S", time.localtime(influx_last_update))), format(points))
        pass

    else:
        if influx_debug > 0:
            print("InfluxDB: pv data published %s:%s" % (format(time.strftime("%H:%M:%S", time.localtime(influx_last_update))),format(points)))