javax.bluetooth.BluetoothStateException Java Examples

The following examples show how to use javax.bluetooth.BluetoothStateException. 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: BluetoothServer.java    From ShootOFF with GNU General Public License v3.0 7 votes vote down vote up
private Optional<String> getLocalAddress() {
	try {
		final LocalDevice localDevice = LocalDevice.getLocalDevice();

		// Insert colons into the address because android needs them
		final StringBuilder addressBuilder = new StringBuilder();
		final String originalAddress = localDevice.getBluetoothAddress();
		for (int i = 0; i < originalAddress.length(); i++) {
			addressBuilder.append(originalAddress.charAt(i));
			if (i > 0 && i < originalAddress.length() - 1 && i % 2 != 0) addressBuilder.append(':');
		}

		return Optional.of(addressBuilder.toString());
	} catch (BluetoothStateException e) {
		logger.error("Failed to access local bluetooth device to fetch its address. Ensure the "
				+ "system's bluetooth service is started with \"sudo systemctl start bluetooth\" "
				+ "and the bluetooth stack is on in the system settings", e);
		return Optional.empty();
	}
}
 
Example #2
Source File: ServiceSearcher.java    From pluotsorbet with GNU General Public License v2.0 6 votes vote down vote up
public int searchService(int[] attrSet, UUID[] uuidSet, RemoteDevice btDev,
        DiscoveryListener discListener) throws BluetoothStateException,
        IllegalArgumentException {

    if (DEBUG) {
        System.out.println("- serviceSearcher: initializing");
    }
    initialize(attrSet, uuidSet, btDev);

    if (discListener == null) {
        throw new NullPointerException("DiscoveryListener is null");
    }
    this.discListener = discListener;

    return start();
}
 
Example #3
Source File: BluetoothDiscoveryUtil.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private static LocalDevice getLocalDevice() {
	try {
		return LocalDevice.getLocalDevice();
	} catch (BluetoothStateException e) {
		throw propagate(e);
	}
}
 
Example #4
Source File: BluetoothService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Value inquire()
	throws FaultException {
	Value retValue = null;
	try {
		DiscoveryListenerImpl listener = new DiscoveryListenerImpl();
		LocalDevice.getLocalDevice().getDiscoveryAgent().startInquiry(
			DiscoveryAgent.GIAC,
			listener );
		retValue = listener.getResult();
	} catch( BluetoothStateException e ) {
		throw new FaultException( e );
	}
	return retValue;
}
 
Example #5
Source File: BluetoothService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings( "PMD" )
public Boolean setDiscoverable( Integer i )
	throws FaultException {
	boolean b = false;
	try {
		b = LocalDevice.getLocalDevice().setDiscoverable( i );
	} catch( BluetoothStateException e ) {
		throw new FaultException( e );
	}
	return b;
}
 
Example #6
Source File: BluetoothStack.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
public synchronized static BluetoothStack getEnabledInstance()
                throws BluetoothStateException {
        BluetoothStack instance = getInstance();
        if (!instance.isEnabled() && !instance.enable()) {
            throw new BluetoothStateException("Failed turning Bluetooth on");
        }
        // intent here is launching EmulationPolling and SDPServer
        // in emulation mode
//????        com.sun.jsr082.bluetooth.SDDB.getInstance();
        return instance;
    }
 
Example #7
Source File: DiscoveryAgentImpl.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
public boolean startInquiry(int accessCode, DiscoveryListener listener)
        throws BluetoothStateException {

    if (accessCode != DiscoveryAgent.GIAC &&
            accessCode != DiscoveryAgent.LIAC &&
            (accessCode < 0x9E8B00 || accessCode > 0x9E8B3F)) {
        throw new IllegalArgumentException("Access code is out of range: "
                + accessCode);
    }

    if (listener == null) {
        throw new NullPointerException("null listener");
    }

    /* IMPL_NOTE see
    // kvem/classes/com/sun/kvem/jsr082/impl/bluetooth/
    //         BTDeviceDiscoverer.java
    // heck what access codes should be supported.
    // Return false if access code is not supported. 
     */

    synchronized (d_lock) {
        if (d_listener != null) {
            throw new BluetoothStateException(
                    "The previous device discovery is running...");
        }
        d_listener = listener;

        /* process the inquiry in the device specific way */
        return startInquiry(accessCode);
    }
}
 
Example #8
Source File: DiscoveryAgentImpl.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
public String selectService(UUID uuid, int security, boolean master)
            throws BluetoothStateException {

        // use the separated class to light this one
        return selectServiceHandler.selectService(uuid, security, master);
//        return ServiceDiscovererFactory.getServiceDiscoverer().
//                                 selectService(uuid, security, master, this);
    }
 
Example #9
Source File: ServiceRecordImpl.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
private void retrieveUrlCommonParams() {
    if (protocol != BluetoothUrl.UNKNOWN) {
        // already retrieved
        return;
    }

    if (remoteDevice != null) {
        btaddr = remoteDevice.getBluetoothAddress();
    } else {
        try {
            btaddr = LocalDevice.getLocalDevice().getBluetoothAddress();
        } catch (BluetoothStateException bse) {
            throw new IllegalArgumentException("cannot generate url");
        }
    }

    /*
     * There are three protocols supported -
     * they are obex or rfcomm or l2cap. So, if obex is
     * found in ProtocolDescriptorList, the protocol is btgoep,
     * if RFCOMM is found (and no obex) - the btspp, otherwise
     * the protocol is btl2cap.
     */
    DataElement protocolList = getAttributeValue(PROTOCOL_DESCRIPTOR_LIST);
    if (protocolList == null) {
    	return;
    }
    Enumeration val = (Enumeration) protocolList.getValue();
    int type = -1; // 0 = l2cap, 1 = spp, 2 = obex
    final UUID L2CAP_UUID = new UUID(0x0100);
    final UUID RFCOMM_UUID = new UUID(0x0003);
    final UUID OBEX_UUID = new UUID(0x0008);

    // go through all of the protocols in the protocols list
    while (val.hasMoreElements()) {
        DataElement protoDE = (DataElement) val.nextElement();

        // application adds a garbage in protocolList - ignore
        if (protoDE.getDataType() != DataElement.DATSEQ) {
            continue;
        }
        Enumeration protoEnum = (Enumeration) protoDE.getValue();
        int tmpPort = -1;
        int tmpType = -1;

        // look on protocol details
        while (protoEnum.hasMoreElements()) {
            DataElement de = (DataElement) protoEnum.nextElement();

            // may be PSM or channel id
            if (de.getDataType() == DataElement.U_INT_1 ||
                    de.getDataType() == DataElement.U_INT_2)  {
                tmpPort = (int) de.getLong();
            } else if (de.getDataType() == DataElement.UUID) {
                UUID protoUUID = (UUID) de.getValue();

                if (protoUUID.equals(L2CAP_UUID)) {
                    tmpType = 0;
                } else if (protoUUID.equals(RFCOMM_UUID)) {
                    tmpType = 1;
                } else if (protoUUID.equals(OBEX_UUID)) {
                    tmpType = 2;
                }
            }
        }

        /*
         * ok, new protocol has been parsed - let's check if it
         * is over the previous one or not.
         *
         * Note, that OBEX protocol may appear before the RFCOMM
         * one - in this case the port (channel id) is not set -
         * need to check this case separately.
         */
        if (tmpType > type) {
            type = tmpType;

            // no "port" for obex type (obex = 2)
            if (tmpType != 2) {
                port = tmpPort;
            }
        } else if (tmpType == 1) {
            port = tmpPort;
        }
    }

    switch (type) {
    case 0:
        protocol = BluetoothUrl.L2CAP;
        break;
    case 1:
        protocol = BluetoothUrl.RFCOMM;
        break;
    case 2:
        protocol = BluetoothUrl.OBEX;
        break;
    default:
        throw new IllegalArgumentException("wrong protocol list");
    }
}
 
Example #10
Source File: LocalDeviceImpl.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized LocalDeviceImpl getInstance()
        throws BluetoothStateException {
    if (instance == null) {
        instance = new LocalDeviceImpl();
    }
    return instance;
}
 
Example #11
Source File: LocalDeviceImpl.java    From pluotsorbet with GNU General Public License v2.0 5 votes vote down vote up
public boolean setDiscoverable(int accessCode)
        throws BluetoothStateException {
    // Check if the specified mode has a valid value
    if (accessCode != DiscoveryAgent.GIAC &&
            accessCode != DiscoveryAgent.LIAC &&
            accessCode != DiscoveryAgent.NOT_DISCOVERABLE &&
            (accessCode < 0x9E8B00 || accessCode > 0x9E8B3F)) {
        throw new IllegalArgumentException("Access code is out of range: "
                + "0x" + Integer.toHexString(accessCode).toUpperCase());
    }
    synchronized (cancelerOfLIAC) {
        /*
         * Accroding to the spec, the device should only be limited
         * discoverable (DiscoveryAgent.LIAC) for 1 minute -
         * then back to the PREVIOUS discoverable mode.
         */
        int oldAccessCode = BCC.getInstance().getAccessCode();
        if (BCC.getInstance().setAccessCode(accessCode)) {
            cancelerOfLIAC.notifyNewAccessCode(oldAccessCode, accessCode);
            if (accessCode != DiscoveryAgent.NOT_DISCOVERABLE) {
                // Start SDDB if discoverable mode was set successfully
                // IMPL_NOTE: Do we really need this step?
                SDDB.getInstance();
            }
            return true;
        }
    }
    return false;
}
 
Example #12
Source File: DiscoveryAgentImpl.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
private boolean startInquiry(int accessCode) throws BluetoothStateException {
    return BluetoothStack.getEnabledInstance().startInquiry(
        accessCode, d_listener);
}
 
Example #13
Source File: DiscoveryAgentImpl.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
public int searchServices(int[] attrSet, UUID[] uuidSet, RemoteDevice btDev,
        DiscoveryListener discListener) throws BluetoothStateException {

    if (DEBUG) {
        System.out.println("searchServices: ");
        System.out.println("\tattrSet=" + attrSet);

        if (attrSet != null) {
            for (int i = 0; i < attrSet.length; i++) {
                System.out.println("\tattrSet[" + i + "]=0x" + attrSet[i]);
            }
        }
        System.out.println("\tuuidSet=" + uuidSet);

        if (uuidSet != null) {
            for (int i = 0; i < uuidSet.length; i++) {
                System.out.println("\tuuidSet[" + i + "]=" + uuidSet[i]);
            }
        }
        System.out.println("\tadderess=" + btDev.getBluetoothAddress());
    }
    if (uuidSet == null) {
        throw new NullPointerException("UUID set is null");
    }

    if (uuidSet.length == 0 || uuidSet.length > MAX_ALLOWED_UUIDS ) {
        throw new IllegalArgumentException("Invalid UUID set length");
    }

    if (btDev == null) {
        throw new NullPointerException("null instance of RemoteDevice");
    }
    
    /* the 'transID' is assigned by service discoverer */
    int transID = ServiceDiscovererFactory.getServiceDiscoverer().
            searchService(
                    ServiceSearcherBase.extendByStandardAttrs(attrSet), 
                    ServiceSearcherBase.removeDuplicatedUuids(uuidSet), 
                    btDev, discListener);

    if (DEBUG) {
        System.out.println("\ttransID=" + transID);
    }
    return transID;
}
 
Example #14
Source File: SelectServiceHandler.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
String selectService(UUID uuid, int security, boolean master)
        throws BluetoothStateException {
    if (DEBUG) {
        System.out.println("selectService:");
        System.out.println("\tuuid=" + uuid);
    }
    Vector disDevsVector = null;
    Hashtable disDevsHash = new Hashtable();

    if (uuid == null) {
        throw new NullPointerException("uuid is null");
    }

    // check in CACHED and PREKNOWN devices
    String url = selectFromDevicesList(agent.retrieveDevices(
            DiscoveryAgent.PREKNOWN), uuid, security, master, disDevsHash);

    if (url != null) {
        return url;
    }
    url = selectFromDevicesList(agent.retrieveDevices(
            DiscoveryAgent.CACHED), uuid, security, master, disDevsHash);

    if (url != null) {
        return url;
    }

    // start own device discovery now
    synchronized (btDevsLock) {
        if (selectDevDisStarted) {
            throw new BluetoothStateException(
                    "The previous device discovery is running...");
        }
        selectDevDisStarted = true;
        btDevs = new Vector();
        btDevsHash = disDevsHash;
    }

    try {
        agent.startInquiry(DiscoveryAgent.GIAC, this);
    } catch (BluetoothStateException btse) {
        synchronized (btDevsLock) {
            selectDevDisStarted = false;
            btDevs = null;
            btDevsHash = null;
        }
        throw btse;
    }

    synchronized (btDevsLock) {
        if (!selectDevDisStopped) {
            try {
                btDevsLock.wait();
            } catch (InterruptedException ie) {
                // ignore (breake waiting)
            }
            disDevsVector = btDevs;
            btDevs = null;
            btDevsHash = null;
            selectDevDisStarted = false;
            selectDevDisStopped = false;
        }
    }

    for (int i = 0; i < disDevsVector.size(); i++) {
        RemoteDevice btDev = (RemoteDevice) disDevsVector.elementAt(i);
        url = selectService(btDev, uuid, security, master);

        if (url != null) {
            if (DEBUG) {
                System.out.println("\turl=" + url);
            }
            return url;
        }
    }
    if (DEBUG) {
        System.out.println("\turl=null");
    }
    return null;
}
 
Example #15
Source File: ServiceSearcher.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
private int start() throws BluetoothStateException {
    if (DEBUG) {
        System.out.println("- serviceSearcher: start");
    }
    synchronized (ServiceSearcher.class) {
        if (requestCounter == ServiceRecordImpl.TRANS_MAX) {
            throw new BluetoothStateException(
                    "Too much concurrent requests");
        }
        requestCounter++;
    }
    transactionID = SDPClientTransaction.newTransactionID();
    searchers.put(new Integer(transactionID), this);
    synchronized (this) {
        notified = false;
    }

    handles = null;
    processedHandle = 0;
    try {
        sdp = new JavaSDPClient(btDev.getBluetoothAddress());
        sdp.serviceSearchAttributeRequest(attrSet, uuidSet, transactionID,
                this);
        // sdp.serviceSearchRequest(uuidSet, transactionID, this);
    } catch (IOException ioe) {
        if (DEBUG) {
            ioe.printStackTrace();
        }

        synchronized (this) {
            stop();
            new NotifyListenerRunner(
                    DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE);
        }
    }

    if (DEBUG) {
        System.out.println("- serviceSearch: started with transaction: "
                + transactionID);
    }
    return transactionID;
}
 
Example #16
Source File: ServiceDiscoverer.java    From pluotsorbet with GNU General Public License v2.0 4 votes vote down vote up
public int searchService(int[] attrSet, UUID[] uuidSet, RemoteDevice btDev,
DiscoveryListener discListener) throws BluetoothStateException ;