Android Studio与HID USB设备通过controlTransfer

时间:2016-09-17 02:48:14

标签: java android-studio usb hid

我在使用Android Studio中的HID USB设备时遇到问题。

我的Python代码完美无缺,所以设备很好。

另请注意,我已经将此java类用于另一个仅接收数据的设备,并且它运行得非常好。

但是这个新设备,我需要发送和接收数据。所以我使用controlTransfer在endpouint 0上发送数据。

这是Python中的代码(片段):

import hid

DEVICEMODE = 0x0B
GBLINK = 0x02

self.dongle = hid.device()
self.dongle.open(self.idVendor, self.idProduct)
self.sendCommand(0, DEVICEMODE, 0x00, 0x01)
self.sendCommand(0, GBLINK, 0x40, 0xFF)

def sendCommand(self, pucknum, cmd, msb, lsb):
    command = (0b11000000 & (devicenum << 6)) | cmd
    self.dongle.set_nonblocking(1)
    self.dongle.write([0x00, command, msb, lsb]) # first byte is report id
    self.dongle.set_nonblocking(0)

然后代码继续通过sendCommand方法发送各种命令。

在Java中,我有以下

public class DongleDevice implements Runnable {

    protected final String TAG = "DongleDevice";

    public UsbDevice usbDevice;
    public UsbManager usbManager;
    public UsbDeviceConnection usbDeviceConnection;

    private UsbInterface intf;
    private UsbEndpoint endpoint;

    public int version = -1;

    public Thread thread;
    public volatile boolean threadRunning = false;

    private boolean status = false;
    private boolean firstTime = true;

    private UsbRequest request = null;

    public DongleDevice() {
        thread = new Thread(this);
    }

    public void requestPermission() {
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        deviceFound = false;
        deviceReady = false;
        while (deviceIterator.hasNext()) {
            usbDevice = deviceIterator.next();
            if (usbDevice.getVendorId() == Constants.VENDOR_ID) {
                deviceFound = true;
                break;
            }
        }
        if (deviceFound == true) {
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent("PERMISSION_GRANTED"), 0);
            usbManager.requestPermission(usbDevice, pi);
        }
    }

    public void openDevice () {
        final Handler handler = new Handler();
        boolean handlePlaced = handler.postDelayed(new Runnable() {
            public void run() {
                usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
                HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
                Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
                deviceFound = false;
                deviceReady = false;
                while (deviceIterator.hasNext()) {
                    usbDevice = deviceIterator.next();
                    if (usbDevice.getVendorId() == Constants.VENDOR_ID) {
                        deviceFound = true;
                        break;
                    }
                }
                if (deviceFound == true) {
                    if (usbManager.hasPermission(usbDevice)) open();
                    else closeDevice();
                }
            }
        }, 2000);
    }

    private void open() {
        endpoint = intf.getEndpoint(0);
        usbDeviceConnection = usbManager.openDevice(usbDevice);
        status = usbDeviceConnection.claimInterface(intf, true);
        if (status) {
            getVersion();
            thread.start();
        } else {
            closeDevice();
        }
    }

    private void getVersion() {
        byte[] rawDescriptors;
        rawDescriptors = usbDeviceConnection.getRawDescriptors();
        version = (int)(rawDescriptors[12] & 0x01);
    }

    public void closeDevice() {
        deviceReady = false;
        deviceFound = false;
        if (threadRunning == true) {
            if (request != null) {
                request.cancel();
            }
        }
    }

    public void onDestroy() {
        closeDevice();
    }

    public boolean isOpen() {
        return deviceFound;
    }

    @Override
    public void run() {
        threadRunning = true;
        deviceReady = true;

        ByteBuffer buffer = ByteBuffer.allocate(60);
        if (request != null) request.cancel();
        request = new UsbRequest();
        status = request.initialize(usbDeviceConnection, endpoint);

        P_Device pd1 = new P_Device(0); //a class for parsing the 60 byte data packet received

        byte[] command;
        int response;
        int requestType = 0x21;
        int requestId = 0x9;
        int value = 0x200; // 0x300 also works
        int index = 0;
        int timeout = 5000;

        byte DEVICEMODE = 0x0B;
        byte GBLINK = 0x02;

        while (deviceFound == true) {

            command = new byte[] {DEVICEMODE, 0x00, 0x01}; // send command followed by two bytes
            response = usbDeviceConnection.controlTransfer(requestType, requestId, value, index, command, command.length, timeout);
            Logger.d(TAG,"controlTransfer response = " + response); // I get 3 as a response
            try { thread.sleep(100); } catch (Exception e) { }

            for (int i=0; i<20; i++) {
                command = new byte[]{GBLINK, (byte) 64, (byte) 255}; // should blink for ~300 ms at full intensity
                response = usbDeviceConnection.controlTransfer(requestType, requestId, value, index, command, command.length, timeout);
                Logger.d(TAG, "controlTransfer response = " + response); // I get 3 as a response
                try { thread.sleep(500); } catch (Exception e) { }
            }

            for (int i=0; i<20; i++) {
                request.queue(buffer, 60);
                if (usbDeviceConnection.requestWait().equals(request)) {
                    //buffer.flip();
                    buffer.position(0);
                    pd1.parse(buffer) // all results are 0, and they shouldn't be.
                }
                try { thread.sleep(100); } catch (Exception e) { }
            }

            command = new byte[] {DEVICEMODE , 0x00, 0x00};
            response = usbDeviceConnection.controlTransfer(requestType, requestId, value, index, command, command.length, timeout);
            Logger.d(TAG,"controlTransfer response = " + response); // I get 3 as a response
            try { thread.sleep(100); } catch (Exception e) { }

            deviceFound = false;

        }
        threadRunning = false;
        deviceReady = false;
    }
}

当我运行我的代码时,我得到确认发送的字节是3(-1表示错误)。但是设备没有按照它应该闪烁,并且我从读取中得到全部0。

任何帮助都将不胜感激。

0 个答案:

没有答案
相关问题