Compare commits
4 Commits
a6b1010650
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7423d7c37e | ||
|
|
9f96a3e534 | ||
|
|
0b377db6c2 | ||
|
|
e75f7222a0 |
91
README.md
91
README.md
@@ -1,7 +1,90 @@
|
||||
# deyeChargeSpeed
|
||||
# Deye Charge Speed Monitor
|
||||
|
||||
https://github.com/jmccrohan/pysolarmanv5
|
||||
A Flask-based application for monitoring Deye Inverters (and compatible models) using the Solarman V5 protocol. This tool connects directly to the inverter via Modbus over TCP to read real-time data including voltages, currents, battery status, and BMS information.
|
||||
|
||||
https://pysolarmanv5.readthedocs.io/en/stable/
|
||||
## Features
|
||||
|
||||
https://pysolarmanv5.readthedocs.io/en/stable/examples.html
|
||||
- **Real-time Monitoring**: Reads critical data such as Input/Output Voltage, Grid/Load Currents, Battery SOC, Temperature, and Power.
|
||||
- **BMS Integration**: Retrieves detailed Battery Management System (BMS) data for up to two battery packs.
|
||||
- **Web Interface**: Provides a user-friendly dashboard to view inverter status (served at `/`).
|
||||
- **JSON API**: Exposes raw data via a RESTful endpoint (`/api/data`) for integration with other systems.
|
||||
- **PDF Utility**: Includes a tool to extract register information from Deye Modbus PDF manuals.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python 3.x
|
||||
- A Deye Inverter (or compatible) connected to the network.
|
||||
- Inverter IP address, Serial Number, and Modbus Slave ID.
|
||||
|
||||
## Installation
|
||||
|
||||
1. **Clone the repository:**
|
||||
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd deyeChargeSpeed
|
||||
```
|
||||
|
||||
2. **Create and activate a virtual environment:**
|
||||
|
||||
```bash
|
||||
python -m venv venv
|
||||
# Windows
|
||||
.\venv\Scripts\activate
|
||||
# Linux/Mac
|
||||
source venv/bin/activate
|
||||
```
|
||||
|
||||
3. **Install dependencies:**
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. **Configuration:**
|
||||
|
||||
Copy the example configuration file and update it with your inverter details:
|
||||
|
||||
```bash
|
||||
cp config.py.example config.py
|
||||
```
|
||||
|
||||
Edit `config.py`:
|
||||
```python
|
||||
INVERTER_IP = "192.168.x.x"
|
||||
INVERTER_SERIAL = 1234567890
|
||||
INVERTER_PORT = 8899
|
||||
INVERTER_SLAVE_ID = 1
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Start the application:**
|
||||
|
||||
```bash
|
||||
python app.py
|
||||
```
|
||||
|
||||
2. **Access the dashboard:**
|
||||
|
||||
Open your web browser and navigate to `http://localhost:5000`.
|
||||
|
||||
## Utilities
|
||||
|
||||
### PDF Register Extractor
|
||||
|
||||
Located in `docs/extract_pdf.py`, this script helps identify Modbus registers from Deye PDF manuals.
|
||||
|
||||
**Usage:**
|
||||
1. Place your PDF manual in the `docs/` folder.
|
||||
2. Update the filename in `docs/extract_pdf.py` if necessary (defaults to `Modbus储能-组串-微逆宁波德业V118-1.pdf`).
|
||||
3. Run the script:
|
||||
```bash
|
||||
python docs/extract_pdf.py
|
||||
```
|
||||
4. Check `pdf_output.txt` for the extracted register locations and context.
|
||||
|
||||
## Resources
|
||||
|
||||
- [PySolarmanV5 Documentation](https://pysolarmanv5.readthedocs.io/en/stable/)
|
||||
- [PySolarmanV5 GitHub](https://github.com/jmccrohan/pysolarmanv5)
|
||||
92
app.py
92
app.py
@@ -18,34 +18,84 @@ def get_inverter_data():
|
||||
verbose=False
|
||||
)
|
||||
|
||||
# Registers to read:
|
||||
# 150: Grid Voltage (Input Voltage) - 0.1V
|
||||
# 154: Output Voltage - 0.1V
|
||||
# 157: Load Voltage - 0.1V
|
||||
# Reading blocks:
|
||||
# Block 1: 150 - 216 (67 registers) - Voltages, Currents, Battery, PV, Control
|
||||
# Block 2: 600 - 627 (28 registers) - BMS Data
|
||||
# Block 3: 245 (1 register) - Max Grid Output
|
||||
# Block 4: 292 - 293 (2 registers) - Peak Shaving
|
||||
# Block 5: 314 - 325 (12 registers) - Advanced Limits
|
||||
|
||||
# Reading individually for simplicity, though block read is more efficient if contiguous
|
||||
# But these are slightly apart (150, 154, 157).
|
||||
# We can read a block from 150 to 157 (8 registers) and parse.
|
||||
block1 = inverter.read_holding_registers(register_addr=150, quantity=67)
|
||||
block2 = inverter.read_holding_registers(register_addr=600, quantity=28)
|
||||
block3 = inverter.read_holding_registers(register_addr=245, quantity=1)
|
||||
block4 = inverter.read_holding_registers(register_addr=292, quantity=2)
|
||||
block5 = inverter.read_holding_registers(register_addr=314, quantity=12)
|
||||
|
||||
# Let's read block starting at 150, length 8.
|
||||
# 150 -> Index 0
|
||||
# 154 -> Index 4
|
||||
# 157 -> Index 7
|
||||
def to_signed(val):
|
||||
return val if val < 32768 else val - 65536
|
||||
|
||||
data = {}
|
||||
|
||||
raw_data = inverter.read_holding_registers(register_addr=150, quantity=8)
|
||||
# Block 1 Parsing (150-216)
|
||||
data["input_voltage"] = round(block1[0] * 0.1, 1) # 150
|
||||
data["output_voltage"] = round(block1[4] * 0.1, 1) # 154
|
||||
data["load_voltage"] = round(block1[7] * 0.1, 1) # 157
|
||||
|
||||
input_voltage = raw_data[0] * 0.1
|
||||
output_voltage = raw_data[4] * 0.1
|
||||
load_voltage = raw_data[7] * 0.1
|
||||
data["grid_current"] = round(to_signed(block1[10]) * 0.01, 2) # 160
|
||||
data["grid_clamp_current"] = round(to_signed(block1[12]) * 0.01, 2) # 162
|
||||
data["output_current"] = round(to_signed(block1[14]) * 0.01, 2) # 164
|
||||
|
||||
data["load_current"] = round(to_signed(block1[29]) * 0.01, 2) # 179
|
||||
|
||||
data["batt_temp"] = round(to_signed(block1[32]) * 0.1, 1) # 182
|
||||
data["batt_voltage"] = round(block1[33] * 0.01, 2) # 183
|
||||
data["batt_soc"] = block1[34] # 184
|
||||
data["batt_charge_status"] = block1[35] # 185
|
||||
data["pv1_power"] = block1[36] # 186
|
||||
data["pv2_power"] = block1[37] # 187
|
||||
|
||||
data["batt_power"] = to_signed(block1[40]) # 190
|
||||
data["batt_current"] = round(to_signed(block1[41]) * 0.01, 2) # 191
|
||||
|
||||
data["grid_relay_status"] = block1[44] # 194
|
||||
data["gen_relay_status"] = block1[45] # 195
|
||||
|
||||
data["max_charge_current"] = block1[60] # 210
|
||||
data["max_discharge_current"] = block1[61] # 211
|
||||
data["batt_charge_efficiency"] = block1[66] # 216
|
||||
|
||||
# Block 2 Parsing (BMS 600-627)
|
||||
data["bms1_soc"] = block2[3] # 603
|
||||
data["bms1_charge_voltage"] = round(block2[6] * 0.01, 2) # 606
|
||||
data["bms1_charge_current"] = round(block2[7] * 0.1, 1) # 607
|
||||
|
||||
data["bms2_soc"] = block2[17] # 617
|
||||
data["bms2_charge_voltage"] = round(block2[20] * 0.01, 2) # 620
|
||||
data["bms2_charge_current"] = round(block2[21] * 0.1, 1) # 621
|
||||
|
||||
# Block 3 Parsing (245)
|
||||
data["max_grid_output_power"] = block3[0] # 245
|
||||
|
||||
# Block 4 Parsing (292-293)
|
||||
data["gen_peak_shaving_power"] = block4[0] # 292
|
||||
data["grid_peak_shaving_power"] = block4[1] # 293
|
||||
|
||||
# Block 5 Parsing (314-325)
|
||||
data["discharge_voltage"] = round(block5[0] * 0.01, 2) # 314
|
||||
data["charge_current_limit"] = block5[1] # 315
|
||||
data["discharge_current_limit"] = block5[2] # 316
|
||||
data["real_time_capacity"] = block5[3] # 317
|
||||
data["real_time_voltage"] = round(block5[4] * 0.01, 2) # 318
|
||||
# 319 skipped
|
||||
data["max_charge_current_limit"] = block5[6] # 320
|
||||
data["max_discharge_current_limit"] = block5[7] # 321
|
||||
# 322-324 skipped
|
||||
data["lithium_battery_type"] = block5[11] # 325
|
||||
|
||||
inverter.disconnect()
|
||||
|
||||
return {
|
||||
"input_voltage": round(input_voltage, 1),
|
||||
"output_voltage": round(output_voltage, 1),
|
||||
"load_voltage": round(load_voltage, 1),
|
||||
"status": "success"
|
||||
}
|
||||
data["status"] = "success"
|
||||
return data
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
|
||||
39
docs/extract_pdf.py
Normal file
39
docs/extract_pdf.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import os
|
||||
import pypdf
|
||||
import re
|
||||
|
||||
pdf_path = os.path.join(os.path.dirname(__file__), "Modbus储能-组串-微逆宁波德业V118-1.pdf")
|
||||
|
||||
def extract_text_from_pdf(pdf_path):
|
||||
reader = pypdf.PdfReader(pdf_path)
|
||||
text = ""
|
||||
for page in reader.pages:
|
||||
text += page.extract_text() + "\n"
|
||||
return text
|
||||
|
||||
full_text = extract_text_from_pdf(pdf_path)
|
||||
|
||||
# Registers to look for
|
||||
registers = [94, 245, 320]
|
||||
|
||||
print("Searching for registers...")
|
||||
|
||||
# Split text into lines for easier processing
|
||||
lines = full_text.split('\n')
|
||||
|
||||
found_registers = {}
|
||||
|
||||
with open("pdf_output.txt", "w", encoding="utf-8") as f:
|
||||
for i, line in enumerate(lines):
|
||||
for reg in registers:
|
||||
if re.search(r'\b' + str(reg) + r'\b', line):
|
||||
f.write(f"MATCH {reg}: {line.strip()}\n")
|
||||
# Write context
|
||||
start = max(0, i - 5)
|
||||
end = min(len(lines), i + 6)
|
||||
for j in range(start, end):
|
||||
if i != j:
|
||||
f.write(f" CTX: {lines[j].strip()}\n")
|
||||
f.write("-" * 20 + "\n")
|
||||
|
||||
print("Done. Check pdf_output.txt")
|
||||
@@ -1,5 +1,6 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
@@ -17,47 +18,6 @@
|
||||
body {
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
font-family: var(--font-family);
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-bottom: 40px;
|
||||
font-weight: 300;
|
||||
letter-spacing: 2px;
|
||||
text-transform: uppercase;
|
||||
background: linear-gradient(45deg, var(--accent-color), var(--secondary-accent));
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.dashboard {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--card-bg);
|
||||
border-radius: 15px;
|
||||
padding: 25px;
|
||||
text-align: center;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
|
||||
transition: transform 0.3s ease, box-shadow 0.3s ease;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
transform: translateY(-5px);
|
||||
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.card::before {
|
||||
@@ -118,19 +78,35 @@
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
100% { opacity: 1; }
|
||||
0% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.loading .value {
|
||||
animation: pulse 1.5s infinite;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.dashboard {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<body>
|
||||
<h1>Deye Inverter Monitor</h1>
|
||||
|
||||
<div class="dashboard">
|
||||
@@ -154,17 +130,370 @@
|
||||
<span class="value" id="load-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card-grid-current">
|
||||
<h2>Grid Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="grid-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card-clamp-current">
|
||||
<h2>Grid Clamp Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="grid-clamp-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="card-output-current">
|
||||
<h2>Output Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="output-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Battery & PV</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>Battery SOC</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="batt-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Voltage</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="batt-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="batt-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Power</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="batt-power">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Temp</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="batt-temp">--</span><span class="unit">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>PV1 Power</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="pv1-power">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>PV2 Power</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="pv2-power">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Control Status</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>Grid Relay</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="grid-relay">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Gen Relay</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="gen-relay">--</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Charge I</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="max-charge">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Discharge I</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="max-discharge">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>BMS Data</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>BMS1 SOC</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms1-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS1 Voltage</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms1-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS1 Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms1-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 SOC</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms2-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 Voltage</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms2-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 Current</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="bms2-current">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Advanced Control & Limits</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>Max Grid Output</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="max-grid-output">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Gen Peak Shaving</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="gen-peak-shaving">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Grid Peak Shaving</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="grid-peak-shaving">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Discharge Voltage</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="discharge-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Charge I Limit</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="charge-i-limit">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Discharge I Limit</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="discharge-i-limit">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Real Time Cap</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="real-time-cap">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Real Time Voltage</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="real-time-voltage">--</span><span class="unit">V</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Charge I Limit</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="max-charge-i-limit">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Discharge I Limit</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="max-discharge-i-limit">--</span><span class="unit">A</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Lithium Type</h2>
|
||||
<div class="value-container loading">
|
||||
<span class="value" id="lithium-type">--</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="status-bar">
|
||||
<span class="status-indicator" id="status-dot"></span>
|
||||
<span id="status-text">Connecting...</span>
|
||||
<div class="card">
|
||||
<h2>Battery SOC</h2>
|
||||
<div class="value-container loading"><span class="value" id="batt-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Voltage</h2>
|
||||
<div class="value-container loading"><span class="value" id="batt-voltage">--</span><span
|
||||
class="unit">V</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Current</h2>
|
||||
<div class="value-container loading"><span class="value" id="batt-current">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Power</h2>
|
||||
<div class="value-container loading"><span class="value" id="batt-power">--</span><span
|
||||
class="unit">W</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Battery Temp</h2>
|
||||
<div class="value-container loading"><span class="value" id="batt-temp">--</span><span
|
||||
class="unit">°C</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>PV1 Power</h2>
|
||||
<div class="value-container loading"><span class="value" id="pv1-power">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>PV2 Power</h2>
|
||||
<div class="value-container loading"><span class="value" id="pv2-power">--</span><span class="unit">W</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const inputVoltageEl = document.getElementById('input-voltage');
|
||||
<h2>Control Status</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>Grid Relay</h2>
|
||||
<div class="value-container loading"><span class="value" id="grid-relay">--</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Gen Relay</h2>
|
||||
<div class="value-container loading"><span class="value" id="gen-relay">--</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Charge I</h2>
|
||||
<div class="value-container loading"><span class="value" id="max-charge">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Discharge I</h2>
|
||||
<div class="value-container loading"><span class="value" id="max-discharge">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<h2>BMS Data</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>BMS1 SOC</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms1-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS1 Voltage</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms1-voltage">--</span><span
|
||||
class="unit">V</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS1 Current</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms1-current">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 SOC</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms2-soc">--</span><span class="unit">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 Voltage</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms2-voltage">--</span><span
|
||||
class="unit">V</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>BMS2 Current</h2>
|
||||
<div class="value-container loading"><span class="value" id="bms2-current">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<h2>Advanced Control & Limits</h2>
|
||||
<div class="dashboard">
|
||||
<div class="card">
|
||||
<h2>Max Grid Output</h2>
|
||||
<div class="value-container loading"><span class="value" id="max-grid-output">--</span><span
|
||||
class="unit">W</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Gen Peak Shaving</h2>
|
||||
<div class="value-container loading"><span class="value" id="gen-peak-shaving">--</span><span
|
||||
class="unit">W</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Grid Peak Shaving</h2>
|
||||
<div class="value-container loading"><span class="value" id="grid-peak-shaving">--</span><span
|
||||
class="unit">W</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Discharge Voltage</h2>
|
||||
<div class="value-container loading"><span class="value" id="discharge-voltage">--</span><span
|
||||
class="unit">V</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Charge I Limit</h2>
|
||||
<div class="value-container loading"><span class="value" id="charge-i-limit">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Discharge I Limit</h2>
|
||||
<div class="value-container loading"><span class="value" id="discharge-i-limit">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Real Time Cap</h2>
|
||||
<div class="value-container loading"><span class="value" id="real-time-cap">--</span><span
|
||||
class="unit">%</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Real Time Voltage</h2>
|
||||
<div class="value-container loading"><span class="value" id="real-time-voltage">--</span><span
|
||||
class="unit">V</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Charge I Limit</h2>
|
||||
<div class="value-container loading"><span class="value" id="max-charge-i-limit">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Max Discharge I Limit</h2>
|
||||
<div class="value-container loading"><span class="value" id="max-discharge-i-limit">--</span><span
|
||||
class="unit">A</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>Lithium Type</h2>
|
||||
<div class="value-container loading"><span class="value" id="lithium-type">--</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="status-bar"><span class="status-indicator" id="status-dot"></span><span
|
||||
id="status-text">Connecting...</span></div>
|
||||
<script>const inputVoltageEl = document.getElementById('input-voltage');
|
||||
const outputVoltageEl = document.getElementById('output-voltage');
|
||||
const loadVoltageEl = document.getElementById('load-voltage');
|
||||
const gridCurrentEl = document.getElementById('grid-current');
|
||||
const gridClampCurrentEl = document.getElementById('grid-clamp-current');
|
||||
const outputCurrentEl = document.getElementById('output-current');
|
||||
const statusDot = document.getElementById('status-dot');
|
||||
const statusText = document.getElementById('status-text');
|
||||
const valueContainers = document.querySelectorAll('.value-container');
|
||||
@@ -175,23 +504,65 @@
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
// Basic
|
||||
inputVoltageEl.textContent = data.input_voltage;
|
||||
outputVoltageEl.textContent = data.output_voltage;
|
||||
loadVoltageEl.textContent = data.load_voltage;
|
||||
|
||||
gridCurrentEl.textContent = data.grid_current;
|
||||
gridClampCurrentEl.textContent = data.grid_clamp_current;
|
||||
outputCurrentEl.textContent = data.output_current;
|
||||
|
||||
// Battery & PV
|
||||
document.getElementById('batt-soc').textContent = data.batt_soc;
|
||||
document.getElementById('batt-voltage').textContent = data.batt_voltage;
|
||||
document.getElementById('batt-current').textContent = data.batt_current;
|
||||
document.getElementById('batt-power').textContent = data.batt_power;
|
||||
document.getElementById('batt-temp').textContent = data.batt_temp;
|
||||
document.getElementById('pv1-power').textContent = data.pv1_power;
|
||||
document.getElementById('pv2-power').textContent = data.pv2_power;
|
||||
|
||||
// Control Status
|
||||
document.getElementById('grid-relay').textContent = data.grid_relay_status;
|
||||
document.getElementById('gen-relay').textContent = data.gen_relay_status;
|
||||
document.getElementById('max-charge').textContent = data.max_charge_current;
|
||||
document.getElementById('max-discharge').textContent = data.max_discharge_current;
|
||||
|
||||
// BMS Data
|
||||
document.getElementById('bms1-soc').textContent = data.bms1_soc;
|
||||
document.getElementById('bms1-voltage').textContent = data.bms1_charge_voltage;
|
||||
document.getElementById('bms1-current').textContent = data.bms1_charge_current;
|
||||
document.getElementById('bms2-soc').textContent = data.bms2_soc;
|
||||
document.getElementById('bms2-voltage').textContent = data.bms2_charge_voltage;
|
||||
document.getElementById('bms2-current').textContent = data.bms2_charge_current;
|
||||
|
||||
// Advanced Control
|
||||
document.getElementById('max-grid-output').textContent = data.max_grid_output_power;
|
||||
document.getElementById('gen-peak-shaving').textContent = data.gen_peak_shaving_power;
|
||||
document.getElementById('grid-peak-shaving').textContent = data.grid_peak_shaving_power;
|
||||
document.getElementById('discharge-voltage').textContent = data.discharge_voltage;
|
||||
document.getElementById('charge-i-limit').textContent = data.charge_current_limit;
|
||||
document.getElementById('discharge-i-limit').textContent = data.discharge_current_limit;
|
||||
document.getElementById('real-time-cap').textContent = data.real_time_capacity;
|
||||
document.getElementById('real-time-voltage').textContent = data.real_time_voltage;
|
||||
document.getElementById('max-charge-i-limit').textContent = data.max_charge_current_limit;
|
||||
document.getElementById('max-discharge-i-limit').textContent = data.max_discharge_current_limit;
|
||||
document.getElementById('lithium-type').textContent = data.lithium_battery_type;
|
||||
|
||||
statusDot.className = 'status-indicator active';
|
||||
statusText.textContent = 'Connected';
|
||||
|
||||
|
||||
valueContainers.forEach(el => el.classList.remove('loading'));
|
||||
} else {
|
||||
}
|
||||
|
||||
else {
|
||||
throw new Error(data.message || 'Unknown error');
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
|
||||
catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
statusDot.className = 'status-indicator error';
|
||||
statusText.textContent = 'Error: ' + error.message;
|
||||
// Don't reset values to '--' immediately to avoid flickering if it's just a transient network blip,
|
||||
// but maybe indicate stale data if needed. For now, keep last known values.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,4 +571,5 @@
|
||||
setInterval(fetchData, 5000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
</html>
|
||||
486
test/read_registers.py
Normal file
486
test/read_registers.py
Normal file
@@ -0,0 +1,486 @@
|
||||
"""
|
||||
Script to read and write holding registers from a Solarman inverter using the pysolarmanv5 library.
|
||||
|
||||
Usage:
|
||||
Read registers: python read_registers.py
|
||||
Write to register 230: python read_registers.py --write 230 75
|
||||
Write to register 293: python read_registers.py --write 293 5000
|
||||
Write to multiple registers: python read_registers.py --write 230 75 --write 293 5000
|
||||
|
||||
Writable registers:
|
||||
- Register 230: range 0-115
|
||||
- Register 293: range 0-6500
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import ipaddress
|
||||
|
||||
# Import required libraries with error handling
|
||||
try:
|
||||
from pysolarmanv5 import PySolarmanV5
|
||||
from pysolarmanv5.pysolarmanv5 import V5FrameError
|
||||
import umodbus.exceptions
|
||||
except ImportError as e:
|
||||
print(f"ERROR: Required library not installed: {e}")
|
||||
print("Install required libraries with: pip install pysolarmanv5 umodbus")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# Helper functions for validated configuration
|
||||
def get_env_int(name, default, min_val=None, max_val=None):
|
||||
"""
|
||||
Get integer from environment variable with validation.
|
||||
|
||||
Args:
|
||||
name: Environment variable name
|
||||
default: Default value if not set or invalid
|
||||
min_val: Minimum allowed value (optional)
|
||||
max_val: Maximum allowed value (optional)
|
||||
|
||||
Returns:
|
||||
int: Validated integer value
|
||||
"""
|
||||
value_str = os.getenv(name)
|
||||
if value_str is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
value = int(value_str)
|
||||
if min_val is not None and value < min_val:
|
||||
print(f"WARNING: {name}={value} is below minimum ({min_val}). Using default: {default}")
|
||||
return default
|
||||
if max_val is not None and value > max_val:
|
||||
print(f"WARNING: {name}={value} exceeds maximum ({max_val}). Using default: {default}")
|
||||
return default
|
||||
return value
|
||||
except ValueError:
|
||||
print(f"WARNING: Invalid {name}='{value_str}' (must be an integer). Using default: {default}")
|
||||
return default
|
||||
|
||||
|
||||
def get_env_ip(name, default):
|
||||
"""
|
||||
Get IP address from environment variable with validation.
|
||||
|
||||
Args:
|
||||
name: Environment variable name
|
||||
default: Default IP address
|
||||
|
||||
Returns:
|
||||
str: Validated IP address
|
||||
"""
|
||||
value = os.getenv(name)
|
||||
if value is None:
|
||||
return default
|
||||
|
||||
try:
|
||||
# Validate IP address format
|
||||
ipaddress.ip_address(value)
|
||||
return value
|
||||
except ValueError:
|
||||
print(f"WARNING: Invalid IP address in {name}='{value}'. Using default: {default}")
|
||||
return default
|
||||
|
||||
|
||||
# Configuration - Can be overridden with environment variables
|
||||
INVERTER_IP = get_env_ip("INVERTER_IP", "192.168.0.203")
|
||||
INVERTER_SERIAL = get_env_int("INVERTER_SERIAL", 2722455016, min_val=0, max_val=4294967295)
|
||||
INVERTER_PORT = get_env_int("INVERTER_PORT", 8899, min_val=1, max_val=65535)
|
||||
MODBUS_SLAVE_ID = get_env_int("MODBUS_SLAVE_ID", 1, min_val=0, max_val=247)
|
||||
SOCKET_TIMEOUT = get_env_int("SOCKET_TIMEOUT", 5, min_val=1, max_val=60)
|
||||
|
||||
# Registers to read
|
||||
REGISTERS = [227, 230, 292, 293]
|
||||
|
||||
# Writable registers whitelist with validation ranges
|
||||
# Format: {register_number: (min_value, max_value)}
|
||||
WRITABLE_REGISTERS = {
|
||||
230: (0, 115), # Register 230: valid range 0-115
|
||||
293: (0, 6500), # Register 293: valid range 0-6500
|
||||
}
|
||||
|
||||
|
||||
def validate_writable_registers():
|
||||
"""Validate WRITABLE_REGISTERS configuration at startup."""
|
||||
if not WRITABLE_REGISTERS:
|
||||
raise ValueError("WRITABLE_REGISTERS cannot be empty. At least one register must be configured.")
|
||||
|
||||
for reg, (min_val, max_val) in WRITABLE_REGISTERS.items():
|
||||
if not isinstance(reg, int) or reg < 0 or reg > 65535:
|
||||
raise ValueError(f"Invalid register address: {reg}. Must be 0-65535.")
|
||||
if not isinstance(min_val, int) or not isinstance(max_val, int):
|
||||
raise ValueError(f"Register {reg} range values must be integers")
|
||||
if min_val > max_val:
|
||||
raise ValueError(f"Invalid range for register {reg}: min ({min_val}) > max ({max_val})")
|
||||
if min_val < 0 or max_val > 65535:
|
||||
raise ValueError(f"Register {reg} range [{min_val}, {max_val}] outside valid Modbus range [0, 65535]")
|
||||
|
||||
|
||||
def validate_registers():
|
||||
"""Validate REGISTERS configuration at startup."""
|
||||
if not isinstance(REGISTERS, list):
|
||||
raise ValueError("REGISTERS must be a list")
|
||||
|
||||
seen = set()
|
||||
for reg in REGISTERS:
|
||||
if not isinstance(reg, int):
|
||||
raise ValueError(f"Invalid register address: {reg}. Must be an integer.")
|
||||
if reg < 0 or reg > 65535:
|
||||
raise ValueError(f"Invalid register address: {reg}. Must be 0-65535.")
|
||||
if reg in seen:
|
||||
raise ValueError(f"Duplicate register address: {reg}")
|
||||
seen.add(reg)
|
||||
|
||||
|
||||
# Validate configuration on module load
|
||||
try:
|
||||
validate_writable_registers()
|
||||
validate_registers()
|
||||
except ValueError as e:
|
||||
print(f"ERROR: Configuration validation failed: {e}")
|
||||
print("Please check WRITABLE_REGISTERS and REGISTERS configuration.")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def validate_register_arg(value_str):
|
||||
"""
|
||||
Validate register address from command line.
|
||||
|
||||
Args:
|
||||
value_str: String value from command line
|
||||
|
||||
Returns:
|
||||
int: Validated register address
|
||||
|
||||
Raises:
|
||||
ValueError: If value is invalid
|
||||
"""
|
||||
try:
|
||||
int_val = int(value_str)
|
||||
if int_val < 0 or int_val > 65535:
|
||||
raise ValueError(f"Register address must be 0-65535, got {int_val}")
|
||||
return int_val
|
||||
except ValueError as e:
|
||||
if "invalid literal" in str(e):
|
||||
raise ValueError(f"Invalid integer: {value_str}")
|
||||
raise
|
||||
|
||||
|
||||
def validate_value_arg(value_str):
|
||||
"""
|
||||
Validate register value from command line.
|
||||
|
||||
Args:
|
||||
value_str: String value from command line
|
||||
|
||||
Returns:
|
||||
int: Validated register value
|
||||
|
||||
Raises:
|
||||
ValueError: If value is invalid
|
||||
"""
|
||||
try:
|
||||
int_val = int(value_str)
|
||||
if int_val < 0 or int_val > 65535:
|
||||
raise ValueError(f"Register value must be 0-65535, got {int_val}")
|
||||
return int_val
|
||||
except ValueError as e:
|
||||
if "invalid literal" in str(e):
|
||||
raise ValueError(f"Invalid integer: {value_str}")
|
||||
raise
|
||||
|
||||
|
||||
def validate_write_operations(write_operations):
|
||||
"""
|
||||
Validate all write operations before connecting to device.
|
||||
|
||||
Args:
|
||||
write_operations: List of (register_addr, value) tuples
|
||||
|
||||
Returns:
|
||||
bool: True if all operations are valid
|
||||
|
||||
Raises:
|
||||
SystemExit: If any validation fails
|
||||
"""
|
||||
if not write_operations:
|
||||
return True
|
||||
|
||||
print("Validating write operations...")
|
||||
|
||||
for register_addr, value in write_operations:
|
||||
# Check if register is in the whitelist
|
||||
if register_addr not in WRITABLE_REGISTERS:
|
||||
print(f"\nERROR: Register {register_addr} is not in the writable registers whitelist")
|
||||
print(f"Allowed registers: {list(WRITABLE_REGISTERS.keys())}")
|
||||
sys.exit(1)
|
||||
|
||||
# Validate value is not negative
|
||||
if value < 0:
|
||||
print(f"\nERROR: Negative values not allowed. Got: {value}")
|
||||
sys.exit(1)
|
||||
|
||||
# Validate value fits in Modbus register
|
||||
if value > 65535:
|
||||
print(f"\nERROR: Value {value} exceeds maximum Modbus register value (65535)")
|
||||
sys.exit(1)
|
||||
|
||||
# Validate value range for this specific register
|
||||
min_val, max_val = WRITABLE_REGISTERS[register_addr]
|
||||
if not min_val <= value <= max_val:
|
||||
print(f"\nERROR: Value {value} out of range for register {register_addr}")
|
||||
print(f"Valid range: {min_val} to {max_val}")
|
||||
sys.exit(1)
|
||||
|
||||
print("All write operations validated.\n")
|
||||
return True
|
||||
|
||||
|
||||
def write_register(modbus, register_addr, value):
|
||||
"""
|
||||
Write a value to a holding register.
|
||||
|
||||
Note: This function assumes the register address and value have already been
|
||||
validated by validate_write_operations() before calling.
|
||||
|
||||
Args:
|
||||
modbus: PySolarmanV5 instance
|
||||
register_addr: Register address to write to (must be pre-validated)
|
||||
value: Integer value to write (must be pre-validated)
|
||||
|
||||
Returns:
|
||||
bool: True if write succeeded, False otherwise
|
||||
"""
|
||||
try:
|
||||
print(f"\nWriting value {value} to register {register_addr}...")
|
||||
|
||||
# Read current value first
|
||||
print("Reading current value...")
|
||||
current = modbus.read_holding_registers(register_addr=register_addr, quantity=1)
|
||||
|
||||
# Check for empty response
|
||||
if not current or len(current) == 0:
|
||||
print("ERROR: Failed to read current value (empty response)")
|
||||
return False
|
||||
|
||||
print(f"Current value: {current[0]}")
|
||||
|
||||
try:
|
||||
result = modbus.write_multiple_holding_registers(register_addr, [value])
|
||||
print(f"Write command sent (method: multi)({result})")
|
||||
except V5FrameError as e:
|
||||
print(f"V5FrameError: {e}")
|
||||
return False
|
||||
except umodbus.exceptions.ModbusError as e:
|
||||
print(f"Modbus protocol error: {e}")
|
||||
return False
|
||||
|
||||
# Verify the write succeeded
|
||||
print("Verifying write...")
|
||||
try:
|
||||
updated = modbus.read_holding_registers(register_addr=register_addr, quantity=1)
|
||||
|
||||
# Check for empty response
|
||||
if not updated or len(updated) == 0:
|
||||
print("ERROR: Failed to verify write (empty response)")
|
||||
return False
|
||||
|
||||
updated_value = updated[0]
|
||||
|
||||
if updated_value == value:
|
||||
print(f"SUCCESS: Register {register_addr} = {updated_value}")
|
||||
return True
|
||||
else:
|
||||
print(f"WARNING: Expected {value}, but register {register_addr} = {updated_value}")
|
||||
print("Note: Value may have been modified by device or another client")
|
||||
return False
|
||||
|
||||
except TimeoutError:
|
||||
print(f"ERROR: Timeout reading back register {register_addr}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"ERROR writing to register {register_addr}: {type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def read_and_display_registers(modbus):
|
||||
"""
|
||||
Read and display the configured registers.
|
||||
|
||||
Args:
|
||||
modbus: PySolarmanV5 instance
|
||||
"""
|
||||
try:
|
||||
# Check if REGISTERS list is empty
|
||||
if not REGISTERS:
|
||||
print("WARNING: No registers configured to read")
|
||||
return
|
||||
|
||||
# Read and display each register
|
||||
print("Reading holding registers:")
|
||||
print("-" * 50)
|
||||
|
||||
for register_addr in REGISTERS:
|
||||
try:
|
||||
# Read single register
|
||||
result = modbus.read_holding_registers(
|
||||
register_addr=register_addr,
|
||||
quantity=1
|
||||
)
|
||||
|
||||
# Check for empty response
|
||||
if not result or len(result) == 0:
|
||||
print(f"Register {register_addr:>3}: Error - empty response")
|
||||
continue
|
||||
|
||||
# Extract value (result is a list)
|
||||
value = result[0]
|
||||
|
||||
# Display the register and its value
|
||||
print(f"Register {register_addr:>3}: {value:>5} (0x{value:04X})")
|
||||
|
||||
except (V5FrameError, umodbus.exceptions.IllegalDataAddressError) as e:
|
||||
print(f"Register {register_addr:>3}: Error reading - {e}")
|
||||
except Exception as e:
|
||||
print(f"Register {register_addr:>3}: Unexpected error - {e}")
|
||||
|
||||
print("-" * 50)
|
||||
print("\nRead complete!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nError reading registers: {e}")
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function to parse arguments and execute operations."""
|
||||
# Parse command line arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Read and write Solarman inverter holding registers",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=f"""
|
||||
Examples:
|
||||
Read registers: python read_registers.py
|
||||
Write to register 230: python read_registers.py --write 230 75
|
||||
Write to register 293: python read_registers.py --write 293 5000
|
||||
Write to multiple registers: python read_registers.py --write 230 75 --write 293 5000
|
||||
Enable verbose output: python read_registers.py --verbose
|
||||
|
||||
Writable registers and their valid ranges:
|
||||
{chr(10).join(f' Register {reg}: {min_val}-{max_val}' for reg, (min_val, max_val) in WRITABLE_REGISTERS.items())}
|
||||
|
||||
Environment Variables:
|
||||
INVERTER_IP - IP address of Solarman data logger (default: {INVERTER_IP})
|
||||
INVERTER_SERIAL - Serial number of data logger (default: {INVERTER_SERIAL})
|
||||
INVERTER_PORT - TCP port (default: {INVERTER_PORT})
|
||||
MODBUS_SLAVE_ID - Modbus slave ID (default: {MODBUS_SLAVE_ID})
|
||||
SOCKET_TIMEOUT - Socket timeout in seconds (default: {SOCKET_TIMEOUT})
|
||||
"""
|
||||
)
|
||||
parser.add_argument(
|
||||
'--write',
|
||||
nargs=2,
|
||||
type=str, # Parse as strings for better validation
|
||||
metavar=('REGISTER', 'VALUE'),
|
||||
action='append',
|
||||
dest='write_operations',
|
||||
help='Write VALUE to REGISTER (can be used multiple times)'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--verbose',
|
||||
action='store_true',
|
||||
help='Enable verbose protocol output for debugging'
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate and convert write operations
|
||||
if args.write_operations:
|
||||
validated_operations = []
|
||||
for reg_str, val_str in args.write_operations:
|
||||
try:
|
||||
register_addr = validate_register_arg(reg_str)
|
||||
value = validate_value_arg(val_str)
|
||||
validated_operations.append((register_addr, value))
|
||||
except ValueError as e:
|
||||
print(f"ERROR: Invalid write argument: {e}")
|
||||
sys.exit(1)
|
||||
args.write_operations = validated_operations
|
||||
|
||||
print("=" * 50)
|
||||
print("Solarman Register Reader/Writer")
|
||||
print("=" * 50)
|
||||
print()
|
||||
|
||||
# Pre-validate write operations before connecting
|
||||
validate_write_operations(args.write_operations)
|
||||
|
||||
modbus = None
|
||||
write_failures = []
|
||||
|
||||
try:
|
||||
# Initialize connection
|
||||
print(f"Connecting to {INVERTER_IP}:{INVERTER_PORT} (Serial: {INVERTER_SERIAL})...")
|
||||
modbus = PySolarmanV5(
|
||||
address=INVERTER_IP,
|
||||
serial=INVERTER_SERIAL,
|
||||
port=INVERTER_PORT,
|
||||
mb_slave_id=MODBUS_SLAVE_ID,
|
||||
socket_timeout=SOCKET_TIMEOUT,
|
||||
verbose=args.verbose,
|
||||
v5_error_correction=True
|
||||
)
|
||||
print("Connected successfully!")
|
||||
|
||||
# Validate connection with a test read
|
||||
if REGISTERS:
|
||||
try:
|
||||
test_read = modbus.read_holding_registers(register_addr=REGISTERS[0], quantity=1)
|
||||
if test_read and len(test_read) > 0:
|
||||
print(f"Connection verified (read register {REGISTERS[0]})!\n")
|
||||
else:
|
||||
print(f"WARNING: Connection test to register {REGISTERS[0]} returned empty response\n")
|
||||
except Exception as e:
|
||||
print(f"WARNING: Connection test to register {REGISTERS[0]} failed: {e}")
|
||||
print("This may indicate a connection issue or invalid register address.")
|
||||
print("Continuing anyway...\n")
|
||||
else:
|
||||
print("Skipping connection test (no registers configured)\n")
|
||||
|
||||
# Perform write operations if requested
|
||||
if args.write_operations:
|
||||
for register_addr, value in args.write_operations:
|
||||
success = write_register(modbus, register_addr, value)
|
||||
if not success:
|
||||
print(f"Write operation failed for register {register_addr}!")
|
||||
write_failures.append(register_addr)
|
||||
|
||||
# Always read registers to show current values
|
||||
print()
|
||||
read_and_display_registers(modbus)
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nConnection error: {e}")
|
||||
print("Please check your IP address, serial number, and network connection.")
|
||||
sys.exit(1)
|
||||
|
||||
finally:
|
||||
# Ensure disconnection
|
||||
if modbus:
|
||||
try:
|
||||
modbus.disconnect()
|
||||
print("\nDisconnected from inverter.")
|
||||
except Exception as e:
|
||||
# Log but don't raise - we're already cleaning up
|
||||
print(f"\nWarning: Error during disconnect: {e}")
|
||||
|
||||
# Exit with error code if any write operations failed
|
||||
if write_failures:
|
||||
print(f"\nERROR: Failed to write to {len(write_failures)} register(s): {write_failures}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user