import requests
import json
import datetime

# Define the iLO5 IP address and login credentials
ilo_ip = "192.168.0.2"  # Replace with your iLO5 IP address or hostname
username = "Administrator"  # Replace with your iLO5 username
password = "B7BXFR62"  # Replace with your iLO5 password

# Function to establish a session with the iLO5 Redfish API
def get_session_token(ilo_ip, username, password):
    login_url = f"https://{ilo_ip}/redfish/v1/SessionService/Sessions"
    headers = {"Content-Type": "application/json"}
    payload = {"UserName": username, "Password": password}

    response = requests.post(login_url, headers=headers, data=json.dumps(payload), verify=False)

    if response.status_code == 201:
        return response.headers.get("X-Auth-Token")
    else:
        raise Exception(f"Login failed: {response.status_code} {response.text}")

# Function to fetch and parse thermal information
def fetch_thermal_info(ilo_ip, session_token):
    thermal_url = f"https://{ilo_ip}/redfish/v1/Chassis/1/Thermal"
    headers = {
        "Content-Type": "application/json",
        "X-Auth-Token": session_token
    }

    response = requests.get(thermal_url, headers=headers, verify=False)
    if response.status_code == 200:
        data = response.json()
        temperatures = [
            {"SensorName": temp["Name"], "ReadingCelsius": temp["ReadingCelsius"]}
            for temp in data.get("Temperatures", [])
        ]
        fans = [
            {"FanName": fan["Name"], "ReadingRPM": fan["Reading"]}
            for fan in data.get("Fans", [])
        ]
        return {"temperatures": temperatures, "fans": fans}
    else:
        raise Exception(f"Failed to fetch thermal information: {response.status_code} {response.text}")

# Function to fetch and parse power consumption information
def fetch_power_info(ilo_ip, session_token):
    power_url = f"https://{ilo_ip}/redfish/v1/Chassis/1/Power"
    headers = {
        "Content-Type": "application/json",
        "X-Auth-Token": session_token
    }

    response = requests.get(power_url, headers=headers, verify=False)
    if response.status_code == 200:
        data = response.json()
        power_reading = data.get("PowerControl", [])[0].get("PowerConsumedWatts", None)
        return {"PowerConsumedWatts": power_reading}
    else:
        raise Exception(f"Failed to fetch power information: {response.status_code} {response.text}")

# Function to log the relevant information
def log_info(parsed_info):
    timestamp = datetime.datetime.now().isoformat()
    log_entry = {
        "timestamp": timestamp,
        "data": parsed_info
    }

    with open("ilo5_log.json", "a") as log_file:
        log_file.write(json.dumps(log_entry, indent=4))
        log_file.write(",\n")  # Add comma and newline for proper JSON formatting if appending

def main():
    try:
        session_token = get_session_token(ilo_ip, username, password)
        thermal_info = fetch_thermal_info(ilo_ip, session_token)
        power_info = fetch_power_info(ilo_ip, session_token)

        parsed_info = {
            "temperatures": thermal_info["temperatures"],
            "fans": thermal_info["fans"],
            "power": power_info
        }

        log_info(parsed_info)
        print("Thermal and power information logged successfully.")
    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()

