
#include "slave.h"
#include "def.h"


Slave::Slave(string slave_id_value)
{
   CLASS_TYPE = 0;
   slave_id = slave_id_value;
   IsConnectRunning = false;
}

void  __stdcall Slave:: MyFunc(const char* str)
{
   char *x = new char[strlen(str)+1];
   lstrcpy(x,str);
   if (Slave::hWnd!=NULL)
   {
       PostMessage(Slave::hWnd,WM_FROM_CORE_MESSAGE,0,(LPARAM)x);
   }
}

void __stdcall Slave::AsyncProc(const char* msg,const char* slave_id,unsigned long user_param)
{
   Slave *obj = (Slave*) user_param;

   char *x = new char[strlen(msg)+1];
   lstrcpy(x,msg);
   if (Slave::hWnd!=NULL)
   {
       int n = obj->CLASS_TYPE;
       PostMessage(Slave::hWnd,WM_FROM_CLIENT_MESSAGE,(WPARAM)n,(LPARAM)x);

       if (lstrcmp(msg,"CONNECTED") == 0)     { obj->OnConnected(); return ; }
       if (lstrcmp(msg,"DISCONNECTED") == 0)  { obj->OnDisconnected(); return ;}
       obj->OnProcessMsg(msg);
   }
}

void Slave::AsyncConnect(string ip,string port)
{
   ::Connect3(ip.c_str(),port.c_str(),slave_id.c_str(),
                    (iidk_callback_func*)AsyncProc,(DWORD)this,-1,0xFFFF);
   IsConnectRunning = true;
}

bool Slave::Connect(string ip,string port)
{
   return ::Connect(ip.c_str(),port.c_str(),slave_id.c_str(),(iidk_old_func*)MyFunc);
}

void Slave::Disconnect()
{
   ::Disconnect(slave_id.c_str());
   IsConnectRunning = false;
}

Slave::~Slave()
{
   Disconnect();
}
