Close() public method

Closes the handle to an open FTDI device.
public Close ( ) : FT_STATUS
return FT_STATUS
		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;
			}
		}
		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;

					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;
						}

						ftdi.SetBaudRate( 115200 );
						ftdi.SetDataCharacteristics( 8, 1, 0 );
						ftdi.SetFlowControl( FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0 );


						txBuffer[0] = (byte)0;		// Set it to MODE_None to stop it writing (reset in case it was disconnected)
						txBuffer[1] = (byte)0xff;	// Send 0xff to the Prop to see if it replies
						uint written = 0;

						for(int j = 0; j < 10 && FoundElev8 == false; j++)	// Keep pinging until it replies, or we give up
						{
							ftdi.Write( txBuffer, 2, 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)
							{
								uint bytesRead = 0;
								ftdi.Read( rxBuffer, 1, ref bytesRead );			// If it comes back with 0xE8 it's the one we want
								if(bytesRead == 1 && rxBuffer[0] == 0xE8)
								{
									FoundElev8 = true;
									commStat = CommStatus.Connected;
									break;
								}
							}
						}

						if(FoundElev8) {
							connected = true;
							txBuffer[0] = 2;	// MODE_Sensors
							written = 0;
							ftdi.Write( txBuffer, 1, ref written );

							if(ConnectionStarted != null) {
								ConnectionStarted();
							}
							break;
						}
						else {
							ftdi.Close();
						}
					}
				}
			}

			catch(Exception)
			{
				return;
			}
		}
        protected bool OpenFTDIDevice(FTDI.FT_DEVICE_INFO_NODE deviceToOpen)
        {
            bool connected = false;

            lock (mFTDIDevice)
            {
                if (IsFTDIDeviceOpen())
                {
                    CloseFTDIDevice();
                }

                if (FTDI.IsFTD2XXDLLLoaded())
                {
                    if (deviceToOpen != null)
                    {
                        if (mFTDIDevice.OpenByLocation(deviceToOpen.LocId) == FTDI.FT_STATUS.FT_OK)
                        {
                            FTDI.FT_STATUS ftdiStatus = FTDI.FT_STATUS.FT_OK;

                            ftdiStatus |= mFTDIDevice.ResetDevice();
                            //ftdiStatus |= mFTDIDevice.ResetPort();
                            ftdiStatus |= mFTDIDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX);

                            if (ftdiStatus == FTDI.FT_STATUS.FT_OK)
                            {
                                DisplayStatusMessage("Opened FTDI device.", StatusMessageType.LOG);
                                DisplayStatusMessage("FTDI device info - Description: " + deviceToOpen.Description
                                                     + " Serial Number: " + deviceToOpen.SerialNumber + " Device Type: " + deviceToOpen.Type
                                                     + " ID: 0x" + deviceToOpen.ID.ToString("X") + " Device Flags: 0x" + deviceToOpen.Flags.ToString("X"), StatusMessageType.LOG);

                                if (FTDI.IsFTDChipIDDLLLoaded())
                                {
                                    DisplayStatusMessage("FTDI ChipID DLL is loaded, checking chip ID...", StatusMessageType.LOG);

                                    uint chipID = 0;
                                    if (mFTDIDevice.GetChipIDFromCurrentDevice(out chipID) == FTDI.FT_STATUS.FT_OK)
                                    {
                                        DisplayStatusMessage("FTDI device chip ID: 0x" + chipID.ToString("X"), StatusMessageType.LOG);
                                    }
                                    else
                                    {
                                        DisplayStatusMessage("Unable to read FTDI device chip ID", StatusMessageType.LOG);
                                    }
                                }

                                connected = true;
                            }
                            else
                            {
                                mFTDIDevice.Close();
                            }
                        }
                        else
                        {
                            DisplayStatusMessage("Could not open FTDI device", StatusMessageType.LOG);
                        }
                    }
                    else
                    {
                        DisplayStatusMessage("No FTDI device selected", StatusMessageType.LOG);
                    }
                }
                else
                {
                    DisplayStatusMessage("FTDI FTD2XX device driver DLL could not be loaded.", StatusMessageType.USER);
                }
            }

            return(connected);
        }
Esempio n. 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            //http://www.chd.at/blog/electronic/FTDI-in-CS
            //Note: don’t forget to connect the xDBUS1 with xDBUS2(!) = SDA

            Optifert.FTDI.Instance.Init(0);

            //Optifert.FTDI.Instance.close();

            if (Optifert.FTDI.Instance.isConnected())
            {
                Console.WriteLine("connected ");
            } else
            {
                Console.WriteLine("Not connected ");
            }

            Optifert.FTDI.Instance.close();

            UInt32 ftdiDeviceCount = 0;
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;

            // Create new instance of the FTDI device class
            FTDI myFtdiDevice = new FTDI();

            // Determine the number of FTDI devices connected to the machine
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                System.Diagnostics.Debug.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());
                System.Diagnostics.Debug.WriteLine("");
            }
            else
            {
                // Wait for a key press
                System.Diagnostics.Debug.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");

                return;
            }

            // If no devices available, return
            if (ftdiDeviceCount == 0)
            {
                // Wait for a key press
                Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Allocate storage for device info list
            FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];

            // Populate our device list
            ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);

            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                {
                    Console.WriteLine("Device Index: " + i.ToString());
                    Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                    Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString());
                    Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                    Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                    Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                    Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString());
                    Console.WriteLine("");
                }
            }

            // Open first device in our list by serial number
            ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Create our device EEPROM structure based on the type of device we have open
            if (ftdiDeviceList[0].Type == FTDI.FT_DEVICE.FT_DEVICE_232H)
            {
                Console.WriteLine("is 232 H");

            }

            myFtdiDevice.Close();
        }
Esempio n. 5
0
        static void open(FTDI myFtdiDevice)
        {
            UInt32 ftdiDeviceCount = 0;
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;

            // Determine the number of FTDI devices connected to the machine
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                return;
            }


            // If no devices available, return
            if (ftdiDeviceCount == 0) return;

            Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());


            // Allocate storage for device info list
            FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];

            // Populate our device list
            ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);

            int oIdx=-1;
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (Int32 i = 0; i < ftdiDeviceCount; i++)
                {
                    if (ftdiDeviceList[i].Type == FTDI.FT_DEVICE.FT_DEVICE_232R)
                    {
                        oIdx = i;
                    }
                }

                if (oIdx < 0)
                {
                    Console.WriteLine("no matching device");
                    return;
                }
            }

            Console.WriteLine("Device Index: " + oIdx.ToString());
            Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[oIdx].Flags));
            Console.WriteLine("Type: " + ftdiDeviceList[oIdx].Type.ToString());
            Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[oIdx].ID));
            Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[oIdx].LocId));
            Console.WriteLine("Serial Number: " + ftdiDeviceList[oIdx].SerialNumber.ToString());
            Console.WriteLine("Description: " + ftdiDeviceList[oIdx].Description.ToString());

            myFtdiDevice.SetDTR(false);
            myFtdiDevice.SetRTS(false);

            // Open first device in our list by serial number
            ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[oIdx].SerialNumber);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")");
                //Console.ReadKey();
                return;
            }

            myFtdiDevice.SetDTR(false);
            myFtdiDevice.SetRTS(false);

            // Set up device data parameters
            uint baud = 230400;
            if (ConfigurationManager.AppSettings["BaudRate"] != null)
            {
                baud = UInt32.Parse(ConfigurationManager.AppSettings["BaudRate"]);
            }
            ftStatus = myFtdiDevice.SetBaudRate(baud);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set Baud rate (error " + ftStatus.ToString() + ")");
                //Console.ReadKey();
                return;
            }

            // Set data characteristics - Data bits, Stop bits, Parity
            ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                //Console.ReadKey();
                return;
            }

            // Set flow control - set RTS/CTS flow control
            ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x11, 0x13);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set flow control (error " + ftStatus.ToString() + ")");
                //Console.ReadKey();
                return;
            }

            // times out at 100ms
            ftStatus = myFtdiDevice.SetTimeouts(100, 100);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set timeouts (error " + ftStatus.ToString() + ")");
                //Console.ReadKey();
                return;
            }

            attention();
            Console.WriteLine("CONNECTED. PRESS ANY KEY TO START.");
            Console.WriteLine("CTRL-R: RESET");
            Console.WriteLine("CTRL-P: PROGRAM");
            Console.WriteLine("CTRL-T: SET TIME");
            prompt();

            myFtdiDevice.SetDTR(true);
            Thread.Sleep(100);
            myFtdiDevice.SetDTR(false);

            while (true)
            {
                UInt32 numBytes = 0;
                byte[] buf = new byte[1024];

                while (Console.KeyAvailable)
                {
                    ConsoleKeyInfo cki = Console.ReadKey(true);
                    //Console.WriteLine("{0} (character '{1}')", cki.Key, cki.KeyChar);
                    if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
                    {
                        if (cki.Key.ToString().ToUpper().EndsWith("R"))
                        {
                            attention();
                            Console.WriteLine("\nRESET!");
                            prompt();

                            myFtdiDevice.SetRTS(false);
                            myFtdiDevice.SetDTR(true);
                            Thread.Sleep(100);
                            myFtdiDevice.SetDTR(false);
                            continue;
                        }
                        if (cki.Key.ToString().ToUpper().EndsWith("P"))
                        {
                            attention();

                            Console.WriteLine("\nPROGRAM MODE:");
                            myFtdiDevice.Close();
                            program();

                            string firmwareName = ConfigurationManager.AppSettings["FirmwareName"];
                            LpcProgrammer p = new LpcProgrammer(new StringOutDelegate(myStrDelegate));
                            //p.Prepare();
                            int r = p.Program(firmwareName);

                            attention();
                            Console.WriteLine("\nRETURN VALUE: {0}", r);
                            subdue();

                            throw new Exception("Leaving program mode");
                        }
                        if (cki.Key.ToString().ToUpper().EndsWith("T"))
                        {
                            //  Time: 10:11:0
                            //  Date: 2827.5.9
                            string datePatt = @"yyyy.M.d";
                            string timePatt = @"HH:mm:ss";
                            DateTime dispDt = DateTime.Now;
                            string dtString = "set_date " + dispDt.ToString(datePatt) + "\r";
                            string tmString = "set_time " + dispDt.ToString(timePatt) + "\r";
                            //Console.WriteLine(dtString);
                            //Console.WriteLine(tmString);
                            System.Text.ASCIIEncoding ASCII  = new System.Text.ASCIIEncoding();
                            Byte[] cmdBytes = ASCII.GetBytes(dtString);
                            myFtdiDevice.Write(cmdBytes, cmdBytes.Length, ref numBytes);
                            Thread.Sleep(200);
                            cmdBytes = ASCII.GetBytes(tmString);
                            myFtdiDevice.Write(cmdBytes, cmdBytes.Length, ref numBytes);
                            continue;
                        }
                    }
                    buf[0] = (byte)(cki.KeyChar & 0xff);
                  
                    numBytes = 0;
                    ftStatus = myFtdiDevice.Write(buf, 1, ref numBytes);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        throw new Exception("Failed to write to device (error " + ftStatus.ToString() + ")");
                        //return;
                    }
                }

                numBytes = 0;
                ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytes);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    throw new Exception("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                    //return;
                }
                if (numBytes > 0)
                {
                    UInt32 numBytesRead = 0;
                    byte[] buffer = new byte[1024];
                    // Note that the Read method is overloaded, so can read string or byte array data
                    //ftStatus = myFtdiDevice.Read(out readData, 1024, ref numBytesRead);
                    ftStatus = myFtdiDevice.Read(buffer, 1024, ref numBytesRead);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        // Wait for a key press
                        throw new Exception("Failed to read data (error " + ftStatus.ToString() + ")");
                        //Console.ReadKey();
                        //return;
                    }
                    string readData = System.Text.Encoding.ASCII.GetString(buffer, 0, (int)numBytesRead);
                    Console.Write(readData);
                }
                else
                {
                    Thread.Sleep(10);
                }

            }
        }
Esempio n. 6
0
        /// <summary>
        /// Called when the window is loaded
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            int i;
            
            // Configure datagrid
            dataGrid1.Items.Clear();
            dataGrid1.Columns.Clear();
            dataGrid1.Columns.Add(new DataGridTextColumn { Header = "Device Number", Binding = new Binding("Dn") });
            dataGrid1.Columns.Add(new DataGridTextColumn { Header = "Serial Number", Binding = new Binding("Sn") });
            dataGrid1.Columns.Add(new DataGridTextColumn { Header = "Device Description", Binding = new Binding("Dd") });

            // Get FTDI basic data
            FTDI f = new FTDI();
            uint devicecount = 0;
            f.GetNumberOfDevices(ref devicecount);

            // Fill datagrid with device data
            string dd, sn, dn;
            if (devicecount == 0)
            {
                FtErrorReport("GetFTDeviceCount", FTDI.FT_STATUS.FT_DEVICE_NOT_FOUND);
            }
            for (i = 0; i < devicecount; i++)
            {
                f.OpenByIndex((uint)i);
                dn = String.Format("Device {0}", i);
                f.GetSerialNumber(out sn);
                f.GetDescription(out dd);
                f.Close();
                dataGrid1.Items.Add( new SDevice{ Dd = dd, Dn = dn, Sn = sn } );
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            UInt32 ftdiDeviceCount = 0;
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;

            // Create new instance of the FTDI device class
            FTDI myFtdiDevice = new FTDI();

            // Determine the number of FTDI devices connected to the machine
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString());
                Console.WriteLine("");
            }
            else
            {
                // Wait for a key press
                Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // If no devices available, return
            if (ftdiDeviceCount == 0)
            {
                // Wait for a key press
                Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Allocate storage for device info list
            FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];

            // Populate our device list
            ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);

            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                {
                    Console.WriteLine("Device Index: " + i.ToString());
                    Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                    Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString());
                    Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                    Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                    Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                    Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString());
                    Console.WriteLine("");
                }
            }

            // Open first device in our list by serial number
            ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[1].SerialNumber);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Set up device data parameters
            // Set Baud rate to 9600
            ftStatus = myFtdiDevice.SetBaudRate(9600);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set Baud rate (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Set data characteristics - Data bits, Stop bits, Parity
            ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Set flow control - set RTS/CTS flow control

            ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE,0,0);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set flow control (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Set read timeout to 5 seconds, write timeout to infinite
            ftStatus = myFtdiDevice.SetTimeouts(5000, 0);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to set timeouts (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Perform loop back - make sure loop back connector is fitted to the device
            // Write string data to the device
            string dataToWrite = "Hello world!";
            UInt32 numBytesWritten = 0;
            // Note that the Write method is overloaded, so can write string or byte array data
            ftStatus = myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);

            myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_TX);
            if (numBytesWritten != dataToWrite.Length)
            {
                Console.WriteLine("Error writting");
                Console.Read();
                return;
            }

            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to write to device (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }

            // Check the amount of data available to read
            // In this case we know how much data we are expecting,
            // so wait until we have all of the bytes we have sent.
            UInt32 numBytesAvailable = 0;
            do
            {

                ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
                //Console.WriteLine(ftStatus + " " + numBytesAvailable);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    // Wait for a key press
                    Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                    Console.ReadKey();
                    return;
                }
                Thread.Sleep(10);
            } while (numBytesAvailable < dataToWrite.Length);

            // Now that we have the amount of data we want available, read it
            string readData;
            UInt32 numBytesRead = 0;
            // Note that the Read method is overloaded, so can read string or byte array data
            ftStatus = myFtdiDevice.Read(out readData, numBytesAvailable, ref numBytesRead);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                Console.WriteLine("Failed to read data (error " + ftStatus.ToString() + ")");
                Console.ReadKey();
                return;
            }
            Console.WriteLine(readData);

            // Close our device
            ftStatus = myFtdiDevice.Close();

            // Wait for a key press
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
            return;
        }
Esempio n. 8
0
		void ConnectFTDI()
		{
			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.NoDevices;
				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;

					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;
						}

						ftdi.SetBaudRate( 115200 );
						ftdi.SetDataCharacteristics( 8, 1, 0 );
						ftdi.SetFlowControl( FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0 );


						txBuffer[0] = (byte)0xff;	// Send 0xff to the Prop to see if it replies
						uint written = 0;

						for(int j = 0; j < 10 && FoundElev8 == false; j++)	// Keep pinging until it replies, or we give up
						{
							ftdi.Write( txBuffer, 1, 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)
							{
								uint bytesRead = 0;
								ftdi.Read( rxBuffer, 1, ref bytesRead );			// If it comes back with 0xE8 it's the one we want
								if(bytesRead == 1 && rxBuffer[0] == 0xE8)
								{
									FoundElev8 = true;
									commStat = CommStatus.Connected;
									break;
								}
							}
						}
						if(FoundElev8)
						{
							break;
						}
						else
						{
							ftdi.Close();
						}
					}
				}
			}

			catch(Exception) {
				return;
			}


			Active = true;
			if( ftdi.IsOpen ) {
				currentMode = (Mode)(tcMainTabs.SelectedIndex + 1);
				txBuffer[0] = (byte)currentMode;
				uint written = 0;
				ftdi.Write( txBuffer, 1, ref written );	// Which mode are we in?
			}

			// Start my 'tick timer' - It's set to tick every 20 milliseconds
			// (used to check the comm port periodically instead of using a thread)
			//tickTimer.Start();
		}
Esempio n. 9
-2
        public SetupDialogForm()
        {
            InitializeComponent();

            UInt32 ftdiDeviceCount = 0;
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
            // Create new instance of the FTDI device class
            FTDI tempFtdiDevice = new FTDI();
            // Determine the number of FTDI devices connected to the machine
            ftStatus = tempFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
                AvailableDevicesListBox.Items.Add("# of FTDI devices = " + ftdiDeviceCount.ToString());
            else
                throw new ASCOM.InvalidValueException("Error getting count FTDI devices");
            if (ftdiDeviceCount > 0)
            {
                // Allocate storage for device info list
                FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
                // Populate our device list
                ftStatus = tempFtdiDevice.GetDeviceList(ftdiDeviceList);
                //Show device properties
                if (ftStatus == FTDI.FT_STATUS.FT_OK)
                {
                    for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                    {
                        if (ftdiDeviceList[i].SerialNumber.Contains("CAM8"))
                        {
                            AvailableDevicesListBox.Items.Add("Device Index: " + i.ToString());
                            AvailableDevicesListBox.Items.Add("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                            AvailableDevicesListBox.Items.Add("Type: " + ftdiDeviceList[i].Type.ToString());
                            AvailableDevicesListBox.Items.Add("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                            AvailableDevicesListBox.Items.Add("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                            AvailableDevicesListBox.Items.Add("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                            AvailableDevicesListBox.Items.Add("Description: " + ftdiDeviceList[i].Description.ToString());
                            AvailableDevicesListBox.Items.Add("");
                        }
                    }
                }
                else throw new ASCOM.InvalidValueException("Error getting parameters from FTDI devices");
            }
            //Close device
            ftStatus = tempFtdiDevice.Close();

            // Initialise current values of user settings from the ASCOM Profile 
            chkTrace.Checked = Camera.traceState;
            coolerCheckBox.Checked = Camera.coolerEnabledState;
            //find available com ports in system
            string[] comPorts;
            comPorts = SerialPort.GetPortNames();
            int j;
            for (j = 0; j < comPorts.Length; j++)
            {
                coolerComPortComboBox.Items.Add(comPorts[j]);
                if (comPorts[j] == Camera.coolerComPortState) coolerComPortComboBox.SelectedIndex = j;
            }

        }
Esempio n. 10
-4
        public SetupDialogForm()
        {
            InitializeComponent();
            //Initialize components;

            UInt32 ftdiDeviceCount = 0;
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
            // Create new instance of the FTDI device class
            FTDI tempFtdiDevice = new FTDI();
            // Determine the number of FTDI devices connected to the machine
            ftStatus = tempFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
                AvailableDevicesListBox.Items.Add("# of FTDI devices = " + ftdiDeviceCount.ToString());
            else
                throw new ASCOM.InvalidValueException("Error getting count FTDI devices");
            if (ftdiDeviceCount > 0)
            {
                // Allocate storage for device info list
                FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
                // Populate our device list
                ftStatus = tempFtdiDevice.GetDeviceList(ftdiDeviceList);
                //Show device properties
                if (ftStatus == FTDI.FT_STATUS.FT_OK)
                {
                    for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                    {
                        AvailableDevicesListBox.Items.Add("Device Index: " + i.ToString());
                        AvailableDevicesListBox.Items.Add("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                        AvailableDevicesListBox.Items.Add("Type: " + ftdiDeviceList[i].Type.ToString());
                        AvailableDevicesListBox.Items.Add("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                        AvailableDevicesListBox.Items.Add("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                        AvailableDevicesListBox.Items.Add("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                        AvailableDevicesListBox.Items.Add("Description: " + ftdiDeviceList[i].Description.ToString());
                        AvailableDevicesListBox.Items.Add("");
                    }
                }
                else throw new ASCOM.InvalidValueException("Error getting parameters from FTDI devices");
            }
            //Close device
            ftStatus = tempFtdiDevice.Close();
        }