下面列出了android.hardware.usb.UsbManager#openDevice ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
UsbTransfer(ResultReceiver resultReceiver, Context context, UsbDevice usbDevice, UsbManager usbManager) throws Exception{
super(resultReceiver, context);
if (usbManager == null) {
finish();
return;
}
usbInterface = usbDevice.getInterface(0);
epIn = usbInterface.getEndpoint(0); // For bulk read
epOut = usbInterface.getEndpoint(1); // For bulk write
deviceConnection = usbManager.openDevice(usbDevice);
if ( ! deviceConnection.claimInterface(usbInterface, false)) {
issueDescription = "USB: failed to claim interface";
throw new Exception("USB: failed to claim interface");
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) throws IOException {
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) throw new IOException("Device not connected");
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
for (int i = 0; i < dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
} else {
out = tmpEndpoint;
}
}
connection.claimInterface(dongleInterface, true);
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out);
}
/**
* USB機器情報(ベンダー名・製品名・バージョン・シリアル等)を取得する
* @param manager
* @param device
* @param out
* @return
*/
@SuppressLint("NewApi")
public static UsbDeviceInfo getDeviceInfo(
@NonNull final UsbManager manager,
@Nullable final UsbDevice device, @Nullable final UsbDeviceInfo out) {
final UsbDeviceConnection connection
= (device != null && manager.hasPermission(device))
? manager.openDevice(device) : null;
try {
return getDeviceInfo(connection, device, out);
} finally {
if (connection != null) {
connection.close();
}
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
return null;
}
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE) || (device.getProductId() == PID_NANOX));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
UsbCardDevice(Context context, UsbDevice usbDevice, String status) throws IOException {
super(context, status);
this.usbDevice = usbDevice;
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
throw new IOException(context.getString(R.string.failed_open_usb_connection));
}
usbDeviceConnection = usbManager.openDevice(usbDevice);
if (usbDeviceConnection == null) {
throw new IOException(context.getString(R.string.failed_open_usb_connection));
}
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
static synchronized MtpDevice openMTP(final UsbDevice device) {
if (device == null) {
return null;
}
final UsbManager usbManager = (UsbManager) xdrip.getAppContext().getSystemService(Context.USB_SERVICE);
if (usbManager == null) {
Log.d(TAG, "usbmanager is null in openMTP");
return null;
}
final MtpDevice mtpDevice = new MtpDevice(device);
final UsbDeviceConnection usbDeviceConnection = usbManager.openDevice(device);
try {
if (!mtpDevice.open(usbDeviceConnection)) {
return null;
}
} catch (Exception e) {
JoH.static_toast_long("Exception opening USB: " + e);
return null;
}
return mtpDevice;
}
public static BTChipTransport open(UsbManager manager, UsbDevice device) {
// Must only be called once permission is granted (see http://developer.android.com/reference/android/hardware/usb/UsbManager.html)
// Important if enumerating, rather than being awaken by the intent notification
UsbInterface dongleInterface = device.getInterface(0);
UsbEndpoint in = null;
UsbEndpoint out = null;
boolean ledger;
for (int i=0; i<dongleInterface.getEndpointCount(); i++) {
UsbEndpoint tmpEndpoint = dongleInterface.getEndpoint(i);
if (tmpEndpoint.getDirection() == UsbConstants.USB_DIR_IN) {
in = tmpEndpoint;
}
else {
out = tmpEndpoint;
}
}
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
return null;
}
connection.claimInterface(dongleInterface, true);
ledger = ((device.getProductId() == PID_HID_LEDGER) || (device.getProductId() == PID_HID_LEDGER_PROTON)
|| (device.getProductId() == PID_NANOS) || (device.getProductId() == PID_BLUE));
if (device.getProductId() == PID_WINUSB) {
return new BTChipTransportAndroidWinUSB(connection, dongleInterface, in, out, TIMEOUT);
}
else {
return new BTChipTransportAndroidHID(connection, dongleInterface, in, out, TIMEOUT, ledger);
}
}
/**
* Constructs a UsbMidiDeviceAndroid.
* @param manager
* @param device The USB device which this object is assocated with.
*/
UsbMidiDeviceAndroid(UsbManager manager, UsbDevice device) {
mConnection = manager.openDevice(device);
mEndpointMap = new SparseArray<UsbEndpoint>();
mRequestMap = new HashMap<UsbEndpoint, UsbRequest>();
mHandler = new Handler();
mUsbDevice = device;
mIsClosed = false;
mHasInputThread = false;
mNativePointer = 0;
for (int i = 0; i < device.getInterfaceCount(); ++i) {
UsbInterface iface = device.getInterface(i);
if (iface.getInterfaceClass() != UsbConstants.USB_CLASS_AUDIO
|| iface.getInterfaceSubclass() != MIDI_SUBCLASS) {
continue;
}
mConnection.claimInterface(iface, true);
for (int j = 0; j < iface.getEndpointCount(); ++j) {
UsbEndpoint endpoint = iface.getEndpoint(j);
if (endpoint.getDirection() == UsbConstants.USB_DIR_OUT) {
mEndpointMap.put(endpoint.getEndpointNumber(), endpoint);
}
}
}
// Start listening for input endpoints.
// This function will create and run a thread if there is USB-MIDI endpoints in the
// device. Note that because UsbMidiDevice is shared among all tabs and the thread
// will be terminated when the device is disconnected, at most one thread can be created
// for each connected USB-MIDI device.
startListen(device);
}
private void connect(Boolean permissionGranted) {
UsbDevice device = null;
UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
for(UsbDevice v : usbManager.getDeviceList().values())
if(v.getDeviceId() == deviceId)
device = v;
if(device == null) {
status("connection failed: device not found");
return;
}
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
if(driver == null) {
driver = CustomProber.getCustomProber().probeDevice(device);
}
if(driver == null) {
status("connection failed: no driver for device");
return;
}
if(driver.getPorts().size() < portNum) {
status("connection failed: not enough ports at device");
return;
}
usbSerialPort = driver.getPorts().get(portNum);
UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
if(usbConnection == null && permissionGranted == null && !usbManager.hasPermission(driver.getDevice())) {
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(Constants.INTENT_ACTION_GRANT_USB), 0);
usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
return;
}
if(usbConnection == null) {
if (!usbManager.hasPermission(driver.getDevice()))
status("connection failed: permission denied");
else
status("connection failed: open failed");
return;
}
connected = Connected.Pending;
try {
usbSerialPort.open(usbConnection);
usbSerialPort.setParameters(baudRate, UsbSerialPort.DATABITS_8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), usbConnection, usbSerialPort);
service.connect(socket);
// usb connect is not asynchronous. connect-success and connect-error are returned immediately from socket.connect
// for consistency to bluetooth/bluetooth-LE app use same SerialListener and SerialService classes
onSerialConnect();
} catch (Exception e) {
onSerialConnectError(e);
}
}
public static Trezor getDevice(final Context context) {
final UsbManager manager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device: manager.getDeviceList().values()) {
// Check if the device is TREZOR (or AvalonWallet or BWALLET)
final int vendorId = device.getVendorId();
final int productId = device.getProductId();
if ((vendorId != 0x534c || productId != 0x0001) &&
(vendorId != 0x1209 || productId != 0x53c0) &&
(vendorId != 0x1209 || productId != 0x53c1) &&
(vendorId != 0x10c4 || productId != 0xea80)) {
continue;
}
Log.d(TAG, "Hardware Wallet device found");
if (device.getInterfaceCount() < 1) {
Log.e(TAG, "Wrong interface count");
continue;
}
// Use first interface
final UsbInterface iface = device.getInterface(0);
// Try to find read/write endpoints
UsbEndpoint readEndpoint = null, writeEndpoint = null;
for (int i = 0; i < iface.getEndpointCount(); ++i) {
final UsbEndpoint ep = iface.getEndpoint(i);
if (readEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
ep.getAddress() == 0x81) {
// number = 1 ; dir = USB_DIR_IN
readEndpoint = ep;
continue;
}
if (writeEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
(ep.getAddress() == 0x01 || ep.getAddress() == 0x02)) {
// number = 1 ; dir = USB_DIR_OUT
writeEndpoint = ep;
continue;
}
Log.d(TAG, String.format("ep %d", ep.getAddress()));
}
if (isEndpointBad(readEndpoint, "read") || isEndpointBad(writeEndpoint, "write"))
continue;
// Try to open the device
final UsbDeviceConnection conn = manager.openDevice(device);
if (conn == null || !conn.claimInterface(iface, true)) {
Log.e(TAG, conn == null ? "Could not open connection" : "Could not claim interface");
continue;
}
// All OK - return the class
return new Trezor(device, conn, readEndpoint, writeEndpoint);
}
return null;
}
protected UsbDeviceConnection serialConnectionForDevice(UsbManager manager, UsbSerialDriver driver) {
return manager.openDevice(driver.getDevice());
}
private boolean init_USB(UsbDevice dev) {
showLog("Init_USB");
try {
if (dev == null)
return false;
UsbManager usbm = (UsbManager) activity
.getSystemService(Context.USB_SERVICE);
conn = usbm.openDevice(dev);
l("Interface Count: " + dev.getInterfaceCount());
l("Using "
+ String.format("%04X:%04X", dev.getVendorId(), dev.getProductId()));
if (!conn.claimInterface(dev.getInterface(0), true))
return false;
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
conn.controlTransfer(0x40, 0, 1, 0, null, 0, 0);// clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x1311, 0x40, null, 0, 0);// control flow
// XOFF/XON
// conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0); //data bit 8,
// parity none, stop bit 1, tx off
// conn.controlTransfer(0x40, 0x03, 0x809C, 0, null, 0, 0);//baudrate
// 19200
conn.controlTransfer(0x40, 0x03, 0x4138, 0, null, 0, 0);// baudrate 9600
usbIf = dev.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: " + String.format("0x%02X", usbIf.getEndpoint(i).getAddress()));
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
l("Bulk Endpoint");
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
else
epOUT = usbIf.getEndpoint(i);
}
else {
l("Not Bulk");
}
}
activity.registerReceiver(mUsbReceiver, new IntentFilter(
UsbManager.ACTION_USB_DEVICE_DETACHED));
l("init_USB: epIN " + epIN + ", epOUT: " + epOUT);
readThread.start();
}
catch (final Exception e) {
e.printStackTrace();
}
showLog("init_USB finish");
return (epIN != null && epOUT != null);
}
private void connect() {
UsbDevice device = null;
UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE);
for(UsbDevice v : usbManager.getDeviceList().values())
if(v.getDeviceId() == deviceId)
device = v;
if(device == null) {
status("connection failed: device not found");
return;
}
UsbSerialDriver driver = UsbSerialProber.getDefaultProber().probeDevice(device);
if(driver == null) {
driver = CustomProber.getCustomProber().probeDevice(device);
}
if(driver == null) {
status("connection failed: no driver for device");
return;
}
if(driver.getPorts().size() < portNum) {
status("connection failed: not enough ports at device");
return;
}
usbSerialPort = driver.getPorts().get(portNum);
UsbDeviceConnection usbConnection = usbManager.openDevice(driver.getDevice());
if(usbConnection == null && usbPermission == UsbPermission.Unknown && !usbManager.hasPermission(driver.getDevice())) {
usbPermission = UsbPermission.Requested;
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(getActivity(), 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
usbManager.requestPermission(driver.getDevice(), usbPermissionIntent);
return;
}
if(usbConnection == null) {
if (!usbManager.hasPermission(driver.getDevice()))
status("connection failed: permission denied");
else
status("connection failed: open failed");
return;
}
try {
usbSerialPort.open(usbConnection);
usbSerialPort.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
if(withIoManager) {
usbIoManager = new SerialInputOutputManager(usbSerialPort, this);
Executors.newSingleThreadExecutor().submit(usbIoManager);
}
status("connected");
connected = true;
controlLines.start();
} catch (Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
}
private WritableMap createUsbSerialDevice(UsbManager manager,
UsbSerialDriver driver) throws IOException {
UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
// Most have just one port (port 0).
UsbSerialPort port = driver.getPorts().get(0);
port.open(connection);
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
String id = generateId();
UsbSerialDevice usd = new UsbSerialDevice(port);
WritableMap map = Arguments.createMap();
// Add UsbSerialDevice to the usbSerialDriverDict map
usbSerialDriverDict.put(id, usd);
map.putString("id", id);
return map;
}
public static Trezor getDevice(final Context context, final TrezorGUICallback guiFn,
final Network network) {
final UsbManager manager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
for (final UsbDevice device: manager.getDeviceList().values()) {
// Check if the device is TREZOR (or AvalonWallet or BWALLET)
final int vendorId = device.getVendorId();
final int productId = device.getProductId();
if ((vendorId != 0x534c || productId != 0x0001) &&
(vendorId != 0x1209 || productId != 0x53c0) &&
(vendorId != 0x1209 || productId != 0x53c1) &&
(vendorId != 0x10c4 || productId != 0xea80)) {
continue;
}
Log.i(TAG, "Hardware Wallet device found");
if (device.getInterfaceCount() < 1) {
Log.e(TAG, "Wrong interface count");
continue;
}
// Use first interface
final UsbInterface iface = device.getInterface(0);
// Try to find read/write endpoints
UsbEndpoint readEndpoint = null, writeEndpoint = null;
for (int i = 0; i < iface.getEndpointCount(); ++i) {
final UsbEndpoint ep = iface.getEndpoint(i);
if (readEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
ep.getAddress() == 0x81) {
// number = 1 ; dir = USB_DIR_IN
readEndpoint = ep;
continue;
}
if (writeEndpoint == null &&
ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT &&
(ep.getAddress() == 0x01 || ep.getAddress() == 0x02)) {
// number = 1 ; dir = USB_DIR_OUT
writeEndpoint = ep;
continue;
}
Log.e(TAG, String.format("ep %d", ep.getAddress()));
}
if (!isEndpointOK(readEndpoint, "read") || !isEndpointOK(writeEndpoint, "write"))
continue;
// Try to open the device
final UsbDeviceConnection conn = manager.openDevice(device);
if (conn == null || !conn.claimInterface(iface, true)) {
Log.e(TAG, conn == null ? "Could not open connection" : "Could not claim interface");
continue;
}
// All OK - return the class
return new Trezor(guiFn, device, conn, readEndpoint, writeEndpoint, network);
}
return null;
}
/**
* Initialize the USB device. Determines endpoints and prepares communication.
*
* @param vid
* @param pid
* @throws IOException if the device cannot be opened
* @throws SecurityException
*/
public void initDevice(int vid, int pid) throws IOException, SecurityException {
mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
if (mUsbManager == null) {
throw new IllegalArgumentException("UsbManager == null!");
}
List<UsbDevice> usbDevices = findUsbDevices(mUsbManager, (short) vid, (short) pid);
if (usbDevices.isEmpty() || usbDevices.get(0) == null) {
throw new IOException("USB device not found. (VID: " + vid + ", PID: " + pid + ")");
}
// TODO: Only gets the first USB device that is found
this.mUsbDevice = usbDevices.get(0);
//request permissions
if (mUsbDevice != null && !mUsbManager.hasPermission(mUsbDevice)) {
Log.d(LOG_TAG, "Request permission");
mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(mContext.getPackageName()+".USB_PERMISSION"), 0);
mUsbManager.requestPermission(mUsbDevice, mPermissionIntent);
} else if (mUsbDevice != null && mUsbManager.hasPermission(mUsbDevice)) {
Log.d(LOG_TAG, "Has permission");
} else {
Log.d(LOG_TAG, "device == null");
return;
}
Log.d(LOG_TAG, "setDevice " + this.mUsbDevice);
// find interface
if (this.mUsbDevice.getInterfaceCount() != 1) {
Log.e(LOG_TAG, "Could not find interface");
return;
}
mIntf = this.mUsbDevice.getInterface(0);
// device should have two endpoints
if (mIntf.getEndpointCount() != 2) {
Log.e(LOG_TAG, "Could not find endpoints");
return;
}
// endpoints should be of type bulk
UsbEndpoint ep = mIntf.getEndpoint(0);
if (ep.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) {
Log.e(LOG_TAG, "Endpoint is not of type bulk");
return;
}
// check endpoint direction
if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
mEpIn = mIntf.getEndpoint(0);
mEpOut = mIntf.getEndpoint(1);
} else {
mEpIn = mIntf.getEndpoint(1);
mEpOut = mIntf.getEndpoint(0);
}
UsbDeviceConnection connection = mUsbManager.openDevice(mUsbDevice);
if (connection != null && connection.claimInterface(mIntf, true)) {
Log.d(LOG_TAG, "open SUCCESS");
mConnection = connection;
} else {
Log.d(LOG_TAG, "open FAIL");
throw new IOException("could not open usb connection");
}
}
/**
* Initilize the device
* @param context - application context
* @return - true on success, false on failure
*/
public boolean init(Context context)
{
PodEmuLog.debug("USBSerial: initialization started.");
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// Find all available drivers from attached devices.
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(usbManager);
if (availableDrivers.isEmpty())
{
PodEmuLog.debug("USBSerial: no devices found. Exiting...");
return false;
}
// Open a connection to the first available driver.
UsbSerialDriver driver = availableDrivers.get(0);
connection = usbManager.openDevice(driver.getDevice());
if (connection == null)
{
// You probably need to call UsbManager.requestPermission(driver.getDevice(), ..)
PodEmuLog.log("USBSerial: Cannot establish serial connection! Exiting...");
return false;
}
// Read some data! Most have just one port (port 0).
List<UsbSerialPort> ports = driver.getPorts();
port = ports.get(0);
try {
PodEmuLog.debug("USBSerial: openning connection with baud rate="+baudRate);
port.open(connection);
port.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
PodEmuService.communicateSerialStatusChange();
PodEmuLog.debug("USBSerial: connection succesfully open");
}
catch (IOException e)
{
// TODO Deal with error
PodEmuLog.debug("USBSerial: unknown exception occured! See trace log below:");
PodEmuLog.error(e.getMessage());
return false;
}
return true;
}
@Override
public void start()
{
if (sPort != null)
{
final UsbManager usbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
if (usbManager == null)
{
connectionFailed();
return;
}
UsbDevice device = sPort.getDriver().getDevice();
if (!usbManager.hasPermission(device))
{
PendingIntent usbPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(INTENT_ACTION_GRANT_USB), 0);
usbManager.requestPermission(device, usbPermissionIntent);
connectionFailed();
return;
}
UsbDeviceConnection connection = usbManager.openDevice(sPort.getDriver().getDevice());
if (connection == null)
{
connectionFailed();
return;
}
try
{
sPort.open(connection);
sPort.setDTR(true);
sPort.setParameters(38400, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
log.info("Starting io manager ..");
Thread runner = new Thread(mSerialIoManager);
runner.setPriority(Thread.MAX_PRIORITY);
runner.start();
// we are connected -> signal connectionEstablished
connectionEstablished(sPort.toString());
}
catch (IOException e)
{
log.log(Level.SEVERE, "Error setting up device: " + e.getMessage(), e);
try
{
sPort.close();
}
catch (IOException e2)
{
// Ignore.
}
connectionFailed();
sPort = null;
}
}
}
public void initialize() {
UsbManager manager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
if (availableDrivers.isEmpty()) {
mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: There is no available device. \n", null);
return;
}
mDriver = availableDrivers.get(0);
if(mDriver == null) {
mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Driver is Null \n", null);
return;
}
// Report to UI
StringBuilder sb = new StringBuilder();
UsbDevice device = mDriver.getDevice();
sb.append(" DName : ").append(device.getDeviceName()).append("\n")
.append(" DID : ").append(device.getDeviceId()).append("\n")
.append(" VID : ").append(device.getVendorId()).append("\n")
.append(" PID : ").append(device.getProductId()).append("\n")
.append(" IF Count : ").append(device.getInterfaceCount()).append("\n");
mListener.onReceive(Constants.MSG_DEVICD_INFO, 0, 0, sb.toString(), null);
UsbDeviceConnection connection = manager.openDevice(device);
if (connection == null) {
mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot connect to device. \n", null);
return;
}
// Read some data! Most have just one port (port 0).
mPort = mDriver.getPorts().get(0);
if(mPort == null) {
mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot get port. \n", null);
return;
}
try {
mPort.open(connection);
mPort.setParameters(9600, 8, 1, 0); // baudrate:9600, dataBits:8, stopBits:1, parity:N
// byte buffer[] = new byte[16];
// int numBytesRead = mPort.read(buffer, 1000);
// Log.d(TAG, "Read " + numBytesRead + " bytes.");
} catch (IOException e) {
// Deal with error.
mListener.onReceive(Constants.MSG_SERIAL_ERROR, 0, 0, "Error: Cannot open port \n" + e.toString() + "\n", null);
} finally {
}
// Everything is fine. Start serial monitoring thread.
startThread();
}