#!/usr/bin/python3

## write2cly.py   - reads json (generated by sml_reader.py) from stdin
##                - writes values to Corlysis time series InfluxDB
##
## Writes data from smart meter to time series database (InfluxDB)
## at Corlysis.com [1]. You need to configure your database and token
## in the config section.
##
## [1] https://corlysis.com/


##==== license section ========
## This code is under MIT License: Copyright (C) 2019 Bernd Künnen 
## License details see https://choosealicense.com/licenses/mit/


##==== config section ========

# define corlysis settings here - set db and token at least
cly_base_url   = 'https://corlysis.com:8086/write'
cly_parameters = {
    "db": "energy",
    "u" : "token",
    "p" : "placeyourtokenhere",
    "precision": "ms"}

# assign readable field names
config = {
  "1.8.0":  "Bezug",
  "2.8.0":  "Einspeisung",
  "16.7.0": "Wirkleistung"
}


##==== code section ==== no need to change lines below ====

##-- import libraries
import json, sys, requests
import requests
import time

# load json from stdin
try:
  myjson = json.load(sys.stdin)
except:
  sys.stderr.write('!! error loading json')
  exit(1)

# decode json
try:
  line = "meter_data "
  # add each meter value to line
  for obis in myjson['data']:
    key   = config[obis]		 # set human readable field name
    value = myjson['data'][obis]	 # get value from smart meter
    line += key + '=' + str(value) + ',' # add key=value to insert line

  # cut off last comma
  line = line[:-1]

  # add timestamp as unix timestamp in ms
  line += ' ' + str(int(time.time()*1000)) #+ '\n'

  # post data into time series database; http response should be 204
  r = requests.post(cly_base_url, params=cly_parameters, data=line)
  if r.status_code != 204 :
    sys.stderr.write(r.status_code)
    sys.stderr.write(r.content)

# catch if input is no valid json
except:
  sys.stderr.write('!!error: no data block in json')
  exit(2)


[(45, 'json.load', 'json.load', False, 'import json, sys, requests\n'), (66, 'requests.post', 'requests.post', False, 'import requests\n'), (47, 'sys.stderr.write', 'sys.stderr.write', False, 'import json, sys, requests\n'), (68, 'sys.stderr.write', 'sys.stderr.write', False, 'import json, sys, requests\n'), (69, 'sys.stderr.write', 'sys.stderr.write', False, 'import json, sys, requests\n'), (73, 'sys.stderr.write', 'sys.stderr.write', False, 'import json, sys, requests\n'), (63, 'time.time', 'time.time', False, 'import time\n')]