Skip to content

Commit

Permalink
process ends when reinit fails max_reinit times
Browse files Browse the repository at this point in the history
  • Loading branch information
Heiko Bauer committed Mar 11, 2024
1 parent e2a8924 commit be1d005
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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 <heiko_bauer@icloud.com>"]
repository = "https://github.com/die-bauerei/smart-meter-to-openhab"
Expand Down
35 changes: 25 additions & 10 deletions smart_meter_to_openhab_scripts/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import logging
import os
import sys
import subprocess
from datetime import timedelta, datetime
from pathlib import Path
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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")
Expand All @@ -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()
Expand All @@ -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()

0 comments on commit be1d005

Please sign in to comment.