from flask import Flask, jsonify, render_template
from pysolarmanv5 import PySolarmanV5
import config

app = Flask(__name__)

def get_inverter_data():
    """
    Connects to the inverter and reads voltage registers.
    Returns a dictionary with the data.
    """
    try:
        inverter = PySolarmanV5(
            config.INVERTER_IP,
            config.INVERTER_SERIAL,
            port=config.INVERTER_PORT,
            mb_slave_id=config.INVERTER_SLAVE_ID,
            verbose=False
        )
        
        # Registers to read:
        # 150: Grid Voltage (Input Voltage) - 0.1V
        # 154: Output Voltage - 0.1V
        # 157: Load Voltage - 0.1V
        
        # 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.
        
        # Let's read block starting at 150, length 8.
        # 150 -> Index 0
        # 154 -> Index 4
        # 157 -> Index 7
        
        raw_data = inverter.read_holding_registers(register_addr=150, quantity=8)
        
        input_voltage = raw_data[0] * 0.1
        output_voltage = raw_data[4] * 0.1
        load_voltage = raw_data[7] * 0.1
        
        inverter.disconnect()
        
        return {
            "input_voltage": round(input_voltage, 1),
            "output_voltage": round(output_voltage, 1),
            "load_voltage": round(load_voltage, 1),
            "status": "success"
        }
        
    except Exception as e:
        return {
            "status": "error",
            "message": str(e)
        }

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/data')
def api_data():
    data = get_inverter_data()
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
