from HardwareMonitor.Hardware import *  # equivalent to 'using LibreHardwareMonitor.Hardware;'
import HardwareMonitor.Util
import json
from flask import Flask, jsonify, request
app = Flask(__name__)

with open("carls.conf", "r") as config_file:
    config = json.load(config_file)
    url_path = "/" + config["service_info"]["url_path"]  # Ensure no leading or trailing slashes

@app.route(url_path + '/hardware_data', methods=['GET'])
def get_cpu_data( ):
    computer = HardwareMonitor.Util.OpenComputer(cpu=True, motherboard=True)
    computer.Update( )

    data = HardwareMonitor.Util.ToBuiltinTypes(computer.Hardware)
    #print(json.dumps(data, indent=4))
    cpu_data = { }
    cpu_data["Tempertures"] = { }
    cpu_data["Loads"] = { }
    cpu_data["Motherboard"] = { }
    for hardware in data:
        if hardware["HardwareType"] == "Cpu":
            for sensor in hardware["Sensors"]:
                if sensor["SensorType"] == "Temperature":
                    cpu_data["Tempertures"][sensor["Name"]] = sensor["Value"]
                if sensor["SensorType"] == "Load":
                    cpu_data["Loads"][sensor["Name"]] = sensor["Value"]
        if hardware["HardwareType"] == "Motherboard": 
            for sub_hardware in hardware["SubHardware"]:
                for sensor in sub_hardware["Sensors"]:
                    if sensor["Type"] == "Sensor":
                        if "Value" in sensor:
                            cpu_data["Motherboard"][sensor["Name"]] = sensor["Value"]
    return cpu_data

if __name__ == '__main__':
   print(url_path + '/cpu_data')
   app.run(port=1098)