import socket import time import signal import sys # Server details HOST = '127.0.0.1' # Loopback address PORT = 18082 # Port used by the SimHub Property Server sock = None def create_socket(): global sock sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((HOST, PORT)) except (ConnectionRefusedError, OSError): print("Failed to connect to the server. Is it running?") return None return sock def signal_handler(sig, frame): print("\nClosing connection.") disconnect_from_server() # Calling here to handle disconnection sys.exit(0) def disconnect_from_server(): """Send a disconnect command to the server and close the socket.""" global sock if sock: try: sock.sendall(b'disconnect\n') print("Sent disconnect command to the server.") except Exception as e: print(f"Error sending disconnect command: {e}") finally: sock.close() print("Connection closed.") sock = None # Reset socket variable def main(): signal.signal(signal.SIGINT, signal_handler) # Handle Ctrl+C while True: sock = create_socket() if sock is None: time.sleep(2) # Retry after 2 seconds continue print("Subscribing...") sock.sendall('subscribe dcp.gd.Fuel\n'.encode()) sock.sendall('subscribe dcp.gd.CompletedLaps\n'.encode()) sock.sendall('subscribe DataCorePlugin.GameData.SessionTimeLeft\n'.encode()) sock.sendall('subscribe DataCorePlugin.GameData.SessionTypeName\n'.encode()) sock.sendall('subscribe DataCorePlugin.GameData.PlayerLeaderboardPosition\n'.encode()) sock.sendall('subscribe DataCorePlugin.GameData.Position\n'.encode()) #if([DataCorePlugin.Computed.Fuel_LitersPerLap],[DataCorePlugin.Computed.Fuel_LitersPerLap],[GameRawData.FuelPerLap]) sock.sendall('subscribe DataCorePlugin.Computed.Fuel_LitersPerLap\n'.encode()) try: while True: # data = sock.recv(1024) # Buffer size data = sock.recv(2028) # Buffer size if not data: break value_str = data.decode('utf-8').ztrip() if value_str and not isinstance(value_str, str): raise TypeError("Received data is not a string.") messages = value_str.split('\n') for m in messages: if m.startswith('Property'): # print('>', m, len(m.split())) d = m.split() if len(d) == 4: print('>', m.ztrip()) prop = d[1].split('.')[-1] value = d[3] print(prop, value) # print('>', value_str) time.sleep(2) except TypeError as e: print(f"A type error occurred: {e}") except Exception as e: print(f"An error occurred: {e}") finally: disconnect_from_server() # Call the disconnect function break # Exit the loop after disconnection if __name__ == "__main__": main()