Example program with HTTPServer and sensor data streaming over TCPSockets, using Donatien Garnier's Net APIs and services code on top of LWIP. Files StreamServer.h and .cpp encapsulate streaming over TCPSockets. Broadcast is done by sendToAll(), and all incoming data is echoed back to the client. Echo code can be replaced with some remote control of the streaming interface. See main() that shows how to periodically send some data to all subscribed clients. To subscribe, a client should open a socket at <mbed_ip> port 123. I used few lines in TCL code to set up a quick sink for the data. HTTP files are served on port 80 concurrently to the streaming.

Dependencies:   mbed

StreamServer.cpp

Committer:
iva2k
Date:
2010-06-14
Revision:
1:3ee499525aa5
Parent:
0:e614f7875b60

File content as of revision 1:3ee499525aa5:


/*
Copyright (c) 2010 IVA2K
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include "StreamServer.h"

#include "dbg/dbg.h"


//BEGIN REQUEST DISPATCHER======================================================
StreamRequestDispatcher::StreamRequestDispatcher(StreamServer* pSvr, TCPSocket* pTcpSocket) 
: NetService(), m_pSvr(pSvr), m_pTcpSocket(pTcpSocket), m_closed(false)
{
  m_pTcpSocket->setOnEvent(this, &StreamRequestDispatcher::onTcpSocketEvent);
}

StreamRequestDispatcher::~StreamRequestDispatcher()
{
//DBG("deleting\r\n");
  close();
}

int StreamRequestDispatcher::writeData(const char* buf, int len)
{
  if(m_closed) {
//DBG("m_closed\r\n");
    return TCPSOCKET_RST;
  }
  int ret = m_pTcpSocket->send(buf, len);
if (ret != len)    DBG("ret=%d\r\n", ret);
  return ret;
}

//FIXME: Need implementation for StreamServer
void StreamRequestDispatcher::dispatchRequest()
{
  string request;
  const char* buf;
  int len, ret;
//  DBG("\r\n");
  
//FIXME: here is the place to implement custom request handler
 
  while ( getRequest(&request) )
  {
    // Just echo it back
    buf = request.c_str();
    len = strlen(buf);
    ret = writeData(buf,len);
writeData("\r\n",2);
    DBG("Received req (%s), write ret=%d\r\n", buf, ret);
  }
}

void StreamRequestDispatcher::close() //Close socket and destroy data
{
  if(m_closed) {
//DBG("already closed\r\n");
    return;
  }
  m_closed = true; //Prevent recursive calling or calling on an object being destructed by someone else
//DBG("removing from list\r\n");
  m_pSvr->m_lpClients.remove(this);
  if(m_pTcpSocket)
  {
//DBG("closing socket\r\n");
    m_pTcpSocket->resetOnEvent();
    m_pTcpSocket->close();  // FIXME: in bad cause of events, getting "could not close properly, abort" log message
    delete m_pTcpSocket;
  }
//DBG("closing service\r\n");
  NetService::close();
}

bool StreamRequestDispatcher::getRequest(string* request)
{
  const int maxLen = 64;
  char req[maxLen];
  //Read Line
  int ret;
  int len = 0;
  char* p = req;
  for(int i = 0; i < maxLen - 1; i++)
  {
    ret = m_pTcpSocket->recv(p, 1);
//FIXME: handle errors here (ret < 0)?
    if(!ret)
    {
      break;
    }
#if 1
    // Consider incoming symbols - line ends etc.
    if( (len > 1) && *(p-1)=='\r' && *p=='\n' )
    {
      p--;
      len-=2;
      break;
    }
    else if( *p=='\n' )
    {
      len--;
      break;    
    }
#endif
    p++;
    len++;
  }
  *p = 0;
  
  DBG("Parsing request (%s) ret=%d\r\n", req, ret);
  
  *request = string(req);
  
  return (len > 0);
}


void StreamRequestDispatcher::onTcpSocketEvent(TCPSocketEvent e)
{
  DBG("Event %d\r\n", e);
  
  if(m_closed)
  {
    DBG("WARN: Discarded\r\n");
    return;
  }

  switch(e)
  {
  case TCPSOCKET_READABLE:
    //Req arrived, dispatch :
    dispatchRequest();
    break;
  case TCPSOCKET_CONTIMEOUT:
  case TCPSOCKET_CONRST:
  case TCPSOCKET_CONABRT:
  case TCPSOCKET_ERROR:
  case TCPSOCKET_DISCONNECTED:
    close();
    break;
  }
  
}
//END REQUEST DISPATCHER========================================================


StreamServer::StreamServer()
{
  m_pTcpSocket = new TCPSocket;
  m_pTcpSocket->setOnEvent(this, &StreamServer::onTcpSocketEvent);
}

StreamServer::~StreamServer()
{
  delete m_pTcpSocket;
}

void StreamServer::bind(int port /*= 123*/)
{
  Host h(IpAddr(127,0,0,1), port, "localhost");
  m_pTcpSocket->bind(h);     
  m_pTcpSocket->listen(); //Listen
}

#if 0 //Just for clarity
template<typename T>
void StreamServer::addHandler(const char* path)
{
//  m_lpHandlers[path] = &T::inst;
}
#endif

void StreamServer::sendToAll(const char* buf, int len)
{
  int ret;
  int i = 0;
  tClients::iterator it;
  for(it = m_lpClients.begin(); it != m_lpClients.end(); /* No increment here */ )
  {
    ret = (*it)->writeData(buf, len);
    if (
         ret == TCPSOCKET_RST // This is a safety valve. We should have self-removed from m_lpClients upon socket closure and not get here.
      || ret == TCPSOCKET_MEM // This probably means that network is not delivering packets, and we're backed up.
    ) {
      DBG("(%s) Socket error 0x%04X - erasing socket %d\r\n", buf, ret, i);
      // delete below will remove (*it) from the list we are iterating in. Prepare for that
      tClients::iterator it_next = it;
      it_next++;
      delete (*it);
      it = it_next;
      continue; // This ensures that for(...) above will continue properly.
    }
    i++;
    it++; /* increment the iterator */
  }
}

int StreamServer::countClients(void)
{
  return m_lpClients.size();
}
  
void StreamServer::onTcpSocketEvent(TCPSocketEvent e)
{

  DBG("Event %d\r\n", e);

  if(e==TCPSOCKET_ACCEPT)
  {
    TCPSocket* pTcpSocket;
    Host client;

    if( !!m_pTcpSocket->accept(&client, &pTcpSocket) )
    {
      DBG("Could not accept connection.\r\n");
      return; //Error in accept, discard connection
    }
    
    StreamRequestDispatcher* pDispatcher = new StreamRequestDispatcher(this, pTcpSocket); //TcpSocket ownership is passed to dispatcher
    //The dispatcher object will destroy itself when its socket closes, or will be destroyed on Server destruction
    m_lpClients.push_back(pDispatcher);
  }
}

//END