/**
 * 应用程序源码文件
 */
#ifndef STT_HMIAPP_CPP_
#define STT_HMIAPP_CPP_

/*********************
 *   头文件
 *********************/
#include "HmiApp.h"
/*PAGES_HEAD_BEGIN*/
#include "pages/Frm01.h"
/*PAGES_HEAD_END*/

using namespace stt;

/********************************
 *
 *  应用程序入口
 *
 *  注意：IDE自动生成，用户勿修改
 *
 ********************************/
IApplication * AppMain(IRuntime* env, char **argv){
	return new HmiApp(env);
}

string getAppArgs() {
	return "{\"r\":0}";
}

/********************************
 *
 *  应用程序类
 *
 *  注意：用户可添加代码
 *
 ********************************/
HmiApp::HmiApp(IRuntime * rt) : HmiAppBase(rt) {
}

HmiApp::~HmiApp() {
}

/********************************
 *
 *  应用构建前调用此函数
 *
 *  注意：用户可添加代码
 *
 ********************************/
void HmiApp::onInit(){
	//用户在此添加客户化代码
}

/********************************
 *
 *  应用构建函数
 *
 *  注意：IDE自动生成，用户勿修改
 *
 ********************************/
void HmiApp::construct() {
	//注册字体文件
	fm->registerFontFile("文泉驿微米黑", "./fnt/wenquanyiweimihei.ttf");
	//设备注册
	dm->addDevice("Modbus/RTU_按分区", R"({"stopBits":"1","maxReadLen":"120","parity":"1","DeviceId":"Modbus/RTU_按分区","portName":"COM1","maxAddrInterval":"5","issim":"true","NoR":"3","coding":"0","seqAsc":"0","comDelay":"1200","StationNo":"1","seqLong":"0","Protocol":"ModbusRtu","if":"RS485","framDelay":"4","seqFloat":"2","period":"100","Optz":"true","dll":"ModBusDriver","seqInt32":"2","dataSize":"8","maxWriteLen":"120","baudRate":"9600","seqInt16":"0"})");
	dm->addDevice("Modbus/RTU_按分区", R"({"stopBits":"1","maxReadLen":"120","parity":"0","DeviceId":"Modbus/RTU_按分区","portName":"COM1","maxAddrInterval":"5","issim":"false","NoR":"3","coding":"0","seqAsc":"0","comDelay":"1200","StationNo":"1","seqLong":"0","Protocol":"ModbusRtu","if":"RS485","framDelay":"4","seqFloat":"2","period":"100","Optz":"true","dll":"ModBusDriver","seqInt32":"2","dataSize":"8","maxWriteLen":"120","baudRate":"9600","seqInt16":"0"})");
	//设备变量
	vm->add("汉字8个", DataType::D_VCHAR, R"({"dvc":"Modbus/RTU_按分区","a":"2","r":"1","c":"[4区]输出寄存器","t":"0","id":"v2","l":"16"})");
	//常规变量
	vm->add("显示", DataType::T_VCHAR, R"({"id":"v3"})");
	vm->add("显示2", DataType::T_VCHAR, R"({"id":"v6"})");
	//背光、屏保
	pm->setBackLightHoldingTime(0, 50);
}

IPagePtr HmiApp::buildPage(string id, uint8_t mode, STTWidget *target) {
	return new Frm01(this, target, "Frm01", "Frm01");
}

/********************************
 *
 *  构建应用后调用此函数
 *
 *  注意：用户可添加代码
 *
 ********************************/

int HmiApp::STTUartWrite(unsigned char * bytes,int size){
	UARTDriverBase * UrHandle = (UARTDriverBase *)dm->getDvcdriver("COM1");
	if(UrHandle == nullptr)return 0;
	std::lock_guard<std::mutex> lock(UrHandle->mtx);
	return Util::uartWrite(UrHandle->uartID, bytes, 0, size);
}

int HmiApp::STTUartSendANDReadall(char * buff,uint8_t recvLen,uint16_t timeOut, unsigned char * bytes,int size){
	UARTDriverBase * UrHandle = (UARTDriverBase *)dm->getDvcdriver("COM1");
	if(UrHandle == nullptr)return 0;
	int ReadSize = 0;
	{
		char buffer[256] = {0};
		std::lock_guard<std::mutex> lock(UrHandle->mtx);
		Util::uartReadAll(UrHandle->uartID,buffer,256,10);
		if(size > 0){
			Util::uartWrite(UrHandle->uartID, bytes, 0, size);
		}
		Util::sleepfor(10);
		ReadSize = Util::uartReadAll(UrHandle->uartID,buff,recvLen,timeOut);
	}
	return ReadSize;
}


// MODBUS 06 - 写单个寄存器
bool HmiApp::modbus06_write(uint8_t slave_addr, uint16_t reg_addr, uint16_t value) {

	vector<uint8_t> cmd;
	bool r = ModbusUtils::build_modbus06_command(slave_addr, reg_addr, value, cmd);
	if (!r)	return r;
    // 发送数据到串口
    int rb = STTUartWrite(cmd.data(), cmd.size());
    if (rb <= 0)	return false;
    return true;
}

bool HmiApp::modbus03_read(char * buff,uint8_t slave_addr, uint16_t reg_addr, uint16_t length) {
	vector<uint8_t> cmd;
	bool r = ModbusUtils::build_modbus03_command(slave_addr, reg_addr, length, cmd);
	if (!r)	return r;

	// 打印参数
	std::stringstream ss;
	ss << std::hex << std::uppercase << std::setfill('0');
	for(int i = 0; i < 8; i++) {
	    ss << std::setw(2) << static_cast<int>(cmd[i]) << " ";
	}
	std::cout << "Data: " << ss.str() << std::endl;

	int ret = STTUartSendANDReadall(buff,length*2 + 3,200,cmd.data(),cmd.size());

	// 打印参数
	cout<<"ret = "<<ret<<endl;
	printf("Buff(HEX): ");
	for(int i = 0; i < ret; i++) {
	    printf("%02X ", (unsigned char)buff[i]);
	}
	printf("\n");
	if (ret <= 0)	return false;
    return true;
}

// MODBUS 10 - 写多个寄存器
bool HmiApp::modbus10_write(uint8_t slave_addr, uint16_t start_addr, const std::vector<uint16_t>& values) {

    if (values.empty()) return false;
	vector<uint8_t> cmd;
	bool r = ModbusUtils::build_modbus10_command(slave_addr, start_addr, values, cmd);
	if (!r)	return r;
    // 发送数据到串口
    // 这里调用实际的串口发送函数，使用UrHandle->uartID
    int rb = STTUartWrite(cmd.data(), cmd.size());
    if (rb <= 0)	return false;
    return true;
}

void HmiApp::onReady(){
	//用户在此添加客户化代码

}

/********************************
 *
 *  应用退出前调用此函数
 *
 *  注意：用户可添加代码
 *
 ********************************/
void HmiApp::onQuit(){
	//用户在此添加客户化代码
}


#endif /* STT_HMIAPP_CPP_ */


