public override void Open(UsbDeviceConnection connection)
        {
            _connection = connection;

            _controlInterface = Device.GetInterface(0);
            if (!connection.ClaimInterface(_controlInterface, true))
            {
                throw new Exception("Could not claim control interface.");
            }

            _controlEndpoint = _controlInterface.GetEndpoint(0);

            _dataInterface = Device.GetInterface(1);
            if (!connection.ClaimInterface(_dataInterface, true))
            {
                throw new Exception("Could not claim data interface.");
            }

            if (Device.VendorId == 0x1cbe)
            {
                _writeEndpoint = _dataInterface.GetEndpoint(1);
                _readEndpoint  = _dataInterface.GetEndpoint(0);
            }
            else
            {
                _writeEndpoint = _dataInterface.GetEndpoint(0);
                _readEndpoint  = _dataInterface.GetEndpoint(1);
            }

            Init();
            var buadSet = SetBaudrate(960000);
        }
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already opened.");
                }

                mConnection = connection;
                bool opened = false;
                bool controlInterfaceFound = false;

                try
                {
                    for (var i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        mControlInterface = mDevice.GetInterface(i);
                        if (mControlInterface.InterfaceClass == UsbClass.Comm)
                        {
                            if (!mConnection.ClaimInterface(mControlInterface, true))
                            {
                                throw new IOException("Could not claim control interface");
                            }
                            (Driver as STM32SerialDriver).mCtrlInterf = i;
                            controlInterfaceFound = true;
                            break;
                        }
                    }
                    if (!controlInterfaceFound)
                    {
                        throw new IOException("Could not claim control interface");
                    }
                    for (var i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        mDataInterface = mDevice.GetInterface(i);
                        if (mDataInterface.InterfaceClass == UsbClass.CdcData)
                        {
                            if (!mConnection.ClaimInterface(mDataInterface, true))
                            {
                                throw new IOException("Could not claim data interface");
                            }
                            mReadEndpoint  = mDataInterface.GetEndpoint(1);
                            mWriteEndpoint = mDataInterface.GetEndpoint(0);
                            opened         = true;
                            break;
                        }
                    }
                    if (!opened)
                    {
                        throw new IOException("Could not claim data interface.");
                    }
                }
                finally
                {
                    if (!opened)
                    {
                        mConnection = null;
                    }
                }
            }
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already open");
                }
                mConnection = connection;

                Boolean opened = false;

                try {
                    for (int i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        if (connection.ClaimInterface(mDevice.GetInterface(i), true))
                        {
                            Log.Debug(TAG, "claimInterface " + i + " SUCCESS");
                        }
                        else
                        {
                            throw new IOException("Error claiming interface " + i);
                        }
                    }
                    Reset();
                    opened = true;
                } finally {
                    if (!opened)
                    {
                        Close();
                        mConnection = null;
                    }
                }
            }
Exemple #4
0
        public SmartScopeUsbInterfaceXamarin(Context context, UsbManager usbManager, UsbDevice device)
        {
            Destroyed = false;
            if (!usbManager.HasPermission(device))
            {
                Logger.Error("Permission denied");
                throw new Exception("Device permission not obtained");
            }

            UsbInterface interf = device.GetInterface(0);

            for (int i = 0; i < interf.EndpointCount; i++)
            {
                if (interf.GetEndpoint(i).EndpointNumber == 1)
                {
                    dataEndpoint = interf.GetEndpoint(i);
                }
                else if (interf.GetEndpoint(i).EndpointNumber == 2)
                {
                    commandWriteEndpoint = interf.GetEndpoint(i);
                }
                else if (interf.GetEndpoint(i).EndpointNumber == 3)
                {
                    commandReadEndpoint = interf.GetEndpoint(i);
                }
            }
            usbConnection = usbManager.OpenDevice(device);
            usbConnection.ClaimInterface(interf, true);
        }
        /**
         * 打开设备
         */
        private void openDevice()
        {
            if (myInterface != null)
            {
                UsbDeviceConnection conn = null;
                // 在open前判断是否有连接权限;对于连接权限可以静态分配,也可以动态分配权限,可以查阅相关资料
                if (myUsbManager.HasPermission(myUsbDevice))
                {
                    conn = myUsbManager.OpenDevice(myUsbDevice);
                }

                if (conn == null)
                {
                    return;
                }

                if (conn.ClaimInterface(myInterface, true))
                {
                    myDeviceConnection = conn; // 到此你的android设备已经连上HID设备
                    Log.Debug(TAG, "打开设备成功");
                }
                else
                {
                    conn.Close();
                }
            }
        }
        /// <summary>
        /// try to retreive an endpoint with the device
        /// Is seems that  usb-serial-for-android does this job
        /// </summary>
        /// <param name="connection"> The created connection</param>
        /// <param name="epIn"> Endpoint found for the interface for device to host transmission </param>
        /// <param name="epOut"> Endpoint found for the interface for host to device transmission </param>
        /// <returns> operation result </returns>
        protected int OpenInterface(UsbDevice usbdev, UsbDeviceConnection connection, ref UsbInterface usbIface, ref UsbEndpoint epIn, ref UsbEndpoint epOut)
        {
            int ret = -1;
            int i;

            // Search and claim the first interface available
            for (i = 0; i < usbdev.InterfaceCount; i++)
            {
                usbIface = usbdev.GetInterface(i);
                if (connection.ClaimInterface(usbIface, true))
                {
                    // Now search IO endpoints
                    if (InterfaceGetBulkEndpoints(usbIface, ref epIn, ref epOut) == 0)
                    {
                        connection.SetInterface(usbIface);
                        return(0);
                    }
                    else
                    {
                        connection.ReleaseInterface(usbIface);
                    }
                }
            }
            return(ret);
        }
Exemple #7
0
        public override void Open(UsbDeviceConnection connection)
        {
            if (Connection != null)
            {
                throw new IOException("Already open");
            }
            Connection = connection;

            bool opened = false;

            try
            {
                if (connection.ClaimInterface(Device.GetInterface(PortNumber), true))
                {
                    Log.Debug(TAG, "claimInterface " + PortNumber + " SUCCESS");
                }
                else
                {
                    throw new IOException("Error claiming interface " + PortNumber);
                }
                Reset();
                opened = true;

                _readEndpoint = Device.GetInterface(PortNumber).GetEndpoint(0);
            }
            finally
            {
                if (!opened)
                {
                    Close();
                    Connection = null;
                }
            }
        }
Exemple #8
0
        public override void Open(UsbDeviceConnection connection)
        {
            if (_connection != null)
            {
                throw new UsbSerialException("Already open");
            }
            _connection = connection;

            bool opened = false;

            try
            {
                for (int i = 0; i < _driver.Device.InterfaceCount; i++)
                {
                    if (connection.ClaimInterface(_driver.Device.GetInterface(i), true))
                    {
                        Log.Debug(nameof(FtdiSerialDriver), "claimInterface " + i + " SUCCESS");
                    }
                    else
                    {
                        throw new UsbSerialException("Error claiming interface " + i);
                    }
                }
                Reset();
                opened = true;
            }
            finally
            {
                if (!opened)
                {
                    Close();
                    _connection = null;
                }
            }
        }
Exemple #9
0
        public override Task ClaimInterface()
        {
            Logger.LogInformation("Claimed interface {interfaceId}", InterfaceNumber);

            return(!_UsbDeviceConnection.ClaimInterface(UsbInterface, true)
                ? throw new DeviceException("could not claim interface")
                : Task.FromResult(true));
        }
        public override void Open(UsbDeviceConnection connection)
        {
            if (_connection != null)
            {
                throw new UsbSerialException("Already opened.");
            }

            _connection = connection;
            bool opened = false;

            try
            {
                for (int i = 0; i < _driver.Device.InterfaceCount; i++)
                {
                    UsbInterface usbIface = _driver.Device.GetInterface(i);
                    Log.Debug(nameof(Ch34xSerialDriver),
                              _connection.ClaimInterface(usbIface, true)
                            ? $"claimInterface {i} SUCCESS"
                            : $"claimInterface {i} FAIL");
                }

                UsbInterface dataIface = _driver.Device.GetInterface(_driver.Device.InterfaceCount - 1);
                for (int i = 0; i < dataIface.EndpointCount; i++)
                {
                    UsbEndpoint ep = dataIface.GetEndpoint(i);
                    if (ep.Type.IsEqualTo(ExtendedUsbConstants.USB_ENDPOINT_XFER_BULK))
                    {
                        if (ep.Direction.IsEqualTo(ExtendedUsbConstants.USB_DIR_IN))
                        {
                            _readEndpoint = ep;
                        }
                        else
                        {
                            _writeEndpoint = ep;
                        }
                    }
                }

                Initialize();
                BaudRate = DEFAULT_BAUD_RATE;

                opened = true;
            }
            finally
            {
                if (!opened)
                {
                    try
                    {
                        Close();
                    }
                    catch (UsbSerialException)
                    {
                        //Swallowing this exception for now
                    }
                }
            }
        }
        public override void Open(UsbDeviceConnection connection)
        {
            if (_connection != null)
            {
                throw new UsbSerialException("Already opened.");
            }

            _connection = connection;
            bool opened = false;

            try
            {
                for (int i = 0; i < _driver.Device.InterfaceCount; i++)
                {
                    UsbInterface usbIface = _driver.Device.GetInterface(i);
                    Log.Debug(nameof(Cp21xxSerialDriver),
                              _connection.ClaimInterface(usbIface, true)
                            ? $"claimInterface {i} SUCCESS"
                            : $"claimInterface {i} FAIL");
                }

                UsbInterface dataIface = _driver.Device.GetInterface(_driver.Device.InterfaceCount - 1);
                for (int i = 0; i < dataIface.EndpointCount; i++)
                {
                    UsbEndpoint ep = dataIface.GetEndpoint(i);
                    if (ep.Type.IsEqualTo(ExtendedUsbConstants.USB_ENDPOINT_XFER_BULK))
                    {
                        if (ep.Direction.IsEqualTo(ExtendedUsbConstants.USB_DIR_IN))
                        {
                            _readEndpoint = ep;
                        }
                        else
                        {
                            _writeEndpoint = ep;
                        }
                    }
                }

                SetConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
                SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
                SetConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
                opened = true;
            }
            finally
            {
                if (!opened)
                {
                    try
                    {
                        Close();
                    }
                    catch (UsbSerialException)
                    {
                        //Swallowing this exception for now
                    }
                }
            }
        }
        public override Task ClaimInterface()
        {
            if (!_UsbDeviceConnection.ClaimInterface(UsbInterface, true))
            {
                throw new Exception("could not claim interface");
            }

            return(Task.FromResult(true));
        }
        public async Task <bool> OpenAsync()
        {
            if (connected)
            {
                return(false);
            }

            //usbManager.RequestPermission(usbDevice, PendingIntent.GetBroadcast(ConnectionService.Instance.Context, 0, new Intent(ConnectionService.Instance.ActionUsbPermission), PendingIntentFlags.CancelCurrent));

            UsbInterface intf = usbDevice.GetInterface(0);

            pinReportEndpoint          = intf.GetEndpoint(0);
            peripheralResponseEndpoint = intf.GetEndpoint(1);
            pinConfigEndpoint          = intf.GetEndpoint(2);
            peripheralConfigEndpoint   = intf.GetEndpoint(3);
            connection = usbManager.OpenDevice(usbDevice);
            if (connection != null)
            {
                bool intfClaimed = connection.ClaimInterface(intf, true);
                if (intfClaimed)
                {
                    connected = true;

                    pinListenerThread = new Thread(
                        () =>
                    {
                        byte[] data = new byte[64];
                        pinListenerThreadRunning = true;
                        while (pinListenerThreadRunning)
                        {
                            int res =
                                connection.BulkTransfer(pinReportEndpoint, data, 41,
                                                        100); // pin reports are 41 bytes long now
                            if (res > 0)
                            {
                                this.PinEventDataReceived?.Invoke(data);
                            }
                        }
                    });

                    pinListenerThread.Start();
                    return(true);
                }
            }
            return(false);
        }
Exemple #14
0
        /// <summary>
        ///
        /// </summary>
        public virtual void OpenDevice(UsbDevice device)
        {
            //
            if ((m_UsbIntf = FindInterface(device)) == null)
            {
                Log.e("UsbStream", "Can't find the UsbInterface" + device.ToString() + ".");
                OnOpenFailure();
                return;
            }
            //
            m_UsbConnection = m_UsbMgr.OpenDevice(m_UsbDevice = device);
            m_UsbConnection.ClaimInterface(m_UsbIntf, true);
            //
            m_UsbReqIn = new UsbRequest();
            m_UsbReqIn.Initialize(m_UsbConnection, m_UsbIntf.intIn);

            // Check read buffer size.
            if (m_SizeRead == -1)
            {
                Log.i("UsbStream", "Use default read buffer size:" + (m_SizeRead = 64).ToString());
            }

#if USB_HANDLER_IN_UNITY
            //
            m_UsbBufferIn = ByteBuffer.Allocate(m_SizeRead);
            //
            m_ReadThread = new NativeThread(ReadThread_Step); //Looper
            m_ReadThread.StartLoop();                         //
#elif USB_HANDLER_IN_ANDROID
            AndroidJavaObject handler = new AndroidJavaObject
                                            ("android.unity.SafeUsbHandler", m_UsbConnection.m_SealedPtr, m_UsbReqIn.m_SealedPtr, m_SizeRead);
            handler.Call("setCallback", new CallbackProxy(this));
            m_ReadThread = new NativeThread(handler);
            m_ReadThread.Start2();
#endif
            //
            UsbManager.main.onUsbDeviceDetached += OnUsbDeviceDetached;
            if (m_OpenCallback != null)
            {
                m_OpenCallback.OnStreamOpenSuccess(this);
            }
            //
            m_IsOpen = true;
        }
        public override void Open(UsbDeviceConnection connection)
        {
            _connection = connection;

            var intf = _device.GetInterface(0);

            if (!connection.ClaimInterface(intf, true))
            {
                throw new Exception("Could not claim control interface.");
            }

            if (intf.EndpointCount > 1)
            {
                _writeEndpoint = intf.GetEndpoint(1);
            }

            _readEndpoint = intf.GetEndpoint(0);
            _buffer       = new byte[_readEndpoint.MaxPacketSize];
        }
        public void Start()
        {
            _usbConnection = _usbManager.OpenDevice(_usbDevice);
            if (_usbConnection == null)
            {
                throw new NullReferenceException("connection");
            }

            _usbInterface = _usbDevice.GetInterface(1);

            if (!_usbConnection.ClaimInterface(_usbInterface, true))
            {
                throw new Exception("claim interface");
            }

            _usbWriteEndpoint = _usbInterface.GetEndpoint(0);
            _usbReadEndpoint  = _usbInterface.GetEndpoint(1);

            ScanNetworks();
        }
        /**
         * 打开设备
         */
        private int openDevice()
        {
            int err = 0;

            if (myInterface != null)
            {
                UsbDeviceConnection conn = null;
                // 在open前判断是否有连接权限;对于连接权限可以静态分配,也可以动态分配权限,可以查阅相关资料
                // conn = myUsbManager.OpenDevice(myUsbDevice);
                if (myUsbManager.HasPermission(myUsbDevice))
                {
                    conn = myUsbManager.OpenDevice(myUsbDevice);
                }
                else
                {
                    err = (int)PrintError.NoPermission;
                    Log.Debug("err", "没有连接权限");
                    return(err);
                }

                if (conn.ClaimInterface(myInterface, true))
                {
                    myDeviceConnection = conn; // 到此你的android设备已经连上HID设备
                    Log.Debug("info", "连接HID设备成功");
                    err = 1;
                    return(err);
                }
                else
                {
                    err = (int)PrintError.ConnectedFailure;
                    Log.Debug("err", "连接HID设备失败");
                    conn.Close();
                    return(err);
                }
            }
            else
            {
                err = (int)PrintError.Error;
                return(err);
            }
        }
Exemple #18
0
        public void Start()
        {
            var manager = (UsbManager)Application.Context.GetSystemService(Context.UsbService);

            _connection = manager.OpenDevice(_device);
            var claimed = _connection.ClaimInterface(_interface, true);

            if (!claimed)
            {
                throw new Exception("Interface could not be claimed");
            }

            var rawDescriptors = _connection.GetRawDescriptors();

            Descriptor = new CcidDescriptor(rawDescriptors);

            if (SupportsInterrupt)
            {
                _interruptListenerThread = new Thread(StartListeningOnInterruptEndpoint);
                _interruptListenerThread.Start();
            }
        }
Exemple #19
0
        public void Load(string devicePath)
        {
            Manager = (UsbManager)context.GetSystemService(Context.UsbService);
            IDictionary <String, UsbDevice> deviceList = Manager.DeviceList;

            DeviceList = deviceList.Values;
            try
            {
                foreach (UsbDevice device in DeviceList)
                {
                    if (device.DeviceName == devicePath)
                    {
                        if (Manager.HasPermission(device))
                        {
                            Connected     = true;
                            NativeDevice  = device;
                            Connection    = Manager.OpenDevice(NativeDevice);
                            Endpoint      = NativeDevice.GetInterface(0).GetEndpoint(0);
                            EndpointWrite = NativeDevice.GetInterface(0).GetEndpoint(1);
                            Connection.ClaimInterface(NativeDevice.GetInterface(0), true);
                        }
                        else
                        {
                            if (LoadReattempt)
                            {
                                LoadReattempt = false;
                                bool Granted = MainActivity.Instance.RequestUSBPermissions(Manager, device, Main);
                                Load(devicePath);
                            }
                            LoadReattempt = true;
                        }
                    }
                }
            }
            catch
            {
            }
        }
Exemple #20
0
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already opened.");
                }

                mConnection = connection;
                bool opened = false;
                bool controlInterfaceFound = false;

                try
                {
                    for (var i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        mControlInterface = mDevice.GetInterface(i);
                        if (mControlInterface.InterfaceClass == UsbClass.Comm)
                        {
                            if (!mConnection.ClaimInterface(mControlInterface, true))
                            {
                                throw new IOException("Could not claim control interface");
                            }
                            (Driver as STM32SerialDriver).mCtrlInterf = i;
                            controlInterfaceFound = true;
                            break;
                        }
                    }
                    if (!controlInterfaceFound)
                    {
                        throw new IOException("Could not claim control interface");
                    }
                    for (var i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        mDataInterface = mDevice.GetInterface(i);
                        if (mDataInterface.InterfaceClass == UsbClass.CdcData)
                        {
                            if (!mConnection.ClaimInterface(mDataInterface, true))
                            {
                                throw new IOException("Could not claim data interface");
                            }

                            for (int j = 0; j < mDataInterface.EndpointCount; ++j)
                            {
                                UsbEndpoint ep = mDataInterface.GetEndpoint(j);
                                if ((ep.Direction == UsbAddressing.In) &&
                                    (ep.Type == UsbAddressing.XferBulk))
                                {
                                    Log.Debug(TAG, "Found reading endpoint");
                                    mReadEndpoint = ep;
                                }
                                else if ((ep.Direction == UsbAddressing.Out) &&
                                         (ep.Type == UsbAddressing.XferBulk))
                                {
                                    Log.Debug(TAG, "Found writing endpoint");
                                    mWriteEndpoint = ep;
                                }
                            }


                            //mReadEndpoint = mDataInterface.GetEndpoint(1);
                            //mWriteEndpoint = mDataInterface.GetEndpoint(0);
                            //mReadEndpoint = mDataInterface.GetEndpoint(0);
                            //mWriteEndpoint = mDataInterface.GetEndpoint(1);
                            opened = true;
                            break;
                        }
                    }
                    if (!opened)
                    {
                        throw new IOException("Could not claim data interface.");
                    }
                }
                finally
                {
                    if (!opened)
                    {
                        mConnection = null;
                    }
                }
            }
        public override void Open(UsbDeviceConnection connection)
        {
            if (Connection != null)
            {
                throw new IOException("Already open");
            }

            Connection = connection;

            UsbInterface usbInterface = Device.GetInterface(0);

            if (!connection.ClaimInterface(usbInterface, true))
            {
                throw new IOException("Error claiming Prolific interface 0");
            }

            var opened = false;

            try
            {
                for (int i = 0; i < usbInterface.EndpointCount; ++i)
                {
                    UsbEndpoint currentEndpoint = usbInterface.GetEndpoint(i);

                    switch (currentEndpoint.Address)
                    {
                    case READ_ENDPOINT:
                        mReadEndpoint = currentEndpoint;
                        break;

                    case WRITE_ENDPOINT:
                        mWriteEndpoint = currentEndpoint;
                        break;

                    case INTERRUPT_ENDPOINT:
                        mInterruptEndpoint = currentEndpoint;
                        break;
                    }
                }

                if (Device.DeviceClass == (UsbClass)0x02)
                {
                    mDeviceType = DEVICE_TYPE_0;
                }
                else
                {
                    if ((Device.DeviceClass == 0x00) ||
                        (Device.DeviceClass == (UsbClass)0xff))
                    {
                        mDeviceType = DEVICE_TYPE_1;
                    }
                    else
                    {
                        mDeviceType = DEVICE_TYPE_HX;
                    }
                }

                SetControlLines(mControlLinesValue);

                DoBlackMagic();
                ResetDevice();
                opened = true;
            }
            finally
            {
                if (!opened)
                {
                    Connection = null;
                    connection.ReleaseInterface(usbInterface);
                }
            }
        }
Exemple #22
0
        public void SetDevice(Intent intent, UsbDevice usbDevice)
        {
            int packetSize = 0;

            IsReading = true;

            if (usbDevice != null && intent.GetBooleanExtra(UsbManager.ExtraPermissionGranted, false))
            {
                connection = mUsbManager.OpenDevice(usbDevice);

                intf = usbDevice.GetInterface(0);
                if (null == connection)
                {
                    Log.Debug("DEBUG", "unable to establish connection)\n");
                }
                else
                {
                    connection.ClaimInterface(intf, true);
                }

                try
                {
                    if (UsbAddressing.DirMask == intf.GetEndpoint(0).Direction)
                    {
                        endPointRead = intf.GetEndpoint(0);
                        packetSize   = endPointRead.MaxPacketSize;
                    }
                    else
                    {
                        Log.Debug("####### DEBUG #######", "######### Cagou geral !!! ############");
                    }
                }
                catch (Exception e)
                {
                    Log.Debug("endPointWrite", "Device have no endPointRead" + e);
                }

                var cancellationTokenSource = new CancellationTokenSource();


                new Thread(new ThreadStart(delegate
                {
                    try
                    {
                        if (connection != null && endPointRead != null)
                        {
                            while (IsReading)
                            {
                                byte[] buffer = new byte[packetSize];
                                int status    = connection.BulkTransfer(endPointRead, buffer, packetSize, 100);
                                if (status > 0)
                                {
                                    var count = bufferReaded.Count(x => x != 0x00);
                                    Buffer.BlockCopy(buffer, 0, bufferReaded, count, buffer.Length);
                                    Log.Debug("####### DEBUG #######", "COPIEEEI!");
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Debug(TAG, "Error in receive thread" + e.Message);
                    }
                })).Start();

                //usbThreadDataReceiver = Task.Factory.StartNew(a =>
                //{
                //    try
                //    {
                //        if (connection != null && endPointRead != null)
                //        {
                //            while (IsReading)
                //            {
                //                byte[] buffer = new byte[packetSize];
                //                int status = connection.BulkTransfer(endPointRead, buffer, packetSize, 100);
                //                if (status > 0)
                //                {
                //                    var count = bufferReaded.Count(x => x != 0x00);
                //                    Buffer.BlockCopy(buffer, 0, bufferReaded, count, buffer.Length);
                //                }
                //            }
                //        }
                //    }
                //    catch (Exception e)
                //    {
                //        Log.Debug(TAG, "Error in receive thread" + e.Message);
                //    }

                //}, TaskCreationOptions.LongRunning, cancellationTokenSource.Token );

                new Thread(new ThreadStart(delegate
                {
                    try
                    {
                        while (IsReading)
                        {
                            if (bufferReaded.Count(x => x != 0x00) > 150)
                            {
                                int n = 0;
                                while ((bufferReaded[bufferReaded.Count(x => x != 0x00) - 2] != 0x7c) && (bufferReaded[bufferReaded.Count(x => x != 0x00) - 1] != 0x41))
                                {
                                    if (bufferReaded.Count(x => x != 0x00) >= 255)
                                    {
                                        Array.Clear(bufferReaded, 0, bufferReaded.Length);
                                        break;
                                    }
                                }
                                var count = bufferReaded.Count(x => x != 0x00);

                                StringBuilder stringBuilder = new StringBuilder();
                                int i = 0;

                                for (; i < bufferReaded.Length && bufferReaded[i] != 0; i++)
                                {
                                    stringBuilder.Append(Convert.ToString((char)bufferReaded[i]));
                                }
                                Array.Clear(bufferReaded, 0, bufferReaded.Length);

                                //Task.Factory.StartNew(() =>
                                //{
                                OnUsbDataReceiver?.Invoke(new object(), stringBuilder.ToString());
                                Log.Debug("####### DEBUG #######", stringBuilder.ToString());
                                //}).ConfigureAwait(false);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Debug(TAG, "Error verify buffer" + e.Message);
                    }
                })).Start();

                //verificaPacoteLido = Task.Factory.StartNew(a =>
                //{
                //    try
                //    {
                //        while (IsReading)
                //        {
                //            if (bufferReaded.Count(x => x != 0x00) > 150)
                //            {
                //                int n = 0;
                //                while ((bufferReaded[bufferReaded.Count(x => x != 0x00) - 2] != 0x7c) && (bufferReaded[bufferReaded.Count(x => x != 0x00) - 1] != 0x41))
                //                {
                //                    if (bufferReaded.Count(x => x != 0x00) >= 255)
                //                    {
                //                        Array.Clear(bufferReaded, 0, bufferReaded.Length);
                //                        break;
                //                    }
                //                }
                //                var count = bufferReaded.Count(x => x != 0x00);

                //                StringBuilder stringBuilder = new StringBuilder();
                //                int i = 0;

                //                for (; i < bufferReaded.Length && bufferReaded[i] != 0; i++)
                //                {
                //                    stringBuilder.Append(Convert.ToString((char)bufferReaded[i]));
                //                }
                //                Array.Clear(bufferReaded, 0, bufferReaded.Length);

                //                //Task.Factory.StartNew(() =>
                //                //{
                //                //OnUsbDataReceiver?.Invoke(new object(), stringBuilder.ToString());
                //                Log.Debug("####### DEBUG #######", stringBuilder.ToString());
                //                //}).ConfigureAwait(false);

                //            }
                //        }
                //    }
                //    catch (Exception e)
                //    {
                //        Log.Debug(TAG, "Error verify buffer" + e.Message);
                //    }

                //}, TaskCreationOptions.LongRunning, cancellationTokenSource.Token);
            }
        }
        public async Task InitializeAsync()
        {
            if (_IsInitializing)
            {
                return;
            }

            _IsInitializing = true;

            try
            {
                var isPermissionGranted = await RequestPermissionAsync();

                if (!isPermissionGranted.HasValue)
                {
                    throw new Exception("User did not respond to permission request");
                }

                if (!isPermissionGranted.Value)
                {
                    throw new Exception("The user did not give the permission to access the device");
                }

                var usbInterface = _UsbDevice.GetInterface(0);

                //TODO: This selection stuff needs to be moved up higher. The contructor should take these arguments
                for (var i = 0; i < usbInterface.EndpointCount; i++)
                {
                    var ep = usbInterface.GetEndpoint(i);
                    if (_ReadEndpoint == null && ep.Type == UsbAddressing.XferInterrupt && ep.Address == (UsbAddressing)129)
                    {
                        _ReadEndpoint = ep;
                        continue;
                    }

                    if (_WriteEndpoint == null && ep.Type == UsbAddressing.XferInterrupt && (ep.Address == (UsbAddressing)1 || ep.Address == (UsbAddressing)2))
                    {
                        _WriteEndpoint = ep;
                    }
                }

                //TODO: This is a bit of a guess. It only kicks in if the previous code fails. This needs to be reworked for different devices
                if (_ReadEndpoint == null)
                {
                    _ReadEndpoint = usbInterface.GetEndpoint(0);
                }

                if (_WriteEndpoint == null)
                {
                    _WriteEndpoint = usbInterface.GetEndpoint(1);
                }

                if (_ReadEndpoint.MaxPacketSize != ReadBufferLength)
                {
                    throw new Exception("Wrong packet size for read endpoint");
                }

                if (_WriteEndpoint.MaxPacketSize != ReadBufferLength)
                {
                    throw new Exception("Wrong packet size for write endpoint");
                }

                _UsbDeviceConnection = UsbManager.OpenDevice(_UsbDevice);

                if (_UsbDeviceConnection == null)
                {
                    throw new Exception("could not open connection");
                }

                if (!_UsbDeviceConnection.ClaimInterface(usbInterface, true))
                {
                    throw new Exception("could not claim interface");
                }

                Logger.Log("Hid device initialized. About to tell everyone.", null, LogSection);

                IsInitialized = true;

                Connected?.Invoke(this, new EventArgs());

                return;
            }
            catch (Exception ex)
            {
                Logger.Log("Error initializing Hid Device", ex, LogSection);
            }

            _IsInitializing = false;
        }
Exemple #24
0
        public override void Open(UsbDeviceConnection connection)
        {
            if (_connection != null)
            {
                throw new UsbSerialException("Already open");
            }

            UsbInterface usbInterface = _driver.Device.GetInterface(0);

            if (!connection.ClaimInterface(usbInterface, true))
            {
                throw new UsbSerialException("Error claiming Prolific interface 0");
            }

            _connection = connection;
            bool opened = false;

            try
            {
                for (int i = 0; i < usbInterface.EndpointCount; ++i)
                {
                    UsbEndpoint currentEndpoint = usbInterface.GetEndpoint(i);

                    if (currentEndpoint.Address.IsEqualTo(READ_ENDPOINT))
                    {
                        _readEndpoint = currentEndpoint;
                    }
                    else if (currentEndpoint.Address.IsEqualTo(WRITE_ENDPOINT))
                    {
                        _writeEndpoint = currentEndpoint;
                    }
                    else if (currentEndpoint.Address.IsEqualTo(INTERRUPT_ENDPOINT))
                    {
                        _interruptEndpoint = currentEndpoint;
                    }
                }

                if ((int)_driver.Device.DeviceClass == 0x02)
                {
                    _deviceType = DEVICE_TYPE_0;
                }
                else
                {
                    try
                    {
                        byte[] rawDescriptors = _connection.GetRawDescriptors();
                        byte   maxPacketSize0 = rawDescriptors[7];
                        if (maxPacketSize0 == 64)
                        {
                            _deviceType = DEVICE_TYPE_HX;
                        }
                        else if ((_driver.Device.DeviceClass == 0x00) || ((int)_driver.Device.DeviceClass == 0xff))
                        {
                            _deviceType = DEVICE_TYPE_1;
                        }
                        else
                        {
                            Log.Warn(nameof(ProlificSerialDriver), "Could not detect PL2303 subtype, " + "Assuming that it is a HX device");
                            _deviceType = DEVICE_TYPE_HX;
                        }
                    }
                    catch (NoSuchMethodException)
                    {
                        Log.Warn(nameof(ProlificSerialDriver), "Method UsbDeviceConnection.getRawDescriptors, " + "required for PL2303 subtype detection, not " + "available! Assuming that it is a HX device");
                        _deviceType = DEVICE_TYPE_HX;
                    }
                    catch (Exception e)
                    {
                        Log.Warn(nameof(ProlificSerialDriver), "An unexpected exception occured while trying " + "to detect PL2303 subtype", e);
                    }
                }

                ControlLines = _controlLinesValue;
                ResetDevice();

                PerformInitializationSequence();
                opened = true;
            }
            finally
            {
                if (!opened)
                {
                    _connection = null;
                    connection.ReleaseInterface(usbInterface);
                }
            }
        }
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already opened.");
                }

                mConnection = connection;
                Boolean opened = false;

                try
                {
                    for (int i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        UsbInterface usbIface = mDevice.GetInterface(i);
                        if (mConnection.ClaimInterface(usbIface, true))
                        {
                            Log.Debug(TAG, "claimInterface " + i + " SUCCESS");
                        }
                        else
                        {
                            Log.Debug(TAG, "claimInterface " + i + " FAIL");
                        }
                    }

                    UsbInterface dataIface = mDevice.GetInterface(mDevice.InterfaceCount - 1);
                    for (int i = 0; i < dataIface.EndpointCount; i++)
                    {
                        UsbEndpoint ep = dataIface.GetEndpoint(i);
                        if (ep.Type == (UsbAddressing)UsbSupport.UsbEndpointXferBulk)
                        {
                            if (ep.Direction == (UsbAddressing)UsbSupport.UsbDirIn)
                            {
                                mReadEndpoint = ep;
                            }
                            else
                            {
                                mWriteEndpoint = ep;
                            }
                        }
                    }


                    Initialize();
                    SetBaudRate(DEFAULT_BAUD_RATE);

                    opened = true;
                }
                finally
                {
                    if (!opened)
                    {
                        try
                        {
                            Close();
                        }
                        catch (IOException e)
                        {
                            // Ignore IOExceptions during close()
                        }
                    }
                }
            }
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already open");
                }

                UsbInterface usbInterface = mDevice.GetInterface(0);

                if (!connection.ClaimInterface(usbInterface, true))
                {
                    throw new IOException("Error claiming Prolific interface 0");
                }
                mConnection = connection;
                Boolean opened = false;

                try
                {
                    for (int i = 0; i < usbInterface.EndpointCount; ++i)
                    {
                        UsbEndpoint currentEndpoint = usbInterface.GetEndpoint(i);

                        switch (currentEndpoint.Address)
                        {
                        case (UsbAddressing)READ_ENDPOINT:
                            mReadEndpoint = currentEndpoint;
                            break;

                        case (UsbAddressing)WRITE_ENDPOINT:
                            mWriteEndpoint = currentEndpoint;
                            break;

                        case (UsbAddressing)INTERRUPT_ENDPOINT:
                            mInterruptEndpoint = currentEndpoint;
                            break;
                        }
                    }

                    if (mDevice.DeviceClass == (UsbClass)0x02)
                    {
                        mDeviceType = DEVICE_TYPE_0;
                    }
                    else
                    {
                        try
                        {
                            //Method getRawDescriptorsMethod
                            //    = mConnection.getClass().getMethod("getRawDescriptors");
                            //byte[] rawDescriptors
                            //    = (byte[])getRawDescriptorsMethod.invoke(mConnection);

                            byte[] rawDescriptors = mConnection.GetRawDescriptors();

                            byte maxPacketSize0 = rawDescriptors[7];
                            if (maxPacketSize0 == 64)
                            {
                                mDeviceType = DEVICE_TYPE_HX;
                            }
                            else if ((mDevice.DeviceClass == 0x00) ||
                                     (mDevice.DeviceClass == (UsbClass)0xff))
                            {
                                mDeviceType = DEVICE_TYPE_1;
                            }
                            else
                            {
                                Log.Warn(TAG, "Could not detect PL2303 subtype, "
                                         + "Assuming that it is a HX device");
                                mDeviceType = DEVICE_TYPE_HX;
                            }
                        }
                        catch (NoSuchMethodException e)
                        {
                            Log.Warn(TAG, "Method UsbDeviceConnection.getRawDescriptors, "
                                     + "required for PL2303 subtype detection, not "
                                     + "available! Assuming that it is a HX device");
                            mDeviceType = DEVICE_TYPE_HX;
                        }
                        catch (Exception e)
                        {
                            Log.Error(TAG, "An unexpected exception occured while trying "
                                      + "to detect PL2303 subtype", e);
                        }
                    }

                    SetControlLines(mControlLinesValue);
                    ResetDevice();

                    DoBlackMagic();
                    opened = true;
                }
                finally
                {
                    if (!opened)
                    {
                        mConnection = null;
                        connection.ReleaseInterface(usbInterface);
                    }
                }
            }
Exemple #27
0
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already opened.");
                }

                mConnection = connection;
                Boolean opened = false;

                try
                {
                    for (int i = 0; i < mDevice.InterfaceCount; i++)
                    {
                        UsbInterface usbIface = mDevice.GetInterface(i);
                        if (mConnection.ClaimInterface(usbIface, true))
                        {
                            Log.Debug(TAG, $"claimInterface {i} SUCCESS");
                        }
                        else
                        {
                            Log.Debug(TAG, $"claimInterface {i} FAIL");
                        }
                    }

                    UsbInterface dataIface = mDevice.GetInterface(mDevice.InterfaceCount - 1);
                    for (int i = 0; i < dataIface.EndpointCount; i++)
                    {
                        UsbEndpoint ep = dataIface.GetEndpoint(i);
                        if (ep.Type == (UsbAddressing)UsbSupport.UsbEndpointXferBulk)
                        {
                            if (ep.Direction == (UsbAddressing)UsbSupport.UsbDirIn)
                            {
                                mReadEndpoint = ep;
                            }
                            else
                            {
                                mWriteEndpoint = ep;
                            }
                        }
                    }

                    SetConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE);
                    SetConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, MCR_ALL | CONTROL_WRITE_DTR | CONTROL_WRITE_RTS);
                    SetConfigSingle(SILABSER_SET_BAUDDIV_REQUEST_CODE, BAUD_RATE_GEN_FREQ / DEFAULT_BAUD_RATE);
                    //            setParameters(DEFAULT_BAUD_RATE, DEFAULT_DATA_BITS, DEFAULT_STOP_BITS, DEFAULT_PARITY);
                    opened = true;
                }
                finally
                {
                    if (!opened)
                    {
                        try
                        {
                            Close();
                        }
                        catch (IOException e)
                        {
                            // Ignore IOExceptions during close()
                        }
                    }
                }
            }