コード例 #1
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;
        }
コード例 #2
0
        /// <summary>
        /// Requests temporary permission for the given package to access the device. 
        /// This may result in a system dialog being displayed to the user if permission had not already been granted.
        /// </summary>
        /// <returns>The observable sequence of permission values.</returns>
        /// <param name="manager">The UsbManager system service.</param>
        /// <param name="context">The Context to request the permission from.</param>
        /// <param name="device">The UsbDevice to request permission for.</param>
        public static IObservable<bool> PermissionRequested(this UsbManager manager, Context context, UsbDevice device)
        {
            return Observable.Create<bool> (observer => {
                var usbPermissionReceiver = new UsbDevicePermissionReceiver (observer, device);
                context.RegisterReceiver (usbPermissionReceiver, new IntentFilter (ACTION_USB_PERMISSION));

                var intent = PendingIntent.GetBroadcast (context, 0, new Intent (ACTION_USB_PERMISSION), 0);
                manager.RequestPermission (device, intent);

                return Disposable.Create (() => context.UnregisterReceiver (usbPermissionReceiver));
            });
        }
コード例 #3
0
 public UsbPermissionBroadcastReceiver(
     UsbManager manager,
     usbDevice device,
     Context context,
     IAndroidFactory androidFactory,
     ILogger logger = null)
 {
     _Manager        = manager ?? throw new ArgumentNullException(nameof(manager));
     _Device         = device ?? throw new ArgumentNullException(nameof(device));
     _Context        = context ?? throw new ArgumentNullException(nameof(context));
     _logger         = logger ?? NullLogger.Instance;
     _androidFactory = androidFactory;
 }
コード例 #4
0
        public UsbSerialDevice(UsbManager usbManager, UsbDevice usbDevice, UsbSerialDeviceID id, UsbSerialDeviceInfo info)
        {
            UsbManager = usbManager;
            UsbDevice = usbDevice;
            ID = id;
            Info = info;

            ConstructorInfo cInfo = Info.DriverType.GetConstructor(new Type[] { typeof(UsbManager), typeof(UsbDevice), typeof(int) });
            if (cInfo == null) {
                throw new InvalidProgramException ();
            }

            Ports = new UsbSerialPort[info.NumberOfPorts];
            for (int i = 0; i < Info.NumberOfPorts; i++) {
                Ports[i] = (UsbSerialPort)cInfo.Invoke(new object[] { UsbManager, UsbDevice, i });
            }
        }
コード例 #5
0
        public UsbSerialPort(UsbManager manager, UsbDevice device, int portNumber)
        {
            Baudrate = DefaultBaudrate;
            DataBits = DefaultDataBits;
            Parity = DefaultParity;
            StopBits = DefaultStopBits;

            UsbManager = manager;
            UsbDevice = device;
            mPortNumber = portNumber;

            mInternalReadBuffer = new byte[DEFAULT_INTERNAL_READ_BUFFER_SIZE];
            mTempReadBuffer = new byte[DEFAULT_TEMP_READ_BUFFER_SIZE];
            mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
            mReadBufferReadCursor = 0;
            mReadBufferWriteCursor = 0;
            mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
        }
コード例 #6
0
        public static ConnectedDeviceDefinition GetAndroidDeviceDefinition(usbDevice usbDevice)
        {
            if (usbDevice == null)
            {
                throw new ArgumentNullException(nameof(usbDevice));
            }

            var deviceId = usbDevice.DeviceId.ToString(AndroidUsbFactoryExtensions.IntParsingCulture);

            return(new ConnectedDeviceDefinition(
                       deviceId,
                       DeviceType.Usb,
                       //TODO: Put these back when it is safe to do so
                       //productName: usbDevice.ProductName,
                       //manufacturer: usbDevice.ManufacturerName,
                       //serialNumber: usbDevice.SerialNumber,
                       productId: (uint)usbDevice.ProductId,
                       vendorId: (uint)usbDevice.VendorId
                       ));
        }
コード例 #7
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);
        }
コード例 #8
0
        public sealed override void Dispose()
        {
            if (disposed)
            {
                Logger.LogWarning(Messages.WarningMessageAlreadyDisposed, DeviceNumberId);
                return;
            }

            disposed = true;

            Logger.LogInformation(Messages.InformationMessageDisposingDevice, DeviceNumberId);

            Close();

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

                _UsbDeviceConnection = null;
                _UsbDevice           = null;
                ReadUsbInterface     = null;
                WriteUsbInterface    = null;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Dispose error DeviceId: {deviceNumberId}", DeviceNumberId);
            }

            _InitializingSemaphoreSlim.Dispose();

            base.Dispose();

            GC.SuppressFinalize(this);
        }
 public ProlificSerialPort(UsbManager manager, UsbDevice device, int portNumber)
     : base(manager, device, portNumber)
 {
 }
コード例 #10
0
 public Cp21xxSerialPort(UsbManager manager, UsbDevice device, int portNumber)
     : base(manager, device, portNumber)
 {
 }
コード例 #11
0
 public UsbPermissionBroadcastReceiver(UsbManager manager, usbDevice device, Context context)
 {
     _Manager = manager;
     _Device  = device;
     _Context = context;
 }
 private UsbSerialDevice GetDevice(UsbManager usbManager, UsbDevice usbDevice, bool allowAnonymousCdcAcmDevices)
 {
     UsbSerialDeviceID id = new UsbSerialDeviceID(usbDevice.VendorId, usbDevice.ProductId);
     UsbSerialDeviceInfo info = FindDeviceInfo (id);
     if (info != null) {
         UsbSerialDevice device = new UsbSerialDevice(usbManager, usbDevice, id, info);
         return device;
     }
     else if (allowAnonymousCdcAcmDevices && usbDevice.DeviceClass == UsbClass.Comm)
     {
         UsbSerialDevice device = new UsbSerialDevice(usbManager, usbDevice, id, UsbSerialDeviceInfo.CdcAcm);
         return device;
     }
     return null;
 }
コード例 #13
0
        public async Task InitializeAsync(CancellationToken cancellationToken = default)
        {
            if (disposed)
            {
                throw new DeviceException(Messages.DeviceDisposedErrorMessage);
            }

            using var logScope = Logger.BeginScope("DeviceId: {deviceId} Call: {call}", DeviceNumberId, nameof(InitializeAsync));

            if (IsInitialized)
            {
                Logger.LogWarning("Device is already initialized...");
            }

            Logger.LogInformation("Attempting to initialize...");

            try
            {
                await Task.Run(async() =>
                {
                    Logger.LogTrace("Waiting for initialization lock ... {deviceId}", DeviceNumberId);

                    await _InitializingSemaphoreSlim.WaitAsync(cancellationToken).ConfigureAwait(false);

                    Close();

                    _UsbDevice = UsbManager.DeviceList.Select(d => d.Value).FirstOrDefault(d => d.DeviceId == DeviceNumberId);

                    if (_UsbDevice == null)
                    {
                        throw new DeviceException($"The device {DeviceNumberId} is not connected to the system");
                    }

                    Logger.LogInformation("Found device: {deviceName} Id: {deviceId}", _UsbDevice.DeviceName, _UsbDevice.DeviceId);

                    var isPermissionGranted = await RequestPermissionAsync().ConfigureAwait(false);
                    if (!isPermissionGranted.HasValue)
                    {
                        throw new DeviceException("User did not respond to permission request");
                    }

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

                    _UsbDeviceConnection = UsbManager.OpenDevice(_UsbDevice);

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

                    Logger.LogInformation("Interface count: {count}", _UsbDevice.InterfaceCount);

                    for (var interfaceNumber = 0; interfaceNumber < _UsbDevice.InterfaceCount; interfaceNumber++)
                    {
                        //TODO: This is the default interface but other interfaces might be needed so this needs to be changed.
                        var usbInterface = _UsbDevice.GetInterface(interfaceNumber);

                        var androidUsbInterface = new AndroidUsbInterface(
                            usbInterface,
                            _UsbDeviceConnection,
                            _androidFactory,
                            LoggerFactory.CreateLogger <AndroidUsbInterface>(),
                            ReadBufferSizeProtected,
                            WriteBufferSizeProtected);

                        Logger.LogInformation("Interface found. Id: {id} Endpoint Count: {endpointCount} Interface Class: {interfaceclass} Interface Subclass: {interfacesubclass} Name: {name}", usbInterface.Id, usbInterface.EndpointCount, usbInterface.InterfaceClass, usbInterface.InterfaceSubclass, usbInterface.Name);

                        UsbInterfaces.Add(androidUsbInterface);

                        for (var endpointNumber = 0; endpointNumber < usbInterface.EndpointCount; endpointNumber++)
                        {
                            var usbEndpoint = usbInterface.GetEndpoint(endpointNumber);

                            if (usbEndpoint == null)
                            {
                                continue;
                            }
                            var androidUsbEndpoint = new AndroidUsbEndpoint(usbEndpoint, interfaceNumber, LoggerFactory.CreateLogger <AndroidUsbEndpoint>());
                            androidUsbInterface.UsbInterfaceEndpoints.Add(androidUsbEndpoint);
                        }

                        await androidUsbInterface.ClaimInterface().ConfigureAwait(false);
                    }

                    RegisterDefaultInterfaces();

                    Logger.LogInformation("Device initialized successfully.");
                }, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error initializing device");
                throw;
            }
            finally
            {
                Logger.LogTrace("Releasing initialization lock");
                _ = _InitializingSemaphoreSlim.Release();
            }
        }
コード例 #14
0
 public UsbDevicePermissionReceiver (IObserver<bool> observer, UsbDevice device)
 {
     this.observer = observer;
     this.device = device;
 }
 //
 internal void AddDevice(UsbManager usbManager, UsbDevice usbDevice)
 {
     UsbSerialDevice serialDevice = GetDevice(usbManager, usbDevice, AllowAnonymousCdcAcmDevices);
     if (serialDevice != null)
     {
         lock (AttachedDevicesSyncRoot) {
             AttachedDevices.Add (serialDevice);
             if (DeviceAttached != null) {
                 DeviceAttached (this, new UsbSerialDeviceEventArgs (serialDevice));
             }
         }
     }
 }
コード例 #16
0
        public async Task InitializeAsync()
        {
            try
            {
                if (disposed)
                {
                    throw new Exception(Messages.DeviceDisposedErrorMessage);
                }

                await _InitializingSemaphoreSlim.WaitAsync();

                Close();

                _UsbDevice = UsbManager.DeviceList.Select(d => d.Value).FirstOrDefault(d => d.DeviceId == DeviceNumberId);
                if (_UsbDevice == null)
                {
                    throw new Exception($"The device {DeviceNumberId} is not connected to the system");
                }
                Logger?.Log($"Found device: {_UsbDevice.DeviceName} Id: {_UsbDevice.DeviceId}", nameof(AndroidUsbInterfaceManager), null, LogLevel.Information);


                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");
                }

                _UsbDeviceConnection = UsbManager.OpenDevice(_UsbDevice);

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

                for (var x = 0; x < _UsbDevice.InterfaceCount; x++)
                {
                    //TODO: This is the default interface but other interfaces might be needed so this needs to be changed.
                    var usbInterface = _UsbDevice.GetInterface(x);

                    var androidUsbInterface = new AndroidUsbInterface(usbInterface, _UsbDeviceConnection, Logger, Tracer, _ReadBufferSize, _WriteBufferSize);
                    UsbInterfaces.Add(androidUsbInterface);

                    for (var y = 0; y < usbInterface.EndpointCount; y++)
                    {
                        var usbEndpoint = usbInterface.GetEndpoint(y);

                        if (usbEndpoint != null)
                        {
                            //TODO: This is probably all wrong...
                            var androidUsbEndpoint = new AndroidUsbEndpoint(usbEndpoint);
                            androidUsbInterface.UsbInterfaceEndpoints.Add(androidUsbEndpoint);
                        }
                    }
                }

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

                RegisterDefaultInterfaces();
            }
            catch (Exception ex)
            {
                Log("Error initializing Hid Device", ex);
                throw;
            }
            finally
            {
                _InitializingSemaphoreSlim.Release();
            }
        }
 internal void RemoveDevice(UsbDevice usbDevice)
 {
     UsbSerialDevice removedDevice = null;
     UsbSerialDevice[] attachedDevices = AttachedDevices.ToArray();
     foreach (UsbSerialDevice device in attachedDevices) {
         if (
             device.UsbDevice.VendorId == usbDevice.VendorId
             && device.UsbDevice.ProductId == usbDevice.ProductId
             && device.UsbDevice.SerialNumber == usbDevice.SerialNumber) {
             removedDevice = device;
             break;
         }
     }
     if (removedDevice != null) {
         RemoveDevice (removedDevice);
     }
 }
コード例 #18
0
 public CdcAcmSerialPort(UsbManager usbManager, UsbDevice usbDevice, int portNumber)
     : base(usbManager, usbDevice, portNumber)
 {
     mEnableAsyncReads = (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1);
 }
コード例 #19
0
 public UsbConnection(UsbDevice device, UsbManager manager)
 {
     this.usbDevice = device;
     this.usbManager = manager;
 }