This commit is contained in:
Your Name
2024-02-15 23:36:30 -06:00
parent a5adf74b23
commit 8c60f0956b
7 changed files with 117 additions and 8 deletions

32
shell/watcher.example.py Normal file
View File

@@ -0,0 +1,32 @@
import socket
import json
# Initialize the socket without connecting
sock = None
def ensure_socket_connected():
global sock
if sock is None or sock.fileno() == -1: # Checks if socket is not initialized or closed
try:
# Attempt to initialize and connect the socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect("/tmp/oscar_watcher.sock")
except socket.error:
# If connection fails, set sock to None and do nothing
sock = None
def log_watch(var_name, message):
ensure_socket_connected() # Ensure the socket is connected before attempting to log
if sock: # Proceed only if sock is not None (i.e., is connected)
message_json = json.dumps(message)
try:
sock.sendall(message_json.encode('utf-8') + b'\n')
except socket.error:
# Handle potential error in sending (e.g., if connection was lost)
global sock
sock.close() # Close the current socket to clean up resources
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)