alliedvision / VimbaPython

Old Allied Vision Vimba Python API. The successor to this API is VmbPy
BSD 2-Clause "Simplified" License
93 stars 40 forks source link

Abrupt USB camera error out: vimba.error.VimbaCameraError: <VmbError.Timeout: -12> #113

Open sabariMLIT18 opened 2 years ago

sabariMLIT18 commented 2 years ago

Hi I have a USB camera from allied vision. I am getting the following error: vimba.error.VimbaCameraError: <VmbError.Timeout: -12>

However after I restart the jetson the code works maybe once or twice before this error comes again. After this only was to make the camera work is restart or manually disconnect USB cable. Below is my code :

import time,os,cv2
from vimba import *
import logging
from logging import handlers
import traceback
from frame_cap_top_v3 import baslerCam
import multiprocessing
def incrementFrameCtr(currCtr):
    global FRAMECTR_FL
    #print(currCtr)
    currCtr+=1
    #print(currCtr)
    with open(FRAMECTR_FL,"w+") as fl:
        fl.write(str(currCtr))
        fl.flush()

def readFrameCtr():
    global FRAMECTR_FL
    frmctr=-1
    with open(FRAMECTR_FL,"r") as fl:
        frmctr=fl.read().replace("\n","")
        if frmctr=="":
            frmctr=int(time.time())
        else:
            frmctr=int(frmctr)
    return(frmctr)

vimba_cam_config=""
TRIGGER_FL_LOC="SYS_START.txt"
STOP_TRGG_FL="SYS_STOP.txt"
INSPECTION_ID=""
SERVER_TOP_LOC="TODO"
SERVER_SIDE_LOC="TODO"
STOP_TROLLEY_TRGG="SYS_STOP_SIDE1.txt"        
FRAMECTR_FL="FRAMECTR.txt"

log_name=__file__[:-2]+"log"
logger=logging.getLogger(log_name[:-4])
log_level=logging.DEBUG

logger.setLevel(log_level)
log_format=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_fl=handlers.RotatingFileHandler(log_name,maxBytes=1048576,backupCount=5) # 1MB log files max
log_fl.setFormatter(log_format)
log_fl.setLevel(log_level)
logger.addHandler(log_fl)
logger.critical("DATA Capture vimba Module Initilized")

def setupCamera(cam: Camera):
    with cam:
        # Enable auto exposure time setting if camera supports it
        try:
            aquisitionMode=cam.get_feature_by_name("AcquisitionMode")
            aquisitionMode.set('Continuous')
            exposure_auto=cam.get_feature_by_name("ExposureAuto")
            exposure_auto.set("Off")
            exposure_time =cam.get_feature_by_name("ExposureTime")
            exposure_time.set(40000)
            #set Aquisition mode
            acquisitionFrameRateEnable=cam.get_feature_by_name("AcquisitionFrameRateEnable")
            acquisitionFrameRateEnable.set('true')
            acquisitionFrameRate=cam.get_feature_by_name("AcquisitionFrameRate")
            acquisitionFrameRate.set(1)
            camTriggerSelector=cam.get_feature_by_name("TriggerSelector")
            camTriggerSelector.set('FrameStart')
            camTriggerActivation=cam.get_feature_by_name("TriggerActivation")
            camTriggerActivation.set('RisingEdge')
            camTriggerSource=cam.get_feature_by_name("TriggerSource")
            camTriggerSource.set('Software')
            camTriggerMode=cam.get_feature_by_name("TriggerMode")
            camTriggerMode.set('Off')

        except Exception as e:
            print(e)
            print(traceback.format_exc())

def vimba_side_cams_USB(writeLock):
    global INSPECTION_ID,TRIGGER_FL_LOC,SERVER_TOP_LOC,SERVER_SIDE_LOC,STOP_TRGG_FL,STOP_TROLLEY_TRGG,sftpTrans,logger,FRAMECTR_FL

    try:
        if not os.path.exists(FRAMECTR_FL):
            currtm=int(time.time())
            writeLock.acquire()
            try:
                incrementFrameCtr(currtm)       
            finally:
                writeLock.release()

        FRAMECTR=readFrameCtr()       
        if os.path.exists(STOP_TRGG_FL) or os.path.exists(STOP_TROLLEY_TRGG):
            if os.path.exists(TRIGGER_FL_LOC):
                os.remove(TRIGGER_FL_LOC)
            if os.path.exists(STOP_TRGG_FL):
                os.remove(STOP_TRGG_FL)
            if os.path.exists(STOP_TROLLEY_TRGG):
                os.remove(STOP_TROLLEY_TRGG)        
        #Img_loc="IMAGES"
        Img_loc="IMAGES/"
        MAX_WAIT_TIME=300
        err_count=0
        if not os.path.exists(Img_loc):
            os.makedirs(Img_loc)
        CAMERA_ID=""
        logger.critical("Data Capture USB initilized")        
        camId="DEV_1AB22C00CB05"
        oneTimeRun=True
        #configuring cameras
        basler_config_fl="BASLER_DATA_CAP.xml"
        baselerUsbCamObj=baslerCam(basler_config_fl)

        with Vimba.get_instance() as vim:
            try:
                cam=vim.get_camera_by_id(camId)
                #setup loop"
                WAIT_START=int(time.time())
                #waiting for start trigger
                while not os.path.exists(TRIGGER_FL_LOC):
                    if int(time.time())-WAIT_START>MAX_WAIT_TIME:
                        break

                while os.path.exists(TRIGGER_FL_LOC):
                    with cam:
                        try:
                            setupCamera(cam)
                            with open(TRIGGER_FL_LOC,"r") as fl:
                                trigger_data=fl.read().replace("\n","")
                            if oneTimeRun:
                                if INSPECTION_ID=="":
                                    with open(TRIGGER_FL_LOC,"r") as fl:
                                        INSPECTION_ID=str(fl.read()).replace("\n","")
                                oneTimeRun=False
                            if os.path.exists(STOP_TRGG_FL) or os.path.exists(STOP_TROLLEY_TRGG):
                                if os.path.exists(TRIGGER_FL_LOC):
                                    os.remove(TRIGGER_FL_LOC)
                                if os.path.exists(STOP_TRGG_FL):
                                    os.remove(STOP_TRGG_FL)
                                if os.path.exists(STOP_TROLLEY_TRGG):
                                    os.remove(STOP_TROLLEY_TRGG)
                                time.sleep(1)
                            if trigger_data=="":  
                                print("Empty Trigger File") 
                                logger.debug("Empty Trigger Detected")

                                continue                        

                            frame=cam.get_frame()   #timeout_ms=3000,allocation_mode=AllocationMode.AllocAndAnnounceFrame
                            if FrameStatus.Incomplete==frame.get_status():
                                logger.debug("Frame incomplete")
                                continue   
                            FRAMECTR=readFrameCtr()
                            fname=INSPECTION_ID+"_SIDE1_VIMBACAMTOP_"+str(FRAMECTR)+".jpg"
                            writeLock.acquire()
                            try:
                                incrementFrameCtr(FRAMECTR)       
                            finally:
                                writeLock.release()                            

                            frame.convert_pixel_format(PixelFormat.Bgr8)
                            cv2.imwrite(os.path.join(Img_loc,fname),frame.as_opencv_image())  
                            print("Frame added")
                            logger.debug("VIMBA Frame added")

                            time.sleep(2)

                        except Exception as e:
                            logger.critical("Exception in VIMBA setup: "+str(e))                        
                            logger.critical(traceback.format_exc())
                            logger.critical("CAM:"+CAMERA_ID)
                            cam=vim.get_camera_by_id(camId)

                    try:
                        #baselr camera right
                        FRAMECTR=readFrameCtr()

                        baselerUsbCamObj.startframegrabing(FRAMECTR)
                        writeLock.acquire()
                        try:
                            incrementFrameCtr(FRAMECTR)       
                        finally:
                            writeLock.release()                            

                        time.sleep(1)
                        logger.debug("Basler frame added")

                    except Exception as e:
                        logger.critical("Exception in Basler setup: "+str(e))                        
                        logger.critical(traceback.format_exc())

            except Exception as e:
                logger.critical("Exception in VIMBA setup: "+str(e))                        
                logger.critical(traceback.format_exc())
                logger.critical("CAM:"+CAMERA_ID)
        logger.critical("Data Capture USB exited")

    except Exception as e:
        print(e)
        logger.critical("Error in main func")
        logger.critical(str(e))
        logger.critical(traceback.format_exc())
        err_count+=1
        if err_count>100:
            exit(1) 

if __name__=="__main__":
    lock=multiprocessing.Lock()
    vimba_side_cams_USB(lock)

What am I doing wrong?

arunprakash-avt commented 2 years ago

Thank you raising this issue. I would request you to send us the full error output from the command promt, so that we can say where the error occurs.

sabariMLIT18 commented 2 years ago

Please find the complete log

2022-06-25 16:30:58,227 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V6_USB - CRITICAL - Exception in VIMBA setup: <VmbError.Timeout: -12>
2022-06-25 16:30:58,264 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V6_USB - CRITICAL - Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/vimba/camera.py", line 908, in _open
    byref(self.__handle))
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/c_binding/vimba_c.py", line 753, in call_vimba_c
    getattr(_lib_instance, func_name)(*args)
  File "/usr/local/lib/python3.7/dist-packages/vimba/c_binding/vimba_c.py", line 671, in _eval_vmberror
    raise VimbaCError(result)
vimba.c_binding.vimba_common.VimbaCError: VimbaCError(<VmbError.Timeout: -12>)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V6_USB.py", line 142, in vimba_side_cams
    with cam:
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/camera.py", line 362, in __enter__
    self._open()
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/context_decorator.py", line 44, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/camera.py", line 924, in _open
    raise exc from e
vimba.error.VimbaCameraError: <VmbError.Timeout: -12>
sabariMLIT18 commented 2 years ago

Also I sometimes get a different error for the same code shown below:

2022-06-29 18:22:11,296 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V7_USB - CRITICAL - Data Capture USB initilized
2022-06-29 18:22:13,642 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V7_USB - DEBUG - Frame incomplete
2022-06-29 18:22:13,858 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V7_USB - CRITICAL - Exception in MAIN setup: VimbaCError(<VmbError.Incomplete: -19>)
2022-06-29 18:22:13,864 - /home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V7_USB - CRITICAL - Traceback (most recent call last):
  File "/home/insightzz_agx6/Insightzz/ALLIED_VISION/DATA_CAP_VIMBA_V7_USB.py", line 131, in vimba_side_cams_USB
    with cam:
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/camera.py", line 362, in __enter__
    self._open()
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/context_decorator.py", line 44, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/camera.py", line 926, in _open
    self.__feats = discover_features(self.__handle)
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/feature.py", line 1242, in discover_features
    call_vimba_c('VmbFeaturesList', handle, None, 0, byref(feats_count), sizeof(VmbFeatureInfo))
  File "/usr/local/lib/python3.7/dist-packages/vimba/util/tracer.py", line 134, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/vimba/c_binding/vimba_c.py", line 753, in call_vimba_c
    getattr(_lib_instance, func_name)(*args)
  File "/usr/local/lib/python3.7/dist-packages/vimba/c_binding/vimba_c.py", line 671, in _eval_vmberror
    raise VimbaCError(result)
vimba.c_binding.vimba_common.VimbaCError: VimbaCError(<VmbError.Incomplete: -19>)
arunprakash-avt commented 2 years ago

The above error is because the camera Acquistion status is TRUE. The camera features cannot be changed and error -12 occurs. So I request you to check the feature AcquisitionStatus and check if the feature is set to True. If it is so then provide an AcquisitionStop until the AcquisitionStatus changes to FALSE.

sabariMLIT18 commented 2 years ago

How do I do that? I am facing issue using the with context managers. Is there any way to know that the camera has been closed after leaving the with context manager? Currently I am relaying on time.sleep() to wait after with statement which is not ideal.

sabariMLIT18 commented 2 years ago

I changed my code from synchronous to asynchronous as shown below, as above error codes were related to opening and closing of the camera object. This code works fine for 1min after that it just hangs, seems the handler is just stops getting called by the vimba system.

import time,os,cv2
from vimba import *
import logging,queue
from logging import handlers
import traceback,copy
import multiprocessing,threading
def incrementFrameCtr(currCtr):
    global FRAMECTR_FL
    #print(currCtr)
    currCtr+=1
    #print(currCtr)
    with open(FRAMECTR_FL,"w+") as fl:
        fl.write(str(currCtr))
        fl.flush()

def readFrameCtr():
    global FRAMECTR_FL
    frmctr=-1
    with open(FRAMECTR_FL,"r") as fl:
        frmctr=fl.read().replace("\n","")
        if frmctr=="":
            frmctr=int(time.time())
        else:
            frmctr=int(frmctr)
    return(frmctr)

vimba_cam_config=""
TRIGGER_FL_LOC="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_START/SYS_START.txt"
STOP_TRGG_FL="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_STOP/SYS_STOP.txt"
INSPECTION_ID=""
SERVER_TOP_LOC="/home/insightzz/Insightzz/BANDRA_INSPECTION/SIDE1/TOP/INPUT/TODO"
SERVER_SIDE_LOC="/home/insightzz/Insightzz/BANDRA_INSPECTION/SIDE1/SIDE/INPUT/TODO"
STOP_TROLLEY_TRGG="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_STOP/SYS_STOP_SIDE1.txt"        
FRAMECTR_FL="/home/insightzz_agx6/Insightzz/ALLIED_VISION/FRAMECTR.txt"

log_name=__file__[:-2]+"log"
logger=logging.getLogger(log_name[:-4])
log_level=logging.DEBUG

logger.setLevel(log_level)
log_format=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_fl=handlers.RotatingFileHandler(log_name,maxBytes=1048576,backupCount=5) # 1MB log files max
log_fl.setFormatter(log_format)
log_fl.setLevel(log_level)
logger.addHandler(log_fl)
logger.critical("DATA Capture vimba Module Initilized")

frame_queue=queue.Queue()

def setupCamera(cam: Camera):
    with cam:
        # Enable auto exposure time setting if camera supports it
        try:
            aquisitionMode=cam.get_feature_by_name("AcquisitionMode")
            aquisitionMode.set('Continuous')
            exposure_auto=cam.get_feature_by_name("ExposureAuto")
            exposure_auto.set("Off")
            exposure_time =cam.get_feature_by_name("ExposureTime")
            exposure_time.set(40000)
            #set Aquisition mode
            acquisitionFrameRateEnable=cam.get_feature_by_name("AcquisitionFrameRateEnable")
            acquisitionFrameRateEnable.set('true')
            acquisitionFrameRate=cam.get_feature_by_name("AcquisitionFrameRate")
            acquisitionFrameRate.set(1)
            camTriggerSelector=cam.get_feature_by_name("TriggerSelector")
            camTriggerSelector.set('FrameStart')
            camTriggerActivation=cam.get_feature_by_name("TriggerActivation")
            camTriggerActivation.set('RisingEdge')
            camTriggerSource=cam.get_feature_by_name("TriggerSource")
            camTriggerSource.set('Software')
            camTriggerMode=cam.get_feature_by_name("TriggerMode")
            camTriggerMode.set('Off')

        except Exception as e:
            print(e)
            print(traceback.format_exc())

def try_put_frame(q: queue.Queue,frame):
    try:
        q.put_nowait(frame)

    except queue.Full:
        logger.critical("Frame queue full")

def try_get_frame(q:queue.Queue,writeLock,Img_loc,killSwitch):
    while True:
        try:
            data=q.get_nowait()
            FRAMECTR=readFrameCtr()       
            fname=INSPECTION_ID+"_SIDE1_VIMBACAMTOP_"+str(FRAMECTR)+".jpg"
            writeLock.acquire()
            try:
                incrementFrameCtr(FRAMECTR)       
            finally:
                writeLock.release() 
            cv2.imwrite(os.path.join(Img_loc,fname),data)  
            logger.debug("Frame written")
            print("Frame written")
            if killSwitch.is_set():
                logger.debug("Kill switch set")
                print("Kill switch set")
                break

        except queue.Empty:
            #logger.critical("No frames")
            if killSwitch.is_set():
                logger.debug("Kill switch set")
                print("Kill switch set")
                break
            #else:
                #continue

def vimba_cam_handler(cam:Camera,frame:Frame):
    #handler for each fram capture
    print("Frame handler")

    if FrameStatus.Incomplete==frame.get_status():
        logger.debug("Frame incomplete")
        print("Frame incomplete")

    else:
        frame.convert_pixel_format(PixelFormat.Bgr8)
        imgframe=frame.as_opencv_image()
        try_put_frame(frame_queue,imgframe)
        print("VIMBA USB Frame added")
        logger.debug("VIMBA Frame added")

    cam.queue_frame(frame)

def vimba_side_cams_USB(writeLock):
    global INSPECTION_ID,TRIGGER_FL_LOC,SERVER_TOP_LOC,SERVER_SIDE_LOC,STOP_TRGG_FL,STOP_TROLLEY_TRGG,sftpTrans,logger,FRAMECTR_FL

    try:
        endProcess=False
        while endProcess==False:
            killSwitch=threading.Event()
            error_detected=False
            if not os.path.exists(FRAMECTR_FL):
                currtm=int(time.time())
                writeLock.acquire()
                try:
                    incrementFrameCtr(currtm)       
                finally:
                    writeLock.release()

            FRAMECTR=readFrameCtr()       
            if os.path.exists(STOP_TRGG_FL) or os.path.exists(STOP_TROLLEY_TRGG):
                if os.path.exists(TRIGGER_FL_LOC):
                    os.remove(TRIGGER_FL_LOC)
                if os.path.exists(STOP_TRGG_FL):
                    os.remove(STOP_TRGG_FL)
                if os.path.exists(STOP_TROLLEY_TRGG):
                    os.remove(STOP_TROLLEY_TRGG)        
            #Img_loc="IMAGES"
            Img_loc="/home/insightzz_agx6/Insightzz/ALLIED_VISION/IMAGES/"
            MAX_WAIT_TIME=300
            err_count=0
            if not os.path.exists(Img_loc):
                os.makedirs(Img_loc)
            CAMERA_ID=""
            logger.critical("Data Capture USB initilized")        
            camId="DEV_1AB22C00CB05"
            oneTimeRun=True
            #configuring cameras
            vimaba_usb_frmaes=threading.Thread(target=try_get_frame,args=(frame_queue,writeLock,Img_loc,killSwitch))
            vimaba_usb_frmaes.setDaemon(True)
            vimaba_usb_frmaes.start()

            with Vimba.get_instance() as vim:
                try:
                    cam=vim.get_camera_by_id(camId)
                    #setup loop"
                    WAIT_START=int(time.time())
                    #waiting for start trigger
                    while not os.path.exists(TRIGGER_FL_LOC):
                        if int(time.time())-WAIT_START>MAX_WAIT_TIME:
                            break
                    logger.debug("Starting data capture")
                    if os.path.exists(TRIGGER_FL_LOC):
                        with cam:
                            try:
                                setupCamera(cam)
                                with open(TRIGGER_FL_LOC,"r") as fl:
                                    trigger_data=fl.read().replace("\n","")
                                if oneTimeRun:
                                    if INSPECTION_ID=="":
                                        with open(TRIGGER_FL_LOC,"r") as fl:
                                            INSPECTION_ID=str(fl.read()).replace("\n","")
                                    oneTimeRun=False

                                if trigger_data=="":  
                                    print("Empty Trigger File") 
                                    logger.debug("Empty Trigger Detected")
                                    exit(1)                        
                                logger.debug("Cam streaming started")

                                cam.start_streaming(vimba_cam_handler)
                                while os.path.exists(TRIGGER_FL_LOC):
                                    if os.path.exists(STOP_TRGG_FL) or os.path.exists(STOP_TROLLEY_TRGG):
                                        if os.path.exists(TRIGGER_FL_LOC):
                                            os.remove(TRIGGER_FL_LOC)
                                        if os.path.exists(STOP_TRGG_FL):
                                            os.remove(STOP_TRGG_FL)
                                        if os.path.exists(STOP_TROLLEY_TRGG):
                                            os.remove(STOP_TROLLEY_TRGG)

                                cam.stop_streaming()
                                if os.path.exists(STOP_TRGG_FL) or os.path.exists(STOP_TROLLEY_TRGG):
                                    if os.path.exists(TRIGGER_FL_LOC):
                                        os.remove(TRIGGER_FL_LOC)
                                    if os.path.exists(STOP_TRGG_FL):
                                        os.remove(STOP_TRGG_FL)
                                    if os.path.exists(STOP_TROLLEY_TRGG):
                                        os.remove(STOP_TROLLEY_TRGG)
                                    time.sleep(1)                                

                            except Exception as e:
                                logger.critical("Exception in VIMBA setup: "+str(e))                        
                                logger.critical(traceback.format_exc())
                                logger.critical("CAM:"+camId)
                                errCode=str(str(e).split(": ")[-1].split(">")[0]).replace(" ","")
                                logger.debug("Error code:"+errCode)

                                if errCode in ["-19","-14"]:
                                    error_detected=True
                                    break

                except Exception as e:
                    logger.critical("Exception in MAIN setup: "+str(e))                        
                    logger.critical(traceback.format_exc())

            if error_detected:
                endProcess=False
            else:
                endProcess=True
                killSwitch.set()
        logger.critical("Data Capture USB exited")
        vimaba_usb_frmaes.join()

    except Exception as e:
        print(e)
        logger.critical("Error in main func")
        logger.critical(str(e))
        logger.critical(traceback.format_exc())
        err_count+=1
        if err_count>100:
            exit(1) 

if __name__=="__main__":
    lock=multiprocessing.Lock()
    vimba_side_cams_USB(lock)
sabariMLIT18 commented 2 years ago

I have amended the code to below ensuring that camera features are not modified once grabbing starts but still I get timeout error. Also I am using 2 USB cameras on my jetson agx using Active USB hub to power the USB cameras. I have set the USBFS memory to 6000 MB. Still timeout occurs randomly.

sabariMLIT18 commented 2 years ago

Below is the new updated complete code

import time,os,cv2
from vimba import *
import logging
from logging import handlers
import traceback
import multiprocessing
from DATA_CAP_BASLER_V7 import baslerCam
vimba_cam_config=""
TRIGGER_FL_LOC="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_START/SYS_START.txt"
STOP_TRGG_FL="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_STOP/SYS_STOP.txt"
INSPECTION_ID=""
SERVER_TOP_LOC="/home/insightzz/Insightzz/BANDRA_INSPECTION/SIDE1/TOP/INPUT/TODO"
SERVER_SIDE_LOC="/home/insightzz/Insightzz/BANDRA_INSPECTION/SIDE1/SIDE/INPUT/TODO"
STOP_TROLLEY_TRGG="/home/insightzz_agx6/Insightzz/ALLIED_VISION/SYSTEM/SYS_STOP/SYS_STOP_SIDE1.txt"        

log_name=__file__[:-2]+"log"
logger=logging.getLogger(log_name[:-4])
log_level=logging.DEBUG

logger.setLevel(log_level)
log_format=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
log_fl=handlers.RotatingFileHandler(log_name,maxBytes=1048576,backupCount=5) # 1MB log files max
log_fl.setFormatter(log_format)
log_fl.setLevel(log_level)
logger.addHandler(log_fl)
logger.critical("DATA Capture vimba Module Initilized")

def setupCamera(cam: Camera):
    with cam:
        # Enable auto exposure time setting if camera supports it
        try:
            aquisitionMode=cam.get_feature_by_name("AcquisitionMode")
            aquisitionMode.set('Continuous')
            exposure_auto=cam.get_feature_by_name("ExposureAuto")
            exposure_auto.set("Off")
            exposure_time =cam.get_feature_by_name("ExposureTime")
            exposure_time.set(40000)
            #set Aquisition mode
            acquisitionFrameRateEnable=cam.get_feature_by_name("AcquisitionFrameRateEnable")
            acquisitionFrameRateEnable.set('true')
            acquisitionFrameRate=cam.get_feature_by_name("AcquisitionFrameRate")
            acquisitionFrameRate.set(1)
            camTriggerSelector=cam.get_feature_by_name("TriggerSelector")
            camTriggerSelector.set('FrameStart')
            camTriggerActivation=cam.get_feature_by_name("TriggerActivation")
            camTriggerActivation.set('RisingEdge')
            camTriggerSource=cam.get_feature_by_name("TriggerSource")
            camTriggerSource.set('Software')
            camTriggerMode=cam.get_feature_by_name("TriggerMode")
            camTriggerMode.set('Off')

        except Exception as e:
            print(e)
            print(traceback.format_exc())

def vimba_side_cams_USB():
    global INSPECTION_ID,TRIGGER_FL_LOC,SERVER_TOP_LOC,SERVER_SIDE_LOC,STOP_TRGG_FL,STOP_TROLLEY_TRGG,sftpTrans,logger,FRAMECTR_FL

    try:
        Img_loc="/home/insightzz_agx6/Insightzz/ALLIED_VISION/USBTMPIMAGES/"
        MAX_WAIT_TIME=300
        err_count=0
        if not os.path.exists(Img_loc):
            os.makedirs(Img_loc)
        CAMERA_ID=""
        logger.critical("Data Capture USB initilized")        
        camId="DEV_1AB22C00CB05"
        oneTimeRun=True
        #waiting for start trigger
        WAIT_START=int(time.time())
        while not os.path.exists(TRIGGER_FL_LOC):
            if int(time.time())-WAIT_START>MAX_WAIT_TIME:
                break
        BASLERconfig_fl="/home/insightzz_agx6/Insightzz/ALLIED_VISION/BASLER_DATA_CAP.xml"
        baslerObj=baslerCam(BASLERconfig_fl)

        with Vimba.get_instance() as vim:
            with vim.get_camera_by_id(camId) as cam:
                try:
                    #setup loop"
                    setupCamera(cam)
                    while os.path.exists(TRIGGER_FL_LOC):
                        try:
                            with open(TRIGGER_FL_LOC,"r") as fl:
                                trigger_data=fl.read().replace("\n","")
                            if trigger_data=="":  
                                print("Empty Trigger File") 
                                logger.debug("Empty Trigger Detected")
                                continue                        
                            if oneTimeRun:
                                if INSPECTION_ID=="":
                                    with open(TRIGGER_FL_LOC,"r") as fl:
                                        INSPECTION_ID=str(fl.read()).replace("\n","")
                                oneTimeRun=False
                            frame=cam.get_frame(3000)
                            if FrameStatus.Incomplete==frame.get_status():
                                logger.debug("Frame incomplete")
                            else:
                                fname=INSPECTION_ID+"_SIDE1_VIMBACAMTOP_"+str(int(time.time()*1000000))+".jpg"
                                frame.convert_pixel_format(PixelFormat.Bgr8)
                                cv2.imwrite(os.path.join(Img_loc,fname),frame.as_opencv_image())  
                                logger.debug("VIMBA Frame added")
                            time.sleep(1.5)
                            #basler cam grab
                            baslerObj.startframegrabing()
                            time.sleep(1.5)

                        except Exception as e:
                            logger.critical("Exception in camera loop: "+str(e))                        
                            logger.critical(traceback.format_exc())
                            logger.critical("CAM:"+camId)
                            errCode=str(str(e).split(": ")[-1].split(">")[0]).replace(" ","")
                            logger.debug("Error code:"+errCode)
                            break

                        time.sleep(2)
                except Exception as e:
                    logger.critical("Exception in MAIN setup: "+str(e))                        
                    logger.critical(traceback.format_exc())

        time.sleep(3)

        logger.critical("Data Capture USB exited")

    except Exception as e:
        print(e)
        logger.critical("Error in main func")
        logger.critical(str(e))
        logger.critical(traceback.format_exc())
        err_count+=1
        if err_count>100:
            exit(1) 

if __name__=="__main__":
    vimba_side_cams_USB()
rebotnix commented 2 years ago

Hi, we have exactly the same problem, tested with all 20 USB allied vision, just one connect to a Jetson Xavier NX. Is there any workaround of fix?

Teresa-AlliedVision commented 1 year ago

Hello, we are working on reproducing the issue. For reproduction, please let us know the specific Jetpack version you have on your boards. If this specific issue is the same as a similar one we have seen on some integrated USB cards on PC, then downgrading the firmware to version 7 could help avoid the issue. Please note, that some newer features will not have been implemented on FW7, so it is recommended to check the release notes. https://cdn.alliedvision.com/fileadmin/content/documents/products/software/firmware/Alvium_USB_Firmware_Release_Notes_2022-12-19.pdf Unfortunately no other workaround is known at the moment. Please send an email to support@alliedvision.com with your request for firmware 7, the serial number of your camera and the model (e.g. Alvium U-500c), to receive a download link. Cheers, Teresa

Teresa-AlliedVision commented 1 year ago

@sabariMLIT18 I tested your code (with some simplifications) on a Jetson NX and was unable to provoke any problem. I saved 500+ frames without issue. If you have a reliable reproducer (with only Allied Vision cameras), please upload it here or send it to support@alliedvision.com.

MhdKAT commented 1 year ago

I have the same issue, with 2 Alvium cameras connected to a jetson AGX Orin. The code I am using is the code suggested here. https://github.com/alliedvision/VimbaPython/issues/143#issuecomment-1380072389

Teresa-AlliedVision commented 1 year ago

What firmware do the cameras have and what Jetpack version do you use? With the AGX Orin I personally found the two USB ports on the opposite side of the Ethernet port to work better, next to the pin header. OrinAGX_goodUSB