CMqttClientWorker.cpp 11 KB

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