InfluxDB to Rubric Content

DB0NS is solar powered only. The data from the solar charger is placed into a influxdb instance in order to display it with Grafana. In addition, the most critical data is also sent periodically into a rubric.

The Python-Code was adapted from Philipp DL7FL: https://github.com/DL7FL/DAPNET/blob/master/DAPNET/senden.py

import urllib.parse
import requests
from requests.auth import HTTPBasicAuth
import json

def getinflux(mytopic, leading, decimals):
  querystring = 'SELECT last("value") FROM "mqtt_consumer" WHERE ("host" = \'control\' AND "topic" = \'' + mytopic + '\') AND time >= now() - 2d'
#  print (querystring)
  payload = {'db': 'telegraf', 'q': querystring}
  r = requests.get('http://localhost:8086/query?', auth=('MYUSER', 'MYPASS'), params=payload)
#  print (r.text)
  jsondata = json.loads(r.text)
  if "series" in jsondata["results"][0]:
#    print (format(round(jsondata["results"][0]["series"][0]["values"][0][1],decimals), '.' + str(decimals) + 'f'))
#    return (format(round(jsondata["results"][0]["series"][0]["values"][0][1],decimals), str(leading) + '.' + str(decimals) + 'f'))
    return ('{:{width}.{prec}f}'.format(jsondata["results"][0]["series"][0]["values"][0][1], width = leading+decimals+1, prec = decimals))

  return (format(0, '.' + str(decimals) + 'f'))



def sendstats(text, pos):

  json_string =json.dumps({"rubricName": "DB0NSStats", "text": text, "number": pos})
  url = "http://dapnet.db0sda.ampr.org:8080/news"
  login = "DAPNETUSER"
  passwd = "DAPNETPASS"
#  import pprint; pprint.pprint(json_string)
  response = requests.post(url, data=json_string, auth=HTTPBasicAuth(login, passwd)) # Exception handling einbauen
  return response.status_code


PV_V = getinflux("N/MYMQTTTOPPIC/solarcharger/288/Pv/V", 3, 1)
PV_I = getinflux("N/MYMQTTTOPPIC/solarcharger/288/Pv/I", 2, 2)
Bat_V = getinflux("N/MYMQTTTOPPIC/solarcharger/288/Dc/0/Voltage", 2, 1)
Bat_I = getinflux("N/MYMQTTTOPPIC/solarcharger/288/Dc/0/Current", 2, 2)
Bat_P = getinflux("N/MYMQTTTOPPIC/system/0/Dc/Battery/Power", 4, 0)
Gen_E = getinflux("N/MYMQTTTOPPIC/solarcharger/288/Yield/System", 5, 0)
msgString = 'PV:' + PV_V + ' V ' + PV_I + ' A  ' + Gen_E + ' kWh          Bat:' + Bat_V + ' V ' + Bat_I + ' A   ' + Bat_P + ' W'
#print (msgString)

sendstats(msgString,1)