Detector_TiRayDR.cpp 90 KB

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