Goodwe_reader/src/main.py

41 lines
1.4 KiB
Python

import goodwe, asyncio, time, json, motor, motor.motor_asyncio
from configuration import get_config
config = get_config()
async def connect_to_inverter(ip: str):
return await goodwe.connect(host=ip)
async def read_inverter(inverter):
return await inverter.read_runtime_data()
async def get_mongodb_client(host: str, port: str, username: str, password: str):
return motor.motor_asyncio.AsyncIOMotorClient(f"mongodb://{username}:{password}@{host}:{port}/")
async def main():
try:
print(f"Connecting to inverter: {config.inverter_host}")
connected_inverter = await connect_to_inverter(ip=config.inverter_host)
mongodb_client = await get_mongodb_client(host=config.mongodb_host, port=config.mongodb_port, username=config.mongodb_user, password=config.mongodb_pass)
db_collection = mongodb_client[config.mongodb_db]["inverters_data"]
while True:
print("")
print("------------------------------------------------")
data = await read_inverter(inverter=connected_inverter)
data["inverter_unique_tag"] = config.inverter_unique_tag
print(json.dumps(data, default=str))
inserted = await db_collection.insert_one(data)
print(f"data saved with id: {inserted.inserted_id}")
except:
mongodb_client.close()
while True:
try:
asyncio.run(main())
except:
print("Error --> script restart")
time.sleep(1)