// RS232_1.cpp
//
// Sends 'H' and 'L' to COM Port every 10 seconds.
// 
// copyright, Peter H Anderson, baltimore, MD, Nov 3, '09
//
#include <conio.h>
#include <stdio.h>
#include <windows.h>
#include <time.h>
#include <string.h>

#define COM_PORT 3 // <<<<<<<<<<<< Modify as required.

#define DEBUG

int meas_DS18B20(int ch, float *p_Tc);
int output_state(int ch, int state);

// RS232 Routines
HANDLE rs_initialise (const long int BaudRate,
                      const char parity, const char data);
void rs_flush(void);
void rs_terminate(void);
char rs_getch(void);
int rs_getline(char line[], clock_t timeout);
void rs_putch(int txchar);
void rs_putstr(const char *string);

// delay_routines
void delay_ms(clock_t millis);

HANDLE hCom;           //handle for serial port I/O
int io_port;

#define FAILURE 0
#define SUCCESS !FAILURE

int main()
{    
    long timeout;
	char s[10];
	
	io_port = COM_PORT;
    if(!rs_initialise(9600, '8', 'N')) // open the COM port
    {
         printf("Opening Port Failed\n");
         delay_ms(5000);
         exit(1);
    }
    
    // now proceed to do the task every 10 secs
    timeout = clock() + 10000;  // every 10 secs
    while(1) // forever
    {
       sprintf(s, "H");
       rs_putstr(s);
       
       delay_ms(1000);
       
       sprintf(s, "L");
       rs_putstr(s);
       
       while(clock() < timeout) // wait for the balance of the 60 seconds
       {
       }
       timeout = timeout + 10000; // new timeout value
    }
    // as written, the program never really gets to this point
    rs_terminate();
    system("pause");
    return 0;
}

void delay_ms(clock_t millis)
{
   clock_t endtime;
   endtime = millis + clock();
   while( endtime > clock() )        ;

}

// RS232 routines
HANDLE rs_initialise (const long int BaudRate, const char parity, const char data)
{
    BOOL bPortReady;
    DCB dcb;
	COMMTIMEOUTS CommTimeouts;

    char ComPortName[5]="COM ";
    ComPortName[3]='0'+ io_port;
    hCom = CreateFile(ComPortName, GENERIC_READ | GENERIC_WRITE,
                                  0,            // exclusive access
                                  NULL,         // no security
                                  OPEN_EXISTING,
                                  0,            // no overlapped I/O
                                  NULL);        // null template


    if ((int)hCom <= 0)
    {
        printf("serial port COM%d connect fail %s error %d\n\r", io_port, ComPortName, GetLastError());
        return 0;
    }
    //else                printf(" serial port COM%d connect OK \n\r", io_port);

    bPortReady = SetupComm(hCom, 128, 128); // set buffer sizes
    if (!bPortReady )
    {
        printf("serial port COM%d SetupComm fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    //else                printf(" serial port COM%d connect OK \n\r", io_port);

    bPortReady = GetCommState(hCom, &dcb);
    if (!bPortReady )
    {
        printf("serial port COM%d  GetCommState fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    //  else                printf(" serial port COM%d connect OK \n\r", io_port);
    dcb.BaudRate = BaudRate;
    if( data == '7') dcb.ByteSize = 7;
    else             dcb.ByteSize = 8;
    if( parity == 'E') dcb.Parity = EVENPARITY;
    if( parity == 'O') dcb.Parity = ODDPARITY;
    else               dcb.Parity = NOPARITY;
    dcb.StopBits = ONESTOPBIT;
    dcb.fAbortOnError = TRUE;

    // set XON/XOFF
    dcb.fOutX = FALSE;                       // XON/XOFF off for transmit
    dcb.fInX = FALSE;                        // XON/XOFF off for receive
    // set RTSCTS
    dcb.fOutxCtsFlow = FALSE;               // turn off CTS flow control
    dcb.fRtsControl = FALSE;                // RTS_CONTROL_HANDSHAKE; //
    // set DSRDTR
    dcb.fOutxDsrFlow = FALSE;               // turn off DSR flow control
    //dcb.fDtrControl = DTR_CONTROL_ENABLE; // DTR handshake
    dcb.fDtrControl = DTR_CONTROL_DISABLE;  //
    // dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; //

    bPortReady = SetCommState(hCom, &dcb);
    if (!bPortReady )
    {
        printf("serial port COM%d  SetCommState fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }

    // Communication timeouts
    //COMMTIMEOUTS CommTimeouts;
    bPortReady = GetCommTimeouts (hCom, &CommTimeouts);
    CommTimeouts.ReadIntervalTimeout = 5 ;
    CommTimeouts.ReadTotalTimeoutConstant = 5 ;
    CommTimeouts.ReadTotalTimeoutMultiplier = 1 ;
    CommTimeouts.WriteTotalTimeoutConstant = 5 ;
    CommTimeouts.WriteTotalTimeoutMultiplier = 1 ;
    bPortReady = SetCommTimeouts (hCom, &CommTimeouts);
    if (!bPortReady )
    {
        printf("serial port COM%d SetCommTimeouts fail  %d\n\r", io_port,  GetLastError());
        return 0;
    }
    else
    {
        printf(" serial port COM%d connect OK \n\r", io_port);
    }
    return (hCom);
}

void rs_terminate(void)
{
   CloseHandle(hCom);
}

char rs_getch(void)
{
    char rxchar;
    BOOL bReadRC;
    static DWORD iBytesRead;
    bReadRC = ReadFile(hCom, &rxchar, 1, &iBytesRead, NULL);
    if (iBytesRead)
    {
        return rxchar;
    }
    else
    {
        return 0;         // return 0 if no character read
    }
}

void rs_flush(void)
{
    while(rs_getch()!=0)   ;
}

int rs_getline(char line[], clock_t timeout)
{
    int num_chars = 0;
    char ch;
    clock_t endtime;
    endtime = timeout + clock();
    //printf("%ld %ld\n", clock(), endtime);
    while(endtime > clock())
    {
        //printf("!");
        ch = rs_getch();
        //printf("%d ", ch);
        if (ch != 0)
        {
            //printf("%c", ch);
            if ((ch == 10) || (ch == 13))
            {
                line[num_chars] = '\0'; // terminate the string
                return(num_chars);
            }

            else
            {
                line[num_chars] = ch;
                ++num_chars;
            }
        }

    } // end of while
    line[num_chars] = '\0';
    return(-1);  // timeout
}

void rs_putch(int txchar)
{
    BOOL bWriteRC;
    static DWORD iBytesWritten;
    bWriteRC = WriteFile(hCom, &txchar, 1, &iBytesWritten,NULL);
    return;
}

void rs_putstr(const char *string)
{
#ifdef DEBUG
    printf("%s\n", string);
#endif
    while (*string != '\0')
    {
        delay_ms(5);
        rs_putch(*string++);
    }
}