示例#1
0
 public void Dispose()
 {
     if (NativeDevice != null)
     {
         NativeDevice.Dispose();
         NativeDevice = null;
     }
     if (Connection != null)
     {
         Connection.Dispose();
         Connection = null;
     }
     if (Endpoint != null)
     {
         Endpoint.Dispose();
         Endpoint = null;
     }
     if (EndpointWrite != null)
     {
         EndpointWrite.Dispose();
         EndpointWrite = null;
     }
     if (Manager != null)
     {
         Manager.Dispose();
         Manager = null;
     }
 }
示例#2
0
 public CH34xSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) : base(device, connection)
 {
     hexData       = new HexData();
     rtsCtsEnabled = false;
     dtrDsrEnabled = false;
     mInterface    = device.GetInterface(iface >= 0 ? iface : 0);
 }
        public void Close()
        {
            if (_IsClosing)
            {
                return;
            }
            _IsClosing = true;

            try
            {
                _UsbDeviceConnection?.Dispose();
                _UsbDevice?.Dispose();
                ReadUsbInterface?.Dispose();
                WriteUsbInterface?.Dispose();

                _UsbDeviceConnection = null;
                _UsbDevice           = null;
                ReadUsbInterface     = null;
                WriteUsbInterface    = null;
            }
            catch (Exception)
            {
                //TODO: Logging
            }

            _IsClosing = false;
        }
示例#4
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;
                }
            }
        }
示例#5
0
        public static UsbSerialDevice CreateUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
        {
            /*
             * It checks given vid and pid and will return a custom driver or a CDC serial driver.
             * When CDC is returned open() method is even more important, its response will inform about if it can be really
             * opened as a serial device with a generic CDC serial driver
             */
            int vid = device.VendorId;
            int pid = device.ProductId;

            if (FTDISioIds.IsDeviceSupported(vid, pid))
            {
                return(new FTDISerialDevice(device, connection, iface));
            }
            else if (CP210xIds.IsDeviceSupported(vid, pid))
            {
                return(new CP2102SerialDevice(device, connection, iface));
            }
            else if (PL2303Ids.IsDeviceSupported(vid, pid))
            {
                return(new PL2303SerialDevice(device, connection, iface));
            }
            else if (CH34xIds.IsDeviceSupported(vid, pid))
            {
                return(new CH34xSerialDevice(device, connection, iface));
            }
            else if (IsCdcDevice(device))
            {
                return(new CDCSerialDevice(device, connection, iface));
            }
            else
            {
                return(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;
                    }
                }
            }
示例#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;
                }
            }
        }
示例#8
0
 public UsbSerialDevice(UsbDevice device, UsbDeviceConnection connection)
 {
     this.device     = device;
     this.connection = connection;
     this.asyncMode  = true;
     serialBuffer    = new SerialBuffer(mr1Version);
 }
示例#9
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);
        }
示例#10
0
        /// <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);
        }
示例#11
0
        private async Task CheckForDeviceAsync()
        {
            var devices = UsbManager.DeviceList.Select(kvp => kvp.Value).ToList();

            Logger.Log($"Connected devices: {(string.Join(",", devices.Select(d => d.VendorId)))}.", null, LogSection);

            _UsbDevice?.Dispose();
            _UsbDevice = devices.FirstOrDefault(d => d.VendorId == VendorId && d.ProductId == ProductId);

            if (_UsbDevice != null)
            {
                if (_UsbDeviceConnection == null)
                {
                    Logger.Log($"Initializing Android Hid device", null, LogSection);
                    await InitializeAsync();
                }
            }
            else
            {
                var wasConnected = _UsbDeviceConnection != null;
                _UsbDeviceConnection?.Dispose();
                _UsbDeviceConnection = null;
                if (wasConnected)
                {
                    Disconnected?.Invoke(this, new EventArgs());
                }
            }
        }
示例#12
0
        /**
         * 打开设备
         */
        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();
                }
            }
        }
        private void WireupUsb(IUsbSerialDriver device)
        {
            UsbManager manager = (UsbManager)GetSystemService(UsbService);

            var port1 = device.Ports[0];

            UsbDeviceConnection connection = manager.OpenDevice(device.Device);

            port1.Open(connection);
            port1.SetParameters(115200, DataBits._8, StopBits._1, Parity.None);

            var buffer = new byte[500];

            Log.Debug("main", "here");

            var timeout = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;

            port1.CtsChanged += Port1_CtsChanged;
            port1.Rts         = true;

            while (true)
            {
                var bytesRead = port1.Read(buffer, timeout);
                if (bytesRead > 0)
                {
                    var str = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Log.Debug("card read", str);
                }
                Thread.Sleep(50);
            }
        }
示例#14
0
        public async Task <bool> Open(int baudRate)
        {
            Console.WriteLine("Getting permission");
            var perm = await usbManager.RequestPermissionAsync(port.Driver.Device, ctx);

            if (perm)
            {
                try {
                    conn = usbManager.OpenDevice(port.Driver.Device);
                    port.Open(conn);
                    port.SetParameters(baudRate, 8, StopBits.One, Parity.None);
                    port.SetDTR(true);

                    new Handler(Looper.MainLooper).Post(() => {
                        Toast.MakeText(ctx, "Serial connected", ToastLength.Short).Show();
                    });
                } catch (Java.IO.IOException) {
                    // TODO: Handle this
                    throw;
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
        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;
                    }
                }
            }
 /// <summary>
 /// 释放连接
 /// </summary>
 public void Close()
 {
     if (myDeviceConnection != null)
     {
         myDeviceConnection.Close();
         myDeviceConnection = null;
     }
 }
        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 UsbDataBinder(UsbManager manager, UsbDevice device)
 {
     // TODO Auto-generated constructor stub
     mUsbManager = manager;
     mDevice     = device;
     mIntf       = mDevice.GetInterface(0);
     mEndpoint   = mIntf.GetEndpoint(0);
     mConnection = mUsbManager.OpenDevice(mDevice);
 }
示例#21
0
        public PL2303SerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) : base(device, connection)
        {
            hexData = new HexData();
            if (iface > 1)
            {
                throw new ArgumentException("Multi-interface PL2303 devices not supported!");
            }

            mInterface = device.GetInterface(iface >= 0 ? iface : 0);
        }
示例#22
0
 public FTDISerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) : base(device, connection)
 {
     ftdiUtilities = new FTDIUtilities(this);
     rtsCtsEnabled = false;
     dtrDsrEnabled = false;
     ctsState      = true;
     dsrState      = true;
     firstTime     = true;
     mInterface    = device.GetInterface(iface >= 0 ? iface : 0);
 }
示例#23
0
 public void Close()
 {
     connection   = null;
     fd           = -1;
     usbdev       = null;
     usbIface     = null;
     ep_in        = null;
     ep_out       = null;
     max_pkt_size = 0;
 }
示例#24
0
 public ReadingRun(UsbDeviceConnection connection, UsbEndpoint readEndpoint, UsbEndpoint writeEndpoint, Handler handler, CancellationToken token, int channel = -1)
 {
     _connection    = connection;
     _readEndpoint  = readEndpoint;
     _writeEndpoint = writeEndpoint;
     _handler       = handler;
     _token         = token;
     _scanMode      = channel < 0;
     _channel       = !_scanMode ? channel : 0;
 }
示例#25
0
 private void getEndpoint(UsbDeviceConnection connection, UsbInterface intf)
 {
     if (intf.GetEndpoint(1) != null)
     {
         epOut = intf.GetEndpoint(1);
     }
     if (intf.GetEndpoint(0) != null)
     {
         epIn = intf.GetEndpoint(0);
     }
 }
示例#26
0
        public static UsbSpiDevice CreateUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface)
        {
            int vid = device.VendorId;
            int pid = device.ProductId;

            if (CP2130Ids.IsDeviceSupported(vid, pid))
            {
                return(new CP2130SpiDevice(device, connection, iface));
            }
            else
            {
                return(null);
            }
        }
示例#27
0
        /// <summary>
        /// The FindSerialPortDevice
        /// </summary>
        public void FindSerialPortDevice()
        {
            isFirstRun = false;
            // This snippet will try to open the first encountered usb device connected, excluding usb root hubs
            IDictionary <string, UsbDevice> usbDevices = usbManager.DeviceList;

            if (usbDevices.Count > 0)
            {
                bool keep = true;
                foreach (KeyValuePair <string, UsbDevice> entry in usbDevices)
                {
                    device = entry.Value;
                    int deviceVID = device.VendorId;
                    int devicePID = device.ProductId;

                    Android.Util.Log.Info("USB DEVICE CONNECTED", " VID: " + deviceVID + " PID: " + devicePID);
                    Android.Util.Log.Info("USB DEVICE CONNECTED", " VID: " + deviceVID.ToString("X2") + " PID: " + devicePID.ToString("X2"));

                    //if (deviceVID != 0x1d6b && (devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003) && deviceVID != 0x5c6 && devicePID != 0x904c)
                    if (deviceVID != 0x1d6b && devicePID != 0x0001 && devicePID != 0x0002 && devicePID != 0x0003)
                    {
                        // There is a device connected to our Android device. Try to open it as a Serial Port.
                        RequestUserPermission();
                        keep = false;
                    }
                    else
                    {
                        connection = null;
                        device     = null;
                    }

                    if (!keep)
                    {
                        break;
                    }
                }
                if (!keep)
                {
                    // There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
                    Intent intent = new Intent(ServiceConstants.ACTION_NO_USB);
                    SendBroadcast(intent);
                }
            }
            else
            {
                // There is no USB devices connected. Send an intent to MainActivity
                Intent intent = new Intent(ServiceConstants.ACTION_NO_USB);
                SendBroadcast(intent);
            }
        }
示例#28
0
        public void Stop()
        {
            _cts.Cancel();
            _cts = null;
            _handler.SendMessage(_handler.ObtainMessage((int)USBDeviceStatus.DeviceConnectionClosed));
            _usbReadEndpoint  = null;
            _usbWriteEndpoint = null;
            _usbConnection.Close();
            _usbInterface  = null;
            _usbConnection = null;
            _thread        = null;

            //Device.DataReceived -= Device_DataReceived;
            //Device.Dispose();
            //Device = null;
        }
示例#29
0
            public override void Open(UsbDeviceConnection connection)
            {
                if (mConnection != null)
                {
                    throw new IOException("Already open");
                }

                mConnection = connection;
                bool opened = false;

                try
                {
                    if (1 == mDevice.InterfaceCount)
                    {
                        Log.Debug(TAG, "device might be castrated ACM device, trying single interface logic");
                        OpenSingleInterface();
                    }
                    else
                    {
                        Log.Debug(TAG, "trying default interface logic");
                        openInterface();
                    }

                    if (mEnableAsyncReads)
                    {
                        Log.Debug(TAG, "Async reads enabled");
                    }
                    else
                    {
                        Log.Debug(TAG, "Async reads disabled.");
                    }


                    opened = true;
                }
                finally
                {
                    if (!opened)
                    {
                        mConnection = null;
                        // just to be on the save side
                        mControlEndpoint = null;
                        mReadEndpoint    = null;
                        mWriteEndpoint   = null;
                    }
                }
            }
示例#30
0
        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);
        }