aboutsummaryrefslogtreecommitdiff
path: root/client.py
diff options
context:
space:
mode:
authorFranoosh <uinarf@autistici.org>2026-01-11 14:26:25 +0100
committerFranoosh <uinarf@autistici.org>2026-01-11 14:26:25 +0100
commita241288241a9dc300014ecfc93c4f537900f3e9f (patch)
tree679c1f1f26289966b5593d5260b6c8da96f0d117 /client.py
parent632fdc7b31dc11ed478f7371676a09a2145eaba4 (diff)
downloadZeroMQ_Video_Streaming-a241288241a9dc300014ecfc93c4f537900f3e9f.tar.gz
ZeroMQ_Video_Streaming-a241288241a9dc300014ecfc93c4f537900f3e9f.tar.bz2
ZeroMQ_Video_Streaming-a241288241a9dc300014ecfc93c4f537900f3e9f.zip
Cleanup.
Diffstat (limited to 'client.py')
-rw-r--r--client.py85
1 files changed, 39 insertions, 46 deletions
diff --git a/client.py b/client.py
index 4b1c6a9..81c8f8b 100644
--- a/client.py
+++ b/client.py
@@ -118,14 +118,14 @@ def _encoder_worker(
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), jpeg_quality]
try:
_, buffer = cv2.imencode('.jpg', frame, encode_param)
+ try:
+ message = [identity, buffer.tobytes()]
+ output_queue.put_nowait(message)
+ except Exception as exc:
+ logger.debug("Send queue full, dropping encoded frame: %r", exc)
+ time.sleep(0.1)
except Exception as exc:
logger.error("Encoder worker: Error encoding frame: %r", exc)
- try:
- message = [identity, buffer.tobytes()]
- output_queue.put_nowait(message)
- except Exception as exc:
- logger.debug("Send queue full, dropping encoded frame: %r", exc)
- time.sleep(0.1)
class ClientVideo(Thread):
"""
@@ -161,15 +161,15 @@ class ClientVideo(Thread):
"""
super().__init__(daemon=True)
self.identity = _id
- self.device_dict = device_dict # <-- A dict with bytes for strings and integers for ints.
+ self.device_dict = device_dict # <-- A dict with bytes
try:
self.device_addr = self.device_dict[b'address'] # No default.
except KeyError:
logger.error("ClientVideo %r: No address specified for device, cannot start video thread.", self.identity)
logger.error("ClientVideo %r: Device dict: %r", self.identity, self.device_dict)
raise
- self.device_threshold = float(device_dict.get(b'contour_size_threshold', CONTOUR_SIZE_THRESHOLD).decode())
- self.device_grace_period = float(device_dict.get(b'movement_grace_period', MOVEMENT_GRACE_PERIOD).decode())
+ self.device_threshold = int(device_dict.get(b'contour_size_threshold', CONTOUR_SIZE_THRESHOLD))
+ self.device_grace_period = int(device_dict.get(b'movement_grace_period', MOVEMENT_GRACE_PERIOD))
self.queue = queue
# Store only FPS number of frames, compare first and last:
self.frame_deque = deque(maxlen=FPS)
@@ -184,7 +184,7 @@ class ClientVideo(Thread):
Parameters
----------
contours: list
- list of contours to draw on a frame
+ List of contours to draw on a frame
"""
raw_frame = self.frame_deque[-1][2]
@@ -218,7 +218,6 @@ class ClientVideo(Thread):
Parameters
----------
- None
Returns
-------
@@ -241,7 +240,7 @@ class ClientVideo(Thread):
# Flag to track movement state. Expires after grace period:
movement_detected = False
- movement_detected_start = movement_now = None
+ movement_detected_start = None
while self.live and not stop_event.is_set():
ret, frame = cap.read()
if not ret:
@@ -325,7 +324,6 @@ class ClientVideo(Thread):
Parameters
----------
- None
Returns
-------
@@ -364,7 +362,7 @@ class ClientTask(Thread):
run
Main client logic
stop
- Stop client task
+ Terminate client task
receive_messages
Receive messages from the server
send_messages
@@ -404,7 +402,6 @@ class ClientTask(Thread):
Parameters
----------
- None
Returns
-------
@@ -420,6 +417,7 @@ class ClientTask(Thread):
logger.info("Client '%r' received message: %r.", self.identity, message)
except Exception as exc:
logger.error("Failed to receive message: %r", exc)
+ continue
try:
logger.debug("Client '%r': Updating config from message ...", self.identity)
self.update_config(message)
@@ -436,7 +434,6 @@ class ClientTask(Thread):
Parameters
----------
- None
Returns
-------
@@ -520,7 +517,7 @@ class ClientTask(Thread):
self.send_messages()
logger.info("Renamed and restarted thread for camera %r to %r.", old_name, new_name)
except Exception as exc:
- logger.error("Error renaming camera %r to %r: %r", old_name, new_name, exc)
+ logger.error("Error renaming camera %r to %r: %r", camera_id, value, exc)
case b'modify_camera_threshold':
try:
_value = int(value)
@@ -577,7 +574,6 @@ class ClientTask(Thread):
Parameters
----------
- None
Returns
-------
@@ -632,7 +628,6 @@ class ClientTask(Thread):
Parameters
----------
- None
Returns
-------
@@ -677,7 +672,6 @@ class ClientTask(Thread):
Parameters
----------
- None
Returns
-------
@@ -744,7 +738,7 @@ def queue_metadata_message(
Queue to put message to
action : bytes
Action as bytes ('start' or 'stop')
- data : float
+ timestamp : float
Data string: this depends on action, for start/stop it's a timestamp, for rename it's old_name:new_name:timestamp
Returns
@@ -763,7 +757,6 @@ def find_present_cameras() -> dict:
Parameters
----------
- None
Returns
-------
@@ -874,8 +867,8 @@ def validate_camera_address(address: str) -> bool:
"""
# Check if address is an integer (device index):
if address.startswith('/dev/video'):
- return address
- raise ValueError("Invalid camera address: %r" % address)
+ return True
+ raise False
def validate_camera_threshold(threshold: str) -> bool:
@@ -894,10 +887,10 @@ def validate_camera_threshold(threshold: str) -> bool:
"""
try:
if int(threshold) > 0:
- return threshold
+ return True
except ValueError:
- raise ValueError("Invalid contour size threshold: %r" % threshold)
- raise ValueError("Invalid contour size threshold: %r" % threshold)
+ raise False
+ return False
def validate_camera_grace_pd(grace_pd: str) -> bool:
@@ -916,10 +909,10 @@ def validate_camera_grace_pd(grace_pd: str) -> bool:
"""
try:
if int(grace_pd) >= 0:
- return grace_pd
+ return True
except ValueError:
- raise ValueError("Invalid movement grace period: %r" % grace_pd)
- raise ValueError("Invalid movement grace period: %r" % grace_pd)
+ return False
+ return False
def camera_address_unique(cfg: ConfigParser, address: str) -> bool:
@@ -948,18 +941,18 @@ def camera_address_unique(cfg: ConfigParser, address: str) -> bool:
return True
-def set_up_cameras(cameras_cfg_section: dict) -> None:
+def set_up_cameras(cameras_cfg_section: list[tuple[str, str]]) -> dict:
"""
Set up camera configuration from config file section.
Validate camera parameters and apply defaults if necessary.
Parameters
----------
- cameras_section : dict
- Dictionary of camera configuration from config file
+ cameras_cfg_section : list[tuple(str, str)]
+ List of (key, val) tuples of camera configuration items from config file.
Returns
-------
cameras_dict : dict
- Dictionary to store validated camera configuration
+ Dictionary to store validated camera configuration.
"""
# ConfigParser does not support nested sections.
# These shenanigans below allow for a nested config simulation with configparser
@@ -970,23 +963,23 @@ def set_up_cameras(cameras_cfg_section: dict) -> None:
cam, param = key.split('.', 1)
match param:
case 'address':
- try:
- cameras_dict[cam][param] = validate_camera_address(val) # <-- still strings
- except ValueError as exc:
- logger.error("Invalid camera address for camera %r: %r, using default: %r.", cam, exc, cameras_dict[cam].get('address', ''))
+ if validate_camera_address(val):
+ cameras_dict[cam][param] = val # <-- still strings
+ else:
+ logger.error("Invalid camera address for camera %r: %r, using default: %r.", cam, val, cameras_dict[cam].get('address', ''))
continue
case 'contour_size_threshold':
- try:
- cameras_dict[cam][param] = validate_camera_threshold(val) # <-- still strings
- except ValueError as exc:
- logger.error("Invalid contour size threshold for camera %r: %r, using default: %r.", cam, exc, cameras_dict[cam].get('contour_size_threshold', ''))
+ if validate_camera_threshold(val):
+ cameras_dict[cam][param] = val # <-- still strings
+ else:
+ logger.error("Invalid contour size threshold for camera %r: %r, using default: %r.", cam, val, cameras_dict[cam].get('contour_size_threshold', ''))
cameras_dict[cam][param] = str(CONTOUR_SIZE_THRESHOLD)
continue
case 'movement_grace_period':
- try:
- cameras_dict[cam][param] = validate_camera_grace_pd(val) # <-- still strings
- except ValueError as exc:
- logger.error("Invalid movement grace period for camera %r: %r, using default: %r.", cam, exc, cameras_dict[cam].get('movement_grace_period', ''))
+ if validate_camera_grace_pd(val):
+ cameras_dict[cam][param] = val # <-- still strings
+ else:
+ logger.error("Invalid movement grace period for camera %r: %r, using default: %r.", cam, val, cameras_dict[cam].get('movement_grace_period', ''))
cameras_dict[cam][param] = str(MOVEMENT_GRACE_PERIOD)
continue
case _: