Files
oscarpilot/shell/watcher.example.py
Your Name 8c60f0956b wip
2024-02-15 23:36:30 -06:00

33 lines
1.3 KiB
Python

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)