takephoto.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #include "takephoto.h"
  2. // 模块名称
  3. static const char MODULE_NAME[] = "HrTakePhoto";
  4. // 相机类型
  5. static unsigned int device_type = interfaceTypeGige | interfaceTypeUsb3;
  6. // 制造厂商
  7. static const char * const manufacturer = "Huaray Technology";
  8. // 触发模式
  9. static const char * const setTriggerMode = "On"; /// 默认: 打开, 可关闭: "Off"
  10. // 曝光取图
  11. #define AE_WAIT_MAX_MS 180000 // 最大曝光稳定等待的时间, 默认3分钟, 单位: ms
  12. #define AE_EXP_TIME_EPS_US 50 // 曝光时间稳定判定的误差, 防抖&区间, 单位: us
  13. #define AE_EXP_STABLE_FRAMES 4 // 相机处于自动曝光模式时, 累计曝光值稳定的帧数
  14. // 保存照片
  15. static int SavePhoto(HANDLE hCam, IMV_Frame *pFrame, DHImgType imgType, const char *imgPath);
  16. // 拍照回调
  17. typedef struct
  18. {
  19. HANDLE hCam; // 打开相机的句柄
  20. uint32_t camType; // 相机类型:U、网
  21. char manuName[MAX_LINE_CHARS]; //制造厂商名称
  22. DHImgType saveImgType; // 保存图像的类型
  23. const char *saveImgPath; // 保存图像的路径
  24. bool isExposureAuto; // 自动曝光:是/否
  25. struct timespec expTime0; // 曝光开始的时间
  26. float lastExpTime; // 上次的曝光时长(us)
  27. int expStableCnt; // 连续曝光稳定帧计数
  28. HANDLE hESig; // 任务结束的通知
  29. int rCode; // 任务结束返回值
  30. void *pUser; // 附加的用户数据
  31. } PthotoProcCtx;
  32. // 非标准的"Huaray Technology"制造商名称, 但也是华睿的相机, 如: "Machine Vision"
  33. static const char * const huaray_manu_aliases[] = { "Machine Vision", NULL };
  34. static bool is_huaray_manu_alias(const char *name)
  35. {
  36. for(int i = 0; huaray_manu_aliases[i] != NULL; i++)
  37. {
  38. if(xstrcasecmp(name, huaray_manu_aliases[i]) == 0) return true;
  39. }
  40. return false;
  41. }
  42. static void OnFrameReceived(IMV_Frame *pFrame, void *pUser) // 数据帧的回调, 完成一次拍照任务
  43. {
  44. PthotoProcCtx *ctx = (PthotoProcCtx *)pUser; int ret = IMV_OK;
  45. if(NULL == pFrame) return;
  46. // 1, 打印该帧信息
  47. sw_log_debug("[%s] +++GetOneFrame+++, Width[%u], Height[%u], FrameNum[%llu], FrameLen[%u], PixelType[0x%08X]", MODULE_NAME,
  48. pFrame->frameInfo.width, pFrame->frameInfo.height, pFrame->frameInfo.blockId, pFrame->frameInfo.size,
  49. (unsigned int)pFrame->frameInfo.pixelFormat);
  50. // 2, 自动曝光模式
  51. if(ctx->isExposureAuto)
  52. {
  53. double curExpTime = 0.0;
  54. ret = IMV_GetDoubleFeatureValue(ctx->hCam, "ExposureTime", &curExpTime);
  55. if(IMV_OK != ret) goto end_p;
  56. struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now);
  57. long elapsed = (now.tv_sec - ctx->expTime0.tv_sec)*1000 + (now.tv_nsec-ctx->expTime0.tv_nsec)/(1000*1000); // 计算时间差, 单位: ms
  58. sw_log_debug("[%s] +++GetOneFrame+++, 等待曝光完成, ExposureTime = %.2fus, ElapsedTime = %ldms", MODULE_NAME, curExpTime, elapsed);
  59. if(fabsf(curExpTime - ctx->lastExpTime) <= AE_EXP_TIME_EPS_US) ctx->expStableCnt++;
  60. else ctx->expStableCnt = 0;
  61. if(ctx->expStableCnt < AE_EXP_STABLE_FRAMES && elapsed < AE_WAIT_MAX_MS)
  62. { // 曝光未稳定, 也未超时, 则继续等下一帧
  63. ctx->lastExpTime = curExpTime; if(0 == ctx->expStableCnt) ctx->expStableCnt = 1;
  64. return;
  65. }
  66. }
  67. // 3, 导出图像文件
  68. ret = SavePhoto(ctx->hCam, pFrame, ctx->saveImgType, ctx->saveImgPath);
  69. // 4, 设置拍照完成
  70. end_p:
  71. ctx->rCode = ret; sw_signal_give(ctx->hESig);
  72. }
  73. static int FrameSoftTrigger(unsigned long wParam, unsigned long lParam) // 线程回调函数, 触发相机拍照
  74. {
  75. PthotoProcCtx *ctx = (PthotoProcCtx *)wParam;
  76. void *hThrd = ctx->pUser; int slot_ms = 100, tick_ms, ret;
  77. while(sw_thrd_isAlive(hThrd))
  78. {
  79. sw_log_debug("[%s] 触发一次拍照", MODULE_NAME);
  80. ret = IMV_ExecuteCommandFeature(ctx->hCam, "TriggerSoftware");
  81. if(IMV_OK != ret) { sw_log_error("[%s] 触发拍照失败, errCode=%d!!", MODULE_NAME, ret); break; }
  82. else tick_ms = 0;
  83. while(sw_thrd_isAlive(hThrd) && tick_ms < 1000) { sw_thrd_delay(slot_ms); tick_ms += slot_ms; }
  84. }
  85. return -1;
  86. }
  87. // 单次执行相机拍照, 并保存到文件, 成功返回: 0值, 失败返回:非0值
  88. // "imgType" - 获取图像类型
  89. // "saveImgPath" - 保存的文件名
  90. // "timeout" - 等待超时时间, 单位:秒: < 0 表示无超时;
  91. // 无论超时怎么设置, 首次尝试拍照一定会执行
  92. // , 但时间不确定; 拍照成功、超时或发生错误
  93. // 时会自动结束任务(相机持续无数据的时间).
  94. // "pImgMark" - 输出本次拍照图像的水印信息, 可以设置NULL
  95. int DH_TakePhoto(DHImgType imgType, const char *saveImgPath, int timeout, DHImgMark *pImgMark)
  96. {
  97. int fd; char runDir[MAX_PATH_CHARS] = { 0 }, lockFile[MAX_PATH_CHARS+32] = { 0 };
  98. int ret, index = 0; DHImgMark imgMark = { 0 }; HANDLE hCam = NULL; PthotoProcCtx ctx = { 0 };
  99. IMV_DeviceList devList = { 0 }; IMV_DeviceInfo *pDevInfo = NULL; IMV_String exposureMode = { 0 };
  100. // 1, 占用锁定, 避免同时间拍照
  101. xGetSelfRunningInfo(runDir, NULL);
  102. if(runDir[strlen(runDir)-1] == '/') sprintf(lockFile, "%s%s", runDir, "status/");
  103. else sprintf(lockFile, "%s/%s", runDir, "status/");
  104. if(!sw_dir_exists(lockFile)) sw_dir_create(lockFile);
  105. strcat(lockFile, "dh_takephoto.lock");
  106. fd = open(lockFile, O_CREAT | O_RDWR | __O_CLOEXEC, 0666);
  107. if(-1 == fd) { return -1; }
  108. if(-1 == flock(fd, LOCK_EX | LOCK_NB)) { close(fd); return -2; }
  109. // 2, 查找相机, 获取其设备信息
  110. ret = IMV_EnumDevices(&devList, device_type);
  111. if(IMV_OK != ret)
  112. {
  113. sw_log_error("[%s] 枚举相机,执行错误, errCode=%d!!", MODULE_NAME, ret);
  114. goto end_p;
  115. }
  116. if(devList.nDevNum < 1)
  117. {
  118. ret = -3;
  119. sw_log_error("[%s] 没有相机,数量=%u!!", MODULE_NAME, devList.nDevNum);
  120. goto end_p;
  121. }
  122. findp:
  123. pDevInfo = &devList.pDevInfo[index++];
  124. if(!pDevInfo)
  125. {
  126. ret = -4;
  127. sw_log_error("[%s] unexpected internal error, failed to obtain camera information!!", MODULE_NAME);
  128. goto end_p;
  129. }
  130. if(pDevInfo->nCameraType == typeU3vCamera) ctx.camType = interfaceTypeUsb3;
  131. else if(pDevInfo->nCameraType == typeGigeCamera) ctx.camType = interfaceTypeGige;
  132. else { // SDK出错, 我只枚举了U口和G口相机, 不可能出现其他类型
  133. ret = -5;
  134. sw_log_error("[%s] unexpected internal error, unknown camera type(%u)!!", MODULE_NAME, pDevInfo->nCameraType);
  135. goto end_p;
  136. }
  137. strcpy(ctx.manuName, pDevInfo->vendorName);
  138. strcpy(imgMark.camModelName, pDevInfo->modelName);
  139. strcpy(imgMark.camSerialNum, pDevInfo->serialNumber);
  140. if(xstrcasecmp(ctx.manuName, manufacturer) != 0 && !is_huaray_manu_alias(ctx.manuName))
  141. {
  142. if(index < devList.nDevNum) goto findp;
  143. ret = -6;
  144. sw_log_error("[%s] 没有找到 \"%s\" 的相机!!", MODULE_NAME, manufacturer);
  145. goto end_p;
  146. }
  147. // 3, 打开相机, 设置其触发模式
  148. unsigned int cameraIndex = (index - 1);
  149. ret = IMV_CreateHandle(&hCam, modeByIndex, (void*)&cameraIndex);
  150. if(IMV_OK == ret) ret = IMV_Open(hCam);
  151. if(IMV_OK != ret)
  152. {
  153. sw_log_error("[%s] 打开相机时发生错误, errCode=%d!!", MODULE_NAME, ret);
  154. goto end_p;
  155. }
  156. if(IMV_OK == ret && xstrcasecmp(setTriggerMode, "On") == 0) ret = IMV_SetEnumFeatureSymbol(hCam, "TriggerSelector", "FrameStart"); // 设置触发条件
  157. if(IMV_OK == ret && xstrcasecmp(setTriggerMode, "On") == 0) ret = IMV_SetEnumFeatureSymbol(hCam, "TriggerSource", "Software"); // 设置软件触发
  158. if(IMV_OK == ret) ret = IMV_SetEnumFeatureSymbol(hCam, "TriggerMode", setTriggerMode); // 设置触发模式
  159. if(IMV_OK != ret)
  160. {
  161. sw_log_error("[%s] 设置相机时发生错误, errCode=%d!!", MODULE_NAME, ret);
  162. goto end_p;
  163. }
  164. // 4, 开始拍照, 等待完成后输出
  165. ret = IMV_GetEnumFeatureSymbol(hCam, "ExposureAuto", &exposureMode);
  166. if(IMV_OK != ret)
  167. {
  168. sw_log_error("[%s] 获取曝光模式时出错, errCode=%d!!", MODULE_NAME, ret);
  169. goto end_p;
  170. }
  171. if(xstrcasecmp(exposureMode.str, "Off") != 0) { ctx.isExposureAuto = true; clock_gettime(CLOCK_MONOTONIC, &ctx.expTime0); }
  172. else ctx.isExposureAuto = false;
  173. ctx.hCam = hCam;
  174. ctx.saveImgType = imgType;
  175. ctx.saveImgPath = saveImgPath;
  176. ctx.hESig = sw_signal_create();
  177. if(!ctx.hESig)
  178. {
  179. ret = -7;
  180. sw_log_error("[%s] SIG信号量创建失败!!", MODULE_NAME);
  181. goto end_p;
  182. }
  183. ctx.rCode = IMV_OK;
  184. ret = IMV_AttachGrabbing(hCam, OnFrameReceived, (void *)&ctx);
  185. if(IMV_OK != ret)
  186. {
  187. sw_log_error("[%s] 注册回调时发生错误, errCode=%d!!", MODULE_NAME, ret);
  188. goto end_p;
  189. }
  190. ret = IMV_StartGrabbing(hCam);
  191. if(IMV_OK != ret)
  192. {
  193. sw_log_error("[%s] 相机取流时发生错误, errCode=%d!!", MODULE_NAME, ret);
  194. goto end_p;
  195. }
  196. HANDLE hThrd = NULL;
  197. if(0 != xstrcasecmp(setTriggerMode, "On")) goto waitp;
  198. hThrd = sw_thrd_create("PhotoProc", THREAD_DEFAULT_PRIORITY, THREAD_DEFAULT_STACK_SIZE, FrameSoftTrigger, (unsigned long)&ctx, 0);
  199. if(!hThrd)
  200. {
  201. ret = -8;
  202. sw_signal_destroy(ctx.hESig);
  203. sw_log_error("[%s] 触发线程-创建失败!!", MODULE_NAME);
  204. goto end_p;
  205. }
  206. ctx.pUser = (void *)hThrd; sw_thrd_resume(hThrd);
  207. waitp:
  208. ret = sw_signal_wait(ctx.hESig, timeout*1000); // 阻塞等待拍照任务结束或超时
  209. if(0 == ret) ret = ctx.rCode;
  210. else
  211. {
  212. ret = -9;
  213. sw_log_error("[%s] 拍照过程-等待超时!!", MODULE_NAME);
  214. }
  215. if(hThrd) sw_thrd_destroy(hThrd, WAITTHRD_SAFEEXIT_TIMEOUT);
  216. sw_signal_destroy(ctx.hESig);
  217. // 5, 成功拍照, 输出相机的信息
  218. if(IMV_OK == ret)
  219. {
  220. double curExpTime = 0.0;
  221. IMV_GetDoubleFeatureValue(hCam, "ExposureTime", &curExpTime);
  222. imgMark.imgExposureTime = curExpTime;
  223. if(pImgMark) memcpy(pImgMark, &imgMark, sizeof(DHImgMark));
  224. }
  225. // 6, 任务结束, 释放相关的资源
  226. end_p:
  227. if(hCam)
  228. {
  229. IMV_StopGrabbing(hCam);
  230. IMV_Close(hCam);
  231. IMV_DestroyHandle(hCam);
  232. }
  233. flock(fd, LOCK_UN);
  234. close(fd);
  235. sw_file_delete(lockFile);
  236. return ret;
  237. }
  238. // 保存给定的数据帧到BMP图像文件, 成功返回:true, 失败返回:false
  239. static bool SaveFrameToBmp(IMV_HANDLE hCam, IMV_Frame *pFrame, const char *path)
  240. {
  241. }
  242. // 保存给定的数据帧到JPG图像文件, 成功返回:true, 失败返回:false
  243. static bool SaveFrameToJpg(IMV_HANDLE hCam, IMV_Frame *pFrame, const char *path)
  244. {
  245. }
  246. // 保存给定的数据帧到指定格式("BMP"/"JPG")的图像文件,成功返回0值
  247. static int SavePhoto(HANDLE hCam, IMV_Frame *pFrame, DHImgType imgType, const char *imgPath)
  248. {
  249. char *path1 = (char *)imgPath, *path2 = NULL; int ret = IMV_OK; char ext[5];
  250. if(!hCam || !pFrame || !path1 || strlen(path1) <= 0) return -15;
  251. switch(imgType)
  252. {
  253. case IMG_TYPE_BMP: // 保存为.bmp格式
  254. strcpy(ext, ".bmp");
  255. break;
  256. case IMG_TYPE_JPG: // 保存为.jpg格式
  257. strcpy(ext, ".jpg");
  258. break;
  259. default: return -16;
  260. }
  261. if(!xstrcasestr(path1, "right", ext))
  262. {
  263. path2 = (char *)sw_heap_malloc(strlen(path1) + sizeof(ext));
  264. if(path2) sprintf(path2, "%s%s", path1, ext);
  265. else return -17;
  266. if(imgType == IMG_TYPE_BMP && !SaveFrameToBmp(hCam, pFrame, path2)) ret = -18;
  267. if(imgType == IMG_TYPE_JPG && !SaveFrameToJpg(hCam, pFrame, path2)) ret = -19;
  268. sw_heap_free(path2);
  269. }
  270. else
  271. {
  272. if(imgType == IMG_TYPE_BMP && !SaveFrameToBmp(hCam, pFrame, path1)) ret = -18;
  273. if(imgType == IMG_TYPE_JPG && !SaveFrameToJpg(hCam, pFrame, path1)) ret = -19;
  274. }
  275. return ret;
  276. }
  277. // 获取系统当前USBFS内存大小(MB), 成功返回: >=0, 失败返回: <0值
  278. int DH_GetSysUsbfsMemCurrentSize()
  279. {
  280. const char *usbfsFile = "/sys/module/usbcore/parameters/usbfs_memory_mb";
  281. char buf[MAX_LINE_CHARS]; int val = -1;
  282. FILE *fp = fopen(usbfsFile, "r");
  283. if(fp)
  284. {
  285. if(fgets(buf, sizeof(buf), fp)) sscanf(buf, "%d", &val);
  286. fclose(fp);
  287. }
  288. return val;
  289. }
  290. // 设置系统新的USBFS内存大小(MB), 成功返回: 0值, 失败返回: <0值
  291. int DH_SetSysUsbfsMemSize(int val)
  292. {
  293. const char *usbfsFile = "/sys/module/usbcore/parameters/usbfs_memory_mb";
  294. char buf[MAX_LINE_CHARS]; sprintf(buf, "%d\n", val);
  295. if(val >= 0 && sw_file_update(usbfsFile, "w", buf, strlen(buf)) == strlen(buf)) return 0;
  296. else return -1;
  297. }
  298. // 获取当前已连接的海康相机的数量, 成功返回: >=0, 失败返回: <0值
  299. int DH_GetCameraCount()
  300. {
  301. IMV_DeviceList devList = { 0 };
  302. int ret;
  303. ret = IMV_EnumDevices(&devList, device_type);
  304. if(IMV_OK != ret)
  305. {
  306. sw_log_error("[%s] 枚举相机,执行错误, errCode=%d!!", MODULE_NAME, ret);
  307. return -1;
  308. }
  309. ret = devList.nDevNum;
  310. if(ret > 0)
  311. {
  312. int index = 0, cnt = 0; IMV_DeviceInfo *pDevInfo; char name[MAX_LINE_CHARS];
  313. findp:
  314. pDevInfo = &devList.pDevInfo[index++];
  315. name[0] = '\0';
  316. if(pDevInfo && (pDevInfo->nCameraType == typeU3vCamera || pDevInfo->nCameraType == typeGigeCamera)) strcpy(name, pDevInfo->vendorName);
  317. if(xstrcasecmp(name, manufacturer) == 0 || is_huaray_manu_alias(name)) cnt++;
  318. if(index < devList.nDevNum) goto findp;
  319. else ret = cnt;
  320. }
  321. return ret;
  322. }