Java Code Examples for android.hardware.usb.UsbManager#hasPermission()

The following examples show how to use android.hardware.usb.UsbManager#hasPermission() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectRcManager.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public synchronized void connectRC(Context mContext) {
    if (!this.isTryConnect) {
        this.isTryConnect = true;
        UsbManager usbManager = (UsbManager) mContext.getSystemService("usb");
        this.mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        if (usbManager != null) {
            UsbAccessory[] accessories = usbManager.getAccessoryList();
            UsbAccessory accessory = accessories == null ? null : accessories[0];
            if (accessory != null) {
                if (usbManager.hasPermission(accessory)) {
                    CommunicationManager.getCommunicationManager().setAccessory(accessory);
                    CommunicationManager.getCommunicationManager().startConnectThread(mContext, ConnectType.Aoa);
                } else if (!this.isRequestPermission) {
                    usbManager.requestPermission(accessory, this.mPermissionIntent);
                    this.isRequestPermission = true;
                }
            }
        }
        this.isTryConnect = false;
    }
}
 
Example 2
Source File: ReactUsbSerialModule.java    From react-native-usbserial with MIT License 6 votes vote down vote up
@ReactMethod
public void openDeviceAsync(ReadableMap deviceObject, Promise p) {

    try {
        int prodId = deviceObject.getInt("productId");
        UsbManager manager = getUsbManager();
        UsbSerialDriver driver = getUsbSerialDriver(prodId, manager);

        if (manager.hasPermission(driver.getDevice())) {
            WritableMap usd = createUsbSerialDevice(manager, driver);

            p.resolve(usd);
        } else {
            requestUsbPermission(manager, driver.getDevice(), p);
        }

    } catch (Exception e) {
        p.reject(e);
    }
}
 
Example 3
Source File: UsbDeviceInfo.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
		}
	}
}
 
Example 4
Source File: InitCH340.java    From USB-OTG-CH340-UART-interface with Apache License 2.0 6 votes vote down vote up
/**
 * initialize ch340 parameters.
 *
 * @param context Application context.
 */
public static void initCH340(Context context) {
    if (context == null) return;
    Context appContext = context.getApplicationContext();
    mUsbManager = (UsbManager) appContext.getSystemService(Context.USB_SERVICE);
    if (mUsbManager != null) {
        HashMap<String, UsbDevice> deviceHashMap = mUsbManager.getDeviceList();
        LogUtils.e(TAG, "deviceHashMap.size()=" + deviceHashMap.size());
        for (UsbDevice device : deviceHashMap.values()) {
            LogUtils.i(TAG, "ProductId:" + device.getProductId() + ",VendorId:" + device.getVendorId());
            if (device.getProductId() == 29987 && device.getVendorId() == 6790) {
                mUsbDevice = device;
                if (mUsbManager.hasPermission(device)) {
                    loadDriver(appContext, mUsbManager);
                } else {
                    if (listener != null) {
                        listener.result(false);
                    }
                }
                break;
            }
        }
    }
}
 
Example 5
Source File: USBConnectionManager.java    From Android-Bridge-App with MIT License 6 votes vote down vote up
public void checkForDJIAccessory() {
    mUsbManager = (UsbManager) BridgeApplication.getInstance().getSystemService(Context.USB_SERVICE);
    UsbAccessory[] accessoryList = mUsbManager.getAccessoryList();
    if (accessoryList != null
        && accessoryList.length > 0
        && !TextUtils.isEmpty(accessoryList[0].getManufacturer())
        && accessoryList[0].getManufacturer().equals("DJI")) {
        BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(true));
        //Check permission
        mAccessory = accessoryList[0];
        if (mUsbManager.hasPermission(mAccessory)) {
            Log.d(TAG, "RC CONNECTED");
        } else {
            Log.d(TAG, "NO Permission to USB Accessory");
            DJILogger.e(TAG, "NO Permission to USB Accessory");
            //mUsbManager.requestPermission(mAccessory, null);
        }
    } else {
        BridgeApplication.getInstance().getBus().post(new RCConnectionEvent(false));
        Log.d(TAG, "RC DISCONNECTED");
    }
}
 
Example 6
Source File: LoginActivity.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
private boolean processUsbIntent(Intent intent) {
    String action = intent.getAction();
    if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
        synchronized (this) {
            final UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                final UsbManager usbManager = getUsbManager();
                if (usbManager.hasPermission(device)) {
                    Timber.d("Ledger attached by intent");
                    connectLedger(usbManager, device);
                }
            }
        }
        return true;
    }
    return false;
}
 
Example 7
Source File: USBTransport.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempts to connect to the specified accessory.
 *
 * If the permission is already granted, opens the accessory. Otherwise,
 * requests permission to use it.
 *
 * @param accessory Accessory to connect to
 */
private void connectToAccessory(UsbAccessory accessory) {

    if (accessory == null) {
        handleTransportError("Can't connect to null accessory", null);
    }

    final State state = getState();
    switch (state) {
        case LISTENING:
            UsbManager usbManager = getUsbManager();
            if (usbManager.hasPermission(accessory)) {
                logI("Already have permission to use " + accessory);
                openAccessory(accessory);
            } else {
                logI("Requesting permission to use " + accessory);

                PendingIntent permissionIntent = PendingIntent
                        .getBroadcast(getContext(), 0,
                                new Intent(ACTION_USB_PERMISSION), 0);
                usbManager.requestPermission(accessory, permissionIntent);
            }

            break;

        default:
            logW("connectToAccessory() called from state " + state +
                    "; doing nothing");
    }
}
 
Example 8
Source File: FTDI_USB_Handler.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
private void enumerate() {
	l("enumerating");

	UsbManager usbman = (UsbManager) activity
			.getSystemService(Context.USB_SERVICE);

	HashMap<String, UsbDevice> devlist = usbman.getDeviceList();
	Iterator<UsbDevice> deviter = devlist.values().iterator();
	PendingIntent pi = PendingIntent.getBroadcast(activity, 0, new Intent(
			ACTION_USB_PERMISSION), 0);

	while (deviter.hasNext()) {
		UsbDevice d = deviter.next();
		l("Found device: "
				+ String.format("%04X:%04X", d.getVendorId(), d.getProductId()));
		if (String.format("%04X:%04X", d.getVendorId(), d.getProductId()).equals(
				VID_PID)) {
			// we need to upload the hex file, first request permission
			l("Device under: " + d.getDeviceName());
			activity.registerReceiver(mPermissionReceiver, new IntentFilter(
					ACTION_USB_PERMISSION));
			if (!usbman.hasPermission(d))
				usbman.requestPermission(d, pi);
			else
				init_USB(d);

			// init_USB(d);
			break;
		}
	}
	l("no more devices found");
}
 
Example 9
Source File: MainActivity.java    From Chorus-RF-Laptimer with MIT License 5 votes vote down vote up
private void checkUSBPermissionsAndConnectIfAllowed() {
    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    UsbDevice device = getAvailableUsbDevice();
    if (device == null) return;

    if (manager.hasPermission(device)) {
        connectToUsbDevice();
        return;
    }

    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);
    manager.requestPermission(device, mPermissionIntent);
}
 
Example 10
Source File: MainActivity.java    From ns-usbloader-mobile with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction() == null)
        return;
    switch (intent.getAction()) {
        case UsbManager.ACTION_USB_DEVICE_ATTACHED:
            usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
            if (usbManager == null)
                break;  // ???
            if (usbManager.hasPermission(usbDevice))
                isUsbDeviceAccessible = true;
            else {
                isUsbDeviceAccessible = false;
                usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(context, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
            }
            break;
        case NsConstants.REQUEST_NS_ACCESS_INTENT:
            isUsbDeviceAccessible = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);
            break;
        case UsbManager.ACTION_USB_DEVICE_DETACHED:
            usbDevice = null;
            isUsbDeviceAccessible = false;
            stopService(new Intent(context, CommunicationsService.class));
            break;
        case NsConstants.SERVICE_TRANSFER_TASK_FINISHED_INTENT:
            ArrayList<NSPElement> nspElements = intent.getParcelableArrayListExtra(NsConstants.SERVICE_CONTENT_NSP_LIST);
            if (nspElements == null)
                break;
            for (int i=0; i < mDataset.size(); i++){
                for (NSPElement receivedNSPe : nspElements)
                    if (receivedNSPe.getFilename().equals(mDataset.get(i).getFilename()))
                        mDataset.get(i).setStatus(receivedNSPe.getStatus());
            }
            mAdapter.notifyDataSetChanged();
            blockUI(false);
            break;
    }
}
 
Example 11
Source File: TerminalFragment.java    From usb-serial-for-android with GNU Lesser General Public License v2.1 4 votes vote down vote up
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();
    }
}
 
Example 12
Source File: USBMonitor.java    From AndroidUSBCamera with Apache License 2.0 4 votes vote down vote up
/**
 * ベンダー名・製品名・バージョン・シリアルを取得する
 * @param manager
 * @param device
 * @param _info
 * @return
 */
@TargetApi(Build.VERSION_CODES.M)
public static UsbDeviceInfo updateDeviceInfo(final UsbManager manager, final UsbDevice device, final UsbDeviceInfo _info) {
	final UsbDeviceInfo info = _info != null ? _info : new UsbDeviceInfo();
	info.clear();

	if (device != null) {
		if (BuildCheck.isLollipop()) {
			info.manufacturer = device.getManufacturerName();
			info.product = device.getProductName();
			info.serial = device.getSerialNumber();
		}
		if (BuildCheck.isMarshmallow()) {
			info.usb_version = device.getVersion();
		}
		if ((manager != null) && manager.hasPermission(device)) {
			final UsbDeviceConnection connection = manager.openDevice(device);
			if(connection == null) {
				return null;
			}
			final byte[] desc = connection.getRawDescriptors();

			if (TextUtils.isEmpty(info.usb_version)) {
				info.usb_version = String.format("%x.%02x", ((int)desc[3] & 0xff), ((int)desc[2] & 0xff));
			}
			if (TextUtils.isEmpty(info.version)) {
				info.version = String.format("%x.%02x", ((int)desc[13] & 0xff), ((int)desc[12] & 0xff));
			}
			if (TextUtils.isEmpty(info.serial)) {
				info.serial = connection.getSerial();
			}

			final byte[] languages = new byte[256];
			int languageCount = 0;
			// controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)
			try {
				int result = connection.controlTransfer(
					USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
    				USB_REQ_GET_DESCRIPTOR,
    				(USB_DT_STRING << 8) | 0, 0, languages, 256, 0);
				if (result > 0) {
        			languageCount = (result - 2) / 2;
				}
				if (languageCount > 0) {
					if (TextUtils.isEmpty(info.manufacturer)) {
						info.manufacturer = getString(connection, desc[14], languageCount, languages);
					}
					if (TextUtils.isEmpty(info.product)) {
						info.product = getString(connection, desc[15], languageCount, languages);
					}
					if (TextUtils.isEmpty(info.serial)) {
						info.serial = getString(connection, desc[16], languageCount, languages);
					}
				}
			} finally {
				connection.close();
			}
		}
		if (TextUtils.isEmpty(info.manufacturer)) {
			info.manufacturer = USBVendorId.vendorName(device.getVendorId());
		}
		if (TextUtils.isEmpty(info.manufacturer)) {
			info.manufacturer = String.format("%04x", device.getVendorId());
		}
		if (TextUtils.isEmpty(info.product)) {
			info.product = String.format("%04x", device.getProductId());
		}
	}
	return info;
}
 
Example 13
Source File: MasterService.java    From 600SeriesAndroidUploader with MIT License 4 votes vote down vote up
private boolean hasUsbPermission() {
    UsbManager usbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
    if (usbManager == null) return false;
    UsbDevice cnlDevice = UsbHidDriver.getUsbDevice(usbManager, MedtronicCnlService.USB_VID, MedtronicCnlService.USB_PID);
    return !(cnlDevice != null && !usbManager.hasPermission(cnlDevice));
}
 
Example 14
Source File: MainActivity.java    From ns-usbloader-mobile with GNU General Public License v3.0 4 votes vote down vote up
private void uploadFiles(){
    ArrayList<NSPElement> NSPElementsToSend = new ArrayList<>();
    for (NSPElement element: mDataset){
        if (element.isSelected())
            NSPElementsToSend.add(element);
    }
    // Do we have files to send?
    if (NSPElementsToSend.isEmpty()){
        Snackbar.make(findViewById(android.R.id.content), getString(R.string.nothing_selected_message), Snackbar.LENGTH_LONG).show();
        return;
    }
    // Do we have selected protocol?
    if (drawerNavView.getCheckedItem() == null) {
        Snackbar.make(findViewById(android.R.id.content), getString(R.string.no_protocol_selected_message), Snackbar.LENGTH_LONG).show();
        return;
    }
    Intent serviceStartIntent = new Intent(this, CommunicationsService.class);
    serviceStartIntent.putExtra(NsConstants.NS_RESULT_RECEIVER, nsResultReciever);
    serviceStartIntent.putParcelableArrayListExtra(NsConstants.SERVICE_CONTENT_NSP_LIST, NSPElementsToSend);
    // Is it TF Net transfer?
    if (drawerNavView.getCheckedItem().getItemId() == R.id.nav_tf_net){
        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_TF_NET);
        SharedPreferences sp = getSharedPreferences("NSUSBloader", MODE_PRIVATE);

        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_NS_DEVICE_IP, sp.getString("SNsIP", "192.168.1.42"));
        if (sp.getBoolean("SAutoIP", true))
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_IP, "");
        else
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_IP, sp.getString("SServerIP", "192.168.1.142"));
        serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PHONE_PORT, sp.getInt("SServerPort", 6042));
        startService(serviceStartIntent);
        blockUI(true);
        return;
    }
    // Ok, so it's something USB related
    UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
    // Do we have manager?
    if (usbManager == null) {
        NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), "Internal issue: getSystemService(Context.USB_SERVICE) returned null");
        return;
    }
    // If device not connected
    if (usbDevice == null){
        HashMap<String, UsbDevice> deviceHashMap;

        deviceHashMap = usbManager.getDeviceList();

        for (UsbDevice device : deviceHashMap.values()) {
            if (device.getVendorId() == 1406 && device.getProductId() == 12288) {
                usbDevice = device;
            }
        }
        // If it's still not connected then it's really not connected.
        if (usbDevice == null) {
            NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), getResources().getString(R.string.ns_not_found_in_connected));
            return;
        }
        // If we have NS connected check for permissions
        if (! usbManager.hasPermission(usbDevice)){
            usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(this, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
            return;
        }
    }
    if (! isUsbDeviceAccessible){
        usbManager.requestPermission(usbDevice, PendingIntent.getBroadcast(this, 0, new Intent(NsConstants.REQUEST_NS_ACCESS_INTENT), 0));
        return;
    }

    switch (drawerNavView.getCheckedItem().getItemId()){
        case R.id.nav_tf_usb:
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_TF_USB);
            break;
        case R.id.nav_gl:
            serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_PROTOCOL, NsConstants.PROTO_GL_USB);
            break;
        default:
            Snackbar.make(findViewById(android.R.id.content), getString(R.string.unknown_protocol_error), Snackbar.LENGTH_LONG).show(); // ?_?
            return;
    }
    serviceStartIntent.putExtra(NsConstants.SERVICE_CONTENT_NS_DEVICE, usbDevice);
    startService(serviceStartIntent);
    blockUI(true);
}
 
Example 15
Source File: USBMonitor.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
/**
 * ベンダー名・製品名・バージョン・シリアルを取得する
 * @param manager
 * @param device
 * @param _info
 * @return
 */
public static UsbDeviceInfo updateDeviceInfo(final UsbManager manager, final UsbDevice device, final UsbDeviceInfo _info) {
	final UsbDeviceInfo info = _info != null ? _info : new UsbDeviceInfo();
	info.clear();

	if (device != null) {
		if (BuildCheck.isLollipop()) {
			info.manufacturer = device.getManufacturerName();
			info.product = device.getProductName();
			info.serial = device.getSerialNumber();
		}
		if (BuildCheck.isMarshmallow()) {
			info.usb_version = device.getVersion();
		}
		if ((manager != null) && manager.hasPermission(device)) {
			final UsbDeviceConnection connection = manager.openDevice(device);
			final byte[] desc = connection.getRawDescriptors();

			if (TextUtils.isEmpty(info.usb_version)) {
				info.usb_version = String.format("%x.%02x", ((int)desc[3] & 0xff), ((int)desc[2] & 0xff));
			}
			if (TextUtils.isEmpty(info.version)) {
				info.version = String.format("%x.%02x", ((int)desc[13] & 0xff), ((int)desc[12] & 0xff));
			}
			if (TextUtils.isEmpty(info.serial)) {
				info.serial = connection.getSerial();
			}

			final byte[] languages = new byte[256];
			int languageCount = 0;
			// controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout)
			try {
				int result = connection.controlTransfer(
					USB_REQ_STANDARD_DEVICE_GET, // USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_DEVICE
    				USB_REQ_GET_DESCRIPTOR,
    				(USB_DT_STRING << 8) | 0, 0, languages, 256, 0);
				if (result > 0) {
        			languageCount = (result - 2) / 2;
				}
				if (languageCount > 0) {
					if (TextUtils.isEmpty(info.manufacturer)) {
						info.manufacturer = getString(connection, desc[14], languageCount, languages);
					}
					if (TextUtils.isEmpty(info.product)) {
						info.product = getString(connection, desc[15], languageCount, languages);
					}
					if (TextUtils.isEmpty(info.serial)) {
						info.serial = getString(connection, desc[16], languageCount, languages);
					}
				}
			} finally {
				connection.close();
			}
		}
		if (TextUtils.isEmpty(info.manufacturer)) {
			info.manufacturer = USBVendorId.vendorName(device.getVendorId());
		}
		if (TextUtils.isEmpty(info.manufacturer)) {
			info.manufacturer = String.format("%04x", device.getVendorId());
		}
		if (TextUtils.isEmpty(info.product)) {
			info.product = String.format("%04x", device.getProductId());
		}
	}
	return info;
}
 
Example 16
Source File: MedtronicCGMService.java    From MedtronicUploader with GNU General Public License v2.0 4 votes vote down vote up
public void run() {
	Log.d(TAG, "run readAndUpload");
	try {
		UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
		boolean hasPermission = faking;
		for (final UsbDevice usbDevice : usbManager.getDeviceList()
				.values()) {
			if (usbManager.hasPermission(usbDevice)) {
				hasPermission = true;
			}
		}
		if (!hasPermission) {
			synchronized (checkSerialLock) {
				Log.d(TAG, "I have lost usb permission changing listener attached to false...");
				listenerAttached = false;
				mSerial.clearReadListener();
				mHandlerRead.removeCallbacks(readByListener);
				sendMessageDisconnectedToUI();
				if (!mHandlerActive || isDestroying){
					Log.d(TAG,"destroy readAnd Upload "+ mHandlerActive + " isDes "+ isDestroying);
					return;
				}
				mHandlerCheckSerial.removeCallbacks(readAndUpload);
				mHandlerCheckSerial.postDelayed(readAndUpload, MedtronicConstants.FIVE_SECONDS__MS);
				return;
			}
		} else
			sendMessageConnectedToUI();
		boolean connected;
		synchronized (mSerialLock) {
			connected = isConnected();
		}
		if (connected) {
			if (!isOnline())
				sendErrorMessageToUI("NET connection error");
			if (!listenerAttached) {
				Log.d(TAG, "!listener attached readByListener triggered");
				mSerial.clearReadListener();
				mHandlerRead.removeCallbacks(readByListener);
				mSerial.addReadListener(readListener);
				mHandlerRead.post(readByListener);
				listenerAttached = true;
				

			}

		} else {
			openUsbSerial(false);
			connected = isConnected();

			if (!connected)
				sendErrorMessageToUI("Receptor connection error");
			else if (!isOnline())
				sendErrorMessageToUI("Not online/connection error");
			else {
				sendMessageConnectedToUI();
				sendMessageToUI("connected");
			}
		}

	} catch (Exception e) {
		sendExceptionToUI("Unable to read from receptor or upload", e);
	}
	synchronized (checkSerialLock) {
		if (!mHandlerActive || isDestroying){
			Log.d(TAG,"destroy readAnd Upload2 "+ mHandlerActive + " isDes "+ isDestroying);
			return;
		}
		mHandlerCheckSerial.removeCallbacks(readAndUpload);
		mHandlerCheckSerial.postDelayed(readAndUpload,  MedtronicConstants.FIVE_SECONDS__MS);
	}
}
 
Example 17
Source File: UsbCommService.java    From AndrOBD with GNU General Public License v3.0 4 votes vote down vote up
@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;
		}
	}
}
 
Example 18
Source File: UsbLinkAndroid.java    From crazyflie-android-client with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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");
    }
}
 
Example 19
Source File: MainActivity.java    From ns-usbloader-mobile with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Initialize ToolBar
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    drawerNavView = findViewById(R.id.nav_view);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    drawerNavView.setNavigationItemSelectedListener(this);
    // Initialize Progress Bar
    progressBarMain = findViewById(R.id.mainProgressBar);
    // Configure data set in case it's restored from screen rotation or something
    if (savedInstanceState != null){
        mDataset = savedInstanceState.getParcelableArrayList("DATASET_LIST");
        // Restore USB device information
        usbDevice = savedInstanceState.getParcelable("USB_DEVICE");
        isUsbDeviceAccessible = savedInstanceState.getBoolean("IS_USB_DEV_ACCESSIBLE", false);
        drawerNavView.setCheckedItem(savedInstanceState.getInt("PROTOCOL", R.id.nav_tf_usb));
        nsResultReciever = savedInstanceState.getParcelable("RECEIVER");
    }
    else {
        mDataset = new ArrayList<>();
        usbDevice = getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);    // If it's started initially, then check if it's started from notification.
        if (usbDevice != null){
            UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
            // If somehow we can't get system service
            if (usbManager == null) {
                NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), "Internal issue: getSystemService(Context.USB_SERVICE) returned null");
                return; // ??? HOW ???
            }
            isUsbDeviceAccessible = usbManager.hasPermission(usbDevice);
        }
        else
            isUsbDeviceAccessible = false;
        switch (getSharedPreferences("NSUSBloader", MODE_PRIVATE).getInt("PROTOCOL", NsConstants.PROTO_TF_USB)){
            case NsConstants.PROTO_TF_USB:
                drawerNavView.setCheckedItem(R.id.nav_tf_usb);
                break;
            case NsConstants.PROTO_TF_NET:
                drawerNavView.setCheckedItem(R.id.nav_tf_net);
                break;
            case NsConstants.PROTO_GL_USB:
                drawerNavView.setCheckedItem(R.id.nav_gl);
                break;
            default:
        }
        nsResultReciever = new NsResultReciever(new Handler()); // We will set callback in onResume and unset onPause
    }

    recyclerView = findViewById(R.id.recyclerView);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    mAdapter = new NspItemsAdapter(mDataset);
    recyclerView.setAdapter(mAdapter);
    this.setSwipeFunctionsToView();
    // Select files button
    selectBtn = findViewById(R.id.buttonSelect);
    selectBtn.setOnClickListener(e->{
        Intent fileChooser = new Intent(Intent.ACTION_GET_CONTENT);
        fileChooser.setType("application/octet-stream"); //fileChooser.setType("*/*"); ???

        if (fileChooser.resolveActivity(getPackageManager()) != null)
            startActivityForResult(Intent.createChooser(fileChooser, getString(R.string.select_file_btn)), ADD_NSP_INTENT_CODE);
        else
            NsNotificationPopUp.getAlertWindow(this, getResources().getString(R.string.popup_error), getResources().getString(R.string.install_file_explorer));
    });
    // Upload to NS button
    uploadToNsBtn = findViewById(R.id.buttonUpload);
}
 
Example 20
Source File: TerminalFragment.java    From SimpleUsbTerminal with MIT License 4 votes vote down vote up
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);
    }
}