Ejemplo n.º 1
0
        public LibUsb_AsyncUsbStream(string port)
        {
            var splited = port.Split('-');
            var finder  = new UsbDeviceFinder(int.Parse(splited [0]), int.Parse(splited [1]));

            device = UsbDevice.OpenUsbDevice(finder);
            if (device == null)
            {
                throw new Exception("Failed to find device:" + port);
            }
            if (!device.IsOpen)
            {
                throw new Exception("Device is not open:" + port);
            }

            var usbDevice     = device as IUsbDevice;
            var interfaceInfo = device.Configs [0].InterfaceInfoList [0];

            if (usbDevice != null)
            {
                usbDevice.SetConfiguration(device.Configs [0].Descriptor.ConfigID);

                usbDevice.ClaimInterface(interfaceInfo.Descriptor.InterfaceID);
                deviceInterfaceId = interfaceInfo.Descriptor.InterfaceID;
            }

            foreach (var ep in interfaceInfo.EndpointInfoList)
            {
                if ((ep.Descriptor.EndpointID & 0x80) > 0)
                {
                    reader = device.OpenEndpointReader((ReadEndpointID)ep.Descriptor.EndpointID);
                    reader.DataReceived       += HandleDataReceived;
                    reader.DataReceivedEnabled = true;
                }
                else
                {
                    writer = device.OpenEndpointWriter((WriteEndpointID)ep.Descriptor.EndpointID);
                }
            }
        }
Ejemplo n.º 2
0
        private void Form1_Load(object sender, EventArgs e)
        {
            if (FindAndOpenUSB(myVID, myPID) == true)
            {
                ShowCon("设备已连接");
            }
            else
            {
                ShowCon("设备未连接");
            }

            DeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;

            writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
            reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);

            if (EnbaleInt == true)
            {
                reader.DataReceived       += (OnRxEndPointData);
                reader.DataReceivedEnabled = true;
            }
        }
        private static ErrorCode doBulkTransferSend(UsbEndpointWriter writer, int command, int dat2_8bit, int dat3_24bit)
        {
            byte[] buf = new byte[32];

            // command
            buf[0] = (byte)(command & 0xff);

            // payload
            if (dat2_8bit != 255)
            {
                buf[1] = (byte)(dat2_8bit & 0xff);
            }
            if (dat3_24bit != -1)
            {
                buf[2] = (byte)(dat3_24bit & 0xff);
                buf[3] = (byte)(dat3_24bit >> 8 & 0xff);
                buf[4] = (byte)(dat3_24bit >> 16 & 0xff);
                buf[5] = 0;
            }

            return(sendBuffer(writer, buf));
        }
        private UsbPrintConnector(UsbDevice usb)
        {
            this.m_usb            = usb;
            this.m_wholeUsbDevice = this.m_usb as IUsbDevice;
            if (this.m_wholeUsbDevice != null)
            {
                // This is a "whole" USB device. Before it can be used,
                // the desired configuration and interface must be selected.

                // Select config #1
                this.m_wholeUsbDevice.SetConfiguration(1);

                // Claim interface #0.
                this.m_wholeUsbDevice.ClaimInterface(0);
            }

            // open read endpoint 1.
            this.m_reader = this.m_usb.OpenEndpointReader(ReadEndpointID.Ep01);

            // open write endpoint 1.
            this.m_writer = this.m_usb.OpenEndpointWriter(WriteEndpointID.Ep01);
        }
Ejemplo n.º 5
0
        private void OpenDevice()
        {
            if (_usbDevice != null && _usbDevice.IsOpen)
            {
                return;
            }

            // Find and open the usb device.
            _usbDevice = UsbDevice.OpenUsbDevice(_usbFinder);

            // If the device is open and ready
            Debug.Assert(_usbDevice != null, string.Format("No device with PID: {0:X4} & VID: {1:X4} Found!", _pid, _vid));

            // If this is a "whole" usb device (libusb-win32, linux libusb)
            // it will have an IUsbDevice interface. If not (WinUSB) the
            // variable will be null indicating this is an interface of a
            // device.
            var wholeUsbDevice = _usbDevice as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                // This is a "whole" USB device. Before it can be used,
                // the desired configuration and interface must be selected.

                // Select config #1
                wholeUsbDevice.SetConfiguration(1);

                // Claim interface #0.
                wholeUsbDevice.ClaimInterface(0);
            }

            // open read endpoint 1.
            _epReader = _usbDevice.OpenEndpointReader((ReadEndpointID)EpIn);
            _epReader.Flush();

            // open write endpoint 1.
            _epWriter = _usbDevice.OpenEndpointWriter((WriteEndpointID)EpOut);
            LibMain.OnConnectedChanged(true);
        }
Ejemplo n.º 6
0
        public void Open()
        {
            try
            {
                Log.Debug("Opening CrazyradioDriver for communication...");

                var wholeUsbDevice = _crazyradioUsbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.Open();

                    Log.Debug("Opened UsbDevice for communication.");

                    wholeUsbDevice.SetConfiguration(1);

                    Log.Debug("Set UsbDevice configuration to 1.");

                    wholeUsbDevice.ClaimInterface(0);

                    Log.Debug("Claimed interface 0 of UsbDevice.");
                }

                if (!_propertiesInitializedToDefaults)
                {
                    SetToDefaults();
                }

                _crazyradioDataEndpointReader = _crazyradioUsbDevice.OpenEndpointReader(CrazyradioDataEndpointId.Read);
                _crazyradioDataEndpointWriter = _crazyradioUsbDevice.OpenEndpointWriter(CrazyradioDataEndpointId.Write);

                Log.Debug("Successfully opened CrazyradioDriver for communication.");
            }
            catch (Exception ex)
            {
                const string message = "Error opening/initializing CrazyradioDriver for communication.";
                Log.Error(message, ex);
                throw new CrazyradioDriverException(message, ex);
            }
        }
Ejemplo n.º 7
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
                if (MyUsbDevice == null)
                {
                    throw new Exception("Device Not Found.");
                    //connected = false;
                }
                else
                {
                    Device_l.Text = "Device: Connected";
                    //connected = true;

                    Scan_b.Enabled = true;

                    wholeUsbDevice = MyUsbDevice as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        // This is a "whole" USB device. Before it can be used,
                        // the desired configuration and interface must be selected.

                        // Select config #1
                        wholeUsbDevice.SetConfiguration(1);

                        // Claim interface #0.
                        wholeUsbDevice.ClaimInterface(0);
                    }

                    reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);
                    writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep04);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
            }
        }
Ejemplo n.º 8
0
        public bool ConnectToOscill()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllLibUsbDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                if ((usbRegistry.Vid == Konstants.MY_VID) && (usbRegistry.Pid == Konstants.MY_PID))
                {
                    usbRegistry.Open(out OscillDevice);
                    if (OscillDevice != null)
                    {
                        reader = OscillDevice.OpenEndpointReader(Konstants.rID);
                        writer = OscillDevice.OpenEndpointWriter(Konstants.wID);

                        Konstants.DeviceName      = OscillDevice.Info.ProductString;
                        Konstants.FirmwareVersion = OscillDevice.Info.SerialString;
                        return(true);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 9
0
        private void DeviceDisconnect()
        {
            if (inUsingDevice != null && inUsingDevice.IsOpen)
            {
                EndpointReader.DataReceivedEnabled = false;
                EndpointReader.DataReceived       -= (OnRxEndPointData);
                IUsbDevice wholeUsbDevice = inUsingDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // Release interface #0.
                    wholeUsbDevice.ReleaseInterface(0);
                }
                inUsingDevice.Close();
            }
            EndpointWriter = null;
            EndpointReader = null;
            inUsingDevice  = null;

            // Update controls
            lb_status.Text      = "未连接";
            lb_status.ForeColor = Color.Red;
        }
Ejemplo n.º 10
0
        public bool Print()
        {
            writer = getWriter();
            int  bytesWritten;
            bool isSuccess = true;

            try
            {
                ec = writer.Write(bytes, 2000, out bytesWritten);
                ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);
                ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);

                /*
                 * for (int i = 0; i < 2; i++)
                 * {
                 *  ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);
                 * }*/
                //ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);

                if (ec.ToString() == "Success")
                {
                    isSuccess = true;
                }
                else
                {
                    isSuccess = false;
                }
                return(isSuccess);
            }
            catch (Exception ex)
            {
                isSuccess = false;
                return(isSuccess);
            }
            finally
            {
            }
        }
Ejemplo n.º 11
0
        private void closeDevice()
        {
            if (mUsbDevice != null)
            {
                if (mUsbDevice.IsOpen)
                {
                    if (mEpReader != null)
                    {
                        mEpReader.DataReceivedEnabled = false;
                        mEpReader.DataReceived       -= mEp_DataReceived;
                        mEpReader.Dispose();
                        mEpReader = null;
                    }
                    if (mEpWriter != null)
                    {
                        mEpWriter.Abort();
                        mEpWriter.Dispose();
                        mEpWriter = null;
                    }

                    // If this is a "whole" usb device (libusb-win32, linux libusb)
                    // it will have an IUsbDevice interface. If not (WinUSB) the
                    // variable will be null indicating this is an interface of a
                    // device.
                    IUsbDevice wholeUsbDevice = mUsbDevice as IUsbDevice;
                    if (!ReferenceEquals(wholeUsbDevice, null))
                    {
                        // Release interface #0.
                        wholeUsbDevice.ReleaseInterface(0);
                    }

                    mUsbDevice.Close();
                    mUsbDevice           = null;
                    chkLogToFile.Checked = false;
                }
            }
            panTransfer.Enabled = false;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 打开USB设备
        /// </summary>
        /// <param name="usb"></param>
        private void OpenDevice()
        {
            if (inUsingDevice != null)
            {
                return;
            }
            // Open Device
            inUsingDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
            if (inUsingDevice != null)
            {
                IUsbDevice wholeUsbDevice = inUsingDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);
                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }
                EndpointWriter = inUsingDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
                EndpointReader = inUsingDevice.OpenEndpointReader(ReadEndpointID.Ep02);

                EndpointReader.DataReceived       += (OnRxEndPointData);
                EndpointReader.DataReceivedEnabled = true;
                // Update controls
                lb_status.Text      = "已连接";
                lb_status.ForeColor = Color.Green;

                Pigeon_Comm_Data data = new Pigeon_Comm_Data();
                data.Head = 0x66;
                data.Cmd  = Pigeon_Comm_Cmd.READ_SETTINGS;
                data.Len  = 0;
                //
                byte[] vs = Data.ToBytes(data);
                // Send to device
                int bytesWritten;
                EndpointWriter.Write(vs, 1000, out bytesWritten);
            }
        }
Ejemplo n.º 13
0
 public UsbEndpointWriter getWriter()
 {
     if (writer == null)
     {
         if (MyUsbDevice == null)
         {
             //throw new Exception("Device Not Found");
             MessageBox.Show("未连接上打印机");
         }
         IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             // This is a "whole" USB device. Before it can be used,
             // the desired configuration and interface must be selected.
             // Select config #1
             wholeUsbDevice.SetConfiguration(1);
             // Claim interface #0.
             wholeUsbDevice.ClaimInterface(0);
         }
         writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
     }
     return(writer);
 }
Ejemplo n.º 14
0
        public void Open()
        {
            if (!Driver.IsOpen)
            {
                Driver.Open();
                IUsbDevice wholeUsbDevice = Driver as IUsbDevice;
                if (wholeUsbDevice is not null)
                {
                    wholeUsbDevice.Open();
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                //Get the first config number of the interface
                Driver.ClaimInterface(Driver.Configs[0].Interfaces[0].Number);
                EndpointWriter = Driver.OpenEndpointWriter(WriteEndpointID.Ep01);
                EndpointReader = Driver.OpenEndpointReader(ReadEndpointID.Ep01);

                DeviceInfo.Manufacturer = Driver.Info.Manufacturer;
                DeviceInfo.Product      = Driver.Info.Product;
                DeviceInfo.SerialNumber = Driver.Info.SerialNumber;
            }
            DeviceInfo.Ready = Driver.IsOpen;
        }
Ejemplo n.º 15
0
        public bool Open()
        {
            IsConnected = Registry.Open(out Device);
            if (IsConnected)
            {
                var wholeUsbDevice = Device as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                // open write endpoint 1.
                Writer = Device.OpenEndpointWriter(WriteEndpointID.Ep02);
            }
            return(IsConnected);
        }
Ejemplo n.º 16
0
        public SmartScopeUsbInterfaceLibUsb(UsbDevice usbDevice)
        {
            if (usbDevice is IUsbDevice)
            {
                bool succes1 = (usbDevice as IUsbDevice).SetConfiguration(1);
                if (!succes1)
                {
                    throw new ScopeIOException("Failed to set usb device configuration");
                }
                bool succes2 = (usbDevice as IUsbDevice).ClaimInterface(0);
                if (!succes2)
                {
                    throw new ScopeIOException("Failed to claim usb interface");
                }
            }
            device               = usbDevice;
            serial               = usbDevice.Info.SerialString;
            dataEndpoint         = usbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
            commandWriteEndpoint = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
            commandReadEndpoint  = usbDevice.OpenEndpointReader(ReadEndpointID.Ep03);

            Common.Logger.Debug("Created new ScopeUsbInterface from device with serial " + serial);
        }
Ejemplo n.º 17
0
 internal bool reopenPort()
 {
     lock (lock_access)
     {
         ClosePort();
         scanDevice();
         UsbRegistry usb_reg;
         if (devicesDIC.TryGetValue(last_device_name, out usb_reg) == false)
         {
             return(false);
         }
         selected_device = usb_reg.Device;
         if (!(selected_device.Open()))
         {
             throw new DriveNotFoundException(string.Format("open USB (port)device {0} fail", Selected_device_name));
         }
         IUsbDevice wholeUsbDevice = selected_device as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             // This is a "whole" USB device. Before it can be used,
             // the desired configuration and interface must be selected.
             // Select config #1
             wholeUsbDevice.SetConfiguration(1);
             // Claim interface #0.
             wholeUsbDevice.ClaimInterface(0);
         }
         else
         {
             throw new DriveNotFoundException(string.Format("selected_device can not as IUsbDevice"));
         }
         srb_reader = selected_device.OpenEndpointReader((ReadEndpointID)(1 | 0x80), 1000, EndpointType.Interrupt);
         srb_writer = selected_device.OpenEndpointWriter((WriteEndpointID)2);
         // srb_reader.DataReceived += mEp_DataReceived;
         srb_reader.Flush();
         return(true);
     }
 }
Ejemplo n.º 18
0
        private void closeDevice()
        {
            if (mDev != null)
            {
                if (mEpReader != null)
                {
                    mEpReader.DataReceivedEnabled = false;
                    mEpReader.DataReceived       -= mEp_DataReceived;
                    mEpReader.Dispose();
                    mEpReader = null;
                }
                if (mEpWriter != null)
                {
                    mEpWriter.Dispose();
                    mEpWriter = null;
                }
                mDev.ReleaseInterface(0);
                mDev.SetConfiguration(0);

                mDev.Close();
                mDev = null;
            }
            panTransfer.Enabled = false;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 断开连接调用
        /// </summary>
        private void disconnected()
        {
            pl_conn.Enabled = true;
            pl_main.Enabled = false;

            if (captureForm != null)
            {
                captureForm.Close();
                captureForm = null;
            }
            if (thread != null && thread.IsAlive)
            {
                thread.Abort();
            }
            writer           = null;
            usbcmd           = null;
            btn_connect.Text = "连接设备";
            btn_capture.Text = "开始窗口捕捉";
            if (inUsingDevce != null)
            {
                inUsingDevce.Close();
                inUsingDevce = null;
            }
        }
Ejemplo n.º 20
0
        public bool PrintSmall()
        {
            writer = getWriter();
            int  bytesWritten;
            bool isSuccess = true;
            int  count     = 1;

            count = (int)nudCount.Value;
            try
            {
                ec = writer.Write(sbytes, 2000, out bytesWritten);
                for (int i = 0; i < 8; i++)
                {
                    ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);
                }
                //ec = writer.Write(new byte[] { 0x0a }, 2000, out bytesWritten);

                if (ec.ToString() == "Success")
                {
                    isSuccess = true;
                }
                else
                {
                    isSuccess = false;
                }
                return(isSuccess);
            }
            catch (Exception ex)
            {
                isSuccess = false;
                return(isSuccess);
            }
            finally
            {
            }
        }
Ejemplo n.º 21
0
    void Awake()
    {
        base.Awake();

        isModCStick          = false;
        calibrModAnalogYPlus = calibrModAnalogYMinus = calibrModAnalogXPlus = calibrModAnalogXMinus = 1f;
        calibrModcstickYPlus = calibrModcstickYMinus = calibrModcstickXPlus = calibrModcstickXMinus = 1f;

        var USBFinder = new UsbDeviceFinder(0x057E, 0x0337);

        GCNAdapter = UsbDevice.OpenUsbDevice(USBFinder);


        if (GCNAdapter != null)
        {
            reader = GCNAdapter.OpenEndpointReader(ReadEndpointID.Ep01);
            writer = GCNAdapter.OpenEndpointWriter(WriteEndpointID.Ep02);

            //prompt controller to start sending
            writer.Write(Convert.ToByte((char)19), 10, out transferLength);

            // PORT 1: bytes 02-09
            // PORT 2: bytes 11-17
            // PORT 3: bytes 20-27
            // PORT 4: bytes 29-36l
            ReadBuffer = new byte[37]; // 32 (4 players x 8) bytes for input, 5 bytes for formatting
            //WriteBuffer = new byte[5]; // 1 for command, 4 for rumble state
            //WriteBuffer[0] = 0x11;
            //WriteBuffer[1] = 0;
            reader.ReadThreadPriority = System.Threading.ThreadPriority.Highest; //DONT ADD THIS BACK!!!!!!! Until further testing
        }
        else
        {
            UnityEngine.Debug.Log("ERROR: Could not detect device WUP-028 Gamecube Controller Adapter.");
        }
    }
Ejemplo n.º 22
0
        private void openAsTestDevice(UsbDevice dev)
        {
            if (!ReferenceEquals(usb, null))
            {
                closeTestDevice();
            }

            usb = dev;
            usb.Open();
            if (usb.SetConfiguration(1) == 0)
            {
                if (usb.ClaimInterface(0) == 0)
                {
                    mEP1Reader = usb.OpenBulkEndpointReader(ReadEndpoints.Ep01);
                    mEP1Writer = usb.OpenBulkEndpointWriter(WriteEndpoints.Ep01);

                    mEP1Reader.DataReceived       += mBulkInOut_DataReceived;
                    mEP1Reader.DataReceivedEnabled = true;
                    return;
                }
            }

            throw new Exception("Failed opening device.");
        }
Ejemplo n.º 23
0
        //--------------------------------------------------------------------------------------------------------
        public static Boolean Open()
        {
            UsbDeviceFinder PCBRulerIIFinder = new UsbDeviceFinder(DEV_VID, DEV_PID);

            USBDev = UsbDevice.OpenUsbDevice(PCBRulerIIFinder);

            if (USBDev == null)
            {
                return(false);
            }

            IUsbDevice wholeUsbDevice = USBDev as IUsbDevice;

            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                wholeUsbDevice.SetConfiguration(1);
                wholeUsbDevice.ClaimInterface(0);
            }

            USBDevReader = USBDev.OpenEndpointReader(ReadEndpointID.Ep01);
            USBDevWriter = USBDev.OpenEndpointWriter(WriteEndpointID.Ep01);

            return(true);
        }
Ejemplo n.º 24
0
 private bool DeviceInit(int vendorID, int productID, bool deviceReset = true)
 {
     try {
         _vendorID  = vendorID;
         _productID = productID;
         Device     = UsbDevice.OpenUsbDevice(new UsbDeviceFinder(vendorID, productID));
         if (Device == null)
         {
             Main.SendDebug(string.Format("No Device Found with VendorID: 0x{0:X04} and ProductID: 0x{1:X04}", vendorID, productID));
             Release();
             return(false);
         }
         if (deviceReset)
         {
             Release();
             Thread.Sleep(1000);
             return(DeviceInit(vendorID, productID, false));
         }
         DeviceConfigInfo = Device.Configs[0];
         var wholeUsbDevice = Device as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             wholeUsbDevice.SetConfiguration(DeviceConfigInfo.Descriptor.ConfigID);
             wholeUsbDevice.ClaimInterface(0);
         }
         _reader = Device.OpenEndpointReader((ReadEndpointID)0x82);
         ClearReadBuffer();
         _writer = Device.OpenEndpointWriter((WriteEndpointID)0x05);
         UsbDevice.UsbErrorEvent += UsbDeviceOnUsbErrorEvent;
         return(true);
     }
     catch (Exception ex) {
         Main.SendDebug(String.Format("Device Init exception occured: {0}", ex.Message));
         throw;
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Open the connection
        /// </summary>
        public override void Open()
        {
            bool hasError = false;

            try
            {
                myUsbDevice = UsbDevice.OpenUsbDevice(myUsbFinder);
                if (myUsbDevice == null)
                {
                    throw new ConnectionException(ConnectionError.OpenError);
                }
                reader = myUsbDevice.OpenEndpointReader(readId, 1024, EndpointType.Bulk);
                writer = myUsbDevice.OpenEndpointWriter(writeId, EndpointType.Bulk);
            }
            catch {
                throw new ConnectionException(ConnectionError.OpenError);
            }
            if (hasError)
            {
                throw new ConnectionException(ConnectionError.OpenError);
            }
            isConnected = true;
            ConnectionWasOpened();
        }
Ejemplo n.º 26
0
 private bool reconnect()
 {
     //clear the info so far
     if (MyUsbDevice != null)
     {
         writer.Dispose();
         wholeUsbDevice.ReleaseInterface(0);
         wholeUsbDevice.Close();
         MyUsbDevice.Close();
         UsbDevice.Exit();
     }
     //now start over
     MyUsbFinder = new UsbDeviceFinder(0x06D3, 0x01D0);
     MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
     // If the device is open and ready
     if (MyUsbDevice == null)
     {
         msgchnl.setcurrMessage("Problem in reconnect() MyUsbDevice is null");
         return(false);
     }
     else
     {
         wholeUsbDevice = MyUsbDevice as IUsbDevice;
         if (!ReferenceEquals(wholeUsbDevice, null))
         {
             // Select config #1
             wholeUsbDevice.SetConfiguration(1);
             // Claim interface #0.
             wholeUsbDevice.ClaimInterface(0);
         }
         writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
         reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
         //Console.WriteLine("New Writer an reader was assigned");
         return(true);
     }
 }
Ejemplo n.º 27
0
        public override bool InitializeCommu()
        {
            m_USBParam.InitUsbParam();
            m_UsbFinder = new UsbDeviceFinder(m_USBParam.Vid, m_USBParam.Pid);
            m_UsbDevice = UsbDevice.OpenUsbDevice(m_UsbFinder);
            if (m_UsbDevice == null)
            {
                return(false);
            }

            #region  // 当设备是一个 "whole" USB 时,我们的设备一般不会是此情况
            // If this is a "whole" usb device (libusb-win32, linux libusb)
            // it will have an IUsbDevice interface. If not (WinUSB) the
            // variable will be null indicating this is an interface of a
            // device.
            IUsbDevice wholeUsbDevice = m_UsbDevice as IUsbDevice;
            if (!ReferenceEquals(wholeUsbDevice, null))
            {
                // This is a "whole" USB device. Before it can be used,
                // the desired configuration and interface must be selected.

                // Select config #1
                wholeUsbDevice.SetConfiguration(1);

                // Claim interface #0.
                wholeUsbDevice.ClaimInterface(0);
            }
            #endregion

            m_UsbReader = m_UsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
            m_UsbReader.ReadBufferSize = nReadBufSize;

            m_UsbWriter = m_UsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

            return(true);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Opens the device in accessory mode.  Sets up the read and write streams.
        /// </summary>
        private bool DeviceSetToAccessoryMode()
        {
            lock (DeviceAccessorySyncLock)
            {
                bool initialized = false;
                if (MyUsbDevice == null || !MyUsbDevice.IsOpen || !MyUsbDevice.UsbRegistryInfo.IsAlive)
                {
                    // If the device is open and  we no longer have this device in the bus enumeration, close it to try to
                    // get it back to a sane state
                    if (MyUsbDevice != null && !MyUsbDevice.UsbRegistryInfo.IsAlive)
                    {
                        if (MyUsbDevice.IsOpen)
                        {
                            MyUsbDevice.Close();
                        }
                    }

                    if (MyUsbDevice == null)
                    {
                        TransportLog("DeviceSetToAccessoryMode(): MyUsbDevice is null.  Attempting to recreate/reopen using WinUSB lib");
                    }
                    else
                    {
                        TransportLog("DeviceSetToAccessoryMode(): MyUsbDevice.IsOpen = false.  Attempting to reopen using WinUSB lib.");
                    }

                    try
                    {
                        for (int i = 0; i < UsbDevice.AllWinUsbDevices.Count && MyUsbDevice == null; i++)
                        {
                            WinUsbRegistry usbDevice = (WinUsbRegistry)UsbDevice.AllWinUsbDevices[i];
                            foreach (UsbDeviceFinder finder in CustomerUsbFinders)
                            {
                                if (usbDevice.Vid == finder.Vid && usbDevice.Pid == finder.Pid && usbDevice.InterfaceID == 0)
                                {
                                    if (usbDevice.Open(out MyUsbDevice))
                                    {
                                        TransportLog("WinUSB Device Found and Open.");
                                        break;
                                    }
                                    else
                                    {
                                        // found the device, but can't open it...Someone else may have this open.
                                        throw new Exception("Found the device, but can't open it. Some other process(service or application) may already have it open.");
                                    }
                                }
                            }
                        }

                        // try libusb, but current WinUsb is the driver of choice
                        if (MyUsbDevice == null)
                        {
                            TransportLog("DeviceSetToAccessoryMode(): MyUsbDevice is null.  Attempting to recreate/reopen using LibUSB driver");
                            for (int i = 0; i < UsbDevice.AllLibUsbDevices.Count; i++)
                            {
                                LibUsbRegistry usbDevice = (LibUsbRegistry)UsbDevice.AllLibUsbDevices[i];
                                foreach (UsbDeviceFinder finder in CustomerUsbFinders)
                                {
                                    if (usbDevice.Vid == finder.Vid && usbDevice.Pid == finder.Pid)
                                    {
                                        if (usbDevice.Open(out MyUsbDevice))
                                        {
                                            TransportLog("LibUSB Device Found and Open.");
                                            break;
                                        }
                                        else
                                        {
                                            // found the device, but can't open it...Someone else may have this open.
                                            throw new Exception("LibUSB: Found the device, but can't open it. Some other process(service or application) may already have it open.");
                                        }
                                    }
                                }
                            }
                        }

                        if (MyUsbDevice == null)
                        {
                            throw new Exception("Obtaining handle to the usb device failed.");
                        }

                        // If this is a "whole" usb device (libusb-win32, linux libusb)
                        // it will have an IUsbDevice interface. If not (WinUSB) the
                        // variable will be null indicating this is an interface of a
                        // device.
                        if (MyUsbDevice is IUsbDevice wholeUsbDevice)
                        {
                            // This is a "whole" USB device. Before it can be used,
                            // the desired configuration and interface must be selected.

                            // Select config #1
                            wholeUsbDevice.SetConfiguration(1);

                            // Claim interface #0.
                            wholeUsbDevice.ClaimInterface(0);
                        }

                        // open read endpoint 1.
                        reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                        if (null != reader)
                        {
                            // open write endpoint 1.
                            writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
                            if (null != writer)
                            {
                                shutdown = false;
                                startListeningForMessages();
                                messageSendLoop();
                                initialized = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        TransportLog(Environment.NewLine);
                        TransportLog(ex.Message);
                    }
                    TransportLog("Exiting DeviceSetToAccessoryMode");
                    if (initialized)
                    {
                        TransportLog("DeviceSetToAccessoryMode(): MyUsbDevice is ready");
                        onDeviceReady();
                    }
                }
                else
                {
                    initialized = true;
                }
                return(initialized);
            }
        }
Ejemplo n.º 29
0
        private void ConnectbuttonClick(object sender, RoutedEventArgs e)
        {
            if (Connectbutton.IsChecked != null && (bool)Connectbutton.IsChecked)
            {
                if (_myUsbDevice != null)
                {
                }
                else
                {
                    if (_regList.Count != 0)
                    {
                        LbxDev.Items.Clear();
                        foreach (UsbRegistry regDevice in _regList)
                        {
                            LbxDev.Items.Add(regDevice.FullName);
                        }

                        _myUsbDevice = UsbDevice.OpenUsbDevice(_myUsbFinder);

                        if (_myUsbDevice is IUsbDevice wholeUsbDevice)
                        {
                            wholeUsbDevice.SetConfiguration(1);
                            wholeUsbDevice.ClaimInterface(0);
                        }

                        _reader = _myUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                        _writer = _myUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);

                        _reader.DataReceived += OnRxEndPointData;

                        _reader.ReadBufferSize = 13760;

                        _reader.Reset();
                        _reader.DataReceivedEnabled = true;

                        ScanButton.IsEnabled = false;
                        SaveButton.IsEnabled = true;
                        Filter.IsEnabled     = true;
                    }
                    else
                    {
                        AddMsg($" > 找不到设备");
                        Connectbutton.IsChecked = false;
                        Filter.IsEnabled        = false;
                    }
                }
            }
            else
            {
                if (_myUsbDevice == null)
                {
                    return;
                }
                _reader.DataReceivedEnabled = false;
                _reader.DataReceived       -= OnRxEndPointData;

                LbxDev.Items.RemoveAt(0);
                AddMsg($" > 关闭设备");
                System.Windows.MessageBox.Show($"再次开启设备需要重新上电");

                if (_myUsbDevice.IsOpen)
                {
                    try
                    {
                        IUsbDevice wholeUsbDevice = _myUsbDevice as IUsbDevice;
                        wholeUsbDevice?.ReleaseInterface(0);
                        _myUsbDevice.Close();
                    }
                    catch (Exception ex)
                    {
                        Console.Write(ex.ToString());
                    }
                }

                _myUsbDevice = null;
                UsbDevice.Exit();

                ScanButton.IsEnabled = true;
                SaveButton.IsEnabled = false;
                Filter.IsEnabled     = true;
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Open the TreehopperBoard. The board must be opened before any other methods are called.
        /// </summary>
        public void Open()
        {
            if (usb.Open())
            {
                // If this is a "whole" usb device (libusb-win32, linux libusb)
                // it will have an IUsbDevice interface. If not (WinUSB) the
                // variable will be null indicating this is an interface of a
                // device.
                IUsbDevice wholeUsbDevice = usb as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    // This is a "whole" USB device. Before it can be used,
                    // the desired configuration and interface must be selected.

                    // Select config #1
                    wholeUsbDevice.SetConfiguration(1);

                    // Claim interface #0.
                    wholeUsbDevice.ClaimInterface(0);
                }

                pinStateBuffer = new byte[64];

                Pins = new List <Pin>();

                // Initialize Pins
                pin1  = new Pin1(this);
                pin2  = new Pin2(this);
                pin3  = new Pin3(this);
                pin4  = new Pin4(this);
                pin5  = new Pin5(this);
                pin6  = new Pin6(this);
                pin7  = new Pin7(this);
                pin8  = new Pin8(this);
                pin9  = new Pin9(this);
                pin10 = new Pin10(this);
                pin11 = new Pin11(this);
                pin12 = new Pin12(this);
                pin13 = new Pin13(this);
                pin14 = new Pin14(this);

                Pins.Add(pin1);
                Pins.Add(pin2);
                Pins.Add(pin3);
                Pins.Add(pin4);
                Pins.Add(pin5);
                Pins.Add(pin6);
                Pins.Add(pin7);
                Pins.Add(pin8);
                Pins.Add(pin9);
                Pins.Add(pin10);
                Pins.Add(pin11);
                Pins.Add(pin12);
                Pins.Add(pin13);
                Pins.Add(pin14);

                SoftPwmMgr = new SoftPwmManager(this);

                // Comparator
                //Comparator1 = new Comparator(1);
                //Comparator2 = new Comparator(2);

                // Initialize modules
                analogOut = new AnalogOut(this);
                i2c       = new I2c(this);
                spi       = new Spi(this);
                //UART = new UART();

                // Initialize endpoint readers/writers
                PinConfig    = usb.OpenEndpointWriter(WriteEndpointID.Ep01);
                pinState     = usb.OpenEndpointReader(ReadEndpointID.Ep01);
                CommsConfig  = usb.OpenEndpointWriter(WriteEndpointID.Ep02);
                CommsReceive = usb.OpenEndpointReader(ReadEndpointID.Ep02);

                // Start reader events
                pinState.DataReceived       += pinState_DataReceived;
                pinState.DataReceivedEnabled = true;
                this.IsConnected             = true;
            }
            else
            {
                if (usb != null)
                {
                    if (usb.IsOpen)
                    {
                        usb.Close();
                    }
                    usb = null;
                }
            }
        }