inverter and meter seems to run
This commit is contained in:
@@ -4,7 +4,10 @@ import pandas as pd
|
||||
from typing import Dict, Any, List, Tuple, Optional
|
||||
from pymodbus.client import ModbusTcpClient
|
||||
|
||||
EXCEL_PATH = "modbus_registers/pv_inverter_registers.xlsx"
|
||||
EXCEL_PATH = "modbus_registers/pv_inverter_registers.xlsx"
|
||||
|
||||
# Obergrenze: bis EXKLUSIVE 40206 (d.h. max. 40205)
|
||||
MAX_ADDR_EXCLUSIVE = 40121
|
||||
|
||||
class PvInverter:
|
||||
def __init__(self, device_name: str, ip_address: str, port: int = 502, unit: int = 1):
|
||||
@@ -34,33 +37,29 @@ class PvInverter:
|
||||
def load_registers(self, excel_path: str):
|
||||
xls = pd.ExcelFile(excel_path)
|
||||
df = xls.parse()
|
||||
# Passen die Spaltennamen bei dir anders, bitte hier anpassen:
|
||||
# Passe Spaltennamen hier an, falls nötig:
|
||||
cols = ["MB Adresse", "Beschreibung", "Variabel Typ"]
|
||||
for c in cols:
|
||||
if c not in df.columns:
|
||||
raise ValueError(f"Spalte '{c}' fehlt in {excel_path}")
|
||||
df = df[cols].dropna()
|
||||
df["MB Adresse"] = df["MB Adresse"].astype(int)
|
||||
# NORMALISIERE TYP
|
||||
def norm_type(x: Any) -> str:
|
||||
s = str(x).strip().upper()
|
||||
return "REAL" if s == "REAL" else "INT"
|
||||
|
||||
# 1) Vorab-Filter: nur Adressen < 40206 übernehmen
|
||||
df = df[df["MB Adresse"] < MAX_ADDR_EXCLUSIVE]
|
||||
|
||||
self.registers = {
|
||||
int(row["MB Adresse"]): {
|
||||
"desc": str(row["Beschreibung"]).strip(),
|
||||
"type": norm_type(row["Variabel Typ"])
|
||||
"type": str(row["Variabel Typ"]).strip()
|
||||
}
|
||||
for _, row in df.iterrows()
|
||||
}
|
||||
print(f"ℹ️ {len(self.registers)} Register aus Excel geladen.")
|
||||
|
||||
|
||||
# ---------- Low-Level Lesen ----------
|
||||
def _try_read(self, fn_name: str, address: int, count: int) -> Optional[List[int]]:
|
||||
fn = getattr(self.client, fn_name)
|
||||
# pymodbus 3.8.x hat 'slave='; Fallbacks schaden nicht
|
||||
for kwargs in (dict(address=address, count=count, slave=self.unit),
|
||||
dict(address=address, count=count),
|
||||
):
|
||||
dict(address=address, count=count)):
|
||||
try:
|
||||
res = fn(**kwargs)
|
||||
if res is None or (hasattr(res, "isError") and res.isError()):
|
||||
@@ -83,33 +82,58 @@ class PvInverter:
|
||||
|
||||
@staticmethod
|
||||
def _to_f32_from_two(u16_hi: int, u16_lo: int, msw_first: bool = True) -> float:
|
||||
if msw_first:
|
||||
b = struct.pack(">HH", u16_hi, u16_lo)
|
||||
else:
|
||||
b = struct.pack(">HH", u16_lo, u16_hi)
|
||||
b = struct.pack(">HH", u16_hi, u16_lo) if msw_first else struct.pack(">HH", u16_lo, u16_hi)
|
||||
return struct.unpack(">f", b)[0]
|
||||
|
||||
# Hilfsfunktion: wie viele 16-Bit-Register braucht dieser Typ?
|
||||
@staticmethod
|
||||
def _word_count_for_type(rtype: str) -> int:
|
||||
rt = (rtype or "").lower()
|
||||
# Passe hier an deine Excel-Typen an:
|
||||
if "uint32" in rt or "real" in rt or "float" in rt or "string(32)" in rt:
|
||||
return 2
|
||||
# Default: 1 Wort (z.B. int16/uint16)
|
||||
return 1
|
||||
|
||||
def read_one(self, address_excel: int, rtype: str) -> Optional[float]:
|
||||
"""Liest einen Wert nach Typ ('INT' oder 'REAL') unter Berücksichtigung Base-1."""
|
||||
addr = address_excel
|
||||
if rtype == "REAL":
|
||||
"""
|
||||
Liest einen Wert nach Typ ('INT' oder 'REAL' etc.).
|
||||
Es werden ausschließlich Register < 40206 gelesen.
|
||||
"""
|
||||
addr = int(address_excel)
|
||||
words = self._word_count_for_type(rtype)
|
||||
|
||||
# 2) Harte Grenze prüfen: höchstes angefasstes Register muss < 40206 sein
|
||||
if addr + words - 1 >= MAX_ADDR_EXCLUSIVE:
|
||||
# Überspringen, da der Lesevorgang die Grenze >= 40206 berühren würde
|
||||
return None
|
||||
|
||||
if words == 2:
|
||||
regs = self._read_any(addr, 2)
|
||||
if not regs or len(regs) < 2:
|
||||
return None
|
||||
# Deine bisherige Logik interpretiert 2 Worte als Float32:
|
||||
return self._to_f32_from_two(regs[0], regs[1])
|
||||
else: # INT
|
||||
else:
|
||||
regs = self._read_any(addr, 1)
|
||||
if not regs:
|
||||
return None
|
||||
return float(self._to_i16(regs[0]))
|
||||
|
||||
def get_state(self) -> Dict[str, Any]:
|
||||
"""Liest ALLE Register aus self.registers und gibt dict zurück."""
|
||||
"""
|
||||
Liest ALLE Register aus self.registers und gibt dict zurück.
|
||||
Achtet darauf, dass keine Adresse (inkl. Mehrwort) >= 40206 gelesen wird.
|
||||
"""
|
||||
data = {"Zeit": time.strftime("%Y-%m-%d %H:%M:%S")}
|
||||
for address, meta in self.registers.items():
|
||||
for address, meta in sorted(self.registers.items()):
|
||||
words = self._word_count_for_type(meta["type"])
|
||||
# 3) Nochmals Schutz auf Ebene der Iteration:
|
||||
if address + words - 1 >= MAX_ADDR_EXCLUSIVE:
|
||||
continue
|
||||
val = self.read_one(address, meta["type"])
|
||||
if val is None:
|
||||
continue
|
||||
key = f"{address} - {meta['desc']}"
|
||||
data[key] = val
|
||||
return data
|
||||
return data
|
||||
|
||||
Reference in New Issue
Block a user