Detector_TiRayDR.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803
  1. #include "Detector_TiRayDR.h"
  2. #include "CCOS.Dev.FPD.TiRayDR.h"
  3. #include "MyPingip.h"
  4. #include <dlfcn.h>
  5. #include <pthread.h>
  6. #include "LogLocalHelper.h"
  7. #include "Log4CPP.h"
  8. using EventListenerType = void(*)(TiRayEvent, void*);
  9. Detector_TiRayDR* g_pDetector = nullptr;
  10. //extern Log4CPP::Logger* mLog::gLogger;
  11. /****************************************/
  12. int (*GetSdkVersion_Ptr)(void);
  13. TiRayError(*Scan_Ptr)(ResultCallback fn, const char* interfaceIp, int scanDuration);
  14. TiRayError(*SetIp_Ptr)(const char* detectorSN, const char* upperIp, const char* lowerIp, const char* interfaceIp);
  15. TiRayError(*Startup_Ptr)(TiRayModel model, EventCallback fn, const StartupOption * option);
  16. void (*Stop_Ptr)();
  17. TiRayError(*Execute_Ptr)(int detectorId, int commandId, TiRayVariant argv[], int argc);
  18. TiRayError(*ApplyPreset_Ptr)(int detectorId, TiRayVariant argv[], int argc, ResultCallback fn);
  19. TiRayError(*GenerateTemplate_Ptr)(TemplateType type, TiRayVariant images[], int count, void* templateBuffer, int bufferSize);
  20. static int g_load_error = 0;
  21. static void LoadOneFunc(void* hInstLib, void** pFunction, const char* funcName)
  22. {
  23. *pFunction = dlsym(hInstLib, funcName);
  24. const char* dlsym_error = dlerror();
  25. if (dlsym_error != NULL) {
  26. printf("Failed to load %s. Error = %s", funcName, dlsym_error);
  27. g_load_error = 1;
  28. }
  29. }
  30. void OnEvent(TiRayEvent eventType, TiRayVariant argv[], int argc) {
  31. if (argc > 0) {
  32. auto arg = new std::vector<TiRayVariant>(argc);
  33. for (int i = 0; i < argc; i++) {
  34. if (argv[i].Type == TiRayVariant::TiRayBuffer) {
  35. arg->at(i).Type = TiRayVariant::TiRayBuffer;
  36. arg->at(i).DataLen = argv[i].DataLen;
  37. arg->at(i).DataValue = new char[argv[i].DataLen];
  38. memcpy(arg->at(i).DataValue, argv[i].DataValue, argv[i].DataLen);
  39. }
  40. else {
  41. memcpy(&arg->at(i), &argv[i], sizeof(TiRayVariant));
  42. }
  43. }
  44. }
  45. }
  46. #define LOAD_ONE_FUNC(handle, funcName) LoadOneFunc(handle, (void**)&(funcName##_Ptr), #funcName)
  47. /****************************************/
  48. Detector_TiRayDR::Detector_TiRayDR()
  49. :m_nPanelCount{},
  50. m_nCurrentPanelID{0},
  51. m_nImageWidth{},
  52. m_nImageHeight{},
  53. m_nWidthOffset{},
  54. m_nHeightOffset{},
  55. m_nRawImgWidth{},
  56. m_nRawImgHeight{},
  57. m_nCalibrationRounds{},
  58. m_nCalibCurrentCalibrationRound{},
  59. m_nCalibCurrentExposureIndex{},
  60. m_nExposureNumCurrentRound{},
  61. m_hTiRayDRModule{},
  62. m_hReconnectThread{},
  63. m_hFPDScanThread{},
  64. m_hRadAcquisitionThread{},
  65. m_hStatusMonitorThread{},
  66. m_pRawImgBuffer{},
  67. m_pImgBuffer{},
  68. m_pZSKKCalib{},
  69. m_strDetectorType{},
  70. m_strSerialNum{},
  71. m_nImageNum{},
  72. m_nDetectorID{},
  73. m_nNotifyStatusTimePeriod{},
  74. m_pStPanelStatus{},
  75. m_nReconnectTimePeriod(5000),
  76. m_nAppStatus(APP_STATUS::APP_STATUS_IDLE),
  77. m_eCaliType(CCOS_CALIBRATION_TYPE_NONE),
  78. m_nSyncMode(SYNC_SOFTWARE),
  79. m_nCalibrationMode(CCOS_CALIBRATION_MODE_ZSKK),
  80. m_bSaveRaw(true),
  81. m_bConnected(false),
  82. m_bAEDReady(false),
  83. m_bAEDWorkFlag(false),
  84. m_bExitRadAcqStatus(false),
  85. m_bMonitorFlag(false)
  86. {
  87. m_pDPC2PanelID = new map<FPDDeviceTiRay*, int>();
  88. m_pPanelID2DPC = new map<int, FPDDeviceTiRay*>();
  89. m_hExitRadAcqStatus = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  90. m_hInitEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  91. m_hExitEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  92. m_hReConnectEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  93. m_hRadEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  94. m_hArrayEvent.push_back(m_hInitEvent);
  95. m_hArrayEvent.push_back(m_hExitEvent);
  96. m_hArrayEvent.push_back(m_hReConnectEvent);
  97. m_hArrayEvent.push_back(m_hRadEvent);
  98. m_hToggleEvent = LinuxEvent::CreateEvent(LinuxEvent::AUTO_RESET, FALSE);
  99. }
  100. Detector_TiRayDR::~Detector_TiRayDR()
  101. {
  102. CloseStatusMonitor();
  103. CloseDetectorScan();
  104. if (m_hReconnectThread != 0) {
  105. if (m_bReconnectThreadRunning) {
  106. struct timespec ts;
  107. clock_gettime(CLOCK_REALTIME, &ts);
  108. ts.tv_sec += 2; // 设置2秒超时
  109. // 等待线程结束
  110. pthread_timedjoin_np(m_hReconnectThread, nullptr, &ts);
  111. }
  112. // 如果线程仍在运行,强制取消
  113. if (m_bReconnectThreadRunning) {
  114. pthread_cancel(m_hReconnectThread);
  115. }
  116. m_hReconnectThread = 0;
  117. }
  118. if (m_pRawImgBuffer)
  119. {
  120. delete[] m_pRawImgBuffer;
  121. m_pRawImgBuffer = nullptr;
  122. }
  123. if (m_pImgBuffer)
  124. {
  125. delete[] m_pImgBuffer;
  126. m_pImgBuffer = nullptr;
  127. }
  128. if (m_pZSKKCalib)
  129. {
  130. delete m_pZSKKCalib;
  131. m_pZSKKCalib = nullptr;
  132. }
  133. }
  134. bool Detector_TiRayDR::ScanDetector(string& strDetectorInfo)
  135. {
  136. ResDataObject result;
  137. std::vector<scan_result> scan_results;
  138. // 扫描探测器并收集所有结果
  139. scan([&scan_results](scan_result&& res) {
  140. scan_results.emplace_back(std::move(res));
  141. });
  142. if (scan_results.empty()) {
  143. std::cerr << "[Detector_TiRayDR::ScanDetector] No detectors were found!" << std::endl;
  144. return false;
  145. }
  146. std::cout << "[Detector_TiRayDR::ScanDetector] Scanned " << scan_results.size() << " detector(s):" << std::endl;
  147. for (size_t i = 0; i < scan_results.size(); ++i) {
  148. const auto& res = scan_results[i];
  149. ResDataObject detectorData;
  150. detectorData.add("SerialNumber", res.sn.c_str());
  151. detectorData.add("Model", res.model.c_str());
  152. detectorData.add("TupperIP", res.upper_ip.c_str());
  153. detectorData.add("DetectorIP", res.detector_ip.c_str());
  154. std::string key = "DetectorData_" + std::to_string(i);
  155. result.add(key.c_str(), detectorData);
  156. // 输出当前探测器信息
  157. std::cout << "[Detector_TiRayDR::ScanDetector] Detector " << (i + 1) << ":"
  158. << " Serial number:" << res.sn
  159. << ", Model:" << res.model
  160. << ", tupper IP:" << res.upper_ip
  161. << ", detector IP:" << res.detector_ip << std::endl;
  162. }
  163. try {
  164. strDetectorInfo = result.encode();
  165. }
  166. catch (const std::exception& e) {
  167. std::cerr << "[Detector_TiRayDR::ScanDetector] Encode failed: " << e.what() << std::endl;
  168. return false;
  169. }
  170. return true;
  171. }
  172. bool Detector_TiRayDR::DriverEntry(FPDDeviceTiRay* pDrvDPC, ResDataObject& Configuration)
  173. {
  174. //FINFO("--TiRayDR Func-- DriverEntry Start");
  175. map<FPDDeviceTiRay*, int>::iterator DPCsIter = m_pDPC2PanelID->find(pDrvDPC);
  176. if (DPCsIter != m_pDPC2PanelID->end())
  177. {
  178. //FERROR("This DPC already exist");
  179. return false;
  180. }
  181. CPanelStatus* p = new CPanelStatus();
  182. m_pStPanelStatus[m_nPanelCount] = p;
  183. m_pDPC2PanelID->insert(pair<FPDDeviceTiRay*, int>(pDrvDPC, m_nPanelCount));
  184. m_pPanelID2DPC->insert(pair<int, FPDDeviceTiRay*>(m_nPanelCount, pDrvDPC));
  185. m_nPanelCount++;
  186. m_ModeConfig = Configuration; //记录配置 --目前只有一个平板,多板时应该分别存储
  187. //FINFO("Config: {$}", m_ModeConfig.encode());
  188. try
  189. {
  190. m_nCalibrationMode = (CCOS_CALIBRATION_MODE)(int)m_ModeConfig["CalibMode"];
  191. }
  192. catch (ResDataObjectExption& e)
  193. {
  194. //FERROR("Read configuration failed, Error code: {$}", e.what());
  195. }
  196. //FINFO("TiRayDR DriverEntry Over");
  197. return true;
  198. }
  199. bool Detector_TiRayDR::Connect(FPDDeviceTiRay* pDrvDPC, const char* szWorkPath)
  200. {
  201. FINFO("--TiRayDR Func-- Connect Start");
  202. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  203. {
  204. FINFO("Not current DPC, return true");
  205. return true;
  206. }
  207. if (!m_pZSKKCalib)
  208. {
  209. m_pZSKKCalib = new CZSKKCalibrationCtrl();
  210. }
  211. m_strWorkPath = szWorkPath;
  212. if (m_hFPDScanThread == 0)
  213. {
  214. pthread_t threadId;
  215. int result = pthread_create(&threadId, NULL, onFPDScanThread, this);
  216. if (result == 0) {
  217. m_hFPDScanThread = threadId; // 存储线程ID
  218. }
  219. else {
  220. FERROR("Thread creation failed: %d", result);
  221. return false;
  222. }
  223. }
  224. if (m_hInitEvent) {
  225. m_hInitEvent->SetEvent();
  226. }
  227. FINFO("TiRayDR Connect Over");
  228. return true;
  229. }
  230. bool Detector_TiRayDR::Disconnect()
  231. {
  232. FINFO("--TiRayDR Func-- Disconnect Begin");
  233. m_hExitEvent->SetEvent(); //关闭Scan线程
  234. bool result = m_hToggleEvent->Wait(65000);
  235. if (result)
  236. {
  237. FINFO("Leave scan thread over");
  238. }
  239. else
  240. {
  241. FERROR("Till time detectorData");
  242. }
  243. FINFO("Call API Stop");
  244. Stop();
  245. FINFO("TiRayDR Disconnect Over");
  246. return true;
  247. }
  248. void Detector_TiRayDR::EnterExamMode(int nExamMode)
  249. {
  250. switch (nExamMode)
  251. {
  252. case APP_STATUS_WORK_BEGIN:
  253. FINFO("Enter into Exam Windows");
  254. m_nAppStatus = APP_STATUS_WORK_BEGIN;
  255. break;
  256. case APP_STATUS_WORK_END:
  257. FINFO("Quit Exam Windows");
  258. m_nAppStatus = APP_STATUS_WORK_END;
  259. break;
  260. case APP_STATUS_DETSHARE_BEGIN:
  261. FINFO("Enter into Detector Share Windows");
  262. m_nAppStatus = APP_STATUS_DETSHARE_BEGIN;
  263. break;
  264. case APP_STATUS_DETSHAR_END:
  265. FINFO("Quit Detector Share Windows");
  266. m_nAppStatus = APP_STATUS_DETSHAR_END;
  267. break;
  268. case APP_STATUS_CAL_BEGIN:
  269. FINFO("Enter into Calibration Windows");
  270. m_nAppStatus = APP_STATUS_CAL_BEGIN;
  271. break;
  272. case APP_STATUS_CAL_END:
  273. FINFO("Quit Calibration Windows");
  274. m_nAppStatus = APP_STATUS_CAL_END;
  275. break;
  276. case APP_STATUS_WORK_IN_SENSITIVITY:
  277. FINFO("Enter into sensitivity test interface");
  278. m_nAppStatus = APP_STATUS_WORK_IN_SENSITIVITY;
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. /***
  285. ** 根据采集模式申请图像buffer
  286. ***/
  287. bool Detector_TiRayDR::SetAcqMode(int nMode)
  288. {
  289. FINFO("--TiRayDR Func-- SetAcqMode Start");
  290. FINFO("Detector_TiRayDR::SetAcqMode mode:{$}", nMode);
  291. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  292. {
  293. FERROR("Detector not connected, return");
  294. return false;
  295. }
  296. int nRes;
  297. m_bExitRadAcqStatus = false;
  298. try
  299. {
  300. //设置采集模式,根据不同的场景设置不同的采集模式
  301. m_nImageWidth = (int)m_ModeConfig["ModeTable"][0]["ImageWidth"];
  302. m_nImageHeight = (int)m_ModeConfig["ModeTable"][0]["ImageHeight"];
  303. m_nWidthOffset = (int)m_ModeConfig["ModeTable"][0]["WidthOffset"];
  304. m_nHeightOffset = (int)m_ModeConfig["ModeTable"][0]["HeightOffset"];
  305. FINFO("After crop image width: {$}, height: {$}, WidthOffset: {$}, HeightOffset: {$}", m_nImageWidth, m_nImageHeight, m_nWidthOffset, m_nHeightOffset);
  306. m_bSaveRaw = (int)m_ModeConfig["ModeTable"][0]["IsSaveRaw"];
  307. FINFO("m_nSaveRaw:{$}", m_bSaveRaw);
  308. if (nullptr != m_pImgBuffer)
  309. {
  310. delete[] m_pImgBuffer;
  311. m_pImgBuffer = nullptr;
  312. }
  313. m_pImgBuffer = new WORD[(size_t)m_nImageWidth * (size_t)m_nImageHeight];
  314. }
  315. catch (ResDataObjectExption& e)
  316. {
  317. FERROR("Get config FERROR: {$}", e.what());
  318. return false;
  319. }
  320. TiRayVariant Param[2]{};
  321. Param[0].Type = TiRayVariant::TiRayInt;
  322. Param[0].IntValue = TiRayAttribute::Attr_BinningMode;
  323. Param[1].Type = TiRayVariant::TiRayInt;
  324. Param[1].IntValue = BinningMode::Binning_None;
  325. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  326. if ((TiRayError)nRes != TiRayError::Err_Success)
  327. {
  328. FERROR("Set BinningMode Failed, Reason:{$}", nRes);
  329. return false;
  330. }
  331. else
  332. {
  333. FINFO("Set BinningMode Success");
  334. }
  335. TiRayVariant ParamAED[2]{};
  336. ParamAED[0].Type = TiRayVariant::TiRayInt;
  337. ParamAED[0].IntValue = TiRayAttribute::Attr_AEDSensitivity;
  338. ParamAED[1].Type = TiRayVariant::TiRayInt;
  339. ParamAED[1].IntValue = 200;
  340. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, ParamAED, 2);
  341. if ((TiRayError)nRes != TiRayError::Err_Success)
  342. {
  343. FERROR("Set BinningMode Failed, Reason:{$}", nRes);
  344. return false;
  345. }
  346. else
  347. {
  348. FINFO("Set BinningMode Success");
  349. }
  350. StatusFeedback(EVT_STATUS_PANEL, PANEL_SLEEP);
  351. FINFO("TiRayDR SetAcqMode Over");
  352. return true;
  353. }
  354. bool Detector_TiRayDR::SetSyncMode(int nSyncMode)
  355. {
  356. FINFO("--TiRayDR Func-- SetSyncMode Start");
  357. FINFO("SetSyncMode: {$}", nSyncMode);
  358. std::cout << "--TiRayDR Func-- SetSyncMode Start" << std::endl;
  359. std::cout << "SetSyncMode: " << nSyncMode << std::endl;
  360. int nRes;
  361. TiRayVariant Param[2]{};
  362. Param[0].Type = TiRayVariant::TiRayInt;
  363. Param[0].IntValue = TiRayAttribute::Attr_WorkMode;
  364. Param[1].Type = TiRayVariant::TiRayInt;
  365. if (nSyncMode == 1)
  366. {
  367. Param[1].IntValue = WorkMode::WorkMode_Idle;
  368. m_nSyncMode = SYNC_MODE::SYNC_SOFTWARE;
  369. std::cout << "Setting SyncMode to Software Sync" << std::endl;
  370. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  371. if ((TiRayError)nRes != TiRayError::Err_Success)
  372. {
  373. std::cout << "Error: Failed to set SyncMode to Software Sync. Reason: " << nRes << std::endl;
  374. FERROR("Set SyncMode SoftSync, Reason:{$}", nRes);
  375. return false;
  376. }
  377. else
  378. {
  379. std::cout << "Success: Software Sync mode set successfully" << std::endl;
  380. FINFO("Set SoftSync Success");
  381. }
  382. }
  383. else if (nSyncMode == 2)
  384. {
  385. m_nSyncMode = SYNC_MODE::SYNC_HARDWARE;
  386. Param[1].IntValue = WorkMode::WorkMode_SyncIn;
  387. std::cout << "Setting SyncMode to Hardware Sync" << std::endl;
  388. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  389. if ((TiRayError)nRes != TiRayError::Err_Success)
  390. {
  391. std::cout << "Error: Failed to set SyncMode to Hardware Sync. Reason: " << nRes << std::endl;
  392. FERROR("Set SyncMode HardSync, Reason:{$}", nRes);
  393. return false;
  394. }
  395. else
  396. {
  397. std::cout << "Success: Hardware Sync mode set successfully" << std::endl;
  398. FINFO("Set HardSync Success");
  399. }
  400. }
  401. else if (nSyncMode == 3)
  402. {
  403. Param[1].IntValue = WorkMode_FreeSync;
  404. m_nSyncMode = SYNC_MODE::SYNC_AED;
  405. std::cout << "Setting SyncMode to AED Sync" << std::endl;
  406. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  407. if ((TiRayError)nRes != TiRayError::Err_Success)
  408. {
  409. std::cout << "Error: Failed to set SyncMode to AED Sync. Reason: " << nRes << std::endl;
  410. FERROR("Set SyncMode AED, Reason:{$}", nRes);
  411. return false;
  412. }
  413. else
  414. {
  415. std::cout << "Success: AED Sync mode set successfully" << std::endl;
  416. FINFO("Set AED Success");
  417. }
  418. }
  419. m_pStPanelStatus[m_nCurrentPanelID]->eSyncMode = (SYNC_MODE)m_nSyncMode;
  420. FINFO("TiRayDR SetSyncMode Over");
  421. std::cout << "TiRayDR SetSyncMode Over" << std::endl;
  422. return true;
  423. }
  424. bool Detector_TiRayDR::PrepareAcquisition(FPDDeviceTiRay* pDrvDPC)
  425. {
  426. FINFO("--TiRayDR Func-- PrepareAcquisition Start");
  427. FINFO("PrepareAcquisition start");
  428. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  429. {
  430. FERROR("Not current DPC, return");
  431. return false;
  432. }
  433. //未初始化、未连接 不执行
  434. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  435. {
  436. FERROR("Detector not connected, return");
  437. return false;
  438. }
  439. g_pDetector->StatusFeedback(EVT_STATUS_PANEL, PANEL_STANDBY);
  440. //m_hRadEvent->SetEvent();
  441. FINFO("TiRayDR PrepareAcquisition Over");
  442. return true;
  443. }
  444. bool Detector_TiRayDR::StartAcquisition(FPDDeviceTiRay* pDrvDPC)
  445. {
  446. std::cout << "--TiRayDR Func-- StartAcquisition Start" << std::endl;
  447. FINFO("--TiRayDR Func-- StartAcquisition Start");
  448. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  449. {
  450. std::cout << "Not current DPC, return" << std::endl;
  451. FERROR("Not current DPC, return");
  452. return false;
  453. }
  454. //未初始化、未连接 不执行
  455. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  456. {
  457. std::cout << "Detector not connected, return" << std::endl;
  458. FERROR("Detector not connected, return");
  459. return false;
  460. }
  461. if (m_nSyncMode == SYNC_MODE::SYNC_SOFTWARE)
  462. {
  463. //SetSyncMode(1);
  464. auto err = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  465. if (err != Err_Success) {
  466. cout << "[Detector_TiRayDR::StartAcquisition] Failed to Execute_Ptr Cmd_Photo. Error code: " << err << endl;
  467. return false;
  468. }
  469. }
  470. StatusFeedback(EVT_STATUS_PANEL, PANEL_START_ACQ);
  471. m_bAEDWorkFlag = true;
  472. StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  473. std::cout << "TiRayDR StartAcquisition Over" << std::endl;
  474. FINFO("TiRayDR StartAcquisition Over");
  475. return true;
  476. }
  477. bool Detector_TiRayDR::StopAcquisition(FPDDeviceTiRay* pDrvDPC)
  478. {
  479. FINFO("--TiRayDR Func-- StopAcquisition Start");
  480. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  481. {
  482. FERROR("Not current DPC, return");
  483. return false;
  484. }
  485. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  486. {
  487. FERROR("Detector not connected, return");
  488. return false;
  489. }
  490. FINFO("## Stop Acquisition ##");
  491. StatusFeedback(EVT_STATUS_PANEL, PANEL_STANDBY);
  492. SetTiRayDPCStatus(eDetStatus::DetStatus_Standby); //停止采集
  493. FINFO("TiRayDR StopAcquisition Over");
  494. return true;
  495. }
  496. bool Detector_TiRayDR::ActiveCalibration(FPDDeviceTiRay* pDrvDPC, CCOS_CALIBRATION_TYPE eType)
  497. {
  498. FINFO("--TiRayDR Func-- ActiveCalibration Start");
  499. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  500. {
  501. FERROR("Not current DPC, return");
  502. return false;
  503. }
  504. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  505. {
  506. FERROR("bConnectState is false, Detector not connected, return");
  507. return false;
  508. }
  509. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_START);
  510. m_nAppStatus = APP_STATUS_CAL_BEGIN; //激活校正,置为校正界面
  511. m_eCaliType = eType;
  512. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  513. {
  514. FINFO("Active Dark Calibration");
  515. }
  516. if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  517. {
  518. FINFO("Active Xray Calibration");
  519. if (m_nCalibrationMode) //厂商校正ActiveCalibration
  520. {
  521. }
  522. //else //ZSKK校正
  523. //{
  524. // if (!m_pZSKKCalib)
  525. // {
  526. // FERROR("ZSKK Calibration object is undefined");
  527. // }
  528. // else
  529. // {
  530. // //加载ZSKK的校正文件
  531. // m_pZSKKCalib->m_strRawImgPath = m_strWorkPath + "/rawdata/";
  532. // m_pZSKKCalib->m_strRefFilePath = m_strWorkPath + "/references/";
  533. // m_pZSKKCalib->m_nFullImgWidth = m_nImageWidth;
  534. // m_pZSKKCalib->m_nFullImgHeight = m_nImageHeight;
  535. // m_pZSKKCalib->m_nReferenceNum = m_nCalibrationRounds;
  536. // m_pZSKKCalib->m_nSaturationValue = 50000;
  537. // //LoadZSKKGainMap 参数为false,意思是开始增益校正
  538. // m_pZSKKCalib->LoadZSKKGainMap(false, m_strDetectorType);
  539. // m_pZSKKCalib->LoadZSKKPixelMap(false, m_strDetectorType);
  540. // FINFO("Load ecom gain and pixel map, references file path: {$}", m_pZSKKCalib->m_strRefFilePath);
  541. // }
  542. //}
  543. }
  544. FINFO("TiRayDR ActiveCalibration Over");
  545. return true;
  546. }
  547. /***
  548. * 接受曝光图像
  549. ***/
  550. bool Detector_TiRayDR::AcceptCalibration()
  551. {
  552. FINFO("--TiRayDR Func-- AcceptCalibration Start");
  553. if (m_nCalibrationMode)//厂商校正AcceptCalibration
  554. {
  555. //不做处理
  556. }
  557. else //ZSKK校正
  558. {
  559. //WORD* pImageBuffer = nullptr;
  560. ////这里要注意使用的image buffer是哪个,裁剪和不裁剪是不一样的
  561. //if (m_nWidthOffset != 0 || m_nHeightOffset != 0)
  562. //{
  563. // pImageBuffer = m_pImgBuffer;
  564. //}
  565. //else
  566. //{
  567. // pImageBuffer = m_pImgBuffer;//之后再做区分,先测试用
  568. //}
  569. //if (m_nCalibCurrentExposureIndex == 1)
  570. //{
  571. // m_pZSKKCalib->AddImageToPixMap(pImageBuffer);
  572. // m_pZSKKCalib->AverageZSKKGainMap(pImageBuffer, m_nCalibCurrentCalibrationRound - 1, true);
  573. //}
  574. //else
  575. //{
  576. // m_pZSKKCalib->AverageZSKKGainMap(pImageBuffer, m_nCalibCurrentCalibrationRound - 1, false); //曝光第几轮
  577. //}
  578. }
  579. FINFO("TiRayDR AcceptCalibration Over");
  580. return true;
  581. }
  582. /***
  583. * 拒绝曝光图像
  584. ***/
  585. bool Detector_TiRayDR::RejectCalibration()
  586. {
  587. const std::string funcTag = "[Detector_TiRayDR::RejectCalibration] ";
  588. // 检查当前是否在进行增益校正
  589. if (m_eCaliType != CCOS_CALIBRATION_TYPE_XRAY)
  590. {
  591. cout << funcTag << "No active gain calibration in progress" << endl;
  592. return false;
  593. }
  594. bool rejected = false;
  595. if (m_bUseGainV2)
  596. {
  597. if (!m_currentDoseImages.empty())
  598. {
  599. m_currentDoseImages.pop_back();
  600. cout << funcTag << "Rejected last image in dose group " << m_currentDoseIndex
  601. << ". Remaining in group: " << m_currentDoseImages.size() << endl;
  602. rejected = true;
  603. }
  604. else
  605. {
  606. cout << funcTag << "No images in current dose group to reject" << endl;
  607. }
  608. }
  609. else
  610. {
  611. if (!m_gainCalibImages.empty())
  612. {
  613. m_gainCalibImages.pop_back(); // 移除最后添加的图像
  614. cout << funcTag << "Rejected last gain image. Remaining: " << m_gainCalibImages.size() << endl;
  615. rejected = true;
  616. }
  617. else
  618. {
  619. cout << funcTag << "No gain images to reject" << endl;
  620. }
  621. }
  622. return rejected;
  623. }
  624. /***
  625. * 设置校正轮数
  626. ***/
  627. bool Detector_TiRayDR::SetCalibRounds(int nCalibRounds)
  628. {
  629. FINFO("--TiRayDR Func-- SetCalibRounds Start");
  630. m_nCalibrationRounds = nCalibRounds;
  631. FINFO("Set reference number: {$}", m_nCalibrationRounds);
  632. FINFO("TiRayDR SetCalibRounds Over");
  633. return true;
  634. }
  635. bool Detector_TiRayDR::GetCalibrationStep(int nCalibCurrentCalibrationRound, int nCalibrationRounds, int nCalibCurrentExposureIndex, int nExposureNumCurrentRound)
  636. {
  637. FINFO("--TiRayDR Func-- GetCalibrationStep Start");
  638. m_nCalibCurrentCalibrationRound = nCalibCurrentCalibrationRound;
  639. m_nCalibrationRounds = nCalibrationRounds;
  640. m_nCalibCurrentExposureIndex = nCalibCurrentExposureIndex;
  641. m_nExposureNumCurrentRound = nExposureNumCurrentRound;
  642. FINFO("Calibration Step===Round: {$}/{$}, ExposureNum: {$}/{$}", nCalibCurrentCalibrationRound, nCalibrationRounds,
  643. nCalibCurrentExposureIndex, nExposureNumCurrentRound);
  644. FINFO("TiRayDR GetCalibrationStep Over");
  645. return true;
  646. }
  647. bool Detector_TiRayDR::PrepareCalibration(FPDDeviceTiRay* pDrvDPC)
  648. {
  649. const std::string funcTag = "[Detector_TiRayDR::PrepareCalibration] ";
  650. std::cout << funcTag << "--TiRayDR Function-- PrepareCalibration started" << std::endl;
  651. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  652. {
  653. std::cout << funcTag << "Error: Not current DPC device, returning false" << std::endl;
  654. return false;
  655. }
  656. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  657. {
  658. std::cout << funcTag << "Error: Detector not connected (bConnectState is false), returning false" << std::endl;
  659. return false;
  660. }
  661. auto writeAttrWithLog = [this](const std::string& attrName, int value, int err) {
  662. if (err == Err_Success)
  663. {
  664. std::cout << "[Detector_TiRayDR::PrepareCalibration] Success: Wrote attribute " << attrName << " with value " << value << std::endl;
  665. }
  666. else
  667. {
  668. std::cout << "[Detector_TiRayDR::PrepareCalibration] Error: Failed to write attribute " << attrName << ", error code: " << err << std::endl;
  669. }
  670. return err;
  671. };
  672. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  673. {
  674. int ret = DarkAcquisition();
  675. std::cout << funcTag << "Info: DarkAcquisition returned " << ret << std::endl;
  676. if (!ret)
  677. {
  678. std::cout << funcTag << "Info: Sending calibration start status (EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_BEGIN)" << std::endl;
  679. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_BEGIN);
  680. }
  681. }
  682. else if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  683. {
  684. std::cout << funcTag << "Info: Preparing X-ray calibration (CCOS_CALIBRATION_TYPE_XRAY)" << std::endl;
  685. int err = write_attribute(Attr_WorkMode, WorkMode_FreeSync);
  686. writeAttrWithLog("Attr_WorkMode", WorkMode_FreeSync, err);
  687. err = write_attribute(Attr_PhotoInterval, 3000);
  688. writeAttrWithLog("Attr_PhotoInterval", 3000, err);
  689. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  690. writeAttrWithLog("Attr_CalibrationMode", CalibrationMode_None, err);
  691. }
  692. std::cout << funcTag << "Info: TiRayDR PrepareCalibration completed" << std::endl;
  693. return true;
  694. }
  695. //软同步调用接口,其它同步模式没有动作
  696. bool Detector_TiRayDR::StartCalibration(FPDDeviceTiRay* pDrvDPC)
  697. {
  698. FINFO("--TiRayDR Func-- StartCalibration Start");
  699. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  700. {
  701. FERROR("Not current DPC, return");
  702. return false;
  703. }
  704. //未初始化、未连接 不执行
  705. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  706. {
  707. FERROR("bConnectState is false, Detector not connected, return");
  708. return false;
  709. }
  710. if (CCOS_CALIBRATION_TYPE_DARK == m_eCaliType)
  711. {
  712. FINFO("StartCalibration DARK");
  713. StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_END_OK);
  714. m_pStPanelStatus[m_nCurrentPanelID]->eFPDStatus = eDetStatus::DetStatus_Offset;
  715. }
  716. else if (CCOS_CALIBRATION_TYPE_XRAY == m_eCaliType)
  717. {
  718. FINFO("StartCalibration XRAY");
  719. bool ret = StartAcquisition(pDrvDPC);
  720. if (!ret)
  721. {
  722. FERROR("StartCalibration Over");
  723. return false;
  724. }
  725. m_pStPanelStatus[m_nCurrentPanelID]->eFPDStatus = eDetStatus::DetStatus_XrayCalibration;
  726. }
  727. FINFO("TiRayDR StartCalibration Over");
  728. return true;
  729. }
  730. /***
  731. ** 说明:终止校正
  732. ***/
  733. RET_STATUS Detector_TiRayDR::AbortCalibration(FPDDeviceTiRay* pDrvDPC)
  734. {
  735. const std::string funcTag = "[Detector_TiRayDR::AbortCalibration] ";
  736. FINFO("--TiRayDR Func-- AbortCalibration Start");
  737. if (m_eCaliType == CCOS_CALIBRATION_TYPE_XRAY)
  738. {
  739. // 清除增益校正相关数据
  740. m_gainCalibImages.clear();
  741. m_currentDoseImages.clear();
  742. m_gainV2MeanImages.clear();
  743. m_currentDoseIndex = 0;
  744. cout << funcTag << "Aborted " << (!m_bUseGainV2 ? "Gain" : "GainV2")
  745. << " calibration. All related data cleared" << endl;
  746. }
  747. auto err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  748. if (err == Err_Success)
  749. {
  750. std::cout << funcTag << "Success: Wrote attribute Attr_CalibrationMode with value CalibrationMode_Defect" << std::endl;
  751. }
  752. else
  753. {
  754. std::cout << funcTag << "Error: Failed to write attribute Attr_CalibrationMode, error code: " << err << std::endl;
  755. }
  756. // 恢复初始状态
  757. m_eCaliType = CCOS_CALIBRATION_TYPE_NONE;
  758. m_nAppStatus = APP_STATUS_CAL_END;
  759. FINFO("TiRayDR AbortCalibration Over");
  760. return RET_STATUS::RET_SUCCEED;
  761. }
  762. bool Detector_TiRayDR::StopCalibration(FPDDeviceTiRay* pDrvDPC)
  763. {
  764. FINFO("--TiRayDR Func-- StopCalibration Start");
  765. if ((*m_pDPC2PanelID)[pDrvDPC] != m_nCurrentPanelID)
  766. {
  767. FERROR("Not current DPC, return");
  768. return false;
  769. }
  770. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  771. {
  772. FERROR("bConnectState is false, Detector not connected, return");
  773. return false;
  774. }
  775. m_nAppStatus = APP_STATUS_CAL_END;
  776. FINFO("TiRayDR StopCalibration Over");
  777. return true;
  778. }
  779. /***
  780. ** 说明:结束校正
  781. ** DPC处理完校正报告后调用,此处上传map、报告等文件
  782. ***/
  783. bool Detector_TiRayDR::CompleteCalibration(FPDDeviceTiRay* pDrvDPC)
  784. {
  785. FINFO("--TiRayDR Func-- CompleteCalibration Start");
  786. FINFO("Calib Type {$}", (int)m_eCaliType);
  787. const std::string funcTag = "[Detector_TiRayDR::CompleteCalibration] ";
  788. if (m_eCaliType == CCOS_CALIBRATION_TYPE_DARK)
  789. {
  790. FINFO("DARK Calib over");
  791. }
  792. else if (m_eCaliType == CCOS_CALIBRATION_TYPE_XRAY)
  793. {
  794. FINFO("XRAY Calib over");
  795. m_nAppStatus = APP_STATUS_CAL_END;
  796. }
  797. m_eCaliType = CCOS_CALIBRATION_TYPE_NONE;
  798. auto err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  799. if (err == Err_Success)
  800. {
  801. std::cout << funcTag << "Success: Wrote attribute Attr_CalibrationMode with value CalibrationMode_Defect" << std::endl;
  802. }
  803. else
  804. {
  805. std::cout << funcTag << "Error: Failed to write attribute Attr_CalibrationMode, error code: " << err << std::endl;
  806. }
  807. FINFO("TiRayDR CompleteCalibration Over");
  808. return true;
  809. }
  810. bool Detector_TiRayDR::SaveCalibrationFile()
  811. {
  812. FINFO("--TiRayDR Func-- SaveCalibrationFile Start");
  813. if (m_nCalibrationMode)//厂商校正
  814. {
  815. //不做处理
  816. }
  817. else
  818. {
  819. FINFO("Save ZSKK Calibration File");
  820. m_pZSKKCalib->StoreZSKKGainMap(m_strDetectorType);
  821. m_pZSKKCalib->StoreZSKKPixMap(m_strDetectorType);
  822. }
  823. //更新配置文件中校正日期和时间
  824. GlobalTime stCurrentTime = { 0 };
  825. GetLocalTime(&stCurrentTime);
  826. FINFO("Current time: {$04d}/{$02d}/{$02d} {$02d}:{$02d}:{$02d}:{$03d}",
  827. stCurrentTime.wYear, stCurrentTime.wMonth, stCurrentTime.wDay,
  828. stCurrentTime.wHour, stCurrentTime.wMinute, stCurrentTime.wSecond, stCurrentTime.wMilliseconds);
  829. FINFO("TiRayDR SaveCalibrationFile Over");
  830. return true;
  831. }
  832. CCOS_CALIBRATION_TYPE Detector_TiRayDR::GetCalibType()
  833. {
  834. FINFO("--TiRayDR Func-- GetCalibType Start");
  835. FINFO("Get Calib Type {$}", (int)m_eCaliType);
  836. FINFO("TiRayDR GetCalibType Over");
  837. return m_eCaliType;
  838. }
  839. ModelResolveResult Detector_TiRayDR::ResolveModelType(const std::string& detectorType)
  840. {
  841. ModelResolveResult result;
  842. result.isValid = true;
  843. if (detectorType == "GQ1613") {
  844. result.model = Model_GQ1613;
  845. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_GQ1613)..." << endl;
  846. }
  847. else if (detectorType == "DY1613") {
  848. result.model = Model_DY1613;
  849. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY1613)..." << endl;
  850. }
  851. else if (detectorType == "LT1719") {
  852. result.model = Model_LT1719;
  853. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_LT1719)..." << endl;
  854. }
  855. else if (detectorType == "DY4343") {
  856. result.model = Model_DY4343;
  857. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343)..." << endl;
  858. }
  859. else if (detectorType == "DY2530W") {
  860. result.model = Model_DY2530W;
  861. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY2530W)..." << endl;
  862. }
  863. else if (detectorType == "DY2121") {
  864. result.model = Model_DY2121;
  865. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY2121)..." << endl;
  866. }
  867. else if (detectorType == "DY4343D") {
  868. result.model = Model_DY4343D;
  869. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343D)..." << endl;
  870. }
  871. else if (detectorType == "GZ0404") {
  872. result.model = Model_GZ0404;
  873. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_GZ0404)..." << endl;
  874. }
  875. else if (detectorType == "DY3543W") {
  876. result.model = Model_DY3543W;
  877. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY3543W)..." << endl;
  878. }
  879. else if (detectorType == "DY4343W") {
  880. result.model = Model_DY4343W;
  881. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY4343W)..." << endl;
  882. }
  883. else if (detectorType == "DY3543") {
  884. result.model = Model_DY3543;
  885. cout << "[Detector_TiRayDR::OpenDetector] Try to start the detector(Model_DY3543)..." << endl;
  886. }
  887. else {
  888. cout << "[Detector_TiRayDR::OpenDetector] Unsupported detector type: " << detectorType << endl;
  889. // 使用第一个枚举值作为默认,通过isValid标志判断有效性
  890. result.model = Model_GQ1613;
  891. result.isValid = false;
  892. }
  893. return result;
  894. }
  895. bool Detector_TiRayDR::LoadDll(string strWorkPath)
  896. {
  897. FINFO("--TiRayDR Func-- LoadDll Start");
  898. string strSDKPath = "";
  899. try
  900. {
  901. strSDKPath = (string)m_ModeConfig["SDKPath"];
  902. }
  903. catch (ResDataObjectExption& e)
  904. {
  905. FERROR("Read configuration failed! reason: {$}", e.what());
  906. return false;
  907. }
  908. string workpath = strWorkPath + strSDKPath;
  909. string drvpath = workpath + "/TiRayLib.so";
  910. FINFO("SDK path:{$}", drvpath);
  911. m_hTiRayDRModule = dlopen(drvpath.c_str(), RTLD_LAZY);
  912. if (m_hTiRayDRModule == nullptr)
  913. {
  914. FERROR("Load {$} failed! FERROR: {$}", drvpath.c_str(), dlerror());
  915. return false;
  916. }
  917. LOAD_ONE_FUNC(m_hTiRayDRModule, GetSdkVersion);
  918. LOAD_ONE_FUNC(m_hTiRayDRModule, Scan);
  919. LOAD_ONE_FUNC(m_hTiRayDRModule, SetIp);
  920. LOAD_ONE_FUNC(m_hTiRayDRModule, Startup);
  921. LOAD_ONE_FUNC(m_hTiRayDRModule, Stop);
  922. LOAD_ONE_FUNC(m_hTiRayDRModule, Execute);
  923. LOAD_ONE_FUNC(m_hTiRayDRModule, ApplyPreset);
  924. LOAD_ONE_FUNC(m_hTiRayDRModule, GenerateTemplate);
  925. FINFO("TiRayDR LoadDll Over");
  926. return true;
  927. }
  928. bool Detector_TiRayDR::ReleaseDll()
  929. {
  930. FINFO("--TiRayDR Func-- ReleaseDll Start");
  931. if (m_hTiRayDRModule != nullptr)
  932. {
  933. int result = dlclose(m_hTiRayDRModule);
  934. if (result != 0) {
  935. const char* error = dlerror();
  936. if (error) {
  937. FERROR("Failed to unload library: %s", error);
  938. }
  939. else {
  940. FERROR("Failed to unload library (unknown error)");
  941. }
  942. return false;
  943. }
  944. m_hTiRayDRModule = nullptr;
  945. }
  946. FINFO("TiRayDR ReleaseDll Over");
  947. return true;
  948. }
  949. /***
  950. ** 连接探测器
  951. ***/
  952. bool Detector_TiRayDR::OpenDetector()
  953. {
  954. FINFO("--TiRayDR Func-- OpenDetector Start");
  955. m_strWiredIP = (std::string)m_ModeConfig["DetectorWiredIP"];
  956. m_strWirelessIP = (std::string)m_ModeConfig["DetectorWirelessIP"];
  957. m_strLocalIP = (std::string)m_ModeConfig["LocalIP"];
  958. m_strSerialNum = (std::string)m_ModeConfig["SerialNumber"];
  959. FINFO("Configuration parameters loaded - Wired IP:{$}, Wireless IP:{$}, Local IP:{$}",
  960. m_strWiredIP, m_strWirelessIP, m_strLocalIP);
  961. FINFO("WiredIP: {$}, LocalIP: {$}, WirelessIP: {$}, SerialNumber:{$}", m_strWiredIP, m_strLocalIP, m_strWirelessIP, m_strSerialNum);
  962. // 检查连接状态
  963. bool wired = CheckConnect(m_strWiredIP);
  964. bool wireless = CheckConnect(m_strWirelessIP);
  965. FINFO("[Detector_TiRayDR::OpenDetector] Connection status - Wired:{$}, wireless:{$}",
  966. wired ? "Connected" : "Not connected",
  967. wireless ? "Connected" : "Not Connected");
  968. FINFO("[Detector_TiRayDR::OpenDetector] Start scanning the detector...");
  969. std::vector<scan_result> scan_results;
  970. scan([&scan_results](scan_result&& result) {
  971. scan_results.emplace_back(std::move(result));
  972. });
  973. if (scan_results.empty()) {
  974. FINFO("[Detector_TiRayDR::OpenDetector] No detectors were found!");
  975. return false;
  976. }
  977. FINFO("[Detector_TiRayDR::OpenDetector] Scanned to {$} detector:", scan_results.size());
  978. for (auto& res : scan_results) {
  979. FINFO("[Detector_TiRayDR::OpenDetector] Serial number:{$}, Model:{$}, tupper IP:{$}, detector IP:{$}",
  980. res.sn, res.model, res.upper_ip, res.detector_ip);
  981. }
  982. m_strDetectorType = (string)m_ModeConfig["DetectorType"];
  983. FINFO("[Detector_TiRayDR::OpenDetector] Target detector type from config: {$}", m_strDetectorType);
  984. // 选择目标探测器:优先匹配型号,否则使用第一个
  985. scan_result target_res = scan_results[0];
  986. bool found_matching = false;
  987. for (auto& res : scan_results) {
  988. if (res.model == m_strDetectorType) {
  989. target_res = res;
  990. found_matching = true;
  991. break; // 找到第一个匹配的即可
  992. }
  993. }
  994. if (found_matching) {
  995. FINFO("[Detector_TiRayDR::OpenDetector] Found matching detector. Model: {$}, Serial: {$}",
  996. target_res.model, target_res.sn);
  997. }
  998. else {
  999. FINFO("[Detector_TiRayDR::OpenDetector] No matching detector model, using first detected. Model: {$}, Serial: {$}",
  1000. target_res.model, target_res.sn);
  1001. }
  1002. // 初始化启动参数
  1003. string ip = "0.0.0.0";
  1004. StartupOption option{};
  1005. memcpy(option.Ip, ip.c_str(), std::min(ip.size(), sizeof(option.Ip) - 1));
  1006. option.EnableLog = false;
  1007. // 调用解析函数处理设备类型
  1008. ModelResolveResult resolveResult = ResolveModelType(target_res.model);
  1009. if (!resolveResult.isValid) {
  1010. return false;
  1011. }
  1012. // 启动探测器
  1013. auto err = Startup_Ptr(resolveResult.model, on_event_callback, &option);
  1014. if (err != Err_Success) {
  1015. FINFO("[Detector_TiRayDR::OpenDetector] Failed to start the detector");
  1016. return false;
  1017. }
  1018. auto LoadCalibrationFile = [this](int calibrationParam)
  1019. {
  1020. TiRayError err;
  1021. switch (calibrationParam) {
  1022. case 1:
  1023. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  1024. break;
  1025. case 2:
  1026. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Gain);
  1027. break;
  1028. case 3:
  1029. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Offset);
  1030. break;
  1031. case 4:
  1032. err = write_attribute(Attr_CalibrationMode, CalibrationMode_Defect);
  1033. break;
  1034. default:
  1035. FINFO("[Detector_TiRayDR::OpenDetector] Invalid calibration parameter: {$}", calibrationParam);
  1036. return false;
  1037. }
  1038. if (err != Err_Success) {
  1039. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_CalibrationMode, error code: {$}", err);
  1040. }
  1041. else {
  1042. FINFO("[Detector_TiRayDR::OpenDetector] Succeeded in writing Attr_CalibrationMode");
  1043. }
  1044. return true;
  1045. };
  1046. FINFO("Start setting the IP address...");
  1047. err = SetIp_Ptr(target_res.sn.c_str(), m_strLocalIP.c_str(), m_strWiredIP.c_str(), nullptr);
  1048. if (err != TiRayError::Err_Success)
  1049. {
  1050. FINFO("The IP setting failed, error code:{$} (will continue to execute)", err);
  1051. return false;
  1052. }
  1053. else {
  1054. FINFO("IP setting was successful");
  1055. }
  1056. while (!m_bConnected)
  1057. {
  1058. usleep(10000);
  1059. }
  1060. m_pStPanelStatus[m_nCurrentPanelID]->bConnectState = true;
  1061. //FINFO("m_pStPanelStatus[m_nCurrentPanelID]->bConnectState = true");
  1062. //StatusFeedback(EVT_STATUS_PANEL, PANEL_CONNECT);
  1063. //FINFO("Connect detector({$}) success", m_nDetectorID);
  1064. if (m_strDetectorType == "DY4343" || m_strDetectorType == "DY4343D")
  1065. {
  1066. m_bUseGainV2 = true;
  1067. }
  1068. m_nImageWidth = (int)m_ModeConfig["ModeTable"][0]["ImageWidth"];
  1069. m_nImageHeight = (int)m_ModeConfig["ModeTable"][0]["ImageHeight"];
  1070. m_nRawImgWidth = (int)m_ModeConfig["ModeTable"][0]["RawImgWidth"];
  1071. m_nRawImgHeight = (int)m_ModeConfig["ModeTable"][0]["RawImgHeight"];
  1072. FINFO("After crop image width: {$}, height: {$}, WidthOffset: {$}, HeightOffset: {$}", m_nImageWidth, m_nImageHeight, m_nWidthOffset, m_nHeightOffset);
  1073. m_bSaveRaw = (int)m_ModeConfig["ModeTable"][0]["IsSaveRaw"];
  1074. if (m_pRawImgBuffer == nullptr)
  1075. {
  1076. m_pRawImgBuffer = new WORD[(size_t)m_nRawImgHeight * (size_t)m_nRawImgWidth];
  1077. }
  1078. if (true)
  1079. {
  1080. m_pImgBuffer = new WORD[(size_t)m_nImageWidth * (size_t)m_nImageWidth];
  1081. }
  1082. // 加载校准文件
  1083. cout << "[Detector_TiRayDR::OpenDetector] Start loading the calibration file..." << endl;
  1084. //if (m_nCalibrationMode) //TiRayCalibration
  1085. SetSyncMode(3);
  1086. int nSensitivity = (int)m_ModeConfig["ModeTable"][0]["Sensitivity"];
  1087. int nXWindow = (int)m_ModeConfig["ModeTable"][0]["XWindow"];
  1088. err = write_attribute(Attr_PhotoInterval, nXWindow);
  1089. if (err != Err_Success)
  1090. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_PhotoInterval. Error code: {$}", err);
  1091. err = write_attribute(Attr_PhotoNumber, 1);
  1092. if (err != Err_Success)
  1093. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_PhotoNumber. Error code: {$}", err);
  1094. LoadCalibrationFile(4);
  1095. err = write_attribute(Attr_AEDSensitivity, nSensitivity);
  1096. if (err != Err_Success)
  1097. FINFO("[Detector_TiRayDR::OpenDetector] Failed to write Attr_AEDSensitivity. Error code: {$}", err);
  1098. SetTiRayDPCStatus(eDetStatus::DetStatus_Standby);
  1099. FINFO("OpenDetector Over");
  1100. return true;
  1101. }
  1102. bool Detector_TiRayDR::CheckConnect(string strIP)
  1103. {
  1104. CMyPingip obPingIp;
  1105. if (!obPingIp.PingFunction(strIP.c_str()))
  1106. {
  1107. FINFO("ping {$} Failed", strIP);
  1108. return false;
  1109. }
  1110. return true;
  1111. }
  1112. bool Detector_TiRayDR::OpenStatusMonitor()
  1113. {
  1114. FINFO("---Open Status Monitor Thread---");
  1115. if (m_hStatusMonitorThread == 0) // 检查线程是否已创建
  1116. {
  1117. int result = pthread_create(&m_hStatusMonitorThread, NULL, TiRayStatusMonitorThread, this);
  1118. if (result != 0) {
  1119. FERROR("Failed to create status monitor thread: %d", result);
  1120. return false;
  1121. }
  1122. }
  1123. return true;
  1124. }
  1125. void* Detector_TiRayDR::TiRayStatusMonitorThread(PVOID pvoid)
  1126. {
  1127. Detector_TiRayDR* pCurrentPanelOpr = static_cast<Detector_TiRayDR*>(pvoid);
  1128. if (pCurrentPanelOpr == nullptr)
  1129. {
  1130. FERROR("TiRay Status Monitor parameter FERROR");
  1131. return nullptr;
  1132. }
  1133. FINFO("Begin StatusMonitor");
  1134. DWORD dwStatusCheckTime = 5000;
  1135. while (!pCurrentPanelOpr->m_bMonitorFlag)
  1136. {
  1137. pCurrentPanelOpr->StatusMonitor();
  1138. usleep(pCurrentPanelOpr->m_nNotifyStatusTimePeriod*1000);
  1139. }
  1140. return 0;
  1141. }
  1142. bool Detector_TiRayDR::StatusMonitor()
  1143. {
  1144. if (!m_pStPanelStatus[m_nCurrentPanelID]->bConnectState)
  1145. {
  1146. FERROR("Detector not connected, return");
  1147. ErrorFeedback(EVT_ERR_COMMUNICATE, "true");
  1148. return false;
  1149. }
  1150. //StatusType: 1:Temperature 2:Wifi 3:Battery
  1151. //auto ReadStatus = [this](int StatusType)
  1152. //{
  1153. // TiRayVariant TempParam[1]{};
  1154. // TempParam[0].Type = TiRayVariant::TiRayInt;
  1155. //};
  1156. int nTemperature = 0;
  1157. int nWifiQuality = 0;
  1158. int nBatteryLevel = 0;
  1159. TiRayVariant TemperatureParam[1]{};
  1160. TemperatureParam[0].Type = TiRayVariant::TiRayInt;
  1161. TemperatureParam[0].IntValue = 0;
  1162. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, TemperatureParam, 1);
  1163. nTemperature = TemperatureParam[0].IntValue;
  1164. TiRayVariant WifiParam[1]{};
  1165. WifiParam[0].Type = TiRayVariant::TiRayInt;
  1166. WifiParam[0].IntValue = nWifiQuality;
  1167. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, WifiParam, 1);
  1168. TiRayVariant BatteryParam[1]{};
  1169. BatteryParam[0].Type = TiRayVariant::TiRayInt;
  1170. BatteryParam[0].IntValue = nBatteryLevel;
  1171. Execute_Ptr(m_nDetectorID, Cmd_ReadAttribute, BatteryParam, 1);
  1172. StatusFeedback(EVT_STATUS_TEMPERATURE, 0, "", m_nCurrentPanelID, nTemperature);
  1173. StatusFeedback(EVT_STATUS_BATTERY_VALUE, nBatteryLevel, "", m_nCurrentPanelID);
  1174. StatusFeedback(EVT_STATUS_WIFI, nWifiQuality, "", m_nCurrentPanelID);
  1175. return true;
  1176. }
  1177. bool Detector_TiRayDR::CloseStatusMonitor()
  1178. {
  1179. m_bMonitorFlag = true;
  1180. m_hStatusMonitorThread = 0;
  1181. FINFO("---Close Status Monitor Thread---");
  1182. return true;
  1183. }
  1184. bool Detector_TiRayDR::CloseDetectorScan()
  1185. {
  1186. m_hExitEvent->SetEvent();
  1187. return false;
  1188. }
  1189. bool Detector_TiRayDR::LoadCalibrationFiles(int nCalibrationMode)
  1190. {
  1191. FINFO("--TiRayDR Func-- LoadCalibrationFiles");
  1192. int nRes;
  1193. TiRayVariant Param[2]{};
  1194. Param[0].Type = TiRayVariant::TiRayInt;
  1195. Param[0].IntValue = TiRayAttribute::Attr_CalibrationMode;
  1196. Param[1].Type = TiRayVariant::TiRayInt;
  1197. if (nCalibrationMode == 1)
  1198. {
  1199. Param[1].IntValue = CalibrationMode::CalibrationMode_None;
  1200. }
  1201. else if (nCalibrationMode == 2)
  1202. {
  1203. Param[1].IntValue = CalibrationMode::CalibrationMode_Gain;
  1204. }
  1205. else if (nCalibrationMode == 3)
  1206. {
  1207. Param[1].IntValue = CalibrationMode::CalibrationMode_Offset;
  1208. }
  1209. else if (nCalibrationMode == 4)
  1210. {
  1211. Param[1].IntValue = CalibrationMode::CalibrationMode_Defect;
  1212. FINFO("All Calibration Mode");
  1213. }
  1214. nRes = Execute_Ptr(m_nDetectorID, Cmd_WriteAttribute, Param, 2);
  1215. if ((TiRayError)nRes != TiRayError::Err_Success)
  1216. {
  1217. FERROR("Use CalibrationMode Failed, Reason:{$}", nRes);
  1218. return false;
  1219. }
  1220. else
  1221. {
  1222. FINFO("Use CalibrationMode Success");
  1223. }
  1224. FINFO("LoadCalibrationFiles Over");
  1225. return true;
  1226. }
  1227. void* Detector_TiRayDR::onFPDScanThread(PVOID pvoid)
  1228. {
  1229. Detector_TiRayDR* pOpr = (Detector_TiRayDR*)pvoid;
  1230. FINFO("Enter scan thread");
  1231. bool bExit = false;
  1232. DWORD dwTimeOut = INFINITE;
  1233. while (!bExit)
  1234. {
  1235. DWORD dwRet = LinuxEvent::WaitForMultipleEvents(pOpr->m_hArrayEvent,dwTimeOut);
  1236. if (WAIT_OBJECT_0 == dwRet) //m_hInitEvent
  1237. {
  1238. pOpr->OnProcessInitFPD();
  1239. }
  1240. else if (WAIT_OBJECT_0 + 1 == dwRet) //m_hExitEvent
  1241. {
  1242. bExit = true;
  1243. }
  1244. else if (WAIT_OBJECT_0 + 2 == dwRet) //m_hReConnectEvent
  1245. {
  1246. pOpr->OnReconnectFPD();
  1247. }
  1248. else if (WAIT_OBJECT_0 + 3 == dwRet) //m_hRadEvent
  1249. {
  1250. FINFO("[Get Rad Event]");
  1251. pOpr->OpenRadAcquisition();
  1252. }
  1253. else if (WAIT_TIMEOUT == dwRet)
  1254. {
  1255. }
  1256. }
  1257. pOpr->m_hToggleEvent->SetEvent();
  1258. FINFO("Leave scan thread");
  1259. return 0;
  1260. }
  1261. void Detector_TiRayDR::OnProcessInitFPD()
  1262. {
  1263. FINFO("--TiRayDR Func-- OnProcessInitFPD");
  1264. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_START);
  1265. if (!LoadDll(m_strWorkPath))
  1266. {
  1267. ErrorFeedback(EVT_ERR_INIT_FAILED, "true");
  1268. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END_ERROR); //初始化失败
  1269. return;
  1270. }
  1271. register_event_listener(OnEvent);
  1272. FINFO("Register Event Listener");
  1273. if (!OpenDetector())
  1274. {
  1275. FINFO("Open detector failed, Connect failed");
  1276. ErrorFeedback(EVT_ERR_COMMUNICATE, "true");
  1277. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END); //初始化时连接失败
  1278. }
  1279. else
  1280. {
  1281. m_pStPanelStatus[m_nCurrentPanelID]->bInitOver = true;
  1282. StatusFeedback(EVT_STATUS_INIT, PANEL_EVENT_END_OK);
  1283. }
  1284. FINFO("OnProcessInitFPD Over");
  1285. }
  1286. void Detector_TiRayDR::OnReconnectFPD()
  1287. {
  1288. FINFO("OnReconnectFPD start");
  1289. if (m_hReconnectThread == 0)
  1290. {
  1291. m_bReconnectThreadRunning = true;
  1292. int result = pthread_create(&m_hReconnectThread, NULL, onReconnectThread, this);
  1293. if (result != 0) {
  1294. FERROR("Failed to create reconnect thread: %d", result);
  1295. m_hReconnectThread = 0;
  1296. m_bReconnectThreadRunning = false;
  1297. }
  1298. }
  1299. FINFO("OnReconnectFPD end");
  1300. }
  1301. /***
  1302. ** 获取一帧暗场图
  1303. ***/
  1304. int Detector_TiRayDR::DarkAcquisition()
  1305. {
  1306. const std::string funcTag = "[Detector_TiRayDR::DarkAcquisition] ";
  1307. TiRayError err;
  1308. // 设置校准模式为None
  1309. err = write_attribute(Attr_CalibrationMode, CalibrationMode_None);
  1310. if (err != Err_Success) {
  1311. cout << funcTag << "Failed to write Attr_CalibrationMode. Error code: " << err << endl;
  1312. return -1;
  1313. }
  1314. // 设置拍摄间隔
  1315. err = write_attribute(Attr_PhotoInterval, 1000);
  1316. if (err != Err_Success) {
  1317. cout << funcTag << "Failed to write Attr_PhotoInterval. Error code: " << err << endl;
  1318. return -1;
  1319. }
  1320. // 设置工作模式为空闲
  1321. err = write_attribute(Attr_WorkMode, WorkMode_Idle);
  1322. if (err != Err_Success) {
  1323. cout << funcTag << "Failed to write Attr_WorkMode. Error code: " << err << endl;
  1324. return -1;
  1325. }
  1326. // 执行拍摄命令
  1327. err = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  1328. if (err != Err_Success) {
  1329. cout << funcTag << "Failed to Execute_Ptr Cmd_Photo. Error code: " << err << endl;
  1330. return -1;
  1331. }
  1332. return 0; // 成功执行返回0
  1333. }
  1334. /***
  1335. ** 裁剪图像
  1336. ** pOutImg: 裁剪后图像; pInImg: 裁剪前图像; nInWidth: 裁剪前图像宽度
  1337. ***/
  1338. bool Detector_TiRayDR::GetEffectiveImage(WORD* pOutImg, WORD* pInImg, int nInWidth)
  1339. {
  1340. if (pOutImg == NULL || pInImg == NULL || nInWidth < 0)
  1341. {
  1342. FERROR("Illegal parameter, can not get effective image");
  1343. return false;
  1344. }
  1345. try
  1346. {
  1347. for (int i = 0; i < m_nImageHeight; i++)
  1348. {
  1349. memcpy(pOutImg + i * m_nImageWidth, pInImg + (i + m_nHeightOffset) * nInWidth + m_nWidthOffset, m_nImageWidth * sizeof(WORD));
  1350. }
  1351. }
  1352. catch (...)
  1353. {
  1354. FERROR("Get effective image crashed");
  1355. return false;
  1356. }
  1357. return true;
  1358. }
  1359. Detector_TiRayDR::eDetStatus Detector_TiRayDR::GetTiRayDPCStatus(int nDetectorIndex)
  1360. {
  1361. if (-1 == nDetectorIndex)
  1362. {
  1363. nDetectorIndex = m_nCurrentPanelID;
  1364. }
  1365. string strStatus = "Unknown";
  1366. switch (m_pStPanelStatus[nDetectorIndex]->eFPDStatus)
  1367. {
  1368. case eDetStatus::DetStatus_NotIni:
  1369. strStatus = "NotIni";
  1370. break;
  1371. case eDetStatus::DetStatus_NotConn:
  1372. strStatus = "NotConn";
  1373. break;
  1374. case eDetStatus::DetStatus_Sleep:
  1375. strStatus = "Sleep";
  1376. break;
  1377. case eDetStatus::DetStatus_Standby:
  1378. strStatus = "Standby";
  1379. break;
  1380. case eDetStatus::DetStatus_Work:
  1381. strStatus = "Work";
  1382. break;
  1383. case eDetStatus::DetStatus_Acquire:
  1384. strStatus = "Acquire";
  1385. break;
  1386. case eDetStatus::DetStatus_Offset:
  1387. strStatus = "Offset";
  1388. break;
  1389. case eDetStatus::DetStatus_XrayCalibration:
  1390. strStatus = "XrayCalibration";
  1391. break;
  1392. default:
  1393. break;
  1394. }
  1395. FINFO("Driver status: {$}", strStatus.c_str());
  1396. return m_pStPanelStatus[nDetectorIndex]->eFPDStatus;
  1397. }
  1398. bool Detector_TiRayDR::SetTiRayDPCStatus(eDetStatus status, int nDetectorIndex)
  1399. {
  1400. if (-1 == nDetectorIndex)
  1401. {
  1402. nDetectorIndex = m_nCurrentPanelID;
  1403. }
  1404. string strStatus = "Unknown";
  1405. bool bSetStatus = true;
  1406. switch (status)
  1407. {
  1408. case eDetStatus::DetStatus_NotIni:
  1409. strStatus = "NotIni";
  1410. break;
  1411. case eDetStatus::DetStatus_NotConn:
  1412. strStatus = "NotConn";
  1413. break;
  1414. case eDetStatus::DetStatus_Sleep:
  1415. strStatus = "Sleep";
  1416. break;
  1417. case eDetStatus::DetStatus_Standby:
  1418. strStatus = "Standby";
  1419. break;
  1420. case eDetStatus::DetStatus_Work:
  1421. strStatus = "Work";
  1422. break;
  1423. case eDetStatus::DetStatus_Acquire:
  1424. strStatus = "Acquire";
  1425. break;
  1426. case eDetStatus::DetStatus_Offset:
  1427. strStatus = "Offset";
  1428. break;
  1429. case eDetStatus::DetStatus_XrayCalibration:
  1430. strStatus = "XrayCalibration";
  1431. break;
  1432. default:
  1433. bSetStatus = false;
  1434. break;
  1435. }
  1436. if (bSetStatus)
  1437. {
  1438. m_pStPanelStatus[nDetectorIndex]->eFPDStatus = status;
  1439. FINFO("Set driver status: {$}", strStatus.c_str());
  1440. }
  1441. else
  1442. {
  1443. FERROR("{$} {$} is a illegal status", strStatus, (int)status);
  1444. }
  1445. return bSetStatus;
  1446. }
  1447. bool Detector_TiRayDR::IsConnected(string strIP)
  1448. {
  1449. FINFO("Check ping {$}", strIP);
  1450. CMyPingip obPingIp;
  1451. if (!obPingIp.PingFunction(strIP.c_str()))
  1452. {
  1453. FINFO("ping {$} Failed", strIP);
  1454. return false;
  1455. }
  1456. return true;
  1457. }
  1458. bool Detector_TiRayDR::CheckConnection()
  1459. {
  1460. return false;
  1461. }
  1462. bool Detector_TiRayDR::ReConnectFPD()
  1463. {
  1464. CloseStatusMonitor();
  1465. return true;
  1466. }
  1467. bool Detector_TiRayDR::OpenRadAcquisition()
  1468. {
  1469. FINFO("---Begin Rad Acquisition Thread---");
  1470. m_bExitRadAcqStatus = true;
  1471. if (m_hRadAcquisitionThread == 0)
  1472. {
  1473. int result = pthread_create(&m_hRadAcquisitionThread, NULL, RadAcquisitionThread, this);
  1474. if (result != 0) {
  1475. FERROR("Failed to create status monitor thread: %d", result);
  1476. return false;
  1477. }
  1478. }
  1479. return true;
  1480. }
  1481. void* Detector_TiRayDR::RadAcquisitionThread(void* pParam)
  1482. {
  1483. Detector_TiRayDR* pCurrentPanelOpr = reinterpret_cast<Detector_TiRayDR*>(pParam);
  1484. if (pCurrentPanelOpr == nullptr)
  1485. {
  1486. FERROR("Query Acq Status Thread parameter FERROR");
  1487. }
  1488. pCurrentPanelOpr->PerformRadAcquisition();
  1489. pCurrentPanelOpr->CloseRadAcquisition();
  1490. return nullptr;
  1491. }
  1492. bool Detector_TiRayDR::PerformRadAcquisition()
  1493. {
  1494. FINFO("## PerformRadAcquisition ##");
  1495. FINFO("Start Acquisition");
  1496. FINFO("DetectorID: {$}", m_nDetectorID);
  1497. //int nRes = Execute_Ptr(m_nDetectorID, Cmd_Photo, nullptr, 0);
  1498. //if ((TiRayError)nRes != TiRayError::Err_Success)
  1499. //{
  1500. // FERROR("Start Acquisition Failed");
  1501. //}
  1502. while (true)
  1503. {
  1504. usleep(100000);
  1505. if (!m_bExitRadAcqStatus)
  1506. {
  1507. break;
  1508. }
  1509. }
  1510. m_hExitRadAcqStatus->SetEvent();
  1511. FINFO("PerformRadAcquisition Over");
  1512. return true;
  1513. }
  1514. bool Detector_TiRayDR::CloseRadAcquisition()
  1515. {
  1516. m_bExitRadAcqStatus = false;
  1517. bool dwResult = false;
  1518. if (m_hExitRadAcqStatus) {
  1519. dwResult = m_hExitRadAcqStatus->Wait(1000);
  1520. }
  1521. if (dwResult)
  1522. {
  1523. FINFO("[Get ExitRadAcqStatus Event]");
  1524. }
  1525. else
  1526. {
  1527. if (m_hRadAcquisitionThread != 0) {
  1528. pthread_cancel(m_hRadAcquisitionThread);
  1529. // 等待线程实际退出
  1530. struct timespec ts;
  1531. clock_gettime(CLOCK_REALTIME, &ts);
  1532. ts.tv_sec += 1; // 等待1秒
  1533. pthread_timedjoin_np(m_hRadAcquisitionThread, nullptr, &ts);
  1534. FWARN("Kill QueryAcqStatus Thread");
  1535. }
  1536. FWARN("Kill QueryAcqStatus Thread");
  1537. }
  1538. m_hRadAcquisitionThread = 0;
  1539. FINFO("---Exit Rad Acq Status Thread---");
  1540. return true;
  1541. }
  1542. /***
  1543. ** 检测接口是否有错误,true:有错;false:没错
  1544. ***/
  1545. bool Detector_TiRayDR::TestError(TiRayError nErrorCode)
  1546. {
  1547. if (nErrorCode == TiRayError::Err_Success)
  1548. {
  1549. return true;
  1550. }
  1551. else
  1552. {
  1553. switch (nErrorCode)
  1554. {
  1555. case TiRayError::Err_SystemFailure:
  1556. {
  1557. FERROR("System Internal Error");
  1558. break;
  1559. }
  1560. case TiRayError::Err_WrongModel:
  1561. {
  1562. FERROR("The specified model is incorrect");
  1563. break;
  1564. }
  1565. case TiRayError::Err_DetectorNonExists:
  1566. {
  1567. FERROR("The specified detector with the given ID dose not exist");
  1568. break;
  1569. }
  1570. case TiRayError::Err_NetworkFailure:
  1571. {
  1572. FERROR("The network communication has failed");
  1573. break;
  1574. }
  1575. case TiRayError::Err_InvalidParam:
  1576. {
  1577. FERROR("The provided parameters are incorrect");
  1578. break;
  1579. }
  1580. case TiRayError::Err_UploadInProgress:
  1581. {
  1582. FERROR("The upload is in progress");
  1583. break;
  1584. }
  1585. default:
  1586. FERROR("Unkonwn Error");
  1587. break;
  1588. }
  1589. return false;
  1590. }
  1591. }
  1592. void Detector_TiRayDR::register_event_listener(const EventListener& fn)
  1593. {
  1594. const auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [&fn](auto& listener) {
  1595. return listener.template target<EventListenerType>() == fn.template target<EventListenerType>();
  1596. });
  1597. if (iter == m_listeners.end())
  1598. m_listeners.push_back(fn);
  1599. }
  1600. void Detector_TiRayDR::unregister_event_listener(const EventListener& fn)
  1601. {
  1602. const auto iter = std::find_if(m_listeners.begin(), m_listeners.end(), [&fn](auto& listener) {
  1603. return listener.template target<EventListenerType>() == fn.template target<EventListenerType>();
  1604. });
  1605. if (iter == m_listeners.end())
  1606. m_listeners.erase(iter);
  1607. }
  1608. bool Detector_TiRayDR::cropImage(unsigned short* srcData, int srcWidth, int srcHeight,
  1609. unsigned short* destData, int destWidth, int destHeight)
  1610. {
  1611. // 验证指针有效性
  1612. if (srcData == nullptr || destData == nullptr) {
  1613. cout << "[Detector_TiRayDR::cropImage] Error: Source or destination pointer is null" << endl;
  1614. return false;
  1615. }
  1616. // 验证尺寸合法性
  1617. if (destWidth <= 0 || destHeight <= 0 ||
  1618. srcWidth <= 0 || srcHeight <= 0 ||
  1619. destWidth > srcWidth || destHeight > srcHeight)
  1620. {
  1621. cout << "[Detector_TiRayDR::cropImage] Invalid crop size: src("
  1622. << srcWidth << "x" << srcHeight << ") dest("
  1623. << destWidth << "x" << destHeight << ")" << endl;
  1624. return false;
  1625. }
  1626. // 计算裁剪起始位置
  1627. int startX = (srcWidth - destWidth) / 2;
  1628. int startY = (srcHeight - destHeight) / 2;
  1629. // 边界检查
  1630. if (startX < 0) startX = 0;
  1631. if (startY < 0) startY = 0;
  1632. // 确保裁剪区域不会超出源图像边界
  1633. if (startX + destWidth > srcWidth) {
  1634. destWidth = srcWidth - startX;
  1635. cout << "[Detector_TiRayDR::cropImage] Adjusted destWidth to " << destWidth
  1636. << " to avoid out-of-bounds access" << endl;
  1637. }
  1638. if (startY + destHeight > srcHeight) {
  1639. destHeight = srcHeight - startY;
  1640. cout << "[Detector_TiRayDR::cropImage] Adjusted destHeight to " << destHeight
  1641. << " to avoid out-of-bounds access" << endl;
  1642. }
  1643. // 逐行复制裁剪区域
  1644. for (int y = 0; y < destHeight; ++y)
  1645. {
  1646. // 计算源图像行起始地址
  1647. const unsigned short* srcRow = srcData + (startY + y) * srcWidth + startX;
  1648. // 计算目标图像行起始地址
  1649. unsigned short* destRow = destData + y * destWidth;
  1650. // 复制一行像素
  1651. memcpy(destRow, srcRow, destWidth * sizeof(unsigned short));
  1652. }
  1653. cout << "[Detector_TiRayDR::cropImage] Successfully cropped image from "
  1654. << srcWidth << "x" << srcHeight << " to " << destWidth << "x" << destHeight << endl;
  1655. return true;
  1656. }
  1657. std::string Detector_TiRayDR::saveProcessedImage(Detector_TiRayDR& detector, unsigned short* data, size_t size, const std::string& baseTimestamp)
  1658. {
  1659. const size_t MAX_PROC_FILE_COUNT = 10;
  1660. const std::string TMPFS_DIR = "/mnt/tmpfs/";
  1661. const std::string ORIGINAL_DIR = detector.m_strWorkPath + "/RawData/";
  1662. std::string procDir;
  1663. bool useTmpfs = false;
  1664. // 确定存储目录
  1665. if (std::filesystem::exists(TMPFS_DIR) && std::filesystem::is_directory(TMPFS_DIR))
  1666. {
  1667. procDir = TMPFS_DIR;
  1668. useTmpfs = true;
  1669. std::cout << "[Detector_TiRayDR::saveProcessedImage] Using tmpfs directory: " << procDir << std::endl;
  1670. }
  1671. else
  1672. {
  1673. procDir = ORIGINAL_DIR;
  1674. std::cout << "[Detector_TiRayDR::saveProcessedImage] /mnt/tmpfs not found, using original directory: " << procDir << std::endl;
  1675. }
  1676. const std::string FILE_PREFIX = "Proc_";
  1677. std::string filePath;
  1678. try
  1679. {
  1680. std::filesystem::create_directories(procDir);
  1681. filePath = procDir + FILE_PREFIX + baseTimestamp + ".raw";
  1682. std::ofstream file(filePath, std::ios::binary);
  1683. if (file.is_open())
  1684. {
  1685. file.write(reinterpret_cast<const char*>(detector.m_pImgBuffer), size);
  1686. std::cout << "[Detector_TiRayDR::saveProcessedImage] Saved image: " << filePath << std::endl;
  1687. }
  1688. else
  1689. {
  1690. std::cout << "[Detector_TiRayDR::saveProcessedImage] Failed to open file: " << filePath << std::endl;
  1691. return "";
  1692. }
  1693. cleanOldFiles(procDir, FILE_PREFIX, MAX_PROC_FILE_COUNT, useTmpfs);
  1694. }
  1695. catch (const std::filesystem::filesystem_error& e)
  1696. {
  1697. std::cout << "[Detector_TiRayDR::saveProcessedImage] File system error: " << e.what() << std::endl;
  1698. return "";
  1699. }
  1700. catch (const std::exception& e)
  1701. {
  1702. std::cout << "[Detector_TiRayDR::saveProcessedImage] Unexpected error: " << e.what() << std::endl;
  1703. return "";
  1704. }
  1705. return filePath;
  1706. }
  1707. void Detector_TiRayDR::saveRawImage(Detector_TiRayDR& detector, unsigned short* data, size_t size, const std::string& baseTimestamp)
  1708. {
  1709. const std::string RAW_DIR = detector.m_strWorkPath + "/OriginalData/";
  1710. const std::string FILE_PREFIX = "orig_";
  1711. const size_t MAX_RAW_FILE_COUNT = 20;
  1712. std::string filePath;
  1713. try
  1714. {
  1715. std::filesystem::create_directories(RAW_DIR);
  1716. filePath = RAW_DIR + FILE_PREFIX + baseTimestamp + ".raw";
  1717. std::ofstream file(filePath, std::ios::binary);
  1718. if (file.is_open())
  1719. {
  1720. // 直接写入unsigned short缓冲区数据
  1721. file.write(reinterpret_cast<const char*>(data), size);
  1722. cout << "[Detector_TiRayDR::saveRawImage] Saved raw image: " << filePath << endl;
  1723. }
  1724. else
  1725. {
  1726. cout << "[Detector_TiRayDR::saveRawImage] Failed to open file: " << filePath << endl;
  1727. return;
  1728. }
  1729. // 清理旧的原始图
  1730. cleanOldFiles(RAW_DIR, FILE_PREFIX, MAX_RAW_FILE_COUNT, false);
  1731. }
  1732. catch (const std::filesystem::filesystem_error& e)
  1733. {
  1734. cout << "[Detector_TiRayDR::saveRawImage] File system error: " << e.what() << endl;
  1735. }
  1736. }
  1737. std::filesystem::space_info getFileSystemInfo(const std::string& dirPath) {
  1738. try {
  1739. return std::filesystem::space(dirPath);
  1740. }
  1741. catch (const std::filesystem::filesystem_error& e) {
  1742. std::cout << "[getFileSystemInfo] Failed to get filesystem info for "
  1743. << dirPath << ": " << e.what() << std::endl;
  1744. return {};
  1745. }
  1746. }
  1747. void Detector_TiRayDR::cleanOldFiles(const std::string& dirPath, const std::string& filePrefix,
  1748. size_t maxCount, bool checkSize)
  1749. {
  1750. const std::string funcTag = "[Detector_TiRayDR::cleanOldFiles] ";
  1751. try
  1752. {
  1753. // 检查目录是否存在
  1754. if (!std::filesystem::exists(dirPath) || !std::filesystem::is_directory(dirPath))
  1755. {
  1756. std::cout << funcTag << "Directory not found: " << dirPath << std::endl;
  1757. return;
  1758. }
  1759. std::vector<std::filesystem::directory_entry> targetFiles;
  1760. for (const auto& entry : std::filesystem::directory_iterator(dirPath))
  1761. {
  1762. // 只处理常规文件
  1763. if (!entry.is_regular_file())
  1764. continue;
  1765. // 检查文件扩展名是否为.raw
  1766. const std::string extension = entry.path().extension().string();
  1767. if (extension != ".raw")
  1768. continue;
  1769. // 检查文件名是否以指定前缀开头
  1770. const std::string filename = entry.path().filename().string();
  1771. if (filename.length() < filePrefix.length())
  1772. continue;
  1773. if (filename.substr(0, filePrefix.length()) == filePrefix)
  1774. {
  1775. targetFiles.push_back(entry);
  1776. }
  1777. }
  1778. // 按文件最后修改时间排序(最旧的在前)
  1779. std::sort(targetFiles.begin(), targetFiles.end(),
  1780. [](const std::filesystem::directory_entry& a, const std::filesystem::directory_entry& b)
  1781. {
  1782. return std::filesystem::last_write_time(a) < std::filesystem::last_write_time(b);
  1783. });
  1784. // 1. 先按数量限制清理
  1785. size_t filesToDelete = 0;
  1786. if (targetFiles.size() > maxCount)
  1787. {
  1788. filesToDelete = targetFiles.size() - maxCount;
  1789. // 删除超出数量限制的最旧文件
  1790. for (size_t i = 0; i < filesToDelete; ++i)
  1791. {
  1792. const auto& fileToDelete = targetFiles[i];
  1793. if (std::filesystem::remove(fileToDelete.path()))
  1794. {
  1795. std::cout << funcTag << "Deleted old file (count limit): " << fileToDelete.path() << std::endl;
  1796. }
  1797. else
  1798. {
  1799. std::cout << funcTag << "Failed to delete file: " << fileToDelete.path() << std::endl;
  1800. }
  1801. }
  1802. // 更新目标文件列表(移除已删除的文件)
  1803. targetFiles.erase(targetFiles.begin(), targetFiles.begin() + filesToDelete);
  1804. filesToDelete = 0; // 重置计数器用于大小检查
  1805. }
  1806. // 2. 如果需要,按大小限制清理(仅对tmpfs目录)
  1807. if (checkSize && !targetFiles.empty())
  1808. {
  1809. // 获取文件系统信息
  1810. auto fsInfo = getFileSystemInfo(dirPath);
  1811. if (fsInfo.capacity == 0) // 获取信息失败
  1812. {
  1813. std::cout << funcTag << "Cannot check filesystem size, skipping size check" << std::endl;
  1814. return;
  1815. }
  1816. // 计算最大允许使用空间(预留10%作为缓冲)
  1817. const uintmax_t reservedSpace = fsInfo.capacity / 10; // 10%预留空间
  1818. const uintmax_t maxAllowedSize = fsInfo.capacity - reservedSpace;
  1819. // 计算当前文件总大小
  1820. auto calculateTotalSize = [](const std::vector<std::filesystem::directory_entry>& files) {
  1821. uintmax_t total = 0;
  1822. for (const auto& file : files) {
  1823. total += file.file_size();
  1824. }
  1825. return total;
  1826. };
  1827. uintmax_t currentTotalSize = calculateTotalSize(targetFiles);
  1828. std::cout << funcTag << "Current files total size: " << currentTotalSize
  1829. << ", Max allowed size: " << maxAllowedSize << std::endl;
  1830. // 如果当前总大小超过限制,继续删除最旧的文件
  1831. while (currentTotalSize > maxAllowedSize && !targetFiles.empty())
  1832. {
  1833. const auto& fileToDelete = targetFiles[0];
  1834. uintmax_t fileSize = fileToDelete.file_size();
  1835. if (std::filesystem::remove(fileToDelete.path()))
  1836. {
  1837. std::cout << funcTag << "Deleted old file (size limit): " << fileToDelete.path()
  1838. << " (" << fileSize << " bytes)" << std::endl;
  1839. // 更新总量和文件列表
  1840. currentTotalSize -= fileSize;
  1841. targetFiles.erase(targetFiles.begin());
  1842. filesToDelete++;
  1843. }
  1844. else
  1845. {
  1846. std::cout << funcTag << "Failed to delete file: " << fileToDelete.path() << std::endl;
  1847. break; // 删除失败时停止处理
  1848. }
  1849. }
  1850. }
  1851. std::cout << funcTag << "Cleanup completed. Deleted " << filesToDelete
  1852. << " files. Remaining: " << targetFiles.size() << std::endl;
  1853. }
  1854. catch (const std::filesystem::filesystem_error& e)
  1855. {
  1856. std::cout << funcTag << "File system error: " << e.what() << std::endl;
  1857. }
  1858. catch (const std::exception& e)
  1859. {
  1860. std::cout << funcTag << "Unexpected error: " << e.what() << std::endl;
  1861. }
  1862. }
  1863. void Detector_TiRayDR::handleHardwareSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  1864. {
  1865. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  1866. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  1867. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  1868. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  1869. bool cropSuccess = cropImage(
  1870. detector.m_pRawImgBuffer,
  1871. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  1872. detector.m_pImgBuffer,
  1873. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  1874. );
  1875. if (!cropSuccess)
  1876. {
  1877. cout << "[Detector_TiRayDR::handleAedSyncImage] Failed to crop image" << endl;
  1878. return;
  1879. }
  1880. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  1881. // 生成关联的基础文件名
  1882. const std::string baseTimestamp = std::to_string(
  1883. std::chrono::duration_cast<std::chrono::milliseconds>(
  1884. std::chrono::system_clock::now().time_since_epoch()
  1885. ).count()
  1886. );
  1887. std::string processedImagePath = saveProcessedImage(
  1888. detector,
  1889. detector.m_pImgBuffer,
  1890. processedSize,
  1891. baseTimestamp
  1892. );
  1893. if (detector.m_bSaveRaw)
  1894. {
  1895. saveRawImage(
  1896. detector,
  1897. detector.m_pRawImgBuffer,
  1898. rawSize,
  1899. baseTimestamp
  1900. );
  1901. }
  1902. // 应用校准
  1903. // applyCalibration(detector);
  1904. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  1905. //detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_OFF);
  1906. detector.m_bExitRadAcqStatus = false;
  1907. }
  1908. void Detector_TiRayDR::handleSoftwareSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  1909. {
  1910. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  1911. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  1912. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  1913. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  1914. bool cropSuccess = cropImage(
  1915. detector.m_pRawImgBuffer,
  1916. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  1917. detector.m_pImgBuffer,
  1918. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  1919. );
  1920. if (!cropSuccess)
  1921. {
  1922. cout << "[Detector_TiRayDR::handleSoftwareSyncImage] Failed to crop image" << endl;
  1923. return;
  1924. }
  1925. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  1926. // 生成关联的基础文件名
  1927. const std::string baseTimestamp = std::to_string(
  1928. std::chrono::duration_cast<std::chrono::milliseconds>(
  1929. std::chrono::system_clock::now().time_since_epoch()
  1930. ).count()
  1931. );
  1932. std::string processedImagePath = saveProcessedImage(
  1933. detector,
  1934. detector.m_pImgBuffer,
  1935. processedSize,
  1936. baseTimestamp
  1937. );
  1938. if (detector.m_bSaveRaw)
  1939. {
  1940. saveRawImage(
  1941. detector,
  1942. detector.m_pRawImgBuffer,
  1943. rawSize,
  1944. baseTimestamp
  1945. );
  1946. }
  1947. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  1948. // 应用校准
  1949. // applyCalibration(detector);
  1950. //detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_OFF);
  1951. detector.m_bExitRadAcqStatus = false;
  1952. }
  1953. void Detector_TiRayDR::handleAedSyncImage(Detector_TiRayDR& detector, TiRayVariant argv[])
  1954. {
  1955. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_START_ACQ);
  1956. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XRAY_ON);
  1957. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_ON);
  1958. const size_t rawPixelCount = argv[3].DataLen / sizeof(unsigned short);
  1959. detector.m_pRawImgBuffer = reinterpret_cast<unsigned short*>(argv[3].DataValue);
  1960. const size_t rawSize = rawPixelCount * sizeof(unsigned short);
  1961. bool cropSuccess = cropImage(
  1962. detector.m_pRawImgBuffer,
  1963. detector.m_nRawImgWidth, detector.m_nRawImgHeight, // 原始图像宽高
  1964. detector.m_pImgBuffer,
  1965. detector.m_nImageWidth, detector.m_nImageHeight // 目标宽高
  1966. );
  1967. if (!cropSuccess)
  1968. {
  1969. cout << "[Detector_TiRayDR::handleAedSyncImage] Failed to crop image" << endl;
  1970. return;
  1971. }
  1972. const size_t processedSize = detector.m_nImageWidth * detector.m_nImageHeight * sizeof(unsigned short);
  1973. // 生成关联的基础文件名
  1974. const std::string baseTimestamp = std::to_string(
  1975. std::chrono::duration_cast<std::chrono::milliseconds>(
  1976. std::chrono::system_clock::now().time_since_epoch()
  1977. ).count()
  1978. );
  1979. std::string processedImagePath = saveProcessedImage(
  1980. detector,
  1981. detector.m_pImgBuffer,
  1982. processedSize,
  1983. baseTimestamp
  1984. );
  1985. if (detector.m_bSaveRaw)
  1986. {
  1987. saveRawImage(
  1988. detector,
  1989. detector.m_pRawImgBuffer,
  1990. rawSize,
  1991. baseTimestamp
  1992. );
  1993. }
  1994. // applyCalibration(detector);
  1995. detector.InfoFeedback(EVT_DATA_RAW_IMAGE, -1, 0, 0, processedImagePath.c_str());
  1996. detector.m_bAEDWorkFlag = false;
  1997. //usleep(500000);
  1998. //detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_XWINDOW_OFF);
  1999. detector.m_bExitRadAcqStatus = false;
  2000. }
  2001. void Detector_TiRayDR::handleDarkCalibration(Detector_TiRayDR& detector, TiRayVariant argv[])
  2002. {
  2003. const std::string funcTag = "[Detector_TiRayDR::handleDarkCalibration] ";
  2004. static int callCount = 0;
  2005. static std::vector<TiRayVariant> datas;
  2006. // 处理当前传入的图像数据
  2007. auto size = argv[3].DataLen;
  2008. auto data = argv[3].DataValue;
  2009. image_info image;
  2010. image.width = argv[0].IntValue;
  2011. image.height = argv[1].IntValue;
  2012. image.data.resize(size);
  2013. memcpy(image.data.data(), data, size);
  2014. // 将当前图像数据存入集合
  2015. TiRayVariant variant;
  2016. variant.Type = TiRayVariant::TiRayBuffer;
  2017. variant.DataLen = static_cast<int>(image.data.size());
  2018. variant.DataValue = image.data.data();
  2019. datas.push_back(variant);
  2020. // 调用次数递增(当前已处理的图像数量)
  2021. callCount++;
  2022. // 若未收集到6张图,调用拍摄命令准备下一张
  2023. if (callCount < 6) {
  2024. auto err = Execute_Ptr(detector.m_nDetectorID, Cmd_Photo, nullptr, 0);
  2025. if (err != Err_Success) {
  2026. cout << funcTag << "Failed to execute Cmd_Photo for next image. Error code: " << err << endl;
  2027. // 重置状态,避免异常累积
  2028. callCount = 0;
  2029. datas.clear();
  2030. return;
  2031. }
  2032. cout << funcTag << "Prepared for " << callCount + 1 << "th image" << endl;
  2033. }
  2034. // 收集到6张图,执行模板生成和上传
  2035. else {
  2036. image_info template_image;
  2037. template_image.data.resize(datas[0].DataLen);
  2038. template_image.width = image.width;
  2039. template_image.height = image.height;
  2040. // 生成模板并检查结果
  2041. auto err = GenerateTemplate_Ptr(Offset, datas.data(), static_cast<int>(datas.size()),
  2042. template_image.data.data(), static_cast<int>(template_image.data.size()));
  2043. if (err != Err_Success) {
  2044. cout << funcTag << "Failed to generate offset template. Error code: " << err << endl;
  2045. }
  2046. else {
  2047. cout << funcTag << "Offset template generated successfully with 6 images" << endl;
  2048. // 上传模板并检查结果
  2049. err = detector.upload(detector.offset, template_image.data.data(), static_cast<int>(template_image.data.size()));
  2050. if (err != Err_Success) {
  2051. cout << funcTag << "Failed to upload offset template. Error code: " << err << endl;
  2052. }
  2053. else {
  2054. cout << funcTag << "Offset template uploaded successfully" << endl;
  2055. }
  2056. }
  2057. // 重置静态变量,为下一次校准做准备
  2058. callCount = 0;
  2059. datas.clear();
  2060. }
  2061. }
  2062. void Detector_TiRayDR::handleGainCalibration(Detector_TiRayDR& detector, TiRayVariant argv[])
  2063. {
  2064. const std::string funcTag = "[Detector_TiRayDR::handleGainCalibration] ";
  2065. int doseCount = 5; // 剂量数量
  2066. int imagesPerDose = 6; // 每个剂量的图像数量
  2067. auto size = argv[3].DataLen;
  2068. auto data = argv[3].DataValue;
  2069. // 创建图像信息并存储
  2070. image_info image;
  2071. image.width = argv[0].IntValue;
  2072. image.height = argv[1].IntValue;
  2073. image.data.resize(size);
  2074. memcpy(image.data.data(), data, size);
  2075. // 根据模式存储图像
  2076. if (!detector.m_bUseGainV2)
  2077. {
  2078. // Gain模式:直接存储所有30张图像
  2079. detector.m_gainCalibImages.push_back(image);
  2080. cout << funcTag << "Gain mode - Collected " << detector.m_gainCalibImages.size()
  2081. << "/" << doseCount * imagesPerDose << " images" << endl;
  2082. // 收集完30张图像后生成并上传模板
  2083. if (detector.m_gainCalibImages.size() == doseCount * imagesPerDose)
  2084. {
  2085. cout << funcTag << "All 30 gain calibration images collected, generating template..." << endl;
  2086. // 准备数据并生成Gain模板
  2087. std::vector<TiRayVariant> datas;
  2088. for (auto& img : detector.m_gainCalibImages)
  2089. {
  2090. TiRayVariant variant;
  2091. variant.Type = TiRayVariant::TiRayBuffer;
  2092. variant.DataLen = static_cast<int>(img.data.size());
  2093. variant.DataValue = img.data.data();
  2094. datas.push_back(variant);
  2095. }
  2096. image_info template_image;
  2097. template_image.width = detector.m_gainCalibImages[0].width;
  2098. template_image.height = detector.m_gainCalibImages[0].height;
  2099. template_image.data.resize(datas[0].DataLen);
  2100. auto err = GenerateTemplate_Ptr(Gain, datas.data(), static_cast<int>(datas.size()),
  2101. template_image.data.data(), static_cast<int>(template_image.data.size()));
  2102. if (err != Err_Success)
  2103. {
  2104. cout << funcTag << "Failed to generate Gain template. Error code: " << err << endl;
  2105. }
  2106. else
  2107. {
  2108. cout << funcTag << "Gain template generated successfully" << endl;
  2109. // 上传模板
  2110. err = detector.upload(detector.gain, template_image.data.data(),
  2111. static_cast<int>(template_image.data.size()));
  2112. if (err != Err_Success)
  2113. {
  2114. cout << funcTag << "Failed to upload Gain template. Error code: " << err << endl;
  2115. }
  2116. else
  2117. {
  2118. cout << funcTag << "Gain template uploaded successfully" << endl;
  2119. }
  2120. }
  2121. // 清空存储的图像,准备下次校正
  2122. detector.m_gainCalibImages.clear();
  2123. }
  2124. }
  2125. else if (detector.m_bUseGainV2)
  2126. {
  2127. // Gainv2模式:按剂量组存储图像
  2128. detector.m_currentDoseImages.push_back(image);
  2129. cout << funcTag << "Gainv2 mode - Collected " << detector.m_currentDoseImages.size()
  2130. << "/" << imagesPerDose << " images for dose " << detector.m_currentDoseIndex + 1 << endl;
  2131. // 收集完当前剂量的6张图像后生成均值图
  2132. if (detector.m_currentDoseImages.size() == imagesPerDose)
  2133. {
  2134. cout << funcTag << "All " << imagesPerDose << " images for dose " << detector.m_currentDoseIndex + 1
  2135. << " collected, generating mean image..." << endl;
  2136. // 生成当前剂量的均值图
  2137. std::vector<TiRayVariant> datas;
  2138. for (auto& img : detector.m_currentDoseImages)
  2139. {
  2140. TiRayVariant variant;
  2141. variant.Type = TiRayVariant::TiRayBuffer;
  2142. variant.DataLen = static_cast<int>(img.data.size());
  2143. variant.DataValue = img.data.data();
  2144. datas.push_back(variant);
  2145. }
  2146. image_info mean_image;
  2147. mean_image.width = detector.m_currentDoseImages[0].width;
  2148. mean_image.height = detector.m_currentDoseImages[0].height;
  2149. mean_image.data.resize(datas[0].DataLen);
  2150. auto err = GenerateTemplate_Ptr(Mean, datas.data(), static_cast<int>(datas.size()),
  2151. mean_image.data.data(), static_cast<int>(mean_image.data.size()));
  2152. if (err != Err_Success)
  2153. {
  2154. cout << funcTag << "Failed to generate mean image for dose " << detector.m_currentDoseIndex + 1
  2155. << ". Error code: " << err << endl;
  2156. // 清空当前剂量数据,重新收集
  2157. detector.m_currentDoseImages.clear();
  2158. return;
  2159. }
  2160. // 保存均值图并重置当前剂量图像集合
  2161. detector.m_gainV2MeanImages.push_back(mean_image);
  2162. detector.m_currentDoseImages.clear();
  2163. detector.m_currentDoseIndex++;
  2164. cout << funcTag << "Mean image for dose " << detector.m_currentDoseIndex
  2165. << " generated successfully. Total mean images: " << detector.m_gainV2MeanImages.size() << endl;
  2166. // 收集完5个剂量的均值图后生成最终模板
  2167. if (detector.m_gainV2MeanImages.size() == doseCount)
  2168. {
  2169. cout << funcTag << "All " << doseCount << " mean images collected, generating final GainV2 template..." << endl;
  2170. // 生成最终的GainV2模板
  2171. std::vector<TiRayVariant> meanDatas;
  2172. for (auto& meanImg : detector.m_gainV2MeanImages)
  2173. {
  2174. TiRayVariant variant;
  2175. variant.Type = TiRayVariant::TiRayBuffer;
  2176. variant.DataLen = static_cast<int>(meanImg.data.size());
  2177. variant.DataValue = meanImg.data.data();
  2178. meanDatas.push_back(variant);
  2179. }
  2180. image_info final_template;
  2181. final_template.width = detector.m_gainV2MeanImages[0].width;
  2182. final_template.height = detector.m_gainV2MeanImages[0].height;
  2183. final_template.data.resize(meanDatas[0].DataLen);
  2184. auto err = GenerateTemplate_Ptr(GainV2, meanDatas.data(), static_cast<int>(meanDatas.size()),
  2185. final_template.data.data(), static_cast<int>(final_template.data.size()));
  2186. if (err != Err_Success)
  2187. {
  2188. cout << funcTag << "Failed to generate GainV2 template. Error code: " << err << endl;
  2189. }
  2190. else
  2191. {
  2192. cout << funcTag << "GainV2 template generated successfully" << endl;
  2193. // 上传模板
  2194. err = detector.upload(detector.gain, final_template.data.data(),
  2195. static_cast<int>(final_template.data.size()));
  2196. if (err != Err_Success)
  2197. {
  2198. cout << funcTag << "Failed to upload GainV2 template. Error code: " << err << endl;
  2199. }
  2200. else
  2201. {
  2202. cout << funcTag << "GainV2 template uploaded successfully" << endl;
  2203. }
  2204. }
  2205. // 重置所有存储和计数器,准备下次校正
  2206. detector.m_gainV2MeanImages.clear();
  2207. detector.m_currentDoseIndex = 0;
  2208. }
  2209. }
  2210. }
  2211. }
  2212. void Detector_TiRayDR::handleImageReceived(Detector_TiRayDR& detector, TiRayVariant argv[])
  2213. {
  2214. // 处理暗校准模式
  2215. if (CCOS_CALIBRATION_TYPE_DARK == detector.m_eCaliType)
  2216. {
  2217. handleDarkCalibration(detector, argv);
  2218. return;
  2219. }
  2220. else if (CCOS_CALIBRATION_TYPE_XRAY == detector.m_eCaliType)
  2221. {
  2222. handleGainCalibration(detector, argv);
  2223. return;
  2224. }
  2225. // 根据同步模式处理图像
  2226. switch (detector.m_nSyncMode)
  2227. {
  2228. case SYNC_MODE::SYNC_AED:
  2229. handleAedSyncImage(detector, argv);
  2230. break;
  2231. case SYNC_MODE::SYNC_SOFTWARE:
  2232. handleSoftwareSyncImage(detector, argv);
  2233. break;
  2234. case SYNC_MODE::SYNC_HARDWARE:
  2235. handleHardwareSyncImage(detector, argv);
  2236. break;
  2237. }
  2238. }
  2239. void Detector_TiRayDR::on_event_callback(int detectorId, TiRayEvent eventType, TiRayVariant argv[], int argc, void* reservedArg, int reservedArgLen)
  2240. {
  2241. auto& detector = *g_pDetector;
  2242. const std::string funcTag = "[Detector_TiRayDR::on_event_callback] ";
  2243. switch (eventType)
  2244. {
  2245. case TiRayEvent::Evt_DetectorConnect:
  2246. {
  2247. detector.m_nDetectorID = detectorId;
  2248. detector.m_bConnected = true;
  2249. detector.m_pStPanelStatus[detector.m_nCurrentPanelID]->bConnectState = true;
  2250. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_CONNECT);
  2251. cout << funcTag << "Evt_DetectorConnect!!!" << endl;
  2252. FINFO("Evt_DetectorConnect!!");
  2253. break;
  2254. }
  2255. case TiRayEvent::Evt_DetectorDisconnect:
  2256. {
  2257. detector.m_nDetectorID = INT_MAX;
  2258. detector.m_bConnected = false;
  2259. detector.m_pStPanelStatus[detector.m_nCurrentPanelID]->bConnectState = false;
  2260. detector.StatusFeedback(EVT_STATUS_PANEL, PANEL_CLOSE);
  2261. detector.m_hReConnectEvent->SetEvent();
  2262. cout << funcTag << "Evt_DetectorDisconnect!!!" << endl;
  2263. FINFO("Evt_DetectorDisconnect!!");
  2264. break;
  2265. }
  2266. case TiRayEvent::Evt_WriteAttribute:
  2267. {
  2268. FINFO("WriteAttribute Success");
  2269. break;
  2270. }
  2271. case TiRayEvent::Evt_ReadAttribute:
  2272. {
  2273. FINFO("ReadAttribute Success");
  2274. //const TiRayAttribute attrib = (TiRayAttribute)argv[0].IntValue;
  2275. //if (attrib == Attr_BatteryStatus) {
  2276. // auto battery_level = argv[1].IntValue;
  2277. // auto is_recharging = argv[2].IntValue;
  2278. //}
  2279. break;
  2280. }
  2281. case TiRayEvent::Evt_ImageReceived:
  2282. {
  2283. cout << funcTag << "Evt_ImageReceived!!!" << endl;
  2284. FINFO("Evt_ImageReceived!!");
  2285. handleImageReceived(detector, argv);
  2286. break;
  2287. }
  2288. case TiRayEvent::Evt_ExposureStatus:
  2289. {
  2290. FINFO("argv {$}, argc {$}", argv[0].IntValue, argc);
  2291. if (argv[0].IntValue == 0)
  2292. {
  2293. detector.m_bAEDReady = true;
  2294. }
  2295. if (argv[0].IntValue == 1)
  2296. {
  2297. detector.m_bAEDReady = false;
  2298. }
  2299. break;
  2300. }
  2301. case TiRayEvent::Evt_UploadProgress:
  2302. cout << funcTag << "Upload progress: " << argv[0].IntValue << "%" << endl;
  2303. break;
  2304. case TiRayEvent::Evt_UpdateFinish:
  2305. cout << funcTag << "Update completed successfully" << endl;
  2306. detector.StatusFeedback(EVT_STATUS_CALIBRATIOIN, PANEL_EVENT_END_OK);
  2307. break;
  2308. case TiRayEvent::Evt_UploadTimeout:
  2309. // 输出上传超时警告
  2310. cout << funcTag << "Warning: Upload timed detectorData" << endl;
  2311. break;
  2312. default:
  2313. FERROR("not support current event ID:{$}", (int)eventType);
  2314. break;
  2315. }
  2316. }
  2317. void Detector_TiRayDR::ConfFeedback(int nEventID, int nDetectorID, const char* pszMsg, int nParam1, float fParam2, int nPtrParamLen, void* pParam)
  2318. {
  2319. if (-1 == nDetectorID)
  2320. {
  2321. nDetectorID = m_nCurrentPanelID;
  2322. }
  2323. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2324. nEventID, EVT_LEVEL_CONFIGURATION, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2325. }
  2326. void Detector_TiRayDR::InfoFeedback(int nEventID, int nDetectorID, int nParam1, float fParam2, const char* pszMsg, int nPtrParamLen, void* pParam)
  2327. {
  2328. if (-1 == nDetectorID)
  2329. {
  2330. nDetectorID = m_nCurrentPanelID;
  2331. }
  2332. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2333. nEventID, EVT_LEVEL_INFORMATOION, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2334. }
  2335. void Detector_TiRayDR::StatusFeedback(int nEventID, int nParam1, const char* pszMsg, int nDetectorID, float fParam2, int nPtrParamLen, void* pParam)
  2336. {
  2337. if (-1 == nDetectorID)
  2338. {
  2339. nDetectorID = m_nCurrentPanelID;
  2340. }
  2341. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2342. nEventID, EVT_LEVEL_STATUS, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2343. }
  2344. void Detector_TiRayDR::DataFeedback(int nEventID, void* pParam, int nParam1, float fParam2, const char* pszMsg, int nPtrParamLen, int nDetectorID)
  2345. {
  2346. if (-1 == nDetectorID)
  2347. {
  2348. nDetectorID = m_nCurrentPanelID;
  2349. }
  2350. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2351. nEventID, EVT_LEVEL_DATA, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2352. }
  2353. void Detector_TiRayDR::WarnFeedback(int nEventID, const char* pszMsg, int nParam1, float fParam2, int nPtrParamLen, void* pParam, int nDetectorID)
  2354. {
  2355. if (-1 == nDetectorID)
  2356. {
  2357. nDetectorID = m_nCurrentPanelID;
  2358. }
  2359. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2360. nEventID, EVT_LEVEL_WARNING, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2361. }
  2362. void Detector_TiRayDR::ErrorFeedback(int nEventID, const char* pszMsg, int nDetectorID, int nParam1, float fParam2, int nPtrParamLen, void* pParam)
  2363. {
  2364. if (-1 == nDetectorID)
  2365. {
  2366. nDetectorID = m_nCurrentPanelID;
  2367. }
  2368. ((FPDDeviceTiRay*)(*m_pPanelID2DPC)[nDetectorID])->OnFPDCallback(nDetectorID,
  2369. nEventID, EVT_LEVEL_ERROR, pszMsg, nParam1, fParam2, nPtrParamLen, pParam);
  2370. }
  2371. bool Detector_TiRayDR::UpdateCalibMode(CCOS_CALIBRATION_MODE eCalibMode)
  2372. {
  2373. FINFO("--TiRayDR Func-- UpdateCalibMode");
  2374. FINFO("CalibMode:{$}", (int)eCalibMode);
  2375. m_nCalibrationMode = eCalibMode;
  2376. FINFO("UpdateCalibMode Over");
  2377. return true;
  2378. }
  2379. void Detector_TiRayDR::SetNotifyStatusTimePeriod(int nTime)
  2380. {
  2381. FINFO("--Func TiRay-- SetNotifyStatusTimePeriod Start");
  2382. FINFO("NotifyStatusTimePeriod:{$}", nTime);
  2383. m_nNotifyStatusTimePeriod = nTime;
  2384. FINFO("SetNotifyStatusTimePeriod Over");
  2385. }
  2386. void Detector_TiRayDR::SetReconnectTimePeriod(int nTime)
  2387. {
  2388. FINFO("--Func TiRay-- SetReconnectTimePeriod Start");
  2389. FINFO("ReconnectTimePeriod:{$}", nTime);
  2390. m_nReconnectTimePeriod = nTime;
  2391. FINFO("SetReconnectTimePeriod Over");
  2392. }
  2393. int Detector_TiRayDR::TiRay_GetSdkVersion()
  2394. {
  2395. return GetSdkVersion_Ptr();
  2396. }
  2397. TiRayError Detector_TiRayDR::TiRay_Execute(int detectorId, int commandId, TiRayVariant argv[], int argc)
  2398. {
  2399. return Execute_Ptr(detectorId, commandId, argv, argc);
  2400. }
  2401. TiRayError Detector_TiRayDR::TiRay_ApplyPreset(int detectorId, TiRayVariant argv[], int argc, ResultCallback fn)
  2402. {
  2403. return ApplyPreset_Ptr(detectorId, argv, argc, fn);
  2404. }
  2405. TiRayError Detector_TiRayDR::TiRay_GenerateTemplate(TemplateType type, TiRayVariant images[], int count, void* templateBuffer, int bufferSize)
  2406. {
  2407. return GenerateTemplate_Ptr(type, images, count, templateBuffer, bufferSize);
  2408. }
  2409. TiRayError Detector_TiRayDR::TiRay_Scan(ResultCallback fn, const char* interfaceIp, int scanDuration)
  2410. {
  2411. return Scan_Ptr(fn, interfaceIp, scanDuration);
  2412. }
  2413. TiRayError Detector_TiRayDR::TiRay_SetIp(const char* detectorSN, const char* upperIp, const char* lowerIp, const char* interfaceIp)
  2414. {
  2415. return SetIp_Ptr(detectorSN, upperIp, lowerIp, interfaceIp);
  2416. }
  2417. TiRayError Detector_TiRayDR::TiRay_Startup(TiRayModel model, EventCallback fn, const StartupOption* option)
  2418. {
  2419. return Startup_Ptr(model, fn, option);
  2420. }
  2421. void Detector_TiRayDR::TiRay_Stop()
  2422. {
  2423. Stop_Ptr();
  2424. }
  2425. /***
  2426. ** 说明:重连探测器线程
  2427. ***/
  2428. void* Detector_TiRayDR::onReconnectThread(PVOID pvoid)
  2429. {
  2430. FINFO("Reconnect detector thread start");
  2431. Detector_TiRayDR* pThis = static_cast<Detector_TiRayDR*>(pvoid);
  2432. while (!pThis->m_bConnected)
  2433. {
  2434. pThis->OpenDetector();
  2435. usleep(pThis->m_nReconnectTimePeriod*1000);
  2436. }
  2437. pThis->m_bReconnectThreadRunning = false;
  2438. FINFO("Leave reconnect detector thread");
  2439. return 0;
  2440. }
  2441. TiRayError Detector_TiRayDR::upload(upload_type type, char* data, int size)
  2442. {
  2443. TiRayVariant param[1]{};
  2444. param[0].Type = TiRayVariant::TiRayBuffer;
  2445. param[0].DataValue = data;
  2446. param[0].DataLen = size;
  2447. if (type == offset) {
  2448. return Execute_Ptr(m_nDetectorID, Cmd_UploadOffsetTemplate, param, 1);
  2449. }
  2450. if (type == gain) {
  2451. return Execute_Ptr(m_nDetectorID, Cmd_UploadGainTemplate, param, 1);
  2452. }
  2453. if (type == firmware) {
  2454. return Execute_Ptr(m_nDetectorID, Cmd_UpdateFirmware, param, 1);
  2455. }
  2456. return Err_InvalidParam;
  2457. }