Dependents:   SimpleLCDClock readCard2Twitter_http AnalogClock_StepperMotor_NTP ServoCamV1

api/TcpSocket.h

Committer:
donatien
Date:
2010-05-24
Revision:
0:3717b703f76d
Child:
1:e52ec2a24c6a

File content as of revision 0:3717b703f76d:

#ifndef TCPSOCKET_H
#define TCPSOCKET_H

#include "if/net/net.h"
//Essentially it is a safe interface to NetTcpSocket

enum TcpSocketErr
{
  __TCPSOCKET_MIN = -0xFFFF,
  TCPSOCKET_SETUP, //NetTcpSocket not properly configured
  TCPSOCKET_TIMEOUT,
  TCPSOCKET_IF, //If has problems, does not exist or is not initialized
  TCPSOCKET_MEM, //Not enough mem
  TCPSOCKET_INUSE, //If/Port is in use
  TCPSOCKET_EMPTY, //Connections queue is empty
  TCPSOCKET_RST, // Connection was reset by remote host
//...
  TCPSOCKET_OK = 0
};

enum TcpSocketEvent
{
  TCPSOCKET_CONNECTED, //Connected to host, must call accept() if we were listening
  TCPSOCKET_ACCEPT,  //Connected to client
  TCPSOCKET_READABLE, //Data in buf
  TCPSOCKET_WRITEABLE, //Can write data to buf
  TCPSOCKET_CONTIMEOUT,
  TCPSOCKET_CONRST,
  TCPSOCKET_CONABRT,
  TCPSOCKET_ERROR,
  TCPSOCKET_DISCONNECTED
};


class TcpSocket
{
public:
  TcpSocket();
protected:
  TcpSocket(NetTcpSocket* pNetTcpSocket);
public:
  ~TcpSocket(); //close()
  
  TcpSocketErr bind(const Host& me);
  TcpSocketErr listen();
  TcpSocketErr connect(const Host& host);
  TcpSocketErr accept(Host* pClient, TcpSocket** ppNewTcpSocket);
  
  int /*if < 0 : TcpSocketErr*/ send(const char* buf, int len);
  int /*if < 0 : TcpSocketErr*/ recv(char* buf, int len);

  /* TODO NTH : printf / scanf helpers that call send/recv */

  TcpSocketErr close();

  class CDummy;
  //Callbacks
  void setOnEvent( void (*pMethod)(TcpSocketEvent) );
  template<class T> 
  //Linker bug : Must be defined here :(
  void setOnEvent( T* pItem, void (T::*pMethod)(TcpSocketEvent) )
  {
    m_pCbItem = (CDummy*) pItem;
    m_pCbMeth = (void (CDummy::*)(TcpSocketEvent)) pMethod;
  }
  
  void resetOnEvent(); //Disable callback
  
protected:
  void onNetTcpSocketEvent(NetTcpSocketEvent e);
  TcpSocketErr checkInst();

private:
  NetTcpSocket* m_pNetTcpSocket;
  
  CDummy* m_pCbItem;
  void (CDummy::*m_pCbMeth)(TcpSocketEvent);
  
  void (*m_pCb)(TcpSocketEvent);
  
};

#endif