public AdbDevice(AdbTestActivity activity, UsbDeviceConnection connection, UsbInterface intf) { mActivity = activity; mDeviceConnection = connection; mSerial = connection.getSerial(); UsbEndpoint epOut = null; UsbEndpoint epIn = null; // look for our bulk endpoints for (int i = 0; i < intf.getEndpointCount(); i++) { UsbEndpoint ep = intf.getEndpoint(i); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { epOut = ep; } else { epIn = ep; } } } if (epOut == null || epIn == null) { throw new IllegalArgumentException("not all endpoints found"); } mEndpointOut = epOut; mEndpointIn = epIn; }
private int startRtlSdrService(final UsbDevice device) { int result; final UsbDeviceConnection connection = usbManager.openDevice(device); if (connection == null) { Log.d(TAG, "Unknown error while opening device: " + device); result = R.string.connect_usb_device_status_error_unknown; } else { final int usbFd = connection.getFileDescriptor(); final String uspfsPathInput = UsbUtils.deriveProperDeviceName(device.getDeviceName()); if (rtlSdrService != null) { rtlSdrService.startRtlSdr(new StartRtlSdrRequest(arguments, usbFd, uspfsPathInput)); } result = R.string.connect_usb_device_status_ok; } return result; }
public static List<AlternateUsbInterface> forUsbInterface(UsbDeviceConnection deviceConnection, UsbInterface usbInterface) { byte[] rawDescriptors = deviceConnection.getRawDescriptors(); List<AlternateUsbInterface> alternateSettings = new ArrayList<>(2); int offset = 0; while(offset < rawDescriptors.length) { int bLength = rawDescriptors[offset] & 0xFF; int bDescriptorType = rawDescriptors[offset + 1] & 0xFF; if (bDescriptorType == 0x04) { // interface descriptor, we are not interested int bInterfaceNumber = rawDescriptors[offset + 2] & 0xFF; int bAlternateSetting = rawDescriptors[offset + 3] & 0xFF; if (bInterfaceNumber == usbInterface.getId()) { alternateSettings.add(new AlternateUsbInterface(usbInterface, bAlternateSetting)); } } // go to next structure offset += bLength; } if (alternateSettings.size() < 1) throw new IllegalStateException(); return alternateSettings; }
@Test public void getAlternateSetting() throws Exception { UsbDeviceConnection usbDeviceConnection = mockConnectionWithRawDescriptors(new byte[] { 18, 1, 0, 2, 0, 0, 0, 64, -38, 11, 56, 40, 0, 1, 1, 2, 3, 1, // Device Descriptor 9, 2, 34, 0, 2, 1, 4, -128, -6, // Configuration Descriptor 9, 4, 0, 0, 1, -1, -1, -1, 5, // Interface Descriptor for interface 0 with alternate setting 0 9, 4, 0, 1, 1, -1, -1, -1, 5, // Interface Descriptor for interface 0 with alternate setting 1 7, 5, -127, 2, 0, 2, 0, // Endpoint Descriptor 9, 4, 1, 0, 0, -1, -1, -1, 5 // Interface Descriptor for interface 1 with alternate setting 0 }); // Interface 0 has alternate settings {0, 1} UsbInterface i0 = mockInterface(0); assertThat(AlternateUsbInterface.forUsbInterface(usbDeviceConnection, i0), equalTo(asList(new AlternateUsbInterface(i0, 0), new AlternateUsbInterface(i0, 1)))); // Interface 1 has alternate settings {0} UsbInterface i1 = mockInterface(1); assertThat(AlternateUsbInterface.forUsbInterface(usbDeviceConnection, i1), equalTo(singletonList(new AlternateUsbInterface(i1, 0)))); }
private boolean setAdbInterface(UsbDevice device, UsbInterface intf) { if (mDeviceConnection != null) { if (mInterface != null) { mDeviceConnection.releaseInterface(mInterface); mInterface = null; } mDeviceConnection.close(); mDevice = null; mDeviceConnection = null; } if (device != null && intf != null) { UsbDeviceConnection connection = mManager.openDevice(device); if (connection != null) { log("open succeeded"); if (connection.claimInterface(intf, false)) { log("claim interface succeeded"); mDevice = device; mDeviceConnection = connection; mInterface = intf; mAdbDevice = new AdbDevice(this, mDeviceConnection, intf); log("call start"); mAdbDevice.start(); return true; } else { log("claim interface failed"); connection.close(); } } else { log("open failed"); } } if (mDeviceConnection == null && mAdbDevice != null) { mAdbDevice.stop(); mAdbDevice = null; } return false; }
@Override public void open(UsbDeviceConnection connection) throws IOException { if (mConnection != null) { throw new IOException("Already open"); } mConnection = connection; boolean opened = false; try { for (int i = 0; i < mDevice.getInterfaceCount(); i++) { if (connection.claimInterface(mDevice.getInterface(i), true)) { Log.d(TAG, "claimInterface " + i + " SUCCESS"); } else { throw new IOException("Error claiming interface " + i); } } reset(); opened = true; } finally { if (!opened) { close(); mConnection = null; } } }
/** * Request the active configuration descriptor through the USB device connection. */ public static ConfigurationDescriptor fromDeviceConnection(UsbDeviceConnection connection) throws IllegalArgumentException, ParseException { //Create a sufficiently large buffer for incoming data byte[] buffer = new byte[LENGTH]; connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX, buffer, LENGTH, TIMEOUT); //Do a short read to determine descriptor length int totalLength = headerLengthCheck(buffer); //Obtain the full descriptor buffer = new byte[totalLength]; connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX, buffer, totalLength, TIMEOUT); return parseResponse(buffer); }
public static UsbSerialDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { /* * It checks given vid and pid and will return a custom driver or a CDC serial driver. * When CDC is returned open() method is even more important, its response will inform about if it can be really * opened as a serial device with a generic CDC serial driver */ int vid = device.getVendorId(); int pid = device.getProductId(); if(FTDISioIds.isDeviceSupported(vid, pid)) return new FTDISerialDevice(device, connection, iface); else if(CP210xIds.isDeviceSupported(vid, pid)) return new CP2102SerialDevice(device, connection, iface); else if(PL2303Ids.isDeviceSupported(vid, pid)) return new PL2303SerialDevice(device, connection, iface); else if(CH34xIds.isDeviceSupported(vid, pid)) return new CH34xSerialDevice(device, connection, iface); else if(isCdcDevice(device)) return new CDCSerialDevice(device, connection, iface); else return null; }
public void setParameter(UsbDeviceConnection connection, byte[] params){ connection.controlTransfer(USB_CONTROL_OUT, SET_LINE_CODING, //requestType 0, //value 0, //index params, // buffer params.length, // length TIMEOUT); // Enable DTR/RTS. connection.controlTransfer(USB_CONTROL_OUT, SET_CONTROL_LINE_STATE, //requestType 0x02, //value 0, //index null, // buffer 0, // length TIMEOUT); }
protected void setupUsb(UsbDevice device) { UsbInterface inf = device.getInterface(0); UsbDeviceConnection conn = mUsbManager.openDevice(device); if (conn == null) { Log.wtf("MainActivity", "unable to open device?"); return; } if (!conn.claimInterface(inf, true)) { conn.close(); Log.wtf("MainActivity", "unable to claim interface!"); return; } mBlinkDevice = device; mBlinkConn = conn; }
private void communicate () { UsbDeviceConnection connection = usbManager.openDevice(device); try { sPort.open(connection); sPort.setParameters(2400, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE); sPort.setRTS(false); sPort.setDTR(true); } catch (IOException e) { Log.e(TAG, "Error setting up device: " + e.getMessage(), e); mTitleTextView.setText("Error opening device: " + e.getMessage()); try { sPort.close(); } catch (IOException e2) { // Ignore. } sPort = null; return; } mTitleTextView.setText("Serial device: " + sPort.getClass().getSimpleName()); onDeviceStateChange(); }
@Override protected void onResume() { super.onResume(); changed=new HandleChange(3); calibCounter=0; Log.d(TAG, "Resumed, port=" + sPort); if (sPort == null) { mTitleTextView.setText("No serial device."); } else { usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager); if (availableDrivers.isEmpty()) { mTitleTextView.append("No drivers available\n"); Log.d("SerialKost", "no drivers available"); return; } UsbSerialDriver driver = availableDrivers.get(0); sPort = driver.getPorts().get(0); device=driver.getDevice(); UsbDeviceConnection connection = usbManager.openDevice(device); if (connection == null) { mTitleTextView.setText("Opening device failed"); PendingIntent mPermissionIntent; Log.i("SerialKost", "Setting PermissionIntent -> MainMenu"); mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); Log.i("SerialKost", "Setting IntentFilter -> MainMenu"); IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION); Log.i("SerialKost", "Setting registerReceiver -> MainMenu"); registerReceiver(mUsbReceiver, filter); Log.i("SerialKost", "Setting requestPermission -> MainMenu"); usbManager.requestPermission(device, mPermissionIntent); return; } communicate(); } }
public Boolean connectSerial(UsbDevice device, Integer baud) { UsbDeviceConnection connection = connectDevice(device); UsbSerialDevice serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection); _workingDevice = device; if(!serialPort.open()){ return false; }else { _serialPort = serialPort; serialPort.setBaudRate(baud); serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8); serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1); serialPort.setParity(UsbSerialInterface.PARITY_NONE); serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF); serialPort.read(mCallback); return true; } }
private boolean setDevice(UsbDevice device) { Logger.d("setDevice " + device); clearDevice(); if (null == device) { return false; } if (device.getVendorId() != mVendorId) { printDevice(device); Logger.i("Not a target vendor: expecting %d", mVendorId); return false; } if (device.getProductId() != mProductId) { printDevice(device); Logger.i("Not a target product: expecting %d", mProductId); return false; } if (!mUsbManager.hasPermission(device)) { Logger.d("request permission"); mUsbManager.requestPermission(device, mPermissionIntent); return false; } printDevice(device); try { UsbInterface usbinterface = device.getInterface(0); UsbDeviceConnection connection = mUsbManager.openDevice(device); if (!connection.claimInterface(usbinterface, true)) { return false; } mDevice = device; mConnection = connection; Logger.d("open SUCCESS"); if (null != mOnDeviceListener) { mOnDeviceListener.onAttached(); } return true; } catch (Exception e) { Logger.e(e, e.getLocalizedMessage()); } return false; }
private boolean setUsbInterface(android.hardware.usb.UsbDevice device, UsbInterface intf) { if (mDeviceConnection != null) { if (mInterface != null) { mDeviceConnection.releaseInterface(mInterface); mInterface = null; } mDeviceConnection.close(); mDevice = null; mDeviceConnection = null; } if (device != null && intf != null) { UsbDeviceConnection connection = mUsbManager.openDevice(device); if (connection != null) { if (connection.claimInterface(intf, true)) { mDevice = device; mDeviceConnection = connection; mInterface = intf; mFcDevice = new FcUsbDevice(this, mDeviceConnection, intf, mXmlObjects); mFcDevice.getObjectTree().setXmlObjects(mXmlObjects); mFcDevice.start(); return true; } else { connection.close(); } } } if (mDeviceConnection == null && mFcDevice != null) { mFcDevice.stop(); mFcDevice = null; } return false; }
public UsbHiSpeedBulk(UsbDeviceConnection usbDeviceConnection, UsbEndpoint usbEndpoint, int nrequests, int packetsPerRequests) { this.usbDeviceConnection = usbDeviceConnection; this.fileDescriptor = usbDeviceConnection.getFileDescriptor(); this.nrequests = nrequests; this.requests = new ArrayList<>(nrequests); this.packetSize = usbEndpoint.getMaxPacketSize(); this.usbEndpoint = usbEndpoint; this.packetsPerRequests = packetsPerRequests; this.buffer = new Buffer(packetsPerRequests * packetSize); }
public static Future<UsbDeviceConnection> obtainFdFor(Context context, UsbDevice usbDevice) { UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); if (!manager.hasPermission(usbDevice)) { AsyncFuture<UsbDeviceConnection> task = new AsyncFuture<>(); registerNewBroadcastReceiver(context, usbDevice, task); manager.requestPermission(usbDevice, PendingIntent.getBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), 0)); return task; } else { return new CompletedFuture<>(manager.openDevice(usbDevice)); } }
public UsbBulkSource(UsbDeviceConnection usbDeviceConnection, UsbEndpoint usbEndpoint, AlternateUsbInterface usbInterface, int numRequests, int numPacketsPerReq) { this.usbDeviceConnection = usbDeviceConnection; this.usbEndpoint = usbEndpoint; this.usbInterface = usbInterface; this.numRequests = numRequests; this.numPacketsPerReq = numPacketsPerReq; }
/** * Constructs a class driver object, if the device supports * operations according to Annex D of the PTP specification. * * @param dev the first PTP interface will be used * @param connection * @throws IllegalArgumentException if the device has no * Digital Still Imaging Class or PTP interfaces */ public SonyInitiator(UsbDevice dev, UsbDeviceConnection connection) throws PTPException { super(); this.mConnection = connection; if (dev == null) { throw new PTPException ("dev = null");//IllegalArgumentException(); } session = new Session(); this.device = dev; intf = findUsbInterface (dev); if (intf == null) { //if (usbInterface == null) { throw new PTPException("No PTP interfaces associated to the device"); } for (int i = 0; i < intf.getEndpointCount(); i++) { UsbEndpoint ep = intf.getEndpoint(i); if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (ep.getDirection() == UsbConstants.USB_DIR_OUT) { epOut = ep; } else { epIn = ep; } } if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT){ epEv = ep; } } endpointSanityCheck(); inMaxPS = epOut.getMaxPacketSize(); intrMaxPS = epIn.getMaxPacketSize(); // clear epOut any previous state reset(); }
/** * This is essentially a class driver, following Annex D of * the PTP specification. */ public NikonInitiator(UsbDevice dev, UsbDeviceConnection connection) throws PTPException { super(dev, connection); /* if (thread != null) eventListenerRunning = false; thread = new Thread (this); thread.start(); */ }
@Override public void open(UsbDeviceConnection connection) throws IOException { if (mConnection != null) { throw new IOException("Already open"); } mConnection = connection; boolean opened = false; try { if (1 == mDevice.getInterfaceCount()) { Log.d(TAG, "device might be castrated ACM device, trying single interface logic"); openSingleInterface(); } else { Log.d(TAG, "trying default interface logic"); openInterface(); } if (mEnableAsyncReads) { Log.d(TAG, "Async reads enabled"); } else { Log.d(TAG, "Async reads disabled."); } opened = true; } finally { if (!opened) { mConnection = null; // just to be on the save side mControlEndpoint = null; mReadEndpoint = null; mWriteEndpoint = null; } } }
@Override public NodeMain[] startNodes(UsbDevice baseUsbDevice, UsbManager usbManager) throws Exception { if(baseUsbDevice == null) { throw new Exception("null USB device provided"); } log.info("Starting base node"); // Wrap the UsbDevice in the HoHo Driver UsbSerialDriver driver = serialDriverForDevice(baseUsbDevice, usbManager); UsbDeviceConnection connection = serialConnectionForDevice(usbManager, driver); if (connection == null) { throw new Exception("No USB connection available to initialize device"); } UsbSerialPort port = serialPortForDevice(driver); // Choose the appropriate BaseDevice implementation for the particular // robot base, using the corresponding subclass BaseDevice baseDevice = getBaseDevice(port, connection); // Create the ROS nodes log.info("Create base controller node"); mBaseControllerNode = new BaseControllerNode(baseDevice, "/cmd_vel"); NodeConfiguration baseControllerNodeConf = NodeConfiguration.newPublic(mRosHostname); baseControllerNodeConf.setNodeName(GraphName.of("base_controller")); baseControllerNodeConf.setMasterUri(mRosMasterUri); mNodeMainExecutor.execute(mBaseControllerNode, baseControllerNodeConf); mBatteryPublisherNode = new RobotBatteryPublisherNode(baseDevice); NodeConfiguration batteryPublisherConf = NodeConfiguration.newPublic(mRosHostname); batteryPublisherConf.setNodeName(mBaseControllerNode.getDefaultNodeName()); batteryPublisherConf.setMasterUri(mRosMasterUri); mNodeMainExecutor.execute(mBatteryPublisherNode, batteryPublisherConf); return new NodeMain[]{mBaseControllerNode, mBaseOdomPublisher}; }
/** * Request the device descriptor through the USB device connection. */ public static DeviceDescriptor fromDeviceConnection(UsbDeviceConnection connection) throws IllegalArgumentException { byte[] buffer = new byte[LENGTH]; connection.controlTransfer(REQUEST_TYPE, REQUEST, REQ_VALUE, REQ_INDEX, buffer, LENGTH, TIMEOUT); return parseResponse(buffer); }
public CH34xSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { super(device, connection); rtsCtsEnabled = false; dtrDsrEnabled = false; mInterface = device.getInterface(iface >= 0 ? iface : 0); }
public CP2102SerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { super(device, connection); rtsCtsEnabled = false; dtrDsrEnabled = false; ctsState = true; dsrState = true; mInterface = device.getInterface(iface >= 0 ? iface : 0); }
public PL2303SerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { super(device, connection); if (iface > 1) { throw new IllegalArgumentException("Multi-interface PL2303 devices not supported!"); } mInterface = device.getInterface(iface >= 0 ? iface : 0); }
public FTDISerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { super(device, connection); ftdiUtilities = new FTDIUtilities(); rtsCtsEnabled = false; dtrDsrEnabled = false; ctsState = true; dsrState = true; firstTime = true; mInterface = device.getInterface(iface >= 0 ? iface : 0); }
public static UsbSpiDevice createUsbSerialDevice(UsbDevice device, UsbDeviceConnection connection, int iface) { int vid = device.getVendorId(); int pid = device.getProductId(); if(CP2130Ids.isDeviceSupported(vid, pid)) return new CP2130SpiDevice(device, connection, iface); else return null; }
@Override public void open(UsbDeviceConnection connection) throws IOException { if (mConnection != null) { throw new IOException("Already open"); } mConnection = connection; boolean opened = false; try { if (1 == mDevice.getInterfaceCount()) { Log.d(TAG,"device might be castrated ACM device, trying single interface logic"); openSingleInterface(); } else { Log.d(TAG,"trying default interface logic"); openInterface(); } if (mEnableAsyncReads) { Log.d(TAG, "Async reads enabled"); } else { Log.d(TAG, "Async reads disabled."); } opened = true; } finally { if (!opened) { mConnection = null; // just to be on the save side mControlEndpoint = null; mReadEndpoint = null; mWriteEndpoint = null; } } }
private void startSerialConnection(UsbManager usbManager, UsbDevice device) { UsbDeviceConnection connection = usbManager.openDevice(device); serial = UsbSerialDevice.createUsbSerialDevice(device, connection); if (serial != null && serial.open()) { serial.setBaudRate(115200); serial.setDataBits(UsbSerialInterface.DATA_BITS_8); serial.setStopBits(UsbSerialInterface.STOP_BITS_1); serial.setParity(UsbSerialInterface.PARITY_NONE); serial.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF); serial.setDTR(false); } }
/** Constructor. Inicia los EndPoints del Interfaz del dispositivo * @param usbDevCon * @param usbInterface */ protected SmartCardChannel(final UsbDeviceConnection usbDevCon, final UsbInterface usbInterface) { this.usbDeviceConnection = usbDevCon; for (int i = 0; i < usbInterface.getEndpointCount(); i++) { final UsbEndpoint usbEndPoint = usbInterface.getEndpoint(i); if (usbEndPoint.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { if (usbEndPoint.getDirection() == UsbConstants.USB_DIR_IN) { this.endPointIn = usbEndPoint; } else if (usbEndPoint.getDirection() == UsbConstants.USB_DIR_OUT) { this.endPointOut = usbEndPoint; } } } }
private void performUsbPermissionCallback(final UsbDevice device) { if (mUsbHandler.getLooper().getThread() != Thread.currentThread()) { mUsbHandler.post(new Runnable() { @Override public void run() { performUsbPermissionCallback(device); } }); return; } if (mPicoflexx != null) { Log.d(TAG, "Already have a picoflexx"); return; } UsbDeviceConnection conn = mUsbManager.openDevice(device); Log.i(TAG, "USB Device: " + device.getDeviceName() + ", fd: " + conn.getFileDescriptor()); if (!openPicoflexx(conn.getFileDescriptor())) { Log.e(TAG, "error initializing the picoflexx"); mUiHandler.obtainMessage(WHAT_STATE, STATE_ERROR, R.string.error_initializing) .sendToTarget(); conn.close(); return; } mConn = conn; mPicoflexx = device; final int width = getMaxWidth(); final int height = getMaxHeight(); mCloud.setWidth(width); mCloud.setHeight(height); mCloud.setRowStep(width * 12); mUiHandler.obtainMessage(WHAT_STATE, STATE_IDLE, -1).sendToTarget(); }