feat: made ping system for automatic disconnection

events, and fixed some issues.

ref: N25B-150
This commit is contained in:
Björn Otgaar
2025-10-08 14:30:55 +02:00
parent ae60105b4d
commit da14a67791

37
main.py
View File

@@ -24,15 +24,10 @@ def listen_for_messages(session):
socket.connect("tcp://localhost:5556")
socket.setsockopt_string(zmq.SUBSCRIBE, u"") # u because Python 2 shenanigans
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
logging.info("Listening for messages")
# Let the CB know we're connected.
pub = context.socket(zmq.PUB)
pub.bind("tcp://*:5555")
time.sleep(1)
print("Now attempting to send connection data to CB.")
connection_data = {
@@ -45,16 +40,42 @@ def listen_for_messages(session):
connection_json = json.dumps(connection_data)
pub.send_string(connection_json)
print("Send data: ", connection_json)
listening_loop(socket, pub)
def listening_loop(socket, pub):
print("Entered listening loop.")
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
logging.info("Listening for messages")
while not state.exit_event.is_set():
if not poller.poll(200): continue # At most 200 ms delay after CTRL+C
# We now know there's a message waiting for us
message = socket.recv_string()
logging.debug("Received message: {}".format(message))
handle_message(message, pub)
if session: say(session, message)
def handle_message(msg, pub):
"""
Parse the message and act accordingly to conditional statements.
"""
msgs = msg.split(",") # Let's split the attributes
if msgs[0] == "ping":
# return ping
ping_data = {
"event": "ping",
"id": state.__getattribute__("id"),
}
ping_json = json.dumps(ping_data)
pub.send_string(ping_json)
logging.debug("Returned ping.")
return
# Other if statements such as `if msgs[0] == "say"`
return
def get_session():
if "--qi-url" not in sys.argv:
logging.info("No Qi URL argument given. Running in stand-alone mode.")
@@ -118,10 +139,8 @@ def main():
state.name = name
logging.info("Session ID: {} (from {})".format(unique_id, id_source))
listen_for_messages(session)
if __name__ == "__main__":
try:
state.initialize()