/******Cypress USB EEPROM Programming****/ //# USB Lg EEPROM programming //This is the method that does the actual work. bool I2CEEPROM_Programming(BackgroundWorker worker, DoWorkEventArgs e) { // USBDeviceList USBdevList, // ref CyUSBDevice TE_USB_FX2_USBDevice // The parameter n must be >= 0 and <= 91. // Fib(n), with n > 91, overflows a long. if (bClearLogTextBeforeEveryProgrammingOperation == true) LogTextLine = String.Empty; if (USBdevList == null) { throw new ArgumentException( "At least one TE USB FX2 module must be attached"); } bool result = false; bool opened = false; // Abort the operation if the user has canceled. // Note that a call to CancelAsync may have set // CancellationPending to true just after the // last invocation of this method exits, so this // code will not have the opportunity to set the // DoWorkEventArgs.Cancel flag to true. This means // that RunWorkerCompletedEventArgs.Cancelled will // not be set to true in your RunWorkerCompleted // event handler. This is a race condition. if (worker.CancellationPending) { //TextLine = "line 1063"; e.Cancel = true; return result; } else if (bFileUSB_Selected) { //TextLine = "line 1069"; //timeout_ms = c_ulong(1000) # Timeout 1s //CardNumber = c_int(0) # Card Number 0 //DriverBufferSize = c_int(132072) # Driver Buffer Size 132072 uint timeout_ms = 1000; //int CardNumber = 0; //int DriverBufferSizeWrite = 131072; //int DriverBufferSizeRead = 131072; byte[] Command = new byte[64]; byte[] Reply = new byte[64]; int CmdLength = 64; int ReplyLength = 64; UInt16 PID = 0; UInt16 VID = 0; op_error = 0; //Stopwatch stopWatch = new Stopwatch(); //stopWatch.Start(); //printlog("Programming EEPROM") //fpga_bitstream_size = len(usb_bitstream) # Calculate size //printlog("Firmware size " + str(fpga_bitstream_size)) if (bVerboseLogText == true) { LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n"; LogTextLine += "Programming FX2 microcontroller EEPROM and RAM using I2C" + "\r\n"; LogTextLine += "INFO: The operation STARTS " + (DateTime.Today).ToString() + "\r\n"; LogTextLine += "INFO: OpenFutNET version running on the host: " + OpenFutNETversion + "\r\n"; LogTextLine += "INFO: Operating system of the host:" + GetOSFriendlyName() + "\r\n"; LogTextLine += "INFO: .NET version running on the host: " + Environment.Version.ToString() + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n"; } if (bVerboseLogText == false) //LogTextLine += "\r\n" + "-----------------------------------------------------------------------------------------------------------------" + "\r\n"; LogTextLine += "FX2 microcontroller EEPROM programming: START....."; else LogTextLine += "FX2 microcontroller EEPROM programming: START" + "\r\n"; if (bVerboseLogText == true) LogTextLine += "Firmware size " + usb_bitstream_size.ToString() + " bytes" + "\r\n"; if (USBFile_FilePath.Length > 0) bFileUSB_Selected = true; USBdevList = new USBDeviceList(CyConst.DEVICES_CYUSB); if (USBdevList.Count != 0) { fx2 = USBdevList[0] as CyFX2Device; PID = fx2.ProductID; VID = fx2.VendorID; if (USBdevList.Count > 1) { MessageBox.Show("In this version the program must be used with a single Trenz Electronic or Cypress module attached. You must remove Cypress and/or Trenz Electronic micromodule(s) until only one module remains. This must be the module that you desire to write."); } } if (((USBdevList.Count == 1) && (PID == PIDCypress) && (VID == VIDCypress) && bEEPROMSwitchSetToOn) || (((USBdevList.Count == 1) && (PID == PIDTrenzElectronic) && (VID == VIDTrenzElectronic)))) { if (bVerboseLogText == true) { LogTextLine += "INFO: VID and PID identify a Cypress Device: therefore EEPROM will be programmed using Cypress DLL 'CyUSB.dll'" + "\r\n"; LogTextLine += "INFO: Found " + (USBdevList.Count).ToString() + " card(s)" + "\r\n"; LogTextLine += "INFO: Connected to card 1" + "\r\n"; } if ((USBdevList.Count == 1) && (PID == PIDCypress) && (VID == VIDCypress) && bEEPROMSwitchSetToOn) { PID_String = "0x8613"; VID_String = "0x04B4"; } else { //PID and VID of Trenz Electronic device PID_String = "0x0300"; VID_String = "0x0BD0"; } opened = true; if ((op_error == 0) && (opened == true)) //# No errors in past { StatusTextLine = "Programming FX2 microcontroller EEPROM"; if (bVerboseLogText == true) LogTextLine += "Writing firmware to EEPROM: START" + "\r\n"; bResultLoadEEPROM = fx2.LoadEEPROM(USBFile_FilePath, true); worker.ReportProgress(percentComplete_USB_EEPROMWrite); if (bResultLoadEEPROM == false) { StatusTextLine = "Error: it is not possible to write EEPROM."; if (bVerboseLogText == true) { LogTextLine += "ERROR: Can't call API function TE_USB_FX2_SendCommand + CMD_FX2_EEPROM_WRITE" + "\r\n"; LogTextLine += "INFO/WARNING: probably, you should move the EEPROM switch to ON" + "\r\n"; } else LogTextLine += " STOP. " + "ERROR: it is not possible to write the EEPROM. Probably, you should move the EEPROM switch to ON" + "\r\n"; op_error = 5; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; worker.ReportProgress(percentComplete_USB_EEPROMWrite); return false; } else { backgroundWakeEvent.WaitOne(750); percentComplete_USB_EEPROMWrite = 100; backgroundWakeEvent.WaitOne(750); if (bVerboseLogText == true) LogTextLine += "Writing firmware to EEPROM: STOP" + "\r\n"; else LogTextLine += " STOP. " + "SUCCESS: FX2 microcontroller EEPROM programmed." + "\r\n"; StatusTextLine = "SUCCESS: FX2 microcontroller EEPROM programmed."; worker.ReportProgress(percentComplete_USB_EEPROMWrite); //break; } } } } else { StatusTextLine = "Error: file not selected"; if (bVerboseLogText == true) LogTextLine += "ERROR: File not selected" + "\r\n"; op_error = 6; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; return false; //op.set("Error") //printlog("ERROR: File not selected") } if ((op_error == 0) || (bResultLoadEEPROM)) { //backgroundWakeEvent.WaitOne(5000); if (bVerboseLogText == true) LogTextLine += "FX2 microcontroller RAM Programming: START" + "\r\n"; else LogTextLine += "FX2 microcontroller RAM Programming: START....."; bResultLoadExternalRam = fx2.LoadExternalRam(USBFile_FilePath); if (bResultLoadExternalRam == true) { StatusTextLine = "SUCCESS: FX2 microcontroller EEPROM and RAM programmed"; if (bVerboseLogText == true) { LogTextLine += "FX2 microcontroller RAM Programming: STOP" + "\r\n"; LogTextLine += "INFO: Programming FX2 microcontroller RAM with TE FX2 firmware v3.02 it is equivalent to remove and insert the module." + "\r\n"; LogTextLine += "INFO: Programming FX2 microcontroller RAM with TE FX2 firmware version earlier than v3.02 it is NOT equivalent to remove and inssert the module:" +"\r\n" +"in this case you should click the button 'Refresh information about FPGA and FX2 microcontroller' to obtain the last value of firmware version" + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n"; LogTextLine += "Programming EEPROM and RAM of FX2 microcontroller using I2C" + "\r\n"; LogTextLine += "INFO: The operation STOPS " + (DateTime.Today).ToString() + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; } else { LogTextLine += " STOP. " + "SUCCESS: FX2 microcontroller RAM programmed" + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; //LogTextLine += "-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; } } else { StatusTextLine = "Warning: RAM has not been written"; if (bVerboseLogText == true) LogTextLine += "Warning: RAM has not been written" + "\r\n"; else LogTextLine += " STOP. " + "Warning: it is not possible to write the RAM. You should power off/on cycle the TE USB FX2 module to load the RAM with EEPROM firmware." + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; worker.ReportProgress(percentComplete_USB_EEPROMWrite); } if (USBdevList != null) { USBdevList.DeviceRemoved -= USBdevList_DeviceRemoved; USBdevList.DeviceAttached -= USBdevList_DeviceAttached; USBdevList.Dispose(); } //backgroundWakeEvent.WaitOne(6000); backgroundWakeEvent.WaitOne(500); USBdevList = new USBDeviceList(CyConst.DEVICES_CYUSB); USBdevList.DeviceAttached += new EventHandler(USBdevList_DeviceAttached); USBdevList.DeviceRemoved += new EventHandler(USBdevList_DeviceRemoved); TE_USB_FX2_USBDevice = USBdevList[0] as CyUSBDevice; //FX2MicronctrollerRamProgrammed = true; backgroundWakeEvent.WaitOne(500); //IF Trenz Electronic, non Cypress o DEWESoft /* while (bResultLoadExternalRam == true ) { textBox_PID.Text = PID_String; textBox_VID.Text = VID_String; backgroundWakeEvent.WaitOne(1000); Command1[0] = (byte)FX2_Commands.CMD_FX2_READ_VERSION; //bSendCommand = false; //if TE_USB_FX2_USBDevice. bSendCommand = TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command1, ref CmdLength1, ref Reply1, ref ReplyLength1, TIMEOUT_MS); backgroundWakeEvent.WaitOne(1000); if ( bSendCommand ) { if (ReplyLength1 >= 4) { bResultLoadExternalRam = false; break; } else { } } } */ worker.ReportProgress(percentComplete_USB_EEPROMWrite); backgroundWakeEvent.WaitOne(1000); worker.ReportProgress(percentComplete_USB_EEPROMWrite); backgroundWakeEvent.WaitOne(1000); //LogTextLine += "Programming RAM of FX2 microcontroller: STOP" + "\r\n"; worker.ReportProgress(percentComplete_USB_EEPROMWrite); return bResultLoadEEPROM; } else { StatusTextLine = "Error: EEPROM has not been written"; if (bVerboseLogText == true) LogTextLine += "ERROR: EEPROM has not been written" + "\r\n"; else LogTextLine += " STOP. " + "ERROR: it is not possible to write the EEPROM." + "\r\n"; LogTextLine += "-----------------------------------------------------------------------------------------------------------------" + "\r\n" + "\r\n"; worker.ReportProgress(percentComplete_USB_EEPROMWrite); result = false; return result; } //return result; }
/* Summary The function sets the device, as the one having VID=04b4 and PID=00F0 This will detect only the devices with the above VID,PID combinations */ public void setDevice() { loopDevice = usbDevices[0x04b4, 0x00F0] as CyUSBDevice; StartBtn.Enabled = (loopDevice != null); if (loopDevice != null) Text = loopDevice.FriendlyName; else Text = "C# Bulkloop - no device"; // Set the IN and OUT endpoints per the selected radio buttons. EptPair1Btn_Click(this, null); }
static int GetFPGAstatus(ref CyUSBDevice TE_USB_FX2_USBDevice) { byte [] Command = new byte[64]; byte [] Reply = new byte[64]; int CmdLength = 64; int ReplyLength = 64; uint TIMEOUT_MS=1000; Command[0] = (byte)FX2_Commands.SET_INTERRUPT; Command[1] = (byte)FX2_Parameters.MB_I2C_ADDRESS; Command[2] = (byte)FX2_Parameters.I2C_BYTES; if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength,TIMEOUT_MS)==false) { //cout << "Error" << endl; Console.WriteLine("Error 1"); return -1; } //Console.WriteLine("Reply {0}, {1} ,{2} ,{3}, {4}", Reply[0], Reply[1], Reply[2], Reply[3], Reply[4]); Command[0] = (byte)FX2_Commands.GET_INTERRUPT; //read from interrupt data register //if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength, TIMEOUT_MS)==false) //{ // //cout << "Error" << endl; // Console.WriteLine("Error 2"); // return -1; //} int ItIsPassed = 0; Reply[0]=0; while (Reply[0] == 0) { //Console.WriteLine("Wait"); //Console.WriteLine("Reply {0}, {1} ,{2} ,{3}, {4}", Reply[0], Reply[1], Reply[2], Reply[3], Reply[4]); if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength, TIMEOUT_MS)==false) { //cout << "Error" << endl; Console.WriteLine("Error 3"); return -1; } ItIsPassed = (int)Reply[4]; } return ItIsPassed;//(int)Reply[4]; //return data verification status }
/// <summary> /// function for all detected thing /// </summary> private void USBDetected() { mCyUSBDev = mUSBDevList[0x04b4, 0x1004] as CyUSBDevice; if (mCyUSBDev == null) { MessageBox.Show("No Such Device!"); } else { //mCyUSBInEP = mCyUSBDev.BulkInEndPt; mCyUSBOutEP = mCyUSBDev.BulkOutEndPt; foreach (CyUSBEndPoint ept in mCyUSBDev.EndPoints) { if (ept.bIn && (ept.Attributes == 2)) { mCyUSBInEP = ept as CyBulkEndPoint; } } } }
public Form1() { InitializeComponent(); usbDevices = new USBDeviceList(CyConst.DEVICES_CYUSB); USBDevice dev = usbDevices[0]; if (dev != null) { MyDevice = (CyUSBDevice)dev; GetEndPoint(MyDevice.Tree); } foreach (CyUSBEndPoint ep in EndPointList) { if (ep.Address == 0x86) inEndPoint = ep; if (ep.Address == 0x2) outEndPoint = ep; } }
/* Summary The function sets the device, as the one having VID=04b4 and PID=1004 This will detect only the devices with the above VID,PID combinations */ public void setDevice() { try { loopDevice = usbDevices[0x04b4, 0x8613] as CyUSBDevice; StartBtn.Enabled = (loopDevice != null); if (loopDevice != null) Text = loopDevice.FriendlyName; else Text = "BVCOMVC - no device"; outEndpoint = loopDevice.EndPointOf(0x02) as CyBulkEndPoint; inEndpoint = loopDevice.EndPointOf(0x86) as CyBulkEndPoint; outEndpoint.TimeOut = 1000; inEndpoint.TimeOut = 1000; } catch { Text = "BVCOMVC - no device"; } }
/* Summary Method to check whether FxDev is selected or not */ public CyUSBDevice FxDevDeviceSelected() { TreeNode selNode = DeviceTreeView.SelectedNode; if (selNode == null) { MessageBox.Show("Select an Cypress USB device in the device tree.", "Wrong device selected"); return null; } // Climb to the top of the tree while (selNode.Parent != null) selNode = selNode.Parent; FxDev = selNode.Tag as CyUSBDevice; if (FxDev == null) MessageBox.Show("Select an Cypress USB device in the device tree.", "Wrong device selected"); return FxDev; }
/* Summary Shows the last state and status of endpoint */ private void URB_Stat_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } if (curEndpt == null) { MessageBox.Show("Select an endpoint to find the status.", "No endpoint selected"); return; } uint status = curEndpt.UsbdStatus; string Hex = String.Format("{0:X}", status); StatLabel.Text = "Last URB Error = 0x" + Hex + " " + CyUSBDevice.UsbdStatusString(status); }
/* Summary Event handler to handle changes in Check box of Device Class Selection Tabpage and at Start */ private void CyUSBDeviceBox_CheckedChanged(object sender, EventArgs e) { byte DeviceMask = 0; DeviceMask |= CyUSBDeviceBox.Checked ? CyConst.DEVICES_CYUSB : (byte)0; DeviceMask |= MSCDeviceBox.Checked ? CyConst.DEVICES_MSC : (byte)0; DeviceMask |= HIDDeviceBox.Checked ? CyConst.DEVICES_HID : (byte)0; if (usbDevices != null) { usbDevices.DeviceRemoved -= usbDevices_DeviceRemoved; usbDevices.DeviceAttached -= usbDevices_DeviceAttached; usbDevices.Dispose(); } usbDevices = new USBDeviceList(DeviceMask); usbDevices.DeviceRemoved += new EventHandler(usbDevices_DeviceRemoved); usbDevices.DeviceAttached += new EventHandler(usbDevices_DeviceAttached); curEndpt = null; curCyUsbDev = null; curHidDev = null; curHidReport = null; RefreshDeviceTree(); }
//This function refresh the information displayed on the GUI (Form1) about the Device inserted //As the name warns, it run on the UIThread //TO DO: add another Backgroundworker to move the SendCommand section to a background thread; //in this way the GUI will avoid the last remaining possible reason to freeze. private void RefreshInformationUIThread() { //These three lines of code has been moved outside of this function to lessen/avoid GUI freezing //backgroundWakeEvent.WaitOne(1000); //USBdevList = new USBDeviceList(CyConst.DEVICES_CYUSB); //backgroundWakeEvent.WaitOne(1000); // Reset the text in the result label. //resultLabel.Text = String.Empty; UInt16 PID = 0; UInt16 VID = 0; //Verify that one Cypress or Trenz Electronic device has been attached (inserted) if (USBdevList.Count != 0) { //Modify this code if multiple USB device should be connected CyFX2Device fx2test = USBdevList[0] as CyFX2Device; PID = fx2test.ProductID; VID = fx2test.VendorID; //If more than one Cypress/TE device has been attached the program warns you that only one attached device is expected if (USBdevList.Count > 1) { MessageBox.Show("In this version the program must be used with a single Trenz Electronic or Cypress module attached. You must remove Cypress and/or Trenz Electronic micromodules until only one module remains. This must be the module that you desire to write."); } //FirmwareTypeUSB.Text = "No Cypress or TE device, maybe you are using an old Firmware."; //DriverType_TextBox.Text = "Undefined or DEWESoft"; //MessageBox.Show("The VID and PID used are for normal Cypress device; if you are starting a recovery procedure, it is correct. Otherwise use a power on/off cycle with EEPROM switch to ON to start with VID and PID of a Trenz Electronic device"); } //If a Cypress Device is attached and it is the first time (bEEPROMSwitchSetToOn = false) that the program register this device a Recovery procedure is advised if ((PID == PIDCypress) && (VID == VIDCypress) && (!bEEPROMSwitchSetToOn)) { FirmwareTypeUSB.Text = "Cypress used for Recovery Procedure"; DriverType_TextBox.Text = "Cypress USB Generic Driver"; if (bVerboseLogText == true) { LogTextLine += "INFO: Cypress USB Generic Driver used for recovery" + "\r\n"; MessageBox.Show("The VID and PID used are for normal Cypress device; if you are starting a recovery procedure, it is correct. Otherwise, you should use a power off/on cycle with EEPROM switch to ON to start with VID and PID of a Trenz Electronic device. If the computer does't see the Trenz Electronic device you must install the 'Trenz Electronic USB FX2' driver."); } LatestMajorVersionFW_String = "Recovery Procedure"; LatestMinorVersionFW_String = "Recovery Procedure"; PID_String = "0x8613"; VID_String = "0x04B4"; LatestMajorVersionFW_textBox.Text = LatestMajorVersionFW_String; LatestMinorVersionFW_textBox.Text = LatestMinorVersionFW_String; textBox_LogText.Text = LogTextLine; LogTextScrollDown(); /* textBox_LogText.SelectionStart = textBox_LogText.Text.Length; textBox_LogText.ScrollToCaret(); textBox_LogText.Refresh(); */ toolStripStatusLabel1.Text = StatusTextLine; LatestMajorVersionFPGA_textBox.Text = LatestMajorVersionFPGA_String; LatestMinorVersionFPGA_textBox.Text = LatestMinorVersionFPGA_String; LatestReleaseVersionFPGA_textBox.Text = LatestReleaseVersionFPGA_String; LatestBuildVersionFPGA_textBox.Text = LatestBuildVersionFPGA_String; textBox_PID.Text = PID_String; textBox_VID.Text = VID_String; } //If a Trenz Electronic Device is attached it is possible to try to use FX2 Command to retrieve information about the TE Device //USB FX2 Firmware version and if a reference FPGA project has been loaded else if (((PID == PIDTrenzElectronic) && (VID == VIDTrenzElectronic)) || bEEPROMSwitchSetToOn) { FirmwareTypeUSB.Text = "TE USB FX2 Gen3"; DriverType_TextBox.Text = "Trenz Electronic USB FX2 Device Driver"; //Send Command Section //TO DO: add another Backgroundworker to move the SendCommand section to a background thread; //in this way the GUI will avoid the last remaining possible reason to freeze. TE_USB_FX2_USBDevice = USBdevList[0] as CyUSBDevice; backgroundWakeEvent.WaitOne(1000); if (bVerboseLogText == true) { LogTextLine += "Checking the use of Trenz Electronic Reference Design: START" + "\r\n"; LogTextScrollDown(); } byte[] Command = new byte[64]; byte[] Reply = new byte[64]; int CmdLength = 64; int ReplyLength = 64; uint TIMEOUT_MS = 1000; Command[0] = (byte)FX2_Commands.CMD_FX2_SET_INTERRUPT; Command[1] = (byte)FX2_Parameters.MB_I2C_ADDRESS; Command[2] = (byte)FX2_Parameters.I2C_BYTES_SIZE; if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength, TIMEOUT_MS) == false) { if (bVerboseLogText == true) { LogTextLine += "WARNING/INFO: Can't call API function TE_USB_FX2_SendCommand + SET_INTERRPUPT" + "\r\n"; LogTextLine += "WARNING/INFO: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; } StatusTextLine = "WARNING/INFO: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; //worker.ReportProgress(percentComplete_FPGA_SPIFlashWrite); } //Command[0] = (byte)FX2_Commands.CMD_FX2_GET_INTERRUPT; //clear interrupt data register Command[0] = (byte)FX2_Commands.CMD_FX2_I2C_WRITE; //Command[1] = (byte)FX2_Parameters.MB_I2C_ADDRESS; //Command[2] = (byte)FX2_Parameters.I2C_BYTES_SIZE; Command[3] = (byte)0; Command[4] = (byte)0; Command[5] = (byte)0; Command[6] = (byte)MB_Commands.FX22MB_REG0_GETVERSION; //get FPGA version if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength, TIMEOUT_MS) == false) { //cout << "Error" << endl; //Console.WriteLine("Error Send Command Get FPGA Version"); if (bVerboseLogText == true) { LogTextLine += "WARNING/INFO: Can't call API function TE_USB_FX2_SendCommand + FX22MB_REG0_GETVERSION" + "\r\n"; LogTextLine += "WARNING/INFO: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; } StatusTextLine = "WARNING/INFO: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; //worker.ReportProgress(percentComplete_FPGA_SPIFlashWrite); LatestMajorVersionFPGA_textBox.Text = "It is impossible to retrieve"; LatestMinorVersionFPGA_textBox.Text = "It is impossible to retrieve"; } Command[0] = (byte)FX2_Commands.CMD_FX2_GET_INTERRUPT; //0xB1;//comand CMD_FX2_GET_INTERRUPT if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, ref ReplyLength, TIMEOUT_MS) == true) { if ((ReplyLength > 4) && (Reply[0] != 0)) { SystemTypeFPGAFlash.Text = "Yes"; if (bVerboseLogText == true) { LogTextLine += "INFO: Trenz Electronic Reference Design based on MicroBlaze soft processor is used" + "\r\n"; LogTextLine += "INFO: Major version: " + Reply[1].ToString() + "\r\n"; LogTextLine += "INFO: Minor version: " + Reply[2].ToString() + "\r\n"; LogTextLine += "INFO: Release version: " + Reply[3].ToString() + "\r\n"; LogTextLine += "INFO: Build version: " + Reply[4].ToString() + "\r\n"; } LatestMajorVersionFPGA_String = Reply[1].ToString(); LatestMinorVersionFPGA_String = Reply[2].ToString(); LatestReleaseVersionFPGA_String = Reply[3].ToString(); LatestBuildVersionFPGA_String = Reply[4].ToString(); } else { if (bVerboseLogText == true) LogTextLine += "INFO: Custom project not based on TE Reference Architecture" + "\r\n"; SystemTypeFPGAFlash.Text = "No, Custom project not based on TE Reference Architecture"; //LogTextLine += "Major version: " + "it doesn't exist" + "\r\n"; //LogTextLine += "Minor version: " + "it doesn't exist" + "\r\n"; //LogTextLine += "Release version: " + "it doesn't exist" + "\r\n"; //LogTextLine += "Build version: " + "it doesn't exist" + "\r\n"; } } else { if (bVerboseLogText == true) { LogTextLine += "INFO: Custom project not based on TE Reference Architecture" + "\r\n"; LogTextLine += "INFO: Warning: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; LogTextLine += "WARNING/INFO: Can't call API function TE_USB_FX2_SendCommand + FX22MB_REG0_GETVERSION" + "\r\n"; } SystemTypeFPGAFlash.Text = "No, Custom project not based on TE Reference Architecture"; StatusTextLine = "Warning: it is not possible to retrieve version of Trenz Electronic System flashed on the FPGA; maybe you have flashed a Custom Client System not based on Trenz Electronic FPGA"; //worker.ReportProgress(percentComplete_FPGA_SPIFlashWrite); } if (bVerboseLogText == true) { LogTextLine += "Checking the use of Trenz Electronic Reference Design :STOP" + "\r\n"; LogTextLine += "Checking the use of Trenz Electronic TE FX2 Firmware :START" + "\r\n"; } //label3.Text = TextLine; textBox_LogText.Text = LogTextLine; LogTextScrollDown(); /* textBox_LogText.SelectionStart = textBox_LogText.Text.Length; textBox_LogText.ScrollToCaret(); textBox_LogText.Refresh(); */ toolStripStatusLabel1.Text = StatusTextLine; LatestMajorVersionFPGA_textBox.Text = LatestMajorVersionFPGA_String; LatestMinorVersionFPGA_textBox.Text = LatestMinorVersionFPGA_String; LatestReleaseVersionFPGA_textBox.Text = LatestReleaseVersionFPGA_String; LatestBuildVersionFPGA_textBox.Text = LatestBuildVersionFPGA_String; textBox_PID.Text = PID_String; textBox_VID.Text = VID_String; byte[] Command1 = new byte[64]; byte[] Reply1 = new byte[64]; //int CmdLength = 64; //int ReplyLength = 64; //uint TIMEOUT_MS = 1000; Command1[0] = (byte)FX2_Commands.CMD_FX2_READ_VERSION; //comand read FX2 version //Console.WriteLine("Command[0] {0:X2} ", Command[0]); if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand(ref TE_USB_FX2_USBDevice, ref Command1, ref CmdLength, ref Reply1, ref ReplyLength, TIMEOUT_MS) == true) { if (ReplyLength >= 4) { if (bVerboseLogText == true) { LogTextLine += "INFO: TE FX2 Firmware Generation 3 stored in FX2 microcontroller EEPROM" + "\r\n"; LogTextLine += "INFO: Major version: " + Reply1[0].ToString() + "\r\n"; LogTextLine += "INFO: Minor version: " + Reply1[1].ToString() + "\r\n"; } LatestMajorVersionFW_String = Reply1[0].ToString(); LatestMinorVersionFW_String = Reply1[1].ToString(); VID_String = "0x" + (TE_USB_FX2_USBDevice.VendorID).ToString("X4"); PID_String = "0x" + (TE_USB_FX2_USBDevice.ProductID).ToString("X4"); } else { if (bVerboseLogText == true) LogTextLine += "ERROR: TE FX2 Firmware Generation 3 is not stored in FX2 microcontroller EEPROM" + "\r\n"; LatestMajorVersionFW_String = "ERROR"; LatestMinorVersionFW_String = "ERROR"; } } else //cout << "Error" << endl; //Console.WriteLine("Error"); { if (bVerboseLogText == true) LogTextLine += "ERROR: TE FX2 Firmware Generation 3 is not stored in FX2 microcontroller EEPROM" + "\r\n"; LatestMajorVersionFW_String = "ERROR"; LatestMinorVersionFW_String = "ERROR"; } if (bVerboseLogText == true) { LogTextLine += "Checking the use of Trenz Electronic TE_USB_FX2 firmware: STOP" + "\r\n"; } textBox_LogText.Text = LogTextLine; LogTextScrollDown(); /* textBox_LogText.SelectionStart = textBox_LogText.Text.Length; textBox_LogText.ScrollToCaret(); textBox_LogText.Refresh(); */ toolStripStatusLabel1.Text = StatusTextLine; textBox_VID.Text = VID_String; textBox_PID.Text = PID_String; LatestMajorVersionFW_textBox.Text = LatestMajorVersionFW_String; LatestMinorVersionFW_textBox.Text = LatestMinorVersionFW_String; } }
/* * 3.6 TE_USB_FX2_SetData() * * 3.6.1 Declaration * public static bool TE_USB_FX2_SetData(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] DataWrite, ref int DataWriteLength, * int PipeNo, uint Timeout, int BufferSize) * * 3.6.2 Function Call * Your application program shall call this function like this: * TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SetData(ref TE_USB_FX2_USBDevice, ref DataWrite, ref DataWriteLength, PI_EP8, Timeout, * BufferSize); * * 3.6.3 Description * This function takes an already initialized USB device (CyUSBDevice is a type defined in CyUSB.dll), selected by * TE_USB_FX2_Open(), and writes data to the USB FX2 microcontroller endpoint EP8 (0x08). This data is then passed to the FPGA. * If there is not a proper connection (not using FX22MB_REG0_START_RX) between FPGA and USB FX2 microcontroller, * the function can experience a strange behavior. For example, a very low throughput (9-10 Mbyte/s even if a 22-24 Mbyte/s are * expected) is measured or the function fails returning false. These happen because buffer EP8 (the HW buffer, not the * SW buffer of the driver whose size is given by BufferSize parameter) is already full (it is not properly read/emptied by the * FPGA) and no longer able to receive further packets. * 3.6.4 Data throughput expected * The maximum data throughput expected (with a DataWriteLength= 120*10^6) is 24 Mbyte/s (PacketSize = BufferSize =131,072) * but in fact this value is variable between 22-24 Mbyte/s (the mean value seems 24 Mbyte/s); so if you measure this range * of values, the data reception can be considered normal. * The data throughput is variable in two way: * 1. depends on which host computer is used (on some host computers this value is even higher: 29 Mbyte/s) * 2. vary with every function call * 3.6.5 DataWrite size shall not be too large * TE_USB_FX2_SetData() seems unable to use too large arrays or, more precisely, this fact seems variable by changing host * computer. To be safe, do not try to transfer in a single packet very large data (120 millions of byte); transfer the same * data with many packets (1,200 packets * 100,000 byte) and copy the data in a single large data array if necessary (with * Buffer.BlockCopy()). Buffer.BlockCopy seems not to hinder throughput too much (max 2 Mbyte/s). * 3.6.5.1 Reduced version (pseudo code) * PACKETLENGTH=100000; * packets=1200; * byte[] data = new byte[packetlen*packets]; * byte[] buffer = new byte[packetlen]; * for (int i = 0; i < packets; i++) * { * Buffer.BlockCopy(data, total_cnt, buffer, 0, packetlen); * TE_USB_FX2_SetData(ref TE_USB_FX2_USBDevice, ref buffer, ref packetlen, PI_EP8, TIMEOUT_MS,BUFFER_SIZE); * total_cnt += packetlen; * } * 3.6.5.2 Expanded version (code) * SendFPGAcommand(ref TE_USB_FX2_USBDevice, MB_Commands.FX22MB_REG0_START_RX, TIMEOUT_MS); * //ElapsedTime.Start(); //StopWatch start * Stopwatch stopWatch = new Stopwatch(); * stopWatch.Start(); * for (int i = 0; i < packets; i++) * { * packetlen = PACKETLENGTH; * Buffer.BlockCopy(data, total_cnt, buffer, 0, packetlen); * if (TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SetData(ref TE_USB_FX2_USBDevice, ref buffer, ref packetlen, PI_EP8, TIMEOUT_MS, * BUFFER_SIZE) == false) errors++; * else total_cnt += packetlen; * } * //total_cnt += (packetlen * packets); * stopWatch.Stop(); * 3.6.6 DataWrite size shall not be too small * The reason is described in section 1.1.4 PacketSize. * PacketSize has also a strong influence on DataThroughput. If PacketSize is too small (512 byte for example) you can achieve * very low data throughput (2.2 Mbyte/s) even if you use a large driver buffer (driver buffer size = 131,072 byte). * See 6 TE_USB_FX2_CyUSB.dll: Data Transfer Throughput Optimization. * * 3.6.7 Parameters * 1. ref CyUSBDevice TE_USB-FX2_USBDevice * This parameter is passed by reference (ref). It points to the module selected by TE_USB_FX2_Open(). See pages 70-93 of * CyUSB.NET.pdf (Cypress CyUSB .NET DLL Programmer's Reference) * 2. ref byte[] DataWrite * This parameter is passed by reference (ref). C# applications use directly TE_USB_FX2_CyUSB.dll based on CyUSB.dll. To avoid * copying back and forth large amount of data between these two DLLs, data is passed by reference and not by value. * This parameter points to the byte array that contains the data to be written to buffer EP8 (0x08) of USB FX2 microcontroller. * Data contained in EP8 are then read by the FPGA. * 3. ref int DataWriteLength * This parameter is passed by reference (ref). This parameter is the length (in bytes) of the previous byte array; * it is the length of the packet read from FX2 USB endpoint EP6 (0x86). Normally it is PacketLength. * 4. int PipeNumber * This parameter is the value that identify the endpoint used for the data transfer. It is called PipeNumber because it * identifies the buffer (pipe) used by the USB FX2 microcontroller. * 5. uint Timeout. * The unsigned integer value is the time in milliseconds assigned to the synchronous method XferData() of data transfer used by * CyUSB.dll. * Timeout is the time that is allowed to the function for sending/receiving the data packet passed to the function; this * timeout shall be large enough to allow the data/command transmission/reception. Otherwise the transmission/reception will * fail. See 1.1.2 Timeout Setting. * 6. int BufferSize * The integer value is the dimension (in bytes) of the driver buffer (SW) used in data transmission of a single endpoint * (EP8 0x08 in this case); the total buffer size is the sum of all BufferSize of every endpoint used. * The BufferSize has a strong influence on DataThroughput. If BufferSize is too small, DataThroughput can be 1/3-1/2 of * the maximum value (from a maximum value of 24 Mbyte/s for write transactions to an actual value of 14 Mbyte/s). * If BufferSize has a large value (a roomy buffer), the program shall be able to cope with the non-deterministic behavior of * C# without losing packets. * * 3.6.8 Return Value * 1. bool: logical type * This function returns true if it is able to write data to buffer EP8 within Timeout milliseconds. * This function returns false otherwise. * */ public static bool TE_USB_FX2_SetData(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] DataWrite, ref int DataWriteLength, int PipeNo, uint Timeout, int BufferSize) //public static bool TE_USB_FX2_SetData(ref CyBulkEndPoint outEndpointPipeNo, ref byte[] DataWrite, ref int DataWriteLength) { bool bResultDataRead = false; byte PipeNoHex = 0x00; CyBulkEndPoint outEndpointPipeNo = null; //Shortest and more portable way to select the Address using the PipeNumber if (PipeNo == 8) PipeNoHex = 0x08; else PipeNoHex = 0x00; if ((TE_USB_FX2_USBDevice != null) && (PipeNoHex == 0x08)) { outEndpointPipeNo = TE_USB_FX2_USBDevice.EndPointOf(PipeNoHex) as CyBulkEndPoint; outEndpointPipeNo.TimeOut = Timeout; //int MaxPacketSize= outEndpointPipeNo.MaxPktSize; //Console.WriteLine("MaxPacketSize {0} ", MaxPacketSize); //int XferSize1 = outEndpointPipeNo.XferSize; //Console.WriteLine("XferSize {0} ", XferSize1); //outEndpointPipeNo.XferMode = XMODE.DIRECT; outEndpointPipeNo.XferSize = BufferSize;// 131072; //calls the XferData function for bulk transfer(IN) in the cyusb.dll bResultDataRead = outEndpointPipeNo.XferData(ref DataWrite, ref DataWriteLength); //Console.WriteLine("bResultDataRead {0} ", bResultDataRead); //uint inUSBstatus1 = outEndpointPipeNo.UsbdStatus; //Console.WriteLine("UsbdStatus {0:X8} e ", inUSBstatus1); //uint inUSBstatus2 = outEndpointPipeNo.NtStatus; //Console.WriteLine("NtStatus {0:X8} e ", inUSBstatus2); if (bResultDataRead == true) return true; else return false; } else return false; }
/* // This one must be corrected, cause trouble public static bool TE_USB_FX2_DisplayDriverInformation(ref CyUSBDevice TE_USB_FX2_USBDevice, ref USBDeviceList USBdevList, int CardNumber) { int CardCounted = 0; // Trenz Board int DeviceNumber = 0; // Cypress Board ( number >= TrenzBoard) int CypressDeviceNumber = 0; int TrenzDeviceNumber = 0; UInt16 PID = 0x0000; UInt16 VID = 0x0000; uint DriverVersion1 = 0; string DriverName1 = null; //Creation of a list of USB device that use the CYUSB.SYS driver USBdevList = new USBDeviceList(CyConst.DEVICES_CYUSB); //If exist at least an USB device that use the CYUSB.SYS driver, //I search and count the number of these devices that are of Trenz Electronic if (USBdevList.Count != 0) { foreach (USBDevice USBdev in USBdevList) { PID = USBdev.ProductID; VID = USBdev.VendorID; //Number of Cypress Card augmented by one CypressDeviceNumber++; if ((((PID == 0x0300) && (VID == 0x0bd0)) == true)) //0x0bd0 . 0x0bd0 { //Number of Trenz Card (a subcategory of Cypress Card) augmented by one //CardCount++; TrenzDeviceNumber++; Console.WriteLine("PID e VID: {0}, {1}", PID, VID); // CardNumber=TrenzDeviceNumber-1 by definition. if ((TrenzDeviceNumber - 1) == CardNumber) { //I store the DeviceNumber that identify the Trenz Card (CardNumber) requested DeviceNumber = CypressDeviceNumber - 1; Console.WriteLine("DeviceNumber: {0}", DeviceNumber); } } } } //At this point I memorize the Cards Counted and zeroed the variable that I have used in the counting. CardCounted = TrenzDeviceNumber; //Console.WriteLine("CardCounted: {0}", CardCount); TrenzDeviceNumber = 0; //Now I search the Trenz USB Device with the Card Number (CardNo) specified if (((CardNumber >= 0) && (CardNumber < CardCounted)) == true) //CardCounted { USBDevice USBdev = USBdevList[DeviceNumber]; PID = USBdev.ProductID; VID = USBdev.VendorID; if ((((PID == 0x0300) && (VID == 0x0bd0)) == true)) { TE_USB_FX2_USBDevice = USBdev as CyUSBDevice; Console.WriteLine("USBdev {0} ", TE_USB_FX2_USBDevice); //I cast the abstract USBdev in a concrete CyUSBDevice TE_USB_FX2_USBDevice = USBdev as CyUSBDevice; DriverVersion1 = TE_USB_FX2_USBDevice.DriverVersion; Console.WriteLine("DriverVersion {0} ", DriverVersion1); DriverName1 = TE_USB_FX2_USBDevice.DriverName; Console.WriteLine("Original Name of the Driver {0} ", DriverName1); return true; } else { TE_USB_FX2_USBDevice = null; return false; } } else { TE_USB_FX2_USBDevice = null; return false; } } */ /* * *3.4 TE_USB_FX2_SendCommand() * *3.4.1 Declaration *public static bool TE_USB_FX2_SendCommand(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] Command, ref int CmdLength, *ref byte[] Reply, ref int ReplyLength, uint Timeout) * *3.4.2 Function Call *Your application program shall call this function like this: *TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_SendCommand (ref TE_USB_FX2_USBDevice, ref Command, ref CmdLength, ref Reply, *ref ReplyLength, Timeout); * *3.4.3 Description *This function takes an already initialized USB device (previously selected by TE_USB_FX2_Open()) and sends a command *(API command) to the USB FX2 microcontroller (USB FX2 API command) or to the MicroBlaze embedded processor *(MicroBlaze API command) through the USB FX2 microcontroller endpoint EP1 buffer. *This function is normally used to send 64 bytes packets to the USB endpoint EP1 (0x01). *This function is also able to obtain the response of the USB FX2 microcontroller or MicroBlaze embedded processor through *the USB FX2 microcontroller endpoint EP1 (0x81). *3.4.4 Parameters *1. ref CyUSBDevice TE_USB-FX2_USBDevice *CyUSBDevice is a type defined in CyUSB.dll. This parameter points to the module selected by TE_USB_FX2_Open(). *This parameter is passed by reference (ref). See pages 70-93 of CyUSB.NET.pdf (Cypress CyUSB .NET DLL Programmer's Reference) *2. ref byte[] Command *This parameter is passed by reference (ref). It is the byte array that contains the commands to send to USB FX2 microcontroller *(FX2_Commands) or to the MicroBlaze embedded processor (MB_Commands). *The byte array shall be properly initialized using instructions similar to the following ones: *Command[0] = (byte)FX2_Commands.I2C_WRITE; *Command[1] = (byte)FX2_Commands.MB_I2C_ADDRESS; *Command[2] = (byte)FX2_Commands.I2C_BYTES; *Command[3] = (byte)0; *Command[4] = (byte)0; *Command[5] = (byte)0; *Command[6] = (byte)Command2MB; *3. ref int CmdLength *This parameter (passed by reference (ref)) is the length (in bytes) of the previous byte array; it is the length of the *packet to transmit to USB FX2 controller endpoint EP1 (0x01). It is typically initialized to 64 bytes. *4. ref byte[] Reply *This parameter (passed by reference (ref)) is the byte array that contains the response to the command sent to the *USB FX2 microcontroller (FX2_Commands) or to the MicroBlaze embedded processor (MB_Commands). *5. ref int ReplyLength *This parameter (passed by reference (ref)) is the length (in bytes) of the previous byte array; it is the length of *the packet to transmit to the USB FX2 microcontroller endpoint EP1 (0x81). It is typically initialized to 64 byes, *but normally the meaningful bytes are less. The parameter is a reference, meaning that the method can modify its value. *The number of bytes actually received is passed back in ReplyLength. *6. uint Timeout *The unsigned integer value is the time in milliseconds assigned to the synchronous method XferData() of data transfer used *by CyUSB.dll. *Timeout is the time that is allowed to the function for sending/receiving the data packet passed to the function; *this timeout shall be large enough to allow the data/command transmission/reception. Otherwise the transmission/reception will fail. See 1.1.2 Timeout Setting. *3.4.5 Return Value *1. bool : logical type *This function returns true if it is able to send a command to EP1 and receive a response within 2*Timeout milliseconds. *This function returns false otherwise. * */ /// <summary> /// ///// /// </summary> /// <param name="TE03xxUSBdevice"></param> /// <param name="Command"></param> /// <param name="CmdLength"></param> /// <param name="Reply"></param> /// <param name="ReplyLength"></param> /// <param name="Timeout"></param> /// <returns></returns> public static bool TE_USB_FX2_SendCommand(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] Command, ref int CmdLength, ref byte[] Reply, ref int ReplyLength, uint Timeout) { bool bResultCommand = false; bool bResultReply = false; //Concrete class CyBulkEndPoint inEndpoint1 = null; CyBulkEndPoint outEndpoint1 = null; if (TE_USB_FX2_USBDevice != null) { //CyBulkEndPoint TE03xxUSBDeviceConcrete = TE03xxUSBdevice as CyBulkEndPoint; //Select the endpoint of IN number 1 (EP1 INPUT) inEndpoint1 = TE_USB_FX2_USBDevice.EndPointOf(0x81) as CyBulkEndPoint; //Select the endpoint of OUT number 1 (EP1 OUTPUT) outEndpoint1 = TE_USB_FX2_USBDevice.EndPointOf(0x01) as CyBulkEndPoint; // Set the timeout outEndpoint1.TimeOut = Timeout; inEndpoint1.TimeOut = Timeout; //calls the XferData function for bulk transfer(OUT) in the cyusb.dll bResultCommand = outEndpoint1.XferData(ref Command, ref CmdLength); //Console.WriteLine("bResultCommand {0} ", bResultCommand); //Console.WriteLine("Command[0] {0:X2} ", Command[0]); //Console.WriteLine("CmdLength {0} ", CmdLength); //uint inUSBstatus1 = inEndpoint1.UsbdStatus; //Console.WriteLine("UsbdStatus {0:X8} e ", inUSBstatus1); //uint inUSBstatus2 = inEndpoint1.NtStatus; //Console.WriteLine("NtStatus {0:X8} e ", inUSBstatus2); if (bResultCommand == true) { //calls the XferData function for bulk transfer(IN) in the cyusb.dll bResultReply = inEndpoint1.XferData(ref Reply, ref ReplyLength); //Console.WriteLine("bResultReply {0} ", bResultReply); } else return false; if ((bResultCommand && bResultReply) == true) return true; else return false; } else return false; }
private bool PrepareForFirmwareDownload() { // Chech for boot loader FxDev = FxDevDeviceSelected(); if (FxDev == null) return false; CyFX3Device fx = FxDev as CyFX3Device; // check for bootloader first, if it is not running then prompt message to user. if (!fx.IsBootLoaderRunning()) { MessageBox.Show("Please reset your device to download firmware", "Bootloader is not running"); return false; } StatLabel.Text = "Downloading Cypress Boot Programmer..."; Refresh(); //Download Default IMG file FX3_FWDWNLOAD_ERROR_CODE enmbResult = FX3_FWDWNLOAD_ERROR_CODE.SUCCESS; string fPath_fromShortcut = Path.Combine(Directory.GetParent(Application.ExecutablePath).FullName, "CyBootProgrammer.img"); string fPath_buildDir = Path.Combine(Directory.GetParent(Application.ExecutablePath).FullName, "..\\..\\CyBootProgrammer.img"); string fPath = null; if (File.Exists(fPath_fromShortcut)) fPath = fPath_fromShortcut; else if (File.Exists(fPath_buildDir)) fPath = fPath_buildDir; else MessageBox.Show("Can't find the file", "CyBootProgrammer.img"); enmbResult = fx.DownloadFw(fPath, FX3_FWDWNLOAD_MEDIA_TYPE.RAM); StatLabel.Text = "Programming of Boot Programmer " + fx.GetFwErrorString(enmbResult); Refresh(); if (enmbResult == FX3_FWDWNLOAD_ERROR_CODE.FAILED) return false; StatLabel.Text = "Waiting for Cypress Boot Programmer device to enumerate...."; Refresh(); return true; }
/* Summary Executes the script loaded */ private void play_button_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } if (playscriptfile.Length == 0) { MessageBox.Show("Load a script before playing it.", "Load script"); return; } StatLabel.Text = "Playing Script " + FOpenDialog.FileName + " in Outputbox"; Refresh(); FileStream stream = new FileStream(playscriptfile, FileMode.Open, FileAccess.Read); if (stream.Length > 0) { try { Xaction.ReadFromStream(stream); if (FxDev.Config != Xaction.ConfigNum) FxDev.Config = Xaction.ConfigNum; if (FxDev.AltIntfc != Xaction.AltIntfc) FxDev.AltIntfc = Xaction.AltIntfc; stream.Close(); stream = new FileStream(playscriptfile, FileMode.Open, FileAccess.Read); long totalFileSize = stream.Length; long file_bytes_read = 0; do { Xaction.ReadFromStream(stream); file_bytes_read += 32; if (Xaction.Tag == 0xFF) { Thread.Sleep(100); } else { byte[] buffer = new byte[Xaction.DataLen]; int len = (int)Xaction.DataLen; curEndpt = FxDev.EndPointOf(Xaction.EndPtAddr); if (curEndpt != null) { if (curEndpt.Attributes == 0) { /* Control transfer */ CyControlEndPoint ctlEpt = curEndpt as CyControlEndPoint; byte tmp = Xaction.bReqType; ctlEpt.Target = (byte)(tmp & TTransaction.ReqType_TGT_MASK); ctlEpt.ReqType = (byte)(tmp & TTransaction.ReqType_TYPE_MASK); ctlEpt.Direction = (byte)(tmp & TTransaction.ReqType_DIR_MASK); ctlEpt.ReqCode = Xaction.CtlReqCode; ctlEpt.Value = Xaction.wValue; ctlEpt.Index = Xaction.wIndex; if (Xaction.Tag == 0) { Xaction.ReadToBuffer(stream, ref buffer, ref len); file_bytes_read += len; } if (Xaction.Tag == 1) { /* Read from device saving to file */ string tmpSFilter = FSave.Filter; string tmpSTitle = FSave.Title; string file; FSave.Title = "Save Data as:"; FSave.Filter = "All Files(*.*) | *.*"; if (FSave.ShowDialog() == DialogResult.OK) { file = FSave.FileName; Refresh(); } else { FSave.Filter = tmpSFilter; FSave.Title = tmpSTitle; return; } FSave.FileName = ""; FSave.Filter = tmpSFilter; FSave.Title = tmpSTitle; PerformCtlFileTransfer(file, ref buffer, ref len); } else { PerformCtlTransfer(ref buffer, ref len); } } else { /* Non Ep0 transfer */ if (Xaction.Tag == 0) { Xaction.ReadToBuffer(stream, ref buffer, ref len); file_bytes_read += len; } if (Xaction.Tag == 1) { /* Read from device saving to file */ string tmpSFilter = FSave.Filter; string tmpSTitle = FSave.Title; string file; FSave.Title = "Save Data as:"; FSave.Filter = "All files(*.*) | *.*"; if (FSave.ShowDialog() == DialogResult.OK) { file = FSave.FileName; Refresh(); } else { FSave.Filter = tmpSFilter; FSave.Title = tmpSTitle; return; } FSave.FileName = ""; FSave.Filter = tmpSFilter; FSave.Title = tmpSTitle; PerformNonEP0FileXfer(file, ref buffer, ref len); } else { PerformNonEP0Xfer(ref buffer, ref len); } } } } } while ((totalFileSize - file_bytes_read) >= 32); } catch (Exception esc) { MessageBox.Show(esc.Message, "Invalid file data"); } } else MessageBox.Show("Script Loaded is empty", "Invalid file"); stream.Close(); }
/* Summary Just get's the file name of .spt for playing */ private void load_button_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } string tmpFilter = FOpenDialog.Filter; string tmpTitle = FOpenDialog.Title; FOpenDialog.Title = "Select a Script file to load: "; FOpenDialog.Filter = "Script files (*.spt) | *.spt"; if (FOpenDialog.ShowDialog() == DialogResult.OK) { playscriptfile = FOpenDialog.FileName; StatLabel.Text = "Script loaded.... " + FOpenDialog.FileName; Refresh(); } else { FOpenDialog.Title = tmpTitle; FOpenDialog.Filter = tmpFilter; return; } FOpenDialog.FileName = ""; FOpenDialog.Title = tmpTitle; FOpenDialog.Filter = tmpFilter; play_button.Enabled = true; }
/* Summary Initialize global variables defined */ private void Initialize() { scriptfile = ""; playscriptfile = ""; Resetreg = 0xE600; Maxaddr = 0x4000; Max_Ctlxfer_size = 0x1000; bRecording = false; Xaction = new TTransaction(); list = new ArrayList(); list1 = new ArrayList(); curEndpt = null; curCyUsbDev = null; curHidDev = null; curHidReport = null; }
/* Summary Event handler to reset or run Fx2's CPU */ private void HaltItem_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); CyFX2Device fx = FxDev as CyFX2Device; if (FxDev != null) if (sender == ProgramFX2haltMenuItem) fx.Reset(1); else fx.Reset(0); }
/* Summary Used for some specific purposes for not showing the MessageBox similar to FxDevDeviceSelected */ private CyUSBDevice FxDevDeviceSelected_forusage() { TreeNode selNode = DeviceTreeView.SelectedNode; while (selNode.Parent != null) selNode = selNode.Parent; FxDev = selNode.Tag as CyUSBDevice; return FxDev; }
/* Summary Any selection changes in the tree view will trigger this function "at start the first device is always selected leading into this function" */ private void DeviceTreeView_AfterSelect(object sender, TreeViewEventArgs e) { XferTextBox.Text = ""; XferDataBox.Text = ""; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(">&&"); for (int i = 1; i < this.XferTextBox.MaxLength; i++) { sb.Append(" &&"); } this.XferDataBox.Mask = sb.ToString(); TreeNode selNode = DeviceTreeView.SelectedNode; string nodeText = selNode.Text; CyUSBInterfaceContainer curIntfcContainer = selNode.Tag as CyUSBInterfaceContainer; CyUSBInterface curIntfc = selNode.Tag as CyUSBInterface; CyUSBConfig curConfig = selNode.Tag as CyUSBConfig; curEndpt = selNode.Tag as CyUSBEndPoint; curCyUsbDev = selNode.Tag as CyUSBDevice; curHidDev = null; curHidReport = null; if (curConfig != null) { curCyUsbDev = selNode.Parent.Tag as CyUSBDevice; } else if (curIntfcContainer != null) { curCyUsbDev = selNode.Parent.Parent.Tag as CyUSBDevice; } else if (curIntfc != null) { curCyUsbDev = selNode.Parent.Parent.Parent.Tag as CyUSBDevice; curCyUsbDev.AltIntfc = curIntfc.bAlternateSetting; } else if (curEndpt != null) { int minXfer = curEndpt.MaxPktSize; if (curEndpt.Attributes == 1) minXfer *= 8; NumBytesBox.Text = minXfer.ToString(); // Set the AltSetting if (curEndpt.Address != 0) // Only if we're not on the Control Endpoint { curCyUsbDev = selNode.Parent.Parent.Parent.Parent.Tag as CyUSBDevice; curIntfc = selNode.Parent.Tag as CyUSBInterface; curCyUsbDev.AltIntfc = curIntfc.bAlternateSetting; } else { curCyUsbDev = selNode.Parent.Parent.Tag as CyUSBDevice; } } else if ((selNode.Tag is CyHidButton) || (selNode.Tag is CyHidValue)) { curHidDev = selNode.Parent.Parent.Tag as CyHidDevice; curHidReport = selNode.Parent.Tag as CyHidReport; NumBytesBox.Text = curHidReport.RptByteLen.ToString(); nodeText = selNode.Parent.Text; } else if (selNode.Tag is CyHidReport) { curHidDev = selNode.Parent.Tag as CyHidDevice; curHidReport = selNode.Tag as CyHidReport; NumBytesBox.Text = curHidReport.RptByteLen.ToString(); } else if (selNode.Tag is CyHidDevice) curHidDev = selNode.Tag as CyHidDevice; ConfigDataXferBtn(nodeText); DescText.Text = selNode.Tag.ToString(); Sync_Form_Resize = 1; Form1_Resize(sender, null); }
/*Summary Search the device with VID-PID 04b4-1003 and if found, select the end point */ private void SetDevice() { USBDevice dev = usbDevices[0x04B4, 0x8613]; if (dev != null) { MyDevice = (CyUSBDevice)dev; GetEndpointsOfNode(MyDevice.Tree); SetEndpoint(0); ////if (EndPointsComboBox.Items.Count > 0) //{ // EndPointsComboBox.SelectedIndex = 0; // //PpxBox.SelectedIndex = 0; // //QueueBox.SelectedIndex = 0; // // StartBtn.Enabled = true; //} CySafeFileHandle handle = MyDevice.DeviceHandle; hDevice = handle.DangerousGetHandle(); bool ret_status; int bytesxfered = 0; UInt32 GET_TRANSFER_SIZE_CTL = 0x00220034; UInt32 SET_TRANSFER_SIZE_CTL = 0x00220038; SET_TRANSFER_SIZE_INFO SetTransferInfo = new SET_TRANSFER_SIZE_INFO(); if (EndPoint.Attributes == 3) { SetTransferInfo.EndPointAddress = MyDevice.InterruptInEndPt.Address; } else if (EndPoint.Attributes == 2) { SetTransferInfo.EndPointAddress = MyDevice.BulkInEndPt.Address; } // //string TransInfo = SetTransferInfo.ToString; byte[] Trans_Info = new byte[9]; Trans_Info[0] = SetTransferInfo.EndPointAddress; ret_status = DeviceIoControl(hDevice, GET_TRANSFER_SIZE_CTL, Trans_Info, Trans_Info.Length, Trans_Info, Trans_Info.Length, ref bytesxfered, null); //change to 65536 KB buffer Trans_Info[2] = 0x00; Trans_Info[3] = 0x80; ret_status = DeviceIoControl(hDevice, SET_TRANSFER_SIZE_CTL, Trans_Info, Trans_Info.Length, Trans_Info, Trans_Info.Length, ref bytesxfered, null); //check to make sure change was made Trans_Info[2] = 0x00; Trans_Info[3] = 0x00; ret_status = DeviceIoControl(hDevice, GET_TRANSFER_SIZE_CTL, Trans_Info, Trans_Info.Length, Trans_Info, Trans_Info.Length, ref bytesxfered, null); } else { // StartBtn.Enabled = false; // EndPointsComboBox.Items.Clear(); // EndPointsComboBox.Text = ""; EndpointList.Clear(); } }
/*Summary This is the event handler for device removal. This method resets the device count and searches for the device with VID-PID 04b4-1003 */ void usbDevices_DeviceRemoved(object sender, EventArgs e) { MyDevice = null; EndPoint = null; SetDevice(); }
/* Summary This event handler handles 3 events: programming large EEprom, small EEprom and loading RAM */ private void ProgE2Item_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); string tmpFilter = FOpenDialog.Filter; if ((sender == ProgramFX264kBEEPROMMenuItem) || (sender == ProgramFX2smallEEPROMMenuItem)) FOpenDialog.Filter = "Firmware Image files (*.iic) | *.iic"; if ((FxDev != null) && (FOpenDialog.ShowDialog() == DialogResult.OK)) { bool bResult = false; if (sender == ProgramFX264kBEEPROMMenuItem) { StatLabel.Text = "Programming EEPROM of " + FxDev.FriendlyName; Refresh(); CyFX2Device fx = FxDev as CyFX2Device; bResult = fx.LoadEEPROM(FOpenDialog.FileName, true); } else if (sender == ProgramFX2smallEEPROMMenuItem) { StatLabel.Text = "Programming EEPROM of " + FxDev.FriendlyName; Refresh(); CyFX2Device fx = FxDev as CyFX2Device; bResult = fx.LoadEEPROM(FOpenDialog.FileName, false); } else { StatLabel.Text = "Programming RAM of " + FxDev.FriendlyName; Refresh(); CyFX2Device fx = FxDev as CyFX2Device; string filename = FOpenDialog.FileName; if (bRecording && (script_stream != null)) { byte ConfigNum = fx.Config; byte IntfcNum = 0; byte AltIntfc = fx.AltIntfc; fx.SetRecordingFlag(true, ConfigNum, IntfcNum, AltIntfc); } if (fx.IsRecordingFlagSet()) { fx.ScriptFileForDwld(script_stream); } bResult = fx.LoadExternalRam(filename); fx.SetRecordingFlag(false, Xaction.ConfigNum, Xaction.IntfcNum, Xaction.AltIntfc); } StatLabel.Text = "Programming " + (bResult ? "succeeded." : "failed."); Refresh(); } FOpenDialog.FileName = ""; FOpenDialog.Filter = tmpFilter; }
/* * 3.2 TE_USB_FX2_Open() * * 3.2.1 Declaration * public static bool TE_USB_FX2_Open(ref CyUSBDevice TE_USB_FX2_USBDevice, ref USBDeviceList USBdevList, int CardNumber) * * 3.2.2 Function Call * Your application program shall call this function like this: * TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_Open( ref TE_USB_FX2_USBDevice, ref USBdevList, CardNumber); * * 3.2.3 Description * This function takes (a null initialized or an already initialized) USB device list, (re-)creates a USB device list , * searches for Trenz Electronic USB FX2 devices (Cypress driver derivative and VID = 0xbd0, PID=0x0300) and counts them. * If no device is attached, TE_USB_FX2_USB_device (CyUSBDevice type) is initialized to null. * If one or more devices are attached and * 1) if 0 <= CardNumber <= (number of attached devices – 1), then * TE_USB_FX2_USBDevice (CyUSBDevice type) will point to and will be initialized according to the selected device. * 2) if CardNumber >= number of attached devices, then * TE_USB_FX2_USBDevice (CyUSBDevice type) is initialized to null. * * A more intuitive name for this function would have been TE_USB_FX2_SelectCard(). * * 3.2.4 Parameters * 1. ref CyUSBDevice TE_USB_FX2_USBDevice * TE_USB_FX2_USBDevice is the module selected by this function. This is the most useful value returned by this function. This parameter is passed by reference (ref). See pages 70-93 of CyUSB.NET.pdf (Cypress CyUSB .NET DLL Programmer's Reference). * 2. ref USBDeviceList USBdevList * USBDeviceList is a type defined in CyUSB.dll. USBdevList is the list of devices served by the CyUSB.sys driver (or a derivative like TE_USB_FX2.sys). This parameter is passed by reference (ref). See page 139-140 of CyUSB.NET.pdf (Cypress CyUSB .NET DLL Programmer's Reference) * 3. int CardNumber * This is the number of the selected Trenz Electronic USB FX2 device. * * 3.2.5 Return Value * 1. bool : logical type * This function returns true if it is able to find the module selected by CardNumber. If unable to do so, it returns false. * */ /// <summary> /// ////// /// </summary> /// <param name="TE_USB_FX2_USBDevice"></param> /// <param name="USBdevList"></param> /// <param name="CardNumber"></param> /// <returns=bool></returns> public static bool TE_USB_FX2_Open(ref CyUSBDevice TE_USB_FX2_USBDevice, ref USBDeviceList USBdevList, int CardNumber) { int CardCounted = 0; // Trenz Device //int DeviceNumber = 0; // Cypress Device ( number >= TrenzDevice) //Number of Cypress Device (Trenz Electronic or not) int CypressDeviceNumber = 0; //Number of Trenz Device int TrenzDeviceNumber = 0; //Position of Trenz Device desired in the USBDeviceList int DeviceNumber = 0; UInt16 PID = 0x0000; UInt16 VID = 0x0000; //Creation of a list of USB device that use the CYUSB.SYS driver USBdevList = new USBDeviceList(CyConst.DEVICES_CYUSB); //If exist at least an USB device that use the CYUSB.SYS driver, //I search and count the number of these devices that are of Trenz Electronic if (USBdevList.Count != 0) { foreach (USBDevice USBdev in USBdevList) { PID = USBdev.ProductID; VID = USBdev.VendorID; //Number of Cypress Card augmented by one CypressDeviceNumber++; if ((((PID == 0x0300) && (VID == 0x0bd0)) == true)) { //Number of Trenz Card (a subcategory of Cypress Card) augmented by one //CardCount++; TrenzDeviceNumber++; //Console.WriteLine("PID e VID: {0}, {1}", PID, VID); // CardNumber=TrenzDeviceNumber-1 by definition. if ((TrenzDeviceNumber - 1) == CardNumber) { //I store the DeviceNumber that identify the Trenz Card (CardNumber) requested //Memorize this number for later use //This is the position of Trenz Device desired in the USBDeviceList DeviceNumber = CypressDeviceNumber - 1; //Console.WriteLine("DeviceNumber: {0}", DeviceNumber); } } } } //At this point I memorize the Cards Counted and zeroed the variable that I have used in the counting. CardCounted = TrenzDeviceNumber; //Console.WriteLine("CardCounted: {0}", CardCount); TrenzDeviceNumber = 0; //Now I search the Trenz USB Device with the Card Number (CardNo) specified if (((CardNumber >= 0) && (CardNumber < CardCounted)) == true) //CardCounted { USBDevice USBdev = USBdevList[DeviceNumber]; PID = USBdev.ProductID; VID = USBdev.VendorID; if ((((PID == 0x0300) && (VID == 0x0bd0)) == true)) { TE_USB_FX2_USBDevice = USBdev as CyUSBDevice; //Console.WriteLine("USBdev {0} ", TE_USB_FX2_USBDevice); return true; } else { TE_USB_FX2_USBDevice = null; return false; } } else { TE_USB_FX2_USBDevice = null; return false; } }
private void ProgramFX3Ram_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) return; CyFX3Device fx = FxDev as CyFX3Device; // check for bootloader first, if it is not running then prompt message to user. if (!fx.IsBootLoaderRunning()) { MessageBox.Show("Please reset your device to download firmware", "Bootloader is not running"); return; } string tmpFilter = FOpenDialog.Filter; if (sender == ProgramFX3Ram) FOpenDialog.Filter = "Firmware Image files (*.img) | *.img"; if ((FxDev != null) && (FOpenDialog.ShowDialog() == DialogResult.OK)) { FX3_FWDWNLOAD_ERROR_CODE enmResult = FX3_FWDWNLOAD_ERROR_CODE.SUCCESS; if (sender == ProgramFX3Ram) { StatLabel.Text = "Programming RAM of " + FxDev.FriendlyName; Refresh(); string filename = FOpenDialog.FileName; if (bRecording && (script_stream != null)) { byte ConfigNum = fx.Config; byte IntfcNum = 0; byte AltIntfc = fx.AltIntfc; fx.SetRecordingFlag(true, ConfigNum, IntfcNum, AltIntfc); } if (fx.IsRecordingFlagSet()) { fx.ScriptFileForDwld(script_stream); } enmResult = fx.DownloadFw(filename, FX3_FWDWNLOAD_MEDIA_TYPE.RAM); fx.SetRecordingFlag(false, Xaction.ConfigNum, Xaction.IntfcNum, Xaction.AltIntfc); } StatLabel.Text = "Programming " + fx.GetFwErrorString(enmResult); Refresh(); } FOpenDialog.FileName = ""; FOpenDialog.Filter = tmpFilter; }
/* * 3.5 TE_USB_FX2_GetData() * * 3.5.1 Declaration * public static bool TE_USB_FX2_GetData(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] DataRead, ref int DataReadLength, * int PipeNo, uint Timeout, int BufferSize) * * 3.5.2 Function Call * Your application program shall call this function like this: * TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_GetData(ref TE_USB_FX2_USBDevice, ref DataRead, ref DataReadLength, PI_EP6, Timeout, * BufferSize); * * 3.5.3 Description * This function takes an already initialized USB Device (previously selected by TE_USB_FX2_Open()) and reads data from * USB FX2 microcontroller endpoint EP6 (0x86) (endpoints EP4(0x84) or EP2(0x82) are also theoretically possible). * Data comes from the FPGA. * Currently (April 2012), only endpoint 0x86 is actually implemented in Trenz Electronic USB FPGA modules, so that endpoints * EP2 and EP4 cannot be read or , more precisely, they are not even connected to the FPGA. That is why attempting to read them * causes a function failure after Timeout expires. * 3.5.4 Expected Data Throughput * The maximum data throughput expected (with a DataReadLength= 120*10^6) is 37 Mbyte/s (PacketSize = BufferSize = 131,072), * but in fact this value is variable between 31-36 Mbyte/s (the mean value seems 33.5 Mbyte/s); so if you measure this range * of values, the data reception can be considered as normal. * The data throughput is variable in two ways: * 1. depends on the used host computer; * 2. varies with every function call. * 3.5.5 DataRead Size Shall Not Be Too Large * TE_USB_FX2_GetData() seems unable to use too large arrays or, more precisely, this fact seems variable by changing host * computer. To be safe, do not try to transfer in a single packet very large data (e.g. 120 millions of byte); transfer the * same data with many packets instead (1,200 packets * 100,000 byte) and copy the data in a single large data array if necessary * (with Buffer.BlockCopy()). Buffer.BlockCopy seems not to hinder throughput too much (max 2 Mbyte/s) * 3.5.5.1 Reduced version (pseudo code) * PACKETLENGTH=100000; * packets=1200; * byte[] data = new byte[packetlen*packets]; * byte[] buffer = new byte[packetlen]; * for (int i = 0; i < packets; i++) * { * TE_USB_FX2_GetData(ref TE_USB_FX2_USBDevice, ref buffer, ref packetlen, PI_EP6, TIMEOUT_MS,BUFFER_SIZE) * Buffer.BlockCopy(buffer, 0, data, total_cnt, packetlen); * total_cnt += packetlen; * } * 3.5.5.2 Expanded version (code) * PACKETLENGTH=100000; * packets=1200; * byte[] data = new byte[packetlen*packets]; * byte[] buffer = new byte[packetlen]; * //starts test: the FPGA start to write data in the buffer EP6 of FX2 chip * SendFPGAcommand(ref TE_USB_FX2_USBDevice, MB_Commands.FX22MB_REG0_START_TX, TIMEOUT_MS); * test_cnt = 0; * total_cnt = 0; * for (int i = 0; i < packets; i++) * { * //buffer = &data[total_cnt]; * packetlen = PACKETLENGTH; * //fixed (byte* buffer = &data[total_cnt] * bResultXfer = TE_USB_FX2.TE_USB_FX2.TE_USB_FX2_GetData(ref TE_USB_FX2_USBDevice, ref buffer, ref packetlen, PI_EP6, * TIMEOUT_MS,BUFFER_SIZE); * Buffer.BlockCopy(buffer, 0, data, total_cnt, packetlen); * if (bResultXfer == false) * { * //cout << "ERROR" << endl; * Console.WriteLine("Error Get Data"); * SendFPGAcommand(ref TE_USB_FX2_USBDevice, MB_Commands.FX22MB_REG0_STOP, TIMEOUT_MS); * return; * } * total_cnt += packetlen *} * //stop test: the FPGA start to write data in the buffer EP6 of //FX2 chip *SendFPGAcommand(ref TE_USB_FX2_USBDevice, *MB_Commands.FX22MB_REG0_STOP, TIMEOUT_MS); *3.5.6 DataRead Size Shall Not Be Too Small *There are two reasons why DataRead size shall not be too small. *The first reason is described in section 1.1.4 PacketSize. PacketSize has also a strong influence on DataThroughput. *If PacketSize is too small (e.g. 512 byte), you can have very low DataThroughput (2.2 Mbyte/s) even if you use a large driver *buffer (driver buffer size = 131,072 bytes). See section 6 TE_USB_FX2_CyUSB.dll: Data Transfer Throughput Optimization. *The second reason is that probably the FPGA imposes your minimum packet size. In a properly used read test mode *(using FX22MB_REG0_START_TX and therefore attaching the FPGA), TE_USB_FX2_GetData() is unable to read less than 1024 byte. *In a improperly used read test mode (not using FX22MB_REG0_START_TX and therefore detaching the FPGA), TE_USB_FX2_GetData() *is able to read a packet size down to 64 byte. The same CyUSB method XferData() used (under the hood) in *TE_USB_FX2_SendCommand() is able to read a packet size of 64 byte. These facts prove that the minimum packet size is imposed *by FPGA. To be safe, we recommend to use this function with a size multiple of 1 kbyte. * *3.5.7 Parameters *1. ref CyUSBDevice TE_USB-FX2_USBDevice *This parameter points to the module selected by TE_USB_FX2_Open(). This parameter is passed by reference (ref). See pages 70-93 *of CyUSB.NET.pdf (Cypress CyUSB .NET DLL Programmer's Reference) *2. ref byte[] DataRead *This parameter is passed by reference (ref). C# applications use directly TE_USB_FX2_CyUSB.dll based on CyUSB.dll. To avoid *copying back and forth large amount of data between these two DLLs, data is passed by reference rather than by value. This *parameter points to the byte array that, after the function returns, will contain the data read from the buffer EP6 of the *USB FX2 microcontroller. The data contained in EP6 generated by the FPGA. If no data is contained in EP6, the byte array is *left unchanged. *3. ref int DataReadLength *This parameter is the length (in bytes) of the previous byte array; it is the length of the packet read from the USB FX2 *microcontroller endpoint EP6 (0x86). It is typically PacketLength. This parameter is passed by reference (ref). *4. int PipeNumber *This parameter is the value that identifies the endpoint used for data transfer. It is called PipeNumber because it identifies *the buffer (pipe) used by the USB FX2 microcontroller. *5. uint Timeout *It is the integer time value in milliseconds assigned to the synchronous method XferData() of data transfer used by CyUSB.dll. *Timeout is the time that is allowed to the function for sending/receiving the data packet passed to the function; this timeout *shall be large enough to allow data/command transmission/reception.. Otherwise the transmission/reception will fail. *See 1.1.2 Timeout Setting. *6. int BufferSize *It is the dimension (in bytes) of the driver buffer (SW) used in data reception of a single endpoint (EP6 0x86 in this case) *single endpoint (EP6 0x86 in this case); the total buffer size is the sum of BufferSize of every endpoint used. BufferSize has *a strong influence on DataThroughput. If the BufferSize is too small, DataThroughput can be 1/3-1/2 of the maximum value *(from a maximum value of 36 Mbyte/s for read transactions to an actual value of 18 Mbyte/s). If BufferSize has a large value *(a roomy buffer), the program shall be able to cope with the non-deterministic behavior of C# without losing packets. * *3.5.8 Return Value *1. bool : logical type *This function returns true if it is able to receive the data from buffer EP6 within Timeout milliseconds. *This function returns false otherwise. * */ /// <summary> /// //////// /// </summary> /// <param name="TE03xxUSBdevice"></param> /// <param name="DataRead"></param> /// <param name="DataReadLength"></param> /// <param name="PipeNo"></param> /// <param name="Timeout"></param> /// /// <returns></returns> //public static bool TE_USB_FX2_GetData(ref CyUSBDevice TE_USB_FX2_USBDevice,ref CyBulkEndPoint inEndpointPipeNo, ref byte[] DataRead, ref int DataReadLength, int PipeNo, uint Timeout) public static bool TE_USB_FX2_GetData(ref CyUSBDevice TE_USB_FX2_USBDevice, ref byte[] DataRead, ref int DataReadLength, int PipeNo, uint Timeout, int BufferSize) { bool bResultDataRead = false; byte PipeNoHex = 0x00; //Shortest and more portable way to select the Address using the PipeNumber CyBulkEndPoint inEndpointPipeNo = null; //Shortest and more portable way if (PipeNo == 2) PipeNoHex = 0x82; else PipeNoHex = 0x00; if (PipeNo == 4) PipeNoHex = 0x84; else PipeNoHex = 0x00; if (PipeNo == 6) PipeNoHex = 0x86; else PipeNoHex = 0x00; //Fundamental Note: currently (March 2012) only 0x86 EndPoint is actually implemented in TE-USB FPGA modules if ((TE_USB_FX2_USBDevice != null) && (PipeNoHex == 0x86)) //(TE_USB_FX2_USBDevice != null) && { inEndpointPipeNo = TE_USB_FX2_USBDevice.EndPointOf(PipeNoHex) as CyBulkEndPoint; inEndpointPipeNo.TimeOut = Timeout; //int MaxPacketSize= outEndpointPipeNo.MaxPktSize; //Console.WriteLine("MaxPacketSize {0} ", MaxPacketSize); //int XferSize1 = outEndpointPipeNo.XferSize; //Console.WriteLine("XferSize {0} ", XferSize1); //outEndpointPipeNo.XferMode = XMODE.DIRECT; inEndpointPipeNo.XferSize = BufferSize; // 131072; //calls the XferData function for bulk transfer(IN) in the cyusb.dll bResultDataRead = inEndpointPipeNo.XferData(ref DataRead, ref DataReadLength); //uint inUSBstatus1 = inEndpointPipeNo.UsbdStatus; //Console.WriteLine("UsbdStatus {0:X8} ", inUSBstatus1); //uint inUSBstatus2 = inEndpointPipeNo.NtStatus; //Console.WriteLine("NtStatus {0:X8} ", inUSBstatus2); if (bResultDataRead == true) return true; else return false; } else return false; }
/* Summary Resets the selected FxDev device */ private void Reset_device_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } FxDev.Reset(); RefreshDeviceTree(); StatLabel.Text = "Device Reset Successfull"; }
/* Summary Aborts the selected endpoint */ private void Abort_endpoint_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } if (curEndpt == null) { MessageBox.Show("Select an endpoint to Abort.", "No endpoint selected"); return; } curEndpt.Abort(); StatLabel.Text = "Abort Successfull"; }
/* Summary Resets the selected pipe */ private void Reset_Pipe_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } if (curEndpt == null) { MessageBox.Show("Select an endpoint to reset.", "No endpoint selected"); return; } curEndpt.Reset(); StatLabel.Text = "Reset Pipe Successfull"; }
/* Summary Reconnects the selected FxDev device */ private void Reconnect_device_Click(object sender, EventArgs e) { FxDev = FxDevDeviceSelected(); if (FxDev == null) { return; } FxDev.ReConnect(); StatLabel.Text = "Device Reconnected"; }
/* Summary Transfer file button should be visible only for certain conditions which is done here. */ private void ConfigDataXferBtn(string nodeTxt) { FileXferBtn.Visible = false; FileXferBtn.Enabled = false; //DataXferBtn.Enabled = true; //Changed here FxDev = FxDevDeviceSelected_forusage(); if (FxDev != null) { FileXferBtn.Visible = true; FileXferBtn.Enabled = true; } ///check device type , enable disable the fx/fx3 file manu button if (FxDev != null) { if (!FxDev.IsFX2Device) {//FX3 ProgramFX3Ram.Enabled = true; fX3ToolStripMenuItem.Enabled = true; fX2ToolStripMenuItem.Enabled = false; ProgramFX2RamMenuItm.Enabled = false; ProgramFX264kBEEPROMMenuItem.Enabled = false; ProgramFX2smallEEPROMMenuItem.Enabled = false; ProgramFX2haltMenuItem.Enabled = false; ProgramFX2runMenuItem.Enabled = false; } else {//FX2 ProgramFX3Ram.Enabled = false; fX3ToolStripMenuItem.Enabled = false; fX2ToolStripMenuItem.Enabled = true; ProgramFX2RamMenuItm.Enabled = true; ProgramFX264kBEEPROMMenuItem.Enabled = true; ProgramFX2smallEEPROMMenuItem.Enabled = true; ProgramFX2haltMenuItem.Enabled = true; ProgramFX2runMenuItem.Enabled = true; } } // if (nodeTxt.Contains("Feature")) { DataXferBtn.Text = "Get Feature"; FileXferBtn.Text = "Set Feature"; FileXferBtn.Visible = true; FileXferBtn.Enabled = true; } else if (nodeTxt.Contains("Input")) { DataXferBtn.Text = "Get Input"; string os = GetOSName(); //GetInput is only supported under WindowsXP and newer. if (!((os == "Windows XP") || (os == "Windows Vista"))) DataXferBtn.Enabled = false; } else if (nodeTxt.Contains("Output")) DataXferBtn.Text = "Set Output"; else { if (curEndpt != null) { if (curEndpt.Attributes != 0) { if (curEndpt.bIn) { DataXferBtn.Text = "Transfer Data-IN"; FileXferBtn.Text = "Transfer File-IN"; } else { DataXferBtn.Text = "Transfer Data-OUT"; FileXferBtn.Text = "Transfer File-OUT"; } } else { DataXferBtn.Text = "Transfer Data"; FileXferBtn.Text = "Transfer File"; } } else { DataXferBtn.Text = "Transfer Data"; FileXferBtn.Text = "Transfer File"; } } if (curHidDev != null) { TreeNode selNode = DeviceTreeView.SelectedNode; DataXferBtn.Enabled = curHidDev.RwAccessible; string os = GetOSName(); //GetInput is only supported under WindowsXP and newer. if (!((os == "Windows XP") || (os == "Windows Vista"))) DataXferBtn.Enabled = false; } else DataXferBtn.Enabled = true; }