import socket import json # Initialize the socket without connecting watcher_sock = None class Watcher: def ensure_socket_connected(): global watcher_sock if watcher_sock is None or watcher_sock.fileno() == -1: # Checks if socket is not initialized or closed try: # Attempt to initialize and connect the socket watcher_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) watcher_sock.connect("/tmp/oscar_watcher.sock") except socket.error: # If connection fails, set sock to None and do nothing watcher_sock = None def log_watch(var_name, message): global watcher_sock self.ensure_socket_connected() # Ensure the socket is connected before attempting to log if watcher_sock: # Proceed only if sock is not None (i.e., is connected) message_json = json.dumps(message) try: watcher_sock.sendall(message_json.encode('utf-8') + b'\n') except socket.error: nothing=False # Handle potential error in sending (e.g., if connection was lost) watcher_sock.close() # Close the current socket to clean up resources watcher_sock = None # Reset sock to ensure reconnection attempt on next call #message = {"variable": "car_stats", "value": {"car_lights_on": [3, 5, 7], "car_state": "on"}} #log_watch(sock, message)