/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: src/drivers/wintel32/core/comms/wintel32commsystem.cpp

*/

#include "drivers/wintel32/core/core.hpp"

CCommPortDevice *CSGXCommsSystem::openCommsPort(const CCommPortSettings &settings) {
	
	HANDLE deviceHandle = CreateFile(settings.m_Name.c_str(),
		GENERIC_READ|GENERIC_WRITE,
		0,NULL,
		OPEN_EXISTING,0,NULL);

	if(deviceHandle == INVALID_HANDLE_VALUE) {
		return NULL;
	}


	// set timeouts
	COMMTIMEOUTS cto = { 1, 100, 1000, 0, 0 };
	DCB dcb;
	if(!SetCommTimeouts(deviceHandle,&cto)) {
		CloseHandle(deviceHandle);
		return NULL;
	}

	// set DCB
	memset(&dcb,0,sizeof(dcb));
	dcb.DCBlength = sizeof(dcb);
	dcb.BaudRate = settings.m_iBaud;
	dcb.fBinary = 1;
	dcb.fDtrControl = settings.m_DTR;
	dcb.fRtsControl = settings.m_RTS;
	//
	dcb.Parity = (BYTE)settings.m_Parity;
	dcb.StopBits = (BYTE)settings.m_StopBits;
	dcb.ByteSize = (BYTE)settings.m_iByteSize;
	if(!SetCommState(deviceHandle,&dcb)) {
		CloseHandle(deviceHandle);
		return NULL;
	}


	return (CCommPortDevice *)new CDriverWintel32CommPortDevice(deviceHandle);
}

