from pymodbus.client import ModbusTcpClient
import pandas as pd
import time

class HeatPump:
    def __init__(self, ip_address: str):
        self.ip = ip_address
        self.client = None
        self.connect_to_modbus()
        self.registers = None
        self.get_registers()

    def connect_to_modbus(self):
        port = 502
        self.client = ModbusTcpClient(self.ip, port=port)
        try:
            if not self.client.connect():
                print("Verbindung zur Wärmepumpe fehlgeschlagen.")
                exit(1)
            print("Verbindung zur Wärmepumpe erfolgreich.")
        except KeyboardInterrupt:
            print("Beendet durch Benutzer (Ctrl+C).")
        finally:
            self.client.close()

    def get_registers(self):
        # Excel-Datei mit den Input-Registerinformationen
        excel_path = "data/ModBus TCPIP 1.17(1).xlsx"
        xls = pd.ExcelFile(excel_path)
        df_input_registers = xls.parse('04 Input Register')

        # Relevante Spalten bereinigen
        df_clean = df_input_registers[['MB Adresse', 'Variable', 'Beschreibung', 'Variabel Typ']].dropna()
        df_clean['MB Adresse'] = df_clean['MB Adresse'].astype(int)

        # Dictionary aus Excel erzeugen
        self.registers = {
            row['MB Adresse']: {
                'desc': row['Beschreibung'],
                'type': 'REAL' if row['Variabel Typ'] == 'REAL' else 'INT'
            }
            for _, row in df_clean.iterrows()
        }

    def get_data(self):
        data = {}
        data['Zeit'] = time.strftime('%Y-%m-%d %H:%M:%S')
        for address, info in self.registers.items():
            reg_type = info['type']
            result = self.client.read_input_registers(address, count=2 if reg_type == 'REAL' else 1)
            if result.isError():
                print(f"Fehler beim Lesen von Adresse {address}: {result}")
                continue

            if reg_type == 'REAL':
                value = result.registers[0] / 10.0
            else:
                value = result.registers[0]

            print(f"Adresse {address} - {info['desc']}: {value}")
            data[f"{address} - {info['desc']}"] = value
        return data
