Detector_TiRayDR.cpp 94 KB

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