a library to use GPRS like ethernet or wifi, which makes it possible to connect to the internet with your GPRS module

Dependencies:   BufferedSerial

Dependents:   ThinkSpeak_Test roam_v1 roam_v2 finalv3

Fork of GPRSInterface by wei zou

Files at this revision

API Documentation at this revision

Comitter:
Yihui Xiong
Date:
Fri Apr 03 15:44:04 2015 +0800
Parent:
12:47488369a980
Child:
14:3c6454f033ac
Commit message:
rework

Changed in this revision

GPRS/GPRS.cpp Show annotated file Show diff for this revision Revisions of this file
GPRS/GPRS.h Show annotated file Show diff for this revision Revisions of this file
GPRS/modem/modem.cpp Show annotated file Show diff for this revision Revisions of this file
GPRS/modem/modem.h Show annotated file Show diff for this revision Revisions of this file
GPRSInterface.cpp Show annotated file Show diff for this revision Revisions of this file
GPRSInterface.h Show annotated file Show diff for this revision Revisions of this file
Socket/TCPSocketConnection.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/GPRS/GPRS.cpp	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRS/GPRS.cpp	Fri Apr 03 15:44:04 2015 +0800
@@ -21,73 +21,67 @@
 */
 
 #include "mbed.h"
-#include "GPRS.h"
+#include "GPRS.h"
+
+#define DEBUG
+
+#ifdef DEBUG
+#include "USBSerial.h"
+extern USBSerial pc;
+#define LOG(args...)        pc.printf(args)
+#else
+#define LOG(args...)
+#endif
+
 
 GPRS* GPRS::inst;
 
-GPRS::GPRS(PinName tx, PinName rx, int baudRate, const char* apn, const char* userName, const char* passWord) : Modem(tx,rx,baudRate)
+GPRS::GPRS(PinName tx, PinName rx, const char* apn, const char* userName, const char* passWord) : Modem(tx,rx)
 {
     inst = this;
     _apn = apn;
     _userName = userName;
     _passWord = passWord;
-    socketID = -1;
-}
-
-bool GPRS::preInit()
-{
-    for(int i = 0; i < 2; i++) {
-        sendCmd("AT\r\n");
-        wait(1);
-    }
-    return checkSIMStatus();
+    socketID = -1;
+    
+    connected = false;
+    recv_bytes = 0;
 }
 
-bool GPRS::checkSIMStatus(void)
-{
-    char gprsBuffer[32];
-    int count = 0;
-    cleanBuffer(gprsBuffer,32);
-    while(count < 3) {
-        sendCmd("AT+CPIN?\r\n");
-        readBuffer(gprsBuffer,32,DEFAULT_TIMEOUT);
-        if((NULL != strstr(gprsBuffer,"+CPIN: READY"))) {
-            break;
-        }
-        count++;
-        wait(1);
-    }
-    if(count == 3) {
-        return false;
-    }
-    return true;
-}
+
 
 bool GPRS::join()
 {
-    char cmd[64];
-    char ipAddr[32];
+    char ip_addr_buf[32];
+    
     //Select multiple connection
-    sendCmdAndWaitForResp("AT+CIPMUX=1\r\n","OK",DEFAULT_TIMEOUT,CMD);
+    command("AT+CIPMUX=1\r\n");
+    
+    // Set APN
+    command("AT+CSTT=\"%s\",\"%s\",\"%s\"\r\n",_apn,_userName,_passWord);
 
-    //set APN
-    snprintf(cmd,sizeof(cmd),"AT+CSTT=\"%s\",\"%s\",\"%s\"\r\n",_apn,_userName,_passWord);
-    sendCmdAndWaitForResp(cmd, "OK", DEFAULT_TIMEOUT,CMD);
-
-    //Brings up wireless connection
-    sendCmdAndWaitForResp("AT+CIICR\r\n","OK",DEFAULT_TIMEOUT,CMD);
+    // Brings up wireless connection
+    command("AT+CIICR\r\n");
 
-    //Get local IP address
-    sendCmd("AT+CIFSR\r\n");
-    readBuffer(ipAddr,32,2);
+    // Get local IP address
+    printf("AT+CIFSR\r\n");
+    
+    readline(ip_addr_buf, sizeof(ip_addr_buf));   // read echo
+
+    if (readline(ip_addr_buf, sizeof(ip_addr_buf)) <= 0) {
+        LOG("failed to join network\r\n");
+        return false;
+    }
+    
+    int a, b, c, d;
+    if (sscanf(ip_addr_buf, "%d.%d.%d.%d", &a, &b, &c, &d) != 4) {
+        LOG("failed to get ip, r(%s)\r\n", ip_addr_buf);
+        return false;
+    }
+    
+    _ip = (a << 24) + (b << 16) + (c << 8) + d;
 
-    if(NULL != strstr(ipAddr,"AT+CIFSR")) {
-        _ip = str_to_ip(ipAddr+12);
-        if(_ip != 0) {
-            return true;
-        }
-    }
-    return false;
+    return true;
 }
 
 bool GPRS::setProtocol(int socket, Protocol p)
@@ -99,65 +93,59 @@
     return true;
 }
 
-bool GPRS::connect(int socket, Protocol ptl,const char * host, int port, int timeout)
-{
-    char cmd[64];
-    char resp[96];
+bool GPRS::connect(int socket, Protocol ptl, const char * host, int port, int timeout)
+{
+    const char *protocol;
     if (socket < 0 || socket > MAX_SOCK_NUM-1) {
         return false;
     }
     if(ptl == TCP) {
-        sprintf(cmd, "AT+CIPSTART=%d,\"TCP\",\"%s\",%d\r\n",socket, host, port);
+        protocol = "TCP";
     } else if(ptl == UDP) {
-        sprintf(cmd, "AT+CIPSTART=%d,\"UDP\",\"%s\",%d\r\n",socket, host, port);
+        protocol = "UDP";
     } else {
         return false;
+    }
+    
+    command("AT+CIPSTART=%d,\"%s\",\"%s\",%d\r\n", socket, protocol, host, port);
+    
+    char response[64] = {0,};
+    if (readline(response, sizeof(response)) < 0) {
+        LOG("wait for connection - timeout\r\n");
+        return false;
+    }
+    
+    if (strstr(response, "CONNECT OK") || strstr(response, "ALREADY CONNECT")) {
+        connected = true;
+        return true;
+    } else {
+        LOG("failed to connect (r:%s)\r\n", response);
+        return false;
     }
-    sendCmd(cmd);
-    readBuffer(resp,96,2*DEFAULT_TIMEOUT);
-    if(NULL != strstr(resp,"CONNECT")) { //ALREADY CONNECT or CONNECT OK
-        return true;
-    }
-    return false;//ERROR
 }
 
 bool GPRS::gethostbyname(const char* host, uint32_t* ip)
-{
-    uint32_t addr = str_to_ip(host);
-    char buf[17];
-    snprintf(buf, sizeof(buf), "%d.%d.%d.%d", (addr>>24)&0xff, (addr>>16)&0xff, (addr>>8)&0xff, addr&0xff);
-    if (strcmp(buf, host) == 0) {
-        *ip = addr;
-        return true;
-    }
+{
+    int a, b, c, d;
+    if (sscanf(host, "%d.%d.%d.%d", &a, &b, &c, &d) == 4) {
+        *ip = (a << 24) + (b << 16) + (c << 8) + d;
+        
+        return true;
+    }
+    
     return false;
 }
 
 bool GPRS::disconnect()
 {
-    sendCmd("AT+CIPSHUT\r\n");
+    puts("AT+CIPSHUT\r\n");
+    connected = false;
     return true;
 }
 
 bool GPRS::is_connected(int socket)
 {
-    char cmd[16];
-    char resp[96];
-    snprintf(cmd,16,"AT+CIPSTATUS=%d\r\n",socket);
-    for (int i = 0; i < 3; i++) {
-        sendCmd(cmd);
-        readBuffer(resp,sizeof(resp),DEFAULT_TIMEOUT);
-        if(NULL != strstr(resp,"CONN")) {
-            //+CIPSTATUS: 1,0,"TCP","216.52.233.120","80","CONNECTED"
-            return true;
-        } else if (NULL != strstr(resp,"CLOSE")) {
-            //+CIPSTATUS: 1,0,"TCP","216.52.233.120","80","CLOSED"
-            //+CIPSTATUS: 0,,"","","","INITIAL"
-            return false;
-        }
-    }
-    
-    return false;
+    return connected;
 }
 
 void GPRS::reset()
@@ -167,121 +155,117 @@
 
 bool GPRS::close(int socket)
 {
-    char cmd[16];
-    char resp[16];
-
-    if (socket < 0 || socket > MAX_SOCK_NUM-1) {
+    if (socket < 0 || socket > (MAX_SOCK_NUM - 1)) {
         return false;
-    }
-    // if not connected, return
-    if (is_connected(socket) == false) {
-        return true;
-    }
-    snprintf(cmd, sizeof(cmd),"AT+CIPCLOSE=%d\r\n",socket);
-    snprintf(resp,sizeof(resp),"%d, CLOSE OK",socket);
-    if(0 != sendCmdAndWaitForResp(cmd, resp, DEFAULT_TIMEOUT,CMD)) {
-        return false;
-    }
+    }
+    
+    printf("AT+CIPCLOSE=%d\r\n", socket);
+    connected = false;
     return true;
-}
-
-bool GPRS::readable(void)
-{
-    return readable();
-}
-
-int GPRS::wait_readable(int socket, int wait_time)
-{
-    if (socket < 0 || socket > MAX_SOCK_NUM-1) {
-        return -1;
-    }
-    char resp[16];
-    snprintf(resp,sizeof(resp),"\r\n\r\n+RECEIVE,%d",socket);//"+RECEIVE:<socketID>,<length>"
-    int len = strlen(resp);
-
-    if(false == respCmp(resp,len,wait_time)) {
-        return -1;
-    }
-    char c = readByte();//','
-    char dataLen[4];
-    int i = 0;
-    c = readByte();
-    while((c >= '0') && (c <= '9')) {
-        dataLen[i++] = c;
-        c = readByte();
-    }
-    c = readByte();//'\n'
-    len = atoi(dataLen);
-    return len;
-}
-
-int GPRS::wait_writeable(int socket, int req_size)
-{
-    if (socket < 0 || socket > MAX_SOCK_NUM-1) {
-        return -1;
-    }
-    return req_size>256?256:req_size+1;
+}
+
+int GPRS::sock_send(int socket, const char * data, int len)
+{
+    if (socket < 0 || socket > MAX_SOCK_NUM-1 || len <= 0) {
+        return -1;
+    }
+
+    char response[64];
+
+    flush();
+    printf("AT+CIPSEND=%d,%d\r\n", socket, len);
+    readline(response, sizeof(response));       // echo, ignore
+    if (match("> ")) {
+        connected = false;
+        return -1;
+    }
+    
+    write(data, len);
+    
+    // read echo data
+    for (int i = 0; i < len; i++) {
+        while (!readable()) {
+        }
+        char ch = getc();
+    }
+    
+    readline(response, sizeof(response));
+    
+    // data received
+    int sock;
+    int bytes = 0;
+    if (sscanf(response, "+RECEIVE,%d,%d:", &sock, &bytes) == 2) {
+        while (bytes > 0) {
+            if (readable()) {
+                recv_buf[recv_bytes] = getc();
+                recv_bytes++;
+                bytes--;
+            }
+        }
+        
+        readline(response, sizeof(response));
+    }
+    
+    if (strstr(response, "SEND OK")) {      // 0, SEND OK
+        return len;
+    }
+    
+    if (strstr(response, "CLOSED")) {
+        connected = false;
+    }
+    return -1;
+}
+
+int GPRS::sock_recv(int socket, char* buf, int len)
+{
+    if (recv_bytes > 0) {
+        if (len >= recv_bytes) {
+            len = recv_bytes;
+            memcpy(buf, recv_buf, recv_bytes);
+            recv_bytes = 0;
+        } else {
+            memcpy(buf, recv_buf, len);
+            recv_bytes -= len;
+            memcpy(recv_buf, recv_buf + len, recv_bytes);
+        }
+        
+        return len;
+    }
+    
+    char response[32];
+    if (readline(response, sizeof(response)) <= 0) {
+        return -1;
+    }
+    
+    if (strstr(response, "CLOSED")) {
+        LOG("socket is closed, r(%s)\r\n", response);
+        connected = false;
+        
+        return -1;
+    }
+    
+    int sock;
+    int bytes = 0;
+    if (sscanf(response, "+RECEIVE,%d,%d:", &sock, &bytes) != 2) {
+        LOG("socket is closed, r(%s)\r\n", response);
+        
+        connected = false;
+        return -1;
+    }
+    
+    int bytes_read = 0;
+    while (bytes_read < bytes) {
+        if (readable()) {
+            buf[bytes_read] = getc();
+            bytes_read++;
+        }
+    }
+    
+    return bytes;  
+}
+
+int GPRS::new_socket()
+{
+    socketID = 0; //we only support one socket.
+    return socketID; 
 }
-
-int GPRS::send(int socket, const char * data, int len)
-{
-    if (socket < 0 || socket > MAX_SOCK_NUM-1) {
-        return -1;
-    }
-
-    char cmd[32];
-    char resp[16];
-    wait(1);
-    if(len > 0){
-        snprintf(cmd,sizeof(cmd),"AT+CIPSEND=%d,%d\r\n",socket,len);
-        if(0 != sendCmdAndWaitForResp(cmd,">",DEFAULT_TIMEOUT,CMD)) {
-            return false;
-        }
-        sendData(data, len);
-        snprintf(resp,sizeof(resp),"%d, SEND OK",socket);
-        if(0 != waitForResp(resp,DEFAULT_TIMEOUT,DATA)) {
-            return -1;
-        }
-    }
-    return len;
-}
-
-int GPRS::recv(int socket, char* buf, int len)
-{
-    if (socket < 0 || socket > MAX_SOCK_NUM-1) {
-        return -1;
-    }
-    cleanBuffer(buf,len);
-    readBuffer(buf,len,DEFAULT_TIMEOUT/2);
-    return len;
-    //return strlen(buf);
-}
-
-int GPRS::new_socket()
-{
-    socketID = 0; //we only support one socket.
-    return socketID; 
-}
-
-uint16_t GPRS::new_port()
-{
-    uint16_t port = rand();
-    port |= 49152;
-    return port;
-}
-
-uint32_t GPRS::str_to_ip(const char* str)
-{
-    uint32_t ip = 0;
-    char* p = (char*)str;
-    for(int i = 0; i < 4; i++) {
-        ip |= atoi(p);
-        p = strchr(p, '.');
-        if (p == NULL) {
-            break;
-        }
-        ip <<= 8;
-        p++;
-    }
-    return ip;
-}
--- a/GPRS/GPRS.h	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRS/GPRS.h	Fri Apr 03 15:44:04 2015 +0800
@@ -27,7 +27,7 @@
 #include "modem.h"
 
 #define DEFAULT_WAIT_RESP_TIMEOUT 500
-#define MAX_SOCK_NUM 7 //(0~6)
+#define MAX_SOCK_NUM 7                  // (0~6)
 
 enum Protocol {
     CLOSED = 0,
@@ -47,7 +47,7 @@
      * 	@param userName apn's username, usually is NULL
      * 	@param passWord apn's password, usually is NULL
      */
-    GPRS(PinName tx, PinName rx, int baudRate, const char* apn, const char* userName = NULL, const char *passWord = NULL);
+    GPRS(PinName tx, PinName rx, const char* apn, const char* userName = NULL, const char *passWord = NULL);
 
     /** get instance of GPRS class
      */
@@ -75,10 +75,10 @@
      * 	@param ptl protocol for socket, TCP/UDP can be choosen
      * 	@param host host (can be either an ip address or a name. If a name is provided, a dns request will be established)
      * 	@param port port
-     * 	@param timeout wait seconds till connected
+     * 	@param timeout wait time (ms)
      * 	@returns true if successful
      */
-    bool connect(int socket, Protocol ptl, const char * host, int port, int timeout = DEFAULT_TIMEOUT);
+    bool connect(int socket, Protocol ptl, const char * host, int port, int timeout = DEFAULT_TIMEOUT_MS);
 
     /** Set the protocol (UDP or TCP)
      * 	@param socket socket
@@ -91,11 +91,6 @@
      */
     void reset();
 
-    /**	check if GPRS module is readable or not
-     *	@returns true if readable
-     */
-    bool readable(void);
-
     /**	wait a few time to check if GPRS module is readable or not
      *	@param socket socket
      *	@param wait_time time of waiting
@@ -119,7 +114,7 @@
      * 	@param len string length
      * 	@returns return bytes that actually been send
      */
-    int send(int socket, const char * str, int len);
+    int sock_send(int socket, const char * str, int len);
 
     /** read data from socket
      * 	@param socket socket
@@ -127,7 +122,7 @@
      *	@param len string length need to read from socket
      *	@returns bytes that actually read
      */
-    int recv(int socket, char* buf, int len);
+    int sock_recv(int socket, char* buf, int len);
 
     /** convert the host to ip
      *  @param host host ip string, ex. 10.11.12.13
@@ -138,18 +133,18 @@
 
     int new_socket();
     uint16_t new_port();
-    uint32_t _ip;
+    uint32_t _ip;
+    
 
 protected:
-
-    bool preInit();
-    bool checkSIMStatus(void);
-    uint32_t str_to_ip(const char* str);
     static GPRS* inst;
     int socketID;
     const char* _apn;
     const char* _userName;
-    const char* _passWord;
+    const char* _passWord;
+    bool connected;
+    uint8_t recv_buf[32];       // for 
+    uint8_t recv_bytes;
 };
 
 #endif
--- a/GPRS/modem/modem.cpp	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRS/modem/modem.cpp	Fri Apr 03 15:44:04 2015 +0800
@@ -1,136 +1,134 @@
 /*
   modem.cpp
-  2014 Copyright (c) Seeed Technology Inc.  All right reserved.
-
-  Author:lawliet zou(lawliet.zou@gmail.com)
-  2014-2-24
-
-  This library is free software; you can redistribute it and/or
-  modify it under the terms of the GNU Lesser General Public
-  License as published by the Free Software Foundation; either
-  version 2.1 of the License, or (at your option) any later version.
-
-  This library is distributed in the hope that it will be useful,
-  but WITHOUT ANY WARRANTY; without even the implied warranty of
-  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-  Lesser General Public License for more details.
-
-  You should have received a copy of the GNU Lesser General Public
-  License along with this library; if not, write to the Free Software
-  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+  2015 Copyright (c) Seeed Technology Limited.  All right reserved.
 */
 
 #include "modem.h"
-
-char Modem::readByte(void)
-{
-    return serialModem.getc();
-}
-
-bool Modem::readable()
-{
-    return serialModem.readable();
-}
-
-int Modem::readBuffer(char *buffer,int count, unsigned int timeOut)
-{
-    int i = 0;
-    timeCnt.start();
-    while(1) {
-        while (serialModem.readable()) {
-            char c = serialModem.getc();
-            buffer[i++] = c;
-            if(i >= count)break;
-        }
-        if(i >= count)break;
-        if(timeCnt.read() > timeOut) {
-            timeCnt.stop();
-            timeCnt.reset();
-            break;
-        }
-    }
-    return 0;
-}
-
-void Modem::cleanBuffer(char *buffer, int count)
-{
-    for(int i=0; i < count; i++) {
-        buffer[i] = '\0';
-    }
-}
-
-void Modem::sendCmd(const char* cmd)
-{
-    serialModem.puts(cmd);
-}
-
-void Modem::sendData(const char* data, int len)
-{
-    for (int i = 0; i < len; i++) {
-        serialModem.putc(data[i]);
-    }
-}
-
-void Modem::sendATTest(void)
-{
-    sendCmdAndWaitForResp("AT\r\n","OK",DEFAULT_TIMEOUT,CMD);
-}
+#include <stdarg.h>
+
+#define DEBUG
+
+#ifdef DEBUG
+#include "USBSerial.h"
+extern USBSerial pc;
+#define LOG(args...)        pc.printf(args)
+#else
+#define LOG(args...)
+#endif
 
-bool Modem::respCmp(const char *resp, unsigned int len, unsigned int timeout)
-{
-    int sum=0;
-    timeCnt.start();
-
-    while(1) {
-        if(serialModem.readable()) {
-            char c = serialModem.getc();
-            sum = (c==resp[sum]) ? sum+1 : 0;
-            if(sum == len)break;
-        }
-        if(timeCnt.read() > timeout) {
-            timeCnt.stop();
-            timeCnt.reset();
-            return false;
-        }
-    }
-    timeCnt.stop();
-    timeCnt.reset();
-
-    return true;
-}
-
-int Modem::waitForResp(const char *resp, unsigned int timeout,DataType type)
-{
-    int len = strlen(resp);
-    int sum=0;
-    timeCnt.start();
+int Modem::readline(char *buf, int len, uint32_t timeout)
+{
+    int bytes = 0;
+    uint32_t start = us_ticker_read();
+    timeout = timeout * 1000;               // ms to us
+    
+    while (bytes < len) {
+        if (readable()) {
+            char ch = getc();
+            if (ch == '\n') {
+                if (bytes > 0 && buf[bytes - 1] == '\r') {
+                    bytes--;
+                }
+                
+                if (bytes > 0) {
+                    buf[bytes] = '\0';
+                    
+                    return bytes;
+                }
+            } else {
+                buf[bytes] = ch;
+                bytes++;
+            }
+        } else {
+            if ((uint32_t)(us_ticker_read() - start) > timeout) {
+                LOG("wait for a line - timeout\r\n");
+                return -1;
+            }
+        }
+    }
+    
+    // buffer is not enough
+    LOG("%s %d line buffer is not enough (max_buf_size: %d)!\r\n", __FILE__, __LINE__, len);
+
+    return 0;
+}
+
+int Modem::command(const char* format, ...)
+{
+    
+    char buffer[64];
+    memset(buffer, 0, sizeof(buffer));
+    int r = 0;
+
+    va_list arg;
+    va_start(arg, format);
+    r = vsprintf(buffer, format, arg);
+    // this may not hit the heap but should alert the user anyways
+    if(r > sizeof(buffer)) {
+        error("%s %d buffer overwrite (max_buf_size: %d exceeded: %d)!\r\n", __FILE__, __LINE__, sizeof(buffer), r);
+        va_end(arg);
+        return 0;
+    }
+    va_end(arg);
+    
+    
+    while (!writeable()) {
+    }
+    flush();
+
+    r = BufferedSerial::write(buffer, r);   // send command
+    
+    char response[64] = {0,};
+    readline(response, sizeof(response));       // echo enabled
+    
+    readline(response, sizeof(response));
+    
+    if (strcmp(response, "OK") == 0) {
+        return 0;
+    }
+    
+    LOG("cmd failed - w(%s), r(%s)\r\n", buffer, response);
+
+    return -1;
+}
+
+int Modem::match(const char *str, uint32_t timeout)
+{
+    const char *ptr = str;
+    uint32_t start = us_ticker_read();
+    timeout = timeout * 1000;               // ms to us
+
+    while(*ptr) {
+        if(readable()) {
+            char c = getc();
+            if (*ptr == c) {
+                ptr++;
+            } else {
+                ptr = str;
+            }
+        } else {
+            if ((uint32_t)(us_ticker_read() - start) > timeout) {
+                LOG("wait for [%s] - timeout\r\n", str);
+                return -1;
+            }
+        }
+    }
+
+    return 0;
+}
+
+void Modem::flush()
+{
+    while (readable()) {                    // flush
+        getc();
+    }
+}
+
+uint8_t Modem::read()
+{
+    while (!readable()) {
+    }
+    
+    return getc();
+}
 
-    while(1) {
-        if(serialModem.readable()) {
-            char c = serialModem.getc();
-            sum = (c==resp[sum]) ? sum+1 : 0;
-            if(sum == len)break;
-        }
-        if(timeCnt.read() > timeout) {
-            timeCnt.stop();
-            timeCnt.reset();
-            return -1;
-        }
-    }
-    timeCnt.stop();
-    timeCnt.reset();
-
-    if(type == CMD) {
-        while(serialModem.readable()) {
-            char c = serialModem.getc();
-        }
-    }
-
-    return 0;
-}
-
-int Modem::sendCmdAndWaitForResp(const char* data, const char *resp, unsigned timeout,DataType type)
-{
-    sendCmd(data);
-    return waitForResp(resp,timeout,type);
-}
--- a/GPRS/modem/modem.h	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRS/modem/modem.h	Fri Apr 03 15:44:04 2015 +0800
@@ -23,121 +23,50 @@
 #ifndef __MODEM_H__
 #define __MODEM_H__
 
-#if defined(LPC11UXX) || defined (LPC176X)
-#include "BufferedSerial.h"
+#if defined(TARGET_LPC11UXX) || defined (TARGET_LPC176X)
+#include "BufferedSerial.h"
+#define INTERFACE_BASE      BufferedSerial
 #else
-#include "mbed.h"
+#include "mbed.h"
+#define INTERFACE_BASE      Serial
 #endif
 
-#define DEFAULT_TIMEOUT   	5
+#define DEFAULT_TIMEOUT_MS   	30000
 
-enum DataType {
-    CMD		= 0,
-    DATA	= 1,
-};
 
 /** Modem class.
  *  Used for Modem communication. attention that Modem module communicate with MCU in serial protocol
  */
-class Modem
+class Modem : public INTERFACE_BASE
 {
 
 public:
     /**	Create Modem Instance
      *  @param tx	uart transmit pin to communicate with Modem
      *  @param rx	uart receive pin to communicate with Modem
-     *  @param baudRate	baud rate of uart communication
      */
-    Modem(PinName tx, PinName rx, int baudRate) : serialModem(tx, rx) {
-        serialModem.baud(baudRate);
+    Modem(PinName tx, PinName rx) : INTERFACE_BASE(tx, rx) {
+        baud(115200);
     };
-
-#if defined(LPC11UXX) || defined (LPC176X)
-	BufferedSerial serialModem;
-#else
-	Serial serialModem;
-#endif
-	
+
 protected:
-    /** Power on Modem
-     */
-    void preInit(void);
-
-    /** check serialModem is readable or not
-     *	@returns
-     *		true on readable
-     *		false on not readable
-     */
-    bool readable();
-
-    /** read one byte from serialModem
-     *	@returns
-     *		one byte read from serialModem
-     */
-    char readByte(void);
-
-    /** read from Modem module and save to buffer array
-     *  @param  buffer	buffer array to save what read from Modem module
-     *  @param  count 	the maximal bytes number read from Modem module
-     *  @param  timeOut	time to wait for reading from Modem module
-     *  @returns
-     *      0 on success
-     *      -1 on error
-     */
-    int readBuffer(char* buffer,int count, unsigned int timeOut);
-
-
-    /** clean Buffer
-     *	@param buffer	buffer to clean
-     *	@param count	number of bytes to clean
-     */
-    void cleanBuffer(char* buffer, int count);
-
-    /** send AT command to Modem module
-     *  @param cmd	command array which will be send to GPRS module
-     */
-    void sendCmd(const char* cmd);
-    
-    /** send data to Modem module
-     *  @param data	 array which will be send to GPRS module
-     *  @param len   data length
-     */
-    void sendData(const char* data, int len);
-
-    /**send "AT" to Modem module
-     */
-    void sendATTest(void);
-
-    /**	compare the response from GPRS module with a string
-     *	@param resp	buffer to be compared
-     *	@param len length that will be compared
-     *	@param timeout	waiting seconds till timeout
-     */
-    bool respCmp(const char *resp, unsigned int len, unsigned int timeout);
-
-    /** check Modem module response before time out
-     *  @param  *resp   correct response which Modem module will return
-     *  @param  *timeout    waiting seconds till timeout
-     *  @returns
-     *      0 on success
-     *      -1 on error
-     */
-    int waitForResp(const char *resp, unsigned int timeout,DataType type);
-
-    /** send AT command to GPRS module and wait for correct response
-     *  @param  *cmd 	AT command which will be send to GPRS module
-     *  @param  *resp   correct response which GPRS module will return
-     *  @param  *timeout 	waiting seconds till timeout
-     *  @returns
-     *      0 on success
-     *      -1 on error
-     */
-    int sendCmdAndWaitForResp(const char* data, const char *resp, unsigned timeout,DataType type);
-
-    Timer timeCnt;
-
-private:
-
+    /** Read a line
+     * @param buf   the buffer to store a line
+     * @param len   size of the buffer
+     * @param timeout   wait time (ms)
+     * @return -1 if timeout, length of the line if otherwise
+     */
+    int readline(char *buf, int len, uint32_t timeout = DEFAULT_TIMEOUT_MS);
+
+    int command(const char* format, ...);
+
+    int match(const char *resp, uint32_t timeout = DEFAULT_TIMEOUT_MS);
+
+    void flush();
+    uint8_t read();
+
+private:
+    Timer timer;
 };
 
 #endif
--- a/GPRSInterface.cpp	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRSInterface.cpp	Fri Apr 03 15:44:04 2015 +0800
@@ -22,14 +22,13 @@
 
 #include "GPRSInterface.h"
 
-GPRSInterface::GPRSInterface(PinName tx, PinName rx, int baudRate, const char* apn, const char* userName, const char *passWord) : GPRS(tx,rx,baudRate,apn,userName,passWord)
+GPRSInterface::GPRSInterface(PinName tx, PinName rx, const char* apn, const char* userName, const char *passWord) : GPRS(tx, rx, apn, userName, passWord)
 {
     ip_set = false;
 }
 
 int GPRSInterface::init()
 {
-    reset();
     return 0;
 }
 
--- a/GPRSInterface.h	Tue Mar 10 03:11:38 2015 +0000
+++ b/GPRSInterface.h	Fri Apr 03 15:44:04 2015 +0800
@@ -42,7 +42,7 @@
      *  @param userName apn's username, usually is NULL
      *  @param passWord apn's password, usually is NULL
      */
-    GPRSInterface(PinName tx, PinName rx, int baudRate, const char* apn, const char* userName = NULL, const char *passWord = NULL);
+    GPRSInterface(PinName tx, PinName rx, const char* apn, const char* userName = NULL, const char *passWord = NULL);
 
     /** Initialize the interface(no connection at this point).
      *  @return 0 on success, a negative number on failure
--- a/Socket/TCPSocketConnection.cpp	Tue Mar 10 03:11:38 2015 +0000
+++ b/Socket/TCPSocketConnection.cpp	Fri Apr 03 15:44:04 2015 +0800
@@ -51,40 +51,17 @@
 
 int TCPSocketConnection::send(char* data, int length)
 {
-    int size = gprs->wait_writeable(_sock_fd, length);
-    if (size < 0) {
-        return -1;
-    }
-    if (size > length) {
-        size = length;
-    }
-    return gprs->send(_sock_fd, data, size);
+    return gprs->sock_send(_sock_fd, data, length);
 }
 
 int TCPSocketConnection::send_all(char* data, int length)
 {
-    return send(data,length);
+    return send(data, length);
 }
 
 int TCPSocketConnection::receive(char* data, int length)
 {
-#if 0
-    if (size < 0) {
-        return -1;
-    }
-    if(size == 0) {
-        size = gprs->wait_readable(_sock_fd, DEFAULT_TIMEOUT);
-    }
-
-    if(size > length) {
-        size = size - length;
-    } else {
-        length = size;
-        size = -1;
-    }
-#endif
-    int size = gprs->wait_readable(_sock_fd, DEFAULT_TIMEOUT);
-    return gprs->recv(_sock_fd, data, size>length?length:size);
+    return gprs->sock_recv(_sock_fd, data, length);
 }
 
 int TCPSocketConnection::receive_all(char* data, int length)