From f3c252939487446e273430667b1a9e1584115d38 Mon Sep 17 00:00:00 2001 From: Tempest Date: Fri, 8 Aug 2025 15:52:38 +0700 Subject: [PATCH] Handled Ctrl C gracefully... I hope. --- src/controllerSoftware/app.py | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/controllerSoftware/app.py b/src/controllerSoftware/app.py index f7ffeda..0fb368b 100644 --- a/src/controllerSoftware/app.py +++ b/src/controllerSoftware/app.py @@ -4,6 +4,9 @@ from bleak import BleakScanner, BleakClient import threading import time import json +import sys +import signal +import os # ================================================================================================= # APP CONFIGURATION @@ -125,7 +128,8 @@ async def connect_to_ble_device(): await ble_client.connect() if ble_client.is_connected: print(f"Connected to {target_device.name}") - services = ble_client.services + services = [service for service in ble_client.services if service.handle != 1] + # The previous logic for filtering services seems incorrect; let's grab all characteristics characteristics = [ char for service in services for char in service.characteristics @@ -247,7 +251,32 @@ def set_matrix(): # APP STARTUP # ================================================================================================= +def signal_handler(signum, frame): + print("Received shutdown signal, gracefully shutting down...") + if not DEBUG_MODE and ble_client and ble_client.is_connected: + print("Disconnecting BLE client...") + disconnect_future = asyncio.run_coroutine_threadsafe(ble_client.disconnect(), ble_event_loop) + try: + # Wait for the disconnect to complete with a timeout + disconnect_future.result(timeout=5) + print("BLE client disconnected successfully.") + except Exception as e: + print(f"Error during BLE disconnect: {e}") + + if not DEBUG_MODE and ble_event_loop and ble_event_loop.is_running(): + print("Stopping BLE event loop...") + # Schedule a stop and wait for the thread to finish + ble_event_loop.call_soon_threadsafe(ble_event_loop.stop) + ble_thread.join(timeout=1) + print("BLE event loop stopped.") + + os._exit(0) + if __name__ == '__main__': + # Register the signal handler before running the app + signal.signal(signal.SIGINT, signal_handler) + signal.signal(signal.SIGTERM, signal_handler) + if not DEBUG_MODE: print("Starting BLE event loop in background thread...") ble_event_loop = asyncio.new_event_loop() @@ -258,4 +287,4 @@ if __name__ == '__main__': future = asyncio.run_coroutine_threadsafe(connect_to_ble_device(), ble_event_loop) future.result(timeout=10) # Wait up to 10 seconds for connection - app.run(debug=True, use_reloader=False) \ No newline at end of file + app.run(debug=True, use_reloader=False, host="0.0.0.0")