This commit is contained in:
Your Name
2024-02-16 19:31:03 -06:00
parent 19673dc652
commit 5c2c44b780
3 changed files with 11 additions and 10 deletions

View File

@@ -5,6 +5,7 @@ import json
watcher_sock = None
class Watcher:
@staticmethod
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
@@ -16,19 +17,17 @@ class Watcher:
# If connection fails, set sock to None and do nothing
watcher_sock = None
@staticmethod
def log_watch(var_name, message):
global watcher_sock
self.ensure_socket_connected() # Ensure the socket is connected before attempting to log
Watcher.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)
message_json = json.dumps({var_name: 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)
watcher_sock = None # Ensure that the next attempt will try to reconnect
finally:
watcher_sock.close() # Close the current socket to clean up resources
watcher_sock = None # Reset sock to ensure reconnection attempt on next call