#include "WINSOCK.H"
#include "stdio.h"
#include "string.h"
char strSubAddr[100];


unsigned char HI(int num_16)
{
	unsigned char tt;
	tt=num_16 & 0xff00;
	tt >>= 8;
	return tt;
}


unsigned char LOW(int num_16)
{
	unsigned char tt;
	tt=num_16 & 0x00ff;
	return tt;
}

extern "C" _declspec(dllexport) void modbus_construct(int *function,int *address,int *value,int send_char[12]) 
{ 
strSubAddr[0]=0x00;
strSubAddr[1]=0x00;
strSubAddr[2]=0x00;
strSubAddr[3]=0x00;
strSubAddr[4]=0x00;
strSubAddr[5]=0x06;
strSubAddr[6]=0x01;
strSubAddr[8]= HI(*address);
strSubAddr[9]=LOW(*address);
switch(*function)
{
case 1:
strSubAddr[7]=0x01;
strSubAddr[10]=HI(*value);
strSubAddr[11]=LOW(*value);
break;

case 2:
strSubAddr[7]=0x02;
strSubAddr[10]=HI(*value);
strSubAddr[11]=LOW(*value);
break;

case 3:
strSubAddr[7]=0x03;
strSubAddr[10]=HI(*value);
strSubAddr[11]=LOW(*value);
break;

case 4:
strSubAddr[7]=0x04;
strSubAddr[10]=HI(*value);
strSubAddr[11]=LOW(*value);
break;

case 5:
strSubAddr[7]=0x05;
if (*value)
    {
       strSubAddr[10] = 0xff;
       strSubAddr[11] = 0;
    }
    else
    {
       strSubAddr[10]= 0;
       strSubAddr[11]= 0;
    } 
break;

case 6:
strSubAddr[7]=0x06;
strSubAddr[10]=HI(*value);
strSubAddr[11]=LOW(*value);
break;

}
for(int send_t=0;send_t<12;send_t++)
send_char[send_t]=strSubAddr[send_t];

}
extern "C" _declspec(dllexport) bool modbus_tcp(char host[15],int *port,int *result) 
{ 
WSADATA ws; 
SOCKET s; 
struct sockaddr_in addr; 

int iResult; 
char strBuffer[11]; 

if(WSAStartup(0x0101,&ws))
{
		MessageBox(NULL,"Initial dll error","Initial dll error",MB_OK);
}
else
		MessageBox(NULL,"Initial dll success","Initial dll error",MB_OK);
s=socket(AF_INET,SOCK_STREAM,0);
if(s==SOCKET_ERROR)
{
		MessageBox(NULL,"creat socket error","creat socket error",MB_OK);
}
else
		MessageBox(NULL,"creat socket success","creat socket success",MB_OK);

addr.sin_family = AF_INET; 
addr.sin_port = htons(*port); 
addr.sin_addr.s_addr = inet_addr(host); 
iResult=connect(s,(struct sockaddr *)&addr, sizeof(addr)); 
if(SOCKET_ERROR == iResult) 
{ 
WSACleanup(); 
		MessageBox(NULL,"connect failed","connect failed",MB_OK);
return FALSE; 
} 
else { 
		MessageBox(NULL,"connect success","connect success",MB_OK);




iResult = send(s, strSubAddr,12,0); 
		MessageBox(NULL,"iResult","iResult",MB_OK);

strset(strBuffer,' '); 
iResult = recv(s,strBuffer,sizeof(strBuffer),0);
		MessageBox(NULL,"iResult2","iResult2",MB_OK);
for(int iii=0;iii<sizeof(strBuffer);iii++)
result[iii]=strBuffer[iii];

} 
closesocket(s);
return(true);
}
