Dependencies:   EthernetNetIf mbed NetServicesMin

message.c

Committer:
alpsayin
Date:
2011-09-21
Revision:
0:be9ccd3a915d

File content as of revision 0:be9ccd3a915d:


#include "message.h"

void (*getMessageHandler)(TCPSocket* pConnectedSocket, char* msg, int len) = defaultMessageHandler;
void (*postMessageHandler)(TCPSocket* pConnectedSocket,char* msg, int len) = defaultMessageHandler;

void defaultMessageHandler(TCPSocket* pConnectedSocket, char* msg, int len)
{
    printf(msg);
    vSendMessage(pConnectedSocket, "DEFAULT\r\n", 9);
}
void vSendMessage(TCPSocket* pConnectedSocket, char* msg, int len)
{
    pConnectedSocket->send("RESPONSE\r\n",10);
    pConnectedSocket->send(msg,len);
    pConnectedSocket->send("\r\n\r\n",4);
}
void vGetMessage(TCPSocket* pConnectedSocket)
{
    char line[BUFFER_LENGTH];
    int len;
    bool endOfMessage = false;
    while(!endOfMessage)
    {
        len = iGetLine(pConnectedSocket, line, BUFFER_LENGTH);
        if(strncmp(line,"GET\r\n", 5)==0)
        {
            len = iGetLine(pConnectedSocket, line, BUFFER_LENGTH);
            getMessageHandler(pConnectedSocket, line, len);
        }
        else if(strncmp(line,"POST\r\n",6)==0)
        {
            len = iGetLine(pConnectedSocket, line, BUFFER_LENGTH);
            postMessageHandler(pConnectedSocket, line, len);
        }
        else if(strncmp(line, "\r\n", 2)==0)
        {
            endOfMessage = true;
        }
    }
}
int iGetLine(TCPSocket* pConnectedSocket, char* buf, int len)
{
    int counter = 0;
    while(counter < len)
    {
        if(pConnectedSocket->recv(&(buf[counter]),1) > 0)
        {
            if(counter > 0)
            {
                if(buf[counter]=='\n' && buf[counter-1]=='\r')
                {
                    return counter+1;
                }
            }
            counter++;
        }
    }
    return -1;
}
void vSetMessageHandler(int messageType, void (*messageHandler)(TCPSocket* pConnectedSocket,char* msg, int len))
{
    switch(messageType)
    {
        case TYPE_GET: getMessageHandler = messageHandler; break;
        case TYPE_POST: postMessageHandler = messageHandler; break;
        default: break;
    }
}