예제 #1
0
        public Fx2Device(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType = EDeviceType.Unknown)
        {
            if (usbDevice != null)
            {
                USBDevice = usbDevice;
            }
            if (usbProfile != null)
            {
                USBProfile = usbProfile;
            }
            DeviceType = deviceType;

            if (deviceType == EDeviceType.Unknown)
            {
                Console.WriteLine($"+ {this}");
            }

            if (deviceType == EDeviceType.DAC_SA || deviceType == EDeviceType.ADC_SA)
            {
                if (usbDevice != null)
                {
                    CyBulkEndPoint outEndpoint = usbDevice.EndPointOf(0x01) as CyBulkEndPoint;
                    CyBulkEndPoint inEndpoint  = usbDevice.EndPointOf(0x81) as CyBulkEndPoint;
                    avalonPacket = new AvalonPacket(outEndpoint, inEndpoint);
                }
                else
                {
                    avalonPacket = new MonoAvalonPacket(MonoDeviceHandle);
                }
            }
        }
 // Predicate functions for finding only devices with the specified VendorID & ProductID.
 private static bool MyVidPidPredicate(MonoUsbProfile profile)
 {
     if (profile.DeviceDescriptor.VendorID == 0x1915 && profile.DeviceDescriptor.ProductID == 0x007B)
     {
         return(true);
     }
     return(false);
 }
예제 #3
0
 // Predicate functions for finding only devices with the specified VendorID & ProductID.
 private static bool predicateWasatchVid(MonoUsbProfile profile)
 {
     if (profile.DeviceDescriptor.VendorID == 0x24aa) // && profile.DeviceDescriptor.ProductID == 0x0053
     {
         return(true);
     }
     return(false);
 }
예제 #4
0
 private bool MyVidPidPredicate(MonoUsbProfile profile)
 {
     if (profile.DeviceDescriptor.VendorID == bt_vid && profile.DeviceDescriptor.ProductID == bt_pid)
     {
         System.Console.WriteLine(String.Format("profile vid:{0} pid:{1}", profile.DeviceDescriptor.VendorID, profile.DeviceDescriptor.ProductID));
         return(true);
     }
     //return true;
     return(false);
 }
예제 #5
0
        public Fx2Device(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType = EDeviceType.Unknown)
        {
            if (usbDevice != null)
            {
                USBDevice = usbDevice;
            }
            if (usbProfile != null)
            {
                USBProfile = usbProfile;
            }
            DeviceType = deviceType;

            if (deviceType == EDeviceType.Unknown)
            {
                Console.WriteLine($"DeviceAttached: {this}");
            }
        }
        public static void ShowConfig(RichTextBox rtb)
        {
            // Assign the control transfer delegate to the callback function.
            controlTransferDelegate = ControlTransferCB;

            // Initialize the context.
            sessionHandle = new MonoUsbSessionHandle();
            if (sessionHandle.IsInvalid)
            {
                throw new Exception(String.Format("Failed intializing libusb context.\n{0}:{1}",
                                                  MonoUsbSessionHandle.LastErrorCode,
                                                  MonoUsbSessionHandle.LastErrorString));
            }

            MonoUsbProfileList  profileList    = new MonoUsbProfileList();
            MonoUsbDeviceHandle myDeviceHandle = null;

            try
            {
                // The list is initially empty.
                // Each time refresh is called the list contents are updated.
                profileList.Refresh(sessionHandle);

                // Use the GetList() method to get a generic List of MonoUsbProfiles
                // Find the first profile that matches in MyVidPidPredicate.
                MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);
                if (myProfile == null)
                {
                    rtb.AppendText("Device not connected.");
                    return;
                }

                // Open the device handle to perform I/O
                myDeviceHandle = myProfile.OpenDeviceHandle();
                if (myDeviceHandle.IsInvalid)
                {
                    throw new Exception(String.Format("Failed opening device handle.\n{0}:{1}",
                                                      MonoUsbDeviceHandle.LastErrorCode,
                                                      MonoUsbDeviceHandle.LastErrorString));
                }
                int          ret;
                MonoUsbError e;

                // Set Configuration
                e = (MonoUsbError)(ret = MonoUsbApi.SetConfiguration(myDeviceHandle, 1));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed SetConfiguration.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Claim Interface
                e = (MonoUsbError)(ret = MonoUsbApi.ClaimInterface(myDeviceHandle, 0));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed ClaimInterface.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Create a vendor specific control setup, allocate 1 byte for return control data.
                byte requestType = (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor);
                byte request     = 0x0F;
                MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(requestType, request, 0, 0, 1);

                // Transfer the control setup packet
                ret = libusb_control_transfer(myDeviceHandle, controlSetupHandle, 1000);
                if (ret > 0)
                {
                    rtb.AppendText("\nSuccess!\n");
                    byte[] ctrlDataBytes  = controlSetupHandle.ControlSetup.GetData(ret);
                    string ctrlDataString = Helper.HexString(ctrlDataBytes, String.Empty, "h ");
                    rtb.AppendText(string.Format("Return Length: {0}", ret));
                    rtb.AppendText(string.Format("DATA (hex)   : [ {0} ]\n", ctrlDataString.Trim()));
                }
                MonoUsbApi.ReleaseInterface(myDeviceHandle, 0);
            }
            finally
            {
                profileList.Close();
                if (myDeviceHandle != null)
                {
                    myDeviceHandle.Close();
                }
                sessionHandle.Close();
            }
        }
예제 #7
0
 internal MonoUsbDevice(ref MonoUsbProfile monoUSBProfile)
     : base(null, null)
 {
     mMonoUSBProfile         = monoUSBProfile;
     mCachedDeviceDescriptor = new UsbDeviceDescriptor(monoUSBProfile.DeviceDescriptor);
 }
예제 #8
0
        public BorIPDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");


            var ct = Cts.Token;

            Task.Run(() =>
            {
                TcpListener listener = BorIPCreateListener(BORIP_SERVERPORT);
                try
                {
                    listener.Start();
                    var addresses = Dns.GetHostAddresses(Dns.GetHostName())
                                    .Where(p => p.ToString().Contains('.'));
                    Console.WriteLine($"{BORIP_SERVERPORT}: {string.Join(" ", addresses)}");

                    CancellationTokenSource tcpCts = null;
                    while (!ct.IsCancellationRequested)
                    {
                        TcpClient client = listener.AcceptTcpClient();
                        Console.WriteLine($"{BORIP_SERVERPORT}: accepted");

                        if (tcpCts != null)
                        {
                            tcpCts.Cancel();
                        }

                        tcpCts    = new CancellationTokenSource();
                        var tcpCt = tcpCts.Token;
                        Task.Run(() =>
                        {
                            BorIPClient borIPClient = new BorIPClient(client);
                            borIPClients.Add(borIPClient);
                            try
                            {
                                using (NetworkStream ns = client.GetStream())
                                    using (StreamReader sr = new StreamReader(ns, Encoding.ASCII))
                                        using (StreamWriter sw = new StreamWriter(ns, Encoding.ASCII))
                                        {
                                            BorIPWriteLine(sw, "DEVICE -");

                                            while (!tcpCt.IsCancellationRequested)
                                            {
                                                string str = sr.ReadLine();
                                                if (string.IsNullOrWhiteSpace(str))
                                                {
                                                    return;                                     // keep alive
                                                }
                                                Console.WriteLine($"{BORIP_SERVERPORT}: [in] {str.Trim()}");

                                                BorIPProcessInput(borIPClient, sw, str);
                                            }
                                        }
                            }
                            catch (Exception)
                            {
                                // nothing to do
                            }
                            finally
                            {
                                borIPClients.Remove(borIPClient);
                                Console.WriteLine($"{BORIP_SERVERPORT}: closed");
                            }
                        }, tcpCt);
                    }
                }
                catch (SocketException ex) when(ex.ErrorCode == 10004)
                {
                    // nothing to do
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{BORIP_SERVERPORT}: {ex.Message}");
                }
                finally
                {
                    listener.Stop();
                    //Console.WriteLine($"{BORIP_PORTNO}: listener stopped");
                }
            }, ct);


            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0))
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData    = new byte[maxPacketSize];
                        byte[] outData   = null;
                        int outDataPos   = 0;
                        byte[] borIPData = null;
                        int borIPDataPos = 0;

                        while (!ct.IsCancellationRequested &&
                               !(borIPClients.Count == 0 && (ControlPortNo > 0 && controlClients.Count == 0)))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                if (borIPData == null)
                                {
                                    borIPData = new byte[4 + 4 * NUM_SAMPLES];
                                    borIPData[borIPDataPos++] = (byte)((RunningState == ERunningState.Start) ? 0x10 : 0x00);
                                    RunningState = ERunningState.Continued;
                                    borIPData[borIPDataPos++] = 0;
                                    borIPData[borIPDataPos++] = (byte)(sequence & 0xff);
                                    borIPData[borIPDataPos++] = (byte)((sequence >> 8) & 0xff);
                                }

                                while (outDataPos < outData.Length && borIPDataPos < borIPData.Length && inDataPos < xferLen)
                                {
                                    byte b = inData[inDataPos++];
                                    outData[outDataPos++]     = b;
                                    borIPData[borIPDataPos++] = b;
                                }

                                if (borIPDataPos == borIPData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(borIPData, borIPData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    sequence++;
                                    if (sequence == 0x10000)
                                    {
                                        sequence = 0;
                                    }

                                    borIPData    = null;
                                    borIPDataPos = 0;
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in borIPClients.ToArray())
                                    {
                                        if (client.Header == false)
                                        {
                                            string remoteAddr;
                                            try
                                            {
                                                remoteAddr = client.DestAddr;
                                            }
                                            catch
                                            {
                                                continue;
                                            }

                                            if (remoteAddrList.Contains(remoteAddr) == false)
                                            {
                                                remoteAddrList.Add(remoteAddr);
                                                udp.Send(outData, outData.Length, remoteAddr, client.DestPort);
                                            }
                                        }
                                    }

                                    remoteAddrList.Clear();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    //catch (Exception ex)
                    //{
                    //	Console.WriteLine($"BorIP: {ex.Message}");
                    //}
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }
예제 #9
0
        private void SendCommand(byte[] data, int duration)
        {
            MonoUsbProfileList  profileList    = new MonoUsbProfileList();
            MonoUsbDeviceHandle myDeviceHandle = null;

            try
            {
                // The list is initially empty.
                // Each time refresh is called the list contents are updated.
                profileList.Refresh(sessionHandle);

                // Use the GetList() method to get a generic List of MonoUsbProfiles
                // Find the first profile that matches in MyVidPidPredicate.
                MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);
                if (myProfile == null)
                {
                    Console.WriteLine("Device not connected.");
                    return;
                }
                Console.WriteLine("Device connected.");
                // Open the device handle to perform I/O
                myDeviceHandle = myProfile.OpenDeviceHandle();
                if (myDeviceHandle.IsInvalid)
                {
                    throw new Exception(String.Format("Failed opening device handle.\n{0}:{1}",
                                                      MonoUsbDeviceHandle.LastErrorCode,
                                                      MonoUsbDeviceHandle.LastErrorString));
                }
                int          ret;
                MonoUsbError e;

                // Set Configuration
                e = (MonoUsbError)(ret = MonoUsbApi.SetConfiguration(myDeviceHandle, 1));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed SetConfiguration.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Claim Interface
                e = (MonoUsbError)(ret = MonoUsbApi.ClaimInterface(myDeviceHandle, 0));
                if (ret < 0)
                {
                    throw new Exception(String.Format("Failed ClaimInterface.\n{0}:{1}", e, MonoUsbApi.StrError(e)));
                }

                // Create a vendor specific control setup, allocate 1 byte for return control data.
                byte requestType = 0x40;// (byte)(UsbCtrlFlags.Direction_In | UsbCtrlFlags.Recipient_Device | UsbCtrlFlags.RequestType_Vendor);
                byte request     = 6;

                MonoUsbControlSetupHandle controlSetupHandle = new MonoUsbControlSetupHandle(requestType, request, 0x100, 0, data, 3);

                // Transfer the control setup packet
                ret = ControlTransfer(myDeviceHandle, controlSetupHandle, 1000);
                Thread.Sleep(duration);

                object data2 = new byte[] { 0, 0, 0 };
                MonoUsbControlSetupHandle controlSetupHandle2 = new MonoUsbControlSetupHandle(requestType, request, 0x100, 0, data2, 3);
                ret = ControlTransfer(myDeviceHandle, controlSetupHandle2, 1000);
                Thread.Sleep(500);
                if (ret > 0)
                {
                    Console.WriteLine("\nSuccess!\n");
                    byte[] ctrlDataBytes  = controlSetupHandle.ControlSetup.GetData(ret);
                    string ctrlDataString = Helper.HexString(ctrlDataBytes, String.Empty, "h ");
                    Console.WriteLine("Return Length: {0}", ret);
                    Console.WriteLine("DATA (hex)   : [ {0} ]\n", ctrlDataString.Trim());
                }
                MonoUsbApi.ReleaseInterface(myDeviceHandle, 0);
            }
            finally
            {
                profileList.Close();
                if (myDeviceHandle != null)
                {
                    myDeviceHandle.Close();
                }
                sessionHandle.Close();
                Console.WriteLine("End");
            }
        }
예제 #10
0
        public DACDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.DAC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x02) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        if (ControlPortNo > 0 && controlClients.Count == 0)
                        {
                            Thread.Sleep(100);
                            continue;
                        }

                        TcpClient client = null;
                        try
                        {
                            string remoteAddr;
                            if (ControlPortNo == 0)
                            {
                                remoteAddr = "127.0.0.1";
                            }
                            else
                            {
                                try
                                {
                                    remoteAddr = ((IPEndPoint)controlClients[0].Client.RemoteEndPoint).Address.ToString();
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                            client = new TcpClient(remoteAddr, dataPortNo);
                        }
                        catch (SocketException ex)
                        {
                            if (ex.ErrorCode == 10061)
                            {
                                Thread.Sleep(1000);
                                continue;
                            }

                            throw ex;
                        }
                        Console.WriteLine($"{dataPortNo}: accepted",
                                          DeviceType,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Address,
                                          ((IPEndPoint)client.Client.RemoteEndPoint).Port);

                        NetworkStream ns = client.GetStream();
                        try
                        {
                            int maxPacketSize;
                            if (USBDevice != null)
                            {
                                maxPacketSize = endpoint2.MaxPktSize;
                            }
                            else
                            {
                                maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x02);
                            }
                            byte[] inData  = new byte[64 * 1024];
                            byte[] outData = new byte[maxPacketSize - 16]; // Some PCs cannot send 1024 bytes
                            int outDataPos = 0;

                            while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                            {
                                int resSize = ns.Read(inData, 0, inData.Length);
                                if (resSize == 0)
                                {
                                    break;
                                }

                                int inDataLen = resSize;
                                int inDataPos = 0;
                                while (!ct.IsCancellationRequested && inDataPos < inDataLen)
                                {
                                    while (outDataPos < outData.Length && inDataPos < inDataLen)
                                    {
                                        outData[outDataPos++] = inData[inDataPos++];
                                    }

                                    if (outDataPos == outData.Length)
                                    {
                                        int xferLen = outData.Length;
                                        bool ret    = false;
                                        if (USBDevice != null)
                                        {
                                            ret = endpoint2.XferData(ref outData, ref xferLen);
                                        }
                                        else
                                        {
                                            ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x02, outData, outData.Length, out xferLen, TIMEOUT) == 0;
                                        }
                                        if (ret == false || xferLen == 0)
                                        {
                                            break;
                                        }
                                        if (xferLen != outData.Length)
                                        {
                                            Console.WriteLine($"{dataPortNo}: the response size {xferLen} not equal to the requested size {outData.Length}");
                                        }
                                        outDataPos = 0;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            // nothing to do
                        }
                        finally
                        {
                            ns.Close();
                            client.Close();
                            Console.WriteLine($"{dataPortNo}: closed");
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{dataPortNo}: {ex.Message}");
                }
            }, ct);
        }
예제 #11
0
        static bool HandleConfigModeDevice(MonoUsbProfile profile)
        {
            MonoUsbDeviceHandle handle;

            handle = profile.OpenDeviceHandle();

            if (handle == null || handle.IsInvalid)
            {
                return(false);
            }

            Usb.ClaimInterface(handle, 0);

            var now = DateTime.Now.ToUniversalTime();

            var date_string = String.Format("{0:d4}/{1:d2}/{2:d2}/{3:d2}/{4:d2}/{5:d2}",
                                            now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second
                                            );

            var date_string_bytes = Encoding.ASCII.GetBytes(date_string);

            MemoryStream date_string_cmd = new MemoryStream();

            date_string_cmd.WriteByte(19);
            date_string_cmd.WriteByte(0);
            date_string_cmd.WriteByte(0);
            date_string_cmd.WriteByte(0);
            date_string_cmd.Write(date_string_bytes, 0, date_string_bytes.Length);

            byte[] seq0 = new byte[] { 69, 58, 2, 103, 203, 15, 16, 15, 9, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq1 = new byte[] { 69, 58, 2, 103, 6, 15, 16, 15, 10, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq2 = new byte[] { 69, 58, 2, 103, 179, 15, 16, 15, 132, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq3 = new byte[] { 69, 58, 2, 103, 17, 15, 16, 15, 12, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq4 = new byte[] { 69, 58, 2, 103, 16, 15, 16, 15, 5, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq5 = new byte[] { 69, 58, 2, 103, 212, 0, 0, 15, 23, 0, 0, 0, 186, 197, 253, 152 };

            //byte[] seq6 = new byte[] { 19,  0, 0,   0,  50,  48, 49,  55,  47,  48, 54, 47,  50,  55,  47,  50, 48, 47, 51, 56, 47, 50, 56 };

            byte[] seq6 = date_string_cmd.ToArray();

            byte[] seq7 = new byte[] { 69, 58, 2, 103, 204, 15, 16, 15, 5, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq8 = new byte[] { 69, 58, 2, 103, 160, 15, 16, 15, 10, 0, 0, 0, 186, 197, 253, 152 };

            // These two packets alone will switch the device into mass storage mode.
            byte[] seq9  = new byte[] { 69, 58, 2, 103, 247, 0, 0, 15, 10, 0, 0, 0, 186, 197, 253, 152 };
            byte[] seq10 = new byte[] { 6, 0, 0, 0, 88, 122, 84, 117, 86, 116 };

            config_op(handle, 1, seq0, 2);
            config_op(handle, 1, seq1, 2);
            config_op(handle, 1, seq2, 2);
            config_op(handle, 1, seq3, 2);
            config_op(handle, 1, seq4, 2);
            config_op(handle, 1, seq5, 0);
            config_op(handle, 1, seq6, 1);
            config_op(handle, 1, seq7, 2);
            config_op(handle, 1, seq8, 2);
            config_op(handle, 1, seq9, 0);
            config_op(handle, 1, seq10, 1);

            handle.Close();
            return(true);
        }
예제 #12
0
        public bool DiscoveryUsbDevice(Boolean assignFlag = false)
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            if (assignFlag)
            {
                profileList   = new MonoUsbProfileList();
                sessionHandle = new MonoUsbSessionHandle();

                if (sessionHandle.IsInvalid)
                {
                    throw new Exception(String.Format("libusb {0}:{1}", MonoUsbSessionHandle.LastErrorCode,
                                                      MonoUsbSessionHandle.LastErrorString));
                }
                MyUsbDeviceArray = new UsbDevice[MAX_USB_DEVICE_COUNT];
            }
            else
            {
            }

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                System.Console.WriteLine("Open one more ");
                if (usbRegistry.Open(out MyUsbDevice))
                {
                    if ((bt_vid == MyUsbDevice.Info.Descriptor.VendorID) && (bt_pid == MyUsbDevice.Info.Descriptor.ProductID))
                    {
                        MyUsbDeviceArray[UsbDeviceCount] = MyUsbDevice;
                        UsbDeviceCount++;
                    }
                    else
                    {
                        System.Console.WriteLine(String.Format("device vid {0} pid {1}", MyUsbDevice.Info.Descriptor.VendorID, MyUsbDevice.Info.Descriptor.ProductID));
                    }

                    for (int iConfig = 0; iConfig < MyUsbDevice.Configs.Count; iConfig++)
                    {
                        UsbConfigInfo configInfo = MyUsbDevice.Configs[iConfig];
                        Console.WriteLine(configInfo.ToString());
                    }
                }
            }

            System.Console.WriteLine(String.Format("Open  {0}", UsbDeviceCount));

            System.Console.WriteLine("begin");
            if (profileList != null)
            {
                profileList.Refresh(sessionHandle);
            }

            MonoUsbProfile myProfile = profileList.GetList().Find(MyVidPidPredicate);

            MatchingUsbDeviceList = profileList.GetList().FindAll(MyVidPidPredicate);

            if (myProfile == null)
            {
                Console.WriteLine("myProfile is 0");
                return(false);
            }

            // Open the device handle to perfom I/O
            myDeviceHandle = myProfile.OpenDeviceHandle();
            if (myDeviceHandle.IsInvalid)
            {
                throw new Exception(String.Format("{0}, {1}", MonoUsbDeviceHandle.LastErrorCode,
                                                  MonoUsbDeviceHandle.LastErrorString));
            }

            for (int i = 0; i < UsbDeviceCount; i++)
            {
                object thisHubPort;
                int    thisPortNum     = -1;
                int    thisHubNum      = -1;
                char[] separatingChars = { '_', '.', '#' };

                MyUsbDeviceArray[i].UsbRegistryInfo.DeviceProperties.TryGetValue("LocationInformation", out thisHubPort);

                System.Console.WriteLine(String.Format("thisHubPort {0}", thisHubPort));
                string[] words = thisHubPort.ToString().Split(separatingChars, System.StringSplitOptions.RemoveEmptyEntries);

                if (words[0].Equals("Port"))
                {
                    thisPortNum = Convert.ToInt32(words[1]);
                }
                if (words[2].Equals("Hub"))
                {
                    thisHubNum = Convert.ToInt32(words[3]);
                }

                if (assignFlag)
                {
                    usbDeviceInfo             = new UsbDeviceInfo();
                    usbDeviceInfo.MyUsbDevice = MyUsbDeviceArray[i];
                    usbDeviceInfo.Port        = thisPortNum;
                    usbDeviceInfo.Hub         = thisHubNum;
                    Console.WriteLine(String.Format("info {0},{1}", thisPortNum, thisHubNum));
                    FinalDeviceIndex = (short)i;
                }
                else
                {
                    if ((usb_port == thisPortNum) && (usb_hub == thisHubNum))
                    {
                        System.Console.WriteLine(String.Format("usb_port {0}, usb_hub {1}", usb_port, usb_hub));
                        FinalDeviceIndex = (short)i;
                        break;
                    }
                }
            }

            return(true);
        }
예제 #13
0
        public ADCDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile)
            : base(usbDevice, usbProfile, EDeviceType.ADC)
        {
            byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
            dataPortNo = (ushort)(response[0] + (response[1] << 8));

            Console.WriteLine($"DeviceAttached: {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                UdpClient udp = new UdpClient();
                try
                {
                    int maxPacketSize;
                    if (USBDevice != null)
                    {
                        maxPacketSize = endpoint2.MaxPktSize;
                    }
                    else
                    {
                        maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                    }
                    byte[] inData  = new byte[maxPacketSize];
                    byte[] outData = null;
                    int outDataPos = 0;

                    while (!ct.IsCancellationRequested)
                    {
                        int xferLen = inData.Length;
                        bool ret    = false;
                        if (USBDevice != null)
                        {
                            ret = endpoint2.XferData(ref inData, ref xferLen);
                        }
                        else
                        {
                            ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                        }
                        if (ret == false)
                        {
                            break;
                        }

                        int inDataPos = 0;
                        while (!ct.IsCancellationRequested && inDataPos < xferLen)
                        {
                            if (outData == null)
                            {
                                outData = new byte[1472];
                            }
                            while (outDataPos < outData.Length && inDataPos < xferLen)
                            {
                                outData[outDataPos++] = inData[inDataPos++];
                            }

                            if (outDataPos == outData.Length)
                            {
                                udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                outData    = null;
                                outDataPos = 0;
                            }
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                    // nothing to do
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{DeviceType}: {ex.Message}");
                }
                finally
                {
                    udp.Close();
                }
            }, ct);
        }
예제 #14
0
        public ADCDevice(CyUSBDevice usbDevice, MonoUsbProfile usbProfile, EDeviceType deviceType)
            : base(usbDevice, usbProfile, deviceType)
        {
            if (deviceType == EDeviceType.ADC)
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 2);
                dataPortNo = (ushort)(response[0] + (response[1] << 8));
            }
            else
            {
                byte[] response = ReceiveVendorResponse((byte)EVendorRequests.DeviceParam, 4);
                dataPortNo    = (ushort)(response[0] + (response[1] << 8));
                ControlPortNo = (ushort)(response[2] + (response[3] << 8));
            }

            Console.WriteLine($"+ {this}");

            if (USBDevice != null)
            {
                endpoint2 = USBDevice.EndPointOf(0x82) as CyBulkEndPoint;
            }

            var ct = Cts.Token;

            Task.Run(() =>
            {
                while (!ct.IsCancellationRequested)
                {
                    if (ControlPortNo > 0 && controlClients.Count == 0)
                    {
                        Thread.Sleep(100);
                        continue;
                    }

                    UdpClient udp = new UdpClient();
                    try
                    {
                        int maxPacketSize;
                        if (USBDevice != null)
                        {
                            maxPacketSize = endpoint2.MaxPktSize;
                        }
                        else
                        {
                            maxPacketSize = MonoUsbApi.GetMaxPacketSize(USBProfile.ProfileHandle, 0x82);
                        }
                        byte[] inData  = new byte[maxPacketSize];
                        byte[] outData = null;
                        int outDataPos = 0;

                        while (!ct.IsCancellationRequested && !(ControlPortNo > 0 && controlClients.Count == 0))
                        {
                            int xferLen = inData.Length;
                            bool ret    = false;
                            if (USBDevice != null)
                            {
                                ret = endpoint2.XferData(ref inData, ref xferLen);
                            }
                            else
                            {
                                ret = MonoUsbApi.BulkTransfer(MonoDeviceHandle, 0x82, inData, inData.Length, out xferLen, TIMEOUT) == 0;
                            }
                            if (ret == false)
                            {
                                break;
                            }

                            int inDataPos = 0;
                            while (!ct.IsCancellationRequested && inDataPos < xferLen)
                            {
                                if (outData == null)
                                {
                                    outData = new byte[1472];
                                }
                                while (outDataPos < outData.Length && inDataPos < xferLen)
                                {
                                    outData[outDataPos++] = inData[inDataPos++];
                                }

                                if (outDataPos == outData.Length)
                                {
                                    List <string> remoteAddrList = new List <string>();
                                    foreach (var client in controlClients.ToArray())
                                    {
                                        string remoteAddr;
                                        try
                                        {
                                            remoteAddr = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
                                        }
                                        catch
                                        {
                                            continue;
                                        }

                                        if (remoteAddrList.Contains(remoteAddr) == false)
                                        {
                                            remoteAddrList.Add(remoteAddr);
                                            udp.Send(outData, outData.Length, remoteAddr, dataPortNo);
                                        }
                                    }

                                    if (ControlPortNo == 0)
                                    {
                                        udp.Send(outData, outData.Length, "127.0.0.1", dataPortNo);
                                    }

                                    outData    = null;
                                    outDataPos = 0;
                                }
                            }
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // nothing to do
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{dataPortNo}: {ex.Message}");
                    }
                    finally
                    {
                        udp.Close();
                    }

                    Thread.Sleep(1000);
                }
            }, ct);
        }