Httpserver.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #pragma execution_character_set("utf-8")
  2. #include "Httpserver.h"
  3. //#include "mongoose.c"
  4. #include <QCoreApplication>
  5. #include <QtCore/qthread.h>
  6. #include <iostream>
  7. #include <thread>
  8. #include <nlohmann/json.hpp>
  9. #include "JdydAlgorithnm.h"
  10. #include "YundaTecAlgorithnm.h"
  11. #include <QtCore/QTextStream>
  12. #include <QtCore/qfile.h>
  13. #include <QFileInfo>
  14. //#include "WriteLog.h"
  15. #include "YunDaISASImageRecognitionService.h"
  16. using json = nlohmann::json;
  17. //static std::map<std::string, AlgorithmModel*> _plugins;
  18. std::string HttpServer::dump_headers(const Headers& headers) {
  19. std::string s;
  20. char buf[BUFSIZ];
  21. for (auto it = headers.begin(); it != headers.end(); ++it) {
  22. const auto& x = *it;
  23. snprintf(buf, sizeof(buf), "%s: %s\n", x.first.c_str(), x.second.c_str());
  24. s += buf;
  25. }
  26. return s;
  27. }
  28. std::string HttpServer::log(const Request& req, const Response& res) {
  29. std::string s;
  30. char buf[BUFSIZ];
  31. s += "================================\n";
  32. snprintf(buf, sizeof(buf), "%s %s %s", req.method.c_str(),
  33. req.version.c_str(), req.path.c_str());
  34. s += buf;
  35. std::string query;
  36. for (auto it = req.params.begin(); it != req.params.end(); ++it) {
  37. const auto& x = *it;
  38. snprintf(buf, sizeof(buf), "%c%s=%s",
  39. (it == req.params.begin()) ? '?' : '&', x.first.c_str(),
  40. x.second.c_str());
  41. query += buf;
  42. }
  43. snprintf(buf, sizeof(buf), "%s\n", query.c_str());
  44. s += buf;
  45. s += dump_headers(req.headers);
  46. s += "--------------------------------\n";
  47. snprintf(buf, sizeof(buf), "%d %s\n", res.status, res.version.c_str());
  48. s += buf;
  49. s += dump_headers(res.headers);
  50. s += "\n";
  51. if (!res.body.empty()) { s += res.body; }
  52. s += "\n";
  53. return s;
  54. }
  55. static std::mutex mtx; // 保护counter
  56. static int errorCount = 0;
  57. int HttpServer::RunHttpServer()
  58. {
  59. std::thread th([]{
  60. Server svr;
  61. if(!svr.is_valid()) {
  62. printf("server has an error...\n");
  63. return -1;
  64. }
  65. svr.Get("/", [=](const Request& /*req*/, Response& res) {
  66. res.set_redirect("/hi");
  67. });
  68. svr.Get("/hi", [](const Request& /*req*/, Response& res) {
  69. res.set_content( "Imgage Recognize Serive Running!\n", "text/plain");
  70. });
  71. svr.Post("/api/recognize", [](const Request& req, Response& res)
  72. {
  73. mtx.lock();
  74. try
  75. {
  76. json resultJson = {};
  77. json ex1 = json::parse(req.body);
  78. bool isNewAlgorithnm = false;
  79. if (ex1["isNewAlgorithnm"].is_boolean())
  80. {
  81. isNewAlgorithnm = ex1["isNewAlgorithnm"].get<bool>();
  82. }
  83. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--isNewAlgorithnm:%1").arg(QString::number(isNewAlgorithnm)));
  84. string pluginName = "";
  85. if (ex1["pluginName"].is_string())
  86. {
  87. pluginName = ex1["pluginName"].get<string>();
  88. }
  89. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--pluginName:%1").arg(QString::fromLocal8Bit(pluginName.c_str())));
  90. string filePath = "";
  91. if (ex1["filePath"].is_string())
  92. {
  93. filePath = UTF8string(ex1["filePath"].get<string>());
  94. }
  95. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--filePath:%1").arg(QString::fromLocal8Bit(filePath.c_str())));
  96. string modelPath = "";
  97. if (ex1["modelPath"].is_string())
  98. {
  99. modelPath = ex1["modelPath"].get<string>();
  100. }
  101. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--modelPath:%1").arg(QString::fromLocal8Bit(modelPath.c_str())));
  102. vector<int> roiVec;
  103. if (ex1["roi"].is_array())
  104. {
  105. roiVec = ex1["roi"].get<vector<int>>();
  106. }
  107. if (8 == roiVec.size())
  108. {
  109. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--roi %1,%2,%3,%4,%5,%6,%7,%8").arg(QString::number(roiVec[0]) , QString::number(roiVec[1]), QString::number(roiVec[2]), QString::number(roiVec[3]), QString::number(roiVec[4]), QString::number(roiVec[5]), QString::number(roiVec[6]), QString::number(roiVec[7])));
  110. }
  111. else
  112. {
  113. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg: roi error"));
  114. }
  115. int* roiArr = new int[sizeof(roiVec)];
  116. if (!roiVec.empty())
  117. {
  118. memcpy(roiArr, &roiVec[0], roiVec.size() * sizeof(int));
  119. }
  120. string pcArg = "";
  121. if (ex1["pcArg"].is_string())
  122. {
  123. pcArg = ex1["pcArg"].get<string>();
  124. }
  125. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("recvMsg--pcArg:%1").arg(QString::fromLocal8Bit(pcArg.c_str())));
  126. if (!isNewAlgorithnm)
  127. {
  128. if (pluginName.size() > 0)
  129. {
  130. ifstream qfile(filePath);
  131. if (qfile.good())
  132. {
  133. resultJson = YundaTecAlgorithnm::CallAlgorithnm(pluginName, filePath, modelPath, roiArr, pcArg);
  134. }
  135. else
  136. {
  137. resultJson = { {"flag", -1}, {"result" , "识别文件未找到"} };
  138. }
  139. qfile.close();
  140. }
  141. else
  142. {
  143. resultJson = { {"flag", -1}, {"result" , "算法路径为空"} };
  144. }
  145. }
  146. else
  147. {
  148. if (8 == roiVec.size())
  149. {
  150. ifstream qfile(filePath);
  151. if (qfile.good())
  152. {
  153. resultJson = JdydAlgorithnm::CallAlgorithnm(pluginName, filePath, modelPath, roiArr, pcArg);
  154. }
  155. else
  156. {
  157. resultJson = { {"flag", -1}, {"result" , "识别文件未找到"} };
  158. }
  159. qfile.close();
  160. }
  161. }
  162. free(roiArr);
  163. std::string serialized_returnstring = resultJson.dump();
  164. //std::string serialized_requeststring = req.dump();
  165. YunDaISASImageRecognitionService::ConsoleLog(QStringLiteral("returnMsg:%1").arg(QString::fromLocal8Bit(serialized_returnstring.c_str())));
  166. res.set_content(serialized_returnstring, "application/json");
  167. }
  168. catch (const std::exception& ex)
  169. {
  170. YunDaISASImageRecognitionService::ConsoleLog(ex.what());
  171. /* errorCount++;
  172. if (errorCount>20)
  173. {
  174. exit(0);
  175. }*/
  176. }
  177. mtx.unlock();
  178. //return 0;
  179. });
  180. //svr.Get("/stop",
  181. // [&](const Request& /*req*/, Response& /*res*/) { svr.stop(); });
  182. svr.set_error_handler([](const Request& /*req*/, Response& res) {
  183. const char* fmt = "<p>Error Status: <span style='color:red;'>%d</span></p>";
  184. char buf[BUFSIZ];
  185. snprintf(buf, sizeof(buf), fmt, res.status);
  186. res.set_content(buf, "text/html");
  187. });
  188. svr.set_logger([](const Request& req, const Response& res) {
  189. printf("%s", log(req, res).c_str());
  190. });
  191. svr.listen("0.0.0.0", 35689);
  192. return 0;
  193. });
  194. th.detach();
  195. return 0;
  196. }
  197. //void HttpServer::SaveLog(QString msg) {
  198. // //WriteLog::SaveLog(msg);
  199. //}
  200. string HttpServer::stringUTF8(const string& str)
  201. {
  202. int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
  203. wchar_t* pwBuf = new wchar_t[nwLen + 1];
  204. ZeroMemory(pwBuf, nwLen * 2 + 2);
  205. ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);
  206. int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
  207. char* pBuf = new char[nLen + 1];
  208. ZeroMemory(pBuf, nLen + 1);
  209. ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
  210. std::string retStr(pBuf);
  211. delete[]pwBuf;
  212. delete[]pBuf;
  213. pwBuf = NULL;
  214. pBuf = NULL;
  215. return retStr;
  216. }
  217. string HttpServer::UTF8string(string strTemp)
  218. {
  219. char buf[1024 * 60];
  220. snprintf(buf, sizeof(buf), u8"%s", strTemp.c_str());
  221. TCHAR wscBuffer[1024 * 10] = { 0 };
  222. MultiByteToWideChar(CP_UTF8, 0, buf, (int)strlen(buf) + 1, wscBuffer, sizeof(wscBuffer) / sizeof(wchar_t));
  223. memset(buf, 0, 1024 * 9);
  224. WideCharToMultiByte(CP_ACP, 0, wscBuffer, -1, buf, 1024 * 9, NULL, NULL);
  225. return buf;
  226. }
  227. void HttpServer::fn(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
  228. }