import time import traceback from src.hardware import Hardware from src.logic import loop from src.util import parse_commandline_args, connect_modbus_client from src.config import MAX_RECONNECTION_ATTEMPTS, INITIAL_BACKOFF_TIME def main(): args = parse_commandline_args() reconnection_attempts = 0 while True: try: client = connect_modbus_client(args) reconnection_attempts = 0 # Reset attempts on successful connection hardware = Hardware(client, args.slave_id) while True: start_time = time.time() hardware.sync_hardware_state() loop(hardware) execution_time = time.time() - start_time if execution_time > args.cycle_time: print(f"Warning: Loop execution time ({execution_time:.4f}s) exceeded cycle time ({args.cycle_time:.4f}s)") sleep_time = max(0, args.cycle_time - execution_time) time.sleep(sleep_time) except KeyboardInterrupt: print("Stopped by user") break except ConnectionError as e: print(f"Connection error: {e}") break # Exit if we've already tried the maximum number of reconnection attempts except Exception as e: print(f"Error: {e}") print(traceback.format_exc()) reconnection_attempts += 1 if reconnection_attempts >= MAX_RECONNECTION_ATTEMPTS: print("Maximum reconnection attempts reached. Exiting.") break backoff_time = INITIAL_BACKOFF_TIME * (2 ** reconnection_attempts) print(f"Attempting to reconnect in {backoff_time} seconds...") time.sleep(backoff_time) finally: if 'client' in locals(): client.close() if __name__ == "__main__": main()