/*
 * tcp_client.cpp
 *
 *  Created on: 2022年10月5日
 *      Author: Allen
 */

#include "tcp_client.h"

#include "entry/EasyuiContext.h"
#include "utils/Log.h"
#include <string>
#include <system/Thread.h>
#include "net/NetManager.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::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 not connect");
	}
	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_serialPortPro";;
			json["code"] = "SW10600070C-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;
					const char* cstr = reinterpret_cast<const char*>(buf);
				    std::string str = cstr;
				    if (str == "1"){
//						LOGD("get a heart beat");
						continue;
					}
					LOGD("TCP received： %s", buf);
					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");
}

bool TcpClient::busy() {
	return instance()->busy_;
}

bool TcpClient::connected() {
	return conn != NULL;
}


