C027 updated to work with latest mBed libraries

Dependents:   Cellular_HelloMQTT UBLOXModemDriver UBLOXMQTTDriver

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