“exception in UsbManager.openDevice Flutter” 可以保持不变。

huangapple go评论82阅读模式
英文:

exception in UsbManager.openDevice Flutter

问题

这个错误信息表明你的应用程序缺少USB设备访问权限,这导致无法打开USB设备。要解决这个问题,你需要确保你的应用程序已经请求了USB设备的权限。你可以在你的Flutter应用程序的Android清单文件(通常是AndroidManifest.xml)中添加USB设备的权限请求。

在清单文件中,你可以添加以下代码:

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.permission.USB_PERMISSION" />

这将请求USB主机特性和USB许可权限,以便你的应用程序能够与USB设备进行通信。确保你的清单文件中包含了这些权限后,重新构建你的Flutter应用程序,然后再次运行它。

这应该解决你遇到的USB设备权限问题。如果你在运行应用程序时仍然遇到问题,还需要确保你的设备在物理上支持USB主机模式,并且USB设备已正确连接到设备上。

英文:

I'm trying to connect my flutter app with USB serial devices to interact with it.
for that, I'm using the usb_serial plugin and using the official example below.
Also, I'm running my app on a Desktop monitor using TvBox H96Max.

`import &#39;dart:async&#39;;
import &#39;dart:typed_data&#39;;

import &#39;package:flutter/material.dart&#39;;
import &#39;package:usb_serial/transaction.dart&#39;;
import &#39;package:usb_serial/usb_serial.dart&#39;;

void main() =&gt; runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() =&gt; _MyAppState();
}

class _MyAppState extends State&lt;MyApp&gt; {
  UsbPort? _port;
  String _status = &quot;Idle&quot;;
  List&lt;Widget&gt; _ports = [];
  List&lt;Widget&gt; _serialData = [];

  StreamSubscription&lt;String&gt;? _subscription;
  Transaction&lt;String&gt;? _transaction;
  UsbDevice? _device;

  TextEditingController _textController = TextEditingController();

  Future&lt;bool&gt; _connectTo(device) async {
    _serialData.clear();

    if (_subscription != null) {
      _subscription!.cancel();
      _subscription = null;
    }

    if (_transaction != null) {
      _transaction!.dispose();
      _transaction = null;
    }

    if (_port != null) {
      _port!.close();
      _port = null;
    }

    if (device == null) {
      _device = null;
      setState(() {
        _status = &quot;Disconnected&quot;;
      });
      return true;
    }

    _port = await device.create();
    if (await (_port!.open()) != true) {
      setState(() {
        _status = &quot;Failed to open port&quot;;
      });
      return false;
    }
    _device = device;

    await _port!.setDTR(true);
    await _port!.setRTS(true);
    await _port!.setPortParameters(115200, UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);

    _transaction = Transaction.stringTerminated(_port!.inputStream as Stream&lt;Uint8List&gt;, Uint8List.fromList([13, 10]));

    _subscription = _transaction!.stream.listen((String line) {
      setState(() {
        _serialData.add(Text(line));
        if (_serialData.length &gt; 20) {
          _serialData.removeAt(0);
        }
      });
    });

    setState(() {
      _status = &quot;Connected&quot;;
    });
    return true;
  }

  void _getPorts() async {
    _ports = [];
    List&lt;UsbDevice&gt; devices = await UsbSerial.listDevices();
    if (!devices.contains(_device)) {
      _connectTo(null);
    }
    print(devices);

    devices.forEach((device) {
      _ports.add(ListTile(
          leading: Icon(Icons.usb),
          title: Text(device.productName!),
          subtitle: Text(device.manufacturerName!),
          trailing: ElevatedButton(
            child: Text(_device == device ? &quot;Disconnect&quot; : &quot;Connect&quot;),
            onPressed: () {
              _connectTo(_device == device ? null : device).then((res) {
                _getPorts();
              });
            },
          )));
    });

    setState(() {
      print(_ports);
    });
  }

  @override
  void initState() {
    super.initState();

    UsbSerial.usbEventStream!.listen((UsbEvent event) {
      _getPorts();
    });

    _getPorts();
  }

  @override
  void dispose() {
    super.dispose();
    _connectTo(null);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text(&#39;USB Serial Plugin example app&#39;),
      ),
      body: Center(
          child: Column(children: &lt;Widget&gt;[
        Text(_ports.length &gt; 0 ? &quot;Available Serial Ports&quot; : &quot;No serial devices available&quot;, style: Theme.of(context).textTheme.headline6),
        ..._ports,
        Text(&#39;Status: $_status\n&#39;),
        Text(&#39;info: ${_port.toString()}\n&#39;),
        ListTile(
          title: TextField(
            controller: _textController,
            decoration: InputDecoration(
              border: OutlineInputBorder(),
              labelText: &#39;Text To Send&#39;,
            ),
          ),
          trailing: ElevatedButton(
            child: Text(&quot;Send&quot;),
            onPressed: _port == null
                ? null
                : () async {
                    if (_port == null) {
                      return;
                    }
                    String data = _textController.text + &quot;\r\n&quot;;
                    await _port!.write(Uint8List.fromList(data.codeUnits));
                    _textController.text = &quot;&quot;;
                  },
          ),
        ),
        Text(&quot;Result Data&quot;, style: Theme.of(context).textTheme.headline6),
        ..._serialData,
      ])),
    ));
  }
}`

It gives me this error message:

`exception in UsbManager.openDevice
E/UsbManager(19118): java.lang.SecurityException: User has not given 10087/com.example.untitled4 permission to access device /dev/bus/usb/001/002
E/UsbManager(19118):   at android.os.Parcel.createExceptionOrNull(Parcel.java:2426)
E/UsbManager(19118):   at android.os.Parcel.createException(Parcel.java:2410)
E/UsbManager(19118):   at android.os.Parcel.readException(Parcel.java:2393)
E/UsbManager(19118):   at android.os.Parcel.readException(Parcel.java:2335)
E/UsbManager(19118):   at android.hardware.usb.IUsbManager$Stub$Proxy.openDevice(IUsbManager.java:1022)
E/UsbManager(19118):   at android.hardware.usb.UsbManager.openDevice(UsbManager.java:719)
E/UsbManager(19118):   at dev.bessems.usbserial.UsbSerialPlugin.openDevice(UsbSerialPlugin.java:145)
E/UsbManager(19118):   at dev.bessems.usbserial.UsbSerialPlugin.createTyped(UsbSerialPlugin.java:186)
E/UsbManager(19118):   at dev.bessems.usbserial.UsbSerialPlugin.onMethodCall(UsbSerialPlugin.java:288)
E/UsbManager(19118):   at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:258)
E/UsbManager(19118):   at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/UsbManager(19118):   at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:322)
E/UsbManager(19118):   at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/UsbManager(19118):   at android.os.Handler.handleCallback(Handler.java:938)
E/UsbManager(19118):   at android.os.Handler.dispatchMessage(Handler.java:99)
E/UsbManager(19118):   at android.os.Looper.loopOnce(Looper.java:201)
E/UsbManager(19118):   at android.os.Looper.loop(Looper.java:288)
E/UsbManager(19118):   at android.app.ActivityThread.main(ActivityThread.java:7870)
E/UsbManager(19118):   at java.lang.reflect.Method.invoke(Native Method)
E/UsbManager(19118):   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
E/UsbManager(19118):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
D/CompatibilityChangeReporter(19118): Compat change id reported: 160794467; UID 10087; state: ENABLED
E/flutter (19118): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(UsbSerialPortAdapter, Failed to acquire USB device., null, null)
E/flutter (19118): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:653:7)
E/flutter (19118): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:315:18)
E/flutter (19118): &lt;asynchronous suspension&gt;
E/flutter (19118): #2      UsbSerial.createFromDeviceId (package:usb_serial/usb_serial.dart:433:33)
E/flutter (19118): &lt;asynchronous suspension&gt;
E/flutter (19118): #3      UsbDevice.create (package:usb_serial/usb_serial.dart:333:13)
E/flutter (19118): &lt;asynchronous suspension&gt;
E/flutter (19118): #4      _MyAppState.build.&lt;anonymous closure&gt; (package:untitled4/main.dart:175:26)
E/flutter (19118): &lt;asynchronous suspension&gt;`

I was trying to show the USB serial devices and interact with it (sending data and so on).

答案1

得分: 0

在我的情况下,它是“Enter”按钮,所以我放置了:

Uint8List.fromList([13, 10])

这对我起作用了。

英文:

It turned out that I have to place the last character of my string, which serves as the string terminator, in the second parameter of Transaction.stringTerminated

in my case it was Enter button. so I put:

Uint8List.fromList([13, 10])

This is what worked for me.

huangapple
  • 本文由 发表于 2023年3月7日 21:26:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定