Changes made for RPC

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers HTTPServer.h Source File

HTTPServer.h

00001 /* HTTPServer.cpp */
00002 /*
00003 Copyright (c) 2013 Henry Leinen (henry[dot]leinen [at] online [dot] de)
00004  
00005 Permission is hereby granted, free of charge, to any person obtaining a copy
00006 of this software and associated documentation files (the "Software"), to deal
00007 in the Software without restriction, including without limitation the rights
00008 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00009 copies of the Software, and to permit persons to whom the Software is
00010 furnished to do so, subject to the following conditions:
00011  
00012 The above copyright notice and this permission notice shall be included in
00013 all copies or substantial portions of the Software.
00014  
00015 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00016 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00017 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00018 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00019 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00020 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
00021 THE SOFTWARE.
00022 */
00023 #ifndef __HTTPSERVER_H__
00024 #define __HTTPSERVER_H__
00025 #include "mbed.h"
00026 #include "EthernetInterface.h"
00027 #include "HTTPConnection.h"
00028 #include "HTTPRequestHandler.h"
00029 #include "RpcHandler.h"
00030 
00031 #include <map>
00032 using std::map;
00033 #include <string>
00034 using std::string;
00035 
00036 #include <TCPSocketConnection.h>
00037 #include <TCPSocketServer.h>
00038 
00039 /** Typedefinition for a handler function
00040 */
00041 typedef void (*HTTPRequestHandlerFunction)(HTTPConnection::HTTPMessage&, TCPSocketConnection&);
00042 
00043 
00044 /** Class HTTPServer for use with <a href="http://mbed.org/users/samux/code/WiflyInterface/">WiflyInterface</a>.
00045 * This class is a simple implementation of an HTTP Server for use with the WiFly interface.
00046 * The class will listen for incoming connections on the (configurable) HTTP port. For each 
00047 * incoming connection, one request will be processed. 
00048 * After instantiating this class, add all required handlers using the \c addHandler function,
00049 * replace the default error handler using \c addErrorHandler if needed and call the \c start
00050 * method to initialize the class.
00051 * You need to continuously poll for any new incoming connections after one request has been
00052 * served using the \c poll member function.
00053 *
00054 * \b Example:
00055 * @code
00056 * #include "mbed.h"
00057 * #include "HTTPServer.h"
00058 * #include "LocalFileSystem.h"
00059 *
00060 * LocalFileSystem local("local"); 
00061 *
00062 * void main(void)
00063 * {
00064 *     HTTPServer svr;
00065 *     svr.mount("/local/", "/");
00066 *     svr.addHandler<HTTPFsRequestHandler>( "/" );
00067 *     svr.start();
00068 *     while(1)
00069 *     {
00070 *         if (svr.poll() < 0)
00071 *             exit(0);
00072 *     }
00073 * }
00074 * @endcode
00075 *
00076 * An alternate approach e.g. if you need to perform additional tasks using the EthernetInterface
00077 * there is the possibility to provide the EthernetInterface object in an initialized and connected
00078 * state. __NOTE: You should choose this scenario for compatibility reasons.___
00079 *
00080 * \b Example2:
00081 * @code
00082 * #include "mbed.h"
00083 * #include "HTTPServer.h"
00084 * #include "EthernetInterface.h"
00085 * #include "LocalFileSystem.h"
00086 *
00087 * LocalFileSystem local("local");
00088 * EthernetInterface eth;
00089 *
00090 * void main(void)
00091 * {
00092 *     HTTPServer svr;
00093 *     //    Initialize the ethernet interface
00094 *     if (eth.init() != 0) {
00095 *         printf("Initialization of EthernetInterface failed !");
00096 *         exit(0);
00097 *     }
00098 *     //    Connect using DHCP
00099 *     if (eth.connect() !=0) {
00100 *         printf("Failed to connect using DHCP !");
00101 *         exit(0);
00102 *     }
00103 *     
00104 *     // Moint the local file system and provide a handler for 'root'.
00105 *     svr.mount("/local/", "/");
00106 *     svr.addHandler<HTTPFsRequestHandler>( "/" );
00107 *     // Start the server on port 80, providing our own ethernet interface object.
00108 *     svr.start(80, &eth);
00109 *     while(1)
00110 *     {
00111 *         if (svr.poll() < 0)
00112 *             exit(0);
00113 *     }
00114 * }
00115 * @endcode
00116 *     
00117 */
00118 class HTTPServer
00119 {
00120         TCPSocketServer         m_Svr;
00121         bool                    m_bServerListening;
00122         EthernetInterface*      m_pEthernet;
00123        
00124     public:
00125         /** Constructor for HTTPServer objects.
00126         */
00127         HTTPServer();
00128         
00129         /** Destructor for HTTPServer objects.
00130         */
00131         ~HTTPServer();
00132 
00133         /**
00134         * Structure which will allow to order the stored handlers according to their associated path.
00135         */
00136         struct handlersComp //Used to order handlers in the right way
00137         {
00138             bool operator() (const string& handler1, const string& handler2) const
00139             {
00140                 //The first handler is longer than the second one
00141                 if (handler1.length() > handler2.length())
00142                     return true; //Returns true if handler1 is to appear before handler2
00143                 else if (handler1.length() < handler2.length())
00144                     return false;
00145                 else //To avoid the == case, sort now by address
00146                     return ((&handler1)>(&handler2));
00147             }
00148         };
00149 
00150         /**
00151         * Adds a request handler to the handlers list. You will have to use one of the existing implementations.
00152         * With each handler a \c uri or \c path is associated. Whenever a request is received the server will
00153         * walk through all registered handlers and check which \c path is matching.
00154         * @param T : class which will be instanciated to serve these requests for the associated \b path.
00155         * @param path : request uri starting with this \c path will be served using this handler.
00156         */
00157         template<typename T>
00158         void addHandler(const char* path)
00159         { m_lpHandlers[path] = &T::create; }
00160     
00161         /**
00162         * Replaces the standard error Handler. The error Handler will be called everytime a request is not
00163         * matching any of the registered \c paths or \c uris.
00164         * @param hdlFunc: User specified handler function which will be used in error conditions.
00165         */
00166         void addErrorHandler(HTTPRequestHandlerFunction hdlFunc)
00167         { m_pErrorHandler = hdlFunc!=NULL ?hdlFunc : StdErrorHandler; }    
00168 
00169         /** Binds server to a specific port and starts listening. This member prepares the internal variables and the server socket
00170         * and terminates after successfull initialization
00171         * @param port : port on which to listen for incoming connections
00172         * @param pEthernet : a pointer to an existing EthernetInterface object or NULL if the HTTPServer shall allocate the object. _Please note that for compatibility reasons
00173         * your should consider to create the EthernetInterface as a static variable. Otherwise the the object will be created on the heap._
00174         * @returns : false if an unrecoverable error occured or if the ethernet interface was not set or not initialized correctly, or true if everything was ok.
00175         */
00176         bool start(int port = 80, EthernetInterface* pEthernet = NULL);
00177         
00178         /** Performs the regular polling of the server component. Needs to be called cyclically.
00179         * The function will internally check whether new connections are requested by a client and will also poll all existing client connections.
00180         * @param blocking : if true, 
00181         * @returns -1 if there was a problem. If 0 is returned, the latest request was served successfully and the server is
00182         * ready for processing the next request. Simply call \c poll as long as you want to serve new incoming requests.
00183         */
00184         int poll(bool blocking = true);
00185         
00186     private:
00187         
00188         /** The standard error handler function.
00189         * @param msg : Request message data.
00190         * @param tcp : Socket to be used for responding.
00191         */
00192         static void StdErrorHandler(HTTPConnection::HTTPMessage& msg, TCPSocketConnection& tcp);
00193         
00194         /** Internal function which processes a request and which will try to find the matching handler function
00195         * for the given request. Please note that the function will search through the list of handlers, iterating
00196         * from longest to shortest \c paths. If the registered \c path is a subset of the request the associated
00197         * handler is considered as being a match.
00198         * @param msg : Request message data. Contains the requested logical \c uri. 
00199         * @param tcp : Socket to be used for communication with the client.
00200         */
00201         void HandleRequest(HTTPConnection::HTTPMessage& msg, TCPSocketConnection& tcp);
00202     
00203         /** Map of handler objects. Can be any object derived from \ref HTTPRequestHeader. Use the \ref addHandler function
00204         * to register new handler objects.
00205         */
00206         map<string, HTTPRequestHandler* (*)(const char*, const char*, HTTPConnection::HTTPMessage&, TCPSocketConnection&), handlersComp>   m_lpHandlers;
00207         HTTPRequestHandlerFunction m_pErrorHandler;
00208         
00209  };
00210  
00211  #endif //__HTTPSERVER_H__