private void AttemptConnect()
{
connected = false;
UInt32 DeviceCount = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
// Create new instance of the FTDI device class
ftdi = new FTDI();
// Determine the number of FTDI devices connected to the machine
ftStatus = ftdi.GetNumberOfDevices( ref DeviceCount );
// Check status
if(ftStatus != FTDI.FT_STATUS.FT_OK || DeviceCount == 0)
{
commStat = CommStatus.NoDevice;
return;
}
commStat = CommStatus.NoElev8;
// Allocate storage for device info list
FTDI.FT_DEVICE_INFO_NODE[] DeviceList = new FTDI.FT_DEVICE_INFO_NODE[DeviceCount];
try
{
// Populate our device list
ftStatus = ftdi.GetDeviceList( DeviceList );
bool FoundElev8 = false;
for(int i = 0; i < DeviceCount && FoundElev8 == false; i++)
{
if(DeviceList[i].Type != FTDI.FT_DEVICE.FT_DEVICE_X_SERIES) continue;
for(int baud = 0; baud < 2; baud++)
{
ftStatus = ftdi.OpenBySerialNumber( DeviceList[i].SerialNumber );
if(ftStatus == FTDI.FT_STATUS.FT_OK)
{
string portName;
ftdi.GetCOMPort( out portName );
if(portName == null || portName == "")
{
ftdi.Close();
continue;
}
if(baud == 0) {
ftdi.SetBaudRate( 115200 ); // try this first
}
else {
ftdi.SetBaudRate( 57600 ); // then try this (xbee)
}
ftdi.SetDataCharacteristics( 8, 1, 0 );
ftdi.SetFlowControl( FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0 );
txBuffer[0] = (byte)'E';
txBuffer[1] = (byte)'l';
txBuffer[2] = (byte)'v';
txBuffer[3] = (byte)'8';
uint written = 0;
for(int j = 0; j < 10 && FoundElev8 == false && !quit; j++) // Keep pinging until it replies, or we give up
{
ftdi.Write( txBuffer, 4, ref written );
System.Threading.Thread.Sleep( 50 );
uint bytesAvail = 0;
ftdi.GetRxBytesAvailable( ref bytesAvail ); // How much data is available from the serial port?
if(bytesAvail > 0)
{
int TestVal = 0;
while(bytesAvail > 0 && !quit)
{
uint bytesRead = 0;
ftdi.Read( rxBuffer, 1, ref bytesRead );
if(bytesRead == 1)
{
TestVal = (TestVal << 8) | rxBuffer[0];
if(TestVal == (int)(('E' << 0) | ('l' << 8) | ('v' << 16) | ('8' << 24)) )
{
FoundElev8 = true;
commStat = CommStatus.Connected;
break;
}
}
if(bytesRead == 0) break;
}
}
}
if(FoundElev8)
{
connected = true;
if(ConnectionStarted != null) {
ConnectionStarted();
}
break;
}
else
{
ftdi.Close();
}
}
}
}
}
catch(Exception)
{
return;
}
}