import logging from pymodbus.client.sync import ModbusTcpClient import time # Logger konfigurieren logging.basicConfig(filename='modbus_log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') cerboip = '192.168.178.***' port = 502 # Funktion zum Lesen eines Input-Registers def read_cerbo(addr, id, unit_to_read): try: client = ModbusTcpClient(cerboip, port=port) result = client.read_input_registers(addr, 1, unit=id) value = result.registers[0] return value / unit_to_read except Exception as e: logging.error(f"Fehler beim Lesen des Registers: {e}") return 99999 finally: if client: client.close() # Funktion zum Schreiben eines Registers def write_cerbo(addr, id, val): try: client = ModbusTcpClient(cerboip, port=port) val_as_int = int(val) result = client.write_register(addr, val_as_int, unit=id) logging.info(f"Schreiben des Registers: {val_as_int}") except Exception as e: logging.error(f"Fehler beim Schreiben des Registers: {e}") finally: if client: client.close() # Beispielaufrufe addr_batt_soc = 843 id_batt_soc = 100 unit_batt_soc = 1 addr_evcs_mode = 3815 id_evcs_mode = 40 unit_evcs_mode = 1 addr_evcs_charge = 3826 id_evcs_charge = 40 unit_evcs_charge = 1 addr_batt_soc_min = 2901 id_batt_soc_min = 100 unit_batt_soc_min = 1 # SOC_remind und SOC_remind_initial initialisieren SOC_remind = None SOC_min_initial = None try: while True: # Werte auslesen value_batt_soc = read_cerbo(addr_batt_soc, id_batt_soc, unit_batt_soc) value_evcs_mode = read_cerbo(addr_evcs_mode, id_evcs_mode, unit_evcs_mode) value_evcs_charge = read_cerbo(addr_evcs_charge, id_evcs_charge, unit_evcs_charge) logging.info(f"aktueller SOC: {value_batt_soc}") #if (value_evcs_mode == 0 or value_evcs_mode == 2) and value_evcs_charge == 0: SOC_min_initial = read_cerbo(addr_batt_soc_min, id_batt_soc_min, unit_batt_soc_min) logging.info(f"Initialer Wert von SOC_min_initial: {SOC_min_initial}") # Wenn der Ladevorgang beginnt while (value_evcs_mode == 0 or value_evcs_mode == 2) and value_evcs_charge == 1: # SOC_remind aktualisieren, wenn sich der Wert ändert SOC_remind = value_batt_soc * 10 logging.info(f"SOC_remind aktualisiert: {SOC_remind}") # batt_soc_min auf SOC_remind setzen write_cerbo(addr_batt_soc_min, id_batt_soc_min, SOC_remind) time.sleep(5) value_evcs_mode = read_cerbo(addr_evcs_mode, id_evcs_mode, unit_evcs_mode) value_evcs_charge = read_cerbo(addr_evcs_charge, id_evcs_charge, unit_evcs_charge) time.sleep(5) # Wenn der Ladevorgang beendet ist # batt_soc_min_init auf den ursprünglichen Wert setzen write_cerbo(addr_batt_soc_min, id_batt_soc_min, SOC_min_initial) logging.info(f"batt_soc_min_init wiederhergestellt: {SOC_min_initial}") SOC_remind = 0 SOC_min_initial = 0 # Wartezeit von einer Sekunde time.sleep(5) except KeyboardInterrupt: logging.info("Programm durch Benutzer abgebrochen.") finally: # Verbindung schließen client.close()