#include "ccam_basler.h"
#include<string>
//#define  ALARM_CAMERA_COMMUNICATION 50240
CCam_Basler::CCam_Basler(const QString& name, int32_t id)
    :CCam(name, id)
{
    m_pDevice = nullptr;
}

int32_t CCam_Basler::init_channel()
{
    if (m_pDevice != nullptr)
    {
        return RTN_SUCCESS1;
    }
    std::string sSerialNumber = m_Variants.get_VData(Var_Base_SerialID_ID)->toString().toStdString();
    
	try{
        CDeviceInfo di;
        di.SetSerialNumber(sSerialNumber.c_str());
        di.SetDeviceClass("BaslerUsb");
        CTlFactory& tlFactory = CTlFactory::GetInstance();
		m_pDevice = tlFactory.CreateDevice(di);
	}catch(const GenericException& ex){
        MQT_THROW_STR(QString("Open Camera failed"));
        return RTN_SUCCESS1;
    }

    m_camera.Attach(m_pDevice, Pylon::Cleanup_Delete);
	m_camera.Open();

    return CCam::init_channel();
}

int32_t CCam_Basler::exit_channel()
{
	if (m_pDevice == nullptr) {
		return CCam::exit_channel();
	}
	if(m_camera.IsGrabbing())
		m_camera.StopGrabbing();
    m_camera.Close();
    m_camera.DetachDevice();
    
    CTlFactory::GetInstance().DestroyDevice(m_pDevice);
    m_pDevice = nullptr;
    return CCam::exit_channel();
}

bool CCam_Basler::Reconnect()
{
    try
    {
        exit_channel();

        init_channel();

        return true;
    }
    catch(const QString& ex)
    {
        return false;
    }
}
