#!/usr/bin/python3

#
# Imports
#
import sys
import time
import argparse
import pmt

#
# Configuration
#
hostname = "shuttle"
measurement_duration = 5
measurement_interval = 15
pm = pmt.create("rapl")

#
# Command line arguments
#
parser = argparse.ArgumentParser(description="Get CPU power consumption")
parser.add_argument("-s", action="store_true", help="print in human readable format")
args = parser.parse_args()
human_readable = args.s


#
# Methods
#
def get_power():
    time.sleep(measurement_duration)
    measurements = dict()
    state = pm.read()
    for i in range(state.nr_measurements()):
        name = state.name(i)
        watts = state.watts(i)
        measurements[name] = watts
    return measurements


def print_rrd(measurements):
    timestamp = int(time.time())
    for measurement in list(measurements.items()):
        name = measurement[0].lower()
        power = measurement[1]
        print(
            (
                "PUTVAL {}/exec-power/gauge-{} {}:{:.1f}".format(
                    hostname, name, timestamp, power
                )
            )
        )


#
# Main
#
if human_readable:
    print(get_power())
else:
    while True:
        power = get_power()
        print_rrd(power)
        sys.stdout.flush()
        time.sleep(measurement_interval)
