/*
 * ProtocolSender.cpp
 *
 *  Created on: Sep 8, 2017
 *      Author: guoxs
 */

#include "uart/ProtocolSender.h"
#include "uart/UartContext.h"
#include "utils/Log.h"
#include <stdio.h>
#include <string>
#include <string.h>
typedef unsigned char byte;

extern BYTE getCheckSum(const BYTE *pData, int len);

/**
 * 需要根据协议格式进行拼接，以下只是个模板
 * Need to be spliced ​​according to the agreement format, the following is just a template
 */
// uart是串口，pData是发送的内容，len发送内容的长度
bool sendProtocolTo(int uart, const BYTE *pData, BYTE len) {
	BYTE dataBuf[256];
	//起始
	dataBuf[0] = 0x24;

	UINT frameLen = 1;
	// 数据
	for (int i = 0; i < len; ++i) {	// 通过循环，判断数据的长度
		dataBuf[frameLen] = pData[i];
		frameLen++;
	}
	//LOGD("send msg len = %d, frameLen = %d", len, frameLen);
	//结束
	dataBuf[frameLen] = 0x23;

	return UartContext::sendTo(uart, dataBuf, frameLen+1);
}


bool sendProtocolTo(int uart, std::string pData) {
	BYTE dataBuf[1024];
	uint16_t dataLen = static_cast<uint16_t>(pData.length() + 4);
	//起始
	dataBuf[0] = 0x24;
	dataBuf[1] = static_cast<BYTE>(dataLen >> 8);
	dataBuf[2] = static_cast<BYTE>(dataLen & 0xFF);

	UINT frameLen = 3;
	byte* _pData = (byte*) (pData.c_str());
	// 数据
	for (int i = 0; i < strlen(pData.c_str()); ++i) {	// 通过循环，判断数据的长度
		dataBuf[frameLen] = _pData[i];
		frameLen++;
	}
	//结束
	dataBuf[frameLen] = 0x23;

	LOGD("发送433串口消息 =================> %s", pData.c_str());

	return UartContext::sendTo(uart, dataBuf, frameLen + 1);
}

bool sendSimpleTo(int uart, const BYTE *pData, UINT len) {
	return UartContext::sendTo(uart, pData, len);
}

bool sendSimpleTo(int uart, std::string &data) {
    const BYTE *pData = reinterpret_cast<const BYTE *>(data.c_str());
    std::uint32_t len = data.size();
    return sendSimpleTo(uart, pData, len);
}
