diff --git a/tplink_smartplug.py b/tplink_smartplug.py index 4012a55..6fbf1e7 100755 --- a/tplink_smartplug.py +++ b/tplink_smartplug.py @@ -75,6 +75,12 @@ def decrypt(string): group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-c", "--command", metavar="", help="Preset command to send. Choices are: "+", ".join(commands), choices=commands) group.add_argument("-j", "--json", metavar="", help="Full JSON string of command to send") +parser.add_argument('--influxdb', type=str, metavar=("URI", "database"), default=None, + nargs=2, help='If command is "energy", push to influxdb. URI should point to influxdb, e.g. [http/https]://:. Database: e.g. smarthome.') +parser.add_argument('--influxdb_energy', type=str, metavar="query", default=None, + help='query to store energy as Joule, e.g. energy,type=elec,device=hs110-1 this will be appended with (as int)') +parser.add_argument('--influxdb_power', type=str, metavar="query", default=None, + help='query to store power as Watt, e.g. power,type=elec,device=hs110-1 this will be appended with (as float)') args = parser.parse_args() @@ -101,3 +107,32 @@ def decrypt(string): except socket.error: quit("Cound not connect to host " + ip + ":" + str(port)) +if (args.command == "energy") and (args.influxdb != None): + import requests + import json + + # Get total_wh and power_mw from json response + energy_response = decrypt(data[4:]) + energy_wh = json.loads(energy_response)['emeter']['get_realtime']['total_wh'] + energy_joule = int(energy_wh)*3600 + power_mW = json.loads(energy_response)['emeter']['get_realtime']['power_mw'] + power_W = float(power_mW)/1000.0 + + # Build URI and query + # Something like req_url = "http://localhost:8086/write?db=smarthometest&precision=s" + # Something like post_data = "water,type=usage,device=devicename value=1" + req_url = args.influxdb[0]+"/write?db="+args.influxdb[1]+"&precision=s" + post_data = "" + if (args.influxdb_energy != None): + post_data = args.influxdb_energy+" value="+str(energy_joule) + if (args.influxdb_power != None): + post_data += "\n"+args.influxdb_power+" value="+str(power_W) + + # Post data to influxdb, check for obvious errors + try: + httpresponse = requests.post(req_url, data=post_data, verify=False, timeout=5) + if (httpresponse.status_code != 204): + print "Push to influxdb failed: " + str(httpresponse.status_code) + " - " + str(httpresponse.text) + except requests.exceptions.Timeout as e: + print "Update failed due to timeout. Is influxdb running?" +