Files
SplitNotes/ls_connection.py
ApfelTeeSaft ca2a6d93a6 Add Multi Platform Support
MacOS and Linux Support
Refined Build Setup
2025-08-01 10:07:32 +02:00

114 lines
2.5 KiB
Python

"""
ls refers to LiveSplit in the entire document.
Conversation with livesplit is done through the server component.
"""
import socket
from threading import Thread
import config
import select # used for checking if socket has data pending
def ls_connect(ls_socket, call_func, window, server_port):
"""Connects given socket to the livesplit server."""
con_thread = Thread(target=try_connection, args=(ls_socket, call_func, window, server_port))
con_thread.daemon = True # Make thread daemon so it doesn't prevent app exit
con_thread.start()
def init_socket():
"""Returns a fresh socket"""
return socket.socket()
def try_connection(ls_socket, call_func, window, server_port):
"""
Tries to connect given socket to ls.
If connection is successful given "call_func"
is called with window as argument.
(made to be ran in a separate thread)
"""
try:
ls_socket.connect((config.HOST, server_port))
except:
return False
call_func(window)
def close_socket(com_socket):
"""Closes given socket."""
try:
com_socket.close()
except:
pass # Socket might already be closed
def check_connection(ls_socket):
"""
Check so connection between socket and livesplit
is still active and working.
Returns boolean
"""
if send_to_ls(ls_socket, "best_possible"):
return True
else:
return False
def send_to_ls(ls_socket, command):
"""
Sends given command to ls using given socket.
If connected is False, tries to send without socket being connected to ls.
Returns the response, or False if an error occurs.
Check config.LS_COMMANDS for available commands.
"""
try:
ls_socket.send(str.encode(config.LS_COMMANDS[command]))
except:
return False
# Use select to check if data is available, with timeout
try:
socket_ready = select.select([ls_socket], [], [], config.COM_TIMEOUT)
if socket_ready[0]:
try:
return (ls_socket.recv(1000)).decode("utf-8")
except:
return False
else:
return False
except:
return False
def get_split_index(ls_socket):
"""
Returns the index of the active split in livesplit.
Returns -1 if timer is not yet started.
(First split is 0)
Returns False on Error
"""
ls_data = send_to_ls(ls_socket, "cur_split_index")
if not isinstance(ls_data, bool):
try:
return int(ls_data.strip())
except:
return False
else:
return False
def get_split_name(ls_socket):
"""
Returns name of the active split in livesplit.
Returns False if no split is active or Error occurs.
"""
ls_data = send_to_ls(ls_socket, "cur_split_name")
if ls_data:
return ls_data.strip()
else:
return False