当前位置: 首页 > 知识库问答 >
问题:

Android USB主机读取设备

万高洁
2023-03-14

我正在尝试从连接到主机模式下的Android手机的USB设备中获取一些数据。我可以发送数据到它,但读取失败。

public class UsbCommunicationManager
{
    static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    UsbManager usbManager;
    UsbDevice usbDevice;
    UsbInterface intf = null;
    UsbEndpoint input, output;
    UsbDeviceConnection connection;

    PendingIntent permissionIntent;

    Context context;

    byte[] readBytes = new byte[64];

    public UsbCommunicationManager(Context context)
    {
        this.context = context;
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

        // ask permission from user to use the usb device
        permissionIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        context.registerReceiver(usbReceiver, filter);
    }

    public void connect()
    {
        // check if there's a connected usb device
        if(usbManager.getDeviceList().isEmpty())
        {
            Log.d("trebla", "No connected devices");
            return;
        }

        // get the first (only) connected device
        usbDevice = usbManager.getDeviceList().values().iterator().next();

        // user must approve of connection
        usbManager.requestPermission(usbDevice, permissionIntent);
    }

    public void stop()
    {
        context.unregisterReceiver(usbReceiver);
    }

    public String send(String data)
    {
        if(usbDevice == null)
        {
            return "no usb device selected";
        }

        int sentBytes = 0;
        if(!data.equals(""))
        {
            synchronized(this)
            {
                // send data to usb device
                byte[] bytes = data.getBytes();
                sentBytes = connection.bulkTransfer(output, bytes, bytes.length, 1000);
            }
        }

        return Integer.toString(sentBytes);
    }

    public String read()
    {
        // reinitialize read value byte array
        Arrays.fill(readBytes, (byte) 0);

        // wait for some data from the mcu
        int recvBytes = connection.bulkTransfer(input, readBytes, readBytes.length, 3000);

        if(recvBytes > 0)
        {
            Log.d("trebla", "Got some data: " + new String(readBytes));
        }
        else
        {
            Log.d("trebla", "Did not get any data: " + recvBytes);
        }

        return Integer.toString(recvBytes);
    }

    public String listUsbDevices()
    {
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();

        if(deviceList.size() == 0)
        {
            return "no usb devices found";
        }

        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        String returnValue = "";
        UsbInterface usbInterface;

        while(deviceIterator.hasNext())
        {
            UsbDevice device = deviceIterator.next();
            returnValue += "Name: " + device.getDeviceName();
            returnValue += "\nID: " + device.getDeviceId();
            returnValue += "\nProtocol: " + device.getDeviceProtocol();
            returnValue += "\nClass: " + device.getDeviceClass();
            returnValue += "\nSubclass: " + device.getDeviceSubclass();
            returnValue += "\nProduct ID: " + device.getProductId();
            returnValue += "\nVendor ID: " + device.getVendorId();
            returnValue += "\nInterface count: " + device.getInterfaceCount();

            for(int i = 0; i < device.getInterfaceCount(); i++)
            {
                usbInterface = device.getInterface(i);
                returnValue += "\n  Interface " + i;
                returnValue += "\n\tInterface ID: " + usbInterface.getId();
                returnValue += "\n\tClass: " + usbInterface.getInterfaceClass();
                returnValue += "\n\tProtocol: " + usbInterface.getInterfaceProtocol();
                returnValue += "\n\tSubclass: " + usbInterface.getInterfaceSubclass();
                returnValue += "\n\tEndpoint count: " + usbInterface.getEndpointCount();

                for(int j = 0; j < usbInterface.getEndpointCount(); j++)
                {
                    returnValue += "\n\t  Endpoint " + j;
                    returnValue += "\n\t\tAddress: " + usbInterface.getEndpoint(j).getAddress();
                    returnValue += "\n\t\tAttributes: " + usbInterface.getEndpoint(j).getAttributes();
                    returnValue += "\n\t\tDirection: " + usbInterface.getEndpoint(j).getDirection();
                    returnValue += "\n\t\tNumber: " + usbInterface.getEndpoint(j).getEndpointNumber();
                    returnValue += "\n\t\tInterval: " + usbInterface.getEndpoint(j).getInterval();
                    returnValue += "\n\t\tType: " + usbInterface.getEndpoint(j).getType();
                    returnValue += "\n\t\tMax packet size: " + usbInterface.getEndpoint(j).getMaxPacketSize();
                }
            }
        }

        return returnValue;
    }

    private void setupConnection()
    {
        // find the right interface
        for(int i = 0; i < usbDevice.getInterfaceCount(); i++)
        {
            // communications device class (CDC) type device
            if(usbDevice.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA)
            {
                intf = usbDevice.getInterface(i);

                // find the endpoints
                for(int j = 0; j < intf.getEndpointCount(); j++)
                {
                    if(intf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT && intf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
                    {
                        // from android to device
                        output = intf.getEndpoint(j);
                    }

                    if(intf.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN && intf.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)
                    {
                        // from device to android
                        input = intf.getEndpoint(j);
                    }
                }
            }
        }
    }

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver()
    {
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if(ACTION_USB_PERMISSION.equals(action))
            {
                // broadcast is like an interrupt and works asynchronously with the class, it must be synced just in case
                synchronized(this)
                {
                    if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                    {
                        setupConnection();

                        connection = usbManager.openDevice(usbDevice);
                        connection.claimInterface(intf, true);

                        // set flow control to 8N1 at 9600 baud
                        int baudRate = 9600;
                        byte stopBitsByte = 1;
                        byte parityBitesByte = 0;
                        byte dataBits = 8;
                        byte[] msg = {
                            (byte) (baudRate & 0xff),
                            (byte) ((baudRate >> 8) & 0xff),
                            (byte) ((baudRate >> 16) & 0xff),
                            (byte) ((baudRate >> 24) & 0xff),
                            stopBitsByte,
                            parityBitesByte,
                            (byte) dataBits
                        };

                        connection.controlTransfer(UsbConstants.USB_TYPE_CLASS | 0x01, 0x20, 0, 0, msg, msg.length, 5000);
                    }
                    else
                    {
                        Log.d("trebla", "Permission denied for USB device");
                    }
                }
            }
            else if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                Log.d("trebla", "USB device detached");
            }
        }
    };
}

我一直从read()方法获得-1,它指示某种错误,它总是超时。也许问题来自于连接配置,我试了几次(读作:试错),没有一次奏效,令人惊讶的是,我不需要任何配置来发送数据到设备。

编辑

还必须注意的是,我使用的电缆是micro-USB到micro-USB的,它只能以一种方式工作,即只有当插头A连接到电话和插头B连接到设备时,我的设备才由我的电话供电,而不是相反。好像很奇怪。我能够发送数据而不能接收数据的事实仍然存在。

编辑2

我发现别人也有同样的问题,但似乎他无法解决。

编辑3

connection.controlTransfer(0x21, 0x22, 0x1, 0, null, 0, 0);

共有1个答案

欧阳元魁
2023-03-14

您可以使用https://github.com/mik3y/usb-serial-for-android中的UsbSerial库

我的示例代码:

    UsbManager usbManager = null;
    UsbDeviceConnection connection = null;
    UsbSerialDriver driver = null;
    UsbSerialPort port = null;

    usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

    List<UsbSerialDriver> availableDrivers =  UsbSerialProber.getDefaultProber().findAllDrivers(manager);
    // Open a connection to the first available driver.

    for (UsbSerialDriver usd : availableDrivers) {
        UsbDevice udv = usd.getDevice(); 
        if (udv.getVendorId()==0x067B || udv.getProductId()==2303){
            driver = usd;
            break;
        }
    }
        connection = usbManager.openDevice(driver.getDevice());

        port = driver.getPorts().get(0);

        driver.getDevice().

    }

        if (connection == null) return;

        try{

            port.open(connection);
            port.setParameters(4800, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);

                try{

                    byte buffer[] = new byte[250];
                    //Log.d("GPS_REQ", "->");
                    int numBytesRead = port.read(buffer, 500); //5000; 

                }catch (Exception e) {
                    Log.d("GPS_ERR", e.getLocalizedMessage());
                }
 类似资料:
  • 问题内容: 我有一个Flask,SQLAlchemy webapp,它使用一个mysql服务器。我想将数据库设置扩展为具有只读从​​属服务器,以便可以在继续写入主数据库服务器的同时在主服务器和从属服务器之间分散读取。 我研究了几种选择,我相信我无法使用普通的SQLAlchemy做到这一点。我打算在我的web应用程序中创建2个数据库句柄,每个用于主数据库服务器和从数据库服务器。然后,使用简单的随机值

  •  主机设定 可调整PSP™主机之设定、阅览相关信息,或替Memory Stick™、主机内存进行格式化。 昵称 您的生日日期   系统语言 文字设定 关闭屏幕盖时   UMD™自动启动     UMD™ Cache(高速缓存)    色彩空间    USB充电     USB自动连接 电池信息     Memory Stick™格式化 主机记忆体格式化   启动WMA播放 启动Flash® Pla

  • 我拥有一个极地H10胸带,它以蓝牙低能量运行,并提供心率和心率变化。 我想用Android应用程序读取这些值。由于官方BLE教程中的帮助,我能够连接到设备。现在的问题是从设备中读取心率和心率变异性值。每次设备上有新值可用时,我都要读取该值(并且至少每秒都有新值)。 我找到了以下代码: 假设我与设备有连接,我如何使用它来提取心率和r-r间隔(节拍到节拍间隔)?如果有人能举个简短的例子,我会很高兴。此

  • 我读过很多关于用Android通过代码读取APN的话题,自从Android 4.2以来,这似乎已经不可能了。然而,所有的主题都超过了2/3年,我想知道是否有一个好的解决方案,使我能够读取设备的当前APN。我看到过一些关于SQLiteWrapper的东西,但它不起作用,或者我只是没有足够的资格让它起作用。

  • 在阅读Kafka主题时,我得到了奇怪的ArrayIndexOutOfBoundsException。花了很多时间却搞不清问题所在。有人能在这方面提供帮助/建议吗。这是我的日志。