Detector_TiRayDR.cpp 91 KB

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