#!/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, 11, 45, 31), 'json.load', 'json.load', ({(45, 21, 45, 30): 'sys.stdin'}, {}), '(sys.stdin)', False, 'import json, sys, requests\n'), ((66, 6, 66, 67), 'requests.post', 'requests.post', (), '', False, 'import requests\n'), ((47, 2, 47, 43), 'sys.stderr.write', 'sys.stderr.write', ({(47, 19, 47, 42): '"""!! error loading json"""'}, {}), "('!! error loading json')", False, 'import json, sys, requests\n'), ((68, 4, 68, 35), 'sys.stderr.write', 'sys.stderr.write', ({(68, 21, 68, 34): 'r.status_code'}, {}), '(r.status_code)', False, 'import json, sys, requests\n'), ((69, 4, 69, 31), 'sys.stderr.write', 'sys.stderr.write', ({(69, 21, 69, 30): 'r.content'}, {}), '(r.content)', False, 'import json, sys, requests\n'), ((73, 2, 73, 52), 'sys.stderr.write', 'sys.stderr.write', ({(73, 19, 73, 51): '"""!!error: no data block in json"""'}, {}), "('!!error: no data block in json')", False, 'import json, sys, requests\n'), ((63, 24, 63, 35), 'time.time', 'time.time', ({}, {}), '()', False, 'import time\n')]