#include "takephoto.h"

// 模块名称
static const char MODULE_NAME[] = "HkTakePhoto";

// 相机类型
static unsigned int device_type =  MV_GIGE_DEVICE | MV_USB_DEVICE;

// 制造厂商
static const char * const manufacturer = "Hikrobot";

// 触发模式
static MV_CAM_TRIGGER_MODE setTriggerMode = MV_TRIGGER_MODE_ON; /// 默认: 打开

// 曝光取图
#define AE_WAIT_MAX_MS     180000 // 最大曝光稳定等待的时间, 默认3分钟, 单位: ms
#define AE_EXP_TIME_EPS_US     50 // 曝光时间稳定判定的误差, 防抖&区间, 单位: us
#define AE_EXP_STABLE_FRAMES    4 // 相机处于自动曝光模式时, 累计曝光值稳定的帧数
static int waitAEDone = 1; // 是否等待自动曝光完成: "1"-等待(默认), "0"-不等待//

// 保存照片
static int SavePhoto(HANDLE hCam, MV_FRAME_OUT *pFrame, HKImgType imgType, const char *imgPath);

// 拍照环境
typedef struct
{
  HANDLE      hCam;           // 打开相机的句柄
  uint32_t    camType;        // 相机类型:U、网
  char manuName[MAX_LINE_CHARS]; //制造厂商名称
  HKImgType   saveImgType;    // 保存图像的类型
  const char *saveImgPath;    // 保存图像的路径
  unsigned int imgWidth;      // 拍照图像宽度px
  unsigned int imgHeight;     // 拍照图像高度px
  bool        isExposureAuto; // 自动曝光:是/否
  struct timespec expTime0;   // 曝光开始的时间
  float       lastExpTime;    // 上次的曝光时长(us)
  int         expStableCnt;   // 连续曝光稳定帧计数
  HANDLE      hESig;          // 任务结束的通知
  int         rCode;          // 任务结束返回值
} PthotoProcCtx;

// 非标准的"Hikrobot"制造商名称, 但也可视为海康的
static const char * const hikrobot_manu_aliases[] = { NULL };
static bool is_hikrobot_manu_alias(const char *name)
{
  for(int i = 0; hikrobot_manu_aliases[i] != NULL; i++)
  {
    if(xstrcasecmp(name, hikrobot_manu_aliases[i]) == 0) return true;
  }
  return false;
}

static int PhotoProc(unsigned long wParam, unsigned long lParam) // 线程回调函数, 执行一次拍照任务
{
  PthotoProcCtx *ctx = (PthotoProcCtx *)wParam; MV_FRAME_OUT frame = { 0 }; int ret;

  // 1, 触发一次拍照
  ret = (setTriggerMode == MV_TRIGGER_MODE_ON) ? MV_CC_SetCommandValue(ctx->hCam, "TriggerSoftware") : MV_OK;
  if(setTriggerMode == MV_TRIGGER_MODE_ON)  sw_thrd_delay(1000); // 软触发后延时, 预留一些执行时间

  // 2, 等待获取图像
  if(MV_OK == ret)
  {
    memset(&frame, 0, sizeof(MV_FRAME_OUT));
    ret = MV_CC_GetImageBuffer(ctx->hCam, &frame, 1000);
  }

  // 3, 导出图像文件
  if(MV_OK == ret)
  {
    sw_log_debug("[%s] +++GetOneFrame+++, Width[%u], Height[%u], FrameNum[%u], FrameLen[%u], PixelType[0x%08X]", MODULE_NAME,
                  frame.stFrameInfo.nWidth, frame.stFrameInfo.nHeight, frame.stFrameInfo.nFrameNum, frame.stFrameInfo.nFrameLen,
                  (unsigned int)frame.stFrameInfo.enPixelType);

    if(ctx->isExposureAuto && waitAEDone != 0)
    { // 自动曝光模式下, 等待曝光稳定或超时
      MVCC_FLOATVALUE stExposureTime = { 0 }; float curExpTime = 0;
      ret = MV_CC_GetExposureTime(ctx->hCam, &stExposureTime); if(MV_OK != ret) goto retp1;
      curExpTime = stExposureTime.fCurValue;

      struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now);
      long elapsed = (now.tv_sec - ctx->expTime0.tv_sec)*1000 + (now.tv_nsec-ctx->expTime0.tv_nsec)/(1000*1000); // 计算时间差, 单位: ms
      sw_log_debug("[%s] +++GetOneFrame+++, 等待曝光完成, ExposureTime = %.2fus, ElapsedTime = %ldms", MODULE_NAME, curExpTime, elapsed);

      if(fabsf(curExpTime - ctx->lastExpTime) <= AE_EXP_TIME_EPS_US) ctx->expStableCnt++;
      else ctx->expStableCnt = 0;

      if(ctx->expStableCnt < AE_EXP_STABLE_FRAMES && elapsed < AE_WAIT_MAX_MS)
      {
        MV_CC_FreeImageBuffer(ctx->hCam, &frame);
        ctx->lastExpTime = curExpTime; if(0 == ctx->expStableCnt) ctx->expStableCnt = 1;
        ret = 1; goto retp2; // 继续取下一帧
      }
    }

    ctx->imgWidth = frame.stFrameInfo.nWidth; ctx->imgHeight = frame.stFrameInfo.nHeight;
    ret = SavePhoto(ctx->hCam, &frame, ctx->saveImgType, ctx->saveImgPath);
    MV_CC_FreeImageBuffer(ctx->hCam, &frame);
  }

  // 4, 控制线程退出
retp1:
  switch(ret)
  {
  case MV_E_NODATA: // 无数据时, 线程继续运行
    sw_log_debug("[%s] +++GetOneFrame+++, 无数据, 继续等待...", MODULE_NAME);
    ret = 1; break;
  default: // 成功或发生其他错误，线程结束运行
    ctx->rCode = ret; sw_signal_give(ctx->hESig); ret = -1; break;
  }

retp2:
  return ret;
}

// 单次拍照时, 如果相机处于自动曝光模式, 是否等待曝光稳定后再拍照
int HK_SetWaitAEDoneForTakePhoto(int waitAE)
{
  waitAEDone = (waitAE != 0);
  return 0;
}

// 单次执行相机拍照, 并保存到文件, 成功返回: 0值, 失败返回:非0值
// "imgType"     - 获取图像类型
// "saveImgPath" - 保存的文件名
// "timeout"     - 等待超时时间, 单位：秒: < 0 表示无超时;
//                 无论超时怎么设置, 首次尝试拍照一定会执行
//                 , 但时间不确定; 拍照成功、超时或发生错误
//                 时会自动结束任务(相机持续无数据的时间).
// "pImgMark"    - 输出本次拍照图像的水印信息, 可以设置NULL
int HK_TakePhoto(HKImgType imgType, const char *saveImgPath, int timeout, HKImgMark *pImgMark)
{
  int fd; char runDir[MAX_PATH_CHARS] = { 0 }, lockFile[MAX_PATH_CHARS+32] = { 0 };
  int ret, index = 0; HKImgMark imgMark = { 0 }; HANDLE hCam = NULL; PthotoProcCtx ctx = { 0 };
  MV_CC_DEVICE_INFO_LIST devList = { 0 }; MV_CC_DEVICE_INFO *pDevInfo; MVCC_ENUMVALUE exposureMode =  { 0 };

  // 1, 占用锁定, 避免同时间拍照
  xGetSelfRunningInfo(runDir, NULL);
  if(runDir[strlen(runDir)-1] == '/') sprintf(lockFile, "%s%s", runDir, "status/");
  else sprintf(lockFile, "%s/%s", runDir, "status/");
  if(!sw_dir_exists(lockFile)) sw_dir_create(lockFile);
  strcat(lockFile, "hk_takephoto.lock");

  fd = open(lockFile, O_CREAT | O_RDWR | __O_CLOEXEC, 0666);
  if(-1 == fd) { return -1; }

  if(-1 == flock(fd, LOCK_EX | LOCK_NB)) { close(fd); return -2; }

  // 2, 查找相机, 获取其设备信息
  ret = MV_CC_Initialize();
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 相机SDK初始化失败, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }

  ret = MV_CC_EnumDevices(device_type, &devList);
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 枚举相机,执行错误, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }
  if(devList.nDeviceNum < 1)
  {
    ret = -3;
    sw_log_error("[%s] 没有相机,数量=%u!!", MODULE_NAME, devList.nDeviceNum);
    goto end_p;
  }

findp:
  pDevInfo = devList.pDeviceInfo[index++];
  if(!pDevInfo)
  {
    ret = -4;
    sw_log_error("[%s] unexpected internal error, failed to obtain camera information!!", MODULE_NAME);
    goto end_p;
  }

  ctx.manuName[0] = '\0'; if(0) ;
  else if(pDevInfo->nTLayerType == MV_USB_DEVICE /*U口相机*/)
  {
    strcpy(ctx.manuName, (const char *)pDevInfo->SpecialInfo.stUsb3VInfo.chManufacturerName);
    ctx.camType = MV_USB_DEVICE;
    strcpy(imgMark.camModelName, (const char *)pDevInfo->SpecialInfo.stUsb3VInfo.chModelName);
    strcpy(imgMark.camSerialNum, (const char *)pDevInfo->SpecialInfo.stUsb3VInfo.chSerialNumber);
  }
  else if(pDevInfo->nTLayerType == MV_GIGE_DEVICE/*G口相机*/)
  {
    strcpy(ctx.manuName, (const char *)pDevInfo->SpecialInfo.stGigEInfo.chManufacturerName);
    ctx.camType = MV_GIGE_DEVICE;
    strcpy(imgMark.camModelName, (const char *)pDevInfo->SpecialInfo.stGigEInfo.chModelName);
    strcpy(imgMark.camSerialNum, (const char *)pDevInfo->SpecialInfo.stGigEInfo.chSerialNumber);
  }
  else { // SDK出错, 我只枚举了U口和G口相机, 不可能出现其他类型
    ret = -5;
    sw_log_error("[%s] unexpected internal error, unknown camera type(%u)!!", MODULE_NAME, pDevInfo->nTLayerType);
    goto end_p;
  }

  if(xstrcasecmp(ctx.manuName, manufacturer) != 0 && !is_hikrobot_manu_alias(ctx.manuName))
  {
    if(index < devList.nDeviceNum) goto findp;
    ret = -6;
    sw_log_error("[%s] 没有找到 \"%s\" 的相机!!", MODULE_NAME, manufacturer);
    goto end_p;
  }

  // 3, 打开相机, 设置其触发模式
  ret = MV_CC_CreateHandleWithoutLog(&hCam, pDevInfo);
  if(MV_OK == ret) ret = MV_CC_OpenDevice(hCam, MV_ACCESS_Exclusive, 0);
  if(MV_OK == ret && pDevInfo->nTLayerType == MV_USB_DEVICE /*U口相机*/)
  {
    ret = MV_USB_SetTransferWays(hCam, 1); // 设置传输通道个数(RTU硬件资源有限, 需要降低通道数)
  }
  if(MV_OK == ret && pDevInfo->nTLayerType == MV_GIGE_DEVICE/*G口相机*/)
  { // 探测网络最佳包大小(只对GigE相机有效)
    int size = MV_CC_GetOptimalPacketSize(hCam);
    if(size > 0) ret = MV_CC_SetIntValueEx(hCam, "GevSCPSPacketSize", size);
    else ret = -7;
  }
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 打开相机时发生错误, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }

  ret = MV_CC_SetEnumValue(hCam, "TriggerMode", setTriggerMode); // 设置触发模式
  if(MV_OK == ret && setTriggerMode == MV_TRIGGER_MODE_ON) ret = MV_CC_SetEnumValue(hCam, "TriggerSource", MV_TRIGGER_SOURCE_SOFTWARE); // 设置软件触发
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 设置相机时发生错误, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }

  // 4, 开始拍照, 等待完成后输出
  ret = MV_CC_GetExposureAutoMode(hCam, &exposureMode);
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 获取曝光模式时出错, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }
  if(exposureMode.nCurValue != MV_EXPOSURE_AUTO_MODE_OFF) { ctx.isExposureAuto = true; clock_gettime(CLOCK_MONOTONIC, &ctx.expTime0); }
  else ctx.isExposureAuto = false;

  ret = MV_CC_StartGrabbing(hCam);
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 相机取流时发生错误, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }

  ctx.hCam = hCam;
  ctx.saveImgType = imgType;
  ctx.saveImgPath = saveImgPath;
  ctx.hESig = sw_signal_create();
  if(!ctx.hESig)
  {
    ret = -8;
    sw_log_error("[%s] SIG信号量创建失败!!", MODULE_NAME);
    goto end_p;
  }
  ctx.rCode = MV_OK;

  HANDLE hThrd = sw_thrd_create("PhotoProc", THREAD_DEFAULT_PRIORITY, THREAD_DEFAULT_STACK_SIZE, PhotoProc, (unsigned long)&ctx, 0);
  if(!hThrd)
  {
    ret = -9;
    sw_signal_destroy(ctx.hESig);
    sw_log_error("[%s] 拍照线程-创建失败!!", MODULE_NAME);
    goto end_p;
  }
  sw_thrd_resume(hThrd);

  ret = sw_signal_wait(ctx.hESig, timeout*1000); // 阻塞等待拍照任务结束或超时
  if(0 == ret) ret = ctx.rCode;
  else
  {
    ret = 10;
    sw_log_error("[%s] 拍照过程-等待超时!!", MODULE_NAME);
  }

  sw_thrd_destroy(hThrd, WAITTHRD_SAFEEXIT_TIMEOUT);
  sw_signal_destroy(ctx.hESig);

  // 5, 成功拍照, 输出相机的信息
  if(MV_OK == ret)
  {
    MVCC_FLOATVALUE fv = { 0 };
    MV_CC_GetFloatValue(hCam, "ExposureTime", &fv);
    imgMark.imgExposureTime = fv.fCurValue;
    imgMark.imgWidth = ctx.imgWidth; imgMark.imgHeight = ctx.imgHeight;
    if(pImgMark) memcpy(pImgMark, &imgMark, sizeof(HKImgMark));
  }

  // 6, 任务结束, 释放相关的资源
end_p:
  if(hCam)
  {
    MV_CC_StopGrabbing(hCam);
    MV_CC_CloseDevice(hCam);
    MV_CC_DestroyHandle(hCam);
  }
  MV_CC_Finalize();

  flock(fd, LOCK_UN);
  close(fd);
  sw_file_delete(lockFile);

  return ret;
}

// 保存照片
static int SavePhoto(HANDLE hCam, MV_FRAME_OUT *pFrame, HKImgType imgType, const char *imgPath)
{
  MV_SAVE_IMAGE_PARAM_EX3 saveParams = { 0 }; MVCC_INTVALUE_EX iv;
  char *path1 = (char *)imgPath, *path2 = NULL; int ret; char ext[5];

  if(!hCam || !pFrame || !path1 || strlen(path1) <= 0) return -15;

  switch(imgType)
  {
   case IMG_TYPE_BMP: // 保存为.bmp格式
    imgType = MV_Image_Bmp;
    strcpy(ext, ".bmp");
    break;
   case IMG_TYPE_JPG: // 保存为.jpg格式
    imgType = MV_Image_Jpeg;
    strcpy(ext, ".jpg");
    break;
   default: return -16;
  }

  ret = MV_CC_GetIntValueEx(hCam, "PayloadSize", &iv);
  if(MV_OK != ret) return ret;

  saveParams.pData        = pFrame->pBufAddr;
  saveParams.nDataLen     = pFrame->stFrameInfo.nFrameLen;
  saveParams.enPixelType  = pFrame->stFrameInfo.enPixelType;
  saveParams.nHeight      = pFrame->stFrameInfo.nHeight; 
  saveParams.nWidth       = pFrame->stFrameInfo.nWidth;

  saveParams.enImageType  = imgType;
  saveParams.nJpgQuality  = 90; // JPG编码质量(50-99], 其它格式无效, 影响JPG图像文件大小
  saveParams.iMethodValue = 1;

  if(imgType == IMG_TYPE_JPG) saveParams.nBufferSize  = (unsigned int)(iv.nCurValue * 1);
  else saveParams.nBufferSize  = (unsigned int)(iv.nCurValue * 4);
  saveParams.pImageBuffer = (unsigned char *)sw_heap_malloc(saveParams.nBufferSize);
  if(!saveParams.pImageBuffer) return -17;

  ret = MV_CC_SaveImageEx3(hCam, &saveParams);
  if(MV_OK != ret) goto end_p;

  if(!xstrcasestr(path1, "right", ext))
  {
    path2 = (char *)sw_heap_malloc(strlen(path1) + sizeof(ext));
    if(path2) sprintf(path2, "%s%s", path1, ext);
    else { ret = -18; goto end_p; }
    ret = sw_file_update(path2, "wb", (const char *)saveParams.pImageBuffer, saveParams.nImageLen);
    sw_heap_free(path2);
  }
  else
  {
    ret = sw_file_update(path1, "wb", (const char *)saveParams.pImageBuffer, saveParams.nImageLen);
  }

  if(ret == saveParams.nImageLen) ret = MV_OK;
  else ret = -19;

end_p:
  sw_heap_free(saveParams.pImageBuffer);
  return ret;
}

// 获取系统当前USBFS内存大小(MB), 成功返回: >=0, 失败返回: <0值
int HK_GetSysUsbfsMemCurrentSize()
{
  const char *usbfsFile = "/sys/module/usbcore/parameters/usbfs_memory_mb";
  char buf[MAX_LINE_CHARS]; int val = -1;
  FILE *fp = fopen(usbfsFile, "r");
  if(fp)
  {
    if(fgets(buf, sizeof(buf), fp)) sscanf(buf, "%d", &val);
    fclose(fp);
  }
  return val;
}

// 设置系统新的USBFS内存大小(MB), 成功返回: 0值, 失败返回: <0值
int HK_SetSysUsbfsMemSize(int val)
{
  const char *usbfsFile = "/sys/module/usbcore/parameters/usbfs_memory_mb";
  char buf[MAX_LINE_CHARS]; sprintf(buf, "%d\n", val);
  if(val >= 0 && sw_file_update(usbfsFile, "w", buf, strlen(buf)) == strlen(buf)) return 0;
  else return -1;
}

// 获取当前已连接的海康相机的数量, 成功返回: >=0, 失败返回: <0值
int HK_GetCameraCount()
{
  MV_CC_DEVICE_INFO_LIST devList = { 0 };
  int ret;

  ret = MV_CC_Initialize();
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 相机SDK初始化失败, errCode=0x%x!!", MODULE_NAME, ret);
    goto end_p;
  }

  ret = MV_CC_EnumDevices(device_type, &devList);
  if(MV_OK != ret)
  {
    sw_log_error("[%s] 枚举相机,执行错误, errCode=0x%x!!", MODULE_NAME, ret);
    ret = -1; goto end_p;
  }

  ret = devList.nDeviceNum;

  if(ret > 0)
  {
    int index = 0, cnt = 0; MV_CC_DEVICE_INFO *pDevInfo; char name[MAX_LINE_CHARS];
findp:
    pDevInfo = devList.pDeviceInfo[index++];
    
    name[0] = '\0'; if(0) ;
    else if(pDevInfo && pDevInfo->nTLayerType == MV_USB_DEVICE /*U口相机*/) strcpy(name, (const char *)pDevInfo->SpecialInfo.stUsb3VInfo.chManufacturerName);
    else if(pDevInfo && pDevInfo->nTLayerType == MV_GIGE_DEVICE/*G口相机*/) strcpy(name, (const char *)pDevInfo->SpecialInfo.stGigEInfo.chManufacturerName) ;

    if(xstrcasecmp(name, manufacturer) == 0 || is_hikrobot_manu_alias(name)) cnt++;
    if(index < devList.nDeviceNum) goto findp;
    else ret = cnt;
  }

end_p:
  MV_CC_Finalize();

  return ret;
}
