#!/usr/bin/env python3

# This file should be placed in ~/local/bin/ and used for a monitoring host that has a/the IP of the device
# in combination with a rule for "individual program call instead of agent" as described on the official docs of CheckMK:
# https://docs.checkmk.com/latest/en/datasource_programs.html
#
# The commandline to be used in CheckMK is : this_script_name.py $HOSTADDRESS$

import sys
import json
import requests

address = sys.argv[1]
response = requests.get('http://{}/api/v1/data'.format(address))
parsed = response.json()

# Using For Loop to iterate thru the data offered by the P1-API
# Threshold values are tuned to my own setup, they might need ajustment for others.

def iterate_json(json_obj):
    for key, value in json_obj.items():
        if isinstance(value, dict):
            iterate_json(value)
        else:
            if key.startswith("active"):
                if key.endswith("_w"):
                    print(f"P {key} watt={value};2100;2200;2300;0;2500 Current Watts:{value}")
                if key.endswith("_v"):
                    print(f"P {key} volt={value};252;253;260;0;300 Current Volts:{value}")
                if key.endswith("_a"):
                    print(f"P {key} amps={value};8;10;15;0;20 Current Amps:{value}")
                if key.endswith("tariff"):
                    print(f"P {key} tariff={value};;;;; Current Tariff:{value}")

# Additional information is available, but not at current needed in my case
#            if key.startswith("external"):
#                continue
#            else:
#                print(f"0 {key} - {value}")

print('<<<local>>>')
iterate_json(parsed)