Flutter中的通讯USB设备

时间:2018-11-14 02:16:40

标签: android flutter

在Android中,我正在使用UsbManager和UsbDevice连接到设备。我想与Flutter中的UsbDevice通信,但不知道该怎么做。

谢谢!

2 个答案:

答案 0 :(得分:2)

嘿,我有同样的问题,但是我发现了这个flutter_usb_write。它可能很有用,但是它是一个非常新的插件,因此我正在对其进行测试,但我还没有解决方案。如果您愿意,也可以尝试使用它,如果我发现有趣的东西,我会告诉您。 flutter_usb_write

答案 1 :(得分:0)

Device.Net是一个.NET跨平台USB连接框架。 Flutnet将.NET和Flutter整合在一起。这是一些使用Flutnet和Device.Net从USB温度计读取温度的示例代码。

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

详细了解此here

使用these instructions克隆并运行示例。

如果/当Flutter进入Windows或macOS之类的其他平台时,USB代码在各个平台上将保持不变。如果您使用本地Android API,则每个平台的代码都会不同。