예제 #1
0
 public UsbConnector(Context context) {
   UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
   HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
   Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
   Log.d(TAG, "===>UsbConnector");
   while (deviceIterator.hasNext()) {
     UsbDevice device = deviceIterator.next();
     Log.d(
         TAG,
         "device="
             + device.getDeviceName()
             + ","
             + device.getDeviceSubclass()
             + ","
             + device.getDeviceProtocol());
     Log.d(TAG, "ifs=" + device.getInterfaceCount() + "," + device.getInterface(0).toString());
     Log.d(TAG, "end=" + device.getInterface(0).getEndpoint(0).toString());
     Log.d(
         TAG,
         "class="
             + device.getDeviceClass()
             + ", pid="
             + device.getProductId()
             + ",vid="
             + device.getVendorId());
     // your code
   }
 }
예제 #2
0
  public static void authorize(Context svcContext, PendingIntent usbAuthPendingIntent) {
    androidUsbManager = ((UsbManager) svcContext.getSystemService(Context.USB_SERVICE));

    if (!androidUsbManager.hasPermission(adkAccessory)) {
      androidUsbManager.requestPermission(adkAccessory, usbAuthPendingIntent);
    }
  }
예제 #3
0
  /**
   * Searches for the device and opens it if successful
   *
   * @return true, if connection was successful
   */
  public boolean FindDevice() {
    _usbManager = (UsbManager) _context.getSystemService(Context.USB_SERVICE);

    HashMap<String, UsbDevice> deviceList = _usbManager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    _usbDevice = null;

    // Iterate all the available devices and find ours.
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      if (device.getProductId() == _productId && device.getVendorId() == _vendorId) {
        _usbDevice = device;
        _deviceName = _usbDevice.getDeviceName();
      }
    }

    if (_usbDevice == null) {
      Log("Cannot find the device. Did you forgot to plug it?");
      Log(String.format("\t I search for VendorId: %s and ProductId: %s", _vendorId, _productId));
      _connectionHandler.onDeviceNotFound();
      return false;
    }

    // Create and intent and request a permission.
    PendingIntent mPermissionIntent =
        PendingIntent.getBroadcast(_context, 0, new Intent(ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    _context.registerReceiver(mUsbReceiver, filter);

    _usbManager.requestPermission(_usbDevice, mPermissionIntent);
    Log("Found the device and requested permission.");
    return true;
  }
 /**
  * Iterate over all attached USB devices and look for Crazyradio. If Crazyradio is found, request
  * permission.
  */
 private static UsbDevice searchForCrazyradio(Context context, UsbManager usbManager) {
   UsbDevice device = null;
   HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
   // Iterate over USB devices
   for (Entry<String, UsbDevice> e : deviceList.entrySet()) {
     Log.i(
         LOG_TAG,
         "String: "
             + e.getKey()
             + " "
             + e.getValue().getVendorId()
             + " "
             + e.getValue().getProductId());
     if (isCrazyradio(e.getValue())) {
       device = e.getValue();
       break; // stop after first matching device is found
     }
   }
   if (device != null && !usbManager.hasPermission(device)) {
     Log.d(LOG_TAG, "Request permission");
     mPermissionIntent =
         PendingIntent.getBroadcast(
             context, 0, new Intent(context.getPackageName() + ".USB_PERMISSION"), 0);
     usbManager.requestPermission(device, mPermissionIntent);
   } else if (device != null && usbManager.hasPermission(device)) {
     Log.d(LOG_TAG, "Has permission");
   } else {
     Log.d(LOG_TAG, "device == null");
   }
   return device;
 }
예제 #5
0
  @Override
  public void onResume() {
    super.onResume();

    // Return if the streams are already initialized
    if (mInputStream != null && mOutputStream != null) {
      return;
    }

    // Initialize the streams
    UsbAccessory[] accessories = mUsbManager.getAccessoryList();
    UsbAccessory accessory = (accessories == null ? null : accessories[0]);
    if (accessory != null) {
      if (mUsbManager.hasPermission(accessory)) {
        openAccessory(accessory);
      } else {
        synchronized (mUsbReceiver) {
          if (!mPermissionRequestPending) {
            mUsbManager.requestPermission(accessory, mPermissionIntent);
            mPermissionRequestPending = true;
          }
        }
      }
    } else {
      Log.d(TAG, "mAccessory is null");
    }
  }
예제 #6
0
  /**
   * デバイスの利用開始。
   *
   * @return null=正常、null以外=エラーメッセージ
   */
  public String onStart(UsbDevice device) {
    Log.d(TAG, "onStart:" + device);
    if (!device.equals(usbDevice)) {
      return "No device attach.";
    }
    if (!usbManager.hasPermission(usbDevice)) {
      return "No device permission.";
    }

    usbConnection = usbManager.openDevice(usbDevice);
    // TODO:インターフェースの検出は端折ってます。
    UsbInterface usbIf = usbDevice.getInterface(INTERFACE_INDEX);

    // EndPointの検索。分かってる場合は直接取り出しても良い。
    for (int i = 0; i < usbIf.getEndpointCount(); i++) {
      UsbEndpoint ep = usbIf.getEndpoint(i);
      Log.d(TAG, "tye=" + ep.getType());
      if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
        if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
          endpointIn = ep;
        } else if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
          endpointOut = ep;
        }
      }
    }
    if (endpointIn == null || endpointOut == null) {
      Log.e(TAG, "Device has not IN/OUT Endpoint.");
      return "Device has not IN/OUT Endpoint.";
    }
    // デバイスの確保
    usbConnection.claimInterface(usbIf, true);
    isReady = true;
    return null;
  }
예제 #7
0
  @Override
  protected void onResume() {
    super.onResume();
    setNames(); // in case name changed, we also want the name to update on its button
    if (mInputStream != null && mOutputStream != null) {
      return;
    }

    UsbAccessory accessories[] = mUsbManager.getAccessoryList();
    UsbAccessory accessory = (accessories == null ? null : accessories[0]);
    if (accessory != null) {
      if (mUsbManager.hasPermission(accessory)) {
        openAccessory(accessory);
      } else {
        synchronized (mUsbReceiver) {
          if (!mPermissionRequestPending) {
            mUsbManager.requestPermission(accessory, mPermissionIntent);
            mPermissionRequestPending = true;
          }
        }
      }
    } else {
      Log.d(TAG, "mAccessory is null");
      debug.setText("didnt reopen accessory");
    }
  }
    private void updateUsbNotification() {
      if (mNotificationManager == null || !mUseUsbNotification) return;
      int id = 0;
      Resources r = mContext.getResources();
      if (mConnected || mHostConnected) {
        if (!mUsbDataUnlocked) {
          id = com.android.internal.R.string.usb_charging_notification_title;
        } else if (UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_MTP)) {
          id = com.android.internal.R.string.usb_mtp_notification_title;
        } else if (UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_PTP)) {
          id = com.android.internal.R.string.usb_ptp_notification_title;
        } else if (UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_MIDI)) {
          id = com.android.internal.R.string.usb_midi_notification_title;
        } else if (UsbManager.containsFunction(
            mCurrentFunctions, UsbManager.USB_FUNCTION_ACCESSORY)) {
          id = com.android.internal.R.string.usb_accessory_notification_title;
        } else {
          id = com.android.internal.R.string.usb_charging_notification_title;
        }
      }
      if (id != mUsbNotificationId) {
        // clear notification if title needs changing
        if (mUsbNotificationId != 0) {
          mNotificationManager.cancelAsUser(null, mUsbNotificationId, UserHandle.ALL);
          mUsbNotificationId = 0;
        }
        if (id != 0) {
          CharSequence message = r.getText(com.android.internal.R.string.usb_notification_message);
          CharSequence title = r.getText(id);

          Intent intent =
              Intent.makeRestartActivityTask(
                  new ComponentName(
                      "com.android.settings",
                      "com.android.settings.deviceinfo.UsbModeChooserActivity"));
          PendingIntent pi =
              PendingIntent.getActivityAsUser(mContext, 0, intent, 0, null, UserHandle.CURRENT);

          Notification notification =
              new Notification.Builder(mContext)
                  .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb)
                  .setWhen(0)
                  .setOngoing(true)
                  .setTicker(title)
                  .setDefaults(0) // please be quiet
                  .setPriority(Notification.PRIORITY_MIN)
                  .setColor(
                      mContext.getColor(
                          com.android.internal.R.color.system_notification_accent_color))
                  .setContentTitle(title)
                  .setContentText(message)
                  .setContentIntent(pi)
                  .setVisibility(Notification.VISIBILITY_PUBLIC)
                  .build();
          mNotificationManager.notifyAsUser(null, id, notification, UserHandle.ALL);
          mUsbNotificationId = id;
        }
      }
    }
 private String applyAdbFunction(String functions) {
   if (mAdbEnabled) {
     functions = UsbManager.addFunction(functions, UsbManager.USB_FUNCTION_ADB);
   } else {
     functions = UsbManager.removeFunction(functions, UsbManager.USB_FUNCTION_ADB);
   }
   return functions;
 }
예제 #10
0
 private void setToMtpByDefault() {
   UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
   StringBuilder builder = new StringBuilder();
   builder.append(UsbManager.USB_FUNCTION_MTP);
   builder.append(",");
   builder.append(UsbManager.USB_FUNCTION_MASS_STORAGE);
   String targetFunction = builder.toString();
   usbManager.setCurrentFunction(targetFunction, true);
 }
        @Override
        public void handleMessage(Message msg) {
          synchronized (mLock) {
            switch (msg.what) {
              case MSG_UPDATE_STATE:
                if (mConnected != mLastConnected || mConfiguration != mLastConfiguration) {
                  if (mConnected == 0) {
                    if (UsbManager.isFunctionEnabled(UsbManager.USB_FUNCTION_ACCESSORY)) {
                      // make sure accessory mode is off, and restore default functions
                      Log.d(TAG, "exited USB accessory mode");
                      if (!UsbManager.setFunctionEnabled(
                          UsbManager.USB_FUNCTION_ACCESSORY, false)) {
                        Log.e(TAG, "could not disable accessory function");
                      }
                      int count = mDefaultFunctions.size();
                      for (int i = 0; i < count; i++) {
                        String function = mDefaultFunctions.get(i);
                        if (!UsbManager.setFunctionEnabled(function, true)) {
                          Log.e(TAG, "could not reenable function " + function);
                        }
                      }

                      if (mCurrentAccessory != null) {
                        mDeviceManager.accessoryDetached(mCurrentAccessory);
                        mCurrentAccessory = null;
                      }
                    }
                  }

                  final ContentResolver cr = mContext.getContentResolver();
                  if (Settings.Secure.getInt(cr, Settings.Secure.DEVICE_PROVISIONED, 0) == 0) {
                    Slog.i(TAG, "Device not provisioned, skipping USB broadcast");
                    return;
                  }

                  mLastConnected = mConnected;
                  mLastConfiguration = mConfiguration;

                  // send a sticky broadcast containing current USB state
                  Intent intent = new Intent(UsbManager.ACTION_USB_STATE);
                  intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
                  intent.putExtra(UsbManager.USB_CONNECTED, mConnected != 0);
                  intent.putExtra(UsbManager.USB_CONFIGURATION, mConfiguration);
                  addEnabledFunctionsLocked(intent);
                  mContext.sendStickyBroadcast(intent);
                }
                break;
              case MSG_FUNCTION_ENABLED:
              case MSG_FUNCTION_DISABLED:
                functionEnabledLocked((String) msg.obj, msg.what == MSG_FUNCTION_ENABLED);
                break;
            }
          }
        }
  int waitForUSBPermission() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    if (usbListener == null) return -1;
    while (!usbListener.permissionGranted()) {
      SystemClock.sleep(100);
    }

    UsbDevice depthCamera = usbListener.getDevice();
    UsbDeviceConnection con = manager.openDevice(depthCamera);
    return con.getFileDescriptor();
  }
예제 #13
0
  @Override
  protected void onResume() {
    super.onResume();

    HashMap<String, UsbDevice> deviceList = mManager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      if (device.getProductId() == PID && device.getVendorId() == VID) {
        if (mManager.hasPermission(device)) mManager.requestPermission(device, mPermissionIntent);
        break;
      }
    }
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
      getFragmentManager()
          .beginTransaction()
          .add(R.id.container, new PlaceholderFragment())
          .commit();
    }
    //
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    //
    filterAttached_and_Detached = new IntentFilter(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
    filterAttached_and_Detached.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
    filterAttached_and_Detached.addAction(ACTION_USB_PERMISSION);
    //
    registerReceiver(mUsbReceiver, filterAttached_and_Detached);
    //

    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
    Log.d("1", deviceList.size() + " USB device(s) found");
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    while (deviceIterator.hasNext()) {
      UsbDevice device = deviceIterator.next();
      Log.d("1", "" + device);
    }
  }
예제 #15
0
  public void setDevice(UsbManager usbManager, UsbDevice usbDevice) {
    //		Log.d(TAG, "setDevice " + usbDevice);

    device = usbDevice;

    if (device != null) {
      usbDeviceDump(usbDevice);

      UsbInterface controlInterface = device.getInterface(1);

      endpoint = controlInterface.getEndpoint(0);

      UsbDeviceConnection connection = usbManager.openDevice(device);

      if (connection != null && connection.claimInterface(controlInterface, true)) {
        controlConnection = connection;
        serial = UsbSerialDevice.createUsbSerialDevice(device, controlConnection);
        boolean t = serial.open();
        Log.d("Set DEVICE : ", "" + t);
        serial.setBaudRate(9600);
        serial.setParity(UsbSerialInterface.PARITY_NONE);
        serial.setStopBits(UsbSerialInterface.STOP_BITS_1);
        serial.setDataBits(UsbSerialInterface.DATA_BITS_8);
      } else {
        Log.e(TAG, "open connection FAIL");
        controlConnection = null;
      }
    }
  }
예제 #16
0
  private UsbDevice findDevice() {
    HashMap<String, UsbDevice> devList = mUsbManager.getDeviceList();

    for (UsbDevice dev : devList.values()) {
      Log.d(
          TAG,
          "Dev: "
              + dev
              + " "
              + dev.hashCode()
              + " "
              + dev.getVendorId()
              + " "
              + dev.getProductId()
              + " "
              + dev.getDeviceId()
              + " "
              + dev.getDeviceName());

      if (isCSCID(dev)) {
        return dev;
      }
    }
    return null;
  }
  private void setDevice(UsbDevice device) {
    mConnection = mUsbManager.openDevice(device);
    intf = device.getInterface(0);
    UsbEndpoint epOut = null;
    UsbEndpoint epIn = null;
    UsbEndpoint epEv = null;
    // Looking for 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 (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
        epEv = ep;
      }
    }
    if (epOut == null || epIn == null || epEv == null) {
      throw new IllegalArgumentException("not all endpoints found");
    }

    mEndpointBulkOut = epOut;
    mEndpointBulkIn = epIn;
    mEndpointIntr = epEv;
    inMaxPS = mEndpointBulkIn.getMaxPacketSize();
  }
예제 #18
0
 @Override
 public void onReceive(Context arg0, Intent arg1) {
   if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
     boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
     if (granted) // User accepted our USB connection. Try to open the device as a serial
                  // port
     {
       Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
       arg0.sendBroadcast(intent);
       connection = usbManager.openDevice(device);
       serialPortConnected = true;
       new ConnectionThread().run();
     } else // User not accepted our USB connection. Send an Intent to the Main Activity
     {
       Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
       arg0.sendBroadcast(intent);
     }
   } else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
     if (!serialPortConnected)
       findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial
                               // port
   } else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
     // Usb device was disconnected. send an intent to the Main Activity
     Intent intent = new Intent(ACTION_USB_DISCONNECTED);
     arg0.sendBroadcast(intent);
     serialPortConnected = false;
     serialPort.close();
   }
 }
예제 #19
0
  private void findSerialPortDevice() {
    // This snippet will try to open the first encountered usb device connected, excluding usb root
    // hubs
    HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
    if (!usbDevices.isEmpty()) {
      boolean keep = true;
      for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
        device = entry.getValue();
        int deviceVID = device.getVendorId();
        int devicePID = device.getProductId();

        if (deviceVID != 0x1d6b
            && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
          // There is a device connected to our Android device. Try to open it as a Serial Port.
          requestUserPermission();
          keep = false;
        } else {
          connection = null;
          device = null;
        }

        if (!keep) break;
      }
      if (!keep) {
        // There is no USB devices connected (but usb host were listed). Send an intent to
        // MainActivity.
        Intent intent = new Intent(ACTION_NO_USB);
        sendBroadcast(intent);
      }
    } else {
      // There is no USB devices connected. Send an intent to MainActivity
      Intent intent = new Intent(ACTION_NO_USB);
      sendBroadcast(intent);
    }
  }
예제 #20
0
 /**
  * デバイスの接続通知。
  *
  * @return null=正常、null以外=エラーメッセージ
  */
 public String onAttach(UsbDevice device) {
   Log.d(TAG, "onAttach:" + device);
   usbDevice = device;
   if (usbDevice == null) {
     Log.e(TAG, "Not found USB Device.");
     return "Not found USB Device.";
   }
   if (usbManager.hasPermission(usbDevice)) {
     return onStart(usbDevice);
   } else {
     // デバイスの利用許可をユーザに求める。
     // 結果は UsbReceiver.onReceive()にコールバック。
     usbManager.requestPermission(usbDevice, permissionIntent);
   }
   return null;
 }
    private void updateAudioSourceFunction() {
      boolean enabled =
          UsbManager.containsFunction(mCurrentFunctions, UsbManager.USB_FUNCTION_AUDIO_SOURCE);
      if (enabled != mAudioSourceEnabled) {
        int card = -1;
        int device = -1;

        if (enabled) {
          Scanner scanner = null;
          try {
            scanner = new Scanner(new File(AUDIO_SOURCE_PCM_PATH));
            card = scanner.nextInt();
            device = scanner.nextInt();
          } catch (FileNotFoundException e) {
            Slog.e(TAG, "could not open audio source PCM file", e);
          } finally {
            if (scanner != null) {
              scanner.close();
            }
          }
        }
        mUsbAlsaManager.setAccessoryAudioState(enabled, card, device);
        mAudioSourceEnabled = enabled;
      }
    }
예제 #22
0
  public String Open_USB_Port() {
    List<UsbSerialDriver> availableDrivers =
        UsbSerialProber.getDefaultProber().findAllDrivers(mUsbManager);
    String message = "null";
    if (availableDrivers.isEmpty()) {
      Log.v(TAG, "No USB Drivers connected");
      return "No Drivers Detected";
    }

    final UsbSerialDriver driver = availableDrivers.get(0);

    connection = mUsbManager.openDevice(driver.getDevice());
    if (connection == null) {
      Log.v(TAG, "No USB connection found");
      return "No USB Available";
    } else {
      final List<UsbSerialPort> portList = driver.getPorts();
      port = portList.get(0);
      try {
        port.open(connection);
        port.setParameters(38400, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
        return "USB Connected";
      } catch (IOException e) {
        System.out.print("Can't Connect to ELM327!");
        // alertView("Connection Problem", "Can't find the ELM327");
      }
    }
    return message;
  }
예제 #23
0
 /**
  * Creates and returns a new {@link UsbSerialDriver} instance for the first compatible {@link
  * UsbDevice} found on the bus. If none are found, returns {@code null}.
  *
  * <p>The order of devices is undefined, therefore if there are multiple devices on the bus, the
  * chosen device may not be predictable (clients should use {@link #findAllDevices(UsbManager)}
  * instead).
  *
  * @param usbManager the {@link UsbManager} to use.
  * @return the first available {@link UsbSerialDriver}, or {@code null} if none are available.
  */
 public static UsbSerialDriver findFirstDevice(final UsbManager usbManager) {
   for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
     for (final UsbSerialProber prober : values()) {
       final List<UsbSerialDriver> probedDevices = prober.probe(usbManager, usbDevice);
       if (!probedDevices.isEmpty()) {
         return probedDevices.get(0);
       }
     }
   }
   return null;
 }
예제 #24
0
 /**
  * Creates a new {@link UsbSerialDriver} instance for all compatible {@link UsbDevice}s found on
  * the bus. If no compatible devices are found, the list will be empty.
  *
  * @param usbManager
  * @return
  */
 public static List<UsbSerialDriver> findAllDevices(final UsbManager usbManager) {
   final List<UsbSerialDriver> result = new ArrayList<UsbSerialDriver>();
   // Log.i("QGC_UsbSerialProber", "Looking for USB devices");
   // For each UsbDevice, call probe() for each prober.
   for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
     // Log.i("QGC_UsbSerialProber", "Probing device: " + usbDevice.getDeviceName() + " mid: " +
     // usbDevice.getVendorId() + " pid: " + usbDevice.getDeviceId());
     result.addAll(probeSingleDevice(usbManager, usbDevice));
   }
   return result;
 }
예제 #25
0
 @Override
 public List<UsbSerialDriver> probe(final UsbManager manager, final UsbDevice usbDevice) {
   if (!testIfSupported(usbDevice, Cp2102SerialDriver.getSupportedDevices())) {
     return Collections.emptyList();
   }
   final UsbDeviceConnection connection = manager.openDevice(usbDevice);
   if (connection == null) {
     return Collections.emptyList();
   }
   final UsbSerialDriver driver = new Cp2102SerialDriver(usbDevice, connection);
   return Collections.singletonList(driver);
 }
예제 #26
0
 private static UsbDevice findDevice(UsbManager usbManager, int venderId, int productId) {
   HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
   Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
   while (deviceIterator.hasNext()) {
     UsbDevice d = deviceIterator.next();
     Log.d(TAG, "device=" + d);
     if (d.getVendorId() == venderId && d.getProductId() == productId) {
       return d;
     }
   }
   return null;
 }
예제 #27
0
  // initializes the usb connection to the arduino
  // returns the the status to be displayed on the GUI
  public static String start(Context context) {
    Log.i(TAG, "Starting ArduinoController");

    // set up usb manager
    if (usbManager == null) usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

    // get all available usb drivers
    Log.i(TAG, "Listing Drivers");
    SystemClock.sleep(1000);
    List<UsbSerialDriver> drivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
    if (drivers.isEmpty()) {
      Log.i(TAG, "No drivers found!");
      return "No drivers found!";
    }

    // look for a supported usb driver
    Log.i(TAG, "Drivers found: " + drivers.toString());
    arduinoPort = drivers.get(0).getPorts().get(0); // assume first one is the arduino

    if (arduinoPort == null) {
      Log.i(TAG, "Did not find arduino device.");
      return "Arduino Not Found!";
    }

    // open the usb device
    UsbDevice device = arduinoPort.getDriver().getDevice();
    Log.i(TAG, "Connected to productID: " + device.getVendorId());
    UsbDeviceConnection connection = usbManager.openDevice(device);
    if (connection == null) {
      Log.i(TAG, "Could not open device");
      return "Opening device failed!";
    }

    // open usb connection and set parity and baud rate
    try {
      arduinoPort.open(connection);
      // set to send over 8 bits
      arduinoPort.setParameters(
          9600, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
    } catch (IOException e) {
      String result = "Error opening device: " + e.getMessage();
      Log.i(TAG, result);
      try {
        arduinoPort.close();
      } catch (IOException e2) {
        // Ignore
      }
      return result;
    }

    onDeviceStateChange(); // Restart the IO manager
    return "Connected to: " + arduinoPort.getClass().getSimpleName();
  }
예제 #28
0
 private void openAccessory(UsbAccessory accessory) {
   mFileDescriptor = mUsbManager.openAccessory(accessory);
   if (mFileDescriptor != null) {
     mAccessory = accessory;
     FileDescriptor fd = mFileDescriptor.getFileDescriptor();
     mInputStream = new FileInputStream(fd);
     mOutputStream = new FileOutputStream(fd);
     Log.d(TAG, "accessory opened");
   } else {
     Log.d(TAG, "accessory open fail");
   }
 }
예제 #29
0
  public ZBCoordinator(Context context, String actionUsbPermission) {
    super();
    UsbManager manager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();

    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
    UsbDevice device = null;
    while (deviceIterator.hasNext()) {
      UsbDevice devi = deviceIterator.next();
      // TODO Remove hardcoded IDs
      if (devi.getProductId() == 0x05dc && devi.getVendorId() == 0x16c0) device = devi;
      // TODO Make sure this is the ZBCoordinator using RAW Descriptors
    }

    PendingIntent mPermissionIntent =
        PendingIntent.getBroadcast(context, 0, new Intent(actionUsbPermission), 0);

    if (device != null && !manager.hasPermission(device))
      manager.requestPermission(device, mPermissionIntent);

    if (device != null && manager.hasPermission(device)) {
      UsbInterface intf = device.getInterface(0);
      this.endpointInt = intf.getEndpoint(0);
      this.usbDeviceConnection = manager.openDevice(device);
      this.usbDeviceConnection.claimInterface(intf, false);
      this.canUse = true;
    }
  }
예제 #30
0
 // GIVEN FUNCTIONS
 private void openAccessory(UsbAccessory mAccessory2) {
   mFileDescriptor = mUsbManager.openAccessory(mAccessory2);
   if (mFileDescriptor != null) {
     mAccessory = mAccessory2;
     FileDescriptor fd = mFileDescriptor.getFileDescriptor();
     mInputStream = new FileInputStream(fd);
     mOutputStream = new FileOutputStream(fd);
     Log.d(TAG, "accessory opened");
   } else {
     Log.d(TAG, "accessory open fail");
     debug.setText("did not open");
   }
 }