Allen's 데이터 맛집

C#을 사용한 Basler Pylon 카메라 디바이스 제거 및 재연결 처리 방법 본문

Programming/Pylon .Net API

C#을 사용한 Basler Pylon 카메라 디바이스 제거 및 재연결 처리 방법

Allen93 2024. 8. 5. 16:00

 

이번 포스팅에서는 C# 언어와 Basler Pylon .NET API를 사용하여 카메라 디바이스의 제거 및 재연결을 처리하는 방법을 다루어보겠습니다. Basler Pylon 카메라와 연동하여 디바이스 연결이 끊어졌을 때 이를 감지하고, 다시 연결하는 과정을 설명합니다. 이 샘플 코드는 실시간 모니터링 시스템을 구축하거나 산업 자동화 시스템에서 유용하게 사용할 수 있습니다.

 

 

코드 설명

 

이 샘플 프로그램은 카메라 디바이스가 제거되었을 때 이를 감지하고, 다시 연결하는 과정을 보여줍니다. 주로 GigE 카메라 디바이스를 대상으로 하며, 디버깅 중에 하트비트 타임아웃을 5분으로 설정하여 디버깅 시 카메라가 연결 해제를 감지하지 못하도록 합니다.


 

주요 구성 요소 및 기능

a. 이벤트 핸들러 설정

static void OnConnectionLost(Object sender, EventArgs e)
{
    // For demonstration purposes, print a message.
    Console.WriteLine("OnConnectionLost has been called.");
}
  • OnConnectionLost 메서드는 카메라의 연결이 끊어졌을 때 호출되는 이벤트 핸들러입니다.

 

b. 메인 메서드

internal static void Main()
{
    // Time to wait for the user to disconnect the camera device.
    const int cTimeOutMs = 20000;

    // The exit code of the sample application.
    int exitCode = 0;

    try
    {
        // Create a camera object that selects the first camera device found.
        using (Camera camera = new Camera())
        {
            // Print the model name of the camera.
            Console.WriteLine("Using camera {0}.", camera.CameraInfo[CameraInfoKey.ModelName]);

            // Set the acquisition mode to free running continuous acquisition when the camera is opened.
            camera.CameraOpened += Configuration.AcquireContinuous;

            // For demonstration purposes, only add an event handler for connection loss.
            camera.ConnectionLost += OnConnectionLost;

            // Open the connection to the camera device.
            camera.Open();
            
            // Set the heartbeat timeout to a short value when using GigE cameras.
            camera.Parameters[PLTransportLayer.HeartbeatTimeout].TrySetValue(1000, IntegerValueCorrection.Nearest);  // 1000 ms timeout

            // Start the grabbing.
            camera.StreamGrabber.Start();

            // Start the timeout timer.
            Console.WriteLine("Please disconnect the device. (Timeout {0}s)", cTimeOutMs / 1000.0);
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();

            // Grab and display images until timeout.
            while (camera.StreamGrabber.IsGrabbing && stopWatch.ElapsedMilliseconds < cTimeOutMs)
            {
                try
                {
                    // Wait for an image and then retrieve it. A timeout of 5000 ms is used.
                    IGrabResult grabResult = camera.StreamGrabber.RetrieveResult(5000, TimeoutHandling.ThrowException);
                    using (grabResult)
                    {
                        // Image grabbed successfully?
                        if (grabResult.GrabSucceeded)
                        {
                            // Display the grabbed image.
                            ImageWindow.DisplayImage(0, grabResult);
                        }
                    }
                }
                catch (Exception)
                {
                    // Wait until the system safely detects a possible removal.
                    System.Threading.Thread.Sleep(100);

                    if (!camera.IsConnected)
                    {
                        // The camera device has been physically removed.
                        Console.WriteLine("The camera device has been removed. Please reconnect. (Timeout {0}s)", cTimeOutMs / 1000.0);

                        // Close the camera object to close underlying resources used for the previous connection.
                        camera.Close();

                        // Try to re-establish a connection to the camera device until timeout.
                        camera.Open(cTimeOutMs, TimeoutHandling.ThrowException);

                        // Restore settings after reconnection.
                        camera.Parameters[PLTransportLayer.HeartbeatTimeout].TrySetValue(1000, IntegerValueCorrection.Nearest);

                        // Restart grabbing.
                        camera.StreamGrabber.Start();

                        // Restart the timeout timer.
                        Console.WriteLine("Camera reconnected. You may disconnect the camera device again (Timeout {0}s)", cTimeOutMs / 1000.0);
                        stopWatch.Restart();
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        Console.Error.WriteLine("Exception: {0}", e.Message);
        exitCode = 1;
    }
    finally
    {
        Console.Error.WriteLine("\nPress enter to exit.");
        Console.ReadLine();
    }

    Environment.Exit(exitCode);
}

 

  • 변수 선언: cTimeOutMs는 디바이스 연결 대기 시간을 설정합니다.
  • 카메라 객체 생성: Camera 객체를 생성하여 첫 번째로 발견된 카메라를 선택합니다.
  • 카메라 정보 출력: 선택된 카메라의 모델 이름을 출력합니다.
  • 이벤트 핸들러 추가: 카메라 연결 손실 이벤트 핸들러를 추가합니다.
  • 카메라 열기: 카메라 연결을 엽니다.
  • 하트비트 타임아웃 설정: GigE 카메라의 하트비트 타임아웃을 1000ms로 설정합니다.
  • 이미지 그랩 시작: 카메라 스트림을 시작합니다.

이미지 처리: 지정된 시간 동안 이미지를 그랩하고 표시합니다. 연결이 끊어지면 재연결을 시도합니다.

 

728x90