Skip to content

Commit

Permalink
ensure flowstop stops if disk is full
Browse files Browse the repository at this point in the history
  • Loading branch information
beniroquai committed Dec 18, 2024
1 parent 6777692 commit 8f4414b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 31 deletions.
42 changes: 12 additions & 30 deletions imswitch/imcommon/framework/noqt.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
import cv2
import base64
from imswitch import SOCKET_STREAM

import time
if TYPE_CHECKING:
from typing import Tuple, Callable, Union

Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -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}")
Expand Down
20 changes: 19 additions & 1 deletion imswitch/imcommon/model/dirtools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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. """
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 8f4414b

Please sign in to comment.