/* * tcp_client.cpp * * Created on: 2022年10月5日 * Author: Allen */ #include "tcp_client.h" #include "entry/EasyuiContext.h" #include "utils/Log.h" #include "base/os.hpp" #include #include #include "base/strings.hpp" #include "net/NetManager.h" #include "service/BusinessConfig.h" #define ETHERNETMANAGER NETMANAGER->getEthernetManager() void handleMsg(byte* msg); TcpClient::TcpClient() { busy_ = false; } TcpClient::~TcpClient() { } TcpClient* TcpClient::instance() { static TcpClient singleton; return &singleton; } static net::Conn* conn; void TcpClient::sendMsg(const char* msg){ instance()->internalSendMsg(msg); } void TcpClient::sendMsgWithCb(const char* msg, TcpCallback callback){ instance()->internalSendMsg(msg); TcpCacheManager::instance()->setFunc(callback.tid, callback); } void TcpClient::internalSendMsg(const char* msg){ if (busy_) { LOGD("tcp client is busy"); return; } busy_ = true; std::string msgStr = msg; std::string endDelimiter = "#END#"; std::string finalMsg = msg + endDelimiter; const char* sendMsg = finalMsg.c_str(); if (conn){ conn->Write((byte*)(sendMsg), strlen(sendMsg)); LOGD("tcp sended msg : %s",sendMsg); } else { LOGD("tcp disconnect"); } busy_ = false; } class MyThread: public Thread { public: /** * 线程创建成功后会调用该函数,可以在该函数中做一些初始化操作 * return true 继续线程 * false 退出线程 */ virtual bool readyToRun() { LOGD("Thread 已经创建完成"); return true; } /** * 线程循环函数 * * return true 继续线程循环 * false 推出线程 */ virtual bool threadLoop() { LOGD("线程循环函数"); //检查是否有退出线程的请求,如果有,则返回false,立即退出线程 if (exitPending()) { return false; } conn = net::Dial("tcp", getTcpGateway()); if (conn) { byte buf[2048] = {0}; TcpModel tcpModel; tcpModel.type = TcpType::DEVICE; tcpModel.action = DeviceAction::CONNECT; // tcpModel.data = ETHERNETMANAGER->getMacAddr(); Json::Value json; json["identification"] = ETHERNETMANAGER->getMacAddr(); json["software_version"] = version; json["model"] = "linux_door";; json["code"] = "SW10600101C-CM"; tcpModel.json = json; std::string req = getTcpModelString(tcpModel); LOGD("待发送 %s",req.c_str()); //发送 // conn->Write((byte*)(req.c_str()), req.length()); TcpClient::instance()->sendMsg(req.c_str()); while (true && !exitPending()) { //读取,超时1000毫秒 int n = conn->Read(buf, sizeof(buf) - 1, 1000); if (n > 0) { buf[n] = 0; handleMsg(buf); } else if (n == 0) { LOGD("连接正常断开"); break; } else if (n == net::E_TIMEOUT) { // LOGD("读取超时"); } else { LOGD("出错"); break; } } //关闭连接 conn->Close(); //释放内存 delete conn; conn = NULL; } //休眠5s usleep(5000 * 1000); LOGD("暂停5秒重新尝试连接TCP"); //返回真,继续下次线程循环 return true; } }; static MyThread my_thread; void TcpClient::startTcp(){ //调用线程类的run函数启动线程, 参数为线程名,可以任意指定。 my_thread.run("tcp thread"); } void TcpClient::closeTcp() { my_thread.requestExitAndWait(); // my_thread.requestExit(); } bool TcpClient::busy() { return instance()->busy_; } bool TcpClient::connected() { return conn != NULL; }