From 260ce4efec7cad1c3ecb3edcb85c9bec206dc3a5 Mon Sep 17 00:00:00 2001 From: Jan Benicek Date: Wed, 17 Jul 2024 08:41:16 +0200 Subject: [PATCH] upgraded script to close connection to DB od error --- .env.exampe | 8 +++++--- src/main.py | 25 ++++++++----------------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/.env.exampe b/.env.exampe index f97f604..fcba763 100644 --- a/.env.exampe +++ b/.env.exampe @@ -1,5 +1,7 @@ -INVERTER_HOST=10.1.20.230 -INVERTER_UNIQUE_TAG=Potec180_inverter_1 +INVERTER_HOST=1.2.3.4 +INVERTER_UNIQUE_TAG=Unique_inverter_identifier MONGODB_HOST=mongodbIP MONGODB_PORT=27017 -MONGODB_DB=DB \ No newline at end of file +MONGODB_DB=DB +MONGODB_USER=mongodb_username +MONGODB_PASS=mongodb_pass \ No newline at end of file diff --git a/src/main.py b/src/main.py index 0524bc0..1174a74 100644 --- a/src/main.py +++ b/src/main.py @@ -1,8 +1,6 @@ -import goodwe, asyncio, time, json +import goodwe, asyncio, time, json, motor, motor.motor_asyncio -import motor.motor_asyncio from configuration import get_config -import motor config = get_config() @@ -14,24 +12,16 @@ async def read_inverter(inverter): return await inverter.read_runtime_data() -async def get_mongodb_collection(host: str, port: str, db: str, username: str, password: str): - client = motor.motor_asyncio.AsyncIOMotorClient(f"mongodb://{username}:{password}@{host}:{port}/") - return client[db]["inverters_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) - db_collection = await get_mongodb_collection(host=config.mongodb_host, port=config.mongodb_port, db=config.mongodb_db, username=config.mongodb_user, password=config.mongodb_pass) + 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("------------------------------------------------") @@ -40,7 +30,8 @@ async def main(): 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: