Bluetooth connection multiple devices

Connect multiple devices to one device via Bluetooth

I would like to create a game, where you must connect multiple devices (4+) to a main device (ex. a tablet) via Bluetooth. There would be two apps, a main one to which all data would be send from the phones, and to the phones. Is that even possible?

7 Answers 7

Yes, that is possible. At its lowest level Bluetooth allows you to connect up to 7 devices to one master device. I have done this and it has worked well for me, but only on other platforms (linux) where I had lots of manual control — I’ve never tried that on Android and there are some possible complications so you will need to do some testing to be certain.

One of the issues is that you need the tablet to the master and Android doesn’t give you any explicit control of this. It is likely that this won’t be a problem because * the tablet will automatically become the master when you try to connect a second device to it, or * you will be able to control the master/slave roles by how you setup your socket connection

I will caution though that most apps using Bluetooth on mobile are not attempting many simultaneous connections and Bluetooth can be a bit fragile, e.g. what if two devices already have a Bluetooth connection for some other app — how might that affect the roles?

Bluetooth 4.0 Allows you in a Bluetooth piconet one master can communicate up to 7 active slaves, there can be some other devices up to 248 devices which sleeping.

Also you can use some slaves as bridge to participate with more devices.

Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2 in dependency section of your build.gradl e .

This is the class where the connection is established and messages are recieved. Make sure to pair the devices before you run the application. If you want to have a slave/master connection, where each slave can only send messages to the master , and the master can broadcast messages to all slaves. You should only pair the master with each slave , but you shouldn’t pair the slaves together.

 package com.example.gaby.coordinatorv1; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.widget.Toast; public class Piconet < private final static String TAG = Piconet.class.getSimpleName(); // Name for the SDP record when creating server socket private static final String PICONET = "ANDROID_PICONET_BLUETOOTH"; private final BluetoothAdapter mBluetoothAdapter; // String: device address // BluetoothSocket: socket that represent a bluetooth connection private HashMapmBtSockets; // String: device address // Thread: thread for connection private HashMap mBtConnectionThreads; private ArrayList mUuidList; private ArrayList mBtDeviceAddresses; private Context context; private Handler handler = new Handler() < public void handleMessage(Message msg) < switch (msg.what) < case 1: Toast.makeText(context, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show(); break; default: break; >>; >; public Piconet(Context context) < this.context = context; mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBtSockets = new HashMap(); mBtConnectionThreads = new HashMap(); mUuidList = new ArrayList(); mBtDeviceAddresses = new ArrayList(); // Allow up to 7 devices to connect to the server mUuidList.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666")); mUuidList.add(UUID.fromString("54d1cc90-1169-11e2-892e-0800200c9a66")); mUuidList.add(UUID.fromString("6acffcb0-1169-11e2-892e-0800200c9a66")); mUuidList.add(UUID.fromString("7b977d20-1169-11e2-892e-0800200c9a66")); mUuidList.add(UUID.fromString("815473d0-1169-11e2-892e-0800200c9a66")); mUuidList.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66")); mUuidList.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66")); Thread connectionProvider = new Thread(new ConnectionProvider()); connectionProvider.start(); > public void startPiconet() < Log.d(TAG, " -- Looking devices -- "); // The devices must be already paired SetpairedDevices = mBluetoothAdapter .getBondedDevices(); if (pairedDevices.size() > 0) < for (BluetoothDevice device : pairedDevices) < // X , Y and Z are the Bluetooth name (ID) for each device you want to connect to if (device != null && (device.getName().equalsIgnoreCase("X") || device.getName().equalsIgnoreCase("Y") || device.getName().equalsIgnoreCase("Z") || device.getName().equalsIgnoreCase("M"))) < Log.d(TAG, " -- Device " + device.getName() + " found --"); BluetoothDevice remoteDevice = mBluetoothAdapter .getRemoteDevice(device.getAddress()); connect(remoteDevice); >> > else < Toast.makeText(context, "No paired devices", Toast.LENGTH_SHORT).show(); >> private class ConnectionProvider implements Runnable < @Override public void run() < try < for (int i=0; icatch (IOException e) < Log.e(TAG, " ** IOException when trying to close serverSocket ** "); >if (myBTsocket != null) < String address = myBTsocket.getRemoteDevice().getAddress(); mBtSockets.put(address, myBTsocket); mBtDeviceAddresses.add(address); Thread mBtConnectionThread = new Thread(new BluetoohConnection(myBTsocket)); mBtConnectionThread.start(); Log.i(TAG," ** Adding " + address + " in mBtDeviceAddresses ** "); mBtConnectionThreads.put(address, mBtConnectionThread); >else < Log.e(TAG, " ** Can't establish connection ** "); >> > catch (IOException e) < Log.e(TAG, " ** IOException in ConnectionService:ConnectionProvider ** ", e); >> > private class BluetoohConnection implements Runnable < private String address; private final InputStream mmInStream; public BluetoohConnection(BluetoothSocket btSocket) < InputStream tmpIn = null; try < tmpIn = new DataInputStream(btSocket.getInputStream()); >catch (IOException e) < Log.e(TAG, " ** IOException on create InputStream object ** ", e); >mmInStream = tmpIn; > @Override public void run() < byte[] buffer = new byte[1]; String message = ""; while (true) < try < int readByte = mmInStream.read(); if (readByte == -1) < Log.e(TAG, "Discarting message: " + message); message = ""; continue; >buffer[0] = (byte) readByte; if (readByte == 0) < // see terminateFlag on write method onReceive(message); message = ""; >else < // a message has been recieved message += new String(buffer, 0, 1); >> catch (IOException e) < Log.e(TAG, " ** disconnected ** ", e); >mBtDeviceAddresses.remove(address); mBtSockets.remove(address); mBtConnectionThreads.remove(address); > > > /** * @param receiveMessage */ private void onReceive(String receiveMessage) < if (receiveMessage != null && receiveMessage.length() >0) < Log.i(TAG, " $$$$ " + receiveMessage + " $$$$ "); Bundle bundle = new Bundle(); bundle.putString("msg", receiveMessage); Message message = new Message(); message.what = 1; message.setData(bundle); handler.sendMessage(message); >> /** * @param device * @param uuidToTry * @return */ private BluetoothSocket getConnectedSocket(BluetoothDevice device, UUID uuidToTry) < BluetoothSocket myBtSocket; try < myBtSocket = device.createRfcommSocketToServiceRecord(uuidToTry); myBtSocket.connect(); return myBtSocket; >catch (IOException e) < Log.e(TAG, "IOException in getConnectedSocket", e); >return null; > private void connect(BluetoothDevice device) < BluetoothSocket myBtSocket = null; String address = device.getAddress(); BluetoothDevice remoteDevice = mBluetoothAdapter.getRemoteDevice(address); // Try to get connection through all uuids available for (int i = 0; i < mUuidList.size() && myBtSocket == null; i++) < // Try to get the socket 2 times for each uuid of the list for (int j = 0; j < 2 && myBtSocket == null; j++) < Log.d(TAG, " ** Trying connection. " + j + " with " + device.getName() + ", uuid " + i + ". ** "); myBtSocket = getConnectedSocket(remoteDevice, mUuidList.get(i)); if (myBtSocket == null) < try < Thread.sleep(200); >catch (InterruptedException e) < Log.e(TAG, "InterruptedException in connect", e); >> > > if (myBtSocket == null) < Log.e(TAG, " ** Could not connect ** "); return; >Log.d(TAG, " ** Connection established with " + device.getName() +"! ** "); mBtSockets.put(address, myBtSocket); mBtDeviceAddresses.add(address); Thread mBluetoohConnectionThread = new Thread(new BluetoohConnection(myBtSocket)); mBluetoohConnectionThread.start(); mBtConnectionThreads.put(address, mBluetoohConnectionThread); > public void bluetoothBroadcastMessage(String message) < //send message to all except Id for (int i = 0; i < mBtDeviceAddresses.size(); i++) < sendMessage(mBtDeviceAddresses.get(i), message); >> private void sendMessage(String destination, String message) < BluetoothSocket myBsock = mBtSockets.get(destination); if (myBsock != null) < try < OutputStream outStream = myBsock.getOutputStream(); final int pieceSize = 16; for (int i = 0; i < message.length(); i += pieceSize) < byte[] send = message.substring(i, Math.min(message.length(), i + pieceSize)).getBytes(); outStream.write(send); >// we put at the end of message a character to sinalize that message // was finished byte[] terminateFlag = new byte[1]; terminateFlag[0] = 0; // ascii table value NULL (code 0) outStream.write(new byte[1]); > catch (IOException e) < Log.d(TAG, "line 278", e); >> > > 

Your main activity should be as follow :

package com.example.gaby.coordinatorv1; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends Activity < private Button discoveryButton; private Button messageButton; private Piconet piconet; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); piconet = new Piconet(getApplicationContext()); messageButton = (Button) findViewById(R.id.messageButton); messageButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < piconet.bluetoothBroadcastMessage("Hello World---*Gaby Bou Tayeh*"); >>); discoveryButton = (Button) findViewById(R.id.discoveryButton); discoveryButton.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < piconet.startPiconet(); >>); > > 

Do not forget to add the following permissions to your Manifest File :

Читайте также:  Bluetooth wireless speaker with nfc

Источник

How to connect multiple bluetooth devices to a single device

Pin It

Most people have Wi-Fi routers in their homes to connect them to the internet. But have you ever heard of a Bluetooth router? With the release of new technology such as a Bluetooth Hub, you may be wondering what you might need it for.

For a start there are more devices and gadgets manufactured that are now wireless. These devices are considered more convenient as there are no annoying wires to plug in, get tangled or create an awful mess around electronics.

But with these wireless devices, you need something to connect them all to a source so you can use them effectively. So this is where your Bluetooth Hub comes in.

What is a Bluetooth Hub?

Bluetooth is a technology that you may use on a daily basis. Yet it has two significant drawbacks. The first drawback is that Bluetooth devices can only be paired on a one-to-one basis. Secondly, the range of Bluetooth is short which means many devices cut out when you move more than 30ft away from the connection source.

One of the leading Bluetooth Hub brands on the market is the Cassia Bluetooth Hub and it can solve both of these problems. The Hub is a white cylindrical device that’s about 8″ in length and 5″ in diameter.

At the back of the Hub is a USB 2.0 port, an Ethernet port, power adapter and LED indicator. The Hub can be hooked up straight through the Ethernet or through the Wi-Fi router easily. But depending on the brand the device could operate differently. So how do Bluetooth Hubs work?

Читайте также:  What is bluetooth low energy technology

How Does a Bluetooth Transmitter and Receiver Work?

There are many types of Bluetooth devices you can connect to that perform other tasks. All it needs is a Bluetooth transmitter to make pairing possible. They work by decoding information such as songs into a transferable format before transmitting that information through radio waves to the receiver.

The transmitter produces audio frequencies which are then detected by the receiver. Together the transmitter and the receiver create a pathway through which data can be transferred.

In the modern world, Bluetooth is an important feature for most applications including mobile phones, TVs, laptops and speakers. If you’re looking for any Bluetooth device it should support version 4.0 as it’s the latest Bluetooth transmitter. But version 2.1 is also more than adequate for everyday applications. With version 2.1 you can pair devices such as Bluetooth headphones or speakers.

You should also consider the range of the Bluetooth transmitter. For instance, if you’re using Bluetooth speakers and your transmitter is inside but you want to hear your music outside you’ll need a device with a longer range. This will prevent the radio signal being interrupted.

As mentioned before standard devices allow for a range of up to 30ft but with Bluetooth Hubs you’re able to connect devices from as far as 1000ft away.

Connect Multiple Devices

Depending on the brand you can pair and stay connected to the Hub with up to 22 devices. You can organize these devices into groups so you can access them quickly and easily. Here’s how to connect multiple Bluetooth devices at the same time.

Читайте также:  Smartbuy z1 74вт ipx5 bluetooth

Some brands such as the Cassia allow you to set up your Bluetooth router through your SmartPhone. If your device has the same feature it should be compatible with Android and Apple applications.

Your SmartPhone application allows you to manage your paired Bluetooth devices easily even when you’re not at home or near the Hub. The 22 devices can all be different from speakers to printers and even TV sets.

Simply download the compatible app on your SmartPhone so you can pair it to your Hub. Switch the Hub on either by using a specific button and use the Bluetooth on your phone to connect to the Hub. Turn on all your Bluetooth receivers so the Hub can connect to them.

On your mobile application that’s compatible with your Hub, it will show all your Bluetooth devices that are turned on. Here you can control the devices straight from your mobile phone. Easily turn on TVs, lights, kettles and radios with a click of a button through Bluetooth transmitters & receivers.

What if Your Device Doesn’t Have Bluetooth?

Not all electronic devices have Bluetooth receivers. In order to convert your device, you’ll have to purchase a portable Bluetooth receiver that you can connect to your device via a cord.

You can turn an ordinary device such as a pair of headphones into a Bluetooth receiver by simply plugging in a portable receiver. People do this with myriads of applications so they can easily control the devices using their Bluetooth Hub.

Can you Connect Multiple Speakers?

If you have an event and you have no idea how to use a soundboard or how to connect all your speakers at the same time, a hub can help you with the task. This is of course if the speakers have Bluetooth receivers.

Simply turn all your Bluetooth speakers on so they can be discovered by the Bluetooth router. Here you can play music with SoundCloud, YouTube, Deezer or even through your phone’s music media via your SmartPhone application.

You can pair four or more speakers at the same time and place them all over the house to transmit sound.

Troubleshooting when Connecting Bluetooth Devices

If you’re experiencing interference or signal dropouts, scan the environment you’re using your Bluetooth device in. The quality of the Bluetooth connection can be negatively affected by concrete walls, microwaves and other wireless devices such as portable radios or cordless telephones.

Final Thoughts

Do you have an application with a Bluetooth router? Turn your Bluetooth on and experiment with how many devices you can connect to simultaneously. You’d be surprised at how many applications out there have Bluetooth technology and the number of devices you can pair to.

Modern technology definitely makes life interesting, find more at Outeraudio!

Final thought. Who has not heard about classic Solitaire card games?

Источник

Оцените статью
Adblock
detector