Detector_TiRayDR.cpp 93 KB

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