tcp_client.cpp 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /*
  2. * tcp_client.cpp
  3. *
  4. * Created on: 2022年10月5日
  5. * Author: Allen
  6. */
  7. #include "tcp_client.h"
  8. #include "entry/EasyuiContext.h"
  9. #include "utils/Log.h"
  10. #include "base/os.hpp"
  11. #include <system/Thread.h>
  12. #include <string>
  13. #include "base/strings.hpp"
  14. #include "net/NetManager.h"
  15. #include "service/BusinessConfig.h"
  16. #include "core/utilities.h"
  17. #define ETHERNETMANAGER NETMANAGER->getEthernetManager()
  18. #define WIFIMANAGER NETMANAGER->getWifiManager()
  19. void handleMsg(byte* msg);
  20. TcpClient::TcpClient() {
  21. busy_ = false;
  22. }
  23. TcpClient::~TcpClient() {
  24. }
  25. TcpClient* TcpClient::instance() {
  26. static TcpClient singleton;
  27. return &singleton;
  28. }
  29. static net::Conn* conn;
  30. static bool isTcpConnect = false;
  31. static int heartbeatTime = 0;
  32. void TcpClient::sendMsg(const char* msg){
  33. instance()->internalSendMsg(msg);
  34. }
  35. void TcpClient::sendMsgWithCb(const char* msg, TcpCallback callback){
  36. instance()->internalSendMsg(msg);
  37. TcpCacheManager::instance()->setFunc(callback.tid, callback);
  38. }
  39. void TcpClient::internalSendMsg(const char* msg){
  40. if (busy_) {
  41. LOGD("tcp client is busy");
  42. return;
  43. }
  44. busy_ = true;
  45. std::string msgStr = msg;
  46. std::string endDelimiter = "#END#";
  47. std::string finalMsg = msg + endDelimiter;
  48. const char* sendMsg = finalMsg.c_str();
  49. if (conn){
  50. conn->Write((byte*)(sendMsg), strlen(sendMsg));
  51. LOGD("tcp sended msg : %s",sendMsg);
  52. } else {
  53. LOGD("tcp disconnect");
  54. }
  55. busy_ = false;
  56. }
  57. class MyThread: public Thread {
  58. public:
  59. /**
  60. * 线程创建成功后会调用该函数,可以在该函数中做一些初始化操作
  61. * return true 继续线程
  62. * false 退出线程
  63. */
  64. virtual bool readyToRun() {
  65. LOGD("Thread 已经创建完成");
  66. return true;
  67. }
  68. /**
  69. * 线程循环函数
  70. *
  71. * return true 继续线程循环
  72. * false 推出线程
  73. */
  74. virtual bool threadLoop() {
  75. LOGD("线程循环函数");
  76. //检查是否有退出线程的请求,如果有,则返回false,立即退出线程
  77. if (exitPending()) {
  78. return false;
  79. }
  80. conn = net::Dial("tcp", getTcpGateway());
  81. if (conn) {
  82. byte buf[2048] = {0};
  83. TcpModel tcpModel;
  84. tcpModel.tid = base::format("t%d", TimeHelper::getCurrentTime());
  85. tcpModel.type = TcpType::DEVICE;
  86. tcpModel.action = DeviceAction::CONNECT;
  87. // tcpModel.data = ETHERNETMANAGER->getMacAddr();
  88. Json::Value json;
  89. json["identification"] = StoragePreferences::getString(STORE_MAC_ADDR, "0.0.0.0");
  90. json["software_version"] = getVersionCode();
  91. json["model"] = "linux_door";;
  92. json["code"] = "SW10600101C-CM";
  93. if (ETHERNETMANAGER->isConnected()) {
  94. json["clientIp"] = ETHERNETMANAGER->getIp();
  95. }
  96. else if (WIFIMANAGER->isConnected()) {
  97. json["clientIp"] = WIFIMANAGER->getIp();
  98. }
  99. tcpModel.json = json;
  100. std::string req = getTcpModelString(tcpModel);
  101. LOGD("待发送 %s",req.c_str());
  102. //发送
  103. // conn->Write((byte*)(req.c_str()), req.length());
  104. TcpClient::instance()->sendMsg(req.c_str());
  105. while (true && !exitPending()) {
  106. //读取,超时1000毫秒
  107. int n = conn->Read(buf, sizeof(buf) - 1, 1000);
  108. heartbeatTime += 1;
  109. if (heartbeatTime >= 90) {
  110. isTcpConnect = false;
  111. heartbeatTime = 0;
  112. LOGD("心跳超时断开");
  113. break;
  114. }
  115. if (n > 0) {
  116. isTcpConnect = true;
  117. buf[n] = 0;
  118. LOGD("TCP received: %s", buf);
  119. const char* cstr = reinterpret_cast<const char*>(buf);
  120. std::string str = cstr;
  121. if (str == "1"){
  122. heartbeatTime = 0;
  123. LOGD("get a heart beat");
  124. continue;
  125. }
  126. handleMsg(buf);
  127. } else if (n == 0) {
  128. isTcpConnect = false;
  129. LOGD("连接正常断开");
  130. break;
  131. } else if (n == net::E_TIMEOUT) {
  132. // LOGD("读取超时");
  133. } else {
  134. isTcpConnect = false;
  135. LOGD("出错");
  136. break;
  137. }
  138. }
  139. //关闭连接
  140. conn->Close();
  141. //释放内存
  142. delete conn;
  143. conn = NULL;
  144. }
  145. //休眠5s
  146. usleep(5000 * 1000);
  147. LOGD("暂停5秒重新尝试连接TCP");
  148. //返回真,继续下次线程循环
  149. return true;
  150. }
  151. };
  152. static MyThread my_thread;
  153. void TcpClient::startTcp(){
  154. //调用线程类的run函数启动线程, 参数为线程名,可以任意指定。
  155. my_thread.run("tcp thread");
  156. }
  157. void TcpClient::closeTcp() {
  158. bool result = my_thread.isRunning();
  159. if (result) {
  160. my_thread.requestExitAndWait();
  161. LOGD("my_thread已关闭");
  162. }
  163. }
  164. bool TcpClient::busy() {
  165. return instance()->busy_;
  166. }
  167. bool TcpClient::connected() {
  168. return conn != NULL;
  169. }
  170. bool TcpClient::isConnect() {
  171. return isTcpConnect;
  172. }