Example #1
0
        public void readRom()
        {
            keyProMap.Clear();
            content.Clear();
            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)
            {
                content.Append("Number of FTDI devices: " + ftdiDeviceCount.ToString() + "\n");
            }
            else
            {
                content.Append("Failed to get number of devices (error " + ftStatus.ToString() + ")" + "\n");
                return;
            }

            // If no devices available, return
            if (ftdiDeviceCount == 0)
            {
                // Wait for a key press
                content.Append("Failed to get number of devices (error " + ftStatus.ToString() + ")" + "\n");
                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);
            int numDevices = 0, ChipID = 0;

            FTChipID.ChipID.GetNumDevices(ref numDevices);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (int i = 0; i < ftdiDeviceCount; i++)
                {
                    FTChipID.ChipID.GetDeviceChipID(i, ref ChipID);

                    keyProMap.Add("0x" + ChipID.ToString("X"), ftdiDeviceList[i]);
                    content.Append("Device Index: " + i.ToString() + "\n");
                    content.Append("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags) + "\n");
                    content.Append("Type: " + ftdiDeviceList[i].Type.ToString() + "\n");
                    content.Append("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID) + "\n");
                    content.Append("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId) + "\n");
                    content.Append("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString() + "\n");
                    content.Append("Description: " + ftdiDeviceList[i].Description.ToString() + "\n");
                    content.Append("\n");
                }
            }
        }
Example #2
0
        private void FT232_Init()
        {
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("Failed to get number of devices (error " + ftStatus.ToString() + ")");
            }
            if (ftdiDeviceCount == 0)
            {
                MessageBox.Show("无可用的FTDI设备 (error " + ftStatus.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);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                label1.Text = "Type:" + ftdiDeviceList[0].Type.ToString();
                label2.Text = "Location ID: " + String.Format("{0:x}", ftdiDeviceList[0].LocId);
                label3.Text = "Serial Number: " + ftdiDeviceList[0].SerialNumber.ToString();
                label4.Text = "Description: " + ftdiDeviceList[0].Description.ToString();
            }
            ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
            OpenFlag = ftStatus;
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("打开设备失败 (error " + ftStatus.ToString() + ")");
            }
            ftStatus = myFtdiDevice.SetBaudRate(921600);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("波特率设置失败 (error " + ftStatus.ToString() + ")");
            }
            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)
            {
                MessageBox.Show("数据特征设置失败 (error " + ftStatus.ToString() + ")");
            }
            ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, 0x13);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("流控制设置失败 (error " + ftStatus.ToString() + ")");
            }
            ftStatus = myFtdiDevice.SetTimeouts(5000, 0);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("超时时间设置失败 (error " + ftStatus.ToString() + ")");
            }
            uint dwEventMask = FTDI.FT_EVENTS.FT_EVENT_RXCHAR;

            ftStatus = myFtdiDevice.SetEventNotification(dwEventMask, eventWait);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                MessageBox.Show("事件响应器设置失败 (error " + ftStatus.ToString() + ")");
            }
        }
Example #3
0
        public static List <Device> GetDeviceList()
        {
            List <Device> devices         = new List <Device>();
            UInt32        ftdiDeviceCount = 0;
            // Create new instance of the FTDI device class
            FTDI tempFtdiDevice = new FTDI();

            Logging.Info("Interogating FTDI for devices.");
            // Determine the number of FTDI devices connected to the machine
            FTDI.FT_STATUS ftStatus = tempFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                Logging.Error($"An error occured getting FTDI devices. {ftStatus.ToString()}");
                return(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 (var i = 0; i < ftdiDeviceCount; i++)
                    {
                        Device d = new Device
                        {
                            Index        = i,
                            Type         = ftdiDeviceList[i].Type.ToString(),
                            Id           = ftdiDeviceList[i].ID.ToString(),
                            Description  = ftdiDeviceList[i].Description,
                            SerialNumber = ftdiDeviceList[i].SerialNumber
                        };
                        devices.Add(d);
                    }
                }
                else
                {
                    Logging.Error($"Error getting FTDI device list {ftStatus.ToString()}");
                }
            }

            //Close device
            ftStatus = tempFtdiDevice.Close();
            Logging.Info("Closing FTDI device interogation.");

            return(devices);
        }
Example #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            // Determine the number of FTDI devices connected to the machine
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                textBox1.Text += "Number of FTDI devices: " + ftdiDeviceCount.ToString() + "\r\n";
            }
            else
            {
                // Wait for a key press
                textBox1.Text += "Failed to get number of devices (error " + ftStatus.ToString() + ")\r\n";
                return;
            }

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

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

            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                {
                    string tempDescription = ftdiDeviceList[i].Description.ToString();
                    string tempSerial      = ftdiDeviceList[i].SerialNumber.ToString();
                    if (tempDescription.Contains(textBox4.Text) && tempSerial.Contains(textBox3.Text))
                    {
                        deviceIndex    = (int)i;
                        textBox1.Text += "Device Index: " + i.ToString() + "\r\n";
                        textBox1.Text += "Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags) + "\r\n";
                        textBox1.Text += "Type: " + ftdiDeviceList[i].Type.ToString() + "\r\n";
                        textBox1.Text += "ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID) + "\r\n";
                        textBox1.Text += "Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId) + "\r\n";
                        textBox1.Text += "Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString() + "\r\n";
                        textBox1.Text += "Description: " + ftdiDeviceList[i].Description.ToString() + "\r\n\r\n";
                    }
                }
            }
        }
Example #5
0
        void RefreshDevice()
        {
            FTDI_combo.Items.Clear();
            FTDISerialNumber = null;
            UInt32 ftdiDeviceCount = 0;

            FTDI.FT_STATUS ftStatus     = FTDI.FT_STATUS.FT_OK;
            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)
            {
            }
            else
            {
                // Wait for a key press
                MessageBox.Show("error :" + ftStatus.ToString());
                return;
            }
            if (ftdiDeviceCount == 0)
            {
                // Wait for a key press
                return;
            }
            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)
            {
                FTDISerialNumber = new string[ftdiDeviceCount];
                comboBox1.Items.Clear();
                for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                {
                    FTDI_combo.Items.Add(ftdiDeviceList[i].Description.ToString());
                    FTDISerialNumber[i] = ftdiDeviceList[i].SerialNumber.ToString();
                    comboBox1.Items.Add(FTDISerialNumber[i]);
                }
            }
            else
            {
                MessageBox.Show("error :" + ftStatus.ToString());
                return;
            }
            FTDI_combo.SelectedIndex = 0;
        }
Example #6
0
        protected void init(MpsseParams param)
        {
            FTDI.FT_STATUS ftStatus = ftdi.ResetDevice();

            DataReadEvent  += param.DataReadEvent;
            DataWriteEvent += param.DataWriteEvent;

            clearInput();

            ftStatus |= ftdi.InTransferSize(param.transferSize);
            ftStatus |= ftdi.SetCharacters(param.EventChar, param.EventCharEnable,
                                           param.ErrorChar, param.ErrorCharEnable);
            ftStatus |= ftdi.SetTimeouts(param.ReadTimeout, param.WriteTimeout);
            ftStatus |= ftdi.SetLatency(param.Latency);

            ftStatus |= ftdi.SetBitMode(0x0, 0x00); //Reset controller
            ftStatus |= ftdi.SetBitMode(0x0, 0x02); //Enable MPSSE mode

            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                String errMsg = "fail to initialize device (error " + ftStatus.ToString() + ")";
                throw new FtdiException(errMsg);
            }

            sendBadCommand(0xAA); // Synchronize the MPSSE interface by sending bad command &xAA*
            sendBadCommand(0xAB); // Synchronize the MPSSE interface by sending bad command &xAB*

            ClkDivisor = param.clockDevisor;
        }
Example #7
0
 private void OpenIdFTDI()
 {
     if (ftdiDeviceList != null)
     {
         // Open first device in our list by serial number
         //ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
         //ftStatus = myFtdiDevice.OpenBySerialNumber(comboBox1.Text);
         ftStatus = myFtdiDevice.OpenByLocation(Convert.ToUInt32(comboBox1.Text));
         Log("Opening device " + comboBox1.Text);
         if (ftStatus != FTDI.FT_STATUS.FT_OK)
         {
             // Wait for a key press
             Log("Failed to open device (error " + ftStatus.ToString() + ")");
             Text = "BitBang - Failed to open";
             return;
         }
         else
         {
             Log("Device opened succesfully");
         }
     }
     else
     {
         Log("NULL");
     }
     Log("_____________________________________");
 }
Example #8
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (deviceIndex >= 0)
            {
                ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[deviceIndex].SerialNumber);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    // Wait for a key press
                    textBox1.Text += "Failed to open device (error " + ftStatus.ToString() + ")\r\n";
                    return;
                }
                else
                {
                    textBox1.Text += "Device opened !!!\r\n";
                }
            }

            ftStatus = myFtdiDevice.SetBitMode(0x00, 0x40);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                textBox1.Text += "Failed to set bit mode (error " + ftStatus.ToString() + ")\r\n";
                return;
            }
            else
            {
                textBox1.Text += "Bit mode = 0x40 !!!\r\n";
            }
        }
Example #9
0
 static void chk(FTDI.FT_STATUS s)
 {
     if (s != FTDI.FT_STATUS.FT_OK)
     {
         throw new Exception(s.ToString());
     }
 }
Example #10
0
        public void sendMsg(byte[] dataToWrite)
        {
            // purge the rest of the message
            ftStatus = ftdi_handle.Purge(FTDI.FT_PURGE.FT_PURGE_RX);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                listBox1.Items.Add("Failed to Purge RX buffer (error " + ftStatus.ToString() + ")");
                return;
            }

            // Write string data to the device

            //byte[] dataToWrite = sRN_DeviceIdent_BA;
            UInt32 numBytesWritten = 0;

            // Note that the Write method is overloaded, so can write string or byte array data
            ftStatus = ftdi_handle.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                listBox1.Items.Add("Failed to write to device (error " + ftStatus.ToString() + ")");
                return;
            }

            //listBox2.Items.Add(BitConverter.ToString(dataToWrite));
            return;
        }
Example #11
0
        public byte[] read(uint bytesToRead = 0)
        {
            if (bytesToRead == 0)
            {
                bytesToRead = inputLen;
            }

            byte[] result = new byte[bytesToRead];
            byte[] buffer = new byte[ioBufferSize];

            uint bytesReaded = 0;

            while (bytesToRead > 0)
            {
                uint readed = 0;
                uint toRead = (bytesToRead > ioBufferSize) ? ioBufferSize : bytesToRead;

                lock (_lock)
                {
                    FTDI.FT_STATUS ftStatus = ftdi.Read(buffer, toRead, ref readed);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        String errMsg = "Failed to Read (error " + ftStatus.ToString() + ")";
                        throw new FtdiException(errMsg);
                    }
                }

                Array.Copy(buffer, 0, result, bytesReaded, readed);
                bytesReaded += readed;
                bytesToRead -= readed;
            }

            DataReadDebugInfo(result);
            return(result);
        }
Example #12
0
        public void write(byte[] data)
        {
            DataWriteDebugInfo(data);

            byte[] outputBuffer = (byte[])data.Clone();
            while (outputBuffer.Length > 0)
            {
                uint bytesWritten = 0;
                lock (_lock)
                {
                    FTDI.FT_STATUS ftStatus = ftdi.Write(outputBuffer, outputBuffer.Length, ref bytesWritten);

                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        String errMsg = "fail to Write (error " + ftStatus.ToString() + ")";
                        throw new FtdiException(errMsg);
                    }
                }

                long   bytesToWrite  = outputBuffer.Length - bytesWritten;
                byte[] remainingData = new byte[bytesToWrite];
                Array.Copy(outputBuffer, bytesWritten, remainingData, 0, bytesToWrite);
                outputBuffer = remainingData;
            }
        }
Example #13
0
            public override void CommSet(BaudRate baud_rate)
            {
                try
                {
                    ftStatus = ftdi.SetBaudRate((uint)baud_rate);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        throw new Bsl430NetException(340, ftStatus.ToString());
                    }

                    ftStatus = ftdi.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_EVEN);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        throw new Bsl430NetException(340, ftStatus.ToString());
                    }

                    ftStatus = ftdi.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x00, 0x00);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        throw new Bsl430NetException(340, ftStatus.ToString());
                    }

                    ftStatus = ftdi.SetTimeouts(5000, 0);
                    if (ftStatus != FTDI.FT_STATUS.FT_OK)
                    {
                        throw new Bsl430NetException(340, ftStatus.ToString());
                    }
                }
                catch (Exception ex) { throw new Bsl430NetException(341, ex); }
            }
Example #14
0
        public int[] readfromDevice()
        {
            UInt32 numBytesAvailable = 0;

            //ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX);
            ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                MessageBox.Show("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                //return;
            }
            //lines = Int32.Parse(RealTimeSignal_number.EditValue.ToString());
            UInt32 numBytesRead = 0;

            byte[] buff = new byte[numBytesAvailable];
            ftStatus = myFtdiDevice.Read(buff, numBytesAvailable, ref numBytesRead);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                // Wait for a key press
                MessageBox.Show("Failed to read data (error " + ftStatus.ToString() + ")");
                // return;
            }

            return(processIntInput(buff));
        }
Example #15
0
        private void RxCheckTimer_Tick(object sender, EventArgs e)
        {
            RxCheckTimer.Enabled = false;
            uint   RxCount    = 0;
            var    rx_buf     = new byte[1000];
            string rx_str_buf = "";
            uint   data_read  = 0;

            ftStatus = myFtdiDevice.GetRxBytesAvailable(ref RxCount);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                textBox1.Text = "<<ERROR: " + ftStatus.ToString() + "\r\n";
            }
            else if (RxCount > 0)
            {
                ftStatus = myFtdiDevice.Read(rx_buf, RxCount, ref data_read);
                //rx_str_buf = System.Text.Encoding.Default.GetString(rx_buf);
                rx_str_buf     = BitConverter.ToString(rx_buf);
                textBox1.Text += "Received " + RxCount + " bytes   <<" + rx_str_buf + ">>\r\n\r\n";
            }
            else
            {
                //textBox1.Text += "<> " + RxCount + " <>" + "\r\n";
            }
            RxCheckTimer.Enabled = true;
        }
Example #16
0
        private void Reciever_DoWork(object sender, DoWorkEventArgs e)
        {
            UInt32 numBytesAvailable = 0;

            do
            {
                ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    // Wait for a key press
                    MessageBox.Show("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                }
            } 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
                MessageBox.Show("Failed to read data (error " + ftStatus.ToString() + ")");
            }
            textBox2.AppendText(readData);
        }
Example #17
0
        private void lin_raw_repeat_func(object sender, EventArgs e)
        {
            byte identifier, data, checksum;

            if (!byte.TryParse(_lin_raw_identifier.Text, NumberStyles.HexNumber, null, out identifier))
            {
                ShowError("Identifier have invalid format");
                return;
            }

            if (!byte.TryParse(_lin_raw_data.Text, NumberStyles.HexNumber, null, out data))
            {
                ShowError("Identifier have data format");
                return;
            }

            if (!byte.TryParse(_lin_raw_checksum.Text, NumberStyles.HexNumber, null, out checksum))
            {
                ShowError("Identifier have checksum format");
                return;
            }

            FTDI.FT_STATUS status = lin_raw_send_data(Convert.ToUInt32(_lin_raw_baudrate.Value), identifier, data, checksum);
            if (status != FTDI.FT_STATUS.FT_OK)
            {
                ShowError("Failed to set data characteristics (error " + status.ToString() + ")");
            }
        }
Example #18
0
        private void refreshFTDIDevicesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            // Check status
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                // MessageBox.Show("Number of FTDI devices: " + ftdiDeviceCount.ToString());
                //  richTextBox1.AppendText("Number of FTDI devices: " + ftdiDeviceCount.ToString());
            }
            else
            {
                // Wait for a key press

                MessageBox.Show("Failed to get number of devices (error " + ftStatus.ToString() + ")");
            }

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

            // Allocate storage for device info list
            FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
            NuberOFFTDIDevieces.Text = "number of FT Devices :" + ftdiDeviceCount + "";
            // Populate our device list
            ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList);

            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                //for (UInt32 i = 0; i < ftdiDeviceCount; i++)
                //{
                //    // + Environment.NewLine
                //    richTextBox1.Text += ("Device Index: " + i.ToString());
                //    richTextBox1.Text += ("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                //    richTextBox1.Text += ("Type: " + ftdiDeviceList[i].Type.ToString());
                //    richTextBox1.Text += ("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                //    richTextBox1.Text += ("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                //    richTextBox1.Text += ("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                //    richTextBox1.Text += ("Description: " + ftdiDeviceList[i].Description.ToString());
                //    richTextBox1.Text += ("");
                //}
                //toolStripStatusLabel2.Text += "FT_OK";
                statusLed.Value = true;
            }
        }
        public mainForm()
        {
            InitializeComponent();
            label1.Text = "Searching for Devices...";


            EasyTimer.SetInterval(() =>
            {
                // start FTDI communication
                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);

                if (ftStatus == FTDI.FT_STATUS.FT_OK)
                {
                    label1.Text = "Number of FTDI devices: " + ftdiDeviceCount.ToString();
                }
                else
                {
                    // Wait for a key press
                    label1.Text = "Failed to get number of devices (error: " + ftStatus.ToString() + ")";
                    return;
                }

                // If no devices available, return
                if (ftdiDeviceCount == 0)
                {
                    label1.Text = "No Devices Found (error " + ftStatus.ToString() + ")";
                    return;
                }
                else
                {
                    label1.Text = "Got Devices! (Mssg: " + ftStatus.ToString() + ")";
                }

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

                // --- You code here ---
                // This piece of code will once after 1000 ms delay
            }, 1000);
        }
Example #20
0
 private void CheckStatus(FTDI.FT_STATUS status)
 {
     if (status != FTDI.FT_STATUS.FT_OK)
     {
         FTDI.FT_EXCEPTION ex = new FTDI.FT_EXCEPTION($"Error: {status.ToString()}");
         throw ex;
     }
 }
Example #21
0
 public void purge(uint mask)
 {
     FTDI.FT_STATUS ftStatus = ftdi.Purge(mask);
     if (ftStatus != FTDI.FT_STATUS.FT_OK)
     {
         String errMsg = "fail to Write (error " + ftStatus.ToString() + ")";
         throw new FtdiException(errMsg);
     }
 }
Example #22
0
 private void SetRW(byte rw)
 {
     if (myFtdiDevice.IsOpen)
     {
         ftStatus = myFtdiDevice.SetBitMode(rw, FTDI.FT_BIT_MODES.FT_BIT_MODE_ASYNC_BITBANG);
         Log("Setting mode status: " + ftStatus.ToString());
     }
     else
     {
         Log("Error: Device is closed!");
     }
 }
Example #23
0
 public override void CommClrBuff()
 {
     try
     {
         ftStatus = ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX);
         if (ftStatus != FTDI.FT_STATUS.FT_OK)
         {
             throw new Bsl430NetException(370, ftStatus.ToString());
         }
     }
     catch (Exception ex) { throw new Bsl430NetException(371, ex); }
 }
Example #24
0
        public string GetComPort()
        {
            string rv;

            FTDI.FT_STATUS ftStatus = ftdi.GetCOMPort(out rv);
            if (ftStatus != FTDI.FT_STATUS.FT_OK)
            {
                String errMsg = "failed to get ComPort (error " + ftStatus.ToString() + ")";
                throw new FtdiException(errMsg);
            }
            return(rv);
        }
Example #25
0
        private static FTDI.FT_DEVICE_INFO_NODE[] GetDeviceList(FTDI ftdi, UInt32 ftdiDeviceCount)
        {
            FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
            FTDI.FT_STATUS             ftStatus       = ftdi.GetDeviceList(ftdiDeviceList);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                return(ftdiDeviceList);
            }

            String errMsg = "Failed to get device list (error " + ftStatus.ToString() + ")";

            throw new FtdiException(errMsg);
        }
Example #26
0
        private void open(string serialNumber)
        {
            lock (_lock)
            {
                FTDI.FT_STATUS ftStatus = ftdi.OpenBySerialNumber(serialNumber);
                if (ftStatus == FTDI.FT_STATUS.FT_OK)
                {
                    return;
                }

                String errMsg = "Failed to open device (error " + ftStatus.ToString() + ")";
                throw new FtdiException(errMsg);
            }
        }
Example #27
0
        // Determine the number of FTDI devices connected to the machine
        private static UInt32 GetNumberOfDevices(FTDI ftdi)
        {
            UInt32 ftdiDeviceCount = 0;

            FTDI.FT_STATUS ftStatus = ftdi.GetNumberOfDevices(ref ftdiDeviceCount);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                return(ftdiDeviceCount);
            }

            String errMsg = "Failed to get number of devices (error " + ftStatus.ToString() + ")";

            throw new FtdiException(errMsg);
        }
Example #28
0
 private void button3_Click(object sender, EventArgs e)
 {
     ftStatus = myFtdiDevice.Close();
     if (ftStatus != FTDI.FT_STATUS.FT_OK)
     {
         // Wait for a key press
         textBox1.Text += "Failed to close device (error " + ftStatus.ToString() + ")\r\n";
         return;
     }
     else
     {
         textBox1.Text += "Device closed !!!" + "\r\n";
     }
 }
Example #29
0
        /// <summary>
        /// Find the FDTI chip, connect, set baud to 9600, set sync bit-bang mode
        /// </summary>
        /// <returns></returns>
        public bool connect()
        {
            // 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
            {
                Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                return(false);
            }

            if (ftdiDeviceCount == 0)
            {
                Console.WriteLine("Relay board not found, please try again");
                return(false);
            }
            else
            {
                // 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);

                // Open first device in our list by serial number
                ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);

                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    Console.WriteLine("Error connecting to relay board");
                    return(false);
                }

                // Set Baud rate to 9600
                ftStatus = myFtdiDevice.SetBaudRate(9600);

                // Set FT245RL to synchronous bit-bang mode, used on sainsmart relay board
                myFtdiDevice.SetBitMode(0xFF, FTD2XX_NET.FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_BITBANG);
                // Switch off all the relays
                myFtdiDevice.Write(startup, 1, ref bytesToSend);

                return(true);
            }
        }
Example #30
0
        /// <summary>
        /// Find the FDTI chip, connect, set baud to 9600, set sync bit-bang mode
        /// </summary>
        /// <returns></returns>
        public bool connect()
        {
            // 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
            {
                Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                return false;
            }

            if (ftdiDeviceCount == 0)
            {              
                Console.WriteLine("Relay board not found, please try again");
                return false;
            }
            else
            {
                // 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);

                // Open first device in our list by serial number
                ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);

                if (ftStatus != FTDI.FT_STATUS.FT_OK)
                {
                    Console.WriteLine("Error connecting to relay board");
                    return false;
                }

                // Set Baud rate to 9600
                ftStatus = myFtdiDevice.SetBaudRate(9600);

                // Set FT245RL to synchronous bit-bang mode, used on sainsmart relay board
                myFtdiDevice.SetBitMode(0xFF, FTD2XX_NET.FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_BITBANG);
                // Switch off all the relays
                myFtdiDevice.Write(startup, 1, ref bytesToSend);

                return true;
            }
        }
Example #31
0
 public override void CommRts(bool val, bool ignore_err = false)
 {
     try
     {
         ftStatus = ftdi.SetRTS(val);
         if (ftStatus != FTDI.FT_STATUS.FT_OK)
         {
             throw new Bsl430NetException(360, ftStatus.ToString());
         }
     }
     catch (Exception ex) { if (!ignore_err)
                            {
                                throw new Bsl430NetException(361, ex);
                            }
     }
 }
Example #32
0
        public void ReadFromChip(char portName, ReadFunctionType call)
        {
            if (portName != 'A' && portName != 'B') throw new Exception("Invalid port name "
                + portName + ". Should be A or B.");
            FTDI rdPort = (portName == 'B') ? portB : portA;
            if (rdPort == null) throw new Exception("No port " + portName + " exists");
            if (!rdPort.IsOpen) throw new Exception("Port " + portName + " is closed");

            uint numBytesAvailable = 0;
            DateTime startClock = DateTime.Now;

            lock (rdPort) {
                // Nothing will be able to write to the chip until ReadFromChip has returned,
                // is this the desired behaviour?
                while (numBytesAvailable <= 0) {
                    // Wait for 2 seconds for data, then throw error
                    if ((DateTime.Now - startClock).TotalSeconds > 2)
                        throw new Exception("2 seconds elapsed with no data. Was data expected?");

                    System.Threading.Thread.Sleep(20);
                    if ((ftStatus = rdPort.GetRxBytesAvailable(ref numBytesAvailable)) != FTDI.FT_STATUS.FT_OK) {
                        throw new FTDI.FT_EXCEPTION("Failed to get number of available bytes from "
                            + portName + ". err: " + ftStatus.ToString());
                    }
                }

                byte[] readData = new byte[numBytesAvailable];
                uint numBytesRead = 0;

                if ((ftStatus = rdPort.Read(readData, numBytesAvailable, ref numBytesRead)) != FTDI.FT_STATUS.FT_OK) {
                    throw new FTDI.FT_EXCEPTION("Failed to read data from "
                        + portName + ". err: " + ftStatus.ToString());
                }
                if (readData.Length != numBytesRead) throw new Exception("Read length mismatch");

                call(portName, readData.ToList());
                // Notify all threads of a change in port status
                System.Threading.Monitor.PulseAll(rdPort);
            }
        }
Example #33
0
        private void Open(FTDI port, string description)
        {
            uint deviceCount = 0;

            if (port == null) throw new Exception(description + "is not initialized");
            if (port.IsOpen) {
                Global.ShowError(description + " is already open");
                return;
            }

            // Determine the number of FTDI devices connected to the machine
            if ((ftStatus = port.GetNumberOfDevices(ref deviceCount)) != FTDI.FT_STATUS.FT_OK) {
                throw new FTDI.FT_EXCEPTION("Failed to get number of devices. err: " + ftStatus.ToString());
            }

            // If no devices available, return
            if (deviceCount == 0) throw new Exception("No devices on " + description);

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

            // Populate our device list
            if ((ftStatus = port.GetDeviceList(ftdiDeviceList)) != FTDI.FT_STATUS.FT_OK) {
                throw new FTDI.FT_EXCEPTION("Failed to get device list. err " + ftStatus.ToString());
            }

            int foundIndex = -1;
            for (int i = 0; i < deviceCount; i++) {
                if (ftdiDeviceList[i].Description.ToString().Contains(description)) {
                    foundIndex = 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("");
                */
            }
            if (foundIndex < 0) {
                throw new Exception("Failed to find device with description " + description);
            }

            if ((ftStatus = port.OpenByIndex((uint) foundIndex)) != FTDI.FT_STATUS.FT_OK) {
                throw new FTDI.FT_EXCEPTION("Failed to open device. err: " + ftStatus.ToString());
            }
        }
Example #34
0
 // Set Async or Sync FIFO bit mode
 static void SetMode(bool sync_mode)
 {
     // Do nothing if already in desired mode (avoids unnecessary reset)
     if ( sync_mode == Program.sync_mode ) {
         //    return;
     }
     Program.sync_mode = sync_mode;
     // Reset to Async Mode
     ftStatus = ftdiDevice.SetBitMode(0xFF, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET);
     if ( ftStatus != FTDI.FT_STATUS.FT_OK ) {
         Console.WriteLine("Failed to reset device to AsyncFIFO mode (error " + ftStatus.ToString() + ")");
         return;
     }
     Thread.Sleep(10);
     if ( sync_mode ) {
         Thread.Sleep(100);
         ftStatus = ftdiDevice.SetBitMode(0xFF, FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO);
         if ( ftStatus != FTDI.FT_STATUS.FT_OK ) {
             Console.WriteLine("Failed to initialize SyncFIFO mode (error " + ftStatus.ToString() + ")");
             return;
         }
         //Console.WriteLine("\n > Sync");
     }
     else {
         //Console.WriteLine("\n > Async");
     }
 }
Example #35
0
        public void Connect()
        {
            Logger.Log("CONNECTING USB GECKO.");
            ftStatus = FTDI.FT_STATUS.FT_OK;

            // determine the number of ftdi devices connected to the machine.
            uint ftdiDeviceCount = 0;
            ftStatus = this.ftdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Logger.Log("Number of FTDI devices: " + ftdiDeviceCount.ToString());
            }
            else
            {
                Logger.Log("FAILED to get number of devices (error " + ftStatus.ToString() + ")");
                Disconnect();
                return;
            }

            // if no devices available, return
            if (ftdiDeviceCount == 0)
            {
                Logger.Log("FAILED because no devices returned.");
                Disconnect();
                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 = this.ftdiDevice.GetDeviceList(ftdiDeviceList);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                for (uint i = 0; i < ftdiDeviceCount; i++)
                {
                    Logger.Log("Device Index: " + i.ToString());
                    Logger.Log("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags));
                    Logger.Log("Type: " + ftdiDeviceList[i].Type.ToString());
                    Logger.Log("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID));
                    Logger.Log("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId));
                    Logger.Log("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString());
                    Logger.Log("Description: " + ftdiDeviceList[i].Description.ToString());
                }
            }
            else
            {
                Logger.Log("FAILED to get device list.");
                Disconnect();
                return;
            }

            // open first device in our list by serial number
            ftStatus = this.ftdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Logger.Log("opened device with serial number " + ftdiDeviceList[0].SerialNumber);
            }
            else
            {
                Logger.Log("FAILED to open device (error " + ftStatus.ToString() + ")");
                Disconnect();
                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
            //	Logger.Log("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
            //	Logger.Log("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_RTS_CTS, 0x11, 0x13);
            //if (ftStatus != FTDI.FT_STATUS.FT_OK)
            //{
            //	// Wait for a key press
            //	Logger.Log("Failed to set flow control (error " + ftStatus.ToString() + ")");
            //	Console.ReadKey();
            //	return;
            //}

            // set read timeout to 1 seconds, write timeout to 1 second
            ftStatus = this.ftdiDevice.SetTimeouts(1000, 1000);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Logger.Log("Set Timeouts to 5 seconds for reads and infinite for writes.");
            }
            else
            {
                Logger.Log("FAILED to set timeouts (error " + ftStatus.ToString() + ")");
                Disconnect();
                return;
            }

            // set latency timer to minimum of 2ms.
            byte latencyTimer = 2;
            ftStatus = this.ftdiDevice.SetLatency(latencyTimer);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Logger.Log("Set latency timer to 2ms.");
            }
            else
            {
                Logger.Log("FAILED to set latency timer.");
                Disconnect();
                return;
            }

            // set transfer rate from default of 4096 bytes to max 64k.
            uint transferSize = 65536;
            ftStatus = this.ftdiDevice.InTransferSize(transferSize);
            if (ftStatus == FTDI.FT_STATUS.FT_OK)
            {
                Logger.Log("Set transfer size to max 64kb.");
            }
            else
            {
                Logger.Log("FAILED to set transfer size");
                Disconnect();
                return;
            }

            // initialise usb gecko
            if (Initialize())
            {
                this.isConnected = true;
                return;
            }
            else
            {
                Logger.Log("FAILED to initialize ftdi device.");
                Disconnect();
                return;
            }
        }
Example #36
0
        // Wait until at least one QuadCam is attached
        // Returns the first QuadCam serial number found
        // Return "" after timeout_seconds or no timeout if timeout_seconds < 1
        static String WaitForQuadCam(int timeout_seconds)
        {
            int timeout_ticks = timeout_seconds * 10;
            int timeout_ticks_counter = 0;
            bool reported_fail = false;
            bool reported_no_quadcam = false;
            bool reported_no_ftdi = false;
            UInt32 ftdiDeviceCount = 0;

            // Poll devices until timeout expires
            while ( timeout_ticks_counter < timeout_ticks || timeout_seconds <= 0 ) {

                // Attempt to count number of attached devices
                ftStatus = ftdiDevice.GetNumberOfDevices(ref ftdiDeviceCount);

                // If device count was determined...
                if ( ftStatus == FTDI.FT_STATUS.FT_OK ) {

                    // If at least one FTDI device was detected...
                    if ( ftdiDeviceCount != 0 ) {
                        String serial = GetQuadCamSerial(ftdiDeviceCount);

                        // If a QuadCam serial number was found...
                        if ( serial != "" ) {
                            return serial;
                        }

                        // If no QuadCam serials found, report once and recheck indefinitely
                        else {
                            if ( !reported_no_quadcam ) {
                                Console.WriteLine("No QuadCam found");
                                reported_no_quadcam = true;
                            }
                        }
                    }

                    // If device count is 0, report the absence once and recheck indefinitely
                    else {
                        if ( !reported_no_ftdi ) {
                            Console.WriteLine("No FTDI devices detected");
                            reported_no_ftdi = true;
                        }
                    }
                }

                // If device count cannot be determined, report an error once and reattempt indefinitely
                else {
                    if ( !reported_fail ) {
                        Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")");
                        reported_fail = true;
                    }
                }

                Thread.Sleep(100);
                ++timeout_ticks_counter;
            }

            Console.WriteLine("Timeout: WaitForQuadCam(): No QuadCams detected");
            return "";
        }
Example #37
0
        public static void Read(FTDI FtdiDevice, UInt32 numToRead, ref byte[] readData, ref UInt32 nBytesRead)
        {
            int i;
            bool frame_end = false;

            String line = "";

            UInt32 numBytesRead = 0;
            UInt32 numBytesAvailable = 0;

            while ( numBytesRead == 0 ) {

                ftStatus = Program.ftdiDevice.GetRxBytesAvailable(ref numBytesAvailable);
                if ( ftStatus != FTDI.FT_STATUS.FT_OK ) {
                    Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")");
                    Thread.Sleep(1000);
                    continue;
                }

                if ( numToRead == 0 ) {
                    ftStatus = Program.ftdiDevice.Read(readData, numBytesAvailable, ref numBytesRead);
                    Thread.Sleep(1);
                }
                else {
                    ftStatus = Program.ftdiDevice.Read(readData, numToRead, ref numBytesRead);
                }
                if ( ftStatus != FTDI.FT_STATUS.FT_OK ) {
                    Console.WriteLine("Failed to read data (error " + ftStatus.ToString() + ")");
                    Console.ReadKey();
                    return;
                }

            }

            nBytesRead = numBytesRead;
            numBytesRead = 0;

            if ( !Program.sync_mode ) {

                for ( i = 0; i < nBytesRead; ++i ) {

                    //line += String.Format("{0:X2}", readData[i]);
                    line += (char)readData[i];

                    if ( is_frame ) {
                        frame_raw[frame_raw_i] = readData[i];
                        ++frame_raw_i;
                    }

                    if ( check_frame_start((char)readData[i]) ) {
                        is_frame = true;
                        Console.Write("Frame Start\n");
                        stopwatch.Reset();
                        stopwatch.Start();
                    }

                    frame_end = check_frame_end((char)readData[i]);
                    if ( is_frame && frame_end ) {
                        stopwatch.Stop();
                        int frame_size = 2 * 1024 * 1280;
                        double transfer_dur = stopwatch.Elapsed.TotalSeconds;
                        Console.Write("Frame End - {0:F2} Mb/sec \n", (frame_size*8) / (1024 * 1024 * transfer_dur));
                        is_frame = false;
                        collate_frame(frame_raw, frame_rgb565);
                        frame_raw_i = 0;
                        up565_to_up888(frame_rgb565, frame_rgb888);

                        string pwd = System.IO.Directory.GetCurrentDirectory(); // Executable directory (ie. ./bin/Debug/)

                        // Write unpacked RGB565 format
                        System.IO.StreamWriter file1 = new System.IO.StreamWriter(pwd + @"\usb_up565.dat");
                        for ( i = 0; i < 2 * 1024 * 1280; ++i ) {
                            file1.Write(frame_rgb565[i]);
                        }
                        file1.Close();

                        // Write unpacked RGB888 format
                        System.IO.BinaryWriter file2 = new System.IO.BinaryWriter(new System.IO.FileStream(pwd + @"\usb_up888.dat", System.IO.FileMode.Create));
                        for ( i = 0; i < 3 * 1024 * 1280; ++i ) {
                            file2.Write (frame_rgb888[i]);
                        }
                        file2.Close();

                        Console.Write("Image Saved\n");

                        // Convert raw image data to bitmap, 1280x1024 res
                        string strCmdText;
                        strCmdText = "1280 1024 " + pwd + @"\usb_up888.dat " + pwd + @"\usb_up888.bmp";
                        Process dat_to_bmp = System.Diagnostics.Process.Start(pwd + @"\..\..\dat_to_bmp.exe", strCmdText);
                        dat_to_bmp.WaitForExit(); // Must wait for conversion to finish

                        /*
                        // Display bitmap using MS Paint
                        System.Diagnostics.Process.Start(@"C:\windows\system32\mspaint.exe", pwd + @"\usb_up888.bmp");
                        */

                        // Crop bitmap into separate camera images
                        Image srcImage = Image.FromFile(pwd + @"\usb_up888.bmp");
                        split_image(srcImage, pwd);

                        Console.Write("Ready\n");

                        /* Mailslot functionality not yet working - 2015-08-18
                        using (var client = new MailslotClient("QuadCam\\ImageReady"))
                        {
                            client.SendMessage("ImageReady");
                        }
                        */
                    }
                    /*
                    if ( check_sync((char)readData[i]) ) {
                        SetSyncMode();
                    }
                    */
                }

                if ( !is_frame && !frame_end ) {
                    Console.Write(line);
                }
                line = "";
            }
        }
Example #38
0
        public void WriteToChip(char portName, List<byte> data)
        {
            if (!isOpen) throw new Exception("Ftdi not initialized");

            uint bytesWritten = 0;
            uint bytesWaiting = 1;

            if (portName == 'A') {
                var dataReverse = new List<byte>();
                dataReverse.InsertRange(0, data);
                dataReverse.Reverse();

                lock (portA) {
                    if ((ftStatus = this.portA.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) {
                        throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: "
                            + ftStatus.ToString());
                    }
                    // If only one thread can read/write to the chip this will wait indefinitely.
                    while (bytesWaiting > 0) {
                        System.Threading.Monitor.Wait(portA);
                        if ((ftStatus = this.portA.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) {
                            throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port A. err: "
                                + ftStatus.ToString());
                        }
                    }
                    if ((ftStatus = this.portA.Write(dataReverse.ToArray(), data.Count, ref bytesWritten))
                        != FTDI.FT_STATUS.FT_OK) {
                        throw new FTDI.FT_EXCEPTION("Failed to write to port A. err: " + ftStatus.ToString());
                    }
                    // Notify all threads of a change in port status
                    System.Threading.Monitor.PulseAll(portA);
                }
            } else { // end Port A
                lock (portB) {
                    if ((ftStatus = this.portB.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) {
                        throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: "
                            + ftStatus.ToString());
                    }
                    // If only one thread can read/write to the chip this will wait indefinitely.
                    while (bytesWaiting > 0) {
                        System.Threading.Monitor.Wait(portB);
                        if ((ftStatus = this.portB.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) {
                            throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: "
                                + ftStatus.ToString());
                        }
                    }

                    if ((ftStatus = this.portB.Write(data.ToArray(), data.Count, ref bytesWritten))
                        != FTDI.FT_STATUS.FT_OK) {
                        throw new FTDI.FT_EXCEPTION("Failed to write to port B. err: " + ftStatus.ToString());
                    }
                    // Notify all threads of a change in port status
                    System.Threading.Monitor.PulseAll(portB);
                }
            } // end Port B

            if (data.Count != bytesWritten) throw new Exception("Write length mismatch");
        }
Example #39
0
        public static void Write(FTDI FtdiDevice, byte[] vals, UInt32 nWriteBytes)
        {
            FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK;
            UInt32 nBytesWritten = 0;
            UInt32 byteCount = 0;
            //byte[] vals = { 0x1F };
            //byte[] vals = { val };
            //do
            //{
            // ftStatus = myFtdiDevice.Write((byte)(0xAA), 1, ref numBytesWritten);
            //sync_mode = false;

            SetAsyncMode();

            while ( nBytesWritten != nWriteBytes ) {
                ftStatus = FtdiDevice.Write(vals, nWriteBytes - nBytesWritten, ref byteCount);
                if ( ftStatus != FTDI.FT_STATUS.FT_OK ) {
                    // Wait for a key press
                    Console.WriteLine("Failed to write data (error " + ftStatus.ToString() + ")");
                    //Console.ReadKey();
                    //return;
                }
                nBytesWritten += byteCount;
                for ( int i = 0; i < nWriteBytes - nBytesWritten; ++i ) {
                    vals[i] = vals[i + byteCount];
                }
               // Console.WriteLine("Wrote {0} bytes ( {0} of {0} total )", byteCount, nBytesWritten, nWriteBytes);
                //if ( numBytesWritten != nBytes ) {
                //    Console.WriteLine("Failed to write data (num " + numBytesWritten.ToString() + ")");
                //}
                //}
                //while (Console.ReadKey().Key != ConsoleKey.Spacebar);

                //Console.WriteLine("\r\nWrote {0} byte, it was {1:X2}", numBytesWritten, vals[0]);
            }
            //sync_mode = true;
        }