#include "stdafx.h"
#include "CSerialPort.h"
#include "Win32COM_DLL.h"

#define MYAPI  extern//__stdcall
CSerialPort Mycomm;
static int Str2Hex(CString str, unsigned char* data);
static char HexChar(char c);


void MYAPI CloseComm(HANDLE hCtrl)
{
	
	Mycomm.ClosePort(hCtrl);
}

HANDLE MYAPI OpenComm(short CommNum,LPCTSTR Settings )
{
	HANDLE statues;
	statues = Mycomm.OpenUartPort(CommNum,Settings);
	return statues;
}

unsigned char MYAPI RecevieData(unsigned char *RxBuff,unsigned char length)
{
	DWORD getBytes;
	getBytes = Mycomm.ReceiveChars(RxBuff,length);
	return (unsigned char)getBytes;
}
unsigned char MYAPI SendData(unsigned char *WriteBuff,unsigned char length)
{
	DWORD BytesWrite;
	BytesWrite = Mycomm.WriteChars(WriteBuff,length);
	return (unsigned char) BytesWrite;
}
unsigned char MYAPI SendString(CString WriteBuff)  //写字符串函数
{
	DWORD BytesWrite;
	unsigned char Hexdata[60];
	unsigned char length;
	int i = 0;
    length = Str2Hex(WriteBuff,Hexdata);  //返回16进制数据的字节数
	BytesWrite = Mycomm.WriteChars(Hexdata,length);
	return (unsigned char)BytesWrite;
}


/************************************************************************
****将一个十六进制的字符串（str），转化为一个字符数组（data）
****改函数要调用下面HexChar
****
***************************************************************************/
int Str2Hex(CString str, unsigned char* data)
{
	int t, t1;
	int rlen = 0, len = str.GetLength();
	for (int i = 0; i < len;)
	{
		char l, h = str[i];
		if (h == ' ')  //如果有空格
		{
			i++;
			continue;
		}
		i++;
		if(i >= len) break;
		l = str[i];
		t = HexChar(h);
		t1 = HexChar(l);
		// data[rlen] = t*10+t1;
		if((t == 16)||(t1 == 16))
			break;
		else
			t = t*16+t1;
		i++;
		data[rlen]=t;  /** 如果写成char(t)则只能表示0到127的ASII字符，
		大于128的字符都表示不了，所以不加char，直接用数字表示*/
		rlen++;
	}
	return rlen;
}

char HexChar(char c)
{
	if((c>='0')&&(c<='9'))
		return c-0x30;
	else if((c>='A')&&(c<='F'))
		return c-'A'+10;
	else if((c>='a')&&(c<='f'))
		return c-'a'+10;
	else
		return 0x10;
}