HTTP/HTTPS Client Library for the X-NUCLEO-IDW01M1v2 wifi board.

Dependents:   HTTPClient_HelloWorld_IDW01M1 wifigianluigi HTTPClient_HelloWorld_IDW01M1_Fabio_Ricezione

Fork of HTTPClient by ST Expansion SW Team

Files at this revision

API Documentation at this revision

Comitter:
mapellil
Date:
Mon Nov 07 17:08:02 2016 +0000
Parent:
18:277279a1891e
Child:
20:bbbfaf4cc055
Commit message:
first committ

Changed in this revision

HTTPClient.cpp Show annotated file Show diff for this revision Revisions of this file
HTTPClient.h Show annotated file Show diff for this revision Revisions of this file
HTTPSocket.h Show annotated file Show diff for this revision Revisions of this file
HTTPWifi.h Show annotated file Show diff for this revision Revisions of this file
--- a/HTTPClient.cpp	Wed May 07 16:48:10 2014 +0000
+++ b/HTTPClient.cpp	Mon Nov 07 17:08:02 2016 +0000
@@ -40,16 +40,16 @@
 #define MIN(x,y) (((x)<(y))?(x):(y))
 #define MAX(x,y) (((x)>(y))?(x):(y))
 
-#define CHUNK_SIZE 256
+
+#define MAX_KEY     64
+#define MAX_VALUE   64
 
 #include <cstring>
 
 #include "HTTPClient.h"
 
-HTTPClient::HTTPClient() :
-m_sock(), m_basicAuthUser(NULL), m_basicAuthPassword(NULL), m_httpResponseCode(0)
+HTTPClient::HTTPClient(HTTPWiFi & _m_sock) : m_sock(_m_sock) 
 {
-
 }
 
 HTTPClient::~HTTPClient()
@@ -65,18 +65,18 @@
 }
 #endif
 
-HTTPResult HTTPClient::get(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking
+HTTPResult HTTPClient::get(const char* url, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT) //Blocking
 {
   return connect(url, HTTP_GET, NULL, pDataIn, timeout);
 }
 
-HTTPResult HTTPClient::get(const char* url, char* result, size_t maxResultLen, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking
+HTTPResult HTTPClient::get(const char* url, char* result, size_t maxResultLen, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT) //Blocking
 {
   HTTPText str(result, maxResultLen);
   return get(url, &str, timeout);
 }
 
-HTTPResult HTTPClient::post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/) //Blocking
+HTTPResult HTTPClient::post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT) //Blocking
 {
   return connect(url, HTTP_POST, (IHTTPDataOut*)&dataOut, pDataIn, timeout);
 }
@@ -113,6 +113,7 @@
     return HTTP_PRTCL; \
   } while(0)
 
+
 HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request
 { 
   m_httpResponseCode = 0; //Invalidate code
@@ -145,6 +146,8 @@
   DBG("Host: %s", host);
   DBG("Port: %d", port);
   DBG("Path: %s", path);
+// Open
+  m_sock.open(&m_sock.getWiFi());
 
   //Connect
   DBG("Connecting socket to server");
@@ -152,18 +155,19 @@
   if (ret < 0)
   {
     m_sock.close();
-    ERR("Could not connect");
+    ERR("TCP Could not connect");
     return HTTP_CONN;
   }
-
+  DBG ("TCP connected\n\r");
   //Send request
   DBG("Sending request");
-  char buf[CHUNK_SIZE];
+//  char buf[CHUNK_SIZE];
   const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":(method==HTTP_PUT)?"PUT":(method==HTTP_DELETE)?"DELETE":"";
   snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request
   ret = send(buf);
   if(ret)
   {
+    //m_sock.close();
     m_sock.close();
     ERR("Could not write request");
     return HTTP_CONN;
@@ -298,7 +302,7 @@
     }
     break;
   }
-
+printf (" ---->> buf: %s\n\r",buf);
   int crlfPos = crlfPtr - buf;
   buf[crlfPos] = '\0';
 
@@ -322,7 +326,7 @@
     PRTCL_ERR();
   }
 
-  DBG("Reading headers");
+  DBG("=======>>>>  Reading headers");
 
   memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well
   trfLen -= (crlfPos + 2);
@@ -364,14 +368,14 @@
 
     buf[crlfPos] = '\0';
 
-    char key[32];
-    char value[32];
+    char key[MAX_KEY];
+    char value[MAX_VALUE];
 
     //key[31] = '\0';
     //value[31] = '\0';
 
-    memset(key, 0, 32);
-    memset(value, 0, 32);
+    memset(key, 0, MAX_KEY);
+    memset(value, 0, MAX_VALUE);
 
     //int n = sscanf(buf, "%31[^:]: %31[^\r\n]", key, value);
     
@@ -381,14 +385,14 @@
     if(keyEnd != NULL)
     {
       *keyEnd = '\0';
-      if(strlen(buf) < 32)
+      if(strlen(buf) < MAX_KEY)
       {
         strcpy(key, buf);
         n++;
         char* valueStart = keyEnd + 2;
         if( (valueStart - buf) < crlfPos )
         {
-          if(strlen(valueStart) < 32)
+          if(strlen(valueStart) < MAX_VALUE)
           { 
             strcpy(value, valueStart);
             n++;
@@ -574,27 +578,40 @@
 {
   DBG("Trying to read between %d and %d bytes", minLen, maxLen);
   size_t readLen = 0;
-      
+
+#ifdef LICIO
+
+#else      
   if(!m_sock.is_connected())
   {
     WARN("Connection was closed by server");
     return HTTP_CLOSED; //Connection was closed by server 
   }
-    
+#endif    
   int ret;
   while(readLen < maxLen)
   {
     if(readLen < minLen)
     {
       DBG("Trying to read at most %d bytes [Blocking]", minLen - readLen);
+#ifdef LICIO
+      m_sock.set_blocking(false);
+      ret = m_sock.recv(buf + readLen, minLen - readLen);
+#else      
       m_sock.set_blocking(false, m_timeout);
       ret = m_sock.receive_all(buf + readLen, minLen - readLen);
+#endif
     }
     else
     {
       DBG("Trying to read at most %d bytes [Not blocking]", maxLen - readLen);
+#ifdef LICIO
+      m_sock.set_blocking(false);
+      ret = m_sock.recv(buf + readLen, maxLen - readLen);
+#else      
       m_sock.set_blocking(false, 0);
       ret = m_sock.receive(buf + readLen, maxLen - readLen);
+#endif      
     }
     
     if( ret > 0)
@@ -607,6 +624,9 @@
     }
     else
     {
+#ifdef LICIO      
+//    if (ret == NSAPI_ERROR_NO_CONNECTION) { *pReadLen = readLen; return HTTP_CONN; }
+#else 
       if(!m_sock.is_connected())
       {
         ERR("Connection error (recv returned %d)", ret);
@@ -617,12 +637,16 @@
       {
         break;      
       }
+#endif
     }
-    
+#ifdef LICIO
+//    if (ret == NSAPI_ERROR_NO_CONNECTION) { *pReadLen = readLen; return HTTP_CONN; }
+#else
     if(!m_sock.is_connected())
     {
       break;
     }
+#endif
   }
   DBG("Read %d bytes", readLen);
   *pReadLen = readLen;
@@ -637,15 +661,23 @@
   }
   DBG("Trying to write %d bytes", len);
   size_t writtenLen = 0;
-    
+
+#ifdef LICIO
+#else
   if(!m_sock.is_connected())
   {
     WARN("Connection was closed by server");
     return HTTP_CLOSED; //Connection was closed by server 
   }
-  
+#endif
+#ifdef LICIO
+  m_sock.set_blocking(false);
+  int ret = m_sock.send(buf, len);
+
+#else
   m_sock.set_blocking(false, m_timeout);
   int ret = m_sock.send_all(buf, len);
+#endif
   if(ret > 0)
   {
     writtenLen += ret;
@@ -736,4 +768,4 @@
   path[pathLen] = '\0';
 
   return HTTP_OK;
-}
+}
\ No newline at end of file
--- a/HTTPClient.h	Wed May 07 16:48:10 2014 +0000
+++ b/HTTPClient.h	Mon Nov 07 17:08:02 2016 +0000
@@ -24,13 +24,17 @@
 #ifndef HTTP_CLIENT_H
 #define HTTP_CLIENT_H
 
-#include "TCPSocketConnection.h"
+#include "TCPSocket.h"
+#include "HTTPWifi.h"
 
+#define LICIO
 #define HTTP_CLIENT_DEFAULT_TIMEOUT 15000
+#define CHUNK_SIZE 256
 
 class HTTPData;
 
 #include "IHTTPData.h"
+
 #include "mbed.h"
 
 ///HTTP client results
@@ -58,7 +62,7 @@
 {
 public:
   ///Instantiate the HTTP client
-  HTTPClient();
+  HTTPClient(HTTPWiFi & _m_sock);  
   ~HTTPClient();
   
 #if 0 //TODO add header handlers
@@ -79,7 +83,7 @@
   @param timeout waiting timeout in ms (osWaitForever for blocking function, not recommended)
   @return 0 on success, HTTP error (<0) on failure
   */
-  HTTPResult get(const char* url, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking
+  HTTPResult get(const char* url, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/); //Blocking
   
   /** Execute a GET request on the URL
   Blocks until completion
@@ -90,7 +94,7 @@
   @param timeout waiting timeout in ms (osWaitForever for blocking function, not recommended)
   @return 0 on success, HTTP error (<0) on failure
   */
-  HTTPResult get(const char* url, char* result, size_t maxResultLen, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking
+  HTTPResult get(const char* url, char* result, size_t maxResultLen, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/); //Blocking
 
   /** Execute a POST request on the URL
   Blocks until completion
@@ -100,7 +104,7 @@
   @param timeout waiting timeout in ms (osWaitForever for blocking function, not recommended)
   @return 0 on success, HTTP error (<0) on failure
   */
-  HTTPResult post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking
+  HTTPResult post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout /*= HTTP_CLIENT_DEFAULT_TIMEOUT*/); //Blocking
   
   /** Execute a PUT request on the URL
   Blocks until completion
@@ -141,14 +145,15 @@
   HTTPResult send(char* buf, size_t len = 0); //0 on success, err code on failure
   HTTPResult parseURL(const char* url, char* scheme, size_t maxSchemeLen, char* host, size_t maxHostLen, uint16_t* port, char* path, size_t maxPathLen); //Parse URL
 
-  //Parameters
-  TCPSocketConnection m_sock;
+  //Parameters 
+  HTTPWiFi m_sock;
   
   int m_timeout;
 
   const char* m_basicAuthUser;
   const char* m_basicAuthPassword;
   int m_httpResponseCode;
+  char buf[CHUNK_SIZE];
 
 };
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPSocket.h	Mon Nov 07 17:08:02 2016 +0000
@@ -0,0 +1,70 @@
+#if !defined(HTTPSOCKET_H)
+#define HTTPSOCKET_H
+
+#include "mbed.h"
+#include "TCPSocket.h"
+
+class HTTPSocket
+{
+public:
+
+    int open(NetworkStack *ipstack)
+    {
+        return mysock.open(ipstack);        
+    }
+  
+    int connect(char* hostname, int port, int timeout=1000)
+    {
+        int err;
+        mysock.set_timeout(timeout);
+//SocketAddress addr(&spwf, hostname);   
+//    pc.printf("\r\nst.com resolved to: %s\r\n", addr.get_ip_address());         
+        
+        printf ("TCP hostaname: %s, port: %d\n\r", hostname, port);
+        err = mysock.connect(hostname, port);  
+//    t.start();             
+        return err; 
+    }
+
+//    int read(unsigned char* buffer, int len, int timeout)
+    int recv(char* buffer, int len)
+    {
+//        mysock.set_timeout(timeout);        
+//t.reset();
+// int start = t.read_ms();
+        int rc = mysock.recv((char*)buffer, len);
+// int stop = t.read_ms();       
+//        if (rc>0) printf ("recv File: %s, Line: %d Read nB: %d rc: %d timeout: %d elaps: %d\n\r",__FILE__,__LINE__, len, rc, timeout, stop-start);        
+        return rc;
+    }
+    
+//    int write(unsigned char* buffer, int len, int timeout)
+    int send(char* buffer, int len)    
+    {
+//        mysock.set_timeout(timeout);                
+//        mysock.set_blocking(false, timeout);  
+//        mysock.set_blocking(false);  
+        int rc = mysock.send((char*)buffer, len);
+//         printf ("send File: %s, Line: %d Write nB: %d rc: %d\n\r",__FILE__,__LINE__, len, rc);
+        return rc;
+    }
+    
+    int set_blocking(bool mode) 
+    {
+        mysock.set_blocking (mode);     
+    }
+
+    
+//    int disconnect()
+    int close()
+    {
+//        t.stop();
+        return mysock.close();
+    }
+     
+private:
+    TCPSocket mysock; 
+ //   Timer t;
+    
+};
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/HTTPWifi.h	Mon Nov 07 17:08:02 2016 +0000
@@ -0,0 +1,36 @@
+
+#if !defined(HTTPWIFI_H)
+#define HTTPWIFI_H
+
+#include "mbed.h"
+#include "SpwfInterface.h"
+#include "WiFiInterface.h"
+#include "HTTPSocket.h"
+
+class HTTPWiFi : public HTTPSocket
+{
+public:    
+    HTTPWiFi(SpwfSAInterface &WiFiIntf, const char *ssid, const char *pass, nsapi_security_t security = NSAPI_SECURITY_NONE) : WiFi(WiFiIntf)
+    {
+//        eth.init();                          // Use DHCP
+        WiFi.connect(ssid, pass,  security);
+        printf ("WIFI ssid: %s connected\n\r", ssid);
+    }
+    
+    SpwfSAInterface& getWiFi()
+    {
+        return WiFi;
+    }
+    
+/*    void reconnect()
+    {
+        WiFi.connect();  // nothing I've tried actually works to reconnect 
+    }
+*/   
+
+private:
+
+SpwfSAInterface& WiFi;
+    
+};
+#endif