reader_service.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. #include "reader_service.h"
  2. #include "../utils.h"
  3. #include <iostream>
  4. #include <thread>
  5. #include <chrono>
  6. #include <mutex>
  7. #include <sstream>
  8. void PrintLogMessage(const std::string &message)
  9. {
  10. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent())
  11. {
  12. CreateAndAttachConsole();
  13. std::cout << message << std::endl;
  14. }
  15. }
  16. ReaderService *ReaderService::GetInstance()
  17. {
  18. static ReaderService instance;
  19. return &instance;
  20. }
  21. std::vector<std::string> ReaderService::ScanUsb()
  22. {
  23. PrintLogMessage("Scanning USB...");
  24. std::vector<std::string> usb_devices;
  25. int iHidNum = SWHid_GetUsbCount();
  26. for (int i = 0; i < iHidNum; i++)
  27. {
  28. char arrHidName[256];
  29. SWHid_GetUsbInfo(static_cast<unsigned short>(i), arrHidName);
  30. usb_devices.push_back(arrHidName);
  31. }
  32. return usb_devices;
  33. }
  34. bool ReaderService::Connect(int deviceIndex)
  35. {
  36. unsigned char arrBuffer[256] = {0};
  37. // Close previous connection (if exists)
  38. if (connected_)
  39. {
  40. SWHid_SetCallback(NULL);
  41. SWHid_CloseDevice();
  42. }
  43. if (SWHid_OpenDevice(static_cast<unsigned short>(deviceIndex)) == FALSE)
  44. {
  45. PrintLogMessage("Failed to connect to device!");
  46. return false;
  47. }
  48. // Get device information
  49. if (SWHid_GetDeviceSystemInfo(0xFF, arrBuffer) == false) // failed
  50. {
  51. Sleep(10);
  52. if (SWHid_GetDeviceSystemInfo(0xFF, arrBuffer) == false) // failed
  53. {
  54. SWHid_CloseDevice();
  55. PrintLogMessage("Failed to get device info!");
  56. return false;
  57. }
  58. }
  59. connected_ = true;
  60. // Set callback function
  61. // SWHid_SetCallback(ReaderService::DeviceCallback);
  62. // Extract device info
  63. int softVer = static_cast<int>(arrBuffer[0]);
  64. int hardVer = static_cast<int>(arrBuffer[1]);
  65. std::string softVersion = std::to_string(softVer >> 4) + "." + std::to_string(softVer & 0x0F);
  66. std::string hardVersion = std::to_string(hardVer >> 4) + "." + std::to_string(hardVer & 0x0F);
  67. // Extract device SN from buffer[2] to buffer[9] (8 bytes)
  68. std::string deviceSN = "";
  69. for (int i = 2; i < 10; i++)
  70. {
  71. char hex[3];
  72. sprintf_s(hex, sizeof(hex), "%.2X", arrBuffer[i]);
  73. deviceSN += hex;
  74. }
  75. std::string log_message = "Connected to device successfully! SN: " + deviceSN +
  76. ", SoftVer: " + softVersion +
  77. ", HardVer: " + hardVersion;
  78. PrintLogMessage(log_message);
  79. return true;
  80. }
  81. void ReaderService::Disconnect()
  82. {
  83. if (connected_)
  84. {
  85. StopRead(); // Stop reading
  86. SWHid_SetCallback(NULL);
  87. SWHid_CloseDevice();
  88. connected_ = false;
  89. PrintLogMessage("Disconnected from device.");
  90. }
  91. }
  92. bool ReaderService::StartRead()
  93. {
  94. if (!connected_)
  95. {
  96. PrintLogMessage("Not connected to any device!");
  97. return false;
  98. }
  99. // SWHid_SetDeviceOneParam(0xFF, 0x02, 0x01); // Set Workmode as Activemode
  100. // Set working mode to answer mode
  101. if (SWHid_SetDeviceOneParam(0xFF, 0x02, 0x00) == false) // Set Workmode as Answermode
  102. {
  103. PrintLogMessage("Failed to set device to answer mode!");
  104. return false;
  105. }
  106. reading_ = true;
  107. timer_running_ = true;
  108. tags_.clear();
  109. // Start timer thread to periodically call AnswerMode
  110. timer_thread_ = std::make_unique<std::thread>(&ReaderService::RunTimer, this);
  111. // Start a thread to periodically send tag list to UI
  112. callback_thread_ = std::make_unique<std::thread>([this]()
  113. {
  114. while (timer_running_) {
  115. SendTagList();
  116. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  117. } });
  118. // // Start a separate thread to automatically stop reading after 3 seconds
  119. // auto stop_thread = std::make_unique<std::thread>([this]() {
  120. // std::this_thread::sleep_for(std::chrono::seconds(3));
  121. // if (reading_) {
  122. // StopRead();
  123. // PrintLogMessage("Automatically stopped reading after 3 seconds.");
  124. // }
  125. // });
  126. // // Detach the thread to run independently and clean up resources
  127. // stop_thread->detach();
  128. PrintLogMessage("Started reading in answer mode. Will auto-stop after 3 seconds.");
  129. return true;
  130. }
  131. void ReaderService::StopRead()
  132. {
  133. if (reading_)
  134. {
  135. // Stop the timer thread
  136. if (timer_running_)
  137. {
  138. timer_running_ = false;
  139. if (timer_thread_ && timer_thread_->joinable())
  140. {
  141. timer_thread_->join();
  142. }
  143. if (callback_thread_ && callback_thread_->joinable())
  144. {
  145. callback_thread_->join();
  146. }
  147. }
  148. reading_ = false;
  149. PrintLogMessage("Stopped reading.");
  150. }
  151. }
  152. void ReaderService::RunTimer()
  153. {
  154. while (timer_running_)
  155. {
  156. AnswerMode();
  157. std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep for 100ms, similar to the demo
  158. }
  159. }
  160. std::string ReaderService::GetDeviceInfo()
  161. {
  162. if (!connected_)
  163. {
  164. return "";
  165. }
  166. unsigned char arrBuffer[256] = {0};
  167. if (SWHid_GetDeviceSystemInfo(0xFF, arrBuffer) == false)
  168. {
  169. Sleep(10);
  170. if (SWHid_GetDeviceSystemInfo(0xFF, arrBuffer) == false)
  171. {
  172. return "";
  173. }
  174. }
  175. // Extract device info
  176. int softVer = static_cast<int>(arrBuffer[0]);
  177. int hardVer = static_cast<int>(arrBuffer[1]);
  178. std::string softVersion = std::to_string(softVer >> 4) + "." + std::to_string(softVer & 0x0F);
  179. std::string hardVersion = std::to_string(hardVer >> 4) + "." + std::to_string(hardVer & 0x0F);
  180. // Extract device SN from buffer[2] to buffer[9] (8 bytes)
  181. std::string deviceSN = "";
  182. for (int i = 2; i < 10; i++)
  183. {
  184. char hex[3];
  185. sprintf_s(hex, sizeof(hex), "%.2X", arrBuffer[i]);
  186. deviceSN += hex;
  187. }
  188. // Create a formatted string with all device info
  189. std::string deviceInfo = "SN:" + deviceSN +
  190. ",SoftVer:" + softVersion +
  191. ",HardVer:" + hardVersion;
  192. std::string log_message = "Device Info - " + deviceInfo;
  193. PrintLogMessage(log_message);
  194. return deviceInfo;
  195. }
  196. // 新增功率查询功能
  197. bool ReaderService::GetPower(unsigned char &power)
  198. {
  199. if (!connected_)
  200. {
  201. PrintLogMessage("Not connected to any device!");
  202. return false;
  203. }
  204. unsigned char bValue = 0;
  205. unsigned char bParamAddr = 0x05; // RFPower parameter address
  206. if (SWHid_ReadDeviceOneParam(0xFF, bParamAddr, &bValue) == false)
  207. {
  208. PrintLogMessage("Failed to read power!");
  209. return false;
  210. }
  211. power = bValue;
  212. std::string log_message = "Power read successfully: " + std::to_string(power);
  213. PrintLogMessage(log_message);
  214. return true;
  215. }
  216. // 新增功率设置功能
  217. bool ReaderService::SetPower(unsigned char power)
  218. {
  219. if (!connected_)
  220. {
  221. PrintLogMessage("Not connected to any device!");
  222. return false;
  223. }
  224. // Check if power is within valid range (based on demo: 5-30)
  225. if (power < 5 || power > 30)
  226. {
  227. std::string log_message = "Invalid power value: " + std::to_string(power) + " (must be between 5-30)";
  228. PrintLogMessage(log_message);
  229. return false;
  230. }
  231. unsigned char bParamAddr = 0x05; // RFPower parameter address
  232. if (SWHid_SetDeviceOneParam(0xFF, bParamAddr, power) == false)
  233. {
  234. PrintLogMessage("Failed to set power!");
  235. return false;
  236. }
  237. std::string log_message = "Power set successfully to: " + std::to_string(power);
  238. PrintLogMessage(log_message);
  239. return true;
  240. }
  241. void ReaderService::DeviceCallback(int msg, int param1, unsigned char *param2, int param3, unsigned char *param4)
  242. {
  243. ReaderService *instance = ReaderService::GetInstance();
  244. if (msg == 2) // Data
  245. {
  246. PrintLogMessage("Data received.");
  247. unsigned short iTagLength = 0;
  248. unsigned short iTagNumber = 0;
  249. iTagLength = static_cast<unsigned short>(param3);
  250. iTagNumber = static_cast<unsigned short>(param1);
  251. unsigned char *pBuffer = NULL;
  252. pBuffer = (unsigned char *)param2;
  253. if (iTagNumber == 0)
  254. return;
  255. int iIndex = 0;
  256. int iLength = 0;
  257. unsigned char *pID;
  258. unsigned char bPackLength = 0;
  259. int iIDLen = 0;
  260. for (iIndex = 0; iIndex < iTagNumber; iIndex++)
  261. {
  262. bPackLength = pBuffer[iLength];
  263. pID = (unsigned char *)&pBuffer[1 + iLength];
  264. std::string str2 = "";
  265. char buffer[256];
  266. sprintf_s(buffer, sizeof(buffer), "Type:%.2X ", pID[0]);
  267. str2 += buffer;
  268. if ((pID[0] & 0x80) == 0x80) // with TimeStamp
  269. {
  270. iIDLen = bPackLength - 7;
  271. }
  272. else
  273. iIDLen = bPackLength - 1;
  274. sprintf_s(buffer, sizeof(buffer), "Ant:%.2X Tag:", pID[1]);
  275. str2 += buffer;
  276. for (int i = 2; i < iIDLen; i++)
  277. {
  278. sprintf_s(buffer, sizeof(buffer), "%.2X ", pID[i]);
  279. str2 += buffer;
  280. }
  281. sprintf_s(buffer, sizeof(buffer), "RSSI:%.2X", pID[iIDLen]);
  282. str2 += buffer;
  283. // Notify UI of new data
  284. if (instance->data_callback_)
  285. {
  286. instance->data_callback_(str2);
  287. }
  288. iLength = iLength + bPackLength + 1;
  289. }
  290. }
  291. else if (msg == 1) // Device Out
  292. {
  293. PrintLogMessage("Device removed.");
  294. if (instance->data_callback_)
  295. {
  296. instance->data_callback_("Device Out");
  297. }
  298. }
  299. else if (msg == 0) // Device Insert
  300. {
  301. PrintLogMessage("Device inserted.");
  302. if (instance->data_callback_)
  303. {
  304. instance->data_callback_("Device Insert");
  305. }
  306. }
  307. }
  308. void ReaderService::AnswerMode()
  309. {
  310. unsigned char arrBuffer[2048] = {0};
  311. unsigned short iTagLength = 0;
  312. unsigned short iTagNumber = 0;
  313. if (SWHid_InventoryG2(0xFF, arrBuffer, &iTagLength, &iTagNumber) == false)
  314. {
  315. PrintLogMessage("Failed to inventory!");
  316. return;
  317. }
  318. if (iTagNumber == 0)
  319. {
  320. // PrintLogMessage("No data!");
  321. return;
  322. }
  323. ReaderService *instance = ReaderService::GetInstance();
  324. int iIndex = 0;
  325. int iLength = 0;
  326. unsigned char *pID;
  327. unsigned char bPackLength = 0;
  328. int iIDLen = 0;
  329. for (iIndex = 0; iIndex < iTagNumber; iIndex++)
  330. {
  331. bPackLength = arrBuffer[iLength];
  332. pID = (unsigned char *)&arrBuffer[1 + iLength];
  333. std::string str2 = "", tag = "";
  334. char buffer[256];
  335. sprintf_s(buffer, sizeof(buffer), "Type:%.2X ", pID[0]);
  336. str2 += buffer;
  337. if ((pID[0] & 0x80) == 0x80) // with TimeStamp
  338. {
  339. iIDLen = bPackLength - 7;
  340. }
  341. else
  342. iIDLen = bPackLength - 1;
  343. sprintf_s(buffer, sizeof(buffer), "Ant:%.2X Tag:", pID[1]);
  344. str2 += buffer;
  345. for (int i = 2; i < iIDLen; i++)
  346. {
  347. sprintf_s(buffer, sizeof(buffer), "%.2X", pID[i]);
  348. str2 += buffer;
  349. str2 += " ";
  350. tag += buffer;
  351. }
  352. sprintf_s(buffer, sizeof(buffer), "RSSI:%.2X", pID[iIDLen]);
  353. str2 += buffer;
  354. PrintLogMessage(str2);
  355. // Store the tag without spaces
  356. if (!tag.empty())
  357. {
  358. std::lock_guard<std::mutex> lock(instance->tags_mutex_);
  359. instance->tags_.insert(tag);
  360. }
  361. iLength = iLength + bPackLength + 1;
  362. }
  363. }
  364. void ReaderService::SendTagList()
  365. {
  366. if (data_callback_ && !tags_.empty())
  367. {
  368. // Convert the set of tags to a JSON string
  369. std::string tag_list_json = "[";
  370. bool first = true;
  371. for (const auto &tag : tags_)
  372. {
  373. if (!first)
  374. {
  375. tag_list_json += ",";
  376. }
  377. tag_list_json += "\"" + tag + "\"";
  378. first = false;
  379. }
  380. tag_list_json += "]";
  381. data_callback_(tag_list_json);
  382. }
  383. }
  384. ReaderService::~ReaderService()
  385. {
  386. // Disconnect during destruction
  387. Disconnect();
  388. }