Example #1
0
        public static void ReadI2CWorker(object data)
        {
            WiiReaderV1 reader = ((WiiReaderV1)data);

            while (!reader.inShutdown)
            {
                I2CPacket packet = reader.packetPool[reader.currentPacketInPool];
                reader.currentPacketInPool += 1;
                reader.currentPacketInPool %= 100;

                uint  status         = 0;
                ulong timeSop        = 0;
                ulong timeDuration   = 0;
                uint  timeDataOffset = 0;

                packet.Length = BeagleApi.bg_i2c_read(
                    ((WiiReaderV1)data).hBeagle, ref status, ref timeSop,
                    ref timeDuration, ref timeDataOffset, 1024, packet.Data);

                if (packet.Length >= 1)
                {
                    reader.packetsToBeProcessed.Enqueue(packet);
                }
            }
        }
Example #2
0
        public static void ReadUSBWorker(object data)
        {
            XboxReader reader = ((XboxReader)data);

            while (!reader.inShutdown)
            {
                USBPacket packet = reader.packetPool[reader.currentPacketInPool];
                reader.currentPacketInPool += 1;
                reader.currentPacketInPool %= 100;

                uint  status         = 0;
                uint  events         = 0;
                ulong timeSop        = 0;
                ulong timeDuration   = 0;
                uint  timeDataOffset = 0;

                packet.Length = BeagleApi.bg_usb2_read(
                    ((XboxReader)data).hBeagle, ref status, ref events, ref timeSop,
                    ref timeDuration, ref timeDataOffset, 1024, packet.Packet);

                if (packet.Length == 23 &&
                    (packet.Packet[0] == BeagleApi.BG_USB_PID_DATA1 || packet.Packet[0] == BeagleApi.BG_USB_PID_DATA0) &&
                    packet.Packet[1] == 0x00 &&
                    packet.Packet[2] == 0x14)
                {
                    reader.packetsToBeProcessed.Enqueue(packet);
                }
            }
        }
Example #3
0
    /*=====================================================================
     | GENERIC DETECTION ROUTINE
     | ====================================================================*/
    static void find_devices()
    {
        ushort[] ports      = new ushort[16];
        uint[]   unique_ids = new uint[16];
        int      nelem      = 16;

        // Find all the attached devices
        int count = BeagleApi.bg_find_devices_ext(nelem, ports,
                                                  nelem, unique_ids);
        int i;

        Console.Write("{0:d} device(s) found:\n", count);

        // Print the information on each device
        if (count > nelem)
        {
            count = nelem;
        }
        for (i = 0; i < count; ++i)
        {
            // Determine if the device is in-use
            String status = "(avail) ";
            if ((ports[i] & BeagleApi.BG_PORT_NOT_FREE) != 0)
            {
                ports[i] &= unchecked ((ushort)~BeagleApi.BG_PORT_NOT_FREE);
                status    = "(in-use)";
            }

            // Display device port number, in-use status, and serial number
            Console.Write("    port={0,-3:d} {1:s} ({2:d4}-{3:d6})\n",
                          ports[i], status,
                          unique_ids[i] / 1000000,
                          unique_ids[i] % 1000000);
        }
    }
    /*=====================================================================
     | BUFFER CONFIGURATION
     | ====================================================================*/
    static void usbConfigBuffer()
    {
        uint pretrig_kb = 0;
        uint capture_kb = 0;

        // Configure Beagle 5000 for capturing USB 3.0, and waiting for a
        // trigger event.
        if (BeagleApi.bg_usb5000_configure(
                beagle,
                BeagleApi.BG_USB5000_CAPTURE_USB3,
                BeagleUsb5000TriggerMode.BG_USB5000_TRIGGER_MODE_EVENT) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write(
                "error: could not configure Beagle 5000 with desired mode\n");
            Environment.Exit(1);
        }

        // Configure the onboard USB 3.0 buffer for 1MB of pretrigger and
        // 3MB of posttrigger.
        if (BeagleApi.bg_usb5000_usb3_capture_config(beagle, 1024, 4096) < 0)
        {
            Console.Write("error: configuring capture buffer failed!\n");
            Environment.Exit(1);
        }

        BeagleApi.bg_usb5000_usb3_capture_config_query(beagle,
                                                       ref pretrig_kb,
                                                       ref capture_kb);

        Console.Write("Configured capture buffer: " +
                      "pretrig = {0:d}KB total capture = {1:d}KB\n\n",
                      pretrig_kb, capture_kb);
    }
Example #5
0
 private void open_handle()
 {
     handle = BeagleApi.bg_open(port);
     if (handle <= 0)
     {
         Console.WriteLine("Unable to open Beagle device on port {0}", port);
         Console.WriteLine("error: {0}", BeagleApi.bg_status_string(handle));
     }
 }
Example #6
0
        public WiiReaderV1(int controllerId)
        {
            if (!Environment.Is64BitProcess)
            {
                throw new IOException("WiiReaderV1 is only support in 64 bit RetroSpy!");
            }

            wm_rand = new byte[10];
            wm_key  = new byte[6];
            wm_ft   = new byte[8];
            wm_sb   = new byte[8];

            // Setup the Beagle
            hBeagle = BeagleApi.bg_open(controllerId);
            if (hBeagle <= 0)
            {
                throw new IOException(String.Format("WiiReaderV1 could not find Beagle USB Protocol Analyzer on port {0}.", controllerId));
            }

            isOpened = true;

            int samplerate = 10000;

            samplerate = BeagleApi.bg_samplerate(hBeagle, samplerate);
            if (samplerate < 0)
            {
                Finish();
                throw new IOException(String.Format("WiiReaderV1 error: {0:s}\n", BeagleApi.bg_status_string(samplerate)));
            }

            BeagleApi.bg_timeout(hBeagle, milliseconds: 500);
            BeagleApi.bg_latency(hBeagle, milliseconds: 0);
            BeagleApi.bg_target_power(hBeagle, BeagleApi.BG_TARGET_POWER_OFF);
            BeagleApi.bg_i2c_pullup(hBeagle, BeagleApi.BG_I2C_PULLUP_OFF);

            if (BeagleApi.bg_enable(hBeagle, BeagleProtocol.BG_PROTOCOL_I2C) != (int)BeagleStatus.BG_OK)
            {
                Finish();
                throw new IOException("WiiReaderV1 error: could not enable I2C capture\n");
            }
            isEnabled = true;

            packetPool = new I2CPacket[1024];

            for (int i = 0; i < 100; ++i)
            {
                packetPool[i] = new I2CPacket();
            }

            Thread usbParsingThread = new Thread(ProcessPacketWorker);
            Thread usbReadingThread = new Thread(ReadI2CWorker);

            usbParsingThread.Start(this);
            usbReadingThread.Start(this);
        }
Example #7
0
        public XboxReader(int controllerId)
        {
            if (!Environment.Is64BitProcess)
            {
                throw new IOException("XboxReader is only support in 64 bit RetroSpy!");
            }

            // Setup the Beagle
            hBeagle = BeagleApi.bg_open(controllerId);
            if (hBeagle <= 0)
            {
                throw new IOException(String.Format("XboxReader could not find Beagle USB Protocol Analyzer on port {0}.", controllerId));
            }

            isOpened = true;

            int samplerate = 0;

            samplerate = BeagleApi.bg_samplerate(hBeagle, samplerate);
            if (samplerate < 0)
            {
                Finish();
                throw new IOException(String.Format("XboxReader error: {0:s}\n", BeagleApi.bg_status_string(samplerate)));
            }

            BeagleApi.bg_timeout(hBeagle, milliseconds: 500);
            BeagleApi.bg_latency(hBeagle, milliseconds: 0);
            BeagleApi.bg_target_power(hBeagle, BeagleApi.BG_TARGET_POWER_OFF);

            if (BeagleApi.bg_enable(hBeagle, BeagleProtocol.BG_PROTOCOL_USB) != (int)BeagleStatus.BG_OK)
            {
                Finish();
                throw new IOException("XboxReader error: could not enable USB capture\n");
            }
            isEnabled = true;

            packetPool = new USBPacket[100];

            for (int i = 0; i < 100; ++i)
            {
                packetPool[i] = new USBPacket();
            }

            Thread usbParsingThread = new Thread(ProcessPacketWorker);
            Thread usbReadingThread = new Thread(ReadUSBWorker);

            usbParsingThread.Start(this);
            usbReadingThread.Start(this);
        }
Example #8
0
        public void Finish()
        {
            inShutdown = true;
            Thread.Sleep(1000);

            if (isEnabled)
            {
                BeagleApi.bg_disable(hBeagle);
            }

            if (isOpened)
            {
                BeagleApi.bg_close(hBeagle);
            }
        }
Example #9
0
        public static List <uint> GetDevices()
        {
            var result = new List <uint>();

            ushort[] ports      = new ushort[16];
            uint[]   unique_ids = new uint[16];
            int      nelem      = 16;

            if (Environment.Is64BitProcess)
            {
                int count = BeagleApi.bg_find_devices_ext(nelem, ports, nelem, unique_ids);
                for (uint i = 0; i < count; i++)
                {
                    result.Add(ports[i]);
                }
            }

            return(result);
        }
Example #10
0
        private void setup_i2c()         //set timing bit size, sample rate, and timeout
        {
            // Get the size of the timing information for a transaction of
            // max_bytes length
            timing_size = BeagleApi.bg_bit_timing_size(BeagleProtocol.BG_PROTOCOL_I2C, max_bytes);
            timing      = new uint[timing_size];

            sample_rate = BeagleApi.bg_samplerate(handle, 200);               //sampling rate in khz
            if (BeagleApi.bg_timeout(handle, 500) != (int)BeagleStatus.BG_OK) //set the timeout to 1s
            {
                Console.WriteLine("error: Could not set Beagle timeout; exiting...\n");
                //throw new InvalidOperationException("Could not set Beagle timeout; exiting...");
            }
            if (BeagleApi.bg_enable(handle, BeagleProtocol.BG_PROTOCOL_I2C) != (int)BeagleStatus.BG_OK)             //start polling bus
            {
                Console.WriteLine("error: could not enable I2C capture; exiting...\n");
                //throw new InvalidOperationException("error: could not enable I2C capture; exiting...");
            }
        }
Example #11
0
    /*=========================================================================
     | DIGITAL INPIT/OUTPUT CONFIG
     | ========================================================================*/
    static void setupDigitalLines()
    {
        // Digital input mask
        byte input_enable_mask =
            BeagleApi.BG_USB2_DIGITAL_IN_ENABLE_PIN1 |
            BeagleApi.BG_USB2_DIGITAL_IN_ENABLE_PIN2 |
            BeagleApi.BG_USB2_DIGITAL_IN_ENABLE_PIN3 |
            BeagleApi.BG_USB2_DIGITAL_IN_ENABLE_PIN4;

        // Define the packet and data match structures.  By using 'new'
        // to define these structures, their value type elements are
        // initialized to 0 and the reference type elements (including
        // the arrays) are set to null.
        BeagleApi.BeagleUsb2PacketMatch packet_match =
            new BeagleApi.BeagleUsb2PacketMatch();
        BeagleApi.BeagleUsb2DataMatch data_match =
            new BeagleApi.BeagleUsb2DataMatch();

        // Enable digital input pins
        BeagleApi.bg_usb480_digital_in_config(beagle, input_enable_mask);
        Console.Write("Configuring digital input with {0:x}\n",
                      input_enable_mask);

        // Configure digital out pins.  Only those fields that we want
        // enabled need to be set here since everything was initialized
        // above.
        packet_match.pid_match_type =
            BeagleUsb2MatchType.BG_USB2_MATCH_TYPE_EQUAL;
        packet_match.pid_match_val = BeagleApi.BG_USB_PID_PING;

        // Enable digital output pin 4
        BeagleApi.bg_usb480_digital_out_config(beagle,
                                               BeagleApi.BG_USB2_DIGITAL_OUT_ENABLE_PIN4,
                                               BeagleApi.BG_USB2_DIGITAL_OUT_PIN4_ACTIVE_HIGH);

        // Configure digital output pin 4 match pattern
        BeagleApi.bg_usb480_digital_out_match(beagle,
                                              BeagleUsb2DigitalOutMatchPins.BG_USB2_DIGITAL_OUT_MATCH_PIN4,
                                              packet_match, data_match);

        Console.Write("Configuring digital output pin 4.\n");
    }
Example #12
0
        string print_general_status(uint status)
        {
            string status_string = " ";

            Console.Write(" ");

            // General status codes
            if (status == BeagleApi.BG_READ_OK)
            {
                status_string += ("OK");
            }

            if (status != 0)
            {
                buffer_available = BeagleApi.bg_host_buffer_used(handle);
                status_string   += "(" + buffer_available + ":" + BeagleApi.bg_host_buffer_size(handle, 0) + ")";
            }
            if ((status & BeagleApi.BG_READ_TIMEOUT) != 0)
            {
                status_string += ("TIMEOUT ");
            }

            if ((status & BeagleApi.BG_READ_ERR_MIDDLE_OF_PACKET) != 0)
            {
                status_string += ("MIDDLE ");
            }

            if ((status & BeagleApi.BG_READ_ERR_SHORT_BUFFER) != 0)
            {
                status_string += ("SHORT BUFFER ");
            }

            if ((status & BeagleApi.BG_READ_ERR_PARTIAL_LAST_BYTE) != 0)
            {
                status_string += string.Format("PARTIAL_BYTE(bit {0:d}) ", status & 0xff);
            }

            return(status_string);
        }
Example #13
0
        public void find_device()
        {
            int device_num = 8;
            var ports      = Enumerable.Repeat <ushort>(9999, device_num).ToArray();
            var ids        = new uint[device_num];

            try
            {
                int aa_num = AardvarkApi.aa_find_devices_ext(device_num, ports, device_num, ids);
                if (aa_num > 0)
                {
                    for (int i = 0; i < device_num; i++)
                    {
                        if (ports[i] != 9999 && !check_aardvark(ids[i]))                         //check if not there already
                        {
                            aardvarks.Add(new Aardvark(ports[i], ids[i]));
                        }
                    }
                }
                int bg_num = BeagleApi.bg_find_devices_ext(device_num, ports, device_num, ids);
                if (bg_num > 0)
                {
                    for (int i = 0; i < device_num; i++)
                    {
                        if (ports[i] != 9999 && !check_beagle(ids[i]))
                        {
                            beagles.Add(new Beagle(ports[i], ids[i]));
                        }
                    }
                }
            }
            catch (System.TypeInitializationException)
            {
                MessageBox.Show("Application must target 64 bit");
            }
        }
Example #14
0
    static void usbDump(int numPackets, byte capMask)
    {
        // Setup variables
        byte[] packet      = new byte[1036];
        byte[] packetKBits = new byte[130];

        int packetnum = 0;

        BeagleUsb5000CaptureStatus captureStatus =
            BeagleUsb5000CaptureStatus.BG_USB5000_CAPTURE_STATUS_INACTIVE;
        uint pretrigAmt   = 0;
        uint pretrigTotal = 0;
        uint capAmt       = 0;
        uint capTotal     = 0;
        int  ret          = 0;

        #if STATS_MODE
        // Statistic mode variables
        ulong dispTimeSop     = 0;
        ulong sstxByteCount   = 0;
        ulong ssrxByteCount   = 0;
        ulong sstxPacketCount = 0;
        ulong ssrxPacketCount = 0;
        ulong usb2ByteCount   = 0;
        ulong usb2PacketCount = 0;
        #endif

        // Configure Beagle 480 for realtime capture
        if (BeagleApi.bg_usb5000_configure(
                beagle, capMask,
                BeagleUsb5000TriggerMode.BG_USB5000_TRIGGER_MODE_IMMEDIATE) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write(
                "error: could not configure Beagle 5000 with desired mode\n");
            Environment.Exit(1);
        }

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_USB) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable USB capture; exiting...\n");
            Environment.Exit(1);
        }

        // Wait for the analyzer to trigger for up to 2 seconds...
        if ((capMask & BeagleApi.BG_USB5000_CAPTURE_USB2) != 0)
        {
            ret = BeagleApi.bg_usb5000_usb2_capture_status(
                beagle, 2000, ref captureStatus,
                ref pretrigAmt, ref pretrigTotal,
                ref capAmt, ref capTotal);
        }
        else
        {
            ret = BeagleApi.bg_usb5000_usb3_capture_status(
                beagle, 2000, ref captureStatus,
                ref pretrigAmt, ref pretrigTotal,
                ref capAmt, ref capTotal);
        }

        if (ret != (int)BeagleStatus.BG_OK)
        {
            Console.Write(
                "error: could not query capture status; exiting...\n");
            Environment.Exit(1);
        }

        if (captureStatus <= BeagleUsb5000CaptureStatus.
            BG_USB5000_CAPTURE_STATUS_PRE_TRIGGER)
        {
            Console.Write("did not trigger.\n");
            Environment.Exit(1);
        }

        // Output the header...
        #if STATS_MODE
        Console.Write(
            "   SSTX PACKETS ( MB/s )    SSRX PACKETS ( MB/s )    USB2 PACKETS ( MB/s )\n");
        #else
        Console.Write(
            "index,time(ns),source,event,status,data0 ... dataN(*)\n");
        #endif
        Console.Out.Flush();

        // ...then start decoding packets
        while (packetnum < numPackets || (numPackets == 0))
        {
            uint  status               = 0;
            uint  events               = 0;
            ulong timeSop              = 0;
            ulong timeDuration         = 0;
            uint  timeDataOffset       = 0;
            BeagleUsb5000Source source =
                BeagleUsb5000Source.BG_USB5000_SOURCE_ASYNC;

            int length = BeagleApi.bg_usb5000_read(
                beagle,
                ref status, ref events, ref timeSop, ref timeDuration,
                ref timeDataOffset, ref source,
                1036, packet, 130, packetKBits);

            // Make sure capture is triggered.
            if (length == (int)BeagleStatus.BG_CAPTURE_NOT_TRIGGERED)
            {
                continue;
            }

            // Check for invalid packet or Beagle error
            if (length < 0)
            {
                Console.Write("error={0:d}\n", length);
                break;
            }

            // Exit if observed end of capture
            if (status == BeagleApi.BG_READ_USB_END_OF_CAPTURE)
            {
                Console.Write("\n");
                Console.Write("End of capture\n");
                break;
            }

            #if STATS_MODE
            // Count the number of packets and bytes
            if (length > 0)
            {
                switch (source)
                {
                case BeagleUsb5000Source.BG_USB5000_SOURCE_USB2:
                    usb2PacketCount++;
                    usb2ByteCount += (ulong)length;
                    break;

                case BeagleUsb5000Source.BG_USB5000_SOURCE_TX:
                    sstxPacketCount++;
                    sstxByteCount += (ulong)length;
                    break;

                case BeagleUsb5000Source.BG_USB5000_SOURCE_RX:
                    ssrxPacketCount++;
                    ssrxByteCount += (ulong)length;
                    break;

                default:
                    break;
                }
            }

            // Periodically print out the stats
            if ((timeSop - dispTimeSop) > DISPLAY_TIME_TICKS)
            {
                double timeS = (double)timestampToNS(timeSop - dispTimeSop,
                                                     samplerateKHz) / 1E9;
                double sstxMBps =
                    ((double)sstxByteCount) / (1024 * 1024L) / timeS;
                double ssrxMBps =
                    ((double)ssrxByteCount) / (1024 * 1024L) / timeS;
                double usb2MBps =
                    ((double)usb2ByteCount) / (1024 * 1024L) / timeS;

                Console.Write("\r{0,15:d} ({1,6:##0.00})" +
                              " {2,15:d} ({3,6:##0.00})" +
                              " {4,15:d} ({5,6:##0.00})",
                              sstxPacketCount, sstxMBps,
                              ssrxPacketCount, ssrxMBps,
                              usb2PacketCount, usb2MBps);

                sstxByteCount = 0;
                ssrxByteCount = 0;
                usb2ByteCount = 0;
                dispTimeSop   = timeSop;
            }
            #else
            // Grab the next packet on a timeout.
            if (length == 0 &&
                status == BeagleApi.BG_READ_TIMEOUT &&
                events == 0)
            {
                continue;
            }

            // Print the packet details
            Console.Write("{0},", packetnum);
            Console.Write("{0},", timestampToNS(timeSop, samplerateKHz));
            printSource(source);
            Console.Write(",");
            printEvents(source, events);
            Console.Write(",");
            printStatus(source, status);
            Console.Write(",");
            printPacket(source, packet, packetKBits, length);
            Console.Write("\n");
            #endif

            packetnum++;
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
Example #15
0
    /*=====================================================================
     | MAIN PROGRAM
     | ====================================================================*/
    public static void Main(String[] args)
    {
        int  port       = 0;     // open port 0 by default
        int  samplerate = 10000; // in kHz
        uint timeout    = 500;   // in milliseconds
        uint latency    = 200;   // in milliseconds
        int  len        = 0;
        int  num        = 0;

        if (args.Length < 2)
        {
            print_usage();
            Environment.Exit(1);
        }
        len = Convert.ToInt32(args[0]);
        num = Convert.ToInt32(args[1]);

        // Open the device
        beagle = BeagleApi.bg_open(port);
        if (beagle <= 0)
        {
            Console.Write("Unable to open Beagle device on port {0:d}\n",
                          port);
            Console.Write("Error code = {0:d}\n", beagle);
            Environment.Exit(1);
        }
        Console.Write("Opened Beagle device on port {0:d}\n", port);

        // Set the samplerate
        samplerate = BeagleApi.bg_samplerate(beagle, samplerate);
        if (samplerate < 0)
        {
            Console.Write("error: {0:s}\n",
                          BeagleApi.bg_status_string(samplerate));
            Environment.Exit(1);
        }
        Console.Write("Sampling rate set to {0:d} KHz.\n", samplerate);

        // Set the idle timeout.
        // The Beagle read functions will return in the specified time
        // if there is no data available on the bus.
        BeagleApi.bg_timeout(beagle, timeout);
        Console.Write("Idle timeout set to {0:d} ms.\n", timeout);

        // Set the latency.
        // The latency parameter allows the programmer to balance the
        // tradeoff between host side buffering and the latency to
        // receive a packet when calling one of the Beagle read
        // functions.
        BeagleApi.bg_latency(beagle, latency);
        Console.Write("Latency set to {0:d} ms.\n", latency);

        Console.Write("Host interface is {0:s}.\n",
                      ((BeagleApi.bg_host_ifce_speed(beagle)) != 0) ? "high speed" :
                      "full speed");
        // Configure the device for SPI
        BeagleApi.bg_spi_configure(
            beagle,
            BeagleSpiSSPolarity.BG_SPI_SS_ACTIVE_LOW,
            BeagleSpiSckSamplingEdge.BG_SPI_SCK_SAMPLING_EDGE_RISING,
            BeagleSpiBitorder.BG_SPI_BITORDER_MSB);

        // There is usually no need for target power when using the
        // Beagle as a passive monitor.
        BeagleApi.bg_target_power(beagle, BeagleApi.BG_TARGET_POWER_OFF);

        Console.Write("\n");
        Console.Out.Flush();

        spidump(len, num);

        // Close the device
        BeagleApi.bg_close(beagle);

        return;
    }
Example #16
0
    static void usbDump(int numPackets)
    {
        // Packets are saved during the collapsing process
        PacketQueue pktQ = new PacketQueue();

        // Info for the packet that was just read
        PacketInfo curPacket;

        // Collapsing counts and time collapsing started
        CollapseInfo collapseInfo = new CollapseInfo();

        CollapseState state = CollapseState.IDLE;
        bool          reRun = false;

        byte pid          = 0;
        int  signalErrors = 0;
        int  packetnum    = 0;

        samplerateKHz = BeagleApi.bg_samplerate(beagle, 0);

        int idle_samples = IDLE_THRESHOLD * samplerateKHz;

        // Configure Beagle 480 for realtime capture
        BeagleApi.bg_usb480_capture_configure(beagle,
                                              BeagleUsb480CaptureMode.BG_USB480_CAPTURE_REALTIME,
                                              BeagleUsb2TargetSpeed.BG_USB2_AUTO_SPEED_DETECT);

        // Filter packets intended for the Beagle analyzer. This is only
        // relevant when one host controller is being used.
        BeagleApi.bg_usb480_hw_filter_config(beagle,
                                             BeagleApi.BG_USB2_HW_FILTER_SELF);

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_USB) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable USB capture; exiting...\n");
            Environment.Exit(1);
        }

        // Output the header...
        Console.Write("index,time(ns),USB,status,pid,data0 ... dataN(*)\n");
        Console.Out.Flush();

        // ...then start decoding packets
        while (packetnum < numPackets || (numPackets == 0))
        {
            curPacket = pktQ.getTail();

            curPacket.length = BeagleApi.bg_usb480_read(
                beagle,
                ref curPacket.status,
                ref curPacket.events,
                ref curPacket.timeSop,
                ref curPacket.timeDuration,
                ref curPacket.timeDataOffset,
                1024,
                curPacket.data);

            curPacket.timeSopNS =
                timestampToNS(curPacket.timeSop, samplerateKHz);

            // Exit if observed end of capture
            if ((curPacket.status &
                 BeagleApi.BG_READ_USB_END_OF_CAPTURE) != 0)
            {
                usbPrintSummaryPacket(ref packetnum, collapseInfo,
                                      ref signalErrors);
                break;
            }

            // Check for invalid packet or Beagle error
            if (curPacket.length < 0)
            {
                String errorStatus = "";
                errorStatus += String.Format("error={0:d}", curPacket.length);
                usbPrintPacket(packetnum, curPacket, errorStatus);
                break;
            }

            // Check for USB error
            if (curPacket.status == BeagleApi.BG_READ_USB_ERR_BAD_SIGNALS)
            {
                ++signalErrors;
            }

            // Set the PID for collapsing state machine below.  Treat
            // KEEP_ALIVEs as packets.
            if (curPacket.length > 0)
            {
                pid = curPacket.data[0];
            }
            else if ((curPacket.events &
                      BeagleApi.BG_EVENT_USB_KEEP_ALIVE) != 0 &&
                     (curPacket.status &
                      BeagleApi.BG_READ_USB_ERR_BAD_PID) == 0)
            {
                pid = (byte)PacketGroup.KEEP_ALIVE;
            }
            else
            {
                pid = 0;
            }

            // Collapse these packets approprietly:
            // KEEP_ALIVE* SOF* (IN (ACK|NAK))* (PING NAK)*
            // (SPLIT (OUT|SETUP) NYET)* (SPLIT IN (ACK|NYET|NACK))*

            // If the time elapsed since collapsing began is greater than
            // the threshold, output the counts and zero out the counters.
            if (curPacket.timeSop - collapseInfo.timeSop >=
                (ulong)idle_samples)
            {
                usbPrintSummaryPacket(ref packetnum, collapseInfo,
                                      ref signalErrors);
            }

            while (true)
            {
                reRun = false;
                switch (state)
                {
                // The initial state of the state machine.  Collapse SOFs
                // and KEEP_ALIVEs.  Save IN, PING, or SPLIT packets and
                // move to the next state for the next packet.  Otherwise,
                // print the collapsed packet counts and the current
                // packet.
                case CollapseState.IDLE:
                    switch (pid)
                    {
                    case (byte)PacketGroup.KEEP_ALIVE:
                        collapse(PacketGroup.KEEP_ALIVE, collapseInfo, pktQ);
                        break;

                    case BeagleApi.BG_USB_PID_SOF:
                        collapse(PacketGroup.SOF, collapseInfo, pktQ);
                        break;

                    case BeagleApi.BG_USB_PID_IN:
                        pktQ.savePacket();
                        state = CollapseState.IN;
                        break;

                    case BeagleApi.BG_USB_PID_PING:
                        pktQ.savePacket();
                        state = CollapseState.PING;
                        break;

                    case BeagleApi.BG_USB_PID_SPLIT:
                        pktQ.savePacket();
                        state = CollapseState.SPLIT;
                        break;

                    default:
                        usbPrintSummaryPacket(ref packetnum, collapseInfo,
                                              ref signalErrors);

                        if (curPacket.length > 0 || curPacket.events != 0 ||
                            (curPacket.status != 0 &&
                             curPacket.status != BeagleApi.BG_READ_TIMEOUT))
                        {
                            usbPrintPacket(packetnum, curPacket, null);
                            packetnum++;
                        }
                        break;
                    }
                    break;

                // Collapsing IN+ACK or IN+NAK.  Otherwise, output any
                // saved packets and rerun the collapsing state machine
                // on the current packet.
                case CollapseState.IN:
                    state = CollapseState.IDLE;
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_ACK:
                        collapse(PacketGroup.IN_ACK, collapseInfo, pktQ);
                        break;

                    case BeagleApi.BG_USB_PID_NAK:
                        collapse(PacketGroup.IN_NAK, collapseInfo, pktQ);
                        break;

                    default:
                        reRun = true;
                        break;
                    }
                    break;

                // Collapsing PING+NAK
                case CollapseState.PING:
                    state = CollapseState.IDLE;
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_NAK:
                        collapse(PacketGroup.PING_NAK, collapseInfo, pktQ);
                        break;

                    default:
                        reRun = true;
                        break;
                    }
                    break;

                // Expecting an IN, OUT, or SETUP
                case CollapseState.SPLIT:
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_IN:
                        pktQ.savePacket();
                        state = CollapseState.SPLIT_IN;
                        break;

                    case BeagleApi.BG_USB_PID_OUT:
                        pktQ.savePacket();
                        state = CollapseState.SPLIT_OUT;
                        break;

                    case BeagleApi.BG_USB_PID_SETUP:
                        pktQ.savePacket();
                        state = CollapseState.SPLIT_SETUP;
                        break;

                    default:
                        state = CollapseState.IDLE;
                        reRun = true;
                        break;
                    }
                    break;

                // Collapsing SPLIT+IN+NYET, SPLIT+IN+NAK, SPLIT+IN+ACK
                case CollapseState.SPLIT_IN:
                    state = CollapseState.IDLE;
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_NYET:
                        collapse(PacketGroup.SPLIT_IN_NYET, collapseInfo,
                                 pktQ);
                        break;

                    case BeagleApi.BG_USB_PID_NAK:
                        collapse(PacketGroup.SPLIT_IN_NAK, collapseInfo,
                                 pktQ);
                        break;

                    case BeagleApi.BG_USB_PID_ACK:
                        collapse(PacketGroup.SPLIT_IN_ACK, collapseInfo,
                                 pktQ);
                        break;

                    default:
                        reRun = true;
                        break;
                    }
                    break;

                // Collapsing SPLIT+OUT+NYET
                case CollapseState.SPLIT_OUT:
                    state = CollapseState.IDLE;
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_NYET:
                        collapse(PacketGroup.SPLIT_OUT_NYET, collapseInfo,
                                 pktQ);
                        break;

                    default:
                        reRun = true;
                        break;
                    }
                    break;

                // Collapsing SPLIT+SETUP+NYET
                case CollapseState.SPLIT_SETUP:
                    state = CollapseState.IDLE;
                    switch (pid)
                    {
                    case BeagleApi.BG_USB_PID_NYET:
                        collapse(PacketGroup.SPLIT_SETUP_NYET, collapseInfo,
                                 pktQ);
                        break;

                    default:
                        reRun = true;
                        break;
                    }
                    break;
                }

                if (reRun == false)
                {
                    break;
                }

                // The state machine is about to be re-run.  This
                // means that a complete packet sequence wasn't collapsed
                // and there are packets in the queue that need to be
                // output before we can process the current packet.
                outputSaved(ref packetnum, ref signalErrors,
                            collapseInfo, pktQ);
            }
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
Example #17
0
    public static void spidump(int max_bytes, int num_packets)
    {
        // Get the size of timing information for each transaction of size
        // max_bytes

        int timing_size = BeagleApi.bg_bit_timing_size(
            BeagleProtocol.BG_PROTOCOL_SPI, max_bytes);

        byte[] data_mosi = new byte[max_bytes];
        byte[] data_miso = new byte[max_bytes];
        uint[] timing    = new uint[timing_size];

        // Get the current sampling rate
        int samplerate_khz = BeagleApi.bg_samplerate(beagle, 0);

        int i;

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_SPI) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable SPI capture; exiting...\n");
            Environment.Exit(1);
        }

        Console.Write("index,time(ns),SPI,status,mosi0/miso0 ... " +
                      "mosiN/misoN\n");
        Console.Out.Flush();

        // Capture and print information for each transaction
        for (i = 0; i < num_packets || num_packets == 0; ++i)
        {
            uint  status          = 0;
            ulong time_sop        = 0;
            ulong time_sop_ns     = 0;
            ulong time_duration   = 0;
            uint  time_dataoffset = 0;
            int   n = 0;

            // Read transaction with bit timing data
            int count = BeagleApi.bg_spi_read_bit_timing(beagle, ref status,
                                                         ref time_sop, ref time_duration,
                                                         ref time_dataoffset,
                                                         max_bytes, data_mosi,
                                                         max_bytes, data_miso,
                                                         timing_size, timing);

            // Translate timestamp to ns
            time_sop_ns = TIMESTAMP_TO_NS(time_sop, samplerate_khz);

            Console.Write("{0:d},{1:d},SPI,(", i, time_sop_ns);

            if (count < 0)
            {
                Console.Write("error={0:d},", count);
            }

            print_general_status(status);
            print_spi_status(status);
            Console.Write(")");

            // Check for errors
            if (count <= 0)
            {
                Console.Write("\n");
                Console.Out.Flush();

                if (count < 0)
                {
                    break;
                }

                // If zero data captured, continue
                continue;
            }

            // Display the data
            for (n = 0; n < count; ++n)
            {
                if (n != 0)
                {
                    Console.Write(", ");
                }
                if ((n & 0xf) == 0)
                {
                    Console.Write("\n    ");
                }

                Console.Write("{0:x2}/{1:x2}", data_mosi[n], data_miso[n]);
            }

            Console.Write("\n");
            Console.Out.Flush();
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
Example #18
0
    static void usbDump(int numPackets, int timeoutMS)
    {
        long start, elapsedTime;

        // Set up variables
        byte[] packet    = new byte[1024];
        int    packetnum = 0;

        samplerateKhz = BeagleApi.bg_samplerate(beagle, 0);

        // Configure Beagle 480 for delayed-download capture
        BeagleApi.bg_usb480_capture_configure(beagle,
                                              BeagleUsb480CaptureMode.BG_USB480_CAPTURE_DELAYED_DOWNLOAD,
                                              BeagleUsb2TargetSpeed.BG_USB2_AUTO_SPEED_DETECT);

        // Enable the hardware filtering.  This will filter out packets with
        // the same device address as the Beagle analyzer and also filter
        // the PID packet groups listed below.
        BeagleApi.bg_usb480_hw_filter_config(beagle,
                                             BeagleApi.BG_USB2_HW_FILTER_SELF |
                                             BeagleApi.BG_USB2_HW_FILTER_PID_SOF |
                                             BeagleApi.BG_USB2_HW_FILTER_PID_IN |
                                             BeagleApi.BG_USB2_HW_FILTER_PID_PING |
                                             BeagleApi.BG_USB2_HW_FILTER_PID_PRE |
                                             BeagleApi.BG_USB2_HW_FILTER_PID_SPLIT);

        // Start the capture portion of the delayed-download capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_USB) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable USB capture; exiting...\n");
            Environment.Exit(1);
        }

        // Wait until timeout period elapses or the hardware buffer on
        // the Beagle USB 480 fills
        Console.Write("Hardware buffer usage:\n");
        start = timeMicroseconds();

        while (true)
        {
            uint bufferSize  = 0;
            uint bufferUsage = 0;
            byte bufferFull  = 0;

            // Poll the hardware buffer status
            BeagleApi.bg_usb480_hw_buffer_stats(beagle, ref bufferSize,
                                                ref bufferUsage,
                                                ref bufferFull);

            // Print out the progress
            elapsedTime = (timeMicroseconds() - start) / 1000;

            printProgress(bufferUsage / (bufferSize / 100),
                          ((double)elapsedTime) / 1000,
                          bufferUsage, bufferSize);

            // If timed out or buffer is full, exit loop
            if (bufferFull != 0 ||
                (timeoutMS != 0 && elapsedTime > timeoutMS))
            {
                break;
            }

            // Sleep for 150 milliseconds
            BeagleApi.bg_sleep_ms(150);
        }

        // Start the download portion of the delayed-download capture
        //
        // Output the header...
        Console.Write("\nindex,time(ns),USB,status,pid,data0 ... dataN(*)\n");
        Console.Out.Flush();

        // ...then start decoding packets
        while (packetnum < numPackets || (numPackets == 0))
        {
            uint  status         = 0;
            uint  events         = 0;
            ulong timeSop        = 0;
            ulong timeSopNS      = 0;
            ulong timeDuration   = 0;
            uint  timeDataOffset = 0;

            // Calling bg_usb480_read will automatically stop the
            // capture portion of the delayed-download capture and
            // will begin downloading the capture results.
            int length = BeagleApi.bg_usb480_read(
                beagle, ref status, ref events,
                ref timeSop, ref timeDuration,
                ref timeDataOffset, 1024, packet);

            timeSopNS = TIMESTAMP_TO_NS(timeSop, samplerateKhz);

            // Check for invalid packet or Beagle error
            if (length < 0)
            {
                String errorStatus = "";
                errorStatus += String.Format("error={0:d}", length);
                usbPrintPacket(packetnum, timeSopNS, status, events,
                               errorStatus, null);
                break;
            }

            // Output the current transaction
            if (length > 0 || events != 0 ||
                (status != 0 && status != BeagleApi.BG_READ_TIMEOUT))
            {
                String packetData = usbPrintDataPacket(ref packet,
                                                       length);
                usbPrintPacket(packetnum, timeSopNS, status,
                               events, null, packetData);
                ++packetnum;
            }

            // Exit if observe end of capture
            if ((status & BeagleApi.BG_READ_USB_END_OF_CAPTURE) != 0)
            {
                break;
            }
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
Example #19
0
 public void reset_beagle()
 {
     BeagleApi.bg_disable(handle);
     System.Threading.Thread.Sleep(250);
     setup_i2c();
 }
Example #20
0
    static void usbDump(int numPackets)
    {
        // Set up variables
        byte[] packet = new byte[1024];

        int timingSize =
            BeagleApi.bg_bit_timing_size(BeagleProtocol.BG_PROTOCOL_USB, 1024);

        uint[] timing = new uint[timingSize];

        byte[] savedIn       = new byte[64];
        uint[] savedInTiming = new uint[8 * 64];
        ulong  savedInSop    = 0;
        int    savedInLength = 0;
        uint   savedInStatus = 0;
        uint   savedInEvents = 0;

        ulong countSop   = 0;
        int   sofCount   = 0;
        int   preCount   = 0;
        int   inAckCount = 0;
        int   inNakCount = 0;

        byte pid        = 0;
        int  syncErrors = 0;
        int  packetnum  = 0;

        samplerateKhz = BeagleApi.bg_samplerate(beagle, 0);

        int idleSamples = IDLE_THRESHOLD * samplerateKhz;

        // Open the connection to the Beagle.  Default to port 0.
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_USB) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable USB capture; exiting...\n");
            Environment.Exit(1);
        }

        // Output the header...
        Console.Write("index,time(ns),USB,status,pid,data0 ... dataN(*)\n");
        Console.Out.Flush();

        // ...then start decoding packets
        while (packetnum < numPackets || (numPackets == 0))
        {
            uint  status         = 0;
            uint  events         = 0;
            ulong timeSop        = 0;
            ulong timeSopNS      = 0;
            ulong timeDuration   = 0;
            uint  timeDataOffset = 0;

            int length = BeagleApi.bg_usb12_read_bit_timing(
                beagle, ref status, ref events, ref timeSop,
                ref timeDuration, ref timeDataOffset,
                1024, packet, timingSize, timing);

            timeSopNS = TIMESTAMP_TO_NS(timeSop, samplerateKhz);

            // Check for invalid packet or Beagle error
            if (length < 0)
            {
                String errorStatus = "";
                errorStatus += String.Format("error={0:d}", length);
                usbPrintPacket(packetnum, timeSopNS, status, events,
                               errorStatus, null);
                break;
            }

            // Check for USB error
            if (status == BeagleApi.BG_READ_USB_ERR_BAD_SYNC)
            {
                ++syncErrors;
            }

            if (length > 0)
            {
                pid = packet[0];
            }
            else
            {
                pid = 0;
            }

            // Check the PID and collapse appropriately:
            // SOF* PRE* (IN (ACK|NAK))*
            // If we have saved summary information, and we have
            // hit an error, received a non-summary packet, or
            // have exceeded the idle time, then dump out the
            // summary information before continuing
            if (status != BeagleApi.BG_READ_OK || usbTrigger(pid) ||
                ((int)(timeSop - countSop) >= idleSamples))
            {
                int offset =
                    usbPrintSummaryPacket(packetnum, countSop,
                                          sofCount, preCount, inAckCount,
                                          inNakCount, syncErrors);

                sofCount   = 0;
                preCount   = 0;
                inAckCount = 0;
                inNakCount = 0;
                syncErrors = 0;
                countSop   = timeSop;

                // Adjust the packet index if any events were printed by
                // usbPrintSummaryPacket.
                packetnum += offset;
            }

            // Now handle the current packet based on its packet ID
            switch (pid)
            {
            case BeagleApi.BG_USB_PID_SOF:
                // Increment the SOF counter
                ++sofCount;
                break;

            case BeagleApi.BG_USB_PID_PRE:
                // Increment the PRE counter
                ++preCount;
                break;

            case BeagleApi.BG_USB_PID_IN:
                // If the transaction is an IN, don't display it yet and
                // save the transaction.
                // If the following transaction is an ACK or NAK,
                // increment the appropriate IN/ACK or IN/NAK counter.
                // If the next transaction is not an ACK or NAK,
                // display the saved IN transaction .
                System.Array.Copy(packet, 0, savedIn, 0, length);
                System.Array.Copy(timing, 0, savedInTiming, 0, length * 8);

                savedInSop    = timeSop;
                savedInLength = length;
                savedInStatus = status;
                savedInEvents = events;
                break;

            case BeagleApi.BG_USB_PID_NAK:
                goto case BeagleApi.BG_USB_PID_ACK;

            case BeagleApi.BG_USB_PID_ACK:
                // If the last transaction was IN, increment the appropriate
                // counter and don't display the transaction.
                if (savedInLength > 0)
                {
                    savedInLength = 0;

                    if (pid == BeagleApi.BG_USB_PID_ACK)
                    {
                        ++inAckCount;
                    }
                    else
                    {
                        ++inNakCount;
                    }

                    break;
                }
                goto default;

            default:
                // If the last transaction was IN, output it
                if (savedInLength > 0)
                {
                    ulong saved_in_sop_ns =
                        TIMESTAMP_TO_NS(savedInSop, samplerateKhz);

                    String packetData = usbPrintDataPacket
                                            (ref savedIn,
                                            savedInLength);
                    usbPrintPacket(packetnum, saved_in_sop_ns, savedInStatus,
                                   savedInEvents, null, packetData);
                    ++packetnum;

                    savedInLength = 0;
                }

                // Output the current transaction
                if (length > 0 || events != 0 ||
                    (status != 0 && status != BeagleApi.BG_READ_TIMEOUT))
                {
                    String packetData = usbPrintDataPacket(ref packet,
                                                           length);
                    usbPrintPacket(packetnum, timeSopNS, status,
                                   events, null, packetData);
                    ++packetnum;
                }
                countSop = timeSop + timeDuration;
                break;
            }
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
Example #21
0
    public static void mdiodump(int num_packets)
    {
        // Get the size of the timing information for a transaction of
        // max_bytes length
        int timing_size =
            BeagleApi.bg_bit_timing_size(BeagleProtocol.BG_PROTOCOL_MDIO, 0);

        uint[] timing = new uint[timing_size];

        // Get the current sampling rate
        int samplerate_khz = BeagleApi.bg_samplerate(beagle, 0);

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_MDIO) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable MDIO capture; " +
                          "exiting...\n");
            Environment.Exit(1);
        }

        Console.Write("index,time(ns),MDIO,status,<clause:opcode>," +
                      "<addr1>,<addr2>,data\n");
        Console.Out.Flush();

        // Capture and print each transaction
        int i;

        for (i = 0; i < num_packets || num_packets == 0; ++i)
        {
            uint  packet = 0;
            uint  status = 0;
            ulong time_sop = 0, time_sop_ns = 0;
            ulong time_duration   = 0;
            uint  time_dataoffset = 0;

            // Read transaction with bit timing data
            int count = BeagleApi.bg_mdio_read_bit_timing(
                beagle, ref status, ref time_sop,
                ref time_duration, ref time_dataoffset,
                ref packet, timing_size, timing);

            // Translate timestamp to ns
            time_sop_ns = TIMESTAMP_TO_NS(time_sop, samplerate_khz);

            // Check for errors
            if (count < 0)
            {
                Console.Write("{0,4:d},{1,13:d},MDIO,( error={2:d},",
                              i, time_sop_ns, count);
                print_general_status(status);
                print_mdio_status(status);
                Console.Write(")\n");
                Console.Out.Flush();
                continue;
            }

            // Parse the MDIO frame
            byte   clause = 0;
            byte   opcode = 0;
            byte   addr1  = 0;
            byte   addr2  = 0;
            ushort data   = 0;
            int    ret    = BeagleApi.bg_mdio_parse(packet, ref clause,
                                                    ref opcode, ref addr1, ref addr2, ref data);

            Console.Write("{0:d},{1:d},MDIO,(", i, time_sop_ns);
            print_general_status(status);
            if ((status & BeagleApi.BG_READ_TIMEOUT) == 0)
            {
                print_mdio_status((uint)ret);
            }
            Console.Write(")");

            // If zero data captured, continue
            if (count == 0)
            {
                Console.Write("\n");
                Console.Out.Flush();
                continue;
            }

            // Print the clause and opcode
            Console.Write(",");
            if ((status & BeagleApi.BG_READ_ERR_MIDDLE_OF_PACKET) == 0)
            {
                if (clause == (byte)BeagleMdioClause.BG_MDIO_CLAUSE_22)
                {
                    Console.Write("<22:");
                    switch (opcode)
                    {
                    case BeagleApi.BG_MDIO_OPCODE22_WRITE:
                        Console.Write("W");
                        break;

                    case BeagleApi.BG_MDIO_OPCODE22_READ:
                        Console.Write("R");
                        break;

                    case BeagleApi.BG_MDIO_OPCODE22_ERROR:
                        Console.Write("?");
                        break;
                    }
                }
                else if (clause == (byte)BeagleMdioClause.BG_MDIO_CLAUSE_45)
                {
                    Console.Write("<45:");
                    switch (opcode)
                    {
                    case BeagleApi.BG_MDIO_OPCODE45_ADDR:
                        Console.Write("A");
                        break;

                    case BeagleApi.BG_MDIO_OPCODE45_WRITE:
                        Console.Write("W");
                        break;

                    case BeagleApi.BG_MDIO_OPCODE45_READ_POSTINC:
                        Console.Write("RI");
                        break;

                    case BeagleApi.BG_MDIO_OPCODE45_READ:
                        Console.Write("R");
                        break;
                    }
                }
                else
                {
                    Console.Write("<?:?");
                }

                // Recall that for Clause 22:
                //     PHY  Addr = addr1, Reg Addr = addr2
                // and for Clause 45:
                //     Port Addr = addr1, Dev Addr = addr2
                Console.Write(">,<{0:X2}>,<{1:X2}>,{2:X4}\n",
                              addr1, addr2, data);
            }
            Console.Out.Flush();
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
    static void usbDump(int numPackets)
    {
        // Setup variables
        byte[] packet      = new byte[1036];
        byte[] packetKBits = new byte[130];

        int packetnum = 0;
        int tries     = 10;

        BeagleUsb5000CaptureStatus captureStatus =
            BeagleUsb5000CaptureStatus.BG_USB5000_CAPTURE_STATUS_INACTIVE;
        uint pretrigAmt   = 0;
        uint pretrigTotal = 0;
        uint capAmt       = 0;
        uint capTotal     = 0;

        // Disable VBUS to device
        BeagleApi.bg_usb5000_target_power(
            beagle, BeagleUsbTargetPower.BG_USB5000_TARGET_POWER_OFF);

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_USB) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable USB capture; exiting...\n");
            Environment.Exit(1);
        }

        // Disable VBUS to device
        BeagleApi.bg_usb5000_target_power(
            beagle, BeagleUsbTargetPower.BG_USB5000_TARGET_POWER_HOST_SUPPLIED);

        // Wait for the analyzer to trigger for up to 10 seconds...
        while (tries != 0)
        {
            if (BeagleApi.bg_usb5000_usb3_capture_status(
                    beagle, 1000, ref captureStatus,
                    ref pretrigAmt, ref pretrigTotal,
                    ref capAmt, ref capTotal) !=
                (int)BeagleStatus.BG_OK)
            {
                Console.Write(
                    "error: could not query capture status; exiting...\n");
                Environment.Exit(1);
            }

            if (captureStatus <= BeagleUsb5000CaptureStatus.
                BG_USB5000_CAPTURE_STATUS_PRE_TRIGGER)
            {
                Console.Write("waiting for trigger...\n");
            }
            else
            {
                break;
            }

            tries--;
        }

        if (tries == 0)
        {
            Console.Write("did not trigger, make sure a host and a device " +
                          "is connected to the analyzer.\n");
            Environment.Exit(1);
        }

        Console.Write(
            "index,time(ns),source,event,status,data0 ... dataN(*)\n");
        Console.Out.Flush();

        // ...then start decoding packets
        while (packetnum < numPackets || (numPackets == 0))
        {
            uint  status               = 0;
            uint  events               = 0;
            ulong timeSop              = 0;
            ulong timeDuration         = 0;
            uint  timeDataOffset       = 0;
            BeagleUsb5000Source source =
                BeagleUsb5000Source.BG_USB5000_SOURCE_ASYNC;

            int length = BeagleApi.bg_usb5000_read(
                beagle,
                ref status, ref events, ref timeSop, ref timeDuration,
                ref timeDataOffset, ref source,
                1036, packet, 130, packetKBits);

            // Make sure capture is triggered.
            if (length == (int)BeagleStatus.BG_CAPTURE_NOT_TRIGGERED)
            {
                continue;
            }

            // Check for invalid packet or Beagle error
            if (length < 0)
            {
                Console.Write("error={0:d}\n", length);
                break;
            }

            // Exit if observed end of capture
            if (status == BeagleApi.BG_READ_USB_END_OF_CAPTURE)
            {
                Console.Write("\n");
                Console.Write("End of capture\n");
                break;
            }

            // Grab the next packet on a timeout.
            if (length == 0 &&
                status == BeagleApi.BG_READ_TIMEOUT &&
                events == 0)
            {
                continue;
            }

            // Print the packet details
            Console.Write("{0},", packetnum);
            Console.Write("{0},", timestampToNS(timeSop, samplerateKHz));
            printSource(source);
            Console.Write(",");
            printEvents(source, events);
            Console.Write(",");
            printStatus(source, status);
            Console.Write(",");
            printPacket(source, packet, packetKBits, length);
            Console.Write("\n");

            packetnum++;
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }
    /*=====================================================================
     | COMPLEX MATCH CONFIGURATION
     | ====================================================================*/
    static void usbConfigComplexMatch()
    {
        int features = BeagleApi.bg_usb5000_features(beagle);

        if (features < 0)
        {
            Console.Write("error: could not retrieve features\n");
            Environment.Exit(1);
        }

        bool adv = (features & BeagleApi.BG_USB5000_FEATURE_CMP_TRIG) != 0;

        // Setup the first state.
        // Do a capture trigger on seeing a SET ADDRESS setup packet.

        // Match on a SET ADDRESS request.  We also construct a data
        // valid mask which masks out the device address from the
        // request as that is variable.
        byte[] setup_data = new byte[] { 0x00, 0x05, 0x00, 0x00,
                                         0x00, 0x00, 0x00, 0x00 };
        byte[] setup_data_valid = new byte[] { 0xff, 0xff, 0x00, 0xff,
                                               0xff, 0xff, 0xff, 0xff };

        // Configure the data match properties.  Since SET ADDRESS only comes
        // on device 0 and ep 0, we can match only on those parameters.
        BeagleApi.BeagleUsb5000DataProperties prop =
            new BeagleApi.BeagleUsb5000DataProperties();
        prop.source_match_type =
            BeagleUsb5000MatchType.BG_USB5000_MATCH_TYPE_EQUAL;
        prop.source_match_val =
            BeagleUsb5000Source.BG_USB5000_SOURCE_TX;
        prop.ep_match_type =
            BeagleUsb5000MatchType.BG_USB5000_MATCH_TYPE_EQUAL;
        prop.ep_match_val   = 0;
        prop.dev_match_type =
            BeagleUsb5000MatchType.BG_USB5000_MATCH_TYPE_EQUAL;
        prop.dev_match_val        = 0;
        prop.stream_id_match_type =
            BeagleUsb5000MatchType.BG_USB5000_MATCH_TYPE_DISABLED;
        prop.data_len_match_type =
            BeagleUsb5000MatchType.BG_USB5000_MATCH_TYPE_EQUAL;
        prop.data_len_match_val = 8;

        // Setup the struct for the Data Match Unit
        BeagleApi.BeagleUsb5000DataMatchUnit match0 =
            new BeagleApi.BeagleUsb5000DataMatchUnit();
        match0.packet_type =
            BeagleUsb5000PacketType.BG_USB5000_MATCH_PACKET_SHP_SDP;
        match0.match_other_packets = 0;   // Only match a qualified SDP.
        match0.data       = setup_data;
        match0.data_not   = 0;            // Match this data only.
        match0.data_valid = setup_data_valid;
        match0.err_match  =
            BeagleUsb5000ErrorType.BG_USB5000_MATCH_CRC_BOTH_VALID;
        match0.data_properties_valid = 1;
        match0.data_properties       = prop;
        match0.repeat_count          = 0; // Match just once.
        match0.sticky_action         = 0; // Match just once.
        match0.action_mask           =
            BeagleApi.BG_USB5000_COMPLEX_MATCH_ACTION_TRIGGER;

        if (adv)
        {
            // Configure state0's data match to goto state1
            // on it's match of the SET ADDRESS.
            match0.goto_selector = 0; // Use the first goto selector.
            match0.action_mask  |= BeagleApi.BG_USB5000_COMPLEX_MATCH_ACTION_GOTO;
        }

        // Configure the State 0 struct.
        BeagleApi.BeagleUsb5000ComplexMatchState state0 =
            new BeagleApi.BeagleUsb5000ComplexMatchState();
        state0.tx_data_0_valid = 1;
        state0.tx_data_0       = match0;
        state0.tx_data_1_valid = 0;
        state0.tx_data_2_valid = 0;
        state0.rx_data_0_valid = 0;
        state0.rx_data_1_valid = 0;
        state0.rx_data_2_valid = 0;
        state0.timer_valid     = 0;
        state0.async_valid     = 0;
        // For units licensed for advanced complex trigger, go to state 1.
        state0.goto_0 = 1;

        // Setup state 2 to filter out all link layer packets on both streams.
        BeagleApi.BeagleUsb5000DataMatchUnit match_slc =
            new BeagleApi.BeagleUsb5000DataMatchUnit();

        match_slc.packet_type =
            BeagleUsb5000PacketType.BG_USB5000_MATCH_PACKET_SLC;
        match_slc.match_other_packets = 0;   // Only match a SLC packet.
        match_slc.data       = null;         // Match all SLCs.
        match_slc.data_not   = 0;
        match_slc.data_valid = null;
        match_slc.err_match  =
            BeagleUsb5000ErrorType.BG_USB5000_MATCH_CRC_BOTH_VALID;
        match_slc.data_properties_valid = 0;
        match_slc.repeat_count          = 0;
        match_slc.sticky_action         = 0;
        match_slc.action_mask           =
            BeagleApi.BG_USB5000_COMPLEX_MATCH_ACTION_FILTER;

        BeagleApi.BeagleUsb5000ComplexMatchState state1 =
            new BeagleApi.BeagleUsb5000ComplexMatchState();
        state1.tx_data_0_valid = 1;
        state1.tx_data_0       = match_slc;
        state1.tx_data_1_valid = 0;
        state1.tx_data_2_valid = 0;
        state1.rx_data_0_valid = 1;
        state1.rx_data_0       = match_slc;
        state1.rx_data_1_valid = 0;
        state1.rx_data_2_valid = 0;
        state1.timer_valid     = 0;
        state1.async_valid     = 0;

        int ret = 0;

        if (adv)
        {
            // Passing null BeagleUsb5000ComplexMatchState objects
            // into bg_usb5000_usb3_complex_match_config is not
            // allowed so unconfigured match state objects are
            // used instead.
            BeagleApi.BeagleUsb5000ComplexMatchState empty = new
                                                             BeagleApi.BeagleUsb5000ComplexMatchState();

            ret = BeagleApi.bg_usb5000_usb3_complex_match_config(
                beagle,
                0, // Validate and program it into the Beagle 5000.
                0, // Not using extout.
                state0, state1, empty, empty, empty, empty, empty, empty);
        }
        else
        {
            ret = BeagleApi.bg_usb5000_usb3_complex_match_config_single(
                beagle,
                0, // Validate and program it into the Beagle 5000.
                0, // Not using extout.
                state0);
        }


        if (ret != (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not configure complex match\n");
            Environment.Exit(1);
        }

        if (BeagleApi.bg_usb5000_usb3_complex_match_enable(beagle) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable complex match\n");
            Environment.Exit(1);
        }
    }
Example #24
0
        public List <string> snoop_i2c(int num_packets)
        {
            // Capture and print each transaction
            List <ushort> full_data = new List <ushort>();           //keep adding bytes to this as it goes
            List <string> lines     = new List <string>();

            for (int i = 0; i < num_packets || num_packets == 0; ++i)
            {
                uint  status = 0;
                ulong time_sop = 0, time_sop_ns = 0;
                ulong time_duration   = 0;
                uint  time_dataoffset = 0;
                int   count           = 0;

                // Read transaction with bit timing data
                try
                {
                    count = BeagleApi.bg_i2c_read(handle, ref status, ref time_sop, ref time_duration, ref time_dataoffset, max_bytes, data_in);
                    //count = BeagleApi.bg_i2c_read_bit_timing(handle, ref status, ref time_sop, ref time_duration, ref time_dataoffset, max_bytes, data_in, timing_size, timing);
                }
                catch
                {
                    Console.WriteLine("Error in I2C bit read, skipping");
                    continue;
                }
                string output        = "";// output_parse(data_in);			//for building console output
                string status_string = print_general_status(status);
                try
                {
                    buffer.AddRange(data_in); //add to my own buffer
                }
                catch (System.ArgumentOutOfRangeException)
                {
                    Console.WriteLine("Skipping measurement..");
                }
                ///lines.Add(status_string + " - " + output + " - " + "Iteration: " + i); //added this so see in gui

                if (status_string.Contains("TIMEOUT"))
                {
                    continue;                     //skip if no activity on bus
                }
                // Translate timestamp to ns
                time_sop_ns = TIMESTAMP_TO_NS(time_sop, sample_rate);

                ///Console.Write("{0:d},{1:d}", i, time_sop_ns);
                ///Console.Write(",I2C,(");

                if (count < 0)                 //error condition
                {
                    Console.Write("error={0:d},", count);
                }
                ///else
                ///	Console.Write("Read " + count + " bits. ");

                //print_general_status(status); //below reference funct -> moved up
                ///Console.Write(status_string);
                ///print_i2c_status(status); //below reference funct
                ///Console.Write(")");

                // Check for errors
                if (count <= 0)
                {
                    Console.Write("\n");
                    Console.Out.Flush();                     //what does this do?

                    if (count < 0)
                    {
                        break;
                    }

                    // If zero data captured, continue
                    continue;
                }

                // Print the address and read/write
                ///Console.Write(",");
                int offset = 0;

                /*
                 *              if ((status & BeagleApi.BG_READ_ERR_MIDDLE_OF_PACKET) == 0)
                 *              {
                 *                      // Display the start condition
                 *                      Console.Write("[S] ");
                 *
                 *                      if (count >= 1)
                 *                      {
                 *                              // Determine if byte was NACKed
                 *                              int nack = (data_in[0] & BeagleApi.BG_I2C_MONITOR_NACK);
                 *
                 *                              // Determine if this is a 10-bit address
                 *                              if (count == 1 || (data_in[0] & 0xf9) != 0xf0 ||
                 *                                      (nack != 0))
                 *                              {
                 *                                      // Display 7-bit address
                 *                                      Console.Write("<{0:x2}:{1:s}>{2:s} ",
                 *                                                 (data_in[0] & 0xff) >> 1,
                 *                                                 ((data_in[0] & 0x01) != 0) ? 'r' : 'w',
                 *                                                 (nack != 0) ? "*" : "");
                 *                                      offset = 1;
                 *                              }
                 *                              else
                 *                              {
                 *                                      // Display 10-bit address
                 *                                      Console.Write("<{0:x3}:{1:s}>{2:s} ", ((data_in[0] << 7) & 0x300) | (data_in[1] & 0xff), ((data_in[0] & 0x01) != 0) ? 'r' : 'w',
                 *                                                 (nack != 0) ? "*" : "");
                 *                                      offset = 2;
                 *                              }
                 *                      }
                 *              }
                 *///take out prints

                // Display rest of transaction - data
                count = count - offset;

                /*
                 *              for (int n = 0; n < count; ++n)
                 *              {
                 *                      // Determine if byte was NACKed
                 *                      int nack = (data_in[offset] & BeagleApi.BG_I2C_MONITOR_NACK);
                 *
                 *                      Console.Write("{0:x2}{1:s} ",
                 *                                      data_in[offset] & 0xff, (nack != 0) ? "*" : "");
                 ++offset;
                 *              }
                 */
            }

            // Stop the capture
            //BeagleApi.bg_disable(handle);
            return(lines);
        }
    /*=====================================================================
     | MAIN PROGRAM
     | ====================================================================*/
    public static void Main(String[] args)
    {
        int  port    = 0;      // open port 0 by default
        uint timeout = 100;    // in milliseconds
        uint latency = 200;    // in milliseconds
        int  num     = 0;

        if (args.Length < 1)
        {
            printUsage();
            Environment.Exit(1);
        }

        num = Convert.ToInt32(args[0]);

        // Open the device
        beagle = BeagleApi.bg_open(port);
        if (beagle <= 0)
        {
            Console.Write("Unable to open Beagle device on port {0:d}\n", port);
            Console.Write("Error code = {0:d}\n", beagle);
            Environment.Exit(1);
        }
        Console.Write("Opened Beagle device on port {0:d}\n", port);

        // Query the samplerate since Beagle USB has a fixed sampling rate
        samplerateKHz = BeagleApi.bg_samplerate(beagle, samplerateKHz);
        if (samplerateKHz < 0)
        {
            Console.Write("error: {0:s}\n",
                          BeagleApi.bg_status_string(samplerateKHz));
            Environment.Exit(1);
        }
        Console.Write("Sampling rate set to {0:d} KHz.\n", samplerateKHz);

        // Set the idle timeout.
        // The Beagle read functions will return in the specified time
        // if there is no data available on the bus.
        BeagleApi.bg_timeout(beagle, timeout);
        Console.Write("Idle timeout set to {0:d} ms.\n", timeout);

        // Set the latency.
        // The latency parameter allows the programmer to balance the
        // tradeoff between host side buffering and the latency to
        // receive a packet when calling one of the Beagle read
        // functions.
        BeagleApi.bg_latency(beagle, latency);
        Console.Write("Latency set to {0:d} ms.\n", latency);

        Console.Write("Host interface is {0:s}.\n",
                      ((BeagleApi.bg_host_ifce_speed(beagle)) != 0) ?
                      "high speed" : "full speed");

        Console.Write("\n");
        Console.Out.Flush();

        // Configure the capture buffer
        usbConfigBuffer();

        // Configure the complex match
        usbConfigComplexMatch();

        usbDump(num);

        // Close the device
        BeagleApi.bg_close(beagle);

        return;
    }
Example #26
0
    public static void i2cdump(int max_bytes, int num_packets)
    {
        // Get the size of the timing information for a transaction of
        // max_bytes length
        int timing_size = BeagleApi.bg_bit_timing_size(
            BeagleProtocol.BG_PROTOCOL_I2C, max_bytes);

        ushort[] data_in = new ushort[max_bytes];
        uint[]   timing  = new uint[timing_size];

        // Get the current sampling rate
        int samplerate_khz = BeagleApi.bg_samplerate(beagle, 0);

        int i;

        // Start the capture
        if (BeagleApi.bg_enable(beagle, BeagleProtocol.BG_PROTOCOL_I2C) !=
            (int)BeagleStatus.BG_OK)
        {
            Console.Write("error: could not enable I2C capture; exiting...\n");
            Environment.Exit(1);
        }

        Console.Write("index,time(ns),I2C,status,<addr:r/w>" +
                      "(*),data0 ... dataN(*)\n");
        Console.Out.Flush();

        // Capture and print each transaction
        for (i = 0; i < num_packets || num_packets == 0; ++i)
        {
            uint  status = 0;
            ulong time_sop = 0, time_sop_ns = 0;
            ulong time_duration   = 0;
            uint  time_dataoffset = 0;

            // Read transaction with bit timing data
            int count = BeagleApi.bg_i2c_read_bit_timing(
                beagle, ref status, ref time_sop,
                ref time_duration, ref time_dataoffset,
                max_bytes, data_in, timing_size, timing);

            // Translate timestamp to ns
            time_sop_ns = TIMESTAMP_TO_NS(time_sop, samplerate_khz);

            Console.Write("{0:d},{1:d}", i, time_sop_ns);
            Console.Write(",I2C,(");

            if (count < 0)
            {
                Console.Write("error={0:d},", count);
            }

            print_general_status(status);
            print_i2c_status(status);
            Console.Write(")");

            // Check for errors
            if (count <= 0)
            {
                Console.Write("\n");
                Console.Out.Flush();

                if (count < 0)
                {
                    break;
                }

                // If zero data captured, continue
                continue;
            }


            // Print the address and read/write
            Console.Write(",");
            int offset = 0;
            if ((status & BeagleApi.BG_READ_ERR_MIDDLE_OF_PACKET) == 0)
            {
                // Display the start condition
                Console.Write("[S] ");

                if (count >= 1)
                {
                    // Determine if byte was NACKed
                    int nack = (data_in[0] & BeagleApi.BG_I2C_MONITOR_NACK);

                    // Determine if this is a 10-bit address
                    if (count == 1 || (data_in[0] & 0xf9) != 0xf0 ||
                        (nack != 0))
                    {
                        // Display 7-bit address
                        Console.Write("<{0:x2}:{1:s}>{2:s} ",
                                      (data_in[0] & 0xff) >> 1,
                                      ((data_in[0] & 0x01) != 0) ? 'r' : 'w',
                                      (nack != 0) ? "*" : "");
                        offset = 1;
                    }
                    else
                    {
                        // Display 10-bit address
                        Console.Write("<{0:x3}:{1:s}>{2:s} ",
                                      ((data_in[0] << 7) & 0x300) |
                                      (data_in[1] & 0xff),
                                      ((data_in[0] & 0x01) != 0) ? 'r' : 'w',
                                      (nack != 0) ? "*" : "");
                        offset = 2;
                    }
                }
            }

            // Display rest of transaction
            count = count - offset;
            for (int n = 0; n < count; ++n)
            {
                // Determine if byte was NACKed
                int nack = (data_in[offset] & BeagleApi.BG_I2C_MONITOR_NACK);

                Console.Write("{0:x2}{1:s} ",
                              data_in[offset] & 0xff, (nack != 0) ? "*" : "");
                ++offset;
            }

            // Display the stop condition
            if ((status & BeagleApi.BG_READ_I2C_NO_STOP) == 0)
            {
                Console.Write("[P]");
            }

            Console.Write("\n");
            Console.Out.Flush();
        }

        // Stop the capture
        BeagleApi.bg_disable(beagle);
    }