EzDevInfo.com

bluetooth interview questions

Top bluetooth frequently asked interview questions

What is the iBeacon Bluetooth Profile

I'd like to create my own iBeacon with some bluetooth low energy dev kits. Apple has yet to release a specification for iBeacons, however a few hardware developers have reverse Engineered the iBeacon from the AirLocate Sample code and started selling iBeacon dev kits.

So what is the iBeacon Bluetooth Profile?

Bluetooth Low Energy uses GATT for LE profile service discovery. So I think we need to know the Attribute Handle, Attribute Type, Attribute Value, and maybe the Attribute Permissions of the iBeacon attribute. So for an iBeacon with a UUID of E2C56DB5-DFFB-48D2-B060-D0F5A71096E0 a major value of 1 and a minor value of 1 what would the Bluetooth GATT profile service be?

Heres some assumptions I've made from the discussion on Apple's forums and through the docs.

  1. You only need to see the profile service (GATT) of a Bluetooth peripheral to know it is an iBeacon.

  2. The Major and Minor keys are encoded somewhere in this profile service

Heres some companies with iBeacon Dev Kits that seem to have this figure out already:

Hopefully in time we will have a profile posted on Bluetooth.org like these: https://www.bluetooth.org/en-us/specification/adopted-specifications


Source: (StackOverflow)

Transfer data between iOS and Android via Bluetooth?

I've been reading up on how to transfer data between iOS devices over Bluetooth using GameKit. I'm not writing a game, per se, but do have a need to transfer a small amount of binary data between two devices. Between two iSO devices, this is easy enough. However, I was wondering if it is possible to transfer data between an iOS device and an Android device via the same mechanism.

Has anyone come across documentation/tutorial that would explain how to do this? Is it even technically possible? Or has Apple put in some sort of restriction that would prevent this?

The other option I discovered was Bonjour over Bluetooth. Would this be a more suitable option for this type of operation?


Source: (StackOverflow)

Advertisements

Reconnecting to disconnected peers

I'm using the iOS 7 Multipeer framework in my app but I'm experiencing a problem with devices disconnecting. If I open the app in two devices: device A and device B the two devices connect to each other automatically. However, after several seconds device A disconnects from device B. i.e. At first the connection is like this:

A ---> B
A <--- B

After several seconds:

A ---> B
A      B

Device A maintains it's connection but device B get's a MCSessionStateNotConnected.

This means that A can send data to B but B can't reply. I tried to get around this by checking if the device is connected and if it's not, re-initiating the connection using:

[browser invitePeer:peerID toSession:_session withContext:Nil timeout:10];

But the didChangeState callback just get's called with MCSessionStateNotConnected.

Strangely if I send app A to the background, then re-open it, B reconnects to it and the connection is maintained.

The Multipeer API (and documentation) seems a bit sparse so I was assuming that it would just work. In this situation how should I re-connect the device?


Source: (StackOverflow)

Bluetooth and WIFI Printing for Android

We would need a portable printer (handheld, it is important) that can connect to android phone via bluetooth or wifi.

What I know currently:

  • No standard printing SDK available for Android this time
  • There is a non official SDK called iPrint SDK. Have any of you tried it through wifi or bluetooth? Does it work?
  • Printershare also claims to be programmaticly available. It would be ok for me to pay the one time fee $5 for it per phone. It has a lot of supported formats. Have you tried it with any handheld device? I asked them about the list of supported bluetooth printers (since it has a menu item "search for BT printer"), but they did not answered.

What I need to know above the already asked:

  • How do you print from your android app?
  • What kind of printer do you use?
  • Is it planned in the standard android SDK to include printing? What is the roadmap? Is it available now as Beta or something?
  • If we somehow (i dont think so) build own solution for printing via bluetooth, can you recommend standards and protocols to check and learn?

Source: (StackOverflow)

Bluetooth Low Energy: listening for notifications/indications in linux

I'm trying to communicate with a BLE module through a Linux machine (the module is running a heart rate profile). So far, I've been able to do everything I need except listening for Notifications and indications (e.g. listening for the Heart Rate Measurement Notification). I'm using kernel version 3.5 and bluez-5.3.

Succcessful commands used so far:

hcitool lescan
hcitool lecc
gatttool -b <Mac Address> --primary
gatttool -b <MAC Address> --characteristics
gatttool -b <MAC Address> --char-read
gatttool -b <MAC Address> --char-desc
gatttool -b <MAC Address> --interactive

Failed commands:

gatttool -b <MAC Address> --listen

Any help is greatly appreciated.


Source: (StackOverflow)

Detecting state changes made to the BluetoothAdapter?

I have an app with a button on it that I use to turn BT on and off. I have the following code in there;

public void buttonFlip(View view) {
    flipBT();
    buttonText(view);
}

public void buttonText(View view) {  
    Button buttonText = (Button) findViewById(R.id.button1);
    if (mBluetoothAdapter.isEnabled() || (mBluetoothAdapter.a)) {
        buttonText.setText(R.string.bluetooth_on);  
    } else {
        buttonText.setText(R.string.bluetooth_off);
    }
}

private void flipBT() {
    if (mBluetoothAdapter.isEnabled()) {
        mBluetoothAdapter.disable();    
    } else {
        mBluetoothAdapter.enable();
    }
}

I'm calling button Flip, which flips the BT state, and then calls ButtonText, which should update the UI. However, the issue I'm having is, it takes a few seconds for BT to turn on - and during these seconds, the BT status is not enabled, making my button say Bluetooth off, even if it will be on in 2 seconds.

I found the STATE_CONNECTING constant in the BluetoothAdapter android documentation, but... I simply don't know how to use it, being a newbie and all.

So, I've got two questions:

  1. Is there a way to dynamically tie a UI element (such as a button or image) to a BT state, so that when the BT state changes, the button will change as well?
  2. Otherwise, I would want to press the button and get the correct state (I would like for it to say BT on, even if it's only connecting, since it will be on in 2 seconds). How do I do this?

Source: (StackOverflow)

Routing audio to Bluetooth Headset (non-A2DP) on Android

I have a non-A2DP single ear BT headset (Plantronics 510) and would like to use it with my Android HTC Magic to listen to low quality audio like podcasts/audio books.

After much googling I found that only phone call audio can be routed to the non-A2DP BT headsets. (I would like to know if you have found a ready solution to route all kinds of audio to non-A2DP BT headsets)

So I figured, somehow programmatically I can channel the audio to the stream that carries phone call audio. This way I will fool the phone to carry my mp3 audio to my BT headset. I wrote following simple code.

import android.content.*;
import android.app.Activity;
import android.os.Bundle;
import android.media.*;
import java.io.*;
import android.util.Log;

public class BTAudioActivity extends Activity
{
    private static final String TAG = "BTAudioActivity";

    private MediaPlayer mPlayer = null;
    private AudioManager amanager = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        amanager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        amanager.setBluetoothScoOn(true);
        amanager.setMode(AudioManager.MODE_IN_CALL);

        mPlayer = new MediaPlayer();

        try {
            mPlayer.setDataSource(new FileInputStream(
                "/sdcard/sample.mp3").getFD());

            mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);

            mPlayer.prepare();

            mPlayer.start();
        } catch(Exception e) {
            Log.e(TAG, e.toString());
        }
    }

    @Override
    public void onDestroy()
    {
        mPlayer.stop();
        amanager.setMode(AudioManager.MODE_NORMAL);
        amanager.setBluetoothScoOn(false);
        super.onDestroy();
    }
}

As you can see I tried combinations of various methods that I thought will fool the phone to believe my audio is a phone call:

  • Using MediaPlayer's setAudioStreamType(STREAM_VOICE_CALL)
  • using AudioManager's setBluetoothScoOn(true)
  • using AudioManager's setMode(MODE_IN_CALL)

But none of the above worked. If I remove the AudioManager calls in the above code, the audio plays from speaker and if I replace them as shown above then the audio stops coming from speakers, but it doesn't come through the BT headset. So this might be a partial success.

I have checked that the BT headset works alright with phone calls.

There must be a reason for Android not supporting this. But I can't let go of the feeling that it is not possible to programmatically reroute the audio. Any ideas?

P.S. above code needs following permission

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>


Source: (StackOverflow)

How to check if bluetooth is enabled programmatically?

I would like to check if bluetooth is enabled on any Android device periodically. Is there any intents that I could catch using BroadcastReceiver to do so, or is there other ways to do it?


Source: (StackOverflow)

Unable to Open SCOAudio connection with phone

I am trying to use IOBluetooth framework on OS X 10.8.2 to connect with the bluetooth enabled phones emulating computer as a hands free device. I can successfully make a connection with the phone and phone can recognise the connection as a HandsFree connected to the phone. But when I try to make a call with the phone and want to send the audio to the mac (by selecting the source as handsfree), the audio never reaches the computer.

As at this point the bluetooth framework tries to open a SCO Audio connection with the device, but the connection establishment is never successful and I get the error code 0x0D status code in scoConnectionOpened status.

I am using IOBluetoothAddSCOAudioDevice function to attach the SCO Audio device with bluetooth device and it is always successful.

//btDevice is paired 
res=IOBluetoothAddSCOAudioDevice((IOBluetoothDeviceRef) btDevice,NULL); 
if(res != kIOReturnSuccess)
{
   self.error.title = [NSString stringWithFormat:
        @"Could not attach the Audio device. Try  paring device again"];
}

The console log says

24/11/2012 4:02:13.000 PM kernel[0]: [SendHCIRequestFormatted] ### ERROR: [0x0428] (Setup Synchronous Connection) -- Send request failed (err = 0x000D (kBluetoothHCIErrorHostRejectedLimitedResources))

24/11/2012 4:02:13.000 PM kernel[0]: REQUIRE_NO_ERR failure: 0xd - file: /SourceCache/IOBluetoothFamily_kexts/IOBluetoothFamily-4090.4.33/Core/Family/Drivers/IOBluetoothSCOAudioDriver/IOBluetoothSCOAudioDevice.cpp:872

Although console log says limited resources but I have tried it with multiple phones having their batteries full.

I am stumped on this and just thinking if I need to do any thing special or different?

Thanks in advance for much appreciated help.


Source: (StackOverflow)

Use a handheld bluetooth printer with android

I have a bluetooth Handheld printer that I am able to communicate to using a SPP connection from my Mac(using Coolterm). When I'm trying to do the same from Android (using platform 7) I am running into multiple issues:

  • The printer doesn't seem to support/need PIN Authentication. When connecting from OSX, I just selected the option that said "Do not use a pin" and it got paired. In Android, when I use device.createRfcommSocketToServiceRecord(), it always ends up asking me for a PIN/Key(which I don't have/need). I solved this using the reflection trick:

    Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
    BluetoothSocket connection = (BluetoothSocket) m.invoke(device, 1);
    

    I am unsure whether this actually worked, but the blinking LED on the printer stops blinking, which makes me believe it did.

  • Once I have the socket, I try to write byte data to the stream using:

    byte[] buffer = new byte[3];
    buffer[0] = (byte) 0x8A;
    buffer[1] = (byte) 0xC1;
    buffer[2] = (byte) 0x04;
    outStream.write(buffer);
    int response = inStream.read();
    mySocket.close();
    

    Sending the same three-byte sequence from Coolterm on OSX printed a test page from the printer. However, this seems to make the thread hang on Android(the read).

Is there something I am missing out here?

EDIT: This seems to work only when I set channel to 1. So that means I am on to something here.


Source: (StackOverflow)

What are the nominal distances for iBeacon "Far", "Near", and "Immediate"

I've been playing around with using iOS devices as both broadcasters and receivers using the new iBeacon API's in iOS 7.

The docs don't go into detail at which distances the receiving device should see each proximity indicator, and specifically calls them out as "relative". When experimenting a with a demo app, I observed these distances (iPhone == receiver, iPad == broadcaster):

Far - 50 feet?

Near - 2-3 feet

Immediate - 2 inches

These seemed really small to me, and there is perhaps a hint in the CLBeaconRegion class reference, which allows you to specify the signal strength of your device from 1m away.

peripheralDataWithMeasuredPower:

Retrieves data that can be used to advertise the current device as a beacon.

Parameters

measuredPower

The received signal strength indicator (RSSI) value (measured in decibels) for the device. This value represents the measured strength of the beacon from one meter away and is used during ranging. Specify nil to use the default value for the device.

My amateur calibration yielded -60, which I set and re-tested:

Far - hundreds(ish) feet

Near - ~50 feet

Immediate - 1 meter (slightly less)

Are the results from my second test the "ideal" ranges according to Apple? They are really far away from the "default" setting I experienced in the first test.

Or should I perhaps consider these ranges "calibratable" depending on my needs?


Source: (StackOverflow)

How to get list of available Bluetooth devices?

I'm currently creating an iPhone app (Xcode 4.3.1, IOS 5) that could use Bluetooth devices! Main goal of this application is indoor navigation (GPS inside buildings isn't really accurate).

The only solution I see here (to keep my app on AppStore) is to try scan for available bluetooth devices!

I tried to use CoreBluetooth framework, but I don't get list of available devices! Maybe I don't use these functions correctly

#import <UIKit/UIKit.h>
#import <CoreBluetooth/CoreBluetooth.h>

@interface AboutBhyperView : UIViewController <CBPeripheralDelegate, CBCentralManagerDelegate>
{
    CBCentralManager *mgr;
}
@property (readwrite, nonatomic) CBCentralManager *mgr;
@end



- (void)viewDidLoad
{
    [super viewDidLoad];

    mgr = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}


- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {


    NSLog([NSString stringWithFormat:@"%@",[advertisementData description]]);
}

-(void)centralManager:(CBCentralManager *)central didRetrievePeripherals:(NSArray *)peripherals{
    NSLog(@"This is it!");
}


- (void)centralManagerDidUpdateState:(CBCentralManager *)central{ 
    NSString *messtoshow;

    switch (central.state) {
        case CBCentralManagerStateUnknown:
        {
            messtoshow=[NSString stringWithFormat:@"State unknown, update imminent."];
            break;
        }
        case CBCentralManagerStateResetting:
        {
            messtoshow=[NSString stringWithFormat:@"The connection with the system service was momentarily lost, update imminent."];
            break;
        }
        case CBCentralManagerStateUnsupported:
        {
            messtoshow=[NSString stringWithFormat:@"The platform doesn't support Bluetooth Low Energy"];
            break;
        }
        case CBCentralManagerStateUnauthorized:
        {
            messtoshow=[NSString stringWithFormat:@"The app is not authorized to use Bluetooth Low Energy"];
            break;
        }
        case CBCentralManagerStatePoweredOff:
        {
            messtoshow=[NSString stringWithFormat:@"Bluetooth is currently powered off."];
            break;
        }
        case CBCentralManagerStatePoweredOn:
        {
            messtoshow=[NSString stringWithFormat:@"Bluetooth is currently powered on and available to use."];
            [mgr scanForPeripheralsWithServices:nil options:nil];
            //[mgr retrieveConnectedPeripherals];

//--- it works, I Do get in this area!

            break;
        }   

    }
    NSLog(messtoshow); 
} 

I'm not sure about this line, how to pass correct parameters?

[mgr scanForPeripheralsWithServices:nil options:nil];

I took a look into apple reference .. and I still don't understand what's that CBUUID ??? Every device has some bluetooth id? where can I find it?

- (void)scanForPeripheralsWithServices:(NSArray *)serviceUUIDs options:(NSDictionary *)options;

Parameters serviceUUIDs - An array of CBUUIDs the app is interested in. options - A dictionary to customize the scan, see CBCentralManagerScanOptionAllowDuplicatesKey.

Is there any other way to use Bluetooth on IOS? I mean, older frameworks that don't use BLE 4.0!

any advice would be appreciated!

thanks!


Source: (StackOverflow)

ActivityManager: Warning: Activity not started, its current task has been brought to the front

package supa.mack.doppler;

import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.bluetooth.*; 
import android.widget.Toast;

public class doppler_test extends Activity {
TextView out;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

out = (TextView) findViewById(R.id.out);

// Getting the Bluetooth adapter
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
out.append("\nAdapter: " + adapter);

// Check for Bluetooth support in the first place 
// Emulator doesn't support Bluetooth and will return null
if(adapter==null) { 
out.append("\nBluetooth NOT supported. Aborting.");
return;
}

// Starting the device discovery
out.append("\nStarting discovery...");
adapter.startDiscovery();
out.append("\nDone with discovery...");

// Listing paired devices
out.append("\nDevices Pared:");
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for (BluetoothDevice device : devices) {
out.append("\nFound device: " + device);
}

Button searchButton=(Button) findViewById(R.id.search_button);
searchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent intent=new Intent(
doppler_test.this,
search_result.class
);

startActivity(intent);
}
}); 
}
} 

--------------------------------------…

Here is the code where the problem lies....

It doesn't give me an error it says exactly this when I run the android emulator

"[2010-08-25 09:12:42 - doppler_test] ActivityManager: Warning: Activity not started, its current task has been brought to the front"

What I think this means is that the intent of the bluetooth function and the button intent is only operation on a hierarchy system. What I mean by this is that if I were to move the button opperator above the Bluetooth stuff the button will work, but currently when the app is run Bluetooth works but when I press the search button nothing happens.

What else may be helpful is my XML code for the button so here it is......

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.co…
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:background="@color/purple_flurp"…
<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="@string/hello"/>
<Button
android:id="@+id/search_button"
android:layout_height="wrap_content" 
android:text="@string/search" 
android:layout_width="fill_parent"/>

<TextView 
android:text="@+id/TextView01" 
android:id="@+id/out" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content">
</TextView>
</LinearLayout>

--------------------------------------…

any ideas? Anything would be great! Thanks


Source: (StackOverflow)

Android BLE API: GATT Notification not received

Device used for testing: Nexus 4, Android 4.3

Connection is working fine but the onCharacteristicChangedMethod of my callback is never called. However I am registering for notifications using setCharacteristicNotification(char, true) inside onServicesDiscovered and that function even returns true.

Device log (there are actually no messages at all when notifications should appear / are sent via the Bluetooth device):

07-28 18:15:06.936  16777-16809/de.ffuf.leica.sketch D/BluetoothGatt: setCharacteristicNotification() - uuid: 3ab10101-f831-4395-b29d-570977d5bf94 enable: true
07-28 18:15:06.936    4372-7645/com.android.bluetooth D/BtGatt.GattService: registerForNotification() - address=C9:79:25:34:19:6C enable: true
07-28 18:15:06.936    4372-7645/com.android.bluetooth D/BtGatt.btif: btif_gattc_reg_for_notification
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1018
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.GattService: onRegisterForNotifications() - address=null, status=0, registered=1, charUuid=3ab10101-f831-4395-b29d-570977d5bf94
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1016
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1018
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.GattService: onRegisterForNotifications() - address=null, status=0, registered=1, charUuid=3ab10102-f831-4395-b29d-570977d5bf94
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1016
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1013
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.946    4372-7645/com.android.bluetooth D/BtGatt.btif: btgattc_handle_event: Event 1013
07-28 18:15:06.946    4372-7684/com.android.bluetooth E/bt-btif: already has a pending command!!
07-28 18:15:06.976    4372-7645/com.android.bluetooth D/BtGatt.btif: btif_gattc_upstreams_evt: Event 9

GATT Notifications work fine using iOS and the app basically does the same as on Android (registering for notification etc.).

Has anyone else experienced this with a possible solution?


Source: (StackOverflow)

Service discovery failed exception using Bluetooth on Android

I'm currently working on an Android application that connects to an instrument via Bluetooth and need to write string commands and receive string responses back. Currently I have the connect/read/write working for TCP/IP over Wi-Fi and now trying to implement Bluetooth. But I am running into some roadblocks. I have been searching the web trying to find examples of something similar and haven't had any luck. I have been using the Android developer resource example: Bluetooth Chat as my main reference point.

My current code seems to work.. Then it throws a Service Discovery Failed exception at the point of the connection. I am using the DeviceListActivity class to do the discovery and selecting of the device I want to connect to. It returns anActivityResult and then my Bluetooth class waits for it to handle that and then does the connect to it. The code beneath is almost identical to the Bluetooth Chat App.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(!m_BluetoothAdapter.isEnabled())
    {
        m_BluetoothAdapter.enable();
    }
    switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = m_BluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                connect(device);
            }
            break;

        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
            }
            else {
                // User did not enable Bluetooth or an error occured

                Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_SHORT).show();
                finish();
            }
    }
}

This is my connect function:

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private void connect(BluetoothDevice device) {
    m_Device = device;
    BluetoothSocket tmp = null;

    // Get a BluetoothSocket for a connection with the
    // given BluetoothDevice
    try {
        tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    }
    catch (IOException e) {

    }
    m_Socket = tmp;

    m_BluetoothAdapter.cancelDiscovery();

    try {
        // This is a blocking call and will only return on a
        // successful connection or an exception
        m_Socket.connect();
    }
    catch (IOException e) {
        try {
            m_Socket.close();
        }
        catch (IOException e2) {
        }
        return;
    }
}

Hopefully, whatever I am doing wrong is simple, but I'm afraid it's never that easy. This is my first time doing any Bluetooth development, and maybe I'm doing something blatantly wrong... But I'm not sure why I get the service discovery failed exception.

You can pair/find the device at all times manually on the phone... It does require a passcode, but I don't think that is the problem that I am having.


Source: (StackOverflow)