Sysbee / sendmessages

Dependents:   App_Pese_Ruche_SYSBEE

Fork of C027_Support by u-blox

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MDM.cpp Source File

MDM.cpp

00001 #include "mbed.h"
00002 #include "MDM.h"
00003 #ifdef TARGET_UBLOX_C027
00004  #include "C027_api.h"
00005 #endif
00006 #include "MDMAPN.h"
00007         
00008 #define PROFILE         "0"   //!< this is the psd profile used
00009 #define MAX_SIZE        128   //!< max expected messages
00010 // num sockets
00011 #define NUMSOCKETS      (sizeof(_sockets)/sizeof(*_sockets))
00012 //! test if it is a socket is ok to use
00013 #define ISSOCKET(s)     (((s) >= 0) && ((s) < NUMSOCKETS) && (_sockets[s].handle != SOCKET_ERROR))
00014 //! check for timeout
00015 #define TIMEOUT(t, ms)  ((ms != TIMEOUT_BLOCKING) && (ms < t.read_ms())) 
00016 // num HTTP profiles
00017 #define NUMPROFILES      (sizeof(_httpProfiles)/sizeof(*_httpProfiles))
00018 //! test if it is an HTTP profile is ok to use
00019 #define ISPROFILE(p)     (((p) >= 0) && ((p) < NUMPROFILES) && (_httpProfiles[p].handle != HTTP_PROF_ERROR))
00020 //! registration ok check helper
00021 #define REG_OK(r)       ((r == REG_HOME) || (r == REG_ROAMING)) 
00022 //! registration done check helper (no need to poll further)
00023 #define REG_DONE(r)     ((r == REG_HOME) || (r == REG_ROAMING) || (r == REG_DENIED)) 
00024 //! helper to make sure that lock unlock pair is always balaced 
00025 #define LOCK()         { lock() 
00026 //! helper to make sure that lock unlock pair is always balaced 
00027 #define UNLOCK()       } unlock()
00028 
00029 #ifdef MDM_DEBUG
00030  #if 1 // colored terminal output using ANSI escape sequences
00031   #define COL(c) "\033[" c
00032  #else
00033   #define COL(c) 
00034  #endif
00035  #define DEF COL("39m")
00036  #define BLA COL("30m")
00037  #define RED COL("31m")
00038  #define GRE COL("32m")
00039  #define YEL COL("33m")
00040  #define BLU COL("34m")
00041  #define MAG COL("35m")
00042  #define CYA COL("36m")
00043  #define WHY COL("37m")
00044  
00045 void dumpAtCmd(const char* buf, int len)
00046 {
00047     ::printf(" %3d \"", len);
00048     while (len --) {
00049         char ch = *buf++;
00050         if ((ch > 0x1F) && (ch != 0x7F)) { // is printable
00051             if      (ch == '%')  ::printf("%%");
00052             else if (ch == '"')  ::printf("\\\"");
00053             else if (ch == '\\') ::printf("\\\\");
00054             else putchar(ch);
00055         } else {
00056             if      (ch == '\a') ::printf("\\a"); // BEL (0x07)
00057             else if (ch == '\b') ::printf("\\b"); // Backspace (0x08)
00058             else if (ch == '\t') ::printf("\\t"); // Horizontal Tab (0x09)
00059             else if (ch == '\n') ::printf("\\n"); // Linefeed (0x0A)
00060             else if (ch == '\v') ::printf("\\v"); // Vertical Tab (0x0B)
00061             else if (ch == '\f') ::printf("\\f"); // Formfeed (0x0C)
00062             else if (ch == '\r') ::printf("\\r"); // Carriage Return (0x0D)
00063             else                 ::printf("\\x%02x", (unsigned char)ch);
00064         }
00065     }
00066     ::printf("\"\r\n");
00067 }
00068  
00069 void MDMParser::_debugPrint(int level, const char* color, const char* format, ...)
00070 {
00071     if (_debugLevel >= level) 
00072     {
00073         va_list args;
00074         va_start (args, format);
00075         if (color) ::printf(color);
00076         ::vprintf(format, args);
00077         if (color) ::printf(DEF);
00078         va_end (args);
00079     }
00080 }
00081    
00082  #define ERROR(...)     _debugPrint(0, RED, __VA_ARGS__)
00083  #define INFO(...)      _debugPrint(1, GRE, __VA_ARGS__)
00084  #define TRACE(...)     _debugPrint(2, DEF, __VA_ARGS__)
00085  #define TEST(...)      _debugPrint(3, CYA, __VA_ARGS__)
00086  
00087 #else
00088  
00089  #define ERROR(...) (void)0 // no tracing
00090  #define TEST(...)  (void)0 // no tracing
00091  #define INFO(...)  (void)0 // no tracing
00092  #define TRACE(...) (void)0 // no tracing
00093 
00094 #endif
00095 
00096 MDMParser* MDMParser::inst;
00097 
00098 MDMParser::MDMParser(void)
00099 {
00100     inst = this;
00101     memset(&_dev, 0, sizeof(_dev));
00102     memset(&_net, 0, sizeof(_net));
00103     _net.lac = 0xFFFF;
00104     _net.ci = 0xFFFFFFFF;
00105     _ip        = NOIP;
00106     _init      = false;
00107     memset(_sockets, 0, sizeof(_sockets));
00108     for (int socket = 0; socket < NUMSOCKETS; socket ++)
00109         _sockets[socket].handle = SOCKET_ERROR;
00110     memset(_httpProfiles, 0, sizeof(_httpProfiles));
00111     for (int profile = 0; profile < NUMPROFILES; profile ++)
00112         _httpProfiles[profile].handle = HTTP_PROF_ERROR;
00113 #ifdef MDM_DEBUG
00114     _debugLevel = 1;
00115     _debugTime.start();
00116 #endif
00117 }
00118 
00119 int MDMParser::send(const char* buf, int len)
00120 {
00121 #ifdef MDM_DEBUG
00122     if (_debugLevel >= 3) {
00123         ::printf("%10.3f AT send    ", _debugTime.read_ms()*0.001);
00124         dumpAtCmd(buf,len);
00125     }
00126 #endif
00127     return _send(buf, len);
00128 }
00129 
00130 int MDMParser::sendFormated(const char* format, ...) {
00131     char buf[MAX_SIZE];
00132     va_list args;
00133     va_start(args, format);
00134     int len = vsnprintf(buf,sizeof(buf), format, args);
00135     va_end(args);
00136     return send(buf, len);
00137 }
00138 
00139 int MDMParser::waitFinalResp(_CALLBACKPTR cb /* = NULL*/, 
00140                              void* param /* = NULL*/, 
00141                              int timeout_ms /*= 5000*/)
00142 {
00143     char buf[MAX_SIZE + 64 /* add some more space for framing */]; 
00144     Timer timer;
00145     timer.start();
00146     do {
00147         int ret = getLine(buf, sizeof(buf));
00148 #ifdef MDM_DEBUG
00149         if ((_debugLevel >= 3) && (ret != WAIT) && (ret != NOT_FOUND))
00150         {
00151             int len = LENGTH(ret);
00152             int type = TYPE(ret);
00153             const char* s = (type == TYPE_UNKNOWN)? YEL "UNK" DEF : 
00154                             (type == TYPE_TEXT)   ? MAG "TXT" DEF : 
00155                             (type == TYPE_OK   )  ? GRE "OK " DEF : 
00156                             (type == TYPE_ERROR)  ? RED "ERR" DEF : 
00157                             (type == TYPE_PLUS)   ? CYA " + " DEF : 
00158                             (type == TYPE_PROMPT) ? BLU " > " DEF : 
00159                                                         "..." ;
00160             ::printf("%10.3f AT read %s", _debugTime.read_ms()*0.001, s);
00161             dumpAtCmd(buf, len);
00162         }
00163 #endif        
00164         if ((ret != WAIT) && (ret != NOT_FOUND))
00165         {
00166             int type = TYPE(ret);
00167             // handle unsolicited commands here
00168             if (type == TYPE_PLUS) {
00169                 const char* cmd = buf+3;
00170                 int a, b, c, d, r;
00171                 char s[32];
00172                                                 
00173                 // SMS Command ---------------------------------
00174                 // +CNMI: <mem>,<index>
00175                 if (sscanf(cmd, "CMTI: \"%*[^\"]\",%d", &a) == 1) { 
00176                     TRACE("New SMS at index %d\r\n", a);
00177                 // Socket Specific Command ---------------------------------
00178                 // +UUSORD: <socket>,<length>
00179                 } else if ((sscanf(cmd, "UUSORD: %d,%d", &a, &b) == 2)) {
00180                     int socket = _findSocket(a);
00181                     TRACE("Socket %d: handle %d has %d bytes pending\r\n", socket, a, b);
00182                     if (socket != SOCKET_ERROR)
00183                         _sockets[socket].pending = b;
00184                 // +UUSORF: <socket>,<length>
00185                 } else if ((sscanf(cmd, "UUSORF: %d,%d", &a, &b) == 2)) {
00186                     int socket = _findSocket(a);
00187                     TRACE("Socket %d: handle %d has %d bytes pending\r\n", socket, a, b);
00188                     if (socket != SOCKET_ERROR)
00189                         _sockets[socket].pending = b;
00190                 // +UUSOCL: <socket>
00191                 } else if ((sscanf(cmd, "UUSOCL: %d", &a) == 1)) {
00192                     int socket = _findSocket(a);
00193                     TRACE("Socket %d: handle %d closed by remote host\r\n", socket, a);
00194                     if ((socket != SOCKET_ERROR) && _sockets[socket].connected)
00195                         _sockets[socket].connected = false;                                    
00196                 // +UULOC: <date>,<time>,<lat>,<long>,<alt>,<uncertainty>,<speed>, <direction>,<vertical_acc>,<sensor_used>,<SV_used>,<antenna_status>, <jamming_status>
00197                 }else if (sscanf(cmd, "UULOC: %d/%d/%d,%d:%d:%d.%*d,%f,%f,%d,%d,%d,%d,%d,%d,%d,%*d,%*d",\
00198                         &_loc[0].time.tm_mday, &_loc[0].time.tm_mon, &_loc[0].time.tm_year, &_loc[0].time.tm_hour, &_loc[0].time.tm_min, &_loc[0].time.tm_sec,\
00199                         &_loc[0].latitude, &_loc[0].longitude, &_loc[0].altitutude, &_loc[0].uncertainty, &_loc[0].speed, &_loc[0].direction, &_loc[0].verticalAcc, \
00200                         &b, &_loc[0].svUsed) == 15) {
00201                     TRACE("Parsed UULOC position at index 0\r\n");                                        
00202                     _loc[0].sensor = (b==0)? CELL_LAST : (b==1)? CELL_GNSS : (b==2)? CELL_LOCATE : (b==3)? CELL_HYBRID : CELL_LAST;
00203                     _loc[0].time.tm_mon -= 1;
00204                     _loc[0].time.tm_wday=0;
00205                     _loc[0].time.tm_yday=0;
00206                     _loc[0].validData = true;
00207                     _locExpPos=1;
00208                     _locRcvPos++;
00209                // +UULOC: <sol>,<num>,<sensor_used>,<date>,<time>,<lat>,<long>,<alt>,<uncertainty>,<speed>, <direction>,<vertical_acc>,,<SV_used>,<antenna_status>, <jamming_status>                              
00210                }else if (sscanf(cmd, "UULOC: %d,%d,%d,%d/%d/%d,%d:%d:%d.%*d,%f,%f,%d,%d,%d,%d,%d,%d,%*d,%*d",\
00211                         &a,&_locExpPos,&b, \
00212                         &_loc[CELL_MAX_HYP-1].time.tm_mday, &_loc[CELL_MAX_HYP-1].time.tm_mon, &_loc[CELL_MAX_HYP-1].time.tm_year, &_loc[CELL_MAX_HYP-1].time.tm_hour, &_loc[CELL_MAX_HYP-1].time.tm_min, &_loc[CELL_MAX_HYP-1].time.tm_sec,\
00213                         &_loc[CELL_MAX_HYP-1].latitude, &_loc[CELL_MAX_HYP-1].longitude, &_loc[CELL_MAX_HYP-1].altitutude, &_loc[CELL_MAX_HYP-1].uncertainty, &_loc[CELL_MAX_HYP-1].speed, &_loc[CELL_MAX_HYP-1].direction, &_loc[CELL_MAX_HYP-1].verticalAcc, \
00214                         &_loc[CELL_MAX_HYP-1].svUsed) == 17) {  
00215                     if (--a>=0){                         
00216                         TRACE("Parsed UULOC position at index %d\r\n",a);                    
00217                         memcpy(&_loc[a], &_loc[CELL_MAX_HYP-1], sizeof(*_loc)); 
00218                         _loc[a].sensor = (b==0)? CELL_LAST : (b==1)? CELL_GNSS : (b==2)? CELL_LOCATE : (b==3)? CELL_HYBRID : CELL_LAST;                                       
00219                         _loc[a].time.tm_mon -= 1;
00220                         _loc[a].time.tm_wday=0;
00221                         _loc[a].time.tm_yday=0;
00222                         _loc[a].validData = true;                    
00223                         _locRcvPos++;                                            
00224                     }
00225               //+UULOC: <sol>,<num>,<sensor_used>,<date>,<time>,<lat>,<long>,<alt>,<lat50>,<long50>,<major50>,<minor50>,<orientation50>,<confidence50>[,<lat95>,<long95>,<major95>,<minor95>,<orientation95>,<confidence95>]
00226                }else if (sscanf(cmd, "UULOC: %d,%d,%d,%d/%d/%d,%d:%d:%d.%*d,%f,%f,%d,%*f,%*f,%d,%*d,%*d,%*d",\
00227                         &a,&_locExpPos,&b, \
00228                         &_loc[CELL_MAX_HYP-1].time.tm_mday, &_loc[CELL_MAX_HYP-1].time.tm_mon, &_loc[CELL_MAX_HYP-1].time.tm_year, &_loc[CELL_MAX_HYP-1].time.tm_hour, &_loc[CELL_MAX_HYP-1].time.tm_min, &_loc[CELL_MAX_HYP-1].time.tm_sec,\
00229                         &_loc[CELL_MAX_HYP-1].latitude, &_loc[CELL_MAX_HYP-1].longitude, &_loc[CELL_MAX_HYP-1].altitutude, &_loc[CELL_MAX_HYP-1].uncertainty) == 13) {                    
00230                     if (--a>=0){    
00231                         TRACE("Parsed UULOC position at index %d\r\n",a);
00232                         memcpy(&_loc[a], &_loc[CELL_MAX_HYP-1], sizeof(*_loc));                                        
00233                         _loc[a].sensor = (b==0)? CELL_LAST : (b==1)? CELL_GNSS : (b==2)? CELL_LOCATE : (b==3)? CELL_HYBRID : CELL_LAST;
00234                         _loc[a].time.tm_mon -= 1;
00235                         _loc[a].time.tm_wday=0;
00236                         _loc[a].time.tm_yday=0;
00237                         _loc[a].validData = true;                    
00238                         _locRcvPos++;                    
00239                     }                              
00240                 // +UHTTPCR: <profile_id>,<op_code>,<param_val>
00241                 } else if ((sscanf(cmd, "UUHTTPCR: %d,%d,%d", &a, &b, &c) == 3)) {
00242                     _httpProfiles[a].cmd = b;          //command
00243                     _httpProfiles[a].result = c;       //result
00244                     TRACE("%s for profile %d: result code is %d\r\n", getHTTPcmd(b), a, c);
00245                 }
00246                 if (_dev.dev == DEV_LISA_C2) {
00247                     // CDMA Specific -------------------------------------------
00248                     // +CREG: <n><SID>,<NID>,<stat>
00249                     if (sscanf(cmd, "CREG: %*d,%d,%d,%d",&a,&b,&c) == 3) {
00250                         // _net.sid = a;
00251                         // _net.nid = b;
00252                         if      (c == 0) _net.csd = REG_NONE;     // not registered, home network
00253                         else if (c == 1) _net.csd = REG_HOME;     // registered, home network
00254                         else if (c == 2) _net.csd = REG_NONE;     // not registered, but MT is currently searching a new operator to register to
00255                         else if (c == 3) _net.csd = REG_DENIED;   // registration denied
00256                         else if (c == 5) _net.csd = REG_ROAMING;  // registered, roaming
00257                         _net.psd = _net.csd; // fake PSD registration (CDMA is always registered)
00258                         _net.act = ACT_CDMA;
00259                         // +CSS: <mode>[,<format>,<oper>[,<AcT>]]
00260                     } else if (sscanf(cmd, "CSS %*c,%2s,%*d",s) == 1) {
00261                         //_net.reg = (strcmp("Z", s) == 0) ? REG_UNKNOWN : REG_HOME;
00262                     }
00263                 } else {
00264                     // GSM/UMTS Specific -------------------------------------------
00265                     // +UUPSDD: <profile_id> 
00266                     if (sscanf(cmd, "UUPSDD: %d",&a) == 1) {
00267                         if (*PROFILE == a) _ip = NOIP;
00268                     } else {
00269                         // +CREG|CGREG: <n>,<stat>[,<lac>,<ci>[,AcT[,<rac>]]] // reply to AT+CREG|AT+CGREG
00270                         // +CREG|CGREG: <stat>[,<lac>,<ci>[,AcT[,<rac>]]]     // URC
00271                         b = 0xFFFF; c = 0xFFFFFFFF; d = -1;
00272                         r = sscanf(cmd, "%s %*d,%d,\"%X\",\"%X\",%d",s,&a,&b,&c,&d);
00273                         if (r <= 1)
00274                             r = sscanf(cmd, "%s %d,\"%X\",\"%X\",%d",s,&a,&b,&c,&d);
00275                         if (r >= 2) {
00276                             Reg *reg = !strcmp(s, "CREG:")  ? &_net.csd : 
00277                                        !strcmp(s, "CGREG:") ? &_net.psd : 
00278                                        !strcmp(s, "CEREG:") ? &_net.eps : NULL;
00279                             if (reg) {
00280                                 // network status
00281                                 if      (a == 0) *reg = REG_NONE;     // 0: not registered, home network
00282                                 else if (a == 1) *reg = REG_HOME;     // 1: registered, home network
00283                                 else if (a == 2) *reg = REG_NONE;     // 2: not registered, but MT is currently searching a new operator to register to
00284                                 else if (a == 3) *reg = REG_DENIED;   // 3: registration denied
00285                                 else if (a == 4) *reg = REG_UNKNOWN;  // 4: unknown
00286                                 else if (a == 5) *reg = REG_ROAMING;  // 5: registered, roaming
00287                                 else if (a == 6) *reg = REG_HOME;     // 6: registered, sms only, home
00288                                 if ((r >= 3) && (b != 0xFFFF))      _net.lac = b; // location area code
00289                                 if ((r >= 4) && (c != 0xFFFFFFFF))  _net.ci  = c; // cell ID                                                                                                
00290                                 // access technology
00291                                 if (r >= 5) {
00292                                     if      (d == 0) _net.act = ACT_GSM;      // 0: GSM
00293                                     else if (d == 1) _net.act = ACT_GSM;      // 1: GSM COMPACT
00294                                     else if (d == 2) _net.act = ACT_UTRAN;    // 2: UTRAN
00295                                     else if (d == 3) _net.act = ACT_EDGE;     // 3: GSM with EDGE availability
00296                                     else if (d == 4) _net.act = ACT_UTRAN;    // 4: UTRAN with HSDPA availability
00297                                     else if (d == 5) _net.act = ACT_UTRAN;    // 5: UTRAN with HSUPA availability
00298                                     else if (d == 6) _net.act = ACT_UTRAN;    // 6: UTRAN with HSDPA and HSUPA availability
00299                                     else if (d == 7) _net.act = ACT_LTE;      // 7: LTE
00300                                 }
00301                             }
00302                         }
00303                     }
00304                 }
00305             }
00306             if (cb) {
00307                 int len = LENGTH(ret);
00308                 int ret = cb(type, buf, len, param);
00309                 if (WAIT != ret)
00310                     return ret; 
00311             }
00312             if (type == TYPE_OK)
00313                 return RESP_OK;
00314             if (type == TYPE_ERROR)
00315                 return RESP_ERROR;
00316             if (type == TYPE_ERROR_CME)
00317                 return RESP_ERROR_CME;                
00318             if (type == TYPE_PROMPT)    
00319                 return RESP_PROMPT;
00320         }
00321         // relax a bit
00322         wait_ms(10); 
00323     }
00324     while (!TIMEOUT(timer, timeout_ms));
00325     return WAIT;
00326 }
00327 
00328 int MDMParser::_cbString(int type, const char* buf, int len, char* str)
00329 {
00330     if (str && (type == TYPE_UNKNOWN)) {
00331         if (sscanf(buf, "\r\n%s\r\n", str) == 1)
00332             /*nothing*/;
00333     }
00334     return WAIT;
00335 }
00336 
00337 int MDMParser::_cbInt(int type, const char* buf, int len, int* val)
00338 {
00339     if (val && (type == TYPE_UNKNOWN)) {
00340         if (sscanf(buf, "\r\n%d\r\n", val) == 1)
00341             /*nothing*/;
00342     }
00343     return WAIT;
00344 }
00345 
00346 // ----------------------------------------------------------------
00347 
00348 bool MDMParser::connect(
00349             const char* simpin, 
00350             const char* apn, const char* username, 
00351             const char* password, Auth auth,
00352             PinName pn)
00353 {
00354     bool ok = init(simpin, NULL, pn);  
00355 #ifdef MDM_DEBUG
00356     if (_debugLevel >= 1) dumpDevStatus(&_dev);
00357 #endif
00358     if (!ok)
00359         return false;
00360     ok = registerNet();
00361 #ifdef MDM_DEBUG
00362     if (_debugLevel >= 1) dumpNetStatus(&_net);
00363 #endif
00364     if (!ok)
00365         return false;
00366     IP ip = join(apn,username,password,auth);
00367 #ifdef MDM_DEBUG
00368     if (_debugLevel >= 1) dumpIp(ip);
00369 #endif
00370     if (ip == NOIP)
00371         return false; 
00372     return true;
00373 }
00374 
00375 bool MDMParser::init(const char* simpin, DevStatus* status, PinName pn)
00376 {
00377     int i = 10;
00378     LOCK();
00379     memset(&_dev, 0, sizeof(_dev));
00380     if (pn != NC) {
00381         INFO("Modem::wakeup\r\n");
00382         DigitalOut pin(pn, 1);
00383         while (i--) {
00384             // SARA-U2/LISA-U2 50..80us
00385             pin = 0; ::wait_us(50);
00386             pin = 1; ::wait_ms(10); 
00387             
00388             // SARA-G35 >5ms, LISA-C2 > 150ms, LEON-G2 >5ms
00389             pin = 0; ::wait_ms(150);
00390             pin = 1; ::wait_ms(100);
00391             
00392             // purge any messages 
00393             purge();
00394             
00395             // check interface
00396             sendFormated("AT\r\n");
00397             int r = waitFinalResp(NULL,NULL,1000);
00398             if(RESP_OK == r) break;
00399         }
00400         if (i < 0) {
00401             ERROR("No Reply from Modem\r\n");
00402             goto failure;
00403         }
00404     }
00405     _init = true;
00406     
00407     INFO("Modem::init\r\n");
00408     // echo off
00409     sendFormated("AT E0\r\n");
00410     if(RESP_OK != waitFinalResp())
00411         goto failure; 
00412     // enable verbose error messages
00413     sendFormated("AT+CMEE=2\r\n");
00414     if(RESP_OK != waitFinalResp())
00415         goto failure;
00416     // set baud rate
00417     sendFormated("AT+IPR=115200\r\n");
00418     if (RESP_OK != waitFinalResp())
00419         goto failure;
00420     // wait some time until baudrate is applied
00421     wait_ms(200); // SARA-G > 40ms
00422     // identify the module 
00423     sendFormated("ATI\r\n");
00424     if (RESP_OK != waitFinalResp(_cbATI, &_dev.dev))
00425         goto failure;
00426     if (_dev.dev == DEV_UNKNOWN)
00427         goto failure;
00428     // device specific init
00429     if (_dev.dev == DEV_LISA_C2) {
00430         // get the manufacturer
00431         sendFormated("AT+GMI\r\n");
00432         if (RESP_OK != waitFinalResp(_cbString, _dev.manu))
00433             goto failure;
00434         // get the model identification
00435         sendFormated("AT+GMM\r\n");
00436         if (RESP_OK != waitFinalResp(_cbString, _dev.model))
00437             goto failure;
00438         // get the sw version
00439         sendFormated("AT+GMR\r\n");
00440         if (RESP_OK != waitFinalResp(_cbString, _dev.ver))
00441             goto failure;
00442         // get the pseudo ESN or MEID
00443         sendFormated("AT+GSN\r\n");
00444         if (RESP_OK != waitFinalResp(_cbString, _dev.meid))
00445             goto failure;
00446 #if 0
00447         // enable power saving
00448         if (_dev.lpm != LPM_DISABLED) {
00449              // enable power saving (requires flow control, cts at least)
00450             sendFormated("AT+UPSV=1,1280\r\n");
00451             if (RESP_OK != waitFinalResp())
00452                 goto failure;  
00453             _dev.lpm = LPM_ACTIVE;
00454         }
00455 #endif
00456     } else {
00457         if ((_dev.dev == DEV_LISA_U2) || (_dev.dev == DEV_LEON_G2) || 
00458             (_dev.dev == DEV_TOBY_L2)) {
00459             // enable the network identification feature 
00460             sendFormated("AT+UGPIOC=20,2\r\n");
00461             if (RESP_OK != waitFinalResp())
00462                 goto failure;
00463         } else if ((_dev.dev == DEV_SARA_U2) || (_dev.dev == DEV_SARA_G35)) {
00464             // enable the network identification feature 
00465             sendFormated("AT+UGPIOC=16,2\r\n");
00466             if (RESP_OK != waitFinalResp())
00467                 goto failure;
00468         }
00469         // check the sim card
00470         for (int i = 0; (i < 5) && (_dev.sim != SIM_READY); i++) {
00471             sendFormated("AT+CPIN?\r\n");
00472             int ret = waitFinalResp(_cbCPIN, &_dev.sim);
00473             // having an error here is ok (sim may still be initializing)
00474             if ((RESP_OK != ret) && (RESP_ERROR != ret))
00475                 goto failure;
00476             // Enter PIN if needed
00477             if (_dev.sim == SIM_PIN) {
00478                 if (!simpin) {
00479                     ERROR("SIM PIN not available\r\n");
00480                     goto failure;
00481                 }
00482                 sendFormated("AT+CPIN=\"%s\"\r\n", simpin);
00483                 if (RESP_OK != waitFinalResp(_cbCPIN, &_dev.sim))
00484                     goto failure;
00485             } else if (_dev.sim != SIM_READY) {
00486                 wait_ms(1000);
00487             }
00488         }
00489         if (_dev.sim != SIM_READY) {
00490             if (_dev.sim == SIM_MISSING)
00491                 ERROR("SIM not inserted\r\n");
00492             goto failure;
00493         }
00494         // get the manufacturer
00495         sendFormated("AT+CGMI\r\n");
00496         if (RESP_OK != waitFinalResp(_cbString, _dev.manu))
00497             goto failure;
00498         // get the model identification
00499         sendFormated("AT+CGMM\r\n");
00500         if (RESP_OK != waitFinalResp(_cbString, _dev.model))
00501             goto failure;
00502         // get the version
00503         sendFormated("ATI9\r\n");
00504         if (RESP_OK != waitFinalResp(_cbString, _dev.ver))
00505             goto failure;
00506         // Returns the ICCID (Integrated Circuit Card ID) of the SIM-card. 
00507         // ICCID is a serial number identifying the SIM.
00508         sendFormated("AT+CCID\r\n");
00509         if (RESP_OK != waitFinalResp(_cbCCID, _dev.ccid))
00510             goto failure;
00511         // Returns the product serial number, IMEI (International Mobile Equipment Identity)
00512         sendFormated("AT+CGSN\r\n");
00513         if (RESP_OK != waitFinalResp(_cbString, _dev.imei))
00514             goto failure;
00515         // enable power saving
00516         if (_dev.lpm != LPM_DISABLED) {
00517              // enable power saving (requires flow control, cts at least)
00518             sendFormated("AT+UPSV=1\r\n");
00519             if (RESP_OK != waitFinalResp())
00520                 goto failure;  
00521             _dev.lpm = LPM_ACTIVE;
00522         }
00523         // enable the psd registration unsolicited result code
00524         sendFormated("AT+CGREG=2\r\n");
00525         if (RESP_OK != waitFinalResp())
00526             goto failure;
00527     } 
00528     // enable the network registration unsolicited result code
00529     sendFormated("AT+CREG=%d\r\n", (_dev.dev == DEV_LISA_C2) ? 1 : 2);
00530     if (RESP_OK != waitFinalResp())
00531         goto failure;
00532     // Setup SMS in text mode 
00533     sendFormated("AT+CMGF=1\r\n");
00534     if (RESP_OK != waitFinalResp())
00535         goto failure;
00536     // setup new message indication
00537     sendFormated("AT+CNMI=2,1\r\n");
00538     if (RESP_OK != waitFinalResp())
00539         goto failure;
00540     // Request IMSI (International Mobile Subscriber Identification)
00541     sendFormated("AT+CIMI\r\n");
00542     if (RESP_OK != waitFinalResp(_cbString, _dev.imsi))
00543         goto failure;
00544     if (status)
00545         memcpy(status, &_dev, sizeof(DevStatus));
00546     UNLOCK();
00547     return true; 
00548 failure:
00549     unlock();
00550     return false; 
00551 }
00552 
00553 bool MDMParser::powerOff(void)
00554 {
00555     bool ok = false;
00556     if (_init) {
00557         LOCK();
00558         INFO("Modem::powerOff\r\n");
00559         sendFormated("AT+CPWROFF\r\n");
00560         if (RESP_OK == waitFinalResp(NULL,NULL,120*1000)) {
00561             _init = false;
00562             ok = true;
00563         }
00564         UNLOCK();
00565     }
00566     return ok;
00567 }
00568 
00569 int MDMParser::_cbATI(int type, const char* buf, int len, Dev* dev)
00570 {
00571     if ((type == TYPE_UNKNOWN) && dev) {
00572         if      (strstr(buf, "SARA-G35"))   *dev = DEV_SARA_G35;
00573         else if (strstr(buf, "LISA-U200-03S")) *dev = DEV_LISA_U2_03S;
00574         else if (strstr(buf, "LISA-U2"))    *dev = DEV_LISA_U2;        
00575         else if (strstr(buf, "LISA-C2"))    *dev = DEV_LISA_C2;
00576         else if (strstr(buf, "SARA-U2"))    *dev = DEV_SARA_U2;
00577         else if (strstr(buf, "LEON-G2"))    *dev = DEV_LEON_G2;
00578         else if (strstr(buf, "TOBY-L2"))    *dev = DEV_TOBY_L2;
00579         else if (strstr(buf, "MPCI-L2"))    *dev = DEV_MPCI_L2;
00580     }
00581     return WAIT;
00582 }
00583 
00584 int MDMParser::_cbCPIN(int type, const char* buf, int len, Sim* sim)
00585 {
00586     if (sim) {
00587         if (type == TYPE_PLUS){
00588             char s[16];
00589             if (sscanf(buf, "\r\n+CPIN: %[^\r]\r\n", s) >= 1)
00590                 *sim = (0 == strcmp("READY", s)) ? SIM_READY : SIM_PIN;
00591         } else if (type == TYPE_ERROR) {
00592             if (strstr(buf, "+CME ERROR: SIM not inserted"))
00593                 *sim = SIM_MISSING;
00594         }
00595     }
00596     return WAIT;
00597 }
00598 
00599 int MDMParser::_cbCCID(int type, const char* buf, int len, char* ccid)
00600 {
00601     if ((type == TYPE_PLUS) && ccid){
00602         if (sscanf(buf, "\r\n+CCID: %[^\r]\r\n", ccid) == 1)
00603             /*TRACE("Got CCID: %s\r\n", ccid)*/;
00604     }
00605     return WAIT;
00606 }
00607 
00608 bool MDMParser::registerNet(NetStatus* status /*= NULL*/, int timeout_ms /*= 180000*/) 
00609 {
00610     Timer timer;
00611     timer.start();
00612     INFO("Modem::register\r\n");
00613     while (!checkNetStatus(status) && !TIMEOUT(timer, timeout_ms))
00614         wait_ms(1000);
00615     if (_net.csd == REG_DENIED) ERROR("CSD Registration Denied\r\n");
00616     if (_net.psd == REG_DENIED) ERROR("PSD Registration Denied\r\n");
00617     if (_net.eps == REG_DENIED) ERROR("EPS Registration Denied\r\n");
00618     return REG_OK(_net.csd) || REG_OK(_net.psd) || REG_OK(_net.eps);
00619 }
00620 
00621 bool MDMParser::checkNetStatus(NetStatus* status /*= NULL*/)
00622 {
00623     bool ok = false;
00624     LOCK();
00625     memset(&_net, 0, sizeof(_net));
00626     _net.lac = 0xFFFF;
00627     _net.ci = 0xFFFFFFFF;
00628     // check registration
00629     sendFormated("AT+CREG?\r\n");
00630     waitFinalResp();     // don't fail as service could be not subscribed 
00631     if (_dev.dev != DEV_LISA_C2) {
00632         // check PSD registration
00633         sendFormated("AT+CGREG?\r\n");
00634         waitFinalResp(); // don't fail as service could be not subscribed 
00635         if ((_dev.dev == DEV_TOBY_L2) ||  (_dev.dev == DEV_MPCI_L2)) {
00636             // check EPS network registration
00637             sendFormated("AT+CEREG?\r\n");
00638             waitFinalResp(); // don't fail as service could be not subscribed
00639         }
00640     }
00641     if (REG_OK(_net.csd) || REG_OK(_net.psd) || REG_OK(_net.eps))
00642     {
00643         // check modem specific status messages 
00644         if (_dev.dev == DEV_LISA_C2) {
00645             sendFormated("AT+CSS?\r\n");
00646             if (RESP_OK != waitFinalResp())
00647                 goto failure;
00648             while (1) {
00649                 // get the Telephone number
00650                 sendFormated("AT$MDN?\r\n");
00651                 if (RESP_OK != waitFinalResp(_cbString, _net.num))
00652                     goto failure;
00653                 // check if we have a Mobile Directory Number
00654                 if (*_net.num && (memcmp(_net.num, "000000", 6) != 0))
00655                     break;
00656                     
00657                 INFO("Device not yet activated\r\n");
00658                 INFO("Make sure you have a valid contract with the network operator for this device.\r\n");
00659                 // Check if the the version contains a V for Verizon 
00660                 // Verizon: E0.V.xx.00.xxR, 
00661                 // Sprint E0.S.xx.00.xxR
00662                 if (_dev.ver[3] == 'V') { 
00663                     int i;
00664                     INFO("Start device over-the-air activation (this can take a few minutes)\r\n");
00665                     sendFormated("AT+CDV=*22899\r\n");
00666                     i = 1;
00667                     if ((RESP_OK != waitFinalResp(_cbUACTIND, &i, 120*1000)) || (i == 1)) {
00668                         ERROR("Device over-the-air activation failed\r\n");
00669                         goto failure;
00670                     }
00671                     INFO("Device over-the-air activation successful\r\n");
00672                     
00673                     INFO("Start PRL over-the-air update (this can take a few minutes)\r\n");
00674                     sendFormated("AT+CDV=*22891\r\n");
00675                     i = 1;
00676                     if ((RESP_OK != waitFinalResp(_cbUACTIND, &i, 120*1000)) || (i == 1)) {
00677                         ERROR("PRL over-the-air update failed\r\n");
00678                         goto failure;
00679                     }
00680                     INFO("PRL over-the-air update successful\r\n");
00681                     
00682                 } else { 
00683                     // Sprint or Aeris 
00684                     INFO("Wait for OMA-DM over-the-air activation (this can take a few minutes)\r\n");
00685                     wait_ms(120*1000);
00686                 }
00687             }
00688             // get the the Network access identifier string
00689             char nai[64];
00690             sendFormated("AT$QCMIPNAI?\r\n");
00691             if (RESP_OK != waitFinalResp(_cbString, nai))
00692                 goto failure;
00693         } else {
00694             sendFormated("AT+COPS?\r\n");
00695             if (RESP_OK != waitFinalResp(_cbCOPS, &_net))
00696                 goto failure;
00697             // get the MSISDNs related to this subscriber
00698             sendFormated("AT+CNUM\r\n");
00699             if (RESP_OK != waitFinalResp(_cbCNUM, _net.num))
00700                 goto failure;
00701         }  
00702         // get the signal strength indication
00703         sendFormated("AT+CSQ\r\n");
00704         if (RESP_OK != waitFinalResp(_cbCSQ, &_net))
00705             goto failure;
00706     }
00707     if (status) {
00708         memcpy(status, &_net, sizeof(NetStatus));
00709     }
00710     ok = REG_DONE(_net.csd) && 
00711         (REG_DONE(_net.psd) || REG_DONE(_net.eps));
00712     UNLOCK();
00713     INFO(".");
00714     return ok;
00715 failure:
00716     unlock();
00717     return false;
00718 }
00719 
00720 int MDMParser::_cbCOPS(int type, const char* buf, int len, NetStatus* status)
00721 {
00722     if ((type == TYPE_PLUS) && status){
00723         int act = 99;
00724         int mode = 99;
00725         // +COPS: <mode>[,<format>,<oper>[,<AcT>]]
00726        if (sscanf(buf, "\r\n+COPS: %d,%*d,\"%[^\"]\",%d",&mode,status->opr,&act) >= 1) {
00727             if      (act == 0) status->act = ACT_GSM;      // 0: GSM, 
00728             else if (act == 2) status->act = ACT_UTRAN;    // 2: UTRAN
00729             else if (act == 7) status->act = ACT_LTE;    // 2: UTRAN
00730             if (mode == 0)  status->regStatus = COPS_AUTOMATIC_REG;
00731             else if (mode == 1) status->regStatus = COPS_MANUAL_REG;
00732             else if (mode == 2) status->regStatus = COPS_DISABLED_REG;
00733         }
00734     }
00735     return WAIT;
00736 }
00737 
00738 int MDMParser::_cbCNUM(int type, const char* buf, int len, char* num)
00739 {
00740     if ((type == TYPE_PLUS) && num){
00741         int a;
00742         if ((sscanf(buf, "\r\n+CNUM: \"My Number\",\"%31[^\"]\",%d", num, &a) == 2) && 
00743             ((a == 129) || (a == 145))) {
00744         }
00745     }
00746     return WAIT;
00747 }
00748                     
00749 int MDMParser::_cbCSQ(int type, const char* buf, int len, NetStatus* status)
00750 {
00751     if ((type == TYPE_PLUS) && status){
00752         int a,b;
00753         char _ber[] = { 49, 43, 37, 25, 19, 13, 7, 0 }; // see 3GPP TS 45.008 [20] subclause 8.2.4
00754         // +CSQ: <rssi>,<qual>
00755         if (sscanf(buf, "\r\n+CSQ: %d,%d",&a,&b) == 2) {
00756             if (a != 99) status->rssi = -113 + 2*a;  // 0: -113 1: -111 ... 30: -53 dBm with 2 dBm steps, 31: >-51 dBm
00757             if ((b != 99) && (b < sizeof(_ber))) status->ber = _ber[b];  // 
00758         }
00759     }
00760     return WAIT;
00761 }
00762 
00763 
00764 int MDMParser::_cbUACTIND(int type, const char* buf, int len, int* i)
00765 {
00766     if ((type == TYPE_PLUS) && i){
00767         int a;
00768         if (sscanf(buf, "\r\n+UACTIND: %d", &a) == 1) {
00769             *i = a;
00770         }
00771     }
00772     return WAIT;
00773 }
00774 
00775 // ----------------------------------------------------------------
00776 // internet connection 
00777 
00778 bool MDMParser::_activateProfile(const char* apn, const char* username, const char* password, Auth auth)
00779 {
00780     // Set up the APN
00781     if (*apn) {
00782         sendFormated("AT+UPSD=" PROFILE ",1,\"%s\"\r\n", apn);
00783         if (RESP_OK != waitFinalResp())
00784             return false;
00785     }
00786     if (*username) {
00787         sendFormated("AT+UPSD=" PROFILE ",2,\"%s\"\r\n", username);
00788         if (RESP_OK != waitFinalResp())
00789             return false;
00790     }
00791     if (*password) {
00792         sendFormated("AT+UPSD=" PROFILE ",3,\"%s\"\r\n", password);
00793         if (RESP_OK != waitFinalResp())
00794             return false;
00795     }
00796     // Set up the dynamic IP address assignment.
00797     sendFormated("AT+UPSD=" PROFILE ",7,\"0.0.0.0\"\r\n");
00798     if (RESP_OK != waitFinalResp())
00799         return false;
00800     // try different Authentication Protocols
00801     // 0 = none 
00802     // 1 = PAP (Password Authentication Protocol)
00803     // 2 = CHAP (Challenge Handshake Authentication Protocol)
00804     for (int i = AUTH_NONE; i <= AUTH_CHAP; i ++) {
00805         if ((auth == AUTH_DETECT) || (auth == i)) {
00806             // Set up the Authentication Protocol
00807             sendFormated("AT+UPSD=" PROFILE ",6,%d\r\n",i);
00808             if (RESP_OK != waitFinalResp())
00809                 return false;
00810             // Activate the profile and make connection
00811             sendFormated("AT+UPSDA=" PROFILE ",3\r\n");
00812             if (RESP_OK == waitFinalResp(NULL,NULL,150*1000))
00813                 return true;
00814         }
00815     }
00816     return false;
00817 }
00818 
00819 bool MDMParser::_activateProfileReuseExternal(void)
00820 {
00821     int cid = -1;
00822     sendFormated("AT+CGDCONT?\r\n");
00823     if (RESP_OK != waitFinalResp(_cbCGDCONT, &cid))
00824         return false;
00825     if (cid == -1)
00826         return false;
00827     // we found a context that provides us a valid IP so lets reuse it for the internal IP stack
00828     sendFormated("AT+UPSD=" PROFILE ",100,%d\r\n", cid);
00829     if (RESP_OK != waitFinalResp())
00830         return false;
00831     // Activate the profile and make connection
00832     sendFormated("AT+UPSDA=" PROFILE ",3\r\n");
00833     return (RESP_OK == waitFinalResp(NULL,NULL,150*1000));
00834 }
00835 
00836 bool MDMParser::_activateProfileByCid(int cid, const char* apn, const char* username, const char* password, Auth auth)
00837 {
00838     sendFormated("AT+CGDCONT=%d,\"IP\",\"%s\"\r\n", cid, apn);
00839     if (RESP_OK != waitFinalResp())
00840         return false;
00841     sendFormated("AT+UAUTHREQ=%d,%d,\"%s\",\"%s\"\r\n", cid, auth, username, password);
00842     if (RESP_OK != waitFinalResp())
00843         return false;
00844     sendFormated("AT+UPSD=" PROFILE ",100,%d\r\n", cid);
00845     if (RESP_OK != waitFinalResp())
00846         return false;
00847     // Activate the profile and make connection
00848     sendFormated("AT+UPSDA=" PROFILE ",3\r\n");
00849     return (RESP_OK == waitFinalResp(NULL,NULL,150*1000));
00850 }
00851  
00852 int MDMParser::_cbCGDCONT(int type, const char* buf, int len, int* cid)
00853 {
00854     // accept with and without leading \r\n in +CGDCONT:
00855     if ((type == TYPE_PLUS) && (buf[0] == '\r') && (buf[1] == '\n') && (len >= 2))
00856         buf += 2, len -= 2, type = TYPE_UNKNOWN;
00857     if (type == TYPE_UNKNOWN) {
00858         int a,b,c,d,t;
00859         //+CGDCONT: <cid>,"IP","<apn name>","<ip adr>",0,0,0,0,0,0
00860         if (sscanf(buf, "+CGDCONT: %d,\"IP\",\"%*[^\"]\",\"" IPSTR "\",%*d,%*d,%*d,%*d,%*d,%*d", &t, &a,&b,&c,&d) == 5) {
00861             if (IPADR(a,b,c,d) != NOIP) 
00862                 *cid = t;
00863         }
00864     }
00865     return WAIT;
00866 }
00867 
00868 MDMParser::IP MDMParser::join(const char* apn /*= NULL*/, const char* username /*= NULL*/, 
00869                               const char* password /*= NULL*/, Auth auth /*= AUTH_DETECT*/)
00870 {
00871     LOCK();
00872     INFO("Modem::join\r\n");
00873     _ip = NOIP;
00874     if (_dev.dev == DEV_LISA_C2) {
00875         // make a dumy dns lookup (which will fail, so ignore the result) 
00876         sendFormated("AT+UDNSRN=0,\"u-blox.com\"\r\n");
00877         waitFinalResp(); 
00878         // This fake lookup will enable the IP connection and we 
00879         // should have an IP after this, so we check it
00880         
00881         //Get local IP address
00882         sendFormated("AT+CMIP?\r\n");
00883         if (RESP_OK != waitFinalResp(_cbCMIP, &_ip))
00884             goto failure;
00885     
00886     } else { 
00887         // check gprs attach status 
00888         sendFormated("AT+CGATT=1\r\n");
00889         if (RESP_OK != waitFinalResp(NULL,NULL,3*60*1000)) 
00890             goto failure;
00891         // Check the profile
00892         int a = 0;
00893         bool force = true;
00894         sendFormated("AT+UPSND=" PROFILE ",8\r\n");
00895         if (RESP_OK != waitFinalResp(_cbUPSND, &a))
00896             goto failure;
00897         if (a == 1 && force) {
00898             // disconnect the profile already if it is connected 
00899             sendFormated("AT+UPSDA=" PROFILE ",4\r\n");
00900             if (RESP_OK != waitFinalResp(NULL,NULL,40*1000))
00901                 goto failure;
00902             a = 0;
00903         }
00904         if (a == 0) {
00905             bool ok = false;
00906             // try to lookup the apn settings from our local database by mccmnc
00907             const char* config = NULL;
00908             if (!apn && !username && !password)
00909                 config = apnconfig(_dev.imsi);
00910             do {
00911                 if (config) {
00912                     apn      = _APN_GET(config);
00913                     username = _APN_GET(config);
00914                     password = _APN_GET(config);
00915                 }
00916                 // convert pointer to empty strings
00917                 apn      = apn      ? apn      : "";
00918                 username = username ? username : "";
00919                 password = password ? password : "";
00920                 auth = (*username && *password) ? auth : AUTH_NONE;
00921                 TRACE("Testing APN Settings(\"%s\",\"%s\",\"%s\",%d)\r\n", apn, username, password, auth);
00922                 if ((_dev.dev != DEV_TOBY_L2) && (_dev.dev != DEV_MPCI_L2))
00923                     ok = _activateProfile(apn, username, password, auth);
00924                 else {
00925                     ok = _activateProfileReuseExternal();
00926                     if (ok) 
00927                         TRACE("Reusing External Context\r\n");
00928                     else
00929                         ok = _activateProfileByCid(1, apn, username, password, auth);
00930                 }
00931             } while (!ok && config && *config); // maybe use next setting ? 
00932             if (!ok) {
00933                 ERROR("Your modem APN/password/username may be wrong\r\n");
00934                 goto failure;
00935             }
00936         }
00937         //Get local IP address
00938         sendFormated("AT+UPSND=" PROFILE ",0\r\n");
00939         if (RESP_OK != waitFinalResp(_cbUPSND, &_ip))
00940             goto failure;
00941     }
00942     UNLOCK();
00943     return _ip;
00944 failure: 
00945     unlock();
00946     return NOIP;
00947 }
00948 
00949 int MDMParser::_cbUDOPN(int type, const char* buf, int len, char* mccmnc)
00950 {
00951     if ((type == TYPE_PLUS) && mccmnc) {
00952         if (sscanf(buf, "\r\n+UDOPN: 0,\"%[^\"]\"", mccmnc) == 1)
00953             ;
00954     }
00955     return WAIT;
00956 }
00957 
00958 int MDMParser::_cbCMIP(int type, const char* buf, int len, IP* ip)
00959 {
00960     if ((type == TYPE_UNKNOWN) && ip) {
00961         int a,b,c,d;
00962         if (sscanf(buf, "\r\n" IPSTR, &a,&b,&c,&d) == 4)
00963             *ip = IPADR(a,b,c,d);
00964     }
00965     return WAIT;
00966 }
00967         
00968 int MDMParser::_cbUPSND(int type, const char* buf, int len, int* act)
00969 {
00970     if ((type == TYPE_PLUS) && act) {
00971         if (sscanf(buf, "\r\n+UPSND: %*d,%*d,%d", act) == 1)
00972             /*nothing*/;
00973     }
00974     return WAIT;
00975 }
00976 
00977 int MDMParser::_cbUPSND(int type, const char* buf, int len, IP* ip)
00978 {
00979     if ((type == TYPE_PLUS) && ip) {
00980         int a,b,c,d;
00981         // +UPSND=<profile_id>,<param_tag>[,<dynamic_param_val>]
00982         if (sscanf(buf, "\r\n+UPSND: " PROFILE ",0,\"" IPSTR "\"", &a,&b,&c,&d) == 4)
00983             *ip = IPADR(a,b,c,d);
00984     }
00985     return WAIT;
00986 }
00987 
00988 int MDMParser::_cbUDNSRN(int type, const char* buf, int len, IP* ip)
00989 {
00990     if ((type == TYPE_PLUS) && ip) {
00991         int a,b,c,d;
00992         if (sscanf(buf, "\r\n+UDNSRN: \"" IPSTR "\"", &a,&b,&c,&d) == 4)
00993             *ip = IPADR(a,b,c,d);
00994     }
00995     return WAIT;
00996 }
00997 
00998 bool MDMParser::disconnect(void)
00999 {
01000     bool ok = false;
01001     LOCK();
01002     INFO("Modem::disconnect\r\n");
01003     if (_ip != NOIP) {
01004         if (_dev.dev == DEV_LISA_C2) {
01005             // There something to do here
01006             _ip = NOIP;
01007             ok = true;
01008         } else { 
01009             sendFormated("AT+UPSDA=" PROFILE ",4\r\n");
01010             if (RESP_OK != waitFinalResp()) {
01011                 _ip = NOIP;
01012                 ok = true;
01013             }
01014         }
01015     }
01016     UNLOCK();
01017     return ok;
01018 }
01019 
01020 MDMParser::IP MDMParser::gethostbyname(const char* host)
01021 {
01022     IP ip = NOIP; 
01023     int a,b,c,d;
01024     if (sscanf(host, IPSTR, &a,&b,&c,&d) == 4)
01025         ip = IPADR(a,b,c,d);
01026     else {
01027         LOCK();
01028         sendFormated("AT+UDNSRN=0,\"%s\"\r\n", host);
01029         if (RESP_OK != waitFinalResp(_cbUDNSRN, &ip))
01030             ip = NOIP;
01031         UNLOCK();
01032     }
01033     return ip;
01034 }
01035 
01036 // ----------------------------------------------------------------
01037 // sockets
01038 
01039 int MDMParser::_cbUSOCR(int type, const char* buf, int len, int* handle)
01040 {
01041     if ((type == TYPE_PLUS) && handle) {
01042         // +USOCR: socket
01043         if (sscanf(buf, "\r\n+USOCR: %d", handle) == 1)
01044             /*nothing*/;  
01045     }
01046     return WAIT;
01047 }
01048 
01049 int MDMParser::socketSocket(IpProtocol ipproto, int port)
01050 {
01051     int socket;
01052     LOCK();
01053     // find an free socket
01054     socket = _findSocket();
01055     TRACE("socketSocket(%d)\r\n", ipproto);
01056     if (socket != SOCKET_ERROR) {
01057         if (ipproto == IPPROTO_UDP) {
01058             // sending port can only be set on 2G/3G modules
01059             if ((port != -1) && (_dev.dev != DEV_LISA_C2)) {
01060                 sendFormated("AT+USOCR=17,%d\r\n", port);
01061             } else {
01062                 sendFormated("AT+USOCR=17\r\n");
01063             }
01064         } else /*(ipproto == IPPROTO_TCP)*/ {
01065             sendFormated("AT+USOCR=6\r\n");
01066         } 
01067         int handle = SOCKET_ERROR;
01068         if ((RESP_OK == waitFinalResp(_cbUSOCR, &handle)) && 
01069             (handle != SOCKET_ERROR)) {
01070             TRACE("Socket %d: handle %d was created\r\n", socket, handle);
01071             _sockets[socket].handle     = handle;
01072             _sockets[socket].timeout_ms = TIMEOUT_BLOCKING;
01073             _sockets[socket].connected  = false;
01074             _sockets[socket].pending    = 0;
01075         }
01076         else
01077             socket = SOCKET_ERROR;
01078     }
01079     UNLOCK();
01080     return socket;
01081 }
01082 
01083 bool MDMParser::socketConnect(int socket, const char * host, int port)
01084 {
01085     IP ip = gethostbyname(host);
01086     if (ip == NOIP)
01087         return false;
01088     // connect to socket
01089     bool ok = false; 
01090     LOCK();
01091     if (ISSOCKET(socket) && (!_sockets[socket].connected)) {
01092         TRACE("socketConnect(%d,%s,%d)\r\n", socket,host,port);
01093         sendFormated("AT+USOCO=%d,\"" IPSTR "\",%d\r\n", _sockets[socket].handle, IPNUM(ip), port);
01094         if (RESP_OK == waitFinalResp())
01095             ok = _sockets[socket].connected = true;
01096     }
01097     UNLOCK();
01098     return ok;
01099 }
01100 
01101 bool MDMParser::socketIsConnected(int socket)
01102 {
01103     bool ok = false;
01104     LOCK();
01105     ok = ISSOCKET(socket) && _sockets[socket].connected;
01106     TRACE("socketIsConnected(%d) %s\r\n", socket, ok?"yes":"no");
01107     UNLOCK();
01108     return ok;
01109 }
01110 
01111 bool MDMParser::socketSetBlocking(int socket, int timeout_ms)
01112 {
01113     bool ok = false;
01114     LOCK();
01115     TRACE("socketSetBlocking(%d,%d)\r\n", socket,timeout_ms);
01116     if (ISSOCKET(socket)) {
01117         _sockets[socket].timeout_ms = timeout_ms;
01118         ok = true;
01119     }
01120     UNLOCK();
01121     return ok;
01122 }
01123 
01124 bool  MDMParser::socketClose(int socket)
01125 {
01126     bool ok = false;
01127     LOCK();
01128     if (ISSOCKET(socket) && _sockets[socket].connected) {
01129         TRACE("socketClose(%d)\r\n", socket);
01130         sendFormated("AT+USOCL=%d\r\n", _sockets[socket].handle);
01131         if (RESP_OK == waitFinalResp()) {
01132             _sockets[socket].connected = false;
01133             ok = true;
01134         }
01135     }
01136     UNLOCK();
01137     return ok;
01138 }
01139 
01140 bool  MDMParser::socketFree(int socket)
01141 {
01142     // make sure it is closed
01143     socketClose(socket);
01144     bool ok = true;
01145     LOCK();
01146     if (ISSOCKET(socket)) {
01147         TRACE("socketFree(%d)\r\n",  socket);
01148         _sockets[socket].handle     = SOCKET_ERROR;
01149         _sockets[socket].timeout_ms = TIMEOUT_BLOCKING;
01150         _sockets[socket].connected  = false;
01151         _sockets[socket].pending    = 0;
01152         ok = true;
01153     }
01154     UNLOCK();
01155     return ok;
01156 }
01157 
01158 #define USO_MAX_WRITE 1024 //!< maximum number of bytes to write to socket
01159 
01160 int MDMParser::socketSend(int socket, const char * buf, int len)
01161 {
01162     TRACE("socketSend(%d,,%d)\r\n", socket,len);
01163     int cnt = len;
01164     while (cnt > 0) {
01165         int blk = USO_MAX_WRITE;
01166         if (cnt < blk) 
01167             blk = cnt;
01168         bool ok = false;
01169         LOCK();
01170         if (ISSOCKET(socket)) {
01171             sendFormated("AT+USOWR=%d,%d\r\n",_sockets[socket].handle,blk);
01172             if (RESP_PROMPT == waitFinalResp()) {
01173                 wait_ms(50);
01174                 send(buf, blk);
01175                 if (RESP_OK == waitFinalResp()) 
01176                     ok = true;
01177             }
01178         }
01179         UNLOCK();
01180         if (!ok) 
01181             return SOCKET_ERROR;
01182         buf += blk;
01183         cnt -= blk;
01184     }
01185     return (len - cnt);
01186 }
01187 
01188 int MDMParser::socketSendTo(int socket, IP ip, int port, const char * buf, int len)
01189 {
01190     TRACE("socketSendTo(%d," IPSTR ",%d,,%d)\r\n", socket,IPNUM(ip),port,len);
01191     int cnt = len;
01192     while (cnt > 0) {
01193         int blk = USO_MAX_WRITE;
01194         if (cnt < blk) 
01195             blk = cnt;
01196         bool ok = false;
01197         LOCK();
01198         if (ISSOCKET(socket)) {
01199             sendFormated("AT+USOST=%d,\"" IPSTR "\",%d,%d\r\n",_sockets[socket].handle,IPNUM(ip),port,blk);
01200             if (RESP_PROMPT == waitFinalResp()) {
01201                 wait_ms(50);
01202                 send(buf, blk);
01203                 if (RESP_OK == waitFinalResp())
01204                     ok = true;
01205             }
01206         }
01207         UNLOCK();
01208         if (!ok)
01209             return SOCKET_ERROR;
01210         buf += blk;
01211         cnt -= blk;
01212     }
01213     return (len - cnt);
01214 }
01215 
01216 int MDMParser::socketReadable(int socket)
01217 {
01218     int pending = SOCKET_ERROR;
01219     LOCK();
01220     if (ISSOCKET(socket) && _sockets[socket].connected) {
01221         TRACE("socketReadable(%d)\r\n", socket);
01222         // allow to receive unsolicited commands 
01223         waitFinalResp(NULL, NULL, 0);
01224         if (_sockets[socket].connected)
01225            pending = _sockets[socket].pending; 
01226     }
01227     UNLOCK();
01228     return pending;
01229 }
01230 
01231 int MDMParser::_cbUSORD(int type, const char* buf, int len, char* out)
01232 {
01233     if ((type == TYPE_PLUS) && out) {
01234         int sz, sk;
01235         if ((sscanf(buf, "\r\n+USORD: %d,%d,", &sk, &sz) == 2) && 
01236             (buf[len-sz-2] == '\"') && (buf[len-1] == '\"')) {
01237             memcpy(out, &buf[len-1-sz], sz);
01238         }
01239     }
01240     return WAIT;
01241 }
01242 
01243 int MDMParser::socketRecv(int socket, char* buf, int len)
01244 {
01245     int cnt = 0;
01246     TRACE("socketRecv(%d,,%d)\r\n", socket, len);
01247 #ifdef MDM_DEBUG
01248     memset(buf, '\0', len);
01249 #endif
01250     Timer timer;
01251     timer.start();
01252     while (len) {
01253         int blk = MAX_SIZE; // still need space for headers and unsolicited  commands 
01254         if (len < blk) blk = len;
01255         bool ok = false;        
01256         LOCK();
01257         if (ISSOCKET(socket)) {
01258             if (_sockets[socket].connected) {
01259                 if (_sockets[socket].pending < blk)
01260                     blk = _sockets[socket].pending;
01261                 if (blk > 0) {
01262                     sendFormated("AT+USORD=%d,%d\r\n",_sockets[socket].handle, blk);
01263                     if (RESP_OK == waitFinalResp(_cbUSORD, buf)) {
01264                         _sockets[socket].pending -= blk;
01265                         len -= blk;
01266                         cnt += blk;
01267                         buf += blk;
01268                         ok = true;
01269                     }
01270                 } else if (!TIMEOUT(timer, _sockets[socket].timeout_ms)) {
01271                     ok = (WAIT == waitFinalResp(NULL,NULL,0)); // wait for URCs
01272                 } else {
01273                     len = 0;
01274                     ok = true;
01275                 }
01276             } else {
01277                 len = 0;
01278                 ok = true;
01279             }
01280         }
01281         UNLOCK();
01282         if (!ok) {
01283             TRACE("socketRecv: ERROR\r\n");
01284             return SOCKET_ERROR;
01285         }
01286     }
01287     TRACE("socketRecv: %d \"%*s\"\r\n", cnt, cnt, buf-cnt);
01288     return cnt;
01289 }
01290 
01291 int MDMParser::_cbUSORF(int type, const char* buf, int len, USORFparam* param)
01292 {
01293     if ((type == TYPE_PLUS) && param) {
01294         int sz, sk, p, a,b,c,d;
01295         int r = sscanf(buf, "\r\n+USORF: %d,\"" IPSTR "\",%d,%d,", 
01296             &sk,&a,&b,&c,&d,&p,&sz);
01297         if ((r == 7) && (buf[len-sz-2] == '\"') && (buf[len-1] == '\"')) {
01298             memcpy(param->buf, &buf[len-1-sz], sz);
01299             param->ip = IPADR(a,b,c,d);
01300             param->port = p;
01301         }
01302     }
01303     return WAIT;
01304 }
01305 
01306 int MDMParser::socketRecvFrom(int socket, IP* ip, int* port, char* buf, int len)
01307 {
01308     int cnt = 0;
01309     TRACE("socketRecvFrom(%d,,%d)\r\n", socket, len);
01310 #ifdef MDM_DEBUG
01311     memset(buf, '\0', len);
01312 #endif
01313     Timer timer;
01314     timer.start();
01315     while (len) {
01316         int blk = MAX_SIZE; // still need space for headers and unsolicited commands 
01317         if (len < blk) blk = len;
01318         bool ok = false;        
01319         LOCK();
01320         if (ISSOCKET(socket)) {
01321             if (_sockets[socket].pending < blk)
01322                 blk = _sockets[socket].pending;
01323             if (blk > 0) {
01324                 sendFormated("AT+USORF=%d,%d\r\n",_sockets[socket].handle, blk);
01325                 USORFparam param;
01326                 param.buf = buf;
01327                 if (RESP_OK == waitFinalResp(_cbUSORF, &param)) {
01328                     _sockets[socket].pending -= blk;
01329                     *ip = param.ip;
01330                     *port = param.port;
01331                     len -= blk;
01332                     cnt += blk;
01333                     buf += blk;
01334                     len = 0; // done 
01335                     ok = true;
01336                 }
01337             } else if (!TIMEOUT(timer, _sockets[socket].timeout_ms)) {
01338                 ok = (WAIT == waitFinalResp(NULL,NULL,0)); // wait for URCs
01339             } else {
01340                 len = 0; // no more data and socket closed or timed-out
01341                 ok = true;
01342             }
01343         }
01344         UNLOCK();
01345         if (!ok) {
01346             TRACE("socketRecv: ERROR\r\n");
01347             return SOCKET_ERROR;
01348         }
01349     }
01350     timer.stop();
01351     timer.reset();
01352     TRACE("socketRecv: %d \"%*s\"\r\n", cnt, cnt, buf-cnt);
01353     return cnt;
01354 }
01355 
01356 int MDMParser::_findSocket(int handle) {
01357     for (int socket = 0; socket < NUMSOCKETS; socket ++) {
01358         if (_sockets[socket].handle == handle)
01359             return socket;
01360     }
01361     return SOCKET_ERROR;
01362 }
01363 
01364 // ----------------------------------------------------------------
01365 // HTTP
01366 
01367 int MDMParser::httpFindProfile()
01368 {
01369     int profile = HTTP_PROF_ERROR;  //default value
01370     LOCK();
01371     // find a free HTTP profile 
01372     profile = _findProfile();
01373     TRACE("httpFindProfile: profile is %d\r\n", profile);
01374     if (profile != HTTP_PROF_ERROR) {
01375         _httpProfiles[profile].handle     = 1;
01376         _httpProfiles[profile].timeout_ms = TIMEOUT_BLOCKING;
01377         _httpProfiles[profile].pending    = false;
01378         _httpProfiles[profile].cmd        = -1;
01379         _httpProfiles[profile].result     = -1;
01380     }
01381     UNLOCK();
01382     return profile;
01383 }
01384 
01385 int MDMParser::_findProfile(int handle) {
01386     for (int profile = 0; profile < NUMPROFILES; profile++) {
01387         if (_httpProfiles[profile].handle == handle)
01388             return profile;
01389     }
01390     return HTTP_PROF_ERROR;
01391 }
01392 
01393 bool MDMParser::httpSetBlocking(int profile, int timeout_ms)
01394 {
01395     bool ok = false;
01396     LOCK();
01397     TRACE("httpSetBlocking(%d,%d)\r\n", profile, timeout_ms);
01398     if (ISPROFILE(profile)) {
01399         _httpProfiles[profile].timeout_ms = timeout_ms;
01400         ok = true;
01401     }
01402     UNLOCK();
01403     return ok;
01404 }
01405 
01406 bool MDMParser::httpSetProfileForCmdMng(int profile)
01407 {
01408     bool ok = false;
01409     LOCK();
01410     TRACE("httpSetProfileForCmdMng(%d)\r\n", profile);
01411     if (ISPROFILE(profile)) {
01412         _httpProfiles[profile].pending = true;
01413         _httpProfiles[profile].result = -1;
01414         ok = true;
01415     }
01416     UNLOCK();
01417     return ok;
01418 }
01419 
01420 bool MDMParser::httpFreeProfile(int profile)
01421 {
01422     bool ok = true;
01423     LOCK();
01424     if (ISPROFILE(profile)) {
01425         TRACE("httpFreeProfile(%d)\r\n", profile);
01426         _httpProfiles[profile].handle     = HTTP_PROF_ERROR;
01427         _httpProfiles[profile].timeout_ms = TIMEOUT_BLOCKING;
01428         _httpProfiles[profile].pending    = false;
01429         _httpProfiles[profile].cmd        = -1;
01430         _httpProfiles[profile].result     = -1;
01431         ok = true;
01432     }
01433     UNLOCK();
01434     return ok;
01435 }
01436 
01437 bool MDMParser::httpResetProfile(int httpProfile)
01438 {
01439     bool ok = false;
01440     
01441     LOCK();
01442     TRACE("httpResetProfile(%d)\r\n", httpProfile);
01443     sendFormated("AT+UHTTP=%d\r\n", httpProfile);
01444     if (RESP_OK == waitFinalResp())
01445         ok = true;
01446     UNLOCK();
01447     
01448     return ok;
01449 }
01450 
01451 bool MDMParser::httpSetPar(int httpProfile, HttpOpCode httpOpCode, const char * httpInPar)
01452 {
01453     bool ok = false;
01454     IP ip = NOIP;
01455     int httpInParNum = 0;
01456     
01457     LOCK();
01458     TRACE("httpSetPar(%d,%d,\"%s\")\r\n", httpProfile, httpOpCode, httpInPar);
01459     switch(httpOpCode){
01460         case HTTP_IP_ADDRESS:   //0
01461             ip = gethostbyname(httpInPar);
01462             if (ip == NOIP)
01463                 return false;
01464             
01465             sendFormated("AT+UHTTP=%d,%d,\"" IPSTR "\"\r\n", httpProfile, httpOpCode, IPNUM(ip));
01466             if (RESP_OK == waitFinalResp())
01467                 ok = true;
01468             break;
01469             
01470         case HTTP_SERVER_NAME:  //1
01471         case HTTP_USER_NAME:    //2
01472         case HTTP_PASSWORD:     //3
01473             sendFormated("AT+UHTTP=%d,%d,\"%s\"\r\n", httpProfile, httpOpCode, httpInPar);
01474             if (RESP_OK == waitFinalResp())
01475                 ok = true;
01476             break;
01477         
01478         case HTTP_AUTH_TYPE:    //4    
01479         case HTTP_SERVER_PORT:  //5
01480             httpInParNum = atoi(httpInPar);
01481             sendFormated("AT+UHTTP=%d,%d,%d\r\n", httpProfile, httpOpCode, httpInParNum); 
01482             if (RESP_OK == waitFinalResp())
01483                 ok = true;
01484             break;
01485             
01486         case HTTP_SECURE:       //6
01487             if(_dev.dev != DEV_LISA_C2)
01488             {
01489                 httpInParNum = atoi(httpInPar);
01490                 sendFormated("AT+UHTTP=%d,%d,%d\r\n", httpProfile, httpOpCode, httpInParNum); 
01491                 if (RESP_OK == waitFinalResp())
01492                     ok = true;
01493             } else {
01494                 TRACE("httpSetPar: HTTP secure option not supported by module\r\n");
01495                 ok = false;
01496             }
01497             break;
01498             
01499         default:
01500             TRACE("httpSetPar: unknown httpOpCode %s\r\n", httpOpCode);
01501             ok = false; 
01502             break;   
01503     }
01504     UNLOCK();
01505     return ok;
01506 }
01507 
01508 bool MDMParser::httpCommand(int httpProfile, HttpCmd httpCmdCode, const char* httpPath, const char* httpOut, \
01509                             const char* httpIn, int httpContentType, const char* httpCustomPar, char* buf, int len)
01510 {   
01511     bool ok = false;
01512 #ifdef MDM_DEBUG
01513     memset(buf, '\0', len);
01514 #endif
01515     LOCK();
01516     TRACE("%s\r\n", getHTTPcmd(httpCmdCode));
01517     switch (httpCmdCode) 
01518     {   
01519         case HTTP_HEAD:
01520             sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\"\r\n", httpProfile, HTTP_HEAD, httpPath, httpOut);
01521             break;
01522             
01523         case HTTP_GET:
01524             sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\"\r\n", httpProfile, HTTP_GET, httpPath, httpOut);
01525             break;
01526             
01527         case HTTP_DELETE:
01528             sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\"\r\n", httpProfile, HTTP_DELETE, httpPath, httpOut);
01529             break;
01530             
01531         case HTTP_PUT:
01532             //in this case the parameter httpIn is a filename
01533             sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\"\r\n", httpProfile, HTTP_PUT, httpPath, httpOut, httpIn);
01534             break;
01535             
01536         case HTTP_POST_FILE:
01537             //in this case the parameter httpIn is a filename
01538             if(_dev.dev != DEV_LISA_C2)
01539             {
01540                 if(httpContentType != 6)
01541                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d\r\n", \
01542                                   httpProfile, HTTP_POST_FILE, httpPath, httpOut, httpIn, httpContentType);
01543                 else
01544                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d,%d\r\n", \
01545                                   httpProfile, HTTP_POST_FILE, httpPath, httpOut, httpIn, httpContentType, httpCustomPar);
01546             }
01547             else{
01548                 if((httpContentType != 5) && (httpContentType != 6) && (httpCustomPar == NULL))
01549                 {
01550                     //parameters values consistent with the AT commands specs of LISA-C200
01551                     //(in particular httpCustomPar has to be not defined)
01552                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d\r\n", \
01553                                   httpProfile, HTTP_POST_FILE, httpPath, httpOut, httpIn, httpContentType);
01554                 } else {
01555                     TRACE("httpCommand: command not supported by module");
01556                     return ok;  //error
01557                 }
01558             }
01559             break;
01560             
01561         case HTTP_POST_DATA:
01562             //in this case the parameter httpIn is a string containing data
01563             if(_dev.dev != DEV_LISA_C2)
01564             {
01565                 if(httpContentType != 6)
01566                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d\r\n", \
01567                                   httpProfile, HTTP_POST_DATA, httpPath, httpOut, httpIn, httpContentType);
01568                 else
01569                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d,%d\r\n", \
01570                                   httpProfile, HTTP_POST_DATA, httpPath, httpOut, httpIn, httpContentType, httpCustomPar);
01571             } else {
01572                 if((httpContentType != 5) && (httpContentType != 6) && (httpCustomPar == NULL))
01573                 {
01574                     //parameters values consistent with the AT commands specs of LISA-C200
01575                     //(in particular httpCustomPar has to be not defined)
01576                     sendFormated("AT+UHTTPC=%d,%d,\"%s\",\"%s\",\"%s\",%d\r\n", \
01577                                   httpProfile, HTTP_POST_DATA, httpPath, httpOut, httpIn, httpContentType);
01578                 } else {
01579                     TRACE("httpCommand: command not supported by module");
01580                     return ok;  //error
01581                 }
01582             }    
01583             break;
01584             
01585         default:
01586             TRACE("HTTP command not recognized\r\n");
01587             return ok;  //error
01588     }
01589     
01590     if (RESP_OK == waitFinalResp())
01591     {
01592         Timer timer;
01593         timer.start();
01594         httpSetProfileForCmdMng(httpProfile);
01595         while (_httpProfiles[httpProfile].pending)  //waiting for unsolicited
01596         {     
01597             ok = false;  //reset variable  
01598             if(_httpProfiles[httpProfile].result != -1)
01599             {    
01600                 //received unsolicited: starting its analysis 
01601                 _httpProfiles[httpProfile].pending = false;   
01602                 if(_httpProfiles[httpProfile].result == 1)
01603                 {
01604                     //HTTP command successfully executed
01605                     if(_dev.dev != DEV_LISA_C2)
01606                     {
01607                         TRACE("httpCommand: reading files with a dimension " \
01608                               "also greater than MAX_SIZE bytes\r\n");
01609                         if(readFileNew(httpOut,buf,len) >=0 )
01610                             ok = true;
01611                     } else {
01612                         TRACE("httpCommand: reading files with a dimension " \
01613                               "less than MAX_SIZE bytes, otherwise error\r\n");
01614                         if(readFile(httpOut,buf,len) >=0 )
01615                             ok = true;
01616                     }
01617                 } else {
01618                     //HTTP command not successfully executed
01619                     ok = false;
01620                 }
01621             } else if (!TIMEOUT(timer, _httpProfiles[httpProfile].timeout_ms)) {
01622                 ok = (WAIT == waitFinalResp(NULL,NULL,0)); // wait for URCs
01623             } else  {
01624                 //not received unsolicited and expired timer
01625                 TRACE("httpCommand: not received unsolicited and expired timer\r\n");
01626                 ok = false;
01627             }
01628             if (!ok) {
01629                 TRACE("%s: ERROR\r\n", getHTTPcmd(httpCmdCode));
01630                 _httpProfiles[httpProfile].pending = false;  //no more while loops
01631             }
01632         }
01633     }
01634     UNLOCK();
01635     return ok;
01636 }
01637 
01638 const char* MDMParser::getHTTPcmd(int httpCmdCode) 
01639 {
01640     switch (httpCmdCode) 
01641     {
01642         case HTTP_HEAD:
01643             return "HTTP HEAD command";
01644         case HTTP_GET:
01645             return "HTTP GET command";
01646         case HTTP_DELETE:
01647             return "HTTP DELETE command";
01648         case HTTP_PUT:
01649             return "HTTP PUT command";
01650         case HTTP_POST_FILE:
01651             return "HTTP POST file command";
01652         case HTTP_POST_DATA:
01653             return "HTTP POST data command";
01654         default:
01655             return "HTTP command not recognized";
01656    }
01657 }
01658 
01659 // ----------------------------------------------------------------
01660 
01661 int MDMParser::_cbCMGL(int type, const char* buf, int len, CMGLparam* param)
01662 { 
01663     if ((type == TYPE_PLUS) && param && param->num) {
01664         // +CMGL: <ix>,...
01665         int ix;
01666         if (sscanf(buf, "\r\n+CMGL: %d,", &ix) == 1)
01667         {
01668             *param->ix++ = ix;
01669             param->num--;
01670         }
01671     }
01672     return WAIT;
01673 }
01674 
01675 int MDMParser::smsList(const char* stat /*= "ALL"*/, int* ix /*=NULL*/, int num /*= 0*/) {
01676     int ret = -1;
01677     LOCK();
01678     sendFormated("AT+CMGL=\"%s\"\r\n", stat);
01679     CMGLparam param;
01680     param.ix = ix;
01681     param.num = num;
01682     if (RESP_OK == waitFinalResp(_cbCMGL, &param))
01683         ret = num - param.num;
01684     UNLOCK();
01685     return ret;
01686 }
01687 
01688 bool MDMParser::smsSend(const char* num, const char* buf)
01689 {
01690     bool ok = false;
01691     LOCK();
01692     sendFormated("AT+CMGS=\"%s\"\r\n",num);
01693     if (RESP_PROMPT == waitFinalResp(NULL,NULL,150*1000)) {
01694         send(buf, strlen(buf));
01695         const char ctrlZ = 0x1A;
01696         send(&ctrlZ, sizeof(ctrlZ));
01697         ok = (RESP_OK == waitFinalResp());
01698     }
01699     UNLOCK();
01700     return ok;
01701 }
01702 
01703 bool MDMParser::smsDelete(int ix)
01704 {
01705     bool ok = false;
01706     LOCK();
01707     sendFormated("AT+CMGD=%d\r\n",ix);
01708     ok = (RESP_OK == waitFinalResp());
01709     UNLOCK();
01710     return ok;
01711 }
01712 
01713 int MDMParser::_cbCMGR(int type, const char* buf, int len, CMGRparam* param)
01714 {
01715     if (param) {
01716         if (type == TYPE_PLUS) {
01717             if (sscanf(buf, "\r\n+CMGR: \"%*[^\"]\",\"%[^\"]", param->num) == 1) {
01718             }
01719         } else if ((type == TYPE_UNKNOWN) && (buf[len-2] == '\r') && (buf[len-1] == '\n')) {
01720             memcpy(param->buf, buf, len-2);
01721             param->buf[len-2] = '\0';
01722         }
01723     }
01724     return WAIT;
01725 }
01726 
01727 bool MDMParser::smsRead(int ix, char* num, char* buf, int len)
01728 {
01729     bool ok = false;
01730     LOCK();
01731     CMGRparam param;
01732     param.num = num;
01733     param.buf = buf;
01734     sendFormated("AT+CMGR=%d\r\n",ix);
01735     ok = (RESP_OK == waitFinalResp(_cbCMGR, &param));
01736     UNLOCK();
01737     return ok;
01738 }
01739    
01740 // ----------------------------------------------------------------
01741   
01742 int MDMParser::_cbCUSD(int type, const char* buf, int len, char* resp)
01743 {
01744     if ((type == TYPE_PLUS) && resp) {
01745         // +USD: \"%*[^\"]\",\"%[^\"]\",,\"%*[^\"]\",%d,%d,%d,%d,\"*[^\"]\",%d,%d"..);
01746         if (sscanf(buf, "\r\n+CUSD: %*d,\"%[^\"]\",%*d", resp) == 1) {
01747             /*nothing*/            
01748         }
01749     }
01750     return WAIT;
01751 }  
01752 
01753 bool MDMParser::ussdCommand(const char* cmd, char* buf)
01754 {
01755     bool ok = false;
01756     LOCK();
01757     *buf = '\0';
01758     if (_dev.dev != DEV_LISA_C2) {
01759         sendFormated("AT+CUSD=1,\"%s\"\r\n",cmd);
01760         ok = (RESP_OK == waitFinalResp(_cbCUSD, buf));
01761     }
01762     UNLOCK();
01763     return ok;
01764 }
01765 
01766 // ----------------------------------------------------------------
01767    
01768 int MDMParser::_cbUDELFILE(int type, const char* buf, int len, void*)
01769 {
01770     if ((type == TYPE_ERROR) && strstr(buf, "+CME ERROR: FILE NOT FOUND")) 
01771         return RESP_OK; // file does not exist, so all ok...
01772     return WAIT;
01773 }  
01774 
01775 bool MDMParser::delFile(const char* filename)
01776 {
01777     bool ok = false;
01778     LOCK();
01779     sendFormated("AT+UDELFILE=\"%s\"\r\n", filename);
01780     ok = (RESP_OK == waitFinalResp(_cbUDELFILE));
01781     UNLOCK();
01782     return ok;
01783 }
01784 
01785 int MDMParser::writeFile(const char* filename, const char* buf, int len)
01786 {
01787     bool ok = false;
01788     LOCK();
01789     sendFormated("AT+UDWNFILE=\"%s\",%d\r\n", filename, len);
01790     if (RESP_PROMPT == waitFinalResp()) {
01791         send(buf, len);
01792         ok = (RESP_OK == waitFinalResp());
01793     }
01794     UNLOCK();
01795     return ok ? len : -1;
01796 }
01797 
01798 int MDMParser::readFile(const char* filename, char* buf, int len)
01799 {
01800     URDFILEparam param;
01801     param.filename = filename;
01802     param.buf = buf; 
01803     param.sz = len; 
01804     param.len = 0;
01805     LOCK();
01806     sendFormated("AT+URDFILE=\"%s\"\r\n", filename, len);
01807     if (RESP_OK != waitFinalResp(_cbURDFILE, &param))
01808         param.len = -1;
01809     UNLOCK();
01810     return param.len;
01811 }
01812 
01813 int MDMParser::_cbURDFILE(int type, const char* buf, int len, URDFILEparam* param)
01814 {
01815     if ((type == TYPE_PLUS) && param && param->filename && param->buf) {
01816         char filename[48];
01817         int sz;
01818         if ((sscanf(buf, "\r\n+URDFILE: \"%[^\"]\",%d,", filename, &sz) == 2) && 
01819             (0 == strcmp(param->filename, filename)) &&
01820             (buf[len-sz-2] == '\"') && (buf[len-1] == '\"')) {
01821             param->len = (sz < param->sz) ? sz : param->sz;
01822             memcpy(param->buf, &buf[len-1-sz], param->len);
01823         }
01824     }
01825     return WAIT;
01826 }
01827 
01828 //The following function is useful for reading files with a dimension greater than MAX_SIZE bytes
01829 int MDMParser::readFileNew(const char* filename, char* buf, int len)
01830 {   
01831     int countBytes = -1;  //counter for file reading (default value)
01832     
01833     if(_dev.dev != DEV_LISA_C2)
01834     {
01835         //retrieve information about the file, in particular its size
01836         int filesize = infoFile(filename);
01837         TRACE("readFileNew: filename is %s; filesize is %d\r\n", filename, filesize);
01838         
01839         if (len < filesize)
01840             TRACE("readFileNew: WARNING. Buffer dimension is %d bytes," \
01841                   "while file size is %d bytes\r\n", len, filesize);
01842         
01843         if (filesize > 0)
01844         {
01845 #ifdef MDM_DEBUG
01846             memset(buf, '\0', len);
01847 #endif
01848             int offset = 0;              //start reading from 0
01849             int blockSize = MAX_SIZE;    //still need space for headers and unsolicited commands
01850             int bytesToRead = filesize;  //bytes to read 
01851             
01852             while (bytesToRead)
01853             {    
01854                 bool ok = false;
01855                 
01856                 if (bytesToRead < blockSize)
01857                     blockSize = bytesToRead;
01858                 
01859                 LOCK();
01860                 if (blockSize > 0) {
01861                             
01862                     sendFormated("AT+URDBLOCK=\"%s\",%d,%d\r\n", filename, offset, blockSize);
01863                     
01864                     if (RESP_OK == waitFinalResp(_cbURDBLOCK, buf)) {
01865                         bytesToRead -= blockSize;
01866                         offset += blockSize;
01867                         buf += blockSize;
01868                         ok = true;
01869                     } else {
01870                         //error condition
01871                         countBytes = -1;
01872                         ok = false;
01873                     }
01874                 }
01875                 UNLOCK();
01876                 
01877                 if (!ok) {
01878                     TRACE("readFileNew: ERROR\r\n");
01879                     return countBytes;  //in this case countBytes is -1
01880                 }
01881             }
01882             
01883             countBytes = offset;  //total read bytes
01884             return countBytes;
01885         }
01886     } else {
01887         TRACE("httpCommand: command not supported by module"); 
01888     }
01889     return countBytes;  //it could be 0 or -1 (possible error)    
01890 }
01891 
01892 int MDMParser::_cbURDBLOCK(int type, const char* buf, int len, char* out)
01893 {   
01894     char fileNameRes[48]; 
01895     int sizeRes;
01896     
01897     if ((type == TYPE_PLUS) && out) {
01898         if ((sscanf(buf, "\r\n+URDBLOCK: \"%[^\"]\",%d,", fileNameRes, &sizeRes) == 2) &&
01899             (buf[len-sizeRes-2] == '\"') && (buf[len-1] == '\"')) {
01900             memcpy(out, &buf[len-1-sizeRes], sizeRes);
01901         }
01902     }
01903     
01904     return WAIT;
01905 }
01906 
01907 int MDMParser::infoFile(const char* filename)
01908 {
01909     int infoFile = 0;  //default value
01910     
01911     LOCK();
01912     sendFormated("AT+ULSTFILE=2,\"%s\"\r\n", filename);
01913     if (RESP_OK != waitFinalResp(_cbULSTFILE, &infoFile))
01914         infoFile = -1;  //error condition    
01915     UNLOCK();
01916     
01917     return infoFile;
01918 }
01919 
01920 int MDMParser::_cbULSTFILE(int type, const char* buf, int len, int* infoFile)
01921 { 
01922     if (infoFile) {
01923         if (type == TYPE_PLUS) {
01924             if (sscanf(buf, "\r\n+ULSTFILE: %d\r\n", infoFile) == 1) {
01925             }
01926         }
01927     }
01928     return WAIT;
01929 }
01930 
01931 // ----------------------------------------------------------------
01932 int MDMParser::cellLocSrvTcp(const char* token, const char* server_1, const char* server_2, int days/* = 14*/, \
01933         int period/* = 4*/, int resolution/* = 1*/)
01934 {
01935     bool ok = false;
01936     LOCK();
01937     if (_dev.dev == DEV_LISA_U2_03S || _dev.dev == DEV_SARA_U2 ){
01938         sendFormated("AT+UGSRV=\"%s\",\"%s\",\"%s\"\r\n", server_1, server_2, token, days, period, resolution);
01939         ok = (RESP_OK == waitFinalResp());
01940     } else
01941         ERROR("Command not supported\r\n"); 
01942     UNLOCK();
01943     return ok;
01944 }
01945 
01946 int MDMParser::cellLocSrvUdp(const char* server_1 /*= "cell-live1.services.u-blox.com"*/, int port /*= 46434*/, \
01947         int latency/* = 1000*/, int mode/* = 0*/)
01948 {
01949     bool ok = false;
01950     LOCK();
01951     if (_dev.dev != DEV_TOBY_L2){
01952         sendFormated("AT+UGAOP=\"%s\",%d,%d,%d\r\n", server_1, port, latency, mode);
01953         ok = (RESP_OK == waitFinalResp());
01954     } else
01955         ERROR("Command not supported\r\n"); 
01956     UNLOCK();
01957     return ok;
01958 }
01959 
01960 int MDMParser::cellLocUnsol(int mode)
01961 {
01962     bool ok = false;
01963     LOCK();
01964     if (_dev.dev == DEV_LISA_U2_03S){
01965         sendFormated("AT+ULOCIND=%d\r\n", mode);
01966         ok = (RESP_OK == waitFinalResp());
01967     } else
01968         ERROR("Command not supported\r\n"); 
01969     UNLOCK();
01970     return ok;
01971 }
01972 
01973 int MDMParser::cellLocConfig(int scanMode)
01974 {
01975     bool ok = false;
01976     LOCK();
01977     if (_dev.dev != DEV_TOBY_L2){
01978         sendFormated("AT+ULOCCELL=%d\r\n", scanMode);
01979         ok = (RESP_OK == waitFinalResp());    
01980     }else
01981         ERROR("Command not supported\r\n"); 
01982     UNLOCK();
01983     return ok;
01984 }
01985 
01986 int MDMParser::cellLocRequest(CellSensType sensor, int timeout, int accuracy, CellRespType type/* =1*/, int hypotesis/* =1*/)
01987 {
01988     bool ok = false;
01989     
01990     if (hypotesis > 1 && type != CELL_MULTIHYP){
01991         ERROR("Num hypotesis is not set accordelying to CellRespType\r\n");
01992         return false;
01993         }        
01994     if (hypotesis > CELL_MAX_HYP){
01995         ERROR("Number of hypotesis is too big\r\n");
01996         return false;  
01997     }        
01998     LOCK();      
01999     _locRcvPos=0;
02000     _locExpPos=0;
02001     for (int i=0; i < hypotesis; i++)
02002         _loc[i].validData = false;          
02003     if (_dev.dev == DEV_LISA_U2_03S){
02004         sendFormated("AT+ULOC=2,%d,%d,%d,%d,%d\r\n", sensor, type, timeout, accuracy, hypotesis);        
02005         ok = (RESP_OK == waitFinalResp());
02006     } else if (_dev.dev != DEV_TOBY_L2){
02007         sendFormated("AT+ULOC=2,%d,1,%d,%d\r\n",  sensor, timeout, accuracy);
02008         ok = (RESP_OK == waitFinalResp());
02009     } else
02010         ERROR("Command not supported\r\n");  
02011     UNLOCK();
02012     return ok;
02013 }  
02014 int MDMParser::cellLocGetRes()
02015 {
02016     return _locRcvPos;
02017 }
02018 int MDMParser::cellLocGetExpRes()
02019 {
02020     int res=0;
02021     waitFinalResp(NULL,NULL,0);
02022     LOCK();
02023     if (_locRcvPos>0)
02024         res = _locExpPos;
02025     UNLOCK();
02026     return res;
02027 }
02028 
02029 int MDMParser::cellLocGetData(CellLocData *data, int index/*=0*/){
02030     
02031     if (!_loc[index].validData)
02032           return false;
02033     LOCK(); 
02034     memcpy(data, &_loc[index], sizeof(*_loc));
02035     UNLOCK();
02036     return true;
02037 }
02038 
02039 // ----------------------------------------------------------------
02040 bool MDMParser::setDebug (int level) 
02041 {
02042 #ifdef MDM_DEBUG
02043     _debugLevel = (level < -1) ? -1 : 
02044                   (level >  3) ?  3 : 
02045                                    level;
02046 #endif
02047     return _debugLevel == level;
02048 }
02049 
02050 void MDMParser::dumpDevStatus(MDMParser::DevStatus* status, 
02051             _DPRINT dprint, void* param) 
02052 {
02053     dprint(param, "\r\nModem::devStatus\r\n");
02054     const char* txtDev[] = { "Unknown",  "SARA-G35", "LISA-U2", "LISA-U2-03S", "LISA-C2", 
02055                              "SARA-U2",  "LEON-G2",  "TOBY-L2", "MPCI-L2" };
02056     if (status->dev < sizeof(txtDev)/sizeof(*txtDev) && (status->dev != DEV_UNKNOWN))
02057         dprint(param, "  Device:       %s\r\n", txtDev[status->dev]);
02058     const char* txtLpm[] = { "Disabled", "Enabled", "Active" };
02059     if (status->lpm < sizeof(txtLpm)/sizeof(*txtLpm))
02060         dprint(param, "  Power Save:   %s\r\n", txtLpm[status->lpm]);
02061     const char* txtSim[] = { "Unknown", "Missing", "Pin", "Ready" };
02062     if (status->sim < sizeof(txtSim)/sizeof(*txtSim) && (status->sim != SIM_UNKNOWN))
02063         dprint(param, "  SIM:          %s\r\n", txtSim[status->sim]);
02064     if (*status->ccid)  
02065         dprint(param, "  CCID:         %s\r\n", status->ccid);
02066     if (*status->imei) 
02067         dprint(param, "  IMEI:         %s\r\n", status->imei);
02068     if (*status->imsi)  
02069         dprint(param, "  IMSI:         %s\r\n", status->imsi);
02070     if (*status->meid) 
02071         dprint(param, "  MEID:         %s\r\n", status->meid); // LISA-C
02072     if (*status->manu) 
02073         dprint(param, "  Manufacturer: %s\r\n", status->manu);
02074     if (*status->model)  
02075         dprint(param, "  Model:        %s\r\n", status->model);
02076     if (*status->ver)  
02077         dprint(param, "  Version:      %s\r\n", status->ver);
02078 }
02079 
02080 void MDMParser::dumpNetStatus(MDMParser::NetStatus *status,
02081             _DPRINT dprint, void* param)
02082 {
02083     dprint(param, "Modem::netStatus\r\n");
02084     const char* txtReg[] = { "Unknown", "Denied", "None", "Home", "Roaming" };
02085     if (status->csd < sizeof(txtReg)/sizeof(*txtReg) && (status->csd != REG_UNKNOWN))
02086         dprint(param, "  CSD Registration:   %s\r\n", txtReg[status->csd]);
02087     if (status->psd < sizeof(txtReg)/sizeof(*txtReg) && (status->psd != REG_UNKNOWN))
02088         dprint(param, "  PSD Registration:   %s\r\n", txtReg[status->psd]);
02089     if (status->eps < sizeof(txtReg)/sizeof(*txtReg) && (status->eps != REG_UNKNOWN))
02090         dprint(param, "  EPS Registration:   %s\r\n", txtReg[status->eps]);
02091     const char* txtAct[] = { "Unknown", "GSM", "Edge", "3G", "CDMA", "LTE" };
02092     if (status->act < sizeof(txtAct)/sizeof(*txtAct) && (status->act != ACT_UNKNOWN))
02093         dprint(param, "  Access Technology:  %s\r\n", txtAct[status->act]);
02094     if (status->rssi) 
02095         dprint(param, "  Signal Strength:    %d dBm\r\n", status->rssi);
02096     if (status->ber) 
02097         dprint(param, "  Bit Error Rate:     %d\r\n", status->ber);
02098     if (*status->opr)  
02099         dprint(param, "  Operator:           %s\r\n", status->opr);
02100     if (status->lac != 0xFFFF)  
02101         dprint(param, "  Location Area Code: %04X\r\n", status->lac);
02102     if (status->ci != 0xFFFFFFFF)  
02103         dprint(param, "  Cell ID:            %08X\r\n", status->ci);
02104     if (*status->num)  
02105         dprint(param, "  Phone Number:       %s\r\n", status->num);
02106 }
02107 
02108 void MDMParser::dumpIp(MDMParser::IP ip,
02109             _DPRINT dprint, void* param) 
02110 {
02111     if (ip != NOIP)
02112         dprint(param, "Modem:IP " IPSTR "\r\n", IPNUM(ip));
02113 }
02114     
02115 // ----------------------------------------------------------------
02116 int MDMParser::_parseMatch(Pipe<char> * pipe, int len, const char* sta, const char* end)
02117 {
02118     int o = 0;
02119     if (sta) {
02120         while (*sta) {
02121             if (++o > len)                  return WAIT;
02122             char ch = pipe->next();
02123             if (*sta++ != ch)               return NOT_FOUND;
02124         }
02125     }
02126     if (!end)                               return o; // no termination
02127     // at least any char
02128     if (++o > len)                      return WAIT;
02129     pipe->next();
02130     // check the end     
02131     int x = 0;
02132     while (end[x]) {
02133         if (++o > len)                      return WAIT;
02134         char ch = pipe->next();
02135         x = (end[x] == ch) ? x + 1 : 
02136             (end[0] == ch) ? 1 : 
02137                             0;
02138     }
02139     return o;
02140 }
02141 
02142 int MDMParser::_parseFormated(Pipe<char> * pipe, int len, const char* fmt)
02143 {
02144     int o = 0;
02145     int num = 0;
02146     if (fmt) {
02147         while (*fmt) {
02148             if (++o > len)                  return WAIT;
02149             char ch = pipe->next();
02150             if (*fmt == '%') {
02151                 fmt++;
02152                 if (*fmt == 'd') { // numeric
02153                     fmt ++;
02154                     num = 0;
02155                     while (ch >= '0' && ch <= '9') {
02156                         num = num * 10 + (ch - '0'); 
02157                         if (++o > len)      return WAIT;
02158                         ch = pipe->next();
02159                     }
02160                 }   
02161                 else if (*fmt == 'c') { // char buffer (takes last numeric as length)
02162                     fmt ++;
02163                     while (num --) {
02164                         if (++o > len)      return WAIT;
02165                         ch = pipe->next();
02166                     }   
02167                 }
02168                 else if (*fmt == 's') {
02169                     fmt ++;
02170                     if (ch != '\"')         return NOT_FOUND;
02171                     do {
02172                         if (++o > len)      return WAIT;
02173                         ch = pipe->next();
02174                     } while (ch != '\"');
02175                     if (++o > len)          return WAIT;
02176                     ch = pipe->next();
02177                 }
02178             }
02179             if (*fmt++ != ch)               return NOT_FOUND;
02180         }
02181     }
02182     return o; 
02183 }
02184 
02185 int MDMParser::_getLine(Pipe<char> * pipe, char* buf, int len)
02186 {
02187     int unkn = 0;
02188     int sz = pipe->size();
02189     int fr = pipe->free();
02190     if (len > sz)
02191         len = sz;
02192     while (len > 0)
02193     {
02194         static struct { 
02195               const char* fmt;                              int type; 
02196         } lutF[] = {
02197             { "\r\n+USORD: %d,%d,\"%c\"",                   TYPE_PLUS       },
02198             { "\r\n+USORF: %d,\"" IPSTR "\",%d,%d,\"%c\"",  TYPE_PLUS       },
02199             { "\r\n+URDFILE: %s,%d,\"%c\"",                 TYPE_PLUS       },
02200             { "\r\n+URDBLOCK: %s,%d,\"%c\"",                TYPE_PLUS       },
02201         };
02202         static struct { 
02203               const char* sta;          const char* end;    int type; 
02204         } lut[] = {
02205             { "\r\nOK\r\n",             NULL,               TYPE_OK         },
02206             { "\r\nERROR\r\n",          NULL,               TYPE_ERROR      },
02207             { "\r\n+CME ERROR:",        "\r\n",             TYPE_ERROR_CME      }, 
02208             { "\r\n+CMS ERROR:",        "\r\n",             TYPE_ERROR      },
02209             { "\r\nRING\r\n",           NULL,               TYPE_RING       },
02210             { "\r\nCONNECT\r\n",        NULL,               TYPE_CONNECT    },
02211             { "\r\nNO CARRIER\r\n",     NULL,               TYPE_NOCARRIER  },
02212             { "\r\nNO DIALTONE\r\n",    NULL,               TYPE_NODIALTONE },
02213             { "\r\nBUSY\r\n",           NULL,               TYPE_BUSY       },
02214             { "\r\nNO ANSWER\r\n",      NULL,               TYPE_NOANSWER   },
02215             { "\r\n+",                  "\r\n",             TYPE_PLUS       },
02216             { "\r\n@",                  NULL,               TYPE_PROMPT     }, // Sockets
02217             { "\r\n>",                  NULL,               TYPE_PROMPT     }, // SMS
02218             { "\n>",                    NULL,               TYPE_PROMPT     }, // File
02219         };
02220         for (int i = 0; i < sizeof(lutF)/sizeof(*lutF); i ++) {
02221             pipe->set(unkn);
02222             int ln = _parseFormated(pipe, len, lutF[i].fmt);
02223             if (ln == WAIT && fr)                       
02224                 return WAIT;
02225             if ((ln != NOT_FOUND) && (unkn > 0))  
02226                 return TYPE_UNKNOWN | pipe->get (buf, unkn);
02227             if (ln > 0)
02228                 return lutF[i].type  | pipe->get (buf, ln);
02229         }
02230         for (int i = 0; i < sizeof(lut)/sizeof(*lut); i ++) {
02231             pipe->set(unkn);
02232             int ln = _parseMatch(pipe, len, lut[i].sta, lut[i].end);
02233             if (ln == WAIT && fr)                       
02234                 return WAIT;
02235             if ((ln != NOT_FOUND) && (unkn > 0))  
02236                 return TYPE_UNKNOWN | pipe->get (buf, unkn);
02237             if (ln > 0)
02238                 return lut[i].type | pipe->get (buf, ln);
02239         }
02240         // UNKNOWN
02241         unkn ++;
02242         len--;
02243     }
02244     return WAIT;
02245 }
02246 
02247 // ----------------------------------------------------------------
02248 // Serial Implementation 
02249 // ----------------------------------------------------------------
02250 
02251 /*! Helper Dev Null Device 
02252     Small helper class used to shut off stderr/stdout. Sometimes stdin/stdout
02253     is shared with the serial port of the modem. Having printfs inbetween the 
02254     AT commands you cause a failure of the modem.
02255 */
02256 class DevNull : public Stream {
02257 public: 
02258     DevNull() : Stream(_name+1) { }             //!< Constructor
02259     void claim(const char* mode, FILE* file) 
02260         { freopen(_name, mode, file); }         //!< claim a stream
02261 protected:
02262     virtual int _getc()         { return EOF; } //!< Nothing
02263     virtual int _putc(int c)    { return c; }   //!< Discard
02264     static const char* _name;                   //!< File name
02265 };
02266 const char* DevNull::_name = "/null";  //!< the null device name
02267 static      DevNull null;              //!< the null device
02268 
02269 MDMSerial::MDMSerial(PinName tx /*= MDMTXD*/, PinName rx /*= MDMRXD*/, 
02270             int baudrate /*= MDMBAUD*/,
02271 #if DEVICE_SERIAL_FC
02272             PinName rts /*= MDMRTS*/, PinName cts /*= MDMCTS*/, 
02273 #endif
02274             int rxSize /*= 256*/, int txSize /*= 128*/) : 
02275             SerialPipe(tx, rx, rxSize, txSize) 
02276 {
02277     if (rx == USBRX) 
02278         null.claim("r", stdin);
02279     if (tx == USBTX) {
02280         null.claim("w", stdout);
02281         null.claim("w", stderr);
02282 #ifdef MDM_DEBUG
02283         _debugLevel = -1;
02284 #endif
02285     }
02286 #ifdef TARGET_UBLOX_C027
02287     _onboard = (tx == MDMTXD) && (rx == MDMRXD);
02288     if (_onboard)
02289        c027_mdm_powerOn(false);
02290 #endif
02291     baud(baudrate);
02292 #if DEVICE_SERIAL_FC
02293     if ((rts != NC) || (cts != NC))
02294     {
02295         Flow flow = (cts == NC) ? RTS :
02296                     (rts == NC) ? CTS : RTSCTS ;
02297         set_flow_control(flow, rts, cts);
02298         if (cts != NC) _dev.lpm = LPM_ENABLED;
02299     }
02300 #endif
02301 }
02302 
02303 MDMSerial::~MDMSerial(void)
02304 {
02305     powerOff();
02306 #ifdef TARGET_UBLOX_C027
02307     if (_onboard)
02308         c027_mdm_powerOff();
02309 #endif
02310 }
02311 
02312 int MDMSerial::_send(const void* buf, int len)   
02313 { 
02314     return put((const char*)buf, len, true/*=blocking*/);
02315 }
02316 
02317 int MDMSerial::getLine(char* buffer, int length)
02318 {
02319     return _getLine(&_pipeRx, buffer, length);
02320 }
02321 
02322 // ----------------------------------------------------------------
02323 // USB Implementation 
02324 // ----------------------------------------------------------------
02325 
02326 #ifdef HAVE_MDMUSB
02327 MDMUsb::MDMUsb(void)                             
02328 { 
02329 #ifdef MDM_DEBUG
02330     _debugLevel = 1;
02331 #endif    
02332 #ifdef TARGET_UBLOX_C027
02333     _onboard = true;
02334     c027_mdm_powerOn(true);
02335 #endif
02336 }
02337 
02338 MDMUsb::~MDMUsb(void)
02339 {
02340     powerOff();
02341 #ifdef TARGET_UBLOX_C027
02342     if (_onboard)
02343         c027_mdm_powerOff();
02344 #endif
02345 }
02346 
02347 int MDMUsb::_send(const void* buf, int len)      { return 0; }
02348 
02349 int MDMUsb::getLine(char* buffer, int length)    { return NOT_FOUND; }
02350 
02351 #endif