#!/usr/bin/env python3
#
# Adapted from: https://harlemsquirrel.github.io/shell/2019/01/05/monitoring-raspberry-pi-power-and-thermal-issues.html
#

import subprocess
import sys

GET_THROTTLED_CMD = 'vcgencmd get_throttled'
MESSAGES = {
    0: 'Under voltage!',
    1: 'ARM frequency capped!',
    2: 'Currently throttled!',
    3: 'Soft temperature limit active',
    16: 'Under-voltage has occurred since last reboot.',
    17: 'Throttling has occurred since last reboot.',
    18: 'ARM frequency capped has occurred since last reboot.',
    19: 'Soft temperature limit has occurred'
}

print("Checking for throttling issues since last reboot...")

throttled_output = subprocess.check_output(GET_THROTTLED_CMD, shell=True).strip()
throttled_binary = bin(int(throttled_output.decode("utf-8").split('=')[1], 0)).split("0b")[-1]

has_msg = False
for position, message in MESSAGES.items():
    # Check for the binary digits to be "on" for each warning message
    if len(throttled_binary) > position and throttled_binary[position] == '1':
        print(f"\x1b[91m{message}\x1b[0m")
        has_msg = True

if not has_msg:
    print("\x1b[32mNo Issues\x1b[0m")

if '-v' in sys.argv:
    print(f"\nRaw Output of {GET_THROTTLED_CMD}: {throttled_output}")
    print(f"Binary Output of {GET_THROTTLED_CMD}: {throttled_binary}\n")