CMqttClientWorker.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. #include "pch.h"
  2. #include "CMqttClientWorker.h"
  3. #include <openssl/hmac.h>
  4. #include <openssl/bio.h>
  5. #include "mmsystem.h"
  6. #include "../worker/CVoiceWorker.h"
  7. #include "../worker/CCommonWorker.h"
  8. #include "../print/CPosPrinter.h"
  9. #include "../tool/CAppEnv.h"
  10. CMqttClientWorker::CMqttClientWorker()
  11. {
  12. }
  13. CMqttClientWorker::~CMqttClientWorker()
  14. {
  15. m_is_closing = true;
  16. m_is_running = false;
  17. m_stopCv.notify_all();
  18. m_async_client.reset();
  19. }
  20. void CMqttClientWorker::Start()
  21. {
  22. m_is_closing = false;
  23. m_is_running = true;
  24. //处理Mqtt消息接收
  25. std::thread(&CMqttClientWorker::Run, this).detach();
  26. CAppEnv::GetInstance()->AddWorkerNum();
  27. }
  28. void CMqttClientWorker::Stop()
  29. {
  30. m_is_closing = true;
  31. m_is_running = false;
  32. m_stopCv.notify_all();
  33. }
  34. void CMqttClientWorker::Run()
  35. {
  36. m_client_id = "GID_ZHIPUZI_WINDOWS_POS@@@" + CSetting::GetInstance()->getUsername();
  37. m_async_client = std::make_shared<mqtt::async_client>(m_server_address, m_client_id);
  38. // A subscriber often wants the server to remember its messages when its
  39. // disconnected. In that case, it needs a unique ClientID and a
  40. // non-clean session.
  41. m_connOpts.set_clean_session(false);
  42. //计算用户名和密码
  43. this->CalUserInfo();
  44. m_connOpts.set_user_name(m_UserName.c_str());
  45. m_connOpts.set_password(m_Password.c_str());
  46. // Install the callback(s) before connecting.
  47. m_async_client->set_callback(*this);
  48. // Start the connection.
  49. // When completed, the callback will subscribe to topic.
  50. try
  51. {
  52. LOG_INFO("Connecting to the MQTT server...");
  53. m_async_client->connect(m_connOpts, nullptr, *this);
  54. }
  55. catch (const mqtt::exception & exc)
  56. {
  57. std::string info = "ERROR: Unable to connect to MQTT server:" + m_server_address + exc.get_message();
  58. LOG_INFO(info.c_str());
  59. return;
  60. }
  61. while (m_is_running && !m_is_closing)
  62. {
  63. std::unique_lock<std::mutex> lock(m_stopMutex);
  64. m_stopCv.wait_for(lock, std::chrono::milliseconds(100), [this]()
  65. {
  66. return !m_is_running || m_is_closing;
  67. });
  68. }
  69. CLewaimaiLog::OutputDebugMessage("准备退出");
  70. //准备退出,禁止回调里继续重连/处理
  71. m_is_closing = true;
  72. m_stopCv.notify_all();
  73. try
  74. {
  75. CLewaimaiLog::OutputDebugMessage("Disconnecting from the MQTT server...");
  76. auto client = m_async_client;
  77. if (client && client->is_connected())
  78. {
  79. auto tok = client->disconnect();
  80. if (!tok->wait_for(std::chrono::milliseconds(200)))
  81. {
  82. CLewaimaiLog::OutputDebugMessage("MQTT disconnect timeout, wait for pending callbacks to finish.");
  83. }
  84. else
  85. {
  86. CLewaimaiLog::OutputDebugMessage("MQTT disconnected.");
  87. }
  88. }
  89. else
  90. {
  91. CLewaimaiLog::OutputDebugMessage("MQTT client is already disconnected.");
  92. }
  93. }
  94. catch (const mqtt::exception& exc)
  95. {
  96. // is_connected() 与 disconnect() 之间连接仍可能被远端断开。
  97. if (exc.get_return_code() == MQTTASYNC_DISCONNECTED)
  98. {
  99. CLewaimaiLog::OutputDebugMessage("MQTT client was already disconnected.");
  100. }
  101. else
  102. {
  103. const std::string msg =
  104. "MQTT disconnect error [" +
  105. std::to_string(exc.get_return_code()) +
  106. "]: " + exc.get_message();
  107. CLewaimaiLog::OutputDebugMessage(msg.c_str());
  108. }
  109. }
  110. CLewaimaiLog::OutputDebugMessage("MQTT client cleanup complete.");
  111. //不要 delete,改成释放智能指针
  112. m_async_client.reset();
  113. CLewaimaiLog::OutputDebugMessage("MQTT client worker thread exiting.");
  114. CAppEnv::GetInstance()->DelWorkerNum(L"CMqttClientWorker::Run");
  115. return;
  116. }
  117. void CMqttClientWorker::reconnect()
  118. {
  119. if (m_is_closing)
  120. return;
  121. auto client = m_async_client;
  122. if (!client)
  123. return;
  124. //暂停10秒后重连
  125. {
  126. std::unique_lock<std::mutex> lock(m_stopMutex);
  127. if (m_stopCv.wait_for(lock, std::chrono::milliseconds(10000), [this]()
  128. {
  129. return m_is_closing.load();
  130. }))
  131. {
  132. return;
  133. }
  134. }
  135. if (m_is_closing)
  136. return;
  137. try
  138. {
  139. m_async_client->connect(m_connOpts, nullptr, *this);
  140. }
  141. catch (const mqtt::exception & exc)
  142. {
  143. //重连异常了
  144. std::string err = "Error: ";
  145. err += exc.what();
  146. LOG_INFO(err.c_str());
  147. }
  148. }
  149. // Re-connection failure
  150. void CMqttClientWorker::on_failure(const mqtt::token & tok)
  151. {
  152. if (m_is_closing)
  153. return;
  154. if (m_is_mqtt_connected == false)
  155. {
  156. //连接失败了
  157. LOG_INFO("Connection attempt failed");
  158. if (++nretry_ > N_RETRY_ATTEMPTS)
  159. {
  160. //重连次数超过了最大重连试错的次数,暂时不做任何处理,还是继续重连
  161. }
  162. reconnect();
  163. }
  164. else
  165. {
  166. //已经连接,那就是订阅失败了
  167. std::string info = "Subscription failure";
  168. if (tok.get_message_id() != 0)
  169. {
  170. info += " for token: [" + std::to_string(tok.get_message_id()) + "]";
  171. }
  172. LOG_INFO(info.c_str());
  173. }
  174. }
  175. void CMqttClientWorker::on_success(const mqtt::token & tok)
  176. {
  177. if (m_is_closing)
  178. return;
  179. if (m_is_mqtt_connected == false)
  180. {
  181. //连接成功了,再connected里面处理
  182. }
  183. else
  184. {
  185. //订阅成功了
  186. std::string info = "Subscription success";
  187. if (tok.get_message_id() != 0)
  188. {
  189. info += " for token: [" + std::to_string(tok.get_message_id()) + "]";
  190. }
  191. auto top = tok.get_topics();
  192. if (top && !top->empty())
  193. {
  194. info += ",token topic: '" + (*top)[0] + "', ...";
  195. }
  196. //LOG_INFO(info.c_str());
  197. }
  198. }
  199. void CMqttClientWorker::connected(const std::string & cause)
  200. {
  201. if (m_is_closing)
  202. return;
  203. m_is_mqtt_connected = true;
  204. std::string info = "Connection success, nSubscribing to topic " + m_topic + " for client " + m_client_id + " using QoS" + std::to_string(MQTT_QOS);
  205. //LOG_INFO(info.c_str());
  206. //不管是第一次连接,还是重连,都订阅一次
  207. auto client = m_async_client;
  208. if (client)
  209. {
  210. client->subscribe(m_topic, MQTT_QOS, nullptr, *this);
  211. }
  212. }
  213. void CMqttClientWorker::connection_lost(const std::string & cause)
  214. {
  215. if (m_is_closing)
  216. return;
  217. m_is_mqtt_connected = false;
  218. std::string info = "Connection lost";
  219. if (!cause.empty())
  220. {
  221. info += ", cause: " + cause;
  222. }
  223. info += ",Reconnecting...";
  224. LOG_INFO(info.c_str());
  225. nretry_ = 0;
  226. reconnect();
  227. }
  228. // Callback for when a message arrives.
  229. void CMqttClientWorker::message_arrived(mqtt::const_message_ptr msg)
  230. {
  231. if (m_is_closing)
  232. return;
  233. std::string info = "Message arrived, ttopic: '" + msg->get_topic() + "', payload: '" + msg->to_string();
  234. LOG_INFO(info.c_str());
  235. //要的就是这个,收到消息了
  236. std::string content = msg->to_string();
  237. //对接收到的消息进行处理
  238. this->HandleMessage(content);
  239. }
  240. void CMqttClientWorker::delivery_complete(mqtt::delivery_token_ptr token)
  241. {
  242. }
  243. void CMqttClientWorker::CalUserInfo()
  244. {
  245. unsigned char tempData[100];
  246. unsigned int len = 0;
  247. //username和 Password 签名模式下的设置方法,参考文档 https://help.aliyun.com/document_detail/48271.html?spm=a2c4g.11186623.6.553.217831c3BSFry7
  248. HMAC(EVP_sha1(), m_secretKey.c_str(), m_secretKey.length(), (unsigned char *)m_client_id.c_str(), m_client_id.length(), tempData, &len);
  249. char resultData[100];
  250. int passWordLen = EVP_EncodeBlock((unsigned char *)resultData, tempData, len);
  251. resultData[passWordLen] = '\0';
  252. char userNameData[128];
  253. sprintf_s(userNameData, "Signature|%s|%s", m_accessKey.c_str(), m_instanceId.c_str());
  254. m_UserName = userNameData;
  255. m_Password = resultData;
  256. }
  257. void CMqttClientWorker::HandleMessage(std::string message)
  258. {
  259. //收到服务器的消息,对服务器的消息进行处理
  260. rapidjson::Document document;
  261. document.Parse(message.c_str());
  262. if (!document.IsObject())
  263. {
  264. LOG_INFO("message 非法!");
  265. return;
  266. }
  267. if (!document.HasMember("version"))
  268. {
  269. return;
  270. }
  271. std::string version = CLewaimaiJson::ToString(document["version"]);
  272. if (version < "1.0")
  273. {
  274. return;
  275. }
  276. std::string timestamp = CLewaimaiJson::ToString(document["timestamp"]);
  277. long int int_timesteamp = atol(timestamp.c_str());
  278. time_t now = time(NULL);
  279. if (now - int_timesteamp > 60 * 3)
  280. {
  281. //大于3分钟的消息直接丢弃
  282. return;
  283. }
  284. rapidjson::Value & data = document["body"];
  285. std::string type = CLewaimaiJson::ToString(data["order_type"]);
  286. if (type == "waimai")
  287. {
  288. //外卖新订单(非预约单,或者预约单快到时间了)
  289. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  290. std::string order_no = CLewaimaiJson::ToString(data["order_no"]);
  291. //新订单来了,首先判断是否要语音提醒
  292. if (CSetting::GetInstance()->GetParam("setting_is_new_waimai_voice") == "1")
  293. {
  294. if (CSetting::GetInstance()->GetParam("setting_is_new_waimai_autoconfirm") == "1")
  295. {
  296. CVoiceWorker::GetInstance()->AddVoice(2);
  297. }
  298. else
  299. {
  300. CVoiceWorker::GetInstance()->AddVoice(1);
  301. }
  302. }
  303. //判断是否要自动确认
  304. if (CSetting::GetInstance()->GetParam("setting_is_new_waimai_autoconfirm") == "1")
  305. {
  306. CCommonWorker::GetInstance()->AddConfirm(order_id);
  307. }
  308. CPosPrinter printer;
  309. printer.PrintWaimaiOrder(order_id, order_no);
  310. }
  311. else if (type == "waimai_yuyue_notify")
  312. {
  313. //外卖新订单(预约单的通知)
  314. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  315. std::string order_no = CLewaimaiJson::ToString(data["order_no"]);
  316. //新订单来了,首先判断是否要语音提醒
  317. if (CSetting::GetInstance()->GetParam("setting_is_new_waimai_voice") == "1")
  318. {
  319. CVoiceWorker::GetInstance()->AddVoice(1);
  320. }
  321. //判断是否要自动确认
  322. if (CSetting::GetInstance()->GetParam("setting_is_new_waimai_autoconfirm") == "1")
  323. {
  324. CCommonWorker::GetInstance()->AddConfirm(order_id);
  325. }
  326. }
  327. else if (type == "waimai_cancel")
  328. {
  329. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  330. std::string order_no = CLewaimaiJson::ToString(data["order_no"]);
  331. //取消外卖订单
  332. CVoiceWorker::GetInstance()->AddVoice(3);
  333. CPosPrinter printer;
  334. printer.PrintWaimaiOrder(order_id, order_no);
  335. }
  336. else if (type == "waimai_order_refund")
  337. {
  338. //外卖订单退款
  339. CVoiceWorker::GetInstance()->AddVoice(4);
  340. }
  341. else if (type == "tangshi")
  342. {
  343. //快餐扫码下单
  344. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  345. //新订单来了,首先判断是否要语音提醒
  346. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_voice") == "1")
  347. {
  348. CVoiceWorker::GetInstance()->AddVoice(5);
  349. }
  350. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  351. {
  352. CPosPrinter printer;
  353. printer.PrintDiandanOrder(order_id);
  354. }
  355. }
  356. else if (type == "kuaican")
  357. {
  358. //新的快餐订单,商家app下单
  359. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  360. //新订单来了,首先判断是否要语音提醒
  361. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_voice") == "1")
  362. {
  363. CVoiceWorker::GetInstance()->AddVoice(5);
  364. }
  365. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  366. {
  367. CPosPrinter printer;
  368. printer.PrintDiandanOrder(order_id);
  369. }
  370. }
  371. else if (type == "zhengcan_jiacai")
  372. {
  373. //这个是通过商家app加菜,或者H5加菜被商家app确认,提醒收银系统去打印
  374. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  375. std::string jiacai_no = CLewaimaiJson::ToString(data["jiacai_no"]);
  376. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  377. {
  378. CPosPrinter printer;
  379. printer.PrintZhengcanOrderXiadan(order_id, jiacai_no);
  380. }
  381. }
  382. else if (type == "zhengcan_jiacai_h5")
  383. {
  384. //通过扫码下单加菜,还没确认,提醒收银系统确认
  385. CVoiceWorker::GetInstance()->AddVoice(6);
  386. //同时自动刷新桌位
  387. PostMessage(m_hwnd, WM_ZHENGCAN_SAOMADIANCAI_XIADAN, 0, 0);
  388. }
  389. else if (type == "zhengcan_tuicai")
  390. {
  391. //正餐退菜
  392. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  393. std::string tuicai_item_id = CLewaimaiJson::ToString(data["tuicai_item_id"]);
  394. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  395. {
  396. CPosPrinter printer;
  397. printer.PrintZhengcanOrderTuicai(order_id, tuicai_item_id);
  398. }
  399. }
  400. else if (type == "zhengcan_jiesuan")
  401. {
  402. //推送正餐收银订单H5上支付成功的消息给收银机,收银打印结算小票
  403. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  404. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  405. {
  406. CPosPrinter printer;
  407. printer.PrintZhengcanOrderJiesuan(order_id);
  408. }
  409. }
  410. else if (type == "shouyintai_order")
  411. {
  412. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  413. std::string content = CLewaimaiJson::ToString(data["content"]);
  414. CVoiceWorker::GetInstance()->AddVoice(content);
  415. if (CSetting::GetInstance()->GetParam("setting_is_new_diannei_saomadiancan_printer") == "1")
  416. {
  417. CPosPrinter printer;
  418. printer.PrintShoukuanOrder(order_id);
  419. }
  420. }
  421. else if (type == "tangshi_service")
  422. {
  423. std::string content = CLewaimaiJson::ToString(data["content"]);
  424. CVoiceWorker::GetInstance()->AddVoice(content);
  425. }
  426. else if (type == "yuyue_order")
  427. {
  428. //预约功能的预约单,不是外卖的预约单
  429. std::string order_id = CLewaimaiJson::ToString(data["order_id"]);
  430. std::string content = CLewaimaiJson::ToString(data["content"]);
  431. CVoiceWorker::GetInstance()->AddVoice(content);
  432. }
  433. }