fix(cam-helper): fix signal wakeup pipe, capture_still mode restore, configure locking, and lores stride

This commit is contained in:
2026-11-19 13:47:24 -05:00
parent 9c6c14f5dd
commit 97b3e93f98
5 changed files with 455 additions and 68 deletions

View File

@@ -51,18 +51,20 @@ def main(argv: Optional[list[str]] = None) -> int:
return MockCameraDriver(frame_writer=frame_writer, emit_event=emit_event)
return Picam2Worker(frame_writer=frame_writer, emit_event=emit_event)
wakeup_r, wakeup_w = os.pipe()
os.set_blocking(wakeup_r, False)
os.set_blocking(wakeup_w, False)
prev_wakeup_fd = signal.set_wakeup_fd(wakeup_w, warn_on_full_buffer=False)
server = JsonProtocolServer(
worker_factory=build_worker,
stdin=sys.stdin,
stdout=sys.stdout,
wakeup_fd=wakeup_r,
)
def _handle_signal(_signum: int, _frame: object) -> None:
server.request_shutdown()
try:
sys.stdin.close()
except OSError:
pass
signal.signal(signal.SIGTERM, _handle_signal)
signal.signal(signal.SIGINT, _handle_signal)
@@ -70,6 +72,15 @@ def main(argv: Optional[list[str]] = None) -> int:
try:
return server.run()
finally:
try:
signal.set_wakeup_fd(prev_wakeup_fd)
except (OSError, ValueError):
pass
for fd in (wakeup_r, wakeup_w):
try:
os.close(fd)
except OSError:
pass
frame_writer.stop()

View File

@@ -298,6 +298,7 @@ class Picam2Worker:
self._picam2: Any = None
self._camera_properties: dict[str, Any] = {}
self._sensor_size: tuple[int, int] = (3280, 2464)
self._state_lock = threading.Lock()
self._started = False
self._paused = False
self._recording = False
@@ -305,6 +306,7 @@ class Picam2Worker:
self._mode = "photo"
self._main_size = (3280, 2464)
self._preview_size = (226, 170)
self._lores_stride: Optional[int] = None
self._fps = 30
self._zoom = 1.0
self._ev = 0.0
@@ -355,7 +357,36 @@ class Picam2Worker:
}
)
def _extract_lores_yuv420(self, request: Any, width: int, height: int) -> bytes:
def _read_negotiated_lores_stride(self, request: Any = None) -> Optional[int]:
if request is not None:
req_cfg = getattr(request, "config", None)
if isinstance(req_cfg, dict):
lores = req_cfg.get("lores")
if isinstance(lores, dict) and isinstance(lores.get("stride"), int) and lores["stride"] > 0:
return int(lores["stride"])
if self._picam2 is not None:
stream_cfg_fn = getattr(self._picam2, "stream_configuration", None)
if callable(stream_cfg_fn):
try:
lores = stream_cfg_fn("lores")
if isinstance(lores, dict) and isinstance(lores.get("stride"), int) and lores["stride"] > 0:
return int(lores["stride"])
except Exception:
pass
cam_cfg = getattr(self._picam2, "camera_config", None)
if isinstance(cam_cfg, dict):
lores = cam_cfg.get("lores")
if isinstance(lores, dict) and isinstance(lores.get("stride"), int) and lores["stride"] > 0:
return int(lores["stride"])
return None
def _extract_lores_yuv420(
self,
request: Any,
width: int,
height: int,
stride_hint: Optional[int] = None,
) -> bytes:
if hasattr(request, "make_buffer"):
raw = request.make_buffer("lores")
else:
@@ -363,15 +394,21 @@ class Picam2Worker:
mv = memoryview(raw).cast("B")
expected = width * height * 3 // 2
if len(mv) == expected:
if len(mv) < expected:
return bytes(mv)
total_rows = height * 3 // 2
if total_rows <= 0 or len(mv) < expected:
stride = self._read_negotiated_lores_stride(request) or stride_hint
if stride is None:
if len(mv) == expected:
return bytes(mv)
total_rows = height * 3 // 2
stride = (len(mv) // total_rows) if total_rows > 0 else width
if stride <= width:
return bytes(mv[:expected])
stride = len(mv) // total_rows
if stride <= width:
required_strided = (height * stride) + 2 * ((height // 2) * (stride // 2))
if len(mv) < required_strided:
return bytes(mv[:expected])
out = bytearray(expected)
@@ -400,16 +437,23 @@ class Picam2Worker:
return bytes(out)
def _on_request(self, request: Any) -> None:
if self._paused or not self._started:
return
pw, ph = self._preview_size
with self._state_lock:
if self._paused or not self._started:
return
pw, ph = self._preview_size
is_16_9 = self._is_16_9
stride_hint = self._lores_stride
try:
payload = self._extract_lores_yuv420(request, pw, ph)
payload = self._extract_lores_yuv420(request, pw, ph, stride_hint=stride_hint)
except Exception:
return
flags = FLAG_ASPECT_16_9 if self._is_16_9 else 0
flags = FLAG_ASPECT_16_9 if is_16_9 else 0
self._frame_writer.push_frame(pw, ph, PIXFMT_YUV420, flags, payload)
def _current_scaler_crop(self) -> tuple[int, int, int, int]:
aspect = (16, 9) if self._is_16_9 else (4, 3)
return compute_scaler_crop(self._sensor_size, aspect[0], aspect[1], self._zoom)
def configure(
self,
mode: str,
@@ -424,49 +468,41 @@ class Picam2Worker:
) -> dict[str, Any]:
if self._recording:
raise RuntimeError("camera_recording")
if self._picam2 is None:
self._open_camera()
if mode not in ("photo", "video", "timelapse"):
raise ValueError(f"Unsupported mode: {mode}")
pw = max(2, int(preview_w) & ~1)
ph = max(2, int(preview_h) & ~1)
mw = max(2, int(main_w) & ~1)
mh = max(2, int(main_h) & ~1)
req_fps = max(1, int(fps))
req_zoom = max(1.0, min(4.0, float(zoom)))
req_ev = max(-2.0, min(2.0, float(ev)))
self._mode = mode
self._main_size = (mw, mh)
self._preview_size = (pw, ph)
self._fps = max(1, int(fps))
self._transform_str = transform
self._is_16_9 = _is_16_9_mode(mode, mw, mh)
self._last_config_kwargs = {
"mode": mode,
"main_w": mw,
"main_h": mh,
"preview_w": pw,
"preview_h": ph,
"fps": self._fps,
"zoom": float(zoom),
"ev": float(ev),
"transform": transform,
}
if self._started:
self._picam2.post_callback = None
self._picam2.stop()
self._started = False
if self._picam2 is None:
self._open_camera()
# Validate transform before stopping camera or mutating worker state.
transform_obj = resolve_transform(
transform,
self._camera_properties,
transform_cls=self._transform_cls,
)
# Detach callback and stop camera before mutating shared geometry/state.
if self._started:
self._picam2.post_callback = None
self._picam2.stop()
with self._state_lock:
self._started = False
lores_cfg = {"size": (pw, ph), "format": "YUV420"}
if mode == "video":
config = self._picam2.create_video_configuration(
main={"size": (mw, mh), "format": "YUV420"},
lores=lores_cfg,
transform=transform_obj,
controls={"FrameRate": self._fps},
controls={"FrameRate": req_fps},
)
else:
config = self._picam2.create_still_configuration(
@@ -476,12 +512,41 @@ class Picam2Worker:
)
self._picam2.configure(config)
self._picam2.post_callback = self._on_request
self._picam2.start()
self._started = True
self._paused = False
negotiated_stride = self._read_negotiated_lores_stride()
is_16_9 = _is_16_9_mode(mode, mw, mh)
self.set_controls(zoom=zoom, ev=ev)
with self._state_lock:
self._mode = mode
self._main_size = (mw, mh)
self._preview_size = (pw, ph)
self._lores_stride = negotiated_stride
self._fps = req_fps
self._transform_str = transform
self._is_16_9 = is_16_9
self._last_config_kwargs = {
"mode": mode,
"main_w": mw,
"main_h": mh,
"preview_w": pw,
"preview_h": ph,
"fps": req_fps,
"zoom": req_zoom,
"ev": req_ev,
"transform": transform,
}
self._paused = False
self._started = True
self._picam2.post_callback = self._on_request
try:
self._picam2.start()
except Exception:
with self._state_lock:
self._started = False
self._picam2.post_callback = None
raise
self.set_controls(zoom=req_zoom, ev=req_ev)
return {
"mode": self._mode,
"main_w": mw,
@@ -505,11 +570,9 @@ class Picam2Worker:
self._last_config_kwargs["ev"] = self._ev
if self._picam2 is not None and self._started:
aspect = (16, 9) if self._is_16_9 else (4, 3)
crop = compute_scaler_crop(self._sensor_size, aspect[0], aspect[1], self._zoom)
self._picam2.set_controls(
{
"ScalerCrop": crop,
"ScalerCrop": self._current_scaler_crop(),
"ExposureValue": float(self._ev),
}
)
@@ -523,7 +586,8 @@ class Picam2Worker:
req_w = max(2, int(width) & ~1)
req_h = max(2, int(height) & ~1)
if (req_w, req_h) != self._main_size and hasattr(
needs_mode_switch = self._mode == "video" or (req_w, req_h) != self._main_size
if needs_mode_switch and hasattr(
self._picam2, "switch_mode_and_capture_file"
):
transform_obj = resolve_transform(
@@ -531,13 +595,19 @@ class Picam2Worker:
self._camera_properties,
transform_cls=self._transform_cls,
)
still_controls = {
"ScalerCrop": compute_scaler_crop(self._sensor_size, 4, 3, self._zoom),
"ExposureValue": float(self._ev),
}
still_cfg = self._picam2.create_still_configuration(
main={"size": (req_w, req_h), "format": "RGB888"},
lores={"size": self._preview_size, "format": "YUV420"},
transform=transform_obj,
controls=still_controls,
)
self._picam2.switch_mode_and_capture_file(still_cfg, tmp_path, format="jpeg")
self._main_size = (req_w, req_h)
# Re-apply active controls after picamera2 restores the prior mode.
self.set_controls()
else:
self._picam2.capture_file(tmp_path, format="jpeg")
@@ -644,21 +714,24 @@ class Picam2Worker:
def pause(self) -> dict[str, Any]:
if self._recording:
self.stop_video()
with self._state_lock:
self._paused = True
was_started = self._started
self._started = False
if self._picam2 is not None:
self._picam2.post_callback = None
if self._started:
if was_started:
self._picam2.stop()
self._started = False
self._picam2.close()
self._picam2 = None
self._paused = True
return {}
def resume(self) -> dict[str, Any]:
if not self._paused and self._picam2 is not None:
return {}
self._open_camera()
self._paused = False
with self._state_lock:
self._paused = False
if self._last_config_kwargs is not None:
self.configure(**self._last_config_kwargs)
return {}
@@ -669,12 +742,15 @@ class Picam2Worker:
self.stop_video()
except Exception:
self._recording = False
with self._state_lock:
self._paused = True
was_started = self._started
self._started = False
if self._picam2 is not None:
try:
self._picam2.post_callback = None
if self._started:
if was_started:
self._picam2.stop()
self._started = False
self._picam2.close()
finally:
self._picam2 = None

View File

@@ -189,9 +189,11 @@ class JsonProtocolServer:
worker_factory: Callable[[Callable[[dict[str, Any]], None]], Any],
stdin: TextIO,
stdout: TextIO,
wakeup_fd: Optional[int] = None,
) -> None:
self._stdin = stdin
self._stdout = stdout
self._wakeup_fd = wakeup_fd
self._write_lock = threading.Lock()
self._shutdown_requested = False
self._worker = worker_factory(self.emit_event)
@@ -282,14 +284,72 @@ class JsonProtocolServer:
except Exception as exc: # noqa: BLE001
self._reply_err(cmd_id, str(exc))
def _get_stdin_fd(self) -> Optional[int]:
try:
fd = self._stdin.fileno()
except (AttributeError, OSError, ValueError):
return None
return fd if isinstance(fd, int) and fd >= 0 else None
def _read_line_fd(self, stdin_fd: int, wakeup_fd: int, buf: bytearray) -> str:
while True:
nl = buf.find(b"\n")
if nl != -1:
line_bytes = bytes(buf[: nl + 1])
del buf[: nl + 1]
return line_bytes.decode("utf-8", errors="replace")
if self._shutdown_requested:
return ""
try:
rlist, _, _ = select.select([stdin_fd, wakeup_fd], [], [], 0.25)
except (InterruptedError, OSError, ValueError):
if self._shutdown_requested:
return ""
continue
if wakeup_fd in rlist:
while True:
try:
drained = os.read(wakeup_fd, 256)
if not drained:
break
except BlockingIOError:
break
except OSError:
break
if self._shutdown_requested:
return ""
if stdin_fd in rlist:
try:
chunk = os.read(stdin_fd, 4096)
except BlockingIOError:
continue
except OSError:
return ""
if not chunk:
if buf:
tail = bytes(buf).decode("utf-8", errors="replace")
buf.clear()
return tail
return ""
buf.extend(chunk)
def run(self) -> int:
self._worker.start()
stdin_fd = self._get_stdin_fd() if self._wakeup_fd is not None else None
fd_buf = bytearray()
try:
while not self._shutdown_requested:
try:
raw_line = self._stdin.readline()
except (OSError, ValueError):
break
if stdin_fd is not None and self._wakeup_fd is not None:
raw_line = self._read_line_fd(stdin_fd, self._wakeup_fd, fd_buf)
else:
try:
raw_line = self._stdin.readline()
except (OSError, ValueError):
break
if not raw_line:
break
line = raw_line.strip()

View File

@@ -35,20 +35,22 @@ class FakeFrameWriter:
class FakeRequest:
def __init__(self, width, height, stride=None):
def __init__(self, width, height, stride=None, trailing_bytes=0, config=None):
self.width = width
self.height = height
self.stride = stride or width
self.trailing_bytes = trailing_bytes
self.config = config
def make_buffer(self, name):
assert name == "lores"
# Produce Y plane (height rows of stride) + U (height//2 rows of stride//2) + V
# Produce Y plane (height rows of stride) + U (height//2 rows of stride//2) + V + optional trailing DMA padding
y_rows = b"".join(bytes([100] * self.width + [255] * (self.stride - self.width)) for _ in range(self.height))
u_stride = self.stride // 2
u_w = self.width // 2
u_rows = b"".join(bytes([128] * u_w + [255] * (u_stride - u_w)) for _ in range(self.height // 2))
v_rows = b"".join(bytes([129] * u_w + [255] * (u_stride - u_w)) for _ in range(self.height // 2))
return y_rows + u_rows + v_rows
return y_rows + u_rows + v_rows + (b"\xaa" * self.trailing_bytes)
class FakeH264Encoder:
@@ -85,6 +87,7 @@ class FakePicamera2:
"Rotation": rotation,
}
self.configured = None
self.camera_config = None
self.started = False
self.closed = False
self.controls_history = []
@@ -93,6 +96,10 @@ class FakePicamera2:
self.recording = False
self.recording_attempts = []
self.captured_files = []
self.direct_captures = []
self.switched_captures = []
self.events = []
self.negotiated_stride = None
self.encoder = None
self.output = None
FakePicamera2.instances.append(self)
@@ -118,12 +125,21 @@ class FakePicamera2:
def configure(self, config):
self.configured = config
cfg_copy = dict(config)
if config.get("lores") is not None:
lores = dict(config["lores"])
lores["stride"] = self.negotiated_stride or lores["size"][0]
cfg_copy["lores"] = lores
self.camera_config = cfg_copy
self.events.append(("configure", config["type"]))
def start(self):
self.started = True
self.events.append(("start", self.configured["type"] if self.configured else None))
def stop(self):
self.started = False
self.events.append(("stop", self.post_callback is None))
def close(self):
self.closed = True
@@ -133,12 +149,19 @@ class FakePicamera2:
def capture_file(self, file_output, name="main", format=None):
self.captured_files.append((file_output, name, format))
self.direct_captures.append((file_output, self.configured["main"]["size"], self.configured["main"]["format"], format))
with open(file_output, "wb") as f:
f.write(b"\xff\xd8\xff\xe0MOCKJPEG\xff\xd9")
def switch_mode_and_capture_file(self, camera_config, file_output, name="main", format=None):
prev_config = self.configured
prev_cam_config = self.camera_config
self.switched_captures.append((camera_config, file_output, name, format))
self.configured = camera_config
self.capture_file(file_output, name=name, format=format)
# Real picamera2 restores the prior configuration after capture completes.
self.configured = prev_config
self.camera_config = prev_cam_config
def start_recording(self, encoder, output):
self.recording_attempts.append((encoder, output))
@@ -155,10 +178,10 @@ class FakePicamera2:
def stop_recording(self):
self.recording = False
def emit_lores_frame(self, stride=None):
def emit_lores_frame(self, stride=None, trailing_bytes=0, request_config=None):
lores = self.configured["lores"]
w, h = lores["size"]
req = FakeRequest(w, h, stride=stride)
req = FakeRequest(w, h, stride=stride, trailing_bytes=trailing_bytes, config=request_config)
cb = self.post_callback or self.pre_callback
if cb is not None:
cb(req)
@@ -252,6 +275,7 @@ class Picam2WorkerTest(unittest.TestCase):
self.assertEqual(events[0]["backend"], "picamera2")
picam = FakePicamera2.instances[-1]
picam.negotiated_stride = 256
worker.configure(
mode="video",
main_w=1280,
@@ -393,24 +417,179 @@ class Picam2WorkerTest(unittest.TestCase):
preview_w=226,
preview_h=170,
fps=30,
zoom=1.0,
ev=0.0,
zoom=2.0,
ev=-0.5,
transform="auto",
)
with tempfile.TemporaryDirectory() as tmpdir:
# 1st capture: matches active photo main_size -> direct capture_file
still_a = os.path.join(tmpdir, ".IMG_1.jpg.tmp")
res_a = worker.capture_still(still_a, 3280, 2464)
self.assertEqual(res_a["width"], 3280)
self.assertEqual(res_a["height"], 2464)
self.assertGreater(res_a["bytes"], 0)
self.assertEqual(picam.captured_files[-1], (still_a, "main", "jpeg"))
self.assertEqual(len(picam.switched_captures), 0)
# 2nd capture: different size -> switch_mode_and_capture_file with controls + restore
controls_before = len(picam.controls_history)
still_b = os.path.join(tmpdir, ".IMG_2.jpg.tmp")
res_b = worker.capture_still(still_b, 1640, 1232)
self.assertEqual(res_b["width"], 1640)
self.assertEqual(res_b["height"], 1232)
self.assertEqual(picam.captured_files[-1], (still_b, "main", "jpeg"))
self.assertEqual(len(picam.switched_captures), 1)
sw_cfg, sw_path, sw_name, sw_fmt = picam.switched_captures[-1]
self.assertEqual((sw_path, sw_name, sw_fmt), (still_b, "main", "jpeg"))
self.assertEqual(
sw_cfg["controls"],
{"ScalerCrop": (820, 616, 1640, 1232), "ExposureValue": -0.5},
)
# Prior photo configuration restored and controls re-applied
self.assertEqual(picam.configured["main"]["size"], (3280, 2464))
self.assertGreater(len(picam.controls_history), controls_before)
self.assertEqual(
picam.controls_history[-1],
{"ScalerCrop": (820, 616, 1640, 1232), "ExposureValue": -0.5},
)
# 3rd capture: back at 3280x2464 -> still matches _main_size, uses direct capture_file
still_c = os.path.join(tmpdir, ".IMG_3.jpg.tmp")
res_c = worker.capture_still(still_c, 3280, 2464)
self.assertEqual(res_c["width"], 3280)
self.assertEqual(len(picam.switched_captures), 1)
self.assertEqual(picam.captured_files[-1], (still_c, "main", "jpeg"))
def test_capture_still_in_video_mode_switches_to_still_format(self):
worker, _, _ = self._make_worker()
worker.start()
picam = FakePicamera2.instances[-1]
worker.configure(
mode="video",
main_w=1280,
main_h=720,
preview_w=226,
preview_h=128,
fps=30,
zoom=2.0,
ev=0.5,
transform="0",
)
controls_before = len(picam.controls_history)
with tempfile.TemporaryDirectory() as tmpdir:
still_path = os.path.join(tmpdir, ".IMG_from_video.jpg.tmp")
res = worker.capture_still(still_path, 1280, 720)
self.assertEqual(res["width"], 1280)
self.assertEqual(res["height"], 720)
# Even though 1280x720 matches video _main_size, video mode uses YUV420 so it must switch
self.assertEqual(len(picam.switched_captures), 1)
sw_cfg = picam.switched_captures[0][0]
self.assertEqual(sw_cfg["main"]["format"], "RGB888")
self.assertEqual(sw_cfg["controls"]["ExposureValue"], 0.5)
# Prior video configuration restored and 16:9 controls re-applied
self.assertEqual(picam.configured["type"], "video")
self.assertGreater(len(picam.controls_history), controls_before)
self.assertEqual(
picam.controls_history[-1],
{"ScalerCrop": (820, 770, 1640, 922), "ExposureValue": 0.5},
)
def test_configure_invalid_transform_preserves_state_and_safe_reconfigure_ordering(self):
worker, writer, _ = self._make_worker()
worker.start()
picam = FakePicamera2.instances[-1]
worker.configure(
mode="photo",
main_w=3280,
main_h=2464,
preview_w=226,
preview_h=170,
fps=30,
zoom=1.5,
ev=0.5,
transform="auto",
)
saved_config = dict(worker._last_config_kwargs)
with self.assertRaises(ValueError):
worker.configure(
mode="video",
main_w=1280,
main_h=720,
preview_w=226,
preview_h=128,
fps=30,
zoom=2.0,
ev=-1.0,
transform="bogus_rot",
)
# Camera remained started and prior state untouched on validation error
self.assertTrue(picam.started)
self.assertIsNotNone(picam.post_callback)
self.assertEqual(worker._mode, "photo")
self.assertEqual(worker._preview_size, (226, 170))
self.assertFalse(worker._is_16_9)
self.assertEqual(worker._last_config_kwargs, saved_config)
# Reconfigure photo -> video must detach post_callback and stop before starting video
picam.events.clear()
worker.configure(
mode="video",
main_w=1280,
main_h=720,
preview_w=226,
preview_h=128,
fps=30,
zoom=1.0,
ev=0.0,
transform="0",
)
self.assertEqual(
picam.events,
[("stop", True), ("configure", "video"), ("start", "video")],
)
picam.emit_lores_frame()
w, h, _, flags, _ = writer.frames[-1]
self.assertEqual((w, h, flags), (226, 128, FLAG_ASPECT_16_9))
def test_extract_lores_yuv420_negotiated_stride_with_trailing_padding(self):
worker, writer, _ = self._make_worker()
worker.start()
picam = FakePicamera2.instances[-1]
picam.negotiated_stride = 256
worker.configure(
mode="photo",
main_w=3280,
main_h=2464,
preview_w=226,
preview_h=170,
fps=30,
zoom=1.0,
ev=0.0,
transform="auto",
)
self.assertEqual(worker._lores_stride, 256)
# Emit frame with stride=256 and 512 trailing DMA alignment bytes
picam.emit_lores_frame(
stride=256,
trailing_bytes=512,
request_config={"lores": {"stride": 256}},
)
self.assertEqual(len(writer.frames), 1)
w, h, pixfmt, flags, payload = writer.frames[0]
self.assertEqual((w, h, pixfmt, flags), (226, 170, PIXFMT_YUV420, 0))
expected = 226 * 170 * 3 // 2
self.assertEqual(len(payload), expected)
self.assertNotIn(255, payload)
self.assertNotIn(0xAA, payload)
# Verify exact Y, U, V plane contents without row skew
y_len = 226 * 170
uv_len = 113 * 85
self.assertEqual(payload[:y_len], b"\x64" * y_len)
self.assertEqual(payload[y_len : y_len + uv_len], b"\x80" * uv_len)
self.assertEqual(payload[y_len + uv_len :], b"\x81" * uv_len)
if __name__ == "__main__":

View File

@@ -333,6 +333,67 @@ class ProtocolTest(unittest.TestCase):
if proc.stderr:
proc.stderr.close()
def test_sigterm_exits_cleanly_without_reentrant_error(self):
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
bin_path = os.path.join(repo_root, "cam-helper", "bin", "czcamera-cam")
r_fd, w_fd = os.pipe()
os.set_inheritable(w_fd, True)
proc = subprocess.Popen(
[bin_path, "--frame-fd", str(w_fd), "--mock-driver"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
pass_fds=(w_fd,),
text=True,
bufsize=1,
)
os.close(w_fd)
try:
assert proc.stdin is not None and proc.stdout is not None and proc.stderr is not None
ready = json.loads(proc.stdout.readline())
self.assertEqual(ready["event"], "ready")
proc.stdin.write(
json.dumps(
{
"id": 1,
"cmd": "configure",
"mode": "photo",
"main_w": 3280,
"main_h": 2464,
"preview_w": 226,
"preview_h": 170,
"fps": 30,
"zoom": 1.0,
"ev": 0.0,
"transform": "auto",
}
)
+ "\n"
)
proc.stdin.flush()
rep = json.loads(proc.stdout.readline())
self.assertTrue(rep["ok"])
# Leave stdin open while blocked waiting for commands, then send SIGTERM.
proc.terminate()
rc = proc.wait(timeout=5.0)
stderr_out = proc.stderr.read()
self.assertEqual(rc, 0, f"Unexpected non-zero exit code {rc}, stderr={stderr_out!r}")
self.assertEqual(stderr_out, "")
finally:
os.close(r_fd)
if proc.poll() is None:
proc.kill()
proc.wait(timeout=5.0)
if proc.stdin:
proc.stdin.close()
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
if __name__ == "__main__":
unittest.main()