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; }
void showListOfDevices(Context context) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context); if (getDeviceList().isEmpty()) { alertBuilder.setTitle(R.string.usb_connect_title) .setPositiveButton(R.string.ok, null); } else { alertBuilder.setTitle(R.string.usb_select_title); List<CharSequence> list = new LinkedList<>(); for (UsbDevice usbDevice : getDeviceList().values()) { list.add("devID:" + usbDevice.getDeviceId() + " VID:" + Integer.toHexString(usbDevice.getVendorId()) + " PID:" + Integer.toHexString(usbDevice.getProductId()) + " " + usbDevice.getDeviceName()); } final CharSequence devicesName[] = new CharSequence[getDeviceList().size()]; list.toArray(devicesName); alertBuilder.setItems(devicesName, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { UsbDevice device = (UsbDevice) getDeviceList().values().toArray()[which]; mUsbManager.requestPermission(device, mPermissionIntent); } }); } alertBuilder.setCancelable(true); adScaleWarning = alertBuilder.show(); }
static public BaselineInitiator produceInitiator(UsbDevice device, UsbManager usbManager) throws PTPException { BaselineInitiator bi; CameraDetector cd = new CameraDetector(device); if (cd.getSupportedVendorId() == CameraDetector.VENDOR_ID_CANON) { Log.d(TAG, "Device is CANON, open EOSInitiator"); bi = new EosInitiator(device, usbManager.openDevice(device)); } else if (cd.getSupportedVendorId() == CameraDetector.VENDOR_ID_NIKON) { Log.d(TAG, "Device is Nikon, open NikonInitiator"); bi = new NikonInitiator(device, usbManager.openDevice(device)); } else if (cd.getSupportedVendorId() == CameraDetector.VENDOR_ID_SONY) { Log.d(TAG, "Device is Sony, open SonyInitiator"); bi = new SonyInitiator(device, usbManager.openDevice(device)); } else /* if (cd.getSupportedVendorId() == CameraDetector.VENDOR_ID_OTHER) */ { Log.d(TAG, "Unkown device, open BaselineInitiator"); bi = new BaselineInitiator (device, usbManager.openDevice(device)); } return bi; }
private UsbSerialPort findUsbSerialPort(ConfigStorage.SerialPortIdentifier identifier) { final List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager); for (final UsbSerialDriver driver : drivers) { for (final UsbSerialPort port : driver.getPorts()) { UsbDevice device = port.getDriver().getDevice(); if (device != null && device.getVendorId() == identifier.getVendorId() && device.getProductId() == identifier.getProductId() && Objects.equals(device.getSerialNumber(), identifier.getSerialNumber())) { return port; } } } return null; }
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; }
public void destroy() { unregister(); final Set<UsbDevice> keys = mCtrlBlocks.keySet(); if (keys != null) { UsbControlBlock ctrlBlock; try { for (final UsbDevice key: keys) { ctrlBlock = mCtrlBlocks.remove(key); ctrlBlock.close(); } } catch (final Exception e) { Log.e(TAG, "destroy:", e); } mCtrlBlocks.clear(); } }
public void getAllUsbDevices() { UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE); HashMap<String, UsbDevice> deviceList = manager.getDeviceList(); Iterator<UsbDevice> deviceIterator = deviceList.values().iterator(); int i = 0; while(deviceIterator.hasNext()){ i++; UsbDevice device = deviceIterator.next(); log("--------"); log("设备 : " + i); log("device id : " + device.getDeviceId()); log("name : " + device.getDeviceName()); log("class : " + device.getDeviceClass()); log("subclass : " + device.getDeviceSubclass()); log("vendorId : " + device.getVendorId()); // log("version : " + device.getVersion() ); log("serial number : " + device.getSerialNumber() ); log("interface count : " + device.getInterfaceCount()); log("device protocol : " + device.getDeviceProtocol()); log("--------"); } }
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; }
/** * Probes a single device for a compatible driver. * * @param usbDevice the usb device to probe * * @return a new {@link UsbSerialDriver} compatible with this device, or * {@code null} if none available. */ @Keep public UsbSerialDriver probeDevice(final UsbDevice usbDevice) { final int vendorId = usbDevice.getVendorId(); final int productId = usbDevice.getProductId(); final Class<? extends UsbSerialDriver> driverClass = mProbeTable.findDriver(vendorId, productId); if (driverClass != null) { final UsbSerialDriver driver; try { final Constructor<? extends UsbSerialDriver> constructor = driverClass.getConstructor(UsbDevice.class); driver = constructor.newInstance(usbDevice); } catch (Exception e) { throw new RuntimeException(e); } return driver; } return null; }
/** * Enumerate the endpoints and interfaces on the connected device. * * @param device Device to query. * @return String description of the device configuration. */ public static String readDevice(UsbDevice device) { StringBuilder sb = new StringBuilder(); sb.append("Device Name: " + device.getDeviceName() + "\n"); sb.append(String.format( "Device Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n", nameForClass(device.getDeviceClass()), device.getDeviceSubclass(), device.getDeviceProtocol())); for (int i = 0; i < device.getInterfaceCount(); i++) { UsbInterface intf = device.getInterface(i); sb.append(String.format(Locale.US, "-- Interface %d Class: %s -> Subclass: 0x%02x -> Protocol: 0x%02x\n", intf.getId(), nameForClass(intf.getInterfaceClass()), intf.getInterfaceSubclass(), intf.getInterfaceProtocol())); sb.append(String.format(Locale.US, " -- Endpoint Count: %d\n", intf.getEndpointCount())); } return sb.toString(); }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) { afterGetUsbPermission(null); } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) { disConnectDevice(); } else if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //user choose YES for your previously popup window asking for grant perssion for this usb device if (onUsbChangeListener != null) { onUsbChangeListener.onPermissionGranted(); } if (null != usbDevice) { afterGetUsbPermission(usbDevice); } } else { //user choose NO for your previously popup window asking for grant perssion for this usb device if (onUsbChangeListener != null) { onUsbChangeListener.onPermissionRefused(); } } } } }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action) || ACTION_USB_PERMISSION_AUTOCONNECT.equals(action)) { synchronized (this) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { Log.d(TAG, "permission denied for mDevice " + device); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage(R.string.permission_denied) .setTitle(R.string.permission_denied_title); builder.show(); } else if (ACTION_USB_PERMISSION_AUTOCONNECT.equals(action)) { // permission was granted, and now we need to hit up the connect button again btnConnect(null); } } } }
Af9035DvbDevice(UsbDevice usbDevice, Context context, DeviceFilter filter) throws DvbException { super(usbDevice, context, filter, DvbDemux.DvbDmxSwfilter()); iface = usbDevice.getInterface(0); controlEndpointIn = iface.getEndpoint(0); controlEndpointOut = iface.getEndpoint(1); endpoint = iface.getEndpoint(2); // Endpoint 3 is a TS USB_DIR_IN endpoint with address 0x85 // but I don't know what it is used for if (controlEndpointIn.getAddress() != 0x81 || controlEndpointIn.getDirection() != USB_DIR_IN) throw new DvbException(DVB_DEVICE_UNSUPPORTED, resources.getString(R.string.unexpected_usb_endpoint)); if (controlEndpointOut.getAddress() != 0x02 || controlEndpointOut.getDirection() != USB_DIR_OUT) throw new DvbException(DVB_DEVICE_UNSUPPORTED, resources.getString(R.string.unexpected_usb_endpoint)); if (endpoint.getAddress() != 0x84 || endpoint.getDirection() != USB_DIR_IN) throw new DvbException(DVB_DEVICE_UNSUPPORTED, resources.getString(R.string.unexpected_usb_endpoint)); }
/** * Gets a {@link DvbDevice} if a supported DVB USB dongle is connected to the system. * If multiple dongles are connected, a {@link Collection} would be returned * @param context a context for obtaining {@link Context#USB_SERVICE} * @return a {@link Collection} of available {@link DvbDevice} devices. Can be empty. */ public static List<DvbDevice> getUsbDvbDevices(Context context) throws DvbException { List<DvbDevice> availableDvbDevices = new ArrayList<>(); UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE); Collection<UsbDevice> availableDevices = manager.getDeviceList().values(); DvbException lastException = null; for (UsbDevice usbDevice : availableDevices) { try { DvbDevice frontend = getDvbUsbDeviceFor(usbDevice, context); if (frontend != null) availableDvbDevices.add(frontend); } catch (DvbException e) { // Failed to initialize this device, try next and capture exception e.printStackTrace(); lastException = e; } } if (availableDvbDevices.isEmpty()) { if (lastException != null) throw lastException; } return availableDvbDevices; }
@Override public void onStatusChanged(final UsbDevice device, int status) { Log.i(TAG, "onStatusChanged:" + status); if(status == FaBoUsbConst.ATTACHED) { mDevice = device; } else if(status == FaBoUsbConst.CONNECTED) { Log.i(TAG, "Write"); mDevice = device; this.runOnUiThread(new Runnable() { @Override public void run() { mEditText.setText("Connected " + device.getDeviceName()); } }); } }
protected void passReceivedUsbAttachmentsToEventLoop() { if (this.eventLoop != null) { for (;;) { UsbDevice usbDevice = receivedUsbAttachmentNotifications.poll(); if (usbDevice == null) break; this.eventLoop.onUsbDeviceAttached(usbDevice); } } else { // Paranoia: we don't want the pending list to grow without bound when we don't // (yet) have an event loop while (receivedUsbAttachmentNotifications.size() > 100) { receivedUsbAttachmentNotifications.poll(); } } }
private static boolean isRoyaleDevice(final UsbDevice device) { final int vid = device.getVendorId(); final int pid = device.getProductId(); if (vid != ROYALE_VENDOR_ID) { return false; } for (int id : ROYALE_PRODUCT_IDS) { if (id == pid) return true; } return false; }
private int connectUsbDevice() { final String tag = "connectUsbDevice - "; Log.d(TAG, tag); int result; if (Utils.is64bit()) { Analytics.getInstance().logEvent(Analytics.CATEGORY_ANDROID_DEVICE, "64 bit device", ""); } UsbDevice device = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device == null) { device = rtlSdrDevice.getUsbDevice(); if (device != null) { result = openDevice(device); } else { result = R.string.connect_usb_device_status_error_no_device_found; } } else { Log.d(TAG, tag + "Reusing connected device."); result = R.string.connect_usb_device_status_ok; } currentDevice = device; return result; }
/** * Find usb device. */ public void findDevice() { // Get UsbManager. UsbManager manager = (UsbManager) this.mContext.getSystemService(this.mContext.USB_SERVICE); // check vid and pid. HashMap<String, UsbDevice> deviceList = manager.getDeviceList(); Iterator<UsbDevice> deviceIterator = deviceList.values().iterator(); while (deviceIterator.hasNext()) { UsbDevice device = deviceIterator.next(); checkDevice(device); } }
private void addRoot(UsbDevice device) { try { UsbPartition usbPartition = new UsbPartition(); usbPartition.device = device; usbPartition.permissionGranted = false; mRoots.put(getRootId(device), usbPartition); } catch (Exception e) { Log.e(TAG, "error setting up device", e); } }
/** * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers} * from the currently-attached {@link UsbDevice} hierarchy. This method does * not require permission from the Android USB system, since it does not * open any of the devices. * * @param usbManager * @return a list, possibly empty, of all compatible drivers */ public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) { final List<UsbSerialDriver> result = new ArrayList<UsbSerialDriver>(); for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) { final UsbSerialDriver driver = probeDevice(usbDevice); if (driver != null) { result.add(driver); } } return result; }
@Override public void onFind(int type, UsbDevice device) { // Find Arduino if(type == TestConst.TEST_TYPE) { mFaBoUsbManger.connection(device); } }
private static int findFirstCDC(UsbDevice device) { int interfaceCount = device.getInterfaceCount(); for (int iIndex = 0; iIndex < interfaceCount; ++iIndex) { if (device.getInterface(iIndex).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) { return iIndex; } } Log.i(CLASS_ID, "There is no CDC class interface"); return -1; }
private static String nameForClass(UsbDevice usbDevice) { int classType = usbDevice.getDeviceClass(); switch (classType) { case UsbConstants.USB_CLASS_AUDIO: return "Audio"; case UsbConstants.USB_CLASS_CDC_DATA: return "CDC Control"; case UsbConstants.USB_CLASS_COMM: return "Communications"; case UsbConstants.USB_CLASS_CONTENT_SEC: return "Content Security"; case UsbConstants.USB_CLASS_CSCID: return "Content Smart Card"; case UsbConstants.USB_CLASS_HID: return "Human Interface Device"; case UsbConstants.USB_CLASS_HUB: return "Hub"; case UsbConstants.USB_CLASS_MASS_STORAGE: return "Mass Storage"; case UsbConstants.USB_CLASS_MISC: return "Wireless Miscellaneous"; case UsbConstants.USB_CLASS_PHYSICA: return "Physical"; case UsbConstants.USB_CLASS_PRINTER: return "Printer"; case UsbConstants.USB_CLASS_STILL_IMAGE: return "Still Image"; case UsbConstants.USB_CLASS_VENDOR_SPEC: return String.format("Vendor Specific 0x%02x", classType); case UsbConstants.USB_CLASS_VIDEO: return "Video"; case UsbConstants.USB_CLASS_WIRELESS_CONTROLLER: return "Wireless Controller"; default: return ""; } }
@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}; }
private UsbInterface findUsbInterface(UsbDevice device) { //Log.d (TAG, "findAdbInterface " + device.getDeviceName()); int count = device.getInterfaceCount(); for (int i = 0; i < count; i++) { UsbInterface intf = device.getInterface(i); Log.d (TAG, "Interface " +i + " Class " +intf.getInterfaceClass() +" Prot " +intf.getInterfaceProtocol()); if (intf.getInterfaceClass() == 6 //255 && intf.getInterfaceSubclass() == 66 && intf.getInterfaceProtocol() == 1 ) { return intf; } } return null; }
@Override public void onDisconnect(UsbDevice device, UsbControlBlock ctrlBlock) { if (cameraHandle != 0) { V4lJni.stopCamera(cameraHandle); cameraHandle = 0; } }
private void findDevice() { HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList(); if (!usbDevices.isEmpty()) { for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) { if (entry.getValue().getVendorId() == vendorId) { //vendor ID check if (App.IS_DEBUG) System.out.println("USB - VENDOR ID MATCH"); usbDevice = entry.getValue(); break; } } } else if (App.IS_DEBUG) { System.out.println("USB DEVICES LIST IS EMPTY"); } }
/** * return device list, return empty list if no device matched * @param filter * @return */ public List<UsbDevice> getDeviceList() { final HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList(); final List<UsbDevice> result = new ArrayList<UsbDevice>(); if (deviceList != null) { final Iterator<UsbDevice> iterator = deviceList.values().iterator(); UsbDevice device; while (iterator.hasNext()) { device = iterator.next(); result.add(device); } } return result; }
/** * Determine whether to list all devices or query a specific device from * the provided intent. * @param intent Intent to query. */ private void handleIntent(Intent intent) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { printStatus(getString(R.string.status_added)); printDeviceDetails(device); } else { // List all devices connected to USB host on startup printStatus(getString(R.string.status_list)); printDeviceList(); } }
private final void processCancel(final UsbDevice device) { if (DEBUG) Log.v(TAG, "processCancel:"); if (mOnDeviceConnectListener != null) { mHandler.post(new Runnable() { @Override public void run() { mOnDeviceConnectListener.onCancel(); } }); } }
private void discoverDevice(UsbDevice device) { for (UsbMassStorageDevice massStorageDevice : UsbMassStorageDevice.getMassStorageDevices(getContext())) { if (device.equals(massStorageDevice.getUsbDevice())) { if (hasPermission(device)) { addRoot(massStorageDevice); } else { requestPermission(device); } } } }
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; }
public CommonUsbSerialPort(UsbDevice device, int portNumber) { mDevice = device; mPortNumber = portNumber; mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE]; mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE]; }
private void detachDevice(UsbDevice usbDevice) { for (Map.Entry<String, UsbPartition> root : mRoots.entrySet()) { if (root.getValue().device.equals(usbDevice)) { Log.d(TAG, "remove rootId " + root.getKey()); mRoots.remove(root.getKey()); mFileCache.evictAll(); notifyRootsChanged(); break; } } }
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); } }
Rtl28xxDvbDevice(UsbDevice usbDevice, Context context, DeviceFilter deviceFilter) throws DvbException { super(usbDevice, context, deviceFilter, DvbDemux.DvbDmxSwfilter()); iface = usbDevice.getInterface(0); endpoint = iface.getEndpoint(0); if (endpoint.getAddress() != 0x81) throw new DvbException(DVB_DEVICE_UNSUPPORTED, resources.getString(R.string.unexpected_usb_endpoint)); }
private void requestPermission() { Activity activity = ctx.get(); if (activity != null) { PendingIntent mPermissionIntent = PendingIntent.getBroadcast(activity, 0, new Intent(ACTION_USB_PERMISSION), 0); //here do emulation to ask all connected usb device for permission for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) { if (usbManager.hasPermission(usbDevice)) { afterGetUsbPermission(usbDevice); } else { usbManager.requestPermission(usbDevice, mPermissionIntent); } } } }