From 8f4414bc6176acdaf28326567f5b11a0623b7e26 Mon Sep 17 00:00:00 2001 From: Benedict Diederich Date: Wed, 18 Dec 2024 05:12:33 -0800 Subject: [PATCH] ensure flowstop stops if disk is full --- imswitch/imcommon/framework/noqt.py | 42 ++++++------------- imswitch/imcommon/model/dirtools.py | 20 ++++++++- .../controllers/FlowStopController.py | 3 ++ 3 files changed, 34 insertions(+), 31 deletions(-) diff --git a/imswitch/imcommon/framework/noqt.py b/imswitch/imcommon/framework/noqt.py index 34ee7fc8..78ba7bc5 100644 --- a/imswitch/imcommon/framework/noqt.py +++ b/imswitch/imcommon/framework/noqt.py @@ -14,7 +14,7 @@ import cv2 import base64 from imswitch import SOCKET_STREAM - +import time if TYPE_CHECKING: from typing import Tuple, Callable, Union @@ -85,6 +85,7 @@ def _handle_image_signal(self, args): # adjust the parameters of the jpeg compression quality = 80 # Set the desired quality level (0-100) encode_params = [cv2.IMWRITE_JPEG_QUALITY, quality] + # Compress image using JPEG format flag, compressed = cv2.imencode(".jpg", output_frame, encode_params) encoded_image = base64.b64encode(compressed).decode('utf-8') @@ -115,40 +116,21 @@ def _generate_json_message(self, args): # Consider using msgpack for efficiency return data + + def _safe_broadcast_message(self, message: dict) -> None: - """Ensure that the emit is scheduled properly.""" + """Throttle the emit to avoid task buildup.""" + now = time.time() + if now - self.last_emit_time < self.emit_interval: + print("too fast") + return # Skip if emit interval hasn't passed + self.last_emit_time = now + try: - # Schedule the emit coroutine in the server's event loop sio.start_background_task(sio.emit, "signal", json.dumps(message)) except Exception as e: - ''' + print(f"Error broadcasting message via Socket.IO: {e}") try: - try: - loop = asyncio.get_event_loop() - except RuntimeError: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - #loop.run_forever() - if loop.is_running(): - asyncio.run_coroutine_threadsafe(sio.emit("signal", json.dumps(message)), loop) - else: - sio.start_background_task(sio.emit, "signal", json.dumps(message)) - except Exception as e: - ''' - - def _safe_broadcast_message(self, message: dict) -> None: - """Throttle the emit to avoid task buildup.""" - now = time.time() - if now - self.last_emit_time < self.emit_interval: - return # Skip if emit interval hasn't passed - self.last_emit_time = now - - try: - sio.start_background_task(sio.emit, "signal", json.dumps(message)) - except Exception as e: - print(f"Error broadcasting message via Socket.IO: {e}") - try: - print(f"Error broadcasting message via Socket.IO: {e}") asyncio.run_coroutine_threadsafe(sio.emit("signal", json.dumps(message)), asyncio.new_event_loop()) except Exception as e: print(f"Error broadcasting message via Socket.IO: {e}") diff --git a/imswitch/imcommon/model/dirtools.py b/imswitch/imcommon/model/dirtools.py index 969431f3..c445816b 100644 --- a/imswitch/imcommon/model/dirtools.py +++ b/imswitch/imcommon/model/dirtools.py @@ -2,7 +2,7 @@ import os from abc import ABC from pathlib import Path -from shutil import copy2 +from shutil import copy2, disk_usage from imswitch import IS_HEADLESS, __file__, DEFAULT_CONFIG_PATH, DEFAULT_DATA_PATH @@ -34,6 +34,24 @@ def getSystemUserDir(): _baseUserFilesDir = os.path.join(getSystemUserDir(), 'ImSwitchConfig') + +def getDiskusage(): + """ + Checks if the available disk space is above the threshold percentage. + Returns True if disk is above the threshold occupied. + """ + # Get the current working directory's drive (cross-platform compatibility) + current_drive = os.path.abspath(os.sep) + + # Get disk usage statistics + total, used, free = disk_usage(current_drive) + + # Calculate percentage used + percent_used = (used / total) + + # Check if it exceeds the threshold + return percent_used + def initUserFilesIfNeeded(): """ Initializes all directories that will be used to store user data and copies example files. """ diff --git a/imswitch/imcontrol/controller/controllers/FlowStopController.py b/imswitch/imcontrol/controller/controllers/FlowStopController.py index f49711dc..ba1cfbe7 100644 --- a/imswitch/imcontrol/controller/controllers/FlowStopController.py +++ b/imswitch/imcontrol/controller/controllers/FlowStopController.py @@ -286,6 +286,9 @@ def flowExperimentThread(self, timeStamp: str, experimentName: str, self.video_safe.start() while True: + if dirtools.getDiskusage()>.95: + self.is_measure = False + self._logger.error("DISK IS FULL. PLEASE DELETE FILES!!!") currentTime = time.time() self.imagesTaken += 1 self.sigImagesTaken.emit(self.imagesTaken)