Xamarin.Forms: чтение данных с помощью библиотеки UsbDeviceConnection

Мне нужно прочитать данные из UsbDeviceConnection, но вызов UsbDeviceConnection.BulkTransfer(......) всегда возвращает -1.

когда мне нужно записать данные, все работает нормально, но когда я пытаюсь получить, вызов всегда возвращает -1 (не удалось получить).

 [Obsolete]
        public string ConnectAndRead()
        {


            // Get a usbManager that can access all of the devices
            var usbManager = (UsbManager)Forms.Context.GetSystemService(Context.UsbService);

            while(usbManager.DeviceList.Count == 0)
            {
                Debug.WriteLine($"Nessun dispositivo connesso alle {DateTime.Now}");

                Thread.Sleep(5000);
            }
            var deviceConnected = usbManager.DeviceList.FirstOrDefault();

            if (deviceConnected.Value == null)
                //throw new Exception("Dispositivo non trovato, provare a configurarlo in Impostazioni");
                Debug.WriteLine( "Dispositivo non trovato");

           //string usbPort = deviceConnected.Key;
            UsbDevice usbDevice = deviceConnected.Value;
            if (!usbManager.HasPermission(usbDevice))
            {
                try
                {
                    PendingIntent pi = PendingIntent.GetBroadcast(Forms.Context, 0, new Intent(ACTION_USB_PERMISSION), 0);
                    usbManager.RequestPermission(usbDevice, pi);
                    //throw new Exception("Rilanciare la stampa");

                }
                catch (Exception ex)
                {
                    //throw new Exception(ex.Message);
                    return ex.Message;
                }
                Debug.WriteLine("Non avevo i permessi");
            }
            try
            {
                UsbDeviceConnection deviceConnection = usbManager.OpenDevice(usbDevice);

                // Get the usbInterface for the device.  It and usbEndpoint implement IDisposable, so wrap in a using
                // You may want to loop through the interfaces to find the one you want (instead of 0)
                using (var usbInterface = usbDevice.GetInterface(0))
                {
                    //var interfaceClass = usbInterface.InterfaceClass;
                    // Get the endpoint, again implementing IDisposable, and again the index you need
                    using (var usbEndpoint = usbInterface.GetEndpoint(2))
                    {

                        byte[] encodingSetting =
                            //new byte[] { (byte)0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08 }; //baudrate 9600
                            new byte[] { (byte)0x00, 0x4b, 0x00, 0x00, 0x00, 0x00, 0x08 };   //baudrate 19200
                        // Make request or whatever you need to do
                        deviceConnection.ControlTransfer(
                            UsbAddressing.Out,
                            0x20,   //SET_LINE_CODING
                            0,      //value
                            0,      //index
                            encodingSetting,  //buffer
                            7,      //length
                            0);     //timeout


                        byte[] buffer = new byte[4096];
                        StringBuilder str = new StringBuilder();

                        while (true)
                        {
                            //int byteReaded = deviceConnection.BulkTransfer(usbEndpoint, buffer, buffer.Length, 5000);
                            int byteReaded = deviceConnection.BulkTransfer(usbEndpoint, buffer, 1, 5000);
                            if (byteReaded > 0)
                            {
                                foreach (byte b in buffer)
                                {
                                    str.Append((char)b);
                                }

                                return str.ToString();
                            }


                        }

                    }
                }
            }catch(Exception ex)
            {
                return ex.Message;
            }




        }

Я ожидаю, что значение byteReaded будет больше 0, потому что я отправляю данные с помощью «замазки», но всегда равно -1

что мне не хватает?


person AccountForWorks    schedule 03.09.2019    source источник


Ответы (1)


Нашел это решение, которое работает https://github.com/ysykhmd/usb-serial-for-xamarin-android

person AccountForWorks    schedule 04.09.2019