From be1d00537159e327306999c92003babcdb165973 Mon Sep 17 00:00:00 2001 From: Heiko Bauer Date: Mon, 11 Mar 2024 11:10:37 +0100 Subject: [PATCH] process ends when reinit fails max_reinit times --- pyproject.toml | 2 +- smart_meter_to_openhab_scripts/main.py | 35 ++++++++++++++++++-------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index d8122cb..3b06853 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "smart_meter_to_openhab" -version = "0.3.0" +version = "0.3.1" description = "Pushing data of ISKRA MT175 smart meter to openhab" authors = ["Heiko Bauer "] repository = "https://github.com/die-bauerei/smart-meter-to-openhab" diff --git a/smart_meter_to_openhab_scripts/main.py b/smart_meter_to_openhab_scripts/main.py index b82f870..1f3b280 100644 --- a/smart_meter_to_openhab_scripts/main.py +++ b/smart_meter_to_openhab_scripts/main.py @@ -1,6 +1,7 @@ import argparse import logging import os +import sys import subprocess from datetime import timedelta, datetime from pathlib import Path @@ -39,8 +40,9 @@ def create_args_parser() -> argparse.ArgumentParser: help="Specifies the number of performed reads that are averaged per interval. Between each read is a sleep of 1 sec.") parser.add_argument("--interval_in_sec", type=int, required=False, default=10, help="Interval in which the data will be read and pushed") parser.add_argument("--ping_in_min", type=int, required=False, default=10, help="Reinit if no data can be found in the openHAB DB in the given timeframe") - parser.add_argument("--logfile", type=Path, required=False, help="Write logging to this file instead of to stdout") + parser.add_argument("--max_reinit", type=int, required=False, default=5, help="Exit process with Return Code 1 when pinging stays unsuccessful.") parser.add_argument('--uhubctl', action='store_true', help="Use uhubctl to power off and on the usb port on reinit") + parser.add_argument("--logfile", type=Path, required=False, help="Write logging to this file instead of to stdout") parser.add_argument('-v', '--verbose', action='count', default=0) return parser @@ -50,7 +52,7 @@ def _exec_process(params : List[str]) -> None: if rc != 0: raise Exception("Failed to execute command "+ ' '.join(params)+". Return code was: "+str(result.returncode)) -def _run(process_start_time : datetime, logger : logging.Logger, read_count : int, interval_in_sec : int, ping_in_min : int, use_uhubctl : bool) -> None: +def _run(process_start_time : datetime, logger : logging.Logger, read_count : int, interval_in_sec : int, ping_in_min : int, use_uhubctl : bool) -> bool: from smart_meter_to_openhab.openhab import OpenhabConnection from smart_meter_to_openhab.sml_iskra_mt175 import SmlIskraMt175 from smart_meter_to_openhab.sml_reader import SmlReader @@ -62,9 +64,9 @@ def _run(process_start_time : datetime, logger : logging.Logger, read_count : in sml_iskra = SmlIskraMt175('/dev/ttyUSB0', logger) sml_reader = SmlReader(logger) logger.info("Connections established. Starting to transfer smart meter values to openhab.") - ping_succeeded = True ping_timedelta = timedelta(minutes=ping_in_min) - while ping_succeeded: + ping_succeeded=False + while True: logger.info("Reading SML data") ref_smart_meter_value=oh_connection.get_median_from_items(SmartMeterValues.oh_item_names()) values, extended_values=sml_reader.read_avg_from_sml_and_compute_extended_values(sml_iskra.read, read_count, ref_smart_meter_value) @@ -73,12 +75,14 @@ def _run(process_start_time : datetime, logger : logging.Logger, read_count : in oh_connection.post_to_items(values) oh_connection.post_to_items(extended_values) logger.info("Values posted to openHAB") + sleep(interval_in_sec) # start pinging after process is running for the specified time if (datetime.now() - process_start_time) > ping_timedelta: - logger.info("Ping openHAB items to check if updated") - ping_succeeded = oh_connection.check_if_updated(SmartMeterValues.oh_item_names(), ping_timedelta) and oh_connection.check_if_updated( - ExtendedSmartMeterValues.oh_item_names(), ping_timedelta) - sleep(interval_in_sec) + if not (oh_connection.check_if_updated(SmartMeterValues.oh_item_names(), ping_timedelta) + and oh_connection.check_if_updated(ExtendedSmartMeterValues.oh_item_names(), ping_timedelta)): + break + ping_succeeded=True + logger.info("openHAB items ping successful.") if use_uhubctl: logger.error("openHAB items seem to have not been updated - Power off and on usb ports and reinit process") @@ -87,6 +91,8 @@ def _run(process_start_time : datetime, logger : logging.Logger, read_count : in sleep(1) else: logger.error("openHAB items seem to have not been updated - reinit process") + + return ping_succeeded def main() -> None: parser=create_args_parser() @@ -99,12 +105,21 @@ def main() -> None: logger.setLevel(log_level_from_arg(args.verbose)) try: process_start_time=datetime.now() - while True: - _run(process_start_time, logger, args.smart_meter_read_count, args.interval_in_sec, args.ping_in_min, args.uhubctl) + unsuccessful_reinit_count=0 + while unsuccessful_reinit_count < args.max_reinit: + if _run(process_start_time, logger, args.smart_meter_read_count, args.interval_in_sec, args.ping_in_min, args.uhubctl): + unsuccessful_reinit_count=0 + else: + unsuccessful_reinit_count+=1 + logger.error("No improvement after reinit. Trying again.") + except Exception as e: logger.exception("Caught Exception: " + str(e)) except: logger.exception("Caught unknow exception") + + logger.error("Unable to upload valid data to openHAB. Exiting Process with Return Code 1.") + sys.exit(1) if __name__ == '__main__': main() \ No newline at end of file