raspberrypi / picamera2

New libcamera based python library
BSD 2-Clause "Simplified" License
852 stars 180 forks source link

[HOW-TO] Reinitialize instance of Picamera2 after failure, without reboot? #991

Open baileypensievision opened 6 months ago

baileypensievision commented 6 months ago

If the Picamera2 object fails to initialize, I want my code to gracefully restart Picamera2 (or some other underlying camera service like libcamera) so that the will camera successfully initialize, without having to reboot the Pi.

Such failures could be the result of a camera suddenly being unplugged during capture (and promptly plugged back in), or due to software related error, such as abruptly ending the code in the middle of capture. Is this possible? If so, how would I implement this? This is the resulting output/error from abruptly ending the code in the middle of image capture:

_**[0:02:02.853094043] [2407]  INFO Camera camera_manager.cpp:299 libcamera v0.0.0+4135-f8a5e271
[0:02:02.855747641] [2430] ERROR V4L2 v4l2_device.cpp:352 'imx219 10-0010': Unable to set controls: Device or resource busy
[0:02:02.877000665] [2430]  WARN RPI raspberrypi.cpp:1308 Mismatch between Unicam and CamHelper for embedded data usage!
[0:02:02.878158150] [2430]  INFO RPI raspberrypi.cpp:1425 Registered camera /base/soc/i2c0mux/i2c@1/imx219@10 to Unicam device /dev/media2 and ISP device /dev/media3
[0:02:02.879935067] [2407]  INFO Camera camera.cpp:839 Pipeline handler in use by another process
Camera __init__ sequence did not complete.
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/picamera2/picamera2.py", line 242, in __init__
    self._open_camera()
  File "/usr/local/lib/python3.9/dist-packages/picamera2/picamera2.py", line 439, in _open_camera
    raise RuntimeError(f"camera.acquire() returned unexpected code: {acq_code}")
RuntimeError: camera.acquire() returned unexpected code: -16

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/Desktop/calibration.py", line 80, in <module>
    picam2 = Picamera2()
  File "/usr/local/lib/python3.9/dist-packages/picamera2/picamera2.py", line 249, in __init__
    raise RuntimeError("Camera __init__ sequence did not complete.")
RuntimeError: Camera __init__ sequence did not complete.**_

My initial thought was to try and restart libcamera using sudo systemctl restart libcamera or sudo systemctl restart libcamera.service, but neither of these worked. I am using the Picamera v2 on an RPi 4. This might not be possible, but I figured it's worth a shot to ask. The only solution may be more robust error handling that gracefully closes the camera anytime one of these hardware/software faults occur.