Communication Usb Device in Flutter

Viewed 6543

In Android, I am using UsbManager and UsbDevice to connect to the device. I want to communicate with the UsbDevice in Flutter but do not know how to do it.

Thanks!

2 Answers

Hey i have the same issues, but i found this flutter_usb_write. It can be useful but it's a very new plug-in so i'm testing it but I'haven't already the solution. If you want you can try to use it i'll do too, and if i found something interesting i'll tell you. flutter_usb_write

Device.Net is a .NET cross-platform USB connectivity framework. Flutnet brings .NET and Flutter together. This is some sample code using Flutnet and Device.Net to read the temperature from a USB thermometer.

    public ThermometerServiceDroid(UsbManager usbManager, Context appContext) : base()
    {
        var filterDeviceDefinitions = new List<FilterDeviceDefinition>
        { new FilterDeviceDefinition ( vendorId : 16701, productId : 8455, usagePage : 65280 ) };

        var deviceDataStreamer =
        filterDeviceDefinitions.CreateAndroidUsbDeviceFactory(usbManager, appContext, writeBufferSize: 8, readBufferSize: 8)
            .ToDeviceManager()
            .CreateDeviceDataStreamer(async (device) =>
            {
                try
                {
                    var data = await device.WriteAndReadAsync(new byte[8] { 0x01, 0x80, 0x33, 0x01, 0x00, 0x00, 0x00, 0x00 });

                    var temperatureTimesOneHundred = (data.Data[3] & 0xFF) + (data.Data[2] << 8);

                    _currentTemperature = (double)Math.Round(temperatureTimesOneHundred / 100.0m, 2, MidpointRounding.ToEven);

                }
                catch
                {
                    _currentTemperature = 0;
                }
            }
            , async (d) =>
            {
                await d.InitializeAsync();

                var usbDevice = (IUsbDevice)d;

                usbDevice.UsbInterfaceManager.WriteUsbInterface = usbDevice.UsbInterfaceManager.UsbInterfaces[1];
                usbDevice.UsbInterfaceManager.ReadUsbInterface = usbDevice.UsbInterfaceManager.UsbInterfaces[1];
                usbDevice.UsbInterfaceManager.ReadUsbInterface.ReadEndpoint = usbDevice.UsbInterfaceManager.ReadUsbInterface.UsbInterfaceEndpoints[0];

            }
            ).Start();
    }

Read more about this here.

Clone and run the sample with these instructions.

If/when Flutter comes to other platforms like Windows or macOS, the USB code will remain the same across platforms. If you use the native Android APIs, the code will be different for each platform.

Related