ThingPlug GMMP library for mbed
Dependents: ThingPlug_WiFi_Example
Diff: Network/Network.cpp
- Revision:
- 0:32c20cfb2b30
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Network/Network.cpp Thu Jul 23 00:55:15 2015 +0000 @@ -0,0 +1,135 @@ +/** TCP Socket 통신을 위한 모듈 + * @file Network.cpp + * @date 2015/07/20 + * @version 0.0.1.0 + **/ + +#include "Client.h" + +#include "Network.h" +#include "GMMP_Operation.h" + +int g_socket = -1; + +//Client client; +Client *pClient = NULL; + +void CloseSocket() +{ + if (g_socket <= 0) return; + + g_socket = -1; + + delete pClient; + pClient = NULL; + + return; +} + +int CheckSocket() +{ + return 0; +} + +int Connect() +{ + int ret = GMMP_SUCCESS; + + if(pClient == NULL) + pClient = new Client; + + //delay(2000); + infoln("Connecting..."); + INFO("server ip: %d.%d.%d.%d:%d", g_serverIp[0], g_serverIp[1], g_serverIp[2], g_serverIp[3], g_nServerPort); + + char szServerIp[24]; + sprintf(szServerIp, "%d.%d.%d.%d", g_serverIp[0], g_serverIp[1], g_serverIp[2], g_serverIp[3]); + + if (/*client.)*/pClient->connect((char *)szServerIp, g_nServerPort)) { + infoln("Connected!!"); + } else { + infoln("connection failed!"); + ret = SERVER_CONNECT_ERROR; + } + + return ret; +} + +int WriteTCP(char* pBuf, int nLen) +{ + DBG("WriteTCP(): %d", nLen); + + if (pBuf == NULL || nLen <= 0) return LIB_PARAM_ERROR; + + /*client.*/pClient->write(pBuf, nLen); + + return GMMP_SUCCESS; +} + +int ReadTCP(char* pBuf, const int nMaxlen) +{ + return ReadTCP2(pBuf, nMaxlen, 1); +} + +int ReadTCPAsync(char* pBuf, const int nMaxlen); + +int ReadTCP2(char* pBuf, const int nMaxlen, byte blocking) +{ + //blocking = 0; + + if (!blocking) { + return ReadTCPAsync(pBuf, nMaxlen); + } + + if (pBuf == NULL || nMaxlen <= 0) return LIB_PARAM_ERROR; + + int idx = 0; + + memset(pBuf, 0, nMaxlen); + + while(idx < nMaxlen) + { + if (/*client.*/pClient->available()) { + pBuf[idx] = /*client.*/pClient->read(); + DBG("%d", idx); + DBG(" %c",(byte)pBuf[idx]); + idx++; + } else { + debugln("E_WOULDBLOCK"); + return E_WOULDBLOCK; + } + } + + return GMMP_SUCCESS; +} + +int ReadTCPAsync(char* pBuf, const int nMaxlen) +{ + if (pBuf == NULL || nMaxlen <= 0) return LIB_PARAM_ERROR; + + int idx = 0; + char val = -1; + + memset(pBuf, 0, nMaxlen); + + while(idx < nMaxlen) + { + val = /*client.*/pClient->read(); + + if (val != -1) { + pBuf[idx++] = (byte)val; + + /* + pBuf[idx] = (byte)val; + debug(idx); + debug(" "); + debugln((byte)pBuf[idx]); + idx++; + */ + } else { + return E_WOULDBLOCK; + } + } + + return GMMP_SUCCESS; +}