#ifndef _COMMDEV_H_
#define _COMMDEV_H_

#include <windows.h>

// hard coded maximum number of ports for device under Win32
#define MAXPORTS                4

// max block size
#define MAXBLOCK                4096

#define RXQUEUE                 8192
#define TXQUEUE                 8192

// Flow control flags
#define FC_DTRDSR               0x01
#define FC_RTSCTS               0x02
#define FC_XONXOFF              0x04

// ascii definitions
#define ASCII_CF                0x06
#define ASCII_BEL               0x07
#define ASCII_BS                0x08
#define ASCII_LF                0x0A
#define ASCII_CR                0x0D
#define ASCII_XON               0x11
#define ASCII_XOFF              0x13


class CommDev 
{
public:
    CommDev(int port);
    CommDev(const char* portname);
    virtual ~CommDev();
    
    void SetCommWatchProc(LPTHREAD_START_ROUTINE proc);
    
    HANDLE getHandle() const
    { 
        return idComDev;
    }
    
    operator HANDLE() const 
    {
        return idComDev;
    }
    
    void setByteSize(int bytesize) 
    { 
        bByteSize = (BYTE)bytesize; 
    }
    
    void setParity(int parity);
    
    int getPort()
    {
        return bPort;
    }
    
    void setPort(int port) 
    { 
        bPort = (BYTE)port;
    }
    
    void setRate(int rate);
    
    void setStopBits(int stopbits);
    
    bool OpenConnection();
    
    bool CloseConnection();
    
    bool Connected() const
    { 
        return fConnected; 
    }
    
    void ClearWatch() 
    { 
        dwThreadID = 0; 
        hWatchThread = NULL; 
    };
    

    unsigned int Read(LPSTR, DWORD);
    
    bool Write(LPSTR, DWORD);
    
    int getCTS() const;
    
    void setRTS(int set);
    
private:
    bool setDefaults();    
    bool SetupConnection();

private:
    HANDLE   idComDev;
    BYTE     bPort;
    bool     fConnected, fXonXoff;
    BYTE     bByteSize, bFlowCtrl, bParity, bStopBits;
    DWORD    dwBaudRate;
    HANDLE   hWatchThread;
    DWORD    dwThreadID;
    DWORD    (*CommWatchProc)(LPVOID);
    
    static   DWORD BaudTable[];
    static   DWORD ParityTable[];
    static   DWORD StopBitsTable[];
};

#endif // _COMMDEV_H_
