#include <iostream>
#include "CameraApi.h"
#include "opencv2/core.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"

unsigned char           * g_pRgbBuffer;

int main(){
    ///////////////////// 主体部分
    int iCameraCounts = 1;
    int iStatues = -1;
    int setStatues = -1;
    tSdkCameraDevInfo   tCameraEnumList;
    double*     pfExposureTime;
    int     hCamera;
    tSdkCameraCapbility     tCapability;
    tSdkFrameHead   sFrameInfo;
    BYTE*       pbyBuffer;
    int     iDisplatFrames = 10000;
    int     channel = 3;

    CameraSdkInit(1);

    iStatues = CameraEnumerateDevice(&tCameraEnumList, &iCameraCounts);
    printf("statue = %d\n", iStatues);

    printf("count = %d\n", iCameraCounts);
    if(iCameraCounts == 0){
        return -1;
    }

    iStatues = CameraInit(&tCameraEnumList, -1, -1, &hCamera);

    printf("state = %d\n", iStatues);
    if(iStatues != CAMERA_STATUS_SUCCESS){
        return -1;
    }

    CameraGetCapability(hCamera, &tCapability);

    g_pRgbBuffer = (unsigned char*)malloc(tCapability.sResolutionRange.iHeightMax*tCapability.sResolutionRange.iWidthMax*3);

    CameraPlay(hCamera);
    ///////////////////////
    CameraSetAeState(hCamera, false);
    setStatues = CameraSetExposureTime(hCamera, 5000);
    CameraSetGain(hCamera, 100, 70, 50);
    printf("statue = %d\n", setStatues);

    if(tCapability.sIspCapacity.bMonoSensor){
        channel = 1;
        CameraSetIspOutFormat(hCamera, CAMERA_MEDIA_TYPE_MONO8);
    }else{
        channel = 3;
        CameraSetIspOutFormat(hCamera, CAMERA_MEDIA_TYPE_BGR8);
    }

    ///////////////////// 主体部分
    while(iDisplatFrames){

        if(CameraGetImageBuffer(hCamera, &sFrameInfo, &pbyBuffer, 1000) == CAMERA_STATUS_SUCCESS){

            CameraImageProcess(hCamera, pbyBuffer, g_pRgbBuffer, &sFrameInfo);

            cv::Mat matImage(
					cv::Size(sFrameInfo.iWidth,sFrameInfo.iHeight), 
					sFrameInfo.uiMediaType == CAMERA_MEDIA_TYPE_MONO8 ? CV_8UC1 : CV_8UC3,
					g_pRgbBuffer
					);


            imshow("example1", matImage);

            cv::waitKey(5);

            CameraReleaseImageBuffer(hCamera, pbyBuffer);
        }
    }

    CameraUnInit(hCamera);

    free(g_pRgbBuffer);
    ////////////////////

    return 0;
}

