How to restart nvargus-daemon automatically within a python script

Is it possible to restart the nvargus-daemon from within a python script in case an error happens with the camera. So that the python script can keep running while capturing video, without having to be stopped and run sudo systemctl restart nvargus-daemon separately?

The code here is probably illustrative (however it does not work fully as explained below):

import cv2
import os
import time
import subprocess

def restart_nvargus_daemon():
    print("Restarting nvargus-daemon...")
    result = subprocess.run(["sudo", "systemctl", "restart", "nvargus-daemon"], capture_output=True, text=True)

    if result.returncode == 0:
        print("nvargus-daemon restarted successfully.")
    else:
        print(f"Failed to restart nvargus-daemon. Return code: {result.returncode}")
        print(f"Error output: {result.stderr}")
        return False

    # Wait for the daemon to become active
    for _ in range(15):  # Try for 10 seconds
        result = subprocess.run(["systemctl", "is-active", "nvargus-daemon"], capture_output=True, text=True)
        if "active" in result.stdout:
            print("nvargus-daemon is active.")
            time.sleep(5)
            return True
        time.sleep(3)

    print("nvargus-daemon failed to become active.")
    return False

def create_capture():
    return cv2.VideoCapture(
        'nvarguscamerasrc !  '
        'video/x-raw(memory:NVMM) , width=1920, height=1080, format=NV12, framerate=30/1 ! '
        'nvvidconv flip-method=2 ! '
        'video/x-raw, width=1920, height=1080, format=BGRx ! '
        'videoconvert ! '
        'video/x-raw, format=BGR ! '
        'appsink'
    )

print("Creating capture pipeline...")
cap = create_capture()

while cap.isOpened():
    ret_val, img = cap.read()

    if not ret_val:
        print("Failed to get the frame from the camera.")
        cap.release()
        if not restart_nvargus_daemon():
            print("Failed to restart nvargus-daemon, exiting...")
            break
        cap = create_capture()
        continue

    # Display the frame (optional)
    cv2.imshow('Frame', img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

If I run sudo systemctl stop nvargus-daemon and then run the above script, it says that it successfully restarts the nvargus-daemon and that it is active, however the capture won’t open:

$ sudo systemctl stop nvargus-daemon
$ python script.py
(Argus) Error FileOperationFailed: Connecting to nvargus-daemon failed: Connection refused (in src/rpc/socket/client/SocketClientDispatch.cpp, function openSocketConnection(), line 204)
(Argus) Error FileOperationFailed: Cannot create camera provider (in src/rpc/socket/client/SocketClientDispatch.cpp, function createCameraProvider(), line 106)
Error generated. /dvs/git/dirty/git-master_linux/multimedia/nvgstreamer/gst-nvarguscamera/gstnvarguscamerasrc.cpp, execute:746 Failed to create CameraProvider
[ WARN:0] global /home/ubuntu/build_opencv/opencv/modules/videoio/src/cap_gstreamer.cpp (1100) open OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1
Failed to get the frame from the camera.
Restarting nvargus-daemon...
nvargus-daemon restarted successfully.
nvargus-daemon is active.
Error generated. /dvs/git/dirty/git-master_linux/multimedia/nvgstreamer/gst-nvarguscamera/gstnvarguscamerasrc.cpp, execute:746 Failed to create CameraProvider
[ WARN:0] global /home/ubuntu/build_opencv/opencv/modules/videoio/src/cap_gstreamer.cpp (1100) open OpenCV | GStreamer warning: Cannot query video position: status=0, value=-1, duration=-1
Failed to get the frame from the camera.
Restarting nvargus-daemon...
nvargus-daemon restarted successfully.
nvargus-daemon is active.

However once I ctrl+c out of that run, and then immediately run the python script again, it works! So it seems that the nvargus-daemon is restarted, however its not useable within the current script.

hello timf34,

may I know what kinds of error has happened in your real use-case.

An argus client error will sometimes occur after leaving the camera running for quite a while, or if I accidentally run another script or gstreamer command, it can affect this python script running in the background.

Main thing though is that I need to restart the nvargus-daemon sometime, and want this to be built into the script so it does it automatically. Do you know how to do this?

it sounds like a bug we’ve fixed before.
may I double confirm the Jetpack release version you’re working with.
if that’s Jetpack-5.1.2/ l4t-r35.4.1, please try apply the pre-built update from Topic 268519.

besides, for a complete camera service restart process.
you have to terminate the capture app (i.e. your script file), and then restart nvargus-daemon.

1 Like

Hi @JerryChang,

Thanks for the response.

The Jetpack version is 5.1.1 (see image below).

Would you please excuse my ignore and explain how I apply the pre-built update/ the .so files? Is there any links on how to do this?

Our devices are in the field already so a full image reflash I don’t think is possible.

Thanks
Tim

hello timf34,

please apply the pre-built update from below since it’s r35.3.1 release version.

  1. Topic 243051, for Argus camera stability and error resiliency bug fixes
  2. Topic 268519, for pre-built update to resolve memory corruption within libnvargus.so.

here’s a sample path of libnvscf pre-built binary, /usr/lib/aarch64-linux-gnu/tegra/libnvscf.so
please back-up the default binary, you may use cp commands to overwrite/update binary files with attachment,
you may preform a warm-reboot, i.e. $ sudo reboot after replace the binary files.

1 Like

Thanks @JerryChang ,

Those are very clear instructions!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.